Always open a dropped file in new tab
[MacVim/jjgod.git] / src / MacVim / MMBackend.m
blobb440f2b0707eadc0da2cb95eae308837a0c6073c
1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
2  *
3  * VIM - Vi IMproved            by Bram Moolenaar
4  *                              MacVim GUI port by Bjorn Winckler
5  *
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.
9  */
11 #import "MMBackend.h"
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.  Also note that
17 // 'transp' is assumed to be a value between 0 and 100.
18 #define MM_COLOR(col) ((unsigned)( ((col)&0xffffff) | 0xff000000 ))
19 #define MM_COLOR_WITH_TRANSP(col,transp) \
20     ((unsigned)( ((col)&0xffffff) \
21         | ((((unsigned)((((100-(transp))*255)/100)+.5f))&0xff)<<24) ))
24 // This constant controls how often the command queue may be flushed.  If it is
25 // too small the app might feel unresponsive; if it is too large there might be
26 // long periods without the screen updating (e.g. when sourcing a large session
27 // file).  (The unit is seconds.)
28 static float MMFlushTimeoutInterval = 0.1f;
29 static int MMFlushQueueLenHint = 80*40;
31 static unsigned MMServerMax = 1000;
33 // NOTE: The default font is bundled with the application.
34 static NSString *MMDefaultFontName = @"DejaVu Sans Mono";
35 static float MMDefaultFontSize = 12.0f;
37 // TODO: Move to separate file.
38 static int eventModifierFlagsToVimModMask(int modifierFlags);
39 static int vimModMaskToEventModifierFlags(int mods);
40 static int eventModifierFlagsToVimMouseModMask(int modifierFlags);
41 static int eventButtonNumberToVimMouseButton(int buttonNumber);
42 static int specialKeyToNSKey(int key);
44 enum {
45     MMBlinkStateNone = 0,
46     MMBlinkStateOn,
47     MMBlinkStateOff
52 @interface NSString (MMServerNameCompare)
53 - (NSComparisonResult)serverNameCompare:(NSString *)string;
54 @end
58 @interface MMBackend (Private)
59 - (void)processInputQueue;
60 - (void)handleInputEvent:(int)msgid data:(NSData *)data;
61 + (NSDictionary *)specialKeys;
62 - (void)handleInsertText:(NSData *)data;
63 - (void)handleKeyDown:(NSString *)key modifiers:(int)mods;
64 - (void)queueMessage:(int)msgid data:(NSData *)data;
65 - (void)connectionDidDie:(NSNotification *)notification;
66 - (void)blinkTimerFired:(NSTimer *)timer;
67 - (void)focusChange:(BOOL)on;
68 - (void)handleToggleToolbar;
69 - (void)handleScrollbarEvent:(NSData *)data;
70 - (void)handleSetFont:(NSData *)data;
71 - (void)handleDropFiles:(NSData *)data;
72 - (void)handleDropString:(NSData *)data;
73 @end
77 @interface MMBackend (ClientServer)
78 - (NSString *)connectionNameFromServerName:(NSString *)name;
79 - (NSConnection *)connectionForServerName:(NSString *)name;
80 - (NSConnection *)connectionForServerPort:(int)port;
81 - (void)serverConnectionDidDie:(NSNotification *)notification;
82 - (void)addClient:(NSDistantObject *)client;
83 - (NSString *)alternateServerNameForName:(NSString *)name;
84 @end
88 @implementation MMBackend
90 + (MMBackend *)sharedInstance
92     static MMBackend *singleton = nil;
93     return singleton ? singleton : (singleton = [MMBackend new]);
96 - (id)init
98     if ((self = [super init])) {
99         fontContainerRef = loadFonts();
101         outputQueue = [[NSMutableArray alloc] init];
102         inputQueue = [[NSMutableArray alloc] init];
103         drawData = [[NSMutableData alloc] initWithCapacity:1024];
104         connectionNameDict = [[NSMutableDictionary alloc] init];
105         clientProxyDict = [[NSMutableDictionary alloc] init];
106         serverReplyDict = [[NSMutableDictionary alloc] init];
108         NSString *path = [[NSBundle mainBundle] pathForResource:@"Colors"
109                                                          ofType:@"plist"];
110         if (path) {
111             colorDict = [[NSDictionary dictionaryWithContentsOfFile:path]
112                 retain];
113         } else {
114             NSLog(@"WARNING: Could not locate Colors.plist.");
115         }
117         path = [[NSBundle mainBundle] pathForResource:@"SystemColors"
118                                                ofType:@"plist"];
119         if (path) {
120             sysColorDict = [[NSDictionary dictionaryWithContentsOfFile:path]
121                 retain];
122         } else {
123             NSLog(@"WARNING: Could not locate SystemColors.plist.");
124         }
125     }
127     return self;
130 - (void)dealloc
132     //NSLog(@"%@ %s", [self className], _cmd);
133     [[NSNotificationCenter defaultCenter] removeObserver:self];
135     [blinkTimer release];  blinkTimer = nil;
136     [alternateServerName release];  alternateServerName = nil;
137     [serverReplyDict release];  serverReplyDict = nil;
138     [clientProxyDict release];  clientProxyDict = nil;
139     [connectionNameDict release];  connectionNameDict = nil;
140     [inputQueue release];  inputQueue = nil;
141     [outputQueue release];  outputQueue = nil;
142     [drawData release];  drawData = nil;
143     [frontendProxy release];  frontendProxy = nil;
144     [connection release];  connection = nil;
145     [sysColorDict release];  sysColorDict = nil;
146     [colorDict release];  colorDict = nil;
148     [super dealloc];
151 - (void)setBackgroundColor:(int)color
153     backgroundColor = MM_COLOR_WITH_TRANSP(color,p_transp);
156 - (void)setForegroundColor:(int)color
158     foregroundColor = MM_COLOR(color);
161 - (void)setSpecialColor:(int)color
163     specialColor = MM_COLOR(color);
166 - (void)setDefaultColorsBackground:(int)bg foreground:(int)fg
168     defaultBackgroundColor = MM_COLOR_WITH_TRANSP(bg,p_transp);
169     defaultForegroundColor = MM_COLOR(fg);
171     NSMutableData *data = [NSMutableData data];
173     [data appendBytes:&defaultBackgroundColor length:sizeof(unsigned)];
174     [data appendBytes:&defaultForegroundColor length:sizeof(unsigned)];
176     [self queueMessage:SetDefaultColorsMsgID data:data];
179 - (NSConnection *)connection
181     if (!connection) {
182         // NOTE!  If the name of the connection changes here it must also be
183         // updated in MMAppController.m.
184         NSString *name = [NSString stringWithFormat:@"%@-connection",
185                [[NSBundle mainBundle] bundleIdentifier]];
187         connection = [NSConnection connectionWithRegisteredName:name host:nil];
188         [connection retain];
189     }
191     // NOTE: 'connection' may be nil here.
192     return connection;
195 - (BOOL)checkin
197     if (![self connection]) {
198         NSBundle *mainBundle = [NSBundle mainBundle];
199 #if 0
200         NSString *path = [mainBundle bundlePath];
201         if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
202             NSLog(@"WARNING: Failed to launch GUI with path %@", path);
203             return NO;
204         }
205 #else
206         // HACK!  It would be preferable to launch the GUI using NSWorkspace,
207         // however I have not managed to figure out how to pass arguments using
208         // NSWorkspace.
209         //
210         // NOTE!  Using NSTask to launch the GUI has the negative side-effect
211         // that the GUI won't be activated (or raised) so there is a hack in
212         // MMWindowController which always raises the app when a new window is
213         // opened.
214         NSMutableArray *args = [NSMutableArray arrayWithObjects:
215             [NSString stringWithFormat:@"-%@", MMNoWindowKey], @"yes", nil];
216         NSString *exeName = [[mainBundle infoDictionary]
217                 objectForKey:@"CFBundleExecutable"];
218         NSString *path = [mainBundle pathForAuxiliaryExecutable:exeName];
219         if (!path) {
220             NSLog(@"ERROR: Could not find MacVim executable in bundle");
221             return NO;
222         }
224         [NSTask launchedTaskWithLaunchPath:path arguments:args];
225 #endif
227         // HACK!  The NSWorkspaceDidLaunchApplicationNotification does not work
228         // for tasks like this, so poll the mach bootstrap server until it
229         // returns a valid connection.  Also set a time-out date so that we
230         // don't get stuck doing this forever.
231         NSDate *timeOutDate = [NSDate dateWithTimeIntervalSinceNow:15];
232         while (!connection &&
233                 NSOrderedDescending == [timeOutDate compare:[NSDate date]])
234         {
235             [[NSRunLoop currentRunLoop]
236                     runMode:NSDefaultRunLoopMode
237                  beforeDate:[NSDate dateWithTimeIntervalSinceNow:1]];
239             // NOTE: This call will set 'connection' as a side-effect.
240             [self connection];
241         }
243         if (!connection) {
244             NSLog(@"WARNING: Timed-out waiting for GUI to launch.");
245             return NO;
246         }
247     }
249     id proxy = [connection rootProxy];
250     [proxy setProtocolForProxy:@protocol(MMAppProtocol)];
252     [[NSNotificationCenter defaultCenter] addObserver:self
253             selector:@selector(connectionDidDie:)
254                 name:NSConnectionDidDieNotification object:connection];
256     int pid = [[NSProcessInfo processInfo] processIdentifier];
258     @try {
259         frontendProxy = [proxy connectBackend:self pid:pid];
260     }
261     @catch (NSException *e) {
262         NSLog(@"Exception caught when trying to connect backend: \"%@\"", e);
263     }
265     if (frontendProxy) {
266         [frontendProxy retain];
267         [frontendProxy setProtocolForProxy:@protocol(MMAppProtocol)];
268     }
270     return connection && frontendProxy;
273 - (BOOL)openVimWindow
275     [self queueMessage:OpenVimWindowMsgID data:nil];
276     return YES;
279 - (void)clearAll
281     int type = ClearAllDrawType;
283     // Any draw commands in queue are effectively obsolete since this clearAll
284     // will negate any effect they have, therefore we may as well clear the
285     // draw queue.
286     [drawData setLength:0];
288     [drawData appendBytes:&type length:sizeof(int)];
291 - (void)clearBlockFromRow:(int)row1 column:(int)col1
292                     toRow:(int)row2 column:(int)col2
294     int type = ClearBlockDrawType;
296     [drawData appendBytes:&type length:sizeof(int)];
298     [drawData appendBytes:&defaultBackgroundColor length:sizeof(unsigned)];
299     [drawData appendBytes:&row1 length:sizeof(int)];
300     [drawData appendBytes:&col1 length:sizeof(int)];
301     [drawData appendBytes:&row2 length:sizeof(int)];
302     [drawData appendBytes:&col2 length:sizeof(int)];
305 - (void)deleteLinesFromRow:(int)row count:(int)count
306               scrollBottom:(int)bottom left:(int)left right:(int)right
308     int type = DeleteLinesDrawType;
310     [drawData appendBytes:&type length:sizeof(int)];
312     [drawData appendBytes:&defaultBackgroundColor length:sizeof(unsigned)];
313     [drawData appendBytes:&row length:sizeof(int)];
314     [drawData appendBytes:&count length:sizeof(int)];
315     [drawData appendBytes:&bottom length:sizeof(int)];
316     [drawData appendBytes:&left length:sizeof(int)];
317     [drawData appendBytes:&right length:sizeof(int)];
320 - (void)replaceString:(char*)s length:(int)len row:(int)row column:(int)col
321                 flags:(int)flags
323     if (len <= 0) return;
325     int type = ReplaceStringDrawType;
327     [drawData appendBytes:&type length:sizeof(int)];
329     [drawData appendBytes:&backgroundColor length:sizeof(unsigned)];
330     [drawData appendBytes:&foregroundColor length:sizeof(unsigned)];
331     [drawData appendBytes:&specialColor length:sizeof(unsigned)];
332     [drawData appendBytes:&row length:sizeof(int)];
333     [drawData appendBytes:&col length:sizeof(int)];
334     [drawData appendBytes:&flags length:sizeof(int)];
335     [drawData appendBytes:&len length:sizeof(int)];
336     [drawData appendBytes:s length:len];
339 - (void)insertLinesFromRow:(int)row count:(int)count
340               scrollBottom:(int)bottom left:(int)left right:(int)right
342     int type = InsertLinesDrawType;
344     [drawData appendBytes:&type length:sizeof(int)];
346     [drawData appendBytes:&defaultBackgroundColor length:sizeof(unsigned)];
347     [drawData appendBytes:&row length:sizeof(int)];
348     [drawData appendBytes:&count length:sizeof(int)];
349     [drawData appendBytes:&bottom length:sizeof(int)];
350     [drawData appendBytes:&left length:sizeof(int)];
351     [drawData appendBytes:&right length:sizeof(int)];
354 - (void)drawCursorAtRow:(int)row column:(int)col shape:(int)shape
355                fraction:(int)percent color:(int)color
357     int type = DrawCursorDrawType;
358     unsigned uc = MM_COLOR(color);
360     [drawData appendBytes:&type length:sizeof(int)];
362     [drawData appendBytes:&uc length:sizeof(unsigned)];
363     [drawData appendBytes:&row length:sizeof(int)];
364     [drawData appendBytes:&col length:sizeof(int)];
365     [drawData appendBytes:&shape length:sizeof(int)];
366     [drawData appendBytes:&percent length:sizeof(int)];
369 - (void)update
371     // Tend to the run loop, returning immediately if there are no events
372     // waiting.
373     [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
374                              beforeDate:[NSDate distantPast]];
376     // Keyboard and mouse input is handled directly, other input is queued and
377     // processed here.  This call may enter a blocking loop.
378     if ([inputQueue count] > 0)
379         [self processInputQueue];
382 - (void)flushQueue:(BOOL)force
384     // NOTE! This method gets called a lot; if we were to flush every time it
385     // got called MacVim would feel unresponsive.  So there is a time out which
386     // ensures that the queue isn't flushed too often.
387     if (!force && lastFlushDate && -[lastFlushDate timeIntervalSinceNow]
388             < MMFlushTimeoutInterval
389             && [drawData length] < MMFlushQueueLenHint)
390         return;
392     if ([drawData length] > 0) {
393         [self queueMessage:BatchDrawMsgID data:[drawData copy]];
394         [drawData setLength:0];
395     }
397     if ([outputQueue count] > 0) {
398         @try {
399             [frontendProxy processCommandQueue:outputQueue];
400         }
401         @catch (NSException *e) {
402             NSLog(@"Exception caught when processing command queue: \"%@\"", e);
403         }
405         [outputQueue removeAllObjects];
407         [lastFlushDate release];
408         lastFlushDate = [[NSDate date] retain];
409     }
412 - (BOOL)waitForInput:(int)milliseconds
414     //NSLog(@"|ENTER| %s%d",  _cmd, milliseconds);
415     NSDate *date = milliseconds > 0 ?
416             [NSDate dateWithTimeIntervalSinceNow:.001*milliseconds] : 
417             [NSDate distantFuture];
419     [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:date];
421     // I know of no way to figure out if the run loop exited because input was
422     // found or because of a time out, so I need to manually indicate when
423     // input was received in processInput:data: and then reset it every time
424     // here.
425     BOOL yn = inputReceived;
426     inputReceived = NO;
428     if ([inputQueue count] > 0)
429         [self processInputQueue];
431     //NSLog(@"|LEAVE| %s input=%d", _cmd, yn);
432     return yn;
435 - (void)exit
437 #ifdef MAC_CLIENTSERVER
438     // The default connection is used for the client/server code.
439     [[NSConnection defaultConnection] setRootObject:nil];
440     [[NSConnection defaultConnection] invalidate];
441 #endif
443     // By invalidating the NSConnection the MMWindowController immediately
444     // finds out that the connection is down and as a result
445     // [MMWindowController connectionDidDie:] is invoked.
446     //NSLog(@"%@ %s", [self className], _cmd);
447     [[NSNotificationCenter defaultCenter] removeObserver:self];
448     [connection invalidate];
450     if (fontContainerRef) {
451         ATSFontDeactivate(fontContainerRef, NULL, kATSOptionFlagsDefault);
452         fontContainerRef = 0;
453     }
457 - (void)selectTab:(int)index
459     //NSLog(@"%s%d", _cmd, index);
461     index -= 1;
462     NSData *data = [NSData dataWithBytes:&index length:sizeof(int)];
463     [self queueMessage:SelectTabMsgID data:data];
466 - (void)updateTabBar
468     //NSLog(@"%s", _cmd);
470     NSMutableData *data = [NSMutableData data];
472     int idx = tabpage_index(curtab) - 1;
473     [data appendBytes:&idx length:sizeof(int)];
475     tabpage_T *tp;
476     for (tp = first_tabpage; tp != NULL; tp = tp->tp_next) {
477         // This function puts the label of the tab in the global 'NameBuff'.
478         get_tabline_label(tp, FALSE);
479         char_u *s = NameBuff;
480         int len = STRLEN(s);
481         if (len <= 0) continue;
483 #ifdef FEAT_MBYTE
484         s = CONVERT_TO_UTF8(s);
485 #endif
487         // Count the number of windows in the tabpage.
488         //win_T *wp = tp->tp_firstwin;
489         //int wincount;
490         //for (wincount = 0; wp != NULL; wp = wp->w_next, ++wincount);
492         //[data appendBytes:&wincount length:sizeof(int)];
493         [data appendBytes:&len length:sizeof(int)];
494         [data appendBytes:s length:len];
496 #ifdef FEAT_MBYTE
497         CONVERT_TO_UTF8_FREE(s);
498 #endif
499     }
501     [self queueMessage:UpdateTabBarMsgID data:data];
504 - (BOOL)tabBarVisible
506     return tabBarVisible;
509 - (void)showTabBar:(BOOL)enable
511     tabBarVisible = enable;
513     int msgid = enable ? ShowTabBarMsgID : HideTabBarMsgID;
514     [self queueMessage:msgid data:nil];
517 - (void)setRows:(int)rows columns:(int)cols
519     //NSLog(@"[VimTask] setRows:%d columns:%d", rows, cols);
521     int dim[] = { rows, cols };
522     NSData *data = [NSData dataWithBytes:&dim length:2*sizeof(int)];
524     [self queueMessage:SetTextDimensionsMsgID data:data];
527 - (void)setWindowTitle:(char *)title
529     NSMutableData *data = [NSMutableData data];
530     int len = strlen(title);
531     if (len <= 0) return;
533     [data appendBytes:&len length:sizeof(int)];
534     [data appendBytes:title length:len];
536     [self queueMessage:SetWindowTitleMsgID data:data];
539 - (char *)browseForFileInDirectory:(char *)dir title:(char *)title
540                             saving:(int)saving
542     //NSLog(@"browseForFileInDirectory:%s title:%s saving:%d", dir, title,
543     //        saving);
545     char_u *s = NULL;
546     NSString *ds = dir ? [NSString stringWithUTF8String:dir] : nil;
547     NSString *ts = title ? [NSString stringWithUTF8String:title] : nil;
548     @try {
549         [frontendProxy showSavePanelForDirectory:ds title:ts saving:saving];
551         // Wait until a reply is sent from MMVimController.
552         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
553                                  beforeDate:[NSDate distantFuture]];
555         if (dialogReturn && [dialogReturn isKindOfClass:[NSString class]]) {
556             char_u *ret = (char_u*)[dialogReturn UTF8String];
557 #ifdef FEAT_MBYTE
558             ret = CONVERT_FROM_UTF8(ret);
559 #endif
560             s = vim_strsave(ret);
561 #ifdef FEAT_MBYTE
562             CONVERT_FROM_UTF8_FREE(ret);
563 #endif
564         }
566         [dialogReturn release];  dialogReturn = nil;
567     }
568     @catch (NSException *e) {
569         NSLog(@"Exception caught when showing save panel: \"%@\"", e);
570     }
572     return (char *)s;
575 - (oneway void)setDialogReturn:(in bycopy id)obj
577     // NOTE: This is called by
578     //   - [MMVimController panelDidEnd:::], and
579     //   - [MMVimController alertDidEnd:::],
580     // to indicate that a save/open panel or alert has finished.
582     if (obj != dialogReturn) {
583         [dialogReturn release];
584         dialogReturn = [obj retain];
585     }
588 - (int)presentDialogWithType:(int)type title:(char *)title message:(char *)msg
589                      buttons:(char *)btns textField:(char *)txtfield
591     int retval = 0;
592     NSString *message = nil, *text = nil, *textFieldString = nil;
593     NSArray *buttons = nil;
594     int style = NSInformationalAlertStyle;
596     if (VIM_WARNING == type) style = NSWarningAlertStyle;
597     else if (VIM_ERROR == type) style = NSCriticalAlertStyle;
599     if (btns) {
600         NSString *btnString = [NSString stringWithUTF8String:btns];
601         buttons = [btnString componentsSeparatedByString:@"\n"];
602     }
603     if (title)
604         message = [NSString stringWithUTF8String:title];
605     if (msg) {
606         text = [NSString stringWithUTF8String:msg];
607         if (!message) {
608             // HACK! If there is a '\n\n' or '\n' sequence in the message, then
609             // make the part up to there into the title.  We only do this
610             // because Vim has lots of dialogs without a title and they look
611             // ugly that way.
612             // TODO: Fix the actual dialog texts.
613             NSRange eolRange = [text rangeOfString:@"\n\n"];
614             if (NSNotFound == eolRange.location)
615                 eolRange = [text rangeOfString:@"\n"];
616             if (NSNotFound != eolRange.location) {
617                 message = [text substringToIndex:eolRange.location];
618                 text = [text substringFromIndex:NSMaxRange(eolRange)];
619             }
620         }
621     }
622     if (txtfield)
623         textFieldString = [NSString stringWithUTF8String:txtfield];
625     @try {
626         [frontendProxy presentDialogWithStyle:style message:message
627                               informativeText:text buttonTitles:buttons
628                               textFieldString:textFieldString];
630         // Wait until a reply is sent from MMVimController.
631         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
632                                  beforeDate:[NSDate distantFuture]];
634         if (dialogReturn && [dialogReturn isKindOfClass:[NSArray class]]
635                 && [dialogReturn count]) {
636             retval = [[dialogReturn objectAtIndex:0] intValue];
637             if (txtfield && [dialogReturn count] > 1) {
638                 NSString *retString = [dialogReturn objectAtIndex:1];
639                 char_u *ret = (char_u*)[retString UTF8String];
640 #ifdef FEAT_MBYTE
641                 ret = CONVERT_FROM_UTF8(ret);
642 #endif
643                 vim_strncpy((char_u*)txtfield, ret, IOSIZE - 1);
644 #ifdef FEAT_MBYTE
645                 CONVERT_FROM_UTF8_FREE(ret);
646 #endif
647             }
648         }
650         [dialogReturn release]; dialogReturn = nil;
651     }
652     @catch (NSException *e) {
653         NSLog(@"Exception caught while showing alert dialog: \"%@\"", e);
654     }
656     return retval;
659 - (void)addMenuWithTag:(int)tag parent:(int)parentTag name:(char *)name
660                atIndex:(int)index
662     //NSLog(@"addMenuWithTag:%d parent:%d name:%s atIndex:%d", tag, parentTag,
663     //        name, index);
665     int namelen = name ? strlen(name) : 0;
666     NSMutableData *data = [NSMutableData data];
668     [data appendBytes:&tag length:sizeof(int)];
669     [data appendBytes:&parentTag length:sizeof(int)];
670     [data appendBytes:&namelen length:sizeof(int)];
671     if (namelen > 0) [data appendBytes:name length:namelen];
672     [data appendBytes:&index length:sizeof(int)];
674     [self queueMessage:AddMenuMsgID data:data];
677 - (void)addMenuItemWithTag:(int)tag parent:(int)parentTag name:(char *)name
678                        tip:(char *)tip icon:(char *)icon
679              keyEquivalent:(int)key modifiers:(int)mods
680                     action:(NSString *)action atIndex:(int)index
682     //NSLog(@"addMenuItemWithTag:%d parent:%d name:%s tip:%s atIndex:%d", tag,
683     //        parentTag, name, tip, index);
685     int namelen = name ? strlen(name) : 0;
686     int tiplen = tip ? strlen(tip) : 0;
687     int iconlen = icon ? strlen(icon) : 0;
688     int eventFlags = vimModMaskToEventModifierFlags(mods);
689     int actionlen = [action lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
690     NSMutableData *data = [NSMutableData data];
692     key = specialKeyToNSKey(key);
694     [data appendBytes:&tag length:sizeof(int)];
695     [data appendBytes:&parentTag length:sizeof(int)];
696     [data appendBytes:&namelen length:sizeof(int)];
697     if (namelen > 0) [data appendBytes:name length:namelen];
698     [data appendBytes:&tiplen length:sizeof(int)];
699     if (tiplen > 0) [data appendBytes:tip length:tiplen];
700     [data appendBytes:&iconlen length:sizeof(int)];
701     if (iconlen > 0) [data appendBytes:icon length:iconlen];
702     [data appendBytes:&actionlen length:sizeof(int)];
703     if (actionlen > 0) [data appendBytes:[action UTF8String] length:actionlen];
704     [data appendBytes:&index length:sizeof(int)];
705     [data appendBytes:&key length:sizeof(int)];
706     [data appendBytes:&eventFlags length:sizeof(int)];
708     [self queueMessage:AddMenuItemMsgID data:data];
711 - (void)removeMenuItemWithTag:(int)tag
713     NSMutableData *data = [NSMutableData data];
714     [data appendBytes:&tag length:sizeof(int)];
716     [self queueMessage:RemoveMenuItemMsgID data:data];
719 - (void)enableMenuItemWithTag:(int)tag state:(int)enabled
721     NSMutableData *data = [NSMutableData data];
723     [data appendBytes:&tag length:sizeof(int)];
724     [data appendBytes:&enabled length:sizeof(int)];
726     [self queueMessage:EnableMenuItemMsgID data:data];
729 - (void)showPopupMenuWithName:(char *)name atMouseLocation:(BOOL)mouse
731     int len = strlen(name);
732     int row = -1, col = -1;
734     if (len <= 0) return;
736     if (!mouse && curwin) {
737         row = curwin->w_wrow;
738         col = curwin->w_wcol;
739     }
741     NSMutableData *data = [NSMutableData data];
743     [data appendBytes:&row length:sizeof(int)];
744     [data appendBytes:&col length:sizeof(int)];
745     [data appendBytes:&len length:sizeof(int)];
746     [data appendBytes:name length:len];
748     [self queueMessage:ShowPopupMenuMsgID data:data];
751 - (void)showToolbar:(int)enable flags:(int)flags
753     NSMutableData *data = [NSMutableData data];
755     [data appendBytes:&enable length:sizeof(int)];
756     [data appendBytes:&flags length:sizeof(int)];
758     [self queueMessage:ShowToolbarMsgID data:data];
761 - (void)createScrollbarWithIdentifier:(long)ident type:(int)type
763     NSMutableData *data = [NSMutableData data];
765     [data appendBytes:&ident length:sizeof(long)];
766     [data appendBytes:&type length:sizeof(int)];
768     [self queueMessage:CreateScrollbarMsgID data:data];
771 - (void)destroyScrollbarWithIdentifier:(long)ident
773     NSMutableData *data = [NSMutableData data];
774     [data appendBytes:&ident length:sizeof(long)];
776     [self queueMessage:DestroyScrollbarMsgID data:data];
779 - (void)showScrollbarWithIdentifier:(long)ident state:(int)visible
781     NSMutableData *data = [NSMutableData data];
783     [data appendBytes:&ident length:sizeof(long)];
784     [data appendBytes:&visible length:sizeof(int)];
786     [self queueMessage:ShowScrollbarMsgID data:data];
789 - (void)setScrollbarPosition:(int)pos length:(int)len identifier:(long)ident
791     NSMutableData *data = [NSMutableData data];
793     [data appendBytes:&ident length:sizeof(long)];
794     [data appendBytes:&pos length:sizeof(int)];
795     [data appendBytes:&len length:sizeof(int)];
797     [self queueMessage:SetScrollbarPositionMsgID data:data];
800 - (void)setScrollbarThumbValue:(long)val size:(long)size max:(long)max
801                     identifier:(long)ident
803     float fval = max-size+1 > 0 ? (float)val/(max-size+1) : 0;
804     float prop = (float)size/(max+1);
805     if (fval < 0) fval = 0;
806     else if (fval > 1.0f) fval = 1.0f;
807     if (prop < 0) prop = 0;
808     else if (prop > 1.0f) prop = 1.0f;
810     NSMutableData *data = [NSMutableData data];
812     [data appendBytes:&ident length:sizeof(long)];
813     [data appendBytes:&fval length:sizeof(float)];
814     [data appendBytes:&prop length:sizeof(float)];
816     [self queueMessage:SetScrollbarThumbMsgID data:data];
819 - (BOOL)setFontWithName:(char *)name
821     NSString *fontName = MMDefaultFontName;
822     float size = MMDefaultFontSize;
823     BOOL parseFailed = NO;
825     if (name) {
826         fontName = [NSString stringWithUTF8String:name];
828         if ([fontName isEqual:@"*"]) {
829             // :set gfn=* shows the font panel.
830             do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
831             return NO;
832         }
834         NSArray *components = [fontName componentsSeparatedByString:@":"];
835         if ([components count] == 2) {
836             NSString *sizeString = [components lastObject];
837             if ([sizeString length] > 0
838                     && [sizeString characterAtIndex:0] == 'h') {
839                 sizeString = [sizeString substringFromIndex:1];
840                 if ([sizeString length] > 0) {
841                     size = [sizeString floatValue];
842                     fontName = [components objectAtIndex:0];
843                 }
844             } else {
845                 parseFailed = YES;
846             }
847         } else if ([components count] > 2) {
848             parseFailed = YES;
849         }
851         if (!parseFailed) {
852             // Replace underscores with spaces.
853             fontName = [[fontName componentsSeparatedByString:@"_"]
854                                      componentsJoinedByString:@" "];
855         }
856     }
858     if (!parseFailed && [fontName length] > 0) {
859         if (size < 6 || size > 100) {
860             // Font size 0.0 tells NSFont to use the 'user default size'.
861             size = 0.0f;
862         }
864         NSFont *font = [NSFont fontWithName:fontName size:size];
866         if (!font && MMDefaultFontName == fontName) {
867             // If for some reason the MacVim default font is not in the app
868             // bundle, then fall back on the system default font.
869             size = 0;
870             font = [NSFont userFixedPitchFontOfSize:size];
871             fontName = [font displayName];
872         }
874         if (font) {
875             //NSLog(@"Setting font '%@' of size %.2f", fontName, size);
876             int len = [fontName
877                     lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
878             if (len > 0) {
879                 NSMutableData *data = [NSMutableData data];
881                 [data appendBytes:&size length:sizeof(float)];
882                 [data appendBytes:&len length:sizeof(int)];
883                 [data appendBytes:[fontName UTF8String] length:len];
885                 [self queueMessage:SetFontMsgID data:data];
886                 return YES;
887             }
888         }
889     }
891     //NSLog(@"WARNING: Cannot set font with name '%@' of size %.2f",
892     //        fontName, size);
893     return NO;
896 - (void)executeActionWithName:(NSString *)name
898     int len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
900     if (len > 0) {
901         NSMutableData *data = [NSMutableData data];
903         [data appendBytes:&len length:sizeof(int)];
904         [data appendBytes:[name UTF8String] length:len];
906         [self queueMessage:ExecuteActionMsgID data:data];
907     }
910 - (void)setMouseShape:(int)shape
912     NSMutableData *data = [NSMutableData data];
913     [data appendBytes:&shape length:sizeof(int)];
914     [self queueMessage:SetMouseShapeMsgID data:data];
917 - (void)setBlinkWait:(int)wait on:(int)on off:(int)off
919     // Vim specifies times in milliseconds, whereas Cocoa wants them in
920     // seconds.
921     blinkWaitInterval = .001f*wait;
922     blinkOnInterval = .001f*on;
923     blinkOffInterval = .001f*off;
926 - (void)startBlink
928     if (blinkTimer) {
929         [blinkTimer invalidate];
930         [blinkTimer release];
931         blinkTimer = nil;
932     }
934     if (blinkWaitInterval > 0 && blinkOnInterval > 0 && blinkOffInterval > 0
935             && gui.in_focus) {
936         blinkState = MMBlinkStateOn;
937         blinkTimer =
938             [[NSTimer scheduledTimerWithTimeInterval:blinkWaitInterval
939                                               target:self
940                                             selector:@selector(blinkTimerFired:)
941                                             userInfo:nil repeats:NO] retain];
942         gui_update_cursor(TRUE, FALSE);
943         [self flushQueue:YES];
944     }
947 - (void)stopBlink
949     if (MMBlinkStateOff == blinkState) {
950         gui_update_cursor(TRUE, FALSE);
951         [self flushQueue:YES];
952     }
954     blinkState = MMBlinkStateNone;
957 - (void)adjustLinespace:(int)linespace
959     NSMutableData *data = [NSMutableData data];
960     [data appendBytes:&linespace length:sizeof(int)];
961     [self queueMessage:AdjustLinespaceMsgID data:data];
964 - (void)activate
966     [self queueMessage:ActivateMsgID data:nil];
969 - (int)lookupColorWithKey:(NSString *)key
971     if (!(key && [key length] > 0))
972         return INVALCOLOR;
974     NSString *stripKey = [[[[key lowercaseString]
975         stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
976             componentsSeparatedByString:@" "]
977                componentsJoinedByString:@""];
979     if (stripKey && [stripKey length] > 0) {
980         // First of all try to lookup key in the color dictionary; note that
981         // all keys in this dictionary are lowercase with no whitespace.
982         id obj = [colorDict objectForKey:stripKey];
983         if (obj) return [obj intValue];
985         // The key was not in the dictionary; is it perhaps of the form
986         // #rrggbb?
987         if ([stripKey length] > 1 && [stripKey characterAtIndex:0] == '#') {
988             NSScanner *scanner = [NSScanner scannerWithString:stripKey];
989             [scanner setScanLocation:1];
990             unsigned hex = 0;
991             if ([scanner scanHexInt:&hex]) {
992                 return (int)hex;
993             }
994         }
996         // As a last resort, check if it is one of the system defined colors.
997         // The keys in this dictionary are also lowercase with no whitespace.
998         obj = [sysColorDict objectForKey:stripKey];
999         if (obj) {
1000             NSColor *col = [NSColor performSelector:NSSelectorFromString(obj)];
1001             if (col) {
1002                 float r, g, b, a;
1003                 col = [col colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
1004                 [col getRed:&r green:&g blue:&b alpha:&a];
1005                 return (((int)(r*255+.5f) & 0xff) << 16)
1006                      + (((int)(g*255+.5f) & 0xff) << 8)
1007                      +  ((int)(b*255+.5f) & 0xff);
1008             }
1009         }
1010     }
1012     NSLog(@"WARNING: No color with key %@ found.", stripKey);
1013     return INVALCOLOR;
1016 - (BOOL)hasSpecialKeyWithValue:(NSString *)value
1018     NSEnumerator *e = [[MMBackend specialKeys] objectEnumerator];
1019     id obj;
1021     while ((obj = [e nextObject])) {
1022         if ([value isEqual:obj])
1023             return YES;
1024     }
1026     return NO;
1029 - (void)enterFullscreen
1031     [self queueMessage:EnterFullscreenMsgID data:nil];
1034 - (void)leaveFullscreen
1036     [self queueMessage:LeaveFullscreenMsgID data:nil];
1039 - (void)updateModifiedFlag
1041     // Notify MacVim if _any_ buffer has changed from unmodified to modified or
1042     // vice versa.
1043     int msgid = [self checkForModifiedBuffers]
1044             ? BuffersModifiedMsgID : BuffersNotModifiedMsgID;
1046     [self queueMessage:msgid data:nil];
1049 - (oneway void)processInput:(int)msgid data:(in bycopy NSData *)data
1051     // NOTE: This method might get called whenever the run loop is tended to.
1052     // Normal keyboard and mouse input is added to input buffers, so there is
1053     // no risk in handling these events directly (they return immediately, and
1054     // do not call any other Vim functions).  However, other events such
1055     // as 'VimShouldCloseMsgID' may enter blocking loops that wait for key
1056     // events which would cause this method to be called recursively.  This
1057     // in turn leads to various difficulties that we do not want to have to
1058     // deal with.  To avoid recursive calls here we add all events except
1059     // keyboard and mouse events to an input queue which is processed whenever
1060     // gui_mch_update() is called (see processInputQueue).
1062     //NSLog(@"%s%s", _cmd, MessageStrings[msgid]);
1064     // Don't flush too soon after receiving input or update speed will suffer.
1065     [lastFlushDate release];
1066     lastFlushDate = [[NSDate date] retain];
1068     // Handle keyboard and mouse input now.  All other events are queued.
1069     if (InsertTextMsgID == msgid) {
1070         [self handleInsertText:data];
1071     } else if (KeyDownMsgID == msgid || CmdKeyMsgID == msgid) {
1072         if (!data) return;
1073         const void *bytes = [data bytes];
1074         int mods = *((int*)bytes);  bytes += sizeof(int);
1075         int len = *((int*)bytes);  bytes += sizeof(int);
1076         NSString *key = [[NSString alloc] initWithBytes:bytes length:len
1077                                               encoding:NSUTF8StringEncoding];
1078         mods = eventModifierFlagsToVimModMask(mods);
1080         [self handleKeyDown:key modifiers:mods];
1082         [key release];
1083     } else if (ScrollWheelMsgID == msgid) {
1084         if (!data) return;
1085         const void *bytes = [data bytes];
1087         int row = *((int*)bytes);  bytes += sizeof(int);
1088         int col = *((int*)bytes);  bytes += sizeof(int);
1089         int flags = *((int*)bytes);  bytes += sizeof(int);
1090         float dy = *((float*)bytes);  bytes += sizeof(float);
1092         int button = MOUSE_5;
1093         if (dy > 0) button = MOUSE_4;
1095         flags = eventModifierFlagsToVimMouseModMask(flags);
1097         gui_send_mouse_event(button, col, row, NO, flags);
1098     } else if (MouseDownMsgID == msgid) {
1099         if (!data) return;
1100         const void *bytes = [data bytes];
1102         int row = *((int*)bytes);  bytes += sizeof(int);
1103         int col = *((int*)bytes);  bytes += sizeof(int);
1104         int button = *((int*)bytes);  bytes += sizeof(int);
1105         int flags = *((int*)bytes);  bytes += sizeof(int);
1106         int count = *((int*)bytes);  bytes += sizeof(int);
1108         button = eventButtonNumberToVimMouseButton(button);
1109         if (button >= 0) {
1110             flags = eventModifierFlagsToVimMouseModMask(flags);
1111             gui_send_mouse_event(button, col, row, count>1, flags);
1112         }
1113     } else if (MouseUpMsgID == msgid) {
1114         if (!data) return;
1115         const void *bytes = [data bytes];
1117         int row = *((int*)bytes);  bytes += sizeof(int);
1118         int col = *((int*)bytes);  bytes += sizeof(int);
1119         int flags = *((int*)bytes);  bytes += sizeof(int);
1121         flags = eventModifierFlagsToVimMouseModMask(flags);
1123         gui_send_mouse_event(MOUSE_RELEASE, col, row, NO, flags);
1124     } else if (MouseDraggedMsgID == msgid) {
1125         if (!data) return;
1126         const void *bytes = [data bytes];
1128         int row = *((int*)bytes);  bytes += sizeof(int);
1129         int col = *((int*)bytes);  bytes += sizeof(int);
1130         int flags = *((int*)bytes);  bytes += sizeof(int);
1132         flags = eventModifierFlagsToVimMouseModMask(flags);
1134         gui_send_mouse_event(MOUSE_DRAG, col, row, NO, flags);
1135     } else if (MouseMovedMsgID == msgid) {
1136         const void *bytes = [data bytes];
1137         int row = *((int*)bytes);  bytes += sizeof(int);
1138         int col = *((int*)bytes);  bytes += sizeof(int);
1140         gui_mouse_moved(col, row);
1141     } else {
1142         // Not keyboard or mouse event, queue it and handle later.
1143         //NSLog(@"Add event %s to input event queue", MessageStrings[msgid]);
1144         [inputQueue addObject:[NSNumber numberWithInt:msgid]];
1145         [inputQueue addObject:(data ? (id)data : (id)[NSNull null])];
1146     }
1148     // See waitForInput: for an explanation of this flag.
1149     inputReceived = YES;
1152 - (oneway void)processInputAndData:(in bycopy NSArray *)messages
1154     // TODO: Get rid of this method?
1155     //NSLog(@"%s%@", _cmd, messages);
1157     unsigned i, count = [messages count];
1158     for (i = 0; i < count; i += 2) {
1159         int msgid = [[messages objectAtIndex:i] intValue];
1160         id data = [messages objectAtIndex:i+1];
1161         if ([data isEqual:[NSNull null]])
1162             data = nil;
1164         [self processInput:msgid data:data];
1165     }
1168 - (BOOL)checkForModifiedBuffers
1170     buf_T *buf;
1171     for (buf = firstbuf; buf != NULL; buf = buf->b_next) {
1172         if (bufIsChanged(buf)) {
1173             return YES;
1174         }
1175     }
1177     return NO;
1180 - (BOOL)starRegisterToPasteboard:(byref NSPasteboard *)pboard
1182     if (VIsual_active && (State & NORMAL) && clip_star.available) {
1183         // If there is no pasteboard, return YES to indicate that there is text
1184         // to copy.
1185         if (!pboard)
1186             return YES;
1188         clip_copy_selection();
1190         // Get the text to put on the pasteboard.
1191         long_u llen = 0; char_u *str = 0;
1192         int type = clip_convert_selection(&str, &llen, &clip_star);
1193         if (type < 0)
1194             return NO;
1195         
1196         // TODO: Avoid overflow.
1197         int len = (int)llen;
1198 #ifdef FEAT_MBYTE
1199         if (output_conv.vc_type != CONV_NONE) {
1200             char_u *conv_str = string_convert(&output_conv, str, &len);
1201             if (conv_str) {
1202                 vim_free(str);
1203                 str = conv_str;
1204             }
1205         }
1206 #endif
1208         NSString *string = [[NSString alloc]
1209             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
1211         NSArray *types = [NSArray arrayWithObject:NSStringPboardType];
1212         [pboard declareTypes:types owner:nil];
1213         BOOL ok = [pboard setString:string forType:NSStringPboardType];
1214     
1215         [string release];
1216         vim_free(str);
1218         return ok;
1219     }
1221     return NO;
1224 - (oneway void)addReply:(in bycopy NSString *)reply
1225                  server:(in byref id <MMVimServerProtocol>)server
1227     //NSLog(@"addReply:%@ server:%@", reply, (id)server);
1229     // Replies might come at any time and in any order so we keep them in an
1230     // array inside a dictionary with the send port used as key.
1232     NSConnection *conn = [(NSDistantObject*)server connectionForProxy];
1233     // HACK! Assume connection uses mach ports.
1234     int port = [(NSMachPort*)[conn sendPort] machPort];
1235     NSNumber *key = [NSNumber numberWithInt:port];
1237     NSMutableArray *replies = [serverReplyDict objectForKey:key];
1238     if (!replies) {
1239         replies = [NSMutableArray array];
1240         [serverReplyDict setObject:replies forKey:key];
1241     }
1243     [replies addObject:reply];
1246 - (void)addInput:(in bycopy NSString *)input
1247                  client:(in byref id <MMVimClientProtocol>)client
1249     //NSLog(@"addInput:%@ client:%@", input, (id)client);
1251     char_u *s = (char_u*)[input UTF8String];
1253 #ifdef FEAT_MBYTE
1254     s = CONVERT_FROM_UTF8(s);
1255 #endif
1257     server_to_input_buf(s);
1259 #ifdef FEAT_MBYTE
1260     CONVERT_FROM_UTF8_FREE(s);
1261 #endif
1263     [self addClient:(id)client];
1265     inputReceived = YES;
1268 - (NSString *)evaluateExpression:(in bycopy NSString *)expr
1269                  client:(in byref id <MMVimClientProtocol>)client
1271     //NSLog(@"evaluateExpression:%@ client:%@", expr, (id)client);
1273     NSString *eval = nil;
1274     char_u *s = (char_u*)[expr UTF8String];
1276 #ifdef FEAT_MBYTE
1277     s = CONVERT_FROM_UTF8(s);
1278 #endif
1280     char_u *res = eval_client_expr_to_string(s);
1282 #ifdef FEAT_MBYTE
1283     CONVERT_FROM_UTF8_FREE(s);
1284 #endif
1286     if (res != NULL) {
1287         s = res;
1288 #ifdef FEAT_MBYTE
1289         s = CONVERT_TO_UTF8(s);
1290 #endif
1291         eval = [NSString stringWithUTF8String:(char*)s];
1292 #ifdef FEAT_MBYTE
1293         CONVERT_TO_UTF8_FREE(s);
1294 #endif
1295         vim_free(res);
1296     }
1298     [self addClient:(id)client];
1300     return eval;
1303 - (void)registerServerWithName:(NSString *)name
1305     NSString *svrName = name;
1306     NSConnection *svrConn = [NSConnection defaultConnection];
1307     unsigned i;
1309     for (i = 0; i < MMServerMax; ++i) {
1310         NSString *connName = [self connectionNameFromServerName:svrName];
1312         if ([svrConn registerName:connName]) {
1313             //NSLog(@"Registered server with name: %@", svrName);
1315             // TODO: Set request/reply time-outs to something else?
1316             //
1317             // Don't wait for requests (time-out means that the message is
1318             // dropped).
1319             [svrConn setRequestTimeout:0];
1320             //[svrConn setReplyTimeout:MMReplyTimeout];
1321             [svrConn setRootObject:self];
1323             char_u *s = (char_u*)[svrName UTF8String];
1324 #ifdef FEAT_MBYTE
1325             s = CONVERT_FROM_UTF8(s);
1326 #endif
1327             // NOTE: 'serverName' is a global variable
1328             serverName = vim_strsave(s);
1329 #ifdef FEAT_MBYTE
1330             CONVERT_FROM_UTF8_FREE(s);
1331 #endif
1332 #ifdef FEAT_EVAL
1333             set_vim_var_string(VV_SEND_SERVER, serverName, -1);
1334 #endif
1335 #ifdef FEAT_TITLE
1336             need_maketitle = TRUE;
1337 #endif
1338             [self queueMessage:SetServerNameMsgID data:
1339                     [svrName dataUsingEncoding:NSUTF8StringEncoding]];
1340             break;
1341         }
1343         svrName = [NSString stringWithFormat:@"%@%d", name, i+1];
1344     }
1347 - (BOOL)sendToServer:(NSString *)name string:(NSString *)string
1348                reply:(char_u **)reply port:(int *)port expression:(BOOL)expr
1349               silent:(BOOL)silent
1351     // NOTE: If 'name' equals 'serverName' then the request is local (client
1352     // and server are the same).  This case is not handled separately, so a
1353     // connection will be set up anyway (this simplifies the code).
1355     NSConnection *conn = [self connectionForServerName:name];
1356     if (!conn) {
1357         if (!silent) {
1358             char_u *s = (char_u*)[name UTF8String];
1359 #ifdef FEAT_MBYTE
1360             s = CONVERT_FROM_UTF8(s);
1361 #endif
1362             EMSG2(_(e_noserver), s);
1363 #ifdef FEAT_MBYTE
1364             CONVERT_FROM_UTF8_FREE(s);
1365 #endif
1366         }
1367         return NO;
1368     }
1370     if (port) {
1371         // HACK! Assume connection uses mach ports.
1372         *port = [(NSMachPort*)[conn sendPort] machPort];
1373     }
1375     id proxy = [conn rootProxy];
1376     [proxy setProtocolForProxy:@protocol(MMVimServerProtocol)];
1378     @try {
1379         if (expr) {
1380             NSString *eval = [proxy evaluateExpression:string client:self];
1381             if (reply) {
1382                 if (eval) {
1383                     char_u *r = (char_u*)[eval UTF8String];
1384 #ifdef FEAT_MBYTE
1385                     r = CONVERT_FROM_UTF8(r);
1386 #endif
1387                     *reply = vim_strsave(r);
1388 #ifdef FEAT_MBYTE
1389                     CONVERT_FROM_UTF8_FREE(r);
1390 #endif
1391                 } else {
1392                     *reply = vim_strsave((char_u*)_(e_invexprmsg));
1393                 }
1394             }
1396             if (!eval)
1397                 return NO;
1398         } else {
1399             [proxy addInput:string client:self];
1400         }
1401     }
1402     @catch (NSException *e) {
1403         NSLog(@"WARNING: Caught exception in %s: \"%@\"", _cmd, e);
1404         return NO;
1405     }
1407     return YES;
1410 - (NSArray *)serverList
1412     NSArray *list = nil;
1414     if ([self connection]) {
1415         id proxy = [connection rootProxy];
1416         [proxy setProtocolForProxy:@protocol(MMAppProtocol)];
1418         @try {
1419             list = [proxy serverList];
1420         }
1421         @catch (NSException *e) {
1422             NSLog(@"Exception caught when listing servers: \"%@\"", e);
1423         }
1424     } else {
1425         EMSG(_("E???: No connection to MacVim, server listing not possible."));
1426     }
1428     return list;
1431 - (NSString *)peekForReplyOnPort:(int)port
1433     //NSLog(@"%s%d", _cmd, port);
1435     NSNumber *key = [NSNumber numberWithInt:port];
1436     NSMutableArray *replies = [serverReplyDict objectForKey:key];
1437     if (replies && [replies count]) {
1438         //NSLog(@"    %d replies, topmost is: %@", [replies count],
1439         //        [replies objectAtIndex:0]);
1440         return [replies objectAtIndex:0];
1441     }
1443     //NSLog(@"    No replies");
1444     return nil;
1447 - (NSString *)waitForReplyOnPort:(int)port
1449     //NSLog(@"%s%d", _cmd, port);
1450     
1451     NSConnection *conn = [self connectionForServerPort:port];
1452     if (!conn)
1453         return nil;
1455     NSNumber *key = [NSNumber numberWithInt:port];
1456     NSMutableArray *replies = nil;
1457     NSString *reply = nil;
1459     // Wait for reply as long as the connection to the server is valid (unless
1460     // user interrupts wait with Ctrl-C).
1461     while (!got_int && [conn isValid] &&
1462             !(replies = [serverReplyDict objectForKey:key])) {
1463         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
1464                                  beforeDate:[NSDate distantFuture]];
1465     }
1467     if (replies) {
1468         if ([replies count] > 0) {
1469             reply = [[replies objectAtIndex:0] retain];
1470             //NSLog(@"    Got reply: %@", reply);
1471             [replies removeObjectAtIndex:0];
1472             [reply autorelease];
1473         }
1475         if ([replies count] == 0)
1476             [serverReplyDict removeObjectForKey:key];
1477     }
1479     return reply;
1482 - (BOOL)sendReply:(NSString *)reply toPort:(int)port
1484     id client = [clientProxyDict objectForKey:[NSNumber numberWithInt:port]];
1485     if (client) {
1486         @try {
1487             //NSLog(@"sendReply:%@ toPort:%d", reply, port);
1488             [client addReply:reply server:self];
1489             return YES;
1490         }
1491         @catch (NSException *e) {
1492             NSLog(@"WARNING: Exception caught in %s: \"%@\"", _cmd, e);
1493         }
1494     } else {
1495         EMSG2(_("E???: server2client failed; no client with id 0x%x"), port);
1496     }
1498     return NO;
1501 @end // MMBackend
1505 @implementation MMBackend (Private)
1507 - (void)processInputQueue
1509     // NOTE: One of the input events may cause this method to be called
1510     // recursively, so copy the input queue to a local variable and clear it
1511     // before starting to process input events (otherwise we could get stuck in
1512     // an endless loop).
1513     NSArray *q = [inputQueue copy];
1514     unsigned i, count = [q count];
1516     [inputQueue removeAllObjects];
1518     for (i = 0; i < count-1; i += 2) {
1519         int msgid = [[q objectAtIndex:i] intValue];
1520         id data = [q objectAtIndex:i+1];
1521         if ([data isEqual:[NSNull null]])
1522             data = nil;
1524         //NSLog(@"(%d) %s:%s", i, _cmd, MessageStrings[msgid]);
1525         [self handleInputEvent:msgid data:data];
1526     }
1528     [q release];
1529     //NSLog(@"Clear input event queue");
1532 - (void)handleInputEvent:(int)msgid data:(NSData *)data
1534     // NOTE: Be careful with what you do in this method.  Ideally, a message
1535     // should be handled by adding something to the input buffer and returning
1536     // immediately.  If you call a Vim function then it should not enter a loop
1537     // waiting for key presses or in any other way block the process.  The
1538     // reason for this being that only one message can be processed at a time,
1539     // so if another message is received while processing, then the new message
1540     // is dropped.  See also the comment in processInput:data:.
1542     //NSLog(@"%s%s", _cmd, MessageStrings[msgid]);
1544     if (SelectTabMsgID == msgid) {
1545         if (!data) return;
1546         const void *bytes = [data bytes];
1547         int idx = *((int*)bytes) + 1;
1548         //NSLog(@"Selecting tab %d", idx);
1549         send_tabline_event(idx);
1550     } else if (CloseTabMsgID == msgid) {
1551         if (!data) return;
1552         const void *bytes = [data bytes];
1553         int idx = *((int*)bytes) + 1;
1554         //NSLog(@"Closing tab %d", idx);
1555         send_tabline_menu_event(idx, TABLINE_MENU_CLOSE);
1556     } else if (AddNewTabMsgID == msgid) {
1557         //NSLog(@"Adding new tab");
1558         send_tabline_menu_event(0, TABLINE_MENU_NEW);
1559     } else if (DraggedTabMsgID == msgid) {
1560         if (!data) return;
1561         const void *bytes = [data bytes];
1562         // NOTE! The destination index is 0 based, so do not add 1 to make it 1
1563         // based.
1564         int idx = *((int*)bytes);
1566         tabpage_move(idx);
1567     } else if (SetTextDimensionsMsgID == msgid) {
1568         if (!data) return;
1569         const void *bytes = [data bytes];
1570         int rows = *((int*)bytes);  bytes += sizeof(int);
1571         int cols = *((int*)bytes);  bytes += sizeof(int);
1573         // NOTE! Vim doesn't call gui_mch_set_shellsize() after
1574         // gui_resize_shell(), so we have to manually set the rows and columns
1575         // here.  (MacVim doesn't change the rows and columns to avoid
1576         // inconsistent states between Vim and MacVim.)
1577         [self setRows:rows columns:cols];
1579         //NSLog(@"[VimTask] Resizing shell to %dx%d.", cols, rows);
1580         gui_resize_shell(cols, rows);
1581     } else if (ExecuteMenuMsgID == msgid) {
1582         if (!data) return;
1583         const void *bytes = [data bytes];
1584         int tag = *((int*)bytes);  bytes += sizeof(int);
1586         vimmenu_T *menu = (vimmenu_T*)tag;
1587         // TODO!  Make sure 'menu' is a valid menu pointer!
1588         if (menu) {
1589             gui_menu_cb(menu);
1590         }
1591     } else if (ToggleToolbarMsgID == msgid) {
1592         [self handleToggleToolbar];
1593     } else if (ScrollbarEventMsgID == msgid) {
1594         [self handleScrollbarEvent:data];
1595     } else if (SetFontMsgID == msgid) {
1596         [self handleSetFont:data];
1597     } else if (VimShouldCloseMsgID == msgid) {
1598         gui_shell_closed();
1599     } else if (DropFilesMsgID == msgid) {
1600         [self handleDropFiles:data];
1601     } else if (DropStringMsgID == msgid) {
1602         [self handleDropString:data];
1603     } else if (GotFocusMsgID == msgid) {
1604         if (!gui.in_focus)
1605             [self focusChange:YES];
1606     } else if (LostFocusMsgID == msgid) {
1607         if (gui.in_focus)
1608             [self focusChange:NO];
1609     } else if (SetMouseShapeMsgID == msgid) {
1610         const void *bytes = [data bytes];
1611         int shape = *((int*)bytes);  bytes += sizeof(int);
1612         update_mouseshape(shape);
1613     } else {
1614         NSLog(@"WARNING: Unknown message received (msgid=%d)", msgid);
1615     }
1618 + (NSDictionary *)specialKeys
1620     static NSDictionary *specialKeys = nil;
1622     if (!specialKeys) {
1623         NSBundle *mainBundle = [NSBundle mainBundle];
1624         NSString *path = [mainBundle pathForResource:@"SpecialKeys"
1625                                               ofType:@"plist"];
1626         specialKeys = [[NSDictionary alloc] initWithContentsOfFile:path];
1627     }
1629     return specialKeys;
1632 - (void)handleInsertText:(NSData *)data
1634     if (!data) return;
1636     NSString *key = [[NSString alloc] initWithData:data
1637                                           encoding:NSUTF8StringEncoding];
1638     char_u *str = (char_u*)[key UTF8String];
1639     int i, len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1641 #ifdef FEAT_MBYTE
1642     char_u *conv_str = NULL;
1643     if (input_conv.vc_type != CONV_NONE) {
1644         conv_str = string_convert(&input_conv, str, &len);
1645         if (conv_str)
1646             str = conv_str;
1647     }
1648 #endif
1650     for (i = 0; i < len; ++i) {
1651         add_to_input_buf(str+i, 1);
1652         if (CSI == str[i]) {
1653             // NOTE: If the converted string contains the byte CSI, then it
1654             // must be followed by the bytes KS_EXTRA, KE_CSI or things
1655             // won't work.
1656             static char_u extra[2] = { KS_EXTRA, KE_CSI };
1657             add_to_input_buf(extra, 2);
1658         }
1659     }
1661 #ifdef FEAT_MBYTE
1662     if (conv_str)
1663         vim_free(conv_str);
1664 #endif
1665     [key release];
1668 - (void)handleKeyDown:(NSString *)key modifiers:(int)mods
1670     char_u special[3];
1671     char_u modChars[3];
1672     char_u *chars = (char_u*)[key UTF8String];
1673 #ifdef FEAT_MBYTE
1674     char_u *conv_str = NULL;
1675 #endif
1676     int length = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1678     // Special keys (arrow keys, function keys, etc.) are stored in a plist so
1679     // that new keys can easily be added.
1680     NSString *specialString = [[MMBackend specialKeys]
1681             objectForKey:key];
1682     if (specialString && [specialString length] > 1) {
1683         //NSLog(@"special key: %@", specialString);
1684         int ikey = TO_SPECIAL([specialString characterAtIndex:0],
1685                 [specialString characterAtIndex:1]);
1687         ikey = simplify_key(ikey, &mods);
1688         if (ikey == CSI)
1689             ikey = K_CSI;
1691         special[0] = CSI;
1692         special[1] = K_SECOND(ikey);
1693         special[2] = K_THIRD(ikey);
1695         chars = special;
1696         length = 3;
1697     } else if (1 == length && TAB == chars[0]) {
1698         // Tab is a trouble child:
1699         // - <Tab> is added to the input buffer as is
1700         // - <S-Tab> is translated to, {CSI,'k','B'} (i.e. 'Back-tab')
1701         // - <M-Tab> should be 0x80|TAB but this is not valid utf-8 so it needs
1702         //   to be converted to utf-8
1703         // - <S-M-Tab> is translated to <S-Tab> with ALT modifier
1704         // - <C-Tab> is reserved by Mac OS X
1705         // - <D-Tab> is reserved by Mac OS X
1706         chars = special;
1707         special[0] = TAB;
1708         length = 1;
1710         if (mods & MOD_MASK_SHIFT) {
1711             mods &= ~MOD_MASK_SHIFT;
1712             special[0] = CSI;
1713             special[1] = K_SECOND(K_S_TAB);
1714             special[2] = K_THIRD(K_S_TAB);
1715             length = 3;
1716         } else if (mods & MOD_MASK_ALT) {
1717             int mtab = 0x80 | TAB;
1718 #ifdef FEAT_MBYTE
1719             if (enc_utf8) {
1720                 // Convert to utf-8
1721                 special[0] = (mtab >> 6) + 0xc0;
1722                 special[1] = mtab & 0xbf;
1723                 length = 2;
1724             } else
1725 #endif
1726             {
1727                 special[0] = mtab;
1728                 length = 1;
1729             }
1730             mods &= ~MOD_MASK_ALT;
1731         }
1732     } else if (length > 0) {
1733         unichar c = [key characterAtIndex:0];
1735         //NSLog(@"non-special: %@ (hex=%x, mods=%d)", key,
1736         //        [key characterAtIndex:0], mods);
1738         if (length == 1 && ((c == Ctrl_C && ctrl_c_interrupts)
1739                 || (c == intr_char && intr_char != Ctrl_C))) {
1740             trash_input_buf();
1741             got_int = TRUE;
1742         }
1744         // HACK!  In most circumstances the Ctrl and Shift modifiers should be
1745         // cleared since they are already added to the key by the AppKit.
1746         // Unfortunately, the only way to deal with when to clear the modifiers
1747         // or not seems to be to have hard-wired rules like this.
1748         if ( !((' ' == c) || (0xa0 == c) || (mods & MOD_MASK_CMD)
1749                     || 0x9 == c || 0xd == c) ) {
1750             mods &= ~MOD_MASK_SHIFT;
1751             mods &= ~MOD_MASK_CTRL;
1752             //NSLog(@"clear shift ctrl");
1753         }
1755         // HACK!  All Option+key presses go via 'insert text' messages, except
1756         // for <M-Space>.  If the Alt flag is not cleared for <M-Space> it does
1757         // not work to map to it.
1758         if (0xa0 == c && !(mods & MOD_MASK_CMD)) {
1759             //NSLog(@"clear alt");
1760             mods &= ~MOD_MASK_ALT;
1761         }
1763 #ifdef FEAT_MBYTE
1764         if (input_conv.vc_type != CONV_NONE) {
1765             conv_str = string_convert(&input_conv, chars, &length);
1766             if (conv_str)
1767                 chars = conv_str;
1768         }
1769 #endif
1770     }
1772     if (chars && length > 0) {
1773         if (mods) {
1774             //NSLog(@"adding mods: %d", mods);
1775             modChars[0] = CSI;
1776             modChars[1] = KS_MODIFIER;
1777             modChars[2] = mods;
1778             add_to_input_buf(modChars, 3);
1779         }
1781         //NSLog(@"add to input buf: 0x%x", chars[0]);
1782         // TODO: Check for CSI bytes?
1783         add_to_input_buf(chars, length);
1784     }
1786 #ifdef FEAT_MBYTE
1787     if (conv_str)
1788         vim_free(conv_str);
1789 #endif
1792 - (void)queueMessage:(int)msgid data:(NSData *)data
1794     [outputQueue addObject:[NSData dataWithBytes:&msgid length:sizeof(int)]];
1795     if (data)
1796         [outputQueue addObject:data];
1797     else
1798         [outputQueue addObject:[NSData data]];
1801 - (void)connectionDidDie:(NSNotification *)notification
1803     // If the main connection to MacVim is lost this means that MacVim was
1804     // either quit (by the user chosing Quit on the MacVim menu), or it has
1805     // crashed.  In either case our only option is to quit now.
1806     // TODO: Write backup file?
1808     //NSLog(@"A Vim process lost its connection to MacVim; quitting.");
1809     getout(0);
1812 - (void)blinkTimerFired:(NSTimer *)timer
1814     NSTimeInterval timeInterval = 0;
1816     [blinkTimer release];
1817     blinkTimer = nil;
1819     if (MMBlinkStateOn == blinkState) {
1820         gui_undraw_cursor();
1821         blinkState = MMBlinkStateOff;
1822         timeInterval = blinkOffInterval;
1823     } else if (MMBlinkStateOff == blinkState) {
1824         gui_update_cursor(TRUE, FALSE);
1825         blinkState = MMBlinkStateOn;
1826         timeInterval = blinkOnInterval;
1827     }
1829     if (timeInterval > 0) {
1830         blinkTimer = 
1831             [[NSTimer scheduledTimerWithTimeInterval:timeInterval target:self
1832                                             selector:@selector(blinkTimerFired:)
1833                                             userInfo:nil repeats:NO] retain];
1834         [self flushQueue:YES];
1835     }
1838 - (void)focusChange:(BOOL)on
1840     gui_focus_change(on);
1843 - (void)handleToggleToolbar
1845     // If 'go' contains 'T', then remove it, else add it.
1847     char_u go[sizeof(GO_ALL)+2];
1848     char_u *p;
1849     int len;
1851     STRCPY(go, p_go);
1852     p = vim_strchr(go, GO_TOOLBAR);
1853     len = STRLEN(go);
1855     if (p != NULL) {
1856         char_u *end = go + len;
1857         while (p < end) {
1858             p[0] = p[1];
1859             ++p;
1860         }
1861     } else {
1862         go[len] = GO_TOOLBAR;
1863         go[len+1] = NUL;
1864     }
1866     set_option_value((char_u*)"guioptions", 0, go, 0);
1868     // Force screen redraw (does it have to be this complicated?).
1869     redraw_all_later(CLEAR);
1870     update_screen(NOT_VALID);
1871     setcursor();
1872     out_flush();
1873     gui_update_cursor(FALSE, FALSE);
1874     gui_mch_flush();
1877 - (void)handleScrollbarEvent:(NSData *)data
1879     if (!data) return;
1881     const void *bytes = [data bytes];
1882     long ident = *((long*)bytes);  bytes += sizeof(long);
1883     int hitPart = *((int*)bytes);  bytes += sizeof(int);
1884     float fval = *((float*)bytes);  bytes += sizeof(float);
1885     scrollbar_T *sb = gui_find_scrollbar(ident);
1887     if (sb) {
1888         scrollbar_T *sb_info = sb->wp ? &sb->wp->w_scrollbars[0] : sb;
1889         long value = sb_info->value;
1890         long size = sb_info->size;
1891         long max = sb_info->max;
1892         BOOL isStillDragging = NO;
1893         BOOL updateKnob = YES;
1895         switch (hitPart) {
1896         case NSScrollerDecrementPage:
1897             value -= (size > 2 ? size - 2 : 1);
1898             break;
1899         case NSScrollerIncrementPage:
1900             value += (size > 2 ? size - 2 : 1);
1901             break;
1902         case NSScrollerDecrementLine:
1903             --value;
1904             break;
1905         case NSScrollerIncrementLine:
1906             ++value;
1907             break;
1908         case NSScrollerKnob:
1909             isStillDragging = YES;
1910             // fall through ...
1911         case NSScrollerKnobSlot:
1912             value = (long)(fval * (max - size + 1));
1913             // fall through ...
1914         default:
1915             updateKnob = NO;
1916             break;
1917         }
1919         //NSLog(@"value %d -> %d", sb_info->value, value);
1920         gui_drag_scrollbar(sb, value, isStillDragging);
1922         if (updateKnob) {
1923             // Dragging the knob or option+clicking automatically updates
1924             // the knob position (on the actual NSScroller), so we only
1925             // need to set the knob position in the other cases.
1926             if (sb->wp) {
1927                 // Update both the left&right vertical scrollbars.
1928                 long identLeft = sb->wp->w_scrollbars[SBAR_LEFT].ident;
1929                 long identRight = sb->wp->w_scrollbars[SBAR_RIGHT].ident;
1930                 [self setScrollbarThumbValue:value size:size max:max
1931                                   identifier:identLeft];
1932                 [self setScrollbarThumbValue:value size:size max:max
1933                                   identifier:identRight];
1934             } else {
1935                 // Update the horizontal scrollbar.
1936                 [self setScrollbarThumbValue:value size:size max:max
1937                                   identifier:ident];
1938             }
1939         }
1940     }
1943 - (void)handleSetFont:(NSData *)data
1945     if (!data) return;
1947     const void *bytes = [data bytes];
1948     float pointSize = *((float*)bytes);  bytes += sizeof(float);
1949     //unsigned len = *((unsigned*)bytes);  bytes += sizeof(unsigned);
1950     bytes += sizeof(unsigned);  // len not used
1952     NSMutableString *name = [NSMutableString stringWithUTF8String:bytes];
1953     [name appendString:[NSString stringWithFormat:@":h%.2f", pointSize]];
1954     char_u *s = (char_u*)[name UTF8String];
1956 #ifdef FEAT_MBYTE
1957     s = CONVERT_FROM_UTF8(s);
1958 #endif
1960     set_option_value((char_u*)"guifont", 0, s, 0);
1962 #ifdef FEAT_MBYTE
1963     CONVERT_FROM_UTF8_FREE(s);
1964 #endif
1966     // Force screen redraw (does it have to be this complicated?).
1967     redraw_all_later(CLEAR);
1968     update_screen(NOT_VALID);
1969     setcursor();
1970     out_flush();
1971     gui_update_cursor(FALSE, FALSE);
1972     gui_mch_flush();
1975 - (void)handleDropFiles:(NSData *)data
1977     if (!data) return;
1979 #ifdef FEAT_DND
1980     const void *bytes = [data bytes];
1981     const void *end = [data bytes] + [data length];
1982     int n = *((int*)bytes);  bytes += sizeof(int);
1984     if (State & CMDLINE) {
1985         // HACK!  If Vim is in command line mode then the files names
1986         // should be added to the command line, instead of opening the
1987         // files in tabs.  This is taken care of by gui_handle_drop().
1988         char_u **fnames = (char_u **)alloc(n * sizeof(char_u *));
1989         if (fnames) {
1990             int i = 0;
1991             while (bytes < end && i < n) {
1992                 int len = *((int*)bytes);  bytes += sizeof(int);
1993                 char_u *s = (char_u*)bytes;
1994 #ifdef FEAT_MBYTE
1995                 s = CONVERT_FROM_UTF8(s);
1996 #endif
1997                 fnames[i++] = vim_strsave(s);
1998 #ifdef FEAT_MBYTE
1999                 CONVERT_FROM_UTF8_FREE(s);
2000 #endif
2001                 bytes += len;
2002             }
2004             // NOTE!  This function will free 'fnames'.
2005             // HACK!  It is assumed that the 'x' and 'y' arguments are
2006             // unused when in command line mode.
2007             gui_handle_drop(0, 0, 0, fnames, i < n ? i : n);
2008         }
2009     } else {
2010         // HACK!  I'm not sure how to get Vim to open a list of files in
2011         // tabs, so instead I create a ':tab drop' command with all the
2012         // files to open and execute it.
2013         NSMutableString *cmd = [NSMutableString stringWithString:@":tab drop"];
2015         int i;
2016         for (i = 0; i < n && bytes < end; ++i) {
2017             int len = *((int*)bytes);  bytes += sizeof(int);
2018             NSString *file = [NSString stringWithUTF8String:bytes];
2019             file = [file stringByEscapingSpecialFilenameCharacters];
2020             bytes += len;
2022             [cmd appendString:@" "];
2023             [cmd appendString:file];
2024         }
2026         // By going to the last tabpage we ensure that the new tabs will
2027         // appear last (if this call is left out, the taborder becomes
2028         // messy).
2029         goto_tabpage(9999);
2031         char_u *s = (char_u*)[cmd UTF8String];
2032 #ifdef FEAT_MBYTE
2033         s = CONVERT_FROM_UTF8(s);
2034 #endif
2035         do_cmdline_cmd(s);
2036 #ifdef FEAT_MBYTE
2037         CONVERT_FROM_UTF8_FREE(s);
2038 #endif
2040         // Force screen redraw (does it have to be this complicated?).
2041         // (This code was taken from the end of gui_handle_drop().)
2042         update_screen(NOT_VALID);
2043         setcursor();
2044         out_flush();
2045         gui_update_cursor(FALSE, FALSE);
2046         maketitle();
2047         gui_mch_flush();
2048     }
2049 #endif // FEAT_DND
2052 - (void)handleDropString:(NSData *)data
2054     if (!data) return;
2056 #ifdef FEAT_DND
2057     char_u  dropkey[3] = { CSI, KS_EXTRA, (char_u)KE_DROP };
2058     const void *bytes = [data bytes];
2059     int len = *((int*)bytes);  bytes += sizeof(int);
2060     NSMutableString *string = [NSMutableString stringWithUTF8String:bytes];
2062     // Replace unrecognized end-of-line sequences with \x0a (line feed).
2063     NSRange range = { 0, [string length] };
2064     unsigned n = [string replaceOccurrencesOfString:@"\x0d\x0a"
2065                                          withString:@"\x0a" options:0
2066                                               range:range];
2067     if (0 == n) {
2068         n = [string replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
2069                                        options:0 range:range];
2070     }
2072     len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
2073     char_u *s = (char_u*)[string UTF8String];
2074 #ifdef FEAT_MBYTE
2075     if (input_conv.vc_type != CONV_NONE)
2076         s = string_convert(&input_conv, s, &len);
2077 #endif
2078     dnd_yank_drag_data(s, len);
2079 #ifdef FEAT_MBYTE
2080     if (input_conv.vc_type != CONV_NONE)
2081         vim_free(s);
2082 #endif
2083     add_to_input_buf(dropkey, sizeof(dropkey));
2084 #endif // FEAT_DND
2087 @end // MMBackend (Private)
2092 @implementation MMBackend (ClientServer)
2094 - (NSString *)connectionNameFromServerName:(NSString *)name
2096     NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
2098     return [[NSString stringWithFormat:@"%@.%@", bundleIdentifier, name]
2099         lowercaseString];
2102 - (NSConnection *)connectionForServerName:(NSString *)name
2104     // TODO: Try 'name%d' if 'name' fails.
2105     NSString *connName = [self connectionNameFromServerName:name];
2106     NSConnection *svrConn = [connectionNameDict objectForKey:connName];
2108     if (!svrConn) {
2109         svrConn = [NSConnection connectionWithRegisteredName:connName
2110                                                            host:nil];
2111         // Try alternate server...
2112         if (!svrConn && alternateServerName) {
2113             //NSLog(@"  trying to connect to alternate server: %@",
2114             //        alternateServerName);
2115             connName = [self connectionNameFromServerName:alternateServerName];
2116             svrConn = [NSConnection connectionWithRegisteredName:connName
2117                                                             host:nil];
2118         }
2120         // Try looking for alternate servers...
2121         if (!svrConn) {
2122             //NSLog(@"  looking for alternate servers...");
2123             NSString *alt = [self alternateServerNameForName:name];
2124             if (alt != alternateServerName) {
2125                 //NSLog(@"  found alternate server: %@", string);
2126                 [alternateServerName release];
2127                 alternateServerName = [alt copy];
2128             }
2129         }
2131         // Try alternate server again...
2132         if (!svrConn && alternateServerName) {
2133             //NSLog(@"  trying to connect to alternate server: %@",
2134             //        alternateServerName);
2135             connName = [self connectionNameFromServerName:alternateServerName];
2136             svrConn = [NSConnection connectionWithRegisteredName:connName
2137                                                             host:nil];
2138         }
2140         if (svrConn) {
2141             [connectionNameDict setObject:svrConn forKey:connName];
2143             //NSLog(@"Adding %@ as connection observer for %@", self, svrConn);
2144             [[NSNotificationCenter defaultCenter] addObserver:self
2145                     selector:@selector(serverConnectionDidDie:)
2146                         name:NSConnectionDidDieNotification object:svrConn];
2147         }
2148     }
2150     return svrConn;
2153 - (NSConnection *)connectionForServerPort:(int)port
2155     NSConnection *conn;
2156     NSEnumerator *e = [connectionNameDict objectEnumerator];
2158     while ((conn = [e nextObject])) {
2159         // HACK! Assume connection uses mach ports.
2160         if (port == [(NSMachPort*)[conn sendPort] machPort])
2161             return conn;
2162     }
2164     return nil;
2167 - (void)serverConnectionDidDie:(NSNotification *)notification
2169     //NSLog(@"%s%@", _cmd, notification);
2171     NSConnection *svrConn = [notification object];
2173     //NSLog(@"Removing %@ as connection observer from %@", self, svrConn);
2174     [[NSNotificationCenter defaultCenter]
2175             removeObserver:self
2176                       name:NSConnectionDidDieNotification
2177                     object:svrConn];
2179     [connectionNameDict removeObjectsForKeys:
2180         [connectionNameDict allKeysForObject:svrConn]];
2182     // HACK! Assume connection uses mach ports.
2183     int port = [(NSMachPort*)[svrConn sendPort] machPort];
2184     NSNumber *key = [NSNumber numberWithInt:port];
2186     [clientProxyDict removeObjectForKey:key];
2187     [serverReplyDict removeObjectForKey:key];
2190 - (void)addClient:(NSDistantObject *)client
2192     NSConnection *conn = [client connectionForProxy];
2193     // HACK! Assume connection uses mach ports.
2194     int port = [(NSMachPort*)[conn sendPort] machPort];
2195     NSNumber *key = [NSNumber numberWithInt:port];
2197     if (![clientProxyDict objectForKey:key]) {
2198         [client setProtocolForProxy:@protocol(MMVimClientProtocol)];
2199         [clientProxyDict setObject:client forKey:key];
2200     }
2202     // NOTE: 'clientWindow' is a global variable which is used by <client>
2203     clientWindow = port;
2206 - (NSString *)alternateServerNameForName:(NSString *)name
2208     if (!(name && [name length] > 0))
2209         return nil;
2211     // Only look for alternates if 'name' doesn't end in a digit.
2212     unichar lastChar = [name characterAtIndex:[name length]-1];
2213     if (lastChar >= '0' && lastChar <= '9')
2214         return nil;
2216     // Look for alternates among all current servers.
2217     NSArray *list = [self serverList];
2218     if (!(list && [list count] > 0))
2219         return nil;
2221     // Filter out servers starting with 'name' and ending with a number. The
2222     // (?i) pattern ensures that the match is case insensitive.
2223     NSString *pat = [NSString stringWithFormat:@"(?i)%@[0-9]+\\z", name];
2224     NSPredicate *pred = [NSPredicate predicateWithFormat:
2225             @"SELF MATCHES %@", pat];
2226     list = [list filteredArrayUsingPredicate:pred];
2227     if ([list count] > 0) {
2228         list = [list sortedArrayUsingSelector:@selector(serverNameCompare:)];
2229         return [list objectAtIndex:0];
2230     }
2232     return nil;
2235 @end // MMBackend (ClientServer)
2240 @implementation NSString (MMServerNameCompare)
2241 - (NSComparisonResult)serverNameCompare:(NSString *)string
2243     return [self compare:string
2244                  options:NSCaseInsensitiveSearch|NSNumericSearch];
2246 @end
2251 static int eventModifierFlagsToVimModMask(int modifierFlags)
2253     int modMask = 0;
2255     if (modifierFlags & NSShiftKeyMask)
2256         modMask |= MOD_MASK_SHIFT;
2257     if (modifierFlags & NSControlKeyMask)
2258         modMask |= MOD_MASK_CTRL;
2259     if (modifierFlags & NSAlternateKeyMask)
2260         modMask |= MOD_MASK_ALT;
2261     if (modifierFlags & NSCommandKeyMask)
2262         modMask |= MOD_MASK_CMD;
2264     return modMask;
2267 static int vimModMaskToEventModifierFlags(int mods)
2269     int flags = 0;
2271     if (mods & MOD_MASK_SHIFT)
2272         flags |= NSShiftKeyMask;
2273     if (mods & MOD_MASK_CTRL)
2274         flags |= NSControlKeyMask;
2275     if (mods & MOD_MASK_ALT)
2276         flags |= NSAlternateKeyMask;
2277     if (mods & MOD_MASK_CMD)
2278         flags |= NSCommandKeyMask;
2280     return flags;
2283 static int eventModifierFlagsToVimMouseModMask(int modifierFlags)
2285     int modMask = 0;
2287     if (modifierFlags & NSShiftKeyMask)
2288         modMask |= MOUSE_SHIFT;
2289     if (modifierFlags & NSControlKeyMask)
2290         modMask |= MOUSE_CTRL;
2291     if (modifierFlags & NSAlternateKeyMask)
2292         modMask |= MOUSE_ALT;
2294     return modMask;
2297 static int eventButtonNumberToVimMouseButton(int buttonNumber)
2299     static int mouseButton[] = { MOUSE_LEFT, MOUSE_RIGHT, MOUSE_MIDDLE };
2301     return (buttonNumber >= 0 && buttonNumber < 3)
2302             ? mouseButton[buttonNumber] : -1;
2305 static int specialKeyToNSKey(int key)
2307     if (!IS_SPECIAL(key))
2308         return key;
2310     static struct {
2311         int special;
2312         int nskey;
2313     } sp2ns[] = {
2314         { K_UP, NSUpArrowFunctionKey },
2315         { K_DOWN, NSDownArrowFunctionKey },
2316         { K_LEFT, NSLeftArrowFunctionKey },
2317         { K_RIGHT, NSRightArrowFunctionKey },
2318         { K_F1, NSF1FunctionKey },
2319         { K_F2, NSF2FunctionKey },
2320         { K_F3, NSF3FunctionKey },
2321         { K_F4, NSF4FunctionKey },
2322         { K_F5, NSF5FunctionKey },
2323         { K_F6, NSF6FunctionKey },
2324         { K_F7, NSF7FunctionKey },
2325         { K_F8, NSF8FunctionKey },
2326         { K_F9, NSF9FunctionKey },
2327         { K_F10, NSF10FunctionKey },
2328         { K_F11, NSF11FunctionKey },
2329         { K_F12, NSF12FunctionKey },
2330         { K_F13, NSF13FunctionKey },
2331         { K_F14, NSF14FunctionKey },
2332         { K_F15, NSF15FunctionKey },
2333         { K_F16, NSF16FunctionKey },
2334         { K_F17, NSF17FunctionKey },
2335         { K_F18, NSF18FunctionKey },
2336         { K_F19, NSF19FunctionKey },
2337         { K_F20, NSF20FunctionKey },
2338         { K_F21, NSF21FunctionKey },
2339         { K_F22, NSF22FunctionKey },
2340         { K_F23, NSF23FunctionKey },
2341         { K_F24, NSF24FunctionKey },
2342         { K_F25, NSF25FunctionKey },
2343         { K_F26, NSF26FunctionKey },
2344         { K_F27, NSF27FunctionKey },
2345         { K_F28, NSF28FunctionKey },
2346         { K_F29, NSF29FunctionKey },
2347         { K_F30, NSF30FunctionKey },
2348         { K_F31, NSF31FunctionKey },
2349         { K_F32, NSF32FunctionKey },
2350         { K_F33, NSF33FunctionKey },
2351         { K_F34, NSF34FunctionKey },
2352         { K_F35, NSF35FunctionKey },
2353         { K_DEL, NSBackspaceCharacter },
2354         { K_BS, NSDeleteCharacter },
2355         { K_HOME, NSHomeFunctionKey },
2356         { K_END, NSEndFunctionKey },
2357         { K_PAGEUP, NSPageUpFunctionKey },
2358         { K_PAGEDOWN, NSPageDownFunctionKey }
2359     };
2361     int i;
2362     for (i = 0; i < sizeof(sp2ns)/sizeof(sp2ns[0]); ++i) {
2363         if (sp2ns[i].special == key)
2364             return sp2ns[i].nskey;
2365     }
2367     return 0;