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 "MMVimController.h"
27 #import "MMWindowController.h"
28 #import "MMTextView.h"
29 #import "MMAppController.h"
30 #import "MMTextStorage.h"
33 // This is taken from gui.h
34 #define DRAW_CURSOR 0x20
36 static NSString *MMDefaultToolbarImageName = @"Attention";
37 static int MMAlertTextFieldHeight = 22;
39 // NOTE: By default a message sent to the backend will be dropped if it cannot
40 // be delivered instantly; otherwise there is a possibility that MacVim will
41 // 'beachball' while waiting to deliver DO messages to an unresponsive Vim
42 // process. This means that you cannot rely on any message sent with
43 // sendMessage: to actually reach Vim.
44 static NSTimeInterval MMBackendProxyRequestTimeout = 0;
46 #if MM_RESEND_LAST_FAILURE
47 // If a message send fails, the message will be resent after this many seconds
48 // have passed. (No queue is kept, only the very last message is resent.)
49 static NSTimeInterval MMResendInterval = 0.5;
53 @interface MMAlert : NSAlert {
54 NSTextField *textField;
56 - (void)setTextFieldString:(NSString *)textFieldString;
57 - (NSTextField *)textField;
61 @interface MMVimController (Private)
62 - (void)handleMessage:(int)msgid data:(NSData *)data;
63 - (void)performBatchDrawWithData:(NSData *)data;
64 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
65 context:(void *)context;
66 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context;
67 - (NSMenuItem *)recurseMenuItemForTag:(int)tag rootMenu:(NSMenu *)root;
68 - (NSMenuItem *)menuItemForTag:(int)tag;
69 - (NSMenu *)menuForTag:(int)tag;
70 - (NSMenu *)topLevelMenuForTitle:(NSString *)title;
71 - (void)addMenuWithTag:(int)tag parent:(int)parentTag title:(NSString *)title
73 - (void)addMenuItemWithTag:(int)tag parent:(NSMenu *)parent
74 title:(NSString *)title tip:(NSString *)tip
75 keyEquivalent:(int)key modifiers:(int)mask
76 action:(NSString *)action atIndex:(int)idx;
77 - (void)updateMainMenu;
78 - (NSToolbarItem *)toolbarItemForTag:(int)tag index:(int *)index;
79 - (void)addToolbarItemToDictionaryWithTag:(int)tag label:(NSString *)title
80 toolTip:(NSString *)tip icon:(NSString *)icon;
81 - (void)addToolbarItemWithTag:(int)tag label:(NSString *)label
82 tip:(NSString *)tip icon:(NSString *)icon
84 - (void)connectionDidDie:(NSNotification *)notification;
85 #if MM_RESEND_LAST_FAILURE
86 - (void)resendTimerFired:(NSTimer *)timer;
92 // TODO: Move to separate file
93 @interface NSColor (MMProtocol)
94 + (NSColor *)colorWithRgbInt:(unsigned)rgb;
95 + (NSColor *)colorWithArgbInt:(unsigned)argb;
101 @implementation MMVimController
103 - (id)initWithBackend:(id)backend pid:(int)processIdentifier
105 if ((self = [super init])) {
107 [[MMWindowController alloc] initWithVimController:self];
108 backendProxy = [backend retain];
109 sendQueue = [NSMutableArray new];
110 mainMenuItems = [[NSMutableArray alloc] init];
111 popupMenuItems = [[NSMutableArray alloc] init];
112 toolbarItemDict = [[NSMutableDictionary alloc] init];
113 pid = processIdentifier;
115 NSConnection *connection = [backendProxy connectionForProxy];
117 // TODO: Check that this will not set the timeout for the root proxy
118 // (in MMAppController).
119 [connection setRequestTimeout:MMBackendProxyRequestTimeout];
121 [[NSNotificationCenter defaultCenter] addObserver:self
122 selector:@selector(connectionDidDie:)
123 name:NSConnectionDidDieNotification object:connection];
126 NSWindow *win = [windowController window];
128 [[NSNotificationCenter defaultCenter]
130 selector:@selector(windowDidBecomeMain:)
131 name:NSWindowDidBecomeMainNotification
142 //NSLog(@"%@ %s", [self className], _cmd);
145 #if MM_RESEND_LAST_FAILURE
146 [resendData release]; resendData = nil;
149 [serverName release]; serverName = nil;
150 [backendProxy release]; backendProxy = nil;
151 [sendQueue release]; sendQueue = nil;
153 [toolbarItemDict release]; toolbarItemDict = nil;
154 [toolbar release]; toolbar = nil;
155 [popupMenuItems release]; popupMenuItems = nil;
156 [mainMenuItems release]; mainMenuItems = nil;
157 [windowController release]; windowController = nil;
162 - (MMWindowController *)windowController
164 return windowController;
167 - (void)setServerName:(NSString *)name
169 if (name != serverName) {
170 [serverName release];
171 serverName = [name copy];
175 - (NSString *)serverName
185 - (void)dropFiles:(NSArray *)filenames
187 int i, numberOfFiles = [filenames count];
188 NSMutableData *data = [NSMutableData data];
190 [data appendBytes:&numberOfFiles length:sizeof(int)];
192 for (i = 0; i < numberOfFiles; ++i) {
193 NSString *file = [filenames objectAtIndex:i];
194 int len = [file lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
197 ++len; // include NUL as well
198 [data appendBytes:&len length:sizeof(int)];
199 [data appendBytes:[file UTF8String] length:len];
203 [self sendMessage:DropFilesMsgID data:data];
206 - (void)dropString:(NSString *)string
208 int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
210 NSMutableData *data = [NSMutableData data];
212 [data appendBytes:&len length:sizeof(int)];
213 [data appendBytes:[string UTF8String] length:len];
215 [self sendMessage:DropStringMsgID data:data];
219 - (void)sendMessage:(int)msgid data:(NSData *)data
221 //NSLog(@"sendMessage:%s (isInitialized=%d inProcessCommandQueue=%d)",
222 // MessageStrings[msgid], isInitialized, inProcessCommandQueue);
224 if (!isInitialized) return;
226 if (inProcessCommandQueue) {
227 //NSLog(@"In process command queue; delaying message send.");
228 [sendQueue addObject:[NSNumber numberWithInt:msgid]];
230 [sendQueue addObject:data];
232 [sendQueue addObject:[NSNull null]];
236 #if MM_RESEND_LAST_FAILURE
238 //NSLog(@"cancelling scheduled resend of %s",
239 // MessageStrings[resendMsgid]);
241 [resendTimer invalidate];
242 [resendTimer release];
247 [resendData release];
253 [backendProxy processInput:msgid data:data];
255 @catch (NSException *e) {
256 //NSLog(@"%@ %s Exception caught during DO call: %@",
257 // [self className], _cmd, e);
258 #if MM_RESEND_LAST_FAILURE
259 //NSLog(@"%s failed, scheduling message %s for resend", _cmd,
260 // MessageStrings[msgid]);
263 resendData = [data retain];
264 resendTimer = [NSTimer
265 scheduledTimerWithTimeInterval:MMResendInterval
267 selector:@selector(resendTimerFired:)
270 [resendTimer retain];
275 - (BOOL)sendMessageNow:(int)msgid data:(NSData *)data
276 timeout:(NSTimeInterval)timeout
278 if (!isInitialized || inProcessCommandQueue)
281 if (timeout < 0) timeout = 0;
284 NSConnection *conn = [backendProxy connectionForProxy];
285 NSTimeInterval oldTimeout = [conn requestTimeout];
287 [conn setRequestTimeout:timeout];
290 [backendProxy processInput:msgid data:data];
292 @catch (NSException *e) {
296 [conn setRequestTimeout:oldTimeout];
302 - (void)addVimInput:(NSString *)string
304 // This is a very general method of adding input to the Vim process. It is
305 // basically the same as calling remote_send() on the process (see
306 // ':h remote_send').
308 NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
309 [self sendMessage:AddInputMsgID data:data];
320 //NSLog(@"%@ %s", [self className], _cmd);
321 if (!isInitialized) return;
324 [toolbar setDelegate:nil];
325 [[NSNotificationCenter defaultCenter] removeObserver:self];
326 [windowController cleanup];
329 - (oneway void)showSavePanelForDirectory:(in bycopy NSString *)dir
330 title:(in bycopy NSString *)title
333 if (!isInitialized) return;
336 [[NSSavePanel savePanel] beginSheetForDirectory:dir file:nil
337 modalForWindow:[windowController window]
339 didEndSelector:@selector(savePanelDidEnd:code:context:)
342 NSOpenPanel *panel = [NSOpenPanel openPanel];
343 [panel setAllowsMultipleSelection:NO];
344 [panel beginSheetForDirectory:dir file:nil types:nil
345 modalForWindow:[windowController window]
347 didEndSelector:@selector(savePanelDidEnd:code:context:)
352 - (oneway void)presentDialogWithStyle:(int)style
353 message:(in bycopy NSString *)message
354 informativeText:(in bycopy NSString *)text
355 buttonTitles:(in bycopy NSArray *)buttonTitles
356 textFieldString:(in bycopy NSString *)textFieldString
358 if (!(windowController && buttonTitles && [buttonTitles count])) return;
360 MMAlert *alert = [[MMAlert alloc] init];
362 // NOTE! This has to be done before setting the informative text.
364 [alert setTextFieldString:textFieldString];
366 [alert setAlertStyle:style];
369 [alert setMessageText:message];
371 // If no message text is specified 'Alert' is used, which we don't
372 // want, so set an empty string as message text.
373 [alert setMessageText:@""];
377 [alert setInformativeText:text];
378 } else if (textFieldString) {
379 // Make sure there is always room for the input text field.
380 [alert setInformativeText:@""];
383 unsigned i, count = [buttonTitles count];
384 for (i = 0; i < count; ++i) {
385 NSString *title = [buttonTitles objectAtIndex:i];
386 // NOTE: The title of the button may contain the character '&' to
387 // indicate that the following letter should be the key equivalent
388 // associated with the button. Extract this letter and lowercase it.
389 NSString *keyEquivalent = nil;
390 NSRange hotkeyRange = [title rangeOfString:@"&"];
391 if (NSNotFound != hotkeyRange.location) {
392 if ([title length] > NSMaxRange(hotkeyRange)) {
393 NSRange keyEquivRange = NSMakeRange(hotkeyRange.location+1, 1);
394 keyEquivalent = [[title substringWithRange:keyEquivRange]
398 NSMutableString *string = [NSMutableString stringWithString:title];
399 [string deleteCharactersInRange:hotkeyRange];
403 [alert addButtonWithTitle:title];
405 // Set key equivalent for the button, but only if NSAlert hasn't
406 // already done so. (Check the documentation for
407 // - [NSAlert addButtonWithTitle:] to see what key equivalents are
408 // automatically assigned.)
409 NSButton *btn = [[alert buttons] lastObject];
410 if ([[btn keyEquivalent] length] == 0 && keyEquivalent) {
411 [btn setKeyEquivalent:keyEquivalent];
415 [alert beginSheetModalForWindow:[windowController window]
417 didEndSelector:@selector(alertDidEnd:code:context:)
423 - (oneway void)processCommandQueue:(in bycopy NSArray *)queue
425 if (!isInitialized) return;
427 unsigned i, count = [queue count];
429 NSLog(@"WARNING: Uneven number of components (%d) in flush queue "
430 "message; ignoring this message.", count);
434 inProcessCommandQueue = YES;
436 //NSLog(@"======== %s BEGIN ========", _cmd);
437 for (i = 0; i < count; i += 2) {
438 NSData *value = [queue objectAtIndex:i];
439 NSData *data = [queue objectAtIndex:i+1];
441 int msgid = *((int*)[value bytes]);
442 //NSLog(@"%s%s", _cmd, MessageStrings[msgid]);
444 [self handleMessage:msgid data:data];
446 //NSLog(@"======== %s END ========", _cmd);
448 if (shouldUpdateMainMenu) {
449 [self updateMainMenu];
452 [windowController processCommandQueueDidFinish];
454 inProcessCommandQueue = NO;
456 if ([sendQueue count] > 0) {
458 [backendProxy processInputAndData:sendQueue];
460 @catch (NSException *e) {
461 // Connection timed out, just ignore this.
462 //NSLog(@"WARNING! Connection timed out in %s", _cmd);
465 [sendQueue removeAllObjects];
469 - (void)windowDidBecomeMain:(NSNotification *)notification
472 [self updateMainMenu];
475 - (NSToolbarItem *)toolbar:(NSToolbar *)theToolbar
476 itemForItemIdentifier:(NSString *)itemId
477 willBeInsertedIntoToolbar:(BOOL)flag
479 NSToolbarItem *item = [toolbarItemDict objectForKey:itemId];
481 NSLog(@"WARNING: No toolbar item with id '%@'", itemId);
487 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)theToolbar
492 - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)theToolbar
497 @end // MMVimController
501 @implementation MMVimController (Private)
503 - (void)handleMessage:(int)msgid data:(NSData *)data
505 //NSLog(@"%@ %s", [self className], _cmd);
507 if (OpenVimWindowMsgID == msgid) {
508 [windowController openWindow];
509 } else if (BatchDrawMsgID == msgid) {
510 [self performBatchDrawWithData:data];
511 } else if (SelectTabMsgID == msgid) {
512 #if 0 // NOTE: Tab selection is done inside updateTabsWithData:.
513 const void *bytes = [data bytes];
514 int idx = *((int*)bytes);
515 //NSLog(@"Selecting tab with index %d", idx);
516 [windowController selectTabWithIndex:idx];
518 } else if (UpdateTabBarMsgID == msgid) {
519 [windowController updateTabsWithData:data];
520 } else if (ShowTabBarMsgID == msgid) {
521 [windowController showTabBar:YES];
522 } else if (HideTabBarMsgID == msgid) {
523 [windowController showTabBar:NO];
524 } else if (SetTextDimensionsMsgID == msgid) {
525 const void *bytes = [data bytes];
526 int rows = *((int*)bytes); bytes += sizeof(int);
527 int cols = *((int*)bytes); bytes += sizeof(int);
529 [windowController setTextDimensionsWithRows:rows columns:cols];
530 } else if (SetWindowTitleMsgID == msgid) {
531 const void *bytes = [data bytes];
532 int len = *((int*)bytes); bytes += sizeof(int);
534 NSString *string = [[NSString alloc] initWithBytes:(void*)bytes
535 length:len encoding:NSUTF8StringEncoding];
537 [[windowController window] setTitle:string];
540 } else if (AddMenuMsgID == msgid) {
541 NSString *title = nil;
542 const void *bytes = [data bytes];
543 int tag = *((int*)bytes); bytes += sizeof(int);
544 int parentTag = *((int*)bytes); bytes += sizeof(int);
545 int len = *((int*)bytes); bytes += sizeof(int);
547 title = [[NSString alloc] initWithBytes:(void*)bytes length:len
548 encoding:NSUTF8StringEncoding];
551 int idx = *((int*)bytes); bytes += sizeof(int);
553 if (MenuToolbarType == parentTag) {
555 // NOTE! Each toolbar must have a unique identifier, else each
556 // window will have the same toolbar.
557 NSString *ident = [NSString stringWithFormat:@"%d.%d",
559 toolbar = [[NSToolbar alloc] initWithIdentifier:ident];
561 [toolbar setShowsBaselineSeparator:NO];
562 [toolbar setDelegate:self];
563 [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
564 [toolbar setSizeMode:NSToolbarSizeModeSmall];
566 NSWindow *win = [windowController window];
567 [win setToolbar:toolbar];
569 // HACK! Redirect the pill button so that we can ask Vim to
571 NSButton *pillButton = [win
572 standardWindowButton:NSWindowToolbarButton];
574 [pillButton setAction:@selector(toggleToolbar:)];
575 [pillButton setTarget:windowController];
579 [self addMenuWithTag:tag parent:parentTag title:title atIndex:idx];
583 } else if (AddMenuItemMsgID == msgid) {
584 NSString *title = nil, *tip = nil, *icon = nil, *action = nil;
585 const void *bytes = [data bytes];
586 int tag = *((int*)bytes); bytes += sizeof(int);
587 int parentTag = *((int*)bytes); bytes += sizeof(int);
588 int namelen = *((int*)bytes); bytes += sizeof(int);
590 title = [[NSString alloc] initWithBytes:(void*)bytes length:namelen
591 encoding:NSUTF8StringEncoding];
594 int tiplen = *((int*)bytes); bytes += sizeof(int);
596 tip = [[NSString alloc] initWithBytes:(void*)bytes length:tiplen
597 encoding:NSUTF8StringEncoding];
600 int iconlen = *((int*)bytes); bytes += sizeof(int);
602 icon = [[NSString alloc] initWithBytes:(void*)bytes length:iconlen
603 encoding:NSUTF8StringEncoding];
606 int actionlen = *((int*)bytes); bytes += sizeof(int);
608 action = [[NSString alloc] initWithBytes:(void*)bytes
610 encoding:NSUTF8StringEncoding];
613 int idx = *((int*)bytes); bytes += sizeof(int);
614 if (idx < 0) idx = 0;
615 int key = *((int*)bytes); bytes += sizeof(int);
616 int mask = *((int*)bytes); bytes += sizeof(int);
618 NSString *ident = [NSString stringWithFormat:@"%d.%d",
619 (int)self, parentTag];
620 if (toolbar && [[toolbar identifier] isEqual:ident]) {
621 [self addToolbarItemWithTag:tag label:title tip:tip icon:icon
624 NSMenu *parent = [self menuForTag:parentTag];
625 [self addMenuItemWithTag:tag parent:parent title:title tip:tip
626 keyEquivalent:key modifiers:mask action:action
634 } else if (RemoveMenuItemMsgID == msgid) {
635 const void *bytes = [data bytes];
636 int tag = *((int*)bytes); bytes += sizeof(int);
640 if ((item = [self toolbarItemForTag:tag index:&idx])) {
641 [toolbar removeItemAtIndex:idx];
642 } else if ((item = [self menuItemForTag:tag])) {
645 if ([item menu] == [NSApp mainMenu] || ![item menu]) {
646 // NOTE: To be on the safe side we try to remove the item from
647 // both arrays (it is ok to call removeObject: even if an array
648 // does not contain the object to remove).
649 [mainMenuItems removeObject:item];
650 [popupMenuItems removeObject:item];
654 [[item menu] removeItem:item];
659 // Reset cached menu, just to be on the safe side.
660 lastMenuSearched = nil;
661 } else if (EnableMenuItemMsgID == msgid) {
662 const void *bytes = [data bytes];
663 int tag = *((int*)bytes); bytes += sizeof(int);
664 int state = *((int*)bytes); bytes += sizeof(int);
666 id item = [self toolbarItemForTag:tag index:NULL];
668 item = [self menuItemForTag:tag];
670 [item setEnabled:state];
671 } else if (ShowToolbarMsgID == msgid) {
672 const void *bytes = [data bytes];
673 int enable = *((int*)bytes); bytes += sizeof(int);
674 int flags = *((int*)bytes); bytes += sizeof(int);
676 int mode = NSToolbarDisplayModeDefault;
677 if (flags & ToolbarLabelFlag) {
678 mode = flags & ToolbarIconFlag ? NSToolbarDisplayModeIconAndLabel
679 : NSToolbarDisplayModeLabelOnly;
680 } else if (flags & ToolbarIconFlag) {
681 mode = NSToolbarDisplayModeIconOnly;
684 int size = flags & ToolbarSizeRegularFlag ? NSToolbarSizeModeRegular
685 : NSToolbarSizeModeSmall;
687 [windowController showToolbar:enable size:size mode:mode];
688 } else if (CreateScrollbarMsgID == msgid) {
689 const void *bytes = [data bytes];
690 long ident = *((long*)bytes); bytes += sizeof(long);
691 int type = *((int*)bytes); bytes += sizeof(int);
693 [windowController createScrollbarWithIdentifier:ident type:type];
694 } else if (DestroyScrollbarMsgID == msgid) {
695 const void *bytes = [data bytes];
696 long ident = *((long*)bytes); bytes += sizeof(long);
698 [windowController destroyScrollbarWithIdentifier:ident];
699 } else if (ShowScrollbarMsgID == msgid) {
700 const void *bytes = [data bytes];
701 long ident = *((long*)bytes); bytes += sizeof(long);
702 int visible = *((int*)bytes); bytes += sizeof(int);
704 [windowController showScrollbarWithIdentifier:ident state:visible];
705 } else if (SetScrollbarPositionMsgID == msgid) {
706 const void *bytes = [data bytes];
707 long ident = *((long*)bytes); bytes += sizeof(long);
708 int pos = *((int*)bytes); bytes += sizeof(int);
709 int len = *((int*)bytes); bytes += sizeof(int);
711 [windowController setScrollbarPosition:pos length:len
713 } else if (SetScrollbarThumbMsgID == msgid) {
714 const void *bytes = [data bytes];
715 long ident = *((long*)bytes); bytes += sizeof(long);
716 float val = *((float*)bytes); bytes += sizeof(float);
717 float prop = *((float*)bytes); bytes += sizeof(float);
719 [windowController setScrollbarThumbValue:val proportion:prop
721 } else if (SetFontMsgID == msgid) {
722 const void *bytes = [data bytes];
723 float size = *((float*)bytes); bytes += sizeof(float);
724 int len = *((int*)bytes); bytes += sizeof(int);
725 NSString *name = [[NSString alloc]
726 initWithBytes:(void*)bytes length:len
727 encoding:NSUTF8StringEncoding];
728 NSFont *font = [NSFont fontWithName:name size:size];
731 [windowController setFont:font];
734 } else if (SetWideFontMsgID == msgid) {
735 const void *bytes = [data bytes];
736 float size = *((float*)bytes); bytes += sizeof(float);
737 int len = *((int*)bytes); bytes += sizeof(int);
739 NSString *name = [[NSString alloc]
740 initWithBytes:(void*)bytes length:len
741 encoding:NSUTF8StringEncoding];
742 NSFont *font = [NSFont fontWithName:name size:size];
743 [windowController setWideFont:font];
747 [windowController setWideFont:nil];
749 } else if (SetDefaultColorsMsgID == msgid) {
750 const void *bytes = [data bytes];
751 unsigned bg = *((unsigned*)bytes); bytes += sizeof(unsigned);
752 unsigned fg = *((unsigned*)bytes); bytes += sizeof(unsigned);
753 NSColor *back = [NSColor colorWithArgbInt:bg];
754 NSColor *fore = [NSColor colorWithRgbInt:fg];
756 [windowController setDefaultColorsBackground:back foreground:fore];
757 } else if (ExecuteActionMsgID == msgid) {
758 const void *bytes = [data bytes];
759 int len = *((int*)bytes); bytes += sizeof(int);
760 NSString *actionName = [[NSString alloc]
761 initWithBytesNoCopy:(void*)bytes
763 encoding:NSUTF8StringEncoding
766 SEL sel = NSSelectorFromString(actionName);
767 [NSApp sendAction:sel to:nil from:self];
769 [actionName release];
770 } else if (ShowPopupMenuMsgID == msgid) {
771 const void *bytes = [data bytes];
772 int row = *((int*)bytes); bytes += sizeof(int);
773 int col = *((int*)bytes); bytes += sizeof(int);
774 int len = *((int*)bytes); bytes += sizeof(int);
775 NSString *title = [[NSString alloc]
776 initWithBytesNoCopy:(void*)bytes
778 encoding:NSUTF8StringEncoding
781 NSMenu *menu = [self topLevelMenuForTitle:title];
783 [windowController popupMenu:menu atRow:row column:col];
785 NSLog(@"WARNING: Cannot popup menu with title %@; no such menu.",
790 } else if (SetMouseShapeMsgID == msgid) {
791 const void *bytes = [data bytes];
792 int shape = *((int*)bytes); bytes += sizeof(int);
794 [windowController setMouseShape:shape];
795 } else if (AdjustLinespaceMsgID == msgid) {
796 const void *bytes = [data bytes];
797 int linespace = *((int*)bytes); bytes += sizeof(int);
799 [windowController adjustLinespace:linespace];
800 } else if (ActivateMsgID == msgid) {
801 //NSLog(@"ActivateMsgID");
802 [NSApp activateIgnoringOtherApps:YES];
803 [[windowController window] makeKeyAndOrderFront:self];
804 } else if (SetServerNameMsgID == msgid) {
805 NSString *name = [[NSString alloc] initWithData:data
806 encoding:NSUTF8StringEncoding];
807 [self setServerName:name];
809 } else if (EnterFullscreenMsgID == msgid) {
810 [windowController enterFullscreen];
811 } else if (LeaveFullscreenMsgID == msgid) {
812 [windowController leaveFullscreen];
813 } else if (BuffersNotModifiedMsgID == msgid) {
814 [[windowController window] setDocumentEdited:NO];
815 } else if (BuffersModifiedMsgID == msgid) {
816 [[windowController window] setDocumentEdited:YES];
818 NSLog(@"WARNING: Unknown message received (msgid=%d)", msgid);
823 #define MM_DEBUG_DRAWING 0
825 - (void)performBatchDrawWithData:(NSData *)data
827 // TODO! Move to window controller.
828 MMTextStorage *textStorage = [windowController textStorage];
829 MMTextView *textView = [windowController textView];
830 if (!(textStorage && textView))
833 const void *bytes = [data bytes];
834 const void *end = bytes + [data length];
837 NSLog(@"====> BEGIN %s", _cmd);
839 [textStorage beginEditing];
841 // TODO: Sanity check input
843 while (bytes < end) {
844 int type = *((int*)bytes); bytes += sizeof(int);
846 if (ClearAllDrawType == type) {
848 NSLog(@" Clear all");
850 [textStorage clearAll];
851 } else if (ClearBlockDrawType == type) {
852 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
853 int row1 = *((int*)bytes); bytes += sizeof(int);
854 int col1 = *((int*)bytes); bytes += sizeof(int);
855 int row2 = *((int*)bytes); bytes += sizeof(int);
856 int col2 = *((int*)bytes); bytes += sizeof(int);
859 NSLog(@" Clear block (%d,%d) -> (%d,%d)", row1, col1,
862 [textStorage clearBlockFromRow:row1 column:col1
863 toRow:row2 column:col2
864 color:[NSColor colorWithArgbInt:color]];
865 } else if (DeleteLinesDrawType == type) {
866 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
867 int row = *((int*)bytes); bytes += sizeof(int);
868 int count = *((int*)bytes); bytes += sizeof(int);
869 int bot = *((int*)bytes); bytes += sizeof(int);
870 int left = *((int*)bytes); bytes += sizeof(int);
871 int right = *((int*)bytes); bytes += sizeof(int);
874 NSLog(@" Delete %d line(s) from %d", count, row);
876 [textStorage deleteLinesFromRow:row lineCount:count
877 scrollBottom:bot left:left right:right
878 color:[NSColor colorWithArgbInt:color]];
879 } else if (DrawStringDrawType == type) {
880 int bg = *((int*)bytes); bytes += sizeof(int);
881 int fg = *((int*)bytes); bytes += sizeof(int);
882 int sp = *((int*)bytes); bytes += sizeof(int);
883 int row = *((int*)bytes); bytes += sizeof(int);
884 int col = *((int*)bytes); bytes += sizeof(int);
885 int cells = *((int*)bytes); bytes += sizeof(int);
886 int flags = *((int*)bytes); bytes += sizeof(int);
887 int len = *((int*)bytes); bytes += sizeof(int);
888 NSString *string = [[NSString alloc]
889 initWithBytesNoCopy:(void*)bytes
891 encoding:NSUTF8StringEncoding
896 NSLog(@" Draw string at (%d,%d) length=%d flags=%d fg=0x%x "
897 "bg=0x%x sp=0x%x (%@)", row, col, len, flags, fg, bg, sp,
898 len > 0 ? [string substringToIndex:1] : @"");
900 // NOTE: If this is a call to draw the (block) cursor, then cancel
901 // any previous request to draw the insertion point, or it might
902 // get drawn as well.
903 if (flags & DRAW_CURSOR) {
904 [textView setShouldDrawInsertionPoint:NO];
905 //NSColor *color = [NSColor colorWithRgbInt:bg];
906 //[textView drawInsertionPointAtRow:row column:col
907 // shape:MMInsertionPointBlock
911 [textStorage drawString:string
912 atRow:row column:col cells:cells
914 foregroundColor:[NSColor colorWithRgbInt:fg]
915 backgroundColor:[NSColor colorWithArgbInt:bg]
916 specialColor:[NSColor colorWithRgbInt:sp]];
919 } else if (InsertLinesDrawType == type) {
920 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
921 int row = *((int*)bytes); bytes += sizeof(int);
922 int count = *((int*)bytes); bytes += sizeof(int);
923 int bot = *((int*)bytes); bytes += sizeof(int);
924 int left = *((int*)bytes); bytes += sizeof(int);
925 int right = *((int*)bytes); bytes += sizeof(int);
928 NSLog(@" Insert %d line(s) at row %d", count, row);
930 [textStorage insertLinesAtRow:row lineCount:count
931 scrollBottom:bot left:left right:right
932 color:[NSColor colorWithArgbInt:color]];
933 } else if (DrawCursorDrawType == type) {
934 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
935 int row = *((int*)bytes); bytes += sizeof(int);
936 int col = *((int*)bytes); bytes += sizeof(int);
937 int shape = *((int*)bytes); bytes += sizeof(int);
938 int percent = *((int*)bytes); bytes += sizeof(int);
941 NSLog(@" Draw cursor at (%d,%d)", row, col);
943 [textView drawInsertionPointAtRow:row column:col shape:shape
945 color:[NSColor colorWithRgbInt:color]];
947 NSLog(@"WARNING: Unknown draw type (type=%d)", type);
951 [textStorage endEditing];
953 // NOTE: During resizing, Cocoa only sends draw messages before Vim's rows
954 // and columns are changed (due to ipc delays). Force a redraw here.
955 [[windowController vimView] displayIfNeeded];
958 NSLog(@"<==== END %s", _cmd);
962 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
963 context:(void *)context
965 NSString *string = (code == NSOKButton) ? [panel filename] : nil;
967 [backendProxy setDialogReturn:string];
969 @catch (NSException *e) {
970 NSLog(@"Exception caught in %s %@", _cmd, e);
974 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context
978 code = code - NSAlertFirstButtonReturn + 1;
980 if ([alert isKindOfClass:[MMAlert class]] && [alert textField]) {
981 ret = [NSArray arrayWithObjects:[NSNumber numberWithInt:code],
982 [[alert textField] stringValue], nil];
984 ret = [NSArray arrayWithObject:[NSNumber numberWithInt:code]];
988 [backendProxy setDialogReturn:ret];
990 @catch (NSException *e) {
991 NSLog(@"Exception caught in %s %@", _cmd, e);
995 - (NSMenuItem *)recurseMenuItemForTag:(int)tag rootMenu:(NSMenu *)root
998 NSMenuItem *item = [root itemWithTag:tag];
1000 lastMenuSearched = root;
1004 NSArray *items = [root itemArray];
1005 unsigned i, count = [items count];
1006 for (i = 0; i < count; ++i) {
1007 item = [items objectAtIndex:i];
1008 if ([item hasSubmenu]) {
1009 item = [self recurseMenuItemForTag:tag
1010 rootMenu:[item submenu]];
1012 lastMenuSearched = [item submenu];
1022 - (NSMenuItem *)menuItemForTag:(int)tag
1024 // First search the same menu that was search last time this method was
1025 // called. Since this method is often called for each menu item in a
1026 // menu this can significantly improve search times.
1027 if (lastMenuSearched) {
1028 NSMenuItem *item = [self recurseMenuItemForTag:tag
1029 rootMenu:lastMenuSearched];
1030 if (item) return item;
1033 // Search the main menu.
1034 int i, count = [mainMenuItems count];
1035 for (i = 0; i < count; ++i) {
1036 NSMenuItem *item = [mainMenuItems objectAtIndex:i];
1037 if ([item tag] == tag) return item;
1038 item = [self recurseMenuItemForTag:tag rootMenu:[item submenu]];
1040 lastMenuSearched = [item submenu];
1045 // Search the popup menus.
1046 count = [popupMenuItems count];
1047 for (i = 0; i < count; ++i) {
1048 NSMenuItem *item = [popupMenuItems objectAtIndex:i];
1049 if ([item tag] == tag) return item;
1050 item = [self recurseMenuItemForTag:tag rootMenu:[item submenu]];
1052 lastMenuSearched = [item submenu];
1060 - (NSMenu *)menuForTag:(int)tag
1062 return [[self menuItemForTag:tag] submenu];
1065 - (NSMenu *)topLevelMenuForTitle:(NSString *)title
1067 // Search only the top-level menus.
1069 unsigned i, count = [popupMenuItems count];
1070 for (i = 0; i < count; ++i) {
1071 NSMenuItem *item = [popupMenuItems objectAtIndex:i];
1072 if ([title isEqual:[item title]])
1073 return [item submenu];
1076 count = [mainMenuItems count];
1077 for (i = 0; i < count; ++i) {
1078 NSMenuItem *item = [mainMenuItems objectAtIndex:i];
1079 if ([title isEqual:[item title]])
1080 return [item submenu];
1086 - (void)addMenuWithTag:(int)tag parent:(int)parentTag title:(NSString *)title
1089 NSMenu *parent = [self menuForTag:parentTag];
1090 NSMenuItem *item = [[NSMenuItem alloc] init];
1091 NSMenu *menu = [[NSMenu alloc] initWithTitle:title];
1093 [menu setAutoenablesItems:NO];
1095 [item setTitle:title];
1096 [item setSubmenu:menu];
1099 if ([parent numberOfItems] <= idx) {
1100 [parent addItem:item];
1102 [parent insertItem:item atIndex:idx];
1105 NSMutableArray *items = (MenuPopupType == parentTag)
1106 ? popupMenuItems : mainMenuItems;
1107 if ([items count] <= idx) {
1108 [items addObject:item];
1110 [items insertObject:item atIndex:idx];
1113 shouldUpdateMainMenu = (MenuPopupType != parentTag);
1120 - (void)addMenuItemWithTag:(int)tag parent:(NSMenu *)parent
1121 title:(NSString *)title tip:(NSString *)tip
1122 keyEquivalent:(int)key modifiers:(int)mask
1123 action:(NSString *)action atIndex:(int)idx
1126 NSMenuItem *item = nil;
1127 if (!title || ([title hasPrefix:@"-"] && [title hasSuffix:@"-"])) {
1128 item = [NSMenuItem separatorItem];
1130 item = [[[NSMenuItem alloc] init] autorelease];
1131 [item setTitle:title];
1132 // TODO: Check that 'action' is a valid action (nothing will happen
1133 // if it isn't, but it would be nice with a warning).
1134 if (action) [item setAction:NSSelectorFromString(action)];
1135 else [item setAction:@selector(vimMenuItemAction:)];
1136 if (tip) [item setToolTip:tip];
1139 NSString *keyString =
1140 [NSString stringWithFormat:@"%C", key];
1141 [item setKeyEquivalent:keyString];
1142 [item setKeyEquivalentModifierMask:mask];
1146 // NOTE! The tag is used to idenfity which menu items were
1147 // added by Vim (tag != 0) and which were added by the AppKit
1151 if ([parent numberOfItems] <= idx) {
1152 [parent addItem:item];
1154 [parent insertItem:item atIndex:idx];
1157 NSLog(@"WARNING: Menu item '%@' (tag=%d) has no parent.", title, tag);
1161 - (void)updateMainMenu
1163 NSMenu *mainMenu = [NSApp mainMenu];
1165 // Stop NSApp from updating the Window menu.
1166 [NSApp setWindowsMenu:nil];
1168 // Remove all menus from main menu (except the MacVim menu).
1169 int i, count = [mainMenu numberOfItems];
1170 for (i = count-1; i > 0; --i) {
1171 [mainMenu removeItemAtIndex:i];
1174 // Add menus from 'mainMenuItems' to main menu.
1175 count = [mainMenuItems count];
1176 for (i = 0; i < count; ++i) {
1177 [mainMenu addItem:[mainMenuItems objectAtIndex:i]];
1180 // Set the new Window menu.
1181 // TODO! Need to look for 'Window' in all localized languages.
1182 NSMenu *windowMenu = [[mainMenu itemWithTitle:@"Window"] submenu];
1184 // Remove all AppKit owned menu items (tag == 0); they will be added
1185 // again when setWindowsMenu: is called.
1186 count = [windowMenu numberOfItems];
1187 for (i = count-1; i >= 0; --i) {
1188 NSMenuItem *item = [windowMenu itemAtIndex:i];
1190 [windowMenu removeItem:item];
1194 [NSApp setWindowsMenu:windowMenu];
1197 shouldUpdateMainMenu = NO;
1200 - (NSToolbarItem *)toolbarItemForTag:(int)tag index:(int *)index
1202 if (!toolbar) return nil;
1204 NSArray *items = [toolbar items];
1205 int i, count = [items count];
1206 for (i = 0; i < count; ++i) {
1207 NSToolbarItem *item = [items objectAtIndex:i];
1208 if ([item tag] == tag) {
1209 if (index) *index = i;
1217 - (void)addToolbarItemToDictionaryWithTag:(int)tag label:(NSString *)title
1218 toolTip:(NSString *)tip icon:(NSString *)icon
1220 // If the item corresponds to a separator then do nothing, since it is
1221 // already defined by Cocoa.
1222 if (!title || [title isEqual:NSToolbarSeparatorItemIdentifier]
1223 || [title isEqual:NSToolbarSpaceItemIdentifier]
1224 || [title isEqual:NSToolbarFlexibleSpaceItemIdentifier])
1227 NSToolbarItem *item = [[NSToolbarItem alloc] initWithItemIdentifier:title];
1229 [item setLabel:title];
1230 [item setToolTip:tip];
1231 [item setAction:@selector(vimMenuItemAction:)];
1232 [item setAutovalidates:NO];
1234 NSImage *img = [NSImage imageNamed:icon];
1236 NSLog(@"WARNING: Could not find image with name '%@' to use as toolbar"
1237 " image for identifier '%@';"
1238 " using default toolbar icon '%@' instead.",
1239 icon, title, MMDefaultToolbarImageName);
1241 img = [NSImage imageNamed:MMDefaultToolbarImageName];
1244 [item setImage:img];
1246 [toolbarItemDict setObject:item forKey:title];
1251 - (void)addToolbarItemWithTag:(int)tag label:(NSString *)label tip:(NSString
1252 *)tip icon:(NSString *)icon atIndex:(int)idx
1254 if (!toolbar) return;
1256 // Check for separator items.
1258 label = NSToolbarSeparatorItemIdentifier;
1259 } else if ([label length] >= 2 && [label hasPrefix:@"-"]
1260 && [label hasSuffix:@"-"]) {
1261 // The label begins and ends with '-'; decided which kind of separator
1262 // item it is by looking at the prefix.
1263 if ([label hasPrefix:@"-space"]) {
1264 label = NSToolbarSpaceItemIdentifier;
1265 } else if ([label hasPrefix:@"-flexspace"]) {
1266 label = NSToolbarFlexibleSpaceItemIdentifier;
1268 label = NSToolbarSeparatorItemIdentifier;
1272 [self addToolbarItemToDictionaryWithTag:tag label:label toolTip:tip
1275 int maxIdx = [[toolbar items] count];
1276 if (maxIdx < idx) idx = maxIdx;
1278 [toolbar insertItemWithItemIdentifier:label atIndex:idx];
1281 - (void)connectionDidDie:(NSNotification *)notification
1283 //NSLog(@"%@ %s%@", [self className], _cmd, notification);
1287 // NOTE! This causes the call to removeVimController: to be delayed.
1289 performSelectorOnMainThread:@selector(removeVimController:)
1290 withObject:self waitUntilDone:NO];
1293 - (NSString *)description
1295 return [NSString stringWithFormat:@"%@ : isInitialized=%d inProcessCommandQueue=%d mainMenuItems=%@ popupMenuItems=%@ toolbar=%@", [self className], isInitialized, inProcessCommandQueue, mainMenuItems, popupMenuItems, toolbar];
1298 #if MM_RESEND_LAST_FAILURE
1299 - (void)resendTimerFired:(NSTimer *)timer
1301 int msgid = resendMsgid;
1304 [resendTimer release];
1311 data = [resendData copy];
1313 //NSLog(@"Resending message: %s", MessageStrings[msgid]);
1314 [self sendMessage:msgid data:data];
1318 @end // MMVimController (Private)
1322 @implementation NSColor (MMProtocol)
1324 + (NSColor *)colorWithRgbInt:(unsigned)rgb
1326 float r = ((rgb>>16) & 0xff)/255.0f;
1327 float g = ((rgb>>8) & 0xff)/255.0f;
1328 float b = (rgb & 0xff)/255.0f;
1330 return [NSColor colorWithCalibratedRed:r green:g blue:b alpha:1.0f];
1333 + (NSColor *)colorWithArgbInt:(unsigned)argb
1335 float a = ((argb>>24) & 0xff)/255.0f;
1336 float r = ((argb>>16) & 0xff)/255.0f;
1337 float g = ((argb>>8) & 0xff)/255.0f;
1338 float b = (argb & 0xff)/255.0f;
1340 return [NSColor colorWithCalibratedRed:r green:g blue:b alpha:a];
1343 @end // NSColor (MMProtocol)
1347 @implementation MMAlert
1350 [textField release];
1354 - (void)setTextFieldString:(NSString *)textFieldString
1356 [textField release];
1357 textField = [[NSTextField alloc] init];
1358 [textField setStringValue:textFieldString];
1361 - (NSTextField *)textField
1366 - (void)setInformativeText:(NSString *)text
1369 // HACK! Add some space for the text field.
1370 [super setInformativeText:[text stringByAppendingString:@"\n\n\n"]];
1372 [super setInformativeText:text];
1376 - (void)beginSheetModalForWindow:(NSWindow *)window
1377 modalDelegate:(id)delegate
1378 didEndSelector:(SEL)didEndSelector
1379 contextInfo:(void *)contextInfo
1381 [super beginSheetModalForWindow:window
1382 modalDelegate:delegate
1383 didEndSelector:didEndSelector
1384 contextInfo:contextInfo];
1386 // HACK! Place the input text field at the bottom of the informative text
1387 // (which has been made a bit larger by adding newline characters).
1388 NSView *contentView = [[self window] contentView];
1389 NSRect rect = [contentView frame];
1390 rect.origin.y = rect.size.height;
1392 NSArray *subviews = [contentView subviews];
1393 unsigned i, count = [subviews count];
1394 for (i = 0; i < count; ++i) {
1395 NSView *view = [subviews objectAtIndex:i];
1396 if ([view isKindOfClass:[NSTextField class]]
1397 && [view frame].origin.y < rect.origin.y) {
1398 // NOTE: The informative text field is the lowest NSTextField in
1399 // the alert dialog.
1400 rect = [view frame];
1404 rect.size.height = MMAlertTextFieldHeight;
1405 [textField setFrame:rect];
1406 [contentView addSubview:textField];
1407 [textField becomeFirstResponder];