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]);
416 //NSLog(@"%s%s", _cmd, MessageStrings[msgid]);
418 [self handleMessage:msgid data:data];
420 //NSLog(@"======== %s END ========", _cmd);
422 if (shouldUpdateMainMenu) {
423 [self updateMainMenu];
426 [windowController processCommandQueueDidFinish];
428 inProcessCommandQueue = NO;
430 if ([sendQueue count] > 0) {
432 [backendProxy processInputAndData:sendQueue];
434 @catch (NSException *e) {
435 // Connection timed out, just ignore this.
436 //NSLog(@"WARNING! Connection timed out in %s", _cmd);
439 [sendQueue removeAllObjects];
443 - (void)windowDidBecomeMain:(NSNotification *)notification
446 [self updateMainMenu];
449 - (NSToolbarItem *)toolbar:(NSToolbar *)theToolbar
450 itemForItemIdentifier:(NSString *)itemId
451 willBeInsertedIntoToolbar:(BOOL)flag
453 NSToolbarItem *item = [toolbarItemDict objectForKey:itemId];
455 NSLog(@"WARNING: No toolbar item with id '%@'", itemId);
461 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)theToolbar
466 - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)theToolbar
471 @end // MMVimController
475 @implementation MMVimController (Private)
477 - (void)handleMessage:(int)msgid data:(NSData *)data
479 //NSLog(@"%@ %s", [self className], _cmd);
481 if (OpenVimWindowMsgID == msgid) {
482 [windowController openWindow];
483 } else if (BatchDrawMsgID == msgid) {
484 [self performBatchDrawWithData:data];
485 } else if (SelectTabMsgID == msgid) {
486 #if 0 // NOTE: Tab selection is done inside updateTabsWithData:.
487 const void *bytes = [data bytes];
488 int idx = *((int*)bytes);
489 //NSLog(@"Selecting tab with index %d", idx);
490 [windowController selectTabWithIndex:idx];
492 } else if (UpdateTabBarMsgID == msgid) {
493 [windowController updateTabsWithData:data];
494 } else if (ShowTabBarMsgID == msgid) {
495 [windowController showTabBar:YES];
496 } else if (HideTabBarMsgID == msgid) {
497 [windowController showTabBar:NO];
498 } else if (SetTextDimensionsMsgID == msgid) {
499 const void *bytes = [data bytes];
500 int rows = *((int*)bytes); bytes += sizeof(int);
501 int cols = *((int*)bytes); bytes += sizeof(int);
503 [windowController setTextDimensionsWithRows:rows columns:cols];
504 } else if (SetWindowTitleMsgID == msgid) {
505 const void *bytes = [data bytes];
506 int len = *((int*)bytes); bytes += sizeof(int);
508 NSString *string = [[NSString alloc] initWithBytes:(void*)bytes
509 length:len encoding:NSUTF8StringEncoding];
511 [[windowController window] setTitle:string];
514 } else if (AddMenuMsgID == msgid) {
515 NSString *title = nil;
516 const void *bytes = [data bytes];
517 int tag = *((int*)bytes); bytes += sizeof(int);
518 int parentTag = *((int*)bytes); bytes += sizeof(int);
519 int len = *((int*)bytes); bytes += sizeof(int);
521 title = [[NSString alloc] initWithBytes:(void*)bytes length:len
522 encoding:NSUTF8StringEncoding];
525 int idx = *((int*)bytes); bytes += sizeof(int);
527 if (MenuToolbarType == parentTag) {
529 // NOTE! Each toolbar must have a unique identifier, else each
530 // window will have the same toolbar.
531 NSString *ident = [NSString stringWithFormat:@"%d.%d",
533 toolbar = [[NSToolbar alloc] initWithIdentifier:ident];
535 [toolbar setShowsBaselineSeparator:NO];
536 [toolbar setDelegate:self];
537 [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
538 [toolbar setSizeMode:NSToolbarSizeModeSmall];
540 NSWindow *win = [windowController window];
541 [win setToolbar:toolbar];
543 // HACK! Redirect the pill button so that we can ask Vim to
545 NSButton *pillButton = [win
546 standardWindowButton:NSWindowToolbarButton];
548 [pillButton setAction:@selector(toggleToolbar:)];
549 [pillButton setTarget:windowController];
553 [self addMenuWithTag:tag parent:parentTag title:title atIndex:idx];
557 } else if (AddMenuItemMsgID == msgid) {
558 NSString *title = nil, *tip = nil, *icon = nil, *action = nil;
559 const void *bytes = [data bytes];
560 int tag = *((int*)bytes); bytes += sizeof(int);
561 int parentTag = *((int*)bytes); bytes += sizeof(int);
562 int namelen = *((int*)bytes); bytes += sizeof(int);
564 title = [[NSString alloc] initWithBytes:(void*)bytes length:namelen
565 encoding:NSUTF8StringEncoding];
568 int tiplen = *((int*)bytes); bytes += sizeof(int);
570 tip = [[NSString alloc] initWithBytes:(void*)bytes length:tiplen
571 encoding:NSUTF8StringEncoding];
574 int iconlen = *((int*)bytes); bytes += sizeof(int);
576 icon = [[NSString alloc] initWithBytes:(void*)bytes length:iconlen
577 encoding:NSUTF8StringEncoding];
580 int actionlen = *((int*)bytes); bytes += sizeof(int);
582 action = [[NSString alloc] initWithBytes:(void*)bytes
584 encoding:NSUTF8StringEncoding];
587 int idx = *((int*)bytes); bytes += sizeof(int);
588 if (idx < 0) idx = 0;
589 int key = *((int*)bytes); bytes += sizeof(int);
590 int mask = *((int*)bytes); bytes += sizeof(int);
592 NSString *ident = [NSString stringWithFormat:@"%d.%d",
593 (int)self, parentTag];
594 if (toolbar && [[toolbar identifier] isEqual:ident]) {
595 [self addToolbarItemWithTag:tag label:title tip:tip icon:icon
598 NSMenu *parent = [self menuForTag:parentTag];
599 [self addMenuItemWithTag:tag parent:parent title:title tip:tip
600 keyEquivalent:key modifiers:mask action:action
608 } else if (RemoveMenuItemMsgID == msgid) {
609 const void *bytes = [data bytes];
610 int tag = *((int*)bytes); bytes += sizeof(int);
614 if ((item = [self toolbarItemForTag:tag index:&idx])) {
615 [toolbar removeItemAtIndex:idx];
616 } else if ((item = [self menuItemForTag:tag])) {
619 if ([item menu] == [NSApp mainMenu] || ![item menu]) {
620 // NOTE: To be on the safe side we try to remove the item from
621 // both arrays (it is ok to call removeObject: even if an array
622 // does not contain the object to remove).
623 [mainMenuItems removeObject:item];
624 [popupMenuItems removeObject:item];
628 [[item menu] removeItem:item];
633 // Reset cached menu, just to be on the safe side.
634 lastMenuSearched = nil;
635 } else if (EnableMenuItemMsgID == msgid) {
636 const void *bytes = [data bytes];
637 int tag = *((int*)bytes); bytes += sizeof(int);
638 int state = *((int*)bytes); bytes += sizeof(int);
640 id item = [self toolbarItemForTag:tag index:NULL];
642 item = [self menuItemForTag:tag];
644 [item setEnabled:state];
645 } else if (ShowToolbarMsgID == msgid) {
646 const void *bytes = [data bytes];
647 int enable = *((int*)bytes); bytes += sizeof(int);
648 int flags = *((int*)bytes); bytes += sizeof(int);
650 int mode = NSToolbarDisplayModeDefault;
651 if (flags & ToolbarLabelFlag) {
652 mode = flags & ToolbarIconFlag ? NSToolbarDisplayModeIconAndLabel
653 : NSToolbarDisplayModeLabelOnly;
654 } else if (flags & ToolbarIconFlag) {
655 mode = NSToolbarDisplayModeIconOnly;
658 int size = flags & ToolbarSizeRegularFlag ? NSToolbarSizeModeRegular
659 : NSToolbarSizeModeSmall;
661 [windowController showToolbar:enable size:size mode:mode];
662 } else if (CreateScrollbarMsgID == msgid) {
663 const void *bytes = [data bytes];
664 long ident = *((long*)bytes); bytes += sizeof(long);
665 int type = *((int*)bytes); bytes += sizeof(int);
667 [windowController createScrollbarWithIdentifier:ident type:type];
668 } else if (DestroyScrollbarMsgID == msgid) {
669 const void *bytes = [data bytes];
670 long ident = *((long*)bytes); bytes += sizeof(long);
672 [windowController destroyScrollbarWithIdentifier:ident];
673 } else if (ShowScrollbarMsgID == msgid) {
674 const void *bytes = [data bytes];
675 long ident = *((long*)bytes); bytes += sizeof(long);
676 int visible = *((int*)bytes); bytes += sizeof(int);
678 [windowController showScrollbarWithIdentifier:ident state:visible];
679 } else if (SetScrollbarPositionMsgID == msgid) {
680 const void *bytes = [data bytes];
681 long ident = *((long*)bytes); bytes += sizeof(long);
682 int pos = *((int*)bytes); bytes += sizeof(int);
683 int len = *((int*)bytes); bytes += sizeof(int);
685 [windowController setScrollbarPosition:pos length:len
687 } else if (SetScrollbarThumbMsgID == msgid) {
688 const void *bytes = [data bytes];
689 long ident = *((long*)bytes); bytes += sizeof(long);
690 float val = *((float*)bytes); bytes += sizeof(float);
691 float prop = *((float*)bytes); bytes += sizeof(float);
693 [windowController setScrollbarThumbValue:val proportion:prop
695 } else if (SetFontMsgID == msgid) {
696 const void *bytes = [data bytes];
697 float size = *((float*)bytes); bytes += sizeof(float);
698 int len = *((int*)bytes); bytes += sizeof(int);
699 NSString *name = [[NSString alloc]
700 initWithBytes:(void*)bytes length:len
701 encoding:NSUTF8StringEncoding];
702 NSFont *font = [NSFont fontWithName:name size:size];
705 [windowController setFont:font];
708 } else if (SetDefaultColorsMsgID == msgid) {
709 const void *bytes = [data bytes];
710 unsigned bg = *((unsigned*)bytes); bytes += sizeof(unsigned);
711 unsigned fg = *((unsigned*)bytes); bytes += sizeof(unsigned);
712 NSColor *back = [NSColor colorWithArgbInt:bg];
713 NSColor *fore = [NSColor colorWithRgbInt:fg];
715 [windowController setDefaultColorsBackground:back foreground:fore];
716 } else if (ExecuteActionMsgID == msgid) {
717 const void *bytes = [data bytes];
718 int len = *((int*)bytes); bytes += sizeof(int);
719 NSString *actionName = [[NSString alloc]
720 initWithBytesNoCopy:(void*)bytes
722 encoding:NSUTF8StringEncoding
725 SEL sel = NSSelectorFromString(actionName);
726 [NSApp sendAction:sel to:nil from:self];
728 [actionName release];
729 } else if (ShowPopupMenuMsgID == msgid) {
730 const void *bytes = [data bytes];
731 int row = *((int*)bytes); bytes += sizeof(int);
732 int col = *((int*)bytes); bytes += sizeof(int);
733 int len = *((int*)bytes); bytes += sizeof(int);
734 NSString *title = [[NSString alloc]
735 initWithBytesNoCopy:(void*)bytes
737 encoding:NSUTF8StringEncoding
740 NSMenu *menu = [self topLevelMenuForTitle:title];
742 [windowController popupMenu:menu atRow:row column:col];
744 NSLog(@"WARNING: Cannot popup menu with title %@; no such menu.",
749 } else if (SetMouseShapeMsgID == msgid) {
750 const void *bytes = [data bytes];
751 int shape = *((int*)bytes); bytes += sizeof(int);
753 [windowController setMouseShape:shape];
754 } else if (AdjustLinespaceMsgID == msgid) {
755 const void *bytes = [data bytes];
756 int linespace = *((int*)bytes); bytes += sizeof(int);
758 [windowController adjustLinespace:linespace];
759 } else if (ActivateMsgID == msgid) {
760 [NSApp activateIgnoringOtherApps:YES];
761 [[windowController window] makeKeyAndOrderFront:self];
762 } else if (SetServerNameMsgID == msgid) {
763 NSString *name = [[NSString alloc] initWithData:data
764 encoding:NSUTF8StringEncoding];
765 [self setServerName:name];
767 } else if (EnterFullscreenMsgID == msgid) {
768 [windowController enterFullscreen];
769 } else if (LeaveFullscreenMsgID == msgid) {
770 [windowController leaveFullscreen];
771 } else if (BuffersNotModifiedMsgID == msgid) {
772 [[windowController window] setDocumentEdited:NO];
773 } else if (BuffersModifiedMsgID == msgid) {
774 [[windowController window] setDocumentEdited:YES];
776 NSLog(@"WARNING: Unknown message received (msgid=%d)", msgid);
781 #define MM_DEBUG_DRAWING 0
783 - (void)performBatchDrawWithData:(NSData *)data
785 // TODO! Move to window controller.
786 MMTextStorage *textStorage = [windowController textStorage];
787 MMTextView *textView = [windowController textView];
788 if (!(textStorage && textView))
791 const void *bytes = [data bytes];
792 const void *end = bytes + [data length];
795 NSLog(@"====> BEGIN %s", _cmd);
797 [textStorage beginEditing];
799 // TODO: Sanity check input
801 while (bytes < end) {
802 int type = *((int*)bytes); bytes += sizeof(int);
804 if (ClearAllDrawType == type) {
806 NSLog(@" Clear all");
808 [textStorage clearAll];
809 } else if (ClearBlockDrawType == type) {
810 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
811 int row1 = *((int*)bytes); bytes += sizeof(int);
812 int col1 = *((int*)bytes); bytes += sizeof(int);
813 int row2 = *((int*)bytes); bytes += sizeof(int);
814 int col2 = *((int*)bytes); bytes += sizeof(int);
817 NSLog(@" Clear block (%d,%d) -> (%d,%d)", row1, col1,
820 [textStorage clearBlockFromRow:row1 column:col1
821 toRow:row2 column:col2
822 color:[NSColor colorWithArgbInt:color]];
823 } else if (DeleteLinesDrawType == type) {
824 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
825 int row = *((int*)bytes); bytes += sizeof(int);
826 int count = *((int*)bytes); bytes += sizeof(int);
827 int bot = *((int*)bytes); bytes += sizeof(int);
828 int left = *((int*)bytes); bytes += sizeof(int);
829 int right = *((int*)bytes); bytes += sizeof(int);
832 NSLog(@" Delete %d line(s) from %d", count, row);
834 [textStorage deleteLinesFromRow:row lineCount:count
835 scrollBottom:bot left:left right:right
836 color:[NSColor colorWithArgbInt:color]];
837 } else if (ReplaceStringDrawType == type) {
838 int bg = *((int*)bytes); bytes += sizeof(int);
839 int fg = *((int*)bytes); bytes += sizeof(int);
840 int sp = *((int*)bytes); bytes += sizeof(int);
841 int row = *((int*)bytes); bytes += sizeof(int);
842 int col = *((int*)bytes); bytes += sizeof(int);
843 int flags = *((int*)bytes); bytes += sizeof(int);
844 int len = *((int*)bytes); bytes += sizeof(int);
845 NSString *string = [[NSString alloc]
846 initWithBytesNoCopy:(void*)bytes
848 encoding:NSUTF8StringEncoding
853 NSLog(@" Draw string at (%d,%d) length=%d flags=%d fg=0x%x "
854 "bg=0x%x sp=0x%x (%@)", row, col, len, flags, fg, bg, sp,
855 len > 0 ? [string substringToIndex:1] : @"");
857 // NOTE: If this is a call to draw the (block) cursor, then cancel
858 // any previous request to draw the insertion point, or it might
859 // get drawn as well.
860 if (flags & DRAW_CURSOR) {
861 [textView setShouldDrawInsertionPoint:NO];
862 //NSColor *color = [NSColor colorWithRgbInt:bg];
863 //[textView drawInsertionPointAtRow:row column:col
864 // shape:MMInsertionPointBlock
867 [textStorage replaceString:string
870 foregroundColor:[NSColor colorWithRgbInt:fg]
871 backgroundColor:[NSColor colorWithArgbInt:bg]
872 specialColor:[NSColor colorWithRgbInt:sp]];
875 } else if (InsertLinesDrawType == type) {
876 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
877 int row = *((int*)bytes); bytes += sizeof(int);
878 int count = *((int*)bytes); bytes += sizeof(int);
879 int bot = *((int*)bytes); bytes += sizeof(int);
880 int left = *((int*)bytes); bytes += sizeof(int);
881 int right = *((int*)bytes); bytes += sizeof(int);
884 NSLog(@" Insert %d line(s) at row %d", count, row);
886 [textStorage insertLinesAtRow:row lineCount:count
887 scrollBottom:bot left:left right:right
888 color:[NSColor colorWithArgbInt:color]];
889 } else if (DrawCursorDrawType == type) {
890 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
891 int row = *((int*)bytes); bytes += sizeof(int);
892 int col = *((int*)bytes); bytes += sizeof(int);
893 int shape = *((int*)bytes); bytes += sizeof(int);
894 int percent = *((int*)bytes); bytes += sizeof(int);
897 NSLog(@" Draw cursor at (%d,%d)", row, col);
899 [textView drawInsertionPointAtRow:row column:col shape:shape
901 color:[NSColor colorWithRgbInt:color]];
903 NSLog(@"WARNING: Unknown draw type (type=%d)", type);
907 [textStorage endEditing];
909 // NOTE: During resizing, Cocoa only sends draw messages before Vim's rows
910 // and columns are changed (due to ipc delays). Force a redraw here.
911 [[windowController vimView] displayIfNeeded];
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];