Don't init backend if Vim is about to fork
[MacVim.git] / src / MacVim / gui_macvim.m
blob5e0ae5a9c98a73cde5c241a5ab7892f8d8a631c1
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     [[MMBackend sharedInstance] flushQueue:NO];
232 /* Force flush output to MacVim.  Do not call this method unless absolutely
233  * necessary (use gui_mch_flush() instead). */
234     void
235 gui_macvim_force_flush(void)
237     [[MMBackend sharedInstance] flushQueue:YES];
242  * GUI input routine called by gui_wait_for_chars().  Waits for a character
243  * from the keyboard.
244  *  wtime == -1     Wait forever.
245  *  wtime == 0      This should never happen.
246  *  wtime > 0       Wait wtime milliseconds for a character.
247  * Returns OK if a character was found to be available within the given time,
248  * or FAIL otherwise.
249  */
250     int
251 gui_mch_wait_for_chars(int wtime)
253     // NOTE! In all likelihood Vim will take a nap when waitForInput: is
254     // called, so force a flush of the command queue here.
255     [[MMBackend sharedInstance] flushQueue:YES];
257     return [[MMBackend sharedInstance] waitForInput:wtime];
261 // -- Drawing ---------------------------------------------------------------
265  * Clear the whole text window.
266  */
267     void
268 gui_mch_clear_all(void)
270     [[MMBackend sharedInstance] clearAll];
275  * Clear a rectangular region of the screen from text pos (row1, col1) to
276  * (row2, col2) inclusive.
277  */
278     void
279 gui_mch_clear_block(int row1, int col1, int row2, int col2)
281     [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
282                                                     toRow:row2 column:col2];
287  * Delete the given number of lines from the given row, scrolling up any
288  * text further down within the scroll region.
289  */
290     void
291 gui_mch_delete_lines(int row, int num_lines)
293     [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
294             scrollBottom:gui.scroll_region_bot
295                     left:gui.scroll_region_left
296                    right:gui.scroll_region_right];
300     void
301 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
303 #ifdef FEAT_MBYTE
304     char_u *conv_str = NULL;
305     if (output_conv.vc_type != CONV_NONE) {
306         conv_str = string_convert(&output_conv, s, &len);
307         if (conv_str)
308             s = conv_str;
309     }
310 #endif
312     [[MMBackend sharedInstance] drawString:(char*)s length:len row:row
313                                     column:col cells:len flags:flags];
315 #ifdef FEAT_MBYTE
316     if (conv_str)
317         vim_free(conv_str);
318 #endif
322     int
323 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
325     int c, cn, cl, i;
326     int start = 0;
327     int endcol = col;
328     int startcol = col;
329     BOOL wide = NO;
330     MMBackend *backend = [MMBackend sharedInstance];
331 #ifdef FEAT_MBYTE
332     char_u *conv_str = NULL;
334     if (output_conv.vc_type != CONV_NONE) {
335         conv_str = string_convert(&output_conv, s, &len);
336         if (conv_str)
337             s = conv_str;
338     }
339 #endif
341     // Loop over each character and output text when it changes from normal to
342     // wide and vice versa.
343     for (i = 0; i < len; i += cl) {
344         c = utf_ptr2char(s + i);
345         cl = utf_ptr2len(s + i);
346         cn = utf_char2cells(c);
348         if (!utf_iscomposing(c)) {
349             if ((cn > 1 && !wide) || (cn <= 1 && wide)) {
350                 // Changed from normal to wide or vice versa.
351                 [backend drawString:(char*)(s+start) length:i-start
352                                    row:row column:startcol
353                                  cells:endcol-startcol
354                                  flags:(wide ? flags|DRAW_WIDE : flags)];
356                 start = i;
357                 startcol = endcol;
358             }
360             wide = cn > 1;
361             endcol += cn;
362         }
363     }
365     // Output remaining characters.
366     [backend drawString:(char*)(s+start) length:len-start
367                     row:row column:startcol cells:endcol-startcol
368                   flags:(wide ? flags|DRAW_WIDE : flags)];
370 #ifdef FEAT_MBYTE
371     if (conv_str)
372         vim_free(conv_str);
373 #endif
375     return endcol - col;
380  * Insert the given number of lines before the given row, scrolling down any
381  * following text within the scroll region.
382  */
383     void
384 gui_mch_insert_lines(int row, int num_lines)
386     [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
387             scrollBottom:gui.scroll_region_bot
388                     left:gui.scroll_region_left
389                    right:gui.scroll_region_right];
394  * Set the current text foreground color.
395  */
396     void
397 gui_mch_set_fg_color(guicolor_T color)
399     [[MMBackend sharedInstance] setForegroundColor:color];
404  * Set the current text background color.
405  */
406     void
407 gui_mch_set_bg_color(guicolor_T color)
409     [[MMBackend sharedInstance] setBackgroundColor:color];
414  * Set the current text special color (used for underlines).
415  */
416     void
417 gui_mch_set_sp_color(guicolor_T color)
419     [[MMBackend sharedInstance] setSpecialColor:color];
424  * Set default colors.
425  */
426     void
427 gui_mch_def_colors()
429     MMBackend *backend = [MMBackend sharedInstance];
431     // The default colors are taken from system values
432     gui.def_norm_pixel = gui.norm_pixel = 
433         [backend lookupColorWithKey:@"MacTextColor"];
434     gui.def_back_pixel = gui.back_pixel = 
435         [backend lookupColorWithKey:@"MacTextBackgroundColor"];
440  * Called when the foreground or background color has been changed.
441  */
442     void
443 gui_mch_new_colors(void)
445     gui.def_back_pixel = gui.back_pixel;
446     gui.def_norm_pixel = gui.norm_pixel;
448     //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
449     //        gui.def_norm_pixel);
451     [[MMBackend sharedInstance]
452         setDefaultColorsBackground:gui.def_back_pixel
453                         foreground:gui.def_norm_pixel];
457  * Invert a rectangle from row r, column c, for nr rows and nc columns.
458  */
459     void
460 gui_mch_invert_rectangle(int r, int c, int nr, int nc, int invert)
462     [[MMBackend sharedInstance] drawInvertedRectAtRow:r column:c numRows:nr
463             numColumns:nc invert:invert];
468 // -- Tabline ---------------------------------------------------------------
472  * Set the current tab to "nr".  First tab is 1.
473  */
474     void
475 gui_mch_set_curtab(int nr)
477     [[MMBackend sharedInstance] selectTab:nr];
482  * Return TRUE when tabline is displayed.
483  */
484     int
485 gui_mch_showing_tabline(void)
487     return [[MMBackend sharedInstance] tabBarVisible];
491  * Update the labels of the tabline.
492  */
493     void
494 gui_mch_update_tabline(void)
496     [[MMBackend sharedInstance] updateTabBar];
500  * Show or hide the tabline.
501  */
502     void
503 gui_mch_show_tabline(int showit)
505     [[MMBackend sharedInstance] showTabBar:showit];
509 // -- Clipboard -------------------------------------------------------------
512     void
513 clip_mch_lose_selection(VimClipboard *cbd)
518     int
519 clip_mch_own_selection(VimClipboard *cbd)
521     return 0;
525     void
526 clip_mch_request_selection(VimClipboard *cbd)
528     NSPasteboard *pb = [NSPasteboard generalPasteboard];
529     NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
530             NSStringPboardType, nil];
531     NSString *bestType = [pb availableTypeFromArray:supportedTypes];
532     if (!bestType) return;
534     int motion_type = MCHAR;
535     NSString *string = nil;
537     if ([bestType isEqual:VimPBoardType]) {
538         // This type should consist of an array with two objects:
539         //   1. motion type (NSNumber)
540         //   2. text (NSString)
541         // If this is not the case we fall back on using NSStringPboardType.
542         id plist = [pb propertyListForType:VimPBoardType];
543         if ([plist isKindOfClass:[NSArray class]] && [plist count] == 2) {
544             id obj = [plist objectAtIndex:1];
545             if ([obj isKindOfClass:[NSString class]]) {
546                 motion_type = [[plist objectAtIndex:0] intValue];
547                 string = obj;
548             }
549         }
550     }
552     if (!string) {
553         // Use NSStringPboardType.  The motion type is set to line-wise if the
554         // string contains at least one EOL character, otherwise it is set to
555         // character-wise (block-wise is never used).
556         NSMutableString *mstring =
557                 [[pb stringForType:NSStringPboardType] mutableCopy];
558         if (!mstring) return;
560         // Replace unrecognized end-of-line sequences with \x0a (line feed).
561         NSRange range = { 0, [mstring length] };
562         unsigned n = [mstring replaceOccurrencesOfString:@"\x0d\x0a"
563                                              withString:@"\x0a" options:0
564                                                   range:range];
565         if (0 == n) {
566             n = [mstring replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
567                                            options:0 range:range];
568         }
569         
570         // Scan for newline character to decide whether the string should be
571         // pasted line-wise or character-wise.
572         motion_type = MCHAR;
573         if (0 < n || NSNotFound != [mstring rangeOfString:@"\n"].location)
574             motion_type = MLINE;
576         string = mstring;
577     }
579     if (!(MCHAR == motion_type || MLINE == motion_type || MBLOCK == motion_type
580             || MAUTO == motion_type))
581         motion_type = MCHAR;
583     char_u *str = (char_u*)[string UTF8String];
584     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
586 #ifdef FEAT_MBYTE
587     if (input_conv.vc_type != CONV_NONE)
588         str = string_convert(&input_conv, str, &len);
589 #endif
591     if (str)
592         clip_yank_selection(motion_type, str, len, cbd);
594 #ifdef FEAT_MBYTE
595     if (input_conv.vc_type != CONV_NONE)
596         vim_free(str);
597 #endif
602  * Send the current selection to the clipboard.
603  */
604     void
605 clip_mch_set_selection(VimClipboard *cbd)
607     // If the '*' register isn't already filled in, fill it in now.
608     cbd->owned = TRUE;
609     clip_get_selection(cbd);
610     cbd->owned = FALSE;
611     
612     // Get the text to put on the pasteboard.
613     long_u llen = 0; char_u *str = 0;
614     int motion_type = clip_convert_selection(&str, &llen, cbd);
615     if (motion_type < 0)
616         return;
618     // TODO: Avoid overflow.
619     int len = (int)llen;
620 #ifdef FEAT_MBYTE
621     if (output_conv.vc_type != CONV_NONE) {
622         char_u *conv_str = string_convert(&output_conv, str, &len);
623         if (conv_str) {
624             vim_free(str);
625             str = conv_str;
626         }
627     }
628 #endif
630     if (len > 0) {
631         NSString *string = [[NSString alloc]
632             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
634         // See clip_mch_request_selection() for info on pasteboard types.
635         NSPasteboard *pb = [NSPasteboard generalPasteboard];
636         NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
637                 NSStringPboardType, nil];
638         [pb declareTypes:supportedTypes owner:nil];
640         NSNumber *motion = [NSNumber numberWithInt:motion_type];
641         NSArray *plist = [NSArray arrayWithObjects:motion, string, nil];
642         [pb setPropertyList:plist forType:VimPBoardType];
644         [pb setString:string forType:NSStringPboardType];
645         
646         [string release];
647     }
649     vim_free(str);
653 // -- Menu ------------------------------------------------------------------
657  * A menu descriptor represents the "address" of a menu as an array of strings.
658  * E.g. the menu "File->Close" has descriptor { "File", "Close" }.
659  */
660     NSArray *
661 descriptor_for_menu(vimmenu_T *menu)
663     if (!menu) return nil;
665     NSMutableArray *desc = [NSMutableArray array];
666     while (menu) {
667         NSString *name = [NSString stringWithVimString:menu->dname];
668         [desc insertObject:name atIndex:0];
669         menu = menu->parent;
670     }
672     return desc;
675     vimmenu_T *
676 menu_for_descriptor(NSArray *desc)
678     if (!(desc && [desc count] > 0)) return NULL;
680     vimmenu_T *menu = root_menu;
681     int i, count = [desc count];
683     for (i = 0; i < count; ++i) {
684         NSString *component = [desc objectAtIndex:i];
685         while (menu) {
686             NSString *name = [NSString stringWithVimString:menu->dname];
687             if ([component isEqual:name]) {
688                 if (i+1 == count)
689                     return menu;    // Matched all components, so return menu
690                 menu = menu->children;
691                 break;
692             }
693             menu = menu->next;
694         }
695     }
697     return NULL;
701  * Add a submenu to the menu bar, toolbar, or a popup menu.
702  */
703     void
704 gui_mch_add_menu(vimmenu_T *menu, int idx)
706     NSArray *desc = descriptor_for_menu(menu);
707     [[MMBackend sharedInstance] queueMessage:AddMenuMsgID properties:
708         [NSDictionary dictionaryWithObjectsAndKeys:
709             desc, @"descriptor",
710             [NSNumber numberWithInt:idx], @"index",
711             nil]];
716  * Add a menu item to a menu
717  */
718     void
719 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
721     char_u *tip = menu->strings[MENU_INDEX_TIP]
722             ? menu->strings[MENU_INDEX_TIP] : menu->actext;
723     NSArray *desc = descriptor_for_menu(menu);
724     NSString *keyEquivalent = menu->mac_key
725         ? [NSString stringWithFormat:@"%C", specialKeyToNSKey(menu->mac_key)]
726         : [NSString string];
727     int modifierMask = vimModMaskToEventModifierFlags(menu->mac_mods);
728     char_u *icon = NULL;
730     if (menu_is_toolbar(menu->parent->name)) {
731         char_u fname[MAXPATHL];
733         // TODO: Ensure menu->iconfile exists (if != NULL)
734         icon = menu->iconfile;
735         if (!icon && gui_find_bitmap(menu->name, fname, "bmp") == OK)
736             icon = fname;
737         if (!icon && menu->iconidx >= 0)
738             icon = menu->dname;
739     }
741     [[MMBackend sharedInstance] queueMessage:AddMenuItemMsgID properties:
742         [NSDictionary dictionaryWithObjectsAndKeys:
743             desc, @"descriptor",
744             [NSNumber numberWithInt:idx], @"index",
745             [NSString stringWithVimString:tip], @"tip",
746             [NSString stringWithVimString:icon], @"icon",
747             keyEquivalent, @"keyEquivalent",
748             [NSNumber numberWithInt:modifierMask], @"modifierMask",
749             [NSString stringWithVimString:menu->mac_action], @"action",
750             [NSNumber numberWithBool:menu->mac_alternate], @"isAlternate",
751             nil]];
756  * Destroy the machine specific menu widget.
757  */
758     void
759 gui_mch_destroy_menu(vimmenu_T *menu)
761     NSArray *desc = descriptor_for_menu(menu);
762     [[MMBackend sharedInstance] queueMessage:RemoveMenuItemMsgID properties:
763         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
768  * Make a menu either grey or not grey.
769  */
770     void
771 gui_mch_menu_grey(vimmenu_T *menu, int grey)
773     /* Only update menu if the 'grey' state has changed to avoid having to pass
774      * lots of unnecessary data to MacVim.  (Skipping this test makes MacVim
775      * pause noticably on mode changes. */
776     NSArray *desc = descriptor_for_menu(menu);
777     if (menu->was_grey == grey)
778         return;
780     menu->was_grey = grey;
782     [[MMBackend sharedInstance] queueMessage:EnableMenuItemMsgID properties:
783         [NSDictionary dictionaryWithObjectsAndKeys:
784             desc, @"descriptor",
785             [NSNumber numberWithInt:!grey], @"enable",
786             nil]];
791  * Make menu item hidden or not hidden
792  */
793     void
794 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
796     // HACK! There is no (obvious) way to hide a menu item, so simply
797     // enable/disable it instead.
798     gui_mch_menu_grey(menu, hidden);
803  * This is called when user right clicks.
804  */
805     void
806 gui_mch_show_popupmenu(vimmenu_T *menu)
808     NSArray *desc = descriptor_for_menu(menu);
809     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:
810         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
815  * This is called when a :popup command is executed.
816  */
817     void
818 gui_make_popup(char_u *path_name, int mouse_pos)
820     vimmenu_T *menu = gui_find_menu(path_name);
821     if (!(menu && menu->children)) return;
823     NSArray *desc = descriptor_for_menu(menu);
824     NSDictionary *p = (mouse_pos || NULL == curwin)
825         ? [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]
826         : [NSDictionary dictionaryWithObjectsAndKeys:
827             desc, @"descriptor",
828             [NSNumber numberWithInt:curwin->w_wrow], @"row",
829             [NSNumber numberWithInt:curwin->w_wcol], @"column",
830             nil];
832     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:p];
837  * This is called after setting all the menus to grey/hidden or not.
838  */
839     void
840 gui_mch_draw_menubar(void)
842     // The (main) menu draws itself in Mac OS X.
846     void
847 gui_mch_enable_menu(int flag)
849     // The (main) menu is always enabled in Mac OS X.
853 #if 0
854     void
855 gui_mch_set_menu_pos(int x, int y, int w, int h)
857     // The (main) menu cannot be moved in Mac OS X.
859 #endif
862     void
863 gui_mch_show_toolbar(int showit)
865     int flags = 0;
866     if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
867     if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
868     if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
870     [[MMBackend sharedInstance] showToolbar:showit flags:flags];
876 // -- Fonts -----------------------------------------------------------------
880  * If a font is not going to be used, free its structure.
881  */
882     void
883 gui_mch_free_font(font)
884     GuiFont     font;
886     if (font != NOFONT) {
887         //NSLog(@"gui_mch_free_font(font=0x%x)", font);
888         [(NSFont*)font release];
889     }
894  * Get a font structure for highlighting.
895  */
896     GuiFont
897 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
899     //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
900     //        giveErrorIfMissing);
902     NSFont *font = gui_macvim_font_with_name(name);
903     if (font)
904         return (GuiFont)[font retain];
906     if (giveErrorIfMissing)
907         EMSG2(_(e_font), name);
909     return NOFONT;
913 #if defined(FEAT_EVAL) || defined(PROTO)
915  * Return the name of font "font" in allocated memory.
916  * Don't know how to get the actual name, thus use the provided name.
917  */
918     char_u *
919 gui_mch_get_fontname(GuiFont font, char_u *name)
921     if (name == NULL)
922         return NULL;
923     return vim_strsave(name);
925 #endif
929  * Initialise vim to use the font with the given name.  Return FAIL if the font
930  * could not be loaded, OK otherwise.
931  */
932     int
933 gui_mch_init_font(char_u *font_name, int fontset)
935     //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
937     if (font_name && STRCMP(font_name, "*") == 0) {
938         // :set gfn=* shows the font panel.
939         do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
940         return FAIL;
941     }
943     NSFont *font = gui_macvim_font_with_name(font_name);
944     if (font) {
945         [(NSFont*)gui.norm_font release];
946         gui.norm_font = (GuiFont)[font retain];
948         // NOTE: MacVim keeps separate track of the normal and wide fonts.
949         // Unless the user changes 'guifontwide' manually, they are based on
950         // the same (normal) font.  Also note that each time the normal font is
951         // set, the advancement may change so the wide font needs to be updated
952         // as well (so that it is always twice the width of the normal font).
953         [[MMBackend sharedInstance] setFont:font];
954         [[MMBackend sharedInstance] setWideFont:
955                (NOFONT == gui.wide_font ? font : (NSFont*)gui.wide_font)];
957         return OK;
958     }
960     return FAIL;
965  * Set the current text font.
966  */
967     void
968 gui_mch_set_font(GuiFont font)
970     // Font selection is done inside MacVim...nothing here to do.
974     NSFont *
975 gui_macvim_font_with_name(char_u *name)
977     NSFont *font = nil;
978     NSString *fontName = MMDefaultFontName;
979     float size = MMDefaultFontSize;
980     BOOL parseFailed = NO;
982 #ifdef FEAT_MBYTE
983     name = CONVERT_TO_UTF8(name);
984 #endif
986     if (name) {
987         fontName = [NSString stringWithUTF8String:(char*)name];
989         NSArray *components = [fontName componentsSeparatedByString:@":"];
990         if ([components count] == 2) {
991             NSString *sizeString = [components lastObject];
992             if ([sizeString length] > 0
993                     && [sizeString characterAtIndex:0] == 'h') {
994                 sizeString = [sizeString substringFromIndex:1];
995                 if ([sizeString length] > 0) {
996                     size = [sizeString floatValue];
997                     fontName = [components objectAtIndex:0];
998                 }
999             } else {
1000                 parseFailed = YES;
1001             }
1002         } else if ([components count] > 2) {
1003             parseFailed = YES;
1004         }
1006         if (!parseFailed) {
1007             // Replace underscores with spaces.
1008             fontName = [[fontName componentsSeparatedByString:@"_"]
1009                                      componentsJoinedByString:@" "];
1010         }
1011     }
1013     if (!parseFailed && [fontName length] > 0) {
1014         if (size < MMMinFontSize) size = MMMinFontSize;
1015         if (size > MMMaxFontSize) size = MMMaxFontSize;
1017         font = [NSFont fontWithName:fontName size:size];
1019         if (!font && MMDefaultFontName == fontName) {
1020             // If for some reason the MacVim default font is not in the app
1021             // bundle, then fall back on the system default font.
1022             font = [NSFont userFixedPitchFontOfSize:0];
1023         }
1024     }
1026 #ifdef FEAT_MBYTE
1027     CONVERT_TO_UTF8_FREE(name);
1028 #endif
1030     return font;
1033 // -- Scrollbars ------------------------------------------------------------
1036     void
1037 gui_mch_create_scrollbar(
1038         scrollbar_T *sb,
1039         int orient)     /* SBAR_VERT or SBAR_HORIZ */
1041     [[MMBackend sharedInstance] 
1042             createScrollbarWithIdentifier:sb->ident type:sb->type];
1046     void
1047 gui_mch_destroy_scrollbar(scrollbar_T *sb)
1049     [[MMBackend sharedInstance] 
1050             destroyScrollbarWithIdentifier:sb->ident];
1054     void
1055 gui_mch_enable_scrollbar(
1056         scrollbar_T     *sb,
1057         int             flag)
1059     [[MMBackend sharedInstance] 
1060             showScrollbarWithIdentifier:sb->ident state:flag];
1064     void
1065 gui_mch_set_scrollbar_pos(
1066         scrollbar_T *sb,
1067         int x,
1068         int y,
1069         int w,
1070         int h)
1072     int pos = y;
1073     int len = h;
1074     if (SBAR_BOTTOM == sb->type) {
1075         pos = x;
1076         len = w; 
1077     }
1079     [[MMBackend sharedInstance] 
1080             setScrollbarPosition:pos length:len identifier:sb->ident];
1084     void
1085 gui_mch_set_scrollbar_thumb(
1086         scrollbar_T *sb,
1087         long val,
1088         long size,
1089         long max)
1091     [[MMBackend sharedInstance] 
1092             setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
1096 // -- Cursor ----------------------------------------------------------------
1100  * Draw a cursor without focus.
1101  */
1102     void
1103 gui_mch_draw_hollow_cursor(guicolor_T color)
1105     return [[MMBackend sharedInstance]
1106         drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
1107                fraction:100 color:color];
1112  * Draw part of a cursor, only w pixels wide, and h pixels high.
1113  */
1114     void
1115 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
1117     // HACK!  'w' and 'h' are always 1 since we do not tell Vim about the exact
1118     // font dimensions.  Thus these parameters are useless.  Instead we look at
1119     // the shape_table to determine the shape and size of the cursor (just like
1120     // gui_update_cursor() does).
1122 #ifdef FEAT_RIGHTLEFT
1123     // If 'rl' is set the insert mode cursor must be drawn on the right-hand
1124     // side of a text cell.
1125     int rl = curwin ? curwin->w_p_rl : FALSE;
1126 #else
1127     int rl = FALSE;
1128 #endif
1129     int idx = get_shape_idx(FALSE);
1130     int shape = MMInsertionPointBlock;
1131     switch (shape_table[idx].shape) {
1132         case SHAPE_HOR:
1133             shape = MMInsertionPointHorizontal;
1134             break;
1135         case SHAPE_VER:
1136             shape = rl ? MMInsertionPointVerticalRight
1137                        : MMInsertionPointVertical;
1138             break;
1139     }
1141     return [[MMBackend sharedInstance]
1142         drawCursorAtRow:gui.row column:gui.col shape:shape
1143                fraction:shape_table[idx].percentage color:color];
1148  * Cursor blink functions.
1150  * This is a simple state machine:
1151  * BLINK_NONE   not blinking at all
1152  * BLINK_OFF    blinking, cursor is not shown
1153  * BLINK_ON blinking, cursor is shown
1154  */
1155     void
1156 gui_mch_set_blinking(long wait, long on, long off)
1158     [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1163  * Start the cursor blinking.  If it was already blinking, this restarts the
1164  * waiting time and shows the cursor.
1165  */
1166     void
1167 gui_mch_start_blink(void)
1169     [[MMBackend sharedInstance] startBlink];
1174  * Stop the cursor blinking.  Show the cursor if it wasn't shown.
1175  */
1176     void
1177 gui_mch_stop_blink(void)
1179     [[MMBackend sharedInstance] stopBlink];
1183 // -- Mouse -----------------------------------------------------------------
1187  * Get current mouse coordinates in text window.
1188  */
1189     void
1190 gui_mch_getmouse(int *x, int *y)
1192     //NSLog(@"gui_mch_getmouse()");
1196     void
1197 gui_mch_setmouse(int x, int y)
1199     //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1203     void
1204 mch_set_mouse_shape(int shape)
1206     [[MMBackend sharedInstance] setMouseShape:shape];
1212 // -- Input Method ----------------------------------------------------------
1214 #if defined(USE_IM_CONTROL)
1216     void
1217 im_set_position(int row, int col)
1219     // The pre-edit area is a popup window which is displayed by MMTextView.
1220     [[MMBackend sharedInstance] setPreEditRow:row column:col];
1224     void
1225 im_set_active(int active)
1227     // Set roman or the system script if 'active' is TRUE or FALSE,
1228     // respectively.
1229     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1231     if (!p_imdisable && smRoman != systemScript)
1232         KeyScript(active ? smKeySysScript : smKeyRoman);
1236     int
1237 im_get_status(void)
1239     // IM is active whenever the current script is the system script and the
1240     // system script isn't roman.  (Hence IM can only be active when using
1241     // non-roman scripts.)
1242     SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
1243     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1245     return currentScript != smRoman && currentScript == systemScript;
1248 #endif // defined(USE_IM_CONTROL)
1253 // -- Unsorted --------------------------------------------------------------
1256     void
1257 ex_macaction(eap)
1258     exarg_T     *eap;
1260     if (!gui.in_use) {
1261         EMSG(_("E???: Command only available in GUI mode"));
1262         return;
1263     }
1265     char_u *arg = eap->arg;
1266 #ifdef FEAT_MBYTE
1267     arg = CONVERT_TO_UTF8(arg);
1268 #endif
1270     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1271     NSString *name = [NSString stringWithUTF8String:(char*)arg];
1272     if (actionDict && [actionDict objectForKey:name] != nil) {
1273         [[MMBackend sharedInstance] executeActionWithName:name];
1274     } else {
1275         EMSG2(_("E???: Invalid action: %s"), eap->arg);
1276     }
1278 #ifdef FEAT_MBYTE
1279     arg = CONVERT_TO_UTF8(arg);
1280 #endif
1285  * Adjust gui.char_height (after 'linespace' was changed).
1286  */
1287     int
1288 gui_mch_adjust_charheight(void)
1290     [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1291     return OK;
1295     void
1296 gui_mch_beep(void)
1298     NSBeep();
1303 #ifdef FEAT_BROWSE
1305  * Pop open a file browser and return the file selected, in allocated memory,
1306  * or NULL if Cancel is hit.
1307  *  saving  - TRUE if the file will be saved to, FALSE if it will be opened.
1308  *  title   - Title message for the file browser dialog.
1309  *  dflt    - Default name of file.
1310  *  ext     - Default extension to be added to files without extensions.
1311  *  initdir - directory in which to open the browser (NULL = current dir)
1312  *  filter  - Filter for matched files to choose from.
1313  *  Has a format like this:
1314  *  "C Files (*.c)\0*.c\0"
1315  *  "All Files\0*.*\0\0"
1316  *  If these two strings were concatenated, then a choice of two file
1317  *  filters will be selectable to the user.  Then only matching files will
1318  *  be shown in the browser.  If NULL, the default allows all files.
1320  *  *NOTE* - the filter string must be terminated with TWO nulls.
1321  */
1322     char_u *
1323 gui_mch_browse(
1324     int saving,
1325     char_u *title,
1326     char_u *dflt,
1327     char_u *ext,
1328     char_u *initdir,
1329     char_u *filter)
1331     //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1332     //        " filter=%s", saving, title, dflt, ext, initdir, filter);
1334     // Ensure no data is on the output queue before presenting the dialog.
1335     gui_macvim_force_flush();
1337     NSMutableDictionary *attr = [NSMutableDictionary
1338         dictionaryWithObject:[NSNumber numberWithBool:saving]
1339                       forKey:@"saving"];
1340     if (initdir)
1341         [attr setObject:[NSString stringWithVimString:initdir] forKey:@"dir"];
1343     char_u *s = (char_u*)[[MMBackend sharedInstance]
1344                             browseForFileWithAttributes:attr];
1346     return s;
1348 #endif /* FEAT_BROWSE */
1352     int
1353 gui_mch_dialog(
1354     int         type,
1355     char_u      *title,
1356     char_u      *message,
1357     char_u      *buttons,
1358     int         dfltbutton,
1359     char_u      *textfield)
1361     //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1362     //        "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1363     //        dfltbutton, textfield);
1365     // Ensure no data is on the output queue before presenting the dialog.
1366     gui_macvim_force_flush();
1368     int style = NSInformationalAlertStyle;
1369     if (VIM_WARNING == type) style = NSWarningAlertStyle;
1370     else if (VIM_ERROR == type) style = NSCriticalAlertStyle;
1372     NSMutableDictionary *attr = [NSMutableDictionary
1373                         dictionaryWithObject:[NSNumber numberWithInt:style]
1374                                       forKey:@"alertStyle"];
1376     if (buttons) {
1377         // 'buttons' is a string of '\n'-separated button titles 
1378         NSString *string = [NSString stringWithVimString:buttons];
1379         NSArray *array = [string componentsSeparatedByString:@"\n"];
1380         [attr setObject:array forKey:@"buttonTitles"];
1381     }
1383     NSString *messageText = nil;
1384     if (title)
1385         messageText = [NSString stringWithVimString:title];
1387     if (message) {
1388         NSString *informativeText = [NSString stringWithVimString:message];
1389         if (!messageText) {
1390             // HACK! If there is a '\n\n' or '\n' sequence in the message, then
1391             // make the part up to there into the title.  We only do this
1392             // because Vim has lots of dialogs without a title and they look
1393             // ugly that way.
1394             // TODO: Fix the actual dialog texts.
1395             NSRange eolRange = [informativeText rangeOfString:@"\n\n"];
1396             if (NSNotFound == eolRange.location)
1397                 eolRange = [informativeText rangeOfString:@"\n"];
1398             if (NSNotFound != eolRange.location) {
1399                 messageText = [informativeText substringToIndex:
1400                                                         eolRange.location];
1401                 informativeText = [informativeText substringFromIndex:
1402                                                         NSMaxRange(eolRange)];
1403             }
1404         }
1406         [attr setObject:informativeText forKey:@"informativeText"];
1407     }
1409     if (messageText)
1410         [attr setObject:messageText forKey:@"messageText"];
1412     if (textfield) {
1413         NSString *string = [NSString stringWithVimString:textfield];
1414         [attr setObject:string forKey:@"textFieldString"];
1415     }
1417     return [[MMBackend sharedInstance] showDialogWithAttributes:attr
1418                                                     textField:(char*)textfield];
1422     void
1423 gui_mch_flash(int msec)
1429  * Return the Pixel value (color) for the given color name.  This routine was
1430  * pretty much taken from example code in the Silicon Graphics OSF/Motif
1431  * Programmer's Guide.
1432  * Return INVALCOLOR when failed.
1433  */
1434     guicolor_T
1435 gui_mch_get_color(char_u *name)
1437 #ifdef FEAT_MBYTE
1438     name = CONVERT_TO_UTF8(name);
1439 #endif
1441     NSString *key = [NSString stringWithUTF8String:(char*)name];
1442     guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1444 #ifdef FEAT_MBYTE
1445     CONVERT_TO_UTF8_FREE(name);
1446 #endif
1448     return col;
1453  * Return the RGB value of a pixel as long.
1454  */
1455     long_u
1456 gui_mch_get_rgb(guicolor_T pixel)
1458     // This is only implemented so that vim can guess the correct value for
1459     // 'background' (which otherwise defaults to 'dark'); it is not used for
1460     // anything else (as far as I know).
1461     // The implementation is simple since colors are stored in an int as
1462     // "rrggbb".
1463     return pixel;
1468  * Get the screen dimensions.
1469  * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1470  * Is there no way to find out how wide the borders really are?
1471  * TODO: Add live udate of those value on suspend/resume.
1472  */
1473     void
1474 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1476     //NSLog(@"gui_mch_get_screen_dimensions()");
1477     *screen_w = Columns;
1478     *screen_h = Rows;
1483  * Get the position of the top left corner of the window.
1484  */
1485     int
1486 gui_mch_get_winpos(int *x, int *y)
1488     *x = *y = 0;
1489     return OK;
1494  * Return OK if the key with the termcap name "name" is supported.
1495  */
1496     int
1497 gui_mch_haskey(char_u *name)
1499     BOOL ok = NO;
1501 #ifdef FEAT_MBYTE
1502     name = CONVERT_TO_UTF8(name);
1503 #endif
1505     NSString *value = [NSString stringWithUTF8String:(char*)name];
1506     if (value)
1507         ok =  [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1509 #ifdef FEAT_MBYTE
1510     CONVERT_TO_UTF8_FREE(name);
1511 #endif
1513     return ok;
1518  * Iconify the GUI window.
1519  */
1520     void
1521 gui_mch_iconify(void)
1526 #if defined(FEAT_EVAL) || defined(PROTO)
1528  * Bring the Vim window to the foreground.
1529  */
1530     void
1531 gui_mch_set_foreground(void)
1533     [[MMBackend sharedInstance] activate];
1535 #endif
1539     void
1540 gui_mch_set_shellsize(
1541     int         width,
1542     int         height,
1543     int         min_width,
1544     int         min_height,
1545     int         base_width,
1546     int         base_height,
1547     int         direction)
1549     //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1550     //        " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1551     //        width, height, min_width, min_height, base_width, base_height,
1552     //        direction);
1553     [[MMBackend sharedInstance] setRows:height columns:width];
1557     void
1558 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1563  * Set the position of the top left corner of the window to the given
1564  * coordinates.
1565  */
1566     void
1567 gui_mch_set_winpos(int x, int y)
1572 #ifdef FEAT_TITLE
1574  * Set the window title and icon.
1575  * (The icon is not taken care of).
1576  */
1577     void
1578 gui_mch_settitle(char_u *title, char_u *icon)
1580     //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1582 #ifdef FEAT_MBYTE
1583     title = CONVERT_TO_UTF8(title);
1584 #endif
1586     MMBackend *backend = [MMBackend sharedInstance];
1587     [backend setWindowTitle:(char*)title];
1589     // TODO: Convert filename to UTF-8?
1590     if (curbuf)
1591         [backend setDocumentFilename:(char*)curbuf->b_ffname];
1593 #ifdef FEAT_MBYTE
1594     CONVERT_TO_UTF8_FREE(title);
1595 #endif
1597 #endif
1600     void
1601 gui_mch_toggle_tearoffs(int enable)
1607     void
1608 gui_mch_enter_fullscreen(int fuoptions_flags, guicolor_T bg)
1610     [[MMBackend sharedInstance] enterFullscreen:fuoptions_flags background:bg];
1614     void
1615 gui_mch_leave_fullscreen()
1617     [[MMBackend sharedInstance] leaveFullscreen];
1621     void
1622 gui_macvim_update_modified_flag()
1624     [[MMBackend sharedInstance] updateModifiedFlag];
1628  * Add search pattern 'pat' to the OS X find pasteboard.  This allows other
1629  * apps access the last pattern searched for (hitting <D-g> in another app will
1630  * initiate a search for the same pattern).
1631  */
1632     void
1633 gui_macvim_add_to_find_pboard(char_u *pat)
1635     if (!pat) return;
1637 #ifdef FEAT_MBYTE
1638     pat = CONVERT_TO_UTF8(pat);
1639 #endif
1640     NSString *s = [NSString stringWithUTF8String:(char*)pat];
1641 #ifdef FEAT_MBYTE
1642     CONVERT_TO_UTF8_FREE(pat);
1643 #endif
1645     if (!s) return;
1647     NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
1648     [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1649     [pb setString:s forType:NSStringPboardType];
1652     void
1653 gui_macvim_set_antialias(int antialias)
1655     [[MMBackend sharedInstance] setAntialias:antialias];
1659     void
1660 gui_macvim_wait_for_startup()
1662     MMBackend *backend = [MMBackend sharedInstance];
1663     if ([backend waitForAck])
1664         [backend waitForConnectionAcknowledgement];
1667 void gui_macvim_get_window_layout(int *count, int *layout)
1669     if (!(count && layout)) return;
1671     // NOTE: Only set 'layout' if the backend has requested a != 0 layout, else
1672     // any command line arguments (-p/-o) would be ignored.
1673     int window_layout = [[MMBackend sharedInstance] initialWindowLayout];
1674     if (window_layout > 0 && window_layout < 4) {
1675         // The window_layout numbers must match the WIN_* defines in main.c.
1676         *count = 0;
1677         *layout = window_layout;
1678     }
1682 // -- Client/Server ---------------------------------------------------------
1684 #ifdef MAC_CLIENTSERVER
1687 // NOTE: Client/Server is only fully supported with a GUI.  Theoretically it
1688 // would be possible to make the server code work with terminal Vim, but it
1689 // would require that a run-loop is set up and checked.  This should not be
1690 // difficult to implement, simply call gui_mch_update() at opportune moments
1691 // and it will take care of the run-loop.  Another (bigger) problem with
1692 // supporting servers in terminal mode is that the server listing code talks to
1693 // MacVim (the GUI) to figure out which servers are running.
1698  * Register connection with 'name'.  The actual connection is named something
1699  * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1700  */
1701     void
1702 serverRegisterName(char_u *name)
1704 #ifdef FEAT_MBYTE
1705     name = CONVERT_TO_UTF8(name);
1706 #endif
1708     NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1709     [[MMBackend sharedInstance] registerServerWithName:svrName];
1711 #ifdef FEAT_MBYTE
1712     CONVERT_TO_UTF8_FREE(name);
1713 #endif
1718  * Send to an instance of Vim.
1719  * Returns 0 for OK, negative for an error.
1720  */
1721     int
1722 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1723         int *port, int asExpr, int silent)
1725 #ifdef FEAT_MBYTE
1726     name = CONVERT_TO_UTF8(name);
1727     cmd = CONVERT_TO_UTF8(cmd);
1728 #endif
1730     BOOL ok = [[MMBackend sharedInstance]
1731             sendToServer:[NSString stringWithUTF8String:(char*)name]
1732                   string:[NSString stringWithUTF8String:(char*)cmd]
1733                    reply:result
1734                     port:port
1735               expression:asExpr
1736                   silent:silent];
1738 #ifdef FEAT_MBYTE
1739     CONVERT_TO_UTF8_FREE(name);
1740     CONVERT_TO_UTF8_FREE(cmd);
1741 #endif
1743     return ok ? 0 : -1;
1748  * Ask MacVim for the names of all Vim servers.
1749  */
1750     char_u *
1751 serverGetVimNames(void)
1753     char_u *names = NULL;
1754     NSArray *list = [[MMBackend sharedInstance] serverList];
1756     if (list) {
1757         NSString *string = [list componentsJoinedByString:@"\n"];
1758         char_u *s = (char_u*)[string UTF8String];
1759 #ifdef FEAT_MBYTE
1760         s = CONVERT_FROM_UTF8(s);
1761 #endif
1762         names = vim_strsave(s);
1763 #ifdef FEAT_MBYTE
1764         CONVERT_FROM_UTF8_FREE(s);
1765 #endif
1766     }
1768     return names;
1773  * 'str' is a hex int representing the send port of the connection.
1774  */
1775     int
1776 serverStrToPort(char_u *str)
1778     int port = 0;
1780     sscanf((char *)str, "0x%x", &port);
1781     if (!port)
1782         EMSG2(_("E573: Invalid server id used: %s"), str);
1784     return port;
1789  * Check for replies from server with send port 'port'.
1790  * Return TRUE and a non-malloc'ed string if there is.  Else return FALSE.
1791  */
1792     int
1793 serverPeekReply(int port, char_u **str)
1795     NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1796     int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1798     if (str && len > 0) {
1799         *str = (char_u*)[reply UTF8String];
1801 #ifdef FEAT_MBYTE
1802         if (input_conv.vc_type != CONV_NONE) {
1803             char_u *s = string_convert(&input_conv, *str, &len);
1805             if (len > 0) {
1806                 // HACK! Since 's' needs to be freed we cannot simply set
1807                 // '*str = s' or memory will leak.  Instead, create a dummy
1808                 // NSData and return its 'bytes' pointer, then autorelease the
1809                 // NSData.
1810                 NSData *data = [NSData dataWithBytes:s length:len+1];
1811                 *str = (char_u*)[data bytes];
1812             }
1814             vim_free(s);
1815         }
1816 #endif
1817     }
1819     return reply != nil;
1824  * Wait for replies from server with send port 'port'.
1825  * Return 0 and the malloc'ed string when a reply is available.
1826  * Return -1 on error.
1827  */
1828     int
1829 serverReadReply(int port, char_u **str)
1831     NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1832     if (reply && str) {
1833         char_u *s = (char_u*)[reply UTF8String];
1834 #ifdef FEAT_MBYTE
1835         s = CONVERT_FROM_UTF8(s);
1836 #endif
1837         *str = vim_strsave(s);
1838 #ifdef FEAT_MBYTE
1839         CONVERT_FROM_UTF8_FREE(s);
1840 #endif
1841         return 0;
1842     }
1844     return -1;
1849  * Send a reply string (notification) to client with port given by "serverid".
1850  * Return -1 if the window is invalid.
1851  */
1852     int
1853 serverSendReply(char_u *serverid, char_u *reply)
1855     int retval = -1;
1856     int port = serverStrToPort(serverid);
1857     if (port > 0 && reply) {
1858 #ifdef FEAT_MBYTE
1859         reply = CONVERT_TO_UTF8(reply);
1860 #endif
1861         BOOL ok = [[MMBackend sharedInstance]
1862                 sendReply:[NSString stringWithUTF8String:(char*)reply]
1863                    toPort:port];
1864         retval = ok ? 0 : -1;
1865 #ifdef FEAT_MBYTE
1866         CONVERT_TO_UTF8_FREE(reply);
1867 #endif
1868     }
1870     return retval;
1873 #endif // MAC_CLIENTSERVER
1878 // -- ODB Editor Support ----------------------------------------------------
1880 #ifdef FEAT_ODB_EDITOR
1882  * The ODB Editor protocol works like this:
1883  * - An external program (the server) asks MacVim to open a file and associates
1884  *   three things with this file: (1) a server id (a four character code that
1885  *   identifies the server), (2) a path that can be used as window title for
1886  *   the file (optional), (3) an arbitrary token (optional)
1887  * - When a file is saved or closed, MacVim should tell the server about which
1888  *   file was modified and also pass back the token
1890  * All communication between MacVim and the server goes via Apple Events.
1891  */
1893     static OSErr
1894 odb_event(buf_T *buf, const AEEventID action)
1896     if (!(buf->b_odb_server_id && buf->b_ffname))
1897         return noErr;
1899     NSAppleEventDescriptor *targetDesc = [NSAppleEventDescriptor
1900             descriptorWithDescriptorType:typeApplSignature
1901                                    bytes:&buf->b_odb_server_id
1902                                   length:sizeof(OSType)];
1904     // TODO: Convert b_ffname to UTF-8?
1905     NSString *path = [NSString stringWithUTF8String:(char*)buf->b_ffname];
1906     NSData *pathData = [[[NSURL fileURLWithPath:path] absoluteString]
1907             dataUsingEncoding:NSUTF8StringEncoding];
1908     NSAppleEventDescriptor *pathDesc = [NSAppleEventDescriptor
1909             descriptorWithDescriptorType:typeFileURL data:pathData];
1911     NSAppleEventDescriptor *event = [NSAppleEventDescriptor
1912             appleEventWithEventClass:kODBEditorSuite
1913                              eventID:action
1914                     targetDescriptor:targetDesc
1915                             returnID:kAutoGenerateReturnID
1916                        transactionID:kAnyTransactionID];
1918     [event setParamDescriptor:pathDesc forKeyword:keyDirectObject];
1920     if (buf->b_odb_token)
1921         [event setParamDescriptor:buf->b_odb_token forKeyword:keySenderToken];
1923     return AESendMessage([event aeDesc], NULL, kAENoReply | kAENeverInteract,
1924             kAEDefaultTimeout);
1927     OSErr
1928 odb_buffer_close(buf_T *buf)
1930     OSErr err = noErr;
1931     if (buf) {
1932         err = odb_event(buf, kAEClosedFile);
1934         buf->b_odb_server_id = 0;
1936         if (buf->b_odb_token) {
1937             [(NSAppleEventDescriptor *)(buf->b_odb_token) release];
1938             buf->b_odb_token = NULL;
1939         }
1941         if (buf->b_odb_fname) {
1942             vim_free(buf->b_odb_fname);
1943             buf->b_odb_fname = NULL;
1944         }
1945     }
1947     return err;
1950     OSErr
1951 odb_post_buffer_write(buf_T *buf)
1953     return buf ? odb_event(buf, kAEModifiedFile) : noErr;
1956     void
1957 odb_end(void)
1959     buf_T *buf;
1960     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1961         odb_buffer_close(buf);
1964 #endif // FEAT_ODB_EDITOR
1967     char_u *
1968 get_macaction_name(expand_T *xp, int idx)
1970     static char_u *str = NULL;
1971     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1973     if (nil == actionDict || idx < 0 || idx >= [actionDict count])
1974         return NULL;
1976     NSString *string = [[actionDict allKeys] objectAtIndex:idx];
1977     if (!string)
1978         return NULL;
1980     char_u *plainStr = (char_u*)[string UTF8String];
1982 #ifdef FEAT_MBYTE
1983     if (str) {
1984         vim_free(str);
1985         str = NULL;
1986     }
1987     if (input_conv.vc_type != CONV_NONE) {
1988         int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1989         str = string_convert(&input_conv, plainStr, &len);
1990         plainStr = str;
1991     }
1992 #endif
1994     return plainStr;
1998     int
1999 is_valid_macaction(char_u *action)
2001     int isValid = NO;
2002     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
2003     if (actionDict) {
2004 #ifdef FEAT_MBYTE
2005         action = CONVERT_TO_UTF8(action);
2006 #endif
2007         NSString *string = [NSString stringWithUTF8String:(char*)action];
2008         isValid = (nil != [actionDict objectForKey:string]);
2009 #ifdef FEAT_MBYTE
2010         CONVERT_TO_UTF8_FREE(action);
2011 #endif
2012     }
2014     return isValid;
2017 static int specialKeyToNSKey(int key)
2019     if (!IS_SPECIAL(key))
2020         return key;
2022     static struct {
2023         int special;
2024         int nskey;
2025     } sp2ns[] = {
2026         { K_UP, NSUpArrowFunctionKey },
2027         { K_DOWN, NSDownArrowFunctionKey },
2028         { K_LEFT, NSLeftArrowFunctionKey },
2029         { K_RIGHT, NSRightArrowFunctionKey },
2030         { K_F1, NSF1FunctionKey },
2031         { K_F2, NSF2FunctionKey },
2032         { K_F3, NSF3FunctionKey },
2033         { K_F4, NSF4FunctionKey },
2034         { K_F5, NSF5FunctionKey },
2035         { K_F6, NSF6FunctionKey },
2036         { K_F7, NSF7FunctionKey },
2037         { K_F8, NSF8FunctionKey },
2038         { K_F9, NSF9FunctionKey },
2039         { K_F10, NSF10FunctionKey },
2040         { K_F11, NSF11FunctionKey },
2041         { K_F12, NSF12FunctionKey },
2042         { K_F13, NSF13FunctionKey },
2043         { K_F14, NSF14FunctionKey },
2044         { K_F15, NSF15FunctionKey },
2045         { K_F16, NSF16FunctionKey },
2046         { K_F17, NSF17FunctionKey },
2047         { K_F18, NSF18FunctionKey },
2048         { K_F19, NSF19FunctionKey },
2049         { K_F20, NSF20FunctionKey },
2050         { K_F21, NSF21FunctionKey },
2051         { K_F22, NSF22FunctionKey },
2052         { K_F23, NSF23FunctionKey },
2053         { K_F24, NSF24FunctionKey },
2054         { K_F25, NSF25FunctionKey },
2055         { K_F26, NSF26FunctionKey },
2056         { K_F27, NSF27FunctionKey },
2057         { K_F28, NSF28FunctionKey },
2058         { K_F29, NSF29FunctionKey },
2059         { K_F30, NSF30FunctionKey },
2060         { K_F31, NSF31FunctionKey },
2061         { K_F32, NSF32FunctionKey },
2062         { K_F33, NSF33FunctionKey },
2063         { K_F34, NSF34FunctionKey },
2064         { K_F35, NSF35FunctionKey },
2065         { K_DEL, NSBackspaceCharacter },
2066         { K_BS, NSDeleteCharacter },
2067         { K_HOME, NSHomeFunctionKey },
2068         { K_END, NSEndFunctionKey },
2069         { K_PAGEUP, NSPageUpFunctionKey },
2070         { K_PAGEDOWN, NSPageDownFunctionKey }
2071     };
2073     int i;
2074     for (i = 0; i < sizeof(sp2ns)/sizeof(sp2ns[0]); ++i) {
2075         if (sp2ns[i].special == key)
2076             return sp2ns[i].nskey;
2077     }
2079     return 0;
2082 static int vimModMaskToEventModifierFlags(int mods)
2084     int flags = 0;
2086     if (mods & MOD_MASK_SHIFT)
2087         flags |= NSShiftKeyMask;
2088     if (mods & MOD_MASK_CTRL)
2089         flags |= NSControlKeyMask;
2090     if (mods & MOD_MASK_ALT)
2091         flags |= NSAlternateKeyMask;
2092     if (mods & MOD_MASK_CMD)
2093         flags |= NSCommandKeyMask;
2095     return flags;