Be more conservative about flushing output queue
[MacVim.git] / src / MacVim / gui_macvim.m
blob990a07d298c17420366d096498eb0c1f16af0dcd
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  * gui_macvim.m
12  *
13  * Hooks for the Vim gui code.  Mainly passes control on to MMBackend.
14  */
16 #import "MMBackend.h"
17 #import "MacVim.h"
18 #import "vim.h"
19 #import <Foundation/Foundation.h>
23 // This constant controls how often [MMBackend update] may get called (see
24 // gui_mch_update()).
25 static NSTimeInterval MMUpdateTimeoutInterval = 0.1f;
27 // NOTE: The default font is bundled with the application.
28 static NSString *MMDefaultFontName = @"DejaVu Sans Mono";
29 static float MMDefaultFontSize = 12.0f;
30 static float MMMinFontSize = 6.0f;
31 static float MMMaxFontSize = 100.0f;
32 static BOOL gui_mch_init_has_finished = NO;
35 static NSFont *gui_macvim_font_with_name(char_u *name);
36 static int specialKeyToNSKey(int key);
37 static int vimModMaskToEventModifierFlags(int mods);
39 NSArray *descriptor_for_menu(vimmenu_T *menu);
40 vimmenu_T *menu_for_descriptor(NSArray *desc);
44 // -- Initialization --------------------------------------------------------
47  * Parse the GUI related command-line arguments.  Any arguments used are
48  * deleted from argv, and *argc is decremented accordingly.  This is called
49  * when vim is started, whether or not the GUI has been started.
50  */
51     void
52 gui_mch_prepare(int *argc, char **argv)
54     //NSLog(@"gui_mch_prepare(argc=%d)", *argc);
56     // Set environment variables $VIM and $VIMRUNTIME
57     // NOTE!  If vim_getenv is called with one of these as parameters before
58     // they have been set here, they will most likely end up with the wrong
59     // values!
60     //
61     // TODO:
62     // - ensure this is called first to avoid above problem
63     // - encoding
65     NSString *path = [[[NSBundle mainBundle] resourcePath]
66         stringByAppendingPathComponent:@"vim"];
67     vim_setenv((char_u*)"VIM", (char_u*)[path UTF8String]);
69     path = [path stringByAppendingPathComponent:@"runtime"];
70     vim_setenv((char_u*)"VIMRUNTIME", (char_u*)[path UTF8String]);
72     int i;
73     for (i = 0; i < *argc; ++i) {
74         if (strncmp(argv[i], "--mmwaitforack", 14) == 0) {
75             [[MMBackend sharedInstance] setWaitForAck:YES];
76             --*argc;
77             if (*argc > i)
78                 mch_memmove(&argv[i], &argv[i+1], (*argc-i) * sizeof(char*));
79             break;
80         }
81     }
86  * Check if the GUI can be started.  Called before gvimrc is sourced.
87  * Return OK or FAIL.
88  */
89     int
90 gui_mch_init_check(void)
92     //NSLog(@"gui_mch_init_check()");
93     return OK;
98  * Initialise the GUI.  Create all the windows, set up all the call-backs etc.
99  * Returns OK for success, FAIL when the GUI can't be started.
100  */
101     int
102 gui_mch_init(void)
104     //NSLog(@"gui_mch_init()");
106     // NOTE! Because OS X has to exec after fork we effectively end up doing
107     // the initialization twice (because this function is called before the
108     // fork).  To avoid all this extra work we check if Vim is about to fork,
109     // and if so do nothing for now.
110     //
111     // TODO: Is this check 100% foolproof?
112     if (gui.dofork && (vim_strchr(p_go, GO_FORG) == NULL))
113         return OK;
115     if (![[MMBackend sharedInstance] checkin]) {
116         // TODO: Kill the process if there is no terminal to fall back on,
117         // otherwise the process will run outputting to the console.
118         return FAIL;
119     }
121     // Force 'termencoding' to utf-8 (changes to 'tenc' are disallowed in
122     // 'option.c', so that ':set termencoding=...' is impossible).
123     set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
125     // Set values so that pixels and characters are in one-to-one
126     // correspondence (assuming all characters have the same dimensions).
127     gui.scrollbar_width = gui.scrollbar_height = 0;
129     gui.char_height = 1;
130     gui.char_width = 1;
131     gui.char_ascent = 0;
133     gui_mch_def_colors();
135     [[MMBackend sharedInstance]
136         setDefaultColorsBackground:gui.back_pixel foreground:gui.norm_pixel];
137     [[MMBackend sharedInstance] setBackgroundColor:gui.back_pixel];
138     [[MMBackend sharedInstance] setForegroundColor:gui.norm_pixel];
140     // NOTE: If this call is left out the cursor is opaque.
141     highlight_gui_started();
143     // Ensure 'linespace' option is passed along to MacVim in case it was set
144     // in [g]vimrc.
145     gui_mch_adjust_charheight();
147     gui_mch_init_has_finished = YES;
149     return OK;
154     void
155 gui_mch_exit(int rc)
157     //NSLog(@"gui_mch_exit(rc=%d)", rc);
159     [[MMBackend sharedInstance] exit];
164  * Open the GUI window which was created by a call to gui_mch_init().
165  */
166     int
167 gui_mch_open(void)
169     //NSLog(@"gui_mch_open()");
171     // This check is to avoid doing extra work when we're about to fork.
172     if (!gui_mch_init_has_finished)
173         return OK;
175     return [[MMBackend sharedInstance] openGUIWindow];
179 // -- Updating --------------------------------------------------------------
183  * Catch up with any queued X events.  This may put keyboard input into the
184  * input buffer, call resize call-backs, trigger timers etc.  If there is
185  * nothing in the X event queue (& no timers pending), then we return
186  * immediately.
187  */
188 #define MM_LOG_UPDATE_STATS 0
189     void
190 gui_mch_update(void)
192     // NOTE: This function can get called A LOT (~1 call/ms) and unfortunately
193     // checking the run loop takes a long time, resulting in noticable slow
194     // downs if it is done every time this function is called.  Therefore we
195     // make sure that it is not done too often.
196     static NSDate *lastUpdateDate = nil;
197 #if MM_LOG_UPDATE_STATS
198     static int skipCount = 0;
199 #endif
201     if (lastUpdateDate && -[lastUpdateDate timeIntervalSinceNow] <
202             MMUpdateTimeoutInterval) {
203 #if MM_LOG_UPDATE_STATS
204         ++skipCount;
205 #endif
206         return;
207     }
209 #if MM_LOG_UPDATE_STATS
210     NSTimeInterval dt = -[lastUpdateDate timeIntervalSinceNow];
211     NSLog(@"Updating (last update %.2f seconds ago, skipped %d updates, "
212             "approx %.1f calls per second)",
213             dt, skipCount, dt > 0 ? skipCount/dt : 0);
214     skipCount = 0;
215 #endif
217     [[MMBackend sharedInstance] update];
219     [lastUpdateDate release];
220     lastUpdateDate = [[NSDate date] retain];
224 /* Flush any output to the screen */
225     void
226 gui_mch_flush(void)
228     // This function is called way too often to be useful as a hint for
229     // flushing.  If we were to flush every time it was called the screen would
230     // flicker.
234 /* Force flush output to MacVim.  Do not call this method unless absolutely
235  * necessary. */
236     void
237 gui_macvim_force_flush(void)
239     [[MMBackend sharedInstance] flushQueue:YES];
244  * GUI input routine called by gui_wait_for_chars().  Waits for a character
245  * from the keyboard.
246  *  wtime == -1     Wait forever.
247  *  wtime == 0      This should never happen.
248  *  wtime > 0       Wait wtime milliseconds for a character.
249  * Returns OK if a character was found to be available within the given time,
250  * or FAIL otherwise.
251  */
252     int
253 gui_mch_wait_for_chars(int wtime)
255     // NOTE! In all likelihood Vim will take a nap when waitForInput: is
256     // called, so force a flush of the command queue here.
257     [[MMBackend sharedInstance] flushQueue:YES];
259     return [[MMBackend sharedInstance] waitForInput:wtime];
263 // -- Drawing ---------------------------------------------------------------
267  * Clear the whole text window.
268  */
269     void
270 gui_mch_clear_all(void)
272     [[MMBackend sharedInstance] clearAll];
277  * Clear a rectangular region of the screen from text pos (row1, col1) to
278  * (row2, col2) inclusive.
279  */
280     void
281 gui_mch_clear_block(int row1, int col1, int row2, int col2)
283     [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
284                                                     toRow:row2 column:col2];
289  * Delete the given number of lines from the given row, scrolling up any
290  * text further down within the scroll region.
291  */
292     void
293 gui_mch_delete_lines(int row, int num_lines)
295     [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
296             scrollBottom:gui.scroll_region_bot
297                     left:gui.scroll_region_left
298                    right:gui.scroll_region_right];
302     void
303 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
305 #ifdef FEAT_MBYTE
306     char_u *conv_str = NULL;
307     if (output_conv.vc_type != CONV_NONE) {
308         conv_str = string_convert(&output_conv, s, &len);
309         if (conv_str)
310             s = conv_str;
311     }
312 #endif
314     [[MMBackend sharedInstance] drawString:(char*)s length:len row:row
315                                     column:col cells:len flags:flags];
317 #ifdef FEAT_MBYTE
318     if (conv_str)
319         vim_free(conv_str);
320 #endif
324     int
325 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
327     int c, cn, cl, i;
328     int start = 0;
329     int endcol = col;
330     int startcol = col;
331     BOOL wide = NO;
332     MMBackend *backend = [MMBackend sharedInstance];
333 #ifdef FEAT_MBYTE
334     char_u *conv_str = NULL;
336     if (output_conv.vc_type != CONV_NONE) {
337         conv_str = string_convert(&output_conv, s, &len);
338         if (conv_str)
339             s = conv_str;
340     }
341 #endif
343     // Loop over each character and output text when it changes from normal to
344     // wide and vice versa.
345     for (i = 0; i < len; i += cl) {
346         c = utf_ptr2char(s + i);
347         cl = utf_ptr2len(s + i);
348         cn = utf_char2cells(c);
350         if (!utf_iscomposing(c)) {
351             if ((cn > 1 && !wide) || (cn <= 1 && wide)) {
352                 // Changed from normal to wide or vice versa.
353                 [backend drawString:(char*)(s+start) length:i-start
354                                    row:row column:startcol
355                                  cells:endcol-startcol
356                                  flags:(wide ? flags|DRAW_WIDE : flags)];
358                 start = i;
359                 startcol = endcol;
360             }
362             wide = cn > 1;
363             endcol += cn;
364         }
365     }
367     // Output remaining characters.
368     [backend drawString:(char*)(s+start) length:len-start
369                     row:row column:startcol cells:endcol-startcol
370                   flags:(wide ? flags|DRAW_WIDE : flags)];
372 #ifdef FEAT_MBYTE
373     if (conv_str)
374         vim_free(conv_str);
375 #endif
377     return endcol - col;
382  * Insert the given number of lines before the given row, scrolling down any
383  * following text within the scroll region.
384  */
385     void
386 gui_mch_insert_lines(int row, int num_lines)
388     [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
389             scrollBottom:gui.scroll_region_bot
390                     left:gui.scroll_region_left
391                    right:gui.scroll_region_right];
396  * Set the current text foreground color.
397  */
398     void
399 gui_mch_set_fg_color(guicolor_T color)
401     [[MMBackend sharedInstance] setForegroundColor:color];
406  * Set the current text background color.
407  */
408     void
409 gui_mch_set_bg_color(guicolor_T color)
411     [[MMBackend sharedInstance] setBackgroundColor:color];
416  * Set the current text special color (used for underlines).
417  */
418     void
419 gui_mch_set_sp_color(guicolor_T color)
421     [[MMBackend sharedInstance] setSpecialColor:color];
426  * Set default colors.
427  */
428     void
429 gui_mch_def_colors()
431     MMBackend *backend = [MMBackend sharedInstance];
433     // The default colors are taken from system values
434     gui.def_norm_pixel = gui.norm_pixel = 
435         [backend lookupColorWithKey:@"MacTextColor"];
436     gui.def_back_pixel = gui.back_pixel = 
437         [backend lookupColorWithKey:@"MacTextBackgroundColor"];
442  * Called when the foreground or background color has been changed.
443  */
444     void
445 gui_mch_new_colors(void)
447     gui.def_back_pixel = gui.back_pixel;
448     gui.def_norm_pixel = gui.norm_pixel;
450     //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
451     //        gui.def_norm_pixel);
453     [[MMBackend sharedInstance]
454         setDefaultColorsBackground:gui.def_back_pixel
455                         foreground:gui.def_norm_pixel];
459  * Invert a rectangle from row r, column c, for nr rows and nc columns.
460  */
461     void
462 gui_mch_invert_rectangle(int r, int c, int nr, int nc, int invert)
464     [[MMBackend sharedInstance] drawInvertedRectAtRow:r column:c numRows:nr
465             numColumns:nc invert:invert];
470 // -- Tabline ---------------------------------------------------------------
474  * Set the current tab to "nr".  First tab is 1.
475  */
476     void
477 gui_mch_set_curtab(int nr)
479     [[MMBackend sharedInstance] selectTab:nr];
484  * Return TRUE when tabline is displayed.
485  */
486     int
487 gui_mch_showing_tabline(void)
489     return [[MMBackend sharedInstance] tabBarVisible];
493  * Update the labels of the tabline.
494  */
495     void
496 gui_mch_update_tabline(void)
498     [[MMBackend sharedInstance] updateTabBar];
502  * Show or hide the tabline.
503  */
504     void
505 gui_mch_show_tabline(int showit)
507     [[MMBackend sharedInstance] showTabBar:showit];
511 // -- Clipboard -------------------------------------------------------------
514     void
515 clip_mch_lose_selection(VimClipboard *cbd)
520     int
521 clip_mch_own_selection(VimClipboard *cbd)
523     return 0;
527     void
528 clip_mch_request_selection(VimClipboard *cbd)
530     NSPasteboard *pb = [NSPasteboard generalPasteboard];
531     NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
532             NSStringPboardType, nil];
533     NSString *bestType = [pb availableTypeFromArray:supportedTypes];
534     if (!bestType) return;
536     int motion_type = MCHAR;
537     NSString *string = nil;
539     if ([bestType isEqual:VimPBoardType]) {
540         // This type should consist of an array with two objects:
541         //   1. motion type (NSNumber)
542         //   2. text (NSString)
543         // If this is not the case we fall back on using NSStringPboardType.
544         id plist = [pb propertyListForType:VimPBoardType];
545         if ([plist isKindOfClass:[NSArray class]] && [plist count] == 2) {
546             id obj = [plist objectAtIndex:1];
547             if ([obj isKindOfClass:[NSString class]]) {
548                 motion_type = [[plist objectAtIndex:0] intValue];
549                 string = obj;
550             }
551         }
552     }
554     if (!string) {
555         // Use NSStringPboardType.  The motion type is set to line-wise if the
556         // string contains at least one EOL character, otherwise it is set to
557         // character-wise (block-wise is never used).
558         NSMutableString *mstring =
559                 [[pb stringForType:NSStringPboardType] mutableCopy];
560         if (!mstring) return;
562         // Replace unrecognized end-of-line sequences with \x0a (line feed).
563         NSRange range = { 0, [mstring length] };
564         unsigned n = [mstring replaceOccurrencesOfString:@"\x0d\x0a"
565                                              withString:@"\x0a" options:0
566                                                   range:range];
567         if (0 == n) {
568             n = [mstring replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
569                                            options:0 range:range];
570         }
571         
572         // Scan for newline character to decide whether the string should be
573         // pasted line-wise or character-wise.
574         motion_type = MCHAR;
575         if (0 < n || NSNotFound != [mstring rangeOfString:@"\n"].location)
576             motion_type = MLINE;
578         string = mstring;
579     }
581     if (!(MCHAR == motion_type || MLINE == motion_type || MBLOCK == motion_type
582             || MAUTO == motion_type))
583         motion_type = MCHAR;
585     char_u *str = (char_u*)[string UTF8String];
586     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
588 #ifdef FEAT_MBYTE
589     if (input_conv.vc_type != CONV_NONE)
590         str = string_convert(&input_conv, str, &len);
591 #endif
593     if (str)
594         clip_yank_selection(motion_type, str, len, cbd);
596 #ifdef FEAT_MBYTE
597     if (input_conv.vc_type != CONV_NONE)
598         vim_free(str);
599 #endif
604  * Send the current selection to the clipboard.
605  */
606     void
607 clip_mch_set_selection(VimClipboard *cbd)
609     // If the '*' register isn't already filled in, fill it in now.
610     cbd->owned = TRUE;
611     clip_get_selection(cbd);
612     cbd->owned = FALSE;
613     
614     // Get the text to put on the pasteboard.
615     long_u llen = 0; char_u *str = 0;
616     int motion_type = clip_convert_selection(&str, &llen, cbd);
617     if (motion_type < 0)
618         return;
620     // TODO: Avoid overflow.
621     int len = (int)llen;
622 #ifdef FEAT_MBYTE
623     if (output_conv.vc_type != CONV_NONE) {
624         char_u *conv_str = string_convert(&output_conv, str, &len);
625         if (conv_str) {
626             vim_free(str);
627             str = conv_str;
628         }
629     }
630 #endif
632     if (len > 0) {
633         NSString *string = [[NSString alloc]
634             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
636         // See clip_mch_request_selection() for info on pasteboard types.
637         NSPasteboard *pb = [NSPasteboard generalPasteboard];
638         NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
639                 NSStringPboardType, nil];
640         [pb declareTypes:supportedTypes owner:nil];
642         NSNumber *motion = [NSNumber numberWithInt:motion_type];
643         NSArray *plist = [NSArray arrayWithObjects:motion, string, nil];
644         [pb setPropertyList:plist forType:VimPBoardType];
646         [pb setString:string forType:NSStringPboardType];
647         
648         [string release];
649     }
651     vim_free(str);
655 // -- Menu ------------------------------------------------------------------
659  * A menu descriptor represents the "address" of a menu as an array of strings.
660  * E.g. the menu "File->Close" has descriptor { "File", "Close" }.
661  */
662     NSArray *
663 descriptor_for_menu(vimmenu_T *menu)
665     if (!menu) return nil;
667     NSMutableArray *desc = [NSMutableArray array];
668     while (menu) {
669         NSString *name = [NSString stringWithVimString:menu->dname];
670         [desc insertObject:name atIndex:0];
671         menu = menu->parent;
672     }
674     return desc;
677     vimmenu_T *
678 menu_for_descriptor(NSArray *desc)
680     if (!(desc && [desc count] > 0)) return NULL;
682     vimmenu_T *menu = root_menu;
683     int i, count = [desc count];
685     for (i = 0; i < count; ++i) {
686         NSString *component = [desc objectAtIndex:i];
687         while (menu) {
688             NSString *name = [NSString stringWithVimString:menu->dname];
689             if ([component isEqual:name]) {
690                 if (i+1 == count)
691                     return menu;    // Matched all components, so return menu
692                 menu = menu->children;
693                 break;
694             }
695             menu = menu->next;
696         }
697     }
699     return NULL;
703  * Add a submenu to the menu bar, toolbar, or a popup menu.
704  */
705     void
706 gui_mch_add_menu(vimmenu_T *menu, int idx)
708     NSArray *desc = descriptor_for_menu(menu);
709     [[MMBackend sharedInstance] queueMessage:AddMenuMsgID properties:
710         [NSDictionary dictionaryWithObjectsAndKeys:
711             desc, @"descriptor",
712             [NSNumber numberWithInt:idx], @"index",
713             nil]];
718  * Add a menu item to a menu
719  */
720     void
721 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
723     char_u *tip = menu->strings[MENU_INDEX_TIP]
724             ? menu->strings[MENU_INDEX_TIP] : menu->actext;
725     NSArray *desc = descriptor_for_menu(menu);
726     NSString *keyEquivalent = menu->mac_key
727         ? [NSString stringWithFormat:@"%C", specialKeyToNSKey(menu->mac_key)]
728         : [NSString string];
729     int modifierMask = vimModMaskToEventModifierFlags(menu->mac_mods);
730     char_u *icon = NULL;
732     if (menu_is_toolbar(menu->parent->name)) {
733         char_u fname[MAXPATHL];
735         // TODO: Ensure menu->iconfile exists (if != NULL)
736         icon = menu->iconfile;
737         if (!icon && gui_find_bitmap(menu->name, fname, "bmp") == OK)
738             icon = fname;
739         if (!icon && menu->iconidx >= 0)
740             icon = menu->dname;
741     }
743     [[MMBackend sharedInstance] queueMessage:AddMenuItemMsgID properties:
744         [NSDictionary dictionaryWithObjectsAndKeys:
745             desc, @"descriptor",
746             [NSNumber numberWithInt:idx], @"index",
747             [NSString stringWithVimString:tip], @"tip",
748             [NSString stringWithVimString:icon], @"icon",
749             keyEquivalent, @"keyEquivalent",
750             [NSNumber numberWithInt:modifierMask], @"modifierMask",
751             [NSString stringWithVimString:menu->mac_action], @"action",
752             [NSNumber numberWithBool:menu->mac_alternate], @"isAlternate",
753             nil]];
758  * Destroy the machine specific menu widget.
759  */
760     void
761 gui_mch_destroy_menu(vimmenu_T *menu)
763     NSArray *desc = descriptor_for_menu(menu);
764     [[MMBackend sharedInstance] queueMessage:RemoveMenuItemMsgID properties:
765         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
770  * Make a menu either grey or not grey.
771  */
772     void
773 gui_mch_menu_grey(vimmenu_T *menu, int grey)
775     /* Only update menu if the 'grey' state has changed to avoid having to pass
776      * lots of unnecessary data to MacVim.  (Skipping this test makes MacVim
777      * pause noticably on mode changes. */
778     NSArray *desc = descriptor_for_menu(menu);
779     if (menu->was_grey == grey)
780         return;
782     menu->was_grey = grey;
784     [[MMBackend sharedInstance] queueMessage:EnableMenuItemMsgID properties:
785         [NSDictionary dictionaryWithObjectsAndKeys:
786             desc, @"descriptor",
787             [NSNumber numberWithInt:!grey], @"enable",
788             nil]];
793  * Make menu item hidden or not hidden
794  */
795     void
796 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
798     // HACK! There is no (obvious) way to hide a menu item, so simply
799     // enable/disable it instead.
800     gui_mch_menu_grey(menu, hidden);
805  * This is called when user right clicks.
806  */
807     void
808 gui_mch_show_popupmenu(vimmenu_T *menu)
810     NSArray *desc = descriptor_for_menu(menu);
811     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:
812         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
817  * This is called when a :popup command is executed.
818  */
819     void
820 gui_make_popup(char_u *path_name, int mouse_pos)
822     vimmenu_T *menu = gui_find_menu(path_name);
823     if (!(menu && menu->children)) return;
825     NSArray *desc = descriptor_for_menu(menu);
826     NSDictionary *p = (mouse_pos || NULL == curwin)
827         ? [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]
828         : [NSDictionary dictionaryWithObjectsAndKeys:
829             desc, @"descriptor",
830             [NSNumber numberWithInt:curwin->w_wrow], @"row",
831             [NSNumber numberWithInt:curwin->w_wcol], @"column",
832             nil];
834     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:p];
839  * This is called after setting all the menus to grey/hidden or not.
840  */
841     void
842 gui_mch_draw_menubar(void)
844     // The (main) menu draws itself in Mac OS X.
848     void
849 gui_mch_enable_menu(int flag)
851     // The (main) menu is always enabled in Mac OS X.
855 #if 0
856     void
857 gui_mch_set_menu_pos(int x, int y, int w, int h)
859     // The (main) menu cannot be moved in Mac OS X.
861 #endif
864     void
865 gui_mch_show_toolbar(int showit)
867     int flags = 0;
868     if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
869     if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
870     if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
872     [[MMBackend sharedInstance] showToolbar:showit flags:flags];
878 // -- Fonts -----------------------------------------------------------------
882  * If a font is not going to be used, free its structure.
883  */
884     void
885 gui_mch_free_font(font)
886     GuiFont     font;
888     if (font != NOFONT) {
889         //NSLog(@"gui_mch_free_font(font=0x%x)", font);
890         [(NSFont*)font release];
891     }
896  * Get a font structure for highlighting.
897  */
898     GuiFont
899 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
901     //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
902     //        giveErrorIfMissing);
904     NSFont *font = gui_macvim_font_with_name(name);
905     if (font)
906         return (GuiFont)[font retain];
908     if (giveErrorIfMissing)
909         EMSG2(_(e_font), name);
911     return NOFONT;
915 #if defined(FEAT_EVAL) || defined(PROTO)
917  * Return the name of font "font" in allocated memory.
918  * Don't know how to get the actual name, thus use the provided name.
919  */
920     char_u *
921 gui_mch_get_fontname(GuiFont font, char_u *name)
923     if (name == NULL)
924         return NULL;
925     return vim_strsave(name);
927 #endif
931  * Initialise vim to use the font with the given name.  Return FAIL if the font
932  * could not be loaded, OK otherwise.
933  */
934     int
935 gui_mch_init_font(char_u *font_name, int fontset)
937     //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
939     if (font_name && STRCMP(font_name, "*") == 0) {
940         // :set gfn=* shows the font panel.
941         do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
942         return FAIL;
943     }
945     NSFont *font = gui_macvim_font_with_name(font_name);
946     if (font) {
947         [(NSFont*)gui.norm_font release];
948         gui.norm_font = (GuiFont)[font retain];
950         // NOTE: MacVim keeps separate track of the normal and wide fonts.
951         // Unless the user changes 'guifontwide' manually, they are based on
952         // the same (normal) font.  Also note that each time the normal font is
953         // set, the advancement may change so the wide font needs to be updated
954         // as well (so that it is always twice the width of the normal font).
955         [[MMBackend sharedInstance] setFont:font];
956         [[MMBackend sharedInstance] setWideFont:
957                (NOFONT == gui.wide_font ? font : (NSFont*)gui.wide_font)];
959         return OK;
960     }
962     return FAIL;
967  * Set the current text font.
968  */
969     void
970 gui_mch_set_font(GuiFont font)
972     // Font selection is done inside MacVim...nothing here to do.
976     NSFont *
977 gui_macvim_font_with_name(char_u *name)
979     NSFont *font = nil;
980     NSString *fontName = MMDefaultFontName;
981     float size = MMDefaultFontSize;
982     BOOL parseFailed = NO;
984 #ifdef FEAT_MBYTE
985     name = CONVERT_TO_UTF8(name);
986 #endif
988     if (name) {
989         fontName = [NSString stringWithUTF8String:(char*)name];
991         NSArray *components = [fontName componentsSeparatedByString:@":"];
992         if ([components count] == 2) {
993             NSString *sizeString = [components lastObject];
994             if ([sizeString length] > 0
995                     && [sizeString characterAtIndex:0] == 'h') {
996                 sizeString = [sizeString substringFromIndex:1];
997                 if ([sizeString length] > 0) {
998                     size = [sizeString floatValue];
999                     fontName = [components objectAtIndex:0];
1000                 }
1001             } else {
1002                 parseFailed = YES;
1003             }
1004         } else if ([components count] > 2) {
1005             parseFailed = YES;
1006         }
1008         if (!parseFailed) {
1009             // Replace underscores with spaces.
1010             fontName = [[fontName componentsSeparatedByString:@"_"]
1011                                      componentsJoinedByString:@" "];
1012         }
1013     }
1015     if (!parseFailed && [fontName length] > 0) {
1016         if (size < MMMinFontSize) size = MMMinFontSize;
1017         if (size > MMMaxFontSize) size = MMMaxFontSize;
1019         font = [NSFont fontWithName:fontName size:size];
1021         if (!font && MMDefaultFontName == fontName) {
1022             // If for some reason the MacVim default font is not in the app
1023             // bundle, then fall back on the system default font.
1024             font = [NSFont userFixedPitchFontOfSize:0];
1025         }
1026     }
1028 #ifdef FEAT_MBYTE
1029     CONVERT_TO_UTF8_FREE(name);
1030 #endif
1032     return font;
1035 // -- Scrollbars ------------------------------------------------------------
1038     void
1039 gui_mch_create_scrollbar(
1040         scrollbar_T *sb,
1041         int orient)     /* SBAR_VERT or SBAR_HORIZ */
1043     [[MMBackend sharedInstance] 
1044             createScrollbarWithIdentifier:sb->ident type:sb->type];
1048     void
1049 gui_mch_destroy_scrollbar(scrollbar_T *sb)
1051     [[MMBackend sharedInstance] 
1052             destroyScrollbarWithIdentifier:sb->ident];
1056     void
1057 gui_mch_enable_scrollbar(
1058         scrollbar_T     *sb,
1059         int             flag)
1061     [[MMBackend sharedInstance] 
1062             showScrollbarWithIdentifier:sb->ident state:flag];
1066     void
1067 gui_mch_set_scrollbar_pos(
1068         scrollbar_T *sb,
1069         int x,
1070         int y,
1071         int w,
1072         int h)
1074     int pos = y;
1075     int len = h;
1076     if (SBAR_BOTTOM == sb->type) {
1077         pos = x;
1078         len = w; 
1079     }
1081     [[MMBackend sharedInstance] 
1082             setScrollbarPosition:pos length:len identifier:sb->ident];
1086     void
1087 gui_mch_set_scrollbar_thumb(
1088         scrollbar_T *sb,
1089         long val,
1090         long size,
1091         long max)
1093     [[MMBackend sharedInstance] 
1094             setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
1098 // -- Cursor ----------------------------------------------------------------
1102  * Draw a cursor without focus.
1103  */
1104     void
1105 gui_mch_draw_hollow_cursor(guicolor_T color)
1107     return [[MMBackend sharedInstance]
1108         drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
1109                fraction:100 color:color];
1114  * Draw part of a cursor, only w pixels wide, and h pixels high.
1115  */
1116     void
1117 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
1119     // HACK!  'w' and 'h' are always 1 since we do not tell Vim about the exact
1120     // font dimensions.  Thus these parameters are useless.  Instead we look at
1121     // the shape_table to determine the shape and size of the cursor (just like
1122     // gui_update_cursor() does).
1124 #ifdef FEAT_RIGHTLEFT
1125     // If 'rl' is set the insert mode cursor must be drawn on the right-hand
1126     // side of a text cell.
1127     int rl = curwin ? curwin->w_p_rl : FALSE;
1128 #else
1129     int rl = FALSE;
1130 #endif
1131     int idx = get_shape_idx(FALSE);
1132     int shape = MMInsertionPointBlock;
1133     switch (shape_table[idx].shape) {
1134         case SHAPE_HOR:
1135             shape = MMInsertionPointHorizontal;
1136             break;
1137         case SHAPE_VER:
1138             shape = rl ? MMInsertionPointVerticalRight
1139                        : MMInsertionPointVertical;
1140             break;
1141     }
1143     return [[MMBackend sharedInstance]
1144         drawCursorAtRow:gui.row column:gui.col shape:shape
1145                fraction:shape_table[idx].percentage color:color];
1150  * Cursor blink functions.
1152  * This is a simple state machine:
1153  * BLINK_NONE   not blinking at all
1154  * BLINK_OFF    blinking, cursor is not shown
1155  * BLINK_ON blinking, cursor is shown
1156  */
1157     void
1158 gui_mch_set_blinking(long wait, long on, long off)
1160     [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1165  * Start the cursor blinking.  If it was already blinking, this restarts the
1166  * waiting time and shows the cursor.
1167  */
1168     void
1169 gui_mch_start_blink(void)
1171     [[MMBackend sharedInstance] startBlink];
1176  * Stop the cursor blinking.  Show the cursor if it wasn't shown.
1177  */
1178     void
1179 gui_mch_stop_blink(void)
1181     [[MMBackend sharedInstance] stopBlink];
1185 // -- Mouse -----------------------------------------------------------------
1189  * Get current mouse coordinates in text window.
1190  */
1191     void
1192 gui_mch_getmouse(int *x, int *y)
1194     //NSLog(@"gui_mch_getmouse()");
1198     void
1199 gui_mch_setmouse(int x, int y)
1201     //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1205     void
1206 mch_set_mouse_shape(int shape)
1208     [[MMBackend sharedInstance] setMouseShape:shape];
1214 // -- Input Method ----------------------------------------------------------
1216 #if defined(USE_IM_CONTROL)
1218     void
1219 im_set_position(int row, int col)
1221     // The pre-edit area is a popup window which is displayed by MMTextView.
1222     [[MMBackend sharedInstance] setPreEditRow:row column:col];
1226     void
1227 im_set_active(int active)
1229     // Set roman or the system script if 'active' is TRUE or FALSE,
1230     // respectively.
1231     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1233     if (!p_imdisable && smRoman != systemScript)
1234         KeyScript(active ? smKeySysScript : smKeyRoman);
1238     int
1239 im_get_status(void)
1241     // IM is active whenever the current script is the system script and the
1242     // system script isn't roman.  (Hence IM can only be active when using
1243     // non-roman scripts.)
1244     SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
1245     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1247     return currentScript != smRoman && currentScript == systemScript;
1250 #endif // defined(USE_IM_CONTROL)
1255 // -- Unsorted --------------------------------------------------------------
1258     void
1259 ex_macaction(eap)
1260     exarg_T     *eap;
1262     if (!gui.in_use) {
1263         EMSG(_("E???: Command only available in GUI mode"));
1264         return;
1265     }
1267     char_u *arg = eap->arg;
1268 #ifdef FEAT_MBYTE
1269     arg = CONVERT_TO_UTF8(arg);
1270 #endif
1272     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1273     NSString *name = [NSString stringWithUTF8String:(char*)arg];
1274     if (actionDict && [actionDict objectForKey:name] != nil) {
1275         [[MMBackend sharedInstance] executeActionWithName:name];
1276     } else {
1277         EMSG2(_("E???: Invalid action: %s"), eap->arg);
1278     }
1280 #ifdef FEAT_MBYTE
1281     arg = CONVERT_TO_UTF8(arg);
1282 #endif
1287  * Adjust gui.char_height (after 'linespace' was changed).
1288  */
1289     int
1290 gui_mch_adjust_charheight(void)
1292     [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1293     return OK;
1297     void
1298 gui_mch_beep(void)
1300     NSBeep();
1305 #ifdef FEAT_BROWSE
1307  * Pop open a file browser and return the file selected, in allocated memory,
1308  * or NULL if Cancel is hit.
1309  *  saving  - TRUE if the file will be saved to, FALSE if it will be opened.
1310  *  title   - Title message for the file browser dialog.
1311  *  dflt    - Default name of file.
1312  *  ext     - Default extension to be added to files without extensions.
1313  *  initdir - directory in which to open the browser (NULL = current dir)
1314  *  filter  - Filter for matched files to choose from.
1315  *  Has a format like this:
1316  *  "C Files (*.c)\0*.c\0"
1317  *  "All Files\0*.*\0\0"
1318  *  If these two strings were concatenated, then a choice of two file
1319  *  filters will be selectable to the user.  Then only matching files will
1320  *  be shown in the browser.  If NULL, the default allows all files.
1322  *  *NOTE* - the filter string must be terminated with TWO nulls.
1323  */
1324     char_u *
1325 gui_mch_browse(
1326     int saving,
1327     char_u *title,
1328     char_u *dflt,
1329     char_u *ext,
1330     char_u *initdir,
1331     char_u *filter)
1333     //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1334     //        " filter=%s", saving, title, dflt, ext, initdir, filter);
1336     // Ensure no data is on the output queue before presenting the dialog.
1337     gui_macvim_force_flush();
1339     NSMutableDictionary *attr = [NSMutableDictionary
1340         dictionaryWithObject:[NSNumber numberWithBool:saving]
1341                       forKey:@"saving"];
1342     if (initdir)
1343         [attr setObject:[NSString stringWithVimString:initdir] forKey:@"dir"];
1345     char_u *s = (char_u*)[[MMBackend sharedInstance]
1346                             browseForFileWithAttributes:attr];
1348     return s;
1350 #endif /* FEAT_BROWSE */
1354     int
1355 gui_mch_dialog(
1356     int         type,
1357     char_u      *title,
1358     char_u      *message,
1359     char_u      *buttons,
1360     int         dfltbutton,
1361     char_u      *textfield)
1363     //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1364     //        "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1365     //        dfltbutton, textfield);
1367     // Ensure no data is on the output queue before presenting the dialog.
1368     gui_macvim_force_flush();
1370     int style = NSInformationalAlertStyle;
1371     if (VIM_WARNING == type) style = NSWarningAlertStyle;
1372     else if (VIM_ERROR == type) style = NSCriticalAlertStyle;
1374     NSMutableDictionary *attr = [NSMutableDictionary
1375                         dictionaryWithObject:[NSNumber numberWithInt:style]
1376                                       forKey:@"alertStyle"];
1378     if (buttons) {
1379         // 'buttons' is a string of '\n'-separated button titles 
1380         NSString *string = [NSString stringWithVimString:buttons];
1381         NSArray *array = [string componentsSeparatedByString:@"\n"];
1382         [attr setObject:array forKey:@"buttonTitles"];
1383     }
1385     NSString *messageText = nil;
1386     if (title)
1387         messageText = [NSString stringWithVimString:title];
1389     if (message) {
1390         NSString *informativeText = [NSString stringWithVimString:message];
1391         if (!messageText) {
1392             // HACK! If there is a '\n\n' or '\n' sequence in the message, then
1393             // make the part up to there into the title.  We only do this
1394             // because Vim has lots of dialogs without a title and they look
1395             // ugly that way.
1396             // TODO: Fix the actual dialog texts.
1397             NSRange eolRange = [informativeText rangeOfString:@"\n\n"];
1398             if (NSNotFound == eolRange.location)
1399                 eolRange = [informativeText rangeOfString:@"\n"];
1400             if (NSNotFound != eolRange.location) {
1401                 messageText = [informativeText substringToIndex:
1402                                                         eolRange.location];
1403                 informativeText = [informativeText substringFromIndex:
1404                                                         NSMaxRange(eolRange)];
1405             }
1406         }
1408         [attr setObject:informativeText forKey:@"informativeText"];
1409     }
1411     if (messageText)
1412         [attr setObject:messageText forKey:@"messageText"];
1414     if (textfield) {
1415         NSString *string = [NSString stringWithVimString:textfield];
1416         [attr setObject:string forKey:@"textFieldString"];
1417     }
1419     return [[MMBackend sharedInstance] showDialogWithAttributes:attr
1420                                                     textField:(char*)textfield];
1424     void
1425 gui_mch_flash(int msec)
1431  * Return the Pixel value (color) for the given color name.  This routine was
1432  * pretty much taken from example code in the Silicon Graphics OSF/Motif
1433  * Programmer's Guide.
1434  * Return INVALCOLOR when failed.
1435  */
1436     guicolor_T
1437 gui_mch_get_color(char_u *name)
1439 #ifdef FEAT_MBYTE
1440     name = CONVERT_TO_UTF8(name);
1441 #endif
1443     NSString *key = [NSString stringWithUTF8String:(char*)name];
1444     guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1446 #ifdef FEAT_MBYTE
1447     CONVERT_TO_UTF8_FREE(name);
1448 #endif
1450     return col;
1455  * Return the RGB value of a pixel as long.
1456  */
1457     long_u
1458 gui_mch_get_rgb(guicolor_T pixel)
1460     // This is only implemented so that vim can guess the correct value for
1461     // 'background' (which otherwise defaults to 'dark'); it is not used for
1462     // anything else (as far as I know).
1463     // The implementation is simple since colors are stored in an int as
1464     // "rrggbb".
1465     return pixel;
1470  * Get the screen dimensions.
1471  * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1472  * Is there no way to find out how wide the borders really are?
1473  * TODO: Add live udate of those value on suspend/resume.
1474  */
1475     void
1476 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1478     //NSLog(@"gui_mch_get_screen_dimensions()");
1479     *screen_w = Columns;
1480     *screen_h = Rows;
1485  * Get the position of the top left corner of the window.
1486  */
1487     int
1488 gui_mch_get_winpos(int *x, int *y)
1490     *x = *y = 0;
1491     return OK;
1496  * Return OK if the key with the termcap name "name" is supported.
1497  */
1498     int
1499 gui_mch_haskey(char_u *name)
1501     BOOL ok = NO;
1503 #ifdef FEAT_MBYTE
1504     name = CONVERT_TO_UTF8(name);
1505 #endif
1507     NSString *value = [NSString stringWithUTF8String:(char*)name];
1508     if (value)
1509         ok =  [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1511 #ifdef FEAT_MBYTE
1512     CONVERT_TO_UTF8_FREE(name);
1513 #endif
1515     return ok;
1520  * Iconify the GUI window.
1521  */
1522     void
1523 gui_mch_iconify(void)
1528 #if defined(FEAT_EVAL) || defined(PROTO)
1530  * Bring the Vim window to the foreground.
1531  */
1532     void
1533 gui_mch_set_foreground(void)
1535     [[MMBackend sharedInstance] activate];
1537 #endif
1541     void
1542 gui_mch_set_shellsize(
1543     int         width,
1544     int         height,
1545     int         min_width,
1546     int         min_height,
1547     int         base_width,
1548     int         base_height,
1549     int         direction)
1551     //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1552     //        " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1553     //        width, height, min_width, min_height, base_width, base_height,
1554     //        direction);
1555     [[MMBackend sharedInstance] setRows:height columns:width];
1559     void
1560 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1565  * Set the position of the top left corner of the window to the given
1566  * coordinates.
1567  */
1568     void
1569 gui_mch_set_winpos(int x, int y)
1574 #ifdef FEAT_TITLE
1576  * Set the window title and icon.
1577  * (The icon is not taken care of).
1578  */
1579     void
1580 gui_mch_settitle(char_u *title, char_u *icon)
1582     //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1584 #ifdef FEAT_MBYTE
1585     title = CONVERT_TO_UTF8(title);
1586 #endif
1588     MMBackend *backend = [MMBackend sharedInstance];
1589     [backend setWindowTitle:(char*)title];
1591     // TODO: Convert filename to UTF-8?
1592     if (curbuf)
1593         [backend setDocumentFilename:(char*)curbuf->b_ffname];
1595 #ifdef FEAT_MBYTE
1596     CONVERT_TO_UTF8_FREE(title);
1597 #endif
1599 #endif
1602     void
1603 gui_mch_toggle_tearoffs(int enable)
1609     void
1610 gui_mch_enter_fullscreen(int fuoptions_flags, guicolor_T bg)
1612     [[MMBackend sharedInstance] enterFullscreen:fuoptions_flags background:bg];
1616     void
1617 gui_mch_leave_fullscreen()
1619     [[MMBackend sharedInstance] leaveFullscreen];
1623     void
1624 gui_macvim_update_modified_flag()
1626     [[MMBackend sharedInstance] updateModifiedFlag];
1630  * Add search pattern 'pat' to the OS X find pasteboard.  This allows other
1631  * apps access the last pattern searched for (hitting <D-g> in another app will
1632  * initiate a search for the same pattern).
1633  */
1634     void
1635 gui_macvim_add_to_find_pboard(char_u *pat)
1637     if (!pat) return;
1639 #ifdef FEAT_MBYTE
1640     pat = CONVERT_TO_UTF8(pat);
1641 #endif
1642     NSString *s = [NSString stringWithUTF8String:(char*)pat];
1643 #ifdef FEAT_MBYTE
1644     CONVERT_TO_UTF8_FREE(pat);
1645 #endif
1647     if (!s) return;
1649     NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
1650     [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1651     [pb setString:s forType:NSStringPboardType];
1654     void
1655 gui_macvim_set_antialias(int antialias)
1657     [[MMBackend sharedInstance] setAntialias:antialias];
1661     void
1662 gui_macvim_wait_for_startup()
1664     MMBackend *backend = [MMBackend sharedInstance];
1665     if ([backend waitForAck])
1666         [backend waitForConnectionAcknowledgement];
1669 void gui_macvim_get_window_layout(int *count, int *layout)
1671     if (!(count && layout)) return;
1673     // NOTE: Only set 'layout' if the backend has requested a != 0 layout, else
1674     // any command line arguments (-p/-o) would be ignored.
1675     int window_layout = [[MMBackend sharedInstance] initialWindowLayout];
1676     if (window_layout > 0 && window_layout < 4) {
1677         // The window_layout numbers must match the WIN_* defines in main.c.
1678         *count = 0;
1679         *layout = window_layout;
1680     }
1684 // -- Client/Server ---------------------------------------------------------
1686 #ifdef MAC_CLIENTSERVER
1689 // NOTE: Client/Server is only fully supported with a GUI.  Theoretically it
1690 // would be possible to make the server code work with terminal Vim, but it
1691 // would require that a run-loop is set up and checked.  This should not be
1692 // difficult to implement, simply call gui_mch_update() at opportune moments
1693 // and it will take care of the run-loop.  Another (bigger) problem with
1694 // supporting servers in terminal mode is that the server listing code talks to
1695 // MacVim (the GUI) to figure out which servers are running.
1700  * Register connection with 'name'.  The actual connection is named something
1701  * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1702  */
1703     void
1704 serverRegisterName(char_u *name)
1706 #ifdef FEAT_MBYTE
1707     name = CONVERT_TO_UTF8(name);
1708 #endif
1710     NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1711     [[MMBackend sharedInstance] registerServerWithName:svrName];
1713 #ifdef FEAT_MBYTE
1714     CONVERT_TO_UTF8_FREE(name);
1715 #endif
1720  * Send to an instance of Vim.
1721  * Returns 0 for OK, negative for an error.
1722  */
1723     int
1724 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1725         int *port, int asExpr, int silent)
1727 #ifdef FEAT_MBYTE
1728     name = CONVERT_TO_UTF8(name);
1729     cmd = CONVERT_TO_UTF8(cmd);
1730 #endif
1732     BOOL ok = [[MMBackend sharedInstance]
1733             sendToServer:[NSString stringWithUTF8String:(char*)name]
1734                   string:[NSString stringWithUTF8String:(char*)cmd]
1735                    reply:result
1736                     port:port
1737               expression:asExpr
1738                   silent:silent];
1740 #ifdef FEAT_MBYTE
1741     CONVERT_TO_UTF8_FREE(name);
1742     CONVERT_TO_UTF8_FREE(cmd);
1743 #endif
1745     return ok ? 0 : -1;
1750  * Ask MacVim for the names of all Vim servers.
1751  */
1752     char_u *
1753 serverGetVimNames(void)
1755     char_u *names = NULL;
1756     NSArray *list = [[MMBackend sharedInstance] serverList];
1758     if (list) {
1759         NSString *string = [list componentsJoinedByString:@"\n"];
1760         char_u *s = (char_u*)[string UTF8String];
1761 #ifdef FEAT_MBYTE
1762         s = CONVERT_FROM_UTF8(s);
1763 #endif
1764         names = vim_strsave(s);
1765 #ifdef FEAT_MBYTE
1766         CONVERT_FROM_UTF8_FREE(s);
1767 #endif
1768     }
1770     return names;
1775  * 'str' is a hex int representing the send port of the connection.
1776  */
1777     int
1778 serverStrToPort(char_u *str)
1780     int port = 0;
1782     sscanf((char *)str, "0x%x", &port);
1783     if (!port)
1784         EMSG2(_("E573: Invalid server id used: %s"), str);
1786     return port;
1791  * Check for replies from server with send port 'port'.
1792  * Return TRUE and a non-malloc'ed string if there is.  Else return FALSE.
1793  */
1794     int
1795 serverPeekReply(int port, char_u **str)
1797     NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1798     int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1800     if (str && len > 0) {
1801         *str = (char_u*)[reply UTF8String];
1803 #ifdef FEAT_MBYTE
1804         if (input_conv.vc_type != CONV_NONE) {
1805             char_u *s = string_convert(&input_conv, *str, &len);
1807             if (len > 0) {
1808                 // HACK! Since 's' needs to be freed we cannot simply set
1809                 // '*str = s' or memory will leak.  Instead, create a dummy
1810                 // NSData and return its 'bytes' pointer, then autorelease the
1811                 // NSData.
1812                 NSData *data = [NSData dataWithBytes:s length:len+1];
1813                 *str = (char_u*)[data bytes];
1814             }
1816             vim_free(s);
1817         }
1818 #endif
1819     }
1821     return reply != nil;
1826  * Wait for replies from server with send port 'port'.
1827  * Return 0 and the malloc'ed string when a reply is available.
1828  * Return -1 on error.
1829  */
1830     int
1831 serverReadReply(int port, char_u **str)
1833     NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1834     if (reply && str) {
1835         char_u *s = (char_u*)[reply UTF8String];
1836 #ifdef FEAT_MBYTE
1837         s = CONVERT_FROM_UTF8(s);
1838 #endif
1839         *str = vim_strsave(s);
1840 #ifdef FEAT_MBYTE
1841         CONVERT_FROM_UTF8_FREE(s);
1842 #endif
1843         return 0;
1844     }
1846     return -1;
1851  * Send a reply string (notification) to client with port given by "serverid".
1852  * Return -1 if the window is invalid.
1853  */
1854     int
1855 serverSendReply(char_u *serverid, char_u *reply)
1857     int retval = -1;
1858     int port = serverStrToPort(serverid);
1859     if (port > 0 && reply) {
1860 #ifdef FEAT_MBYTE
1861         reply = CONVERT_TO_UTF8(reply);
1862 #endif
1863         BOOL ok = [[MMBackend sharedInstance]
1864                 sendReply:[NSString stringWithUTF8String:(char*)reply]
1865                    toPort:port];
1866         retval = ok ? 0 : -1;
1867 #ifdef FEAT_MBYTE
1868         CONVERT_TO_UTF8_FREE(reply);
1869 #endif
1870     }
1872     return retval;
1875 #endif // MAC_CLIENTSERVER
1880 // -- ODB Editor Support ----------------------------------------------------
1882 #ifdef FEAT_ODB_EDITOR
1884  * The ODB Editor protocol works like this:
1885  * - An external program (the server) asks MacVim to open a file and associates
1886  *   three things with this file: (1) a server id (a four character code that
1887  *   identifies the server), (2) a path that can be used as window title for
1888  *   the file (optional), (3) an arbitrary token (optional)
1889  * - When a file is saved or closed, MacVim should tell the server about which
1890  *   file was modified and also pass back the token
1892  * All communication between MacVim and the server goes via Apple Events.
1893  */
1895     static OSErr
1896 odb_event(buf_T *buf, const AEEventID action)
1898     if (!(buf->b_odb_server_id && buf->b_ffname))
1899         return noErr;
1901     NSAppleEventDescriptor *targetDesc = [NSAppleEventDescriptor
1902             descriptorWithDescriptorType:typeApplSignature
1903                                    bytes:&buf->b_odb_server_id
1904                                   length:sizeof(OSType)];
1906     // TODO: Convert b_ffname to UTF-8?
1907     NSString *path = [NSString stringWithUTF8String:(char*)buf->b_ffname];
1908     NSData *pathData = [[[NSURL fileURLWithPath:path] absoluteString]
1909             dataUsingEncoding:NSUTF8StringEncoding];
1910     NSAppleEventDescriptor *pathDesc = [NSAppleEventDescriptor
1911             descriptorWithDescriptorType:typeFileURL data:pathData];
1913     NSAppleEventDescriptor *event = [NSAppleEventDescriptor
1914             appleEventWithEventClass:kODBEditorSuite
1915                              eventID:action
1916                     targetDescriptor:targetDesc
1917                             returnID:kAutoGenerateReturnID
1918                        transactionID:kAnyTransactionID];
1920     [event setParamDescriptor:pathDesc forKeyword:keyDirectObject];
1922     if (buf->b_odb_token)
1923         [event setParamDescriptor:buf->b_odb_token forKeyword:keySenderToken];
1925     return AESendMessage([event aeDesc], NULL, kAENoReply | kAENeverInteract,
1926             kAEDefaultTimeout);
1929     OSErr
1930 odb_buffer_close(buf_T *buf)
1932     OSErr err = noErr;
1933     if (buf) {
1934         err = odb_event(buf, kAEClosedFile);
1936         buf->b_odb_server_id = 0;
1938         if (buf->b_odb_token) {
1939             [(NSAppleEventDescriptor *)(buf->b_odb_token) release];
1940             buf->b_odb_token = NULL;
1941         }
1943         if (buf->b_odb_fname) {
1944             vim_free(buf->b_odb_fname);
1945             buf->b_odb_fname = NULL;
1946         }
1947     }
1949     return err;
1952     OSErr
1953 odb_post_buffer_write(buf_T *buf)
1955     return buf ? odb_event(buf, kAEModifiedFile) : noErr;
1958     void
1959 odb_end(void)
1961     buf_T *buf;
1962     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1963         odb_buffer_close(buf);
1966 #endif // FEAT_ODB_EDITOR
1969     char_u *
1970 get_macaction_name(expand_T *xp, int idx)
1972     static char_u *str = NULL;
1973     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1975     if (nil == actionDict || idx < 0 || idx >= [actionDict count])
1976         return NULL;
1978     NSString *string = [[actionDict allKeys] objectAtIndex:idx];
1979     if (!string)
1980         return NULL;
1982     char_u *plainStr = (char_u*)[string UTF8String];
1984 #ifdef FEAT_MBYTE
1985     if (str) {
1986         vim_free(str);
1987         str = NULL;
1988     }
1989     if (input_conv.vc_type != CONV_NONE) {
1990         int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1991         str = string_convert(&input_conv, plainStr, &len);
1992         plainStr = str;
1993     }
1994 #endif
1996     return plainStr;
2000     int
2001 is_valid_macaction(char_u *action)
2003     int isValid = NO;
2004     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
2005     if (actionDict) {
2006 #ifdef FEAT_MBYTE
2007         action = CONVERT_TO_UTF8(action);
2008 #endif
2009         NSString *string = [NSString stringWithUTF8String:(char*)action];
2010         isValid = (nil != [actionDict objectForKey:string]);
2011 #ifdef FEAT_MBYTE
2012         CONVERT_TO_UTF8_FREE(action);
2013 #endif
2014     }
2016     return isValid;
2019 static int specialKeyToNSKey(int key)
2021     if (!IS_SPECIAL(key))
2022         return key;
2024     static struct {
2025         int special;
2026         int nskey;
2027     } sp2ns[] = {
2028         { K_UP, NSUpArrowFunctionKey },
2029         { K_DOWN, NSDownArrowFunctionKey },
2030         { K_LEFT, NSLeftArrowFunctionKey },
2031         { K_RIGHT, NSRightArrowFunctionKey },
2032         { K_F1, NSF1FunctionKey },
2033         { K_F2, NSF2FunctionKey },
2034         { K_F3, NSF3FunctionKey },
2035         { K_F4, NSF4FunctionKey },
2036         { K_F5, NSF5FunctionKey },
2037         { K_F6, NSF6FunctionKey },
2038         { K_F7, NSF7FunctionKey },
2039         { K_F8, NSF8FunctionKey },
2040         { K_F9, NSF9FunctionKey },
2041         { K_F10, NSF10FunctionKey },
2042         { K_F11, NSF11FunctionKey },
2043         { K_F12, NSF12FunctionKey },
2044         { K_F13, NSF13FunctionKey },
2045         { K_F14, NSF14FunctionKey },
2046         { K_F15, NSF15FunctionKey },
2047         { K_F16, NSF16FunctionKey },
2048         { K_F17, NSF17FunctionKey },
2049         { K_F18, NSF18FunctionKey },
2050         { K_F19, NSF19FunctionKey },
2051         { K_F20, NSF20FunctionKey },
2052         { K_F21, NSF21FunctionKey },
2053         { K_F22, NSF22FunctionKey },
2054         { K_F23, NSF23FunctionKey },
2055         { K_F24, NSF24FunctionKey },
2056         { K_F25, NSF25FunctionKey },
2057         { K_F26, NSF26FunctionKey },
2058         { K_F27, NSF27FunctionKey },
2059         { K_F28, NSF28FunctionKey },
2060         { K_F29, NSF29FunctionKey },
2061         { K_F30, NSF30FunctionKey },
2062         { K_F31, NSF31FunctionKey },
2063         { K_F32, NSF32FunctionKey },
2064         { K_F33, NSF33FunctionKey },
2065         { K_F34, NSF34FunctionKey },
2066         { K_F35, NSF35FunctionKey },
2067         { K_DEL, NSBackspaceCharacter },
2068         { K_BS, NSDeleteCharacter },
2069         { K_HOME, NSHomeFunctionKey },
2070         { K_END, NSEndFunctionKey },
2071         { K_PAGEUP, NSPageUpFunctionKey },
2072         { K_PAGEDOWN, NSPageDownFunctionKey }
2073     };
2075     int i;
2076     for (i = 0; i < sizeof(sp2ns)/sizeof(sp2ns[0]); ++i) {
2077         if (sp2ns[i].special == key)
2078             return sp2ns[i].nskey;
2079     }
2081     return 0;
2084 static int vimModMaskToEventModifierFlags(int mods)
2086     int flags = 0;
2088     if (mods & MOD_MASK_SHIFT)
2089         flags |= NSShiftKeyMask;
2090     if (mods & MOD_MASK_CTRL)
2091         flags |= NSControlKeyMask;
2092     if (mods & MOD_MASK_ALT)
2093         flags |= NSAlternateKeyMask;
2094     if (mods & MOD_MASK_CMD)
2095         flags |= NSCommandKeyMask;
2097     return flags;