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 #define MM_NO_REQUEST_TIMEOUT 1
20 // This is taken from gui.h
21 #define DRAW_CURSOR 0x20
23 static NSString *MMDefaultToolbarImageName = @"Attention";
24 static int MMAlertTextFieldHeight = 22;
26 #if MM_NO_REQUEST_TIMEOUT
27 // NOTE: By default a message sent to the backend will be dropped if it cannot
28 // be delivered instantly; otherwise there is a possibility that MacVim will
29 // 'beachball' while waiting to deliver DO messages to an unresponsive Vim
30 // process. This means that you cannot rely on any message sent with
31 // sendMessage:: to actually reach Vim.
32 static NSTimeInterval MMBackendProxyRequestTimeout = 0;
36 @interface MMAlert : NSAlert {
37 NSTextField *textField;
39 - (void)setTextFieldString:(NSString *)textFieldString;
40 - (NSTextField *)textField;
44 @interface MMVimController (Private)
45 - (void)handleMessage:(int)msgid data:(NSData *)data;
46 - (void)performBatchDrawWithData:(NSData *)data;
47 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
48 context:(void *)context;
49 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context;
50 - (NSMenuItem *)menuItemForTag:(int)tag;
51 - (NSMenu *)menuForTag:(int)tag;
52 - (NSMenu *)topLevelMenuForTitle:(NSString *)title;
53 - (void)addMenuWithTag:(int)tag parent:(int)parentTag title:(NSString *)title
55 - (void)addMenuItemWithTag:(int)tag parent:(NSMenu *)parent
56 title:(NSString *)title tip:(NSString *)tip
57 keyEquivalent:(int)key modifiers:(int)mask
58 action:(NSString *)action atIndex:(int)idx;
59 - (void)updateMainMenu;
60 - (NSToolbarItem *)toolbarItemForTag:(int)tag index:(int *)index;
61 - (void)addToolbarItemToDictionaryWithTag:(int)tag label:(NSString *)title
62 toolTip:(NSString *)tip icon:(NSString *)icon;
63 - (void)addToolbarItemWithTag:(int)tag label:(NSString *)label
64 tip:(NSString *)tip icon:(NSString *)icon
66 - (void)connectionDidDie:(NSNotification *)notification;
71 // TODO: Move to separate file
72 @interface NSColor (MMProtocol)
73 + (NSColor *)colorWithRgbInt:(int)rgb;
78 static NSMenuItem *findMenuItemWithTagInMenu(NSMenu *root, int tag)
81 NSMenuItem *item = [root itemWithTag:tag];
82 if (item) return item;
84 NSArray *items = [root itemArray];
85 unsigned i, count = [items count];
86 for (i = 0; i < count; ++i) {
87 item = [items objectAtIndex:i];
88 if ([item hasSubmenu]) {
89 item = findMenuItemWithTagInMenu([item submenu], tag);
90 if (item) return item;
100 @implementation MMVimController
102 - (id)initWithBackend:(id)backend pid:(int)processIdentifier
104 if ((self = [super init])) {
106 [[MMWindowController alloc] initWithVimController:self];
107 backendProxy = [backend retain];
108 sendQueue = [NSMutableArray new];
109 mainMenuItems = [[NSMutableArray alloc] init];
110 popupMenuItems = [[NSMutableArray alloc] init];
111 toolbarItemDict = [[NSMutableDictionary alloc] init];
112 pid = processIdentifier;
114 NSConnection *connection = [backendProxy connectionForProxy];
116 #if MM_NO_REQUEST_TIMEOUT
117 // TODO: Check that this will not set the timeout for the root proxy
118 // (in MMAppController).
119 [connection setRequestTimeout:MMBackendProxyRequestTimeout];
122 [[NSNotificationCenter defaultCenter] addObserver:self
123 selector:@selector(connectionDidDie:)
124 name:NSConnectionDidDieNotification object:connection];
127 NSWindow *win = [windowController window];
129 [[NSNotificationCenter defaultCenter]
131 selector:@selector(windowDidBecomeMain:)
132 name:NSWindowDidBecomeMainNotification
143 //NSLog(@"%@ %s", [self className], _cmd);
146 [backendProxy release]; backendProxy = nil;
147 [sendQueue release]; sendQueue = nil;
149 [toolbarItemDict release]; toolbarItemDict = nil;
150 [toolbar release]; toolbar = nil;
151 [popupMenuItems release]; popupMenuItems = nil;
152 [mainMenuItems release]; mainMenuItems = nil;
153 [windowController release]; windowController = nil;
158 - (MMWindowController *)windowController
160 return windowController;
168 - (void)dropFiles:(NSArray *)filenames
170 int i, numberOfFiles = [filenames count];
171 NSMutableData *data = [NSMutableData data];
173 [data appendBytes:&numberOfFiles length:sizeof(int)];
175 for (i = 0; i < numberOfFiles; ++i) {
176 NSString *file = [filenames objectAtIndex:i];
177 int len = [file lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
180 ++len; // append NUL as well
181 [data appendBytes:&len length:sizeof(int)];
182 [data appendBytes:[file UTF8String] length:len];
186 [self sendMessage:DropFilesMsgID data:data wait:NO];
189 - (void)dropString:(NSString *)string
191 int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
193 NSMutableData *data = [NSMutableData data];
195 [data appendBytes:&len length:sizeof(int)];
196 [data appendBytes:[string UTF8String] length:len];
198 [self sendMessage:DropStringMsgID data:data wait:NO];
202 - (void)sendMessage:(int)msgid data:(NSData *)data wait:(BOOL)wait
204 //NSLog(@"sendMessage:%s (isInitialized=%d inProcessCommandQueue=%d)",
205 // MessageStrings[msgid], isInitialized, inProcessCommandQueue);
207 if (!isInitialized) return;
209 if (inProcessCommandQueue) {
210 //NSLog(@"In process command queue; delaying message send.");
211 [sendQueue addObject:[NSNumber numberWithInt:msgid]];
213 [sendQueue addObject:data];
215 [sendQueue addObject:[NSNull null]];
219 #if MM_NO_REQUEST_TIMEOUT
221 [backendProxy processInput:msgid data:data];
223 @catch (NSException *e) {
224 //NSLog(@"%@ %s Exception caught during DO call: %@",
225 // [self className], _cmd, e);
230 [backendProxy processInput:msgid data:data];
232 @catch (NSException *e) {
233 NSLog(@"%@ %s Exception caught during DO call: %@",
234 [self className], _cmd, e);
237 // Do not wait for the message to be sent, i.e. drop the message if it
238 // can't be delivered immediately.
239 NSConnection *connection = [backendProxy connectionForProxy];
241 NSTimeInterval req = [connection requestTimeout];
242 [connection setRequestTimeout:0];
244 [backendProxy processInput:msgid data:data];
246 @catch (NSException *e) {
247 // Connection timed out, just ignore this.
248 //NSLog(@"WARNING! Connection timed out in %s", _cmd);
251 [connection setRequestTimeout:req];
265 //NSLog(@"%@ %s", [self className], _cmd);
266 if (!isInitialized) return;
269 [toolbar setDelegate:nil];
270 [[NSNotificationCenter defaultCenter] removeObserver:self];
271 [windowController cleanup];
274 - (oneway void)showSavePanelForDirectory:(in bycopy NSString *)dir
275 title:(in bycopy NSString *)title
278 if (!isInitialized) return;
281 [[NSSavePanel savePanel] beginSheetForDirectory:dir file:nil
282 modalForWindow:[windowController window]
284 didEndSelector:@selector(savePanelDidEnd:code:context:)
287 NSOpenPanel *panel = [NSOpenPanel openPanel];
288 [panel setAllowsMultipleSelection:NO];
289 [panel beginSheetForDirectory:dir file:nil types:nil
290 modalForWindow:[windowController window]
292 didEndSelector:@selector(savePanelDidEnd:code:context:)
297 - (oneway void)presentDialogWithStyle:(int)style
298 message:(in bycopy NSString *)message
299 informativeText:(in bycopy NSString *)text
300 buttonTitles:(in bycopy NSArray *)buttonTitles
301 textFieldString:(in bycopy NSString *)textFieldString
303 if (!(windowController && buttonTitles && [buttonTitles count])) return;
305 MMAlert *alert = [[MMAlert alloc] init];
307 // NOTE! This has to be done before setting the informative text.
309 [alert setTextFieldString:textFieldString];
311 [alert setAlertStyle:style];
314 [alert setMessageText:message];
316 // If no message text is specified 'Alert' is used, which we don't
317 // want, so set an empty string as message text.
318 [alert setMessageText:@""];
322 [alert setInformativeText:text];
323 } else if (textFieldString) {
324 // Make sure there is always room for the input text field.
325 [alert setInformativeText:@""];
328 unsigned i, count = [buttonTitles count];
329 for (i = 0; i < count; ++i) {
330 NSString *title = [buttonTitles objectAtIndex:i];
331 // NOTE: The title of the button may contain the character '&' to
332 // indicate that the following letter should be the key equivalent
333 // associated with the button. Extract this letter and lowercase it.
334 NSString *keyEquivalent = nil;
335 NSRange hotkeyRange = [title rangeOfString:@"&"];
336 if (NSNotFound != hotkeyRange.location) {
337 if ([title length] > NSMaxRange(hotkeyRange)) {
338 NSRange keyEquivRange = NSMakeRange(hotkeyRange.location+1, 1);
339 keyEquivalent = [[title substringWithRange:keyEquivRange]
343 NSMutableString *string = [NSMutableString stringWithString:title];
344 [string deleteCharactersInRange:hotkeyRange];
348 [alert addButtonWithTitle:title];
350 // Set key equivalent for the button, but only if NSAlert hasn't
351 // already done so. (Check the documentation for
352 // - [NSAlert addButtonWithTitle:] to see what key equivalents are
353 // automatically assigned.)
354 NSButton *btn = [[alert buttons] lastObject];
355 if ([[btn keyEquivalent] length] == 0 && keyEquivalent) {
356 [btn setKeyEquivalent:keyEquivalent];
360 [alert beginSheetModalForWindow:[windowController window]
362 didEndSelector:@selector(alertDidEnd:code:context:)
368 - (oneway void)processCommandQueue:(in NSArray *)queue
370 if (!isInitialized) return;
372 unsigned i, count = [queue count];
374 NSLog(@"WARNING: Uneven number of components (%d) in flush queue "
375 "message; ignoring this message.", count);
379 inProcessCommandQueue = YES;
381 //NSLog(@"======== %s BEGIN ========", _cmd);
382 for (i = 0; i < count; i += 2) {
383 NSData *value = [queue objectAtIndex:i];
384 NSData *data = [queue objectAtIndex:i+1];
386 int msgid = *((int*)[value bytes]);
388 if (msgid != EnableMenuItemMsgID && msgid != AddMenuItemMsgID
389 && msgid != AddMenuMsgID) {
390 NSLog(@"%s%s", _cmd, MessageStrings[msgid]);
394 [self handleMessage:msgid data:data];
396 //NSLog(@"======== %s END ========", _cmd);
398 if (shouldUpdateMainMenu) {
399 [self updateMainMenu];
402 [windowController processCommandQueueDidFinish];
404 inProcessCommandQueue = NO;
406 if ([sendQueue count] > 0) {
407 #if MM_NO_REQUEST_TIMEOUT
409 [backendProxy processInputAndData:sendQueue];
411 @catch (NSException *e) {
412 // Connection timed out, just ignore this.
413 //NSLog(@"WARNING! Connection timed out in %s", _cmd);
416 // Do not wait for the message to be sent, i.e. drop the message if it
417 // can't be delivered immediately.
418 NSConnection *connection = [backendProxy connectionForProxy];
420 NSTimeInterval req = [connection requestTimeout];
421 [connection setRequestTimeout:0];
423 [backendProxy processInputAndData:sendQueue];
425 @catch (NSException *e) {
426 // Connection timed out, just ignore this.
427 //NSLog(@"WARNING! Connection timed out in %s", _cmd);
430 [connection setRequestTimeout:req];
435 [sendQueue removeAllObjects];
439 - (void)windowDidBecomeMain:(NSNotification *)notification
442 [self updateMainMenu];
445 - (NSToolbarItem *)toolbar:(NSToolbar *)theToolbar
446 itemForItemIdentifier:(NSString *)itemId
447 willBeInsertedIntoToolbar:(BOOL)flag
449 NSToolbarItem *item = [toolbarItemDict objectForKey:itemId];
451 NSLog(@"WARNING: No toolbar item with id '%@'", itemId);
457 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)theToolbar
462 - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)theToolbar
467 @end // MMVimController
471 @implementation MMVimController (Private)
473 - (void)handleMessage:(int)msgid data:(NSData *)data
475 //NSLog(@"%@ %s", [self className], _cmd);
477 if (OpenVimWindowMsgID == msgid) {
478 [windowController openWindow];
479 } else if (BatchDrawMsgID == msgid) {
480 [self performBatchDrawWithData:data];
481 } else if (SelectTabMsgID == msgid) {
482 #if 0 // NOTE: Tab selection is done inside updateTabsWithData:.
483 const void *bytes = [data bytes];
484 int idx = *((int*)bytes);
485 //NSLog(@"Selecting tab with index %d", idx);
486 [windowController selectTabWithIndex:idx];
488 } else if (UpdateTabBarMsgID == msgid) {
489 [windowController updateTabsWithData:data];
490 } else if (ShowTabBarMsgID == msgid) {
491 [windowController showTabBar:YES];
492 } else if (HideTabBarMsgID == msgid) {
493 [windowController showTabBar:NO];
494 } else if (SetTextDimensionsMsgID == msgid) {
495 const void *bytes = [data bytes];
496 int rows = *((int*)bytes); bytes += sizeof(int);
497 int cols = *((int*)bytes); bytes += sizeof(int);
499 [windowController setTextDimensionsWithRows:rows columns:cols];
500 } else if (SetVimWindowTitleMsgID == msgid) {
501 const void *bytes = [data bytes];
502 int len = *((int*)bytes); bytes += sizeof(int);
504 NSString *string = [[NSString alloc] initWithBytes:(void*)bytes
505 length:len encoding:NSUTF8StringEncoding];
507 [[windowController window] setTitle:string];
510 } else if (AddMenuMsgID == msgid) {
511 NSString *title = nil;
512 const void *bytes = [data bytes];
513 int tag = *((int*)bytes); bytes += sizeof(int);
514 int parentTag = *((int*)bytes); bytes += sizeof(int);
515 int len = *((int*)bytes); bytes += sizeof(int);
517 title = [[NSString alloc] initWithBytes:(void*)bytes length:len
518 encoding:NSUTF8StringEncoding];
521 int idx = *((int*)bytes); bytes += sizeof(int);
523 if (MenuToolbarType == parentTag) {
525 // NOTE! Each toolbar must have a unique identifier, else each
526 // window will have the same toolbar.
527 NSString *ident = [NSString stringWithFormat:@"%d.%d",
529 toolbar = [[NSToolbar alloc] initWithIdentifier:ident];
531 [toolbar setShowsBaselineSeparator:NO];
532 [toolbar setDelegate:self];
533 [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
534 [toolbar setSizeMode:NSToolbarSizeModeSmall];
536 NSWindow *win = [windowController window];
537 [win setToolbar:toolbar];
539 // HACK! Redirect the pill button so that we can ask Vim to
541 NSButton *pillButton = [win
542 standardWindowButton:NSWindowToolbarButton];
544 [pillButton setAction:@selector(toggleToolbar:)];
545 [pillButton setTarget:windowController];
549 [self addMenuWithTag:tag parent:parentTag title:title atIndex:idx];
553 } else if (AddMenuItemMsgID == msgid) {
554 NSString *title = nil, *tip = nil, *icon = nil, *action = nil;
555 const void *bytes = [data bytes];
556 int tag = *((int*)bytes); bytes += sizeof(int);
557 int parentTag = *((int*)bytes); bytes += sizeof(int);
558 int namelen = *((int*)bytes); bytes += sizeof(int);
560 title = [[NSString alloc] initWithBytes:(void*)bytes length:namelen
561 encoding:NSUTF8StringEncoding];
564 int tiplen = *((int*)bytes); bytes += sizeof(int);
566 tip = [[NSString alloc] initWithBytes:(void*)bytes length:tiplen
567 encoding:NSUTF8StringEncoding];
570 int iconlen = *((int*)bytes); bytes += sizeof(int);
572 icon = [[NSString alloc] initWithBytes:(void*)bytes length:iconlen
573 encoding:NSUTF8StringEncoding];
576 int actionlen = *((int*)bytes); bytes += sizeof(int);
578 action = [[NSString alloc] initWithBytes:(void*)bytes
580 encoding:NSUTF8StringEncoding];
583 int idx = *((int*)bytes); bytes += sizeof(int);
584 if (idx < 0) idx = 0;
585 int key = *((int*)bytes); bytes += sizeof(int);
586 int mask = *((int*)bytes); bytes += sizeof(int);
588 NSString *ident = [NSString stringWithFormat:@"%d.%d",
589 (int)self, parentTag];
590 if (toolbar && [[toolbar identifier] isEqual:ident]) {
591 [self addToolbarItemWithTag:tag label:title tip:tip icon:icon
594 NSMenu *parent = [self menuForTag:parentTag];
595 [self addMenuItemWithTag:tag parent:parent title:title tip:tip
596 keyEquivalent:key modifiers:mask action:action
604 } else if (RemoveMenuItemMsgID == msgid) {
605 const void *bytes = [data bytes];
606 int tag = *((int*)bytes); bytes += sizeof(int);
610 if ((item = [self toolbarItemForTag:tag index:&idx])) {
611 [toolbar removeItemAtIndex:idx];
612 } else if ((item = [self menuItemForTag:tag])) {
615 if ([item menu] == [NSApp mainMenu] || ![item menu]) {
616 // NOTE: To be on the safe side we try to remove the item from
617 // both arrays (it is ok to call removeObject: even if an array
618 // does not contain the object to remove).
619 [mainMenuItems removeObject:item];
620 [popupMenuItems removeObject:item];
624 [[item menu] removeItem:item];
628 } else if (EnableMenuItemMsgID == msgid) {
629 const void *bytes = [data bytes];
630 int tag = *((int*)bytes); bytes += sizeof(int);
631 int state = *((int*)bytes); bytes += sizeof(int);
633 id item = [self toolbarItemForTag:tag index:NULL];
635 item = [self menuItemForTag:tag];
637 [item setEnabled:state];
638 } else if (ShowToolbarMsgID == msgid) {
639 const void *bytes = [data bytes];
640 int enable = *((int*)bytes); bytes += sizeof(int);
641 int flags = *((int*)bytes); bytes += sizeof(int);
643 int mode = NSToolbarDisplayModeDefault;
644 if (flags & ToolbarLabelFlag) {
645 mode = flags & ToolbarIconFlag ? NSToolbarDisplayModeIconAndLabel
646 : NSToolbarDisplayModeLabelOnly;
647 } else if (flags & ToolbarIconFlag) {
648 mode = NSToolbarDisplayModeIconOnly;
651 int size = flags & ToolbarSizeRegularFlag ? NSToolbarSizeModeRegular
652 : NSToolbarSizeModeSmall;
654 [windowController showToolbar:enable size:size mode:mode];
655 } else if (CreateScrollbarMsgID == msgid) {
656 const void *bytes = [data bytes];
657 long ident = *((long*)bytes); bytes += sizeof(long);
658 int type = *((int*)bytes); bytes += sizeof(int);
660 [windowController createScrollbarWithIdentifier:ident type:type];
661 } else if (DestroyScrollbarMsgID == msgid) {
662 const void *bytes = [data bytes];
663 long ident = *((long*)bytes); bytes += sizeof(long);
665 [windowController destroyScrollbarWithIdentifier:ident];
666 } else if (ShowScrollbarMsgID == msgid) {
667 const void *bytes = [data bytes];
668 long ident = *((long*)bytes); bytes += sizeof(long);
669 int visible = *((int*)bytes); bytes += sizeof(int);
671 [windowController showScrollbarWithIdentifier:ident state:visible];
672 } else if (SetScrollbarPositionMsgID == msgid) {
673 const void *bytes = [data bytes];
674 long ident = *((long*)bytes); bytes += sizeof(long);
675 int pos = *((int*)bytes); bytes += sizeof(int);
676 int len = *((int*)bytes); bytes += sizeof(int);
678 [windowController setScrollbarPosition:pos length:len
680 } else if (SetScrollbarThumbMsgID == msgid) {
681 const void *bytes = [data bytes];
682 long ident = *((long*)bytes); bytes += sizeof(long);
683 float val = *((float*)bytes); bytes += sizeof(float);
684 float prop = *((float*)bytes); bytes += sizeof(float);
686 [windowController setScrollbarThumbValue:val proportion:prop
688 } else if (SetFontMsgID == msgid) {
689 const void *bytes = [data bytes];
690 float size = *((float*)bytes); bytes += sizeof(float);
691 int len = *((int*)bytes); bytes += sizeof(int);
692 NSString *name = [[NSString alloc]
693 initWithBytes:(void*)bytes length:len
694 encoding:NSUTF8StringEncoding];
695 NSFont *font = [NSFont fontWithName:name size:size];
698 [windowController setFont:font];
701 } else if (SetDefaultColorsMsgID == msgid) {
702 const void *bytes = [data bytes];
703 int bg = *((int*)bytes); bytes += sizeof(int);
704 int fg = *((int*)bytes); bytes += sizeof(int);
705 NSColor *back = [NSColor colorWithRgbInt:bg];
706 NSColor *fore = [NSColor colorWithRgbInt:fg];
708 [windowController setDefaultColorsBackground:back foreground:fore];
709 } else if (ExecuteActionMsgID == msgid) {
710 const void *bytes = [data bytes];
711 int len = *((int*)bytes); bytes += sizeof(int);
712 NSString *actionName = [[NSString alloc]
713 initWithBytesNoCopy:(void*)bytes
715 encoding:NSUTF8StringEncoding
718 SEL sel = NSSelectorFromString(actionName);
719 [NSApp sendAction:sel to:nil from:self];
721 [actionName release];
722 } else if (ShowPopupMenuMsgID == msgid) {
723 const void *bytes = [data bytes];
724 int row = *((int*)bytes); bytes += sizeof(int);
725 int col = *((int*)bytes); bytes += sizeof(int);
726 int len = *((int*)bytes); bytes += sizeof(int);
727 NSString *title = [[NSString alloc]
728 initWithBytesNoCopy:(void*)bytes
730 encoding:NSUTF8StringEncoding
733 NSMenu *menu = [self topLevelMenuForTitle:title];
735 [windowController popupMenu:menu atRow:row column:col];
737 NSLog(@"WARNING: Cannot popup menu with title %@; no such menu.",
742 } else if (SetMouseShapeMsgID == msgid) {
743 const void *bytes = [data bytes];
744 int shape = *((int*)bytes); bytes += sizeof(int);
746 [windowController setMouseShape:shape];
748 NSLog(@"WARNING: Unknown message received (msgid=%d)", msgid);
753 #define MM_DEBUG_DRAWING 0
755 - (void)performBatchDrawWithData:(NSData *)data
757 // TODO! Move to window controller.
758 MMTextStorage *textStorage = [windowController textStorage];
759 MMTextView *textView = [windowController textView];
760 if (!(textStorage && textView))
763 const void *bytes = [data bytes];
764 const void *end = bytes + [data length];
767 NSLog(@"====> BEGIN %s", _cmd);
769 [textStorage beginEditing];
771 // TODO: Sanity check input
773 while (bytes < end) {
774 int type = *((int*)bytes); bytes += sizeof(int);
776 if (ClearAllDrawType == type) {
777 int color = *((int*)bytes); bytes += sizeof(int);
780 NSLog(@" Clear all");
782 [textStorage clearAllWithColor:[NSColor colorWithRgbInt:color]];
783 } else if (ClearBlockDrawType == type) {
784 int color = *((int*)bytes); bytes += sizeof(int);
785 int row1 = *((int*)bytes); bytes += sizeof(int);
786 int col1 = *((int*)bytes); bytes += sizeof(int);
787 int row2 = *((int*)bytes); bytes += sizeof(int);
788 int col2 = *((int*)bytes); bytes += sizeof(int);
791 NSLog(@" Clear block (%d,%d) -> (%d,%d)", row1, col1,
794 [textStorage clearBlockFromRow:row1 column:col1
795 toRow:row2 column:col2
796 color:[NSColor colorWithRgbInt:color]];
797 } else if (DeleteLinesDrawType == type) {
798 int color = *((int*)bytes); bytes += sizeof(int);
799 int row = *((int*)bytes); bytes += sizeof(int);
800 int count = *((int*)bytes); bytes += sizeof(int);
801 int bot = *((int*)bytes); bytes += sizeof(int);
802 int left = *((int*)bytes); bytes += sizeof(int);
803 int right = *((int*)bytes); bytes += sizeof(int);
806 NSLog(@" Delete %d line(s) from %d", count, row);
808 [textStorage deleteLinesFromRow:row lineCount:count
809 scrollBottom:bot left:left right:right
810 color:[NSColor colorWithRgbInt:color]];
811 } else if (ReplaceStringDrawType == type) {
812 int bg = *((int*)bytes); bytes += sizeof(int);
813 int fg = *((int*)bytes); bytes += sizeof(int);
814 int sp = *((int*)bytes); bytes += sizeof(int);
815 int row = *((int*)bytes); bytes += sizeof(int);
816 int col = *((int*)bytes); bytes += sizeof(int);
817 int flags = *((int*)bytes); bytes += sizeof(int);
818 int len = *((int*)bytes); bytes += sizeof(int);
819 NSString *string = [[NSString alloc]
820 initWithBytesNoCopy:(void*)bytes
822 encoding:NSUTF8StringEncoding
827 NSLog(@" Draw string at (%d,%d) length=%d flags=%d fg=0x%x "
828 "bg=0x%x sp=0x%x (%@)", row, col, len, flags, fg, bg, sp,
829 len > 0 ? [string substringToIndex:1] : @"");
831 // NOTE: If this is a call to draw the (block) cursor, then cancel
832 // any previous request to draw the insertion point, or it might
833 // get drawn as well.
834 if (flags & DRAW_CURSOR) {
835 [textView setShouldDrawInsertionPoint:NO];
836 //[textView drawInsertionPointAtRow:row column:col
837 // shape:MMInsertionPointBlock
838 // color:[NSColor colorWithRgbInt:bg]];
840 [textStorage replaceString:string
843 foregroundColor:[NSColor colorWithRgbInt:fg]
844 backgroundColor:[NSColor colorWithRgbInt:bg]
845 specialColor:[NSColor colorWithRgbInt:sp]];
848 } else if (InsertLinesDrawType == type) {
849 int color = *((int*)bytes); bytes += sizeof(int);
850 int row = *((int*)bytes); bytes += sizeof(int);
851 int count = *((int*)bytes); bytes += sizeof(int);
852 int bot = *((int*)bytes); bytes += sizeof(int);
853 int left = *((int*)bytes); bytes += sizeof(int);
854 int right = *((int*)bytes); bytes += sizeof(int);
857 NSLog(@" Insert %d line(s) at row %d", count, row);
859 [textStorage insertLinesAtRow:row lineCount:count
860 scrollBottom:bot left:left right:right
861 color:[NSColor colorWithRgbInt:color]];
862 } else if (DrawCursorDrawType == type) {
863 int color = *((int*)bytes); bytes += sizeof(int);
864 int row = *((int*)bytes); bytes += sizeof(int);
865 int col = *((int*)bytes); bytes += sizeof(int);
866 int shape = *((int*)bytes); bytes += sizeof(int);
869 NSLog(@" Draw cursor at (%d,%d)", row, col);
871 [textView drawInsertionPointAtRow:row column:col shape:shape
872 color:[NSColor colorWithRgbInt:color]];
874 NSLog(@"WARNING: Unknown draw type (type=%d)", type);
878 [textStorage endEditing];
880 NSLog(@"<==== END %s", _cmd);
884 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
885 context:(void *)context
887 NSString *string = (code == NSOKButton) ? [panel filename] : nil;
889 [backendProxy setDialogReturn:string];
891 @catch (NSException *e) {
892 NSLog(@"Exception caught in %s %@", _cmd, e);
896 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context
900 code = code - NSAlertFirstButtonReturn + 1;
902 if ([alert isKindOfClass:[MMAlert class]] && [alert textField]) {
903 ret = [NSArray arrayWithObjects:[NSNumber numberWithInt:code],
904 [[alert textField] stringValue], nil];
906 ret = [NSArray arrayWithObject:[NSNumber numberWithInt:code]];
910 [backendProxy setDialogReturn:ret];
912 @catch (NSException *e) {
913 NSLog(@"Exception caught in %s %@", _cmd, e);
917 - (NSMenuItem *)menuItemForTag:(int)tag
919 // Search the main menu.
920 int i, count = [mainMenuItems count];
921 for (i = 0; i < count; ++i) {
922 NSMenuItem *item = [mainMenuItems objectAtIndex:i];
923 if ([item tag] == tag) return item;
924 item = findMenuItemWithTagInMenu([item submenu], tag);
925 if (item) return item;
928 // Search the popup menus.
929 count = [popupMenuItems count];
930 for (i = 0; i < count; ++i) {
931 NSMenuItem *item = [popupMenuItems objectAtIndex:i];
932 if ([item tag] == tag) return item;
933 item = findMenuItemWithTagInMenu([item submenu], tag);
934 if (item) return item;
940 - (NSMenu *)menuForTag:(int)tag
942 return [[self menuItemForTag:tag] submenu];
945 - (NSMenu *)topLevelMenuForTitle:(NSString *)title
947 // Search only the top-level menus.
949 unsigned i, count = [popupMenuItems count];
950 for (i = 0; i < count; ++i) {
951 NSMenuItem *item = [popupMenuItems objectAtIndex:i];
952 if ([title isEqual:[item title]])
953 return [item submenu];
956 count = [mainMenuItems count];
957 for (i = 0; i < count; ++i) {
958 NSMenuItem *item = [mainMenuItems objectAtIndex:i];
959 if ([title isEqual:[item title]])
960 return [item submenu];
966 - (void)addMenuWithTag:(int)tag parent:(int)parentTag title:(NSString *)title
969 NSMenu *parent = [self menuForTag:parentTag];
970 NSMenuItem *item = [[NSMenuItem alloc] init];
971 NSMenu *menu = [[NSMenu alloc] initWithTitle:title];
973 [menu setAutoenablesItems:NO];
975 [item setTitle:title];
976 [item setSubmenu:menu];
979 if ([parent numberOfItems] <= idx) {
980 [parent addItem:item];
982 [parent insertItem:item atIndex:idx];
985 NSMutableArray *items = (MenuPopupType == parentTag)
986 ? popupMenuItems : mainMenuItems;
987 if ([items count] <= idx) {
988 [items addObject:item];
990 [items insertObject:item atIndex:idx];
993 shouldUpdateMainMenu = (MenuPopupType != parentTag);
1000 - (void)addMenuItemWithTag:(int)tag parent:(NSMenu *)parent
1001 title:(NSString *)title tip:(NSString *)tip
1002 keyEquivalent:(int)key modifiers:(int)mask
1003 action:(NSString *)action atIndex:(int)idx
1006 NSMenuItem *item = nil;
1007 if (!title || ([title hasPrefix:@"-"] && [title hasSuffix:@"-"])) {
1008 item = [NSMenuItem separatorItem];
1010 item = [[[NSMenuItem alloc] init] autorelease];
1011 [item setTitle:title];
1012 // TODO: Check that 'action' is a valid action (nothing will happen
1013 // if it isn't, but it would be nice with a warning).
1014 if (action) [item setAction:NSSelectorFromString(action)];
1015 else [item setAction:@selector(vimMenuItemAction:)];
1016 if (tip) [item setToolTip:tip];
1019 NSString *keyString =
1020 [NSString stringWithFormat:@"%C", key];
1021 [item setKeyEquivalent:keyString];
1022 [item setKeyEquivalentModifierMask:mask];
1026 // NOTE! The tag is used to idenfity which menu items were
1027 // added by Vim (tag != 0) and which were added by the AppKit
1031 if ([parent numberOfItems] <= idx) {
1032 [parent addItem:item];
1034 [parent insertItem:item atIndex:idx];
1037 NSLog(@"WARNING: Menu item '%@' (tag=%d) has no parent.", title, tag);
1041 - (void)updateMainMenu
1043 NSMenu *mainMenu = [NSApp mainMenu];
1045 // Stop NSApp from updating the Window menu.
1046 [NSApp setWindowsMenu:nil];
1048 // Remove all menus from main menu (except the MacVim menu).
1049 int i, count = [mainMenu numberOfItems];
1050 for (i = count-1; i > 0; --i) {
1051 [mainMenu removeItemAtIndex:i];
1054 // Add menus from 'mainMenuItems' to main menu.
1055 count = [mainMenuItems count];
1056 for (i = 0; i < count; ++i) {
1057 [mainMenu addItem:[mainMenuItems objectAtIndex:i]];
1060 // Set the new Window menu.
1061 // TODO! Need to look for 'Window' in all localized languages.
1062 NSMenu *windowMenu = [[mainMenu itemWithTitle:@"Window"] submenu];
1064 // Remove all AppKit owned menu items (tag == 0); they will be added
1065 // again when setWindowsMenu: is called.
1066 count = [windowMenu numberOfItems];
1067 for (i = count-1; i >= 0; --i) {
1068 NSMenuItem *item = [windowMenu itemAtIndex:i];
1070 [windowMenu removeItem:item];
1074 [NSApp setWindowsMenu:windowMenu];
1077 shouldUpdateMainMenu = NO;
1080 - (NSToolbarItem *)toolbarItemForTag:(int)tag index:(int *)index
1082 if (!toolbar) return nil;
1084 NSArray *items = [toolbar items];
1085 int i, count = [items count];
1086 for (i = 0; i < count; ++i) {
1087 NSToolbarItem *item = [items objectAtIndex:i];
1088 if ([item tag] == tag) {
1089 if (index) *index = i;
1097 - (void)addToolbarItemToDictionaryWithTag:(int)tag label:(NSString *)title
1098 toolTip:(NSString *)tip icon:(NSString *)icon
1100 // If the item corresponds to a separator then do nothing, since it is
1101 // already defined by Cocoa.
1102 if (!title || [title isEqual:NSToolbarSeparatorItemIdentifier]
1103 || [title isEqual:NSToolbarSpaceItemIdentifier]
1104 || [title isEqual:NSToolbarFlexibleSpaceItemIdentifier])
1107 NSToolbarItem *item = [[NSToolbarItem alloc] initWithItemIdentifier:title];
1109 [item setLabel:title];
1110 [item setToolTip:tip];
1111 [item setAction:@selector(vimMenuItemAction:)];
1112 [item setAutovalidates:NO];
1114 NSImage *img = [NSImage imageNamed:icon];
1116 NSLog(@"WARNING: Could not find image with name '%@' to use as toolbar"
1117 " image for identifier '%@';"
1118 " using default toolbar icon '%@' instead.",
1119 icon, title, MMDefaultToolbarImageName);
1121 img = [NSImage imageNamed:MMDefaultToolbarImageName];
1124 [item setImage:img];
1126 [toolbarItemDict setObject:item forKey:title];
1131 - (void)addToolbarItemWithTag:(int)tag label:(NSString *)label tip:(NSString
1132 *)tip icon:(NSString *)icon atIndex:(int)idx
1134 if (!toolbar) return;
1136 // Check for separator items.
1138 label = NSToolbarSeparatorItemIdentifier;
1139 } else if ([label length] >= 2 && [label hasPrefix:@"-"]
1140 && [label hasSuffix:@"-"]) {
1141 // The label begins and ends with '-'; decided which kind of separator
1142 // item it is by looking at the prefix.
1143 if ([label hasPrefix:@"-space"]) {
1144 label = NSToolbarSpaceItemIdentifier;
1145 } else if ([label hasPrefix:@"-flexspace"]) {
1146 label = NSToolbarFlexibleSpaceItemIdentifier;
1148 label = NSToolbarSeparatorItemIdentifier;
1152 [self addToolbarItemToDictionaryWithTag:tag label:label toolTip:tip
1155 int maxIdx = [[toolbar items] count];
1156 if (maxIdx < idx) idx = maxIdx;
1158 [toolbar insertItemWithItemIdentifier:label atIndex:idx];
1161 - (void)connectionDidDie:(NSNotification *)notification
1163 //NSLog(@"%@ %s%@", [self className], _cmd, notification);
1167 // NOTE! This causes the call to removeVimController: to be delayed.
1169 performSelectorOnMainThread:@selector(removeVimController:)
1170 withObject:self waitUntilDone:NO];
1173 - (NSString *)description
1175 return [NSString stringWithFormat:@"%@ : isInitialized=%d inProcessCommandQueue=%d mainMenuItems=%@ popupMenuItems=%@ toolbar=%@", [self className], isInitialized, inProcessCommandQueue, mainMenuItems, popupMenuItems, toolbar];
1178 @end // MMVimController (Private)
1182 @implementation NSColor (MMProtocol)
1184 + (NSColor *)colorWithRgbInt:(int)rgb
1186 float r = ((rgb>>16) & 0xff)/255.0f;
1187 float g = ((rgb>>8) & 0xff)/255.0f;
1188 float b = (rgb & 0xff)/255.0f;
1190 return [NSColor colorWithCalibratedRed:r green:g blue:b alpha:1.0f];
1193 @end // NSColor (MMProtocol)
1197 @implementation MMAlert
1200 [textField release];
1204 - (void)setTextFieldString:(NSString *)textFieldString
1206 [textField release];
1207 textField = [[NSTextField alloc] init];
1208 [textField setStringValue:textFieldString];
1211 - (NSTextField *)textField
1216 - (void)setInformativeText:(NSString *)text
1219 // HACK! Add some space for the text field.
1220 [super setInformativeText:[text stringByAppendingString:@"\n\n\n"]];
1222 [super setInformativeText:text];
1226 - (void)beginSheetModalForWindow:(NSWindow *)window
1227 modalDelegate:(id)delegate
1228 didEndSelector:(SEL)didEndSelector
1229 contextInfo:(void *)contextInfo
1231 [super beginSheetModalForWindow:window
1232 modalDelegate:delegate
1233 didEndSelector:didEndSelector
1234 contextInfo:contextInfo];
1236 // HACK! Place the input text field at the bottom of the informative text
1237 // (which has been made a bit larger by adding newline characters).
1238 NSView *contentView = [[self window] contentView];
1239 NSRect rect = [contentView frame];
1240 rect.origin.y = rect.size.height;
1242 NSArray *subviews = [contentView subviews];
1243 unsigned i, count = [subviews count];
1244 for (i = 0; i < count; ++i) {
1245 NSView *view = [subviews objectAtIndex:i];
1246 if ([view isKindOfClass:[NSTextField class]]
1247 && [view frame].origin.y < rect.origin.y) {
1248 // NOTE: The informative text field is the lowest NSTextField in
1249 // the alert dialog.
1250 rect = [view frame];
1254 rect.size.height = MMAlertTextFieldHeight;
1255 [textField setFrame:rect];
1256 [contentView addSubview:textField];
1257 [textField becomeFirstResponder];