1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
3 * VIM - Vi IMproved by Bram Moolenaar
4 * MacVim GUI port by Bjorn Winckler
6 * Do ":help uganda" in Vim to read copying and usage conditions.
7 * Do ":help credits" in Vim to see a list of people who contributed.
8 * See README.txt for an overview of the Vim source code.
16 // This constant controls how often the command queue may be flushed. If it is
17 // too small the app might feel unresponsive; if it is too large there might be
18 // long periods without the screen updating (e.g. when sourcing a large session
19 // file). (The unit is seconds.)
20 static float MMFlushTimeoutInterval = 0.1f;
23 // TODO: Move to separate file.
24 static int eventModifierFlagsToVimModMask(int modifierFlags);
25 static int vimModMaskToEventModifierFlags(int mods);
26 static int eventModifierFlagsToVimMouseModMask(int modifierFlags);
27 static int eventButtonNumberToVimMouseButton(int buttonNumber);
28 static int specialKeyToNSKey(int key);
37 @interface MMBackend (Private)
38 - (void)handleMessage:(int)msgid data:(NSData *)data;
39 + (NSDictionary *)specialKeys;
40 - (void)handleKeyDown:(NSString *)key modifiers:(int)mods;
41 - (void)queueMessage:(int)msgid data:(NSData *)data;
42 - (void)connectionDidDie:(NSNotification *)notification;
43 - (void)blinkTimerFired:(NSTimer *)timer;
44 - (void)focusChange:(BOOL)on;
45 - (void)processInputBegin;
46 - (void)processInputEnd;
51 @implementation MMBackend
53 + (MMBackend *)sharedInstance
55 static MMBackend *singleton = nil;
56 return singleton ? singleton : (singleton = [MMBackend new]);
61 if ((self = [super init])) {
62 queue = [[NSMutableArray alloc] init];
63 #if MM_USE_INPUT_QUEUE
64 inputQueue = [[NSMutableArray alloc] init];
66 drawData = [[NSMutableData alloc] initWithCapacity:1024];
68 NSString *path = [[NSBundle mainBundle] pathForResource:@"Colors"
71 colorDict = [[NSDictionary dictionaryWithContentsOfFile:path]
74 NSLog(@"WARNING: Could not locate Colors.plist.");
77 path = [[NSBundle mainBundle] pathForResource:@"SystemColors"
80 sysColorDict = [[NSDictionary dictionaryWithContentsOfFile:path]
83 NSLog(@"WARNING: Could not locate SystemColors.plist.");
92 //NSLog(@"%@ %s", [self className], _cmd);
94 [[NSNotificationCenter defaultCenter] removeObserver:self];
96 [blinkTimer release]; blinkTimer = nil;
97 #if MM_USE_INPUT_QUEUE
98 [inputQueue release]; inputQueue = nil;
100 [queue release]; queue = nil;
101 [drawData release]; drawData = nil;
102 [frontendProxy release]; frontendProxy = nil;
103 [connection release]; connection = nil;
104 [sysColorDict release]; sysColorDict = nil;
105 [colorDict release]; colorDict = nil;
110 - (void)setBackgroundColor:(int)color
112 backgroundColor = color;
115 - (void)setForegroundColor:(int)color
117 foregroundColor = color;
120 - (void)setSpecialColor:(int)color
122 specialColor = color;
125 - (void)setDefaultColorsBackground:(int)bg foreground:(int)fg
127 defaultBackgroundColor = bg;
128 defaultForegroundColor = fg;
130 NSMutableData *data = [NSMutableData data];
132 [data appendBytes:&bg length:sizeof(int)];
133 [data appendBytes:&fg length:sizeof(int)];
135 [self queueMessage:SetDefaultColorsMsgID data:data];
140 NSBundle *mainBundle = [NSBundle mainBundle];
142 // NOTE! If the name of the connection changes here it must also be
143 // updated in MMAppController.m.
144 NSString *name = [NSString stringWithFormat:@"%@-connection",
145 [mainBundle bundleIdentifier]];
146 connection = [NSConnection connectionWithRegisteredName:name host:nil];
149 NSString *path = [mainBundle bundlePath];
150 if (![[NSWorkspace sharedWorkspace] launchApplication:path]) {
151 NSLog(@"WARNING: Failed to launch GUI with path %@", path);
155 // HACK! It would be preferable to launch the GUI using NSWorkspace,
156 // however I have not managed to figure out how to pass arguments using
159 // NOTE! Using NSTask to launch the GUI has the negative side-effect
160 // that the GUI won't be activated (or raised) so there is a hack in
161 // MMWindowController which always raises the app when a new window is
163 NSMutableArray *args = [NSMutableArray arrayWithObjects:
164 [NSString stringWithFormat:@"-%@", MMNoWindowKey], @"yes", nil];
165 NSString *exeName = [[mainBundle infoDictionary]
166 objectForKey:@"CFBundleExecutable"];
167 NSString *path = [mainBundle pathForAuxiliaryExecutable:exeName];
169 NSLog(@"ERROR: Could not find MacVim executable in bundle");
173 [NSTask launchedTaskWithLaunchPath:path arguments:args];
176 // HACK! The NSWorkspaceDidLaunchApplicationNotification does not work
177 // for tasks like this, so poll the mach bootstrap server until it
178 // returns a valid connection. Also set a time-out date so that we
179 // don't get stuck doing this forever.
180 NSDate *timeOutDate = [NSDate dateWithTimeIntervalSinceNow:15];
181 while (!connection &&
182 NSOrderedDescending == [timeOutDate compare:[NSDate date]])
184 [[NSRunLoop currentRunLoop]
185 runMode:NSDefaultRunLoopMode
186 beforeDate:[NSDate dateWithTimeIntervalSinceNow:1]];
188 connection = [NSConnection connectionWithRegisteredName:name
193 NSLog(@"WARNING: Timed-out waiting for GUI to launch.");
198 id proxy = [connection rootProxy];
199 [proxy setProtocolForProxy:@protocol(MMAppProtocol)];
201 [[NSNotificationCenter defaultCenter] addObserver:self
202 selector:@selector(connectionDidDie:)
203 name:NSConnectionDidDieNotification object:connection];
205 int pid = [[NSProcessInfo processInfo] processIdentifier];
208 frontendProxy = [(NSDistantObject*)[proxy connectBackend:self
211 @catch (NSException *e) {
212 NSLog(@"Exception caught when trying to connect backend: \"%@\"", e);
216 [frontendProxy setProtocolForProxy:@protocol(MMAppProtocol)];
219 return connection && frontendProxy;
222 - (BOOL)openVimWindow
224 [self queueMessage:OpenVimWindowMsgID data:nil];
230 int type = ClearAllDrawType;
232 // Any draw commands in queue are effectively obsolete since this clearAll
233 // will negate any effect they have, therefore we may as well clear the
235 [drawData setLength:0];
237 [drawData appendBytes:&type length:sizeof(int)];
239 [drawData appendBytes:&defaultBackgroundColor length:sizeof(int)];
242 - (void)clearBlockFromRow:(int)row1 column:(int)col1
243 toRow:(int)row2 column:(int)col2
245 int type = ClearBlockDrawType;
247 [drawData appendBytes:&type length:sizeof(int)];
249 [drawData appendBytes:&defaultBackgroundColor length:sizeof(int)];
250 [drawData appendBytes:&row1 length:sizeof(int)];
251 [drawData appendBytes:&col1 length:sizeof(int)];
252 [drawData appendBytes:&row2 length:sizeof(int)];
253 [drawData appendBytes:&col2 length:sizeof(int)];
256 - (void)deleteLinesFromRow:(int)row count:(int)count
257 scrollBottom:(int)bottom left:(int)left right:(int)right
259 int type = DeleteLinesDrawType;
261 [drawData appendBytes:&type length:sizeof(int)];
263 [drawData appendBytes:&defaultBackgroundColor length:sizeof(int)];
264 [drawData appendBytes:&row length:sizeof(int)];
265 [drawData appendBytes:&count length:sizeof(int)];
266 [drawData appendBytes:&bottom length:sizeof(int)];
267 [drawData appendBytes:&left length:sizeof(int)];
268 [drawData appendBytes:&right length:sizeof(int)];
271 - (void)replaceString:(char*)s length:(int)len row:(int)row column:(int)col
274 if (len <= 0) return;
276 int type = ReplaceStringDrawType;
278 [drawData appendBytes:&type length:sizeof(int)];
280 [drawData appendBytes:&backgroundColor length:sizeof(int)];
281 [drawData appendBytes:&foregroundColor length:sizeof(int)];
282 [drawData appendBytes:&specialColor length:sizeof(int)];
283 [drawData appendBytes:&row length:sizeof(int)];
284 [drawData appendBytes:&col length:sizeof(int)];
285 [drawData appendBytes:&flags length:sizeof(int)];
286 [drawData appendBytes:&len length:sizeof(int)];
287 [drawData appendBytes:s length:len];
290 - (void)insertLinesFromRow:(int)row count:(int)count
291 scrollBottom:(int)bottom left:(int)left right:(int)right
293 int type = InsertLinesDrawType;
295 [drawData appendBytes:&type length:sizeof(int)];
297 [drawData appendBytes:&defaultBackgroundColor length:sizeof(int)];
298 [drawData appendBytes:&row length:sizeof(int)];
299 [drawData appendBytes:&count length:sizeof(int)];
300 [drawData appendBytes:&bottom length:sizeof(int)];
301 [drawData appendBytes:&left length:sizeof(int)];
302 [drawData appendBytes:&right length:sizeof(int)];
305 - (void)drawCursorAtRow:(int)row column:(int)col shape:(int)shape
306 fraction:(int)percent color:(int)color
308 int type = DrawCursorDrawType;
310 [drawData appendBytes:&type length:sizeof(int)];
312 [drawData appendBytes:&color length:sizeof(int)];
313 [drawData appendBytes:&row length:sizeof(int)];
314 [drawData appendBytes:&col length:sizeof(int)];
315 [drawData appendBytes:&shape length:sizeof(int)];
316 [drawData appendBytes:&percent length:sizeof(int)];
319 - (void)flushQueue:(BOOL)force
321 // NOTE! This method gets called a lot; if we were to flush every time it
322 // was called MacVim would feel unresponsive. So there is a time out which
323 // ensures that the queue isn't flushed too often.
324 if (!force && lastFlushDate && -[lastFlushDate timeIntervalSinceNow]
325 < MMFlushTimeoutInterval)
328 if ([drawData length] > 0) {
329 [self queueMessage:BatchDrawMsgID data:[drawData copy]];
330 [drawData setLength:0];
333 if ([queue count] > 0) {
335 [frontendProxy processCommandQueue:queue];
337 @catch (NSException *e) {
338 NSLog(@"Exception caught when processing command queue: \"%@\"", e);
341 [queue removeAllObjects];
343 [lastFlushDate release];
344 lastFlushDate = [[NSDate date] retain];
348 - (BOOL)waitForInput:(int)milliseconds
350 NSDate *date = milliseconds > 0 ?
351 [NSDate dateWithTimeIntervalSinceNow:.001*milliseconds] :
352 [NSDate distantFuture];
354 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:date];
356 // I know of no way to figure out if the run loop exited because input was
357 // found or because of a time out, so I need to manually indicate when
358 // input was received in processInput:data: and then reset it every time
360 BOOL yn = inputReceived;
368 // By invalidating the NSConnection the MMWindowController immediately
369 // finds out that the connection is down and as a result
370 // [MMWindowController connectionDidDie:] is invoked.
371 //NSLog(@"%@ %s", [self className], _cmd);
372 [[NSNotificationCenter defaultCenter] removeObserver:self];
373 [connection invalidate];
376 - (void)selectTab:(int)index
378 //NSLog(@"%s%d", _cmd, index);
381 NSData *data = [NSData dataWithBytes:&index length:sizeof(int)];
382 [self queueMessage:SelectTabMsgID data:data];
387 //NSLog(@"%s", _cmd);
389 NSMutableData *data = [NSMutableData data];
391 int idx = tabpage_index(curtab) - 1;
392 [data appendBytes:&idx length:sizeof(int)];
395 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next) {
396 // This function puts the label of the tab in the global 'NameBuff'.
397 get_tabline_label(tp, FALSE);
398 int len = strlen((char*)NameBuff);
399 if (len <= 0) continue;
401 // Count the number of windows in the tabpage.
402 //win_T *wp = tp->tp_firstwin;
404 //for (wincount = 0; wp != NULL; wp = wp->w_next, ++wincount);
406 //[data appendBytes:&wincount length:sizeof(int)];
407 [data appendBytes:&len length:sizeof(int)];
408 [data appendBytes:NameBuff length:len];
411 [self queueMessage:UpdateTabBarMsgID data:data];
414 - (BOOL)tabBarVisible
416 return tabBarVisible;
419 - (void)showTabBar:(BOOL)enable
421 tabBarVisible = enable;
423 int msgid = enable ? ShowTabBarMsgID : HideTabBarMsgID;
424 [self queueMessage:msgid data:nil];
427 - (void)setRows:(int)rows columns:(int)cols
429 //NSLog(@"[VimTask] setRows:%d columns:%d", rows, cols);
431 int dim[] = { rows, cols };
432 NSData *data = [NSData dataWithBytes:&dim length:2*sizeof(int)];
434 [self queueMessage:SetTextDimensionsMsgID data:data];
437 - (void)setVimWindowTitle:(char *)title
439 NSMutableData *data = [NSMutableData data];
440 int len = strlen(title);
441 if (len <= 0) return;
443 [data appendBytes:&len length:sizeof(int)];
444 [data appendBytes:title length:len];
446 [self queueMessage:SetVimWindowTitleMsgID data:data];
449 - (char *)browseForFileInDirectory:(char *)dir title:(char *)title
452 //NSLog(@"browseForFileInDirectory:%s title:%s saving:%d", dir, title,
457 ? [NSString stringWithCString:dir encoding:NSUTF8StringEncoding]
460 ? [NSString stringWithCString:title encoding:NSUTF8StringEncoding]
463 [frontendProxy showSavePanelForDirectory:ds title:ts saving:saving];
465 // Wait until a reply is sent from MMVimController.
466 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
467 beforeDate:[NSDate distantFuture]];
469 if (dialogReturn && [dialogReturn isKindOfClass:[NSString class]]) {
470 s = vim_strsave((char_u*)[dialogReturn UTF8String]);
473 [dialogReturn release]; dialogReturn = nil;
475 @catch (NSException *e) {
476 NSLog(@"Exception caught when showing save panel: \"%@\"", e);
482 - (oneway void)setDialogReturn:(in bycopy id)obj
484 // NOTE: This is called by
485 // - [MMVimController panelDidEnd:::], and
486 // - [MMVimController alertDidEnd:::],
487 // to indicate that a save/open panel or alert has finished.
489 if (obj != dialogReturn) {
490 [dialogReturn release];
491 dialogReturn = [obj retain];
495 - (int)presentDialogWithType:(int)type title:(char *)title message:(char *)msg
496 buttons:(char *)btns textField:(char *)txtfield
499 NSString *message = nil, *text = nil, *textFieldString = nil;
500 NSArray *buttons = nil;
501 int style = NSInformationalAlertStyle;
503 if (VIM_WARNING == type) style = NSWarningAlertStyle;
504 else if (VIM_ERROR == type) style = NSCriticalAlertStyle;
507 NSString *btnString = [NSString stringWithUTF8String:btns];
508 buttons = [btnString componentsSeparatedByString:@"\n"];
511 message = [NSString stringWithUTF8String:title];
513 text = [NSString stringWithUTF8String:msg];
515 // HACK! If there is a '\n\n' or '\n' sequence in the message, then
516 // make the part up to there into the title. We only do this
517 // because Vim has lots of dialogs without a title and they look
519 // TODO: Fix the actual dialog texts.
520 NSRange eolRange = [text rangeOfString:@"\n\n"];
521 if (NSNotFound == eolRange.location)
522 eolRange = [text rangeOfString:@"\n"];
523 if (NSNotFound != eolRange.location) {
524 message = [text substringToIndex:eolRange.location];
525 text = [text substringFromIndex:NSMaxRange(eolRange)];
530 textFieldString = [NSString stringWithUTF8String:txtfield];
533 [frontendProxy presentDialogWithStyle:style message:message
534 informativeText:text buttonTitles:buttons
535 textFieldString:textFieldString];
537 // Wait until a reply is sent from MMVimController.
538 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
539 beforeDate:[NSDate distantFuture]];
541 if (dialogReturn && [dialogReturn isKindOfClass:[NSArray class]]
542 && [dialogReturn count]) {
543 retval = [[dialogReturn objectAtIndex:0] intValue];
544 if (txtfield && [dialogReturn count] > 1) {
545 NSString *retString = [dialogReturn objectAtIndex:1];
546 vim_strncpy((char_u*)txtfield, (char_u*)[retString UTF8String],
551 [dialogReturn release]; dialogReturn = nil;
553 @catch (NSException *e) {
554 NSLog(@"Exception caught while showing alert dialog: \"%@\"", e);
560 - (void)addMenuWithTag:(int)tag parent:(int)parentTag name:(char *)name
563 //NSLog(@"addMenuWithTag:%d parent:%d name:%s atIndex:%d", tag, parentTag,
566 int namelen = name ? strlen(name) : 0;
567 NSMutableData *data = [NSMutableData data];
569 [data appendBytes:&tag length:sizeof(int)];
570 [data appendBytes:&parentTag length:sizeof(int)];
571 [data appendBytes:&namelen length:sizeof(int)];
572 if (namelen > 0) [data appendBytes:name length:namelen];
573 [data appendBytes:&index length:sizeof(int)];
575 [self queueMessage:AddMenuMsgID data:data];
578 - (void)addMenuItemWithTag:(int)tag parent:(int)parentTag name:(char *)name
579 tip:(char *)tip icon:(char *)icon
580 keyEquivalent:(int)key modifiers:(int)mods
581 action:(NSString *)action atIndex:(int)index
583 //NSLog(@"addMenuItemWithTag:%d parent:%d name:%s tip:%s atIndex:%d", tag,
584 // parentTag, name, tip, index);
586 int namelen = name ? strlen(name) : 0;
587 int tiplen = tip ? strlen(tip) : 0;
588 int iconlen = icon ? strlen(icon) : 0;
589 int eventFlags = vimModMaskToEventModifierFlags(mods);
590 int actionlen = [action lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
591 NSMutableData *data = [NSMutableData data];
593 key = specialKeyToNSKey(key);
595 [data appendBytes:&tag length:sizeof(int)];
596 [data appendBytes:&parentTag length:sizeof(int)];
597 [data appendBytes:&namelen length:sizeof(int)];
598 if (namelen > 0) [data appendBytes:name length:namelen];
599 [data appendBytes:&tiplen length:sizeof(int)];
600 if (tiplen > 0) [data appendBytes:tip length:tiplen];
601 [data appendBytes:&iconlen length:sizeof(int)];
602 if (iconlen > 0) [data appendBytes:icon length:iconlen];
603 [data appendBytes:&actionlen length:sizeof(int)];
604 if (actionlen > 0) [data appendBytes:[action UTF8String] length:actionlen];
605 [data appendBytes:&index length:sizeof(int)];
606 [data appendBytes:&key length:sizeof(int)];
607 [data appendBytes:&eventFlags length:sizeof(int)];
609 [self queueMessage:AddMenuItemMsgID data:data];
612 - (void)removeMenuItemWithTag:(int)tag
614 NSMutableData *data = [NSMutableData data];
615 [data appendBytes:&tag length:sizeof(int)];
617 [self queueMessage:RemoveMenuItemMsgID data:data];
620 - (void)enableMenuItemWithTag:(int)tag state:(int)enabled
622 NSMutableData *data = [NSMutableData data];
624 [data appendBytes:&tag length:sizeof(int)];
625 [data appendBytes:&enabled length:sizeof(int)];
627 [self queueMessage:EnableMenuItemMsgID data:data];
630 - (void)showPopupMenuWithName:(char *)name atMouseLocation:(BOOL)mouse
632 int len = strlen(name);
633 int row = -1, col = -1;
635 if (len <= 0) return;
637 if (!mouse && curwin) {
638 row = curwin->w_wrow;
639 col = curwin->w_wcol;
642 NSMutableData *data = [NSMutableData data];
644 [data appendBytes:&row length:sizeof(int)];
645 [data appendBytes:&col length:sizeof(int)];
646 [data appendBytes:&len length:sizeof(int)];
647 [data appendBytes:name length:len];
649 [self queueMessage:ShowPopupMenuMsgID data:data];
652 - (void)showToolbar:(int)enable flags:(int)flags
654 NSMutableData *data = [NSMutableData data];
656 [data appendBytes:&enable length:sizeof(int)];
657 [data appendBytes:&flags length:sizeof(int)];
659 [self queueMessage:ShowToolbarMsgID data:data];
662 - (void)createScrollbarWithIdentifier:(long)ident type:(int)type
664 NSMutableData *data = [NSMutableData data];
666 [data appendBytes:&ident length:sizeof(long)];
667 [data appendBytes:&type length:sizeof(int)];
669 [self queueMessage:CreateScrollbarMsgID data:data];
672 - (void)destroyScrollbarWithIdentifier:(long)ident
674 NSMutableData *data = [NSMutableData data];
675 [data appendBytes:&ident length:sizeof(long)];
677 [self queueMessage:DestroyScrollbarMsgID data:data];
680 - (void)showScrollbarWithIdentifier:(long)ident state:(int)visible
682 NSMutableData *data = [NSMutableData data];
684 [data appendBytes:&ident length:sizeof(long)];
685 [data appendBytes:&visible length:sizeof(int)];
687 [self queueMessage:ShowScrollbarMsgID data:data];
690 - (void)setScrollbarPosition:(int)pos length:(int)len identifier:(long)ident
692 NSMutableData *data = [NSMutableData data];
694 [data appendBytes:&ident length:sizeof(long)];
695 [data appendBytes:&pos length:sizeof(int)];
696 [data appendBytes:&len length:sizeof(int)];
698 [self queueMessage:SetScrollbarPositionMsgID data:data];
701 - (void)setScrollbarThumbValue:(long)val size:(long)size max:(long)max
702 identifier:(long)ident
704 float fval = max-size+1 > 0 ? (float)val/(max-size+1) : 0;
705 float prop = (float)size/(max+1);
706 if (fval < 0) fval = 0;
707 else if (fval > 1.0f) fval = 1.0f;
708 if (prop < 0) prop = 0;
709 else if (prop > 1.0f) prop = 1.0f;
711 NSMutableData *data = [NSMutableData data];
713 [data appendBytes:&ident length:sizeof(long)];
714 [data appendBytes:&fval length:sizeof(float)];
715 [data appendBytes:&prop length:sizeof(float)];
717 [self queueMessage:SetScrollbarThumbMsgID data:data];
720 - (BOOL)setFontWithName:(char *)name
724 BOOL parseFailed = NO;
727 fontName = [[[NSString alloc] initWithCString:name
728 encoding:NSUTF8StringEncoding] autorelease];
729 NSArray *components = [fontName componentsSeparatedByString:@":"];
730 if ([components count] == 2) {
731 NSString *sizeString = [components lastObject];
732 if ([sizeString length] > 0
733 && [sizeString characterAtIndex:0] == 'h') {
734 sizeString = [sizeString substringFromIndex:1];
735 if ([sizeString length] > 0) {
736 size = [sizeString floatValue];
737 fontName = [components objectAtIndex:0];
742 } else if ([components count] > 2) {
746 fontName = [[NSFont userFixedPitchFontOfSize:0] displayName];
749 if (!parseFailed && [fontName length] > 0) {
750 if (size < 6 || size > 100) {
751 // Font size 0.0 tells NSFont to use the 'user default size'.
755 NSFont *font = [NSFont fontWithName:fontName size:size];
757 //NSLog(@"Setting font '%@' of size %.2f", fontName, size);
759 lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
761 NSMutableData *data = [NSMutableData data];
763 [data appendBytes:&size length:sizeof(float)];
764 [data appendBytes:&len length:sizeof(int)];
765 [data appendBytes:[fontName UTF8String] length:len];
767 [self queueMessage:SetFontMsgID data:data];
773 NSLog(@"WARNING: Cannot set font with name '%@' of size %.2f",
778 - (void)executeActionWithName:(NSString *)name
780 int len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
783 NSMutableData *data = [NSMutableData data];
785 [data appendBytes:&len length:sizeof(int)];
786 [data appendBytes:[name UTF8String] length:len];
788 [self queueMessage:ExecuteActionMsgID data:data];
792 - (void)setMouseShape:(int)shape
794 NSMutableData *data = [NSMutableData data];
795 [data appendBytes:&shape length:sizeof(int)];
796 [self queueMessage:SetMouseShapeMsgID data:data];
799 - (void)setBlinkWait:(int)wait on:(int)on off:(int)off
801 // Vim specifies times in milliseconds, whereas Cocoa wants them in
803 blinkWaitInterval = .001f*wait;
804 blinkOnInterval = .001f*on;
805 blinkOffInterval = .001f*off;
811 [blinkTimer invalidate];
812 [blinkTimer release];
816 if (blinkWaitInterval > 0 && blinkOnInterval > 0 && blinkOffInterval > 0
818 blinkState = MMBlinkStateOn;
820 [[NSTimer scheduledTimerWithTimeInterval:blinkWaitInterval
822 selector:@selector(blinkTimerFired:)
823 userInfo:nil repeats:NO] retain];
824 gui_update_cursor(TRUE, FALSE);
825 [self flushQueue:YES];
831 if (MMBlinkStateOff == blinkState) {
832 gui_update_cursor(TRUE, FALSE);
833 [self flushQueue:YES];
836 blinkState = MMBlinkStateNone;
839 - (int)lookupColorWithKey:(NSString *)key
841 if (!(key && [key length] > 0))
844 NSString *stripKey = [[[[key lowercaseString]
845 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
846 componentsSeparatedByString:@" "]
847 componentsJoinedByString:@""];
849 if (stripKey && [stripKey length] > 0) {
850 // First of all try to lookup key in the color dictionary; note that
851 // all keys in this dictionary are lowercase with no whitespace.
852 id obj = [colorDict objectForKey:stripKey];
853 if (obj) return [obj intValue];
855 // The key was not in the dictionary; is it perhaps of the form
857 if ([stripKey length] > 1 && [stripKey characterAtIndex:0] == '#') {
858 NSScanner *scanner = [NSScanner scannerWithString:stripKey];
859 [scanner setScanLocation:1];
861 if ([scanner scanHexInt:&hex]) {
866 // As a last resort, check if it is one of the system defined colors.
867 // The keys in this dictionary are also lowercase with no whitespace.
868 obj = [sysColorDict objectForKey:stripKey];
870 NSColor *col = [NSColor performSelector:NSSelectorFromString(obj)];
873 col = [col colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
874 [col getRed:&r green:&g blue:&b alpha:&a];
875 return ((int)(r*255) << 16) + ((int)(g*255) << 8)
881 NSLog(@"WARNING: No color with key %@ found.", stripKey);
885 - (oneway void)processInput:(int)msgid data:(in NSData *)data
887 if (inProcessInput) {
888 #if MM_USE_INPUT_QUEUE
889 [inputQueue addObject:[NSNumber numberWithInt:msgid]];
890 [inputQueue addObject:data];
892 // Just drop the input
893 NSLog(@"WARNING: Dropping input in %s", _cmd);
896 [self processInputBegin];
897 [self handleMessage:msgid data:data];
898 [self processInputEnd];
902 - (oneway void)processInputAndData:(in NSArray *)messages
904 unsigned i, count = [messages count];
906 NSLog(@"WARNING: [messages count] is odd in %s", _cmd);
910 if (inProcessInput) {
911 #if MM_USE_INPUT_QUEUE
912 [inputQueue addObjectsFromArray:messages];
914 // Just drop the input
915 NSLog(@"WARNING: Dropping input in %s", _cmd);
918 [self processInputBegin];
920 for (i = 0; i < count; i += 2) {
921 int msgid = [[messages objectAtIndex:i] intValue];
922 id data = [messages objectAtIndex:i+1];
923 if ([data isEqual:[NSNull null]])
926 [self handleMessage:msgid data:data];
929 [self processInputEnd];
933 - (BOOL)checkForModifiedBuffers
936 for (buf = firstbuf; buf != NULL; buf = buf->b_next) {
937 if (bufIsChanged(buf)) {
945 - (BOOL)starRegisterToPasteboard:(byref NSPasteboard *)pboard
947 if (VIsual_active && (State & NORMAL) && clip_star.available) {
948 // If there is no pasteboard, return YES to indicate that there is text
953 clip_copy_selection();
955 // Get the text to put on the pasteboard.
956 long_u len = 0; char_u *str = 0;
957 int type = clip_convert_selection(&str, &len, &clip_star);
961 NSString *string = [[NSString alloc]
962 initWithBytes:str length:len encoding:NSUTF8StringEncoding];
964 NSArray *types = [NSArray arrayWithObject:NSStringPboardType];
965 [pboard declareTypes:types owner:nil];
966 BOOL ok = [pboard setString:string forType:NSStringPboardType];
981 @implementation MMBackend (Private)
983 - (void)handleMessage:(int)msgid data:(NSData *)data
985 if (InsertTextMsgID == msgid) {
987 NSString *key = [[NSString alloc] initWithData:data
988 encoding:NSUTF8StringEncoding];
989 char_u *str = (char_u*)[key UTF8String];
990 int i, len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
993 char_u *conv_str = NULL;
994 if (input_conv.vc_type != CONV_NONE) {
995 conv_str = string_convert(&input_conv, str, &len);
1001 for (i = 0; i < len; ++i) {
1002 add_to_input_buf(str+i, 1);
1003 if (CSI == str[i]) {
1004 // NOTE: If the converted string contains the byte CSI, then it
1005 // must be followed by the bytes KS_EXTRA, KE_CSI or things
1007 static char_u extra[2] = { KS_EXTRA, KE_CSI };
1008 add_to_input_buf(extra, 2);
1017 } else if (KeyDownMsgID == msgid || CmdKeyMsgID == msgid) {
1019 const void *bytes = [data bytes];
1020 int mods = *((int*)bytes); bytes += sizeof(int);
1021 int len = *((int*)bytes); bytes += sizeof(int);
1022 NSString *key = [[NSString alloc] initWithBytes:bytes length:len
1023 encoding:NSUTF8StringEncoding];
1024 mods = eventModifierFlagsToVimModMask(mods);
1026 [self handleKeyDown:key modifiers:mods];
1029 } else if (SelectTabMsgID == msgid) {
1031 const void *bytes = [data bytes];
1032 int idx = *((int*)bytes) + 1;
1033 //NSLog(@"Selecting tab %d", idx);
1034 send_tabline_event(idx);
1035 } else if (CloseTabMsgID == msgid) {
1037 const void *bytes = [data bytes];
1038 int idx = *((int*)bytes) + 1;
1039 //NSLog(@"Closing tab %d", idx);
1040 send_tabline_menu_event(idx, TABLINE_MENU_CLOSE);
1041 } else if (AddNewTabMsgID == msgid) {
1042 //NSLog(@"Adding new tab");
1043 send_tabline_menu_event(0, TABLINE_MENU_NEW);
1044 } else if (DraggedTabMsgID == msgid) {
1046 const void *bytes = [data bytes];
1047 // NOTE! The destination index is 0 based, so do not add 1 to make it 1
1049 int idx = *((int*)bytes);
1052 } else if (ScrollWheelMsgID == msgid) {
1054 const void *bytes = [data bytes];
1056 int row = *((int*)bytes); bytes += sizeof(int);
1057 int col = *((int*)bytes); bytes += sizeof(int);
1058 int flags = *((int*)bytes); bytes += sizeof(int);
1059 float dy = *((float*)bytes); bytes += sizeof(float);
1061 int button = MOUSE_5;
1062 if (dy > 0) button = MOUSE_4;
1064 flags = eventModifierFlagsToVimMouseModMask(flags);
1066 gui_send_mouse_event(button, col, row, NO, flags);
1067 } else if (MouseDownMsgID == msgid) {
1069 const void *bytes = [data bytes];
1071 int row = *((int*)bytes); bytes += sizeof(int);
1072 int col = *((int*)bytes); bytes += sizeof(int);
1073 int button = *((int*)bytes); bytes += sizeof(int);
1074 int flags = *((int*)bytes); bytes += sizeof(int);
1075 int count = *((int*)bytes); bytes += sizeof(int);
1077 button = eventButtonNumberToVimMouseButton(button);
1078 flags = eventModifierFlagsToVimMouseModMask(flags);
1080 gui_send_mouse_event(button, col, row, 0 != count, flags);
1081 } else if (MouseUpMsgID == msgid) {
1083 const void *bytes = [data bytes];
1085 int row = *((int*)bytes); bytes += sizeof(int);
1086 int col = *((int*)bytes); bytes += sizeof(int);
1087 int flags = *((int*)bytes); bytes += sizeof(int);
1089 flags = eventModifierFlagsToVimMouseModMask(flags);
1091 gui_send_mouse_event(MOUSE_RELEASE, col, row, NO, flags);
1092 } else if (MouseDraggedMsgID == msgid) {
1094 const void *bytes = [data bytes];
1096 int row = *((int*)bytes); bytes += sizeof(int);
1097 int col = *((int*)bytes); bytes += sizeof(int);
1098 int flags = *((int*)bytes); bytes += sizeof(int);
1100 flags = eventModifierFlagsToVimMouseModMask(flags);
1102 gui_send_mouse_event(MOUSE_DRAG, col, row, NO, flags);
1103 } else if (SetTextDimensionsMsgID == msgid) {
1105 const void *bytes = [data bytes];
1106 int rows = *((int*)bytes); bytes += sizeof(int);
1107 int cols = *((int*)bytes); bytes += sizeof(int);
1109 // NOTE! Vim doesn't call gui_mch_set_shellsize() after
1110 // gui_resize_shell(), so we have to manually set the rows and columns
1111 // here. (MacVim doesn't change the rows and columns to avoid
1112 // inconsistent states between Vim and MacVim.)
1113 [self setRows:rows columns:cols];
1115 //NSLog(@"[VimTask] Resizing shell to %dx%d.", cols, rows);
1116 gui_resize_shell(cols, rows);
1117 } else if (ExecuteMenuMsgID == msgid) {
1119 const void *bytes = [data bytes];
1120 int tag = *((int*)bytes); bytes += sizeof(int);
1122 vimmenu_T *menu = (vimmenu_T*)tag;
1123 // TODO! Make sure 'menu' is a valid menu pointer!
1127 } else if (ToggleToolbarMsgID == msgid) {
1128 char_u go[sizeof(GO_ALL)+2];
1133 p = vim_strchr(go, GO_TOOLBAR);
1137 char_u *end = go + len;
1143 go[len] = GO_TOOLBAR;
1147 set_option_value((char_u*)"guioptions", 0, go, 0);
1149 // Force screen redraw (does it have to be this complicated?).
1150 redraw_all_later(CLEAR);
1151 update_screen(NOT_VALID);
1154 gui_update_cursor(FALSE, FALSE);
1156 } else if (ScrollbarEventMsgID == msgid) {
1158 const void *bytes = [data bytes];
1159 long ident = *((long*)bytes); bytes += sizeof(long);
1160 int hitPart = *((int*)bytes); bytes += sizeof(int);
1161 float fval = *((float*)bytes); bytes += sizeof(float);
1162 scrollbar_T *sb = gui_find_scrollbar(ident);
1165 scrollbar_T *sb_info = sb->wp ? &sb->wp->w_scrollbars[0] : sb;
1166 long value = sb_info->value;
1167 long size = sb_info->size;
1168 long max = sb_info->max;
1169 BOOL isStillDragging = NO;
1170 BOOL updateKnob = YES;
1173 case NSScrollerDecrementPage:
1174 value -= (size > 2 ? size - 2 : 1);
1176 case NSScrollerIncrementPage:
1177 value += (size > 2 ? size - 2 : 1);
1179 case NSScrollerDecrementLine:
1182 case NSScrollerIncrementLine:
1185 case NSScrollerKnob:
1186 isStillDragging = YES;
1188 case NSScrollerKnobSlot:
1189 value = (long)(fval * (max - size + 1));
1196 //NSLog(@"value %d -> %d", sb_info->value, value);
1197 gui_drag_scrollbar(sb, value, isStillDragging);
1200 // Dragging the knob or option+clicking automatically updates
1201 // the knob position (on the actual NSScroller), so we only
1202 // need to set the knob position in the other cases.
1204 // Update both the left&right vertical scrollbars.
1205 long identLeft = sb->wp->w_scrollbars[SBAR_LEFT].ident;
1206 long identRight = sb->wp->w_scrollbars[SBAR_RIGHT].ident;
1207 [self setScrollbarThumbValue:value size:size max:max
1208 identifier:identLeft];
1209 [self setScrollbarThumbValue:value size:size max:max
1210 identifier:identRight];
1212 // Update the horizontal scrollbar.
1213 [self setScrollbarThumbValue:value size:size max:max
1218 } else if (SetFontMsgID == msgid) {
1220 const void *bytes = [data bytes];
1221 float pointSize = *((float*)bytes); bytes += sizeof(float);
1222 //unsigned len = *((unsigned*)bytes); bytes += sizeof(unsigned);
1223 bytes += sizeof(unsigned); // len not used
1225 NSMutableString *name = [NSMutableString stringWithUTF8String:bytes];
1226 [name appendString:[NSString stringWithFormat:@":h%.2f", pointSize]];
1228 set_option_value((char_u*)"gfn", 0, (char_u*)[name UTF8String], 0);
1230 // Force screen redraw (does it have to be this complicated?).
1231 redraw_all_later(CLEAR);
1232 update_screen(NOT_VALID);
1235 gui_update_cursor(FALSE, FALSE);
1237 } else if (VimShouldCloseMsgID == msgid) {
1239 } else if (DropFilesMsgID == msgid) {
1241 const void *bytes = [data bytes];
1242 int n = *((int*)bytes); bytes += sizeof(int);
1245 int row = *((int*)bytes); bytes += sizeof(int);
1246 int col = *((int*)bytes); bytes += sizeof(int);
1248 char_u **fnames = (char_u **)alloc(n * sizeof(char_u *));
1250 const void *end = [data bytes] + [data length];
1252 while (bytes < end && i < n) {
1253 int len = *((int*)bytes); bytes += sizeof(int);
1254 fnames[i++] = vim_strnsave((char_u*)bytes, len);
1258 // NOTE! This function will free 'fnames'.
1259 gui_handle_drop(col, row, 0, fnames, i < n ? i : n);
1262 // HACK! I'm not sure how to get Vim to open a list of files in tabs,
1263 // so instead I create a ':tab drop' command with all the files to open
1265 NSMutableString *cmd = (n > 1)
1266 ? [NSMutableString stringWithString:@":tab drop"]
1267 : [NSMutableString stringWithString:@":drop"];
1269 const void *end = [data bytes] + [data length];
1271 for (i = 0; i < n && bytes < end; ++i) {
1272 int len = *((int*)bytes); bytes += sizeof(int);
1273 NSMutableString *file =
1274 [NSMutableString stringWithUTF8String:bytes];
1275 [file replaceOccurrencesOfString:@" "
1278 range:NSMakeRange(0, [file length])];
1281 [cmd appendString:@" "];
1282 [cmd appendString:file];
1285 // By going to the last tabpage we ensure that the new tabs will appear
1286 // last (if this call is left out, the taborder becomes messy).
1289 do_cmdline_cmd((char_u*)[cmd UTF8String]);
1291 // Force screen redraw (does it have to be this complicated?).
1292 // (This code was taken from the end of gui_handle_drop().)
1293 update_screen(NOT_VALID);
1296 gui_update_cursor(FALSE, FALSE);
1300 } else if (DropStringMsgID == msgid) {
1302 char_u dropkey[3] = { CSI, KS_EXTRA, (char_u)KE_DROP };
1303 const void *bytes = [data bytes];
1304 int len = *((int*)bytes); bytes += sizeof(int);
1305 NSMutableString *string = [NSMutableString stringWithUTF8String:bytes];
1307 // Replace unrecognized end-of-line sequences with \x0a (line feed).
1308 NSRange range = { 0, [string length] };
1309 unsigned n = [string replaceOccurrencesOfString:@"\x0d\x0a"
1310 withString:@"\x0a" options:0
1313 n = [string replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
1314 options:0 range:range];
1317 len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1318 dnd_yank_drag_data((char_u*)[string UTF8String], len);
1319 add_to_input_buf(dropkey, sizeof(dropkey));
1321 } else if (GotFocusMsgID == msgid) {
1323 [self focusChange:YES];
1324 } else if (LostFocusMsgID == msgid) {
1326 [self focusChange:NO];
1327 } else if (MouseMovedMsgID == msgid) {
1328 const void *bytes = [data bytes];
1329 int row = *((int*)bytes); bytes += sizeof(int);
1330 int col = *((int*)bytes); bytes += sizeof(int);
1332 gui_mouse_moved(col, row);
1333 } else if (SetMouseShapeMsgID == msgid) {
1334 const void *bytes = [data bytes];
1335 int shape = *((int*)bytes); bytes += sizeof(int);
1336 update_mouseshape(shape);
1338 NSLog(@"WARNING: Unknown message received (msgid=%d)", msgid);
1342 + (NSDictionary *)specialKeys
1344 static NSDictionary *specialKeys = nil;
1347 NSBundle *mainBundle = [NSBundle mainBundle];
1348 NSString *path = [mainBundle pathForResource:@"SpecialKeys"
1350 specialKeys = [[NSDictionary alloc] initWithContentsOfFile:path];
1356 - (void)handleKeyDown:(NSString *)key modifiers:(int)mods
1363 // Special keys (arrow keys, function keys, etc.) are stored in a plist so
1364 // that new keys can easily be added.
1365 NSString *specialString = [[MMBackend specialKeys]
1367 if (specialString && [specialString length] > 1) {
1368 //NSLog(@"special key: %@", specialString);
1369 int ikey = TO_SPECIAL([specialString characterAtIndex:0],
1370 [specialString characterAtIndex:1]);
1372 ikey = simplify_key(ikey, &mods);
1377 special[1] = K_SECOND(ikey);
1378 special[2] = K_THIRD(ikey);
1382 } else if ([key length] > 0) {
1383 chars = (char_u*)[key UTF8String];
1384 length = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1385 unichar c = [key characterAtIndex:0];
1387 //NSLog(@"non-special: %@ (hex=%x, mods=%d)", key,
1388 // [key characterAtIndex:0], mods);
1390 if (length == 1 && ((c == Ctrl_C && ctrl_c_interrupts)
1391 || (c == intr_char && intr_char != Ctrl_C))) {
1396 // HACK! In most circumstances the Ctrl and Shift modifiers should be
1397 // cleared since they are already added to the key by the AppKit.
1398 // Unfortunately, the only way to deal with when to clear the modifiers
1399 // or not seems to be to have hard-wired rules like this.
1400 if ( !((' ' == c) || (0xa0 == c) || (mods & MOD_MASK_CMD)) ) {
1401 mods &= ~MOD_MASK_SHIFT;
1402 mods &= ~MOD_MASK_CTRL;
1403 //NSLog(@"clear shift ctrl");
1406 // HACK! All Option+key presses go via 'insert text' messages, except
1407 // for <M-Space>. If the Alt flag is not cleared for <M-Space> it does
1408 // not work to map to it.
1409 if (0xa0 == c && !(mods & MOD_MASK_CMD)) {
1410 //NSLog(@"clear alt");
1411 mods &= ~MOD_MASK_ALT;
1415 if (chars && length > 0) {
1417 //NSLog(@"adding mods: %d", mods);
1419 modChars[1] = KS_MODIFIER;
1421 add_to_input_buf(modChars, 3);
1424 //NSLog(@"add to input buf: 0x%x", chars[0]);
1425 // TODO: Check for CSI bytes?
1426 add_to_input_buf(chars, length);
1430 - (void)queueMessage:(int)msgid data:(NSData *)data
1432 [queue addObject:[NSData dataWithBytes:&msgid length:sizeof(int)]];
1434 [queue addObject:data];
1436 [queue addObject:[NSData data]];
1439 - (void)connectionDidDie:(NSNotification *)notification
1441 // If the main connection to MacVim is lost this means that MacVim was
1442 // either quit (by the user chosing Quit on the MacVim menu), or it has
1443 // crashed. In either case our only option is to quit now.
1444 // TODO: Write backup file?
1446 //NSLog(@"A Vim process lots its connection to MacVim; quitting.");
1450 - (void)blinkTimerFired:(NSTimer *)timer
1452 NSTimeInterval timeInterval = 0;
1454 [blinkTimer release];
1457 if (MMBlinkStateOn == blinkState) {
1458 gui_undraw_cursor();
1459 blinkState = MMBlinkStateOff;
1460 timeInterval = blinkOffInterval;
1461 } else if (MMBlinkStateOff == blinkState) {
1462 gui_update_cursor(TRUE, FALSE);
1463 blinkState = MMBlinkStateOn;
1464 timeInterval = blinkOnInterval;
1467 if (timeInterval > 0) {
1469 [[NSTimer scheduledTimerWithTimeInterval:timeInterval target:self
1470 selector:@selector(blinkTimerFired:)
1471 userInfo:nil repeats:NO] retain];
1472 [self flushQueue:YES];
1476 - (void)focusChange:(BOOL)on
1478 // This is a bit of an ugly way to change the selection color.
1479 // TODO: Is there a nicer way to do this?
1481 ? "hi Visual guibg=MacSelectedTextBackgroundColor"
1482 : "hi Visual guibg=MacSecondarySelectedControlColor";
1484 do_cmdline_cmd((char_u*)cmd);
1485 gui_focus_change(on);
1487 // TODO: Is all this necessary just to get the highlights to update?
1488 redraw_all_later(CLEAR);
1489 update_screen(NOT_VALID);
1492 gui_update_cursor(FALSE, FALSE);
1496 - (void)processInputBegin
1498 inProcessInput = YES;
1499 [lastFlushDate release];
1500 lastFlushDate = [[NSDate date] retain];
1503 - (void)processInputEnd
1505 #if MM_USE_INPUT_QUEUE
1506 int count = [inputQueue count];
1508 // TODO: This is troubling, but it is not hard to get Vim to end up
1509 // here. Why does this happen?
1510 NSLog(@"WARNING: inputQueue has odd number of objects (%d)", count);
1511 [inputQueue removeAllObjects];
1512 } else if (count > 0) {
1513 // TODO: Dispatch these messages? Maybe not; usually when the
1514 // 'inputQueue' is non-empty it means that a LOT of messages has been
1515 // sent simultaneously. The only way this happens is when Vim is being
1516 // tormented, e.g. if the user holds down <D-`> to rapidly switch
1519 for (i = 0; i < count; i+=2) {
1520 int msgid = [[inputQueue objectAtIndex:i] intValue];
1521 NSLog(@"%s: Dropping message %s", _cmd, MessageStrings[msgid]);
1524 [inputQueue removeAllObjects];
1528 #if 0 // This does not work...for now, just don't care if a focus msg was lost.
1529 // HACK! A focus message might get lost, but whenever we get here the GUI
1532 [self focusChange:TRUE];
1535 inputReceived = YES;
1536 inProcessInput = NO;
1539 @end // MMBackend (Private)
1544 static int eventModifierFlagsToVimModMask(int modifierFlags)
1548 if (modifierFlags & NSShiftKeyMask)
1549 modMask |= MOD_MASK_SHIFT;
1550 if (modifierFlags & NSControlKeyMask)
1551 modMask |= MOD_MASK_CTRL;
1552 if (modifierFlags & NSAlternateKeyMask)
1553 modMask |= MOD_MASK_ALT;
1554 if (modifierFlags & NSCommandKeyMask)
1555 modMask |= MOD_MASK_CMD;
1560 static int vimModMaskToEventModifierFlags(int mods)
1564 if (mods & MOD_MASK_SHIFT)
1565 flags |= NSShiftKeyMask;
1566 if (mods & MOD_MASK_CTRL)
1567 flags |= NSControlKeyMask;
1568 if (mods & MOD_MASK_ALT)
1569 flags |= NSAlternateKeyMask;
1570 if (mods & MOD_MASK_CMD)
1571 flags |= NSCommandKeyMask;
1576 static int eventModifierFlagsToVimMouseModMask(int modifierFlags)
1580 if (modifierFlags & NSShiftKeyMask)
1581 modMask |= MOUSE_SHIFT;
1582 if (modifierFlags & NSControlKeyMask)
1583 modMask |= MOUSE_CTRL;
1584 if (modifierFlags & NSAlternateKeyMask)
1585 modMask |= MOUSE_ALT;
1590 static int eventButtonNumberToVimMouseButton(int buttonNumber)
1592 static int mouseButton[] = { MOUSE_LEFT, MOUSE_RIGHT, MOUSE_MIDDLE,
1593 MOUSE_X1, MOUSE_X2 };
1595 return mouseButton[buttonNumber < 5 ? buttonNumber : 0];
1598 static int specialKeyToNSKey(int key)
1600 if (!IS_SPECIAL(key))
1607 { K_UP, NSUpArrowFunctionKey },
1608 { K_DOWN, NSDownArrowFunctionKey },
1609 { K_LEFT, NSLeftArrowFunctionKey },
1610 { K_RIGHT, NSRightArrowFunctionKey },
1611 { K_F1, NSF1FunctionKey },
1612 { K_F2, NSF2FunctionKey },
1613 { K_F3, NSF3FunctionKey },
1614 { K_F4, NSF4FunctionKey },
1615 { K_F5, NSF5FunctionKey },
1616 { K_F6, NSF6FunctionKey },
1617 { K_F7, NSF7FunctionKey },
1618 { K_F8, NSF8FunctionKey },
1619 { K_F9, NSF9FunctionKey },
1620 { K_F10, NSF10FunctionKey },
1621 { K_F11, NSF11FunctionKey },
1622 { K_F12, NSF12FunctionKey },
1623 { K_F13, NSF13FunctionKey },
1624 { K_F14, NSF14FunctionKey },
1625 { K_F15, NSF15FunctionKey },
1626 { K_F16, NSF16FunctionKey },
1627 { K_F17, NSF17FunctionKey },
1628 { K_F18, NSF18FunctionKey },
1629 { K_F19, NSF19FunctionKey },
1630 { K_F20, NSF20FunctionKey },
1631 { K_F21, NSF21FunctionKey },
1632 { K_F22, NSF22FunctionKey },
1633 { K_F23, NSF23FunctionKey },
1634 { K_F24, NSF24FunctionKey },
1635 { K_F25, NSF25FunctionKey },
1636 { K_F26, NSF26FunctionKey },
1637 { K_F27, NSF27FunctionKey },
1638 { K_F28, NSF28FunctionKey },
1639 { K_F29, NSF29FunctionKey },
1640 { K_F30, NSF30FunctionKey },
1641 { K_F31, NSF31FunctionKey },
1642 { K_F32, NSF32FunctionKey },
1643 { K_F33, NSF33FunctionKey },
1644 { K_F34, NSF34FunctionKey },
1645 { K_F35, NSF35FunctionKey },
1646 { K_DEL, NSBackspaceCharacter },
1647 { K_BS, NSDeleteCharacter },
1648 { K_HOME, NSHomeFunctionKey },
1649 { K_END, NSEndFunctionKey },
1650 { K_PAGEUP, NSPageUpFunctionKey },
1651 { K_PAGEDOWN, NSPageDownFunctionKey }
1655 for (i = 0; i < sizeof(sp2ns)/sizeof(sp2ns[0]); ++i) {
1656 if (sp2ns[i].special == key)
1657 return sp2ns[i].nskey;