279cf8f8b01d16c1a7f0fa65ab344dc571120750
[MacVim.git] / src / MacVim / MMVimController.m
blob279cf8f8b01d16c1a7f0fa65ab344dc571120750
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  * MMVimController
12  *
13  * Coordinates input/output to/from backend.  A MMVimController sends input
14  * directly to a MMBackend, but communication from MMBackend to MMVimController
15  * goes via MMAppController so that it can coordinate all incoming distributed
16  * object messages.
17  *
18  * MMVimController does not deal with visual presentation.  Essentially it
19  * should be able to run with no window present.
20  *
21  * Output from the backend is received in processInputQueue: (this message is
22  * called from MMAppController so it is not a DO call).  Input is sent to the
23  * backend via sendMessage:data: or addVimInput:.  The latter allows execution
24  * of arbitrary strings in the Vim process, much like the Vim script function
25  * remote_send() does.  The messages that may be passed between frontend and
26  * backend are defined in an enum in MacVim.h.
27  */
29 #import "MMAppController.h"
30 #import "MMFindReplaceController.h"
31 #import "MMTextView.h"
32 #import "MMVimController.h"
33 #import "MMVimView.h"
34 #import "MMWindowController.h"
35 #import "Miscellaneous.h"
37 #ifdef MM_ENABLE_PLUGINS
38 #import "MMPlugInManager.h"
39 #endif
41 static NSString *MMDefaultToolbarImageName = @"Attention";
42 static int MMAlertTextFieldHeight = 22;
44 // NOTE: By default a message sent to the backend will be dropped if it cannot
45 // be delivered instantly; otherwise there is a possibility that MacVim will
46 // 'beachball' while waiting to deliver DO messages to an unresponsive Vim
47 // process.  This means that you cannot rely on any message sent with
48 // sendMessage: to actually reach Vim.
49 static NSTimeInterval MMBackendProxyRequestTimeout = 0;
51 // Timeout used for setDialogReturn:.
52 static NSTimeInterval MMSetDialogReturnTimeout = 1.0;
54 static unsigned identifierCounter = 1;
56 static BOOL isUnsafeMessage(int msgid);
59 @interface MMAlert : NSAlert {
60     NSTextField *textField;
62 - (void)setTextFieldString:(NSString *)textFieldString;
63 - (NSTextField *)textField;
64 @end
67 @interface MMVimController (Private)
68 - (void)doProcessInputQueue:(NSArray *)queue;
69 - (void)handleMessage:(int)msgid data:(NSData *)data;
70 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
71                 context:(void *)context;
72 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context;
73 - (NSMenuItem *)menuItemForDescriptor:(NSArray *)desc;
74 - (NSMenu *)parentMenuForDescriptor:(NSArray *)desc;
75 - (NSMenu *)topLevelMenuForTitle:(NSString *)title;
76 - (void)addMenuWithDescriptor:(NSArray *)desc atIndex:(int)index;
77 - (void)addMenuItemWithDescriptor:(NSArray *)desc
78                           atIndex:(int)index
79                               tip:(NSString *)tip
80                              icon:(NSString *)icon
81                     keyEquivalent:(NSString *)keyEquivalent
82                      modifierMask:(int)modifierMask
83                            action:(NSString *)action
84                       isAlternate:(BOOL)isAlternate;
85 - (void)removeMenuItemWithDescriptor:(NSArray *)desc;
86 - (void)enableMenuItemWithDescriptor:(NSArray *)desc state:(BOOL)on;
87 - (void)addToolbarItemToDictionaryWithLabel:(NSString *)title
88         toolTip:(NSString *)tip icon:(NSString *)icon;
89 - (void)addToolbarItemWithLabel:(NSString *)label
90                           tip:(NSString *)tip icon:(NSString *)icon
91                       atIndex:(int)idx;
92 - (void)popupMenuWithDescriptor:(NSArray *)desc
93                           atRow:(NSNumber *)row
94                          column:(NSNumber *)col;
95 - (void)popupMenuWithAttributes:(NSDictionary *)attrs;
96 - (void)connectionDidDie:(NSNotification *)notification;
97 - (void)scheduleClose;
98 - (void)handleBrowseForFile:(NSDictionary *)attr;
99 - (void)handleShowDialog:(NSDictionary *)attr;
100 @end
105 @implementation MMVimController
107 - (id)initWithBackend:(id)backend pid:(int)processIdentifier
109     if (!(self = [super init]))
110         return nil;
112     // TODO: Come up with a better way of creating an identifier.
113     identifier = identifierCounter++;
115     windowController =
116         [[MMWindowController alloc] initWithVimController:self];
117     backendProxy = [backend retain];
118     popupMenuItems = [[NSMutableArray alloc] init];
119     toolbarItemDict = [[NSMutableDictionary alloc] init];
120     pid = processIdentifier;
121     creationDate = [[NSDate alloc] init];
123     NSConnection *connection = [backendProxy connectionForProxy];
125     // TODO: Check that this will not set the timeout for the root proxy
126     // (in MMAppController).
127     [connection setRequestTimeout:MMBackendProxyRequestTimeout];
129     [[NSNotificationCenter defaultCenter] addObserver:self
130             selector:@selector(connectionDidDie:)
131                 name:NSConnectionDidDieNotification object:connection];
133     // Set up a main menu with only a "MacVim" menu (copied from a template
134     // which itself is set up in MainMenu.nib).  The main menu is populated
135     // by Vim later on.
136     mainMenu = [[NSMenu alloc] initWithTitle:@"MainMenu"];
137     NSMenuItem *appMenuItem = [[MMAppController sharedInstance]
138                                         appMenuItemTemplate];
139     appMenuItem = [[appMenuItem copy] autorelease];
141     // Note: If the title of the application menu is anything but what
142     // CFBundleName says then the application menu will not be typeset in
143     // boldface for some reason.  (It should already be set when we copy
144     // from the default main menu, but this is not the case for some
145     // reason.)
146     NSString *appName = [[NSBundle mainBundle]
147             objectForInfoDictionaryKey:@"CFBundleName"];
148     [appMenuItem setTitle:appName];
150     [mainMenu addItem:appMenuItem];
152 #ifdef MM_ENABLE_PLUGINS
153     instanceMediator = [[MMPlugInInstanceMediator alloc]
154             initWithVimController:self];
155 #endif
157     isInitialized = YES;
159     return self;
162 - (void)dealloc
164     ASLogDebug(@"");
166     isInitialized = NO;
168 #ifdef MM_ENABLE_PLUGINS
169     [instanceMediator release]; instanceMediator = nil;
170 #endif
172     [serverName release];  serverName = nil;
173     [backendProxy release];  backendProxy = nil;
175     [toolbarItemDict release];  toolbarItemDict = nil;
176     [toolbar release];  toolbar = nil;
177     [popupMenuItems release];  popupMenuItems = nil;
178     [windowController release];  windowController = nil;
180     [vimState release];  vimState = nil;
181     [mainMenu release];  mainMenu = nil;
182     [creationDate release];  creationDate = nil;
184     [super dealloc];
187 - (unsigned)vimControllerId
189     return identifier;
192 - (MMWindowController *)windowController
194     return windowController;
197 #ifdef MM_ENABLE_PLUGINS
198 - (MMPlugInInstanceMediator *)instanceMediator
200     return instanceMediator;
202 #endif
204 - (NSDictionary *)vimState
206     return vimState;
209 - (id)objectForVimStateKey:(NSString *)key
211     return [vimState objectForKey:key];
214 - (NSMenu *)mainMenu
216     return mainMenu;
219 - (BOOL)isPreloading
221     return isPreloading;
224 - (void)setIsPreloading:(BOOL)yn
226     isPreloading = yn;
229 - (NSDate *)creationDate
231     return creationDate;
234 - (void)setServerName:(NSString *)name
236     if (name != serverName) {
237         [serverName release];
238         serverName = [name copy];
239     }
242 - (NSString *)serverName
244     return serverName;
247 - (int)pid
249     return pid;
252 - (void)dropFiles:(NSArray *)filenames forceOpen:(BOOL)force
254     filenames = normalizeFilenames(filenames);
255     ASLogInfo(@"filenames=%@ force=%d", filenames, force);
257     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
259     // Default to opening in tabs if layout is invalid or set to "windows".
260     int layout = [ud integerForKey:MMOpenLayoutKey];
261     if (layout < 0 || layout > MMLayoutTabs)
262         layout = MMLayoutTabs;
264     BOOL splitVert = [ud boolForKey:MMVerticalSplitKey];
265     if (splitVert && MMLayoutHorizontalSplit == layout)
266         layout = MMLayoutVerticalSplit;
268     NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
269             [NSNumber numberWithInt:layout],    @"layout",
270             filenames,                          @"filenames",
271             [NSNumber numberWithBool:force],    @"forceOpen",
272             nil];
274     [self sendMessage:DropFilesMsgID data:[args dictionaryAsData]];
277 - (void)file:(NSString *)filename draggedToTabAtIndex:(NSUInteger)tabIndex
279     filename = normalizeFilename(filename);
280     ASLogInfo(@"filename=%@ index=%d", filename, tabIndex);
282     NSString *fnEsc = [filename stringByEscapingSpecialFilenameCharacters];
283     NSString *input = [NSString stringWithFormat:@"<C-\\><C-N>:silent "
284                        "tabnext %d |"
285                        "edit! %@<CR>", tabIndex + 1, fnEsc];
286     [self addVimInput:input];
289 - (void)filesDraggedToTabBar:(NSArray *)filenames
291     filenames = normalizeFilenames(filenames);
292     ASLogInfo(@"%@", filenames);
294     NSUInteger i, count = [filenames count];
295     NSMutableString *input = [NSMutableString stringWithString:@"<C-\\><C-N>"
296                               ":silent! tabnext 9999"];
297     for (i = 0; i < count; i++) {
298         NSString *fn = [filenames objectAtIndex:i];
299         NSString *fnEsc = [fn stringByEscapingSpecialFilenameCharacters];
300         [input appendFormat:@"|tabedit %@", fnEsc];
301     }
302     [input appendString:@"<CR>"];
303     [self addVimInput:input];
306 - (void)dropString:(NSString *)string
308     ASLogInfo(@"%@", string);
309     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
310     if (len > 0) {
311         NSMutableData *data = [NSMutableData data];
313         [data appendBytes:&len length:sizeof(int)];
314         [data appendBytes:[string UTF8String] length:len];
316         [self sendMessage:DropStringMsgID data:data];
317     }
320 - (void)passArguments:(NSDictionary *)args
322     if (!args) return;
324     ASLogDebug(@"args=%@", args);
326     [self sendMessage:OpenWithArgumentsMsgID data:[args dictionaryAsData]];
329 - (void)sendMessage:(int)msgid data:(NSData *)data
331     ASLogDebug(@"msg=%s (isInitialized=%d)",
332                MessageStrings[msgid], isInitialized);
334     if (!isInitialized) return;
336     @try {
337         [backendProxy processInput:msgid data:data];
338     }
339     @catch (NSException *ex) {
340         ASLogDebug(@"processInput:data: failed: pid=%d id=%d msg=%s reason=%@",
341                 pid, identifier, MessageStrings[msgid], ex);
342     }
345 - (BOOL)sendMessageNow:(int)msgid data:(NSData *)data
346                timeout:(NSTimeInterval)timeout
348     // Send a message with a timeout.  USE WITH EXTREME CAUTION!  Sending
349     // messages in rapid succession with a timeout may cause MacVim to beach
350     // ball forever.  In almost all circumstances sendMessage:data: should be
351     // used instead.
353     ASLogDebug(@"msg=%s (isInitialized=%d)",
354                MessageStrings[msgid], isInitialized);
356     if (!isInitialized)
357         return NO;
359     if (timeout < 0) timeout = 0;
361     BOOL sendOk = YES;
362     NSConnection *conn = [backendProxy connectionForProxy];
363     NSTimeInterval oldTimeout = [conn requestTimeout];
365     [conn setRequestTimeout:timeout];
367     @try {
368         [backendProxy processInput:msgid data:data];
369     }
370     @catch (NSException *ex) {
371         sendOk = NO;
372         ASLogDebug(@"processInput:data: failed: pid=%d id=%d msg=%s reason=%@",
373                 pid, identifier, MessageStrings[msgid], ex);
374     }
375     @finally {
376         [conn setRequestTimeout:oldTimeout];
377     }
379     return sendOk;
382 - (void)addVimInput:(NSString *)string
384     ASLogDebug(@"%@", string);
386     // This is a very general method of adding input to the Vim process.  It is
387     // basically the same as calling remote_send() on the process (see
388     // ':h remote_send').
389     if (string) {
390         NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
391         [self sendMessage:AddInputMsgID data:data];
392     }
395 - (NSString *)evaluateVimExpression:(NSString *)expr
397     NSString *eval = nil;
399     @try {
400         eval = [backendProxy evaluateExpression:expr];
401         ASLogDebug(@"eval(%@)=%@", expr, eval);
402     }
403     @catch (NSException *ex) {
404         ASLogDebug(@"evaluateExpression: failed: pid=%d id=%d reason=%@",
405                 pid, identifier, ex);
406     }
408     return eval;
411 - (id)evaluateVimExpressionCocoa:(NSString *)expr
412                      errorString:(NSString **)errstr
414     id eval = nil;
416     @try {
417         eval = [backendProxy evaluateExpressionCocoa:expr
418                                          errorString:errstr];
419         ASLogDebug(@"eval(%@)=%@", expr, eval);
420     } @catch (NSException *ex) {
421         ASLogDebug(@"evaluateExpressionCocoa: failed: pid=%d id=%d reason=%@",
422                 pid, identifier, ex);
423         *errstr = [ex reason];
424     }
426     return eval;
429 - (id)backendProxy
431     return backendProxy;
434 - (void)cleanup
436     if (!isInitialized) return;
438     // Remove any delayed calls made on this object.
439     [NSObject cancelPreviousPerformRequestsWithTarget:self];
441     isInitialized = NO;
442     [toolbar setDelegate:nil];
443     [[NSNotificationCenter defaultCenter] removeObserver:self];
444     //[[backendProxy connectionForProxy] invalidate];
445     //[windowController close];
446     [windowController cleanup];
449 - (void)processInputQueue:(NSArray *)queue
451     if (!isInitialized) return;
453     // NOTE: This method must not raise any exceptions (see comment in the
454     // calling method).
455     @try {
456         [self doProcessInputQueue:queue];
457         [windowController processInputQueueDidFinish];
458     }
459     @catch (NSException *ex) {
460         ASLogDebug(@"Exception: pid=%d id=%d reason=%@", pid, identifier, ex);
461     }
464 - (NSToolbarItem *)toolbar:(NSToolbar *)theToolbar
465     itemForItemIdentifier:(NSString *)itemId
466     willBeInsertedIntoToolbar:(BOOL)flag
468     NSToolbarItem *item = [toolbarItemDict objectForKey:itemId];
469     if (!item) {
470         ASLogWarn(@"No toolbar item with id '%@'", itemId);
471     }
473     return item;
476 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)theToolbar
478     return nil;
481 - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)theToolbar
483     return nil;
486 @end // MMVimController
490 @implementation MMVimController (Private)
492 - (void)doProcessInputQueue:(NSArray *)queue
494     NSMutableArray *delayQueue = nil;
496     unsigned i, count = [queue count];
497     if (count % 2) {
498         ASLogWarn(@"Uneven number of components (%d) in command queue.  "
499                   "Skipping...", count);
500         return;
501     }
503     for (i = 0; i < count; i += 2) {
504         NSData *value = [queue objectAtIndex:i];
505         NSData *data = [queue objectAtIndex:i+1];
507         int msgid = *((int*)[value bytes]);
509         BOOL inDefaultMode = [[[NSRunLoop currentRunLoop] currentMode]
510                                             isEqual:NSDefaultRunLoopMode];
511         if (!inDefaultMode && isUnsafeMessage(msgid)) {
512             // NOTE: Because we may be listening to DO messages in "event
513             // tracking mode" we have to take extra care when doing things
514             // like releasing view items (and other Cocoa objects).
515             // Messages that may be potentially "unsafe" are delayed until
516             // the run loop is back to default mode at which time they are
517             // safe to call again.
518             //   A problem with this approach is that it is hard to
519             // classify which messages are unsafe.  As a rule of thumb, if
520             // a message may release an object used by the Cocoa framework
521             // (e.g. views) then the message should be considered unsafe.
522             //   Delaying messages may have undesired side-effects since it
523             // means that messages may not be processed in the order Vim
524             // sent them, so beware.
525             if (!delayQueue)
526                 delayQueue = [NSMutableArray array];
528             ASLogDebug(@"Adding unsafe message '%s' to delay queue (mode=%@)",
529                        MessageStrings[msgid],
530                        [[NSRunLoop currentRunLoop] currentMode]);
531             [delayQueue addObject:value];
532             [delayQueue addObject:data];
533         } else {
534             [self handleMessage:msgid data:data];
535         }
536     }
538     if (delayQueue) {
539         ASLogDebug(@"    Flushing delay queue (%d items)",
540                    [delayQueue count]/2);
541         [self performSelector:@selector(processInputQueue:)
542                    withObject:delayQueue
543                    afterDelay:0];
544     }
547 - (void)handleMessage:(int)msgid data:(NSData *)data
549     if (OpenWindowMsgID == msgid) {
550         [windowController openWindow];
552         // If the vim controller is preloading then the window will be
553         // displayed when it is taken off the preload cache.
554         if (!isPreloading)
555             [windowController showWindow];
556     } else if (BatchDrawMsgID == msgid) {
557         [[[windowController vimView] textView] performBatchDrawWithData:data];
558     } else if (SelectTabMsgID == msgid) {
559 #if 0   // NOTE: Tab selection is done inside updateTabsWithData:.
560         const void *bytes = [data bytes];
561         int idx = *((int*)bytes);
562         [windowController selectTabWithIndex:idx];
563 #endif
564     } else if (UpdateTabBarMsgID == msgid) {
565         [windowController updateTabsWithData:data];
566     } else if (ShowTabBarMsgID == msgid) {
567         [windowController showTabBar:YES];
568     } else if (HideTabBarMsgID == msgid) {
569         [windowController showTabBar:NO];
570     } else if (SetTextDimensionsMsgID == msgid || LiveResizeMsgID == msgid ||
571             SetTextDimensionsReplyMsgID == msgid) {
572         const void *bytes = [data bytes];
573         int rows = *((int*)bytes);  bytes += sizeof(int);
574         int cols = *((int*)bytes);  bytes += sizeof(int);
576         // NOTE: When a resize message originated in the frontend, Vim
577         // acknowledges it with a reply message.  When this happens the window
578         // should not move (the frontend would already have moved the window).
579         BOOL onScreen = SetTextDimensionsReplyMsgID!=msgid;
581         [windowController setTextDimensionsWithRows:rows
582                                  columns:cols
583                                   isLive:(LiveResizeMsgID==msgid)
584                             keepOnScreen:onScreen];
585     } else if (SetWindowTitleMsgID == msgid) {
586         const void *bytes = [data bytes];
587         int len = *((int*)bytes);  bytes += sizeof(int);
589         NSString *string = [[NSString alloc] initWithBytes:(void*)bytes
590                 length:len encoding:NSUTF8StringEncoding];
592         // While in live resize the window title displays the dimensions of the
593         // window so don't clobber this with a spurious "set title" message
594         // from Vim.
595         if (![[windowController vimView] inLiveResize])
596             [windowController setTitle:string];
598         [string release];
599     } else if (SetDocumentFilenameMsgID == msgid) {
600         const void *bytes = [data bytes];
601         int len = *((int*)bytes);  bytes += sizeof(int);
603         if (len > 0) {
604             NSString *filename = [[NSString alloc] initWithBytes:(void*)bytes
605                     length:len encoding:NSUTF8StringEncoding];
607             [windowController setDocumentFilename:filename];
609             [filename release];
610         } else {
611             [windowController setDocumentFilename:@""];
612         }
613     } else if (AddMenuMsgID == msgid) {
614         NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
615         [self addMenuWithDescriptor:[attrs objectForKey:@"descriptor"]
616                 atIndex:[[attrs objectForKey:@"index"] intValue]];
617     } else if (AddMenuItemMsgID == msgid) {
618         NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
619         [self addMenuItemWithDescriptor:[attrs objectForKey:@"descriptor"]
620                       atIndex:[[attrs objectForKey:@"index"] intValue]
621                           tip:[attrs objectForKey:@"tip"]
622                          icon:[attrs objectForKey:@"icon"]
623                 keyEquivalent:[attrs objectForKey:@"keyEquivalent"]
624                  modifierMask:[[attrs objectForKey:@"modifierMask"] intValue]
625                        action:[attrs objectForKey:@"action"]
626                   isAlternate:[[attrs objectForKey:@"isAlternate"] boolValue]];
627     } else if (RemoveMenuItemMsgID == msgid) {
628         NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
629         [self removeMenuItemWithDescriptor:[attrs objectForKey:@"descriptor"]];
630     } else if (EnableMenuItemMsgID == msgid) {
631         NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
632         [self enableMenuItemWithDescriptor:[attrs objectForKey:@"descriptor"]
633                 state:[[attrs objectForKey:@"enable"] boolValue]];
634     } else if (ShowToolbarMsgID == msgid) {
635         const void *bytes = [data bytes];
636         int enable = *((int*)bytes);  bytes += sizeof(int);
637         int flags = *((int*)bytes);  bytes += sizeof(int);
639         int mode = NSToolbarDisplayModeDefault;
640         if (flags & ToolbarLabelFlag) {
641             mode = flags & ToolbarIconFlag ? NSToolbarDisplayModeIconAndLabel
642                     : NSToolbarDisplayModeLabelOnly;
643         } else if (flags & ToolbarIconFlag) {
644             mode = NSToolbarDisplayModeIconOnly;
645         }
647         int size = flags & ToolbarSizeRegularFlag ? NSToolbarSizeModeRegular
648                 : NSToolbarSizeModeSmall;
650         [windowController showToolbar:enable size:size mode:mode];
651     } else if (CreateScrollbarMsgID == msgid) {
652         const void *bytes = [data bytes];
653         int32_t ident = *((int32_t*)bytes);  bytes += sizeof(int32_t);
654         int type = *((int*)bytes);  bytes += sizeof(int);
656         [windowController createScrollbarWithIdentifier:ident type:type];
657     } else if (DestroyScrollbarMsgID == msgid) {
658         const void *bytes = [data bytes];
659         int32_t ident = *((int32_t*)bytes);  bytes += sizeof(int32_t);
661         [windowController destroyScrollbarWithIdentifier:ident];
662     } else if (ShowScrollbarMsgID == msgid) {
663         const void *bytes = [data bytes];
664         int32_t ident = *((int32_t*)bytes);  bytes += sizeof(int32_t);
665         int visible = *((int*)bytes);  bytes += sizeof(int);
667         [windowController showScrollbarWithIdentifier:ident state:visible];
668     } else if (SetScrollbarPositionMsgID == msgid) {
669         const void *bytes = [data bytes];
670         int32_t ident = *((int32_t*)bytes);  bytes += sizeof(int32_t);
671         int pos = *((int*)bytes);  bytes += sizeof(int);
672         int len = *((int*)bytes);  bytes += sizeof(int);
674         [windowController setScrollbarPosition:pos length:len
675                                     identifier:ident];
676     } else if (SetScrollbarThumbMsgID == msgid) {
677         const void *bytes = [data bytes];
678         int32_t ident = *((int32_t*)bytes);  bytes += sizeof(int32_t);
679         float val = *((float*)bytes);  bytes += sizeof(float);
680         float prop = *((float*)bytes);  bytes += sizeof(float);
682         [windowController setScrollbarThumbValue:val proportion:prop
683                                       identifier:ident];
684     } else if (SetFontMsgID == msgid) {
685         const void *bytes = [data bytes];
686         float size = *((float*)bytes);  bytes += sizeof(float);
687         int len = *((int*)bytes);  bytes += sizeof(int);
688         NSString *name = [[NSString alloc]
689                 initWithBytes:(void*)bytes length:len
690                      encoding:NSUTF8StringEncoding];
691         NSFont *font = [NSFont fontWithName:name size:size];
692         if (!font) {
693             // This should only happen if the default font was not loaded in
694             // which case we fall back on using the Cocoa default fixed width
695             // font.
696             font = [NSFont userFixedPitchFontOfSize:size];
697         }
699         [windowController setFont:font];
700         [name release];
701     } else if (SetWideFontMsgID == msgid) {
702         const void *bytes = [data bytes];
703         float size = *((float*)bytes);  bytes += sizeof(float);
704         int len = *((int*)bytes);  bytes += sizeof(int);
705         if (len > 0) {
706             NSString *name = [[NSString alloc]
707                     initWithBytes:(void*)bytes length:len
708                          encoding:NSUTF8StringEncoding];
709             NSFont *font = [NSFont fontWithName:name size:size];
710             [windowController setWideFont:font];
712             [name release];
713         } else {
714             [windowController setWideFont:nil];
715         }
716     } else if (SetDefaultColorsMsgID == msgid) {
717         const void *bytes = [data bytes];
718         unsigned bg = *((unsigned*)bytes);  bytes += sizeof(unsigned);
719         unsigned fg = *((unsigned*)bytes);  bytes += sizeof(unsigned);
720         NSColor *back = [NSColor colorWithArgbInt:bg];
721         NSColor *fore = [NSColor colorWithRgbInt:fg];
723         [windowController setDefaultColorsBackground:back foreground:fore];
724     } else if (ExecuteActionMsgID == msgid) {
725         const void *bytes = [data bytes];
726         int len = *((int*)bytes);  bytes += sizeof(int);
727         NSString *actionName = [[NSString alloc]
728                 initWithBytes:(void*)bytes length:len
729                      encoding:NSUTF8StringEncoding];
731         SEL sel = NSSelectorFromString(actionName);
732         [NSApp sendAction:sel to:nil from:self];
734         [actionName release];
735     } else if (ShowPopupMenuMsgID == msgid) {
736         NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
738         // The popup menu enters a modal loop so delay this call so that we
739         // don't block inside processInputQueue:.
740         [self performSelector:@selector(popupMenuWithAttributes:)
741                    withObject:attrs
742                    afterDelay:0];
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 if (EnterFullscreenMsgID == msgid) {
762         const void *bytes = [data bytes];
763         int fuoptions = *((int*)bytes); bytes += sizeof(int);
764         int bg = *((int*)bytes);
765         NSColor *back = [NSColor colorWithArgbInt:bg];
767         [windowController enterFullscreen:fuoptions backgroundColor:back];
768     } else if (LeaveFullscreenMsgID == msgid) {
769         [windowController leaveFullscreen];
770     } else if (BuffersNotModifiedMsgID == msgid) {
771         [windowController setBuffersModified:NO];
772     } else if (BuffersModifiedMsgID == msgid) {
773         [windowController setBuffersModified:YES];
774     } else if (SetPreEditPositionMsgID == msgid) {
775         const int *dim = (const int*)[data bytes];
776         [[[windowController vimView] textView] setPreEditRow:dim[0]
777                                                       column:dim[1]];
778     } else if (EnableAntialiasMsgID == msgid) {
779         [[[windowController vimView] textView] setAntialias:YES];
780     } else if (DisableAntialiasMsgID == msgid) {
781         [[[windowController vimView] textView] setAntialias:NO];
782     } else if (SetVimStateMsgID == msgid) {
783         NSDictionary *dict = [NSDictionary dictionaryWithData:data];
784         if (dict) {
785             [vimState release];
786             vimState = [dict retain];
787         }
788     } else if (CloseWindowMsgID == msgid) {
789         [self scheduleClose];
790     } else if (SetFullscreenColorMsgID == msgid) {
791         const int *bg = (const int*)[data bytes];
792         NSColor *color = [NSColor colorWithRgbInt:*bg];
794         [windowController setFullscreenBackgroundColor:color];
795     } else if (ShowFindReplaceDialogMsgID == msgid) {
796         NSDictionary *dict = [NSDictionary dictionaryWithData:data];
797         if (dict) {
798             [[MMFindReplaceController sharedInstance]
799                 showWithText:[dict objectForKey:@"text"]
800                        flags:[[dict objectForKey:@"flags"] intValue]];
801         }
802     } else if (ActivateKeyScriptMsgID == msgid) {
803         [[[windowController vimView] textView] activateIm:YES];
804     } else if (DeactivateKeyScriptMsgID == msgid) {
805         [[[windowController vimView] textView] activateIm:NO];
806     } else if (EnableImControlMsgID == msgid) {
807         [[[windowController vimView] textView] setImControl:YES];
808     } else if (DisableImControlMsgID == msgid) {
809         [[[windowController vimView] textView] setImControl:NO];
810     } else if (BrowseForFileMsgID == msgid) {
811         NSDictionary *dict = [NSDictionary dictionaryWithData:data];
812         if (dict)
813             [self handleBrowseForFile:dict];
814     } else if (ShowDialogMsgID == msgid) {
815         NSDictionary *dict = [NSDictionary dictionaryWithData:data];
816         if (dict)
817             [self handleShowDialog:dict];
818     } else if (ZoomMsgID == msgid) {
819         const void *bytes = [data bytes];
820         int rows = *((int*)bytes);  bytes += sizeof(int);
821         int cols = *((int*)bytes);  bytes += sizeof(int);
822         int state = *((int*)bytes);  bytes += sizeof(int);
824         [windowController zoomWithRows:rows
825                                columns:cols
826                                  state:state];
827     // IMPORTANT: When adding a new message, make sure to update
828     // isUnsafeMessage() if necessary!
829     } else {
830         ASLogWarn(@"Unknown message received (msgid=%d)", msgid);
831     }
834 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
835                 context:(void *)context
837     NSString *path = (code == NSOKButton) ? [panel filename] : nil;
838     ASLogDebug(@"Open/save panel path=%@", path);
840     // NOTE!  This causes the sheet animation to run its course BEFORE the rest
841     // of this function is executed.  If we do not wait for the sheet to
842     // disappear before continuing it can happen that the controller is
843     // released from under us (i.e. we'll crash and burn) because this
844     // animation is otherwise performed in the default run loop mode!
845     [panel orderOut:self];
847     // NOTE! setDialogReturn: is a synchronous call so set a proper timeout to
848     // avoid waiting forever for it to finish.  We make this a synchronous call
849     // so that we can be fairly certain that Vim doesn't think the dialog box
850     // is still showing when MacVim has in fact already dismissed it.
851     NSConnection *conn = [backendProxy connectionForProxy];
852     NSTimeInterval oldTimeout = [conn requestTimeout];
853     [conn setRequestTimeout:MMSetDialogReturnTimeout];
855     @try {
856         [backendProxy setDialogReturn:path];
858         // Add file to the "Recent Files" menu (this ensures that files that
859         // are opened/saved from a :browse command are added to this menu).
860         if (path)
861             [[NSDocumentController sharedDocumentController]
862                     noteNewRecentFilePath:path];
863     }
864     @catch (NSException *ex) {
865         ASLogDebug(@"Exception: pid=%d id=%d reason=%@", pid, identifier, ex);
866     }
867     @finally {
868         [conn setRequestTimeout:oldTimeout];
869     }
872 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context
874     NSArray *ret = nil;
876     code = code - NSAlertFirstButtonReturn + 1;
878     if ([alert isKindOfClass:[MMAlert class]] && [alert textField]) {
879         ret = [NSArray arrayWithObjects:[NSNumber numberWithInt:code],
880             [[alert textField] stringValue], nil];
881     } else {
882         ret = [NSArray arrayWithObject:[NSNumber numberWithInt:code]];
883     }
885     ASLogDebug(@"Alert return=%@", ret);
887     // NOTE!  This causes the sheet animation to run its course BEFORE the rest
888     // of this function is executed.  If we do not wait for the sheet to
889     // disappear before continuing it can happen that the controller is
890     // released from under us (i.e. we'll crash and burn) because this
891     // animation is otherwise performed in the default run loop mode!
892     [[alert window] orderOut:self];
894     @try {
895         [backendProxy setDialogReturn:ret];
896     }
897     @catch (NSException *ex) {
898         ASLogDebug(@"setDialogReturn: failed: pid=%d id=%d reason=%@",
899                 pid, identifier, ex);
900     }
903 - (NSMenuItem *)menuItemForDescriptor:(NSArray *)desc
905     if (!(desc && [desc count] > 0)) return nil;
907     NSString *rootName = [desc objectAtIndex:0];
908     NSArray *rootItems = [rootName hasPrefix:@"PopUp"] ? popupMenuItems
909                                                        : [mainMenu itemArray];
911     NSMenuItem *item = nil;
912     int i, count = [rootItems count];
913     for (i = 0; i < count; ++i) {
914         item = [rootItems objectAtIndex:i];
915         if ([[item title] isEqual:rootName])
916             break;
917     }
919     if (i == count) return nil;
921     count = [desc count];
922     for (i = 1; i < count; ++i) {
923         item = [[item submenu] itemWithTitle:[desc objectAtIndex:i]];
924         if (!item) return nil;
925     }
927     return item;
930 - (NSMenu *)parentMenuForDescriptor:(NSArray *)desc
932     if (!(desc && [desc count] > 0)) return nil;
934     NSString *rootName = [desc objectAtIndex:0];
935     NSArray *rootItems = [rootName hasPrefix:@"PopUp"] ? popupMenuItems
936                                                        : [mainMenu itemArray];
938     NSMenu *menu = nil;
939     int i, count = [rootItems count];
940     for (i = 0; i < count; ++i) {
941         NSMenuItem *item = [rootItems objectAtIndex:i];
942         if ([[item title] isEqual:rootName]) {
943             menu = [item submenu];
944             break;
945         }
946     }
948     if (!menu) return nil;
950     count = [desc count] - 1;
951     for (i = 1; i < count; ++i) {
952         NSMenuItem *item = [menu itemWithTitle:[desc objectAtIndex:i]];
953         menu = [item submenu];
954         if (!menu) return nil;
955     }
957     return menu;
960 - (NSMenu *)topLevelMenuForTitle:(NSString *)title
962     // Search only the top-level menus.
964     unsigned i, count = [popupMenuItems count];
965     for (i = 0; i < count; ++i) {
966         NSMenuItem *item = [popupMenuItems objectAtIndex:i];
967         if ([title isEqual:[item title]])
968             return [item submenu];
969     }
971     count = [mainMenu numberOfItems];
972     for (i = 0; i < count; ++i) {
973         NSMenuItem *item = [mainMenu itemAtIndex:i];
974         if ([title isEqual:[item title]])
975             return [item submenu];
976     }
978     return nil;
981 - (void)addMenuWithDescriptor:(NSArray *)desc atIndex:(int)idx
983     if (!(desc && [desc count] > 0 && idx >= 0)) return;
985     NSString *rootName = [desc objectAtIndex:0];
986     if ([rootName isEqual:@"ToolBar"]) {
987         // The toolbar only has one menu, we take this as a hint to create a
988         // toolbar, then we return.
989         if (!toolbar) {
990             // NOTE! Each toolbar must have a unique identifier, else each
991             // window will have the same toolbar.
992             NSString *ident = [NSString stringWithFormat:@"%d", identifier];
993             toolbar = [[NSToolbar alloc] initWithIdentifier:ident];
995             [toolbar setShowsBaselineSeparator:NO];
996             [toolbar setDelegate:self];
997             [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
998             [toolbar setSizeMode:NSToolbarSizeModeSmall];
1000             [windowController setToolbar:toolbar];
1001         }
1003         return;
1004     }
1006     // This is either a main menu item or a popup menu item.
1007     NSString *title = [desc lastObject];
1008     NSMenuItem *item = [[NSMenuItem alloc] init];
1009     NSMenu *menu = [[NSMenu alloc] initWithTitle:title];
1011     [item setTitle:title];
1012     [item setSubmenu:menu];
1014     NSMenu *parent = [self parentMenuForDescriptor:desc];
1015     if (!parent && [rootName hasPrefix:@"PopUp"]) {
1016         if ([popupMenuItems count] <= idx) {
1017             [popupMenuItems addObject:item];
1018         } else {
1019             [popupMenuItems insertObject:item atIndex:idx];
1020         }
1021     } else {
1022         // If descriptor has no parent and its not a popup (or toolbar) menu,
1023         // then it must belong to main menu.
1024         if (!parent) parent = mainMenu;
1026         if ([parent numberOfItems] <= idx) {
1027             [parent addItem:item];
1028         } else {
1029             [parent insertItem:item atIndex:idx];
1030         }
1031     }
1033     [item release];
1034     [menu release];
1037 - (void)addMenuItemWithDescriptor:(NSArray *)desc
1038                           atIndex:(int)idx
1039                               tip:(NSString *)tip
1040                              icon:(NSString *)icon
1041                     keyEquivalent:(NSString *)keyEquivalent
1042                      modifierMask:(int)modifierMask
1043                            action:(NSString *)action
1044                       isAlternate:(BOOL)isAlternate
1046     if (!(desc && [desc count] > 1 && idx >= 0)) return;
1048     NSString *title = [desc lastObject];
1049     NSString *rootName = [desc objectAtIndex:0];
1051     if ([rootName isEqual:@"ToolBar"]) {
1052         if (toolbar && [desc count] == 2)
1053             [self addToolbarItemWithLabel:title tip:tip icon:icon atIndex:idx];
1054         return;
1055     }
1057     NSMenu *parent = [self parentMenuForDescriptor:desc];
1058     if (!parent) {
1059         ASLogWarn(@"Menu item '%@' has no parent",
1060                   [desc componentsJoinedByString:@"->"]);
1061         return;
1062     }
1064     NSMenuItem *item = nil;
1065     if (0 == [title length]
1066             || ([title hasPrefix:@"-"] && [title hasSuffix:@"-"])) {
1067         item = [NSMenuItem separatorItem];
1068         [item setTitle:title];
1069     } else {
1070         item = [[[NSMenuItem alloc] init] autorelease];
1071         [item setTitle:title];
1073         // Note: It is possible to set the action to a message that "doesn't
1074         // exist" without problems.  We take advantage of this when adding
1075         // "dummy items" e.g. when dealing with the "Recent Files" menu (in
1076         // which case a recentFilesDummy: action is set, although it is never
1077         // used).
1078         if ([action length] > 0)
1079             [item setAction:NSSelectorFromString(action)];
1080         else
1081             [item setAction:@selector(vimMenuItemAction:)];
1082         if ([tip length] > 0) [item setToolTip:tip];
1083         if ([keyEquivalent length] > 0) {
1084             [item setKeyEquivalent:keyEquivalent];
1085             [item setKeyEquivalentModifierMask:modifierMask];
1086         }
1087         [item setAlternate:isAlternate];
1089         // The tag is used to indicate whether Vim thinks a menu item should be
1090         // enabled or disabled.  By default Vim thinks menu items are enabled.
1091         [item setTag:1];
1092     }
1094     if ([parent numberOfItems] <= idx) {
1095         [parent addItem:item];
1096     } else {
1097         [parent insertItem:item atIndex:idx];
1098     }
1101 - (void)removeMenuItemWithDescriptor:(NSArray *)desc
1103     if (!(desc && [desc count] > 0)) return;
1105     NSString *title = [desc lastObject];
1106     NSString *rootName = [desc objectAtIndex:0];
1107     if ([rootName isEqual:@"ToolBar"]) {
1108         if (toolbar) {
1109             // Only remove toolbar items, never actually remove the toolbar
1110             // itself or strange things may happen.
1111             if ([desc count] == 2) {
1112                 NSUInteger idx = [toolbar indexOfItemWithItemIdentifier:title];
1113                 if (idx != NSNotFound)
1114                     [toolbar removeItemAtIndex:idx];
1115             }
1116         }
1117         return;
1118     }
1120     NSMenuItem *item = [self menuItemForDescriptor:desc];
1121     if (!item) {
1122         ASLogWarn(@"Failed to remove menu item, descriptor not found: %@",
1123                   [desc componentsJoinedByString:@"->"]);
1124         return;
1125     }
1127     [item retain];
1129     if ([item menu] == [NSApp mainMenu] || ![item menu]) {
1130         // NOTE: To be on the safe side we try to remove the item from
1131         // both arrays (it is ok to call removeObject: even if an array
1132         // does not contain the object to remove).
1133         [popupMenuItems removeObject:item];
1134     }
1136     if ([item menu])
1137         [[item menu] removeItem:item];
1139     [item release];
1142 - (void)enableMenuItemWithDescriptor:(NSArray *)desc state:(BOOL)on
1144     if (!(desc && [desc count] > 0)) return;
1146     NSString *rootName = [desc objectAtIndex:0];
1147     if ([rootName isEqual:@"ToolBar"]) {
1148         if (toolbar && [desc count] == 2) {
1149             NSString *title = [desc lastObject];
1150             [[toolbar itemWithItemIdentifier:title] setEnabled:on];
1151         }
1152     } else {
1153         // Use tag to set whether item is enabled or disabled instead of
1154         // calling setEnabled:.  This way the menus can autoenable themselves
1155         // but at the same time Vim can set if a menu is enabled whenever it
1156         // wants to.
1157         [[self menuItemForDescriptor:desc] setTag:on];
1158     }
1161 - (void)addToolbarItemToDictionaryWithLabel:(NSString *)title
1162                                     toolTip:(NSString *)tip
1163                                        icon:(NSString *)icon
1165     // If the item corresponds to a separator then do nothing, since it is
1166     // already defined by Cocoa.
1167     if (!title || [title isEqual:NSToolbarSeparatorItemIdentifier]
1168                || [title isEqual:NSToolbarSpaceItemIdentifier]
1169                || [title isEqual:NSToolbarFlexibleSpaceItemIdentifier])
1170         return;
1172     NSToolbarItem *item = [[NSToolbarItem alloc] initWithItemIdentifier:title];
1173     [item setLabel:title];
1174     [item setToolTip:tip];
1175     [item setAction:@selector(vimToolbarItemAction:)];
1176     [item setAutovalidates:NO];
1178     NSImage *img = [NSImage imageNamed:icon];
1179     if (!img) {
1180         img = [[[NSImage alloc] initByReferencingFile:icon] autorelease];
1181         if (!(img && [img isValid]))
1182             img = nil;
1183     }
1184     if (!img) {
1185         ASLogNotice(@"Could not find image with name '%@' to use as toolbar"
1186             " image for identifier '%@';"
1187             " using default toolbar icon '%@' instead.",
1188             icon, title, MMDefaultToolbarImageName);
1190         img = [NSImage imageNamed:MMDefaultToolbarImageName];
1191     }
1193     [item setImage:img];
1195     [toolbarItemDict setObject:item forKey:title];
1197     [item release];
1200 - (void)addToolbarItemWithLabel:(NSString *)label
1201                             tip:(NSString *)tip
1202                            icon:(NSString *)icon
1203                         atIndex:(int)idx
1205     if (!toolbar) return;
1207     // Check for separator items.
1208     if (!label) {
1209         label = NSToolbarSeparatorItemIdentifier;
1210     } else if ([label length] >= 2 && [label hasPrefix:@"-"]
1211                                    && [label hasSuffix:@"-"]) {
1212         // The label begins and ends with '-'; decided which kind of separator
1213         // item it is by looking at the prefix.
1214         if ([label hasPrefix:@"-space"]) {
1215             label = NSToolbarSpaceItemIdentifier;
1216         } else if ([label hasPrefix:@"-flexspace"]) {
1217             label = NSToolbarFlexibleSpaceItemIdentifier;
1218         } else {
1219             label = NSToolbarSeparatorItemIdentifier;
1220         }
1221     }
1223     [self addToolbarItemToDictionaryWithLabel:label toolTip:tip icon:icon];
1225     int maxIdx = [[toolbar items] count];
1226     if (maxIdx < idx) idx = maxIdx;
1228     [toolbar insertItemWithItemIdentifier:label atIndex:idx];
1231 - (void)popupMenuWithDescriptor:(NSArray *)desc
1232                           atRow:(NSNumber *)row
1233                          column:(NSNumber *)col
1235     NSMenu *menu = [[self menuItemForDescriptor:desc] submenu];
1236     if (!menu) return;
1238     id textView = [[windowController vimView] textView];
1239     NSPoint pt;
1240     if (row && col) {
1241         // TODO: Let textView convert (row,col) to NSPoint.
1242         int r = [row intValue];
1243         int c = [col intValue];
1244         NSSize cellSize = [textView cellSize];
1245         pt = NSMakePoint((c+1)*cellSize.width, (r+1)*cellSize.height);
1246         pt = [textView convertPoint:pt toView:nil];
1247     } else {
1248         pt = [[windowController window] mouseLocationOutsideOfEventStream];
1249     }
1251     NSEvent *event = [NSEvent mouseEventWithType:NSRightMouseDown
1252                            location:pt
1253                       modifierFlags:0
1254                           timestamp:0
1255                        windowNumber:[[windowController window] windowNumber]
1256                             context:nil
1257                         eventNumber:0
1258                          clickCount:0
1259                            pressure:1.0];
1261     [NSMenu popUpContextMenu:menu withEvent:event forView:textView];
1264 - (void)popupMenuWithAttributes:(NSDictionary *)attrs
1266     if (!attrs) return;
1268     [self popupMenuWithDescriptor:[attrs objectForKey:@"descriptor"]
1269                             atRow:[attrs objectForKey:@"row"]
1270                            column:[attrs objectForKey:@"column"]];
1273 - (void)connectionDidDie:(NSNotification *)notification
1275     ASLogDebug(@"%@", notification);
1276     [self scheduleClose];
1279 - (void)scheduleClose
1281     ASLogDebug(@"pid=%d id=%d", pid, identifier);
1283     // NOTE!  This message can arrive at pretty much anytime, e.g. while
1284     // the run loop is the 'event tracking' mode.  This means that Cocoa may
1285     // well be in the middle of processing some message while this message is
1286     // received.  If we were to remove the vim controller straight away we may
1287     // free objects that Cocoa is currently using (e.g. view objects).  The
1288     // following call ensures that the vim controller is not released until the
1289     // run loop is back in the 'default' mode.
1290     // Also, since the app may be multithreaded (e.g. as a result of showing
1291     // the open panel) we have to ensure this call happens on the main thread,
1292     // else there is a race condition that may lead to a crash.
1293     [[MMAppController sharedInstance]
1294             performSelectorOnMainThread:@selector(removeVimController:)
1295                              withObject:self
1296                           waitUntilDone:NO
1297                                   modes:[NSArray arrayWithObject:
1298                                          NSDefaultRunLoopMode]];
1301 // NSSavePanel delegate
1302 - (void)panel:(id)sender willExpand:(BOOL)expanding
1304     // Show or hide the "show hidden files" button
1305     if (expanding) {
1306         [sender setAccessoryView:showHiddenFilesView()];
1307     } else {
1308         [sender setShowsHiddenFiles:NO];
1309         [sender setAccessoryView:nil];
1310     }
1313 - (void)handleBrowseForFile:(NSDictionary *)attr
1315     if (!isInitialized) return;
1317     NSString *dir = [attr objectForKey:@"dir"];
1318     BOOL saving = [[attr objectForKey:@"saving"] boolValue];
1320     if (!dir) {
1321         // 'dir == nil' means: set dir to the pwd of the Vim process, or let
1322         // open dialog decide (depending on the below user default).
1323         BOOL trackPwd = [[NSUserDefaults standardUserDefaults]
1324                 boolForKey:MMDialogsTrackPwdKey];
1325         if (trackPwd)
1326             dir = [vimState objectForKey:@"pwd"];
1327     }
1329     if (saving) {
1330         NSSavePanel *panel = [NSSavePanel savePanel];
1332         // The delegate will be notified when the panel is expanded at which
1333         // time we may hide/show the "show hidden files" button (this button is
1334         // always visible for the open panel since it is always expanded).
1335         [panel setDelegate:self];
1336         if ([panel isExpanded])
1337             [panel setAccessoryView:showHiddenFilesView()];
1339         [panel beginSheetForDirectory:dir file:nil
1340                 modalForWindow:[windowController window]
1341                  modalDelegate:self
1342                 didEndSelector:@selector(savePanelDidEnd:code:context:)
1343                    contextInfo:NULL];
1344     } else {
1345         NSOpenPanel *panel = [NSOpenPanel openPanel];
1346         [panel setAllowsMultipleSelection:NO];
1347         [panel setAccessoryView:showHiddenFilesView()];
1349         [panel beginSheetForDirectory:dir file:nil types:nil
1350                 modalForWindow:[windowController window]
1351                  modalDelegate:self
1352                 didEndSelector:@selector(savePanelDidEnd:code:context:)
1353                    contextInfo:NULL];
1354     }
1357 - (void)handleShowDialog:(NSDictionary *)attr
1359     if (!isInitialized) return;
1361     NSArray *buttonTitles = [attr objectForKey:@"buttonTitles"];
1362     if (!(buttonTitles && [buttonTitles count])) return;
1364     int style = [[attr objectForKey:@"alertStyle"] intValue];
1365     NSString *message = [attr objectForKey:@"messageText"];
1366     NSString *text = [attr objectForKey:@"informativeText"];
1367     NSString *textFieldString = [attr objectForKey:@"textFieldString"];
1368     MMAlert *alert = [[MMAlert alloc] init];
1370     // NOTE! This has to be done before setting the informative text.
1371     if (textFieldString)
1372         [alert setTextFieldString:textFieldString];
1374     [alert setAlertStyle:style];
1376     if (message) {
1377         [alert setMessageText:message];
1378     } else {
1379         // If no message text is specified 'Alert' is used, which we don't
1380         // want, so set an empty string as message text.
1381         [alert setMessageText:@""];
1382     }
1384     if (text) {
1385         [alert setInformativeText:text];
1386     } else if (textFieldString) {
1387         // Make sure there is always room for the input text field.
1388         [alert setInformativeText:@""];
1389     }
1391     unsigned i, count = [buttonTitles count];
1392     for (i = 0; i < count; ++i) {
1393         NSString *title = [buttonTitles objectAtIndex:i];
1394         // NOTE: The title of the button may contain the character '&' to
1395         // indicate that the following letter should be the key equivalent
1396         // associated with the button.  Extract this letter and lowercase it.
1397         NSString *keyEquivalent = nil;
1398         NSRange hotkeyRange = [title rangeOfString:@"&"];
1399         if (NSNotFound != hotkeyRange.location) {
1400             if ([title length] > NSMaxRange(hotkeyRange)) {
1401                 NSRange keyEquivRange = NSMakeRange(hotkeyRange.location+1, 1);
1402                 keyEquivalent = [[title substringWithRange:keyEquivRange]
1403                     lowercaseString];
1404             }
1406             NSMutableString *string = [NSMutableString stringWithString:title];
1407             [string deleteCharactersInRange:hotkeyRange];
1408             title = string;
1409         }
1411         [alert addButtonWithTitle:title];
1413         // Set key equivalent for the button, but only if NSAlert hasn't
1414         // already done so.  (Check the documentation for
1415         // - [NSAlert addButtonWithTitle:] to see what key equivalents are
1416         // automatically assigned.)
1417         NSButton *btn = [[alert buttons] lastObject];
1418         if ([[btn keyEquivalent] length] == 0 && keyEquivalent) {
1419             [btn setKeyEquivalent:keyEquivalent];
1420         }
1421     }
1423     [alert beginSheetModalForWindow:[windowController window]
1424                       modalDelegate:self
1425                      didEndSelector:@selector(alertDidEnd:code:context:)
1426                         contextInfo:NULL];
1428     [alert release];
1432 @end // MMVimController (Private)
1437 @implementation MMAlert
1439 - (void)dealloc
1441     ASLogDebug(@"");
1443     [textField release];  textField = nil;
1444     [super dealloc];
1447 - (void)setTextFieldString:(NSString *)textFieldString
1449     [textField release];
1450     textField = [[NSTextField alloc] init];
1451     [textField setStringValue:textFieldString];
1454 - (NSTextField *)textField
1456     return textField;
1459 - (void)setInformativeText:(NSString *)text
1461     if (textField) {
1462         // HACK! Add some space for the text field.
1463         [super setInformativeText:[text stringByAppendingString:@"\n\n\n"]];
1464     } else {
1465         [super setInformativeText:text];
1466     }
1469 - (void)beginSheetModalForWindow:(NSWindow *)window
1470                    modalDelegate:(id)delegate
1471                   didEndSelector:(SEL)didEndSelector
1472                      contextInfo:(void *)contextInfo
1474     [super beginSheetModalForWindow:window
1475                       modalDelegate:delegate
1476                      didEndSelector:didEndSelector
1477                         contextInfo:contextInfo];
1479     // HACK! Place the input text field at the bottom of the informative text
1480     // (which has been made a bit larger by adding newline characters).
1481     NSView *contentView = [[self window] contentView];
1482     NSRect rect = [contentView frame];
1483     rect.origin.y = rect.size.height;
1485     NSArray *subviews = [contentView subviews];
1486     unsigned i, count = [subviews count];
1487     for (i = 0; i < count; ++i) {
1488         NSView *view = [subviews objectAtIndex:i];
1489         if ([view isKindOfClass:[NSTextField class]]
1490                 && [view frame].origin.y < rect.origin.y) {
1491             // NOTE: The informative text field is the lowest NSTextField in
1492             // the alert dialog.
1493             rect = [view frame];
1494         }
1495     }
1497     rect.size.height = MMAlertTextFieldHeight;
1498     [textField setFrame:rect];
1499     [contentView addSubview:textField];
1500     [textField becomeFirstResponder];
1503 @end // MMAlert
1508     static BOOL
1509 isUnsafeMessage(int msgid)
1511     // Messages that may release Cocoa objects must be added to this list.  For
1512     // example, UpdateTabBarMsgID may delete NSTabViewItem objects so it goes
1513     // on this list.
1514     static int unsafeMessages[] = { // REASON MESSAGE IS ON THIS LIST:
1515         //OpenWindowMsgID,            // Changes lots of state
1516         UpdateTabBarMsgID,          // May delete NSTabViewItem
1517         RemoveMenuItemMsgID,        // Deletes NSMenuItem
1518         DestroyScrollbarMsgID,      // Deletes NSScroller
1519         ExecuteActionMsgID,         // Impossible to predict
1520         ShowPopupMenuMsgID,         // Enters modal loop
1521         ActivateMsgID,              // ?
1522         EnterFullscreenMsgID,       // Modifies delegate of window controller
1523         LeaveFullscreenMsgID,       // Modifies delegate of window controller
1524         CloseWindowMsgID,           // See note below
1525         BrowseForFileMsgID,         // Enters modal loop
1526         ShowDialogMsgID,            // Enters modal loop
1527     };
1529     // NOTE about CloseWindowMsgID: If this arrives at the same time as say
1530     // ExecuteActionMsgID, then the "execute" message will be lost due to it
1531     // being queued and handled after the "close" message has caused the
1532     // controller to cleanup...UNLESS we add CloseWindowMsgID to the list of
1533     // unsafe messages.  This is the _only_ reason it is on this list (since
1534     // all that happens in response to it is that we schedule another message
1535     // for later handling).
1537     int i, count = sizeof(unsafeMessages)/sizeof(unsafeMessages[0]);
1538     for (i = 0; i < count; ++i)
1539         if (msgid == unsafeMessages[i])
1540             return YES;
1542     return NO;