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.
15 // This constant controls how often the command queue may be flushed. If it is
16 // too small the app might feel unresponsive; if it is too large there might be
17 // long periods without the screen updating (e.g. when sourcing a large session
18 // file). (The unit is seconds.)
19 static float MMFlushTimeoutInterval = 0.1f;
21 static unsigned MMServerMax = 1000;
23 // NOTE: The default font is bundled with the application.
24 static NSString *MMDefaultFontName = @"DejaVu Sans Mono";
25 static float MMDefaultFontSize = 12.0f;
27 // TODO: Move to separate file.
28 static int eventModifierFlagsToVimModMask(int modifierFlags);
29 static int vimModMaskToEventModifierFlags(int mods);
30 static int eventModifierFlagsToVimMouseModMask(int modifierFlags);
31 static int eventButtonNumberToVimMouseButton(int buttonNumber);
32 static int specialKeyToNSKey(int key);
42 @interface NSString (MMServerNameCompare)
43 - (NSComparisonResult)serverNameCompare:(NSString *)string;
48 @interface MMBackend (Private)
49 - (void)handleMessage:(int)msgid data:(NSData *)data;
50 + (NSDictionary *)specialKeys;
51 - (void)handleKeyDown:(NSString *)key modifiers:(int)mods;
52 - (void)queueMessage:(int)msgid data:(NSData *)data;
53 - (void)connectionDidDie:(NSNotification *)notification;
54 - (void)blinkTimerFired:(NSTimer *)timer;
55 - (void)focusChange:(BOOL)on;
56 - (void)processInputBegin;
57 - (void)processInputEnd;
58 - (NSString *)connectionNameFromServerName:(NSString *)name;
59 - (NSConnection *)connectionForServerName:(NSString *)name;
60 - (NSConnection *)connectionForServerPort:(int)port;
61 - (void)serverConnectionDidDie:(NSNotification *)notification;
62 - (void)addClient:(NSDistantObject *)client;
63 - (NSString *)alternateServerNameForName:(NSString *)name;
68 @implementation MMBackend
70 + (MMBackend *)sharedInstance
72 static MMBackend *singleton = nil;
73 return singleton ? singleton : (singleton = [MMBackend new]);
78 if ((self = [super init])) {
79 fontContainerRef = loadFonts();
81 queue = [[NSMutableArray alloc] init];
82 #if MM_USE_INPUT_QUEUE
83 inputQueue = [[NSMutableArray alloc] init];
85 drawData = [[NSMutableData alloc] initWithCapacity:1024];
86 connectionNameDict = [[NSMutableDictionary alloc] init];
87 clientProxyDict = [[NSMutableDictionary alloc] init];
88 serverReplyDict = [[NSMutableDictionary alloc] init];
90 NSString *path = [[NSBundle mainBundle] pathForResource:@"Colors"
93 colorDict = [[NSDictionary dictionaryWithContentsOfFile:path]
96 NSLog(@"WARNING: Could not locate Colors.plist.");
99 path = [[NSBundle mainBundle] pathForResource:@"SystemColors"
102 sysColorDict = [[NSDictionary dictionaryWithContentsOfFile:path]
105 NSLog(@"WARNING: Could not locate SystemColors.plist.");
114 //NSLog(@"%@ %s", [self className], _cmd);
116 [[NSNotificationCenter defaultCenter] removeObserver:self];
118 [blinkTimer release]; blinkTimer = nil;
119 #if MM_USE_INPUT_QUEUE
120 [inputQueue release]; inputQueue = nil;
122 [alternateServerName release]; alternateServerName = nil;
123 [serverReplyDict release]; serverReplyDict = nil;
124 [clientProxyDict release]; clientProxyDict = nil;
125 [connectionNameDict release]; connectionNameDict = nil;
126 [queue release]; queue = nil;
127 [drawData release]; drawData = nil;
128 [frontendProxy release]; frontendProxy = nil;
129 [connection release]; connection = nil;
130 [sysColorDict release]; sysColorDict = nil;
131 [colorDict release]; colorDict = nil;
136 - (void)setBackgroundColor:(int)color
138 backgroundColor = color;
141 - (void)setForegroundColor:(int)color
143 foregroundColor = color;
146 - (void)setSpecialColor:(int)color
148 specialColor = color;
151 - (void)setDefaultColorsBackground:(int)bg foreground:(int)fg
153 defaultBackgroundColor = bg;
154 defaultForegroundColor = fg;
156 NSMutableData *data = [NSMutableData data];
158 [data appendBytes:&bg length:sizeof(int)];
159 [data appendBytes:&fg length:sizeof(int)];
161 [self queueMessage:SetDefaultColorsMsgID data:data];
164 - (NSConnection *)connection
167 // NOTE! If the name of the connection changes here it must also be
168 // updated in MMAppController.m.
169 NSString *name = [NSString stringWithFormat:@"%@-connection",
170 [[NSBundle mainBundle] bundleIdentifier]];
172 connection = [NSConnection connectionWithRegisteredName:name host:nil];
176 // NOTE: 'connection' may be nil here.
182 if (![self connection]) {
183 NSBundle *mainBundle = [NSBundle mainBundle];
185 NSString *path = [mainBundle bundlePath];
186 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
187 NSLog(@"WARNING: Failed to launch GUI with path %@", path);
191 // HACK! It would be preferable to launch the GUI using NSWorkspace,
192 // however I have not managed to figure out how to pass arguments using
195 // NOTE! Using NSTask to launch the GUI has the negative side-effect
196 // that the GUI won't be activated (or raised) so there is a hack in
197 // MMWindowController which always raises the app when a new window is
199 NSMutableArray *args = [NSMutableArray arrayWithObjects:
200 [NSString stringWithFormat:@"-%@", MMNoWindowKey], @"yes", nil];
201 NSString *exeName = [[mainBundle infoDictionary]
202 objectForKey:@"CFBundleExecutable"];
203 NSString *path = [mainBundle pathForAuxiliaryExecutable:exeName];
205 NSLog(@"ERROR: Could not find MacVim executable in bundle");
209 [NSTask launchedTaskWithLaunchPath:path arguments:args];
212 // HACK! The NSWorkspaceDidLaunchApplicationNotification does not work
213 // for tasks like this, so poll the mach bootstrap server until it
214 // returns a valid connection. Also set a time-out date so that we
215 // don't get stuck doing this forever.
216 NSDate *timeOutDate = [NSDate dateWithTimeIntervalSinceNow:15];
217 while (!connection &&
218 NSOrderedDescending == [timeOutDate compare:[NSDate date]])
220 [[NSRunLoop currentRunLoop]
221 runMode:NSDefaultRunLoopMode
222 beforeDate:[NSDate dateWithTimeIntervalSinceNow:1]];
224 // NOTE: This call will set 'connection' as a side-effect.
229 NSLog(@"WARNING: Timed-out waiting for GUI to launch.");
234 id proxy = [connection rootProxy];
235 [proxy setProtocolForProxy:@protocol(MMAppProtocol)];
237 [[NSNotificationCenter defaultCenter] addObserver:self
238 selector:@selector(connectionDidDie:)
239 name:NSConnectionDidDieNotification object:connection];
241 int pid = [[NSProcessInfo processInfo] processIdentifier];
244 frontendProxy = [proxy connectBackend:self pid:pid];
246 @catch (NSException *e) {
247 NSLog(@"Exception caught when trying to connect backend: \"%@\"", e);
251 [frontendProxy retain];
252 [frontendProxy setProtocolForProxy:@protocol(MMAppProtocol)];
255 return connection && frontendProxy;
258 - (BOOL)openVimWindow
260 [self queueMessage:OpenVimWindowMsgID data:nil];
266 int type = ClearAllDrawType;
268 // Any draw commands in queue are effectively obsolete since this clearAll
269 // will negate any effect they have, therefore we may as well clear the
271 [drawData setLength:0];
273 [drawData appendBytes:&type length:sizeof(int)];
275 [drawData appendBytes:&defaultBackgroundColor length:sizeof(int)];
278 - (void)clearBlockFromRow:(int)row1 column:(int)col1
279 toRow:(int)row2 column:(int)col2
281 int type = ClearBlockDrawType;
283 [drawData appendBytes:&type length:sizeof(int)];
285 [drawData appendBytes:&defaultBackgroundColor length:sizeof(int)];
286 [drawData appendBytes:&row1 length:sizeof(int)];
287 [drawData appendBytes:&col1 length:sizeof(int)];
288 [drawData appendBytes:&row2 length:sizeof(int)];
289 [drawData appendBytes:&col2 length:sizeof(int)];
292 - (void)deleteLinesFromRow:(int)row count:(int)count
293 scrollBottom:(int)bottom left:(int)left right:(int)right
295 int type = DeleteLinesDrawType;
297 [drawData appendBytes:&type length:sizeof(int)];
299 [drawData appendBytes:&defaultBackgroundColor length:sizeof(int)];
300 [drawData appendBytes:&row length:sizeof(int)];
301 [drawData appendBytes:&count length:sizeof(int)];
302 [drawData appendBytes:&bottom length:sizeof(int)];
303 [drawData appendBytes:&left length:sizeof(int)];
304 [drawData appendBytes:&right length:sizeof(int)];
307 - (void)replaceString:(char*)s length:(int)len row:(int)row column:(int)col
310 if (len <= 0) return;
312 int type = ReplaceStringDrawType;
314 [drawData appendBytes:&type length:sizeof(int)];
316 [drawData appendBytes:&backgroundColor length:sizeof(int)];
317 [drawData appendBytes:&foregroundColor length:sizeof(int)];
318 [drawData appendBytes:&specialColor length:sizeof(int)];
319 [drawData appendBytes:&row length:sizeof(int)];
320 [drawData appendBytes:&col length:sizeof(int)];
321 [drawData appendBytes:&flags length:sizeof(int)];
322 [drawData appendBytes:&len length:sizeof(int)];
323 [drawData appendBytes:s length:len];
326 - (void)insertLinesFromRow:(int)row count:(int)count
327 scrollBottom:(int)bottom left:(int)left right:(int)right
329 int type = InsertLinesDrawType;
331 [drawData appendBytes:&type length:sizeof(int)];
333 [drawData appendBytes:&defaultBackgroundColor length:sizeof(int)];
334 [drawData appendBytes:&row length:sizeof(int)];
335 [drawData appendBytes:&count length:sizeof(int)];
336 [drawData appendBytes:&bottom length:sizeof(int)];
337 [drawData appendBytes:&left length:sizeof(int)];
338 [drawData appendBytes:&right length:sizeof(int)];
341 - (void)drawCursorAtRow:(int)row column:(int)col shape:(int)shape
342 fraction:(int)percent color:(int)color
344 int type = DrawCursorDrawType;
346 [drawData appendBytes:&type length:sizeof(int)];
348 [drawData appendBytes:&color length:sizeof(int)];
349 [drawData appendBytes:&row length:sizeof(int)];
350 [drawData appendBytes:&col length:sizeof(int)];
351 [drawData appendBytes:&shape length:sizeof(int)];
352 [drawData appendBytes:&percent length:sizeof(int)];
355 - (void)flushQueue:(BOOL)force
357 // NOTE! This method gets called a lot; if we were to flush every time it
358 // was called MacVim would feel unresponsive. So there is a time out which
359 // ensures that the queue isn't flushed too often.
360 if (!force && lastFlushDate && -[lastFlushDate timeIntervalSinceNow]
361 < MMFlushTimeoutInterval)
364 if ([drawData length] > 0) {
365 [self queueMessage:BatchDrawMsgID data:[drawData copy]];
366 [drawData setLength:0];
369 if ([queue count] > 0) {
371 [frontendProxy processCommandQueue:queue];
373 @catch (NSException *e) {
374 NSLog(@"Exception caught when processing command queue: \"%@\"", e);
377 [queue removeAllObjects];
379 [lastFlushDate release];
380 lastFlushDate = [[NSDate date] retain];
384 - (BOOL)waitForInput:(int)milliseconds
386 NSDate *date = milliseconds > 0 ?
387 [NSDate dateWithTimeIntervalSinceNow:.001*milliseconds] :
388 [NSDate distantFuture];
390 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:date];
392 // I know of no way to figure out if the run loop exited because input was
393 // found or because of a time out, so I need to manually indicate when
394 // input was received in processInput:data: and then reset it every time
396 BOOL yn = inputReceived;
404 #ifdef MAC_CLIENTSERVER
405 // The default connection is used for the client/server code.
406 [[NSConnection defaultConnection] setRootObject:nil];
407 [[NSConnection defaultConnection] invalidate];
410 // By invalidating the NSConnection the MMWindowController immediately
411 // finds out that the connection is down and as a result
412 // [MMWindowController connectionDidDie:] is invoked.
413 //NSLog(@"%@ %s", [self className], _cmd);
414 [[NSNotificationCenter defaultCenter] removeObserver:self];
415 [connection invalidate];
417 if (fontContainerRef) {
418 ATSFontDeactivate(fontContainerRef, NULL, kATSOptionFlagsDefault);
419 fontContainerRef = 0;
424 - (void)selectTab:(int)index
426 //NSLog(@"%s%d", _cmd, index);
429 NSData *data = [NSData dataWithBytes:&index length:sizeof(int)];
430 [self queueMessage:SelectTabMsgID data:data];
435 //NSLog(@"%s", _cmd);
437 NSMutableData *data = [NSMutableData data];
439 int idx = tabpage_index(curtab) - 1;
440 [data appendBytes:&idx length:sizeof(int)];
443 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next) {
444 // This function puts the label of the tab in the global 'NameBuff'.
445 get_tabline_label(tp, FALSE);
446 int len = strlen((char*)NameBuff);
447 if (len <= 0) continue;
449 // Count the number of windows in the tabpage.
450 //win_T *wp = tp->tp_firstwin;
452 //for (wincount = 0; wp != NULL; wp = wp->w_next, ++wincount);
454 //[data appendBytes:&wincount length:sizeof(int)];
455 [data appendBytes:&len length:sizeof(int)];
456 [data appendBytes:NameBuff length:len];
459 [self queueMessage:UpdateTabBarMsgID data:data];
462 - (BOOL)tabBarVisible
464 return tabBarVisible;
467 - (void)showTabBar:(BOOL)enable
469 tabBarVisible = enable;
471 int msgid = enable ? ShowTabBarMsgID : HideTabBarMsgID;
472 [self queueMessage:msgid data:nil];
475 - (void)setRows:(int)rows columns:(int)cols
477 //NSLog(@"[VimTask] setRows:%d columns:%d", rows, cols);
479 int dim[] = { rows, cols };
480 NSData *data = [NSData dataWithBytes:&dim length:2*sizeof(int)];
482 [self queueMessage:SetTextDimensionsMsgID data:data];
485 - (void)setVimWindowTitle:(char *)title
487 NSMutableData *data = [NSMutableData data];
488 int len = strlen(title);
489 if (len <= 0) return;
491 [data appendBytes:&len length:sizeof(int)];
492 [data appendBytes:title length:len];
494 [self queueMessage:SetVimWindowTitleMsgID data:data];
497 - (char *)browseForFileInDirectory:(char *)dir title:(char *)title
500 //NSLog(@"browseForFileInDirectory:%s title:%s saving:%d", dir, title,
505 ? [NSString stringWithCString:dir encoding:NSUTF8StringEncoding]
508 ? [NSString stringWithCString:title encoding:NSUTF8StringEncoding]
511 [frontendProxy showSavePanelForDirectory:ds title:ts saving:saving];
513 // Wait until a reply is sent from MMVimController.
514 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
515 beforeDate:[NSDate distantFuture]];
517 if (dialogReturn && [dialogReturn isKindOfClass:[NSString class]]) {
518 s = vim_strsave((char_u*)[dialogReturn UTF8String]);
521 [dialogReturn release]; dialogReturn = nil;
523 @catch (NSException *e) {
524 NSLog(@"Exception caught when showing save panel: \"%@\"", e);
530 - (oneway void)setDialogReturn:(in bycopy id)obj
532 // NOTE: This is called by
533 // - [MMVimController panelDidEnd:::], and
534 // - [MMVimController alertDidEnd:::],
535 // to indicate that a save/open panel or alert has finished.
537 if (obj != dialogReturn) {
538 [dialogReturn release];
539 dialogReturn = [obj retain];
543 - (int)presentDialogWithType:(int)type title:(char *)title message:(char *)msg
544 buttons:(char *)btns textField:(char *)txtfield
547 NSString *message = nil, *text = nil, *textFieldString = nil;
548 NSArray *buttons = nil;
549 int style = NSInformationalAlertStyle;
551 if (VIM_WARNING == type) style = NSWarningAlertStyle;
552 else if (VIM_ERROR == type) style = NSCriticalAlertStyle;
555 NSString *btnString = [NSString stringWithUTF8String:btns];
556 buttons = [btnString componentsSeparatedByString:@"\n"];
559 message = [NSString stringWithUTF8String:title];
561 text = [NSString stringWithUTF8String:msg];
563 // HACK! If there is a '\n\n' or '\n' sequence in the message, then
564 // make the part up to there into the title. We only do this
565 // because Vim has lots of dialogs without a title and they look
567 // TODO: Fix the actual dialog texts.
568 NSRange eolRange = [text rangeOfString:@"\n\n"];
569 if (NSNotFound == eolRange.location)
570 eolRange = [text rangeOfString:@"\n"];
571 if (NSNotFound != eolRange.location) {
572 message = [text substringToIndex:eolRange.location];
573 text = [text substringFromIndex:NSMaxRange(eolRange)];
578 textFieldString = [NSString stringWithUTF8String:txtfield];
581 [frontendProxy presentDialogWithStyle:style message:message
582 informativeText:text buttonTitles:buttons
583 textFieldString:textFieldString];
585 // Wait until a reply is sent from MMVimController.
586 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
587 beforeDate:[NSDate distantFuture]];
589 if (dialogReturn && [dialogReturn isKindOfClass:[NSArray class]]
590 && [dialogReturn count]) {
591 retval = [[dialogReturn objectAtIndex:0] intValue];
592 if (txtfield && [dialogReturn count] > 1) {
593 NSString *retString = [dialogReturn objectAtIndex:1];
594 vim_strncpy((char_u*)txtfield, (char_u*)[retString UTF8String],
599 [dialogReturn release]; dialogReturn = nil;
601 @catch (NSException *e) {
602 NSLog(@"Exception caught while showing alert dialog: \"%@\"", e);
608 - (void)addMenuWithTag:(int)tag parent:(int)parentTag name:(char *)name
611 //NSLog(@"addMenuWithTag:%d parent:%d name:%s atIndex:%d", tag, parentTag,
614 int namelen = name ? strlen(name) : 0;
615 NSMutableData *data = [NSMutableData data];
617 [data appendBytes:&tag length:sizeof(int)];
618 [data appendBytes:&parentTag length:sizeof(int)];
619 [data appendBytes:&namelen length:sizeof(int)];
620 if (namelen > 0) [data appendBytes:name length:namelen];
621 [data appendBytes:&index length:sizeof(int)];
623 [self queueMessage:AddMenuMsgID data:data];
626 - (void)addMenuItemWithTag:(int)tag parent:(int)parentTag name:(char *)name
627 tip:(char *)tip icon:(char *)icon
628 keyEquivalent:(int)key modifiers:(int)mods
629 action:(NSString *)action atIndex:(int)index
631 //NSLog(@"addMenuItemWithTag:%d parent:%d name:%s tip:%s atIndex:%d", tag,
632 // parentTag, name, tip, index);
634 int namelen = name ? strlen(name) : 0;
635 int tiplen = tip ? strlen(tip) : 0;
636 int iconlen = icon ? strlen(icon) : 0;
637 int eventFlags = vimModMaskToEventModifierFlags(mods);
638 int actionlen = [action lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
639 NSMutableData *data = [NSMutableData data];
641 key = specialKeyToNSKey(key);
643 [data appendBytes:&tag length:sizeof(int)];
644 [data appendBytes:&parentTag length:sizeof(int)];
645 [data appendBytes:&namelen length:sizeof(int)];
646 if (namelen > 0) [data appendBytes:name length:namelen];
647 [data appendBytes:&tiplen length:sizeof(int)];
648 if (tiplen > 0) [data appendBytes:tip length:tiplen];
649 [data appendBytes:&iconlen length:sizeof(int)];
650 if (iconlen > 0) [data appendBytes:icon length:iconlen];
651 [data appendBytes:&actionlen length:sizeof(int)];
652 if (actionlen > 0) [data appendBytes:[action UTF8String] length:actionlen];
653 [data appendBytes:&index length:sizeof(int)];
654 [data appendBytes:&key length:sizeof(int)];
655 [data appendBytes:&eventFlags length:sizeof(int)];
657 [self queueMessage:AddMenuItemMsgID data:data];
660 - (void)removeMenuItemWithTag:(int)tag
662 NSMutableData *data = [NSMutableData data];
663 [data appendBytes:&tag length:sizeof(int)];
665 [self queueMessage:RemoveMenuItemMsgID data:data];
668 - (void)enableMenuItemWithTag:(int)tag state:(int)enabled
670 NSMutableData *data = [NSMutableData data];
672 [data appendBytes:&tag length:sizeof(int)];
673 [data appendBytes:&enabled length:sizeof(int)];
675 [self queueMessage:EnableMenuItemMsgID data:data];
678 - (void)showPopupMenuWithName:(char *)name atMouseLocation:(BOOL)mouse
680 int len = strlen(name);
681 int row = -1, col = -1;
683 if (len <= 0) return;
685 if (!mouse && curwin) {
686 row = curwin->w_wrow;
687 col = curwin->w_wcol;
690 NSMutableData *data = [NSMutableData data];
692 [data appendBytes:&row length:sizeof(int)];
693 [data appendBytes:&col length:sizeof(int)];
694 [data appendBytes:&len length:sizeof(int)];
695 [data appendBytes:name length:len];
697 [self queueMessage:ShowPopupMenuMsgID data:data];
700 - (void)showToolbar:(int)enable flags:(int)flags
702 NSMutableData *data = [NSMutableData data];
704 [data appendBytes:&enable length:sizeof(int)];
705 [data appendBytes:&flags length:sizeof(int)];
707 [self queueMessage:ShowToolbarMsgID data:data];
710 - (void)createScrollbarWithIdentifier:(long)ident type:(int)type
712 NSMutableData *data = [NSMutableData data];
714 [data appendBytes:&ident length:sizeof(long)];
715 [data appendBytes:&type length:sizeof(int)];
717 [self queueMessage:CreateScrollbarMsgID data:data];
720 - (void)destroyScrollbarWithIdentifier:(long)ident
722 NSMutableData *data = [NSMutableData data];
723 [data appendBytes:&ident length:sizeof(long)];
725 [self queueMessage:DestroyScrollbarMsgID data:data];
728 - (void)showScrollbarWithIdentifier:(long)ident state:(int)visible
730 NSMutableData *data = [NSMutableData data];
732 [data appendBytes:&ident length:sizeof(long)];
733 [data appendBytes:&visible length:sizeof(int)];
735 [self queueMessage:ShowScrollbarMsgID data:data];
738 - (void)setScrollbarPosition:(int)pos length:(int)len identifier:(long)ident
740 NSMutableData *data = [NSMutableData data];
742 [data appendBytes:&ident length:sizeof(long)];
743 [data appendBytes:&pos length:sizeof(int)];
744 [data appendBytes:&len length:sizeof(int)];
746 [self queueMessage:SetScrollbarPositionMsgID data:data];
749 - (void)setScrollbarThumbValue:(long)val size:(long)size max:(long)max
750 identifier:(long)ident
752 float fval = max-size+1 > 0 ? (float)val/(max-size+1) : 0;
753 float prop = (float)size/(max+1);
754 if (fval < 0) fval = 0;
755 else if (fval > 1.0f) fval = 1.0f;
756 if (prop < 0) prop = 0;
757 else if (prop > 1.0f) prop = 1.0f;
759 NSMutableData *data = [NSMutableData data];
761 [data appendBytes:&ident length:sizeof(long)];
762 [data appendBytes:&fval length:sizeof(float)];
763 [data appendBytes:&prop length:sizeof(float)];
765 [self queueMessage:SetScrollbarThumbMsgID data:data];
768 - (BOOL)setFontWithName:(char *)name
770 NSString *fontName = MMDefaultFontName;
771 float size = MMDefaultFontSize;
772 BOOL parseFailed = NO;
775 fontName = [[[NSString alloc] initWithCString:name
776 encoding:NSUTF8StringEncoding] autorelease];
778 if ([fontName isEqual:@"*"]) {
779 // :set gfn=* shows the font panel.
780 do_cmdline_cmd((char_u*)":action orderFrontFontPanel:");
784 NSArray *components = [fontName componentsSeparatedByString:@":"];
785 if ([components count] == 2) {
786 NSString *sizeString = [components lastObject];
787 if ([sizeString length] > 0
788 && [sizeString characterAtIndex:0] == 'h') {
789 sizeString = [sizeString substringFromIndex:1];
790 if ([sizeString length] > 0) {
791 size = [sizeString floatValue];
792 fontName = [components objectAtIndex:0];
797 } else if ([components count] > 2) {
802 if (!parseFailed && [fontName length] > 0) {
803 if (size < 6 || size > 100) {
804 // Font size 0.0 tells NSFont to use the 'user default size'.
808 NSFont *font = [NSFont fontWithName:fontName size:size];
810 if (!font && MMDefaultFontName == fontName) {
811 // If for some reason the MacVim default font is not in the app
812 // bundle, then fall back on the system default font.
814 font = [NSFont userFixedPitchFontOfSize:size];
815 fontName = [font displayName];
819 //NSLog(@"Setting font '%@' of size %.2f", fontName, size);
821 lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
823 NSMutableData *data = [NSMutableData data];
825 [data appendBytes:&size length:sizeof(float)];
826 [data appendBytes:&len length:sizeof(int)];
827 [data appendBytes:[fontName UTF8String] length:len];
829 [self queueMessage:SetFontMsgID data:data];
835 //NSLog(@"WARNING: Cannot set font with name '%@' of size %.2f",
840 - (void)executeActionWithName:(NSString *)name
842 int len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
845 NSMutableData *data = [NSMutableData data];
847 [data appendBytes:&len length:sizeof(int)];
848 [data appendBytes:[name UTF8String] length:len];
850 [self queueMessage:ExecuteActionMsgID data:data];
854 - (void)setMouseShape:(int)shape
856 NSMutableData *data = [NSMutableData data];
857 [data appendBytes:&shape length:sizeof(int)];
858 [self queueMessage:SetMouseShapeMsgID data:data];
861 - (void)setBlinkWait:(int)wait on:(int)on off:(int)off
863 // Vim specifies times in milliseconds, whereas Cocoa wants them in
865 blinkWaitInterval = .001f*wait;
866 blinkOnInterval = .001f*on;
867 blinkOffInterval = .001f*off;
873 [blinkTimer invalidate];
874 [blinkTimer release];
878 if (blinkWaitInterval > 0 && blinkOnInterval > 0 && blinkOffInterval > 0
880 blinkState = MMBlinkStateOn;
882 [[NSTimer scheduledTimerWithTimeInterval:blinkWaitInterval
884 selector:@selector(blinkTimerFired:)
885 userInfo:nil repeats:NO] retain];
886 gui_update_cursor(TRUE, FALSE);
887 [self flushQueue:YES];
893 if (MMBlinkStateOff == blinkState) {
894 gui_update_cursor(TRUE, FALSE);
895 [self flushQueue:YES];
898 blinkState = MMBlinkStateNone;
901 - (void)adjustLinespace:(int)linespace
903 NSMutableData *data = [NSMutableData data];
904 [data appendBytes:&linespace length:sizeof(int)];
905 [self queueMessage:AdjustLinespaceMsgID data:data];
910 [self queueMessage:ActivateMsgID data:nil];
913 - (void)setServerName:(NSString *)name
915 NSData *data = [name dataUsingEncoding:NSUTF8StringEncoding];
916 [self queueMessage:SetServerNameMsgID data:data];
919 - (int)lookupColorWithKey:(NSString *)key
921 if (!(key && [key length] > 0))
924 NSString *stripKey = [[[[key lowercaseString]
925 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
926 componentsSeparatedByString:@" "]
927 componentsJoinedByString:@""];
929 if (stripKey && [stripKey length] > 0) {
930 // First of all try to lookup key in the color dictionary; note that
931 // all keys in this dictionary are lowercase with no whitespace.
932 id obj = [colorDict objectForKey:stripKey];
933 if (obj) return [obj intValue];
935 // The key was not in the dictionary; is it perhaps of the form
937 if ([stripKey length] > 1 && [stripKey characterAtIndex:0] == '#') {
938 NSScanner *scanner = [NSScanner scannerWithString:stripKey];
939 [scanner setScanLocation:1];
941 if ([scanner scanHexInt:&hex]) {
946 // As a last resort, check if it is one of the system defined colors.
947 // The keys in this dictionary are also lowercase with no whitespace.
948 obj = [sysColorDict objectForKey:stripKey];
950 NSColor *col = [NSColor performSelector:NSSelectorFromString(obj)];
953 col = [col colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
954 [col getRed:&r green:&g blue:&b alpha:&a];
955 return (((int)(r*255+.5f) & 0xff) << 16)
956 + (((int)(g*255+.5f) & 0xff) << 8)
957 + ((int)(b*255+.5f) & 0xff);
962 NSLog(@"WARNING: No color with key %@ found.", stripKey);
966 - (BOOL)hasSpecialKeyWithValue:(NSString *)value
968 NSEnumerator *e = [[MMBackend specialKeys] objectEnumerator];
971 while ((obj = [e nextObject])) {
972 if ([value isEqual:obj])
979 - (oneway void)processInput:(int)msgid data:(in NSData *)data
981 // NOTE: This method might get called whenever the run loop is tended to.
982 // Thus it might get called whilst input is being processed. Normally this
983 // is not a problem, but if it gets called often then it might become
984 // dangerous. E.g. when a focus messages is received the screen is redrawn
985 // because the selection color changes and if another focus message is
986 // received whilst the first one is being processed Vim might crash. To
987 // deal with this problem at the moment, we simply drop messages that are
988 // received while other input is being processed.
989 if (inProcessInput) {
990 #if MM_USE_INPUT_QUEUE
991 [inputQueue addObject:[NSNumber numberWithInt:msgid]];
992 [inputQueue addObject:data];
994 // Just drop the input
995 //NSLog(@"WARNING: Dropping input in %s", _cmd);
998 [self processInputBegin];
999 [self handleMessage:msgid data:data];
1000 [self processInputEnd];
1004 - (oneway void)processInputAndData:(in NSArray *)messages
1006 // NOTE: See comment in processInput:data:.
1007 unsigned i, count = [messages count];
1009 NSLog(@"WARNING: [messages count] is odd in %s", _cmd);
1013 if (inProcessInput) {
1014 #if MM_USE_INPUT_QUEUE
1015 [inputQueue addObjectsFromArray:messages];
1017 // Just drop the input
1018 //NSLog(@"WARNING: Dropping input in %s", _cmd);
1021 [self processInputBegin];
1023 for (i = 0; i < count; i += 2) {
1024 int msgid = [[messages objectAtIndex:i] intValue];
1025 id data = [messages objectAtIndex:i+1];
1026 if ([data isEqual:[NSNull null]])
1029 [self handleMessage:msgid data:data];
1032 [self processInputEnd];
1036 - (BOOL)checkForModifiedBuffers
1039 for (buf = firstbuf; buf != NULL; buf = buf->b_next) {
1040 if (bufIsChanged(buf)) {
1048 - (BOOL)starRegisterToPasteboard:(byref NSPasteboard *)pboard
1050 if (VIsual_active && (State & NORMAL) && clip_star.available) {
1051 // If there is no pasteboard, return YES to indicate that there is text
1056 clip_copy_selection();
1058 // Get the text to put on the pasteboard.
1059 long_u len = 0; char_u *str = 0;
1060 int type = clip_convert_selection(&str, &len, &clip_star);
1064 NSString *string = [[NSString alloc]
1065 initWithBytes:str length:len encoding:NSUTF8StringEncoding];
1067 NSArray *types = [NSArray arrayWithObject:NSStringPboardType];
1068 [pboard declareTypes:types owner:nil];
1069 BOOL ok = [pboard setString:string forType:NSStringPboardType];
1080 - (oneway void)addReply:(in bycopy NSString *)reply
1081 server:(in byref id <MMVimServerProtocol>)server
1083 //NSLog(@"addReply:%@ server:%@", reply, (id)server);
1085 // Replies might come at any time and in any order so we keep them in an
1086 // array inside a dictionary with the send port used as key.
1088 NSConnection *conn = [(NSDistantObject*)server connectionForProxy];
1089 // HACK! Assume connection uses mach ports.
1090 int port = [(NSMachPort*)[conn sendPort] machPort];
1091 NSNumber *key = [NSNumber numberWithInt:port];
1093 NSMutableArray *replies = [serverReplyDict objectForKey:key];
1095 replies = [NSMutableArray array];
1096 [serverReplyDict setObject:replies forKey:key];
1099 [replies addObject:reply];
1102 - (void)addInput:(in bycopy NSString *)input
1103 client:(in byref id <MMVimClientProtocol>)client
1105 //NSLog(@"addInput:%@ client:%@", input, (id)client);
1107 server_to_input_buf((char_u*)[input UTF8String]);
1109 [self addClient:(id)client];
1111 inputReceived = YES;
1114 - (NSString *)evaluateExpression:(in bycopy NSString *)expr
1115 client:(in byref id <MMVimClientProtocol>)client
1117 //NSLog(@"evaluateExpression:%@ client:%@", expr, (id)client);
1119 NSString *eval = nil;
1120 char_u *res = eval_client_expr_to_string((char_u*)[expr UTF8String]);
1123 eval = [NSString stringWithUTF8String:(char*)res];
1127 [self addClient:(id)client];
1132 - (void)registerServerWithName:(NSString *)name
1134 NSString *svrName = name;
1135 NSConnection *svrConn = [NSConnection defaultConnection];
1138 for (i = 0; i < MMServerMax; ++i) {
1139 NSString *connName = [self connectionNameFromServerName:svrName];
1141 if ([svrConn registerName:connName]) {
1142 //NSLog(@"Registered server with name: %@", svrName);
1144 // TODO: Set request/reply time-outs to something else?
1146 // Don't wait for requests (time-out means that the message is
1148 [svrConn setRequestTimeout:0];
1149 //[svrConn setReplyTimeout:MMReplyTimeout];
1150 [svrConn setRootObject:self];
1152 // NOTE: 'serverName' is a global variable
1153 serverName = vim_strsave((char_u*)[svrName UTF8String]);
1155 set_vim_var_string(VV_SEND_SERVER, serverName, -1);
1158 need_maketitle = TRUE;
1160 [self queueMessage:SetServerNameMsgID data:
1161 [svrName dataUsingEncoding:NSUTF8StringEncoding]];
1165 svrName = [NSString stringWithFormat:@"%@%d", name, i+1];
1169 - (BOOL)sendToServer:(NSString *)name string:(NSString *)string
1170 reply:(char_u **)reply port:(int *)port expression:(BOOL)expr
1173 // NOTE: If 'name' equals 'serverName' then the request is local (client
1174 // and server are the same). This case is not handled separately, so a
1175 // connection will be set up anyway (this simplifies the code).
1177 NSConnection *conn = [self connectionForServerName:name];
1180 EMSG2(_(e_noserver), [name UTF8String]);
1185 // HACK! Assume connection uses mach ports.
1186 *port = [(NSMachPort*)[conn sendPort] machPort];
1189 id proxy = [conn rootProxy];
1190 [proxy setProtocolForProxy:@protocol(MMVimServerProtocol)];
1194 NSString *eval = [proxy evaluateExpression:string client:self];
1196 *reply = (eval ? vim_strsave((char_u*)[eval UTF8String])
1197 : vim_strsave((char_u*)_(e_invexprmsg)));
1203 [proxy addInput:string client:self];
1206 @catch (NSException *e) {
1207 NSLog(@"WARNING: Caught exception in %s: \"%@\"", _cmd, e);
1214 - (NSArray *)serverList
1216 NSArray *list = nil;
1218 if ([self connection]) {
1219 id proxy = [connection rootProxy];
1220 [proxy setProtocolForProxy:@protocol(MMAppProtocol)];
1223 list = [proxy serverList];
1225 @catch (NSException *e) {
1226 NSLog(@"Exception caught when listing servers: \"%@\"", e);
1229 EMSG(_("E???: No connection to MacVim, server listing not possible."));
1235 - (NSString *)peekForReplyOnPort:(int)port
1237 //NSLog(@"%s%d", _cmd, port);
1239 NSNumber *key = [NSNumber numberWithInt:port];
1240 NSMutableArray *replies = [serverReplyDict objectForKey:key];
1241 if (replies && [replies count]) {
1242 //NSLog(@" %d replies, topmost is: %@", [replies count],
1243 // [replies objectAtIndex:0]);
1244 return [replies objectAtIndex:0];
1247 //NSLog(@" No replies");
1251 - (NSString *)waitForReplyOnPort:(int)port
1253 //NSLog(@"%s%d", _cmd, port);
1255 NSConnection *conn = [self connectionForServerPort:port];
1259 NSNumber *key = [NSNumber numberWithInt:port];
1260 NSMutableArray *replies = nil;
1261 NSString *reply = nil;
1263 // Wait for reply as long as the connection to the server is valid (unless
1264 // user interrupts wait with Ctrl-C).
1265 while (!got_int && [conn isValid] &&
1266 !(replies = [serverReplyDict objectForKey:key])) {
1267 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
1268 beforeDate:[NSDate distantFuture]];
1272 if ([replies count] > 0) {
1273 reply = [[replies objectAtIndex:0] retain];
1274 //NSLog(@" Got reply: %@", reply);
1275 [replies removeObjectAtIndex:0];
1276 [reply autorelease];
1279 if ([replies count] == 0)
1280 [serverReplyDict removeObjectForKey:key];
1286 - (BOOL)sendReply:(NSString *)reply toPort:(int)port
1288 id client = [clientProxyDict objectForKey:[NSNumber numberWithInt:port]];
1291 //NSLog(@"sendReply:%@ toPort:%d", reply, port);
1292 [client addReply:reply server:self];
1295 @catch (NSException *e) {
1296 NSLog(@"WARNING: Exception caught in %s: \"%@\"", _cmd, e);
1299 EMSG2(_("E???: server2client failed; no client with id 0x%x"), port);
1309 @implementation MMBackend (Private)
1311 - (void)handleMessage:(int)msgid data:(NSData *)data
1313 if (InsertTextMsgID == msgid) {
1315 NSString *key = [[NSString alloc] initWithData:data
1316 encoding:NSUTF8StringEncoding];
1317 char_u *str = (char_u*)[key UTF8String];
1318 int i, len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1321 char_u *conv_str = NULL;
1322 if (input_conv.vc_type != CONV_NONE) {
1323 conv_str = string_convert(&input_conv, str, &len);
1329 for (i = 0; i < len; ++i) {
1330 add_to_input_buf(str+i, 1);
1331 if (CSI == str[i]) {
1332 // NOTE: If the converted string contains the byte CSI, then it
1333 // must be followed by the bytes KS_EXTRA, KE_CSI or things
1335 static char_u extra[2] = { KS_EXTRA, KE_CSI };
1336 add_to_input_buf(extra, 2);
1345 } else if (KeyDownMsgID == msgid || CmdKeyMsgID == msgid) {
1347 const void *bytes = [data bytes];
1348 int mods = *((int*)bytes); bytes += sizeof(int);
1349 int len = *((int*)bytes); bytes += sizeof(int);
1350 NSString *key = [[NSString alloc] initWithBytes:bytes length:len
1351 encoding:NSUTF8StringEncoding];
1352 mods = eventModifierFlagsToVimModMask(mods);
1354 [self handleKeyDown:key modifiers:mods];
1357 } else if (SelectTabMsgID == msgid) {
1359 const void *bytes = [data bytes];
1360 int idx = *((int*)bytes) + 1;
1361 //NSLog(@"Selecting tab %d", idx);
1362 send_tabline_event(idx);
1363 } else if (CloseTabMsgID == msgid) {
1365 const void *bytes = [data bytes];
1366 int idx = *((int*)bytes) + 1;
1367 //NSLog(@"Closing tab %d", idx);
1368 send_tabline_menu_event(idx, TABLINE_MENU_CLOSE);
1369 } else if (AddNewTabMsgID == msgid) {
1370 //NSLog(@"Adding new tab");
1371 send_tabline_menu_event(0, TABLINE_MENU_NEW);
1372 } else if (DraggedTabMsgID == msgid) {
1374 const void *bytes = [data bytes];
1375 // NOTE! The destination index is 0 based, so do not add 1 to make it 1
1377 int idx = *((int*)bytes);
1380 } else if (ScrollWheelMsgID == msgid) {
1382 const void *bytes = [data bytes];
1384 int row = *((int*)bytes); bytes += sizeof(int);
1385 int col = *((int*)bytes); bytes += sizeof(int);
1386 int flags = *((int*)bytes); bytes += sizeof(int);
1387 float dy = *((float*)bytes); bytes += sizeof(float);
1389 int button = MOUSE_5;
1390 if (dy > 0) button = MOUSE_4;
1392 flags = eventModifierFlagsToVimMouseModMask(flags);
1394 gui_send_mouse_event(button, col, row, NO, flags);
1395 } else if (MouseDownMsgID == msgid) {
1397 const void *bytes = [data bytes];
1399 int row = *((int*)bytes); bytes += sizeof(int);
1400 int col = *((int*)bytes); bytes += sizeof(int);
1401 int button = *((int*)bytes); bytes += sizeof(int);
1402 int flags = *((int*)bytes); bytes += sizeof(int);
1403 int count = *((int*)bytes); bytes += sizeof(int);
1405 button = eventButtonNumberToVimMouseButton(button);
1406 flags = eventModifierFlagsToVimMouseModMask(flags);
1408 gui_send_mouse_event(button, col, row, count>1, flags);
1409 } else if (MouseUpMsgID == msgid) {
1411 const void *bytes = [data bytes];
1413 int row = *((int*)bytes); bytes += sizeof(int);
1414 int col = *((int*)bytes); bytes += sizeof(int);
1415 int flags = *((int*)bytes); bytes += sizeof(int);
1417 flags = eventModifierFlagsToVimMouseModMask(flags);
1419 gui_send_mouse_event(MOUSE_RELEASE, col, row, NO, flags);
1420 } else if (MouseDraggedMsgID == msgid) {
1422 const void *bytes = [data bytes];
1424 int row = *((int*)bytes); bytes += sizeof(int);
1425 int col = *((int*)bytes); bytes += sizeof(int);
1426 int flags = *((int*)bytes); bytes += sizeof(int);
1428 flags = eventModifierFlagsToVimMouseModMask(flags);
1430 gui_send_mouse_event(MOUSE_DRAG, col, row, NO, flags);
1431 } else if (SetTextDimensionsMsgID == msgid) {
1433 const void *bytes = [data bytes];
1434 int rows = *((int*)bytes); bytes += sizeof(int);
1435 int cols = *((int*)bytes); bytes += sizeof(int);
1437 // NOTE! Vim doesn't call gui_mch_set_shellsize() after
1438 // gui_resize_shell(), so we have to manually set the rows and columns
1439 // here. (MacVim doesn't change the rows and columns to avoid
1440 // inconsistent states between Vim and MacVim.)
1441 [self setRows:rows columns:cols];
1443 //NSLog(@"[VimTask] Resizing shell to %dx%d.", cols, rows);
1444 gui_resize_shell(cols, rows);
1445 } else if (ExecuteMenuMsgID == msgid) {
1447 const void *bytes = [data bytes];
1448 int tag = *((int*)bytes); bytes += sizeof(int);
1450 vimmenu_T *menu = (vimmenu_T*)tag;
1451 // TODO! Make sure 'menu' is a valid menu pointer!
1455 } else if (ToggleToolbarMsgID == msgid) {
1456 char_u go[sizeof(GO_ALL)+2];
1461 p = vim_strchr(go, GO_TOOLBAR);
1465 char_u *end = go + len;
1471 go[len] = GO_TOOLBAR;
1475 set_option_value((char_u*)"guioptions", 0, go, 0);
1477 // Force screen redraw (does it have to be this complicated?).
1478 redraw_all_later(CLEAR);
1479 update_screen(NOT_VALID);
1482 gui_update_cursor(FALSE, FALSE);
1484 } else if (ScrollbarEventMsgID == msgid) {
1486 const void *bytes = [data bytes];
1487 long ident = *((long*)bytes); bytes += sizeof(long);
1488 int hitPart = *((int*)bytes); bytes += sizeof(int);
1489 float fval = *((float*)bytes); bytes += sizeof(float);
1490 scrollbar_T *sb = gui_find_scrollbar(ident);
1493 scrollbar_T *sb_info = sb->wp ? &sb->wp->w_scrollbars[0] : sb;
1494 long value = sb_info->value;
1495 long size = sb_info->size;
1496 long max = sb_info->max;
1497 BOOL isStillDragging = NO;
1498 BOOL updateKnob = YES;
1501 case NSScrollerDecrementPage:
1502 value -= (size > 2 ? size - 2 : 1);
1504 case NSScrollerIncrementPage:
1505 value += (size > 2 ? size - 2 : 1);
1507 case NSScrollerDecrementLine:
1510 case NSScrollerIncrementLine:
1513 case NSScrollerKnob:
1514 isStillDragging = YES;
1516 case NSScrollerKnobSlot:
1517 value = (long)(fval * (max - size + 1));
1524 //NSLog(@"value %d -> %d", sb_info->value, value);
1525 gui_drag_scrollbar(sb, value, isStillDragging);
1528 // Dragging the knob or option+clicking automatically updates
1529 // the knob position (on the actual NSScroller), so we only
1530 // need to set the knob position in the other cases.
1532 // Update both the left&right vertical scrollbars.
1533 long identLeft = sb->wp->w_scrollbars[SBAR_LEFT].ident;
1534 long identRight = sb->wp->w_scrollbars[SBAR_RIGHT].ident;
1535 [self setScrollbarThumbValue:value size:size max:max
1536 identifier:identLeft];
1537 [self setScrollbarThumbValue:value size:size max:max
1538 identifier:identRight];
1540 // Update the horizontal scrollbar.
1541 [self setScrollbarThumbValue:value size:size max:max
1546 } else if (SetFontMsgID == msgid) {
1548 const void *bytes = [data bytes];
1549 float pointSize = *((float*)bytes); bytes += sizeof(float);
1550 //unsigned len = *((unsigned*)bytes); bytes += sizeof(unsigned);
1551 bytes += sizeof(unsigned); // len not used
1553 NSMutableString *name = [NSMutableString stringWithUTF8String:bytes];
1554 [name appendString:[NSString stringWithFormat:@":h%.2f", pointSize]];
1556 set_option_value((char_u*)"gfn", 0, (char_u*)[name UTF8String], 0);
1558 // Force screen redraw (does it have to be this complicated?).
1559 redraw_all_later(CLEAR);
1560 update_screen(NOT_VALID);
1563 gui_update_cursor(FALSE, FALSE);
1565 } else if (VimShouldCloseMsgID == msgid) {
1567 } else if (DropFilesMsgID == msgid) {
1569 const void *bytes = [data bytes];
1570 const void *end = [data bytes] + [data length];
1571 int n = *((int*)bytes); bytes += sizeof(int);
1573 if (State & CMDLINE) {
1574 // HACK! If Vim is in command line mode then the files names
1575 // should be added to the command line, instead of opening the
1576 // files in tabs. This is taken care of by gui_handle_drop().
1577 char_u **fnames = (char_u **)alloc(n * sizeof(char_u *));
1580 while (bytes < end && i < n) {
1581 int len = *((int*)bytes); bytes += sizeof(int);
1582 fnames[i++] = vim_strnsave((char_u*)bytes, len);
1586 // NOTE! This function will free 'fnames'.
1587 // HACK! It is assumed that the 'x' and 'y' arguments are
1588 // unused when in command line mode.
1589 gui_handle_drop(0, 0, 0, fnames, i < n ? i : n);
1592 // HACK! I'm not sure how to get Vim to open a list of files in
1593 // tabs, so instead I create a ':tab drop' command with all the
1594 // files to open and execute it.
1595 NSMutableString *cmd = (n > 1)
1596 ? [NSMutableString stringWithString:@":tab drop"]
1597 : [NSMutableString stringWithString:@":drop"];
1600 for (i = 0; i < n && bytes < end; ++i) {
1601 int len = *((int*)bytes); bytes += sizeof(int);
1602 NSMutableString *file =
1603 [NSMutableString stringWithUTF8String:bytes];
1604 [file replaceOccurrencesOfString:@" "
1607 range:NSMakeRange(0,[file length])];
1610 [cmd appendString:@" "];
1611 [cmd appendString:file];
1614 // By going to the last tabpage we ensure that the new tabs will
1615 // appear last (if this call is left out, the taborder becomes
1619 do_cmdline_cmd((char_u*)[cmd UTF8String]);
1621 // Force screen redraw (does it have to be this complicated?).
1622 // (This code was taken from the end of gui_handle_drop().)
1623 update_screen(NOT_VALID);
1626 gui_update_cursor(FALSE, FALSE);
1630 } else if (DropStringMsgID == msgid) {
1632 char_u dropkey[3] = { CSI, KS_EXTRA, (char_u)KE_DROP };
1633 const void *bytes = [data bytes];
1634 int len = *((int*)bytes); bytes += sizeof(int);
1635 NSMutableString *string = [NSMutableString stringWithUTF8String:bytes];
1637 // Replace unrecognized end-of-line sequences with \x0a (line feed).
1638 NSRange range = { 0, [string length] };
1639 unsigned n = [string replaceOccurrencesOfString:@"\x0d\x0a"
1640 withString:@"\x0a" options:0
1643 n = [string replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
1644 options:0 range:range];
1647 len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1648 dnd_yank_drag_data((char_u*)[string UTF8String], len);
1649 add_to_input_buf(dropkey, sizeof(dropkey));
1651 } else if (GotFocusMsgID == msgid) {
1653 [self focusChange:YES];
1654 } else if (LostFocusMsgID == msgid) {
1656 [self focusChange:NO];
1657 } else if (MouseMovedMsgID == msgid) {
1658 const void *bytes = [data bytes];
1659 int row = *((int*)bytes); bytes += sizeof(int);
1660 int col = *((int*)bytes); bytes += sizeof(int);
1662 gui_mouse_moved(col, row);
1663 } else if (SetMouseShapeMsgID == msgid) {
1664 const void *bytes = [data bytes];
1665 int shape = *((int*)bytes); bytes += sizeof(int);
1666 update_mouseshape(shape);
1668 NSLog(@"WARNING: Unknown message received (msgid=%d)", msgid);
1672 + (NSDictionary *)specialKeys
1674 static NSDictionary *specialKeys = nil;
1677 NSBundle *mainBundle = [NSBundle mainBundle];
1678 NSString *path = [mainBundle pathForResource:@"SpecialKeys"
1680 specialKeys = [[NSDictionary alloc] initWithContentsOfFile:path];
1686 - (void)handleKeyDown:(NSString *)key modifiers:(int)mods
1690 char_u *chars = (char_u*)[key UTF8String];
1691 int length = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1693 // Special keys (arrow keys, function keys, etc.) are stored in a plist so
1694 // that new keys can easily be added.
1695 NSString *specialString = [[MMBackend specialKeys]
1697 if (specialString && [specialString length] > 1) {
1698 //NSLog(@"special key: %@", specialString);
1699 int ikey = TO_SPECIAL([specialString characterAtIndex:0],
1700 [specialString characterAtIndex:1]);
1702 ikey = simplify_key(ikey, &mods);
1707 special[1] = K_SECOND(ikey);
1708 special[2] = K_THIRD(ikey);
1712 } else if (1 == length && TAB == chars[0]) {
1713 // Tab is a trouble child:
1714 // - <Tab> is added to the input buffer as is
1715 // - <S-Tab> is translated to, {CSI,'k','B'} (i.e. 'Back-tab')
1716 // - <M-Tab> should be 0x80|TAB but this is not valid utf-8 so it needs
1717 // to be converted to utf-8
1718 // - <S-M-Tab> is translated to <S-Tab> with ALT modifier
1719 // - <C-Tab> is reserved by Mac OS X
1720 // - <D-Tab> is reserved by Mac OS X
1725 if (mods & MOD_MASK_SHIFT) {
1726 mods &= ~MOD_MASK_SHIFT;
1728 special[1] = K_SECOND(K_S_TAB);
1729 special[2] = K_THIRD(K_S_TAB);
1731 } else if (mods & MOD_MASK_ALT) {
1732 int mtab = 0x80 | TAB;
1734 special[0] = (mtab >> 6) + 0xc0;
1735 special[1] = mtab & 0xbf;
1737 mods &= ~MOD_MASK_ALT;
1739 } else if (length > 0) {
1740 unichar c = [key characterAtIndex:0];
1742 //NSLog(@"non-special: %@ (hex=%x, mods=%d)", key,
1743 // [key characterAtIndex:0], mods);
1745 if (length == 1 && ((c == Ctrl_C && ctrl_c_interrupts)
1746 || (c == intr_char && intr_char != Ctrl_C))) {
1751 // HACK! In most circumstances the Ctrl and Shift modifiers should be
1752 // cleared since they are already added to the key by the AppKit.
1753 // Unfortunately, the only way to deal with when to clear the modifiers
1754 // or not seems to be to have hard-wired rules like this.
1755 if ( !((' ' == c) || (0xa0 == c) || (mods & MOD_MASK_CMD)
1757 mods &= ~MOD_MASK_SHIFT;
1758 mods &= ~MOD_MASK_CTRL;
1759 //NSLog(@"clear shift ctrl");
1762 // HACK! All Option+key presses go via 'insert text' messages, except
1763 // for <M-Space>. If the Alt flag is not cleared for <M-Space> it does
1764 // not work to map to it.
1765 if (0xa0 == c && !(mods & MOD_MASK_CMD)) {
1766 //NSLog(@"clear alt");
1767 mods &= ~MOD_MASK_ALT;
1771 if (chars && length > 0) {
1773 //NSLog(@"adding mods: %d", mods);
1775 modChars[1] = KS_MODIFIER;
1777 add_to_input_buf(modChars, 3);
1780 //NSLog(@"add to input buf: 0x%x", chars[0]);
1781 // TODO: Check for CSI bytes?
1782 add_to_input_buf(chars, length);
1786 - (void)queueMessage:(int)msgid data:(NSData *)data
1788 [queue addObject:[NSData dataWithBytes:&msgid length:sizeof(int)]];
1790 [queue addObject:data];
1792 [queue addObject:[NSData data]];
1795 - (void)connectionDidDie:(NSNotification *)notification
1797 // If the main connection to MacVim is lost this means that MacVim was
1798 // either quit (by the user chosing Quit on the MacVim menu), or it has
1799 // crashed. In either case our only option is to quit now.
1800 // TODO: Write backup file?
1802 //NSLog(@"A Vim process lots its connection to MacVim; quitting.");
1806 - (void)blinkTimerFired:(NSTimer *)timer
1808 NSTimeInterval timeInterval = 0;
1810 [blinkTimer release];
1813 if (MMBlinkStateOn == blinkState) {
1814 gui_undraw_cursor();
1815 blinkState = MMBlinkStateOff;
1816 timeInterval = blinkOffInterval;
1817 } else if (MMBlinkStateOff == blinkState) {
1818 gui_update_cursor(TRUE, FALSE);
1819 blinkState = MMBlinkStateOn;
1820 timeInterval = blinkOnInterval;
1823 if (timeInterval > 0) {
1825 [[NSTimer scheduledTimerWithTimeInterval:timeInterval target:self
1826 selector:@selector(blinkTimerFired:)
1827 userInfo:nil repeats:NO] retain];
1828 [self flushQueue:YES];
1832 - (void)focusChange:(BOOL)on
1834 gui_focus_change(on);
1837 - (void)processInputBegin
1839 inProcessInput = YES;
1841 // Reset last flush date otherwise timed error message from e.g.
1842 // ':set tenc=latin1' are never displayed.
1843 [lastFlushDate release];
1844 lastFlushDate = nil;
1847 - (void)processInputEnd
1849 #if MM_USE_INPUT_QUEUE
1850 int count = [inputQueue count];
1852 // TODO: This is troubling, but it is not hard to get Vim to end up
1853 // here. Why does this happen?
1854 NSLog(@"WARNING: inputQueue has odd number of objects (%d)", count);
1855 [inputQueue removeAllObjects];
1856 } else if (count > 0) {
1857 // TODO: Dispatch these messages? Maybe not; usually when the
1858 // 'inputQueue' is non-empty it means that a LOT of messages has been
1859 // sent simultaneously. The only way this happens is when Vim is being
1860 // tormented, e.g. if the user holds down <D-`> to rapidly switch
1863 for (i = 0; i < count; i+=2) {
1864 int msgid = [[inputQueue objectAtIndex:i] intValue];
1865 NSLog(@"%s: Dropping message %s", _cmd, MessageStrings[msgid]);
1868 [inputQueue removeAllObjects];
1872 inputReceived = YES;
1873 inProcessInput = NO;
1876 - (NSString *)connectionNameFromServerName:(NSString *)name
1878 NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
1880 return [[NSString stringWithFormat:@"%@.%@", bundleIdentifier, name]
1884 - (NSConnection *)connectionForServerName:(NSString *)name
1886 // TODO: Try 'name%d' if 'name' fails.
1887 NSString *connName = [self connectionNameFromServerName:name];
1888 NSConnection *svrConn = [connectionNameDict objectForKey:connName];
1891 svrConn = [NSConnection connectionWithRegisteredName:connName
1893 // Try alternate server...
1894 if (!svrConn && alternateServerName) {
1895 //NSLog(@" trying to connect to alternate server: %@",
1896 // alternateServerName);
1897 connName = [self connectionNameFromServerName:alternateServerName];
1898 svrConn = [NSConnection connectionWithRegisteredName:connName
1902 // Try looking for alternate servers...
1904 //NSLog(@" looking for alternate servers...");
1905 NSString *alt = [self alternateServerNameForName:name];
1906 if (alt != alternateServerName) {
1907 //NSLog(@" found alternate server: %@", string);
1908 [alternateServerName release];
1909 alternateServerName = [alt copy];
1913 // Try alternate server again...
1914 if (!svrConn && alternateServerName) {
1915 //NSLog(@" trying to connect to alternate server: %@",
1916 // alternateServerName);
1917 connName = [self connectionNameFromServerName:alternateServerName];
1918 svrConn = [NSConnection connectionWithRegisteredName:connName
1923 [connectionNameDict setObject:svrConn forKey:connName];
1925 //NSLog(@"Adding %@ as connection observer for %@", self, svrConn);
1926 [[NSNotificationCenter defaultCenter] addObserver:self
1927 selector:@selector(serverConnectionDidDie:)
1928 name:NSConnectionDidDieNotification object:svrConn];
1935 - (NSConnection *)connectionForServerPort:(int)port
1938 NSEnumerator *e = [connectionNameDict objectEnumerator];
1940 while ((conn = [e nextObject])) {
1941 // HACK! Assume connection uses mach ports.
1942 if (port == [(NSMachPort*)[conn sendPort] machPort])
1949 - (void)serverConnectionDidDie:(NSNotification *)notification
1951 //NSLog(@"%s%@", _cmd, notification);
1953 NSConnection *svrConn = [notification object];
1955 //NSLog(@"Removing %@ as connection observer from %@", self, svrConn);
1956 [[NSNotificationCenter defaultCenter]
1958 name:NSConnectionDidDieNotification
1961 [connectionNameDict removeObjectsForKeys:
1962 [connectionNameDict allKeysForObject:svrConn]];
1964 // HACK! Assume connection uses mach ports.
1965 int port = [(NSMachPort*)[svrConn sendPort] machPort];
1966 NSNumber *key = [NSNumber numberWithInt:port];
1968 [clientProxyDict removeObjectForKey:key];
1969 [serverReplyDict removeObjectForKey:key];
1972 - (void)addClient:(NSDistantObject *)client
1974 NSConnection *conn = [client connectionForProxy];
1975 // HACK! Assume connection uses mach ports.
1976 int port = [(NSMachPort*)[conn sendPort] machPort];
1977 NSNumber *key = [NSNumber numberWithInt:port];
1979 if (![clientProxyDict objectForKey:key]) {
1980 [client setProtocolForProxy:@protocol(MMVimClientProtocol)];
1981 [clientProxyDict setObject:client forKey:key];
1984 // NOTE: 'clientWindow' is a global variable which is used by <client>
1985 clientWindow = port;
1988 - (NSString *)alternateServerNameForName:(NSString *)name
1990 if (!(name && [name length] > 0))
1993 // Only look for alternates if 'name' doesn't end in a digit.
1994 unichar lastChar = [name characterAtIndex:[name length]-1];
1995 if (lastChar >= '0' && lastChar <= '9')
1998 // Look for alternates among all current servers.
1999 NSArray *list = [self serverList];
2000 if (!(list && [list count] > 0))
2003 // Filter out servers starting with 'name' and ending with a number. The
2004 // (?i) pattern ensures that the match is case insensitive.
2005 NSString *pat = [NSString stringWithFormat:@"(?i)%@[0-9]+\\z", name];
2006 NSPredicate *pred = [NSPredicate predicateWithFormat:
2007 @"SELF MATCHES %@", pat];
2008 list = [list filteredArrayUsingPredicate:pred];
2009 if ([list count] > 0) {
2010 list = [list sortedArrayUsingSelector:@selector(serverNameCompare:)];
2011 return [list objectAtIndex:0];
2017 @end // MMBackend (Private)
2022 @implementation NSString (MMServerNameCompare)
2023 - (NSComparisonResult)serverNameCompare:(NSString *)string
2025 return [self compare:string
2026 options:NSCaseInsensitiveSearch|NSNumericSearch];
2033 static int eventModifierFlagsToVimModMask(int modifierFlags)
2037 if (modifierFlags & NSShiftKeyMask)
2038 modMask |= MOD_MASK_SHIFT;
2039 if (modifierFlags & NSControlKeyMask)
2040 modMask |= MOD_MASK_CTRL;
2041 if (modifierFlags & NSAlternateKeyMask)
2042 modMask |= MOD_MASK_ALT;
2043 if (modifierFlags & NSCommandKeyMask)
2044 modMask |= MOD_MASK_CMD;
2049 static int vimModMaskToEventModifierFlags(int mods)
2053 if (mods & MOD_MASK_SHIFT)
2054 flags |= NSShiftKeyMask;
2055 if (mods & MOD_MASK_CTRL)
2056 flags |= NSControlKeyMask;
2057 if (mods & MOD_MASK_ALT)
2058 flags |= NSAlternateKeyMask;
2059 if (mods & MOD_MASK_CMD)
2060 flags |= NSCommandKeyMask;
2065 static int eventModifierFlagsToVimMouseModMask(int modifierFlags)
2069 if (modifierFlags & NSShiftKeyMask)
2070 modMask |= MOUSE_SHIFT;
2071 if (modifierFlags & NSControlKeyMask)
2072 modMask |= MOUSE_CTRL;
2073 if (modifierFlags & NSAlternateKeyMask)
2074 modMask |= MOUSE_ALT;
2079 static int eventButtonNumberToVimMouseButton(int buttonNumber)
2081 static int mouseButton[] = { MOUSE_LEFT, MOUSE_RIGHT, MOUSE_MIDDLE,
2082 MOUSE_X1, MOUSE_X2 };
2084 return mouseButton[buttonNumber < 5 ? buttonNumber : 0];
2087 static int specialKeyToNSKey(int key)
2089 if (!IS_SPECIAL(key))
2096 { K_UP, NSUpArrowFunctionKey },
2097 { K_DOWN, NSDownArrowFunctionKey },
2098 { K_LEFT, NSLeftArrowFunctionKey },
2099 { K_RIGHT, NSRightArrowFunctionKey },
2100 { K_F1, NSF1FunctionKey },
2101 { K_F2, NSF2FunctionKey },
2102 { K_F3, NSF3FunctionKey },
2103 { K_F4, NSF4FunctionKey },
2104 { K_F5, NSF5FunctionKey },
2105 { K_F6, NSF6FunctionKey },
2106 { K_F7, NSF7FunctionKey },
2107 { K_F8, NSF8FunctionKey },
2108 { K_F9, NSF9FunctionKey },
2109 { K_F10, NSF10FunctionKey },
2110 { K_F11, NSF11FunctionKey },
2111 { K_F12, NSF12FunctionKey },
2112 { K_F13, NSF13FunctionKey },
2113 { K_F14, NSF14FunctionKey },
2114 { K_F15, NSF15FunctionKey },
2115 { K_F16, NSF16FunctionKey },
2116 { K_F17, NSF17FunctionKey },
2117 { K_F18, NSF18FunctionKey },
2118 { K_F19, NSF19FunctionKey },
2119 { K_F20, NSF20FunctionKey },
2120 { K_F21, NSF21FunctionKey },
2121 { K_F22, NSF22FunctionKey },
2122 { K_F23, NSF23FunctionKey },
2123 { K_F24, NSF24FunctionKey },
2124 { K_F25, NSF25FunctionKey },
2125 { K_F26, NSF26FunctionKey },
2126 { K_F27, NSF27FunctionKey },
2127 { K_F28, NSF28FunctionKey },
2128 { K_F29, NSF29FunctionKey },
2129 { K_F30, NSF30FunctionKey },
2130 { K_F31, NSF31FunctionKey },
2131 { K_F32, NSF32FunctionKey },
2132 { K_F33, NSF33FunctionKey },
2133 { K_F34, NSF34FunctionKey },
2134 { K_F35, NSF35FunctionKey },
2135 { K_DEL, NSBackspaceCharacter },
2136 { K_BS, NSDeleteCharacter },
2137 { K_HOME, NSHomeFunctionKey },
2138 { K_END, NSEndFunctionKey },
2139 { K_PAGEUP, NSPageUpFunctionKey },
2140 { K_PAGEDOWN, NSPageDownFunctionKey }
2144 for (i = 0; i < sizeof(sp2ns)/sizeof(sp2ns[0]); ++i) {
2145 if (sp2ns[i].special == key)
2146 return sp2ns[i].nskey;