Changed date
[MacVim/jjgod.git] / MMVimController.m
blobea3ca67c07fe664144216dc56ee8eed57d486ced
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 *)menuItemForTag:(int)tag;
53 - (NSMenu *)menuForTag:(int)tag;
54 - (NSMenu *)topLevelMenuForTitle:(NSString *)title;
55 - (void)addMenuWithTag:(int)tag parent:(int)parentTag title:(NSString *)title
56                atIndex:(int)idx;
57 - (void)addMenuItemWithTag:(int)tag parent:(NSMenu *)parent
58                      title:(NSString *)title tip:(NSString *)tip
59              keyEquivalent:(int)key modifiers:(int)mask
60                     action:(NSString *)action atIndex:(int)idx;
61 - (void)updateMainMenu;
62 - (NSToolbarItem *)toolbarItemForTag:(int)tag index:(int *)index;
63 - (void)addToolbarItemToDictionaryWithTag:(int)tag label:(NSString *)title
64         toolTip:(NSString *)tip icon:(NSString *)icon;
65 - (void)addToolbarItemWithTag:(int)tag label:(NSString *)label
66                           tip:(NSString *)tip icon:(NSString *)icon
67                       atIndex:(int)idx;
68 - (void)connectionDidDie:(NSNotification *)notification;
69 #if MM_RESEND_LAST_FAILURE
70 - (void)resendTimerFired:(NSTimer *)timer;
71 #endif
72 @end
76 // TODO: Move to separate file
77 @interface NSColor (MMProtocol)
78 + (NSColor *)colorWithRgbInt:(int)rgb;
79 @end
83 static NSMenuItem *findMenuItemWithTagInMenu(NSMenu *root, int tag)
85     if (root) {
86         NSMenuItem *item = [root itemWithTag:tag];
87         if (item) return item;
89         NSArray *items = [root itemArray];
90         unsigned i, count = [items count];
91         for (i = 0; i < count; ++i) {
92             item = [items objectAtIndex:i];
93             if ([item hasSubmenu]) {
94                 item = findMenuItemWithTagInMenu([item submenu], tag);
95                 if (item) return item;
96             }
97         }
98     }
100     return nil;
105 @implementation MMVimController
107 - (id)initWithBackend:(id)backend pid:(int)processIdentifier
109     if ((self = [super init])) {
110         windowController =
111             [[MMWindowController alloc] initWithVimController:self];
112         backendProxy = [backend retain];
113         sendQueue = [NSMutableArray new];
114         mainMenuItems = [[NSMutableArray alloc] init];
115         popupMenuItems = [[NSMutableArray alloc] init];
116         toolbarItemDict = [[NSMutableDictionary alloc] init];
117         pid = processIdentifier;
119         NSConnection *connection = [backendProxy connectionForProxy];
121         // TODO: Check that this will not set the timeout for the root proxy
122         // (in MMAppController).
123         [connection setRequestTimeout:MMBackendProxyRequestTimeout];
125         [[NSNotificationCenter defaultCenter] addObserver:self
126                 selector:@selector(connectionDidDie:)
127                     name:NSConnectionDidDieNotification object:connection];
130         NSWindow *win = [windowController window];
132         [[NSNotificationCenter defaultCenter]
133                 addObserver:self
134                    selector:@selector(windowDidBecomeMain:)
135                        name:NSWindowDidBecomeMainNotification
136                      object:win];
138         isInitialized = YES;
139     }
141     return self;
144 - (void)dealloc
146     //NSLog(@"%@ %s", [self className], _cmd);
147     isInitialized = NO;
149 #if MM_RESEND_LAST_FAILURE
150     [resendData release];  resendData = nil;
151 #endif
153     [serverName release];  serverName = nil;
154     [backendProxy release];  backendProxy = nil;
155     [sendQueue release];  sendQueue = nil;
157     [toolbarItemDict release];  toolbarItemDict = nil;
158     [toolbar release];  toolbar = nil;
159     [popupMenuItems release];  popupMenuItems = nil;
160     [mainMenuItems release];  mainMenuItems = nil;
161     [windowController release];  windowController = nil;
163     [super dealloc];
166 - (MMWindowController *)windowController
168     return windowController;
171 - (void)setServerName:(NSString *)name
173     if (name != serverName) {
174         [serverName release];
175         serverName = [name copy];
176     }
179 - (NSString *)serverName
181     return serverName;
184 - (int)pid
186     return pid;
189 - (void)dropFiles:(NSArray *)filenames
191     int i, numberOfFiles = [filenames count];
192     NSMutableData *data = [NSMutableData data];
194     [data appendBytes:&numberOfFiles length:sizeof(int)];
196     for (i = 0; i < numberOfFiles; ++i) {
197         NSString *file = [filenames objectAtIndex:i];
198         int len = [file lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
200         if (len > 0) {
201             ++len;  // append NUL as well
202             [data appendBytes:&len length:sizeof(int)];
203             [data appendBytes:[file UTF8String] length:len];
204         }
205     }
207     [self sendMessage:DropFilesMsgID data:data];
210 - (void)dropString:(NSString *)string
212     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
213     if (len > 0) {
214         NSMutableData *data = [NSMutableData data];
216         [data appendBytes:&len length:sizeof(int)];
217         [data appendBytes:[string UTF8String] length:len];
219         [self sendMessage:DropStringMsgID data:data];
220     }
223 - (void)sendMessage:(int)msgid data:(NSData *)data
225     //NSLog(@"sendMessage:%s (isInitialized=%d inProcessCommandQueue=%d)",
226     //        MessageStrings[msgid], isInitialized, inProcessCommandQueue);
228     if (!isInitialized) return;
230     if (inProcessCommandQueue) {
231         //NSLog(@"In process command queue; delaying message send.");
232         [sendQueue addObject:[NSNumber numberWithInt:msgid]];
233         if (data)
234             [sendQueue addObject:data];
235         else
236             [sendQueue addObject:[NSNull null]];
237         return;
238     }
240 #if MM_RESEND_LAST_FAILURE
241     if (resendTimer) {
242         //NSLog(@"cancelling scheduled resend of %s",
243         //        MessageStrings[resendMsgid]);
245         [resendTimer invalidate];
246         [resendTimer release];
247         resendTimer = nil;
248     }
250     if (resendData) {
251         [resendData release];
252         resendData = nil;
253     }
254 #endif
256     @try {
257         [backendProxy processInput:msgid data:data];
258     }
259     @catch (NSException *e) {
260         //NSLog(@"%@ %s Exception caught during DO call: %@",
261         //        [self className], _cmd, e);
262 #if MM_RESEND_LAST_FAILURE
263         //NSLog(@"%s failed, scheduling message %s for resend", _cmd,
264         //        MessageStrings[msgid]);
266         resendMsgid = msgid;
267         resendData = [data retain];
268         resendTimer = [NSTimer
269             scheduledTimerWithTimeInterval:MMResendInterval
270                                     target:self
271                                   selector:@selector(resendTimerFired:)
272                                   userInfo:nil
273                                    repeats:NO];
274         [resendTimer retain];
275 #endif
276     }
279 - (id)backendProxy
281     return backendProxy;
284 - (void)cleanup
286     //NSLog(@"%@ %s", [self className], _cmd);
287     if (!isInitialized) return;
289     isInitialized = NO;
290     [toolbar setDelegate:nil];
291     [[NSNotificationCenter defaultCenter] removeObserver:self];
292     [windowController cleanup];
295 - (oneway void)showSavePanelForDirectory:(in bycopy NSString *)dir
296                                    title:(in bycopy NSString *)title
297                                   saving:(int)saving
299     if (!isInitialized) return;
301     if (saving) {
302         [[NSSavePanel savePanel] beginSheetForDirectory:dir file:nil
303                 modalForWindow:[windowController window]
304                  modalDelegate:self
305                 didEndSelector:@selector(savePanelDidEnd:code:context:)
306                    contextInfo:NULL];
307     } else {
308         NSOpenPanel *panel = [NSOpenPanel openPanel];
309         [panel setAllowsMultipleSelection:NO];
310         [panel beginSheetForDirectory:dir file:nil types:nil
311                 modalForWindow:[windowController window]
312                  modalDelegate:self
313                 didEndSelector:@selector(savePanelDidEnd:code:context:)
314                    contextInfo:NULL];
315     }
318 - (oneway void)presentDialogWithStyle:(int)style
319                               message:(in bycopy NSString *)message
320                       informativeText:(in bycopy NSString *)text
321                          buttonTitles:(in bycopy NSArray *)buttonTitles
322                       textFieldString:(in bycopy NSString *)textFieldString
324     if (!(windowController && buttonTitles && [buttonTitles count])) return;
326     MMAlert *alert = [[MMAlert alloc] init];
328     // NOTE! This has to be done before setting the informative text.
329     if (textFieldString)
330         [alert setTextFieldString:textFieldString];
332     [alert setAlertStyle:style];
334     if (message) {
335         [alert setMessageText:message];
336     } else {
337         // If no message text is specified 'Alert' is used, which we don't
338         // want, so set an empty string as message text.
339         [alert setMessageText:@""];
340     }
342     if (text) {
343         [alert setInformativeText:text];
344     } else if (textFieldString) {
345         // Make sure there is always room for the input text field.
346         [alert setInformativeText:@""];
347     }
349     unsigned i, count = [buttonTitles count];
350     for (i = 0; i < count; ++i) {
351         NSString *title = [buttonTitles objectAtIndex:i];
352         // NOTE: The title of the button may contain the character '&' to
353         // indicate that the following letter should be the key equivalent
354         // associated with the button.  Extract this letter and lowercase it.
355         NSString *keyEquivalent = nil;
356         NSRange hotkeyRange = [title rangeOfString:@"&"];
357         if (NSNotFound != hotkeyRange.location) {
358             if ([title length] > NSMaxRange(hotkeyRange)) {
359                 NSRange keyEquivRange = NSMakeRange(hotkeyRange.location+1, 1);
360                 keyEquivalent = [[title substringWithRange:keyEquivRange]
361                     lowercaseString];
362             }
364             NSMutableString *string = [NSMutableString stringWithString:title];
365             [string deleteCharactersInRange:hotkeyRange];
366             title = string;
367         }
369         [alert addButtonWithTitle:title];
371         // Set key equivalent for the button, but only if NSAlert hasn't
372         // already done so.  (Check the documentation for
373         // - [NSAlert addButtonWithTitle:] to see what key equivalents are
374         // automatically assigned.)
375         NSButton *btn = [[alert buttons] lastObject];
376         if ([[btn keyEquivalent] length] == 0 && keyEquivalent) {
377             [btn setKeyEquivalent:keyEquivalent];
378         }
379     }
381     [alert beginSheetModalForWindow:[windowController window]
382                       modalDelegate:self
383                      didEndSelector:@selector(alertDidEnd:code:context:)
384                         contextInfo:NULL];
386     [alert release];
389 - (oneway void)processCommandQueue:(in NSArray *)queue
391     if (!isInitialized) return;
393     unsigned i, count = [queue count];
394     if (count % 2) {
395         NSLog(@"WARNING: Uneven number of components (%d) in flush queue "
396                 "message; ignoring this message.", count);
397         return;
398     }
400     inProcessCommandQueue = YES;
402     //NSLog(@"======== %s BEGIN ========", _cmd);
403     for (i = 0; i < count; i += 2) {
404         NSData *value = [queue objectAtIndex:i];
405         NSData *data = [queue objectAtIndex:i+1];
407         int msgid = *((int*)[value bytes]);
408 #if 0
409         if (msgid != EnableMenuItemMsgID && msgid != AddMenuItemMsgID
410                 && msgid != AddMenuMsgID) {
411             NSLog(@"%s%s", _cmd, MessageStrings[msgid]);
412         }
413 #endif
415         [self handleMessage:msgid data:data];
416     }
417     //NSLog(@"======== %s  END  ========", _cmd);
419     if (shouldUpdateMainMenu) {
420         [self updateMainMenu];
421     }
423     [windowController processCommandQueueDidFinish];
425     inProcessCommandQueue = NO;
427     if ([sendQueue count] > 0) {
428         @try {
429             [backendProxy processInputAndData:sendQueue];
430         }
431         @catch (NSException *e) {
432             // Connection timed out, just ignore this.
433             //NSLog(@"WARNING! Connection timed out in %s", _cmd);
434         }
436         [sendQueue removeAllObjects];
437     }
440 - (void)windowDidBecomeMain:(NSNotification *)notification
442     if (isInitialized)
443         [self updateMainMenu];
446 - (NSToolbarItem *)toolbar:(NSToolbar *)theToolbar
447     itemForItemIdentifier:(NSString *)itemId
448     willBeInsertedIntoToolbar:(BOOL)flag
450     NSToolbarItem *item = [toolbarItemDict objectForKey:itemId];
451     if (!item) {
452         NSLog(@"WARNING:  No toolbar item with id '%@'", itemId);
453     }
455     return item;
458 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)theToolbar
460     return nil;
463 - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)theToolbar
465     return nil;
468 @end // MMVimController
472 @implementation MMVimController (Private)
474 - (void)handleMessage:(int)msgid data:(NSData *)data
476     //NSLog(@"%@ %s", [self className], _cmd);
478     if (OpenVimWindowMsgID == msgid) {
479         [windowController openWindow];
480     } else if (BatchDrawMsgID == msgid) {
481         [self performBatchDrawWithData:data];
482     } else if (SelectTabMsgID == msgid) {
483 #if 0   // NOTE: Tab selection is done inside updateTabsWithData:.
484         const void *bytes = [data bytes];
485         int idx = *((int*)bytes);
486         //NSLog(@"Selecting tab with index %d", idx);
487         [windowController selectTabWithIndex:idx];
488 #endif
489     } else if (UpdateTabBarMsgID == msgid) {
490         [windowController updateTabsWithData:data];
491     } else if (ShowTabBarMsgID == msgid) {
492         [windowController showTabBar:YES];
493     } else if (HideTabBarMsgID == msgid) {
494         [windowController showTabBar:NO];
495     } else if (SetTextDimensionsMsgID == msgid) {
496         const void *bytes = [data bytes];
497         int rows = *((int*)bytes);  bytes += sizeof(int);
498         int cols = *((int*)bytes);  bytes += sizeof(int);
500         [windowController setTextDimensionsWithRows:rows columns:cols];
501     } else if (SetVimWindowTitleMsgID == msgid) {
502         const void *bytes = [data bytes];
503         int len = *((int*)bytes);  bytes += sizeof(int);
505         NSString *string = [[NSString alloc] initWithBytes:(void*)bytes
506                 length:len encoding:NSUTF8StringEncoding];
508         [[windowController window] setTitle:string];
510         [string release];
511     } else if (AddMenuMsgID == msgid) {
512         NSString *title = nil;
513         const void *bytes = [data bytes];
514         int tag = *((int*)bytes);  bytes += sizeof(int);
515         int parentTag = *((int*)bytes);  bytes += sizeof(int);
516         int len = *((int*)bytes);  bytes += sizeof(int);
517         if (len > 0) {
518             title = [[NSString alloc] initWithBytes:(void*)bytes length:len
519                                            encoding:NSUTF8StringEncoding];
520             bytes += len;
521         }
522         int idx = *((int*)bytes);  bytes += sizeof(int);
524         if (MenuToolbarType == parentTag) {
525             if (!toolbar) {
526                 // NOTE! Each toolbar must have a unique identifier, else each
527                 // window will have the same toolbar.
528                 NSString *ident = [NSString stringWithFormat:@"%d.%d",
529                          (int)self, tag];
530                 toolbar = [[NSToolbar alloc] initWithIdentifier:ident];
532                 [toolbar setShowsBaselineSeparator:NO];
533                 [toolbar setDelegate:self];
534                 [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
535                 [toolbar setSizeMode:NSToolbarSizeModeSmall];
537                 NSWindow *win = [windowController window];
538                 [win setToolbar:toolbar];
540                 // HACK! Redirect the pill button so that we can ask Vim to
541                 // hide the toolbar.
542                 NSButton *pillButton = [win
543                     standardWindowButton:NSWindowToolbarButton];
544                 if (pillButton) {
545                     [pillButton setAction:@selector(toggleToolbar:)];
546                     [pillButton setTarget:windowController];
547                 }
548             }
549         } else if (title) {
550             [self addMenuWithTag:tag parent:parentTag title:title atIndex:idx];
551         }
553         [title release];
554     } else if (AddMenuItemMsgID == msgid) {
555         NSString *title = nil, *tip = nil, *icon = nil, *action = nil;
556         const void *bytes = [data bytes];
557         int tag = *((int*)bytes);  bytes += sizeof(int);
558         int parentTag = *((int*)bytes);  bytes += sizeof(int);
559         int namelen = *((int*)bytes);  bytes += sizeof(int);
560         if (namelen > 0) {
561             title = [[NSString alloc] initWithBytes:(void*)bytes length:namelen
562                                            encoding:NSUTF8StringEncoding];
563             bytes += namelen;
564         }
565         int tiplen = *((int*)bytes);  bytes += sizeof(int);
566         if (tiplen > 0) {
567             tip = [[NSString alloc] initWithBytes:(void*)bytes length:tiplen
568                                            encoding:NSUTF8StringEncoding];
569             bytes += tiplen;
570         }
571         int iconlen = *((int*)bytes);  bytes += sizeof(int);
572         if (iconlen > 0) {
573             icon = [[NSString alloc] initWithBytes:(void*)bytes length:iconlen
574                                            encoding:NSUTF8StringEncoding];
575             bytes += iconlen;
576         }
577         int actionlen = *((int*)bytes);  bytes += sizeof(int);
578         if (actionlen > 0) {
579             action = [[NSString alloc] initWithBytes:(void*)bytes
580                                               length:actionlen
581                                             encoding:NSUTF8StringEncoding];
582             bytes += actionlen;
583         }
584         int idx = *((int*)bytes);  bytes += sizeof(int);
585         if (idx < 0) idx = 0;
586         int key = *((int*)bytes);  bytes += sizeof(int);
587         int mask = *((int*)bytes);  bytes += sizeof(int);
589         NSString *ident = [NSString stringWithFormat:@"%d.%d",
590                 (int)self, parentTag];
591         if (toolbar && [[toolbar identifier] isEqual:ident]) {
592             [self addToolbarItemWithTag:tag label:title tip:tip icon:icon
593                                 atIndex:idx];
594         } else {
595             NSMenu *parent = [self menuForTag:parentTag];
596             [self addMenuItemWithTag:tag parent:parent title:title tip:tip
597                        keyEquivalent:key modifiers:mask action:action
598                              atIndex:idx];
599         }
601         [title release];
602         [tip release];
603         [icon release];
604         [action release];
605     } else if (RemoveMenuItemMsgID == msgid) {
606         const void *bytes = [data bytes];
607         int tag = *((int*)bytes);  bytes += sizeof(int);
609         id item;
610         int idx;
611         if ((item = [self toolbarItemForTag:tag index:&idx])) {
612             [toolbar removeItemAtIndex:idx];
613         } else if ((item = [self menuItemForTag:tag])) {
614             [item retain];
616             if ([item menu] == [NSApp mainMenu] || ![item menu]) {
617                 // NOTE: To be on the safe side we try to remove the item from
618                 // both arrays (it is ok to call removeObject: even if an array
619                 // does not contain the object to remove).
620                 [mainMenuItems removeObject:item];
621                 [popupMenuItems removeObject:item];
622             }
624             if ([item menu])
625                 [[item menu] removeItem:item];
627             [item release];
628         }
629     } else if (EnableMenuItemMsgID == msgid) {
630         const void *bytes = [data bytes];
631         int tag = *((int*)bytes);  bytes += sizeof(int);
632         int state = *((int*)bytes);  bytes += sizeof(int);
634         id item = [self toolbarItemForTag:tag index:NULL];
635         if (!item)
636             item = [self menuItemForTag:tag];
638         [item setEnabled:state];
639     } else if (ShowToolbarMsgID == msgid) {
640         const void *bytes = [data bytes];
641         int enable = *((int*)bytes);  bytes += sizeof(int);
642         int flags = *((int*)bytes);  bytes += sizeof(int);
644         int mode = NSToolbarDisplayModeDefault;
645         if (flags & ToolbarLabelFlag) {
646             mode = flags & ToolbarIconFlag ? NSToolbarDisplayModeIconAndLabel
647                     : NSToolbarDisplayModeLabelOnly;
648         } else if (flags & ToolbarIconFlag) {
649             mode = NSToolbarDisplayModeIconOnly;
650         }
652         int size = flags & ToolbarSizeRegularFlag ? NSToolbarSizeModeRegular
653                 : NSToolbarSizeModeSmall;
655         [windowController showToolbar:enable size:size mode:mode];
656     } else if (CreateScrollbarMsgID == msgid) {
657         const void *bytes = [data bytes];
658         long ident = *((long*)bytes);  bytes += sizeof(long);
659         int type = *((int*)bytes);  bytes += sizeof(int);
661         [windowController createScrollbarWithIdentifier:ident type:type];
662     } else if (DestroyScrollbarMsgID == msgid) {
663         const void *bytes = [data bytes];
664         long ident = *((long*)bytes);  bytes += sizeof(long);
666         [windowController destroyScrollbarWithIdentifier:ident];
667     } else if (ShowScrollbarMsgID == msgid) {
668         const void *bytes = [data bytes];
669         long ident = *((long*)bytes);  bytes += sizeof(long);
670         int visible = *((int*)bytes);  bytes += sizeof(int);
672         [windowController showScrollbarWithIdentifier:ident state:visible];
673     } else if (SetScrollbarPositionMsgID == msgid) {
674         const void *bytes = [data bytes];
675         long ident = *((long*)bytes);  bytes += sizeof(long);
676         int pos = *((int*)bytes);  bytes += sizeof(int);
677         int len = *((int*)bytes);  bytes += sizeof(int);
679         [windowController setScrollbarPosition:pos length:len
680                                     identifier:ident];
681     } else if (SetScrollbarThumbMsgID == msgid) {
682         const void *bytes = [data bytes];
683         long ident = *((long*)bytes);  bytes += sizeof(long);
684         float val = *((float*)bytes);  bytes += sizeof(float);
685         float prop = *((float*)bytes);  bytes += sizeof(float);
687         [windowController setScrollbarThumbValue:val proportion:prop
688                                       identifier:ident];
689     } else if (SetFontMsgID == msgid) {
690         const void *bytes = [data bytes];
691         float size = *((float*)bytes);  bytes += sizeof(float);
692         int len = *((int*)bytes);  bytes += sizeof(int);
693         NSString *name = [[NSString alloc]
694                 initWithBytes:(void*)bytes length:len
695                      encoding:NSUTF8StringEncoding];
696         NSFont *font = [NSFont fontWithName:name size:size];
698         if (font)
699             [windowController setFont:font];
701         [name release];
702     } else if (SetDefaultColorsMsgID == msgid) {
703         const void *bytes = [data bytes];
704         int bg = *((int*)bytes);  bytes += sizeof(int);
705         int fg = *((int*)bytes);  bytes += sizeof(int);
706         NSColor *back = [NSColor colorWithRgbInt:bg];
707         NSColor *fore = [NSColor colorWithRgbInt:fg];
709         [windowController setDefaultColorsBackground:back foreground:fore];
710     } else if (ExecuteActionMsgID == msgid) {
711         const void *bytes = [data bytes];
712         int len = *((int*)bytes);  bytes += sizeof(int);
713         NSString *actionName = [[NSString alloc]
714                 initWithBytesNoCopy:(void*)bytes
715                              length:len
716                            encoding:NSUTF8StringEncoding
717                        freeWhenDone:NO];
719         SEL sel = NSSelectorFromString(actionName);
720         [NSApp sendAction:sel to:nil from:self];
722         [actionName release];
723     } else if (ShowPopupMenuMsgID == msgid) {
724         const void *bytes = [data bytes];
725         int row = *((int*)bytes);  bytes += sizeof(int);
726         int col = *((int*)bytes);  bytes += sizeof(int);
727         int len = *((int*)bytes);  bytes += sizeof(int);
728         NSString *title = [[NSString alloc]
729                 initWithBytesNoCopy:(void*)bytes
730                              length:len
731                            encoding:NSUTF8StringEncoding
732                        freeWhenDone:NO];
734         NSMenu *menu = [self topLevelMenuForTitle:title];
735         if (menu) {
736             [windowController popupMenu:menu atRow:row column:col];
737         } else {
738             NSLog(@"WARNING: Cannot popup menu with title %@; no such menu.",
739                     title);
740         }
742         [title release];
743     } else if (SetMouseShapeMsgID == msgid) {
744         const void *bytes = [data bytes];
745         int shape = *((int*)bytes);  bytes += sizeof(int);
747         [windowController setMouseShape:shape];
748     } else if (AdjustLinespaceMsgID == msgid) {
749         const void *bytes = [data bytes];
750         int linespace = *((int*)bytes);  bytes += sizeof(int);
752         [windowController adjustLinespace:linespace];
753     } else if (ActivateMsgID == msgid) {
754         [NSApp activateIgnoringOtherApps:YES];
755         [[windowController window] makeKeyAndOrderFront:self];
756     } else if (SetServerNameMsgID == msgid) {
757         NSString *name = [[NSString alloc] initWithData:data
758                                                encoding:NSUTF8StringEncoding];
759         [self setServerName:name];
760         [name release];
761     } else {
762         NSLog(@"WARNING: Unknown message received (msgid=%d)", msgid);
763     }
767 #define MM_DEBUG_DRAWING 0
769 - (void)performBatchDrawWithData:(NSData *)data
771     // TODO!  Move to window controller.
772     MMTextStorage *textStorage = [windowController textStorage];
773     MMTextView *textView = [windowController textView];
774     if (!(textStorage && textView))
775         return;
777     const void *bytes = [data bytes];
778     const void *end = bytes + [data length];
780 #if MM_DEBUG_DRAWING
781     NSLog(@"====> BEGIN %s", _cmd);
782 #endif
783     [textStorage beginEditing];
785     // TODO: Sanity check input
787     while (bytes < end) {
788         int type = *((int*)bytes);  bytes += sizeof(int);
790         if (ClearAllDrawType == type) {
791             int color = *((int*)bytes);  bytes += sizeof(int);
793 #if MM_DEBUG_DRAWING
794             NSLog(@"   Clear all");
795 #endif
796             [textStorage clearAllWithColor:[NSColor colorWithRgbInt:color]];
797         } else if (ClearBlockDrawType == type) {
798             int color = *((int*)bytes);  bytes += sizeof(int);
799             int row1 = *((int*)bytes);  bytes += sizeof(int);
800             int col1 = *((int*)bytes);  bytes += sizeof(int);
801             int row2 = *((int*)bytes);  bytes += sizeof(int);
802             int col2 = *((int*)bytes);  bytes += sizeof(int);
804 #if MM_DEBUG_DRAWING
805             NSLog(@"   Clear block (%d,%d) -> (%d,%d)", row1, col1,
806                     row2,col2);
807 #endif
808             [textStorage clearBlockFromRow:row1 column:col1
809                     toRow:row2 column:col2
810                     color:[NSColor colorWithRgbInt:color]];
811         } else if (DeleteLinesDrawType == type) {
812             int color = *((int*)bytes);  bytes += sizeof(int);
813             int row = *((int*)bytes);  bytes += sizeof(int);
814             int count = *((int*)bytes);  bytes += sizeof(int);
815             int bot = *((int*)bytes);  bytes += sizeof(int);
816             int left = *((int*)bytes);  bytes += sizeof(int);
817             int right = *((int*)bytes);  bytes += sizeof(int);
819 #if MM_DEBUG_DRAWING
820             NSLog(@"   Delete %d line(s) from %d", count, row);
821 #endif
822             [textStorage deleteLinesFromRow:row lineCount:count
823                     scrollBottom:bot left:left right:right
824                            color:[NSColor colorWithRgbInt:color]];
825         } else if (ReplaceStringDrawType == type) {
826             int bg = *((int*)bytes);  bytes += sizeof(int);
827             int fg = *((int*)bytes);  bytes += sizeof(int);
828             int sp = *((int*)bytes);  bytes += sizeof(int);
829             int row = *((int*)bytes);  bytes += sizeof(int);
830             int col = *((int*)bytes);  bytes += sizeof(int);
831             int flags = *((int*)bytes);  bytes += sizeof(int);
832             int len = *((int*)bytes);  bytes += sizeof(int);
833             NSString *string = [[NSString alloc]
834                     initWithBytesNoCopy:(void*)bytes
835                                  length:len
836                                encoding:NSUTF8StringEncoding
837                            freeWhenDone:NO];
838             bytes += len;
840 #if MM_DEBUG_DRAWING
841             NSLog(@"   Draw string at (%d,%d) length=%d flags=%d fg=0x%x "
842                     "bg=0x%x sp=0x%x (%@)", row, col, len, flags, fg, bg, sp,
843                     len > 0 ? [string substringToIndex:1] : @"");
844 #endif
845             // NOTE: If this is a call to draw the (block) cursor, then cancel
846             // any previous request to draw the insertion point, or it might
847             // get drawn as well.
848             if (flags & DRAW_CURSOR) {
849                 [textView setShouldDrawInsertionPoint:NO];
850                 //[textView drawInsertionPointAtRow:row column:col
851                 //                            shape:MMInsertionPointBlock
852                 //                            color:[NSColor colorWithRgbInt:bg]];
853             }
854             [textStorage replaceString:string
855                                  atRow:row column:col
856                              withFlags:flags
857                        foregroundColor:[NSColor colorWithRgbInt:fg]
858                        backgroundColor:[NSColor colorWithRgbInt:bg]
859                           specialColor:[NSColor colorWithRgbInt:sp]];
861             [string release];
862         } else if (InsertLinesDrawType == type) {
863             int color = *((int*)bytes);  bytes += sizeof(int);
864             int row = *((int*)bytes);  bytes += sizeof(int);
865             int count = *((int*)bytes);  bytes += sizeof(int);
866             int bot = *((int*)bytes);  bytes += sizeof(int);
867             int left = *((int*)bytes);  bytes += sizeof(int);
868             int right = *((int*)bytes);  bytes += sizeof(int);
870 #if MM_DEBUG_DRAWING
871             NSLog(@"   Insert %d line(s) at row %d", count, row);
872 #endif
873             [textStorage insertLinesAtRow:row lineCount:count
874                              scrollBottom:bot left:left right:right
875                                     color:[NSColor colorWithRgbInt:color]];
876         } else if (DrawCursorDrawType == type) {
877             int color = *((int*)bytes);  bytes += sizeof(int);
878             int row = *((int*)bytes);  bytes += sizeof(int);
879             int col = *((int*)bytes);  bytes += sizeof(int);
880             int shape = *((int*)bytes);  bytes += sizeof(int);
881             int percent = *((int*)bytes);  bytes += sizeof(int);
883 #if MM_DEBUG_DRAWING
884             NSLog(@"   Draw cursor at (%d,%d)", row, col);
885 #endif
886             [textView drawInsertionPointAtRow:row column:col shape:shape
887                                      fraction:percent
888                                         color:[NSColor colorWithRgbInt:color]];
889         } else {
890             NSLog(@"WARNING: Unknown draw type (type=%d)", type);
891         }
892     }
894     [textStorage endEditing];
895 #if MM_DEBUG_DRAWING
896     NSLog(@"<==== END   %s", _cmd);
897 #endif
900 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
901                 context:(void *)context
903     NSString *string = (code == NSOKButton) ? [panel filename] : nil;
904     @try {
905         [backendProxy setDialogReturn:string];
906     }
907     @catch (NSException *e) {
908         NSLog(@"Exception caught in %s %@", _cmd, e);
909     }
912 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context
914     NSArray *ret = nil;
916     code = code - NSAlertFirstButtonReturn + 1;
918     if ([alert isKindOfClass:[MMAlert class]] && [alert textField]) {
919         ret = [NSArray arrayWithObjects:[NSNumber numberWithInt:code],
920             [[alert textField] stringValue], nil];
921     } else {
922         ret = [NSArray arrayWithObject:[NSNumber numberWithInt:code]];
923     }
925     @try {
926         [backendProxy setDialogReturn:ret];
927     }
928     @catch (NSException *e) {
929         NSLog(@"Exception caught in %s %@", _cmd, e);
930     }
933 - (NSMenuItem *)menuItemForTag:(int)tag
935     // Search the main menu.
936     int i, count = [mainMenuItems count];
937     for (i = 0; i < count; ++i) {
938         NSMenuItem *item = [mainMenuItems objectAtIndex:i];
939         if ([item tag] == tag) return item;
940         item = findMenuItemWithTagInMenu([item submenu], tag);
941         if (item) return item;
942     }
944     // Search the popup menus.
945     count = [popupMenuItems count];
946     for (i = 0; i < count; ++i) {
947         NSMenuItem *item = [popupMenuItems objectAtIndex:i];
948         if ([item tag] == tag) return item;
949         item = findMenuItemWithTagInMenu([item submenu], tag);
950         if (item) return item;
951     }
953     return nil;
956 - (NSMenu *)menuForTag:(int)tag
958     return [[self menuItemForTag:tag] submenu];
961 - (NSMenu *)topLevelMenuForTitle:(NSString *)title
963     // Search only the top-level menus.
965     unsigned i, count = [popupMenuItems count];
966     for (i = 0; i < count; ++i) {
967         NSMenuItem *item = [popupMenuItems objectAtIndex:i];
968         if ([title isEqual:[item title]])
969             return [item submenu];
970     }
972     count = [mainMenuItems count];
973     for (i = 0; i < count; ++i) {
974         NSMenuItem *item = [mainMenuItems objectAtIndex:i];
975         if ([title isEqual:[item title]])
976             return [item submenu];
977     }
979     return nil;
982 - (void)addMenuWithTag:(int)tag parent:(int)parentTag title:(NSString *)title
983                atIndex:(int)idx
985     NSMenu *parent = [self menuForTag:parentTag];
986     NSMenuItem *item = [[NSMenuItem alloc] init];
987     NSMenu *menu = [[NSMenu alloc] initWithTitle:title];
989     [menu setAutoenablesItems:NO];
990     [item setTag:tag];
991     [item setTitle:title];
992     [item setSubmenu:menu];
994     if (parent) {
995         if ([parent numberOfItems] <= idx) {
996             [parent addItem:item];
997         } else {
998             [parent insertItem:item atIndex:idx];
999         }
1000     } else {
1001         NSMutableArray *items = (MenuPopupType == parentTag)
1002             ? popupMenuItems : mainMenuItems;
1003         if ([items count] <= idx) {
1004             [items addObject:item];
1005         } else {
1006             [items insertObject:item atIndex:idx];
1007         }
1009         shouldUpdateMainMenu = (MenuPopupType != parentTag);
1010     }
1012     [item release];
1013     [menu release];
1016 - (void)addMenuItemWithTag:(int)tag parent:(NSMenu *)parent
1017                      title:(NSString *)title tip:(NSString *)tip
1018              keyEquivalent:(int)key modifiers:(int)mask
1019                     action:(NSString *)action atIndex:(int)idx
1021     if (parent) {
1022         NSMenuItem *item = nil;
1023         if (!title || ([title hasPrefix:@"-"] && [title hasSuffix:@"-"])) {
1024             item = [NSMenuItem separatorItem];
1025         } else {
1026             item = [[[NSMenuItem alloc] init] autorelease];
1027             [item setTitle:title];
1028             // TODO: Check that 'action' is a valid action (nothing will happen
1029             // if it isn't, but it would be nice with a warning).
1030             if (action) [item setAction:NSSelectorFromString(action)];
1031             else        [item setAction:@selector(vimMenuItemAction:)];
1032             if (tip) [item setToolTip:tip];
1034             if (key != 0) {
1035                 NSString *keyString =
1036                     [NSString stringWithFormat:@"%C", key];
1037                 [item setKeyEquivalent:keyString];
1038                 [item setKeyEquivalentModifierMask:mask];
1039             }
1040         }
1042         // NOTE!  The tag is used to idenfity which menu items were
1043         // added by Vim (tag != 0) and which were added by the AppKit
1044         // (tag == 0).
1045         [item setTag:tag];
1047         if ([parent numberOfItems] <= idx) {
1048             [parent addItem:item];
1049         } else {
1050             [parent insertItem:item atIndex:idx];
1051         }
1052     } else {
1053         NSLog(@"WARNING: Menu item '%@' (tag=%d) has no parent.", title, tag);
1054     }
1057 - (void)updateMainMenu
1059     NSMenu *mainMenu = [NSApp mainMenu];
1061     // Stop NSApp from updating the Window menu.
1062     [NSApp setWindowsMenu:nil];
1064     // Remove all menus from main menu (except the MacVim menu).
1065     int i, count = [mainMenu numberOfItems];
1066     for (i = count-1; i > 0; --i) {
1067         [mainMenu removeItemAtIndex:i];
1068     }
1070     // Add menus from 'mainMenuItems' to main menu.
1071     count = [mainMenuItems count];
1072     for (i = 0; i < count; ++i) {
1073         [mainMenu addItem:[mainMenuItems objectAtIndex:i]];
1074     }
1076     // Set the new Window menu.
1077     // TODO!  Need to look for 'Window' in all localized languages.
1078     NSMenu *windowMenu = [[mainMenu itemWithTitle:@"Window"] submenu];
1079     if (windowMenu) {
1080         // Remove all AppKit owned menu items (tag == 0); they will be added
1081         // again when setWindowsMenu: is called.
1082         count = [windowMenu numberOfItems];
1083         for (i = count-1; i >= 0; --i) {
1084             NSMenuItem *item = [windowMenu itemAtIndex:i];
1085             if (![item tag]) {
1086                 [windowMenu removeItem:item];
1087             }
1088         }
1090         [NSApp setWindowsMenu:windowMenu];
1091     }
1093     shouldUpdateMainMenu = NO;
1096 - (NSToolbarItem *)toolbarItemForTag:(int)tag index:(int *)index
1098     if (!toolbar) return nil;
1100     NSArray *items = [toolbar items];
1101     int i, count = [items count];
1102     for (i = 0; i < count; ++i) {
1103         NSToolbarItem *item = [items objectAtIndex:i];
1104         if ([item tag] == tag) {
1105             if (index) *index = i;
1106             return item;
1107         }
1108     }
1110     return nil;
1113 - (void)addToolbarItemToDictionaryWithTag:(int)tag label:(NSString *)title
1114         toolTip:(NSString *)tip icon:(NSString *)icon
1116     // If the item corresponds to a separator then do nothing, since it is
1117     // already defined by Cocoa.
1118     if (!title || [title isEqual:NSToolbarSeparatorItemIdentifier]
1119                || [title isEqual:NSToolbarSpaceItemIdentifier]
1120                || [title isEqual:NSToolbarFlexibleSpaceItemIdentifier])
1121         return;
1123     NSToolbarItem *item = [[NSToolbarItem alloc] initWithItemIdentifier:title];
1124     [item setTag:tag];
1125     [item setLabel:title];
1126     [item setToolTip:tip];
1127     [item setAction:@selector(vimMenuItemAction:)];
1128     [item setAutovalidates:NO];
1130     NSImage *img = [NSImage imageNamed:icon];
1131     if (!img) {
1132         NSLog(@"WARNING: Could not find image with name '%@' to use as toolbar"
1133                " image for identifier '%@';"
1134                " using default toolbar icon '%@' instead.",
1135                icon, title, MMDefaultToolbarImageName);
1137         img = [NSImage imageNamed:MMDefaultToolbarImageName];
1138     }
1140     [item setImage:img];
1142     [toolbarItemDict setObject:item forKey:title];
1144     [item release];
1147 - (void)addToolbarItemWithTag:(int)tag label:(NSString *)label tip:(NSString
1148                    *)tip icon:(NSString *)icon atIndex:(int)idx
1150     if (!toolbar) return;
1152     // Check for separator items.
1153     if (!label) {
1154         label = NSToolbarSeparatorItemIdentifier;
1155     } else if ([label length] >= 2 && [label hasPrefix:@"-"]
1156                                    && [label hasSuffix:@"-"]) {
1157         // The label begins and ends with '-'; decided which kind of separator
1158         // item it is by looking at the prefix.
1159         if ([label hasPrefix:@"-space"]) {
1160             label = NSToolbarSpaceItemIdentifier;
1161         } else if ([label hasPrefix:@"-flexspace"]) {
1162             label = NSToolbarFlexibleSpaceItemIdentifier;
1163         } else {
1164             label = NSToolbarSeparatorItemIdentifier;
1165         }
1166     }
1168     [self addToolbarItemToDictionaryWithTag:tag label:label toolTip:tip
1169                                        icon:icon];
1171     int maxIdx = [[toolbar items] count];
1172     if (maxIdx < idx) idx = maxIdx;
1174     [toolbar insertItemWithItemIdentifier:label atIndex:idx];
1177 - (void)connectionDidDie:(NSNotification *)notification
1179     //NSLog(@"%@ %s%@", [self className], _cmd, notification);
1181     [self cleanup];
1183     // NOTE!  This causes the call to removeVimController: to be delayed.
1184     [[NSApp delegate]
1185             performSelectorOnMainThread:@selector(removeVimController:)
1186                              withObject:self waitUntilDone:NO];
1189 - (NSString *)description
1191     return [NSString stringWithFormat:@"%@ : isInitialized=%d inProcessCommandQueue=%d mainMenuItems=%@ popupMenuItems=%@ toolbar=%@", [self className], isInitialized, inProcessCommandQueue, mainMenuItems, popupMenuItems, toolbar];
1194 #if MM_RESEND_LAST_FAILURE
1195 - (void)resendTimerFired:(NSTimer *)timer
1197     int msgid = resendMsgid;
1198     NSData *data = nil;
1200     [resendTimer release];
1201     resendTimer = nil;
1203     if (!isInitialized)
1204         return;
1206     if (resendData)
1207         data = [resendData copy];
1209     //NSLog(@"Resending message: %s", MessageStrings[msgid]);
1210     [self sendMessage:msgid data:data];
1212 #endif
1214 @end // MMVimController (Private)
1218 @implementation NSColor (MMProtocol)
1220 + (NSColor *)colorWithRgbInt:(int)rgb
1222     float r = ((rgb>>16) & 0xff)/255.0f;
1223     float g = ((rgb>>8) & 0xff)/255.0f;
1224     float b = (rgb & 0xff)/255.0f;
1226     return [NSColor colorWithCalibratedRed:r green:g blue:b alpha:1.0f];
1229 @end // NSColor (MMProtocol)
1233 @implementation MMAlert
1234 - (void)dealloc
1236     [textField release];
1237     [super dealloc];
1240 - (void)setTextFieldString:(NSString *)textFieldString
1242     [textField release];
1243     textField = [[NSTextField alloc] init];
1244     [textField setStringValue:textFieldString];
1247 - (NSTextField *)textField
1249     return textField;
1252 - (void)setInformativeText:(NSString *)text
1254     if (textField) {
1255         // HACK! Add some space for the text field.
1256         [super setInformativeText:[text stringByAppendingString:@"\n\n\n"]];
1257     } else {
1258         [super setInformativeText:text];
1259     }
1262 - (void)beginSheetModalForWindow:(NSWindow *)window
1263                    modalDelegate:(id)delegate
1264                   didEndSelector:(SEL)didEndSelector
1265                      contextInfo:(void *)contextInfo
1267     [super beginSheetModalForWindow:window
1268                       modalDelegate:delegate
1269                      didEndSelector:didEndSelector
1270                         contextInfo:contextInfo];
1272     // HACK! Place the input text field at the bottom of the informative text
1273     // (which has been made a bit larger by adding newline characters).
1274     NSView *contentView = [[self window] contentView];
1275     NSRect rect = [contentView frame];
1276     rect.origin.y = rect.size.height;
1278     NSArray *subviews = [contentView subviews];
1279     unsigned i, count = [subviews count];
1280     for (i = 0; i < count; ++i) {
1281         NSView *view = [subviews objectAtIndex:i];
1282         if ([view isKindOfClass:[NSTextField class]]
1283                 && [view frame].origin.y < rect.origin.y) {
1284             // NOTE: The informative text field is the lowest NSTextField in
1285             // the alert dialog.
1286             rect = [view frame];
1287         }
1288     }
1290     rect.size.height = MMAlertTextFieldHeight;
1291     [textField setFrame:rect];
1292     [contentView addSubview:textField];
1293     [textField becomeFirstResponder];
1296 @end // MMAlert