Merge commit 'svn-macvim'
[MacVim.git] / MMVimController.m
blob8e4b2022a86cb13c2b4ebe48417c53ba572fa837
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 #if 0
417         if (msgid != EnableMenuItemMsgID && msgid != AddMenuItemMsgID
418                 && msgid != AddMenuMsgID) {
419             NSLog(@"%s%s", _cmd, MessageStrings[msgid]);
420         }
421 #endif
423         [self handleMessage:msgid data:data];
424     }
425     //NSLog(@"======== %s  END  ========", _cmd);
427     if (shouldUpdateMainMenu) {
428         [self updateMainMenu];
429     }
431     [windowController processCommandQueueDidFinish];
433     inProcessCommandQueue = NO;
435     if ([sendQueue count] > 0) {
436         @try {
437             [backendProxy processInputAndData:sendQueue];
438         }
439         @catch (NSException *e) {
440             // Connection timed out, just ignore this.
441             //NSLog(@"WARNING! Connection timed out in %s", _cmd);
442         }
444         [sendQueue removeAllObjects];
445     }
448 - (void)windowDidBecomeMain:(NSNotification *)notification
450     if (isInitialized)
451         [self updateMainMenu];
454 - (NSToolbarItem *)toolbar:(NSToolbar *)theToolbar
455     itemForItemIdentifier:(NSString *)itemId
456     willBeInsertedIntoToolbar:(BOOL)flag
458     NSToolbarItem *item = [toolbarItemDict objectForKey:itemId];
459     if (!item) {
460         NSLog(@"WARNING:  No toolbar item with id '%@'", itemId);
461     }
463     return item;
466 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)theToolbar
468     return nil;
471 - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)theToolbar
473     return nil;
476 @end // MMVimController
480 @implementation MMVimController (Private)
482 - (void)handleMessage:(int)msgid data:(NSData *)data
484     //NSLog(@"%@ %s", [self className], _cmd);
486     if (OpenVimWindowMsgID == msgid) {
487         [windowController openWindow];
488     } else if (BatchDrawMsgID == msgid) {
489         [self performBatchDrawWithData:data];
490     } else if (SelectTabMsgID == msgid) {
491 #if 0   // NOTE: Tab selection is done inside updateTabsWithData:.
492         const void *bytes = [data bytes];
493         int idx = *((int*)bytes);
494         //NSLog(@"Selecting tab with index %d", idx);
495         [windowController selectTabWithIndex:idx];
496 #endif
497     } else if (UpdateTabBarMsgID == msgid) {
498         [windowController updateTabsWithData:data];
499     } else if (ShowTabBarMsgID == msgid) {
500         [windowController showTabBar:YES];
501     } else if (HideTabBarMsgID == msgid) {
502         [windowController showTabBar:NO];
503     } else if (SetTextDimensionsMsgID == msgid) {
504         const void *bytes = [data bytes];
505         int rows = *((int*)bytes);  bytes += sizeof(int);
506         int cols = *((int*)bytes);  bytes += sizeof(int);
508         [windowController setTextDimensionsWithRows:rows columns:cols];
509     } else if (SetWindowTitleMsgID == msgid) {
510         const void *bytes = [data bytes];
511         int len = *((int*)bytes);  bytes += sizeof(int);
513         NSString *string = [[NSString alloc] initWithBytes:(void*)bytes
514                 length:len encoding:NSUTF8StringEncoding];
516         [[windowController window] setTitle:string];
518         [string release];
519     } else if (AddMenuMsgID == msgid) {
520         NSString *title = nil;
521         const void *bytes = [data bytes];
522         int tag = *((int*)bytes);  bytes += sizeof(int);
523         int parentTag = *((int*)bytes);  bytes += sizeof(int);
524         int len = *((int*)bytes);  bytes += sizeof(int);
525         if (len > 0) {
526             title = [[NSString alloc] initWithBytes:(void*)bytes length:len
527                                            encoding:NSUTF8StringEncoding];
528             bytes += len;
529         }
530         int idx = *((int*)bytes);  bytes += sizeof(int);
532         if (MenuToolbarType == parentTag) {
533             if (!toolbar) {
534                 // NOTE! Each toolbar must have a unique identifier, else each
535                 // window will have the same toolbar.
536                 NSString *ident = [NSString stringWithFormat:@"%d.%d",
537                          (int)self, tag];
538                 toolbar = [[NSToolbar alloc] initWithIdentifier:ident];
540                 [toolbar setShowsBaselineSeparator:NO];
541                 [toolbar setDelegate:self];
542                 [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
543                 [toolbar setSizeMode:NSToolbarSizeModeSmall];
545                 NSWindow *win = [windowController window];
546                 [win setToolbar:toolbar];
548                 // HACK! Redirect the pill button so that we can ask Vim to
549                 // hide the toolbar.
550                 NSButton *pillButton = [win
551                     standardWindowButton:NSWindowToolbarButton];
552                 if (pillButton) {
553                     [pillButton setAction:@selector(toggleToolbar:)];
554                     [pillButton setTarget:windowController];
555                 }
556             }
557         } else if (title) {
558             [self addMenuWithTag:tag parent:parentTag title:title atIndex:idx];
559         }
561         [title release];
562     } else if (AddMenuItemMsgID == msgid) {
563         NSString *title = nil, *tip = nil, *icon = nil, *action = nil;
564         const void *bytes = [data bytes];
565         int tag = *((int*)bytes);  bytes += sizeof(int);
566         int parentTag = *((int*)bytes);  bytes += sizeof(int);
567         int namelen = *((int*)bytes);  bytes += sizeof(int);
568         if (namelen > 0) {
569             title = [[NSString alloc] initWithBytes:(void*)bytes length:namelen
570                                            encoding:NSUTF8StringEncoding];
571             bytes += namelen;
572         }
573         int tiplen = *((int*)bytes);  bytes += sizeof(int);
574         if (tiplen > 0) {
575             tip = [[NSString alloc] initWithBytes:(void*)bytes length:tiplen
576                                            encoding:NSUTF8StringEncoding];
577             bytes += tiplen;
578         }
579         int iconlen = *((int*)bytes);  bytes += sizeof(int);
580         if (iconlen > 0) {
581             icon = [[NSString alloc] initWithBytes:(void*)bytes length:iconlen
582                                            encoding:NSUTF8StringEncoding];
583             bytes += iconlen;
584         }
585         int actionlen = *((int*)bytes);  bytes += sizeof(int);
586         if (actionlen > 0) {
587             action = [[NSString alloc] initWithBytes:(void*)bytes
588                                               length:actionlen
589                                             encoding:NSUTF8StringEncoding];
590             bytes += actionlen;
591         }
592         int idx = *((int*)bytes);  bytes += sizeof(int);
593         if (idx < 0) idx = 0;
594         int key = *((int*)bytes);  bytes += sizeof(int);
595         int mask = *((int*)bytes);  bytes += sizeof(int);
597         NSString *ident = [NSString stringWithFormat:@"%d.%d",
598                 (int)self, parentTag];
599         if (toolbar && [[toolbar identifier] isEqual:ident]) {
600             [self addToolbarItemWithTag:tag label:title tip:tip icon:icon
601                                 atIndex:idx];
602         } else {
603             NSMenu *parent = [self menuForTag:parentTag];
604             [self addMenuItemWithTag:tag parent:parent title:title tip:tip
605                        keyEquivalent:key modifiers:mask action:action
606                              atIndex:idx];
607         }
609         [title release];
610         [tip release];
611         [icon release];
612         [action release];
613     } else if (RemoveMenuItemMsgID == msgid) {
614         const void *bytes = [data bytes];
615         int tag = *((int*)bytes);  bytes += sizeof(int);
617         id item;
618         int idx;
619         if ((item = [self toolbarItemForTag:tag index:&idx])) {
620             [toolbar removeItemAtIndex:idx];
621         } else if ((item = [self menuItemForTag:tag])) {
622             [item retain];
624             if ([item menu] == [NSApp mainMenu] || ![item menu]) {
625                 // NOTE: To be on the safe side we try to remove the item from
626                 // both arrays (it is ok to call removeObject: even if an array
627                 // does not contain the object to remove).
628                 [mainMenuItems removeObject:item];
629                 [popupMenuItems removeObject:item];
630             }
632             if ([item menu])
633                 [[item menu] removeItem:item];
635             [item release];
636         }
638         // Reset cached menu, just to be on the safe side.
639         lastMenuSearched = nil;
640     } else if (EnableMenuItemMsgID == msgid) {
641         const void *bytes = [data bytes];
642         int tag = *((int*)bytes);  bytes += sizeof(int);
643         int state = *((int*)bytes);  bytes += sizeof(int);
645         id item = [self toolbarItemForTag:tag index:NULL];
646         if (!item)
647             item = [self menuItemForTag:tag];
649         [item setEnabled:state];
650     } else if (ShowToolbarMsgID == msgid) {
651         const void *bytes = [data bytes];
652         int enable = *((int*)bytes);  bytes += sizeof(int);
653         int flags = *((int*)bytes);  bytes += sizeof(int);
655         int mode = NSToolbarDisplayModeDefault;
656         if (flags & ToolbarLabelFlag) {
657             mode = flags & ToolbarIconFlag ? NSToolbarDisplayModeIconAndLabel
658                     : NSToolbarDisplayModeLabelOnly;
659         } else if (flags & ToolbarIconFlag) {
660             mode = NSToolbarDisplayModeIconOnly;
661         }
663         int size = flags & ToolbarSizeRegularFlag ? NSToolbarSizeModeRegular
664                 : NSToolbarSizeModeSmall;
666         [windowController showToolbar:enable size:size mode:mode];
667     } else if (CreateScrollbarMsgID == msgid) {
668         const void *bytes = [data bytes];
669         long ident = *((long*)bytes);  bytes += sizeof(long);
670         int type = *((int*)bytes);  bytes += sizeof(int);
672         [windowController createScrollbarWithIdentifier:ident type:type];
673     } else if (DestroyScrollbarMsgID == msgid) {
674         const void *bytes = [data bytes];
675         long ident = *((long*)bytes);  bytes += sizeof(long);
677         [windowController destroyScrollbarWithIdentifier:ident];
678     } else if (ShowScrollbarMsgID == msgid) {
679         const void *bytes = [data bytes];
680         long ident = *((long*)bytes);  bytes += sizeof(long);
681         int visible = *((int*)bytes);  bytes += sizeof(int);
683         [windowController showScrollbarWithIdentifier:ident state:visible];
684     } else if (SetScrollbarPositionMsgID == msgid) {
685         const void *bytes = [data bytes];
686         long ident = *((long*)bytes);  bytes += sizeof(long);
687         int pos = *((int*)bytes);  bytes += sizeof(int);
688         int len = *((int*)bytes);  bytes += sizeof(int);
690         [windowController setScrollbarPosition:pos length:len
691                                     identifier:ident];
692     } else if (SetScrollbarThumbMsgID == msgid) {
693         const void *bytes = [data bytes];
694         long ident = *((long*)bytes);  bytes += sizeof(long);
695         float val = *((float*)bytes);  bytes += sizeof(float);
696         float prop = *((float*)bytes);  bytes += sizeof(float);
698         [windowController setScrollbarThumbValue:val proportion:prop
699                                       identifier:ident];
700     } else if (SetFontMsgID == msgid) {
701         const void *bytes = [data bytes];
702         float size = *((float*)bytes);  bytes += sizeof(float);
703         int len = *((int*)bytes);  bytes += sizeof(int);
704         NSString *name = [[NSString alloc]
705                 initWithBytes:(void*)bytes length:len
706                      encoding:NSUTF8StringEncoding];
707         NSFont *font = [NSFont fontWithName:name size:size];
709         if (font)
710             [windowController setFont:font];
712         [name release];
713     } else if (SetDefaultColorsMsgID == msgid) {
714         const void *bytes = [data bytes];
715         unsigned bg = *((unsigned*)bytes);  bytes += sizeof(unsigned);
716         unsigned fg = *((unsigned*)bytes);  bytes += sizeof(unsigned);
717         NSColor *back = [NSColor colorWithArgbInt:bg];
718         NSColor *fore = [NSColor colorWithRgbInt:fg];
720         [windowController setDefaultColorsBackground:back foreground:fore];
721     } else if (ExecuteActionMsgID == msgid) {
722         const void *bytes = [data bytes];
723         int len = *((int*)bytes);  bytes += sizeof(int);
724         NSString *actionName = [[NSString alloc]
725                 initWithBytesNoCopy:(void*)bytes
726                              length:len
727                            encoding:NSUTF8StringEncoding
728                        freeWhenDone:NO];
730         SEL sel = NSSelectorFromString(actionName);
731         [NSApp sendAction:sel to:nil from:self];
733         [actionName release];
734     } else if (ShowPopupMenuMsgID == msgid) {
735         const void *bytes = [data bytes];
736         int row = *((int*)bytes);  bytes += sizeof(int);
737         int col = *((int*)bytes);  bytes += sizeof(int);
738         int len = *((int*)bytes);  bytes += sizeof(int);
739         NSString *title = [[NSString alloc]
740                 initWithBytesNoCopy:(void*)bytes
741                              length:len
742                            encoding:NSUTF8StringEncoding
743                        freeWhenDone:NO];
745         NSMenu *menu = [self topLevelMenuForTitle:title];
746         if (menu) {
747             [windowController popupMenu:menu atRow:row column:col];
748         } else {
749             NSLog(@"WARNING: Cannot popup menu with title %@; no such menu.",
750                     title);
751         }
753         [title release];
754     } else if (SetMouseShapeMsgID == msgid) {
755         const void *bytes = [data bytes];
756         int shape = *((int*)bytes);  bytes += sizeof(int);
758         [windowController setMouseShape:shape];
759     } else if (AdjustLinespaceMsgID == msgid) {
760         const void *bytes = [data bytes];
761         int linespace = *((int*)bytes);  bytes += sizeof(int);
763         [windowController adjustLinespace:linespace];
764     } else if (ActivateMsgID == msgid) {
765         [NSApp activateIgnoringOtherApps:YES];
766         [[windowController window] makeKeyAndOrderFront:self];
767     } else if (SetServerNameMsgID == msgid) {
768         NSString *name = [[NSString alloc] initWithData:data
769                                                encoding:NSUTF8StringEncoding];
770         [self setServerName:name];
771         [name release];
772     } else if (EnterFullscreenMsgID == msgid) {
773         [windowController enterFullscreen];
774     } else if (LeaveFullscreenMsgID == msgid) {
775         [windowController leaveFullscreen];
776     } else if (BuffersNotModifiedMsgID == msgid) {
777         [[windowController window] setDocumentEdited:NO];
778     } else if (BuffersModifiedMsgID == msgid) {
779         [[windowController window] setDocumentEdited:YES];
780     } else {
781         NSLog(@"WARNING: Unknown message received (msgid=%d)", msgid);
782     }
786 #define MM_DEBUG_DRAWING 0
788 - (void)performBatchDrawWithData:(NSData *)data
790     // TODO!  Move to window controller.
791     MMTextStorage *textStorage = [windowController textStorage];
792     MMTextView *textView = [windowController textView];
793     if (!(textStorage && textView))
794         return;
796     const void *bytes = [data bytes];
797     const void *end = bytes + [data length];
799 #if MM_DEBUG_DRAWING
800     NSLog(@"====> BEGIN %s", _cmd);
801 #endif
802     [textStorage beginEditing];
804     // TODO: Sanity check input
806     while (bytes < end) {
807         int type = *((int*)bytes);  bytes += sizeof(int);
809         if (ClearAllDrawType == type) {
810 #if MM_DEBUG_DRAWING
811             NSLog(@"   Clear all");
812 #endif
813             [textStorage clearAll];
814         } else if (ClearBlockDrawType == type) {
815             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
816             int row1 = *((int*)bytes);  bytes += sizeof(int);
817             int col1 = *((int*)bytes);  bytes += sizeof(int);
818             int row2 = *((int*)bytes);  bytes += sizeof(int);
819             int col2 = *((int*)bytes);  bytes += sizeof(int);
821 #if MM_DEBUG_DRAWING
822             NSLog(@"   Clear block (%d,%d) -> (%d,%d)", row1, col1,
823                     row2,col2);
824 #endif
825             [textStorage clearBlockFromRow:row1 column:col1
826                     toRow:row2 column:col2
827                     color:[NSColor colorWithArgbInt:color]];
828         } else if (DeleteLinesDrawType == type) {
829             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
830             int row = *((int*)bytes);  bytes += sizeof(int);
831             int count = *((int*)bytes);  bytes += sizeof(int);
832             int bot = *((int*)bytes);  bytes += sizeof(int);
833             int left = *((int*)bytes);  bytes += sizeof(int);
834             int right = *((int*)bytes);  bytes += sizeof(int);
836 #if MM_DEBUG_DRAWING
837             NSLog(@"   Delete %d line(s) from %d", count, row);
838 #endif
839             [textStorage deleteLinesFromRow:row lineCount:count
840                     scrollBottom:bot left:left right:right
841                            color:[NSColor colorWithArgbInt:color]];
842         } else if (ReplaceStringDrawType == type) {
843             int bg = *((int*)bytes);  bytes += sizeof(int);
844             int fg = *((int*)bytes);  bytes += sizeof(int);
845             int sp = *((int*)bytes);  bytes += sizeof(int);
846             int row = *((int*)bytes);  bytes += sizeof(int);
847             int col = *((int*)bytes);  bytes += sizeof(int);
848             int flags = *((int*)bytes);  bytes += sizeof(int);
849             int len = *((int*)bytes);  bytes += sizeof(int);
850             NSString *string = [[NSString alloc]
851                     initWithBytesNoCopy:(void*)bytes
852                                  length:len
853                                encoding:NSUTF8StringEncoding
854                            freeWhenDone:NO];
855             bytes += len;
857 #if MM_DEBUG_DRAWING
858             NSLog(@"   Draw string at (%d,%d) length=%d flags=%d fg=0x%x "
859                     "bg=0x%x sp=0x%x (%@)", row, col, len, flags, fg, bg, sp,
860                     len > 0 ? [string substringToIndex:1] : @"");
861 #endif
862             // NOTE: If this is a call to draw the (block) cursor, then cancel
863             // any previous request to draw the insertion point, or it might
864             // get drawn as well.
865             if (flags & DRAW_CURSOR) {
866                 [textView setShouldDrawInsertionPoint:NO];
867                 //NSColor *color = [NSColor colorWithRgbInt:bg];
868                 //[textView drawInsertionPointAtRow:row column:col
869                 //                            shape:MMInsertionPointBlock
870                 //                            color:color];
871             }
872             [textStorage replaceString:string
873                                  atRow:row column:col
874                              withFlags:flags
875                        foregroundColor:[NSColor colorWithRgbInt:fg]
876                        backgroundColor:[NSColor colorWithArgbInt:bg]
877                           specialColor:[NSColor colorWithRgbInt:sp]];
879             [string release];
880         } else if (InsertLinesDrawType == type) {
881             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
882             int row = *((int*)bytes);  bytes += sizeof(int);
883             int count = *((int*)bytes);  bytes += sizeof(int);
884             int bot = *((int*)bytes);  bytes += sizeof(int);
885             int left = *((int*)bytes);  bytes += sizeof(int);
886             int right = *((int*)bytes);  bytes += sizeof(int);
888 #if MM_DEBUG_DRAWING
889             NSLog(@"   Insert %d line(s) at row %d", count, row);
890 #endif
891             [textStorage insertLinesAtRow:row lineCount:count
892                              scrollBottom:bot left:left right:right
893                                     color:[NSColor colorWithArgbInt:color]];
894         } else if (DrawCursorDrawType == type) {
895             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
896             int row = *((int*)bytes);  bytes += sizeof(int);
897             int col = *((int*)bytes);  bytes += sizeof(int);
898             int shape = *((int*)bytes);  bytes += sizeof(int);
899             int percent = *((int*)bytes);  bytes += sizeof(int);
901 #if MM_DEBUG_DRAWING
902             NSLog(@"   Draw cursor at (%d,%d)", row, col);
903 #endif
904             [textView drawInsertionPointAtRow:row column:col shape:shape
905                                      fraction:percent
906                                         color:[NSColor colorWithRgbInt:color]];
907         } else {
908             NSLog(@"WARNING: Unknown draw type (type=%d)", type);
909         }
910     }
912     [textStorage endEditing];
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