Changed DiffText and Constant highlight groups
[MacVim/jjgod.git] / src / MacVim / MMVimController.m
blob0f0a3c60ee2d80164b154640fc4c8ce9a0c73d25
1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
2  *
3  * VIM - Vi IMproved            by Bram Moolenaar
4  *                              MacVim GUI port by Bjorn Winckler
5  *
6  * Do ":help uganda"  in Vim to read copying and usage conditions.
7  * Do ":help credits" in Vim to see a list of people who contributed.
8  * See README.txt for an overview of the Vim source code.
9  */
11 #import "MMVimController.h"
12 #import "MMWindowController.h"
13 #import "MMTextView.h"
14 #import "MMAppController.h"
15 #import "MMTextStorage.h"
18 // This is taken from gui.h
19 #define DRAW_CURSOR 0x20
21 static NSString *MMDefaultToolbarImageName = @"Attention";
22 static int MMAlertTextFieldHeight = 22;
24 // NOTE: By default a message sent to the backend will be dropped if it cannot
25 // be delivered instantly; otherwise there is a possibility that MacVim will
26 // 'beachball' while waiting to deliver DO messages to an unresponsive Vim
27 // process.  This means that you cannot rely on any message sent with
28 // sendMessage: to actually reach Vim.
29 static NSTimeInterval MMBackendProxyRequestTimeout = 0;
31 #if MM_RESEND_LAST_FAILURE
32 // If a message send fails, the message will be resent after this many seconds
33 // have passed.  (No queue is kept, only the very last message is resent.)
34 static NSTimeInterval MMResendInterval = 0.5;
35 #endif
38 @interface MMAlert : NSAlert {
39     NSTextField *textField;
41 - (void)setTextFieldString:(NSString *)textFieldString;
42 - (NSTextField *)textField;
43 @end
46 @interface MMVimController (Private)
47 - (void)handleMessage:(int)msgid data:(NSData *)data;
48 - (void)performBatchDrawWithData:(NSData *)data;
49 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
50                 context:(void *)context;
51 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context;
52 - (NSMenuItem *)recurseMenuItemForTag:(int)tag rootMenu:(NSMenu *)root;
53 - (NSMenuItem *)menuItemForTag:(int)tag;
54 - (NSMenu *)menuForTag:(int)tag;
55 - (NSMenu *)topLevelMenuForTitle:(NSString *)title;
56 - (void)addMenuWithTag:(int)tag parent:(int)parentTag title:(NSString *)title
57                atIndex:(int)idx;
58 - (void)addMenuItemWithTag:(int)tag parent:(NSMenu *)parent
59                      title:(NSString *)title tip:(NSString *)tip
60              keyEquivalent:(int)key modifiers:(int)mask
61                     action:(NSString *)action atIndex:(int)idx;
62 - (void)updateMainMenu;
63 - (NSToolbarItem *)toolbarItemForTag:(int)tag index:(int *)index;
64 - (void)addToolbarItemToDictionaryWithTag:(int)tag label:(NSString *)title
65         toolTip:(NSString *)tip icon:(NSString *)icon;
66 - (void)addToolbarItemWithTag:(int)tag label:(NSString *)label
67                           tip:(NSString *)tip icon:(NSString *)icon
68                       atIndex:(int)idx;
69 - (void)connectionDidDie:(NSNotification *)notification;
70 #if MM_RESEND_LAST_FAILURE
71 - (void)resendTimerFired:(NSTimer *)timer;
72 #endif
73 @end
77 // TODO: Move to separate file
78 @interface NSColor (MMProtocol)
79 + (NSColor *)colorWithRgbInt:(unsigned)rgb;
80 + (NSColor *)colorWithArgbInt:(unsigned)argb;
81 @end
86 @implementation MMVimController
88 - (id)initWithBackend:(id)backend pid:(int)processIdentifier
90     if ((self = [super init])) {
91         windowController =
92             [[MMWindowController alloc] initWithVimController:self];
93         backendProxy = [backend retain];
94         sendQueue = [NSMutableArray new];
95         mainMenuItems = [[NSMutableArray alloc] init];
96         popupMenuItems = [[NSMutableArray alloc] init];
97         toolbarItemDict = [[NSMutableDictionary alloc] init];
98         pid = processIdentifier;
100         NSConnection *connection = [backendProxy connectionForProxy];
102         // TODO: Check that this will not set the timeout for the root proxy
103         // (in MMAppController).
104         [connection setRequestTimeout:MMBackendProxyRequestTimeout];
106         [[NSNotificationCenter defaultCenter] addObserver:self
107                 selector:@selector(connectionDidDie:)
108                     name:NSConnectionDidDieNotification object:connection];
111         NSWindow *win = [windowController window];
113         [[NSNotificationCenter defaultCenter]
114                 addObserver:self
115                    selector:@selector(windowDidBecomeMain:)
116                        name:NSWindowDidBecomeMainNotification
117                      object:win];
119         isInitialized = YES;
120     }
122     return self;
125 - (void)dealloc
127     //NSLog(@"%@ %s", [self className], _cmd);
128     isInitialized = NO;
130 #if MM_RESEND_LAST_FAILURE
131     [resendData release];  resendData = nil;
132 #endif
134     [serverName release];  serverName = nil;
135     [backendProxy release];  backendProxy = nil;
136     [sendQueue release];  sendQueue = nil;
138     [toolbarItemDict release];  toolbarItemDict = nil;
139     [toolbar release];  toolbar = nil;
140     [popupMenuItems release];  popupMenuItems = nil;
141     [mainMenuItems release];  mainMenuItems = nil;
142     [windowController release];  windowController = nil;
144     [super dealloc];
147 - (MMWindowController *)windowController
149     return windowController;
152 - (void)setServerName:(NSString *)name
154     if (name != serverName) {
155         [serverName release];
156         serverName = [name copy];
157     }
160 - (NSString *)serverName
162     return serverName;
165 - (int)pid
167     return pid;
170 - (void)dropFiles:(NSArray *)filenames
172     int i, numberOfFiles = [filenames count];
173     NSMutableData *data = [NSMutableData data];
175     [data appendBytes:&numberOfFiles length:sizeof(int)];
177     for (i = 0; i < numberOfFiles; ++i) {
178         NSString *file = [filenames objectAtIndex:i];
179         int len = [file lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
181         if (len > 0) {
182             ++len;  // include NUL as well
183             [data appendBytes:&len length:sizeof(int)];
184             [data appendBytes:[file UTF8String] length:len];
185         }
186     }
188     [self sendMessage:DropFilesMsgID data:data];
191 - (void)dropString:(NSString *)string
193     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
194     if (len > 0) {
195         NSMutableData *data = [NSMutableData data];
197         [data appendBytes:&len length:sizeof(int)];
198         [data appendBytes:[string UTF8String] length:len];
200         [self sendMessage:DropStringMsgID data:data];
201     }
204 - (void)sendMessage:(int)msgid data:(NSData *)data
206     //NSLog(@"sendMessage:%s (isInitialized=%d inProcessCommandQueue=%d)",
207     //        MessageStrings[msgid], isInitialized, inProcessCommandQueue);
209     if (!isInitialized) return;
211     if (inProcessCommandQueue) {
212         //NSLog(@"In process command queue; delaying message send.");
213         [sendQueue addObject:[NSNumber numberWithInt:msgid]];
214         if (data)
215             [sendQueue addObject:data];
216         else
217             [sendQueue addObject:[NSNull null]];
218         return;
219     }
221 #if MM_RESEND_LAST_FAILURE
222     if (resendTimer) {
223         //NSLog(@"cancelling scheduled resend of %s",
224         //        MessageStrings[resendMsgid]);
226         [resendTimer invalidate];
227         [resendTimer release];
228         resendTimer = nil;
229     }
231     if (resendData) {
232         [resendData release];
233         resendData = nil;
234     }
235 #endif
237     @try {
238         [backendProxy processInput:msgid data:data];
239     }
240     @catch (NSException *e) {
241         //NSLog(@"%@ %s Exception caught during DO call: %@",
242         //        [self className], _cmd, e);
243 #if MM_RESEND_LAST_FAILURE
244         //NSLog(@"%s failed, scheduling message %s for resend", _cmd,
245         //        MessageStrings[msgid]);
247         resendMsgid = msgid;
248         resendData = [data retain];
249         resendTimer = [NSTimer
250             scheduledTimerWithTimeInterval:MMResendInterval
251                                     target:self
252                                   selector:@selector(resendTimerFired:)
253                                   userInfo:nil
254                                    repeats:NO];
255         [resendTimer retain];
256 #endif
257     }
260 - (BOOL)sendMessageNow:(int)msgid data:(NSData *)data
261                timeout:(NSTimeInterval)timeout
263     if (!isInitialized || inProcessCommandQueue)
264         return NO;
266     if (timeout < 0) timeout = 0;
268     BOOL sendOk = YES;
269     NSConnection *conn = [backendProxy connectionForProxy];
270     NSTimeInterval oldTimeout = [conn requestTimeout];
272     [conn setRequestTimeout:timeout];
274     @try {
275         [backendProxy processInput:msgid data:data];
276     }
277     @catch (NSException *e) {
278         sendOk = NO;
279     }
280     @finally {
281         [conn setRequestTimeout:oldTimeout];
282     }
284     return sendOk;
287 - (id)backendProxy
289     return backendProxy;
292 - (void)cleanup
294     //NSLog(@"%@ %s", [self className], _cmd);
295     if (!isInitialized) return;
297     isInitialized = NO;
298     [toolbar setDelegate:nil];
299     [[NSNotificationCenter defaultCenter] removeObserver:self];
300     [windowController cleanup];
303 - (oneway void)showSavePanelForDirectory:(in bycopy NSString *)dir
304                                    title:(in bycopy NSString *)title
305                                   saving:(int)saving
307     if (!isInitialized) return;
309     if (saving) {
310         [[NSSavePanel savePanel] beginSheetForDirectory:dir file:nil
311                 modalForWindow:[windowController window]
312                  modalDelegate:self
313                 didEndSelector:@selector(savePanelDidEnd:code:context:)
314                    contextInfo:NULL];
315     } else {
316         NSOpenPanel *panel = [NSOpenPanel openPanel];
317         [panel setAllowsMultipleSelection:NO];
318         [panel beginSheetForDirectory:dir file:nil types:nil
319                 modalForWindow:[windowController window]
320                  modalDelegate:self
321                 didEndSelector:@selector(savePanelDidEnd:code:context:)
322                    contextInfo:NULL];
323     }
326 - (oneway void)presentDialogWithStyle:(int)style
327                               message:(in bycopy NSString *)message
328                       informativeText:(in bycopy NSString *)text
329                          buttonTitles:(in bycopy NSArray *)buttonTitles
330                       textFieldString:(in bycopy NSString *)textFieldString
332     if (!(windowController && buttonTitles && [buttonTitles count])) return;
334     MMAlert *alert = [[MMAlert alloc] init];
336     // NOTE! This has to be done before setting the informative text.
337     if (textFieldString)
338         [alert setTextFieldString:textFieldString];
340     [alert setAlertStyle:style];
342     if (message) {
343         [alert setMessageText:message];
344     } else {
345         // If no message text is specified 'Alert' is used, which we don't
346         // want, so set an empty string as message text.
347         [alert setMessageText:@""];
348     }
350     if (text) {
351         [alert setInformativeText:text];
352     } else if (textFieldString) {
353         // Make sure there is always room for the input text field.
354         [alert setInformativeText:@""];
355     }
357     unsigned i, count = [buttonTitles count];
358     for (i = 0; i < count; ++i) {
359         NSString *title = [buttonTitles objectAtIndex:i];
360         // NOTE: The title of the button may contain the character '&' to
361         // indicate that the following letter should be the key equivalent
362         // associated with the button.  Extract this letter and lowercase it.
363         NSString *keyEquivalent = nil;
364         NSRange hotkeyRange = [title rangeOfString:@"&"];
365         if (NSNotFound != hotkeyRange.location) {
366             if ([title length] > NSMaxRange(hotkeyRange)) {
367                 NSRange keyEquivRange = NSMakeRange(hotkeyRange.location+1, 1);
368                 keyEquivalent = [[title substringWithRange:keyEquivRange]
369                     lowercaseString];
370             }
372             NSMutableString *string = [NSMutableString stringWithString:title];
373             [string deleteCharactersInRange:hotkeyRange];
374             title = string;
375         }
377         [alert addButtonWithTitle:title];
379         // Set key equivalent for the button, but only if NSAlert hasn't
380         // already done so.  (Check the documentation for
381         // - [NSAlert addButtonWithTitle:] to see what key equivalents are
382         // automatically assigned.)
383         NSButton *btn = [[alert buttons] lastObject];
384         if ([[btn keyEquivalent] length] == 0 && keyEquivalent) {
385             [btn setKeyEquivalent:keyEquivalent];
386         }
387     }
389     [alert beginSheetModalForWindow:[windowController window]
390                       modalDelegate:self
391                      didEndSelector:@selector(alertDidEnd:code:context:)
392                         contextInfo:NULL];
394     [alert release];
397 - (oneway void)processCommandQueue:(in bycopy NSArray *)queue
399     if (!isInitialized) return;
401     unsigned i, count = [queue count];
402     if (count % 2) {
403         NSLog(@"WARNING: Uneven number of components (%d) in flush queue "
404                 "message; ignoring this message.", count);
405         return;
406     }
408     inProcessCommandQueue = YES;
410     //NSLog(@"======== %s BEGIN ========", _cmd);
411     for (i = 0; i < count; i += 2) {
412         NSData *value = [queue objectAtIndex:i];
413         NSData *data = [queue objectAtIndex:i+1];
415         int msgid = *((int*)[value bytes]);
416         //NSLog(@"%s%s", _cmd, MessageStrings[msgid]);
418         [self handleMessage:msgid data:data];
419     }
420     //NSLog(@"======== %s  END  ========", _cmd);
422     if (shouldUpdateMainMenu) {
423         [self updateMainMenu];
424     }
426     [windowController processCommandQueueDidFinish];
428     inProcessCommandQueue = NO;
430     if ([sendQueue count] > 0) {
431         @try {
432             [backendProxy processInputAndData:sendQueue];
433         }
434         @catch (NSException *e) {
435             // Connection timed out, just ignore this.
436             //NSLog(@"WARNING! Connection timed out in %s", _cmd);
437         }
439         [sendQueue removeAllObjects];
440     }
443 - (void)windowDidBecomeMain:(NSNotification *)notification
445     if (isInitialized)
446         [self updateMainMenu];
449 - (NSToolbarItem *)toolbar:(NSToolbar *)theToolbar
450     itemForItemIdentifier:(NSString *)itemId
451     willBeInsertedIntoToolbar:(BOOL)flag
453     NSToolbarItem *item = [toolbarItemDict objectForKey:itemId];
454     if (!item) {
455         NSLog(@"WARNING:  No toolbar item with id '%@'", itemId);
456     }
458     return item;
461 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)theToolbar
463     return nil;
466 - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)theToolbar
468     return nil;
471 @end // MMVimController
475 @implementation MMVimController (Private)
477 - (void)handleMessage:(int)msgid data:(NSData *)data
479     //NSLog(@"%@ %s", [self className], _cmd);
481     if (OpenVimWindowMsgID == msgid) {
482         [windowController openWindow];
483     } else if (BatchDrawMsgID == msgid) {
484         [self performBatchDrawWithData:data];
485     } else if (SelectTabMsgID == msgid) {
486 #if 0   // NOTE: Tab selection is done inside updateTabsWithData:.
487         const void *bytes = [data bytes];
488         int idx = *((int*)bytes);
489         //NSLog(@"Selecting tab with index %d", idx);
490         [windowController selectTabWithIndex:idx];
491 #endif
492     } else if (UpdateTabBarMsgID == msgid) {
493         [windowController updateTabsWithData:data];
494     } else if (ShowTabBarMsgID == msgid) {
495         [windowController showTabBar:YES];
496     } else if (HideTabBarMsgID == msgid) {
497         [windowController showTabBar:NO];
498     } else if (SetTextDimensionsMsgID == msgid) {
499         const void *bytes = [data bytes];
500         int rows = *((int*)bytes);  bytes += sizeof(int);
501         int cols = *((int*)bytes);  bytes += sizeof(int);
503         [windowController setTextDimensionsWithRows:rows columns:cols];
504     } else if (SetWindowTitleMsgID == msgid) {
505         const void *bytes = [data bytes];
506         int len = *((int*)bytes);  bytes += sizeof(int);
508         NSString *string = [[NSString alloc] initWithBytes:(void*)bytes
509                 length:len encoding:NSUTF8StringEncoding];
511         [[windowController window] setTitle:string];
513         [string release];
514     } else if (AddMenuMsgID == msgid) {
515         NSString *title = nil;
516         const void *bytes = [data bytes];
517         int tag = *((int*)bytes);  bytes += sizeof(int);
518         int parentTag = *((int*)bytes);  bytes += sizeof(int);
519         int len = *((int*)bytes);  bytes += sizeof(int);
520         if (len > 0) {
521             title = [[NSString alloc] initWithBytes:(void*)bytes length:len
522                                            encoding:NSUTF8StringEncoding];
523             bytes += len;
524         }
525         int idx = *((int*)bytes);  bytes += sizeof(int);
527         if (MenuToolbarType == parentTag) {
528             if (!toolbar) {
529                 // NOTE! Each toolbar must have a unique identifier, else each
530                 // window will have the same toolbar.
531                 NSString *ident = [NSString stringWithFormat:@"%d.%d",
532                          (int)self, tag];
533                 toolbar = [[NSToolbar alloc] initWithIdentifier:ident];
535                 [toolbar setShowsBaselineSeparator:NO];
536                 [toolbar setDelegate:self];
537                 [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
538                 [toolbar setSizeMode:NSToolbarSizeModeSmall];
540                 NSWindow *win = [windowController window];
541                 [win setToolbar:toolbar];
543                 // HACK! Redirect the pill button so that we can ask Vim to
544                 // hide the toolbar.
545                 NSButton *pillButton = [win
546                     standardWindowButton:NSWindowToolbarButton];
547                 if (pillButton) {
548                     [pillButton setAction:@selector(toggleToolbar:)];
549                     [pillButton setTarget:windowController];
550                 }
551             }
552         } else if (title) {
553             [self addMenuWithTag:tag parent:parentTag title:title atIndex:idx];
554         }
556         [title release];
557     } else if (AddMenuItemMsgID == msgid) {
558         NSString *title = nil, *tip = nil, *icon = nil, *action = nil;
559         const void *bytes = [data bytes];
560         int tag = *((int*)bytes);  bytes += sizeof(int);
561         int parentTag = *((int*)bytes);  bytes += sizeof(int);
562         int namelen = *((int*)bytes);  bytes += sizeof(int);
563         if (namelen > 0) {
564             title = [[NSString alloc] initWithBytes:(void*)bytes length:namelen
565                                            encoding:NSUTF8StringEncoding];
566             bytes += namelen;
567         }
568         int tiplen = *((int*)bytes);  bytes += sizeof(int);
569         if (tiplen > 0) {
570             tip = [[NSString alloc] initWithBytes:(void*)bytes length:tiplen
571                                            encoding:NSUTF8StringEncoding];
572             bytes += tiplen;
573         }
574         int iconlen = *((int*)bytes);  bytes += sizeof(int);
575         if (iconlen > 0) {
576             icon = [[NSString alloc] initWithBytes:(void*)bytes length:iconlen
577                                            encoding:NSUTF8StringEncoding];
578             bytes += iconlen;
579         }
580         int actionlen = *((int*)bytes);  bytes += sizeof(int);
581         if (actionlen > 0) {
582             action = [[NSString alloc] initWithBytes:(void*)bytes
583                                               length:actionlen
584                                             encoding:NSUTF8StringEncoding];
585             bytes += actionlen;
586         }
587         int idx = *((int*)bytes);  bytes += sizeof(int);
588         if (idx < 0) idx = 0;
589         int key = *((int*)bytes);  bytes += sizeof(int);
590         int mask = *((int*)bytes);  bytes += sizeof(int);
592         NSString *ident = [NSString stringWithFormat:@"%d.%d",
593                 (int)self, parentTag];
594         if (toolbar && [[toolbar identifier] isEqual:ident]) {
595             [self addToolbarItemWithTag:tag label:title tip:tip icon:icon
596                                 atIndex:idx];
597         } else {
598             NSMenu *parent = [self menuForTag:parentTag];
599             [self addMenuItemWithTag:tag parent:parent title:title tip:tip
600                        keyEquivalent:key modifiers:mask action:action
601                              atIndex:idx];
602         }
604         [title release];
605         [tip release];
606         [icon release];
607         [action release];
608     } else if (RemoveMenuItemMsgID == msgid) {
609         const void *bytes = [data bytes];
610         int tag = *((int*)bytes);  bytes += sizeof(int);
612         id item;
613         int idx;
614         if ((item = [self toolbarItemForTag:tag index:&idx])) {
615             [toolbar removeItemAtIndex:idx];
616         } else if ((item = [self menuItemForTag:tag])) {
617             [item retain];
619             if ([item menu] == [NSApp mainMenu] || ![item menu]) {
620                 // NOTE: To be on the safe side we try to remove the item from
621                 // both arrays (it is ok to call removeObject: even if an array
622                 // does not contain the object to remove).
623                 [mainMenuItems removeObject:item];
624                 [popupMenuItems removeObject:item];
625             }
627             if ([item menu])
628                 [[item menu] removeItem:item];
630             [item release];
631         }
633         // Reset cached menu, just to be on the safe side.
634         lastMenuSearched = nil;
635     } else if (EnableMenuItemMsgID == msgid) {
636         const void *bytes = [data bytes];
637         int tag = *((int*)bytes);  bytes += sizeof(int);
638         int state = *((int*)bytes);  bytes += sizeof(int);
640         id item = [self toolbarItemForTag:tag index:NULL];
641         if (!item)
642             item = [self menuItemForTag:tag];
644         [item setEnabled:state];
645     } else if (ShowToolbarMsgID == msgid) {
646         const void *bytes = [data bytes];
647         int enable = *((int*)bytes);  bytes += sizeof(int);
648         int flags = *((int*)bytes);  bytes += sizeof(int);
650         int mode = NSToolbarDisplayModeDefault;
651         if (flags & ToolbarLabelFlag) {
652             mode = flags & ToolbarIconFlag ? NSToolbarDisplayModeIconAndLabel
653                     : NSToolbarDisplayModeLabelOnly;
654         } else if (flags & ToolbarIconFlag) {
655             mode = NSToolbarDisplayModeIconOnly;
656         }
658         int size = flags & ToolbarSizeRegularFlag ? NSToolbarSizeModeRegular
659                 : NSToolbarSizeModeSmall;
661         [windowController showToolbar:enable size:size mode:mode];
662     } else if (CreateScrollbarMsgID == msgid) {
663         const void *bytes = [data bytes];
664         long ident = *((long*)bytes);  bytes += sizeof(long);
665         int type = *((int*)bytes);  bytes += sizeof(int);
667         [windowController createScrollbarWithIdentifier:ident type:type];
668     } else if (DestroyScrollbarMsgID == msgid) {
669         const void *bytes = [data bytes];
670         long ident = *((long*)bytes);  bytes += sizeof(long);
672         [windowController destroyScrollbarWithIdentifier:ident];
673     } else if (ShowScrollbarMsgID == msgid) {
674         const void *bytes = [data bytes];
675         long ident = *((long*)bytes);  bytes += sizeof(long);
676         int visible = *((int*)bytes);  bytes += sizeof(int);
678         [windowController showScrollbarWithIdentifier:ident state:visible];
679     } else if (SetScrollbarPositionMsgID == msgid) {
680         const void *bytes = [data bytes];
681         long ident = *((long*)bytes);  bytes += sizeof(long);
682         int pos = *((int*)bytes);  bytes += sizeof(int);
683         int len = *((int*)bytes);  bytes += sizeof(int);
685         [windowController setScrollbarPosition:pos length:len
686                                     identifier:ident];
687     } else if (SetScrollbarThumbMsgID == msgid) {
688         const void *bytes = [data bytes];
689         long ident = *((long*)bytes);  bytes += sizeof(long);
690         float val = *((float*)bytes);  bytes += sizeof(float);
691         float prop = *((float*)bytes);  bytes += sizeof(float);
693         [windowController setScrollbarThumbValue:val proportion:prop
694                                       identifier:ident];
695     } else if (SetFontMsgID == msgid) {
696         const void *bytes = [data bytes];
697         float size = *((float*)bytes);  bytes += sizeof(float);
698         int len = *((int*)bytes);  bytes += sizeof(int);
699         NSString *name = [[NSString alloc]
700                 initWithBytes:(void*)bytes length:len
701                      encoding:NSUTF8StringEncoding];
702         NSFont *font = [NSFont fontWithName:name size:size];
704         if (font)
705             [windowController setFont:font];
707         [name release];
708     } else if (SetDefaultColorsMsgID == msgid) {
709         const void *bytes = [data bytes];
710         unsigned bg = *((unsigned*)bytes);  bytes += sizeof(unsigned);
711         unsigned fg = *((unsigned*)bytes);  bytes += sizeof(unsigned);
712         NSColor *back = [NSColor colorWithArgbInt:bg];
713         NSColor *fore = [NSColor colorWithRgbInt:fg];
715         [windowController setDefaultColorsBackground:back foreground:fore];
716     } else if (ExecuteActionMsgID == msgid) {
717         const void *bytes = [data bytes];
718         int len = *((int*)bytes);  bytes += sizeof(int);
719         NSString *actionName = [[NSString alloc]
720                 initWithBytesNoCopy:(void*)bytes
721                              length:len
722                            encoding:NSUTF8StringEncoding
723                        freeWhenDone:NO];
725         SEL sel = NSSelectorFromString(actionName);
726         [NSApp sendAction:sel to:nil from:self];
728         [actionName release];
729     } else if (ShowPopupMenuMsgID == msgid) {
730         const void *bytes = [data bytes];
731         int row = *((int*)bytes);  bytes += sizeof(int);
732         int col = *((int*)bytes);  bytes += sizeof(int);
733         int len = *((int*)bytes);  bytes += sizeof(int);
734         NSString *title = [[NSString alloc]
735                 initWithBytesNoCopy:(void*)bytes
736                              length:len
737                            encoding:NSUTF8StringEncoding
738                        freeWhenDone:NO];
740         NSMenu *menu = [self topLevelMenuForTitle:title];
741         if (menu) {
742             [windowController popupMenu:menu atRow:row column:col];
743         } else {
744             NSLog(@"WARNING: Cannot popup menu with title %@; no such menu.",
745                     title);
746         }
748         [title release];
749     } else if (SetMouseShapeMsgID == msgid) {
750         const void *bytes = [data bytes];
751         int shape = *((int*)bytes);  bytes += sizeof(int);
753         [windowController setMouseShape:shape];
754     } else if (AdjustLinespaceMsgID == msgid) {
755         const void *bytes = [data bytes];
756         int linespace = *((int*)bytes);  bytes += sizeof(int);
758         [windowController adjustLinespace:linespace];
759     } else if (ActivateMsgID == msgid) {
760         [NSApp activateIgnoringOtherApps:YES];
761         [[windowController window] makeKeyAndOrderFront:self];
762     } else if (SetServerNameMsgID == msgid) {
763         NSString *name = [[NSString alloc] initWithData:data
764                                                encoding:NSUTF8StringEncoding];
765         [self setServerName:name];
766         [name release];
767     } else if (EnterFullscreenMsgID == msgid) {
768         [windowController enterFullscreen];
769     } else if (LeaveFullscreenMsgID == msgid) {
770         [windowController leaveFullscreen];
771     } else if (BuffersNotModifiedMsgID == msgid) {
772         [[windowController window] setDocumentEdited:NO];
773     } else if (BuffersModifiedMsgID == msgid) {
774         [[windowController window] setDocumentEdited:YES];
775     } else {
776         NSLog(@"WARNING: Unknown message received (msgid=%d)", msgid);
777     }
781 #define MM_DEBUG_DRAWING 0
783 - (void)performBatchDrawWithData:(NSData *)data
785     // TODO!  Move to window controller.
786     MMTextStorage *textStorage = [windowController textStorage];
787     MMTextView *textView = [windowController textView];
788     if (!(textStorage && textView))
789         return;
791     const void *bytes = [data bytes];
792     const void *end = bytes + [data length];
794 #if MM_DEBUG_DRAWING
795     NSLog(@"====> BEGIN %s", _cmd);
796 #endif
797     [textStorage beginEditing];
799     // TODO: Sanity check input
801     while (bytes < end) {
802         int type = *((int*)bytes);  bytes += sizeof(int);
804         if (ClearAllDrawType == type) {
805 #if MM_DEBUG_DRAWING
806             NSLog(@"   Clear all");
807 #endif
808             [textStorage clearAll];
809         } else if (ClearBlockDrawType == type) {
810             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
811             int row1 = *((int*)bytes);  bytes += sizeof(int);
812             int col1 = *((int*)bytes);  bytes += sizeof(int);
813             int row2 = *((int*)bytes);  bytes += sizeof(int);
814             int col2 = *((int*)bytes);  bytes += sizeof(int);
816 #if MM_DEBUG_DRAWING
817             NSLog(@"   Clear block (%d,%d) -> (%d,%d)", row1, col1,
818                     row2,col2);
819 #endif
820             [textStorage clearBlockFromRow:row1 column:col1
821                     toRow:row2 column:col2
822                     color:[NSColor colorWithArgbInt:color]];
823         } else if (DeleteLinesDrawType == type) {
824             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
825             int row = *((int*)bytes);  bytes += sizeof(int);
826             int count = *((int*)bytes);  bytes += sizeof(int);
827             int bot = *((int*)bytes);  bytes += sizeof(int);
828             int left = *((int*)bytes);  bytes += sizeof(int);
829             int right = *((int*)bytes);  bytes += sizeof(int);
831 #if MM_DEBUG_DRAWING
832             NSLog(@"   Delete %d line(s) from %d", count, row);
833 #endif
834             [textStorage deleteLinesFromRow:row lineCount:count
835                     scrollBottom:bot left:left right:right
836                            color:[NSColor colorWithArgbInt:color]];
837         } else if (ReplaceStringDrawType == type) {
838             int bg = *((int*)bytes);  bytes += sizeof(int);
839             int fg = *((int*)bytes);  bytes += sizeof(int);
840             int sp = *((int*)bytes);  bytes += sizeof(int);
841             int row = *((int*)bytes);  bytes += sizeof(int);
842             int col = *((int*)bytes);  bytes += sizeof(int);
843             int flags = *((int*)bytes);  bytes += sizeof(int);
844             int len = *((int*)bytes);  bytes += sizeof(int);
845             NSString *string = [[NSString alloc]
846                     initWithBytesNoCopy:(void*)bytes
847                                  length:len
848                                encoding:NSUTF8StringEncoding
849                            freeWhenDone:NO];
850             bytes += len;
852 #if MM_DEBUG_DRAWING
853             NSLog(@"   Draw string at (%d,%d) length=%d flags=%d fg=0x%x "
854                     "bg=0x%x sp=0x%x (%@)", row, col, len, flags, fg, bg, sp,
855                     len > 0 ? [string substringToIndex:1] : @"");
856 #endif
857             // NOTE: If this is a call to draw the (block) cursor, then cancel
858             // any previous request to draw the insertion point, or it might
859             // get drawn as well.
860             if (flags & DRAW_CURSOR) {
861                 [textView setShouldDrawInsertionPoint:NO];
862                 //NSColor *color = [NSColor colorWithRgbInt:bg];
863                 //[textView drawInsertionPointAtRow:row column:col
864                 //                            shape:MMInsertionPointBlock
865                 //                            color:color];
866             }
867             [textStorage replaceString:string
868                                  atRow:row column:col
869                              withFlags:flags
870                        foregroundColor:[NSColor colorWithRgbInt:fg]
871                        backgroundColor:[NSColor colorWithArgbInt:bg]
872                           specialColor:[NSColor colorWithRgbInt:sp]];
874             [string release];
875         } else if (InsertLinesDrawType == type) {
876             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
877             int row = *((int*)bytes);  bytes += sizeof(int);
878             int count = *((int*)bytes);  bytes += sizeof(int);
879             int bot = *((int*)bytes);  bytes += sizeof(int);
880             int left = *((int*)bytes);  bytes += sizeof(int);
881             int right = *((int*)bytes);  bytes += sizeof(int);
883 #if MM_DEBUG_DRAWING
884             NSLog(@"   Insert %d line(s) at row %d", count, row);
885 #endif
886             [textStorage insertLinesAtRow:row lineCount:count
887                              scrollBottom:bot left:left right:right
888                                     color:[NSColor colorWithArgbInt:color]];
889         } else if (DrawCursorDrawType == type) {
890             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
891             int row = *((int*)bytes);  bytes += sizeof(int);
892             int col = *((int*)bytes);  bytes += sizeof(int);
893             int shape = *((int*)bytes);  bytes += sizeof(int);
894             int percent = *((int*)bytes);  bytes += sizeof(int);
896 #if MM_DEBUG_DRAWING
897             NSLog(@"   Draw cursor at (%d,%d)", row, col);
898 #endif
899             [textView drawInsertionPointAtRow:row column:col shape:shape
900                                      fraction:percent
901                                         color:[NSColor colorWithRgbInt:color]];
902         } else {
903             NSLog(@"WARNING: Unknown draw type (type=%d)", type);
904         }
905     }
907     [textStorage endEditing];
909     // NOTE: During resizing, Cocoa only sends draw messages before Vim's rows
910     // and columns are changed (due to ipc delays). Force a redraw here.
911     [[windowController vimView] displayIfNeeded];
913 #if MM_DEBUG_DRAWING
914     NSLog(@"<==== END   %s", _cmd);
915 #endif
918 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
919                 context:(void *)context
921     NSString *string = (code == NSOKButton) ? [panel filename] : nil;
922     @try {
923         [backendProxy setDialogReturn:string];
924     }
925     @catch (NSException *e) {
926         NSLog(@"Exception caught in %s %@", _cmd, e);
927     }
930 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context
932     NSArray *ret = nil;
934     code = code - NSAlertFirstButtonReturn + 1;
936     if ([alert isKindOfClass:[MMAlert class]] && [alert textField]) {
937         ret = [NSArray arrayWithObjects:[NSNumber numberWithInt:code],
938             [[alert textField] stringValue], nil];
939     } else {
940         ret = [NSArray arrayWithObject:[NSNumber numberWithInt:code]];
941     }
943     @try {
944         [backendProxy setDialogReturn:ret];
945     }
946     @catch (NSException *e) {
947         NSLog(@"Exception caught in %s %@", _cmd, e);
948     }
951 - (NSMenuItem *)recurseMenuItemForTag:(int)tag rootMenu:(NSMenu *)root
953     if (root) {
954         NSMenuItem *item = [root itemWithTag:tag];
955         if (item) {
956             lastMenuSearched = root;
957             return item;
958         }
960         NSArray *items = [root itemArray];
961         unsigned i, count = [items count];
962         for (i = 0; i < count; ++i) {
963             item = [items objectAtIndex:i];
964             if ([item hasSubmenu]) {
965                 item = [self recurseMenuItemForTag:tag
966                                           rootMenu:[item submenu]];
967                 if (item) {
968                     lastMenuSearched = [item submenu];
969                     return item;
970                 }
971             }
972         }
973     }
975     return nil;
978 - (NSMenuItem *)menuItemForTag:(int)tag
980     // First search the same menu that was search last time this method was
981     // called.  Since this method is often called for each menu item in a
982     // menu this can significantly improve search times.
983     if (lastMenuSearched) {
984         NSMenuItem *item = [self recurseMenuItemForTag:tag
985                                               rootMenu:lastMenuSearched];
986         if (item) return item;
987     }
989     // Search the main menu.
990     int i, count = [mainMenuItems count];
991     for (i = 0; i < count; ++i) {
992         NSMenuItem *item = [mainMenuItems objectAtIndex:i];
993         if ([item tag] == tag) return item;
994         item = [self recurseMenuItemForTag:tag rootMenu:[item submenu]];
995         if (item) {
996             lastMenuSearched = [item submenu];
997             return item;
998         }
999     }
1001     // Search the popup menus.
1002     count = [popupMenuItems count];
1003     for (i = 0; i < count; ++i) {
1004         NSMenuItem *item = [popupMenuItems objectAtIndex:i];
1005         if ([item tag] == tag) return item;
1006         item = [self recurseMenuItemForTag:tag rootMenu:[item submenu]];
1007         if (item) {
1008             lastMenuSearched = [item submenu];
1009             return item;
1010         }
1011     }
1013     return nil;
1016 - (NSMenu *)menuForTag:(int)tag
1018     return [[self menuItemForTag:tag] submenu];
1021 - (NSMenu *)topLevelMenuForTitle:(NSString *)title
1023     // Search only the top-level menus.
1025     unsigned i, count = [popupMenuItems count];
1026     for (i = 0; i < count; ++i) {
1027         NSMenuItem *item = [popupMenuItems objectAtIndex:i];
1028         if ([title isEqual:[item title]])
1029             return [item submenu];
1030     }
1032     count = [mainMenuItems count];
1033     for (i = 0; i < count; ++i) {
1034         NSMenuItem *item = [mainMenuItems objectAtIndex:i];
1035         if ([title isEqual:[item title]])
1036             return [item submenu];
1037     }
1039     return nil;
1042 - (void)addMenuWithTag:(int)tag parent:(int)parentTag title:(NSString *)title
1043                atIndex:(int)idx
1045     NSMenu *parent = [self menuForTag:parentTag];
1046     NSMenuItem *item = [[NSMenuItem alloc] init];
1047     NSMenu *menu = [[NSMenu alloc] initWithTitle:title];
1049     [menu setAutoenablesItems:NO];
1050     [item setTag:tag];
1051     [item setTitle:title];
1052     [item setSubmenu:menu];
1054     if (parent) {
1055         if ([parent numberOfItems] <= idx) {
1056             [parent addItem:item];
1057         } else {
1058             [parent insertItem:item atIndex:idx];
1059         }
1060     } else {
1061         NSMutableArray *items = (MenuPopupType == parentTag)
1062             ? popupMenuItems : mainMenuItems;
1063         if ([items count] <= idx) {
1064             [items addObject:item];
1065         } else {
1066             [items insertObject:item atIndex:idx];
1067         }
1069         shouldUpdateMainMenu = (MenuPopupType != parentTag);
1070     }
1072     [item release];
1073     [menu release];
1076 - (void)addMenuItemWithTag:(int)tag parent:(NSMenu *)parent
1077                      title:(NSString *)title tip:(NSString *)tip
1078              keyEquivalent:(int)key modifiers:(int)mask
1079                     action:(NSString *)action atIndex:(int)idx
1081     if (parent) {
1082         NSMenuItem *item = nil;
1083         if (!title || ([title hasPrefix:@"-"] && [title hasSuffix:@"-"])) {
1084             item = [NSMenuItem separatorItem];
1085         } else {
1086             item = [[[NSMenuItem alloc] init] autorelease];
1087             [item setTitle:title];
1088             // TODO: Check that 'action' is a valid action (nothing will happen
1089             // if it isn't, but it would be nice with a warning).
1090             if (action) [item setAction:NSSelectorFromString(action)];
1091             else        [item setAction:@selector(vimMenuItemAction:)];
1092             if (tip) [item setToolTip:tip];
1094             if (key != 0) {
1095                 NSString *keyString =
1096                     [NSString stringWithFormat:@"%C", key];
1097                 [item setKeyEquivalent:keyString];
1098                 [item setKeyEquivalentModifierMask:mask];
1099             }
1100         }
1102         // NOTE!  The tag is used to idenfity which menu items were
1103         // added by Vim (tag != 0) and which were added by the AppKit
1104         // (tag == 0).
1105         [item setTag:tag];
1107         if ([parent numberOfItems] <= idx) {
1108             [parent addItem:item];
1109         } else {
1110             [parent insertItem:item atIndex:idx];
1111         }
1112     } else {
1113         NSLog(@"WARNING: Menu item '%@' (tag=%d) has no parent.", title, tag);
1114     }
1117 - (void)updateMainMenu
1119     NSMenu *mainMenu = [NSApp mainMenu];
1121     // Stop NSApp from updating the Window menu.
1122     [NSApp setWindowsMenu:nil];
1124     // Remove all menus from main menu (except the MacVim menu).
1125     int i, count = [mainMenu numberOfItems];
1126     for (i = count-1; i > 0; --i) {
1127         [mainMenu removeItemAtIndex:i];
1128     }
1130     // Add menus from 'mainMenuItems' to main menu.
1131     count = [mainMenuItems count];
1132     for (i = 0; i < count; ++i) {
1133         [mainMenu addItem:[mainMenuItems objectAtIndex:i]];
1134     }
1136     // Set the new Window menu.
1137     // TODO!  Need to look for 'Window' in all localized languages.
1138     NSMenu *windowMenu = [[mainMenu itemWithTitle:@"Window"] submenu];
1139     if (windowMenu) {
1140         // Remove all AppKit owned menu items (tag == 0); they will be added
1141         // again when setWindowsMenu: is called.
1142         count = [windowMenu numberOfItems];
1143         for (i = count-1; i >= 0; --i) {
1144             NSMenuItem *item = [windowMenu itemAtIndex:i];
1145             if (![item tag]) {
1146                 [windowMenu removeItem:item];
1147             }
1148         }
1150         [NSApp setWindowsMenu:windowMenu];
1151     }
1153     shouldUpdateMainMenu = NO;
1156 - (NSToolbarItem *)toolbarItemForTag:(int)tag index:(int *)index
1158     if (!toolbar) return nil;
1160     NSArray *items = [toolbar items];
1161     int i, count = [items count];
1162     for (i = 0; i < count; ++i) {
1163         NSToolbarItem *item = [items objectAtIndex:i];
1164         if ([item tag] == tag) {
1165             if (index) *index = i;
1166             return item;
1167         }
1168     }
1170     return nil;
1173 - (void)addToolbarItemToDictionaryWithTag:(int)tag label:(NSString *)title
1174         toolTip:(NSString *)tip icon:(NSString *)icon
1176     // If the item corresponds to a separator then do nothing, since it is
1177     // already defined by Cocoa.
1178     if (!title || [title isEqual:NSToolbarSeparatorItemIdentifier]
1179                || [title isEqual:NSToolbarSpaceItemIdentifier]
1180                || [title isEqual:NSToolbarFlexibleSpaceItemIdentifier])
1181         return;
1183     NSToolbarItem *item = [[NSToolbarItem alloc] initWithItemIdentifier:title];
1184     [item setTag:tag];
1185     [item setLabel:title];
1186     [item setToolTip:tip];
1187     [item setAction:@selector(vimMenuItemAction:)];
1188     [item setAutovalidates:NO];
1190     NSImage *img = [NSImage imageNamed:icon];
1191     if (!img) {
1192         NSLog(@"WARNING: Could not find image with name '%@' to use as toolbar"
1193                " image for identifier '%@';"
1194                " using default toolbar icon '%@' instead.",
1195                icon, title, MMDefaultToolbarImageName);
1197         img = [NSImage imageNamed:MMDefaultToolbarImageName];
1198     }
1200     [item setImage:img];
1202     [toolbarItemDict setObject:item forKey:title];
1204     [item release];
1207 - (void)addToolbarItemWithTag:(int)tag label:(NSString *)label tip:(NSString
1208                    *)tip icon:(NSString *)icon atIndex:(int)idx
1210     if (!toolbar) return;
1212     // Check for separator items.
1213     if (!label) {
1214         label = NSToolbarSeparatorItemIdentifier;
1215     } else if ([label length] >= 2 && [label hasPrefix:@"-"]
1216                                    && [label hasSuffix:@"-"]) {
1217         // The label begins and ends with '-'; decided which kind of separator
1218         // item it is by looking at the prefix.
1219         if ([label hasPrefix:@"-space"]) {
1220             label = NSToolbarSpaceItemIdentifier;
1221         } else if ([label hasPrefix:@"-flexspace"]) {
1222             label = NSToolbarFlexibleSpaceItemIdentifier;
1223         } else {
1224             label = NSToolbarSeparatorItemIdentifier;
1225         }
1226     }
1228     [self addToolbarItemToDictionaryWithTag:tag label:label toolTip:tip
1229                                        icon:icon];
1231     int maxIdx = [[toolbar items] count];
1232     if (maxIdx < idx) idx = maxIdx;
1234     [toolbar insertItemWithItemIdentifier:label atIndex:idx];
1237 - (void)connectionDidDie:(NSNotification *)notification
1239     //NSLog(@"%@ %s%@", [self className], _cmd, notification);
1241     [self cleanup];
1243     // NOTE!  This causes the call to removeVimController: to be delayed.
1244     [[NSApp delegate]
1245             performSelectorOnMainThread:@selector(removeVimController:)
1246                              withObject:self waitUntilDone:NO];
1249 - (NSString *)description
1251     return [NSString stringWithFormat:@"%@ : isInitialized=%d inProcessCommandQueue=%d mainMenuItems=%@ popupMenuItems=%@ toolbar=%@", [self className], isInitialized, inProcessCommandQueue, mainMenuItems, popupMenuItems, toolbar];
1254 #if MM_RESEND_LAST_FAILURE
1255 - (void)resendTimerFired:(NSTimer *)timer
1257     int msgid = resendMsgid;
1258     NSData *data = nil;
1260     [resendTimer release];
1261     resendTimer = nil;
1263     if (!isInitialized)
1264         return;
1266     if (resendData)
1267         data = [resendData copy];
1269     //NSLog(@"Resending message: %s", MessageStrings[msgid]);
1270     [self sendMessage:msgid data:data];
1272 #endif
1274 @end // MMVimController (Private)
1278 @implementation NSColor (MMProtocol)
1280 + (NSColor *)colorWithRgbInt:(unsigned)rgb
1282     float r = ((rgb>>16) & 0xff)/255.0f;
1283     float g = ((rgb>>8) & 0xff)/255.0f;
1284     float b = (rgb & 0xff)/255.0f;
1286     return [NSColor colorWithCalibratedRed:r green:g blue:b alpha:1.0f];
1289 + (NSColor *)colorWithArgbInt:(unsigned)argb
1291     float a = ((argb>>24) & 0xff)/255.0f;
1292     float r = ((argb>>16) & 0xff)/255.0f;
1293     float g = ((argb>>8) & 0xff)/255.0f;
1294     float b = (argb & 0xff)/255.0f;
1296     return [NSColor colorWithCalibratedRed:r green:g blue:b alpha:a];
1299 @end // NSColor (MMProtocol)
1303 @implementation MMAlert
1304 - (void)dealloc
1306     [textField release];
1307     [super dealloc];
1310 - (void)setTextFieldString:(NSString *)textFieldString
1312     [textField release];
1313     textField = [[NSTextField alloc] init];
1314     [textField setStringValue:textFieldString];
1317 - (NSTextField *)textField
1319     return textField;
1322 - (void)setInformativeText:(NSString *)text
1324     if (textField) {
1325         // HACK! Add some space for the text field.
1326         [super setInformativeText:[text stringByAppendingString:@"\n\n\n"]];
1327     } else {
1328         [super setInformativeText:text];
1329     }
1332 - (void)beginSheetModalForWindow:(NSWindow *)window
1333                    modalDelegate:(id)delegate
1334                   didEndSelector:(SEL)didEndSelector
1335                      contextInfo:(void *)contextInfo
1337     [super beginSheetModalForWindow:window
1338                       modalDelegate:delegate
1339                      didEndSelector:didEndSelector
1340                         contextInfo:contextInfo];
1342     // HACK! Place the input text field at the bottom of the informative text
1343     // (which has been made a bit larger by adding newline characters).
1344     NSView *contentView = [[self window] contentView];
1345     NSRect rect = [contentView frame];
1346     rect.origin.y = rect.size.height;
1348     NSArray *subviews = [contentView subviews];
1349     unsigned i, count = [subviews count];
1350     for (i = 0; i < count; ++i) {
1351         NSView *view = [subviews objectAtIndex:i];
1352         if ([view isKindOfClass:[NSTextField class]]
1353                 && [view frame].origin.y < rect.origin.y) {
1354             // NOTE: The informative text field is the lowest NSTextField in
1355             // the alert dialog.
1356             rect = [view frame];
1357         }
1358     }
1360     rect.size.height = MMAlertTextFieldHeight;
1361     [textField setFrame:rect];
1362     [contentView addSubview:textField];
1363     [textField becomeFirstResponder];
1366 @end // MMAlert