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. 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
18 * MMVimController does not deal with visual presentation. Essentially it
19 * should be able to run with no window present.
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.
29 #import "MMAppController.h"
30 #import "MMAtsuiTextView.h"
31 #import "MMFindReplaceController.h"
32 #import "MMTextView.h"
33 #import "MMVimController.h"
35 #import "MMWindowController.h"
36 #import "Miscellaneous.h"
38 #ifdef MM_ENABLE_PLUGINS
39 #import "MMPlugInManager.h"
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;
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
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
93 - (void)popupMenuWithDescriptor:(NSArray *)desc
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;
106 @implementation MMVimController
108 - (id)initWithBackend:(id)backend pid:(int)processIdentifier
110 if (!(self = [super init]))
113 // TODO: Come up with a better way of creating an identifier.
114 identifier = identifierCounter++;
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
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
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];
169 #ifdef MM_ENABLE_PLUGINS
170 [instanceMediator release]; instanceMediator = nil;
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;
188 - (unsigned)identifier
193 - (MMWindowController *)windowController
195 return windowController;
198 #ifdef MM_ENABLE_PLUGINS
199 - (MMPlugInInstanceMediator *)instanceMediator
201 return instanceMediator;
205 - (NSDictionary *)vimState
210 - (id)objectForVimStateKey:(NSString *)key
212 return [vimState objectForKey:key];
225 - (void)setIsPreloading:(BOOL)yn
230 - (NSDate *)creationDate
235 - (void)setServerName:(NSString *)name
237 if (name != serverName) {
238 [serverName release];
239 serverName = [name copy];
243 - (NSString *)serverName
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",
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 "
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];
294 [input appendString:@"<CR>"];
295 [self addVimInput:input];
298 - (void)dropString:(NSString *)string
300 int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
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];
311 - (void)passArguments:(NSDictionary *)args
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:
324 [dict setObject:[NSNumber numberWithBool:NO] forKey:@"unusedEditor"];
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;
337 [backendProxy processInput:msgid data:data];
339 @catch (NSException *e) {
340 //NSLog(@"%@ %s Exception caught during DO call: %@",
341 // [self className], _cmd, e);
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
356 if (timeout < 0) timeout = 0;
359 NSConnection *conn = [backendProxy connectionForProxy];
360 NSTimeInterval oldTimeout = [conn requestTimeout];
362 [conn setRequestTimeout:timeout];
365 [backendProxy processInput:msgid data:data];
367 @catch (NSException *e) {
371 [conn setRequestTimeout:oldTimeout];
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').
383 NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
384 [self sendMessage:AddInputMsgID data:data];
388 - (NSString *)evaluateVimExpression:(NSString *)expr
390 NSString *eval = nil;
393 eval = [backendProxy evaluateExpression:expr];
395 @catch (NSException *ex) { /* do nothing */ }
400 - (id)evaluateVimExpressionCocoa:(NSString *)expr
401 errorString:(NSString **)errstr
406 eval = [backendProxy evaluateExpressionCocoa:expr
408 } @catch (NSException *ex) {
409 *errstr = [ex reason];
422 if (!isInitialized) return;
424 // Remove any delayed calls made on this object.
425 [NSObject cancelPreviousPerformRequestsWithTarget:self];
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
442 [self doProcessInputQueue:queue];
443 [windowController processInputQueueDidFinish];
445 @catch (NSException *ex) {
446 NSLog(@"[%s] Caught exception (pid=%d): %@", _cmd, pid, ex);
450 - (NSToolbarItem *)toolbar:(NSToolbar *)theToolbar
451 itemForItemIdentifier:(NSString *)itemId
452 willBeInsertedIntoToolbar:(BOOL)flag
454 NSToolbarItem *item = [toolbarItemDict objectForKey:itemId];
456 NSLog(@"WARNING: No toolbar item with id '%@'", itemId);
462 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)theToolbar
467 - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)theToolbar
472 @end // MMVimController
476 @implementation MMVimController (Private)
478 - (void)doProcessInputQueue:(NSArray *)queue
480 NSMutableArray *delayQueue = nil;
482 unsigned i, count = [queue count];
484 NSLog(@"WARNING: Uneven number of components (%d) in command "
485 "queue. Skipping...", count);
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.
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];
522 [self handleMessage:msgid data:data];
525 //NSLog(@"======== %s END ========", _cmd);
528 //NSLog(@" Flushing delay queue (%d items)", [delayQueue count]/2);
529 [self performSelector:@selector(processInputQueue:)
530 withObject:delayQueue
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.
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];
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
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
583 if (![[windowController vimView] inLiveResize])
584 [windowController setTitle:string];
587 } else if (SetDocumentFilenameMsgID == msgid) {
588 const void *bytes = [data bytes];
589 int len = *((int*)bytes); bytes += sizeof(int);
592 NSString *filename = [[NSString alloc] initWithBytes:(void*)bytes
593 length:len encoding:NSUTF8StringEncoding];
595 [windowController setDocumentFilename:filename];
599 [windowController setDocumentFilename:@""];
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;
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
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
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];
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
684 font = [NSFont userFixedPitchFontOfSize:size];
687 [windowController setFont:font];
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);
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];
702 [windowController setWideFont:nil];
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:)
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];
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]
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];
775 vimState = [dict retain];
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];
787 [[MMFindReplaceController sharedInstance]
788 showWithText:[dict objectForKey:@"text"]
789 flags:[[dict objectForKey:@"flags"] intValue]];
791 } else if (ActivateKeyScriptMsgID == msgid) {
792 KeyScript(smKeySysScript);
793 } else if (DeactivateKeyScriptMsgID == msgid) {
794 KeyScript(smKeyRoman);
795 } else if (EnableImControlMsgID == msgid) {
796 [[[windowController vimView] textView] setImControl:YES];
797 } else if (DisableImControlMsgID == msgid) {
798 [[[windowController vimView] textView] setImControl:NO];
799 } else if (BrowseForFileMsgID == msgid) {
800 NSDictionary *dict = [NSDictionary dictionaryWithData:data];
802 [self handleBrowseForFile:dict];
803 } else if (ShowDialogMsgID == msgid) {
804 NSDictionary *dict = [NSDictionary dictionaryWithData:data];
806 [self handleShowDialog:dict];
807 // IMPORTANT: When adding a new message, make sure to update
808 // isUnsafeMessage() if necessary!
810 NSLog(@"WARNING: Unknown message received (msgid=%d)", msgid);
814 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
815 context:(void *)context
817 NSString *path = (code == NSOKButton) ? [panel filename] : nil;
819 // NOTE! setDialogReturn: is a synchronous call so set a proper timeout to
820 // avoid waiting forever for it to finish. We make this a synchronous call
821 // so that we can be fairly certain that Vim doesn't think the dialog box
822 // is still showing when MacVim has in fact already dismissed it.
823 NSConnection *conn = [backendProxy connectionForProxy];
824 NSTimeInterval oldTimeout = [conn requestTimeout];
825 [conn setRequestTimeout:MMSetDialogReturnTimeout];
828 [backendProxy setDialogReturn:path];
830 // Add file to the "Recent Files" menu (this ensures that files that
831 // are opened/saved from a :browse command are added to this menu).
833 [[NSDocumentController sharedDocumentController]
834 noteNewRecentFilePath:path];
836 @catch (NSException *e) {
837 NSLog(@"Exception caught in %s %@", _cmd, e);
840 [conn setRequestTimeout:oldTimeout];
844 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context
848 code = code - NSAlertFirstButtonReturn + 1;
850 if ([alert isKindOfClass:[MMAlert class]] && [alert textField]) {
851 ret = [NSArray arrayWithObjects:[NSNumber numberWithInt:code],
852 [[alert textField] stringValue], nil];
854 ret = [NSArray arrayWithObject:[NSNumber numberWithInt:code]];
858 [backendProxy setDialogReturn:ret];
860 @catch (NSException *e) {
861 NSLog(@"Exception caught in %s %@", _cmd, e);
865 - (NSMenuItem *)menuItemForDescriptor:(NSArray *)desc
867 if (!(desc && [desc count] > 0)) return nil;
869 NSString *rootName = [desc objectAtIndex:0];
870 NSArray *rootItems = [rootName hasPrefix:@"PopUp"] ? popupMenuItems
871 : [mainMenu itemArray];
873 NSMenuItem *item = nil;
874 int i, count = [rootItems count];
875 for (i = 0; i < count; ++i) {
876 item = [rootItems objectAtIndex:i];
877 if ([[item title] isEqual:rootName])
881 if (i == count) return nil;
883 count = [desc count];
884 for (i = 1; i < count; ++i) {
885 item = [[item submenu] itemWithTitle:[desc objectAtIndex:i]];
886 if (!item) return nil;
892 - (NSMenu *)parentMenuForDescriptor:(NSArray *)desc
894 if (!(desc && [desc count] > 0)) return nil;
896 NSString *rootName = [desc objectAtIndex:0];
897 NSArray *rootItems = [rootName hasPrefix:@"PopUp"] ? popupMenuItems
898 : [mainMenu itemArray];
901 int i, count = [rootItems count];
902 for (i = 0; i < count; ++i) {
903 NSMenuItem *item = [rootItems objectAtIndex:i];
904 if ([[item title] isEqual:rootName]) {
905 menu = [item submenu];
910 if (!menu) return nil;
912 count = [desc count] - 1;
913 for (i = 1; i < count; ++i) {
914 NSMenuItem *item = [menu itemWithTitle:[desc objectAtIndex:i]];
915 menu = [item submenu];
916 if (!menu) return nil;
922 - (NSMenu *)topLevelMenuForTitle:(NSString *)title
924 // Search only the top-level menus.
926 unsigned i, count = [popupMenuItems count];
927 for (i = 0; i < count; ++i) {
928 NSMenuItem *item = [popupMenuItems objectAtIndex:i];
929 if ([title isEqual:[item title]])
930 return [item submenu];
933 count = [mainMenu numberOfItems];
934 for (i = 0; i < count; ++i) {
935 NSMenuItem *item = [mainMenu itemAtIndex:i];
936 if ([title isEqual:[item title]])
937 return [item submenu];
943 - (void)addMenuWithDescriptor:(NSArray *)desc atIndex:(int)idx
945 if (!(desc && [desc count] > 0 && idx >= 0)) return;
947 NSString *rootName = [desc objectAtIndex:0];
948 if ([rootName isEqual:@"ToolBar"]) {
949 // The toolbar only has one menu, we take this as a hint to create a
950 // toolbar, then we return.
952 // NOTE! Each toolbar must have a unique identifier, else each
953 // window will have the same toolbar.
954 NSString *ident = [NSString stringWithFormat:@"%d", (int)self];
955 toolbar = [[NSToolbar alloc] initWithIdentifier:ident];
957 [toolbar setShowsBaselineSeparator:NO];
958 [toolbar setDelegate:self];
959 [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
960 [toolbar setSizeMode:NSToolbarSizeModeSmall];
962 [windowController setToolbar:toolbar];
968 // This is either a main menu item or a popup menu item.
969 NSString *title = [desc lastObject];
970 NSMenuItem *item = [[NSMenuItem alloc] init];
971 NSMenu *menu = [[NSMenu alloc] initWithTitle:title];
973 [item setTitle:title];
974 [item setSubmenu:menu];
976 NSMenu *parent = [self parentMenuForDescriptor:desc];
977 if (!parent && [rootName hasPrefix:@"PopUp"]) {
978 if ([popupMenuItems count] <= idx) {
979 [popupMenuItems addObject:item];
981 [popupMenuItems insertObject:item atIndex:idx];
984 // If descriptor has no parent and its not a popup (or toolbar) menu,
985 // then it must belong to main menu.
986 if (!parent) parent = mainMenu;
988 if ([parent numberOfItems] <= idx) {
989 [parent addItem:item];
991 [parent insertItem:item atIndex:idx];
999 - (void)addMenuItemWithDescriptor:(NSArray *)desc
1002 icon:(NSString *)icon
1003 keyEquivalent:(NSString *)keyEquivalent
1004 modifierMask:(int)modifierMask
1005 action:(NSString *)action
1006 isAlternate:(BOOL)isAlternate
1008 if (!(desc && [desc count] > 1 && idx >= 0)) return;
1010 NSString *title = [desc lastObject];
1011 NSString *rootName = [desc objectAtIndex:0];
1013 if ([rootName isEqual:@"ToolBar"]) {
1014 if (toolbar && [desc count] == 2)
1015 [self addToolbarItemWithLabel:title tip:tip icon:icon atIndex:idx];
1019 NSMenu *parent = [self parentMenuForDescriptor:desc];
1021 NSLog(@"WARNING: Menu item '%@' has no parent",
1022 [desc componentsJoinedByString:@"->"]);
1026 NSMenuItem *item = nil;
1027 if (0 == [title length]
1028 || ([title hasPrefix:@"-"] && [title hasSuffix:@"-"])) {
1029 item = [NSMenuItem separatorItem];
1030 [item setTitle:title];
1032 item = [[[NSMenuItem alloc] init] autorelease];
1033 [item setTitle:title];
1035 // Note: It is possible to set the action to a message that "doesn't
1036 // exist" without problems. We take advantage of this when adding
1037 // "dummy items" e.g. when dealing with the "Recent Files" menu (in
1038 // which case a recentFilesDummy: action is set, although it is never
1040 if ([action length] > 0)
1041 [item setAction:NSSelectorFromString(action)];
1043 [item setAction:@selector(vimMenuItemAction:)];
1044 if ([tip length] > 0) [item setToolTip:tip];
1045 if ([keyEquivalent length] > 0) {
1046 [item setKeyEquivalent:keyEquivalent];
1047 [item setKeyEquivalentModifierMask:modifierMask];
1049 [item setAlternate:isAlternate];
1051 // The tag is used to indicate whether Vim thinks a menu item should be
1052 // enabled or disabled. By default Vim thinks menu items are enabled.
1056 if ([parent numberOfItems] <= idx) {
1057 [parent addItem:item];
1059 [parent insertItem:item atIndex:idx];
1063 - (void)removeMenuItemWithDescriptor:(NSArray *)desc
1065 if (!(desc && [desc count] > 0)) return;
1067 NSString *title = [desc lastObject];
1068 NSString *rootName = [desc objectAtIndex:0];
1069 if ([rootName isEqual:@"ToolBar"]) {
1071 // Only remove toolbar items, never actually remove the toolbar
1072 // itself or strange things may happen.
1073 if ([desc count] == 2) {
1074 int idx = [toolbar indexOfItemWithItemIdentifier:title];
1075 if (idx != NSNotFound)
1076 [toolbar removeItemAtIndex:idx];
1082 NSMenuItem *item = [self menuItemForDescriptor:desc];
1084 NSLog(@"Failed to remove menu item, descriptor not found: %@",
1085 [desc componentsJoinedByString:@"->"]);
1091 if ([item menu] == [NSApp mainMenu] || ![item menu]) {
1092 // NOTE: To be on the safe side we try to remove the item from
1093 // both arrays (it is ok to call removeObject: even if an array
1094 // does not contain the object to remove).
1095 [popupMenuItems removeObject:item];
1099 [[item menu] removeItem:item];
1104 - (void)enableMenuItemWithDescriptor:(NSArray *)desc state:(BOOL)on
1106 if (!(desc && [desc count] > 0)) return;
1108 /*NSLog(@"%sable item %@", on ? "En" : "Dis",
1109 [desc componentsJoinedByString:@"->"]);*/
1111 NSString *rootName = [desc objectAtIndex:0];
1112 if ([rootName isEqual:@"ToolBar"]) {
1113 if (toolbar && [desc count] == 2) {
1114 NSString *title = [desc lastObject];
1115 [[toolbar itemWithItemIdentifier:title] setEnabled:on];
1118 // Use tag to set whether item is enabled or disabled instead of
1119 // calling setEnabled:. This way the menus can autoenable themselves
1120 // but at the same time Vim can set if a menu is enabled whenever it
1122 [[self menuItemForDescriptor:desc] setTag:on];
1126 - (void)addToolbarItemToDictionaryWithLabel:(NSString *)title
1127 toolTip:(NSString *)tip
1128 icon:(NSString *)icon
1130 // If the item corresponds to a separator then do nothing, since it is
1131 // already defined by Cocoa.
1132 if (!title || [title isEqual:NSToolbarSeparatorItemIdentifier]
1133 || [title isEqual:NSToolbarSpaceItemIdentifier]
1134 || [title isEqual:NSToolbarFlexibleSpaceItemIdentifier])
1137 NSToolbarItem *item = [[NSToolbarItem alloc] initWithItemIdentifier:title];
1138 [item setLabel:title];
1139 [item setToolTip:tip];
1140 [item setAction:@selector(vimToolbarItemAction:)];
1141 [item setAutovalidates:NO];
1143 NSImage *img = [NSImage imageNamed:icon];
1145 img = [[[NSImage alloc] initByReferencingFile:icon] autorelease];
1146 if (!(img && [img isValid]))
1150 NSLog(@"WARNING: Could not find image with name '%@' to use as toolbar"
1151 " image for identifier '%@';"
1152 " using default toolbar icon '%@' instead.",
1153 icon, title, MMDefaultToolbarImageName);
1155 img = [NSImage imageNamed:MMDefaultToolbarImageName];
1158 [item setImage:img];
1160 [toolbarItemDict setObject:item forKey:title];
1165 - (void)addToolbarItemWithLabel:(NSString *)label
1167 icon:(NSString *)icon
1170 if (!toolbar) return;
1172 // Check for separator items.
1174 label = NSToolbarSeparatorItemIdentifier;
1175 } else if ([label length] >= 2 && [label hasPrefix:@"-"]
1176 && [label hasSuffix:@"-"]) {
1177 // The label begins and ends with '-'; decided which kind of separator
1178 // item it is by looking at the prefix.
1179 if ([label hasPrefix:@"-space"]) {
1180 label = NSToolbarSpaceItemIdentifier;
1181 } else if ([label hasPrefix:@"-flexspace"]) {
1182 label = NSToolbarFlexibleSpaceItemIdentifier;
1184 label = NSToolbarSeparatorItemIdentifier;
1188 [self addToolbarItemToDictionaryWithLabel:label toolTip:tip icon:icon];
1190 int maxIdx = [[toolbar items] count];
1191 if (maxIdx < idx) idx = maxIdx;
1193 [toolbar insertItemWithItemIdentifier:label atIndex:idx];
1196 - (void)popupMenuWithDescriptor:(NSArray *)desc
1197 atRow:(NSNumber *)row
1198 column:(NSNumber *)col
1200 NSMenu *menu = [[self menuItemForDescriptor:desc] submenu];
1203 id textView = [[windowController vimView] textView];
1206 // TODO: Let textView convert (row,col) to NSPoint.
1207 int r = [row intValue];
1208 int c = [col intValue];
1209 NSSize cellSize = [textView cellSize];
1210 pt = NSMakePoint((c+1)*cellSize.width, (r+1)*cellSize.height);
1211 pt = [textView convertPoint:pt toView:nil];
1213 pt = [[windowController window] mouseLocationOutsideOfEventStream];
1216 NSEvent *event = [NSEvent mouseEventWithType:NSRightMouseDown
1220 windowNumber:[[windowController window] windowNumber]
1226 [NSMenu popUpContextMenu:menu withEvent:event forView:textView];
1229 - (void)popupMenuWithAttributes:(NSDictionary *)attrs
1233 [self popupMenuWithDescriptor:[attrs objectForKey:@"descriptor"]
1234 atRow:[attrs objectForKey:@"row"]
1235 column:[attrs objectForKey:@"column"]];
1238 - (void)connectionDidDie:(NSNotification *)notification
1240 //NSLog(@"%@ %s%@", [self className], _cmd, notification);
1241 [self scheduleClose];
1244 - (void)scheduleClose
1246 // NOTE! This message can arrive at pretty much anytime, e.g. while
1247 // the run loop is the 'event tracking' mode. This means that Cocoa may
1248 // well be in the middle of processing some message while this message is
1249 // received. If we were to remove the vim controller straight away we may
1250 // free objects that Cocoa is currently using (e.g. view objects). The
1251 // following call ensures that the vim controller is not released until the
1252 // run loop is back in the 'default' mode.
1253 [[MMAppController sharedInstance]
1254 performSelector:@selector(removeVimController:)
1259 // NSSavePanel delegate
1260 - (void)panel:(id)sender willExpand:(BOOL)expanding
1262 // Show or hide the "show hidden files" button
1264 [sender setAccessoryView:showHiddenFilesView()];
1266 [sender setShowsHiddenFiles:NO];
1267 [sender setAccessoryView:nil];
1271 - (void)handleBrowseForFile:(NSDictionary *)attr
1273 if (!isInitialized) return;
1275 NSString *dir = [attr objectForKey:@"dir"];
1276 BOOL saving = [[attr objectForKey:@"saving"] boolValue];
1279 // 'dir == nil' means: set dir to the pwd of the Vim process, or let
1280 // open dialog decide (depending on the below user default).
1281 BOOL trackPwd = [[NSUserDefaults standardUserDefaults]
1282 boolForKey:MMDialogsTrackPwdKey];
1284 dir = [vimState objectForKey:@"pwd"];
1288 NSSavePanel *panel = [NSSavePanel savePanel];
1290 // The delegate will be notified when the panel is expanded at which
1291 // time we may hide/show the "show hidden files" button (this button is
1292 // always visible for the open panel since it is always expanded).
1293 [panel setDelegate:self];
1294 if ([panel isExpanded])
1295 [panel setAccessoryView:showHiddenFilesView()];
1297 [panel beginSheetForDirectory:dir file:nil
1298 modalForWindow:[windowController window]
1300 didEndSelector:@selector(savePanelDidEnd:code:context:)
1303 NSOpenPanel *panel = [NSOpenPanel openPanel];
1304 [panel setAllowsMultipleSelection:NO];
1305 [panel setAccessoryView:showHiddenFilesView()];
1307 [panel beginSheetForDirectory:dir file:nil types:nil
1308 modalForWindow:[windowController window]
1310 didEndSelector:@selector(savePanelDidEnd:code:context:)
1315 - (void)handleShowDialog:(NSDictionary *)attr
1317 if (!isInitialized) return;
1319 NSArray *buttonTitles = [attr objectForKey:@"buttonTitles"];
1320 if (!(buttonTitles && [buttonTitles count])) return;
1322 int style = [[attr objectForKey:@"alertStyle"] intValue];
1323 NSString *message = [attr objectForKey:@"messageText"];
1324 NSString *text = [attr objectForKey:@"informativeText"];
1325 NSString *textFieldString = [attr objectForKey:@"textFieldString"];
1326 MMAlert *alert = [[MMAlert alloc] init];
1328 // NOTE! This has to be done before setting the informative text.
1329 if (textFieldString)
1330 [alert setTextFieldString:textFieldString];
1332 [alert setAlertStyle:style];
1335 [alert setMessageText:message];
1337 // If no message text is specified 'Alert' is used, which we don't
1338 // want, so set an empty string as message text.
1339 [alert setMessageText:@""];
1343 [alert setInformativeText:text];
1344 } else if (textFieldString) {
1345 // Make sure there is always room for the input text field.
1346 [alert setInformativeText:@""];
1349 unsigned i, count = [buttonTitles count];
1350 for (i = 0; i < count; ++i) {
1351 NSString *title = [buttonTitles objectAtIndex:i];
1352 // NOTE: The title of the button may contain the character '&' to
1353 // indicate that the following letter should be the key equivalent
1354 // associated with the button. Extract this letter and lowercase it.
1355 NSString *keyEquivalent = nil;
1356 NSRange hotkeyRange = [title rangeOfString:@"&"];
1357 if (NSNotFound != hotkeyRange.location) {
1358 if ([title length] > NSMaxRange(hotkeyRange)) {
1359 NSRange keyEquivRange = NSMakeRange(hotkeyRange.location+1, 1);
1360 keyEquivalent = [[title substringWithRange:keyEquivRange]
1364 NSMutableString *string = [NSMutableString stringWithString:title];
1365 [string deleteCharactersInRange:hotkeyRange];
1369 [alert addButtonWithTitle:title];
1371 // Set key equivalent for the button, but only if NSAlert hasn't
1372 // already done so. (Check the documentation for
1373 // - [NSAlert addButtonWithTitle:] to see what key equivalents are
1374 // automatically assigned.)
1375 NSButton *btn = [[alert buttons] lastObject];
1376 if ([[btn keyEquivalent] length] == 0 && keyEquivalent) {
1377 [btn setKeyEquivalent:keyEquivalent];
1381 [alert beginSheetModalForWindow:[windowController window]
1383 didEndSelector:@selector(alertDidEnd:code:context:)
1390 @end // MMVimController (Private)
1395 @implementation MMAlert
1398 [textField release]; textField = nil;
1402 - (void)setTextFieldString:(NSString *)textFieldString
1404 [textField release];
1405 textField = [[NSTextField alloc] init];
1406 [textField setStringValue:textFieldString];
1409 - (NSTextField *)textField
1414 - (void)setInformativeText:(NSString *)text
1417 // HACK! Add some space for the text field.
1418 [super setInformativeText:[text stringByAppendingString:@"\n\n\n"]];
1420 [super setInformativeText:text];
1424 - (void)beginSheetModalForWindow:(NSWindow *)window
1425 modalDelegate:(id)delegate
1426 didEndSelector:(SEL)didEndSelector
1427 contextInfo:(void *)contextInfo
1429 [super beginSheetModalForWindow:window
1430 modalDelegate:delegate
1431 didEndSelector:didEndSelector
1432 contextInfo:contextInfo];
1434 // HACK! Place the input text field at the bottom of the informative text
1435 // (which has been made a bit larger by adding newline characters).
1436 NSView *contentView = [[self window] contentView];
1437 NSRect rect = [contentView frame];
1438 rect.origin.y = rect.size.height;
1440 NSArray *subviews = [contentView subviews];
1441 unsigned i, count = [subviews count];
1442 for (i = 0; i < count; ++i) {
1443 NSView *view = [subviews objectAtIndex:i];
1444 if ([view isKindOfClass:[NSTextField class]]
1445 && [view frame].origin.y < rect.origin.y) {
1446 // NOTE: The informative text field is the lowest NSTextField in
1447 // the alert dialog.
1448 rect = [view frame];
1452 rect.size.height = MMAlertTextFieldHeight;
1453 [textField setFrame:rect];
1454 [contentView addSubview:textField];
1455 [textField becomeFirstResponder];
1464 isUnsafeMessage(int msgid)
1466 // Messages that may release Cocoa objects must be added to this list. For
1467 // example, UpdateTabBarMsgID may delete NSTabViewItem objects so it goes
1469 static int unsafeMessages[] = { // REASON MESSAGE IS ON THIS LIST:
1470 //OpenWindowMsgID, // Changes lots of state
1471 UpdateTabBarMsgID, // May delete NSTabViewItem
1472 RemoveMenuItemMsgID, // Deletes NSMenuItem
1473 DestroyScrollbarMsgID, // Deletes NSScroller
1474 ExecuteActionMsgID, // Impossible to predict
1475 ShowPopupMenuMsgID, // Enters modal loop
1477 EnterFullscreenMsgID, // Modifies delegate of window controller
1478 LeaveFullscreenMsgID, // Modifies delegate of window controller
1479 CloseWindowMsgID, // See note below
1480 BrowseForFileMsgID, // Enters modal loop
1481 ShowDialogMsgID, // Enters modal loop
1484 // NOTE about CloseWindowMsgID: If this arrives at the same time as say
1485 // ExecuteActionMsgID, then the "execute" message will be lost due to it
1486 // being queued and handled after the "close" message has caused the
1487 // controller to cleanup...UNLESS we add CloseWindowMsgID to the list of
1488 // unsafe messages. This is the _only_ reason it is on this list (since
1489 // all that happens in response to it is that we schedule another message
1490 // for later handling).
1492 int i, count = sizeof(unsafeMessages)/sizeof(unsafeMessages[0]);
1493 for (i = 0; i < count; ++i)
1494 if (msgid == unsafeMessages[i])