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