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.
11 #import "MMVimController.h"
12 #import "MMWindowController.h"
13 #import "MMTextView.h"
14 #import "MMAppController.h"
15 #import "MMTextStorage.h"
18 // This is taken from gui.h
19 #define DRAW_CURSOR 0x20
21 static NSString *MMDefaultToolbarImageName = @"Attention";
22 static int MMAlertTextFieldHeight = 22;
24 // NOTE: By default a message sent to the backend will be dropped if it cannot
25 // be delivered instantly; otherwise there is a possibility that MacVim will
26 // 'beachball' while waiting to deliver DO messages to an unresponsive Vim
27 // process. This means that you cannot rely on any message sent with
28 // sendMessage: to actually reach Vim.
29 static NSTimeInterval MMBackendProxyRequestTimeout = 0;
31 #if MM_RESEND_LAST_FAILURE
32 // If a message send fails, the message will be resent after this many seconds
33 // have passed. (No queue is kept, only the very last message is resent.)
34 static NSTimeInterval MMResendInterval = 0.5;
38 @interface MMAlert : NSAlert {
39 NSTextField *textField;
41 - (void)setTextFieldString:(NSString *)textFieldString;
42 - (NSTextField *)textField;
46 @interface MMVimController (Private)
47 - (void)handleMessage:(int)msgid data:(NSData *)data;
48 - (void)performBatchDrawWithData:(NSData *)data;
49 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
50 context:(void *)context;
51 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context;
52 - (NSMenuItem *)menuItemForTag:(int)tag;
53 - (NSMenu *)menuForTag:(int)tag;
54 - (NSMenu *)topLevelMenuForTitle:(NSString *)title;
55 - (void)addMenuWithTag:(int)tag parent:(int)parentTag title:(NSString *)title
57 - (void)addMenuItemWithTag:(int)tag parent:(NSMenu *)parent
58 title:(NSString *)title tip:(NSString *)tip
59 keyEquivalent:(int)key modifiers:(int)mask
60 action:(NSString *)action atIndex:(int)idx;
61 - (void)updateMainMenu;
62 - (NSToolbarItem *)toolbarItemForTag:(int)tag index:(int *)index;
63 - (void)addToolbarItemToDictionaryWithTag:(int)tag label:(NSString *)title
64 toolTip:(NSString *)tip icon:(NSString *)icon;
65 - (void)addToolbarItemWithTag:(int)tag label:(NSString *)label
66 tip:(NSString *)tip icon:(NSString *)icon
68 - (void)connectionDidDie:(NSNotification *)notification;
69 #if MM_RESEND_LAST_FAILURE
70 - (void)resendTimerFired:(NSTimer *)timer;
76 // TODO: Move to separate file
77 @interface NSColor (MMProtocol)
78 + (NSColor *)colorWithRgbInt:(unsigned)rgb;
79 + (NSColor *)colorWithArgbInt:(unsigned)argb;
84 static NSMenuItem *findMenuItemWithTagInMenu(NSMenu *root, int tag)
87 NSMenuItem *item = [root itemWithTag:tag];
88 if (item) return item;
90 NSArray *items = [root itemArray];
91 unsigned i, count = [items count];
92 for (i = 0; i < count; ++i) {
93 item = [items objectAtIndex:i];
94 if ([item hasSubmenu]) {
95 item = findMenuItemWithTagInMenu([item submenu], tag);
96 if (item) return item;
106 @implementation MMVimController
108 - (id)initWithBackend:(id)backend pid:(int)processIdentifier
110 if ((self = [super init])) {
112 [[MMWindowController alloc] initWithVimController:self];
113 backendProxy = [backend retain];
114 sendQueue = [NSMutableArray new];
115 mainMenuItems = [[NSMutableArray alloc] init];
116 popupMenuItems = [[NSMutableArray alloc] init];
117 toolbarItemDict = [[NSMutableDictionary alloc] init];
118 pid = processIdentifier;
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];
131 NSWindow *win = [windowController window];
133 [[NSNotificationCenter defaultCenter]
135 selector:@selector(windowDidBecomeMain:)
136 name:NSWindowDidBecomeMainNotification
147 //NSLog(@"%@ %s", [self className], _cmd);
150 #if MM_RESEND_LAST_FAILURE
151 [resendData release]; resendData = nil;
154 [serverName release]; serverName = nil;
155 [backendProxy release]; backendProxy = nil;
156 [sendQueue release]; sendQueue = nil;
158 [toolbarItemDict release]; toolbarItemDict = nil;
159 [toolbar release]; toolbar = nil;
160 [popupMenuItems release]; popupMenuItems = nil;
161 [mainMenuItems release]; mainMenuItems = nil;
162 [windowController release]; windowController = nil;
167 - (MMWindowController *)windowController
169 return windowController;
172 - (void)setServerName:(NSString *)name
174 if (name != serverName) {
175 [serverName release];
176 serverName = [name copy];
180 - (NSString *)serverName
190 - (void)dropFiles:(NSArray *)filenames
192 int i, numberOfFiles = [filenames count];
193 NSMutableData *data = [NSMutableData data];
195 [data appendBytes:&numberOfFiles length:sizeof(int)];
197 for (i = 0; i < numberOfFiles; ++i) {
198 NSString *file = [filenames objectAtIndex:i];
199 int len = [file lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
202 ++len; // include NUL as well
203 [data appendBytes:&len length:sizeof(int)];
204 [data appendBytes:[file UTF8String] length:len];
208 [self sendMessage:DropFilesMsgID data:data];
211 - (void)dropString:(NSString *)string
213 int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
215 NSMutableData *data = [NSMutableData data];
217 [data appendBytes:&len length:sizeof(int)];
218 [data appendBytes:[string UTF8String] length:len];
220 [self sendMessage:DropStringMsgID data:data];
224 - (void)sendMessage:(int)msgid data:(NSData *)data
226 //NSLog(@"sendMessage:%s (isInitialized=%d inProcessCommandQueue=%d)",
227 // MessageStrings[msgid], isInitialized, inProcessCommandQueue);
229 if (!isInitialized) return;
231 if (inProcessCommandQueue) {
232 //NSLog(@"In process command queue; delaying message send.");
233 [sendQueue addObject:[NSNumber numberWithInt:msgid]];
235 [sendQueue addObject:data];
237 [sendQueue addObject:[NSNull null]];
241 #if MM_RESEND_LAST_FAILURE
243 //NSLog(@"cancelling scheduled resend of %s",
244 // MessageStrings[resendMsgid]);
246 [resendTimer invalidate];
247 [resendTimer release];
252 [resendData release];
258 [backendProxy processInput:msgid data:data];
260 @catch (NSException *e) {
261 //NSLog(@"%@ %s Exception caught during DO call: %@",
262 // [self className], _cmd, e);
263 #if MM_RESEND_LAST_FAILURE
264 //NSLog(@"%s failed, scheduling message %s for resend", _cmd,
265 // MessageStrings[msgid]);
268 resendData = [data retain];
269 resendTimer = [NSTimer
270 scheduledTimerWithTimeInterval:MMResendInterval
272 selector:@selector(resendTimerFired:)
275 [resendTimer retain];
280 - (BOOL)sendMessageNow:(int)msgid data:(NSData *)data
281 timeout:(NSTimeInterval)timeout
283 if (!isInitialized || inProcessCommandQueue)
286 if (timeout < 0) timeout = 0;
289 NSConnection *conn = [backendProxy connectionForProxy];
290 NSTimeInterval oldTimeout = [conn requestTimeout];
292 [conn setRequestTimeout:timeout];
295 [backendProxy processInput:msgid data:data];
297 @catch (NSException *e) {
301 [conn setRequestTimeout:oldTimeout];
314 //NSLog(@"%@ %s", [self className], _cmd);
315 if (!isInitialized) return;
318 [toolbar setDelegate:nil];
319 [[NSNotificationCenter defaultCenter] removeObserver:self];
320 [windowController cleanup];
323 - (oneway void)showSavePanelForDirectory:(in bycopy NSString *)dir
324 title:(in bycopy NSString *)title
327 if (!isInitialized) return;
330 [[NSSavePanel savePanel] beginSheetForDirectory:dir file:nil
331 modalForWindow:[windowController window]
333 didEndSelector:@selector(savePanelDidEnd:code:context:)
336 NSOpenPanel *panel = [NSOpenPanel openPanel];
337 [panel setAllowsMultipleSelection:NO];
338 [panel beginSheetForDirectory:dir file:nil types:nil
339 modalForWindow:[windowController window]
341 didEndSelector:@selector(savePanelDidEnd:code:context:)
346 - (oneway void)presentDialogWithStyle:(int)style
347 message:(in bycopy NSString *)message
348 informativeText:(in bycopy NSString *)text
349 buttonTitles:(in bycopy NSArray *)buttonTitles
350 textFieldString:(in bycopy NSString *)textFieldString
352 if (!(windowController && buttonTitles && [buttonTitles count])) return;
354 MMAlert *alert = [[MMAlert alloc] init];
356 // NOTE! This has to be done before setting the informative text.
358 [alert setTextFieldString:textFieldString];
360 [alert setAlertStyle:style];
363 [alert setMessageText:message];
365 // If no message text is specified 'Alert' is used, which we don't
366 // want, so set an empty string as message text.
367 [alert setMessageText:@""];
371 [alert setInformativeText:text];
372 } else if (textFieldString) {
373 // Make sure there is always room for the input text field.
374 [alert setInformativeText:@""];
377 unsigned i, count = [buttonTitles count];
378 for (i = 0; i < count; ++i) {
379 NSString *title = [buttonTitles objectAtIndex:i];
380 // NOTE: The title of the button may contain the character '&' to
381 // indicate that the following letter should be the key equivalent
382 // associated with the button. Extract this letter and lowercase it.
383 NSString *keyEquivalent = nil;
384 NSRange hotkeyRange = [title rangeOfString:@"&"];
385 if (NSNotFound != hotkeyRange.location) {
386 if ([title length] > NSMaxRange(hotkeyRange)) {
387 NSRange keyEquivRange = NSMakeRange(hotkeyRange.location+1, 1);
388 keyEquivalent = [[title substringWithRange:keyEquivRange]
392 NSMutableString *string = [NSMutableString stringWithString:title];
393 [string deleteCharactersInRange:hotkeyRange];
397 [alert addButtonWithTitle:title];
399 // Set key equivalent for the button, but only if NSAlert hasn't
400 // already done so. (Check the documentation for
401 // - [NSAlert addButtonWithTitle:] to see what key equivalents are
402 // automatically assigned.)
403 NSButton *btn = [[alert buttons] lastObject];
404 if ([[btn keyEquivalent] length] == 0 && keyEquivalent) {
405 [btn setKeyEquivalent:keyEquivalent];
409 [alert beginSheetModalForWindow:[windowController window]
411 didEndSelector:@selector(alertDidEnd:code:context:)
417 - (oneway void)processCommandQueue:(in NSArray *)queue
419 if (!isInitialized) return;
421 unsigned i, count = [queue count];
423 NSLog(@"WARNING: Uneven number of components (%d) in flush queue "
424 "message; ignoring this message.", count);
428 inProcessCommandQueue = YES;
430 //NSLog(@"======== %s BEGIN ========", _cmd);
431 for (i = 0; i < count; i += 2) {
432 NSData *value = [queue objectAtIndex:i];
433 NSData *data = [queue objectAtIndex:i+1];
435 int msgid = *((int*)[value bytes]);
437 if (msgid != EnableMenuItemMsgID && msgid != AddMenuItemMsgID
438 && msgid != AddMenuMsgID) {
439 NSLog(@"%s%s", _cmd, MessageStrings[msgid]);
443 [self handleMessage:msgid data:data];
445 //NSLog(@"======== %s END ========", _cmd);
447 if (shouldUpdateMainMenu) {
448 [self updateMainMenu];
451 [windowController processCommandQueueDidFinish];
453 inProcessCommandQueue = NO;
455 if ([sendQueue count] > 0) {
457 [backendProxy processInputAndData:sendQueue];
459 @catch (NSException *e) {
460 // Connection timed out, just ignore this.
461 //NSLog(@"WARNING! Connection timed out in %s", _cmd);
464 [sendQueue removeAllObjects];
468 - (void)windowDidBecomeMain:(NSNotification *)notification
471 [self updateMainMenu];
474 - (NSToolbarItem *)toolbar:(NSToolbar *)theToolbar
475 itemForItemIdentifier:(NSString *)itemId
476 willBeInsertedIntoToolbar:(BOOL)flag
478 NSToolbarItem *item = [toolbarItemDict objectForKey:itemId];
480 NSLog(@"WARNING: No toolbar item with id '%@'", itemId);
486 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)theToolbar
491 - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)theToolbar
496 @end // MMVimController
500 @implementation MMVimController (Private)
502 - (void)handleMessage:(int)msgid data:(NSData *)data
504 //NSLog(@"%@ %s", [self className], _cmd);
506 if (OpenVimWindowMsgID == msgid) {
507 [windowController openWindow];
508 } else if (BatchDrawMsgID == msgid) {
509 [self performBatchDrawWithData:data];
510 } else if (SelectTabMsgID == msgid) {
511 #if 0 // NOTE: Tab selection is done inside updateTabsWithData:.
512 const void *bytes = [data bytes];
513 int idx = *((int*)bytes);
514 //NSLog(@"Selecting tab with index %d", idx);
515 [windowController selectTabWithIndex:idx];
517 } else if (UpdateTabBarMsgID == msgid) {
518 [windowController updateTabsWithData:data];
519 } else if (ShowTabBarMsgID == msgid) {
520 [windowController showTabBar:YES];
521 } else if (HideTabBarMsgID == msgid) {
522 [windowController showTabBar:NO];
523 } else if (SetTextDimensionsMsgID == msgid) {
524 const void *bytes = [data bytes];
525 int rows = *((int*)bytes); bytes += sizeof(int);
526 int cols = *((int*)bytes); bytes += sizeof(int);
528 [windowController setTextDimensionsWithRows:rows columns:cols];
529 } else if (SetWindowTitleMsgID == msgid) {
530 const void *bytes = [data bytes];
531 int len = *((int*)bytes); bytes += sizeof(int);
533 NSString *string = [[NSString alloc] initWithBytes:(void*)bytes
534 length:len encoding:NSUTF8StringEncoding];
536 [[windowController window] setTitle:string];
539 } else if (AddMenuMsgID == msgid) {
540 NSString *title = nil;
541 const void *bytes = [data bytes];
542 int tag = *((int*)bytes); bytes += sizeof(int);
543 int parentTag = *((int*)bytes); bytes += sizeof(int);
544 int len = *((int*)bytes); bytes += sizeof(int);
546 title = [[NSString alloc] initWithBytes:(void*)bytes length:len
547 encoding:NSUTF8StringEncoding];
550 int idx = *((int*)bytes); bytes += sizeof(int);
552 if (MenuToolbarType == parentTag) {
554 // NOTE! Each toolbar must have a unique identifier, else each
555 // window will have the same toolbar.
556 NSString *ident = [NSString stringWithFormat:@"%d.%d",
558 toolbar = [[NSToolbar alloc] initWithIdentifier:ident];
560 [toolbar setShowsBaselineSeparator:NO];
561 [toolbar setDelegate:self];
562 [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
563 [toolbar setSizeMode:NSToolbarSizeModeSmall];
565 NSWindow *win = [windowController window];
566 [win setToolbar:toolbar];
568 // HACK! Redirect the pill button so that we can ask Vim to
570 NSButton *pillButton = [win
571 standardWindowButton:NSWindowToolbarButton];
573 [pillButton setAction:@selector(toggleToolbar:)];
574 [pillButton setTarget:windowController];
578 [self addMenuWithTag:tag parent:parentTag title:title atIndex:idx];
582 } else if (AddMenuItemMsgID == msgid) {
583 NSString *title = nil, *tip = nil, *icon = nil, *action = nil;
584 const void *bytes = [data bytes];
585 int tag = *((int*)bytes); bytes += sizeof(int);
586 int parentTag = *((int*)bytes); bytes += sizeof(int);
587 int namelen = *((int*)bytes); bytes += sizeof(int);
589 title = [[NSString alloc] initWithBytes:(void*)bytes length:namelen
590 encoding:NSUTF8StringEncoding];
593 int tiplen = *((int*)bytes); bytes += sizeof(int);
595 tip = [[NSString alloc] initWithBytes:(void*)bytes length:tiplen
596 encoding:NSUTF8StringEncoding];
599 int iconlen = *((int*)bytes); bytes += sizeof(int);
601 icon = [[NSString alloc] initWithBytes:(void*)bytes length:iconlen
602 encoding:NSUTF8StringEncoding];
605 int actionlen = *((int*)bytes); bytes += sizeof(int);
607 action = [[NSString alloc] initWithBytes:(void*)bytes
609 encoding:NSUTF8StringEncoding];
612 int idx = *((int*)bytes); bytes += sizeof(int);
613 if (idx < 0) idx = 0;
614 int key = *((int*)bytes); bytes += sizeof(int);
615 int mask = *((int*)bytes); bytes += sizeof(int);
617 NSString *ident = [NSString stringWithFormat:@"%d.%d",
618 (int)self, parentTag];
619 if (toolbar && [[toolbar identifier] isEqual:ident]) {
620 [self addToolbarItemWithTag:tag label:title tip:tip icon:icon
623 NSMenu *parent = [self menuForTag:parentTag];
624 [self addMenuItemWithTag:tag parent:parent title:title tip:tip
625 keyEquivalent:key modifiers:mask action:action
633 } else if (RemoveMenuItemMsgID == msgid) {
634 const void *bytes = [data bytes];
635 int tag = *((int*)bytes); bytes += sizeof(int);
639 if ((item = [self toolbarItemForTag:tag index:&idx])) {
640 [toolbar removeItemAtIndex:idx];
641 } else if ((item = [self menuItemForTag:tag])) {
644 if ([item menu] == [NSApp mainMenu] || ![item menu]) {
645 // NOTE: To be on the safe side we try to remove the item from
646 // both arrays (it is ok to call removeObject: even if an array
647 // does not contain the object to remove).
648 [mainMenuItems removeObject:item];
649 [popupMenuItems removeObject:item];
653 [[item menu] removeItem:item];
657 } else if (EnableMenuItemMsgID == msgid) {
658 const void *bytes = [data bytes];
659 int tag = *((int*)bytes); bytes += sizeof(int);
660 int state = *((int*)bytes); bytes += sizeof(int);
662 id item = [self toolbarItemForTag:tag index:NULL];
664 item = [self menuItemForTag:tag];
666 [item setEnabled:state];
667 } else if (ShowToolbarMsgID == msgid) {
668 const void *bytes = [data bytes];
669 int enable = *((int*)bytes); bytes += sizeof(int);
670 int flags = *((int*)bytes); bytes += sizeof(int);
672 int mode = NSToolbarDisplayModeDefault;
673 if (flags & ToolbarLabelFlag) {
674 mode = flags & ToolbarIconFlag ? NSToolbarDisplayModeIconAndLabel
675 : NSToolbarDisplayModeLabelOnly;
676 } else if (flags & ToolbarIconFlag) {
677 mode = NSToolbarDisplayModeIconOnly;
680 int size = flags & ToolbarSizeRegularFlag ? NSToolbarSizeModeRegular
681 : NSToolbarSizeModeSmall;
683 [windowController showToolbar:enable size:size mode:mode];
684 } else if (CreateScrollbarMsgID == msgid) {
685 const void *bytes = [data bytes];
686 long ident = *((long*)bytes); bytes += sizeof(long);
687 int type = *((int*)bytes); bytes += sizeof(int);
689 [windowController createScrollbarWithIdentifier:ident type:type];
690 } else if (DestroyScrollbarMsgID == msgid) {
691 const void *bytes = [data bytes];
692 long ident = *((long*)bytes); bytes += sizeof(long);
694 [windowController destroyScrollbarWithIdentifier:ident];
695 } else if (ShowScrollbarMsgID == msgid) {
696 const void *bytes = [data bytes];
697 long ident = *((long*)bytes); bytes += sizeof(long);
698 int visible = *((int*)bytes); bytes += sizeof(int);
700 [windowController showScrollbarWithIdentifier:ident state:visible];
701 } else if (SetScrollbarPositionMsgID == msgid) {
702 const void *bytes = [data bytes];
703 long ident = *((long*)bytes); bytes += sizeof(long);
704 int pos = *((int*)bytes); bytes += sizeof(int);
705 int len = *((int*)bytes); bytes += sizeof(int);
707 [windowController setScrollbarPosition:pos length:len
709 } else if (SetScrollbarThumbMsgID == msgid) {
710 const void *bytes = [data bytes];
711 long ident = *((long*)bytes); bytes += sizeof(long);
712 float val = *((float*)bytes); bytes += sizeof(float);
713 float prop = *((float*)bytes); bytes += sizeof(float);
715 [windowController setScrollbarThumbValue:val proportion:prop
717 } else if (SetFontMsgID == msgid) {
718 const void *bytes = [data bytes];
719 float size = *((float*)bytes); bytes += sizeof(float);
720 int len = *((int*)bytes); bytes += sizeof(int);
721 NSString *name = [[NSString alloc]
722 initWithBytes:(void*)bytes length:len
723 encoding:NSUTF8StringEncoding];
724 NSFont *font = [NSFont fontWithName:name size:size];
727 [windowController setFont:font];
730 } else if (SetDefaultColorsMsgID == msgid) {
731 const void *bytes = [data bytes];
732 unsigned bg = *((unsigned*)bytes); bytes += sizeof(unsigned);
733 unsigned fg = *((unsigned*)bytes); bytes += sizeof(unsigned);
734 NSColor *back = [NSColor colorWithArgbInt:bg];
735 NSColor *fore = [NSColor colorWithRgbInt:fg];
737 [windowController setDefaultColorsBackground:back foreground:fore];
738 } else if (ExecuteActionMsgID == msgid) {
739 const void *bytes = [data bytes];
740 int len = *((int*)bytes); bytes += sizeof(int);
741 NSString *actionName = [[NSString alloc]
742 initWithBytesNoCopy:(void*)bytes
744 encoding:NSUTF8StringEncoding
747 SEL sel = NSSelectorFromString(actionName);
748 [NSApp sendAction:sel to:nil from:self];
750 [actionName release];
751 } else if (ShowPopupMenuMsgID == msgid) {
752 const void *bytes = [data bytes];
753 int row = *((int*)bytes); bytes += sizeof(int);
754 int col = *((int*)bytes); bytes += sizeof(int);
755 int len = *((int*)bytes); bytes += sizeof(int);
756 NSString *title = [[NSString alloc]
757 initWithBytesNoCopy:(void*)bytes
759 encoding:NSUTF8StringEncoding
762 NSMenu *menu = [self topLevelMenuForTitle:title];
764 [windowController popupMenu:menu atRow:row column:col];
766 NSLog(@"WARNING: Cannot popup menu with title %@; no such menu.",
771 } else if (SetMouseShapeMsgID == msgid) {
772 const void *bytes = [data bytes];
773 int shape = *((int*)bytes); bytes += sizeof(int);
775 [windowController setMouseShape:shape];
776 } else if (AdjustLinespaceMsgID == msgid) {
777 const void *bytes = [data bytes];
778 int linespace = *((int*)bytes); bytes += sizeof(int);
780 [windowController adjustLinespace:linespace];
781 } else if (ActivateMsgID == msgid) {
782 [NSApp activateIgnoringOtherApps:YES];
783 [[windowController window] makeKeyAndOrderFront:self];
784 } else if (SetServerNameMsgID == msgid) {
785 NSString *name = [[NSString alloc] initWithData:data
786 encoding:NSUTF8StringEncoding];
787 [self setServerName:name];
789 } else if (EnterFullscreenMsgID == msgid) {
790 [windowController enterFullscreen];
791 } else if (LeaveFullscreenMsgID == msgid) {
792 [windowController leaveFullscreen];
794 NSLog(@"WARNING: Unknown message received (msgid=%d)", msgid);
799 #define MM_DEBUG_DRAWING 0
801 - (void)performBatchDrawWithData:(NSData *)data
803 // TODO! Move to window controller.
804 MMTextStorage *textStorage = [windowController textStorage];
805 MMTextView *textView = [windowController textView];
806 if (!(textStorage && textView))
809 const void *bytes = [data bytes];
810 const void *end = bytes + [data length];
813 NSLog(@"====> BEGIN %s", _cmd);
815 [textStorage beginEditing];
817 // TODO: Sanity check input
819 while (bytes < end) {
820 int type = *((int*)bytes); bytes += sizeof(int);
822 if (ClearAllDrawType == type) {
824 NSLog(@" Clear all");
826 [textStorage clearAll];
827 } else if (ClearBlockDrawType == type) {
828 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
829 int row1 = *((int*)bytes); bytes += sizeof(int);
830 int col1 = *((int*)bytes); bytes += sizeof(int);
831 int row2 = *((int*)bytes); bytes += sizeof(int);
832 int col2 = *((int*)bytes); bytes += sizeof(int);
835 NSLog(@" Clear block (%d,%d) -> (%d,%d)", row1, col1,
838 [textStorage clearBlockFromRow:row1 column:col1
839 toRow:row2 column:col2
840 color:[NSColor colorWithArgbInt:color]];
841 } else if (DeleteLinesDrawType == type) {
842 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
843 int row = *((int*)bytes); bytes += sizeof(int);
844 int count = *((int*)bytes); bytes += sizeof(int);
845 int bot = *((int*)bytes); bytes += sizeof(int);
846 int left = *((int*)bytes); bytes += sizeof(int);
847 int right = *((int*)bytes); bytes += sizeof(int);
850 NSLog(@" Delete %d line(s) from %d", count, row);
852 [textStorage deleteLinesFromRow:row lineCount:count
853 scrollBottom:bot left:left right:right
854 color:[NSColor colorWithArgbInt:color]];
855 } else if (ReplaceStringDrawType == type) {
856 int bg = *((int*)bytes); bytes += sizeof(int);
857 int fg = *((int*)bytes); bytes += sizeof(int);
858 int sp = *((int*)bytes); bytes += sizeof(int);
859 int row = *((int*)bytes); bytes += sizeof(int);
860 int col = *((int*)bytes); bytes += sizeof(int);
861 int flags = *((int*)bytes); bytes += sizeof(int);
862 int len = *((int*)bytes); bytes += sizeof(int);
863 NSString *string = [[NSString alloc]
864 initWithBytesNoCopy:(void*)bytes
866 encoding:NSUTF8StringEncoding
871 NSLog(@" Draw string at (%d,%d) length=%d flags=%d fg=0x%x "
872 "bg=0x%x sp=0x%x (%@)", row, col, len, flags, fg, bg, sp,
873 len > 0 ? [string substringToIndex:1] : @"");
875 // NOTE: If this is a call to draw the (block) cursor, then cancel
876 // any previous request to draw the insertion point, or it might
877 // get drawn as well.
878 if (flags & DRAW_CURSOR) {
879 [textView setShouldDrawInsertionPoint:NO];
880 //NSColor *color = [NSColor colorWithRgbInt:bg];
881 //[textView drawInsertionPointAtRow:row column:col
882 // shape:MMInsertionPointBlock
885 [textStorage replaceString:string
888 foregroundColor:[NSColor colorWithRgbInt:fg]
889 backgroundColor:[NSColor colorWithArgbInt:bg]
890 specialColor:[NSColor colorWithRgbInt:sp]];
893 } else if (InsertLinesDrawType == type) {
894 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
895 int row = *((int*)bytes); bytes += sizeof(int);
896 int count = *((int*)bytes); bytes += sizeof(int);
897 int bot = *((int*)bytes); bytes += sizeof(int);
898 int left = *((int*)bytes); bytes += sizeof(int);
899 int right = *((int*)bytes); bytes += sizeof(int);
902 NSLog(@" Insert %d line(s) at row %d", count, row);
904 [textStorage insertLinesAtRow:row lineCount:count
905 scrollBottom:bot left:left right:right
906 color:[NSColor colorWithArgbInt:color]];
907 } else if (DrawCursorDrawType == type) {
908 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
909 int row = *((int*)bytes); bytes += sizeof(int);
910 int col = *((int*)bytes); bytes += sizeof(int);
911 int shape = *((int*)bytes); bytes += sizeof(int);
912 int percent = *((int*)bytes); bytes += sizeof(int);
915 NSLog(@" Draw cursor at (%d,%d)", row, col);
917 [textView drawInsertionPointAtRow:row column:col shape:shape
919 color:[NSColor colorWithRgbInt:color]];
921 NSLog(@"WARNING: Unknown draw type (type=%d)", type);
925 [textStorage endEditing];
927 NSLog(@"<==== END %s", _cmd);
931 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
932 context:(void *)context
934 NSString *string = (code == NSOKButton) ? [panel filename] : nil;
936 [backendProxy setDialogReturn:string];
938 @catch (NSException *e) {
939 NSLog(@"Exception caught in %s %@", _cmd, e);
943 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context
947 code = code - NSAlertFirstButtonReturn + 1;
949 if ([alert isKindOfClass:[MMAlert class]] && [alert textField]) {
950 ret = [NSArray arrayWithObjects:[NSNumber numberWithInt:code],
951 [[alert textField] stringValue], nil];
953 ret = [NSArray arrayWithObject:[NSNumber numberWithInt:code]];
957 [backendProxy setDialogReturn:ret];
959 @catch (NSException *e) {
960 NSLog(@"Exception caught in %s %@", _cmd, e);
964 - (NSMenuItem *)menuItemForTag:(int)tag
966 // Search the main menu.
967 int i, count = [mainMenuItems count];
968 for (i = 0; i < count; ++i) {
969 NSMenuItem *item = [mainMenuItems objectAtIndex:i];
970 if ([item tag] == tag) return item;
971 item = findMenuItemWithTagInMenu([item submenu], tag);
972 if (item) return item;
975 // Search the popup menus.
976 count = [popupMenuItems count];
977 for (i = 0; i < count; ++i) {
978 NSMenuItem *item = [popupMenuItems objectAtIndex:i];
979 if ([item tag] == tag) return item;
980 item = findMenuItemWithTagInMenu([item submenu], tag);
981 if (item) return item;
987 - (NSMenu *)menuForTag:(int)tag
989 return [[self menuItemForTag:tag] submenu];
992 - (NSMenu *)topLevelMenuForTitle:(NSString *)title
994 // Search only the top-level menus.
996 unsigned i, count = [popupMenuItems count];
997 for (i = 0; i < count; ++i) {
998 NSMenuItem *item = [popupMenuItems objectAtIndex:i];
999 if ([title isEqual:[item title]])
1000 return [item submenu];
1003 count = [mainMenuItems count];
1004 for (i = 0; i < count; ++i) {
1005 NSMenuItem *item = [mainMenuItems objectAtIndex:i];
1006 if ([title isEqual:[item title]])
1007 return [item submenu];
1013 - (void)addMenuWithTag:(int)tag parent:(int)parentTag title:(NSString *)title
1016 NSMenu *parent = [self menuForTag:parentTag];
1017 NSMenuItem *item = [[NSMenuItem alloc] init];
1018 NSMenu *menu = [[NSMenu alloc] initWithTitle:title];
1020 [menu setAutoenablesItems:NO];
1022 [item setTitle:title];
1023 [item setSubmenu:menu];
1026 if ([parent numberOfItems] <= idx) {
1027 [parent addItem:item];
1029 [parent insertItem:item atIndex:idx];
1032 NSMutableArray *items = (MenuPopupType == parentTag)
1033 ? popupMenuItems : mainMenuItems;
1034 if ([items count] <= idx) {
1035 [items addObject:item];
1037 [items insertObject:item atIndex:idx];
1040 shouldUpdateMainMenu = (MenuPopupType != parentTag);
1047 - (void)addMenuItemWithTag:(int)tag parent:(NSMenu *)parent
1048 title:(NSString *)title tip:(NSString *)tip
1049 keyEquivalent:(int)key modifiers:(int)mask
1050 action:(NSString *)action atIndex:(int)idx
1053 NSMenuItem *item = nil;
1054 if (!title || ([title hasPrefix:@"-"] && [title hasSuffix:@"-"])) {
1055 item = [NSMenuItem separatorItem];
1057 item = [[[NSMenuItem alloc] init] autorelease];
1058 [item setTitle:title];
1059 // TODO: Check that 'action' is a valid action (nothing will happen
1060 // if it isn't, but it would be nice with a warning).
1061 if (action) [item setAction:NSSelectorFromString(action)];
1062 else [item setAction:@selector(vimMenuItemAction:)];
1063 if (tip) [item setToolTip:tip];
1066 NSString *keyString =
1067 [NSString stringWithFormat:@"%C", key];
1068 [item setKeyEquivalent:keyString];
1069 [item setKeyEquivalentModifierMask:mask];
1073 // NOTE! The tag is used to idenfity which menu items were
1074 // added by Vim (tag != 0) and which were added by the AppKit
1078 if ([parent numberOfItems] <= idx) {
1079 [parent addItem:item];
1081 [parent insertItem:item atIndex:idx];
1084 NSLog(@"WARNING: Menu item '%@' (tag=%d) has no parent.", title, tag);
1088 - (void)updateMainMenu
1090 NSMenu *mainMenu = [NSApp mainMenu];
1092 // Stop NSApp from updating the Window menu.
1093 [NSApp setWindowsMenu:nil];
1095 // Remove all menus from main menu (except the MacVim menu).
1096 int i, count = [mainMenu numberOfItems];
1097 for (i = count-1; i > 0; --i) {
1098 [mainMenu removeItemAtIndex:i];
1101 // Add menus from 'mainMenuItems' to main menu.
1102 count = [mainMenuItems count];
1103 for (i = 0; i < count; ++i) {
1104 [mainMenu addItem:[mainMenuItems objectAtIndex:i]];
1107 // Set the new Window menu.
1108 // TODO! Need to look for 'Window' in all localized languages.
1109 NSMenu *windowMenu = [[mainMenu itemWithTitle:@"Window"] submenu];
1111 // Remove all AppKit owned menu items (tag == 0); they will be added
1112 // again when setWindowsMenu: is called.
1113 count = [windowMenu numberOfItems];
1114 for (i = count-1; i >= 0; --i) {
1115 NSMenuItem *item = [windowMenu itemAtIndex:i];
1117 [windowMenu removeItem:item];
1121 [NSApp setWindowsMenu:windowMenu];
1124 shouldUpdateMainMenu = NO;
1127 - (NSToolbarItem *)toolbarItemForTag:(int)tag index:(int *)index
1129 if (!toolbar) return nil;
1131 NSArray *items = [toolbar items];
1132 int i, count = [items count];
1133 for (i = 0; i < count; ++i) {
1134 NSToolbarItem *item = [items objectAtIndex:i];
1135 if ([item tag] == tag) {
1136 if (index) *index = i;
1144 - (void)addToolbarItemToDictionaryWithTag:(int)tag label:(NSString *)title
1145 toolTip:(NSString *)tip icon:(NSString *)icon
1147 // If the item corresponds to a separator then do nothing, since it is
1148 // already defined by Cocoa.
1149 if (!title || [title isEqual:NSToolbarSeparatorItemIdentifier]
1150 || [title isEqual:NSToolbarSpaceItemIdentifier]
1151 || [title isEqual:NSToolbarFlexibleSpaceItemIdentifier])
1154 NSToolbarItem *item = [[NSToolbarItem alloc] initWithItemIdentifier:title];
1156 [item setLabel:title];
1157 [item setToolTip:tip];
1158 [item setAction:@selector(vimMenuItemAction:)];
1159 [item setAutovalidates:NO];
1161 NSImage *img = [NSImage imageNamed:icon];
1163 NSLog(@"WARNING: Could not find image with name '%@' to use as toolbar"
1164 " image for identifier '%@';"
1165 " using default toolbar icon '%@' instead.",
1166 icon, title, MMDefaultToolbarImageName);
1168 img = [NSImage imageNamed:MMDefaultToolbarImageName];
1171 [item setImage:img];
1173 [toolbarItemDict setObject:item forKey:title];
1178 - (void)addToolbarItemWithTag:(int)tag label:(NSString *)label tip:(NSString
1179 *)tip icon:(NSString *)icon atIndex:(int)idx
1181 if (!toolbar) return;
1183 // Check for separator items.
1185 label = NSToolbarSeparatorItemIdentifier;
1186 } else if ([label length] >= 2 && [label hasPrefix:@"-"]
1187 && [label hasSuffix:@"-"]) {
1188 // The label begins and ends with '-'; decided which kind of separator
1189 // item it is by looking at the prefix.
1190 if ([label hasPrefix:@"-space"]) {
1191 label = NSToolbarSpaceItemIdentifier;
1192 } else if ([label hasPrefix:@"-flexspace"]) {
1193 label = NSToolbarFlexibleSpaceItemIdentifier;
1195 label = NSToolbarSeparatorItemIdentifier;
1199 [self addToolbarItemToDictionaryWithTag:tag label:label toolTip:tip
1202 int maxIdx = [[toolbar items] count];
1203 if (maxIdx < idx) idx = maxIdx;
1205 [toolbar insertItemWithItemIdentifier:label atIndex:idx];
1208 - (void)connectionDidDie:(NSNotification *)notification
1210 //NSLog(@"%@ %s%@", [self className], _cmd, notification);
1214 // NOTE! This causes the call to removeVimController: to be delayed.
1216 performSelectorOnMainThread:@selector(removeVimController:)
1217 withObject:self waitUntilDone:NO];
1220 - (NSString *)description
1222 return [NSString stringWithFormat:@"%@ : isInitialized=%d inProcessCommandQueue=%d mainMenuItems=%@ popupMenuItems=%@ toolbar=%@", [self className], isInitialized, inProcessCommandQueue, mainMenuItems, popupMenuItems, toolbar];
1225 #if MM_RESEND_LAST_FAILURE
1226 - (void)resendTimerFired:(NSTimer *)timer
1228 int msgid = resendMsgid;
1231 [resendTimer release];
1238 data = [resendData copy];
1240 //NSLog(@"Resending message: %s", MessageStrings[msgid]);
1241 [self sendMessage:msgid data:data];
1245 @end // MMVimController (Private)
1249 @implementation NSColor (MMProtocol)
1251 + (NSColor *)colorWithRgbInt:(unsigned)rgb
1253 float r = ((rgb>>16) & 0xff)/255.0f;
1254 float g = ((rgb>>8) & 0xff)/255.0f;
1255 float b = (rgb & 0xff)/255.0f;
1257 return [NSColor colorWithCalibratedRed:r green:g blue:b alpha:1.0f];
1260 + (NSColor *)colorWithArgbInt:(unsigned)argb
1262 float a = ((argb>>24) & 0xff)/255.0f;
1263 float r = ((argb>>16) & 0xff)/255.0f;
1264 float g = ((argb>>8) & 0xff)/255.0f;
1265 float b = (argb & 0xff)/255.0f;
1267 return [NSColor colorWithCalibratedRed:r green:g blue:b alpha:a];
1270 @end // NSColor (MMProtocol)
1274 @implementation MMAlert
1277 [textField release];
1281 - (void)setTextFieldString:(NSString *)textFieldString
1283 [textField release];
1284 textField = [[NSTextField alloc] init];
1285 [textField setStringValue:textFieldString];
1288 - (NSTextField *)textField
1293 - (void)setInformativeText:(NSString *)text
1296 // HACK! Add some space for the text field.
1297 [super setInformativeText:[text stringByAppendingString:@"\n\n\n"]];
1299 [super setInformativeText:text];
1303 - (void)beginSheetModalForWindow:(NSWindow *)window
1304 modalDelegate:(id)delegate
1305 didEndSelector:(SEL)didEndSelector
1306 contextInfo:(void *)contextInfo
1308 [super beginSheetModalForWindow:window
1309 modalDelegate:delegate
1310 didEndSelector:didEndSelector
1311 contextInfo:contextInfo];
1313 // HACK! Place the input text field at the bottom of the informative text
1314 // (which has been made a bit larger by adding newline characters).
1315 NSView *contentView = [[self window] contentView];
1316 NSRect rect = [contentView frame];
1317 rect.origin.y = rect.size.height;
1319 NSArray *subviews = [contentView subviews];
1320 unsigned i, count = [subviews count];
1321 for (i = 0; i < count; ++i) {
1322 NSView *view = [subviews objectAtIndex:i];
1323 if ([view isKindOfClass:[NSTextField class]]
1324 && [view frame].origin.y < rect.origin.y) {
1325 // NOTE: The informative text field is the lowest NSTextField in
1326 // the alert dialog.
1327 rect = [view frame];
1331 rect.size.height = MMAlertTextFieldHeight;
1332 [textField setFrame:rect];
1333 [contentView addSubview:textField];
1334 [textField becomeFirstResponder];