Prepare for 64 bit
[MacVim.git] / src / MacVim / MMVimController.m
blob8c90550ef45d1c1a51a2a311fb4f3df61a0ae7b5
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]];
328     // HACK! Fool findUnusedEditor into thinking that this controller is not
329     // unused anymore, in case it is called before the arguments have reached
330     // the Vim process.  This should be a "safe" hack since the next time the
331     // Vim process flushes its output queue the state will be updated again (at
332     // which time the "unusedEditor" state will have been properly set).
333     NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:
334             vimState];
335     [dict setObject:[NSNumber numberWithBool:NO] forKey:@"unusedEditor"];
336     [vimState release];
337     vimState = [dict copy];
340 - (void)sendMessage:(int)msgid data:(NSData *)data
342     ASLogDebug(@"msg=%s (isInitialized=%d)",
343                MessageStrings[msgid], isInitialized);
345     if (!isInitialized) return;
347     @try {
348         [backendProxy processInput:msgid data:data];
349     }
350     @catch (NSException *ex) {
351         ASLogNotice(@"processInput:data: failed: pid=%d id=%d msg=%s reason=%@",
352                 pid, identifier, MessageStrings[msgid], ex);
353     }
356 - (BOOL)sendMessageNow:(int)msgid data:(NSData *)data
357                timeout:(NSTimeInterval)timeout
359     // Send a message with a timeout.  USE WITH EXTREME CAUTION!  Sending
360     // messages in rapid succession with a timeout may cause MacVim to beach
361     // ball forever.  In almost all circumstances sendMessage:data: should be
362     // used instead.
364     ASLogDebug(@"msg=%s (isInitialized=%d)",
365                MessageStrings[msgid], isInitialized);
367     if (!isInitialized)
368         return NO;
370     if (timeout < 0) timeout = 0;
372     BOOL sendOk = YES;
373     NSConnection *conn = [backendProxy connectionForProxy];
374     NSTimeInterval oldTimeout = [conn requestTimeout];
376     [conn setRequestTimeout:timeout];
378     @try {
379         [backendProxy processInput:msgid data:data];
380     }
381     @catch (NSException *ex) {
382         sendOk = NO;
383         ASLogNotice(@"processInput:data: failed: pid=%d id=%d msg=%s reason=%@",
384                 pid, identifier, MessageStrings[msgid], ex);
385     }
386     @finally {
387         [conn setRequestTimeout:oldTimeout];
388     }
390     return sendOk;
393 - (void)addVimInput:(NSString *)string
395     ASLogDebug(@"%@", string);
397     // This is a very general method of adding input to the Vim process.  It is
398     // basically the same as calling remote_send() on the process (see
399     // ':h remote_send').
400     if (string) {
401         NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
402         [self sendMessage:AddInputMsgID data:data];
403     }
406 - (NSString *)evaluateVimExpression:(NSString *)expr
408     NSString *eval = nil;
410     @try {
411         eval = [backendProxy evaluateExpression:expr];
412         ASLogDebug(@"eval(%@)=%@", expr, eval);
413     }
414     @catch (NSException *ex) {
415         ASLogNotice(@"evaluateExpression: failed: pid=%d id=%d reason=%@",
416                 pid, identifier, ex);
417     }
419     return eval;
422 - (id)evaluateVimExpressionCocoa:(NSString *)expr
423                      errorString:(NSString **)errstr
425     id eval = nil;
427     @try {
428         eval = [backendProxy evaluateExpressionCocoa:expr
429                                          errorString:errstr];
430         ASLogDebug(@"eval(%@)=%@", expr, eval);
431     } @catch (NSException *ex) {
432         ASLogNotice(@"evaluateExpressionCocoa: failed: pid=%d id=%d reason=%@",
433                 pid, identifier, ex);
434         *errstr = [ex reason];
435     }
437     return eval;
440 - (id)backendProxy
442     return backendProxy;
445 - (void)cleanup
447     if (!isInitialized) return;
449     // Remove any delayed calls made on this object.
450     [NSObject cancelPreviousPerformRequestsWithTarget:self];
452     isInitialized = NO;
453     [toolbar setDelegate:nil];
454     [[NSNotificationCenter defaultCenter] removeObserver:self];
455     //[[backendProxy connectionForProxy] invalidate];
456     //[windowController close];
457     [windowController cleanup];
460 - (void)processInputQueue:(NSArray *)queue
462     if (!isInitialized) return;
464     // NOTE: This method must not raise any exceptions (see comment in the
465     // calling method).
466     @try {
467         [self doProcessInputQueue:queue];
468         [windowController processInputQueueDidFinish];
469     }
470     @catch (NSException *ex) {
471         ASLogNotice(@"Exception: pid=%d id=%d reason=%@", pid, identifier, ex);
472     }
475 - (NSToolbarItem *)toolbar:(NSToolbar *)theToolbar
476     itemForItemIdentifier:(NSString *)itemId
477     willBeInsertedIntoToolbar:(BOOL)flag
479     NSToolbarItem *item = [toolbarItemDict objectForKey:itemId];
480     if (!item) {
481         ASLogWarn(@"No toolbar item with id '%@'", itemId);
482     }
484     return item;
487 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)theToolbar
489     return nil;
492 - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)theToolbar
494     return nil;
497 @end // MMVimController
501 @implementation MMVimController (Private)
503 - (void)doProcessInputQueue:(NSArray *)queue
505     NSMutableArray *delayQueue = nil;
507     unsigned i, count = [queue count];
508     if (count % 2) {
509         ASLogWarn(@"Uneven number of components (%d) in command queue.  "
510                   "Skipping...", count);
511         return;
512     }
514     for (i = 0; i < count; i += 2) {
515         NSData *value = [queue objectAtIndex:i];
516         NSData *data = [queue objectAtIndex:i+1];
518         int msgid = *((int*)[value bytes]);
520         BOOL inDefaultMode = [[[NSRunLoop currentRunLoop] currentMode]
521                                             isEqual:NSDefaultRunLoopMode];
522         if (!inDefaultMode && isUnsafeMessage(msgid)) {
523             // NOTE: Because we may be listening to DO messages in "event
524             // tracking mode" we have to take extra care when doing things
525             // like releasing view items (and other Cocoa objects).
526             // Messages that may be potentially "unsafe" are delayed until
527             // the run loop is back to default mode at which time they are
528             // safe to call again.
529             //   A problem with this approach is that it is hard to
530             // classify which messages are unsafe.  As a rule of thumb, if
531             // a message may release an object used by the Cocoa framework
532             // (e.g. views) then the message should be considered unsafe.
533             //   Delaying messages may have undesired side-effects since it
534             // means that messages may not be processed in the order Vim
535             // sent them, so beware.
536             if (!delayQueue)
537                 delayQueue = [NSMutableArray array];
539             ASLogDebug(@"Adding unsafe message '%s' to delay queue (mode=%@)",
540                        MessageStrings[msgid],
541                        [[NSRunLoop currentRunLoop] currentMode]);
542             [delayQueue addObject:value];
543             [delayQueue addObject:data];
544         } else {
545             [self handleMessage:msgid data:data];
546         }
547     }
549     if (delayQueue) {
550         ASLogDebug(@"    Flushing delay queue (%d items)",
551                    [delayQueue count]/2);
552         [self performSelector:@selector(processInputQueue:)
553                    withObject:delayQueue
554                    afterDelay:0];
555     }
558 - (void)handleMessage:(int)msgid data:(NSData *)data
560     if (OpenWindowMsgID == msgid) {
561         [windowController openWindow];
563         // If the vim controller is preloading then the window will be
564         // displayed when it is taken off the preload cache.
565         if (!isPreloading)
566             [windowController showWindow];
567     } else if (BatchDrawMsgID == msgid) {
568         [[[windowController vimView] textView] performBatchDrawWithData:data];
569     } else if (SelectTabMsgID == msgid) {
570 #if 0   // NOTE: Tab selection is done inside updateTabsWithData:.
571         const void *bytes = [data bytes];
572         int idx = *((int*)bytes);
573         [windowController selectTabWithIndex:idx];
574 #endif
575     } else if (UpdateTabBarMsgID == msgid) {
576         [windowController updateTabsWithData:data];
577     } else if (ShowTabBarMsgID == msgid) {
578         [windowController showTabBar:YES];
579     } else if (HideTabBarMsgID == msgid) {
580         [windowController showTabBar:NO];
581     } else if (SetTextDimensionsMsgID == msgid || LiveResizeMsgID == msgid ||
582             SetTextDimensionsReplyMsgID == msgid) {
583         const void *bytes = [data bytes];
584         int rows = *((int*)bytes);  bytes += sizeof(int);
585         int cols = *((int*)bytes);  bytes += sizeof(int);
587         [windowController setTextDimensionsWithRows:rows
588                                  columns:cols
589                                   isLive:(LiveResizeMsgID==msgid)
590                                  isReply:(SetTextDimensionsReplyMsgID==msgid)];
591     } else if (SetWindowTitleMsgID == msgid) {
592         const void *bytes = [data bytes];
593         int len = *((int*)bytes);  bytes += sizeof(int);
595         NSString *string = [[NSString alloc] initWithBytes:(void*)bytes
596                 length:len encoding:NSUTF8StringEncoding];
598         // While in live resize the window title displays the dimensions of the
599         // window so don't clobber this with a spurious "set title" message
600         // from Vim.
601         if (![[windowController vimView] inLiveResize])
602             [windowController setTitle:string];
604         [string release];
605     } else if (SetDocumentFilenameMsgID == msgid) {
606         const void *bytes = [data bytes];
607         int len = *((int*)bytes);  bytes += sizeof(int);
609         if (len > 0) {
610             NSString *filename = [[NSString alloc] initWithBytes:(void*)bytes
611                     length:len encoding:NSUTF8StringEncoding];
613             [windowController setDocumentFilename:filename];
615             [filename release];
616         } else {
617             [windowController setDocumentFilename:@""];
618         }
619     } else if (AddMenuMsgID == msgid) {
620         NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
621         [self addMenuWithDescriptor:[attrs objectForKey:@"descriptor"]
622                 atIndex:[[attrs objectForKey:@"index"] intValue]];
623     } else if (AddMenuItemMsgID == msgid) {
624         NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
625         [self addMenuItemWithDescriptor:[attrs objectForKey:@"descriptor"]
626                       atIndex:[[attrs objectForKey:@"index"] intValue]
627                           tip:[attrs objectForKey:@"tip"]
628                          icon:[attrs objectForKey:@"icon"]
629                 keyEquivalent:[attrs objectForKey:@"keyEquivalent"]
630                  modifierMask:[[attrs objectForKey:@"modifierMask"] intValue]
631                        action:[attrs objectForKey:@"action"]
632                   isAlternate:[[attrs objectForKey:@"isAlternate"] boolValue]];
633     } else if (RemoveMenuItemMsgID == msgid) {
634         NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
635         [self removeMenuItemWithDescriptor:[attrs objectForKey:@"descriptor"]];
636     } else if (EnableMenuItemMsgID == msgid) {
637         NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
638         [self enableMenuItemWithDescriptor:[attrs objectForKey:@"descriptor"]
639                 state:[[attrs objectForKey:@"enable"] boolValue]];
640     } else if (ShowToolbarMsgID == msgid) {
641         const void *bytes = [data bytes];
642         int enable = *((int*)bytes);  bytes += sizeof(int);
643         int flags = *((int*)bytes);  bytes += sizeof(int);
645         int mode = NSToolbarDisplayModeDefault;
646         if (flags & ToolbarLabelFlag) {
647             mode = flags & ToolbarIconFlag ? NSToolbarDisplayModeIconAndLabel
648                     : NSToolbarDisplayModeLabelOnly;
649         } else if (flags & ToolbarIconFlag) {
650             mode = NSToolbarDisplayModeIconOnly;
651         }
653         int size = flags & ToolbarSizeRegularFlag ? NSToolbarSizeModeRegular
654                 : NSToolbarSizeModeSmall;
656         [windowController showToolbar:enable size:size mode:mode];
657     } else if (CreateScrollbarMsgID == msgid) {
658         const void *bytes = [data bytes];
659         int32_t ident = *((int32_t*)bytes);  bytes += sizeof(int32_t);
660         int type = *((int*)bytes);  bytes += sizeof(int);
662         [windowController createScrollbarWithIdentifier:ident type:type];
663     } else if (DestroyScrollbarMsgID == msgid) {
664         const void *bytes = [data bytes];
665         int32_t ident = *((int32_t*)bytes);  bytes += sizeof(int32_t);
667         [windowController destroyScrollbarWithIdentifier:ident];
668     } else if (ShowScrollbarMsgID == msgid) {
669         const void *bytes = [data bytes];
670         int32_t ident = *((int32_t*)bytes);  bytes += sizeof(int32_t);
671         int visible = *((int*)bytes);  bytes += sizeof(int);
673         [windowController showScrollbarWithIdentifier:ident state:visible];
674     } else if (SetScrollbarPositionMsgID == msgid) {
675         const void *bytes = [data bytes];
676         int32_t ident = *((int32_t*)bytes);  bytes += sizeof(int32_t);
677         int pos = *((int*)bytes);  bytes += sizeof(int);
678         int len = *((int*)bytes);  bytes += sizeof(int);
680         [windowController setScrollbarPosition:pos length:len
681                                     identifier:ident];
682     } else if (SetScrollbarThumbMsgID == msgid) {
683         const void *bytes = [data bytes];
684         int32_t ident = *((int32_t*)bytes);  bytes += sizeof(int32_t);
685         float val = *((float*)bytes);  bytes += sizeof(float);
686         float prop = *((float*)bytes);  bytes += sizeof(float);
688         [windowController setScrollbarThumbValue:val proportion:prop
689                                       identifier:ident];
690     } else if (SetFontMsgID == msgid) {
691         const void *bytes = [data bytes];
692         float size = *((float*)bytes);  bytes += sizeof(float);
693         int len = *((int*)bytes);  bytes += sizeof(int);
694         NSString *name = [[NSString alloc]
695                 initWithBytes:(void*)bytes length:len
696                      encoding:NSUTF8StringEncoding];
697         NSFont *font = [NSFont fontWithName:name size:size];
698         if (!font) {
699             // This should only happen if the default font was not loaded in
700             // which case we fall back on using the Cocoa default fixed width
701             // font.
702             font = [NSFont userFixedPitchFontOfSize:size];
703         }
705         [windowController setFont:font];
706         [name release];
707     } else if (SetWideFontMsgID == msgid) {
708         const void *bytes = [data bytes];
709         float size = *((float*)bytes);  bytes += sizeof(float);
710         int len = *((int*)bytes);  bytes += sizeof(int);
711         if (len > 0) {
712             NSString *name = [[NSString alloc]
713                     initWithBytes:(void*)bytes length:len
714                          encoding:NSUTF8StringEncoding];
715             NSFont *font = [NSFont fontWithName:name size:size];
716             [windowController setWideFont:font];
718             [name release];
719         } else {
720             [windowController setWideFont:nil];
721         }
722     } else if (SetDefaultColorsMsgID == msgid) {
723         const void *bytes = [data bytes];
724         unsigned bg = *((unsigned*)bytes);  bytes += sizeof(unsigned);
725         unsigned fg = *((unsigned*)bytes);  bytes += sizeof(unsigned);
726         NSColor *back = [NSColor colorWithArgbInt:bg];
727         NSColor *fore = [NSColor colorWithRgbInt:fg];
729         [windowController setDefaultColorsBackground:back foreground:fore];
730     } else if (ExecuteActionMsgID == msgid) {
731         const void *bytes = [data bytes];
732         int len = *((int*)bytes);  bytes += sizeof(int);
733         NSString *actionName = [[NSString alloc]
734                 initWithBytes:(void*)bytes length:len
735                      encoding:NSUTF8StringEncoding];
737         SEL sel = NSSelectorFromString(actionName);
738         [NSApp sendAction:sel to:nil from:self];
740         [actionName release];
741     } else if (ShowPopupMenuMsgID == msgid) {
742         NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
744         // The popup menu enters a modal loop so delay this call so that we
745         // don't block inside processInputQueue:.
746         [self performSelector:@selector(popupMenuWithAttributes:)
747                    withObject:attrs
748                    afterDelay:0];
749     } else if (SetMouseShapeMsgID == msgid) {
750         const void *bytes = [data bytes];
751         int shape = *((int*)bytes);  bytes += sizeof(int);
753         [windowController setMouseShape:shape];
754     } else if (AdjustLinespaceMsgID == msgid) {
755         const void *bytes = [data bytes];
756         int linespace = *((int*)bytes);  bytes += sizeof(int);
758         [windowController adjustLinespace:linespace];
759     } else if (ActivateMsgID == msgid) {
760         [NSApp activateIgnoringOtherApps:YES];
761         [[windowController window] makeKeyAndOrderFront:self];
762     } else if (SetServerNameMsgID == msgid) {
763         NSString *name = [[NSString alloc] initWithData:data
764                                                encoding:NSUTF8StringEncoding];
765         [self setServerName:name];
766         [name release];
767     } else if (EnterFullscreenMsgID == msgid) {
768         const void *bytes = [data bytes];
769         int fuoptions = *((int*)bytes); bytes += sizeof(int);
770         int bg = *((int*)bytes);
771         NSColor *back = [NSColor colorWithArgbInt:bg];
773         [windowController enterFullscreen:fuoptions backgroundColor:back];
774     } else if (LeaveFullscreenMsgID == msgid) {
775         [windowController leaveFullscreen];
776     } else if (BuffersNotModifiedMsgID == msgid) {
777         [windowController setBuffersModified:NO];
778     } else if (BuffersModifiedMsgID == msgid) {
779         [windowController setBuffersModified:YES];
780     } else if (SetPreEditPositionMsgID == msgid) {
781         const int *dim = (const int*)[data bytes];
782         [[[windowController vimView] textView] setPreEditRow:dim[0]
783                                                       column:dim[1]];
784     } else if (EnableAntialiasMsgID == msgid) {
785         [[[windowController vimView] textView] setAntialias:YES];
786     } else if (DisableAntialiasMsgID == msgid) {
787         [[[windowController vimView] textView] setAntialias:NO];
788     } else if (SetVimStateMsgID == msgid) {
789         NSDictionary *dict = [NSDictionary dictionaryWithData:data];
790         if (dict) {
791             [vimState release];
792             vimState = [dict retain];
793         }
794     } else if (CloseWindowMsgID == msgid) {
795         [self scheduleClose];
796     } else if (SetFullscreenColorMsgID == msgid) {
797         const int *bg = (const int*)[data bytes];
798         NSColor *color = [NSColor colorWithRgbInt:*bg];
800         [windowController setFullscreenBackgroundColor:color];
801     } else if (ShowFindReplaceDialogMsgID == msgid) {
802         NSDictionary *dict = [NSDictionary dictionaryWithData:data];
803         if (dict) {
804             [[MMFindReplaceController sharedInstance]
805                 showWithText:[dict objectForKey:@"text"]
806                        flags:[[dict objectForKey:@"flags"] intValue]];
807         }
808     } else if (ActivateKeyScriptMsgID == msgid) {
809         [[[windowController vimView] textView] activateIm:YES];
810     } else if (DeactivateKeyScriptMsgID == msgid) {
811         [[[windowController vimView] textView] activateIm:NO];
812     } else if (EnableImControlMsgID == msgid) {
813         [[[windowController vimView] textView] setImControl:YES];
814     } else if (DisableImControlMsgID == msgid) {
815         [[[windowController vimView] textView] setImControl:NO];
816     } else if (BrowseForFileMsgID == msgid) {
817         NSDictionary *dict = [NSDictionary dictionaryWithData:data];
818         if (dict)
819             [self handleBrowseForFile:dict];
820     } else if (ShowDialogMsgID == msgid) {
821         NSDictionary *dict = [NSDictionary dictionaryWithData:data];
822         if (dict)
823             [self handleShowDialog:dict];
824     // IMPORTANT: When adding a new message, make sure to update
825     // isUnsafeMessage() if necessary!
826     } else {
827         ASLogWarn(@"Unknown message received (msgid=%d)", msgid);
828     }
831 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
832                 context:(void *)context
834     NSString *path = (code == NSOKButton) ? [panel filename] : nil;
835     ASLogDebug(@"Open/save panel path=%@", path);
837     // NOTE!  This causes the sheet animation to run its course BEFORE the rest
838     // of this function is executed.  If we do not wait for the sheet to
839     // disappear before continuing it can happen that the controller is
840     // released from under us (i.e. we'll crash and burn) because this
841     // animation is otherwise performed in the default run loop mode!
842     [panel orderOut:self];
844     // NOTE! setDialogReturn: is a synchronous call so set a proper timeout to
845     // avoid waiting forever for it to finish.  We make this a synchronous call
846     // so that we can be fairly certain that Vim doesn't think the dialog box
847     // is still showing when MacVim has in fact already dismissed it.
848     NSConnection *conn = [backendProxy connectionForProxy];
849     NSTimeInterval oldTimeout = [conn requestTimeout];
850     [conn setRequestTimeout:MMSetDialogReturnTimeout];
852     @try {
853         [backendProxy setDialogReturn:path];
855         // Add file to the "Recent Files" menu (this ensures that files that
856         // are opened/saved from a :browse command are added to this menu).
857         if (path)
858             [[NSDocumentController sharedDocumentController]
859                     noteNewRecentFilePath:path];
860     }
861     @catch (NSException *ex) {
862         ASLogNotice(@"Exception: pid=%d id=%d reason=%@", pid, identifier, ex);
863     }
864     @finally {
865         [conn setRequestTimeout:oldTimeout];
866     }
869 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context
871     NSArray *ret = nil;
873     code = code - NSAlertFirstButtonReturn + 1;
875     if ([alert isKindOfClass:[MMAlert class]] && [alert textField]) {
876         ret = [NSArray arrayWithObjects:[NSNumber numberWithInt:code],
877             [[alert textField] stringValue], nil];
878     } else {
879         ret = [NSArray arrayWithObject:[NSNumber numberWithInt:code]];
880     }
882     ASLogDebug(@"Alert return=%@", ret);
884     // NOTE!  This causes the sheet animation to run its course BEFORE the rest
885     // of this function is executed.  If we do not wait for the sheet to
886     // disappear before continuing it can happen that the controller is
887     // released from under us (i.e. we'll crash and burn) because this
888     // animation is otherwise performed in the default run loop mode!
889     [[alert window] orderOut:self];
891     @try {
892         [backendProxy setDialogReturn:ret];
893     }
894     @catch (NSException *ex) {
895         ASLogNotice(@"setDialogReturn: failed: pid=%d id=%d reason=%@",
896                 pid, identifier, ex);
897     }
900 - (NSMenuItem *)menuItemForDescriptor:(NSArray *)desc
902     if (!(desc && [desc count] > 0)) return nil;
904     NSString *rootName = [desc objectAtIndex:0];
905     NSArray *rootItems = [rootName hasPrefix:@"PopUp"] ? popupMenuItems
906                                                        : [mainMenu itemArray];
908     NSMenuItem *item = nil;
909     int i, count = [rootItems count];
910     for (i = 0; i < count; ++i) {
911         item = [rootItems objectAtIndex:i];
912         if ([[item title] isEqual:rootName])
913             break;
914     }
916     if (i == count) return nil;
918     count = [desc count];
919     for (i = 1; i < count; ++i) {
920         item = [[item submenu] itemWithTitle:[desc objectAtIndex:i]];
921         if (!item) return nil;
922     }
924     return item;
927 - (NSMenu *)parentMenuForDescriptor:(NSArray *)desc
929     if (!(desc && [desc count] > 0)) return nil;
931     NSString *rootName = [desc objectAtIndex:0];
932     NSArray *rootItems = [rootName hasPrefix:@"PopUp"] ? popupMenuItems
933                                                        : [mainMenu itemArray];
935     NSMenu *menu = nil;
936     int i, count = [rootItems count];
937     for (i = 0; i < count; ++i) {
938         NSMenuItem *item = [rootItems objectAtIndex:i];
939         if ([[item title] isEqual:rootName]) {
940             menu = [item submenu];
941             break;
942         }
943     }
945     if (!menu) return nil;
947     count = [desc count] - 1;
948     for (i = 1; i < count; ++i) {
949         NSMenuItem *item = [menu itemWithTitle:[desc objectAtIndex:i]];
950         menu = [item submenu];
951         if (!menu) return nil;
952     }
954     return menu;
957 - (NSMenu *)topLevelMenuForTitle:(NSString *)title
959     // Search only the top-level menus.
961     unsigned i, count = [popupMenuItems count];
962     for (i = 0; i < count; ++i) {
963         NSMenuItem *item = [popupMenuItems objectAtIndex:i];
964         if ([title isEqual:[item title]])
965             return [item submenu];
966     }
968     count = [mainMenu numberOfItems];
969     for (i = 0; i < count; ++i) {
970         NSMenuItem *item = [mainMenu itemAtIndex:i];
971         if ([title isEqual:[item title]])
972             return [item submenu];
973     }
975     return nil;
978 - (void)addMenuWithDescriptor:(NSArray *)desc atIndex:(int)idx
980     if (!(desc && [desc count] > 0 && idx >= 0)) return;
982     NSString *rootName = [desc objectAtIndex:0];
983     if ([rootName isEqual:@"ToolBar"]) {
984         // The toolbar only has one menu, we take this as a hint to create a
985         // toolbar, then we return.
986         if (!toolbar) {
987             // NOTE! Each toolbar must have a unique identifier, else each
988             // window will have the same toolbar.
989             NSString *ident = [NSString stringWithFormat:@"%d", identifier];
990             toolbar = [[NSToolbar alloc] initWithIdentifier:ident];
992             [toolbar setShowsBaselineSeparator:NO];
993             [toolbar setDelegate:self];
994             [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
995             [toolbar setSizeMode:NSToolbarSizeModeSmall];
997             [windowController setToolbar:toolbar];
998         }
1000         return;
1001     }
1003     // This is either a main menu item or a popup menu item.
1004     NSString *title = [desc lastObject];
1005     NSMenuItem *item = [[NSMenuItem alloc] init];
1006     NSMenu *menu = [[NSMenu alloc] initWithTitle:title];
1008     [item setTitle:title];
1009     [item setSubmenu:menu];
1011     NSMenu *parent = [self parentMenuForDescriptor:desc];
1012     if (!parent && [rootName hasPrefix:@"PopUp"]) {
1013         if ([popupMenuItems count] <= idx) {
1014             [popupMenuItems addObject:item];
1015         } else {
1016             [popupMenuItems insertObject:item atIndex:idx];
1017         }
1018     } else {
1019         // If descriptor has no parent and its not a popup (or toolbar) menu,
1020         // then it must belong to main menu.
1021         if (!parent) parent = mainMenu;
1023         if ([parent numberOfItems] <= idx) {
1024             [parent addItem:item];
1025         } else {
1026             [parent insertItem:item atIndex:idx];
1027         }
1028     }
1030     [item release];
1031     [menu release];
1034 - (void)addMenuItemWithDescriptor:(NSArray *)desc
1035                           atIndex:(int)idx
1036                               tip:(NSString *)tip
1037                              icon:(NSString *)icon
1038                     keyEquivalent:(NSString *)keyEquivalent
1039                      modifierMask:(int)modifierMask
1040                            action:(NSString *)action
1041                       isAlternate:(BOOL)isAlternate
1043     if (!(desc && [desc count] > 1 && idx >= 0)) return;
1045     NSString *title = [desc lastObject];
1046     NSString *rootName = [desc objectAtIndex:0];
1048     if ([rootName isEqual:@"ToolBar"]) {
1049         if (toolbar && [desc count] == 2)
1050             [self addToolbarItemWithLabel:title tip:tip icon:icon atIndex:idx];
1051         return;
1052     }
1054     NSMenu *parent = [self parentMenuForDescriptor:desc];
1055     if (!parent) {
1056         ASLogWarn(@"Menu item '%@' has no parent",
1057                   [desc componentsJoinedByString:@"->"]);
1058         return;
1059     }
1061     NSMenuItem *item = nil;
1062     if (0 == [title length]
1063             || ([title hasPrefix:@"-"] && [title hasSuffix:@"-"])) {
1064         item = [NSMenuItem separatorItem];
1065         [item setTitle:title];
1066     } else {
1067         item = [[[NSMenuItem alloc] init] autorelease];
1068         [item setTitle:title];
1070         // Note: It is possible to set the action to a message that "doesn't
1071         // exist" without problems.  We take advantage of this when adding
1072         // "dummy items" e.g. when dealing with the "Recent Files" menu (in
1073         // which case a recentFilesDummy: action is set, although it is never
1074         // used).
1075         if ([action length] > 0)
1076             [item setAction:NSSelectorFromString(action)];
1077         else
1078             [item setAction:@selector(vimMenuItemAction:)];
1079         if ([tip length] > 0) [item setToolTip:tip];
1080         if ([keyEquivalent length] > 0) {
1081             [item setKeyEquivalent:keyEquivalent];
1082             [item setKeyEquivalentModifierMask:modifierMask];
1083         }
1084         [item setAlternate:isAlternate];
1086         // The tag is used to indicate whether Vim thinks a menu item should be
1087         // enabled or disabled.  By default Vim thinks menu items are enabled.
1088         [item setTag:1];
1089     }
1091     if ([parent numberOfItems] <= idx) {
1092         [parent addItem:item];
1093     } else {
1094         [parent insertItem:item atIndex:idx];
1095     }
1098 - (void)removeMenuItemWithDescriptor:(NSArray *)desc
1100     if (!(desc && [desc count] > 0)) return;
1102     NSString *title = [desc lastObject];
1103     NSString *rootName = [desc objectAtIndex:0];
1104     if ([rootName isEqual:@"ToolBar"]) {
1105         if (toolbar) {
1106             // Only remove toolbar items, never actually remove the toolbar
1107             // itself or strange things may happen.
1108             if ([desc count] == 2) {
1109                 NSUInteger idx = [toolbar indexOfItemWithItemIdentifier:title];
1110                 if (idx != NSNotFound)
1111                     [toolbar removeItemAtIndex:idx];
1112             }
1113         }
1114         return;
1115     }
1117     NSMenuItem *item = [self menuItemForDescriptor:desc];
1118     if (!item) {
1119         ASLogWarn(@"Failed to remove menu item, descriptor not found: %@",
1120                   [desc componentsJoinedByString:@"->"]);
1121         return;
1122     }
1124     [item retain];
1126     if ([item menu] == [NSApp mainMenu] || ![item menu]) {
1127         // NOTE: To be on the safe side we try to remove the item from
1128         // both arrays (it is ok to call removeObject: even if an array
1129         // does not contain the object to remove).
1130         [popupMenuItems removeObject:item];
1131     }
1133     if ([item menu])
1134         [[item menu] removeItem:item];
1136     [item release];
1139 - (void)enableMenuItemWithDescriptor:(NSArray *)desc state:(BOOL)on
1141     if (!(desc && [desc count] > 0)) return;
1143     NSString *rootName = [desc objectAtIndex:0];
1144     if ([rootName isEqual:@"ToolBar"]) {
1145         if (toolbar && [desc count] == 2) {
1146             NSString *title = [desc lastObject];
1147             [[toolbar itemWithItemIdentifier:title] setEnabled:on];
1148         }
1149     } else {
1150         // Use tag to set whether item is enabled or disabled instead of
1151         // calling setEnabled:.  This way the menus can autoenable themselves
1152         // but at the same time Vim can set if a menu is enabled whenever it
1153         // wants to.
1154         [[self menuItemForDescriptor:desc] setTag:on];
1155     }
1158 - (void)addToolbarItemToDictionaryWithLabel:(NSString *)title
1159                                     toolTip:(NSString *)tip
1160                                        icon:(NSString *)icon
1162     // If the item corresponds to a separator then do nothing, since it is
1163     // already defined by Cocoa.
1164     if (!title || [title isEqual:NSToolbarSeparatorItemIdentifier]
1165                || [title isEqual:NSToolbarSpaceItemIdentifier]
1166                || [title isEqual:NSToolbarFlexibleSpaceItemIdentifier])
1167         return;
1169     NSToolbarItem *item = [[NSToolbarItem alloc] initWithItemIdentifier:title];
1170     [item setLabel:title];
1171     [item setToolTip:tip];
1172     [item setAction:@selector(vimToolbarItemAction:)];
1173     [item setAutovalidates:NO];
1175     NSImage *img = [NSImage imageNamed:icon];
1176     if (!img) {
1177         img = [[[NSImage alloc] initByReferencingFile:icon] autorelease];
1178         if (!(img && [img isValid]))
1179             img = nil;
1180     }
1181     if (!img) {
1182         ASLogNotice(@"Could not find image with name '%@' to use as toolbar"
1183             " image for identifier '%@';"
1184             " using default toolbar icon '%@' instead.",
1185             icon, title, MMDefaultToolbarImageName);
1187         img = [NSImage imageNamed:MMDefaultToolbarImageName];
1188     }
1190     [item setImage:img];
1192     [toolbarItemDict setObject:item forKey:title];
1194     [item release];
1197 - (void)addToolbarItemWithLabel:(NSString *)label
1198                             tip:(NSString *)tip
1199                            icon:(NSString *)icon
1200                         atIndex:(int)idx
1202     if (!toolbar) return;
1204     // Check for separator items.
1205     if (!label) {
1206         label = NSToolbarSeparatorItemIdentifier;
1207     } else if ([label length] >= 2 && [label hasPrefix:@"-"]
1208                                    && [label hasSuffix:@"-"]) {
1209         // The label begins and ends with '-'; decided which kind of separator
1210         // item it is by looking at the prefix.
1211         if ([label hasPrefix:@"-space"]) {
1212             label = NSToolbarSpaceItemIdentifier;
1213         } else if ([label hasPrefix:@"-flexspace"]) {
1214             label = NSToolbarFlexibleSpaceItemIdentifier;
1215         } else {
1216             label = NSToolbarSeparatorItemIdentifier;
1217         }
1218     }
1220     [self addToolbarItemToDictionaryWithLabel:label toolTip:tip icon:icon];
1222     int maxIdx = [[toolbar items] count];
1223     if (maxIdx < idx) idx = maxIdx;
1225     [toolbar insertItemWithItemIdentifier:label atIndex:idx];
1228 - (void)popupMenuWithDescriptor:(NSArray *)desc
1229                           atRow:(NSNumber *)row
1230                          column:(NSNumber *)col
1232     NSMenu *menu = [[self menuItemForDescriptor:desc] submenu];
1233     if (!menu) return;
1235     id textView = [[windowController vimView] textView];
1236     NSPoint pt;
1237     if (row && col) {
1238         // TODO: Let textView convert (row,col) to NSPoint.
1239         int r = [row intValue];
1240         int c = [col intValue];
1241         NSSize cellSize = [textView cellSize];
1242         pt = NSMakePoint((c+1)*cellSize.width, (r+1)*cellSize.height);
1243         pt = [textView convertPoint:pt toView:nil];
1244     } else {
1245         pt = [[windowController window] mouseLocationOutsideOfEventStream];
1246     }
1248     NSEvent *event = [NSEvent mouseEventWithType:NSRightMouseDown
1249                            location:pt
1250                       modifierFlags:0
1251                           timestamp:0
1252                        windowNumber:[[windowController window] windowNumber]
1253                             context:nil
1254                         eventNumber:0
1255                          clickCount:0
1256                            pressure:1.0];
1258     [NSMenu popUpContextMenu:menu withEvent:event forView:textView];
1261 - (void)popupMenuWithAttributes:(NSDictionary *)attrs
1263     if (!attrs) return;
1265     [self popupMenuWithDescriptor:[attrs objectForKey:@"descriptor"]
1266                             atRow:[attrs objectForKey:@"row"]
1267                            column:[attrs objectForKey:@"column"]];
1270 - (void)connectionDidDie:(NSNotification *)notification
1272     ASLogDebug(@"%@", notification);
1273     [self scheduleClose];
1276 - (void)scheduleClose
1278     ASLogDebug(@"pid=%d id=%d", pid, identifier);
1280     // NOTE!  This message can arrive at pretty much anytime, e.g. while
1281     // the run loop is the 'event tracking' mode.  This means that Cocoa may
1282     // well be in the middle of processing some message while this message is
1283     // received.  If we were to remove the vim controller straight away we may
1284     // free objects that Cocoa is currently using (e.g. view objects).  The
1285     // following call ensures that the vim controller is not released until the
1286     // run loop is back in the 'default' mode.
1287     // Also, since the app may be multithreaded (e.g. as a result of showing
1288     // the open panel) we have to ensure this call happens on the main thread,
1289     // else there is a race condition that may lead to a crash.
1290     [[MMAppController sharedInstance]
1291             performSelectorOnMainThread:@selector(removeVimController:)
1292                              withObject:self
1293                           waitUntilDone:NO
1294                                   modes:[NSArray arrayWithObject:
1295                                          NSDefaultRunLoopMode]];
1298 // NSSavePanel delegate
1299 - (void)panel:(id)sender willExpand:(BOOL)expanding
1301     // Show or hide the "show hidden files" button
1302     if (expanding) {
1303         [sender setAccessoryView:showHiddenFilesView()];
1304     } else {
1305         [sender setShowsHiddenFiles:NO];
1306         [sender setAccessoryView:nil];
1307     }
1310 - (void)handleBrowseForFile:(NSDictionary *)attr
1312     if (!isInitialized) return;
1314     NSString *dir = [attr objectForKey:@"dir"];
1315     BOOL saving = [[attr objectForKey:@"saving"] boolValue];
1317     if (!dir) {
1318         // 'dir == nil' means: set dir to the pwd of the Vim process, or let
1319         // open dialog decide (depending on the below user default).
1320         BOOL trackPwd = [[NSUserDefaults standardUserDefaults]
1321                 boolForKey:MMDialogsTrackPwdKey];
1322         if (trackPwd)
1323             dir = [vimState objectForKey:@"pwd"];
1324     }
1326     if (saving) {
1327         NSSavePanel *panel = [NSSavePanel savePanel];
1329         // The delegate will be notified when the panel is expanded at which
1330         // time we may hide/show the "show hidden files" button (this button is
1331         // always visible for the open panel since it is always expanded).
1332         [panel setDelegate:self];
1333         if ([panel isExpanded])
1334             [panel setAccessoryView:showHiddenFilesView()];
1336         [panel beginSheetForDirectory:dir file:nil
1337                 modalForWindow:[windowController window]
1338                  modalDelegate:self
1339                 didEndSelector:@selector(savePanelDidEnd:code:context:)
1340                    contextInfo:NULL];
1341     } else {
1342         NSOpenPanel *panel = [NSOpenPanel openPanel];
1343         [panel setAllowsMultipleSelection:NO];
1344         [panel setAccessoryView:showHiddenFilesView()];
1346         [panel beginSheetForDirectory:dir file:nil types:nil
1347                 modalForWindow:[windowController window]
1348                  modalDelegate:self
1349                 didEndSelector:@selector(savePanelDidEnd:code:context:)
1350                    contextInfo:NULL];
1351     }
1354 - (void)handleShowDialog:(NSDictionary *)attr
1356     if (!isInitialized) return;
1358     NSArray *buttonTitles = [attr objectForKey:@"buttonTitles"];
1359     if (!(buttonTitles && [buttonTitles count])) return;
1361     int style = [[attr objectForKey:@"alertStyle"] intValue];
1362     NSString *message = [attr objectForKey:@"messageText"];
1363     NSString *text = [attr objectForKey:@"informativeText"];
1364     NSString *textFieldString = [attr objectForKey:@"textFieldString"];
1365     MMAlert *alert = [[MMAlert alloc] init];
1367     // NOTE! This has to be done before setting the informative text.
1368     if (textFieldString)
1369         [alert setTextFieldString:textFieldString];
1371     [alert setAlertStyle:style];
1373     if (message) {
1374         [alert setMessageText:message];
1375     } else {
1376         // If no message text is specified 'Alert' is used, which we don't
1377         // want, so set an empty string as message text.
1378         [alert setMessageText:@""];
1379     }
1381     if (text) {
1382         [alert setInformativeText:text];
1383     } else if (textFieldString) {
1384         // Make sure there is always room for the input text field.
1385         [alert setInformativeText:@""];
1386     }
1388     unsigned i, count = [buttonTitles count];
1389     for (i = 0; i < count; ++i) {
1390         NSString *title = [buttonTitles objectAtIndex:i];
1391         // NOTE: The title of the button may contain the character '&' to
1392         // indicate that the following letter should be the key equivalent
1393         // associated with the button.  Extract this letter and lowercase it.
1394         NSString *keyEquivalent = nil;
1395         NSRange hotkeyRange = [title rangeOfString:@"&"];
1396         if (NSNotFound != hotkeyRange.location) {
1397             if ([title length] > NSMaxRange(hotkeyRange)) {
1398                 NSRange keyEquivRange = NSMakeRange(hotkeyRange.location+1, 1);
1399                 keyEquivalent = [[title substringWithRange:keyEquivRange]
1400                     lowercaseString];
1401             }
1403             NSMutableString *string = [NSMutableString stringWithString:title];
1404             [string deleteCharactersInRange:hotkeyRange];
1405             title = string;
1406         }
1408         [alert addButtonWithTitle:title];
1410         // Set key equivalent for the button, but only if NSAlert hasn't
1411         // already done so.  (Check the documentation for
1412         // - [NSAlert addButtonWithTitle:] to see what key equivalents are
1413         // automatically assigned.)
1414         NSButton *btn = [[alert buttons] lastObject];
1415         if ([[btn keyEquivalent] length] == 0 && keyEquivalent) {
1416             [btn setKeyEquivalent:keyEquivalent];
1417         }
1418     }
1420     [alert beginSheetModalForWindow:[windowController window]
1421                       modalDelegate:self
1422                      didEndSelector:@selector(alertDidEnd:code:context:)
1423                         contextInfo:NULL];
1425     [alert release];
1429 @end // MMVimController (Private)
1434 @implementation MMAlert
1436 - (void)dealloc
1438     ASLogDebug(@"");
1440     [textField release];  textField = nil;
1441     [super dealloc];
1444 - (void)setTextFieldString:(NSString *)textFieldString
1446     [textField release];
1447     textField = [[NSTextField alloc] init];
1448     [textField setStringValue:textFieldString];
1451 - (NSTextField *)textField
1453     return textField;
1456 - (void)setInformativeText:(NSString *)text
1458     if (textField) {
1459         // HACK! Add some space for the text field.
1460         [super setInformativeText:[text stringByAppendingString:@"\n\n\n"]];
1461     } else {
1462         [super setInformativeText:text];
1463     }
1466 - (void)beginSheetModalForWindow:(NSWindow *)window
1467                    modalDelegate:(id)delegate
1468                   didEndSelector:(SEL)didEndSelector
1469                      contextInfo:(void *)contextInfo
1471     [super beginSheetModalForWindow:window
1472                       modalDelegate:delegate
1473                      didEndSelector:didEndSelector
1474                         contextInfo:contextInfo];
1476     // HACK! Place the input text field at the bottom of the informative text
1477     // (which has been made a bit larger by adding newline characters).
1478     NSView *contentView = [[self window] contentView];
1479     NSRect rect = [contentView frame];
1480     rect.origin.y = rect.size.height;
1482     NSArray *subviews = [contentView subviews];
1483     unsigned i, count = [subviews count];
1484     for (i = 0; i < count; ++i) {
1485         NSView *view = [subviews objectAtIndex:i];
1486         if ([view isKindOfClass:[NSTextField class]]
1487                 && [view frame].origin.y < rect.origin.y) {
1488             // NOTE: The informative text field is the lowest NSTextField in
1489             // the alert dialog.
1490             rect = [view frame];
1491         }
1492     }
1494     rect.size.height = MMAlertTextFieldHeight;
1495     [textField setFrame:rect];
1496     [contentView addSubview:textField];
1497     [textField becomeFirstResponder];
1500 @end // MMAlert
1505     static BOOL
1506 isUnsafeMessage(int msgid)
1508     // Messages that may release Cocoa objects must be added to this list.  For
1509     // example, UpdateTabBarMsgID may delete NSTabViewItem objects so it goes
1510     // on this list.
1511     static int unsafeMessages[] = { // REASON MESSAGE IS ON THIS LIST:
1512         //OpenWindowMsgID,            // Changes lots of state
1513         UpdateTabBarMsgID,          // May delete NSTabViewItem
1514         RemoveMenuItemMsgID,        // Deletes NSMenuItem
1515         DestroyScrollbarMsgID,      // Deletes NSScroller
1516         ExecuteActionMsgID,         // Impossible to predict
1517         ShowPopupMenuMsgID,         // Enters modal loop
1518         ActivateMsgID,              // ?
1519         EnterFullscreenMsgID,       // Modifies delegate of window controller
1520         LeaveFullscreenMsgID,       // Modifies delegate of window controller
1521         CloseWindowMsgID,           // See note below
1522         BrowseForFileMsgID,         // Enters modal loop
1523         ShowDialogMsgID,            // Enters modal loop
1524     };
1526     // NOTE about CloseWindowMsgID: If this arrives at the same time as say
1527     // ExecuteActionMsgID, then the "execute" message will be lost due to it
1528     // being queued and handled after the "close" message has caused the
1529     // controller to cleanup...UNLESS we add CloseWindowMsgID to the list of
1530     // unsafe messages.  This is the _only_ reason it is on this list (since
1531     // all that happens in response to it is that we schedule another message
1532     // for later handling).
1534     int i, count = sizeof(unsafeMessages)/sizeof(unsafeMessages[0]);
1535     for (i = 0; i < count; ++i)
1536         if (msgid == unsafeMessages[i])
1537             return YES;
1539     return NO;