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