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 *)recurseMenuItemForTag:(int)tag rootMenu:(NSMenu *)root;
53 - (NSMenuItem *)menuItemForTag:(int)tag;
54 - (NSMenu *)menuForTag:(int)tag;
55 - (NSMenu *)topLevelMenuForTitle:(NSString *)title;
56 - (void)addMenuWithTag:(int)tag parent:(int)parentTag title:(NSString *)title
58 - (void)addMenuItemWithTag:(int)tag parent:(NSMenu *)parent
59 title:(NSString *)title tip:(NSString *)tip
60 keyEquivalent:(int)key modifiers:(int)mask
61 action:(NSString *)action atIndex:(int)idx;
62 - (void)updateMainMenu;
63 - (NSToolbarItem *)toolbarItemForTag:(int)tag index:(int *)index;
64 - (void)addToolbarItemToDictionaryWithTag:(int)tag label:(NSString *)title
65 toolTip:(NSString *)tip icon:(NSString *)icon;
66 - (void)addToolbarItemWithTag:(int)tag label:(NSString *)label
67 tip:(NSString *)tip icon:(NSString *)icon
69 - (void)connectionDidDie:(NSNotification *)notification;
70 #if MM_RESEND_LAST_FAILURE
71 - (void)resendTimerFired:(NSTimer *)timer;
77 // TODO: Move to separate file
78 @interface NSColor (MMProtocol)
79 + (NSColor *)colorWithRgbInt:(unsigned)rgb;
80 + (NSColor *)colorWithArgbInt:(unsigned)argb;
86 @implementation MMVimController
88 - (id)initWithBackend:(id)backend pid:(int)processIdentifier
90 if ((self = [super init])) {
92 [[MMWindowController alloc] initWithVimController:self];
93 backendProxy = [backend retain];
94 sendQueue = [NSMutableArray new];
95 mainMenuItems = [[NSMutableArray alloc] init];
96 popupMenuItems = [[NSMutableArray alloc] init];
97 toolbarItemDict = [[NSMutableDictionary alloc] init];
98 pid = processIdentifier;
100 NSConnection *connection = [backendProxy connectionForProxy];
102 // TODO: Check that this will not set the timeout for the root proxy
103 // (in MMAppController).
104 [connection setRequestTimeout:MMBackendProxyRequestTimeout];
106 [[NSNotificationCenter defaultCenter] addObserver:self
107 selector:@selector(connectionDidDie:)
108 name:NSConnectionDidDieNotification object:connection];
111 NSWindow *win = [windowController window];
113 [[NSNotificationCenter defaultCenter]
115 selector:@selector(windowDidBecomeMain:)
116 name:NSWindowDidBecomeMainNotification
127 //NSLog(@"%@ %s", [self className], _cmd);
130 #if MM_RESEND_LAST_FAILURE
131 [resendData release]; resendData = nil;
134 [serverName release]; serverName = nil;
135 [backendProxy release]; backendProxy = nil;
136 [sendQueue release]; sendQueue = nil;
138 [toolbarItemDict release]; toolbarItemDict = nil;
139 [toolbar release]; toolbar = nil;
140 [popupMenuItems release]; popupMenuItems = nil;
141 [mainMenuItems release]; mainMenuItems = nil;
142 [windowController release]; windowController = nil;
147 - (MMWindowController *)windowController
149 return windowController;
152 - (void)setServerName:(NSString *)name
154 if (name != serverName) {
155 [serverName release];
156 serverName = [name copy];
160 - (NSString *)serverName
170 - (void)dropFiles:(NSArray *)filenames
172 int i, numberOfFiles = [filenames count];
173 NSMutableData *data = [NSMutableData data];
175 [data appendBytes:&numberOfFiles length:sizeof(int)];
177 for (i = 0; i < numberOfFiles; ++i) {
178 NSString *file = [filenames objectAtIndex:i];
179 int len = [file lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
182 ++len; // include NUL as well
183 [data appendBytes:&len length:sizeof(int)];
184 [data appendBytes:[file UTF8String] length:len];
188 [self sendMessage:DropFilesMsgID data:data];
191 - (void)dropString:(NSString *)string
193 int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
195 NSMutableData *data = [NSMutableData data];
197 [data appendBytes:&len length:sizeof(int)];
198 [data appendBytes:[string UTF8String] length:len];
200 [self sendMessage:DropStringMsgID data:data];
204 - (void)sendMessage:(int)msgid data:(NSData *)data
206 //NSLog(@"sendMessage:%s (isInitialized=%d inProcessCommandQueue=%d)",
207 // MessageStrings[msgid], isInitialized, inProcessCommandQueue);
209 if (!isInitialized) return;
211 if (inProcessCommandQueue) {
212 //NSLog(@"In process command queue; delaying message send.");
213 [sendQueue addObject:[NSNumber numberWithInt:msgid]];
215 [sendQueue addObject:data];
217 [sendQueue addObject:[NSNull null]];
221 #if MM_RESEND_LAST_FAILURE
223 //NSLog(@"cancelling scheduled resend of %s",
224 // MessageStrings[resendMsgid]);
226 [resendTimer invalidate];
227 [resendTimer release];
232 [resendData release];
238 [backendProxy processInput:msgid data:data];
240 @catch (NSException *e) {
241 //NSLog(@"%@ %s Exception caught during DO call: %@",
242 // [self className], _cmd, e);
243 #if MM_RESEND_LAST_FAILURE
244 //NSLog(@"%s failed, scheduling message %s for resend", _cmd,
245 // MessageStrings[msgid]);
248 resendData = [data retain];
249 resendTimer = [NSTimer
250 scheduledTimerWithTimeInterval:MMResendInterval
252 selector:@selector(resendTimerFired:)
255 [resendTimer retain];
260 - (BOOL)sendMessageNow:(int)msgid data:(NSData *)data
261 timeout:(NSTimeInterval)timeout
263 if (!isInitialized || inProcessCommandQueue)
266 if (timeout < 0) timeout = 0;
269 NSConnection *conn = [backendProxy connectionForProxy];
270 NSTimeInterval oldTimeout = [conn requestTimeout];
272 [conn setRequestTimeout:timeout];
275 [backendProxy processInput:msgid data:data];
277 @catch (NSException *e) {
281 [conn setRequestTimeout:oldTimeout];
294 //NSLog(@"%@ %s", [self className], _cmd);
295 if (!isInitialized) return;
298 [toolbar setDelegate:nil];
299 [[NSNotificationCenter defaultCenter] removeObserver:self];
300 [windowController cleanup];
303 - (oneway void)showSavePanelForDirectory:(in bycopy NSString *)dir
304 title:(in bycopy NSString *)title
307 if (!isInitialized) return;
310 [[NSSavePanel savePanel] beginSheetForDirectory:dir file:nil
311 modalForWindow:[windowController window]
313 didEndSelector:@selector(savePanelDidEnd:code:context:)
316 NSOpenPanel *panel = [NSOpenPanel openPanel];
317 [panel setAllowsMultipleSelection:NO];
318 [panel beginSheetForDirectory:dir file:nil types:nil
319 modalForWindow:[windowController window]
321 didEndSelector:@selector(savePanelDidEnd:code:context:)
326 - (oneway void)presentDialogWithStyle:(int)style
327 message:(in bycopy NSString *)message
328 informativeText:(in bycopy NSString *)text
329 buttonTitles:(in bycopy NSArray *)buttonTitles
330 textFieldString:(in bycopy NSString *)textFieldString
332 if (!(windowController && buttonTitles && [buttonTitles count])) return;
334 MMAlert *alert = [[MMAlert alloc] init];
336 // NOTE! This has to be done before setting the informative text.
338 [alert setTextFieldString:textFieldString];
340 [alert setAlertStyle:style];
343 [alert setMessageText:message];
345 // If no message text is specified 'Alert' is used, which we don't
346 // want, so set an empty string as message text.
347 [alert setMessageText:@""];
351 [alert setInformativeText:text];
352 } else if (textFieldString) {
353 // Make sure there is always room for the input text field.
354 [alert setInformativeText:@""];
357 unsigned i, count = [buttonTitles count];
358 for (i = 0; i < count; ++i) {
359 NSString *title = [buttonTitles objectAtIndex:i];
360 // NOTE: The title of the button may contain the character '&' to
361 // indicate that the following letter should be the key equivalent
362 // associated with the button. Extract this letter and lowercase it.
363 NSString *keyEquivalent = nil;
364 NSRange hotkeyRange = [title rangeOfString:@"&"];
365 if (NSNotFound != hotkeyRange.location) {
366 if ([title length] > NSMaxRange(hotkeyRange)) {
367 NSRange keyEquivRange = NSMakeRange(hotkeyRange.location+1, 1);
368 keyEquivalent = [[title substringWithRange:keyEquivRange]
372 NSMutableString *string = [NSMutableString stringWithString:title];
373 [string deleteCharactersInRange:hotkeyRange];
377 [alert addButtonWithTitle:title];
379 // Set key equivalent for the button, but only if NSAlert hasn't
380 // already done so. (Check the documentation for
381 // - [NSAlert addButtonWithTitle:] to see what key equivalents are
382 // automatically assigned.)
383 NSButton *btn = [[alert buttons] lastObject];
384 if ([[btn keyEquivalent] length] == 0 && keyEquivalent) {
385 [btn setKeyEquivalent:keyEquivalent];
389 [alert beginSheetModalForWindow:[windowController window]
391 didEndSelector:@selector(alertDidEnd:code:context:)
397 - (oneway void)processCommandQueue:(in bycopy NSArray *)queue
399 if (!isInitialized) return;
401 unsigned i, count = [queue count];
403 NSLog(@"WARNING: Uneven number of components (%d) in flush queue "
404 "message; ignoring this message.", count);
408 inProcessCommandQueue = YES;
410 //NSLog(@"======== %s BEGIN ========", _cmd);
411 for (i = 0; i < count; i += 2) {
412 NSData *value = [queue objectAtIndex:i];
413 NSData *data = [queue objectAtIndex:i+1];
415 int msgid = *((int*)[value bytes]);
417 if (msgid != EnableMenuItemMsgID && msgid != AddMenuItemMsgID
418 && msgid != AddMenuMsgID) {
419 NSLog(@"%s%s", _cmd, MessageStrings[msgid]);
423 [self handleMessage:msgid data:data];
425 //NSLog(@"======== %s END ========", _cmd);
427 if (shouldUpdateMainMenu) {
428 [self updateMainMenu];
431 [windowController processCommandQueueDidFinish];
433 inProcessCommandQueue = NO;
435 if ([sendQueue count] > 0) {
437 [backendProxy processInputAndData:sendQueue];
439 @catch (NSException *e) {
440 // Connection timed out, just ignore this.
441 //NSLog(@"WARNING! Connection timed out in %s", _cmd);
444 [sendQueue removeAllObjects];
448 - (void)windowDidBecomeMain:(NSNotification *)notification
451 [self updateMainMenu];
454 - (NSToolbarItem *)toolbar:(NSToolbar *)theToolbar
455 itemForItemIdentifier:(NSString *)itemId
456 willBeInsertedIntoToolbar:(BOOL)flag
458 NSToolbarItem *item = [toolbarItemDict objectForKey:itemId];
460 NSLog(@"WARNING: No toolbar item with id '%@'", itemId);
466 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)theToolbar
471 - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)theToolbar
476 @end // MMVimController
480 @implementation MMVimController (Private)
482 - (void)handleMessage:(int)msgid data:(NSData *)data
484 //NSLog(@"%@ %s", [self className], _cmd);
486 if (OpenVimWindowMsgID == msgid) {
487 [windowController openWindow];
488 } else if (BatchDrawMsgID == msgid) {
489 [self performBatchDrawWithData:data];
490 } else if (SelectTabMsgID == msgid) {
491 #if 0 // NOTE: Tab selection is done inside updateTabsWithData:.
492 const void *bytes = [data bytes];
493 int idx = *((int*)bytes);
494 //NSLog(@"Selecting tab with index %d", idx);
495 [windowController selectTabWithIndex:idx];
497 } else if (UpdateTabBarMsgID == msgid) {
498 [windowController updateTabsWithData:data];
499 } else if (ShowTabBarMsgID == msgid) {
500 [windowController showTabBar:YES];
501 } else if (HideTabBarMsgID == msgid) {
502 [windowController showTabBar:NO];
503 } else if (SetTextDimensionsMsgID == msgid) {
504 const void *bytes = [data bytes];
505 int rows = *((int*)bytes); bytes += sizeof(int);
506 int cols = *((int*)bytes); bytes += sizeof(int);
508 [windowController setTextDimensionsWithRows:rows columns:cols];
509 } else if (SetWindowTitleMsgID == msgid) {
510 const void *bytes = [data bytes];
511 int len = *((int*)bytes); bytes += sizeof(int);
513 NSString *string = [[NSString alloc] initWithBytes:(void*)bytes
514 length:len encoding:NSUTF8StringEncoding];
516 [[windowController window] setTitle:string];
519 } else if (AddMenuMsgID == msgid) {
520 NSString *title = nil;
521 const void *bytes = [data bytes];
522 int tag = *((int*)bytes); bytes += sizeof(int);
523 int parentTag = *((int*)bytes); bytes += sizeof(int);
524 int len = *((int*)bytes); bytes += sizeof(int);
526 title = [[NSString alloc] initWithBytes:(void*)bytes length:len
527 encoding:NSUTF8StringEncoding];
530 int idx = *((int*)bytes); bytes += sizeof(int);
532 if (MenuToolbarType == parentTag) {
534 // NOTE! Each toolbar must have a unique identifier, else each
535 // window will have the same toolbar.
536 NSString *ident = [NSString stringWithFormat:@"%d.%d",
538 toolbar = [[NSToolbar alloc] initWithIdentifier:ident];
540 [toolbar setShowsBaselineSeparator:NO];
541 [toolbar setDelegate:self];
542 [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
543 [toolbar setSizeMode:NSToolbarSizeModeSmall];
545 NSWindow *win = [windowController window];
546 [win setToolbar:toolbar];
548 // HACK! Redirect the pill button so that we can ask Vim to
550 NSButton *pillButton = [win
551 standardWindowButton:NSWindowToolbarButton];
553 [pillButton setAction:@selector(toggleToolbar:)];
554 [pillButton setTarget:windowController];
558 [self addMenuWithTag:tag parent:parentTag title:title atIndex:idx];
562 } else if (AddMenuItemMsgID == msgid) {
563 NSString *title = nil, *tip = nil, *icon = nil, *action = nil;
564 const void *bytes = [data bytes];
565 int tag = *((int*)bytes); bytes += sizeof(int);
566 int parentTag = *((int*)bytes); bytes += sizeof(int);
567 int namelen = *((int*)bytes); bytes += sizeof(int);
569 title = [[NSString alloc] initWithBytes:(void*)bytes length:namelen
570 encoding:NSUTF8StringEncoding];
573 int tiplen = *((int*)bytes); bytes += sizeof(int);
575 tip = [[NSString alloc] initWithBytes:(void*)bytes length:tiplen
576 encoding:NSUTF8StringEncoding];
579 int iconlen = *((int*)bytes); bytes += sizeof(int);
581 icon = [[NSString alloc] initWithBytes:(void*)bytes length:iconlen
582 encoding:NSUTF8StringEncoding];
585 int actionlen = *((int*)bytes); bytes += sizeof(int);
587 action = [[NSString alloc] initWithBytes:(void*)bytes
589 encoding:NSUTF8StringEncoding];
592 int idx = *((int*)bytes); bytes += sizeof(int);
593 if (idx < 0) idx = 0;
594 int key = *((int*)bytes); bytes += sizeof(int);
595 int mask = *((int*)bytes); bytes += sizeof(int);
597 NSString *ident = [NSString stringWithFormat:@"%d.%d",
598 (int)self, parentTag];
599 if (toolbar && [[toolbar identifier] isEqual:ident]) {
600 [self addToolbarItemWithTag:tag label:title tip:tip icon:icon
603 NSMenu *parent = [self menuForTag:parentTag];
604 [self addMenuItemWithTag:tag parent:parent title:title tip:tip
605 keyEquivalent:key modifiers:mask action:action
613 } else if (RemoveMenuItemMsgID == msgid) {
614 const void *bytes = [data bytes];
615 int tag = *((int*)bytes); bytes += sizeof(int);
619 if ((item = [self toolbarItemForTag:tag index:&idx])) {
620 [toolbar removeItemAtIndex:idx];
621 } else if ((item = [self menuItemForTag:tag])) {
624 if ([item menu] == [NSApp mainMenu] || ![item menu]) {
625 // NOTE: To be on the safe side we try to remove the item from
626 // both arrays (it is ok to call removeObject: even if an array
627 // does not contain the object to remove).
628 [mainMenuItems removeObject:item];
629 [popupMenuItems removeObject:item];
633 [[item menu] removeItem:item];
638 // Reset cached menu, just to be on the safe side.
639 lastMenuSearched = nil;
640 } else if (EnableMenuItemMsgID == msgid) {
641 const void *bytes = [data bytes];
642 int tag = *((int*)bytes); bytes += sizeof(int);
643 int state = *((int*)bytes); bytes += sizeof(int);
645 id item = [self toolbarItemForTag:tag index:NULL];
647 item = [self menuItemForTag:tag];
649 [item setEnabled:state];
650 } else if (ShowToolbarMsgID == msgid) {
651 const void *bytes = [data bytes];
652 int enable = *((int*)bytes); bytes += sizeof(int);
653 int flags = *((int*)bytes); bytes += sizeof(int);
655 int mode = NSToolbarDisplayModeDefault;
656 if (flags & ToolbarLabelFlag) {
657 mode = flags & ToolbarIconFlag ? NSToolbarDisplayModeIconAndLabel
658 : NSToolbarDisplayModeLabelOnly;
659 } else if (flags & ToolbarIconFlag) {
660 mode = NSToolbarDisplayModeIconOnly;
663 int size = flags & ToolbarSizeRegularFlag ? NSToolbarSizeModeRegular
664 : NSToolbarSizeModeSmall;
666 [windowController showToolbar:enable size:size mode:mode];
667 } else if (CreateScrollbarMsgID == msgid) {
668 const void *bytes = [data bytes];
669 long ident = *((long*)bytes); bytes += sizeof(long);
670 int type = *((int*)bytes); bytes += sizeof(int);
672 [windowController createScrollbarWithIdentifier:ident type:type];
673 } else if (DestroyScrollbarMsgID == msgid) {
674 const void *bytes = [data bytes];
675 long ident = *((long*)bytes); bytes += sizeof(long);
677 [windowController destroyScrollbarWithIdentifier:ident];
678 } else if (ShowScrollbarMsgID == msgid) {
679 const void *bytes = [data bytes];
680 long ident = *((long*)bytes); bytes += sizeof(long);
681 int visible = *((int*)bytes); bytes += sizeof(int);
683 [windowController showScrollbarWithIdentifier:ident state:visible];
684 } else if (SetScrollbarPositionMsgID == msgid) {
685 const void *bytes = [data bytes];
686 long ident = *((long*)bytes); bytes += sizeof(long);
687 int pos = *((int*)bytes); bytes += sizeof(int);
688 int len = *((int*)bytes); bytes += sizeof(int);
690 [windowController setScrollbarPosition:pos length:len
692 } else if (SetScrollbarThumbMsgID == msgid) {
693 const void *bytes = [data bytes];
694 long ident = *((long*)bytes); bytes += sizeof(long);
695 float val = *((float*)bytes); bytes += sizeof(float);
696 float prop = *((float*)bytes); bytes += sizeof(float);
698 [windowController setScrollbarThumbValue:val proportion:prop
700 } else if (SetFontMsgID == msgid) {
701 const void *bytes = [data bytes];
702 float size = *((float*)bytes); bytes += sizeof(float);
703 int len = *((int*)bytes); bytes += sizeof(int);
704 NSString *name = [[NSString alloc]
705 initWithBytes:(void*)bytes length:len
706 encoding:NSUTF8StringEncoding];
707 NSFont *font = [NSFont fontWithName:name size:size];
710 [windowController setFont:font];
713 } else if (SetDefaultColorsMsgID == msgid) {
714 const void *bytes = [data bytes];
715 unsigned bg = *((unsigned*)bytes); bytes += sizeof(unsigned);
716 unsigned fg = *((unsigned*)bytes); bytes += sizeof(unsigned);
717 NSColor *back = [NSColor colorWithArgbInt:bg];
718 NSColor *fore = [NSColor colorWithRgbInt:fg];
720 [windowController setDefaultColorsBackground:back foreground:fore];
721 } else if (ExecuteActionMsgID == msgid) {
722 const void *bytes = [data bytes];
723 int len = *((int*)bytes); bytes += sizeof(int);
724 NSString *actionName = [[NSString alloc]
725 initWithBytesNoCopy:(void*)bytes
727 encoding:NSUTF8StringEncoding
730 SEL sel = NSSelectorFromString(actionName);
731 [NSApp sendAction:sel to:nil from:self];
733 [actionName release];
734 } else if (ShowPopupMenuMsgID == msgid) {
735 const void *bytes = [data bytes];
736 int row = *((int*)bytes); bytes += sizeof(int);
737 int col = *((int*)bytes); bytes += sizeof(int);
738 int len = *((int*)bytes); bytes += sizeof(int);
739 NSString *title = [[NSString alloc]
740 initWithBytesNoCopy:(void*)bytes
742 encoding:NSUTF8StringEncoding
745 NSMenu *menu = [self topLevelMenuForTitle:title];
747 [windowController popupMenu:menu atRow:row column:col];
749 NSLog(@"WARNING: Cannot popup menu with title %@; no such menu.",
754 } else if (SetMouseShapeMsgID == msgid) {
755 const void *bytes = [data bytes];
756 int shape = *((int*)bytes); bytes += sizeof(int);
758 [windowController setMouseShape:shape];
759 } else if (AdjustLinespaceMsgID == msgid) {
760 const void *bytes = [data bytes];
761 int linespace = *((int*)bytes); bytes += sizeof(int);
763 [windowController adjustLinespace:linespace];
764 } else if (ActivateMsgID == msgid) {
765 [NSApp activateIgnoringOtherApps:YES];
766 [[windowController window] makeKeyAndOrderFront:self];
767 } else if (SetServerNameMsgID == msgid) {
768 NSString *name = [[NSString alloc] initWithData:data
769 encoding:NSUTF8StringEncoding];
770 [self setServerName:name];
772 } else if (EnterFullscreenMsgID == msgid) {
773 [windowController enterFullscreen];
774 } else if (LeaveFullscreenMsgID == msgid) {
775 [windowController leaveFullscreen];
776 } else if (BuffersNotModifiedMsgID == msgid) {
777 [[windowController window] setDocumentEdited:NO];
778 } else if (BuffersModifiedMsgID == msgid) {
779 [[windowController window] setDocumentEdited:YES];
781 NSLog(@"WARNING: Unknown message received (msgid=%d)", msgid);
786 #define MM_DEBUG_DRAWING 0
788 - (void)performBatchDrawWithData:(NSData *)data
790 // TODO! Move to window controller.
791 MMTextStorage *textStorage = [windowController textStorage];
792 MMTextView *textView = [windowController textView];
793 if (!(textStorage && textView))
796 const void *bytes = [data bytes];
797 const void *end = bytes + [data length];
800 NSLog(@"====> BEGIN %s", _cmd);
802 [textStorage beginEditing];
804 // TODO: Sanity check input
806 while (bytes < end) {
807 int type = *((int*)bytes); bytes += sizeof(int);
809 if (ClearAllDrawType == type) {
811 NSLog(@" Clear all");
813 [textStorage clearAll];
814 } else if (ClearBlockDrawType == type) {
815 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
816 int row1 = *((int*)bytes); bytes += sizeof(int);
817 int col1 = *((int*)bytes); bytes += sizeof(int);
818 int row2 = *((int*)bytes); bytes += sizeof(int);
819 int col2 = *((int*)bytes); bytes += sizeof(int);
822 NSLog(@" Clear block (%d,%d) -> (%d,%d)", row1, col1,
825 [textStorage clearBlockFromRow:row1 column:col1
826 toRow:row2 column:col2
827 color:[NSColor colorWithArgbInt:color]];
828 } else if (DeleteLinesDrawType == type) {
829 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
830 int row = *((int*)bytes); bytes += sizeof(int);
831 int count = *((int*)bytes); bytes += sizeof(int);
832 int bot = *((int*)bytes); bytes += sizeof(int);
833 int left = *((int*)bytes); bytes += sizeof(int);
834 int right = *((int*)bytes); bytes += sizeof(int);
837 NSLog(@" Delete %d line(s) from %d", count, row);
839 [textStorage deleteLinesFromRow:row lineCount:count
840 scrollBottom:bot left:left right:right
841 color:[NSColor colorWithArgbInt:color]];
842 } else if (ReplaceStringDrawType == type) {
843 int bg = *((int*)bytes); bytes += sizeof(int);
844 int fg = *((int*)bytes); bytes += sizeof(int);
845 int sp = *((int*)bytes); bytes += sizeof(int);
846 int row = *((int*)bytes); bytes += sizeof(int);
847 int col = *((int*)bytes); bytes += sizeof(int);
848 int flags = *((int*)bytes); bytes += sizeof(int);
849 int len = *((int*)bytes); bytes += sizeof(int);
850 NSString *string = [[NSString alloc]
851 initWithBytesNoCopy:(void*)bytes
853 encoding:NSUTF8StringEncoding
858 NSLog(@" Draw string at (%d,%d) length=%d flags=%d fg=0x%x "
859 "bg=0x%x sp=0x%x (%@)", row, col, len, flags, fg, bg, sp,
860 len > 0 ? [string substringToIndex:1] : @"");
862 // NOTE: If this is a call to draw the (block) cursor, then cancel
863 // any previous request to draw the insertion point, or it might
864 // get drawn as well.
865 if (flags & DRAW_CURSOR) {
866 [textView setShouldDrawInsertionPoint:NO];
867 //NSColor *color = [NSColor colorWithRgbInt:bg];
868 //[textView drawInsertionPointAtRow:row column:col
869 // shape:MMInsertionPointBlock
872 [textStorage replaceString:string
875 foregroundColor:[NSColor colorWithRgbInt:fg]
876 backgroundColor:[NSColor colorWithArgbInt:bg]
877 specialColor:[NSColor colorWithRgbInt:sp]];
880 } else if (InsertLinesDrawType == type) {
881 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
882 int row = *((int*)bytes); bytes += sizeof(int);
883 int count = *((int*)bytes); bytes += sizeof(int);
884 int bot = *((int*)bytes); bytes += sizeof(int);
885 int left = *((int*)bytes); bytes += sizeof(int);
886 int right = *((int*)bytes); bytes += sizeof(int);
889 NSLog(@" Insert %d line(s) at row %d", count, row);
891 [textStorage insertLinesAtRow:row lineCount:count
892 scrollBottom:bot left:left right:right
893 color:[NSColor colorWithArgbInt:color]];
894 } else if (DrawCursorDrawType == type) {
895 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
896 int row = *((int*)bytes); bytes += sizeof(int);
897 int col = *((int*)bytes); bytes += sizeof(int);
898 int shape = *((int*)bytes); bytes += sizeof(int);
899 int percent = *((int*)bytes); bytes += sizeof(int);
902 NSLog(@" Draw cursor at (%d,%d)", row, col);
904 [textView drawInsertionPointAtRow:row column:col shape:shape
906 color:[NSColor colorWithRgbInt:color]];
908 NSLog(@"WARNING: Unknown draw type (type=%d)", type);
912 [textStorage endEditing];
914 NSLog(@"<==== END %s", _cmd);
918 - (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
919 context:(void *)context
921 NSString *string = (code == NSOKButton) ? [panel filename] : nil;
923 [backendProxy setDialogReturn:string];
925 @catch (NSException *e) {
926 NSLog(@"Exception caught in %s %@", _cmd, e);
930 - (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context
934 code = code - NSAlertFirstButtonReturn + 1;
936 if ([alert isKindOfClass:[MMAlert class]] && [alert textField]) {
937 ret = [NSArray arrayWithObjects:[NSNumber numberWithInt:code],
938 [[alert textField] stringValue], nil];
940 ret = [NSArray arrayWithObject:[NSNumber numberWithInt:code]];
944 [backendProxy setDialogReturn:ret];
946 @catch (NSException *e) {
947 NSLog(@"Exception caught in %s %@", _cmd, e);
951 - (NSMenuItem *)recurseMenuItemForTag:(int)tag rootMenu:(NSMenu *)root
954 NSMenuItem *item = [root itemWithTag:tag];
956 lastMenuSearched = root;
960 NSArray *items = [root itemArray];
961 unsigned i, count = [items count];
962 for (i = 0; i < count; ++i) {
963 item = [items objectAtIndex:i];
964 if ([item hasSubmenu]) {
965 item = [self recurseMenuItemForTag:tag
966 rootMenu:[item submenu]];
968 lastMenuSearched = [item submenu];
978 - (NSMenuItem *)menuItemForTag:(int)tag
980 // First search the same menu that was search last time this method was
981 // called. Since this method is often called for each menu item in a
982 // menu this can significantly improve search times.
983 if (lastMenuSearched) {
984 NSMenuItem *item = [self recurseMenuItemForTag:tag
985 rootMenu:lastMenuSearched];
986 if (item) return item;
989 // Search the main menu.
990 int i, count = [mainMenuItems count];
991 for (i = 0; i < count; ++i) {
992 NSMenuItem *item = [mainMenuItems objectAtIndex:i];
993 if ([item tag] == tag) return item;
994 item = [self recurseMenuItemForTag:tag rootMenu:[item submenu]];
996 lastMenuSearched = [item submenu];
1001 // Search the popup menus.
1002 count = [popupMenuItems count];
1003 for (i = 0; i < count; ++i) {
1004 NSMenuItem *item = [popupMenuItems objectAtIndex:i];
1005 if ([item tag] == tag) return item;
1006 item = [self recurseMenuItemForTag:tag rootMenu:[item submenu]];
1008 lastMenuSearched = [item submenu];
1016 - (NSMenu *)menuForTag:(int)tag
1018 return [[self menuItemForTag:tag] submenu];
1021 - (NSMenu *)topLevelMenuForTitle:(NSString *)title
1023 // Search only the top-level menus.
1025 unsigned i, count = [popupMenuItems count];
1026 for (i = 0; i < count; ++i) {
1027 NSMenuItem *item = [popupMenuItems objectAtIndex:i];
1028 if ([title isEqual:[item title]])
1029 return [item submenu];
1032 count = [mainMenuItems count];
1033 for (i = 0; i < count; ++i) {
1034 NSMenuItem *item = [mainMenuItems objectAtIndex:i];
1035 if ([title isEqual:[item title]])
1036 return [item submenu];
1042 - (void)addMenuWithTag:(int)tag parent:(int)parentTag title:(NSString *)title
1045 NSMenu *parent = [self menuForTag:parentTag];
1046 NSMenuItem *item = [[NSMenuItem alloc] init];
1047 NSMenu *menu = [[NSMenu alloc] initWithTitle:title];
1049 [menu setAutoenablesItems:NO];
1051 [item setTitle:title];
1052 [item setSubmenu:menu];
1055 if ([parent numberOfItems] <= idx) {
1056 [parent addItem:item];
1058 [parent insertItem:item atIndex:idx];
1061 NSMutableArray *items = (MenuPopupType == parentTag)
1062 ? popupMenuItems : mainMenuItems;
1063 if ([items count] <= idx) {
1064 [items addObject:item];
1066 [items insertObject:item atIndex:idx];
1069 shouldUpdateMainMenu = (MenuPopupType != parentTag);
1076 - (void)addMenuItemWithTag:(int)tag parent:(NSMenu *)parent
1077 title:(NSString *)title tip:(NSString *)tip
1078 keyEquivalent:(int)key modifiers:(int)mask
1079 action:(NSString *)action atIndex:(int)idx
1082 NSMenuItem *item = nil;
1083 if (!title || ([title hasPrefix:@"-"] && [title hasSuffix:@"-"])) {
1084 item = [NSMenuItem separatorItem];
1086 item = [[[NSMenuItem alloc] init] autorelease];
1087 [item setTitle:title];
1088 // TODO: Check that 'action' is a valid action (nothing will happen
1089 // if it isn't, but it would be nice with a warning).
1090 if (action) [item setAction:NSSelectorFromString(action)];
1091 else [item setAction:@selector(vimMenuItemAction:)];
1092 if (tip) [item setToolTip:tip];
1095 NSString *keyString =
1096 [NSString stringWithFormat:@"%C", key];
1097 [item setKeyEquivalent:keyString];
1098 [item setKeyEquivalentModifierMask:mask];
1102 // NOTE! The tag is used to idenfity which menu items were
1103 // added by Vim (tag != 0) and which were added by the AppKit
1107 if ([parent numberOfItems] <= idx) {
1108 [parent addItem:item];
1110 [parent insertItem:item atIndex:idx];
1113 NSLog(@"WARNING: Menu item '%@' (tag=%d) has no parent.", title, tag);
1117 - (void)updateMainMenu
1119 NSMenu *mainMenu = [NSApp mainMenu];
1121 // Stop NSApp from updating the Window menu.
1122 [NSApp setWindowsMenu:nil];
1124 // Remove all menus from main menu (except the MacVim menu).
1125 int i, count = [mainMenu numberOfItems];
1126 for (i = count-1; i > 0; --i) {
1127 [mainMenu removeItemAtIndex:i];
1130 // Add menus from 'mainMenuItems' to main menu.
1131 count = [mainMenuItems count];
1132 for (i = 0; i < count; ++i) {
1133 [mainMenu addItem:[mainMenuItems objectAtIndex:i]];
1136 // Set the new Window menu.
1137 // TODO! Need to look for 'Window' in all localized languages.
1138 NSMenu *windowMenu = [[mainMenu itemWithTitle:@"Window"] submenu];
1140 // Remove all AppKit owned menu items (tag == 0); they will be added
1141 // again when setWindowsMenu: is called.
1142 count = [windowMenu numberOfItems];
1143 for (i = count-1; i >= 0; --i) {
1144 NSMenuItem *item = [windowMenu itemAtIndex:i];
1146 [windowMenu removeItem:item];
1150 [NSApp setWindowsMenu:windowMenu];
1153 shouldUpdateMainMenu = NO;
1156 - (NSToolbarItem *)toolbarItemForTag:(int)tag index:(int *)index
1158 if (!toolbar) return nil;
1160 NSArray *items = [toolbar items];
1161 int i, count = [items count];
1162 for (i = 0; i < count; ++i) {
1163 NSToolbarItem *item = [items objectAtIndex:i];
1164 if ([item tag] == tag) {
1165 if (index) *index = i;
1173 - (void)addToolbarItemToDictionaryWithTag:(int)tag label:(NSString *)title
1174 toolTip:(NSString *)tip icon:(NSString *)icon
1176 // If the item corresponds to a separator then do nothing, since it is
1177 // already defined by Cocoa.
1178 if (!title || [title isEqual:NSToolbarSeparatorItemIdentifier]
1179 || [title isEqual:NSToolbarSpaceItemIdentifier]
1180 || [title isEqual:NSToolbarFlexibleSpaceItemIdentifier])
1183 NSToolbarItem *item = [[NSToolbarItem alloc] initWithItemIdentifier:title];
1185 [item setLabel:title];
1186 [item setToolTip:tip];
1187 [item setAction:@selector(vimMenuItemAction:)];
1188 [item setAutovalidates:NO];
1190 NSImage *img = [NSImage imageNamed:icon];
1192 NSLog(@"WARNING: Could not find image with name '%@' to use as toolbar"
1193 " image for identifier '%@';"
1194 " using default toolbar icon '%@' instead.",
1195 icon, title, MMDefaultToolbarImageName);
1197 img = [NSImage imageNamed:MMDefaultToolbarImageName];
1200 [item setImage:img];
1202 [toolbarItemDict setObject:item forKey:title];
1207 - (void)addToolbarItemWithTag:(int)tag label:(NSString *)label tip:(NSString
1208 *)tip icon:(NSString *)icon atIndex:(int)idx
1210 if (!toolbar) return;
1212 // Check for separator items.
1214 label = NSToolbarSeparatorItemIdentifier;
1215 } else if ([label length] >= 2 && [label hasPrefix:@"-"]
1216 && [label hasSuffix:@"-"]) {
1217 // The label begins and ends with '-'; decided which kind of separator
1218 // item it is by looking at the prefix.
1219 if ([label hasPrefix:@"-space"]) {
1220 label = NSToolbarSpaceItemIdentifier;
1221 } else if ([label hasPrefix:@"-flexspace"]) {
1222 label = NSToolbarFlexibleSpaceItemIdentifier;
1224 label = NSToolbarSeparatorItemIdentifier;
1228 [self addToolbarItemToDictionaryWithTag:tag label:label toolTip:tip
1231 int maxIdx = [[toolbar items] count];
1232 if (maxIdx < idx) idx = maxIdx;
1234 [toolbar insertItemWithItemIdentifier:label atIndex:idx];
1237 - (void)connectionDidDie:(NSNotification *)notification
1239 //NSLog(@"%@ %s%@", [self className], _cmd, notification);
1243 // NOTE! This causes the call to removeVimController: to be delayed.
1245 performSelectorOnMainThread:@selector(removeVimController:)
1246 withObject:self waitUntilDone:NO];
1249 - (NSString *)description
1251 return [NSString stringWithFormat:@"%@ : isInitialized=%d inProcessCommandQueue=%d mainMenuItems=%@ popupMenuItems=%@ toolbar=%@", [self className], isInitialized, inProcessCommandQueue, mainMenuItems, popupMenuItems, toolbar];
1254 #if MM_RESEND_LAST_FAILURE
1255 - (void)resendTimerFired:(NSTimer *)timer
1257 int msgid = resendMsgid;
1260 [resendTimer release];
1267 data = [resendData copy];
1269 //NSLog(@"Resending message: %s", MessageStrings[msgid]);
1270 [self sendMessage:msgid data:data];
1274 @end // MMVimController (Private)
1278 @implementation NSColor (MMProtocol)
1280 + (NSColor *)colorWithRgbInt:(unsigned)rgb
1282 float r = ((rgb>>16) & 0xff)/255.0f;
1283 float g = ((rgb>>8) & 0xff)/255.0f;
1284 float b = (rgb & 0xff)/255.0f;
1286 return [NSColor colorWithCalibratedRed:r green:g blue:b alpha:1.0f];
1289 + (NSColor *)colorWithArgbInt:(unsigned)argb
1291 float a = ((argb>>24) & 0xff)/255.0f;
1292 float r = ((argb>>16) & 0xff)/255.0f;
1293 float g = ((argb>>8) & 0xff)/255.0f;
1294 float b = (argb & 0xff)/255.0f;
1296 return [NSColor colorWithCalibratedRed:r green:g blue:b alpha:a];
1299 @end // NSColor (MMProtocol)
1303 @implementation MMAlert
1306 [textField release];
1310 - (void)setTextFieldString:(NSString *)textFieldString
1312 [textField release];
1313 textField = [[NSTextField alloc] init];
1314 [textField setStringValue:textFieldString];
1317 - (NSTextField *)textField
1322 - (void)setInformativeText:(NSString *)text
1325 // HACK! Add some space for the text field.
1326 [super setInformativeText:[text stringByAppendingString:@"\n\n\n"]];
1328 [super setInformativeText:text];
1332 - (void)beginSheetModalForWindow:(NSWindow *)window
1333 modalDelegate:(id)delegate
1334 didEndSelector:(SEL)didEndSelector
1335 contextInfo:(void *)contextInfo
1337 [super beginSheetModalForWindow:window
1338 modalDelegate:delegate
1339 didEndSelector:didEndSelector
1340 contextInfo:contextInfo];
1342 // HACK! Place the input text field at the bottom of the informative text
1343 // (which has been made a bit larger by adding newline characters).
1344 NSView *contentView = [[self window] contentView];
1345 NSRect rect = [contentView frame];
1346 rect.origin.y = rect.size.height;
1348 NSArray *subviews = [contentView subviews];
1349 unsigned i, count = [subviews count];
1350 for (i = 0; i < count; ++i) {
1351 NSView *view = [subviews objectAtIndex:i];
1352 if ([view isKindOfClass:[NSTextField class]]
1353 && [view frame].origin.y < rect.origin.y) {
1354 // NOTE: The informative text field is the lowest NSTextField in
1355 // the alert dialog.
1356 rect = [view frame];
1360 rect.size.height = MMAlertTextFieldHeight;
1361 [textField setFrame:rect];
1362 [contentView addSubview:textField];
1363 [textField becomeFirstResponder];