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.
13 * MMBackend communicates with the frontend (MacVim). It maintains a queue of
14 * output which is flushed to the frontend under controlled circumstances (so
15 * as to maintain a steady framerate). Input from the frontend is also handled
18 * The frontend communicates with the backend via the MMBackendProtocol. In
19 * particular, input is sent to the backend via processInput:data: and Vim
20 * state can be queried from the frontend with evaluateExpression:.
22 * It is very important to realize that all state is held by the backend, the
23 * frontend must either ask for state [MMBackend evaluateExpression:] or wait
24 * for the backend to update [MMVimController processCommandQueue:].
26 * The client/server functionality of Vim is handled by the backend. It sets
27 * up a named NSConnection to which other Vim processes can connect.
34 // NOTE: Colors in MMBackend are stored as unsigned ints on the form 0xaarrggbb
35 // whereas colors in Vim are int without the alpha component. Also note that
36 // 'transp' is assumed to be a value between 0 and 100.
37 #define MM_COLOR(col) ((unsigned)( ((col)&0xffffff) | 0xff000000 ))
38 #define MM_COLOR_WITH_TRANSP(col,transp) \
39 ((unsigned)( ((col)&0xffffff) \
40 | ((((unsigned)((((100-(transp))*255)/100)+.5f))&0xff)<<24) ))
43 // This constant controls how often the command queue may be flushed. If it is
44 // too small the app might feel unresponsive; if it is too large there might be
45 // long periods without the screen updating (e.g. when sourcing a large session
46 // file). (The unit is seconds.)
47 static float MMFlushTimeoutInterval = 0.1f;
48 static int MMFlushQueueLenHint = 80*40;
50 static unsigned MMServerMax = 1000;
52 // TODO: Move to separate file.
53 static int eventModifierFlagsToVimModMask(int modifierFlags);
54 static int vimModMaskToEventModifierFlags(int mods);
55 static int eventModifierFlagsToVimMouseModMask(int modifierFlags);
56 static int eventButtonNumberToVimMouseButton(int buttonNumber);
57 static int specialKeyToNSKey(int key);
67 @interface NSString (MMServerNameCompare)
68 - (NSComparisonResult)serverNameCompare:(NSString *)string;
73 @interface MMBackend (Private)
74 - (void)processInputQueue;
75 - (void)handleInputEvent:(int)msgid data:(NSData *)data;
76 + (NSDictionary *)specialKeys;
77 - (void)handleInsertText:(NSData *)data;
78 - (void)handleKeyDown:(NSString *)key modifiers:(int)mods;
79 - (void)queueMessage:(int)msgid data:(NSData *)data;
80 - (void)connectionDidDie:(NSNotification *)notification;
81 - (void)blinkTimerFired:(NSTimer *)timer;
82 - (void)focusChange:(BOOL)on;
83 - (void)handleToggleToolbar;
84 - (void)handleScrollbarEvent:(NSData *)data;
85 - (void)handleSetFont:(NSData *)data;
86 - (void)handleDropFiles:(NSData *)data;
87 - (void)handleDropString:(NSData *)data;
88 - (BOOL)checkForModifiedBuffers;
89 - (void)addInput:(NSString *)input;
94 @interface MMBackend (ClientServer)
95 - (NSString *)connectionNameFromServerName:(NSString *)name;
96 - (NSConnection *)connectionForServerName:(NSString *)name;
97 - (NSConnection *)connectionForServerPort:(int)port;
98 - (void)serverConnectionDidDie:(NSNotification *)notification;
99 - (void)addClient:(NSDistantObject *)client;
100 - (NSString *)alternateServerNameForName:(NSString *)name;
105 @implementation MMBackend
107 + (MMBackend *)sharedInstance
109 static MMBackend *singleton = nil;
110 return singleton ? singleton : (singleton = [MMBackend new]);
115 if ((self = [super init])) {
116 fontContainerRef = loadFonts();
118 outputQueue = [[NSMutableArray alloc] init];
119 inputQueue = [[NSMutableArray alloc] init];
120 drawData = [[NSMutableData alloc] initWithCapacity:1024];
121 connectionNameDict = [[NSMutableDictionary alloc] init];
122 clientProxyDict = [[NSMutableDictionary alloc] init];
123 serverReplyDict = [[NSMutableDictionary alloc] init];
125 NSString *path = [[NSBundle mainBundle] pathForResource:@"Colors"
128 colorDict = [[NSDictionary dictionaryWithContentsOfFile:path]
131 NSLog(@"WARNING: Could not locate Colors.plist.");
134 path = [[NSBundle mainBundle] pathForResource:@"SystemColors"
137 sysColorDict = [[NSDictionary dictionaryWithContentsOfFile:path]
140 NSLog(@"WARNING: Could not locate SystemColors.plist.");
149 //NSLog(@"%@ %s", [self className], _cmd);
150 [[NSNotificationCenter defaultCenter] removeObserver:self];
152 [oldWideFont release]; oldWideFont = nil;
153 [blinkTimer release]; blinkTimer = nil;
154 [alternateServerName release]; alternateServerName = nil;
155 [serverReplyDict release]; serverReplyDict = nil;
156 [clientProxyDict release]; clientProxyDict = nil;
157 [connectionNameDict release]; connectionNameDict = nil;
158 [inputQueue release]; inputQueue = nil;
159 [outputQueue release]; outputQueue = nil;
160 [drawData release]; drawData = nil;
161 [frontendProxy release]; frontendProxy = nil;
162 [connection release]; connection = nil;
163 [sysColorDict release]; sysColorDict = nil;
164 [colorDict release]; colorDict = nil;
169 - (void)setBackgroundColor:(int)color
171 backgroundColor = MM_COLOR_WITH_TRANSP(color,p_transp);
174 - (void)setForegroundColor:(int)color
176 foregroundColor = MM_COLOR(color);
179 - (void)setSpecialColor:(int)color
181 specialColor = MM_COLOR(color);
184 - (void)setDefaultColorsBackground:(int)bg foreground:(int)fg
186 defaultBackgroundColor = MM_COLOR_WITH_TRANSP(bg,p_transp);
187 defaultForegroundColor = MM_COLOR(fg);
189 NSMutableData *data = [NSMutableData data];
191 [data appendBytes:&defaultBackgroundColor length:sizeof(unsigned)];
192 [data appendBytes:&defaultForegroundColor length:sizeof(unsigned)];
194 [self queueMessage:SetDefaultColorsMsgID data:data];
197 - (NSConnection *)connection
200 // NOTE! If the name of the connection changes here it must also be
201 // updated in MMAppController.m.
202 NSString *name = [NSString stringWithFormat:@"%@-connection",
203 [[NSBundle mainBundle] bundleIdentifier]];
205 connection = [NSConnection connectionWithRegisteredName:name host:nil];
209 // NOTE: 'connection' may be nil here.
215 if (![self connection]) {
216 NSBundle *mainBundle = [NSBundle mainBundle];
218 NSString *path = [mainBundle bundlePath];
219 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
220 NSLog(@"WARNING: Failed to launch GUI with path %@", path);
224 // HACK! It would be preferable to launch the GUI using NSWorkspace,
225 // however I have not managed to figure out how to pass arguments using
228 // NOTE! Using NSTask to launch the GUI has the negative side-effect
229 // that the GUI won't be activated (or raised) so there is a hack in
230 // MMWindowController which always raises the app when a new window is
232 NSMutableArray *args = [NSMutableArray arrayWithObjects:
233 [NSString stringWithFormat:@"-%@", MMNoWindowKey], @"yes", nil];
234 NSString *exeName = [[mainBundle infoDictionary]
235 objectForKey:@"CFBundleExecutable"];
236 NSString *path = [mainBundle pathForAuxiliaryExecutable:exeName];
238 NSLog(@"ERROR: Could not find MacVim executable in bundle");
242 [NSTask launchedTaskWithLaunchPath:path arguments:args];
245 // HACK! The NSWorkspaceDidLaunchApplicationNotification does not work
246 // for tasks like this, so poll the mach bootstrap server until it
247 // returns a valid connection. Also set a time-out date so that we
248 // don't get stuck doing this forever.
249 NSDate *timeOutDate = [NSDate dateWithTimeIntervalSinceNow:15];
250 while (!connection &&
251 NSOrderedDescending == [timeOutDate compare:[NSDate date]])
253 [[NSRunLoop currentRunLoop]
254 runMode:NSDefaultRunLoopMode
255 beforeDate:[NSDate dateWithTimeIntervalSinceNow:1]];
257 // NOTE: This call will set 'connection' as a side-effect.
262 NSLog(@"WARNING: Timed-out waiting for GUI to launch.");
267 id proxy = [connection rootProxy];
268 [proxy setProtocolForProxy:@protocol(MMAppProtocol)];
270 [[NSNotificationCenter defaultCenter] addObserver:self
271 selector:@selector(connectionDidDie:)
272 name:NSConnectionDidDieNotification object:connection];
274 int pid = [[NSProcessInfo processInfo] processIdentifier];
277 frontendProxy = [proxy connectBackend:self pid:pid];
279 @catch (NSException *e) {
280 NSLog(@"Exception caught when trying to connect backend: \"%@\"", e);
284 [frontendProxy retain];
285 [frontendProxy setProtocolForProxy:@protocol(MMAppProtocol)];
288 return connection && frontendProxy;
291 - (BOOL)openVimWindow
293 [self queueMessage:OpenVimWindowMsgID data:nil];
299 int type = ClearAllDrawType;
301 // Any draw commands in queue are effectively obsolete since this clearAll
302 // will negate any effect they have, therefore we may as well clear the
304 [drawData setLength:0];
306 [drawData appendBytes:&type length:sizeof(int)];
309 - (void)clearBlockFromRow:(int)row1 column:(int)col1
310 toRow:(int)row2 column:(int)col2
312 int type = ClearBlockDrawType;
314 [drawData appendBytes:&type length:sizeof(int)];
316 [drawData appendBytes:&defaultBackgroundColor length:sizeof(unsigned)];
317 [drawData appendBytes:&row1 length:sizeof(int)];
318 [drawData appendBytes:&col1 length:sizeof(int)];
319 [drawData appendBytes:&row2 length:sizeof(int)];
320 [drawData appendBytes:&col2 length:sizeof(int)];
323 - (void)deleteLinesFromRow:(int)row count:(int)count
324 scrollBottom:(int)bottom left:(int)left right:(int)right
326 int type = DeleteLinesDrawType;
328 [drawData appendBytes:&type length:sizeof(int)];
330 [drawData appendBytes:&defaultBackgroundColor length:sizeof(unsigned)];
331 [drawData appendBytes:&row length:sizeof(int)];
332 [drawData appendBytes:&count length:sizeof(int)];
333 [drawData appendBytes:&bottom length:sizeof(int)];
334 [drawData appendBytes:&left length:sizeof(int)];
335 [drawData appendBytes:&right length:sizeof(int)];
338 - (void)drawString:(char*)s length:(int)len row:(int)row column:(int)col
339 cells:(int)cells flags:(int)flags
341 if (len <= 0 || cells <= 0) return;
343 int type = DrawStringDrawType;
345 [drawData appendBytes:&type length:sizeof(int)];
347 [drawData appendBytes:&backgroundColor length:sizeof(unsigned)];
348 [drawData appendBytes:&foregroundColor length:sizeof(unsigned)];
349 [drawData appendBytes:&specialColor length:sizeof(unsigned)];
350 [drawData appendBytes:&row length:sizeof(int)];
351 [drawData appendBytes:&col length:sizeof(int)];
352 [drawData appendBytes:&cells length:sizeof(int)];
353 [drawData appendBytes:&flags length:sizeof(int)];
354 [drawData appendBytes:&len length:sizeof(int)];
355 [drawData appendBytes:s length:len];
358 - (void)insertLinesFromRow:(int)row count:(int)count
359 scrollBottom:(int)bottom left:(int)left right:(int)right
361 int type = InsertLinesDrawType;
363 [drawData appendBytes:&type length:sizeof(int)];
365 [drawData appendBytes:&defaultBackgroundColor length:sizeof(unsigned)];
366 [drawData appendBytes:&row length:sizeof(int)];
367 [drawData appendBytes:&count length:sizeof(int)];
368 [drawData appendBytes:&bottom length:sizeof(int)];
369 [drawData appendBytes:&left length:sizeof(int)];
370 [drawData appendBytes:&right length:sizeof(int)];
373 - (void)drawCursorAtRow:(int)row column:(int)col shape:(int)shape
374 fraction:(int)percent color:(int)color
376 int type = DrawCursorDrawType;
377 unsigned uc = MM_COLOR(color);
379 [drawData appendBytes:&type length:sizeof(int)];
381 [drawData appendBytes:&uc length:sizeof(unsigned)];
382 [drawData appendBytes:&row length:sizeof(int)];
383 [drawData appendBytes:&col length:sizeof(int)];
384 [drawData appendBytes:&shape length:sizeof(int)];
385 [drawData appendBytes:&percent length:sizeof(int)];
390 // Tend to the run loop, returning immediately if there are no events
392 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
393 beforeDate:[NSDate distantPast]];
395 // Keyboard and mouse input is handled directly, other input is queued and
396 // processed here. This call may enter a blocking loop.
397 if ([inputQueue count] > 0)
398 [self processInputQueue];
401 - (void)flushQueue:(BOOL)force
403 // NOTE! This method gets called a lot; if we were to flush every time it
404 // got called MacVim would feel unresponsive. So there is a time out which
405 // ensures that the queue isn't flushed too often.
406 if (!force && lastFlushDate && -[lastFlushDate timeIntervalSinceNow]
407 < MMFlushTimeoutInterval
408 && [drawData length] < MMFlushQueueLenHint)
411 if ([drawData length] > 0) {
412 // HACK! Detect changes to 'guifontwide'.
413 if (gui.wide_font != (GuiFont)oldWideFont) {
414 [oldWideFont release];
415 oldWideFont = [(NSFont*)gui.wide_font retain];
416 [self setWideFont:oldWideFont];
419 [self queueMessage:BatchDrawMsgID data:[drawData copy]];
420 [drawData setLength:0];
423 if ([outputQueue count] > 0) {
425 [frontendProxy processCommandQueue:outputQueue];
427 @catch (NSException *e) {
428 NSLog(@"Exception caught when processing command queue: \"%@\"", e);
431 [outputQueue removeAllObjects];
433 [lastFlushDate release];
434 lastFlushDate = [[NSDate date] retain];
438 - (BOOL)waitForInput:(int)milliseconds
440 //NSLog(@"|ENTER| %s%d", _cmd, milliseconds);
441 NSDate *date = milliseconds > 0 ?
442 [NSDate dateWithTimeIntervalSinceNow:.001*milliseconds] :
443 [NSDate distantFuture];
445 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:date];
447 // I know of no way to figure out if the run loop exited because input was
448 // found or because of a time out, so I need to manually indicate when
449 // input was received in processInput:data: and then reset it every time
451 BOOL yn = inputReceived;
454 if ([inputQueue count] > 0)
455 [self processInputQueue];
457 //NSLog(@"|LEAVE| %s input=%d", _cmd, yn);
463 #ifdef MAC_CLIENTSERVER
464 // The default connection is used for the client/server code.
465 [[NSConnection defaultConnection] setRootObject:nil];
466 [[NSConnection defaultConnection] invalidate];
469 // By invalidating the NSConnection the MMWindowController immediately
470 // finds out that the connection is down and as a result
471 // [MMWindowController connectionDidDie:] is invoked.
472 //NSLog(@"%@ %s", [self className], _cmd);
473 [[NSNotificationCenter defaultCenter] removeObserver:self];
474 [connection invalidate];
476 if (fontContainerRef) {
477 ATSFontDeactivate(fontContainerRef, NULL, kATSOptionFlagsDefault);
478 fontContainerRef = 0;
483 - (void)selectTab:(int)index
485 //NSLog(@"%s%d", _cmd, index);
488 NSData *data = [NSData dataWithBytes:&index length:sizeof(int)];
489 [self queueMessage:SelectTabMsgID data:data];
494 //NSLog(@"%s", _cmd);
496 NSMutableData *data = [NSMutableData data];
498 int idx = tabpage_index(curtab) - 1;
499 [data appendBytes:&idx length:sizeof(int)];
502 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next) {
503 // This function puts the label of the tab in the global 'NameBuff'.
504 get_tabline_label(tp, FALSE);
505 char_u *s = NameBuff;
507 if (len <= 0) continue;
510 s = CONVERT_TO_UTF8(s);
513 // Count the number of windows in the tabpage.
514 //win_T *wp = tp->tp_firstwin;
516 //for (wincount = 0; wp != NULL; wp = wp->w_next, ++wincount);
518 //[data appendBytes:&wincount length:sizeof(int)];
519 [data appendBytes:&len length:sizeof(int)];
520 [data appendBytes:s length:len];
523 CONVERT_TO_UTF8_FREE(s);
527 [self queueMessage:UpdateTabBarMsgID data:data];
530 - (BOOL)tabBarVisible
532 return tabBarVisible;
535 - (void)showTabBar:(BOOL)enable
537 tabBarVisible = enable;
539 int msgid = enable ? ShowTabBarMsgID : HideTabBarMsgID;
540 [self queueMessage:msgid data:nil];
543 - (void)setRows:(int)rows columns:(int)cols
545 //NSLog(@"[VimTask] setRows:%d columns:%d", rows, cols);
547 int dim[] = { rows, cols };
548 NSData *data = [NSData dataWithBytes:&dim length:2*sizeof(int)];
550 [self queueMessage:SetTextDimensionsMsgID data:data];
553 - (void)setWindowTitle:(char *)title
555 NSMutableData *data = [NSMutableData data];
556 int len = strlen(title);
557 if (len <= 0) return;
559 [data appendBytes:&len length:sizeof(int)];
560 [data appendBytes:title length:len];
562 [self queueMessage:SetWindowTitleMsgID data:data];
565 - (char *)browseForFileInDirectory:(char *)dir title:(char *)title
568 //NSLog(@"browseForFileInDirectory:%s title:%s saving:%d", dir, title,
572 NSString *ds = dir ? [NSString stringWithUTF8String:dir] : nil;
573 NSString *ts = title ? [NSString stringWithUTF8String:title] : nil;
575 [frontendProxy showSavePanelForDirectory:ds title:ts saving:saving];
577 // Wait until a reply is sent from MMVimController.
578 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
579 beforeDate:[NSDate distantFuture]];
581 if (dialogReturn && [dialogReturn isKindOfClass:[NSString class]]) {
582 char_u *ret = (char_u*)[dialogReturn UTF8String];
584 ret = CONVERT_FROM_UTF8(ret);
586 s = vim_strsave(ret);
588 CONVERT_FROM_UTF8_FREE(ret);
592 [dialogReturn release]; dialogReturn = nil;
594 @catch (NSException *e) {
595 NSLog(@"Exception caught when showing save panel: \"%@\"", e);
601 - (oneway void)setDialogReturn:(in bycopy id)obj
603 // NOTE: This is called by
604 // - [MMVimController panelDidEnd:::], and
605 // - [MMVimController alertDidEnd:::],
606 // to indicate that a save/open panel or alert has finished.
608 if (obj != dialogReturn) {
609 [dialogReturn release];
610 dialogReturn = [obj retain];
614 - (int)presentDialogWithType:(int)type title:(char *)title message:(char *)msg
615 buttons:(char *)btns textField:(char *)txtfield
618 NSString *message = nil, *text = nil, *textFieldString = nil;
619 NSArray *buttons = nil;
620 int style = NSInformationalAlertStyle;
622 if (VIM_WARNING == type) style = NSWarningAlertStyle;
623 else if (VIM_ERROR == type) style = NSCriticalAlertStyle;
626 NSString *btnString = [NSString stringWithUTF8String:btns];
627 buttons = [btnString componentsSeparatedByString:@"\n"];
630 message = [NSString stringWithUTF8String:title];
632 text = [NSString stringWithUTF8String:msg];
634 // HACK! If there is a '\n\n' or '\n' sequence in the message, then
635 // make the part up to there into the title. We only do this
636 // because Vim has lots of dialogs without a title and they look
638 // TODO: Fix the actual dialog texts.
639 NSRange eolRange = [text rangeOfString:@"\n\n"];
640 if (NSNotFound == eolRange.location)
641 eolRange = [text rangeOfString:@"\n"];
642 if (NSNotFound != eolRange.location) {
643 message = [text substringToIndex:eolRange.location];
644 text = [text substringFromIndex:NSMaxRange(eolRange)];
649 textFieldString = [NSString stringWithUTF8String:txtfield];
652 [frontendProxy presentDialogWithStyle:style message:message
653 informativeText:text buttonTitles:buttons
654 textFieldString:textFieldString];
656 // Wait until a reply is sent from MMVimController.
657 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
658 beforeDate:[NSDate distantFuture]];
660 if (dialogReturn && [dialogReturn isKindOfClass:[NSArray class]]
661 && [dialogReturn count]) {
662 retval = [[dialogReturn objectAtIndex:0] intValue];
663 if (txtfield && [dialogReturn count] > 1) {
664 NSString *retString = [dialogReturn objectAtIndex:1];
665 char_u *ret = (char_u*)[retString UTF8String];
667 ret = CONVERT_FROM_UTF8(ret);
669 vim_strncpy((char_u*)txtfield, ret, IOSIZE - 1);
671 CONVERT_FROM_UTF8_FREE(ret);
676 [dialogReturn release]; dialogReturn = nil;
678 @catch (NSException *e) {
679 NSLog(@"Exception caught while showing alert dialog: \"%@\"", e);
685 - (void)addMenuWithTag:(int)tag parent:(int)parentTag name:(char *)name
688 //NSLog(@"addMenuWithTag:%d parent:%d name:%s atIndex:%d", tag, parentTag,
691 int namelen = name ? strlen(name) : 0;
692 NSMutableData *data = [NSMutableData data];
694 [data appendBytes:&tag length:sizeof(int)];
695 [data appendBytes:&parentTag length:sizeof(int)];
696 [data appendBytes:&namelen length:sizeof(int)];
697 if (namelen > 0) [data appendBytes:name length:namelen];
698 [data appendBytes:&index length:sizeof(int)];
700 [self queueMessage:AddMenuMsgID data:data];
703 - (void)addMenuItemWithTag:(int)tag parent:(int)parentTag name:(char *)name
704 tip:(char *)tip icon:(char *)icon
705 keyEquivalent:(int)key modifiers:(int)mods
706 action:(NSString *)action atIndex:(int)index
708 //NSLog(@"addMenuItemWithTag:%d parent:%d name:%s tip:%s atIndex:%d", tag,
709 // parentTag, name, tip, index);
711 int namelen = name ? strlen(name) : 0;
712 int tiplen = tip ? strlen(tip) : 0;
713 int iconlen = icon ? strlen(icon) : 0;
714 int eventFlags = vimModMaskToEventModifierFlags(mods);
715 int actionlen = [action lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
716 NSMutableData *data = [NSMutableData data];
718 key = specialKeyToNSKey(key);
720 [data appendBytes:&tag length:sizeof(int)];
721 [data appendBytes:&parentTag length:sizeof(int)];
722 [data appendBytes:&namelen length:sizeof(int)];
723 if (namelen > 0) [data appendBytes:name length:namelen];
724 [data appendBytes:&tiplen length:sizeof(int)];
725 if (tiplen > 0) [data appendBytes:tip length:tiplen];
726 [data appendBytes:&iconlen length:sizeof(int)];
727 if (iconlen > 0) [data appendBytes:icon length:iconlen];
728 [data appendBytes:&actionlen length:sizeof(int)];
729 if (actionlen > 0) [data appendBytes:[action UTF8String] length:actionlen];
730 [data appendBytes:&index length:sizeof(int)];
731 [data appendBytes:&key length:sizeof(int)];
732 [data appendBytes:&eventFlags length:sizeof(int)];
734 [self queueMessage:AddMenuItemMsgID data:data];
737 - (void)removeMenuItemWithTag:(int)tag
739 NSMutableData *data = [NSMutableData data];
740 [data appendBytes:&tag length:sizeof(int)];
742 [self queueMessage:RemoveMenuItemMsgID data:data];
745 - (void)enableMenuItemWithTag:(int)tag state:(int)enabled
747 NSMutableData *data = [NSMutableData data];
749 [data appendBytes:&tag length:sizeof(int)];
750 [data appendBytes:&enabled length:sizeof(int)];
752 [self queueMessage:EnableMenuItemMsgID data:data];
755 - (void)showPopupMenuWithName:(char *)name atMouseLocation:(BOOL)mouse
757 int len = strlen(name);
758 int row = -1, col = -1;
760 if (len <= 0) return;
762 if (!mouse && curwin) {
763 row = curwin->w_wrow;
764 col = curwin->w_wcol;
767 NSMutableData *data = [NSMutableData data];
769 [data appendBytes:&row length:sizeof(int)];
770 [data appendBytes:&col length:sizeof(int)];
771 [data appendBytes:&len length:sizeof(int)];
772 [data appendBytes:name length:len];
774 [self queueMessage:ShowPopupMenuMsgID data:data];
777 - (void)showToolbar:(int)enable flags:(int)flags
779 NSMutableData *data = [NSMutableData data];
781 [data appendBytes:&enable length:sizeof(int)];
782 [data appendBytes:&flags length:sizeof(int)];
784 [self queueMessage:ShowToolbarMsgID data:data];
787 - (void)createScrollbarWithIdentifier:(long)ident type:(int)type
789 NSMutableData *data = [NSMutableData data];
791 [data appendBytes:&ident length:sizeof(long)];
792 [data appendBytes:&type length:sizeof(int)];
794 [self queueMessage:CreateScrollbarMsgID data:data];
797 - (void)destroyScrollbarWithIdentifier:(long)ident
799 NSMutableData *data = [NSMutableData data];
800 [data appendBytes:&ident length:sizeof(long)];
802 [self queueMessage:DestroyScrollbarMsgID data:data];
805 - (void)showScrollbarWithIdentifier:(long)ident state:(int)visible
807 NSMutableData *data = [NSMutableData data];
809 [data appendBytes:&ident length:sizeof(long)];
810 [data appendBytes:&visible length:sizeof(int)];
812 [self queueMessage:ShowScrollbarMsgID data:data];
815 - (void)setScrollbarPosition:(int)pos length:(int)len identifier:(long)ident
817 NSMutableData *data = [NSMutableData data];
819 [data appendBytes:&ident length:sizeof(long)];
820 [data appendBytes:&pos length:sizeof(int)];
821 [data appendBytes:&len length:sizeof(int)];
823 [self queueMessage:SetScrollbarPositionMsgID data:data];
826 - (void)setScrollbarThumbValue:(long)val size:(long)size max:(long)max
827 identifier:(long)ident
829 float fval = max-size+1 > 0 ? (float)val/(max-size+1) : 0;
830 float prop = (float)size/(max+1);
831 if (fval < 0) fval = 0;
832 else if (fval > 1.0f) fval = 1.0f;
833 if (prop < 0) prop = 0;
834 else if (prop > 1.0f) prop = 1.0f;
836 NSMutableData *data = [NSMutableData data];
838 [data appendBytes:&ident length:sizeof(long)];
839 [data appendBytes:&fval length:sizeof(float)];
840 [data appendBytes:&prop length:sizeof(float)];
842 [self queueMessage:SetScrollbarThumbMsgID data:data];
845 - (void)setFont:(NSFont *)font
847 NSString *fontName = [font displayName];
848 float size = [font pointSize];
849 int len = [fontName lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
851 NSMutableData *data = [NSMutableData data];
853 [data appendBytes:&size length:sizeof(float)];
854 [data appendBytes:&len length:sizeof(int)];
855 [data appendBytes:[fontName UTF8String] length:len];
857 [self queueMessage:SetFontMsgID data:data];
861 - (void)setWideFont:(NSFont *)font
863 NSString *fontName = [font displayName];
864 float size = [font pointSize];
865 int len = [fontName lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
866 NSMutableData *data = [NSMutableData data];
868 [data appendBytes:&size length:sizeof(float)];
869 [data appendBytes:&len length:sizeof(int)];
871 [data appendBytes:[fontName UTF8String] length:len];
873 [self queueMessage:SetWideFontMsgID data:data];
876 - (void)executeActionWithName:(NSString *)name
878 int len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
881 NSMutableData *data = [NSMutableData data];
883 [data appendBytes:&len length:sizeof(int)];
884 [data appendBytes:[name UTF8String] length:len];
886 [self queueMessage:ExecuteActionMsgID data:data];
890 - (void)setMouseShape:(int)shape
892 NSMutableData *data = [NSMutableData data];
893 [data appendBytes:&shape length:sizeof(int)];
894 [self queueMessage:SetMouseShapeMsgID data:data];
897 - (void)setBlinkWait:(int)wait on:(int)on off:(int)off
899 // Vim specifies times in milliseconds, whereas Cocoa wants them in
901 blinkWaitInterval = .001f*wait;
902 blinkOnInterval = .001f*on;
903 blinkOffInterval = .001f*off;
909 [blinkTimer invalidate];
910 [blinkTimer release];
914 if (blinkWaitInterval > 0 && blinkOnInterval > 0 && blinkOffInterval > 0
916 blinkState = MMBlinkStateOn;
918 [[NSTimer scheduledTimerWithTimeInterval:blinkWaitInterval
920 selector:@selector(blinkTimerFired:)
921 userInfo:nil repeats:NO] retain];
922 gui_update_cursor(TRUE, FALSE);
923 [self flushQueue:YES];
929 if (MMBlinkStateOff == blinkState) {
930 gui_update_cursor(TRUE, FALSE);
931 [self flushQueue:YES];
934 blinkState = MMBlinkStateNone;
937 - (void)adjustLinespace:(int)linespace
939 NSMutableData *data = [NSMutableData data];
940 [data appendBytes:&linespace length:sizeof(int)];
941 [self queueMessage:AdjustLinespaceMsgID data:data];
946 [self queueMessage:ActivateMsgID data:nil];
949 - (void)setPreEditRow:(int)row column:(int)col
951 NSMutableData *data = [NSMutableData data];
952 [data appendBytes:&row length:sizeof(int)];
953 [data appendBytes:&col length:sizeof(int)];
954 [self queueMessage:SetPreEditPositionMsgID data:data];
957 - (int)lookupColorWithKey:(NSString *)key
959 if (!(key && [key length] > 0))
962 NSString *stripKey = [[[[key lowercaseString]
963 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
964 componentsSeparatedByString:@" "]
965 componentsJoinedByString:@""];
967 if (stripKey && [stripKey length] > 0) {
968 // First of all try to lookup key in the color dictionary; note that
969 // all keys in this dictionary are lowercase with no whitespace.
970 id obj = [colorDict objectForKey:stripKey];
971 if (obj) return [obj intValue];
973 // The key was not in the dictionary; is it perhaps of the form
975 if ([stripKey length] > 1 && [stripKey characterAtIndex:0] == '#') {
976 NSScanner *scanner = [NSScanner scannerWithString:stripKey];
977 [scanner setScanLocation:1];
979 if ([scanner scanHexInt:&hex]) {
984 // As a last resort, check if it is one of the system defined colors.
985 // The keys in this dictionary are also lowercase with no whitespace.
986 obj = [sysColorDict objectForKey:stripKey];
988 NSColor *col = [NSColor performSelector:NSSelectorFromString(obj)];
991 col = [col colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
992 [col getRed:&r green:&g blue:&b alpha:&a];
993 return (((int)(r*255+.5f) & 0xff) << 16)
994 + (((int)(g*255+.5f) & 0xff) << 8)
995 + ((int)(b*255+.5f) & 0xff);
1000 NSLog(@"WARNING: No color with key %@ found.", stripKey);
1004 - (BOOL)hasSpecialKeyWithValue:(NSString *)value
1006 NSEnumerator *e = [[MMBackend specialKeys] objectEnumerator];
1009 while ((obj = [e nextObject])) {
1010 if ([value isEqual:obj])
1017 - (void)enterFullscreen
1019 [self queueMessage:EnterFullscreenMsgID data:nil];
1022 - (void)leaveFullscreen
1024 [self queueMessage:LeaveFullscreenMsgID data:nil];
1027 - (void)updateModifiedFlag
1029 // Notify MacVim if _any_ buffer has changed from unmodified to modified or
1031 int msgid = [self checkForModifiedBuffers]
1032 ? BuffersModifiedMsgID : BuffersNotModifiedMsgID;
1034 [self queueMessage:msgid data:nil];
1037 - (oneway void)processInput:(int)msgid data:(in bycopy NSData *)data
1039 // NOTE: This method might get called whenever the run loop is tended to.
1040 // Normal keyboard and mouse input is added to input buffers, so there is
1041 // no risk in handling these events directly (they return immediately, and
1042 // do not call any other Vim functions). However, other events such
1043 // as 'VimShouldCloseMsgID' may enter blocking loops that wait for key
1044 // events which would cause this method to be called recursively. This
1045 // in turn leads to various difficulties that we do not want to have to
1046 // deal with. To avoid recursive calls here we add all events except
1047 // keyboard and mouse events to an input queue which is processed whenever
1048 // gui_mch_update() is called (see processInputQueue).
1050 //NSLog(@"%s%s", _cmd, MessageStrings[msgid]);
1052 // Don't flush too soon after receiving input or update speed will suffer.
1053 [lastFlushDate release];
1054 lastFlushDate = [[NSDate date] retain];
1056 // Handle keyboard and mouse input now. All other events are queued.
1057 if (InsertTextMsgID == msgid) {
1058 [self handleInsertText:data];
1059 } else if (KeyDownMsgID == msgid || CmdKeyMsgID == msgid) {
1061 const void *bytes = [data bytes];
1062 int mods = *((int*)bytes); bytes += sizeof(int);
1063 int len = *((int*)bytes); bytes += sizeof(int);
1064 NSString *key = [[NSString alloc] initWithBytes:bytes length:len
1065 encoding:NSUTF8StringEncoding];
1066 mods = eventModifierFlagsToVimModMask(mods);
1068 [self handleKeyDown:key modifiers:mods];
1071 } else if (ScrollWheelMsgID == msgid) {
1073 const void *bytes = [data bytes];
1075 int row = *((int*)bytes); bytes += sizeof(int);
1076 int col = *((int*)bytes); bytes += sizeof(int);
1077 int flags = *((int*)bytes); bytes += sizeof(int);
1078 float dy = *((float*)bytes); bytes += sizeof(float);
1080 int button = MOUSE_5;
1081 if (dy > 0) button = MOUSE_4;
1083 flags = eventModifierFlagsToVimMouseModMask(flags);
1085 gui_send_mouse_event(button, col, row, NO, flags);
1086 } else if (MouseDownMsgID == msgid) {
1088 const void *bytes = [data bytes];
1090 int row = *((int*)bytes); bytes += sizeof(int);
1091 int col = *((int*)bytes); bytes += sizeof(int);
1092 int button = *((int*)bytes); bytes += sizeof(int);
1093 int flags = *((int*)bytes); bytes += sizeof(int);
1094 int count = *((int*)bytes); bytes += sizeof(int);
1096 button = eventButtonNumberToVimMouseButton(button);
1098 flags = eventModifierFlagsToVimMouseModMask(flags);
1099 gui_send_mouse_event(button, col, row, count>1, flags);
1101 } else if (MouseUpMsgID == msgid) {
1103 const void *bytes = [data bytes];
1105 int row = *((int*)bytes); bytes += sizeof(int);
1106 int col = *((int*)bytes); bytes += sizeof(int);
1107 int flags = *((int*)bytes); bytes += sizeof(int);
1109 flags = eventModifierFlagsToVimMouseModMask(flags);
1111 gui_send_mouse_event(MOUSE_RELEASE, col, row, NO, flags);
1112 } else if (MouseDraggedMsgID == msgid) {
1114 const void *bytes = [data bytes];
1116 int row = *((int*)bytes); bytes += sizeof(int);
1117 int col = *((int*)bytes); bytes += sizeof(int);
1118 int flags = *((int*)bytes); bytes += sizeof(int);
1120 flags = eventModifierFlagsToVimMouseModMask(flags);
1122 gui_send_mouse_event(MOUSE_DRAG, col, row, NO, flags);
1123 } else if (MouseMovedMsgID == msgid) {
1124 const void *bytes = [data bytes];
1125 int row = *((int*)bytes); bytes += sizeof(int);
1126 int col = *((int*)bytes); bytes += sizeof(int);
1128 gui_mouse_moved(col, row);
1129 } else if (AddInputMsgID == msgid) {
1130 NSString *string = [[NSString alloc] initWithData:data
1131 encoding:NSUTF8StringEncoding];
1133 [self addInput:string];
1137 // Not keyboard or mouse event, queue it and handle later.
1138 //NSLog(@"Add event %s to input event queue", MessageStrings[msgid]);
1139 [inputQueue addObject:[NSNumber numberWithInt:msgid]];
1140 [inputQueue addObject:(data ? (id)data : (id)[NSNull null])];
1143 // See waitForInput: for an explanation of this flag.
1144 inputReceived = YES;
1147 - (oneway void)processInputAndData:(in bycopy NSArray *)messages
1149 // TODO: Get rid of this method?
1150 //NSLog(@"%s%@", _cmd, messages);
1152 unsigned i, count = [messages count];
1153 for (i = 0; i < count; i += 2) {
1154 int msgid = [[messages objectAtIndex:i] intValue];
1155 id data = [messages objectAtIndex:i+1];
1156 if ([data isEqual:[NSNull null]])
1159 [self processInput:msgid data:data];
1163 - (NSString *)evaluateExpression:(in bycopy NSString *)expr
1165 NSString *eval = nil;
1166 char_u *s = (char_u*)[expr UTF8String];
1169 s = CONVERT_FROM_UTF8(s);
1172 char_u *res = eval_client_expr_to_string(s);
1175 CONVERT_FROM_UTF8_FREE(s);
1181 s = CONVERT_TO_UTF8(s);
1183 eval = [NSString stringWithUTF8String:(char*)s];
1185 CONVERT_TO_UTF8_FREE(s);
1193 - (BOOL)starRegisterToPasteboard:(byref NSPasteboard *)pboard
1195 if (VIsual_active && (State & NORMAL) && clip_star.available) {
1196 // If there is no pasteboard, return YES to indicate that there is text
1201 clip_copy_selection();
1203 // Get the text to put on the pasteboard.
1204 long_u llen = 0; char_u *str = 0;
1205 int type = clip_convert_selection(&str, &llen, &clip_star);
1209 // TODO: Avoid overflow.
1210 int len = (int)llen;
1212 if (output_conv.vc_type != CONV_NONE) {
1213 char_u *conv_str = string_convert(&output_conv, str, &len);
1221 NSString *string = [[NSString alloc]
1222 initWithBytes:str length:len encoding:NSUTF8StringEncoding];
1224 NSArray *types = [NSArray arrayWithObject:NSStringPboardType];
1225 [pboard declareTypes:types owner:nil];
1226 BOOL ok = [pboard setString:string forType:NSStringPboardType];
1237 - (oneway void)addReply:(in bycopy NSString *)reply
1238 server:(in byref id <MMVimServerProtocol>)server
1240 //NSLog(@"addReply:%@ server:%@", reply, (id)server);
1242 // Replies might come at any time and in any order so we keep them in an
1243 // array inside a dictionary with the send port used as key.
1245 NSConnection *conn = [(NSDistantObject*)server connectionForProxy];
1246 // HACK! Assume connection uses mach ports.
1247 int port = [(NSMachPort*)[conn sendPort] machPort];
1248 NSNumber *key = [NSNumber numberWithInt:port];
1250 NSMutableArray *replies = [serverReplyDict objectForKey:key];
1252 replies = [NSMutableArray array];
1253 [serverReplyDict setObject:replies forKey:key];
1256 [replies addObject:reply];
1259 - (void)addInput:(in bycopy NSString *)input
1260 client:(in byref id <MMVimClientProtocol>)client
1262 //NSLog(@"addInput:%@ client:%@", input, (id)client);
1264 [self addInput:input];
1265 [self addClient:(id)client];
1267 inputReceived = YES;
1270 - (NSString *)evaluateExpression:(in bycopy NSString *)expr
1271 client:(in byref id <MMVimClientProtocol>)client
1273 [self addClient:(id)client];
1274 return [self evaluateExpression:expr];
1277 - (void)registerServerWithName:(NSString *)name
1279 NSString *svrName = name;
1280 NSConnection *svrConn = [NSConnection defaultConnection];
1283 for (i = 0; i < MMServerMax; ++i) {
1284 NSString *connName = [self connectionNameFromServerName:svrName];
1286 if ([svrConn registerName:connName]) {
1287 //NSLog(@"Registered server with name: %@", svrName);
1289 // TODO: Set request/reply time-outs to something else?
1291 // Don't wait for requests (time-out means that the message is
1293 [svrConn setRequestTimeout:0];
1294 //[svrConn setReplyTimeout:MMReplyTimeout];
1295 [svrConn setRootObject:self];
1297 char_u *s = (char_u*)[svrName UTF8String];
1299 s = CONVERT_FROM_UTF8(s);
1301 // NOTE: 'serverName' is a global variable
1302 serverName = vim_strsave(s);
1304 CONVERT_FROM_UTF8_FREE(s);
1307 set_vim_var_string(VV_SEND_SERVER, serverName, -1);
1310 need_maketitle = TRUE;
1312 [self queueMessage:SetServerNameMsgID data:
1313 [svrName dataUsingEncoding:NSUTF8StringEncoding]];
1317 svrName = [NSString stringWithFormat:@"%@%d", name, i+1];
1321 - (BOOL)sendToServer:(NSString *)name string:(NSString *)string
1322 reply:(char_u **)reply port:(int *)port expression:(BOOL)expr
1325 // NOTE: If 'name' equals 'serverName' then the request is local (client
1326 // and server are the same). This case is not handled separately, so a
1327 // connection will be set up anyway (this simplifies the code).
1329 NSConnection *conn = [self connectionForServerName:name];
1332 char_u *s = (char_u*)[name UTF8String];
1334 s = CONVERT_FROM_UTF8(s);
1336 EMSG2(_(e_noserver), s);
1338 CONVERT_FROM_UTF8_FREE(s);
1345 // HACK! Assume connection uses mach ports.
1346 *port = [(NSMachPort*)[conn sendPort] machPort];
1349 id proxy = [conn rootProxy];
1350 [proxy setProtocolForProxy:@protocol(MMVimServerProtocol)];
1354 NSString *eval = [proxy evaluateExpression:string client:self];
1357 char_u *r = (char_u*)[eval UTF8String];
1359 r = CONVERT_FROM_UTF8(r);
1361 *reply = vim_strsave(r);
1363 CONVERT_FROM_UTF8_FREE(r);
1366 *reply = vim_strsave((char_u*)_(e_invexprmsg));
1373 [proxy addInput:string client:self];
1376 @catch (NSException *e) {
1377 NSLog(@"WARNING: Caught exception in %s: \"%@\"", _cmd, e);
1384 - (NSArray *)serverList
1386 NSArray *list = nil;
1388 if ([self connection]) {
1389 id proxy = [connection rootProxy];
1390 [proxy setProtocolForProxy:@protocol(MMAppProtocol)];
1393 list = [proxy serverList];
1395 @catch (NSException *e) {
1396 NSLog(@"Exception caught when listing servers: \"%@\"", e);
1399 EMSG(_("E???: No connection to MacVim, server listing not possible."));
1405 - (NSString *)peekForReplyOnPort:(int)port
1407 //NSLog(@"%s%d", _cmd, port);
1409 NSNumber *key = [NSNumber numberWithInt:port];
1410 NSMutableArray *replies = [serverReplyDict objectForKey:key];
1411 if (replies && [replies count]) {
1412 //NSLog(@" %d replies, topmost is: %@", [replies count],
1413 // [replies objectAtIndex:0]);
1414 return [replies objectAtIndex:0];
1417 //NSLog(@" No replies");
1421 - (NSString *)waitForReplyOnPort:(int)port
1423 //NSLog(@"%s%d", _cmd, port);
1425 NSConnection *conn = [self connectionForServerPort:port];
1429 NSNumber *key = [NSNumber numberWithInt:port];
1430 NSMutableArray *replies = nil;
1431 NSString *reply = nil;
1433 // Wait for reply as long as the connection to the server is valid (unless
1434 // user interrupts wait with Ctrl-C).
1435 while (!got_int && [conn isValid] &&
1436 !(replies = [serverReplyDict objectForKey:key])) {
1437 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
1438 beforeDate:[NSDate distantFuture]];
1442 if ([replies count] > 0) {
1443 reply = [[replies objectAtIndex:0] retain];
1444 //NSLog(@" Got reply: %@", reply);
1445 [replies removeObjectAtIndex:0];
1446 [reply autorelease];
1449 if ([replies count] == 0)
1450 [serverReplyDict removeObjectForKey:key];
1456 - (BOOL)sendReply:(NSString *)reply toPort:(int)port
1458 id client = [clientProxyDict objectForKey:[NSNumber numberWithInt:port]];
1461 //NSLog(@"sendReply:%@ toPort:%d", reply, port);
1462 [client addReply:reply server:self];
1465 @catch (NSException *e) {
1466 NSLog(@"WARNING: Exception caught in %s: \"%@\"", _cmd, e);
1469 EMSG2(_("E???: server2client failed; no client with id 0x%x"), port);
1479 @implementation MMBackend (Private)
1481 - (void)processInputQueue
1483 // NOTE: One of the input events may cause this method to be called
1484 // recursively, so copy the input queue to a local variable and clear it
1485 // before starting to process input events (otherwise we could get stuck in
1486 // an endless loop).
1487 NSArray *q = [inputQueue copy];
1488 unsigned i, count = [q count];
1490 [inputQueue removeAllObjects];
1492 for (i = 0; i < count-1; i += 2) {
1493 int msgid = [[q objectAtIndex:i] intValue];
1494 id data = [q objectAtIndex:i+1];
1495 if ([data isEqual:[NSNull null]])
1498 //NSLog(@"(%d) %s:%s", i, _cmd, MessageStrings[msgid]);
1499 [self handleInputEvent:msgid data:data];
1503 //NSLog(@"Clear input event queue");
1506 - (void)handleInputEvent:(int)msgid data:(NSData *)data
1508 // NOTE: Be careful with what you do in this method. Ideally, a message
1509 // should be handled by adding something to the input buffer and returning
1510 // immediately. If you call a Vim function then it should not enter a loop
1511 // waiting for key presses or in any other way block the process. The
1512 // reason for this being that only one message can be processed at a time,
1513 // so if another message is received while processing, then the new message
1514 // is dropped. See also the comment in processInput:data:.
1516 //NSLog(@"%s%s", _cmd, MessageStrings[msgid]);
1518 if (SelectTabMsgID == msgid) {
1520 const void *bytes = [data bytes];
1521 int idx = *((int*)bytes) + 1;
1522 //NSLog(@"Selecting tab %d", idx);
1523 send_tabline_event(idx);
1524 } else if (CloseTabMsgID == msgid) {
1526 const void *bytes = [data bytes];
1527 int idx = *((int*)bytes) + 1;
1528 //NSLog(@"Closing tab %d", idx);
1529 send_tabline_menu_event(idx, TABLINE_MENU_CLOSE);
1530 } else if (AddNewTabMsgID == msgid) {
1531 //NSLog(@"Adding new tab");
1532 send_tabline_menu_event(0, TABLINE_MENU_NEW);
1533 } else if (DraggedTabMsgID == msgid) {
1535 const void *bytes = [data bytes];
1536 // NOTE! The destination index is 0 based, so do not add 1 to make it 1
1538 int idx = *((int*)bytes);
1541 } else if (SetTextDimensionsMsgID == msgid) {
1543 const void *bytes = [data bytes];
1544 int rows = *((int*)bytes); bytes += sizeof(int);
1545 int cols = *((int*)bytes); bytes += sizeof(int);
1547 // NOTE! Vim doesn't call gui_mch_set_shellsize() after
1548 // gui_resize_shell(), so we have to manually set the rows and columns
1549 // here. (MacVim doesn't change the rows and columns to avoid
1550 // inconsistent states between Vim and MacVim.)
1551 [self setRows:rows columns:cols];
1553 //NSLog(@"[VimTask] Resizing shell to %dx%d.", cols, rows);
1554 gui_resize_shell(cols, rows);
1555 } else if (ExecuteMenuMsgID == msgid) {
1557 const void *bytes = [data bytes];
1558 int tag = *((int*)bytes); bytes += sizeof(int);
1560 vimmenu_T *menu = (vimmenu_T*)tag;
1561 // TODO! Make sure 'menu' is a valid menu pointer!
1565 } else if (ToggleToolbarMsgID == msgid) {
1566 [self handleToggleToolbar];
1567 } else if (ScrollbarEventMsgID == msgid) {
1568 [self handleScrollbarEvent:data];
1569 } else if (SetFontMsgID == msgid) {
1570 [self handleSetFont:data];
1571 } else if (VimShouldCloseMsgID == msgid) {
1573 } else if (DropFilesMsgID == msgid) {
1574 [self handleDropFiles:data];
1575 } else if (DropStringMsgID == msgid) {
1576 [self handleDropString:data];
1577 } else if (GotFocusMsgID == msgid) {
1579 [self focusChange:YES];
1580 } else if (LostFocusMsgID == msgid) {
1582 [self focusChange:NO];
1583 } else if (SetMouseShapeMsgID == msgid) {
1584 const void *bytes = [data bytes];
1585 int shape = *((int*)bytes); bytes += sizeof(int);
1586 update_mouseshape(shape);
1588 NSLog(@"WARNING: Unknown message received (msgid=%d)", msgid);
1592 + (NSDictionary *)specialKeys
1594 static NSDictionary *specialKeys = nil;
1597 NSBundle *mainBundle = [NSBundle mainBundle];
1598 NSString *path = [mainBundle pathForResource:@"SpecialKeys"
1600 specialKeys = [[NSDictionary alloc] initWithContentsOfFile:path];
1606 - (void)handleInsertText:(NSData *)data
1610 NSString *key = [[NSString alloc] initWithData:data
1611 encoding:NSUTF8StringEncoding];
1612 char_u *str = (char_u*)[key UTF8String];
1613 int i, len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1616 char_u *conv_str = NULL;
1617 if (input_conv.vc_type != CONV_NONE) {
1618 conv_str = string_convert(&input_conv, str, &len);
1624 for (i = 0; i < len; ++i) {
1625 add_to_input_buf(str+i, 1);
1626 if (CSI == str[i]) {
1627 // NOTE: If the converted string contains the byte CSI, then it
1628 // must be followed by the bytes KS_EXTRA, KE_CSI or things
1630 static char_u extra[2] = { KS_EXTRA, KE_CSI };
1631 add_to_input_buf(extra, 2);
1642 - (void)handleKeyDown:(NSString *)key modifiers:(int)mods
1646 char_u *chars = (char_u*)[key UTF8String];
1648 char_u *conv_str = NULL;
1650 int length = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1652 // Special keys (arrow keys, function keys, etc.) are stored in a plist so
1653 // that new keys can easily be added.
1654 NSString *specialString = [[MMBackend specialKeys]
1656 if (specialString && [specialString length] > 1) {
1657 //NSLog(@"special key: %@", specialString);
1658 int ikey = TO_SPECIAL([specialString characterAtIndex:0],
1659 [specialString characterAtIndex:1]);
1661 ikey = simplify_key(ikey, &mods);
1666 special[1] = K_SECOND(ikey);
1667 special[2] = K_THIRD(ikey);
1671 } else if (1 == length && TAB == chars[0]) {
1672 // Tab is a trouble child:
1673 // - <Tab> is added to the input buffer as is
1674 // - <S-Tab> is translated to, {CSI,'k','B'} (i.e. 'Back-tab')
1675 // - <M-Tab> should be 0x80|TAB but this is not valid utf-8 so it needs
1676 // to be converted to utf-8
1677 // - <S-M-Tab> is translated to <S-Tab> with ALT modifier
1678 // - <C-Tab> is reserved by Mac OS X
1679 // - <D-Tab> is reserved by Mac OS X
1684 if (mods & MOD_MASK_SHIFT) {
1685 mods &= ~MOD_MASK_SHIFT;
1687 special[1] = K_SECOND(K_S_TAB);
1688 special[2] = K_THIRD(K_S_TAB);
1690 } else if (mods & MOD_MASK_ALT) {
1691 int mtab = 0x80 | TAB;
1695 special[0] = (mtab >> 6) + 0xc0;
1696 special[1] = mtab & 0xbf;
1704 mods &= ~MOD_MASK_ALT;
1706 } else if (length > 0) {
1707 unichar c = [key characterAtIndex:0];
1709 //NSLog(@"non-special: %@ (hex=%x, mods=%d)", key,
1710 // [key characterAtIndex:0], mods);
1712 if (length == 1 && ((c == Ctrl_C && ctrl_c_interrupts)
1713 || (c == intr_char && intr_char != Ctrl_C))) {
1718 // HACK! In most circumstances the Ctrl and Shift modifiers should be
1719 // cleared since they are already added to the key by the AppKit.
1720 // Unfortunately, the only way to deal with when to clear the modifiers
1721 // or not seems to be to have hard-wired rules like this.
1722 if ( !((' ' == c) || (0xa0 == c) || (mods & MOD_MASK_CMD)
1723 || 0x9 == c || 0xd == c) ) {
1724 mods &= ~MOD_MASK_SHIFT;
1725 mods &= ~MOD_MASK_CTRL;
1726 //NSLog(@"clear shift ctrl");
1729 // HACK! All Option+key presses go via 'insert text' messages, except
1730 // for <M-Space>. If the Alt flag is not cleared for <M-Space> it does
1731 // not work to map to it.
1732 if (0xa0 == c && !(mods & MOD_MASK_CMD)) {
1733 //NSLog(@"clear alt");
1734 mods &= ~MOD_MASK_ALT;
1738 if (input_conv.vc_type != CONV_NONE) {
1739 conv_str = string_convert(&input_conv, chars, &length);
1746 if (chars && length > 0) {
1748 //NSLog(@"adding mods: %d", mods);
1750 modChars[1] = KS_MODIFIER;
1752 add_to_input_buf(modChars, 3);
1755 //NSLog(@"add to input buf: 0x%x", chars[0]);
1756 // TODO: Check for CSI bytes?
1757 add_to_input_buf(chars, length);
1766 - (void)queueMessage:(int)msgid data:(NSData *)data
1768 [outputQueue addObject:[NSData dataWithBytes:&msgid length:sizeof(int)]];
1770 [outputQueue addObject:data];
1772 [outputQueue addObject:[NSData data]];
1775 - (void)connectionDidDie:(NSNotification *)notification
1777 // If the main connection to MacVim is lost this means that MacVim was
1778 // either quit (by the user chosing Quit on the MacVim menu), or it has
1779 // crashed. In either case our only option is to quit now.
1780 // TODO: Write backup file?
1782 //NSLog(@"A Vim process lost its connection to MacVim; quitting.");
1786 - (void)blinkTimerFired:(NSTimer *)timer
1788 NSTimeInterval timeInterval = 0;
1790 [blinkTimer release];
1793 if (MMBlinkStateOn == blinkState) {
1794 gui_undraw_cursor();
1795 blinkState = MMBlinkStateOff;
1796 timeInterval = blinkOffInterval;
1797 } else if (MMBlinkStateOff == blinkState) {
1798 gui_update_cursor(TRUE, FALSE);
1799 blinkState = MMBlinkStateOn;
1800 timeInterval = blinkOnInterval;
1803 if (timeInterval > 0) {
1805 [[NSTimer scheduledTimerWithTimeInterval:timeInterval target:self
1806 selector:@selector(blinkTimerFired:)
1807 userInfo:nil repeats:NO] retain];
1808 [self flushQueue:YES];
1812 - (void)focusChange:(BOOL)on
1814 gui_focus_change(on);
1817 - (void)handleToggleToolbar
1819 // If 'go' contains 'T', then remove it, else add it.
1821 char_u go[sizeof(GO_ALL)+2];
1826 p = vim_strchr(go, GO_TOOLBAR);
1830 char_u *end = go + len;
1836 go[len] = GO_TOOLBAR;
1840 set_option_value((char_u*)"guioptions", 0, go, 0);
1842 // Force screen redraw (does it have to be this complicated?).
1843 redraw_all_later(CLEAR);
1844 update_screen(NOT_VALID);
1847 gui_update_cursor(FALSE, FALSE);
1851 - (void)handleScrollbarEvent:(NSData *)data
1855 const void *bytes = [data bytes];
1856 long ident = *((long*)bytes); bytes += sizeof(long);
1857 int hitPart = *((int*)bytes); bytes += sizeof(int);
1858 float fval = *((float*)bytes); bytes += sizeof(float);
1859 scrollbar_T *sb = gui_find_scrollbar(ident);
1862 scrollbar_T *sb_info = sb->wp ? &sb->wp->w_scrollbars[0] : sb;
1863 long value = sb_info->value;
1864 long size = sb_info->size;
1865 long max = sb_info->max;
1866 BOOL isStillDragging = NO;
1867 BOOL updateKnob = YES;
1870 case NSScrollerDecrementPage:
1871 value -= (size > 2 ? size - 2 : 1);
1873 case NSScrollerIncrementPage:
1874 value += (size > 2 ? size - 2 : 1);
1876 case NSScrollerDecrementLine:
1879 case NSScrollerIncrementLine:
1882 case NSScrollerKnob:
1883 isStillDragging = YES;
1885 case NSScrollerKnobSlot:
1886 value = (long)(fval * (max - size + 1));
1893 //NSLog(@"value %d -> %d", sb_info->value, value);
1894 gui_drag_scrollbar(sb, value, isStillDragging);
1897 // Dragging the knob or option+clicking automatically updates
1898 // the knob position (on the actual NSScroller), so we only
1899 // need to set the knob position in the other cases.
1901 // Update both the left&right vertical scrollbars.
1902 long identLeft = sb->wp->w_scrollbars[SBAR_LEFT].ident;
1903 long identRight = sb->wp->w_scrollbars[SBAR_RIGHT].ident;
1904 [self setScrollbarThumbValue:value size:size max:max
1905 identifier:identLeft];
1906 [self setScrollbarThumbValue:value size:size max:max
1907 identifier:identRight];
1909 // Update the horizontal scrollbar.
1910 [self setScrollbarThumbValue:value size:size max:max
1917 - (void)handleSetFont:(NSData *)data
1921 const void *bytes = [data bytes];
1922 float pointSize = *((float*)bytes); bytes += sizeof(float);
1923 //unsigned len = *((unsigned*)bytes); bytes += sizeof(unsigned);
1924 bytes += sizeof(unsigned); // len not used
1926 NSMutableString *name = [NSMutableString stringWithUTF8String:bytes];
1927 [name appendString:[NSString stringWithFormat:@":h%.2f", pointSize]];
1928 char_u *s = (char_u*)[name UTF8String];
1931 s = CONVERT_FROM_UTF8(s);
1934 set_option_value((char_u*)"guifont", 0, s, 0);
1937 CONVERT_FROM_UTF8_FREE(s);
1940 // Force screen redraw (does it have to be this complicated?).
1941 redraw_all_later(CLEAR);
1942 update_screen(NOT_VALID);
1945 gui_update_cursor(FALSE, FALSE);
1949 - (void)handleDropFiles:(NSData *)data
1954 const void *bytes = [data bytes];
1955 const void *end = [data bytes] + [data length];
1956 int n = *((int*)bytes); bytes += sizeof(int);
1958 if (State & CMDLINE) {
1959 // HACK! If Vim is in command line mode then the files names
1960 // should be added to the command line, instead of opening the
1961 // files in tabs. This is taken care of by gui_handle_drop().
1962 char_u **fnames = (char_u **)alloc(n * sizeof(char_u *));
1965 while (bytes < end && i < n) {
1966 int len = *((int*)bytes); bytes += sizeof(int);
1967 char_u *s = (char_u*)bytes;
1969 s = CONVERT_FROM_UTF8(s);
1971 fnames[i++] = vim_strsave(s);
1973 CONVERT_FROM_UTF8_FREE(s);
1978 // NOTE! This function will free 'fnames'.
1979 // HACK! It is assumed that the 'x' and 'y' arguments are
1980 // unused when in command line mode.
1981 gui_handle_drop(0, 0, 0, fnames, i < n ? i : n);
1984 // HACK! I'm not sure how to get Vim to open a list of files in
1985 // tabs, so instead I create a ':tab drop' command with all the
1986 // files to open and execute it.
1987 NSMutableString *cmd = [NSMutableString stringWithString:@":tab drop"];
1990 for (i = 0; i < n && bytes < end; ++i) {
1991 int len = *((int*)bytes); bytes += sizeof(int);
1992 NSString *file = [NSString stringWithUTF8String:bytes];
1993 file = [file stringByEscapingSpecialFilenameCharacters];
1996 [cmd appendString:@" "];
1997 [cmd appendString:file];
2000 // By going to the last tabpage we ensure that the new tabs will
2001 // appear last (if this call is left out, the taborder becomes
2005 char_u *s = (char_u*)[cmd UTF8String];
2007 s = CONVERT_FROM_UTF8(s);
2011 CONVERT_FROM_UTF8_FREE(s);
2014 // Force screen redraw (does it have to be this complicated?).
2015 // (This code was taken from the end of gui_handle_drop().)
2016 update_screen(NOT_VALID);
2019 gui_update_cursor(FALSE, FALSE);
2026 - (void)handleDropString:(NSData *)data
2031 char_u dropkey[3] = { CSI, KS_EXTRA, (char_u)KE_DROP };
2032 const void *bytes = [data bytes];
2033 int len = *((int*)bytes); bytes += sizeof(int);
2034 NSMutableString *string = [NSMutableString stringWithUTF8String:bytes];
2036 // Replace unrecognized end-of-line sequences with \x0a (line feed).
2037 NSRange range = { 0, [string length] };
2038 unsigned n = [string replaceOccurrencesOfString:@"\x0d\x0a"
2039 withString:@"\x0a" options:0
2042 n = [string replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
2043 options:0 range:range];
2046 len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
2047 char_u *s = (char_u*)[string UTF8String];
2049 if (input_conv.vc_type != CONV_NONE)
2050 s = string_convert(&input_conv, s, &len);
2052 dnd_yank_drag_data(s, len);
2054 if (input_conv.vc_type != CONV_NONE)
2057 add_to_input_buf(dropkey, sizeof(dropkey));
2061 - (BOOL)checkForModifiedBuffers
2064 for (buf = firstbuf; buf != NULL; buf = buf->b_next) {
2065 if (bufIsChanged(buf)) {
2073 - (void)addInput:(NSString *)input
2075 char_u *s = (char_u*)[input UTF8String];
2078 s = CONVERT_FROM_UTF8(s);
2081 server_to_input_buf(s);
2084 CONVERT_FROM_UTF8_FREE(s);
2088 @end // MMBackend (Private)
2093 @implementation MMBackend (ClientServer)
2095 - (NSString *)connectionNameFromServerName:(NSString *)name
2097 NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
2099 return [[NSString stringWithFormat:@"%@.%@", bundleIdentifier, name]
2103 - (NSConnection *)connectionForServerName:(NSString *)name
2105 // TODO: Try 'name%d' if 'name' fails.
2106 NSString *connName = [self connectionNameFromServerName:name];
2107 NSConnection *svrConn = [connectionNameDict objectForKey:connName];
2110 svrConn = [NSConnection connectionWithRegisteredName:connName
2112 // Try alternate server...
2113 if (!svrConn && alternateServerName) {
2114 //NSLog(@" trying to connect to alternate server: %@",
2115 // alternateServerName);
2116 connName = [self connectionNameFromServerName:alternateServerName];
2117 svrConn = [NSConnection connectionWithRegisteredName:connName
2121 // Try looking for alternate servers...
2123 //NSLog(@" looking for alternate servers...");
2124 NSString *alt = [self alternateServerNameForName:name];
2125 if (alt != alternateServerName) {
2126 //NSLog(@" found alternate server: %@", string);
2127 [alternateServerName release];
2128 alternateServerName = [alt copy];
2132 // Try alternate server again...
2133 if (!svrConn && alternateServerName) {
2134 //NSLog(@" trying to connect to alternate server: %@",
2135 // alternateServerName);
2136 connName = [self connectionNameFromServerName:alternateServerName];
2137 svrConn = [NSConnection connectionWithRegisteredName:connName
2142 [connectionNameDict setObject:svrConn forKey:connName];
2144 //NSLog(@"Adding %@ as connection observer for %@", self, svrConn);
2145 [[NSNotificationCenter defaultCenter] addObserver:self
2146 selector:@selector(serverConnectionDidDie:)
2147 name:NSConnectionDidDieNotification object:svrConn];
2154 - (NSConnection *)connectionForServerPort:(int)port
2157 NSEnumerator *e = [connectionNameDict objectEnumerator];
2159 while ((conn = [e nextObject])) {
2160 // HACK! Assume connection uses mach ports.
2161 if (port == [(NSMachPort*)[conn sendPort] machPort])
2168 - (void)serverConnectionDidDie:(NSNotification *)notification
2170 //NSLog(@"%s%@", _cmd, notification);
2172 NSConnection *svrConn = [notification object];
2174 //NSLog(@"Removing %@ as connection observer from %@", self, svrConn);
2175 [[NSNotificationCenter defaultCenter]
2177 name:NSConnectionDidDieNotification
2180 [connectionNameDict removeObjectsForKeys:
2181 [connectionNameDict allKeysForObject:svrConn]];
2183 // HACK! Assume connection uses mach ports.
2184 int port = [(NSMachPort*)[svrConn sendPort] machPort];
2185 NSNumber *key = [NSNumber numberWithInt:port];
2187 [clientProxyDict removeObjectForKey:key];
2188 [serverReplyDict removeObjectForKey:key];
2191 - (void)addClient:(NSDistantObject *)client
2193 NSConnection *conn = [client connectionForProxy];
2194 // HACK! Assume connection uses mach ports.
2195 int port = [(NSMachPort*)[conn sendPort] machPort];
2196 NSNumber *key = [NSNumber numberWithInt:port];
2198 if (![clientProxyDict objectForKey:key]) {
2199 [client setProtocolForProxy:@protocol(MMVimClientProtocol)];
2200 [clientProxyDict setObject:client forKey:key];
2203 // NOTE: 'clientWindow' is a global variable which is used by <client>
2204 clientWindow = port;
2207 - (NSString *)alternateServerNameForName:(NSString *)name
2209 if (!(name && [name length] > 0))
2212 // Only look for alternates if 'name' doesn't end in a digit.
2213 unichar lastChar = [name characterAtIndex:[name length]-1];
2214 if (lastChar >= '0' && lastChar <= '9')
2217 // Look for alternates among all current servers.
2218 NSArray *list = [self serverList];
2219 if (!(list && [list count] > 0))
2222 // Filter out servers starting with 'name' and ending with a number. The
2223 // (?i) pattern ensures that the match is case insensitive.
2224 NSString *pat = [NSString stringWithFormat:@"(?i)%@[0-9]+\\z", name];
2225 NSPredicate *pred = [NSPredicate predicateWithFormat:
2226 @"SELF MATCHES %@", pat];
2227 list = [list filteredArrayUsingPredicate:pred];
2228 if ([list count] > 0) {
2229 list = [list sortedArrayUsingSelector:@selector(serverNameCompare:)];
2230 return [list objectAtIndex:0];
2236 @end // MMBackend (ClientServer)
2241 @implementation NSString (MMServerNameCompare)
2242 - (NSComparisonResult)serverNameCompare:(NSString *)string
2244 return [self compare:string
2245 options:NSCaseInsensitiveSearch|NSNumericSearch];
2252 static int eventModifierFlagsToVimModMask(int modifierFlags)
2256 if (modifierFlags & NSShiftKeyMask)
2257 modMask |= MOD_MASK_SHIFT;
2258 if (modifierFlags & NSControlKeyMask)
2259 modMask |= MOD_MASK_CTRL;
2260 if (modifierFlags & NSAlternateKeyMask)
2261 modMask |= MOD_MASK_ALT;
2262 if (modifierFlags & NSCommandKeyMask)
2263 modMask |= MOD_MASK_CMD;
2268 static int vimModMaskToEventModifierFlags(int mods)
2272 if (mods & MOD_MASK_SHIFT)
2273 flags |= NSShiftKeyMask;
2274 if (mods & MOD_MASK_CTRL)
2275 flags |= NSControlKeyMask;
2276 if (mods & MOD_MASK_ALT)
2277 flags |= NSAlternateKeyMask;
2278 if (mods & MOD_MASK_CMD)
2279 flags |= NSCommandKeyMask;
2284 static int eventModifierFlagsToVimMouseModMask(int modifierFlags)
2288 if (modifierFlags & NSShiftKeyMask)
2289 modMask |= MOUSE_SHIFT;
2290 if (modifierFlags & NSControlKeyMask)
2291 modMask |= MOUSE_CTRL;
2292 if (modifierFlags & NSAlternateKeyMask)
2293 modMask |= MOUSE_ALT;
2298 static int eventButtonNumberToVimMouseButton(int buttonNumber)
2300 static int mouseButton[] = { MOUSE_LEFT, MOUSE_RIGHT, MOUSE_MIDDLE };
2302 return (buttonNumber >= 0 && buttonNumber < 3)
2303 ? mouseButton[buttonNumber] : -1;
2306 static int specialKeyToNSKey(int key)
2308 if (!IS_SPECIAL(key))
2315 { K_UP, NSUpArrowFunctionKey },
2316 { K_DOWN, NSDownArrowFunctionKey },
2317 { K_LEFT, NSLeftArrowFunctionKey },
2318 { K_RIGHT, NSRightArrowFunctionKey },
2319 { K_F1, NSF1FunctionKey },
2320 { K_F2, NSF2FunctionKey },
2321 { K_F3, NSF3FunctionKey },
2322 { K_F4, NSF4FunctionKey },
2323 { K_F5, NSF5FunctionKey },
2324 { K_F6, NSF6FunctionKey },
2325 { K_F7, NSF7FunctionKey },
2326 { K_F8, NSF8FunctionKey },
2327 { K_F9, NSF9FunctionKey },
2328 { K_F10, NSF10FunctionKey },
2329 { K_F11, NSF11FunctionKey },
2330 { K_F12, NSF12FunctionKey },
2331 { K_F13, NSF13FunctionKey },
2332 { K_F14, NSF14FunctionKey },
2333 { K_F15, NSF15FunctionKey },
2334 { K_F16, NSF16FunctionKey },
2335 { K_F17, NSF17FunctionKey },
2336 { K_F18, NSF18FunctionKey },
2337 { K_F19, NSF19FunctionKey },
2338 { K_F20, NSF20FunctionKey },
2339 { K_F21, NSF21FunctionKey },
2340 { K_F22, NSF22FunctionKey },
2341 { K_F23, NSF23FunctionKey },
2342 { K_F24, NSF24FunctionKey },
2343 { K_F25, NSF25FunctionKey },
2344 { K_F26, NSF26FunctionKey },
2345 { K_F27, NSF27FunctionKey },
2346 { K_F28, NSF28FunctionKey },
2347 { K_F29, NSF29FunctionKey },
2348 { K_F30, NSF30FunctionKey },
2349 { K_F31, NSF31FunctionKey },
2350 { K_F32, NSF32FunctionKey },
2351 { K_F33, NSF33FunctionKey },
2352 { K_F34, NSF34FunctionKey },
2353 { K_F35, NSF35FunctionKey },
2354 { K_DEL, NSBackspaceCharacter },
2355 { K_BS, NSDeleteCharacter },
2356 { K_HOME, NSHomeFunctionKey },
2357 { K_END, NSEndFunctionKey },
2358 { K_PAGEUP, NSPageUpFunctionKey },
2359 { K_PAGEDOWN, NSPageDownFunctionKey }
2363 for (i = 0; i < sizeof(sp2ns)/sizeof(sp2ns[0]); ++i) {
2364 if (sp2ns[i].special == key)
2365 return sp2ns[i].nskey;