Add support for :winpos
[MacVim.git] / src / MacVim / MMVimController.m
blobf114bae06cf2f81f9dec8e685054a0710a231ffe
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     } else if (SetWindowPositionMsgID == msgid) {
828         const void *bytes = [data bytes];
829         int x = *((int*)bytes);  bytes += sizeof(int);
830         int y = *((int*)bytes);  bytes += sizeof(int);
832         [windowController setTopLeft:NSMakePoint(x,y)];
833     // IMPORTANT: When adding a new message, make sure to update
834     // isUnsafeMessage() if necessary!
835     } else {
836         ASLogWarn(@"Unknown message received (msgid=%d)", msgid);
837     }
840 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
841                 context:(void *)context
843     NSString *path = (code == NSOKButton) ? [panel filename] : nil;
844     ASLogDebug(@"Open/save panel path=%@", path);
846     // NOTE!  This causes the sheet animation to run its course BEFORE the rest
847     // of this function is executed.  If we do not wait for the sheet to
848     // disappear before continuing it can happen that the controller is
849     // released from under us (i.e. we'll crash and burn) because this
850     // animation is otherwise performed in the default run loop mode!
851     [panel orderOut:self];
853     // NOTE! setDialogReturn: is a synchronous call so set a proper timeout to
854     // avoid waiting forever for it to finish.  We make this a synchronous call
855     // so that we can be fairly certain that Vim doesn't think the dialog box
856     // is still showing when MacVim has in fact already dismissed it.
857     NSConnection *conn = [backendProxy connectionForProxy];
858     NSTimeInterval oldTimeout = [conn requestTimeout];
859     [conn setRequestTimeout:MMSetDialogReturnTimeout];
861     @try {
862         [backendProxy setDialogReturn:path];
864         // Add file to the "Recent Files" menu (this ensures that files that
865         // are opened/saved from a :browse command are added to this menu).
866         if (path)
867             [[NSDocumentController sharedDocumentController]
868                     noteNewRecentFilePath:path];
869     }
870     @catch (NSException *ex) {
871         ASLogDebug(@"Exception: pid=%d id=%d reason=%@", pid, identifier, ex);
872     }
873     @finally {
874         [conn setRequestTimeout:oldTimeout];
875     }
878 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context
880     NSArray *ret = nil;
882     code = code - NSAlertFirstButtonReturn + 1;
884     if ([alert isKindOfClass:[MMAlert class]] && [alert textField]) {
885         ret = [NSArray arrayWithObjects:[NSNumber numberWithInt:code],
886             [[alert textField] stringValue], nil];
887     } else {
888         ret = [NSArray arrayWithObject:[NSNumber numberWithInt:code]];
889     }
891     ASLogDebug(@"Alert return=%@", ret);
893     // NOTE!  This causes the sheet animation to run its course BEFORE the rest
894     // of this function is executed.  If we do not wait for the sheet to
895     // disappear before continuing it can happen that the controller is
896     // released from under us (i.e. we'll crash and burn) because this
897     // animation is otherwise performed in the default run loop mode!
898     [[alert window] orderOut:self];
900     @try {
901         [backendProxy setDialogReturn:ret];
902     }
903     @catch (NSException *ex) {
904         ASLogDebug(@"setDialogReturn: failed: pid=%d id=%d reason=%@",
905                 pid, identifier, ex);
906     }
909 - (NSMenuItem *)menuItemForDescriptor:(NSArray *)desc
911     if (!(desc && [desc count] > 0)) return nil;
913     NSString *rootName = [desc objectAtIndex:0];
914     NSArray *rootItems = [rootName hasPrefix:@"PopUp"] ? popupMenuItems
915                                                        : [mainMenu itemArray];
917     NSMenuItem *item = nil;
918     int i, count = [rootItems count];
919     for (i = 0; i < count; ++i) {
920         item = [rootItems objectAtIndex:i];
921         if ([[item title] isEqual:rootName])
922             break;
923     }
925     if (i == count) return nil;
927     count = [desc count];
928     for (i = 1; i < count; ++i) {
929         item = [[item submenu] itemWithTitle:[desc objectAtIndex:i]];
930         if (!item) return nil;
931     }
933     return item;
936 - (NSMenu *)parentMenuForDescriptor:(NSArray *)desc
938     if (!(desc && [desc count] > 0)) return nil;
940     NSString *rootName = [desc objectAtIndex:0];
941     NSArray *rootItems = [rootName hasPrefix:@"PopUp"] ? popupMenuItems
942                                                        : [mainMenu itemArray];
944     NSMenu *menu = nil;
945     int i, count = [rootItems count];
946     for (i = 0; i < count; ++i) {
947         NSMenuItem *item = [rootItems objectAtIndex:i];
948         if ([[item title] isEqual:rootName]) {
949             menu = [item submenu];
950             break;
951         }
952     }
954     if (!menu) return nil;
956     count = [desc count] - 1;
957     for (i = 1; i < count; ++i) {
958         NSMenuItem *item = [menu itemWithTitle:[desc objectAtIndex:i]];
959         menu = [item submenu];
960         if (!menu) return nil;
961     }
963     return menu;
966 - (NSMenu *)topLevelMenuForTitle:(NSString *)title
968     // Search only the top-level menus.
970     unsigned i, count = [popupMenuItems count];
971     for (i = 0; i < count; ++i) {
972         NSMenuItem *item = [popupMenuItems objectAtIndex:i];
973         if ([title isEqual:[item title]])
974             return [item submenu];
975     }
977     count = [mainMenu numberOfItems];
978     for (i = 0; i < count; ++i) {
979         NSMenuItem *item = [mainMenu itemAtIndex:i];
980         if ([title isEqual:[item title]])
981             return [item submenu];
982     }
984     return nil;
987 - (void)addMenuWithDescriptor:(NSArray *)desc atIndex:(int)idx
989     if (!(desc && [desc count] > 0 && idx >= 0)) return;
991     NSString *rootName = [desc objectAtIndex:0];
992     if ([rootName isEqual:@"ToolBar"]) {
993         // The toolbar only has one menu, we take this as a hint to create a
994         // toolbar, then we return.
995         if (!toolbar) {
996             // NOTE! Each toolbar must have a unique identifier, else each
997             // window will have the same toolbar.
998             NSString *ident = [NSString stringWithFormat:@"%d", identifier];
999             toolbar = [[NSToolbar alloc] initWithIdentifier:ident];
1001             [toolbar setShowsBaselineSeparator:NO];
1002             [toolbar setDelegate:self];
1003             [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
1004             [toolbar setSizeMode:NSToolbarSizeModeSmall];
1006             [windowController setToolbar:toolbar];
1007         }
1009         return;
1010     }
1012     // This is either a main menu item or a popup menu item.
1013     NSString *title = [desc lastObject];
1014     NSMenuItem *item = [[NSMenuItem alloc] init];
1015     NSMenu *menu = [[NSMenu alloc] initWithTitle:title];
1017     [item setTitle:title];
1018     [item setSubmenu:menu];
1020     NSMenu *parent = [self parentMenuForDescriptor:desc];
1021     if (!parent && [rootName hasPrefix:@"PopUp"]) {
1022         if ([popupMenuItems count] <= idx) {
1023             [popupMenuItems addObject:item];
1024         } else {
1025             [popupMenuItems insertObject:item atIndex:idx];
1026         }
1027     } else {
1028         // If descriptor has no parent and its not a popup (or toolbar) menu,
1029         // then it must belong to main menu.
1030         if (!parent) parent = mainMenu;
1032         if ([parent numberOfItems] <= idx) {
1033             [parent addItem:item];
1034         } else {
1035             [parent insertItem:item atIndex:idx];
1036         }
1037     }
1039     [item release];
1040     [menu release];
1043 - (void)addMenuItemWithDescriptor:(NSArray *)desc
1044                           atIndex:(int)idx
1045                               tip:(NSString *)tip
1046                              icon:(NSString *)icon
1047                     keyEquivalent:(NSString *)keyEquivalent
1048                      modifierMask:(int)modifierMask
1049                            action:(NSString *)action
1050                       isAlternate:(BOOL)isAlternate
1052     if (!(desc && [desc count] > 1 && idx >= 0)) return;
1054     NSString *title = [desc lastObject];
1055     NSString *rootName = [desc objectAtIndex:0];
1057     if ([rootName isEqual:@"ToolBar"]) {
1058         if (toolbar && [desc count] == 2)
1059             [self addToolbarItemWithLabel:title tip:tip icon:icon atIndex:idx];
1060         return;
1061     }
1063     NSMenu *parent = [self parentMenuForDescriptor:desc];
1064     if (!parent) {
1065         ASLogWarn(@"Menu item '%@' has no parent",
1066                   [desc componentsJoinedByString:@"->"]);
1067         return;
1068     }
1070     NSMenuItem *item = nil;
1071     if (0 == [title length]
1072             || ([title hasPrefix:@"-"] && [title hasSuffix:@"-"])) {
1073         item = [NSMenuItem separatorItem];
1074         [item setTitle:title];
1075     } else {
1076         item = [[[NSMenuItem alloc] init] autorelease];
1077         [item setTitle:title];
1079         // Note: It is possible to set the action to a message that "doesn't
1080         // exist" without problems.  We take advantage of this when adding
1081         // "dummy items" e.g. when dealing with the "Recent Files" menu (in
1082         // which case a recentFilesDummy: action is set, although it is never
1083         // used).
1084         if ([action length] > 0)
1085             [item setAction:NSSelectorFromString(action)];
1086         else
1087             [item setAction:@selector(vimMenuItemAction:)];
1088         if ([tip length] > 0) [item setToolTip:tip];
1089         if ([keyEquivalent length] > 0) {
1090             [item setKeyEquivalent:keyEquivalent];
1091             [item setKeyEquivalentModifierMask:modifierMask];
1092         }
1093         [item setAlternate:isAlternate];
1095         // The tag is used to indicate whether Vim thinks a menu item should be
1096         // enabled or disabled.  By default Vim thinks menu items are enabled.
1097         [item setTag:1];
1098     }
1100     if ([parent numberOfItems] <= idx) {
1101         [parent addItem:item];
1102     } else {
1103         [parent insertItem:item atIndex:idx];
1104     }
1107 - (void)removeMenuItemWithDescriptor:(NSArray *)desc
1109     if (!(desc && [desc count] > 0)) return;
1111     NSString *title = [desc lastObject];
1112     NSString *rootName = [desc objectAtIndex:0];
1113     if ([rootName isEqual:@"ToolBar"]) {
1114         if (toolbar) {
1115             // Only remove toolbar items, never actually remove the toolbar
1116             // itself or strange things may happen.
1117             if ([desc count] == 2) {
1118                 NSUInteger idx = [toolbar indexOfItemWithItemIdentifier:title];
1119                 if (idx != NSNotFound)
1120                     [toolbar removeItemAtIndex:idx];
1121             }
1122         }
1123         return;
1124     }
1126     NSMenuItem *item = [self menuItemForDescriptor:desc];
1127     if (!item) {
1128         ASLogWarn(@"Failed to remove menu item, descriptor not found: %@",
1129                   [desc componentsJoinedByString:@"->"]);
1130         return;
1131     }
1133     [item retain];
1135     if ([item menu] == [NSApp mainMenu] || ![item menu]) {
1136         // NOTE: To be on the safe side we try to remove the item from
1137         // both arrays (it is ok to call removeObject: even if an array
1138         // does not contain the object to remove).
1139         [popupMenuItems removeObject:item];
1140     }
1142     if ([item menu])
1143         [[item menu] removeItem:item];
1145     [item release];
1148 - (void)enableMenuItemWithDescriptor:(NSArray *)desc state:(BOOL)on
1150     if (!(desc && [desc count] > 0)) return;
1152     NSString *rootName = [desc objectAtIndex:0];
1153     if ([rootName isEqual:@"ToolBar"]) {
1154         if (toolbar && [desc count] == 2) {
1155             NSString *title = [desc lastObject];
1156             [[toolbar itemWithItemIdentifier:title] setEnabled:on];
1157         }
1158     } else {
1159         // Use tag to set whether item is enabled or disabled instead of
1160         // calling setEnabled:.  This way the menus can autoenable themselves
1161         // but at the same time Vim can set if a menu is enabled whenever it
1162         // wants to.
1163         [[self menuItemForDescriptor:desc] setTag:on];
1164     }
1167 - (void)addToolbarItemToDictionaryWithLabel:(NSString *)title
1168                                     toolTip:(NSString *)tip
1169                                        icon:(NSString *)icon
1171     // If the item corresponds to a separator then do nothing, since it is
1172     // already defined by Cocoa.
1173     if (!title || [title isEqual:NSToolbarSeparatorItemIdentifier]
1174                || [title isEqual:NSToolbarSpaceItemIdentifier]
1175                || [title isEqual:NSToolbarFlexibleSpaceItemIdentifier])
1176         return;
1178     NSToolbarItem *item = [[NSToolbarItem alloc] initWithItemIdentifier:title];
1179     [item setLabel:title];
1180     [item setToolTip:tip];
1181     [item setAction:@selector(vimToolbarItemAction:)];
1182     [item setAutovalidates:NO];
1184     NSImage *img = [NSImage imageNamed:icon];
1185     if (!img) {
1186         img = [[[NSImage alloc] initByReferencingFile:icon] autorelease];
1187         if (!(img && [img isValid]))
1188             img = nil;
1189     }
1190     if (!img) {
1191         ASLogNotice(@"Could not find image with name '%@' to use as toolbar"
1192             " image for identifier '%@';"
1193             " using default toolbar icon '%@' instead.",
1194             icon, title, MMDefaultToolbarImageName);
1196         img = [NSImage imageNamed:MMDefaultToolbarImageName];
1197     }
1199     [item setImage:img];
1201     [toolbarItemDict setObject:item forKey:title];
1203     [item release];
1206 - (void)addToolbarItemWithLabel:(NSString *)label
1207                             tip:(NSString *)tip
1208                            icon:(NSString *)icon
1209                         atIndex:(int)idx
1211     if (!toolbar) return;
1213     // Check for separator items.
1214     if (!label) {
1215         label = NSToolbarSeparatorItemIdentifier;
1216     } else if ([label length] >= 2 && [label hasPrefix:@"-"]
1217                                    && [label hasSuffix:@"-"]) {
1218         // The label begins and ends with '-'; decided which kind of separator
1219         // item it is by looking at the prefix.
1220         if ([label hasPrefix:@"-space"]) {
1221             label = NSToolbarSpaceItemIdentifier;
1222         } else if ([label hasPrefix:@"-flexspace"]) {
1223             label = NSToolbarFlexibleSpaceItemIdentifier;
1224         } else {
1225             label = NSToolbarSeparatorItemIdentifier;
1226         }
1227     }
1229     [self addToolbarItemToDictionaryWithLabel:label toolTip:tip icon:icon];
1231     int maxIdx = [[toolbar items] count];
1232     if (maxIdx < idx) idx = maxIdx;
1234     [toolbar insertItemWithItemIdentifier:label atIndex:idx];
1237 - (void)popupMenuWithDescriptor:(NSArray *)desc
1238                           atRow:(NSNumber *)row
1239                          column:(NSNumber *)col
1241     NSMenu *menu = [[self menuItemForDescriptor:desc] submenu];
1242     if (!menu) return;
1244     id textView = [[windowController vimView] textView];
1245     NSPoint pt;
1246     if (row && col) {
1247         // TODO: Let textView convert (row,col) to NSPoint.
1248         int r = [row intValue];
1249         int c = [col intValue];
1250         NSSize cellSize = [textView cellSize];
1251         pt = NSMakePoint((c+1)*cellSize.width, (r+1)*cellSize.height);
1252         pt = [textView convertPoint:pt toView:nil];
1253     } else {
1254         pt = [[windowController window] mouseLocationOutsideOfEventStream];
1255     }
1257     NSEvent *event = [NSEvent mouseEventWithType:NSRightMouseDown
1258                            location:pt
1259                       modifierFlags:0
1260                           timestamp:0
1261                        windowNumber:[[windowController window] windowNumber]
1262                             context:nil
1263                         eventNumber:0
1264                          clickCount:0
1265                            pressure:1.0];
1267     [NSMenu popUpContextMenu:menu withEvent:event forView:textView];
1270 - (void)popupMenuWithAttributes:(NSDictionary *)attrs
1272     if (!attrs) return;
1274     [self popupMenuWithDescriptor:[attrs objectForKey:@"descriptor"]
1275                             atRow:[attrs objectForKey:@"row"]
1276                            column:[attrs objectForKey:@"column"]];
1279 - (void)connectionDidDie:(NSNotification *)notification
1281     ASLogDebug(@"%@", notification);
1282     [self scheduleClose];
1285 - (void)scheduleClose
1287     ASLogDebug(@"pid=%d id=%d", pid, identifier);
1289     // NOTE!  This message can arrive at pretty much anytime, e.g. while
1290     // the run loop is the 'event tracking' mode.  This means that Cocoa may
1291     // well be in the middle of processing some message while this message is
1292     // received.  If we were to remove the vim controller straight away we may
1293     // free objects that Cocoa is currently using (e.g. view objects).  The
1294     // following call ensures that the vim controller is not released until the
1295     // run loop is back in the 'default' mode.
1296     // Also, since the app may be multithreaded (e.g. as a result of showing
1297     // the open panel) we have to ensure this call happens on the main thread,
1298     // else there is a race condition that may lead to a crash.
1299     [[MMAppController sharedInstance]
1300             performSelectorOnMainThread:@selector(removeVimController:)
1301                              withObject:self
1302                           waitUntilDone:NO
1303                                   modes:[NSArray arrayWithObject:
1304                                          NSDefaultRunLoopMode]];
1307 // NSSavePanel delegate
1308 - (void)panel:(id)sender willExpand:(BOOL)expanding
1310     // Show or hide the "show hidden files" button
1311     if (expanding) {
1312         [sender setAccessoryView:showHiddenFilesView()];
1313     } else {
1314         [sender setShowsHiddenFiles:NO];
1315         [sender setAccessoryView:nil];
1316     }
1319 - (void)handleBrowseForFile:(NSDictionary *)attr
1321     if (!isInitialized) return;
1323     NSString *dir = [attr objectForKey:@"dir"];
1324     BOOL saving = [[attr objectForKey:@"saving"] boolValue];
1326     if (!dir) {
1327         // 'dir == nil' means: set dir to the pwd of the Vim process, or let
1328         // open dialog decide (depending on the below user default).
1329         BOOL trackPwd = [[NSUserDefaults standardUserDefaults]
1330                 boolForKey:MMDialogsTrackPwdKey];
1331         if (trackPwd)
1332             dir = [vimState objectForKey:@"pwd"];
1333     }
1335     if (saving) {
1336         NSSavePanel *panel = [NSSavePanel savePanel];
1338         // The delegate will be notified when the panel is expanded at which
1339         // time we may hide/show the "show hidden files" button (this button is
1340         // always visible for the open panel since it is always expanded).
1341         [panel setDelegate:self];
1342         if ([panel isExpanded])
1343             [panel setAccessoryView:showHiddenFilesView()];
1345         [panel beginSheetForDirectory:dir file:nil
1346                 modalForWindow:[windowController window]
1347                  modalDelegate:self
1348                 didEndSelector:@selector(savePanelDidEnd:code:context:)
1349                    contextInfo:NULL];
1350     } else {
1351         NSOpenPanel *panel = [NSOpenPanel openPanel];
1352         [panel setAllowsMultipleSelection:NO];
1353         [panel setAccessoryView:showHiddenFilesView()];
1355         [panel beginSheetForDirectory:dir file:nil types:nil
1356                 modalForWindow:[windowController window]
1357                  modalDelegate:self
1358                 didEndSelector:@selector(savePanelDidEnd:code:context:)
1359                    contextInfo:NULL];
1360     }
1363 - (void)handleShowDialog:(NSDictionary *)attr
1365     if (!isInitialized) return;
1367     NSArray *buttonTitles = [attr objectForKey:@"buttonTitles"];
1368     if (!(buttonTitles && [buttonTitles count])) return;
1370     int style = [[attr objectForKey:@"alertStyle"] intValue];
1371     NSString *message = [attr objectForKey:@"messageText"];
1372     NSString *text = [attr objectForKey:@"informativeText"];
1373     NSString *textFieldString = [attr objectForKey:@"textFieldString"];
1374     MMAlert *alert = [[MMAlert alloc] init];
1376     // NOTE! This has to be done before setting the informative text.
1377     if (textFieldString)
1378         [alert setTextFieldString:textFieldString];
1380     [alert setAlertStyle:style];
1382     if (message) {
1383         [alert setMessageText:message];
1384     } else {
1385         // If no message text is specified 'Alert' is used, which we don't
1386         // want, so set an empty string as message text.
1387         [alert setMessageText:@""];
1388     }
1390     if (text) {
1391         [alert setInformativeText:text];
1392     } else if (textFieldString) {
1393         // Make sure there is always room for the input text field.
1394         [alert setInformativeText:@""];
1395     }
1397     unsigned i, count = [buttonTitles count];
1398     for (i = 0; i < count; ++i) {
1399         NSString *title = [buttonTitles objectAtIndex:i];
1400         // NOTE: The title of the button may contain the character '&' to
1401         // indicate that the following letter should be the key equivalent
1402         // associated with the button.  Extract this letter and lowercase it.
1403         NSString *keyEquivalent = nil;
1404         NSRange hotkeyRange = [title rangeOfString:@"&"];
1405         if (NSNotFound != hotkeyRange.location) {
1406             if ([title length] > NSMaxRange(hotkeyRange)) {
1407                 NSRange keyEquivRange = NSMakeRange(hotkeyRange.location+1, 1);
1408                 keyEquivalent = [[title substringWithRange:keyEquivRange]
1409                     lowercaseString];
1410             }
1412             NSMutableString *string = [NSMutableString stringWithString:title];
1413             [string deleteCharactersInRange:hotkeyRange];
1414             title = string;
1415         }
1417         [alert addButtonWithTitle:title];
1419         // Set key equivalent for the button, but only if NSAlert hasn't
1420         // already done so.  (Check the documentation for
1421         // - [NSAlert addButtonWithTitle:] to see what key equivalents are
1422         // automatically assigned.)
1423         NSButton *btn = [[alert buttons] lastObject];
1424         if ([[btn keyEquivalent] length] == 0 && keyEquivalent) {
1425             [btn setKeyEquivalent:keyEquivalent];
1426         }
1427     }
1429     [alert beginSheetModalForWindow:[windowController window]
1430                       modalDelegate:self
1431                      didEndSelector:@selector(alertDidEnd:code:context:)
1432                         contextInfo:NULL];
1434     [alert release];
1438 @end // MMVimController (Private)
1443 @implementation MMAlert
1445 - (void)dealloc
1447     ASLogDebug(@"");
1449     [textField release];  textField = nil;
1450     [super dealloc];
1453 - (void)setTextFieldString:(NSString *)textFieldString
1455     [textField release];
1456     textField = [[NSTextField alloc] init];
1457     [textField setStringValue:textFieldString];
1460 - (NSTextField *)textField
1462     return textField;
1465 - (void)setInformativeText:(NSString *)text
1467     if (textField) {
1468         // HACK! Add some space for the text field.
1469         [super setInformativeText:[text stringByAppendingString:@"\n\n\n"]];
1470     } else {
1471         [super setInformativeText:text];
1472     }
1475 - (void)beginSheetModalForWindow:(NSWindow *)window
1476                    modalDelegate:(id)delegate
1477                   didEndSelector:(SEL)didEndSelector
1478                      contextInfo:(void *)contextInfo
1480     [super beginSheetModalForWindow:window
1481                       modalDelegate:delegate
1482                      didEndSelector:didEndSelector
1483                         contextInfo:contextInfo];
1485     // HACK! Place the input text field at the bottom of the informative text
1486     // (which has been made a bit larger by adding newline characters).
1487     NSView *contentView = [[self window] contentView];
1488     NSRect rect = [contentView frame];
1489     rect.origin.y = rect.size.height;
1491     NSArray *subviews = [contentView subviews];
1492     unsigned i, count = [subviews count];
1493     for (i = 0; i < count; ++i) {
1494         NSView *view = [subviews objectAtIndex:i];
1495         if ([view isKindOfClass:[NSTextField class]]
1496                 && [view frame].origin.y < rect.origin.y) {
1497             // NOTE: The informative text field is the lowest NSTextField in
1498             // the alert dialog.
1499             rect = [view frame];
1500         }
1501     }
1503     rect.size.height = MMAlertTextFieldHeight;
1504     [textField setFrame:rect];
1505     [contentView addSubview:textField];
1506     [textField becomeFirstResponder];
1509 @end // MMAlert
1514     static BOOL
1515 isUnsafeMessage(int msgid)
1517     // Messages that may release Cocoa objects must be added to this list.  For
1518     // example, UpdateTabBarMsgID may delete NSTabViewItem objects so it goes
1519     // on this list.
1520     static int unsafeMessages[] = { // REASON MESSAGE IS ON THIS LIST:
1521         //OpenWindowMsgID,            // Changes lots of state
1522         UpdateTabBarMsgID,          // May delete NSTabViewItem
1523         RemoveMenuItemMsgID,        // Deletes NSMenuItem
1524         DestroyScrollbarMsgID,      // Deletes NSScroller
1525         ExecuteActionMsgID,         // Impossible to predict
1526         ShowPopupMenuMsgID,         // Enters modal loop
1527         ActivateMsgID,              // ?
1528         EnterFullscreenMsgID,       // Modifies delegate of window controller
1529         LeaveFullscreenMsgID,       // Modifies delegate of window controller
1530         CloseWindowMsgID,           // See note below
1531         BrowseForFileMsgID,         // Enters modal loop
1532         ShowDialogMsgID,            // Enters modal loop
1533     };
1535     // NOTE about CloseWindowMsgID: If this arrives at the same time as say
1536     // ExecuteActionMsgID, then the "execute" message will be lost due to it
1537     // being queued and handled after the "close" message has caused the
1538     // controller to cleanup...UNLESS we add CloseWindowMsgID to the list of
1539     // unsafe messages.  This is the _only_ reason it is on this list (since
1540     // all that happens in response to it is that we schedule another message
1541     // for later handling).
1543     int i, count = sizeof(unsafeMessages)/sizeof(unsafeMessages[0]);
1544     for (i = 0; i < count; ++i)
1545         if (msgid == unsafeMessages[i])
1546             return YES;
1548     return NO;