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