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 // NOTE: Colors in MMBackend are stored as unsigned ints on the form 0xaarrggbb
16 // whereas colors in Vim are int without the alpha component.
17 #define MM_COLOR(col) ((unsigned)( ((col)&0xffffff) | 0xff000000 ))
18 #define MM_COLOR_WITH_TRANSP(col,transp) \
19 ((unsigned)( ((col)&0xffffff) | (((unsigned)(255-(transp))&0xff)<<24) ))
22 // This constant controls how often the command queue may be flushed. If it is
23 // too small the app might feel unresponsive; if it is too large there might be
24 // long periods without the screen updating (e.g. when sourcing a large session
25 // file). (The unit is seconds.)
26 static float MMFlushTimeoutInterval = 0.1f;
28 static unsigned MMServerMax = 1000;
30 // NOTE: The default font is bundled with the application.
31 static NSString *MMDefaultFontName = @"DejaVu Sans Mono";
32 static float MMDefaultFontSize = 12.0f;
34 // TODO: Move to separate file.
35 static int eventModifierFlagsToVimModMask(int modifierFlags);
36 static int vimModMaskToEventModifierFlags(int mods);
37 static int eventModifierFlagsToVimMouseModMask(int modifierFlags);
38 static int eventButtonNumberToVimMouseButton(int buttonNumber);
39 static int specialKeyToNSKey(int key);
49 @interface NSString (MMServerNameCompare)
50 - (NSComparisonResult)serverNameCompare:(NSString *)string;
55 @interface MMBackend (Private)
56 - (void)handleMessage:(int)msgid data:(NSData *)data;
57 + (NSDictionary *)specialKeys;
58 - (void)handleKeyDown:(NSString *)key modifiers:(int)mods;
59 - (void)queueMessage:(int)msgid data:(NSData *)data;
60 - (void)connectionDidDie:(NSNotification *)notification;
61 - (void)blinkTimerFired:(NSTimer *)timer;
62 - (void)focusChange:(BOOL)on;
63 - (void)processInputBegin;
64 - (void)processInputEnd;
65 - (NSString *)connectionNameFromServerName:(NSString *)name;
66 - (NSConnection *)connectionForServerName:(NSString *)name;
67 - (NSConnection *)connectionForServerPort:(int)port;
68 - (void)serverConnectionDidDie:(NSNotification *)notification;
69 - (void)addClient:(NSDistantObject *)client;
70 - (NSString *)alternateServerNameForName:(NSString *)name;
75 @implementation MMBackend
77 + (MMBackend *)sharedInstance
79 static MMBackend *singleton = nil;
80 return singleton ? singleton : (singleton = [MMBackend new]);
85 if ((self = [super init])) {
86 fontContainerRef = loadFonts();
88 queue = [[NSMutableArray alloc] init];
89 #if MM_USE_INPUT_QUEUE
90 inputQueue = [[NSMutableArray alloc] init];
92 drawData = [[NSMutableData alloc] initWithCapacity:1024];
93 connectionNameDict = [[NSMutableDictionary alloc] init];
94 clientProxyDict = [[NSMutableDictionary alloc] init];
95 serverReplyDict = [[NSMutableDictionary alloc] init];
97 NSString *path = [[NSBundle mainBundle] pathForResource:@"Colors"
100 colorDict = [[NSDictionary dictionaryWithContentsOfFile:path]
103 NSLog(@"WARNING: Could not locate Colors.plist.");
106 path = [[NSBundle mainBundle] pathForResource:@"SystemColors"
109 sysColorDict = [[NSDictionary dictionaryWithContentsOfFile:path]
112 NSLog(@"WARNING: Could not locate SystemColors.plist.");
121 //NSLog(@"%@ %s", [self className], _cmd);
123 [[NSNotificationCenter defaultCenter] removeObserver:self];
125 [blinkTimer release]; blinkTimer = nil;
126 #if MM_USE_INPUT_QUEUE
127 [inputQueue release]; inputQueue = nil;
129 [alternateServerName release]; alternateServerName = nil;
130 [serverReplyDict release]; serverReplyDict = nil;
131 [clientProxyDict release]; clientProxyDict = nil;
132 [connectionNameDict release]; connectionNameDict = nil;
133 [queue release]; queue = nil;
134 [drawData release]; drawData = nil;
135 [frontendProxy release]; frontendProxy = nil;
136 [connection release]; connection = nil;
137 [sysColorDict release]; sysColorDict = nil;
138 [colorDict release]; colorDict = nil;
143 - (void)setBackgroundColor:(int)color
145 backgroundColor = MM_COLOR_WITH_TRANSP(color,p_transp);
148 - (void)setForegroundColor:(int)color
150 foregroundColor = MM_COLOR(color);
153 - (void)setSpecialColor:(int)color
155 specialColor = MM_COLOR(color);
158 - (void)setDefaultColorsBackground:(int)bg foreground:(int)fg
160 defaultBackgroundColor = MM_COLOR_WITH_TRANSP(bg,p_transp);
161 defaultForegroundColor = MM_COLOR(fg);
163 NSMutableData *data = [NSMutableData data];
165 [data appendBytes:&defaultBackgroundColor length:sizeof(unsigned)];
166 [data appendBytes:&defaultForegroundColor length:sizeof(unsigned)];
168 [self queueMessage:SetDefaultColorsMsgID data:data];
171 - (NSConnection *)connection
174 // NOTE! If the name of the connection changes here it must also be
175 // updated in MMAppController.m.
176 NSString *name = [NSString stringWithFormat:@"%@-connection",
177 [[NSBundle mainBundle] bundleIdentifier]];
179 connection = [NSConnection connectionWithRegisteredName:name host:nil];
183 // NOTE: 'connection' may be nil here.
189 if (![self connection]) {
190 NSBundle *mainBundle = [NSBundle mainBundle];
192 NSString *path = [mainBundle bundlePath];
193 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
194 NSLog(@"WARNING: Failed to launch GUI with path %@", path);
198 // HACK! It would be preferable to launch the GUI using NSWorkspace,
199 // however I have not managed to figure out how to pass arguments using
202 // NOTE! Using NSTask to launch the GUI has the negative side-effect
203 // that the GUI won't be activated (or raised) so there is a hack in
204 // MMWindowController which always raises the app when a new window is
206 NSMutableArray *args = [NSMutableArray arrayWithObjects:
207 [NSString stringWithFormat:@"-%@", MMNoWindowKey], @"yes", nil];
208 NSString *exeName = [[mainBundle infoDictionary]
209 objectForKey:@"CFBundleExecutable"];
210 NSString *path = [mainBundle pathForAuxiliaryExecutable:exeName];
212 NSLog(@"ERROR: Could not find MacVim executable in bundle");
216 [NSTask launchedTaskWithLaunchPath:path arguments:args];
219 // HACK! The NSWorkspaceDidLaunchApplicationNotification does not work
220 // for tasks like this, so poll the mach bootstrap server until it
221 // returns a valid connection. Also set a time-out date so that we
222 // don't get stuck doing this forever.
223 NSDate *timeOutDate = [NSDate dateWithTimeIntervalSinceNow:15];
224 while (!connection &&
225 NSOrderedDescending == [timeOutDate compare:[NSDate date]])
227 [[NSRunLoop currentRunLoop]
228 runMode:NSDefaultRunLoopMode
229 beforeDate:[NSDate dateWithTimeIntervalSinceNow:1]];
231 // NOTE: This call will set 'connection' as a side-effect.
236 NSLog(@"WARNING: Timed-out waiting for GUI to launch.");
241 id proxy = [connection rootProxy];
242 [proxy setProtocolForProxy:@protocol(MMAppProtocol)];
244 [[NSNotificationCenter defaultCenter] addObserver:self
245 selector:@selector(connectionDidDie:)
246 name:NSConnectionDidDieNotification object:connection];
248 int pid = [[NSProcessInfo processInfo] processIdentifier];
251 frontendProxy = [proxy connectBackend:self pid:pid];
253 @catch (NSException *e) {
254 NSLog(@"Exception caught when trying to connect backend: \"%@\"", e);
258 [frontendProxy retain];
259 [frontendProxy setProtocolForProxy:@protocol(MMAppProtocol)];
262 return connection && frontendProxy;
265 - (BOOL)openVimWindow
267 [self queueMessage:OpenVimWindowMsgID data:nil];
273 int type = ClearAllDrawType;
275 // Any draw commands in queue are effectively obsolete since this clearAll
276 // will negate any effect they have, therefore we may as well clear the
278 [drawData setLength:0];
280 [drawData appendBytes:&type length:sizeof(int)];
283 - (void)clearBlockFromRow:(int)row1 column:(int)col1
284 toRow:(int)row2 column:(int)col2
286 int type = ClearBlockDrawType;
288 [drawData appendBytes:&type length:sizeof(int)];
290 [drawData appendBytes:&defaultBackgroundColor length:sizeof(unsigned)];
291 [drawData appendBytes:&row1 length:sizeof(int)];
292 [drawData appendBytes:&col1 length:sizeof(int)];
293 [drawData appendBytes:&row2 length:sizeof(int)];
294 [drawData appendBytes:&col2 length:sizeof(int)];
297 - (void)deleteLinesFromRow:(int)row count:(int)count
298 scrollBottom:(int)bottom left:(int)left right:(int)right
300 int type = DeleteLinesDrawType;
302 [drawData appendBytes:&type length:sizeof(int)];
304 [drawData appendBytes:&defaultBackgroundColor length:sizeof(unsigned)];
305 [drawData appendBytes:&row length:sizeof(int)];
306 [drawData appendBytes:&count length:sizeof(int)];
307 [drawData appendBytes:&bottom length:sizeof(int)];
308 [drawData appendBytes:&left length:sizeof(int)];
309 [drawData appendBytes:&right length:sizeof(int)];
312 - (void)replaceString:(char*)s length:(int)len row:(int)row column:(int)col
315 if (len <= 0) return;
317 int type = ReplaceStringDrawType;
319 [drawData appendBytes:&type length:sizeof(int)];
321 [drawData appendBytes:&backgroundColor length:sizeof(unsigned)];
322 [drawData appendBytes:&foregroundColor length:sizeof(unsigned)];
323 [drawData appendBytes:&specialColor length:sizeof(unsigned)];
324 [drawData appendBytes:&row length:sizeof(int)];
325 [drawData appendBytes:&col length:sizeof(int)];
326 [drawData appendBytes:&flags length:sizeof(int)];
327 [drawData appendBytes:&len length:sizeof(int)];
328 [drawData appendBytes:s length:len];
331 - (void)insertLinesFromRow:(int)row count:(int)count
332 scrollBottom:(int)bottom left:(int)left right:(int)right
334 int type = InsertLinesDrawType;
336 [drawData appendBytes:&type length:sizeof(int)];
338 [drawData appendBytes:&defaultBackgroundColor length:sizeof(unsigned)];
339 [drawData appendBytes:&row length:sizeof(int)];
340 [drawData appendBytes:&count length:sizeof(int)];
341 [drawData appendBytes:&bottom length:sizeof(int)];
342 [drawData appendBytes:&left length:sizeof(int)];
343 [drawData appendBytes:&right length:sizeof(int)];
346 - (void)drawCursorAtRow:(int)row column:(int)col shape:(int)shape
347 fraction:(int)percent color:(int)color
349 int type = DrawCursorDrawType;
350 unsigned uc = MM_COLOR(color);
352 [drawData appendBytes:&type length:sizeof(int)];
354 [drawData appendBytes:&uc length:sizeof(unsigned)];
355 [drawData appendBytes:&row length:sizeof(int)];
356 [drawData appendBytes:&col length:sizeof(int)];
357 [drawData appendBytes:&shape length:sizeof(int)];
358 [drawData appendBytes:&percent length:sizeof(int)];
361 - (void)flushQueue:(BOOL)force
363 // NOTE! This method gets called a lot; if we were to flush every time it
364 // was called MacVim would feel unresponsive. So there is a time out which
365 // ensures that the queue isn't flushed too often.
366 if (!force && lastFlushDate && -[lastFlushDate timeIntervalSinceNow]
367 < MMFlushTimeoutInterval)
370 if ([drawData length] > 0) {
371 [self queueMessage:BatchDrawMsgID data:[drawData copy]];
372 [drawData setLength:0];
375 if ([queue count] > 0) {
377 [frontendProxy processCommandQueue:queue];
379 @catch (NSException *e) {
380 NSLog(@"Exception caught when processing command queue: \"%@\"", e);
383 [queue removeAllObjects];
385 [lastFlushDate release];
386 lastFlushDate = [[NSDate date] retain];
390 - (BOOL)waitForInput:(int)milliseconds
392 NSDate *date = milliseconds > 0 ?
393 [NSDate dateWithTimeIntervalSinceNow:.001*milliseconds] :
394 [NSDate distantFuture];
396 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:date];
398 // I know of no way to figure out if the run loop exited because input was
399 // found or because of a time out, so I need to manually indicate when
400 // input was received in processInput:data: and then reset it every time
402 BOOL yn = inputReceived;
410 #ifdef MAC_CLIENTSERVER
411 // The default connection is used for the client/server code.
412 [[NSConnection defaultConnection] setRootObject:nil];
413 [[NSConnection defaultConnection] invalidate];
416 // By invalidating the NSConnection the MMWindowController immediately
417 // finds out that the connection is down and as a result
418 // [MMWindowController connectionDidDie:] is invoked.
419 //NSLog(@"%@ %s", [self className], _cmd);
420 [[NSNotificationCenter defaultCenter] removeObserver:self];
421 [connection invalidate];
423 if (fontContainerRef) {
424 ATSFontDeactivate(fontContainerRef, NULL, kATSOptionFlagsDefault);
425 fontContainerRef = 0;
430 - (void)selectTab:(int)index
432 //NSLog(@"%s%d", _cmd, index);
435 NSData *data = [NSData dataWithBytes:&index length:sizeof(int)];
436 [self queueMessage:SelectTabMsgID data:data];
441 //NSLog(@"%s", _cmd);
443 NSMutableData *data = [NSMutableData data];
445 int idx = tabpage_index(curtab) - 1;
446 [data appendBytes:&idx length:sizeof(int)];
449 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next) {
450 // This function puts the label of the tab in the global 'NameBuff'.
451 get_tabline_label(tp, FALSE);
452 char_u *s = NameBuff;
454 if (len <= 0) continue;
457 s = CONVERT_TO_UTF8(s);
460 // Count the number of windows in the tabpage.
461 //win_T *wp = tp->tp_firstwin;
463 //for (wincount = 0; wp != NULL; wp = wp->w_next, ++wincount);
465 //[data appendBytes:&wincount length:sizeof(int)];
466 [data appendBytes:&len length:sizeof(int)];
467 [data appendBytes:s length:len];
470 CONVERT_TO_UTF8_FREE(s);
474 [self queueMessage:UpdateTabBarMsgID data:data];
477 - (BOOL)tabBarVisible
479 return tabBarVisible;
482 - (void)showTabBar:(BOOL)enable
484 tabBarVisible = enable;
486 int msgid = enable ? ShowTabBarMsgID : HideTabBarMsgID;
487 [self queueMessage:msgid data:nil];
490 - (void)setRows:(int)rows columns:(int)cols
492 //NSLog(@"[VimTask] setRows:%d columns:%d", rows, cols);
494 int dim[] = { rows, cols };
495 NSData *data = [NSData dataWithBytes:&dim length:2*sizeof(int)];
497 [self queueMessage:SetTextDimensionsMsgID data:data];
500 - (void)setWindowTitle:(char *)title
502 NSMutableData *data = [NSMutableData data];
503 int len = strlen(title);
504 if (len <= 0) return;
506 [data appendBytes:&len length:sizeof(int)];
507 [data appendBytes:title length:len];
509 [self queueMessage:SetWindowTitleMsgID data:data];
512 - (char *)browseForFileInDirectory:(char *)dir title:(char *)title
515 //NSLog(@"browseForFileInDirectory:%s title:%s saving:%d", dir, title,
519 NSString *ds = dir ? [NSString stringWithUTF8String:dir] : nil;
520 NSString *ts = title ? [NSString stringWithUTF8String:title] : nil;
522 [frontendProxy showSavePanelForDirectory:ds title:ts saving:saving];
524 // Wait until a reply is sent from MMVimController.
525 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
526 beforeDate:[NSDate distantFuture]];
528 if (dialogReturn && [dialogReturn isKindOfClass:[NSString class]]) {
529 char_u *ret = (char_u*)[dialogReturn UTF8String];
531 ret = CONVERT_FROM_UTF8(ret);
533 s = vim_strsave(ret);
535 CONVERT_FROM_UTF8_FREE(ret);
539 [dialogReturn release]; dialogReturn = nil;
541 @catch (NSException *e) {
542 NSLog(@"Exception caught when showing save panel: \"%@\"", e);
548 - (oneway void)setDialogReturn:(in bycopy id)obj
550 // NOTE: This is called by
551 // - [MMVimController panelDidEnd:::], and
552 // - [MMVimController alertDidEnd:::],
553 // to indicate that a save/open panel or alert has finished.
555 if (obj != dialogReturn) {
556 [dialogReturn release];
557 dialogReturn = [obj retain];
561 - (int)presentDialogWithType:(int)type title:(char *)title message:(char *)msg
562 buttons:(char *)btns textField:(char *)txtfield
565 NSString *message = nil, *text = nil, *textFieldString = nil;
566 NSArray *buttons = nil;
567 int style = NSInformationalAlertStyle;
569 if (VIM_WARNING == type) style = NSWarningAlertStyle;
570 else if (VIM_ERROR == type) style = NSCriticalAlertStyle;
573 NSString *btnString = [NSString stringWithUTF8String:btns];
574 buttons = [btnString componentsSeparatedByString:@"\n"];
577 message = [NSString stringWithUTF8String:title];
579 text = [NSString stringWithUTF8String:msg];
581 // HACK! If there is a '\n\n' or '\n' sequence in the message, then
582 // make the part up to there into the title. We only do this
583 // because Vim has lots of dialogs without a title and they look
585 // TODO: Fix the actual dialog texts.
586 NSRange eolRange = [text rangeOfString:@"\n\n"];
587 if (NSNotFound == eolRange.location)
588 eolRange = [text rangeOfString:@"\n"];
589 if (NSNotFound != eolRange.location) {
590 message = [text substringToIndex:eolRange.location];
591 text = [text substringFromIndex:NSMaxRange(eolRange)];
596 textFieldString = [NSString stringWithUTF8String:txtfield];
599 [frontendProxy presentDialogWithStyle:style message:message
600 informativeText:text buttonTitles:buttons
601 textFieldString:textFieldString];
603 // Wait until a reply is sent from MMVimController.
604 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
605 beforeDate:[NSDate distantFuture]];
607 if (dialogReturn && [dialogReturn isKindOfClass:[NSArray class]]
608 && [dialogReturn count]) {
609 retval = [[dialogReturn objectAtIndex:0] intValue];
610 if (txtfield && [dialogReturn count] > 1) {
611 NSString *retString = [dialogReturn objectAtIndex:1];
612 char_u *ret = (char_u*)[retString UTF8String];
614 ret = CONVERT_FROM_UTF8(ret);
616 vim_strncpy((char_u*)txtfield, ret, IOSIZE - 1);
618 CONVERT_FROM_UTF8_FREE(ret);
623 [dialogReturn release]; dialogReturn = nil;
625 @catch (NSException *e) {
626 NSLog(@"Exception caught while showing alert dialog: \"%@\"", e);
632 - (void)addMenuWithTag:(int)tag parent:(int)parentTag name:(char *)name
635 //NSLog(@"addMenuWithTag:%d parent:%d name:%s atIndex:%d", tag, parentTag,
638 int namelen = name ? strlen(name) : 0;
639 NSMutableData *data = [NSMutableData data];
641 [data appendBytes:&tag length:sizeof(int)];
642 [data appendBytes:&parentTag length:sizeof(int)];
643 [data appendBytes:&namelen length:sizeof(int)];
644 if (namelen > 0) [data appendBytes:name length:namelen];
645 [data appendBytes:&index length:sizeof(int)];
647 [self queueMessage:AddMenuMsgID data:data];
650 - (void)addMenuItemWithTag:(int)tag parent:(int)parentTag name:(char *)name
651 tip:(char *)tip icon:(char *)icon
652 keyEquivalent:(int)key modifiers:(int)mods
653 action:(NSString *)action atIndex:(int)index
655 //NSLog(@"addMenuItemWithTag:%d parent:%d name:%s tip:%s atIndex:%d", tag,
656 // parentTag, name, tip, index);
658 int namelen = name ? strlen(name) : 0;
659 int tiplen = tip ? strlen(tip) : 0;
660 int iconlen = icon ? strlen(icon) : 0;
661 int eventFlags = vimModMaskToEventModifierFlags(mods);
662 int actionlen = [action lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
663 NSMutableData *data = [NSMutableData data];
665 key = specialKeyToNSKey(key);
667 [data appendBytes:&tag length:sizeof(int)];
668 [data appendBytes:&parentTag length:sizeof(int)];
669 [data appendBytes:&namelen length:sizeof(int)];
670 if (namelen > 0) [data appendBytes:name length:namelen];
671 [data appendBytes:&tiplen length:sizeof(int)];
672 if (tiplen > 0) [data appendBytes:tip length:tiplen];
673 [data appendBytes:&iconlen length:sizeof(int)];
674 if (iconlen > 0) [data appendBytes:icon length:iconlen];
675 [data appendBytes:&actionlen length:sizeof(int)];
676 if (actionlen > 0) [data appendBytes:[action UTF8String] length:actionlen];
677 [data appendBytes:&index length:sizeof(int)];
678 [data appendBytes:&key length:sizeof(int)];
679 [data appendBytes:&eventFlags length:sizeof(int)];
681 [self queueMessage:AddMenuItemMsgID data:data];
684 - (void)removeMenuItemWithTag:(int)tag
686 NSMutableData *data = [NSMutableData data];
687 [data appendBytes:&tag length:sizeof(int)];
689 [self queueMessage:RemoveMenuItemMsgID data:data];
692 - (void)enableMenuItemWithTag:(int)tag state:(int)enabled
694 NSMutableData *data = [NSMutableData data];
696 [data appendBytes:&tag length:sizeof(int)];
697 [data appendBytes:&enabled length:sizeof(int)];
699 [self queueMessage:EnableMenuItemMsgID data:data];
702 - (void)showPopupMenuWithName:(char *)name atMouseLocation:(BOOL)mouse
704 int len = strlen(name);
705 int row = -1, col = -1;
707 if (len <= 0) return;
709 if (!mouse && curwin) {
710 row = curwin->w_wrow;
711 col = curwin->w_wcol;
714 NSMutableData *data = [NSMutableData data];
716 [data appendBytes:&row length:sizeof(int)];
717 [data appendBytes:&col length:sizeof(int)];
718 [data appendBytes:&len length:sizeof(int)];
719 [data appendBytes:name length:len];
721 [self queueMessage:ShowPopupMenuMsgID data:data];
724 - (void)showToolbar:(int)enable flags:(int)flags
726 NSMutableData *data = [NSMutableData data];
728 [data appendBytes:&enable length:sizeof(int)];
729 [data appendBytes:&flags length:sizeof(int)];
731 [self queueMessage:ShowToolbarMsgID data:data];
734 - (void)createScrollbarWithIdentifier:(long)ident type:(int)type
736 NSMutableData *data = [NSMutableData data];
738 [data appendBytes:&ident length:sizeof(long)];
739 [data appendBytes:&type length:sizeof(int)];
741 [self queueMessage:CreateScrollbarMsgID data:data];
744 - (void)destroyScrollbarWithIdentifier:(long)ident
746 NSMutableData *data = [NSMutableData data];
747 [data appendBytes:&ident length:sizeof(long)];
749 [self queueMessage:DestroyScrollbarMsgID data:data];
752 - (void)showScrollbarWithIdentifier:(long)ident state:(int)visible
754 NSMutableData *data = [NSMutableData data];
756 [data appendBytes:&ident length:sizeof(long)];
757 [data appendBytes:&visible length:sizeof(int)];
759 [self queueMessage:ShowScrollbarMsgID data:data];
762 - (void)setScrollbarPosition:(int)pos length:(int)len identifier:(long)ident
764 NSMutableData *data = [NSMutableData data];
766 [data appendBytes:&ident length:sizeof(long)];
767 [data appendBytes:&pos length:sizeof(int)];
768 [data appendBytes:&len length:sizeof(int)];
770 [self queueMessage:SetScrollbarPositionMsgID data:data];
773 - (void)setScrollbarThumbValue:(long)val size:(long)size max:(long)max
774 identifier:(long)ident
776 float fval = max-size+1 > 0 ? (float)val/(max-size+1) : 0;
777 float prop = (float)size/(max+1);
778 if (fval < 0) fval = 0;
779 else if (fval > 1.0f) fval = 1.0f;
780 if (prop < 0) prop = 0;
781 else if (prop > 1.0f) prop = 1.0f;
783 NSMutableData *data = [NSMutableData data];
785 [data appendBytes:&ident length:sizeof(long)];
786 [data appendBytes:&fval length:sizeof(float)];
787 [data appendBytes:&prop length:sizeof(float)];
789 [self queueMessage:SetScrollbarThumbMsgID data:data];
792 - (BOOL)setFontWithName:(char *)name
794 NSString *fontName = MMDefaultFontName;
795 float size = MMDefaultFontSize;
796 BOOL parseFailed = NO;
799 fontName = [NSString stringWithUTF8String:name];
801 if ([fontName isEqual:@"*"]) {
802 // :set gfn=* shows the font panel.
803 do_cmdline_cmd((char_u*)":action orderFrontFontPanel:");
807 NSArray *components = [fontName componentsSeparatedByString:@":"];
808 if ([components count] == 2) {
809 NSString *sizeString = [components lastObject];
810 if ([sizeString length] > 0
811 && [sizeString characterAtIndex:0] == 'h') {
812 sizeString = [sizeString substringFromIndex:1];
813 if ([sizeString length] > 0) {
814 size = [sizeString floatValue];
815 fontName = [components objectAtIndex:0];
820 } else if ([components count] > 2) {
825 if (!parseFailed && [fontName length] > 0) {
826 if (size < 6 || size > 100) {
827 // Font size 0.0 tells NSFont to use the 'user default size'.
831 NSFont *font = [NSFont fontWithName:fontName size:size];
833 if (!font && MMDefaultFontName == fontName) {
834 // If for some reason the MacVim default font is not in the app
835 // bundle, then fall back on the system default font.
837 font = [NSFont userFixedPitchFontOfSize:size];
838 fontName = [font displayName];
842 //NSLog(@"Setting font '%@' of size %.2f", fontName, size);
844 lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
846 NSMutableData *data = [NSMutableData data];
848 [data appendBytes:&size length:sizeof(float)];
849 [data appendBytes:&len length:sizeof(int)];
850 [data appendBytes:[fontName UTF8String] length:len];
852 [self queueMessage:SetFontMsgID data:data];
858 //NSLog(@"WARNING: Cannot set font with name '%@' of size %.2f",
863 - (void)executeActionWithName:(NSString *)name
865 int len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
868 NSMutableData *data = [NSMutableData data];
870 [data appendBytes:&len length:sizeof(int)];
871 [data appendBytes:[name UTF8String] length:len];
873 [self queueMessage:ExecuteActionMsgID data:data];
877 - (void)setMouseShape:(int)shape
879 NSMutableData *data = [NSMutableData data];
880 [data appendBytes:&shape length:sizeof(int)];
881 [self queueMessage:SetMouseShapeMsgID data:data];
884 - (void)setBlinkWait:(int)wait on:(int)on off:(int)off
886 // Vim specifies times in milliseconds, whereas Cocoa wants them in
888 blinkWaitInterval = .001f*wait;
889 blinkOnInterval = .001f*on;
890 blinkOffInterval = .001f*off;
896 [blinkTimer invalidate];
897 [blinkTimer release];
901 if (blinkWaitInterval > 0 && blinkOnInterval > 0 && blinkOffInterval > 0
903 blinkState = MMBlinkStateOn;
905 [[NSTimer scheduledTimerWithTimeInterval:blinkWaitInterval
907 selector:@selector(blinkTimerFired:)
908 userInfo:nil repeats:NO] retain];
909 gui_update_cursor(TRUE, FALSE);
910 [self flushQueue:YES];
916 if (MMBlinkStateOff == blinkState) {
917 gui_update_cursor(TRUE, FALSE);
918 [self flushQueue:YES];
921 blinkState = MMBlinkStateNone;
924 - (void)adjustLinespace:(int)linespace
926 NSMutableData *data = [NSMutableData data];
927 [data appendBytes:&linespace length:sizeof(int)];
928 [self queueMessage:AdjustLinespaceMsgID data:data];
933 [self queueMessage:ActivateMsgID data:nil];
936 - (int)lookupColorWithKey:(NSString *)key
938 if (!(key && [key length] > 0))
941 NSString *stripKey = [[[[key lowercaseString]
942 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
943 componentsSeparatedByString:@" "]
944 componentsJoinedByString:@""];
946 if (stripKey && [stripKey length] > 0) {
947 // First of all try to lookup key in the color dictionary; note that
948 // all keys in this dictionary are lowercase with no whitespace.
949 id obj = [colorDict objectForKey:stripKey];
950 if (obj) return [obj intValue];
952 // The key was not in the dictionary; is it perhaps of the form
954 if ([stripKey length] > 1 && [stripKey characterAtIndex:0] == '#') {
955 NSScanner *scanner = [NSScanner scannerWithString:stripKey];
956 [scanner setScanLocation:1];
958 if ([scanner scanHexInt:&hex]) {
963 // As a last resort, check if it is one of the system defined colors.
964 // The keys in this dictionary are also lowercase with no whitespace.
965 obj = [sysColorDict objectForKey:stripKey];
967 NSColor *col = [NSColor performSelector:NSSelectorFromString(obj)];
970 col = [col colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
971 [col getRed:&r green:&g blue:&b alpha:&a];
972 return (((int)(r*255+.5f) & 0xff) << 16)
973 + (((int)(g*255+.5f) & 0xff) << 8)
974 + ((int)(b*255+.5f) & 0xff);
979 NSLog(@"WARNING: No color with key %@ found.", stripKey);
983 - (BOOL)hasSpecialKeyWithValue:(NSString *)value
985 NSEnumerator *e = [[MMBackend specialKeys] objectEnumerator];
988 while ((obj = [e nextObject])) {
989 if ([value isEqual:obj])
996 - (oneway void)processInput:(int)msgid data:(in NSData *)data
998 // NOTE: This method might get called whenever the run loop is tended to.
999 // Thus it might get called whilst input is being processed. Normally this
1000 // is not a problem, but if it gets called often then it might become
1001 // dangerous. E.g. say a message causes the screen to be redrawn and then
1002 // another message is received causing another simultaneous screen redraw;
1003 // this is not good. To deal with this problem at the moment, we simply
1004 // drop messages that are received while other input is being processed.
1005 if (inProcessInput) {
1006 #if MM_USE_INPUT_QUEUE
1007 [inputQueue addObject:[NSNumber numberWithInt:msgid]];
1008 [inputQueue addObject:data];
1010 // Just drop the input
1011 //NSLog(@"WARNING: Dropping input in %s", _cmd);
1014 [self processInputBegin];
1015 [self handleMessage:msgid data:data];
1016 [self processInputEnd];
1020 - (oneway void)processInputAndData:(in NSArray *)messages
1022 // NOTE: See comment in processInput:data:.
1023 unsigned i, count = [messages count];
1025 NSLog(@"WARNING: [messages count] is odd in %s", _cmd);
1029 if (inProcessInput) {
1030 #if MM_USE_INPUT_QUEUE
1031 [inputQueue addObjectsFromArray:messages];
1033 // Just drop the input
1034 //NSLog(@"WARNING: Dropping input in %s", _cmd);
1037 [self processInputBegin];
1039 for (i = 0; i < count; i += 2) {
1040 int msgid = [[messages objectAtIndex:i] intValue];
1041 id data = [messages objectAtIndex:i+1];
1042 if ([data isEqual:[NSNull null]])
1045 [self handleMessage:msgid data:data];
1048 [self processInputEnd];
1052 - (BOOL)checkForModifiedBuffers
1055 for (buf = firstbuf; buf != NULL; buf = buf->b_next) {
1056 if (bufIsChanged(buf)) {
1064 - (BOOL)starRegisterToPasteboard:(byref NSPasteboard *)pboard
1066 if (VIsual_active && (State & NORMAL) && clip_star.available) {
1067 // If there is no pasteboard, return YES to indicate that there is text
1072 clip_copy_selection();
1074 // Get the text to put on the pasteboard.
1075 long_u llen = 0; char_u *str = 0;
1076 int type = clip_convert_selection(&str, &llen, &clip_star);
1080 // TODO: Avoid overflow.
1081 int len = (int)llen;
1083 if (output_conv.vc_type != CONV_NONE) {
1084 char_u *conv_str = string_convert(&output_conv, str, &len);
1092 NSString *string = [[NSString alloc]
1093 initWithBytes:str length:len encoding:NSUTF8StringEncoding];
1095 NSArray *types = [NSArray arrayWithObject:NSStringPboardType];
1096 [pboard declareTypes:types owner:nil];
1097 BOOL ok = [pboard setString:string forType:NSStringPboardType];
1108 - (oneway void)addReply:(in bycopy NSString *)reply
1109 server:(in byref id <MMVimServerProtocol>)server
1111 //NSLog(@"addReply:%@ server:%@", reply, (id)server);
1113 // Replies might come at any time and in any order so we keep them in an
1114 // array inside a dictionary with the send port used as key.
1116 NSConnection *conn = [(NSDistantObject*)server connectionForProxy];
1117 // HACK! Assume connection uses mach ports.
1118 int port = [(NSMachPort*)[conn sendPort] machPort];
1119 NSNumber *key = [NSNumber numberWithInt:port];
1121 NSMutableArray *replies = [serverReplyDict objectForKey:key];
1123 replies = [NSMutableArray array];
1124 [serverReplyDict setObject:replies forKey:key];
1127 [replies addObject:reply];
1130 - (void)addInput:(in bycopy NSString *)input
1131 client:(in byref id <MMVimClientProtocol>)client
1133 //NSLog(@"addInput:%@ client:%@", input, (id)client);
1135 char_u *s = (char_u*)[input UTF8String];
1138 s = CONVERT_FROM_UTF8(s);
1141 server_to_input_buf(s);
1144 CONVERT_FROM_UTF8_FREE(s);
1147 [self addClient:(id)client];
1149 inputReceived = YES;
1152 - (NSString *)evaluateExpression:(in bycopy NSString *)expr
1153 client:(in byref id <MMVimClientProtocol>)client
1155 //NSLog(@"evaluateExpression:%@ client:%@", expr, (id)client);
1157 NSString *eval = nil;
1158 char_u *s = (char_u*)[expr UTF8String];
1161 s = CONVERT_FROM_UTF8(s);
1164 char_u *res = eval_client_expr_to_string(s);
1167 CONVERT_FROM_UTF8_FREE(s);
1173 s = CONVERT_TO_UTF8(s);
1175 eval = [NSString stringWithUTF8String:(char*)s];
1177 CONVERT_TO_UTF8_FREE(s);
1182 [self addClient:(id)client];
1187 - (void)registerServerWithName:(NSString *)name
1189 NSString *svrName = name;
1190 NSConnection *svrConn = [NSConnection defaultConnection];
1193 for (i = 0; i < MMServerMax; ++i) {
1194 NSString *connName = [self connectionNameFromServerName:svrName];
1196 if ([svrConn registerName:connName]) {
1197 //NSLog(@"Registered server with name: %@", svrName);
1199 // TODO: Set request/reply time-outs to something else?
1201 // Don't wait for requests (time-out means that the message is
1203 [svrConn setRequestTimeout:0];
1204 //[svrConn setReplyTimeout:MMReplyTimeout];
1205 [svrConn setRootObject:self];
1207 char_u *s = (char_u*)[svrName UTF8String];
1209 s = CONVERT_FROM_UTF8(s);
1211 // NOTE: 'serverName' is a global variable
1212 serverName = vim_strsave(s);
1214 CONVERT_FROM_UTF8_FREE(s);
1217 set_vim_var_string(VV_SEND_SERVER, serverName, -1);
1220 need_maketitle = TRUE;
1222 [self queueMessage:SetServerNameMsgID data:
1223 [svrName dataUsingEncoding:NSUTF8StringEncoding]];
1227 svrName = [NSString stringWithFormat:@"%@%d", name, i+1];
1231 - (BOOL)sendToServer:(NSString *)name string:(NSString *)string
1232 reply:(char_u **)reply port:(int *)port expression:(BOOL)expr
1235 // NOTE: If 'name' equals 'serverName' then the request is local (client
1236 // and server are the same). This case is not handled separately, so a
1237 // connection will be set up anyway (this simplifies the code).
1239 NSConnection *conn = [self connectionForServerName:name];
1242 char_u *s = (char_u*)[name UTF8String];
1244 s = CONVERT_FROM_UTF8(s);
1246 EMSG2(_(e_noserver), s);
1248 CONVERT_FROM_UTF8_FREE(s);
1255 // HACK! Assume connection uses mach ports.
1256 *port = [(NSMachPort*)[conn sendPort] machPort];
1259 id proxy = [conn rootProxy];
1260 [proxy setProtocolForProxy:@protocol(MMVimServerProtocol)];
1264 NSString *eval = [proxy evaluateExpression:string client:self];
1267 char_u *r = (char_u*)[eval UTF8String];
1269 r = CONVERT_FROM_UTF8(r);
1271 *reply = vim_strsave(r);
1273 CONVERT_FROM_UTF8_FREE(r);
1276 *reply = vim_strsave((char_u*)_(e_invexprmsg));
1283 [proxy addInput:string client:self];
1286 @catch (NSException *e) {
1287 NSLog(@"WARNING: Caught exception in %s: \"%@\"", _cmd, e);
1294 - (NSArray *)serverList
1296 NSArray *list = nil;
1298 if ([self connection]) {
1299 id proxy = [connection rootProxy];
1300 [proxy setProtocolForProxy:@protocol(MMAppProtocol)];
1303 list = [proxy serverList];
1305 @catch (NSException *e) {
1306 NSLog(@"Exception caught when listing servers: \"%@\"", e);
1309 EMSG(_("E???: No connection to MacVim, server listing not possible."));
1315 - (NSString *)peekForReplyOnPort:(int)port
1317 //NSLog(@"%s%d", _cmd, port);
1319 NSNumber *key = [NSNumber numberWithInt:port];
1320 NSMutableArray *replies = [serverReplyDict objectForKey:key];
1321 if (replies && [replies count]) {
1322 //NSLog(@" %d replies, topmost is: %@", [replies count],
1323 // [replies objectAtIndex:0]);
1324 return [replies objectAtIndex:0];
1327 //NSLog(@" No replies");
1331 - (NSString *)waitForReplyOnPort:(int)port
1333 //NSLog(@"%s%d", _cmd, port);
1335 NSConnection *conn = [self connectionForServerPort:port];
1339 NSNumber *key = [NSNumber numberWithInt:port];
1340 NSMutableArray *replies = nil;
1341 NSString *reply = nil;
1343 // Wait for reply as long as the connection to the server is valid (unless
1344 // user interrupts wait with Ctrl-C).
1345 while (!got_int && [conn isValid] &&
1346 !(replies = [serverReplyDict objectForKey:key])) {
1347 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
1348 beforeDate:[NSDate distantFuture]];
1352 if ([replies count] > 0) {
1353 reply = [[replies objectAtIndex:0] retain];
1354 //NSLog(@" Got reply: %@", reply);
1355 [replies removeObjectAtIndex:0];
1356 [reply autorelease];
1359 if ([replies count] == 0)
1360 [serverReplyDict removeObjectForKey:key];
1366 - (BOOL)sendReply:(NSString *)reply toPort:(int)port
1368 id client = [clientProxyDict objectForKey:[NSNumber numberWithInt:port]];
1371 //NSLog(@"sendReply:%@ toPort:%d", reply, port);
1372 [client addReply:reply server:self];
1375 @catch (NSException *e) {
1376 NSLog(@"WARNING: Exception caught in %s: \"%@\"", _cmd, e);
1379 EMSG2(_("E???: server2client failed; no client with id 0x%x"), port);
1389 @implementation MMBackend (Private)
1391 - (void)handleMessage:(int)msgid data:(NSData *)data
1393 if (InsertTextMsgID == msgid) {
1395 NSString *key = [[NSString alloc] initWithData:data
1396 encoding:NSUTF8StringEncoding];
1397 char_u *str = (char_u*)[key UTF8String];
1398 int i, len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1401 char_u *conv_str = NULL;
1402 if (input_conv.vc_type != CONV_NONE) {
1403 conv_str = string_convert(&input_conv, str, &len);
1409 for (i = 0; i < len; ++i) {
1410 add_to_input_buf(str+i, 1);
1411 if (CSI == str[i]) {
1412 // NOTE: If the converted string contains the byte CSI, then it
1413 // must be followed by the bytes KS_EXTRA, KE_CSI or things
1415 static char_u extra[2] = { KS_EXTRA, KE_CSI };
1416 add_to_input_buf(extra, 2);
1425 } else if (KeyDownMsgID == msgid || CmdKeyMsgID == msgid) {
1427 const void *bytes = [data bytes];
1428 int mods = *((int*)bytes); bytes += sizeof(int);
1429 int len = *((int*)bytes); bytes += sizeof(int);
1430 NSString *key = [[NSString alloc] initWithBytes:bytes length:len
1431 encoding:NSUTF8StringEncoding];
1432 mods = eventModifierFlagsToVimModMask(mods);
1434 [self handleKeyDown:key modifiers:mods];
1437 } else if (SelectTabMsgID == msgid) {
1439 const void *bytes = [data bytes];
1440 int idx = *((int*)bytes) + 1;
1441 //NSLog(@"Selecting tab %d", idx);
1442 send_tabline_event(idx);
1443 } else if (CloseTabMsgID == msgid) {
1445 const void *bytes = [data bytes];
1446 int idx = *((int*)bytes) + 1;
1447 //NSLog(@"Closing tab %d", idx);
1448 send_tabline_menu_event(idx, TABLINE_MENU_CLOSE);
1449 } else if (AddNewTabMsgID == msgid) {
1450 //NSLog(@"Adding new tab");
1451 send_tabline_menu_event(0, TABLINE_MENU_NEW);
1452 } else if (DraggedTabMsgID == msgid) {
1454 const void *bytes = [data bytes];
1455 // NOTE! The destination index is 0 based, so do not add 1 to make it 1
1457 int idx = *((int*)bytes);
1460 } else if (ScrollWheelMsgID == msgid) {
1462 const void *bytes = [data bytes];
1464 int row = *((int*)bytes); bytes += sizeof(int);
1465 int col = *((int*)bytes); bytes += sizeof(int);
1466 int flags = *((int*)bytes); bytes += sizeof(int);
1467 float dy = *((float*)bytes); bytes += sizeof(float);
1469 int button = MOUSE_5;
1470 if (dy > 0) button = MOUSE_4;
1472 flags = eventModifierFlagsToVimMouseModMask(flags);
1474 gui_send_mouse_event(button, col, row, NO, flags);
1475 } else if (MouseDownMsgID == msgid) {
1477 const void *bytes = [data bytes];
1479 int row = *((int*)bytes); bytes += sizeof(int);
1480 int col = *((int*)bytes); bytes += sizeof(int);
1481 int button = *((int*)bytes); bytes += sizeof(int);
1482 int flags = *((int*)bytes); bytes += sizeof(int);
1483 int count = *((int*)bytes); bytes += sizeof(int);
1485 button = eventButtonNumberToVimMouseButton(button);
1486 flags = eventModifierFlagsToVimMouseModMask(flags);
1488 gui_send_mouse_event(button, col, row, count>1, flags);
1489 } else if (MouseUpMsgID == msgid) {
1491 const void *bytes = [data bytes];
1493 int row = *((int*)bytes); bytes += sizeof(int);
1494 int col = *((int*)bytes); bytes += sizeof(int);
1495 int flags = *((int*)bytes); bytes += sizeof(int);
1497 flags = eventModifierFlagsToVimMouseModMask(flags);
1499 gui_send_mouse_event(MOUSE_RELEASE, col, row, NO, flags);
1500 } else if (MouseDraggedMsgID == msgid) {
1502 const void *bytes = [data bytes];
1504 int row = *((int*)bytes); bytes += sizeof(int);
1505 int col = *((int*)bytes); bytes += sizeof(int);
1506 int flags = *((int*)bytes); bytes += sizeof(int);
1508 flags = eventModifierFlagsToVimMouseModMask(flags);
1510 gui_send_mouse_event(MOUSE_DRAG, col, row, NO, flags);
1511 } else if (SetTextDimensionsMsgID == msgid) {
1513 const void *bytes = [data bytes];
1514 int rows = *((int*)bytes); bytes += sizeof(int);
1515 int cols = *((int*)bytes); bytes += sizeof(int);
1517 // NOTE! Vim doesn't call gui_mch_set_shellsize() after
1518 // gui_resize_shell(), so we have to manually set the rows and columns
1519 // here. (MacVim doesn't change the rows and columns to avoid
1520 // inconsistent states between Vim and MacVim.)
1521 [self setRows:rows columns:cols];
1523 //NSLog(@"[VimTask] Resizing shell to %dx%d.", cols, rows);
1524 gui_resize_shell(cols, rows);
1525 } else if (ExecuteMenuMsgID == msgid) {
1527 const void *bytes = [data bytes];
1528 int tag = *((int*)bytes); bytes += sizeof(int);
1530 vimmenu_T *menu = (vimmenu_T*)tag;
1531 // TODO! Make sure 'menu' is a valid menu pointer!
1535 } else if (ToggleToolbarMsgID == msgid) {
1536 char_u go[sizeof(GO_ALL)+2];
1541 p = vim_strchr(go, GO_TOOLBAR);
1545 char_u *end = go + len;
1551 go[len] = GO_TOOLBAR;
1555 set_option_value((char_u*)"guioptions", 0, go, 0);
1557 // Force screen redraw (does it have to be this complicated?).
1558 redraw_all_later(CLEAR);
1559 update_screen(NOT_VALID);
1562 gui_update_cursor(FALSE, FALSE);
1564 } else if (ScrollbarEventMsgID == msgid) {
1566 const void *bytes = [data bytes];
1567 long ident = *((long*)bytes); bytes += sizeof(long);
1568 int hitPart = *((int*)bytes); bytes += sizeof(int);
1569 float fval = *((float*)bytes); bytes += sizeof(float);
1570 scrollbar_T *sb = gui_find_scrollbar(ident);
1573 scrollbar_T *sb_info = sb->wp ? &sb->wp->w_scrollbars[0] : sb;
1574 long value = sb_info->value;
1575 long size = sb_info->size;
1576 long max = sb_info->max;
1577 BOOL isStillDragging = NO;
1578 BOOL updateKnob = YES;
1581 case NSScrollerDecrementPage:
1582 value -= (size > 2 ? size - 2 : 1);
1584 case NSScrollerIncrementPage:
1585 value += (size > 2 ? size - 2 : 1);
1587 case NSScrollerDecrementLine:
1590 case NSScrollerIncrementLine:
1593 case NSScrollerKnob:
1594 isStillDragging = YES;
1596 case NSScrollerKnobSlot:
1597 value = (long)(fval * (max - size + 1));
1604 //NSLog(@"value %d -> %d", sb_info->value, value);
1605 gui_drag_scrollbar(sb, value, isStillDragging);
1608 // Dragging the knob or option+clicking automatically updates
1609 // the knob position (on the actual NSScroller), so we only
1610 // need to set the knob position in the other cases.
1612 // Update both the left&right vertical scrollbars.
1613 long identLeft = sb->wp->w_scrollbars[SBAR_LEFT].ident;
1614 long identRight = sb->wp->w_scrollbars[SBAR_RIGHT].ident;
1615 [self setScrollbarThumbValue:value size:size max:max
1616 identifier:identLeft];
1617 [self setScrollbarThumbValue:value size:size max:max
1618 identifier:identRight];
1620 // Update the horizontal scrollbar.
1621 [self setScrollbarThumbValue:value size:size max:max
1626 } else if (SetFontMsgID == msgid) {
1628 const void *bytes = [data bytes];
1629 float pointSize = *((float*)bytes); bytes += sizeof(float);
1630 //unsigned len = *((unsigned*)bytes); bytes += sizeof(unsigned);
1631 bytes += sizeof(unsigned); // len not used
1633 NSMutableString *name = [NSMutableString stringWithUTF8String:bytes];
1634 [name appendString:[NSString stringWithFormat:@":h%.2f", pointSize]];
1635 char_u *s = (char_u*)[name UTF8String];
1638 s = CONVERT_FROM_UTF8(s);
1641 set_option_value((char_u*)"guifont", 0, s, 0);
1644 CONVERT_FROM_UTF8_FREE(s);
1647 // Force screen redraw (does it have to be this complicated?).
1648 redraw_all_later(CLEAR);
1649 update_screen(NOT_VALID);
1652 gui_update_cursor(FALSE, FALSE);
1654 } else if (VimShouldCloseMsgID == msgid) {
1656 } else if (DropFilesMsgID == msgid) {
1658 const void *bytes = [data bytes];
1659 const void *end = [data bytes] + [data length];
1660 int n = *((int*)bytes); bytes += sizeof(int);
1662 if (State & CMDLINE) {
1663 // HACK! If Vim is in command line mode then the files names
1664 // should be added to the command line, instead of opening the
1665 // files in tabs. This is taken care of by gui_handle_drop().
1666 char_u **fnames = (char_u **)alloc(n * sizeof(char_u *));
1669 while (bytes < end && i < n) {
1670 int len = *((int*)bytes); bytes += sizeof(int);
1671 char_u *s = (char_u*)bytes;
1673 s = CONVERT_FROM_UTF8(s);
1675 fnames[i++] = vim_strsave(s);
1677 CONVERT_FROM_UTF8_FREE(s);
1682 // NOTE! This function will free 'fnames'.
1683 // HACK! It is assumed that the 'x' and 'y' arguments are
1684 // unused when in command line mode.
1685 gui_handle_drop(0, 0, 0, fnames, i < n ? i : n);
1688 // HACK! I'm not sure how to get Vim to open a list of files in
1689 // tabs, so instead I create a ':tab drop' command with all the
1690 // files to open and execute it.
1691 NSMutableString *cmd = (n > 1)
1692 ? [NSMutableString stringWithString:@":tab drop"]
1693 : [NSMutableString stringWithString:@":drop"];
1696 for (i = 0; i < n && bytes < end; ++i) {
1697 int len = *((int*)bytes); bytes += sizeof(int);
1698 NSMutableString *file =
1699 [NSMutableString stringWithUTF8String:bytes];
1700 [file replaceOccurrencesOfString:@" "
1703 range:NSMakeRange(0,[file length])];
1706 [cmd appendString:@" "];
1707 [cmd appendString:file];
1710 // By going to the last tabpage we ensure that the new tabs will
1711 // appear last (if this call is left out, the taborder becomes
1715 char_u *s = (char_u*)[cmd UTF8String];
1717 s = CONVERT_FROM_UTF8(s);
1721 CONVERT_FROM_UTF8_FREE(s);
1724 // Force screen redraw (does it have to be this complicated?).
1725 // (This code was taken from the end of gui_handle_drop().)
1726 update_screen(NOT_VALID);
1729 gui_update_cursor(FALSE, FALSE);
1733 } else if (DropStringMsgID == msgid) {
1735 char_u dropkey[3] = { CSI, KS_EXTRA, (char_u)KE_DROP };
1736 const void *bytes = [data bytes];
1737 int len = *((int*)bytes); bytes += sizeof(int);
1738 NSMutableString *string = [NSMutableString stringWithUTF8String:bytes];
1740 // Replace unrecognized end-of-line sequences with \x0a (line feed).
1741 NSRange range = { 0, [string length] };
1742 unsigned n = [string replaceOccurrencesOfString:@"\x0d\x0a"
1743 withString:@"\x0a" options:0
1746 n = [string replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
1747 options:0 range:range];
1750 len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1751 char_u *s = (char_u*)[string UTF8String];
1753 if (input_conv.vc_type != CONV_NONE)
1754 s = string_convert(&input_conv, s, &len);
1756 dnd_yank_drag_data(s, len);
1758 if (input_conv.vc_type != CONV_NONE)
1761 add_to_input_buf(dropkey, sizeof(dropkey));
1763 } else if (GotFocusMsgID == msgid) {
1765 [self focusChange:YES];
1766 } else if (LostFocusMsgID == msgid) {
1768 [self focusChange:NO];
1769 } else if (MouseMovedMsgID == msgid) {
1770 const void *bytes = [data bytes];
1771 int row = *((int*)bytes); bytes += sizeof(int);
1772 int col = *((int*)bytes); bytes += sizeof(int);
1774 gui_mouse_moved(col, row);
1775 } else if (SetMouseShapeMsgID == msgid) {
1776 const void *bytes = [data bytes];
1777 int shape = *((int*)bytes); bytes += sizeof(int);
1778 update_mouseshape(shape);
1780 NSLog(@"WARNING: Unknown message received (msgid=%d)", msgid);
1784 + (NSDictionary *)specialKeys
1786 static NSDictionary *specialKeys = nil;
1789 NSBundle *mainBundle = [NSBundle mainBundle];
1790 NSString *path = [mainBundle pathForResource:@"SpecialKeys"
1792 specialKeys = [[NSDictionary alloc] initWithContentsOfFile:path];
1798 - (void)handleKeyDown:(NSString *)key modifiers:(int)mods
1802 char_u *chars = (char_u*)[key UTF8String];
1804 char_u *conv_str = NULL;
1806 int length = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1808 // Special keys (arrow keys, function keys, etc.) are stored in a plist so
1809 // that new keys can easily be added.
1810 NSString *specialString = [[MMBackend specialKeys]
1812 if (specialString && [specialString length] > 1) {
1813 //NSLog(@"special key: %@", specialString);
1814 int ikey = TO_SPECIAL([specialString characterAtIndex:0],
1815 [specialString characterAtIndex:1]);
1817 ikey = simplify_key(ikey, &mods);
1822 special[1] = K_SECOND(ikey);
1823 special[2] = K_THIRD(ikey);
1827 } else if (1 == length && TAB == chars[0]) {
1828 // Tab is a trouble child:
1829 // - <Tab> is added to the input buffer as is
1830 // - <S-Tab> is translated to, {CSI,'k','B'} (i.e. 'Back-tab')
1831 // - <M-Tab> should be 0x80|TAB but this is not valid utf-8 so it needs
1832 // to be converted to utf-8
1833 // - <S-M-Tab> is translated to <S-Tab> with ALT modifier
1834 // - <C-Tab> is reserved by Mac OS X
1835 // - <D-Tab> is reserved by Mac OS X
1840 if (mods & MOD_MASK_SHIFT) {
1841 mods &= ~MOD_MASK_SHIFT;
1843 special[1] = K_SECOND(K_S_TAB);
1844 special[2] = K_THIRD(K_S_TAB);
1846 } else if (mods & MOD_MASK_ALT) {
1847 int mtab = 0x80 | TAB;
1850 special[0] = (mtab >> 6) + 0xc0;
1851 special[1] = mtab & 0xbf;
1857 mods &= ~MOD_MASK_ALT;
1859 } else if (length > 0) {
1860 unichar c = [key characterAtIndex:0];
1862 //NSLog(@"non-special: %@ (hex=%x, mods=%d)", key,
1863 // [key characterAtIndex:0], mods);
1865 if (length == 1 && ((c == Ctrl_C && ctrl_c_interrupts)
1866 || (c == intr_char && intr_char != Ctrl_C))) {
1871 // HACK! In most circumstances the Ctrl and Shift modifiers should be
1872 // cleared since they are already added to the key by the AppKit.
1873 // Unfortunately, the only way to deal with when to clear the modifiers
1874 // or not seems to be to have hard-wired rules like this.
1875 if ( !((' ' == c) || (0xa0 == c) || (mods & MOD_MASK_CMD)
1877 mods &= ~MOD_MASK_SHIFT;
1878 mods &= ~MOD_MASK_CTRL;
1879 //NSLog(@"clear shift ctrl");
1882 // HACK! All Option+key presses go via 'insert text' messages, except
1883 // for <M-Space>. If the Alt flag is not cleared for <M-Space> it does
1884 // not work to map to it.
1885 if (0xa0 == c && !(mods & MOD_MASK_CMD)) {
1886 //NSLog(@"clear alt");
1887 mods &= ~MOD_MASK_ALT;
1891 if (input_conv.vc_type != CONV_NONE) {
1892 conv_str = string_convert(&input_conv, chars, &length);
1899 if (chars && length > 0) {
1901 //NSLog(@"adding mods: %d", mods);
1903 modChars[1] = KS_MODIFIER;
1905 add_to_input_buf(modChars, 3);
1908 //NSLog(@"add to input buf: 0x%x", chars[0]);
1909 // TODO: Check for CSI bytes?
1910 add_to_input_buf(chars, length);
1919 - (void)queueMessage:(int)msgid data:(NSData *)data
1921 [queue addObject:[NSData dataWithBytes:&msgid length:sizeof(int)]];
1923 [queue addObject:data];
1925 [queue addObject:[NSData data]];
1928 - (void)connectionDidDie:(NSNotification *)notification
1930 // If the main connection to MacVim is lost this means that MacVim was
1931 // either quit (by the user chosing Quit on the MacVim menu), or it has
1932 // crashed. In either case our only option is to quit now.
1933 // TODO: Write backup file?
1935 //NSLog(@"A Vim process lots its connection to MacVim; quitting.");
1939 - (void)blinkTimerFired:(NSTimer *)timer
1941 NSTimeInterval timeInterval = 0;
1943 [blinkTimer release];
1946 if (MMBlinkStateOn == blinkState) {
1947 gui_undraw_cursor();
1948 blinkState = MMBlinkStateOff;
1949 timeInterval = blinkOffInterval;
1950 } else if (MMBlinkStateOff == blinkState) {
1951 gui_update_cursor(TRUE, FALSE);
1952 blinkState = MMBlinkStateOn;
1953 timeInterval = blinkOnInterval;
1956 if (timeInterval > 0) {
1958 [[NSTimer scheduledTimerWithTimeInterval:timeInterval target:self
1959 selector:@selector(blinkTimerFired:)
1960 userInfo:nil repeats:NO] retain];
1961 [self flushQueue:YES];
1965 - (void)focusChange:(BOOL)on
1967 gui_focus_change(on);
1970 - (void)processInputBegin
1972 inProcessInput = YES;
1974 // Don't flush too soon or update speed will suffer.
1975 [lastFlushDate release];
1976 lastFlushDate = [[NSDate date] retain];
1979 - (void)processInputEnd
1981 #if MM_USE_INPUT_QUEUE
1982 int count = [inputQueue count];
1984 // TODO: This is troubling, but it is not hard to get Vim to end up
1985 // here. Why does this happen?
1986 NSLog(@"WARNING: inputQueue has odd number of objects (%d)", count);
1987 [inputQueue removeAllObjects];
1988 } else if (count > 0) {
1989 // TODO: Dispatch these messages? Maybe not; usually when the
1990 // 'inputQueue' is non-empty it means that a LOT of messages has been
1991 // sent simultaneously. The only way this happens is when Vim is being
1992 // tormented, e.g. if the user holds down <D-`> to rapidly switch
1995 for (i = 0; i < count; i+=2) {
1996 int msgid = [[inputQueue objectAtIndex:i] intValue];
1997 NSLog(@"%s: Dropping message %s", _cmd, MessageStrings[msgid]);
2000 [inputQueue removeAllObjects];
2004 inputReceived = YES;
2005 inProcessInput = NO;
2008 - (NSString *)connectionNameFromServerName:(NSString *)name
2010 NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
2012 return [[NSString stringWithFormat:@"%@.%@", bundleIdentifier, name]
2016 - (NSConnection *)connectionForServerName:(NSString *)name
2018 // TODO: Try 'name%d' if 'name' fails.
2019 NSString *connName = [self connectionNameFromServerName:name];
2020 NSConnection *svrConn = [connectionNameDict objectForKey:connName];
2023 svrConn = [NSConnection connectionWithRegisteredName:connName
2025 // Try alternate server...
2026 if (!svrConn && alternateServerName) {
2027 //NSLog(@" trying to connect to alternate server: %@",
2028 // alternateServerName);
2029 connName = [self connectionNameFromServerName:alternateServerName];
2030 svrConn = [NSConnection connectionWithRegisteredName:connName
2034 // Try looking for alternate servers...
2036 //NSLog(@" looking for alternate servers...");
2037 NSString *alt = [self alternateServerNameForName:name];
2038 if (alt != alternateServerName) {
2039 //NSLog(@" found alternate server: %@", string);
2040 [alternateServerName release];
2041 alternateServerName = [alt copy];
2045 // Try alternate server again...
2046 if (!svrConn && alternateServerName) {
2047 //NSLog(@" trying to connect to alternate server: %@",
2048 // alternateServerName);
2049 connName = [self connectionNameFromServerName:alternateServerName];
2050 svrConn = [NSConnection connectionWithRegisteredName:connName
2055 [connectionNameDict setObject:svrConn forKey:connName];
2057 //NSLog(@"Adding %@ as connection observer for %@", self, svrConn);
2058 [[NSNotificationCenter defaultCenter] addObserver:self
2059 selector:@selector(serverConnectionDidDie:)
2060 name:NSConnectionDidDieNotification object:svrConn];
2067 - (NSConnection *)connectionForServerPort:(int)port
2070 NSEnumerator *e = [connectionNameDict objectEnumerator];
2072 while ((conn = [e nextObject])) {
2073 // HACK! Assume connection uses mach ports.
2074 if (port == [(NSMachPort*)[conn sendPort] machPort])
2081 - (void)serverConnectionDidDie:(NSNotification *)notification
2083 //NSLog(@"%s%@", _cmd, notification);
2085 NSConnection *svrConn = [notification object];
2087 //NSLog(@"Removing %@ as connection observer from %@", self, svrConn);
2088 [[NSNotificationCenter defaultCenter]
2090 name:NSConnectionDidDieNotification
2093 [connectionNameDict removeObjectsForKeys:
2094 [connectionNameDict allKeysForObject:svrConn]];
2096 // HACK! Assume connection uses mach ports.
2097 int port = [(NSMachPort*)[svrConn sendPort] machPort];
2098 NSNumber *key = [NSNumber numberWithInt:port];
2100 [clientProxyDict removeObjectForKey:key];
2101 [serverReplyDict removeObjectForKey:key];
2104 - (void)addClient:(NSDistantObject *)client
2106 NSConnection *conn = [client connectionForProxy];
2107 // HACK! Assume connection uses mach ports.
2108 int port = [(NSMachPort*)[conn sendPort] machPort];
2109 NSNumber *key = [NSNumber numberWithInt:port];
2111 if (![clientProxyDict objectForKey:key]) {
2112 [client setProtocolForProxy:@protocol(MMVimClientProtocol)];
2113 [clientProxyDict setObject:client forKey:key];
2116 // NOTE: 'clientWindow' is a global variable which is used by <client>
2117 clientWindow = port;
2120 - (NSString *)alternateServerNameForName:(NSString *)name
2122 if (!(name && [name length] > 0))
2125 // Only look for alternates if 'name' doesn't end in a digit.
2126 unichar lastChar = [name characterAtIndex:[name length]-1];
2127 if (lastChar >= '0' && lastChar <= '9')
2130 // Look for alternates among all current servers.
2131 NSArray *list = [self serverList];
2132 if (!(list && [list count] > 0))
2135 // Filter out servers starting with 'name' and ending with a number. The
2136 // (?i) pattern ensures that the match is case insensitive.
2137 NSString *pat = [NSString stringWithFormat:@"(?i)%@[0-9]+\\z", name];
2138 NSPredicate *pred = [NSPredicate predicateWithFormat:
2139 @"SELF MATCHES %@", pat];
2140 list = [list filteredArrayUsingPredicate:pred];
2141 if ([list count] > 0) {
2142 list = [list sortedArrayUsingSelector:@selector(serverNameCompare:)];
2143 return [list objectAtIndex:0];
2149 @end // MMBackend (Private)
2154 @implementation NSString (MMServerNameCompare)
2155 - (NSComparisonResult)serverNameCompare:(NSString *)string
2157 return [self compare:string
2158 options:NSCaseInsensitiveSearch|NSNumericSearch];
2165 static int eventModifierFlagsToVimModMask(int modifierFlags)
2169 if (modifierFlags & NSShiftKeyMask)
2170 modMask |= MOD_MASK_SHIFT;
2171 if (modifierFlags & NSControlKeyMask)
2172 modMask |= MOD_MASK_CTRL;
2173 if (modifierFlags & NSAlternateKeyMask)
2174 modMask |= MOD_MASK_ALT;
2175 if (modifierFlags & NSCommandKeyMask)
2176 modMask |= MOD_MASK_CMD;
2181 static int vimModMaskToEventModifierFlags(int mods)
2185 if (mods & MOD_MASK_SHIFT)
2186 flags |= NSShiftKeyMask;
2187 if (mods & MOD_MASK_CTRL)
2188 flags |= NSControlKeyMask;
2189 if (mods & MOD_MASK_ALT)
2190 flags |= NSAlternateKeyMask;
2191 if (mods & MOD_MASK_CMD)
2192 flags |= NSCommandKeyMask;
2197 static int eventModifierFlagsToVimMouseModMask(int modifierFlags)
2201 if (modifierFlags & NSShiftKeyMask)
2202 modMask |= MOUSE_SHIFT;
2203 if (modifierFlags & NSControlKeyMask)
2204 modMask |= MOUSE_CTRL;
2205 if (modifierFlags & NSAlternateKeyMask)
2206 modMask |= MOUSE_ALT;
2211 static int eventButtonNumberToVimMouseButton(int buttonNumber)
2213 static int mouseButton[] = { MOUSE_LEFT, MOUSE_RIGHT, MOUSE_MIDDLE,
2214 MOUSE_X1, MOUSE_X2 };
2216 return mouseButton[buttonNumber < 5 ? buttonNumber : 0];
2219 static int specialKeyToNSKey(int key)
2221 if (!IS_SPECIAL(key))
2228 { K_UP, NSUpArrowFunctionKey },
2229 { K_DOWN, NSDownArrowFunctionKey },
2230 { K_LEFT, NSLeftArrowFunctionKey },
2231 { K_RIGHT, NSRightArrowFunctionKey },
2232 { K_F1, NSF1FunctionKey },
2233 { K_F2, NSF2FunctionKey },
2234 { K_F3, NSF3FunctionKey },
2235 { K_F4, NSF4FunctionKey },
2236 { K_F5, NSF5FunctionKey },
2237 { K_F6, NSF6FunctionKey },
2238 { K_F7, NSF7FunctionKey },
2239 { K_F8, NSF8FunctionKey },
2240 { K_F9, NSF9FunctionKey },
2241 { K_F10, NSF10FunctionKey },
2242 { K_F11, NSF11FunctionKey },
2243 { K_F12, NSF12FunctionKey },
2244 { K_F13, NSF13FunctionKey },
2245 { K_F14, NSF14FunctionKey },
2246 { K_F15, NSF15FunctionKey },
2247 { K_F16, NSF16FunctionKey },
2248 { K_F17, NSF17FunctionKey },
2249 { K_F18, NSF18FunctionKey },
2250 { K_F19, NSF19FunctionKey },
2251 { K_F20, NSF20FunctionKey },
2252 { K_F21, NSF21FunctionKey },
2253 { K_F22, NSF22FunctionKey },
2254 { K_F23, NSF23FunctionKey },
2255 { K_F24, NSF24FunctionKey },
2256 { K_F25, NSF25FunctionKey },
2257 { K_F26, NSF26FunctionKey },
2258 { K_F27, NSF27FunctionKey },
2259 { K_F28, NSF28FunctionKey },
2260 { K_F29, NSF29FunctionKey },
2261 { K_F30, NSF30FunctionKey },
2262 { K_F31, NSF31FunctionKey },
2263 { K_F32, NSF32FunctionKey },
2264 { K_F33, NSF33FunctionKey },
2265 { K_F34, NSF34FunctionKey },
2266 { K_F35, NSF35FunctionKey },
2267 { K_DEL, NSBackspaceCharacter },
2268 { K_BS, NSDeleteCharacter },
2269 { K_HOME, NSHomeFunctionKey },
2270 { K_END, NSEndFunctionKey },
2271 { K_PAGEUP, NSPageUpFunctionKey },
2272 { K_PAGEDOWN, NSPageDownFunctionKey }
2276 for (i = 0; i < sizeof(sp2ns)/sizeof(sp2ns[0]); ++i) {
2277 if (sp2ns[i].special == key)
2278 return sp2ns[i].nskey;