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:(int)rgb;
83 static NSMenuItem *findMenuItemWithTagInMenu(NSMenu *root, int tag)
86 NSMenuItem *item = [root itemWithTag:tag];
87 if (item) return item;
89 NSArray *items = [root itemArray];
90 unsigned i, count = [items count];
91 for (i = 0; i < count; ++i) {
92 item = [items objectAtIndex:i];
93 if ([item hasSubmenu]) {
94 item = findMenuItemWithTagInMenu([item submenu], tag);
95 if (item) return item;
105 @implementation MMVimController
107 - (id)initWithBackend:(id)backend pid:(int)processIdentifier
109 if ((self = [super init])) {
111 [[MMWindowController alloc] initWithVimController:self];
112 backendProxy = [backend retain];
113 sendQueue = [NSMutableArray new];
114 mainMenuItems = [[NSMutableArray alloc] init];
115 popupMenuItems = [[NSMutableArray alloc] init];
116 toolbarItemDict = [[NSMutableDictionary alloc] init];
117 pid = processIdentifier;
119 NSConnection *connection = [backendProxy connectionForProxy];
121 // TODO: Check that this will not set the timeout for the root proxy
122 // (in MMAppController).
123 [connection setRequestTimeout:MMBackendProxyRequestTimeout];
125 [[NSNotificationCenter defaultCenter] addObserver:self
126 selector:@selector(connectionDidDie:)
127 name:NSConnectionDidDieNotification object:connection];
130 NSWindow *win = [windowController window];
132 [[NSNotificationCenter defaultCenter]
134 selector:@selector(windowDidBecomeMain:)
135 name:NSWindowDidBecomeMainNotification
146 //NSLog(@"%@ %s", [self className], _cmd);
149 #if MM_RESEND_LAST_FAILURE
150 [resendData release]; resendData = nil;
153 [serverName release]; serverName = nil;
154 [backendProxy release]; backendProxy = nil;
155 [sendQueue release]; sendQueue = nil;
157 [toolbarItemDict release]; toolbarItemDict = nil;
158 [toolbar release]; toolbar = nil;
159 [popupMenuItems release]; popupMenuItems = nil;
160 [mainMenuItems release]; mainMenuItems = nil;
161 [windowController release]; windowController = nil;
166 - (MMWindowController *)windowController
168 return windowController;
171 - (void)setServerName:(NSString *)name
173 if (name != serverName) {
174 [serverName release];
175 serverName = [name copy];
179 - (NSString *)serverName
189 - (void)dropFiles:(NSArray *)filenames
191 int i, numberOfFiles = [filenames count];
192 NSMutableData *data = [NSMutableData data];
194 [data appendBytes:&numberOfFiles length:sizeof(int)];
196 for (i = 0; i < numberOfFiles; ++i) {
197 NSString *file = [filenames objectAtIndex:i];
198 int len = [file lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
201 ++len; // append NUL as well
202 [data appendBytes:&len length:sizeof(int)];
203 [data appendBytes:[file UTF8String] length:len];
207 [self sendMessage:DropFilesMsgID data:data];
210 - (void)dropString:(NSString *)string
212 int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
214 NSMutableData *data = [NSMutableData data];
216 [data appendBytes:&len length:sizeof(int)];
217 [data appendBytes:[string UTF8String] length:len];
219 [self sendMessage:DropStringMsgID data:data];
223 - (void)sendMessage:(int)msgid data:(NSData *)data
225 //NSLog(@"sendMessage:%s (isInitialized=%d inProcessCommandQueue=%d)",
226 // MessageStrings[msgid], isInitialized, inProcessCommandQueue);
228 if (!isInitialized) return;
230 if (inProcessCommandQueue) {
231 //NSLog(@"In process command queue; delaying message send.");
232 [sendQueue addObject:[NSNumber numberWithInt:msgid]];
234 [sendQueue addObject:data];
236 [sendQueue addObject:[NSNull null]];
240 #if MM_RESEND_LAST_FAILURE
242 //NSLog(@"cancelling scheduled resend of %s",
243 // MessageStrings[resendMsgid]);
245 [resendTimer invalidate];
246 [resendTimer release];
251 [resendData release];
257 [backendProxy processInput:msgid data:data];
259 @catch (NSException *e) {
260 //NSLog(@"%@ %s Exception caught during DO call: %@",
261 // [self className], _cmd, e);
262 #if MM_RESEND_LAST_FAILURE
263 //NSLog(@"%s failed, scheduling message %s for resend", _cmd,
264 // MessageStrings[msgid]);
267 resendData = [data retain];
268 resendTimer = [NSTimer
269 scheduledTimerWithTimeInterval:MMResendInterval
271 selector:@selector(resendTimerFired:)
274 [resendTimer retain];
286 //NSLog(@"%@ %s", [self className], _cmd);
287 if (!isInitialized) return;
290 [toolbar setDelegate:nil];
291 [[NSNotificationCenter defaultCenter] removeObserver:self];
292 [windowController cleanup];
295 - (oneway void)showSavePanelForDirectory:(in bycopy NSString *)dir
296 title:(in bycopy NSString *)title
299 if (!isInitialized) return;
302 [[NSSavePanel savePanel] beginSheetForDirectory:dir file:nil
303 modalForWindow:[windowController window]
305 didEndSelector:@selector(savePanelDidEnd:code:context:)
308 NSOpenPanel *panel = [NSOpenPanel openPanel];
309 [panel setAllowsMultipleSelection:NO];
310 [panel beginSheetForDirectory:dir file:nil types:nil
311 modalForWindow:[windowController window]
313 didEndSelector:@selector(savePanelDidEnd:code:context:)
318 - (oneway void)presentDialogWithStyle:(int)style
319 message:(in bycopy NSString *)message
320 informativeText:(in bycopy NSString *)text
321 buttonTitles:(in bycopy NSArray *)buttonTitles
322 textFieldString:(in bycopy NSString *)textFieldString
324 if (!(windowController && buttonTitles && [buttonTitles count])) return;
326 MMAlert *alert = [[MMAlert alloc] init];
328 // NOTE! This has to be done before setting the informative text.
330 [alert setTextFieldString:textFieldString];
332 [alert setAlertStyle:style];
335 [alert setMessageText:message];
337 // If no message text is specified 'Alert' is used, which we don't
338 // want, so set an empty string as message text.
339 [alert setMessageText:@""];
343 [alert setInformativeText:text];
344 } else if (textFieldString) {
345 // Make sure there is always room for the input text field.
346 [alert setInformativeText:@""];
349 unsigned i, count = [buttonTitles count];
350 for (i = 0; i < count; ++i) {
351 NSString *title = [buttonTitles objectAtIndex:i];
352 // NOTE: The title of the button may contain the character '&' to
353 // indicate that the following letter should be the key equivalent
354 // associated with the button. Extract this letter and lowercase it.
355 NSString *keyEquivalent = nil;
356 NSRange hotkeyRange = [title rangeOfString:@"&"];
357 if (NSNotFound != hotkeyRange.location) {
358 if ([title length] > NSMaxRange(hotkeyRange)) {
359 NSRange keyEquivRange = NSMakeRange(hotkeyRange.location+1, 1);
360 keyEquivalent = [[title substringWithRange:keyEquivRange]
364 NSMutableString *string = [NSMutableString stringWithString:title];
365 [string deleteCharactersInRange:hotkeyRange];
369 [alert addButtonWithTitle:title];
371 // Set key equivalent for the button, but only if NSAlert hasn't
372 // already done so. (Check the documentation for
373 // - [NSAlert addButtonWithTitle:] to see what key equivalents are
374 // automatically assigned.)
375 NSButton *btn = [[alert buttons] lastObject];
376 if ([[btn keyEquivalent] length] == 0 && keyEquivalent) {
377 [btn setKeyEquivalent:keyEquivalent];
381 [alert beginSheetModalForWindow:[windowController window]
383 didEndSelector:@selector(alertDidEnd:code:context:)
389 - (oneway void)processCommandQueue:(in NSArray *)queue
391 if (!isInitialized) return;
393 unsigned i, count = [queue count];
395 NSLog(@"WARNING: Uneven number of components (%d) in flush queue "
396 "message; ignoring this message.", count);
400 inProcessCommandQueue = YES;
402 //NSLog(@"======== %s BEGIN ========", _cmd);
403 for (i = 0; i < count; i += 2) {
404 NSData *value = [queue objectAtIndex:i];
405 NSData *data = [queue objectAtIndex:i+1];
407 int msgid = *((int*)[value bytes]);
409 if (msgid != EnableMenuItemMsgID && msgid != AddMenuItemMsgID
410 && msgid != AddMenuMsgID) {
411 NSLog(@"%s%s", _cmd, MessageStrings[msgid]);
415 [self handleMessage:msgid data:data];
417 //NSLog(@"======== %s END ========", _cmd);
419 if (shouldUpdateMainMenu) {
420 [self updateMainMenu];
423 [windowController processCommandQueueDidFinish];
425 inProcessCommandQueue = NO;
427 if ([sendQueue count] > 0) {
429 [backendProxy processInputAndData:sendQueue];
431 @catch (NSException *e) {
432 // Connection timed out, just ignore this.
433 //NSLog(@"WARNING! Connection timed out in %s", _cmd);
436 [sendQueue removeAllObjects];
440 - (void)windowDidBecomeMain:(NSNotification *)notification
443 [self updateMainMenu];
446 - (NSToolbarItem *)toolbar:(NSToolbar *)theToolbar
447 itemForItemIdentifier:(NSString *)itemId
448 willBeInsertedIntoToolbar:(BOOL)flag
450 NSToolbarItem *item = [toolbarItemDict objectForKey:itemId];
452 NSLog(@"WARNING: No toolbar item with id '%@'", itemId);
458 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)theToolbar
463 - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)theToolbar
468 @end // MMVimController
472 @implementation MMVimController (Private)
474 - (void)handleMessage:(int)msgid data:(NSData *)data
476 //NSLog(@"%@ %s", [self className], _cmd);
478 if (OpenVimWindowMsgID == msgid) {
479 [windowController openWindow];
480 } else if (BatchDrawMsgID == msgid) {
481 [self performBatchDrawWithData:data];
482 } else if (SelectTabMsgID == msgid) {
483 #if 0 // NOTE: Tab selection is done inside updateTabsWithData:.
484 const void *bytes = [data bytes];
485 int idx = *((int*)bytes);
486 //NSLog(@"Selecting tab with index %d", idx);
487 [windowController selectTabWithIndex:idx];
489 } else if (UpdateTabBarMsgID == msgid) {
490 [windowController updateTabsWithData:data];
491 } else if (ShowTabBarMsgID == msgid) {
492 [windowController showTabBar:YES];
493 } else if (HideTabBarMsgID == msgid) {
494 [windowController showTabBar:NO];
495 } else if (SetTextDimensionsMsgID == msgid) {
496 const void *bytes = [data bytes];
497 int rows = *((int*)bytes); bytes += sizeof(int);
498 int cols = *((int*)bytes); bytes += sizeof(int);
500 [windowController setTextDimensionsWithRows:rows columns:cols];
501 } else if (SetVimWindowTitleMsgID == msgid) {
502 const void *bytes = [data bytes];
503 int len = *((int*)bytes); bytes += sizeof(int);
505 NSString *string = [[NSString alloc] initWithBytes:(void*)bytes
506 length:len encoding:NSUTF8StringEncoding];
508 [[windowController window] setTitle:string];
511 } else if (AddMenuMsgID == msgid) {
512 NSString *title = nil;
513 const void *bytes = [data bytes];
514 int tag = *((int*)bytes); bytes += sizeof(int);
515 int parentTag = *((int*)bytes); bytes += sizeof(int);
516 int len = *((int*)bytes); bytes += sizeof(int);
518 title = [[NSString alloc] initWithBytes:(void*)bytes length:len
519 encoding:NSUTF8StringEncoding];
522 int idx = *((int*)bytes); bytes += sizeof(int);
524 if (MenuToolbarType == parentTag) {
526 // NOTE! Each toolbar must have a unique identifier, else each
527 // window will have the same toolbar.
528 NSString *ident = [NSString stringWithFormat:@"%d.%d",
530 toolbar = [[NSToolbar alloc] initWithIdentifier:ident];
532 [toolbar setShowsBaselineSeparator:NO];
533 [toolbar setDelegate:self];
534 [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
535 [toolbar setSizeMode:NSToolbarSizeModeSmall];
537 NSWindow *win = [windowController window];
538 [win setToolbar:toolbar];
540 // HACK! Redirect the pill button so that we can ask Vim to
542 NSButton *pillButton = [win
543 standardWindowButton:NSWindowToolbarButton];
545 [pillButton setAction:@selector(toggleToolbar:)];
546 [pillButton setTarget:windowController];
550 [self addMenuWithTag:tag parent:parentTag title:title atIndex:idx];
554 } else if (AddMenuItemMsgID == msgid) {
555 NSString *title = nil, *tip = nil, *icon = nil, *action = nil;
556 const void *bytes = [data bytes];
557 int tag = *((int*)bytes); bytes += sizeof(int);
558 int parentTag = *((int*)bytes); bytes += sizeof(int);
559 int namelen = *((int*)bytes); bytes += sizeof(int);
561 title = [[NSString alloc] initWithBytes:(void*)bytes length:namelen
562 encoding:NSUTF8StringEncoding];
565 int tiplen = *((int*)bytes); bytes += sizeof(int);
567 tip = [[NSString alloc] initWithBytes:(void*)bytes length:tiplen
568 encoding:NSUTF8StringEncoding];
571 int iconlen = *((int*)bytes); bytes += sizeof(int);
573 icon = [[NSString alloc] initWithBytes:(void*)bytes length:iconlen
574 encoding:NSUTF8StringEncoding];
577 int actionlen = *((int*)bytes); bytes += sizeof(int);
579 action = [[NSString alloc] initWithBytes:(void*)bytes
581 encoding:NSUTF8StringEncoding];
584 int idx = *((int*)bytes); bytes += sizeof(int);
585 if (idx < 0) idx = 0;
586 int key = *((int*)bytes); bytes += sizeof(int);
587 int mask = *((int*)bytes); bytes += sizeof(int);
589 NSString *ident = [NSString stringWithFormat:@"%d.%d",
590 (int)self, parentTag];
591 if (toolbar && [[toolbar identifier] isEqual:ident]) {
592 [self addToolbarItemWithTag:tag label:title tip:tip icon:icon
595 NSMenu *parent = [self menuForTag:parentTag];
596 [self addMenuItemWithTag:tag parent:parent title:title tip:tip
597 keyEquivalent:key modifiers:mask action:action
605 } else if (RemoveMenuItemMsgID == msgid) {
606 const void *bytes = [data bytes];
607 int tag = *((int*)bytes); bytes += sizeof(int);
611 if ((item = [self toolbarItemForTag:tag index:&idx])) {
612 [toolbar removeItemAtIndex:idx];
613 } else if ((item = [self menuItemForTag:tag])) {
616 if ([item menu] == [NSApp mainMenu] || ![item menu]) {
617 // NOTE: To be on the safe side we try to remove the item from
618 // both arrays (it is ok to call removeObject: even if an array
619 // does not contain the object to remove).
620 [mainMenuItems removeObject:item];
621 [popupMenuItems removeObject:item];
625 [[item menu] removeItem:item];
629 } else if (EnableMenuItemMsgID == msgid) {
630 const void *bytes = [data bytes];
631 int tag = *((int*)bytes); bytes += sizeof(int);
632 int state = *((int*)bytes); bytes += sizeof(int);
634 id item = [self toolbarItemForTag:tag index:NULL];
636 item = [self menuItemForTag:tag];
638 [item setEnabled:state];
639 } else if (ShowToolbarMsgID == msgid) {
640 const void *bytes = [data bytes];
641 int enable = *((int*)bytes); bytes += sizeof(int);
642 int flags = *((int*)bytes); bytes += sizeof(int);
644 int mode = NSToolbarDisplayModeDefault;
645 if (flags & ToolbarLabelFlag) {
646 mode = flags & ToolbarIconFlag ? NSToolbarDisplayModeIconAndLabel
647 : NSToolbarDisplayModeLabelOnly;
648 } else if (flags & ToolbarIconFlag) {
649 mode = NSToolbarDisplayModeIconOnly;
652 int size = flags & ToolbarSizeRegularFlag ? NSToolbarSizeModeRegular
653 : NSToolbarSizeModeSmall;
655 [windowController showToolbar:enable size:size mode:mode];
656 } else if (CreateScrollbarMsgID == msgid) {
657 const void *bytes = [data bytes];
658 long ident = *((long*)bytes); bytes += sizeof(long);
659 int type = *((int*)bytes); bytes += sizeof(int);
661 [windowController createScrollbarWithIdentifier:ident type:type];
662 } else if (DestroyScrollbarMsgID == msgid) {
663 const void *bytes = [data bytes];
664 long ident = *((long*)bytes); bytes += sizeof(long);
666 [windowController destroyScrollbarWithIdentifier:ident];
667 } else if (ShowScrollbarMsgID == msgid) {
668 const void *bytes = [data bytes];
669 long ident = *((long*)bytes); bytes += sizeof(long);
670 int visible = *((int*)bytes); bytes += sizeof(int);
672 [windowController showScrollbarWithIdentifier:ident state:visible];
673 } else if (SetScrollbarPositionMsgID == msgid) {
674 const void *bytes = [data bytes];
675 long ident = *((long*)bytes); bytes += sizeof(long);
676 int pos = *((int*)bytes); bytes += sizeof(int);
677 int len = *((int*)bytes); bytes += sizeof(int);
679 [windowController setScrollbarPosition:pos length:len
681 } else if (SetScrollbarThumbMsgID == msgid) {
682 const void *bytes = [data bytes];
683 long ident = *((long*)bytes); bytes += sizeof(long);
684 float val = *((float*)bytes); bytes += sizeof(float);
685 float prop = *((float*)bytes); bytes += sizeof(float);
687 [windowController setScrollbarThumbValue:val proportion:prop
689 } else if (SetFontMsgID == msgid) {
690 const void *bytes = [data bytes];
691 float size = *((float*)bytes); bytes += sizeof(float);
692 int len = *((int*)bytes); bytes += sizeof(int);
693 NSString *name = [[NSString alloc]
694 initWithBytes:(void*)bytes length:len
695 encoding:NSUTF8StringEncoding];
696 NSFont *font = [NSFont fontWithName:name size:size];
699 [windowController setFont:font];
702 } else if (SetDefaultColorsMsgID == msgid) {
703 const void *bytes = [data bytes];
704 int bg = *((int*)bytes); bytes += sizeof(int);
705 int fg = *((int*)bytes); bytes += sizeof(int);
706 NSColor *back = [NSColor colorWithRgbInt:bg];
707 NSColor *fore = [NSColor colorWithRgbInt:fg];
709 [windowController setDefaultColorsBackground:back foreground:fore];
710 } else if (ExecuteActionMsgID == msgid) {
711 const void *bytes = [data bytes];
712 int len = *((int*)bytes); bytes += sizeof(int);
713 NSString *actionName = [[NSString alloc]
714 initWithBytesNoCopy:(void*)bytes
716 encoding:NSUTF8StringEncoding
719 SEL sel = NSSelectorFromString(actionName);
720 [NSApp sendAction:sel to:nil from:self];
722 [actionName release];
723 } else if (ShowPopupMenuMsgID == msgid) {
724 const void *bytes = [data bytes];
725 int row = *((int*)bytes); bytes += sizeof(int);
726 int col = *((int*)bytes); bytes += sizeof(int);
727 int len = *((int*)bytes); bytes += sizeof(int);
728 NSString *title = [[NSString alloc]
729 initWithBytesNoCopy:(void*)bytes
731 encoding:NSUTF8StringEncoding
734 NSMenu *menu = [self topLevelMenuForTitle:title];
736 [windowController popupMenu:menu atRow:row column:col];
738 NSLog(@"WARNING: Cannot popup menu with title %@; no such menu.",
743 } else if (SetMouseShapeMsgID == msgid) {
744 const void *bytes = [data bytes];
745 int shape = *((int*)bytes); bytes += sizeof(int);
747 [windowController setMouseShape:shape];
748 } else if (AdjustLinespaceMsgID == msgid) {
749 const void *bytes = [data bytes];
750 int linespace = *((int*)bytes); bytes += sizeof(int);
752 [windowController adjustLinespace:linespace];
753 } else if (ActivateMsgID == msgid) {
754 [NSApp activateIgnoringOtherApps:YES];
755 [[windowController window] makeKeyAndOrderFront:self];
756 } else if (SetServerNameMsgID == msgid) {
757 NSString *name = [[NSString alloc] initWithData:data
758 encoding:NSUTF8StringEncoding];
759 [self setServerName:name];
762 NSLog(@"WARNING: Unknown message received (msgid=%d)", msgid);
767 #define MM_DEBUG_DRAWING 0
769 - (void)performBatchDrawWithData:(NSData *)data
771 // TODO! Move to window controller.
772 MMTextStorage *textStorage = [windowController textStorage];
773 MMTextView *textView = [windowController textView];
774 if (!(textStorage && textView))
777 const void *bytes = [data bytes];
778 const void *end = bytes + [data length];
781 NSLog(@"====> BEGIN %s", _cmd);
783 [textStorage beginEditing];
785 // TODO: Sanity check input
787 while (bytes < end) {
788 int type = *((int*)bytes); bytes += sizeof(int);
790 if (ClearAllDrawType == type) {
791 int color = *((int*)bytes); bytes += sizeof(int);
794 NSLog(@" Clear all");
796 [textStorage clearAllWithColor:[NSColor colorWithRgbInt:color]];
797 } else if (ClearBlockDrawType == type) {
798 int color = *((int*)bytes); bytes += sizeof(int);
799 int row1 = *((int*)bytes); bytes += sizeof(int);
800 int col1 = *((int*)bytes); bytes += sizeof(int);
801 int row2 = *((int*)bytes); bytes += sizeof(int);
802 int col2 = *((int*)bytes); bytes += sizeof(int);
805 NSLog(@" Clear block (%d,%d) -> (%d,%d)", row1, col1,
808 [textStorage clearBlockFromRow:row1 column:col1
809 toRow:row2 column:col2
810 color:[NSColor colorWithRgbInt:color]];
811 } else if (DeleteLinesDrawType == type) {
812 int color = *((int*)bytes); bytes += sizeof(int);
813 int row = *((int*)bytes); bytes += sizeof(int);
814 int count = *((int*)bytes); bytes += sizeof(int);
815 int bot = *((int*)bytes); bytes += sizeof(int);
816 int left = *((int*)bytes); bytes += sizeof(int);
817 int right = *((int*)bytes); bytes += sizeof(int);
820 NSLog(@" Delete %d line(s) from %d", count, row);
822 [textStorage deleteLinesFromRow:row lineCount:count
823 scrollBottom:bot left:left right:right
824 color:[NSColor colorWithRgbInt:color]];
825 } else if (ReplaceStringDrawType == type) {
826 int bg = *((int*)bytes); bytes += sizeof(int);
827 int fg = *((int*)bytes); bytes += sizeof(int);
828 int sp = *((int*)bytes); bytes += sizeof(int);
829 int row = *((int*)bytes); bytes += sizeof(int);
830 int col = *((int*)bytes); bytes += sizeof(int);
831 int flags = *((int*)bytes); bytes += sizeof(int);
832 int len = *((int*)bytes); bytes += sizeof(int);
833 NSString *string = [[NSString alloc]
834 initWithBytesNoCopy:(void*)bytes
836 encoding:NSUTF8StringEncoding
841 NSLog(@" Draw string at (%d,%d) length=%d flags=%d fg=0x%x "
842 "bg=0x%x sp=0x%x (%@)", row, col, len, flags, fg, bg, sp,
843 len > 0 ? [string substringToIndex:1] : @"");
845 // NOTE: If this is a call to draw the (block) cursor, then cancel
846 // any previous request to draw the insertion point, or it might
847 // get drawn as well.
848 if (flags & DRAW_CURSOR) {
849 [textView setShouldDrawInsertionPoint:NO];
850 //[textView drawInsertionPointAtRow:row column:col
851 // shape:MMInsertionPointBlock
852 // color:[NSColor colorWithRgbInt:bg]];
854 [textStorage replaceString:string
857 foregroundColor:[NSColor colorWithRgbInt:fg]
858 backgroundColor:[NSColor colorWithRgbInt:bg]
859 specialColor:[NSColor colorWithRgbInt:sp]];
862 } else if (InsertLinesDrawType == type) {
863 int color = *((int*)bytes); bytes += sizeof(int);
864 int row = *((int*)bytes); bytes += sizeof(int);
865 int count = *((int*)bytes); bytes += sizeof(int);
866 int bot = *((int*)bytes); bytes += sizeof(int);
867 int left = *((int*)bytes); bytes += sizeof(int);
868 int right = *((int*)bytes); bytes += sizeof(int);
871 NSLog(@" Insert %d line(s) at row %d", count, row);
873 [textStorage insertLinesAtRow:row lineCount:count
874 scrollBottom:bot left:left right:right
875 color:[NSColor colorWithRgbInt:color]];
876 } else if (DrawCursorDrawType == type) {
877 int color = *((int*)bytes); bytes += sizeof(int);
878 int row = *((int*)bytes); bytes += sizeof(int);
879 int col = *((int*)bytes); bytes += sizeof(int);
880 int shape = *((int*)bytes); bytes += sizeof(int);
881 int percent = *((int*)bytes); bytes += sizeof(int);
884 NSLog(@" Draw cursor at (%d,%d)", row, col);
886 [textView drawInsertionPointAtRow:row column:col shape:shape
888 color:[NSColor colorWithRgbInt:color]];
890 NSLog(@"WARNING: Unknown draw type (type=%d)", type);
894 [textStorage endEditing];
896 NSLog(@"<==== END %s", _cmd);
900 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
901 context:(void *)context
903 NSString *string = (code == NSOKButton) ? [panel filename] : nil;
905 [backendProxy setDialogReturn:string];
907 @catch (NSException *e) {
908 NSLog(@"Exception caught in %s %@", _cmd, e);
912 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context
916 code = code - NSAlertFirstButtonReturn + 1;
918 if ([alert isKindOfClass:[MMAlert class]] && [alert textField]) {
919 ret = [NSArray arrayWithObjects:[NSNumber numberWithInt:code],
920 [[alert textField] stringValue], nil];
922 ret = [NSArray arrayWithObject:[NSNumber numberWithInt:code]];
926 [backendProxy setDialogReturn:ret];
928 @catch (NSException *e) {
929 NSLog(@"Exception caught in %s %@", _cmd, e);
933 - (NSMenuItem *)menuItemForTag:(int)tag
935 // Search the main menu.
936 int i, count = [mainMenuItems count];
937 for (i = 0; i < count; ++i) {
938 NSMenuItem *item = [mainMenuItems objectAtIndex:i];
939 if ([item tag] == tag) return item;
940 item = findMenuItemWithTagInMenu([item submenu], tag);
941 if (item) return item;
944 // Search the popup menus.
945 count = [popupMenuItems count];
946 for (i = 0; i < count; ++i) {
947 NSMenuItem *item = [popupMenuItems objectAtIndex:i];
948 if ([item tag] == tag) return item;
949 item = findMenuItemWithTagInMenu([item submenu], tag);
950 if (item) return item;
956 - (NSMenu *)menuForTag:(int)tag
958 return [[self menuItemForTag:tag] submenu];
961 - (NSMenu *)topLevelMenuForTitle:(NSString *)title
963 // Search only the top-level menus.
965 unsigned i, count = [popupMenuItems count];
966 for (i = 0; i < count; ++i) {
967 NSMenuItem *item = [popupMenuItems objectAtIndex:i];
968 if ([title isEqual:[item title]])
969 return [item submenu];
972 count = [mainMenuItems count];
973 for (i = 0; i < count; ++i) {
974 NSMenuItem *item = [mainMenuItems objectAtIndex:i];
975 if ([title isEqual:[item title]])
976 return [item submenu];
982 - (void)addMenuWithTag:(int)tag parent:(int)parentTag title:(NSString *)title
985 NSMenu *parent = [self menuForTag:parentTag];
986 NSMenuItem *item = [[NSMenuItem alloc] init];
987 NSMenu *menu = [[NSMenu alloc] initWithTitle:title];
989 [menu setAutoenablesItems:NO];
991 [item setTitle:title];
992 [item setSubmenu:menu];
995 if ([parent numberOfItems] <= idx) {
996 [parent addItem:item];
998 [parent insertItem:item atIndex:idx];
1001 NSMutableArray *items = (MenuPopupType == parentTag)
1002 ? popupMenuItems : mainMenuItems;
1003 if ([items count] <= idx) {
1004 [items addObject:item];
1006 [items insertObject:item atIndex:idx];
1009 shouldUpdateMainMenu = (MenuPopupType != parentTag);
1016 - (void)addMenuItemWithTag:(int)tag parent:(NSMenu *)parent
1017 title:(NSString *)title tip:(NSString *)tip
1018 keyEquivalent:(int)key modifiers:(int)mask
1019 action:(NSString *)action atIndex:(int)idx
1022 NSMenuItem *item = nil;
1023 if (!title || ([title hasPrefix:@"-"] && [title hasSuffix:@"-"])) {
1024 item = [NSMenuItem separatorItem];
1026 item = [[[NSMenuItem alloc] init] autorelease];
1027 [item setTitle:title];
1028 // TODO: Check that 'action' is a valid action (nothing will happen
1029 // if it isn't, but it would be nice with a warning).
1030 if (action) [item setAction:NSSelectorFromString(action)];
1031 else [item setAction:@selector(vimMenuItemAction:)];
1032 if (tip) [item setToolTip:tip];
1035 NSString *keyString =
1036 [NSString stringWithFormat:@"%C", key];
1037 [item setKeyEquivalent:keyString];
1038 [item setKeyEquivalentModifierMask:mask];
1042 // NOTE! The tag is used to idenfity which menu items were
1043 // added by Vim (tag != 0) and which were added by the AppKit
1047 if ([parent numberOfItems] <= idx) {
1048 [parent addItem:item];
1050 [parent insertItem:item atIndex:idx];
1053 NSLog(@"WARNING: Menu item '%@' (tag=%d) has no parent.", title, tag);
1057 - (void)updateMainMenu
1059 NSMenu *mainMenu = [NSApp mainMenu];
1061 // Stop NSApp from updating the Window menu.
1062 [NSApp setWindowsMenu:nil];
1064 // Remove all menus from main menu (except the MacVim menu).
1065 int i, count = [mainMenu numberOfItems];
1066 for (i = count-1; i > 0; --i) {
1067 [mainMenu removeItemAtIndex:i];
1070 // Add menus from 'mainMenuItems' to main menu.
1071 count = [mainMenuItems count];
1072 for (i = 0; i < count; ++i) {
1073 [mainMenu addItem:[mainMenuItems objectAtIndex:i]];
1076 // Set the new Window menu.
1077 // TODO! Need to look for 'Window' in all localized languages.
1078 NSMenu *windowMenu = [[mainMenu itemWithTitle:@"Window"] submenu];
1080 // Remove all AppKit owned menu items (tag == 0); they will be added
1081 // again when setWindowsMenu: is called.
1082 count = [windowMenu numberOfItems];
1083 for (i = count-1; i >= 0; --i) {
1084 NSMenuItem *item = [windowMenu itemAtIndex:i];
1086 [windowMenu removeItem:item];
1090 [NSApp setWindowsMenu:windowMenu];
1093 shouldUpdateMainMenu = NO;
1096 - (NSToolbarItem *)toolbarItemForTag:(int)tag index:(int *)index
1098 if (!toolbar) return nil;
1100 NSArray *items = [toolbar items];
1101 int i, count = [items count];
1102 for (i = 0; i < count; ++i) {
1103 NSToolbarItem *item = [items objectAtIndex:i];
1104 if ([item tag] == tag) {
1105 if (index) *index = i;
1113 - (void)addToolbarItemToDictionaryWithTag:(int)tag label:(NSString *)title
1114 toolTip:(NSString *)tip icon:(NSString *)icon
1116 // If the item corresponds to a separator then do nothing, since it is
1117 // already defined by Cocoa.
1118 if (!title || [title isEqual:NSToolbarSeparatorItemIdentifier]
1119 || [title isEqual:NSToolbarSpaceItemIdentifier]
1120 || [title isEqual:NSToolbarFlexibleSpaceItemIdentifier])
1123 NSToolbarItem *item = [[NSToolbarItem alloc] initWithItemIdentifier:title];
1125 [item setLabel:title];
1126 [item setToolTip:tip];
1127 [item setAction:@selector(vimMenuItemAction:)];
1128 [item setAutovalidates:NO];
1130 NSImage *img = [NSImage imageNamed:icon];
1132 NSLog(@"WARNING: Could not find image with name '%@' to use as toolbar"
1133 " image for identifier '%@';"
1134 " using default toolbar icon '%@' instead.",
1135 icon, title, MMDefaultToolbarImageName);
1137 img = [NSImage imageNamed:MMDefaultToolbarImageName];
1140 [item setImage:img];
1142 [toolbarItemDict setObject:item forKey:title];
1147 - (void)addToolbarItemWithTag:(int)tag label:(NSString *)label tip:(NSString
1148 *)tip icon:(NSString *)icon atIndex:(int)idx
1150 if (!toolbar) return;
1152 // Check for separator items.
1154 label = NSToolbarSeparatorItemIdentifier;
1155 } else if ([label length] >= 2 && [label hasPrefix:@"-"]
1156 && [label hasSuffix:@"-"]) {
1157 // The label begins and ends with '-'; decided which kind of separator
1158 // item it is by looking at the prefix.
1159 if ([label hasPrefix:@"-space"]) {
1160 label = NSToolbarSpaceItemIdentifier;
1161 } else if ([label hasPrefix:@"-flexspace"]) {
1162 label = NSToolbarFlexibleSpaceItemIdentifier;
1164 label = NSToolbarSeparatorItemIdentifier;
1168 [self addToolbarItemToDictionaryWithTag:tag label:label toolTip:tip
1171 int maxIdx = [[toolbar items] count];
1172 if (maxIdx < idx) idx = maxIdx;
1174 [toolbar insertItemWithItemIdentifier:label atIndex:idx];
1177 - (void)connectionDidDie:(NSNotification *)notification
1179 //NSLog(@"%@ %s%@", [self className], _cmd, notification);
1183 // NOTE! This causes the call to removeVimController: to be delayed.
1185 performSelectorOnMainThread:@selector(removeVimController:)
1186 withObject:self waitUntilDone:NO];
1189 - (NSString *)description
1191 return [NSString stringWithFormat:@"%@ : isInitialized=%d inProcessCommandQueue=%d mainMenuItems=%@ popupMenuItems=%@ toolbar=%@", [self className], isInitialized, inProcessCommandQueue, mainMenuItems, popupMenuItems, toolbar];
1194 #if MM_RESEND_LAST_FAILURE
1195 - (void)resendTimerFired:(NSTimer *)timer
1197 int msgid = resendMsgid;
1200 [resendTimer release];
1207 data = [resendData copy];
1209 //NSLog(@"Resending message: %s", MessageStrings[msgid]);
1210 [self sendMessage:msgid data:data];
1214 @end // MMVimController (Private)
1218 @implementation NSColor (MMProtocol)
1220 + (NSColor *)colorWithRgbInt:(int)rgb
1222 float r = ((rgb>>16) & 0xff)/255.0f;
1223 float g = ((rgb>>8) & 0xff)/255.0f;
1224 float b = (rgb & 0xff)/255.0f;
1226 return [NSColor colorWithCalibratedRed:r green:g blue:b alpha:1.0f];
1229 @end // NSColor (MMProtocol)
1233 @implementation MMAlert
1236 [textField release];
1240 - (void)setTextFieldString:(NSString *)textFieldString
1242 [textField release];
1243 textField = [[NSTextField alloc] init];
1244 [textField setStringValue:textFieldString];
1247 - (NSTextField *)textField
1252 - (void)setInformativeText:(NSString *)text
1255 // HACK! Add some space for the text field.
1256 [super setInformativeText:[text stringByAppendingString:@"\n\n\n"]];
1258 [super setInformativeText:text];
1262 - (void)beginSheetModalForWindow:(NSWindow *)window
1263 modalDelegate:(id)delegate
1264 didEndSelector:(SEL)didEndSelector
1265 contextInfo:(void *)contextInfo
1267 [super beginSheetModalForWindow:window
1268 modalDelegate:delegate
1269 didEndSelector:didEndSelector
1270 contextInfo:contextInfo];
1272 // HACK! Place the input text field at the bottom of the informative text
1273 // (which has been made a bit larger by adding newline characters).
1274 NSView *contentView = [[self window] contentView];
1275 NSRect rect = [contentView frame];
1276 rect.origin.y = rect.size.height;
1278 NSArray *subviews = [contentView subviews];
1279 unsigned i, count = [subviews count];
1280 for (i = 0; i < count; ++i) {
1281 NSView *view = [subviews objectAtIndex:i];
1282 if ([view isKindOfClass:[NSTextField class]]
1283 && [view frame].origin.y < rect.origin.y) {
1284 // NOTE: The informative text field is the lowest NSTextField in
1285 // the alert dialog.
1286 rect = [view frame];
1290 rect.size.height = MMAlertTextFieldHeight;
1291 [textField setFrame:rect];
1292 [contentView addSubview:textField];
1293 [textField becomeFirstResponder];