Add "show hidden files" checkbox to save dialog
[MacVim.git] / src / MacVim / MMVimController.m
blobafdbfb3b464d95f4b6dd1ef85f5116adfb92cb17
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 "MMAtsuiTextView.h"
31 #import "MMFindReplaceController.h"
32 #import "MMTextView.h"
33 #import "MMVimController.h"
34 #import "MMVimView.h"
35 #import "MMWindowController.h"
36 #import "Miscellaneous.h"
38 #ifdef MM_ENABLE_PLUGINS
39 #import "MMPlugInManager.h"
40 #endif
42 static NSString *MMDefaultToolbarImageName = @"Attention";
43 static int MMAlertTextFieldHeight = 22;
45 // NOTE: By default a message sent to the backend will be dropped if it cannot
46 // be delivered instantly; otherwise there is a possibility that MacVim will
47 // 'beachball' while waiting to deliver DO messages to an unresponsive Vim
48 // process.  This means that you cannot rely on any message sent with
49 // sendMessage: to actually reach Vim.
50 static NSTimeInterval MMBackendProxyRequestTimeout = 0;
52 // Timeout used for setDialogReturn:.
53 static NSTimeInterval MMSetDialogReturnTimeout = 1.0;
55 static unsigned identifierCounter = 1;
57 static BOOL isUnsafeMessage(int msgid);
60 @interface MMAlert : NSAlert {
61     NSTextField *textField;
63 - (void)setTextFieldString:(NSString *)textFieldString;
64 - (NSTextField *)textField;
65 @end
68 @interface MMVimController (Private)
69 - (void)doProcessInputQueue:(NSArray *)queue;
70 - (void)handleMessage:(int)msgid data:(NSData *)data;
71 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
72                 context:(void *)context;
73 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context;
74 - (NSMenuItem *)menuItemForDescriptor:(NSArray *)desc;
75 - (NSMenu *)parentMenuForDescriptor:(NSArray *)desc;
76 - (NSMenu *)topLevelMenuForTitle:(NSString *)title;
77 - (void)addMenuWithDescriptor:(NSArray *)desc atIndex:(int)index;
78 - (void)addMenuItemWithDescriptor:(NSArray *)desc
79                           atIndex:(int)index
80                               tip:(NSString *)tip
81                              icon:(NSString *)icon
82                     keyEquivalent:(NSString *)keyEquivalent
83                      modifierMask:(int)modifierMask
84                            action:(NSString *)action
85                       isAlternate:(BOOL)isAlternate;
86 - (void)removeMenuItemWithDescriptor:(NSArray *)desc;
87 - (void)enableMenuItemWithDescriptor:(NSArray *)desc state:(BOOL)on;
88 - (void)addToolbarItemToDictionaryWithLabel:(NSString *)title
89         toolTip:(NSString *)tip icon:(NSString *)icon;
90 - (void)addToolbarItemWithLabel:(NSString *)label
91                           tip:(NSString *)tip icon:(NSString *)icon
92                       atIndex:(int)idx;
93 - (void)popupMenuWithDescriptor:(NSArray *)desc
94                           atRow:(NSNumber *)row
95                          column:(NSNumber *)col;
96 - (void)popupMenuWithAttributes:(NSDictionary *)attrs;
97 - (void)connectionDidDie:(NSNotification *)notification;
98 - (void)scheduleClose;
99 - (void)handleBrowseForFile:(NSDictionary *)attr;
100 - (void)handleShowDialog:(NSDictionary *)attr;
101 @end
106 @implementation MMVimController
108 - (id)initWithBackend:(id)backend pid:(int)processIdentifier
110     if (!(self = [super init]))
111         return nil;
113     // TODO: Come up with a better way of creating an identifier.
114     identifier = identifierCounter++;
116     windowController =
117         [[MMWindowController alloc] initWithVimController:self];
118     backendProxy = [backend retain];
119     popupMenuItems = [[NSMutableArray alloc] init];
120     toolbarItemDict = [[NSMutableDictionary alloc] init];
121     pid = processIdentifier;
122     creationDate = [[NSDate alloc] init];
124     NSConnection *connection = [backendProxy connectionForProxy];
126     // TODO: Check that this will not set the timeout for the root proxy
127     // (in MMAppController).
128     [connection setRequestTimeout:MMBackendProxyRequestTimeout];
130     [[NSNotificationCenter defaultCenter] addObserver:self
131             selector:@selector(connectionDidDie:)
132                 name:NSConnectionDidDieNotification object:connection];
134     // Set up a main menu with only a "MacVim" menu (copied from a template
135     // which itself is set up in MainMenu.nib).  The main menu is populated
136     // by Vim later on.
137     mainMenu = [[NSMenu alloc] initWithTitle:@"MainMenu"];
138     NSMenuItem *appMenuItem = [[MMAppController sharedInstance]
139                                         appMenuItemTemplate];
140     appMenuItem = [[appMenuItem copy] autorelease];
142     // Note: If the title of the application menu is anything but what
143     // CFBundleName says then the application menu will not be typeset in
144     // boldface for some reason.  (It should already be set when we copy
145     // from the default main menu, but this is not the case for some
146     // reason.)
147     NSString *appName = [[NSBundle mainBundle]
148             objectForInfoDictionaryKey:@"CFBundleName"];
149     [appMenuItem setTitle:appName];
151     [mainMenu addItem:appMenuItem];
153 #ifdef MM_ENABLE_PLUGINS
154     instanceMediator = [[MMPlugInInstanceMediator alloc]
155             initWithVimController:self];
156 #endif
158     isInitialized = YES;
160     return self;
163 - (void)dealloc
165     LOG_DEALLOC
167     isInitialized = NO;
169 #ifdef MM_ENABLE_PLUGINS
170     [instanceMediator release]; instanceMediator = nil;
171 #endif
173     [serverName release];  serverName = nil;
174     [backendProxy release];  backendProxy = nil;
176     [toolbarItemDict release];  toolbarItemDict = nil;
177     [toolbar release];  toolbar = nil;
178     [popupMenuItems release];  popupMenuItems = nil;
179     [windowController release];  windowController = nil;
181     [vimState release];  vimState = nil;
182     [mainMenu release];  mainMenu = nil;
183     [creationDate release];  creationDate = nil;
185     [super dealloc];
188 - (unsigned)identifier
190     return identifier;
193 - (MMWindowController *)windowController
195     return windowController;
198 #ifdef MM_ENABLE_PLUGINS
199 - (MMPlugInInstanceMediator *)instanceMediator
201     return instanceMediator;
203 #endif
205 - (NSDictionary *)vimState
207     return vimState;
210 - (id)objectForVimStateKey:(NSString *)key
212     return [vimState objectForKey:key];
215 - (NSMenu *)mainMenu
217     return mainMenu;
220 - (BOOL)isPreloading
222     return isPreloading;
225 - (void)setIsPreloading:(BOOL)yn
227     isPreloading = yn;
230 - (NSDate *)creationDate
232     return creationDate;
235 - (void)setServerName:(NSString *)name
237     if (name != serverName) {
238         [serverName release];
239         serverName = [name copy];
240     }
243 - (NSString *)serverName
245     return serverName;
248 - (int)pid
250     return pid;
253 - (void)dropFiles:(NSArray *)filenames forceOpen:(BOOL)force
255     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
257     // Default to opening in tabs if layout is invalid or set to "windows".
258     int layout = [ud integerForKey:MMOpenLayoutKey];
259     if (layout < 0 || layout > MMLayoutTabs)
260         layout = MMLayoutTabs;
262     BOOL splitVert = [ud boolForKey:MMVerticalSplitKey];
263     if (splitVert && MMLayoutHorizontalSplit == layout)
264         layout = MMLayoutVerticalSplit;
266     NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
267             [NSNumber numberWithInt:layout],    @"layout",
268             filenames,                          @"filenames",
269             [NSNumber numberWithBool:force],    @"forceOpen",
270             nil];
272     [self sendMessage:DropFilesMsgID data:[args dictionaryAsData]];
275 - (void)file:(NSString *)filename draggedToTabAtIndex:(NSUInteger)tabIndex
277     NSString *fnEsc = [filename stringByEscapingSpecialFilenameCharacters];
278     NSString *input = [NSString stringWithFormat:@"<C-\\><C-N>:silent "
279                        "tabnext %d |"
280                        "edit! %@<CR>", tabIndex + 1, fnEsc];
281     [self addVimInput:input];
284 - (void)filesDraggedToTabBar:(NSArray *)filenames
286     NSUInteger i, count = [filenames count];
287     NSMutableString *input = [NSMutableString stringWithString:@"<C-\\><C-N>"
288                               ":silent! tabnext 9999"];
289     for (i = 0; i < count; i++) {
290         NSString *fn = [filenames objectAtIndex:i];
291         NSString *fnEsc = [fn stringByEscapingSpecialFilenameCharacters];
292         [input appendFormat:@"|tabedit %@", fnEsc];
293     }
294     [input appendString:@"<CR>"];
295     [self addVimInput:input];
298 - (void)dropString:(NSString *)string
300     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
301     if (len > 0) {
302         NSMutableData *data = [NSMutableData data];
304         [data appendBytes:&len length:sizeof(int)];
305         [data appendBytes:[string UTF8String] length:len];
307         [self sendMessage:DropStringMsgID data:data];
308     }
311 - (void)passArguments:(NSDictionary *)args
313     if (!args) return;
315     [self sendMessage:OpenWithArgumentsMsgID data:[args dictionaryAsData]];
317     // HACK! Fool findUnusedEditor into thinking that this controller is not
318     // unused anymore, in case it is called before the arguments have reached
319     // the Vim process.  This should be a "safe" hack since the next time the
320     // Vim process flushes its output queue the state will be updated again (at
321     // which time the "unusedEditor" state will have been properly set).
322     NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:
323             vimState];
324     [dict setObject:[NSNumber numberWithBool:NO] forKey:@"unusedEditor"];
325     [vimState release];
326     vimState = [dict copy];
329 - (void)sendMessage:(int)msgid data:(NSData *)data
331     //NSLog(@"sendMessage:%s (isInitialized=%d)",
332     //        MessageStrings[msgid], isInitialized);
334     if (!isInitialized) return;
336     @try {
337         [backendProxy processInput:msgid data:data];
338     }
339     @catch (NSException *e) {
340         //NSLog(@"%@ %s Exception caught during DO call: %@",
341         //        [self className], _cmd, e);
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     if (!isInitialized)
354         return NO;
356     if (timeout < 0) timeout = 0;
358     BOOL sendOk = YES;
359     NSConnection *conn = [backendProxy connectionForProxy];
360     NSTimeInterval oldTimeout = [conn requestTimeout];
362     [conn setRequestTimeout:timeout];
364     @try {
365         [backendProxy processInput:msgid data:data];
366     }
367     @catch (NSException *e) {
368         sendOk = NO;
369     }
370     @finally {
371         [conn setRequestTimeout:oldTimeout];
372     }
374     return sendOk;
377 - (void)addVimInput:(NSString *)string
379     // This is a very general method of adding input to the Vim process.  It is
380     // basically the same as calling remote_send() on the process (see
381     // ':h remote_send').
382     if (string) {
383         NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
384         [self sendMessage:AddInputMsgID data:data];
385     }
388 - (NSString *)evaluateVimExpression:(NSString *)expr
390     NSString *eval = nil;
392     @try {
393         eval = [backendProxy evaluateExpression:expr];
394     }
395     @catch (NSException *ex) { /* do nothing */ }
397     return eval;
400 - (id)evaluateVimExpressionCocoa:(NSString *)expr
401                      errorString:(NSString **)errstr
403     id eval = nil;
405     @try {
406         eval = [backendProxy evaluateExpressionCocoa:expr
407                                          errorString:errstr];
408     } @catch (NSException *ex) {
409         *errstr = [ex reason];
410     }
412     return eval;
415 - (id)backendProxy
417     return backendProxy;
420 - (void)cleanup
422     if (!isInitialized) return;
424     // Remove any delayed calls made on this object.
425     [NSObject cancelPreviousPerformRequestsWithTarget:self];
427     isInitialized = NO;
428     [toolbar setDelegate:nil];
429     [[NSNotificationCenter defaultCenter] removeObserver:self];
430     //[[backendProxy connectionForProxy] invalidate];
431     //[windowController close];
432     [windowController cleanup];
435 - (void)processInputQueue:(NSArray *)queue
437     if (!isInitialized) return;
439     // NOTE: This method must not raise any exceptions (see comment in the
440     // calling method).
441     @try {
442         [self doProcessInputQueue:queue];
443         [windowController processInputQueueDidFinish];
444     }
445     @catch (NSException *ex) {
446         NSLog(@"[%s] Caught exception (pid=%d): %@", _cmd, pid, ex);
447     }
450 - (NSToolbarItem *)toolbar:(NSToolbar *)theToolbar
451     itemForItemIdentifier:(NSString *)itemId
452     willBeInsertedIntoToolbar:(BOOL)flag
454     NSToolbarItem *item = [toolbarItemDict objectForKey:itemId];
455     if (!item) {
456         NSLog(@"WARNING:  No toolbar item with id '%@'", itemId);
457     }
459     return item;
462 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)theToolbar
464     return nil;
467 - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)theToolbar
469     return nil;
472 @end // MMVimController
476 @implementation MMVimController (Private)
478 - (void)doProcessInputQueue:(NSArray *)queue
480     NSMutableArray *delayQueue = nil;
482     unsigned i, count = [queue count];
483     if (count % 2) {
484         NSLog(@"WARNING: Uneven number of components (%d) in command "
485                 "queue.  Skipping...", count);
486         return;
487     }
489     //NSLog(@"======== %s BEGIN ========", _cmd);
490     for (i = 0; i < count; i += 2) {
491         NSData *value = [queue objectAtIndex:i];
492         NSData *data = [queue objectAtIndex:i+1];
494         int msgid = *((int*)[value bytes]);
495         //NSLog(@"%s%s", _cmd, MessageStrings[msgid]);
497         BOOL inDefaultMode = [[[NSRunLoop currentRunLoop] currentMode]
498                                             isEqual:NSDefaultRunLoopMode];
499         if (!inDefaultMode && isUnsafeMessage(msgid)) {
500             // NOTE: Because we may be listening to DO messages in "event
501             // tracking mode" we have to take extra care when doing things
502             // like releasing view items (and other Cocoa objects).
503             // Messages that may be potentially "unsafe" are delayed until
504             // the run loop is back to default mode at which time they are
505             // safe to call again.
506             //   A problem with this approach is that it is hard to
507             // classify which messages are unsafe.  As a rule of thumb, if
508             // a message may release an object used by the Cocoa framework
509             // (e.g. views) then the message should be considered unsafe.
510             //   Delaying messages may have undesired side-effects since it
511             // means that messages may not be processed in the order Vim
512             // sent them, so beware.
513             if (!delayQueue)
514                 delayQueue = [NSMutableArray array];
516             //NSLog(@"Adding unsafe message '%s' to delay queue (mode=%@)",
517             //        MessageStrings[msgid],
518             //        [[NSRunLoop currentRunLoop] currentMode]);
519             [delayQueue addObject:value];
520             [delayQueue addObject:data];
521         } else {
522             [self handleMessage:msgid data:data];
523         }
524     }
525     //NSLog(@"======== %s  END  ========", _cmd);
527     if (delayQueue) {
528         //NSLog(@"    Flushing delay queue (%d items)", [delayQueue count]/2);
529         [self performSelector:@selector(processInputQueue:)
530                    withObject:delayQueue
531                    afterDelay:0];
532     }
535 - (void)handleMessage:(int)msgid data:(NSData *)data
537     //if (msgid != AddMenuMsgID && msgid != AddMenuItemMsgID &&
538     //        msgid != EnableMenuItemMsgID)
539     //    NSLog(@"%@ %s%s", [self className], _cmd, MessageStrings[msgid]);
541     if (OpenWindowMsgID == msgid) {
542         [windowController openWindow];
544         // If the vim controller is preloading then the window will be
545         // displayed when it is taken off the preload cache.
546         if (!isPreloading)
547             [windowController showWindow];
548     } else if (BatchDrawMsgID == msgid) {
549         [[[windowController vimView] textView] performBatchDrawWithData:data];
550     } else if (SelectTabMsgID == msgid) {
551 #if 0   // NOTE: Tab selection is done inside updateTabsWithData:.
552         const void *bytes = [data bytes];
553         int idx = *((int*)bytes);
554         //NSLog(@"Selecting tab with index %d", idx);
555         [windowController selectTabWithIndex:idx];
556 #endif
557     } else if (UpdateTabBarMsgID == msgid) {
558         [windowController updateTabsWithData:data];
559     } else if (ShowTabBarMsgID == msgid) {
560         [windowController showTabBar:YES];
561     } else if (HideTabBarMsgID == msgid) {
562         [windowController showTabBar:NO];
563     } else if (SetTextDimensionsMsgID == msgid || LiveResizeMsgID == msgid ||
564             SetTextDimensionsReplyMsgID == msgid) {
565         const void *bytes = [data bytes];
566         int rows = *((int*)bytes);  bytes += sizeof(int);
567         int cols = *((int*)bytes);  bytes += sizeof(int);
569         [windowController setTextDimensionsWithRows:rows
570                                  columns:cols
571                                   isLive:(LiveResizeMsgID==msgid)
572                                  isReply:(SetTextDimensionsReplyMsgID==msgid)];
573     } else if (SetWindowTitleMsgID == msgid) {
574         const void *bytes = [data bytes];
575         int len = *((int*)bytes);  bytes += sizeof(int);
577         NSString *string = [[NSString alloc] initWithBytes:(void*)bytes
578                 length:len encoding:NSUTF8StringEncoding];
580         // While in live resize the window title displays the dimensions of the
581         // window so don't clobber this with a spurious "set title" message
582         // from Vim.
583         if (![[windowController vimView] inLiveResize])
584             [windowController setTitle:string];
586         [string release];
587     } else if (SetDocumentFilenameMsgID == msgid) {
588         const void *bytes = [data bytes];
589         int len = *((int*)bytes);  bytes += sizeof(int);
591         if (len > 0) {
592             NSString *filename = [[NSString alloc] initWithBytes:(void*)bytes
593                     length:len encoding:NSUTF8StringEncoding];
595             [windowController setDocumentFilename:filename];
597             [filename release];
598         } else {
599             [windowController setDocumentFilename:@""];
600         }
601     } else if (AddMenuMsgID == msgid) {
602         NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
603         [self addMenuWithDescriptor:[attrs objectForKey:@"descriptor"]
604                 atIndex:[[attrs objectForKey:@"index"] intValue]];
605     } else if (AddMenuItemMsgID == msgid) {
606         NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
607         [self addMenuItemWithDescriptor:[attrs objectForKey:@"descriptor"]
608                       atIndex:[[attrs objectForKey:@"index"] intValue]
609                           tip:[attrs objectForKey:@"tip"]
610                          icon:[attrs objectForKey:@"icon"]
611                 keyEquivalent:[attrs objectForKey:@"keyEquivalent"]
612                  modifierMask:[[attrs objectForKey:@"modifierMask"] intValue]
613                        action:[attrs objectForKey:@"action"]
614                   isAlternate:[[attrs objectForKey:@"isAlternate"] boolValue]];
615     } else if (RemoveMenuItemMsgID == msgid) {
616         NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
617         [self removeMenuItemWithDescriptor:[attrs objectForKey:@"descriptor"]];
618     } else if (EnableMenuItemMsgID == msgid) {
619         NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
620         [self enableMenuItemWithDescriptor:[attrs objectForKey:@"descriptor"]
621                 state:[[attrs objectForKey:@"enable"] boolValue]];
622     } else if (ShowToolbarMsgID == msgid) {
623         const void *bytes = [data bytes];
624         int enable = *((int*)bytes);  bytes += sizeof(int);
625         int flags = *((int*)bytes);  bytes += sizeof(int);
627         int mode = NSToolbarDisplayModeDefault;
628         if (flags & ToolbarLabelFlag) {
629             mode = flags & ToolbarIconFlag ? NSToolbarDisplayModeIconAndLabel
630                     : NSToolbarDisplayModeLabelOnly;
631         } else if (flags & ToolbarIconFlag) {
632             mode = NSToolbarDisplayModeIconOnly;
633         }
635         int size = flags & ToolbarSizeRegularFlag ? NSToolbarSizeModeRegular
636                 : NSToolbarSizeModeSmall;
638         [windowController showToolbar:enable size:size mode:mode];
639     } else if (CreateScrollbarMsgID == msgid) {
640         const void *bytes = [data bytes];
641         long ident = *((long*)bytes);  bytes += sizeof(long);
642         int type = *((int*)bytes);  bytes += sizeof(int);
644         [windowController createScrollbarWithIdentifier:ident type:type];
645     } else if (DestroyScrollbarMsgID == msgid) {
646         const void *bytes = [data bytes];
647         long ident = *((long*)bytes);  bytes += sizeof(long);
649         [windowController destroyScrollbarWithIdentifier:ident];
650     } else if (ShowScrollbarMsgID == msgid) {
651         const void *bytes = [data bytes];
652         long ident = *((long*)bytes);  bytes += sizeof(long);
653         int visible = *((int*)bytes);  bytes += sizeof(int);
655         [windowController showScrollbarWithIdentifier:ident state:visible];
656     } else if (SetScrollbarPositionMsgID == msgid) {
657         const void *bytes = [data bytes];
658         long ident = *((long*)bytes);  bytes += sizeof(long);
659         int pos = *((int*)bytes);  bytes += sizeof(int);
660         int len = *((int*)bytes);  bytes += sizeof(int);
662         [windowController setScrollbarPosition:pos length:len
663                                     identifier:ident];
664     } else if (SetScrollbarThumbMsgID == msgid) {
665         const void *bytes = [data bytes];
666         long ident = *((long*)bytes);  bytes += sizeof(long);
667         float val = *((float*)bytes);  bytes += sizeof(float);
668         float prop = *((float*)bytes);  bytes += sizeof(float);
670         [windowController setScrollbarThumbValue:val proportion:prop
671                                       identifier:ident];
672     } else if (SetFontMsgID == msgid) {
673         const void *bytes = [data bytes];
674         float size = *((float*)bytes);  bytes += sizeof(float);
675         int len = *((int*)bytes);  bytes += sizeof(int);
676         NSString *name = [[NSString alloc]
677                 initWithBytes:(void*)bytes length:len
678                      encoding:NSUTF8StringEncoding];
679         NSFont *font = [NSFont fontWithName:name size:size];
680         if (!font) {
681             // This should only happen if the default font was not loaded in
682             // which case we fall back on using the Cocoa default fixed width
683             // font.
684             font = [NSFont userFixedPitchFontOfSize:size];
685         }
687         [windowController setFont:font];
688         [name release];
689     } else if (SetWideFontMsgID == msgid) {
690         const void *bytes = [data bytes];
691         float size = *((float*)bytes);  bytes += sizeof(float);
692         int len = *((int*)bytes);  bytes += sizeof(int);
693         if (len > 0) {
694             NSString *name = [[NSString alloc]
695                     initWithBytes:(void*)bytes length:len
696                          encoding:NSUTF8StringEncoding];
697             NSFont *font = [NSFont fontWithName:name size:size];
698             [windowController setWideFont:font];
700             [name release];
701         } else {
702             [windowController setWideFont:nil];
703         }
704     } else if (SetDefaultColorsMsgID == msgid) {
705         const void *bytes = [data bytes];
706         unsigned bg = *((unsigned*)bytes);  bytes += sizeof(unsigned);
707         unsigned fg = *((unsigned*)bytes);  bytes += sizeof(unsigned);
708         NSColor *back = [NSColor colorWithArgbInt:bg];
709         NSColor *fore = [NSColor colorWithRgbInt:fg];
711         [windowController setDefaultColorsBackground:back foreground:fore];
712     } else if (ExecuteActionMsgID == msgid) {
713         const void *bytes = [data bytes];
714         int len = *((int*)bytes);  bytes += sizeof(int);
715         NSString *actionName = [[NSString alloc]
716                 initWithBytes:(void*)bytes length:len
717                      encoding:NSUTF8StringEncoding];
719         SEL sel = NSSelectorFromString(actionName);
720         [NSApp sendAction:sel to:nil from:self];
722         [actionName release];
723     } else if (ShowPopupMenuMsgID == msgid) {
724         NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
726         // The popup menu enters a modal loop so delay this call so that we
727         // don't block inside processInputQueue:.
728         [self performSelector:@selector(popupMenuWithAttributes:)
729                    withObject:attrs
730                    afterDelay:0];
731     } else if (SetMouseShapeMsgID == msgid) {
732         const void *bytes = [data bytes];
733         int shape = *((int*)bytes);  bytes += sizeof(int);
735         [windowController setMouseShape:shape];
736     } else if (AdjustLinespaceMsgID == msgid) {
737         const void *bytes = [data bytes];
738         int linespace = *((int*)bytes);  bytes += sizeof(int);
740         [windowController adjustLinespace:linespace];
741     } else if (ActivateMsgID == msgid) {
742         //NSLog(@"ActivateMsgID");
743         [NSApp activateIgnoringOtherApps:YES];
744         [[windowController window] makeKeyAndOrderFront:self];
745     } else if (SetServerNameMsgID == msgid) {
746         NSString *name = [[NSString alloc] initWithData:data
747                                                encoding:NSUTF8StringEncoding];
748         [self setServerName:name];
749         [name release];
750     } else if (EnterFullscreenMsgID == msgid) {
751         const void *bytes = [data bytes];
752         int fuoptions = *((int*)bytes); bytes += sizeof(int);
753         int bg = *((int*)bytes);
754         NSColor *back = [NSColor colorWithArgbInt:bg];
756         [windowController enterFullscreen:fuoptions backgroundColor:back];
757     } else if (LeaveFullscreenMsgID == msgid) {
758         [windowController leaveFullscreen];
759     } else if (BuffersNotModifiedMsgID == msgid) {
760         [windowController setBuffersModified:NO];
761     } else if (BuffersModifiedMsgID == msgid) {
762         [windowController setBuffersModified:YES];
763     } else if (SetPreEditPositionMsgID == msgid) {
764         const int *dim = (const int*)[data bytes];
765         [[[windowController vimView] textView] setPreEditRow:dim[0]
766                                                       column:dim[1]];
767     } else if (EnableAntialiasMsgID == msgid) {
768         [[[windowController vimView] textView] setAntialias:YES];
769     } else if (DisableAntialiasMsgID == msgid) {
770         [[[windowController vimView] textView] setAntialias:NO];
771     } else if (SetVimStateMsgID == msgid) {
772         NSDictionary *dict = [NSDictionary dictionaryWithData:data];
773         if (dict) {
774             [vimState release];
775             vimState = [dict retain];
776         }
777     } else if (CloseWindowMsgID == msgid) {
778         [self scheduleClose];
779     } else if (SetFullscreenColorMsgID == msgid) {
780         const int *bg = (const int*)[data bytes];
781         NSColor *color = [NSColor colorWithRgbInt:*bg];
783         [windowController setFullscreenBackgroundColor:color];
784     } else if (ShowFindReplaceDialogMsgID == msgid) {
785         NSDictionary *dict = [NSDictionary dictionaryWithData:data];
786         if (dict) {
787             [[MMFindReplaceController sharedInstance]
788                 showWithText:[dict objectForKey:@"text"]
789                        flags:[[dict objectForKey:@"flags"] intValue]];
790         }
791     } else if (ActivateKeyScriptID == msgid) {
792         KeyScript(smKeySysScript);
793     } else if (DeactivateKeyScriptID == msgid) {
794         KeyScript(smKeyRoman);
795     } else if (BrowseForFileMsgID == msgid) {
796         NSDictionary *dict = [NSDictionary dictionaryWithData:data];
797         if (dict)
798             [self handleBrowseForFile:dict];
799     } else if (ShowDialogMsgID == msgid) {
800         NSDictionary *dict = [NSDictionary dictionaryWithData:data];
801         if (dict)
802             [self handleShowDialog:dict];
803     // IMPORTANT: When adding a new message, make sure to update
804     // isUnsafeMessage() if necessary!
805     } else {
806         NSLog(@"WARNING: Unknown message received (msgid=%d)", msgid);
807     }
810 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
811                 context:(void *)context
813     NSString *path = (code == NSOKButton) ? [panel filename] : nil;
815     // NOTE! setDialogReturn: is a synchronous call so set a proper timeout to
816     // avoid waiting forever for it to finish.  We make this a synchronous call
817     // so that we can be fairly certain that Vim doesn't think the dialog box
818     // is still showing when MacVim has in fact already dismissed it.
819     NSConnection *conn = [backendProxy connectionForProxy];
820     NSTimeInterval oldTimeout = [conn requestTimeout];
821     [conn setRequestTimeout:MMSetDialogReturnTimeout];
823     @try {
824         [backendProxy setDialogReturn:path];
826         // Add file to the "Recent Files" menu (this ensures that files that
827         // are opened/saved from a :browse command are added to this menu).
828         if (path)
829             [[NSDocumentController sharedDocumentController]
830                     noteNewRecentFilePath:path];
831     }
832     @catch (NSException *e) {
833         NSLog(@"Exception caught in %s %@", _cmd, e);
834     }
835     @finally {
836         [conn setRequestTimeout:oldTimeout];
837     }
840 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context
842     NSArray *ret = nil;
844     code = code - NSAlertFirstButtonReturn + 1;
846     if ([alert isKindOfClass:[MMAlert class]] && [alert textField]) {
847         ret = [NSArray arrayWithObjects:[NSNumber numberWithInt:code],
848             [[alert textField] stringValue], nil];
849     } else {
850         ret = [NSArray arrayWithObject:[NSNumber numberWithInt:code]];
851     }
853     @try {
854         [backendProxy setDialogReturn:ret];
855     }
856     @catch (NSException *e) {
857         NSLog(@"Exception caught in %s %@", _cmd, e);
858     }
861 - (NSMenuItem *)menuItemForDescriptor:(NSArray *)desc
863     if (!(desc && [desc count] > 0)) return nil;
865     NSString *rootName = [desc objectAtIndex:0];
866     NSArray *rootItems = [rootName hasPrefix:@"PopUp"] ? popupMenuItems
867                                                        : [mainMenu itemArray];
869     NSMenuItem *item = nil;
870     int i, count = [rootItems count];
871     for (i = 0; i < count; ++i) {
872         item = [rootItems objectAtIndex:i];
873         if ([[item title] isEqual:rootName])
874             break;
875     }
877     if (i == count) return nil;
879     count = [desc count];
880     for (i = 1; i < count; ++i) {
881         item = [[item submenu] itemWithTitle:[desc objectAtIndex:i]];
882         if (!item) return nil;
883     }
885     return item;
888 - (NSMenu *)parentMenuForDescriptor:(NSArray *)desc
890     if (!(desc && [desc count] > 0)) return nil;
892     NSString *rootName = [desc objectAtIndex:0];
893     NSArray *rootItems = [rootName hasPrefix:@"PopUp"] ? popupMenuItems
894                                                        : [mainMenu itemArray];
896     NSMenu *menu = nil;
897     int i, count = [rootItems count];
898     for (i = 0; i < count; ++i) {
899         NSMenuItem *item = [rootItems objectAtIndex:i];
900         if ([[item title] isEqual:rootName]) {
901             menu = [item submenu];
902             break;
903         }
904     }
906     if (!menu) return nil;
908     count = [desc count] - 1;
909     for (i = 1; i < count; ++i) {
910         NSMenuItem *item = [menu itemWithTitle:[desc objectAtIndex:i]];
911         menu = [item submenu];
912         if (!menu) return nil;
913     }
915     return menu;
918 - (NSMenu *)topLevelMenuForTitle:(NSString *)title
920     // Search only the top-level menus.
922     unsigned i, count = [popupMenuItems count];
923     for (i = 0; i < count; ++i) {
924         NSMenuItem *item = [popupMenuItems objectAtIndex:i];
925         if ([title isEqual:[item title]])
926             return [item submenu];
927     }
929     count = [mainMenu numberOfItems];
930     for (i = 0; i < count; ++i) {
931         NSMenuItem *item = [mainMenu itemAtIndex:i];
932         if ([title isEqual:[item title]])
933             return [item submenu];
934     }
936     return nil;
939 - (void)addMenuWithDescriptor:(NSArray *)desc atIndex:(int)idx
941     if (!(desc && [desc count] > 0 && idx >= 0)) return;
943     NSString *rootName = [desc objectAtIndex:0];
944     if ([rootName isEqual:@"ToolBar"]) {
945         // The toolbar only has one menu, we take this as a hint to create a
946         // toolbar, then we return.
947         if (!toolbar) {
948             // NOTE! Each toolbar must have a unique identifier, else each
949             // window will have the same toolbar.
950             NSString *ident = [NSString stringWithFormat:@"%d", (int)self];
951             toolbar = [[NSToolbar alloc] initWithIdentifier:ident];
953             [toolbar setShowsBaselineSeparator:NO];
954             [toolbar setDelegate:self];
955             [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
956             [toolbar setSizeMode:NSToolbarSizeModeSmall];
958             [windowController setToolbar:toolbar];
959         }
961         return;
962     }
964     // This is either a main menu item or a popup menu item.
965     NSString *title = [desc lastObject];
966     NSMenuItem *item = [[NSMenuItem alloc] init];
967     NSMenu *menu = [[NSMenu alloc] initWithTitle:title];
969     [item setTitle:title];
970     [item setSubmenu:menu];
972     NSMenu *parent = [self parentMenuForDescriptor:desc];
973     if (!parent && [rootName hasPrefix:@"PopUp"]) {
974         if ([popupMenuItems count] <= idx) {
975             [popupMenuItems addObject:item];
976         } else {
977             [popupMenuItems insertObject:item atIndex:idx];
978         }
979     } else {
980         // If descriptor has no parent and its not a popup (or toolbar) menu,
981         // then it must belong to main menu.
982         if (!parent) parent = mainMenu;
984         if ([parent numberOfItems] <= idx) {
985             [parent addItem:item];
986         } else {
987             [parent insertItem:item atIndex:idx];
988         }
989     }
991     [item release];
992     [menu release];
995 - (void)addMenuItemWithDescriptor:(NSArray *)desc
996                           atIndex:(int)idx
997                               tip:(NSString *)tip
998                              icon:(NSString *)icon
999                     keyEquivalent:(NSString *)keyEquivalent
1000                      modifierMask:(int)modifierMask
1001                            action:(NSString *)action
1002                       isAlternate:(BOOL)isAlternate
1004     if (!(desc && [desc count] > 1 && idx >= 0)) return;
1006     NSString *title = [desc lastObject];
1007     NSString *rootName = [desc objectAtIndex:0];
1009     if ([rootName isEqual:@"ToolBar"]) {
1010         if (toolbar && [desc count] == 2)
1011             [self addToolbarItemWithLabel:title tip:tip icon:icon atIndex:idx];
1012         return;
1013     }
1015     NSMenu *parent = [self parentMenuForDescriptor:desc];
1016     if (!parent) {
1017         NSLog(@"WARNING: Menu item '%@' has no parent",
1018                 [desc componentsJoinedByString:@"->"]);
1019         return;
1020     }
1022     NSMenuItem *item = nil;
1023     if (0 == [title length]
1024             || ([title hasPrefix:@"-"] && [title hasSuffix:@"-"])) {
1025         item = [NSMenuItem separatorItem];
1026         [item setTitle:title];
1027     } else {
1028         item = [[[NSMenuItem alloc] init] autorelease];
1029         [item setTitle:title];
1031         // Note: It is possible to set the action to a message that "doesn't
1032         // exist" without problems.  We take advantage of this when adding
1033         // "dummy items" e.g. when dealing with the "Recent Files" menu (in
1034         // which case a recentFilesDummy: action is set, although it is never
1035         // used).
1036         if ([action length] > 0)
1037             [item setAction:NSSelectorFromString(action)];
1038         else
1039             [item setAction:@selector(vimMenuItemAction:)];
1040         if ([tip length] > 0) [item setToolTip:tip];
1041         if ([keyEquivalent length] > 0) {
1042             [item setKeyEquivalent:keyEquivalent];
1043             [item setKeyEquivalentModifierMask:modifierMask];
1044         }
1045         [item setAlternate:isAlternate];
1047         // The tag is used to indicate whether Vim thinks a menu item should be
1048         // enabled or disabled.  By default Vim thinks menu items are enabled.
1049         [item setTag:1];
1050     }
1052     if ([parent numberOfItems] <= idx) {
1053         [parent addItem:item];
1054     } else {
1055         [parent insertItem:item atIndex:idx];
1056     }
1059 - (void)removeMenuItemWithDescriptor:(NSArray *)desc
1061     if (!(desc && [desc count] > 0)) return;
1063     NSString *title = [desc lastObject];
1064     NSString *rootName = [desc objectAtIndex:0];
1065     if ([rootName isEqual:@"ToolBar"]) {
1066         if (toolbar) {
1067             // Only remove toolbar items, never actually remove the toolbar
1068             // itself or strange things may happen.
1069             if ([desc count] == 2) {
1070                 int idx = [toolbar indexOfItemWithItemIdentifier:title];
1071                 if (idx != NSNotFound)
1072                     [toolbar removeItemAtIndex:idx];
1073             }
1074         }
1075         return;
1076     }
1078     NSMenuItem *item = [self menuItemForDescriptor:desc];
1079     if (!item) {
1080         NSLog(@"Failed to remove menu item, descriptor not found: %@",
1081                 [desc componentsJoinedByString:@"->"]);
1082         return;
1083     }
1085     [item retain];
1087     if ([item menu] == [NSApp mainMenu] || ![item menu]) {
1088         // NOTE: To be on the safe side we try to remove the item from
1089         // both arrays (it is ok to call removeObject: even if an array
1090         // does not contain the object to remove).
1091         [popupMenuItems removeObject:item];
1092     }
1094     if ([item menu])
1095         [[item menu] removeItem:item];
1097     [item release];
1100 - (void)enableMenuItemWithDescriptor:(NSArray *)desc state:(BOOL)on
1102     if (!(desc && [desc count] > 0)) return;
1104     /*NSLog(@"%sable item %@", on ? "En" : "Dis",
1105             [desc componentsJoinedByString:@"->"]);*/
1107     NSString *rootName = [desc objectAtIndex:0];
1108     if ([rootName isEqual:@"ToolBar"]) {
1109         if (toolbar && [desc count] == 2) {
1110             NSString *title = [desc lastObject];
1111             [[toolbar itemWithItemIdentifier:title] setEnabled:on];
1112         }
1113     } else {
1114         // Use tag to set whether item is enabled or disabled instead of
1115         // calling setEnabled:.  This way the menus can autoenable themselves
1116         // but at the same time Vim can set if a menu is enabled whenever it
1117         // wants to.
1118         [[self menuItemForDescriptor:desc] setTag:on];
1119     }
1122 - (void)addToolbarItemToDictionaryWithLabel:(NSString *)title
1123                                     toolTip:(NSString *)tip
1124                                        icon:(NSString *)icon
1126     // If the item corresponds to a separator then do nothing, since it is
1127     // already defined by Cocoa.
1128     if (!title || [title isEqual:NSToolbarSeparatorItemIdentifier]
1129                || [title isEqual:NSToolbarSpaceItemIdentifier]
1130                || [title isEqual:NSToolbarFlexibleSpaceItemIdentifier])
1131         return;
1133     NSToolbarItem *item = [[NSToolbarItem alloc] initWithItemIdentifier:title];
1134     [item setLabel:title];
1135     [item setToolTip:tip];
1136     [item setAction:@selector(vimToolbarItemAction:)];
1137     [item setAutovalidates:NO];
1139     NSImage *img = [NSImage imageNamed:icon];
1140     if (!img) {
1141         img = [[[NSImage alloc] initByReferencingFile:icon] autorelease];
1142         if (!(img && [img isValid]))
1143             img = nil;
1144     }
1145     if (!img) {
1146         NSLog(@"WARNING: Could not find image with name '%@' to use as toolbar"
1147                " image for identifier '%@';"
1148                " using default toolbar icon '%@' instead.",
1149                icon, title, MMDefaultToolbarImageName);
1151         img = [NSImage imageNamed:MMDefaultToolbarImageName];
1152     }
1154     [item setImage:img];
1156     [toolbarItemDict setObject:item forKey:title];
1158     [item release];
1161 - (void)addToolbarItemWithLabel:(NSString *)label
1162                             tip:(NSString *)tip
1163                            icon:(NSString *)icon
1164                         atIndex:(int)idx
1166     if (!toolbar) return;
1168     // Check for separator items.
1169     if (!label) {
1170         label = NSToolbarSeparatorItemIdentifier;
1171     } else if ([label length] >= 2 && [label hasPrefix:@"-"]
1172                                    && [label hasSuffix:@"-"]) {
1173         // The label begins and ends with '-'; decided which kind of separator
1174         // item it is by looking at the prefix.
1175         if ([label hasPrefix:@"-space"]) {
1176             label = NSToolbarSpaceItemIdentifier;
1177         } else if ([label hasPrefix:@"-flexspace"]) {
1178             label = NSToolbarFlexibleSpaceItemIdentifier;
1179         } else {
1180             label = NSToolbarSeparatorItemIdentifier;
1181         }
1182     }
1184     [self addToolbarItemToDictionaryWithLabel:label toolTip:tip icon:icon];
1186     int maxIdx = [[toolbar items] count];
1187     if (maxIdx < idx) idx = maxIdx;
1189     [toolbar insertItemWithItemIdentifier:label atIndex:idx];
1192 - (void)popupMenuWithDescriptor:(NSArray *)desc
1193                           atRow:(NSNumber *)row
1194                          column:(NSNumber *)col
1196     NSMenu *menu = [[self menuItemForDescriptor:desc] submenu];
1197     if (!menu) return;
1199     id textView = [[windowController vimView] textView];
1200     NSPoint pt;
1201     if (row && col) {
1202         // TODO: Let textView convert (row,col) to NSPoint.
1203         int r = [row intValue];
1204         int c = [col intValue];
1205         NSSize cellSize = [textView cellSize];
1206         pt = NSMakePoint((c+1)*cellSize.width, (r+1)*cellSize.height);
1207         pt = [textView convertPoint:pt toView:nil];
1208     } else {
1209         pt = [[windowController window] mouseLocationOutsideOfEventStream];
1210     }
1212     NSEvent *event = [NSEvent mouseEventWithType:NSRightMouseDown
1213                            location:pt
1214                       modifierFlags:0
1215                           timestamp:0
1216                        windowNumber:[[windowController window] windowNumber]
1217                             context:nil
1218                         eventNumber:0
1219                          clickCount:0
1220                            pressure:1.0];
1222     [NSMenu popUpContextMenu:menu withEvent:event forView:textView];
1225 - (void)popupMenuWithAttributes:(NSDictionary *)attrs
1227     if (!attrs) return;
1229     [self popupMenuWithDescriptor:[attrs objectForKey:@"descriptor"]
1230                             atRow:[attrs objectForKey:@"row"]
1231                            column:[attrs objectForKey:@"column"]];
1234 - (void)connectionDidDie:(NSNotification *)notification
1236     //NSLog(@"%@ %s%@", [self className], _cmd, notification);
1237     [self scheduleClose];
1240 - (void)scheduleClose
1242     // NOTE!  This message can arrive at pretty much anytime, e.g. while
1243     // the run loop is the 'event tracking' mode.  This means that Cocoa may
1244     // well be in the middle of processing some message while this message is
1245     // received.  If we were to remove the vim controller straight away we may
1246     // free objects that Cocoa is currently using (e.g. view objects).  The
1247     // following call ensures that the vim controller is not released until the
1248     // run loop is back in the 'default' mode.
1249     [[MMAppController sharedInstance]
1250             performSelector:@selector(removeVimController:)
1251                  withObject:self
1252                  afterDelay:0];
1255 // NSSavePanel delegate
1256 - (void)panel:(id)sender willExpand:(BOOL)expanding
1258     // Show or hide the "show hidden files" button
1259     if (expanding) {
1260         [sender setAccessoryView:showHiddenFilesView()];
1261     } else {
1262         [sender setShowsHiddenFiles:NO];
1263         [sender setAccessoryView:nil];
1264     }
1267 - (void)handleBrowseForFile:(NSDictionary *)attr
1269     if (!isInitialized) return;
1271     NSString *dir = [attr objectForKey:@"dir"];
1272     BOOL saving = [[attr objectForKey:@"saving"] boolValue];
1274     if (!dir) {
1275         // 'dir == nil' means: set dir to the pwd of the Vim process, or let
1276         // open dialog decide (depending on the below user default).
1277         BOOL trackPwd = [[NSUserDefaults standardUserDefaults]
1278                 boolForKey:MMDialogsTrackPwdKey];
1279         if (trackPwd)
1280             dir = [vimState objectForKey:@"pwd"];
1281     }
1283     if (saving) {
1284         NSSavePanel *panel = [NSSavePanel savePanel];
1286         // The delegate will be notified when the panel is expanded at which
1287         // time we may hide/show the "show hidden files" button (this button is
1288         // always visible for the open panel since it is always expanded).
1289         [panel setDelegate:self];
1290         if ([panel isExpanded])
1291             [panel setAccessoryView:showHiddenFilesView()];
1293         [panel beginSheetForDirectory:dir file:nil
1294                 modalForWindow:[windowController window]
1295                  modalDelegate:self
1296                 didEndSelector:@selector(savePanelDidEnd:code:context:)
1297                    contextInfo:NULL];
1298     } else {
1299         NSOpenPanel *panel = [NSOpenPanel openPanel];
1300         [panel setAllowsMultipleSelection:NO];
1301         [panel setAccessoryView:showHiddenFilesView()];
1303         [panel beginSheetForDirectory:dir file:nil types:nil
1304                 modalForWindow:[windowController window]
1305                  modalDelegate:self
1306                 didEndSelector:@selector(savePanelDidEnd:code:context:)
1307                    contextInfo:NULL];
1308     }
1311 - (void)handleShowDialog:(NSDictionary *)attr
1313     if (!isInitialized) return;
1315     NSArray *buttonTitles = [attr objectForKey:@"buttonTitles"];
1316     if (!(buttonTitles && [buttonTitles count])) return;
1318     int style = [[attr objectForKey:@"alertStyle"] intValue];
1319     NSString *message = [attr objectForKey:@"messageText"];
1320     NSString *text = [attr objectForKey:@"informativeText"];
1321     NSString *textFieldString = [attr objectForKey:@"textFieldString"];
1322     MMAlert *alert = [[MMAlert alloc] init];
1324     // NOTE! This has to be done before setting the informative text.
1325     if (textFieldString)
1326         [alert setTextFieldString:textFieldString];
1328     [alert setAlertStyle:style];
1330     if (message) {
1331         [alert setMessageText:message];
1332     } else {
1333         // If no message text is specified 'Alert' is used, which we don't
1334         // want, so set an empty string as message text.
1335         [alert setMessageText:@""];
1336     }
1338     if (text) {
1339         [alert setInformativeText:text];
1340     } else if (textFieldString) {
1341         // Make sure there is always room for the input text field.
1342         [alert setInformativeText:@""];
1343     }
1345     unsigned i, count = [buttonTitles count];
1346     for (i = 0; i < count; ++i) {
1347         NSString *title = [buttonTitles objectAtIndex:i];
1348         // NOTE: The title of the button may contain the character '&' to
1349         // indicate that the following letter should be the key equivalent
1350         // associated with the button.  Extract this letter and lowercase it.
1351         NSString *keyEquivalent = nil;
1352         NSRange hotkeyRange = [title rangeOfString:@"&"];
1353         if (NSNotFound != hotkeyRange.location) {
1354             if ([title length] > NSMaxRange(hotkeyRange)) {
1355                 NSRange keyEquivRange = NSMakeRange(hotkeyRange.location+1, 1);
1356                 keyEquivalent = [[title substringWithRange:keyEquivRange]
1357                     lowercaseString];
1358             }
1360             NSMutableString *string = [NSMutableString stringWithString:title];
1361             [string deleteCharactersInRange:hotkeyRange];
1362             title = string;
1363         }
1365         [alert addButtonWithTitle:title];
1367         // Set key equivalent for the button, but only if NSAlert hasn't
1368         // already done so.  (Check the documentation for
1369         // - [NSAlert addButtonWithTitle:] to see what key equivalents are
1370         // automatically assigned.)
1371         NSButton *btn = [[alert buttons] lastObject];
1372         if ([[btn keyEquivalent] length] == 0 && keyEquivalent) {
1373             [btn setKeyEquivalent:keyEquivalent];
1374         }
1375     }
1377     [alert beginSheetModalForWindow:[windowController window]
1378                       modalDelegate:self
1379                      didEndSelector:@selector(alertDidEnd:code:context:)
1380                         contextInfo:NULL];
1382     [alert release];
1386 @end // MMVimController (Private)
1391 @implementation MMAlert
1392 - (void)dealloc
1394     [textField release];  textField = nil;
1395     [super dealloc];
1398 - (void)setTextFieldString:(NSString *)textFieldString
1400     [textField release];
1401     textField = [[NSTextField alloc] init];
1402     [textField setStringValue:textFieldString];
1405 - (NSTextField *)textField
1407     return textField;
1410 - (void)setInformativeText:(NSString *)text
1412     if (textField) {
1413         // HACK! Add some space for the text field.
1414         [super setInformativeText:[text stringByAppendingString:@"\n\n\n"]];
1415     } else {
1416         [super setInformativeText:text];
1417     }
1420 - (void)beginSheetModalForWindow:(NSWindow *)window
1421                    modalDelegate:(id)delegate
1422                   didEndSelector:(SEL)didEndSelector
1423                      contextInfo:(void *)contextInfo
1425     [super beginSheetModalForWindow:window
1426                       modalDelegate:delegate
1427                      didEndSelector:didEndSelector
1428                         contextInfo:contextInfo];
1430     // HACK! Place the input text field at the bottom of the informative text
1431     // (which has been made a bit larger by adding newline characters).
1432     NSView *contentView = [[self window] contentView];
1433     NSRect rect = [contentView frame];
1434     rect.origin.y = rect.size.height;
1436     NSArray *subviews = [contentView subviews];
1437     unsigned i, count = [subviews count];
1438     for (i = 0; i < count; ++i) {
1439         NSView *view = [subviews objectAtIndex:i];
1440         if ([view isKindOfClass:[NSTextField class]]
1441                 && [view frame].origin.y < rect.origin.y) {
1442             // NOTE: The informative text field is the lowest NSTextField in
1443             // the alert dialog.
1444             rect = [view frame];
1445         }
1446     }
1448     rect.size.height = MMAlertTextFieldHeight;
1449     [textField setFrame:rect];
1450     [contentView addSubview:textField];
1451     [textField becomeFirstResponder];
1454 @end // MMAlert
1459     static BOOL
1460 isUnsafeMessage(int msgid)
1462     // Messages that may release Cocoa objects must be added to this list.  For
1463     // example, UpdateTabBarMsgID may delete NSTabViewItem objects so it goes
1464     // on this list.
1465     static int unsafeMessages[] = { // REASON MESSAGE IS ON THIS LIST:
1466         //OpenWindowMsgID,            // Changes lots of state
1467         UpdateTabBarMsgID,          // May delete NSTabViewItem
1468         RemoveMenuItemMsgID,        // Deletes NSMenuItem
1469         DestroyScrollbarMsgID,      // Deletes NSScroller
1470         ExecuteActionMsgID,         // Impossible to predict
1471         ShowPopupMenuMsgID,         // Enters modal loop
1472         ActivateMsgID,              // ?
1473         EnterFullscreenMsgID,       // Modifies delegate of window controller
1474         LeaveFullscreenMsgID,       // Modifies delegate of window controller
1475         CloseWindowMsgID,           // See note below
1476         BrowseForFileMsgID,         // Enters modal loop
1477         ShowDialogMsgID,            // Enters modal loop
1478     };
1480     // NOTE about CloseWindowMsgID: If this arrives at the same time as say
1481     // ExecuteActionMsgID, then the "execute" message will be lost due to it
1482     // being queued and handled after the "close" message has caused the
1483     // controller to cleanup...UNLESS we add CloseWindowMsgID to the list of
1484     // unsafe messages.  This is the _only_ reason it is on this list (since
1485     // all that happens in response to it is that we schedule another message
1486     // for later handling).
1488     int i, count = sizeof(unsafeMessages)/sizeof(unsafeMessages[0]);
1489     for (i = 0; i < count; ++i)
1490         if (msgid == unsafeMessages[i])
1491             return YES;
1493     return NO;