1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
3 * VIM - Vi IMproved by Bram Moolenaar
4 * MacVim GUI port by Bjorn Winckler
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.
13 * Coordinates input/output to/from backend. Each MMBackend communicates
14 * directly with a MMVimController.
16 * MMVimController does not deal with visual presentation. Essentially it
17 * should be able to run with no window present.
19 * Output from the backend is received in processCommandQueue:. Input is sent
20 * to the backend via sendMessage:data: or addVimInput:. The latter allows
21 * execution of arbitrary stings in the Vim process, much like the Vim script
22 * function remote_send() does. The messages that may be passed between
23 * frontend and backend are defined in an enum in MacVim.h.
26 #import "MMAppController.h"
27 #import "MMAtsuiTextView.h"
28 #import "MMFindReplaceController.h"
29 #import "MMTextView.h"
30 #import "MMVimController.h"
32 #import "MMWindowController.h"
33 #import "Miscellaneous.h"
35 #ifdef MM_ENABLE_PLUGINS
36 #import "MMPlugInManager.h"
39 static NSString *MMDefaultToolbarImageName = @"Attention";
40 static int MMAlertTextFieldHeight = 22;
42 // NOTE: By default a message sent to the backend will be dropped if it cannot
43 // be delivered instantly; otherwise there is a possibility that MacVim will
44 // 'beachball' while waiting to deliver DO messages to an unresponsive Vim
45 // process. This means that you cannot rely on any message sent with
46 // sendMessage: to actually reach Vim.
47 static NSTimeInterval MMBackendProxyRequestTimeout = 0;
49 // Timeout used for setDialogReturn:.
50 static NSTimeInterval MMSetDialogReturnTimeout = 1.0;
52 // Maximum number of items in the receiveQueue. (It is hard to predict what
53 // consequences changing this number will have.)
54 static int MMReceiveQueueCap = 100;
56 static BOOL isUnsafeMessage(int msgid);
59 @interface MMAlert : NSAlert {
60 NSTextField *textField;
62 - (void)setTextFieldString:(NSString *)textFieldString;
63 - (NSTextField *)textField;
67 @interface MMVimController (Private)
68 - (void)doProcessCommandQueue:(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
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
92 - (void)popupMenuWithDescriptor:(NSArray *)desc
94 column:(NSNumber *)col;
95 - (void)popupMenuWithAttributes:(NSDictionary *)attrs;
96 - (void)connectionDidDie:(NSNotification *)notification;
97 - (void)scheduleClose;
103 @implementation MMVimController
105 - (id)initWithBackend:(id)backend pid:(int)processIdentifier
107 if (!(self = [super init]))
111 [[MMWindowController alloc] initWithVimController:self];
112 backendProxy = [backend retain];
113 sendQueue = [NSMutableArray new];
114 receiveQueue = [NSMutableArray new];
115 popupMenuItems = [[NSMutableArray alloc] init];
116 toolbarItemDict = [[NSMutableDictionary alloc] init];
117 pid = processIdentifier;
118 creationDate = [[NSDate alloc] init];
120 NSConnection *connection = [backendProxy connectionForProxy];
122 // TODO: Check that this will not set the timeout for the root proxy
123 // (in MMAppController).
124 [connection setRequestTimeout:MMBackendProxyRequestTimeout];
126 [[NSNotificationCenter defaultCenter] addObserver:self
127 selector:@selector(connectionDidDie:)
128 name:NSConnectionDidDieNotification object:connection];
130 // Set up a main menu with only a "MacVim" menu (copied from a template
131 // which itself is set up in MainMenu.nib). The main menu is populated
133 mainMenu = [[NSMenu alloc] initWithTitle:@"MainMenu"];
134 NSMenuItem *appMenuItem = [[MMAppController sharedInstance]
135 appMenuItemTemplate];
136 appMenuItem = [[appMenuItem copy] autorelease];
138 // Note: If the title of the application menu is anything but what
139 // CFBundleName says then the application menu will not be typeset in
140 // boldface for some reason. (It should already be set when we copy
141 // from the default main menu, but this is not the case for some
143 NSString *appName = [[NSBundle mainBundle]
144 objectForInfoDictionaryKey:@"CFBundleName"];
145 [appMenuItem setTitle:appName];
147 [mainMenu addItem:appMenuItem];
149 #ifdef MM_ENABLE_PLUGINS
150 instanceMediator = [[MMPlugInInstanceMediator alloc]
151 initWithVimController:self];
165 #ifdef MM_ENABLE_PLUGINS
166 [instanceMediator release]; instanceMediator = nil;
169 [serverName release]; serverName = nil;
170 [backendProxy release]; backendProxy = nil;
171 [sendQueue release]; sendQueue = nil;
172 [receiveQueue release]; receiveQueue = nil;
174 [toolbarItemDict release]; toolbarItemDict = nil;
175 [toolbar release]; toolbar = nil;
176 [popupMenuItems release]; popupMenuItems = nil;
177 [windowController release]; windowController = nil;
179 [vimState release]; vimState = nil;
180 [mainMenu release]; mainMenu = nil;
181 [creationDate release]; creationDate = nil;
186 - (MMWindowController *)windowController
188 return windowController;
191 #ifdef MM_ENABLE_PLUGINS
192 - (MMPlugInInstanceMediator *)instanceMediator
194 return instanceMediator;
198 - (NSDictionary *)vimState
213 - (void)setIsPreloading:(BOOL)yn
218 - (NSDate *)creationDate
223 - (void)setServerName:(NSString *)name
225 if (name != serverName) {
226 [serverName release];
227 serverName = [name copy];
231 - (NSString *)serverName
241 - (void)dropFiles:(NSArray *)filenames forceOpen:(BOOL)force
243 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
245 // Default to opening in tabs if layout is invalid or set to "windows".
246 int layout = [ud integerForKey:MMOpenLayoutKey];
247 if (layout < 0 || layout > MMLayoutTabs)
248 layout = MMLayoutTabs;
250 NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
251 [NSNumber numberWithInt:layout], @"layout",
252 filenames, @"filenames",
253 [NSNumber numberWithBool:force], @"forceOpen",
256 [self sendMessage:DropFilesMsgID data:[args dictionaryAsData]];
259 - (void)file:(NSString *)filename draggedToTabAtIndex:(NSUInteger)tabIndex
261 NSString *fnEsc = [filename stringByEscapingSpecialFilenameCharacters];
262 NSString *input = [NSString stringWithFormat:@"<C-\\><C-N>:silent "
264 "edit! %@<CR>", tabIndex + 1, fnEsc];
265 [self addVimInput:input];
268 - (void)filesDraggedToTabBar:(NSArray *)filenames
270 NSUInteger i, count = [filenames count];
271 NSMutableString *input = [NSMutableString stringWithString:@"<C-\\><C-N>"
272 ":silent! tabnext 9999"];
273 for (i = 0; i < count; i++) {
274 NSString *fn = [filenames objectAtIndex:i];
275 NSString *fnEsc = [fn stringByEscapingSpecialFilenameCharacters];
276 [input appendFormat:@"|tabedit %@", fnEsc];
278 [input appendString:@"<CR>"];
279 [self addVimInput:input];
282 - (void)dropString:(NSString *)string
284 int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
286 NSMutableData *data = [NSMutableData data];
288 [data appendBytes:&len length:sizeof(int)];
289 [data appendBytes:[string UTF8String] length:len];
291 [self sendMessage:DropStringMsgID data:data];
295 - (void)passArguments:(NSDictionary *)args
299 [self sendMessage:OpenWithArgumentsMsgID data:[args dictionaryAsData]];
301 // HACK! Fool findUnusedEditor into thinking that this controller is not
302 // unused anymore, in case it is called before the arguments have reached
303 // the Vim process. This should be a "safe" hack since the next time the
304 // Vim process flushes its output queue the state will be updated again (at
305 // which time the "unusedEditor" state will have been properly set).
306 NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:
308 [dict setObject:[NSNumber numberWithBool:NO] forKey:@"unusedEditor"];
310 vimState = [dict copy];
313 - (void)sendMessage:(int)msgid data:(NSData *)data
315 //NSLog(@"sendMessage:%s (isInitialized=%d inProcessCommandQueue=%d)",
316 // MessageStrings[msgid], isInitialized, inProcessCommandQueue);
318 if (!isInitialized) return;
320 if (inProcessCommandQueue) {
321 //NSLog(@"In process command queue; delaying message send.");
322 [sendQueue addObject:[NSNumber numberWithInt:msgid]];
324 [sendQueue addObject:data];
326 [sendQueue addObject:[NSNull null]];
331 [backendProxy processInput:msgid data:data];
333 @catch (NSException *e) {
334 //NSLog(@"%@ %s Exception caught during DO call: %@",
335 // [self className], _cmd, e);
339 - (BOOL)sendMessageNow:(int)msgid data:(NSData *)data
340 timeout:(NSTimeInterval)timeout
342 // Send a message with a timeout. USE WITH EXTREME CAUTION! Sending
343 // messages in rapid succession with a timeout may cause MacVim to beach
344 // ball forever. In almost all circumstances sendMessage:data: should be
347 if (!isInitialized || inProcessCommandQueue)
350 if (timeout < 0) timeout = 0;
353 NSConnection *conn = [backendProxy connectionForProxy];
354 NSTimeInterval oldTimeout = [conn requestTimeout];
356 [conn setRequestTimeout:timeout];
359 [backendProxy processInput:msgid data:data];
361 @catch (NSException *e) {
365 [conn setRequestTimeout:oldTimeout];
371 - (void)addVimInput:(NSString *)string
373 // This is a very general method of adding input to the Vim process. It is
374 // basically the same as calling remote_send() on the process (see
375 // ':h remote_send').
377 NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
378 [self sendMessage:AddInputMsgID data:data];
382 - (NSString *)evaluateVimExpression:(NSString *)expr
384 NSString *eval = nil;
387 eval = [backendProxy evaluateExpression:expr];
389 @catch (NSException *ex) { /* do nothing */ }
394 - (id)evaluateVimExpressionCocoa:(NSString *)expr errorString:(NSString **)errstr
399 eval = [backendProxy evaluateExpressionCocoa:expr
401 } @catch (NSException *ex) {
402 *errstr = [ex reason];
415 if (!isInitialized) return;
418 [toolbar setDelegate:nil];
419 [[NSNotificationCenter defaultCenter] removeObserver:self];
420 //[[backendProxy connectionForProxy] invalidate];
421 //[windowController close];
422 [windowController cleanup];
425 - (oneway void)showSavePanelWithAttributes:(in bycopy NSDictionary *)attr
427 if (!isInitialized) return;
429 BOOL inDefaultMode = [[[NSRunLoop currentRunLoop] currentMode]
430 isEqual:NSDefaultRunLoopMode];
431 if (!inDefaultMode) {
432 // Delay call until run loop is in default mode.
433 [self performSelectorOnMainThread:
434 @selector(showSavePanelWithAttributes:)
437 modes:[NSArray arrayWithObject:
438 NSDefaultRunLoopMode]];
442 NSString *dir = [attr objectForKey:@"dir"];
443 BOOL saving = [[attr objectForKey:@"saving"] boolValue];
446 // 'dir == nil' means: set dir to the pwd of the Vim process, or let
447 // open dialog decide (depending on the below user default).
448 BOOL trackPwd = [[NSUserDefaults standardUserDefaults]
449 boolForKey:MMDialogsTrackPwdKey];
451 dir = [vimState objectForKey:@"pwd"];
455 [[NSSavePanel savePanel] beginSheetForDirectory:dir file:nil
456 modalForWindow:[windowController window]
458 didEndSelector:@selector(savePanelDidEnd:code:context:)
461 NSOpenPanel *panel = [NSOpenPanel openPanel];
462 [panel setAllowsMultipleSelection:NO];
463 [panel setAccessoryView:openPanelAccessoryView()];
465 [panel beginSheetForDirectory:dir file:nil types:nil
466 modalForWindow:[windowController window]
468 didEndSelector:@selector(savePanelDidEnd:code:context:)
473 - (oneway void)presentDialogWithAttributes:(in bycopy NSDictionary *)attr
475 if (!isInitialized) return;
477 BOOL inDefaultMode = [[[NSRunLoop currentRunLoop] currentMode]
478 isEqual:NSDefaultRunLoopMode];
479 if (!inDefaultMode) {
480 // Delay call until run loop is in default mode.
481 [self performSelectorOnMainThread:
482 @selector(presentDialogWithAttributes:)
485 modes:[NSArray arrayWithObject:
486 NSDefaultRunLoopMode]];
490 NSArray *buttonTitles = [attr objectForKey:@"buttonTitles"];
491 if (!(buttonTitles && [buttonTitles count])) return;
493 int style = [[attr objectForKey:@"alertStyle"] intValue];
494 NSString *message = [attr objectForKey:@"messageText"];
495 NSString *text = [attr objectForKey:@"informativeText"];
496 NSString *textFieldString = [attr objectForKey:@"textFieldString"];
497 MMAlert *alert = [[MMAlert alloc] init];
499 // NOTE! This has to be done before setting the informative text.
501 [alert setTextFieldString:textFieldString];
503 [alert setAlertStyle:style];
506 [alert setMessageText:message];
508 // If no message text is specified 'Alert' is used, which we don't
509 // want, so set an empty string as message text.
510 [alert setMessageText:@""];
514 [alert setInformativeText:text];
515 } else if (textFieldString) {
516 // Make sure there is always room for the input text field.
517 [alert setInformativeText:@""];
520 unsigned i, count = [buttonTitles count];
521 for (i = 0; i < count; ++i) {
522 NSString *title = [buttonTitles objectAtIndex:i];
523 // NOTE: The title of the button may contain the character '&' to
524 // indicate that the following letter should be the key equivalent
525 // associated with the button. Extract this letter and lowercase it.
526 NSString *keyEquivalent = nil;
527 NSRange hotkeyRange = [title rangeOfString:@"&"];
528 if (NSNotFound != hotkeyRange.location) {
529 if ([title length] > NSMaxRange(hotkeyRange)) {
530 NSRange keyEquivRange = NSMakeRange(hotkeyRange.location+1, 1);
531 keyEquivalent = [[title substringWithRange:keyEquivRange]
535 NSMutableString *string = [NSMutableString stringWithString:title];
536 [string deleteCharactersInRange:hotkeyRange];
540 [alert addButtonWithTitle:title];
542 // Set key equivalent for the button, but only if NSAlert hasn't
543 // already done so. (Check the documentation for
544 // - [NSAlert addButtonWithTitle:] to see what key equivalents are
545 // automatically assigned.)
546 NSButton *btn = [[alert buttons] lastObject];
547 if ([[btn keyEquivalent] length] == 0 && keyEquivalent) {
548 [btn setKeyEquivalent:keyEquivalent];
552 [alert beginSheetModalForWindow:[windowController window]
554 didEndSelector:@selector(alertDidEnd:code:context:)
560 - (oneway void)processCommandQueue:(in bycopy NSArray *)queue
562 if (!isInitialized) return;
564 if (inProcessCommandQueue) {
565 // NOTE! If a synchronous DO call is made during
566 // doProcessCommandQueue: below it may happen that this method is
567 // called a second time while the synchronous message is waiting for a
568 // reply (could also happen if doProcessCommandQueue: enters a modal
569 // loop, see comment below). Since this method cannot be considered
570 // reentrant, we queue the input and return immediately.
572 // If doProcessCommandQueue: enters a modal loop (happens e.g. on
573 // ShowPopupMenuMsgID) then the receiveQueue could grow to become
574 // arbitrarily large because DO calls still get processed. To avoid
575 // this we set a cap on the size of the queue and simply clear it if it
576 // becomes too large. (That is messages will be dropped and hence Vim
577 // and MacVim will at least temporarily be out of sync.)
578 if ([receiveQueue count] >= MMReceiveQueueCap)
579 [receiveQueue removeAllObjects];
581 [receiveQueue addObject:queue];
585 inProcessCommandQueue = YES;
586 [self doProcessCommandQueue:queue];
589 for (i = 0; i < [receiveQueue count]; ++i) {
590 // Note that doProcessCommandQueue: may cause the receiveQueue to grow
591 // or get cleared (due to cap being hit). Make sure to retain the item
592 // to process or it may get released from under us.
593 NSArray *q = [[receiveQueue objectAtIndex:i] retain];
594 [self doProcessCommandQueue:q];
598 // We assume that the remaining calls make no synchronous DO calls. If
599 // that did happen anyway, the command queue could get processed out of
602 // See comment below why this is called here and not later.
603 [windowController processCommandQueueDidFinish];
605 // NOTE: Ensure that no calls are made after this "if" clause that may call
606 // sendMessage::. If this happens anyway, such messages will be put on the
607 // send queue and then the queue will not be flushed until the next time
608 // this method is called.
609 if ([sendQueue count] > 0) {
611 [backendProxy processInputAndData:sendQueue];
613 @catch (NSException *e) {
614 // Connection timed out, just ignore this.
615 //NSLog(@"WARNING! Connection timed out in %s", _cmd);
618 [sendQueue removeAllObjects];
621 [receiveQueue removeAllObjects];
622 inProcessCommandQueue = NO;
625 - (NSToolbarItem *)toolbar:(NSToolbar *)theToolbar
626 itemForItemIdentifier:(NSString *)itemId
627 willBeInsertedIntoToolbar:(BOOL)flag
629 NSToolbarItem *item = [toolbarItemDict objectForKey:itemId];
631 NSLog(@"WARNING: No toolbar item with id '%@'", itemId);
637 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)theToolbar
642 - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)theToolbar
647 @end // MMVimController
651 @implementation MMVimController (Private)
653 - (void)doProcessCommandQueue:(NSArray *)queue
655 NSMutableArray *delayQueue = nil;
658 unsigned i, count = [queue count];
660 NSLog(@"WARNING: Uneven number of components (%d) in command "
661 "queue. Skipping...", count);
665 //NSLog(@"======== %s BEGIN ========", _cmd);
666 for (i = 0; i < count; i += 2) {
667 NSData *value = [queue objectAtIndex:i];
668 NSData *data = [queue objectAtIndex:i+1];
670 int msgid = *((int*)[value bytes]);
671 //NSLog(@"%s%s", _cmd, MessageStrings[msgid]);
673 BOOL inDefaultMode = [[[NSRunLoop currentRunLoop] currentMode]
674 isEqual:NSDefaultRunLoopMode];
675 if (!inDefaultMode && isUnsafeMessage(msgid)) {
676 // NOTE: Because we listen to DO messages in 'event tracking'
677 // mode we have to take extra care when doing things like
678 // releasing view items (and other Cocoa objects). Messages
679 // that may be potentially "unsafe" are delayed until the run
680 // loop is back to default mode at which time they are safe to
682 // A problem with this approach is that it is hard to
683 // classify which messages are unsafe. As a rule of thumb, if
684 // a message may release an object used by the Cocoa framework
685 // (e.g. views) then the message should be considered unsafe.
686 // Delaying messages may have undesired side-effects since it
687 // means that messages may not be processed in the order Vim
688 // sent them, so beware.
690 delayQueue = [NSMutableArray array];
692 //NSLog(@"Adding unsafe message '%s' to delay queue (mode=%@)",
693 // MessageStrings[msgid],
694 // [[NSRunLoop currentRunLoop] currentMode]);
695 [delayQueue addObject:value];
696 [delayQueue addObject:data];
698 [self handleMessage:msgid data:data];
701 //NSLog(@"======== %s END ========", _cmd);
703 @catch (NSException *e) {
704 NSLog(@"Exception caught whilst processing command queue: %@", e);
708 //NSLog(@" Flushing delay queue (%d items)", [delayQueue count]/2);
709 [self performSelectorOnMainThread:@selector(processCommandQueue:)
710 withObject:delayQueue
712 modes:[NSArray arrayWithObject:
713 NSDefaultRunLoopMode]];
717 - (void)handleMessage:(int)msgid data:(NSData *)data
719 //if (msgid != AddMenuMsgID && msgid != AddMenuItemMsgID &&
720 // msgid != EnableMenuItemMsgID)
721 // NSLog(@"%@ %s%s", [self className], _cmd, MessageStrings[msgid]);
723 if (OpenWindowMsgID == msgid) {
724 [windowController openWindow];
726 // If the vim controller is preloading then the window will be
727 // displayed when it is taken off the preload cache.
729 [windowController showWindow];
730 } else if (BatchDrawMsgID == msgid) {
731 [[[windowController vimView] textView] performBatchDrawWithData:data];
732 } else if (SelectTabMsgID == msgid) {
733 #if 0 // NOTE: Tab selection is done inside updateTabsWithData:.
734 const void *bytes = [data bytes];
735 int idx = *((int*)bytes);
736 //NSLog(@"Selecting tab with index %d", idx);
737 [windowController selectTabWithIndex:idx];
739 } else if (UpdateTabBarMsgID == msgid) {
740 [windowController updateTabsWithData:data];
741 } else if (ShowTabBarMsgID == msgid) {
742 [windowController showTabBar:YES];
743 } else if (HideTabBarMsgID == msgid) {
744 [windowController showTabBar:NO];
745 } else if (SetTextDimensionsMsgID == msgid || LiveResizeMsgID == msgid) {
746 const void *bytes = [data bytes];
747 int rows = *((int*)bytes); bytes += sizeof(int);
748 int cols = *((int*)bytes); bytes += sizeof(int);
750 [windowController setTextDimensionsWithRows:rows columns:cols
751 live:(LiveResizeMsgID==msgid)];
752 } else if (SetWindowTitleMsgID == msgid) {
753 const void *bytes = [data bytes];
754 int len = *((int*)bytes); bytes += sizeof(int);
756 NSString *string = [[NSString alloc] initWithBytes:(void*)bytes
757 length:len encoding:NSUTF8StringEncoding];
759 // While in live resize the window title displays the dimensions of the
760 // window so don't clobber this with a spurious "set title" message
762 if (![[windowController vimView] inLiveResize])
763 [windowController setTitle:string];
766 } else if (SetDocumentFilenameMsgID == msgid) {
767 const void *bytes = [data bytes];
768 int len = *((int*)bytes); bytes += sizeof(int);
771 NSString *filename = [[NSString alloc] initWithBytes:(void*)bytes
772 length:len encoding:NSUTF8StringEncoding];
774 [windowController setDocumentFilename:filename];
778 [windowController setDocumentFilename:@""];
780 } else if (AddMenuMsgID == msgid) {
781 NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
782 [self addMenuWithDescriptor:[attrs objectForKey:@"descriptor"]
783 atIndex:[[attrs objectForKey:@"index"] intValue]];
784 } else if (AddMenuItemMsgID == msgid) {
785 NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
786 [self addMenuItemWithDescriptor:[attrs objectForKey:@"descriptor"]
787 atIndex:[[attrs objectForKey:@"index"] intValue]
788 tip:[attrs objectForKey:@"tip"]
789 icon:[attrs objectForKey:@"icon"]
790 keyEquivalent:[attrs objectForKey:@"keyEquivalent"]
791 modifierMask:[[attrs objectForKey:@"modifierMask"] intValue]
792 action:[attrs objectForKey:@"action"]
793 isAlternate:[[attrs objectForKey:@"isAlternate"] boolValue]];
794 } else if (RemoveMenuItemMsgID == msgid) {
795 NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
796 [self removeMenuItemWithDescriptor:[attrs objectForKey:@"descriptor"]];
797 } else if (EnableMenuItemMsgID == msgid) {
798 NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
799 [self enableMenuItemWithDescriptor:[attrs objectForKey:@"descriptor"]
800 state:[[attrs objectForKey:@"enable"] boolValue]];
801 } else if (ShowToolbarMsgID == msgid) {
802 const void *bytes = [data bytes];
803 int enable = *((int*)bytes); bytes += sizeof(int);
804 int flags = *((int*)bytes); bytes += sizeof(int);
806 int mode = NSToolbarDisplayModeDefault;
807 if (flags & ToolbarLabelFlag) {
808 mode = flags & ToolbarIconFlag ? NSToolbarDisplayModeIconAndLabel
809 : NSToolbarDisplayModeLabelOnly;
810 } else if (flags & ToolbarIconFlag) {
811 mode = NSToolbarDisplayModeIconOnly;
814 int size = flags & ToolbarSizeRegularFlag ? NSToolbarSizeModeRegular
815 : NSToolbarSizeModeSmall;
817 [windowController showToolbar:enable size:size mode:mode];
818 } else if (CreateScrollbarMsgID == msgid) {
819 const void *bytes = [data bytes];
820 long ident = *((long*)bytes); bytes += sizeof(long);
821 int type = *((int*)bytes); bytes += sizeof(int);
823 [windowController createScrollbarWithIdentifier:ident type:type];
824 } else if (DestroyScrollbarMsgID == msgid) {
825 const void *bytes = [data bytes];
826 long ident = *((long*)bytes); bytes += sizeof(long);
828 [windowController destroyScrollbarWithIdentifier:ident];
829 } else if (ShowScrollbarMsgID == msgid) {
830 const void *bytes = [data bytes];
831 long ident = *((long*)bytes); bytes += sizeof(long);
832 int visible = *((int*)bytes); bytes += sizeof(int);
834 [windowController showScrollbarWithIdentifier:ident state:visible];
835 } else if (SetScrollbarPositionMsgID == msgid) {
836 const void *bytes = [data bytes];
837 long ident = *((long*)bytes); bytes += sizeof(long);
838 int pos = *((int*)bytes); bytes += sizeof(int);
839 int len = *((int*)bytes); bytes += sizeof(int);
841 [windowController setScrollbarPosition:pos length:len
843 } else if (SetScrollbarThumbMsgID == msgid) {
844 const void *bytes = [data bytes];
845 long ident = *((long*)bytes); bytes += sizeof(long);
846 float val = *((float*)bytes); bytes += sizeof(float);
847 float prop = *((float*)bytes); bytes += sizeof(float);
849 [windowController setScrollbarThumbValue:val proportion:prop
851 } else if (SetFontMsgID == msgid) {
852 const void *bytes = [data bytes];
853 float size = *((float*)bytes); bytes += sizeof(float);
854 int len = *((int*)bytes); bytes += sizeof(int);
855 NSString *name = [[NSString alloc]
856 initWithBytes:(void*)bytes length:len
857 encoding:NSUTF8StringEncoding];
858 NSFont *font = [NSFont fontWithName:name size:size];
861 [windowController setFont:font];
864 } else if (SetWideFontMsgID == msgid) {
865 const void *bytes = [data bytes];
866 float size = *((float*)bytes); bytes += sizeof(float);
867 int len = *((int*)bytes); bytes += sizeof(int);
869 NSString *name = [[NSString alloc]
870 initWithBytes:(void*)bytes length:len
871 encoding:NSUTF8StringEncoding];
872 NSFont *font = [NSFont fontWithName:name size:size];
873 [windowController setWideFont:font];
877 [windowController setWideFont:nil];
879 } else if (SetDefaultColorsMsgID == msgid) {
880 const void *bytes = [data bytes];
881 unsigned bg = *((unsigned*)bytes); bytes += sizeof(unsigned);
882 unsigned fg = *((unsigned*)bytes); bytes += sizeof(unsigned);
883 NSColor *back = [NSColor colorWithArgbInt:bg];
884 NSColor *fore = [NSColor colorWithRgbInt:fg];
886 [windowController setDefaultColorsBackground:back foreground:fore];
887 } else if (ExecuteActionMsgID == msgid) {
888 const void *bytes = [data bytes];
889 int len = *((int*)bytes); bytes += sizeof(int);
890 NSString *actionName = [[NSString alloc]
891 initWithBytes:(void*)bytes length:len
892 encoding:NSUTF8StringEncoding];
894 SEL sel = NSSelectorFromString(actionName);
895 [NSApp sendAction:sel to:nil from:self];
897 [actionName release];
898 } else if (ShowPopupMenuMsgID == msgid) {
899 NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
901 // The popup menu enters a modal loop so delay this call so that we
902 // don't block inside processCommandQueue:.
903 [self performSelectorOnMainThread:@selector(popupMenuWithAttributes:)
906 modes:[NSArray arrayWithObject:
907 NSDefaultRunLoopMode]];
908 } else if (SetMouseShapeMsgID == msgid) {
909 const void *bytes = [data bytes];
910 int shape = *((int*)bytes); bytes += sizeof(int);
912 [windowController setMouseShape:shape];
913 } else if (AdjustLinespaceMsgID == msgid) {
914 const void *bytes = [data bytes];
915 int linespace = *((int*)bytes); bytes += sizeof(int);
917 [windowController adjustLinespace:linespace];
918 } else if (ActivateMsgID == msgid) {
919 //NSLog(@"ActivateMsgID");
920 [NSApp activateIgnoringOtherApps:YES];
921 [[windowController window] makeKeyAndOrderFront:self];
922 } else if (SetServerNameMsgID == msgid) {
923 NSString *name = [[NSString alloc] initWithData:data
924 encoding:NSUTF8StringEncoding];
925 [self setServerName:name];
927 } else if (EnterFullscreenMsgID == msgid) {
928 const void *bytes = [data bytes];
929 int fuoptions = *((int*)bytes); bytes += sizeof(int);
930 int bg = *((int*)bytes);
931 NSColor *back = [NSColor colorWithArgbInt:bg];
933 [windowController enterFullscreen:fuoptions backgroundColor:back];
934 } else if (LeaveFullscreenMsgID == msgid) {
935 [windowController leaveFullscreen];
936 } else if (BuffersNotModifiedMsgID == msgid) {
937 [windowController setBuffersModified:NO];
938 } else if (BuffersModifiedMsgID == msgid) {
939 [windowController setBuffersModified:YES];
940 } else if (SetPreEditPositionMsgID == msgid) {
941 const int *dim = (const int*)[data bytes];
942 [[[windowController vimView] textView] setPreEditRow:dim[0]
944 } else if (EnableAntialiasMsgID == msgid) {
945 [[[windowController vimView] textView] setAntialias:YES];
946 } else if (DisableAntialiasMsgID == msgid) {
947 [[[windowController vimView] textView] setAntialias:NO];
948 } else if (SetVimStateMsgID == msgid) {
949 NSDictionary *dict = [NSDictionary dictionaryWithData:data];
952 vimState = [dict retain];
954 } else if (CloseWindowMsgID == msgid) {
955 [self scheduleClose];
956 } else if (SetFullscreenColorMsgID == msgid) {
957 const int *bg = (const int*)[data bytes];
958 NSColor *color = [NSColor colorWithRgbInt:*bg];
960 [windowController setFullscreenBackgroundColor:color];
961 } else if (ShowFindReplaceDialogMsgID == msgid) {
962 NSDictionary *dict = [NSDictionary dictionaryWithData:data];
964 [[MMFindReplaceController sharedInstance]
965 showWithText:[dict objectForKey:@"text"]
966 flags:[[dict objectForKey:@"flags"] intValue]];
968 // IMPORTANT: When adding a new message, make sure to update
969 // isUnsafeMessage() if necessary!
971 NSLog(@"WARNING: Unknown message received (msgid=%d)", msgid);
975 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
976 context:(void *)context
978 NSString *path = (code == NSOKButton) ? [panel filename] : nil;
980 // NOTE! setDialogReturn: is a synchronous call so set a proper timeout to
981 // avoid waiting forever for it to finish. We make this a synchronous call
982 // so that we can be fairly certain that Vim doesn't think the dialog box
983 // is still showing when MacVim has in fact already dismissed it.
984 NSConnection *conn = [backendProxy connectionForProxy];
985 NSTimeInterval oldTimeout = [conn requestTimeout];
986 [conn setRequestTimeout:MMSetDialogReturnTimeout];
989 [backendProxy setDialogReturn:path];
991 // Add file to the "Recent Files" menu (this ensures that files that
992 // are opened/saved from a :browse command are added to this menu).
994 [[NSDocumentController sharedDocumentController]
995 noteNewRecentFilePath:path];
997 @catch (NSException *e) {
998 NSLog(@"Exception caught in %s %@", _cmd, e);
1001 [conn setRequestTimeout:oldTimeout];
1005 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context
1009 code = code - NSAlertFirstButtonReturn + 1;
1011 if ([alert isKindOfClass:[MMAlert class]] && [alert textField]) {
1012 ret = [NSArray arrayWithObjects:[NSNumber numberWithInt:code],
1013 [[alert textField] stringValue], nil];
1015 ret = [NSArray arrayWithObject:[NSNumber numberWithInt:code]];
1019 [backendProxy setDialogReturn:ret];
1021 @catch (NSException *e) {
1022 NSLog(@"Exception caught in %s %@", _cmd, e);
1026 - (NSMenuItem *)menuItemForDescriptor:(NSArray *)desc
1028 if (!(desc && [desc count] > 0)) return nil;
1030 NSString *rootName = [desc objectAtIndex:0];
1031 NSArray *rootItems = [rootName hasPrefix:@"PopUp"] ? popupMenuItems
1032 : [mainMenu itemArray];
1034 NSMenuItem *item = nil;
1035 int i, count = [rootItems count];
1036 for (i = 0; i < count; ++i) {
1037 item = [rootItems objectAtIndex:i];
1038 if ([[item title] isEqual:rootName])
1042 if (i == count) return nil;
1044 count = [desc count];
1045 for (i = 1; i < count; ++i) {
1046 item = [[item submenu] itemWithTitle:[desc objectAtIndex:i]];
1047 if (!item) return nil;
1053 - (NSMenu *)parentMenuForDescriptor:(NSArray *)desc
1055 if (!(desc && [desc count] > 0)) return nil;
1057 NSString *rootName = [desc objectAtIndex:0];
1058 NSArray *rootItems = [rootName hasPrefix:@"PopUp"] ? popupMenuItems
1059 : [mainMenu itemArray];
1062 int i, count = [rootItems count];
1063 for (i = 0; i < count; ++i) {
1064 NSMenuItem *item = [rootItems objectAtIndex:i];
1065 if ([[item title] isEqual:rootName]) {
1066 menu = [item submenu];
1071 if (!menu) return nil;
1073 count = [desc count] - 1;
1074 for (i = 1; i < count; ++i) {
1075 NSMenuItem *item = [menu itemWithTitle:[desc objectAtIndex:i]];
1076 menu = [item submenu];
1077 if (!menu) return nil;
1083 - (NSMenu *)topLevelMenuForTitle:(NSString *)title
1085 // Search only the top-level menus.
1087 unsigned i, count = [popupMenuItems count];
1088 for (i = 0; i < count; ++i) {
1089 NSMenuItem *item = [popupMenuItems objectAtIndex:i];
1090 if ([title isEqual:[item title]])
1091 return [item submenu];
1094 count = [mainMenu numberOfItems];
1095 for (i = 0; i < count; ++i) {
1096 NSMenuItem *item = [mainMenu itemAtIndex:i];
1097 if ([title isEqual:[item title]])
1098 return [item submenu];
1104 - (void)addMenuWithDescriptor:(NSArray *)desc atIndex:(int)idx
1106 if (!(desc && [desc count] > 0 && idx >= 0)) return;
1108 NSString *rootName = [desc objectAtIndex:0];
1109 if ([rootName isEqual:@"ToolBar"]) {
1110 // The toolbar only has one menu, we take this as a hint to create a
1111 // toolbar, then we return.
1113 // NOTE! Each toolbar must have a unique identifier, else each
1114 // window will have the same toolbar.
1115 NSString *ident = [NSString stringWithFormat:@"%d", (int)self];
1116 toolbar = [[NSToolbar alloc] initWithIdentifier:ident];
1118 [toolbar setShowsBaselineSeparator:NO];
1119 [toolbar setDelegate:self];
1120 [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
1121 [toolbar setSizeMode:NSToolbarSizeModeSmall];
1123 [windowController setToolbar:toolbar];
1129 // This is either a main menu item or a popup menu item.
1130 NSString *title = [desc lastObject];
1131 NSMenuItem *item = [[NSMenuItem alloc] init];
1132 NSMenu *menu = [[NSMenu alloc] initWithTitle:title];
1134 [item setTitle:title];
1135 [item setSubmenu:menu];
1137 NSMenu *parent = [self parentMenuForDescriptor:desc];
1138 if (!parent && [rootName hasPrefix:@"PopUp"]) {
1139 if ([popupMenuItems count] <= idx) {
1140 [popupMenuItems addObject:item];
1142 [popupMenuItems insertObject:item atIndex:idx];
1145 // If descriptor has no parent and its not a popup (or toolbar) menu,
1146 // then it must belong to main menu.
1147 if (!parent) parent = mainMenu;
1149 if ([parent numberOfItems] <= idx) {
1150 [parent addItem:item];
1152 [parent insertItem:item atIndex:idx];
1160 - (void)addMenuItemWithDescriptor:(NSArray *)desc
1163 icon:(NSString *)icon
1164 keyEquivalent:(NSString *)keyEquivalent
1165 modifierMask:(int)modifierMask
1166 action:(NSString *)action
1167 isAlternate:(BOOL)isAlternate
1169 if (!(desc && [desc count] > 1 && idx >= 0)) return;
1171 NSString *title = [desc lastObject];
1172 NSString *rootName = [desc objectAtIndex:0];
1174 if ([rootName isEqual:@"ToolBar"]) {
1175 if (toolbar && [desc count] == 2)
1176 [self addToolbarItemWithLabel:title tip:tip icon:icon atIndex:idx];
1180 NSMenu *parent = [self parentMenuForDescriptor:desc];
1182 NSLog(@"WARNING: Menu item '%@' has no parent",
1183 [desc componentsJoinedByString:@"->"]);
1187 NSMenuItem *item = nil;
1188 if (0 == [title length]
1189 || ([title hasPrefix:@"-"] && [title hasSuffix:@"-"])) {
1190 item = [NSMenuItem separatorItem];
1191 [item setTitle:title];
1193 item = [[[NSMenuItem alloc] init] autorelease];
1194 [item setTitle:title];
1196 // Note: It is possible to set the action to a message that "doesn't
1197 // exist" without problems. We take advantage of this when adding
1198 // "dummy items" e.g. when dealing with the "Recent Files" menu (in
1199 // which case a recentFilesDummy: action is set, although it is never
1201 if ([action length] > 0)
1202 [item setAction:NSSelectorFromString(action)];
1204 [item setAction:@selector(vimMenuItemAction:)];
1205 if ([tip length] > 0) [item setToolTip:tip];
1206 if ([keyEquivalent length] > 0) {
1207 [item setKeyEquivalent:keyEquivalent];
1208 [item setKeyEquivalentModifierMask:modifierMask];
1210 [item setAlternate:isAlternate];
1212 // The tag is used to indicate whether Vim thinks a menu item should be
1213 // enabled or disabled. By default Vim thinks menu items are enabled.
1217 if ([parent numberOfItems] <= idx) {
1218 [parent addItem:item];
1220 [parent insertItem:item atIndex:idx];
1224 - (void)removeMenuItemWithDescriptor:(NSArray *)desc
1226 if (!(desc && [desc count] > 0)) return;
1228 NSString *title = [desc lastObject];
1229 NSString *rootName = [desc objectAtIndex:0];
1230 if ([rootName isEqual:@"ToolBar"]) {
1232 // Only remove toolbar items, never actually remove the toolbar
1233 // itself or strange things may happen.
1234 if ([desc count] == 2) {
1235 int idx = [toolbar indexOfItemWithItemIdentifier:title];
1236 if (idx != NSNotFound)
1237 [toolbar removeItemAtIndex:idx];
1243 NSMenuItem *item = [self menuItemForDescriptor:desc];
1245 NSLog(@"Failed to remove menu item, descriptor not found: %@",
1246 [desc componentsJoinedByString:@"->"]);
1252 if ([item menu] == [NSApp mainMenu] || ![item menu]) {
1253 // NOTE: To be on the safe side we try to remove the item from
1254 // both arrays (it is ok to call removeObject: even if an array
1255 // does not contain the object to remove).
1256 [popupMenuItems removeObject:item];
1260 [[item menu] removeItem:item];
1265 - (void)enableMenuItemWithDescriptor:(NSArray *)desc state:(BOOL)on
1267 if (!(desc && [desc count] > 0)) return;
1269 /*NSLog(@"%sable item %@", on ? "En" : "Dis",
1270 [desc componentsJoinedByString:@"->"]);*/
1272 NSString *rootName = [desc objectAtIndex:0];
1273 if ([rootName isEqual:@"ToolBar"]) {
1274 if (toolbar && [desc count] == 2) {
1275 NSString *title = [desc lastObject];
1276 [[toolbar itemWithItemIdentifier:title] setEnabled:on];
1279 // Use tag to set whether item is enabled or disabled instead of
1280 // calling setEnabled:. This way the menus can autoenable themselves
1281 // but at the same time Vim can set if a menu is enabled whenever it
1283 [[self menuItemForDescriptor:desc] setTag:on];
1287 - (void)addToolbarItemToDictionaryWithLabel:(NSString *)title
1288 toolTip:(NSString *)tip
1289 icon:(NSString *)icon
1291 // If the item corresponds to a separator then do nothing, since it is
1292 // already defined by Cocoa.
1293 if (!title || [title isEqual:NSToolbarSeparatorItemIdentifier]
1294 || [title isEqual:NSToolbarSpaceItemIdentifier]
1295 || [title isEqual:NSToolbarFlexibleSpaceItemIdentifier])
1298 NSToolbarItem *item = [[NSToolbarItem alloc] initWithItemIdentifier:title];
1299 [item setLabel:title];
1300 [item setToolTip:tip];
1301 [item setAction:@selector(vimToolbarItemAction:)];
1302 [item setAutovalidates:NO];
1304 NSImage *img = [NSImage imageNamed:icon];
1306 img = [[[NSImage alloc] initByReferencingFile:icon] autorelease];
1307 if (!(img && [img isValid]))
1311 NSLog(@"WARNING: Could not find image with name '%@' to use as toolbar"
1312 " image for identifier '%@';"
1313 " using default toolbar icon '%@' instead.",
1314 icon, title, MMDefaultToolbarImageName);
1316 img = [NSImage imageNamed:MMDefaultToolbarImageName];
1319 [item setImage:img];
1321 [toolbarItemDict setObject:item forKey:title];
1326 - (void)addToolbarItemWithLabel:(NSString *)label
1328 icon:(NSString *)icon
1331 if (!toolbar) return;
1333 // Check for separator items.
1335 label = NSToolbarSeparatorItemIdentifier;
1336 } else if ([label length] >= 2 && [label hasPrefix:@"-"]
1337 && [label hasSuffix:@"-"]) {
1338 // The label begins and ends with '-'; decided which kind of separator
1339 // item it is by looking at the prefix.
1340 if ([label hasPrefix:@"-space"]) {
1341 label = NSToolbarSpaceItemIdentifier;
1342 } else if ([label hasPrefix:@"-flexspace"]) {
1343 label = NSToolbarFlexibleSpaceItemIdentifier;
1345 label = NSToolbarSeparatorItemIdentifier;
1349 [self addToolbarItemToDictionaryWithLabel:label toolTip:tip icon:icon];
1351 int maxIdx = [[toolbar items] count];
1352 if (maxIdx < idx) idx = maxIdx;
1354 [toolbar insertItemWithItemIdentifier:label atIndex:idx];
1357 - (void)popupMenuWithDescriptor:(NSArray *)desc
1358 atRow:(NSNumber *)row
1359 column:(NSNumber *)col
1361 NSMenu *menu = [[self menuItemForDescriptor:desc] submenu];
1364 id textView = [[windowController vimView] textView];
1367 // TODO: Let textView convert (row,col) to NSPoint.
1368 int r = [row intValue];
1369 int c = [col intValue];
1370 NSSize cellSize = [textView cellSize];
1371 pt = NSMakePoint((c+1)*cellSize.width, (r+1)*cellSize.height);
1372 pt = [textView convertPoint:pt toView:nil];
1374 pt = [[windowController window] mouseLocationOutsideOfEventStream];
1377 NSEvent *event = [NSEvent mouseEventWithType:NSRightMouseDown
1381 windowNumber:[[windowController window] windowNumber]
1387 [NSMenu popUpContextMenu:menu withEvent:event forView:textView];
1390 - (void)popupMenuWithAttributes:(NSDictionary *)attrs
1394 [self popupMenuWithDescriptor:[attrs objectForKey:@"descriptor"]
1395 atRow:[attrs objectForKey:@"row"]
1396 column:[attrs objectForKey:@"column"]];
1399 - (void)connectionDidDie:(NSNotification *)notification
1401 //NSLog(@"%@ %s%@", [self className], _cmd, notification);
1402 [self scheduleClose];
1405 - (void)scheduleClose
1407 // NOTE! This message can arrive at pretty much anytime, e.g. while
1408 // the run loop is the 'event tracking' mode. This means that Cocoa may
1409 // well be in the middle of processing some message while this message is
1410 // received. If we were to remove the vim controller straight away we may
1411 // free objects that Cocoa is currently using (e.g. view objects). The
1412 // following call ensures that the vim controller is not released until the
1413 // run loop is back in the 'default' mode.
1414 [[MMAppController sharedInstance]
1415 performSelectorOnMainThread:@selector(removeVimController:)
1418 modes:[NSArray arrayWithObject:
1419 NSDefaultRunLoopMode]];
1422 @end // MMVimController (Private)
1427 @implementation MMAlert
1430 [textField release]; textField = nil;
1434 - (void)setTextFieldString:(NSString *)textFieldString
1436 [textField release];
1437 textField = [[NSTextField alloc] init];
1438 [textField setStringValue:textFieldString];
1441 - (NSTextField *)textField
1446 - (void)setInformativeText:(NSString *)text
1449 // HACK! Add some space for the text field.
1450 [super setInformativeText:[text stringByAppendingString:@"\n\n\n"]];
1452 [super setInformativeText:text];
1456 - (void)beginSheetModalForWindow:(NSWindow *)window
1457 modalDelegate:(id)delegate
1458 didEndSelector:(SEL)didEndSelector
1459 contextInfo:(void *)contextInfo
1461 [super beginSheetModalForWindow:window
1462 modalDelegate:delegate
1463 didEndSelector:didEndSelector
1464 contextInfo:contextInfo];
1466 // HACK! Place the input text field at the bottom of the informative text
1467 // (which has been made a bit larger by adding newline characters).
1468 NSView *contentView = [[self window] contentView];
1469 NSRect rect = [contentView frame];
1470 rect.origin.y = rect.size.height;
1472 NSArray *subviews = [contentView subviews];
1473 unsigned i, count = [subviews count];
1474 for (i = 0; i < count; ++i) {
1475 NSView *view = [subviews objectAtIndex:i];
1476 if ([view isKindOfClass:[NSTextField class]]
1477 && [view frame].origin.y < rect.origin.y) {
1478 // NOTE: The informative text field is the lowest NSTextField in
1479 // the alert dialog.
1480 rect = [view frame];
1484 rect.size.height = MMAlertTextFieldHeight;
1485 [textField setFrame:rect];
1486 [contentView addSubview:textField];
1487 [textField becomeFirstResponder];
1496 isUnsafeMessage(int msgid)
1498 // Messages that may release Cocoa objects must be added to this list. For
1499 // example, UpdateTabBarMsgID may delete NSTabViewItem objects so it goes
1501 static int unsafeMessages[] = { // REASON MESSAGE IS ON THIS LIST:
1502 //OpenWindowMsgID, // Changes lots of state
1503 UpdateTabBarMsgID, // May delete NSTabViewItem
1504 RemoveMenuItemMsgID, // Deletes NSMenuItem
1505 DestroyScrollbarMsgID, // Deletes NSScroller
1506 ExecuteActionMsgID, // Impossible to predict
1507 ShowPopupMenuMsgID, // Enters modal loop
1509 EnterFullscreenMsgID, // Modifies delegate of window controller
1510 LeaveFullscreenMsgID, // Modifies delegate of window controller
1511 CloseWindowMsgID, // See note below
1514 // NOTE about CloseWindowMsgID: If this arrives at the same time as say
1515 // ExecuteActionMsgID, then the "execute" message will be lost due to it
1516 // being queued and handled after the "close" message has caused the
1517 // controller to cleanup...UNLESS we add CloseWindowMsgID to the list of
1518 // unsafe messages. This is the _only_ reason it is on this list (since
1519 // all that happens in response to it is that we schedule another message
1520 // for later handling).
1522 int i, count = sizeof(unsafeMessages)/sizeof(unsafeMessages[0]);
1523 for (i = 0; i < count; ++i)
1524 if (msgid == unsafeMessages[i])