Don't update 'fuoptions' before GUI has started
[MacVim.git] / src / MacVim / gui_macvim.m
blob062db5e3e0d34861c59e8f25402fcfa60237664b
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 // NOTE: The default font is bundled with the application.
24 static NSString *MMDefaultFontName = @"DejaVu Sans Mono";
25 static int MMDefaultFontSize       = 12;
26 static int MMMinFontSize           = 6;
27 static int MMMaxFontSize           = 100;
28 static BOOL gui_mch_init_has_finished = NO;
31 static GuiFont gui_macvim_font_with_name(char_u *name);
32 static int specialKeyToNSKey(int key);
33 static int vimModMaskToEventModifierFlags(int mods);
35 NSArray *descriptor_for_menu(vimmenu_T *menu);
36 vimmenu_T *menu_for_descriptor(NSArray *desc);
40 // -- Initialization --------------------------------------------------------
43  * Parse the GUI related command-line arguments.  Any arguments used are
44  * deleted from argv, and *argc is decremented accordingly.  This is called
45  * when vim is started, whether or not the GUI has been started.
46  */
47     void
48 gui_mch_prepare(int *argc, char **argv)
50     //NSLog(@"gui_mch_prepare(argc=%d)", *argc);
52     // Set environment variables $VIM and $VIMRUNTIME
53     // NOTE!  If vim_getenv is called with one of these as parameters before
54     // they have been set here, they will most likely end up with the wrong
55     // values!
56     //
57     // TODO:
58     // - ensure this is called first to avoid above problem
59     // - encoding
61     NSString *path = [[[NSBundle mainBundle] resourcePath]
62         stringByAppendingPathComponent:@"vim"];
63     vim_setenv((char_u*)"VIM", (char_u*)[path UTF8String]);
65     path = [path stringByAppendingPathComponent:@"runtime"];
66     vim_setenv((char_u*)"VIMRUNTIME", (char_u*)[path UTF8String]);
68     int i;
69     for (i = 0; i < *argc; ++i) {
70         if (strncmp(argv[i], "--mmwaitforack", 14) == 0) {
71             [[MMBackend sharedInstance] setWaitForAck:YES];
72             --*argc;
73             if (*argc > i)
74                 mch_memmove(&argv[i], &argv[i+1], (*argc-i) * sizeof(char*));
75             break;
76         }
77     }
82  * Check if the GUI can be started.  Called before gvimrc is sourced.
83  * Return OK or FAIL.
84  */
85     int
86 gui_mch_init_check(void)
88     //NSLog(@"gui_mch_init_check()");
89     return OK;
94  * Initialise the GUI.  Create all the windows, set up all the call-backs etc.
95  * Returns OK for success, FAIL when the GUI can't be started.
96  */
97     int
98 gui_mch_init(void)
100     //NSLog(@"gui_mch_init()");
102     // NOTE! Because OS X has to exec after fork we effectively end up doing
103     // the initialization twice (because this function is called before the
104     // fork).  To avoid all this extra work we check if Vim is about to fork,
105     // and if so do nothing for now.
106     //
107     // TODO: Is this check 100% foolproof?
108     if (gui.dofork && (vim_strchr(p_go, GO_FORG) == NULL))
109         return OK;
111     if (![[MMBackend sharedInstance] checkin]) {
112         // TODO: Kill the process if there is no terminal to fall back on,
113         // otherwise the process will run outputting to the console.
114         return FAIL;
115     }
117     // Force 'termencoding' to utf-8 (changes to 'tenc' are disallowed in
118     // 'option.c', so that ':set termencoding=...' is impossible).
119     set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
121     // Set values so that pixels and characters are in one-to-one
122     // correspondence (assuming all characters have the same dimensions).
123     gui.scrollbar_width = gui.scrollbar_height = 0;
125     gui.char_height = 1;
126     gui.char_width = 1;
127     gui.char_ascent = 0;
129     gui_mch_def_colors();
131     [[MMBackend sharedInstance]
132         setDefaultColorsBackground:gui.back_pixel foreground:gui.norm_pixel];
133     [[MMBackend sharedInstance] setBackgroundColor:gui.back_pixel];
134     [[MMBackend sharedInstance] setForegroundColor:gui.norm_pixel];
136     // NOTE: If this call is left out the cursor is opaque.
137     highlight_gui_started();
139     // Ensure 'linespace' option is passed along to MacVim in case it was set
140     // in [g]vimrc.
141     gui_mch_adjust_charheight();
143     gui_mch_init_has_finished = YES;
145     return OK;
150     void
151 gui_mch_exit(int rc)
153     //NSLog(@"gui_mch_exit(rc=%d)", rc);
155     [[MMBackend sharedInstance] exit];
160  * Open the GUI window which was created by a call to gui_mch_init().
161  */
162     int
163 gui_mch_open(void)
165     //NSLog(@"gui_mch_open()");
167     // This check is to avoid doing extra work when we're about to fork.
168     if (!gui_mch_init_has_finished)
169         return OK;
171     return [[MMBackend sharedInstance] openGUIWindow];
175 // -- Updating --------------------------------------------------------------
179  * Catch up with any queued X events.  This may put keyboard input into the
180  * input buffer, call resize call-backs, trigger timers etc.  If there is
181  * nothing in the X event queue (& no timers pending), then we return
182  * immediately.
183  */
184     void
185 gui_mch_update(void)
187     // This function is called extremely often.  It is tempting to do nothing
188     // here to avoid reduced frame-rates but then it would not be possible to
189     // interrupt Vim by presssing Ctrl-C during lengthy operations (e.g. after
190     // entering "10gs" it would not be possible to bring Vim out of the 10 s
191     // sleep prematurely).  As a compromise we check for Ctrl-C only once per
192     // second.  Note that Cmd-. sends SIGINT so it has higher success rate at
193     // interrupting Vim.
194     static CFAbsoluteTime lastTime = 0;
196     CFAbsoluteTime nowTime = CFAbsoluteTimeGetCurrent();
197     if (nowTime - lastTime > 1.0) {
198         [[MMBackend sharedInstance] update];
199         lastTime = nowTime;
200     }
204 /* Flush any output to the screen */
205     void
206 gui_mch_flush(void)
208     // This function is called way too often to be useful as a hint for
209     // flushing.  If we were to flush every time it was called the screen would
210     // flicker.
214     void
215 gui_macvim_flush(void)
217     // This function counts how many times it is called and only flushes the
218     // draw queue if called sufficiently often.  The first few times it is
219     // called it will flush often, but the more it is called the less likely is
220     // it that anything will be flushed.  (The counter resets itself if the
221     // function isn't called for a second.)
222     //
223     // NOTE: Should only be used in loops where it is impossible to know how
224     // often Vim needs to flush.  It was written to handle output from external
225     // commands (see mch_call_shell() in os_unix.c).
227     static CFAbsoluteTime lastTime = 0;
228     static int delay = 1;
229     static int counter = 0;
230     static int scrolls = 0;
232     CFAbsoluteTime nowTime = CFAbsoluteTimeGetCurrent();
233     CFAbsoluteTime delta = nowTime - lastTime;
234     if (delta > 1.0)
235         delay = 1;
237     // We assume that each call corresponds roughly to one line of output.
238     // When one page has scrolled by we increase the delay before the next
239     // flush.
240     if (++scrolls > gui.num_rows) {
241         delay <<= 1;
242         if (delay > 2048)
243             delay = 2048;
244         scrolls = 0;
245     }
247     if (++counter > delay) {
248         gui_macvim_force_flush();
249         counter = 0;
250     }
252     lastTime = nowTime;
256 /* Force flush output to MacVim.  Do not call this method unless absolutely
257  * necessary. */
258     void
259 gui_macvim_force_flush(void)
261     [[MMBackend sharedInstance] flushQueue:YES];
266  * GUI input routine called by gui_wait_for_chars().  Waits for a character
267  * from the keyboard.
268  *  wtime == -1     Wait forever.
269  *  wtime == 0      This should never happen.
270  *  wtime > 0       Wait wtime milliseconds for a character.
271  * Returns OK if a character was found to be available within the given time,
272  * or FAIL otherwise.
273  */
274     int
275 gui_mch_wait_for_chars(int wtime)
277     // NOTE! In all likelihood Vim will take a nap when waitForInput: is
278     // called, so force a flush of the command queue here.
279     [[MMBackend sharedInstance] flushQueue:YES];
281     return [[MMBackend sharedInstance] waitForInput:wtime];
285 // -- Drawing ---------------------------------------------------------------
289  * Clear the whole text window.
290  */
291     void
292 gui_mch_clear_all(void)
294     [[MMBackend sharedInstance] clearAll];
299  * Clear a rectangular region of the screen from text pos (row1, col1) to
300  * (row2, col2) inclusive.
301  */
302     void
303 gui_mch_clear_block(int row1, int col1, int row2, int col2)
305     [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
306                                                     toRow:row2 column:col2];
311  * Delete the given number of lines from the given row, scrolling up any
312  * text further down within the scroll region.
313  */
314     void
315 gui_mch_delete_lines(int row, int num_lines)
317     [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
318             scrollBottom:gui.scroll_region_bot
319                     left:gui.scroll_region_left
320                    right:gui.scroll_region_right];
324     void
325 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
327 #ifdef FEAT_MBYTE
328     char_u *conv_str = NULL;
329     if (output_conv.vc_type != CONV_NONE) {
330         conv_str = string_convert(&output_conv, s, &len);
331         if (conv_str)
332             s = conv_str;
333     }
334 #endif
336     [[MMBackend sharedInstance] drawString:(char*)s length:len row:row
337                                     column:col cells:len flags:flags];
339 #ifdef FEAT_MBYTE
340     if (conv_str)
341         vim_free(conv_str);
342 #endif
346     int
347 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
349     int c, cn, cl, i;
350     int start = 0;
351     int endcol = col;
352     int startcol = col;
353     BOOL wide = NO;
354     MMBackend *backend = [MMBackend sharedInstance];
355 #ifdef FEAT_MBYTE
356     char_u *conv_str = NULL;
358     if (output_conv.vc_type != CONV_NONE) {
359         conv_str = string_convert(&output_conv, s, &len);
360         if (conv_str)
361             s = conv_str;
362     }
363 #endif
365     // Loop over each character and output text when it changes from normal to
366     // wide and vice versa.
367     for (i = 0; i < len; i += cl) {
368         c = utf_ptr2char(s + i);
369         cn = utf_char2cells(c);
370         cl = utf_ptr2len(s + i);
371         if (0 == cl)
372             len = i;    // len must be wrong (shouldn't happen)
374         if (!utf_iscomposing(c)) {
375             if ((cn > 1 && !wide) || (cn <= 1 && wide)) {
376                 // Changed from normal to wide or vice versa.
377                 [backend drawString:(char*)(s+start) length:i-start
378                                    row:row column:startcol
379                                  cells:endcol-startcol
380                                  flags:(wide ? flags|DRAW_WIDE : flags)];
382                 start = i;
383                 startcol = endcol;
384             }
386             wide = cn > 1;
387             endcol += cn;
388         }
389     }
391     // Output remaining characters.
392     [backend drawString:(char*)(s+start) length:len-start
393                     row:row column:startcol cells:endcol-startcol
394                   flags:(wide ? flags|DRAW_WIDE : flags)];
396 #ifdef FEAT_MBYTE
397     if (conv_str)
398         vim_free(conv_str);
399 #endif
401     return endcol - col;
406  * Insert the given number of lines before the given row, scrolling down any
407  * following text within the scroll region.
408  */
409     void
410 gui_mch_insert_lines(int row, int num_lines)
412     [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
413             scrollBottom:gui.scroll_region_bot
414                     left:gui.scroll_region_left
415                    right:gui.scroll_region_right];
420  * Set the current text foreground color.
421  */
422     void
423 gui_mch_set_fg_color(guicolor_T color)
425     [[MMBackend sharedInstance] setForegroundColor:color];
430  * Set the current text background color.
431  */
432     void
433 gui_mch_set_bg_color(guicolor_T color)
435     [[MMBackend sharedInstance] setBackgroundColor:color];
440  * Set the current text special color (used for underlines).
441  */
442     void
443 gui_mch_set_sp_color(guicolor_T color)
445     [[MMBackend sharedInstance] setSpecialColor:color];
450  * Set default colors.
451  */
452     void
453 gui_mch_def_colors()
455     MMBackend *backend = [MMBackend sharedInstance];
457     // The default colors are taken from system values
458     gui.def_norm_pixel = gui.norm_pixel = 
459         [backend lookupColorWithKey:@"MacTextColor"];
460     gui.def_back_pixel = gui.back_pixel = 
461         [backend lookupColorWithKey:@"MacTextBackgroundColor"];
466  * Called when the foreground or background color has been changed.
467  */
468     void
469 gui_mch_new_colors(void)
471     gui.def_back_pixel = gui.back_pixel;
472     gui.def_norm_pixel = gui.norm_pixel;
474     //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
475     //        gui.def_norm_pixel);
477     [[MMBackend sharedInstance]
478         setDefaultColorsBackground:gui.def_back_pixel
479                         foreground:gui.def_norm_pixel];
483  * Invert a rectangle from row r, column c, for nr rows and nc columns.
484  */
485     void
486 gui_mch_invert_rectangle(int r, int c, int nr, int nc, int invert)
488     [[MMBackend sharedInstance] drawInvertedRectAtRow:r column:c numRows:nr
489             numColumns:nc invert:invert];
494 // -- Tabline ---------------------------------------------------------------
498  * Set the current tab to "nr".  First tab is 1.
499  */
500     void
501 gui_mch_set_curtab(int nr)
503     [[MMBackend sharedInstance] selectTab:nr];
508  * Return TRUE when tabline is displayed.
509  */
510     int
511 gui_mch_showing_tabline(void)
513     return [[MMBackend sharedInstance] tabBarVisible];
517  * Update the labels of the tabline.
518  */
519     void
520 gui_mch_update_tabline(void)
522     [[MMBackend sharedInstance] updateTabBar];
526  * Show or hide the tabline.
527  */
528     void
529 gui_mch_show_tabline(int showit)
531     [[MMBackend sharedInstance] showTabBar:showit];
535 // -- Clipboard -------------------------------------------------------------
538     void
539 clip_mch_lose_selection(VimClipboard *cbd)
544     int
545 clip_mch_own_selection(VimClipboard *cbd)
547     return 0;
551     void
552 clip_mch_request_selection(VimClipboard *cbd)
554     NSPasteboard *pb = [NSPasteboard generalPasteboard];
555     NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
556             NSStringPboardType, nil];
557     NSString *bestType = [pb availableTypeFromArray:supportedTypes];
558     if (!bestType) return;
560     int motion_type = MCHAR;
561     NSString *string = nil;
563     if ([bestType isEqual:VimPBoardType]) {
564         // This type should consist of an array with two objects:
565         //   1. motion type (NSNumber)
566         //   2. text (NSString)
567         // If this is not the case we fall back on using NSStringPboardType.
568         id plist = [pb propertyListForType:VimPBoardType];
569         if ([plist isKindOfClass:[NSArray class]] && [plist count] == 2) {
570             id obj = [plist objectAtIndex:1];
571             if ([obj isKindOfClass:[NSString class]]) {
572                 motion_type = [[plist objectAtIndex:0] intValue];
573                 string = obj;
574             }
575         }
576     }
578     if (!string) {
579         // Use NSStringPboardType.  The motion type is set to line-wise if the
580         // string contains at least one EOL character, otherwise it is set to
581         // character-wise (block-wise is never used).
582         NSMutableString *mstring =
583                 [[pb stringForType:NSStringPboardType] mutableCopy];
584         if (!mstring) return;
586         // Replace unrecognized end-of-line sequences with \x0a (line feed).
587         NSRange range = { 0, [mstring length] };
588         unsigned n = [mstring replaceOccurrencesOfString:@"\x0d\x0a"
589                                              withString:@"\x0a" options:0
590                                                   range:range];
591         if (0 == n) {
592             n = [mstring replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
593                                            options:0 range:range];
594         }
595         
596         // Scan for newline character to decide whether the string should be
597         // pasted line-wise or character-wise.
598         motion_type = MCHAR;
599         if (0 < n || NSNotFound != [mstring rangeOfString:@"\n"].location)
600             motion_type = MLINE;
602         string = mstring;
603     }
605     if (!(MCHAR == motion_type || MLINE == motion_type || MBLOCK == motion_type
606             || MAUTO == motion_type))
607         motion_type = MCHAR;
609     char_u *str = (char_u*)[string UTF8String];
610     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
612 #ifdef FEAT_MBYTE
613     if (input_conv.vc_type != CONV_NONE)
614         str = string_convert(&input_conv, str, &len);
615 #endif
617     if (str)
618         clip_yank_selection(motion_type, str, len, cbd);
620 #ifdef FEAT_MBYTE
621     if (input_conv.vc_type != CONV_NONE)
622         vim_free(str);
623 #endif
628  * Send the current selection to the clipboard.
629  */
630     void
631 clip_mch_set_selection(VimClipboard *cbd)
633     // If the '*' register isn't already filled in, fill it in now.
634     cbd->owned = TRUE;
635     clip_get_selection(cbd);
636     cbd->owned = FALSE;
637     
638     // Get the text to put on the pasteboard.
639     long_u llen = 0; char_u *str = 0;
640     int motion_type = clip_convert_selection(&str, &llen, cbd);
641     if (motion_type < 0)
642         return;
644     // TODO: Avoid overflow.
645     int len = (int)llen;
646 #ifdef FEAT_MBYTE
647     if (output_conv.vc_type != CONV_NONE) {
648         char_u *conv_str = string_convert(&output_conv, str, &len);
649         if (conv_str) {
650             vim_free(str);
651             str = conv_str;
652         }
653     }
654 #endif
656     if (len > 0) {
657         NSString *string = [[NSString alloc]
658             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
660         // See clip_mch_request_selection() for info on pasteboard types.
661         NSPasteboard *pb = [NSPasteboard generalPasteboard];
662         NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
663                 NSStringPboardType, nil];
664         [pb declareTypes:supportedTypes owner:nil];
666         NSNumber *motion = [NSNumber numberWithInt:motion_type];
667         NSArray *plist = [NSArray arrayWithObjects:motion, string, nil];
668         [pb setPropertyList:plist forType:VimPBoardType];
670         [pb setString:string forType:NSStringPboardType];
671         
672         [string release];
673     }
675     vim_free(str);
679 // -- Menu ------------------------------------------------------------------
683  * A menu descriptor represents the "address" of a menu as an array of strings.
684  * E.g. the menu "File->Close" has descriptor { "File", "Close" }.
685  */
686     NSArray *
687 descriptor_for_menu(vimmenu_T *menu)
689     if (!menu) return nil;
691     NSMutableArray *desc = [NSMutableArray array];
692     while (menu) {
693         NSString *name = [NSString stringWithVimString:menu->dname];
694         [desc insertObject:name atIndex:0];
695         menu = menu->parent;
696     }
698     return desc;
701     vimmenu_T *
702 menu_for_descriptor(NSArray *desc)
704     if (!(desc && [desc count] > 0)) return NULL;
706     vimmenu_T *menu = root_menu;
707     int i, count = [desc count];
709     for (i = 0; i < count; ++i) {
710         NSString *component = [desc objectAtIndex:i];
711         while (menu) {
712             NSString *name = [NSString stringWithVimString:menu->dname];
713             if ([component isEqual:name]) {
714                 if (i+1 == count)
715                     return menu;    // Matched all components, so return menu
716                 menu = menu->children;
717                 break;
718             }
719             menu = menu->next;
720         }
721     }
723     return NULL;
727  * Add a submenu to the menu bar, toolbar, or a popup menu.
728  */
729     void
730 gui_mch_add_menu(vimmenu_T *menu, int idx)
732     NSArray *desc = descriptor_for_menu(menu);
733     [[MMBackend sharedInstance] queueMessage:AddMenuMsgID properties:
734         [NSDictionary dictionaryWithObjectsAndKeys:
735             desc, @"descriptor",
736             [NSNumber numberWithInt:idx], @"index",
737             nil]];
741 // Taken from gui_gtk.c (slightly modified)
742     static int
743 lookup_menu_iconfile(char_u *iconfile, char_u *dest)
745     expand_env(iconfile, dest, MAXPATHL);
747     if (mch_isFullName(dest))
748         return vim_fexists(dest);
750     static const char   suffixes[][4] = {"png", "bmp"};
751     char_u              buf[MAXPATHL];
752     unsigned int        i;
754     for (i = 0; i < sizeof(suffixes)/sizeof(suffixes[0]); ++i)
755         if (gui_find_bitmap(dest, buf, (char *)suffixes[i]) == OK) {
756             STRCPY(dest, buf);
757             return TRUE;
758         }
760     return FALSE;
765  * Add a menu item to a menu
766  */
767     void
768 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
770     char_u *tip = menu->strings[MENU_INDEX_TIP]
771             ? menu->strings[MENU_INDEX_TIP] : menu->actext;
772     NSArray *desc = descriptor_for_menu(menu);
773     NSString *keyEquivalent = menu->mac_key
774         ? [NSString stringWithFormat:@"%C", specialKeyToNSKey(menu->mac_key)]
775         : [NSString string];
776     int modifierMask = vimModMaskToEventModifierFlags(menu->mac_mods);
777     char_u *icon = NULL;
779     if (menu_is_toolbar(menu->parent->name)) {
780         char_u fname[MAXPATHL];
782         // Try to use the icon=.. argument
783         if (menu->iconfile && lookup_menu_iconfile(menu->iconfile, fname))
784             icon = fname;
786         // If not found and not builtin specified try using the menu name
787         if (!icon && !menu->icon_builtin
788                                     && lookup_menu_iconfile(menu->name, fname))
789             icon = fname;
791         // Last resort, use display name (usually signals a builtin icon)
792         if (!icon)
793             icon = menu->dname;
794     }
796     [[MMBackend sharedInstance] queueMessage:AddMenuItemMsgID properties:
797         [NSDictionary dictionaryWithObjectsAndKeys:
798             desc, @"descriptor",
799             [NSNumber numberWithInt:idx], @"index",
800             [NSString stringWithVimString:tip], @"tip",
801             [NSString stringWithVimString:icon], @"icon",
802             keyEquivalent, @"keyEquivalent",
803             [NSNumber numberWithInt:modifierMask], @"modifierMask",
804             [NSString stringWithVimString:menu->mac_action], @"action",
805             [NSNumber numberWithBool:menu->mac_alternate], @"isAlternate",
806             nil]];
811  * Destroy the machine specific menu widget.
812  */
813     void
814 gui_mch_destroy_menu(vimmenu_T *menu)
816     NSArray *desc = descriptor_for_menu(menu);
817     [[MMBackend sharedInstance] queueMessage:RemoveMenuItemMsgID properties:
818         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
823  * Make a menu either grey or not grey.
824  */
825     void
826 gui_mch_menu_grey(vimmenu_T *menu, int grey)
828     /* Only update menu if the 'grey' state has changed to avoid having to pass
829      * lots of unnecessary data to MacVim.  (Skipping this test makes MacVim
830      * pause noticably on mode changes. */
831     NSArray *desc = descriptor_for_menu(menu);
832     if (menu->was_grey == grey)
833         return;
835     menu->was_grey = grey;
837     [[MMBackend sharedInstance] queueMessage:EnableMenuItemMsgID properties:
838         [NSDictionary dictionaryWithObjectsAndKeys:
839             desc, @"descriptor",
840             [NSNumber numberWithInt:!grey], @"enable",
841             nil]];
846  * Make menu item hidden or not hidden
847  */
848     void
849 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
851     // HACK! There is no (obvious) way to hide a menu item, so simply
852     // enable/disable it instead.
853     gui_mch_menu_grey(menu, hidden);
858  * This is called when user right clicks.
859  */
860     void
861 gui_mch_show_popupmenu(vimmenu_T *menu)
863     NSArray *desc = descriptor_for_menu(menu);
864     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:
865         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
870  * This is called when a :popup command is executed.
871  */
872     void
873 gui_make_popup(char_u *path_name, int mouse_pos)
875     vimmenu_T *menu = gui_find_menu(path_name);
876     if (!(menu && menu->children)) return;
878     NSArray *desc = descriptor_for_menu(menu);
879     NSDictionary *p = (mouse_pos || NULL == curwin)
880         ? [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]
881         : [NSDictionary dictionaryWithObjectsAndKeys:
882             desc, @"descriptor",
883             [NSNumber numberWithInt:curwin->w_wrow], @"row",
884             [NSNumber numberWithInt:curwin->w_wcol], @"column",
885             nil];
887     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:p];
892  * This is called after setting all the menus to grey/hidden or not.
893  */
894     void
895 gui_mch_draw_menubar(void)
897     // The (main) menu draws itself in Mac OS X.
901     void
902 gui_mch_enable_menu(int flag)
904     // The (main) menu is always enabled in Mac OS X.
908 #if 0
909     void
910 gui_mch_set_menu_pos(int x, int y, int w, int h)
912     // The (main) menu cannot be moved in Mac OS X.
914 #endif
917     void
918 gui_mch_show_toolbar(int showit)
920     int flags = 0;
921     if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
922     if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
923     if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
925     [[MMBackend sharedInstance] showToolbar:showit flags:flags];
931 // -- Fonts -----------------------------------------------------------------
935  * If a font is not going to be used, free its structure.
936  */
937     void
938 gui_mch_free_font(font)
939     GuiFont     font;
941     if (font != NOFONT) {
942         //NSLog(@"gui_mch_free_font(font=0x%x)", font);
943         [(id)font release];
944     }
948     GuiFont
949 gui_mch_retain_font(GuiFont font)
951     return (GuiFont)[(id)font retain];
956  * Get a font structure for highlighting.
957  */
958     GuiFont
959 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
961     //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
962     //        giveErrorIfMissing);
964     GuiFont font = gui_macvim_font_with_name(name);
965     if (font != NOFONT)
966         return font;
968     if (giveErrorIfMissing)
969         EMSG2(_(e_font), name);
971     return NOFONT;
975 #if defined(FEAT_EVAL) || defined(PROTO)
977  * Return the name of font "font" in allocated memory.
978  * TODO: use 'font' instead of 'name'?
979  */
980     char_u *
981 gui_mch_get_fontname(GuiFont font, char_u *name)
983     return name ? vim_strsave(name) : NULL;
985 #endif
989  * Initialise vim to use the font with the given name.  Return FAIL if the font
990  * could not be loaded, OK otherwise.
991  */
992     int
993 gui_mch_init_font(char_u *font_name, int fontset)
995     //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
997     if (font_name && STRCMP(font_name, "*") == 0) {
998         // :set gfn=* shows the font panel.
999         do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
1000         return FAIL;
1001     }
1003     GuiFont font = gui_macvim_font_with_name(font_name);
1004     if (font == NOFONT)
1005         return FAIL;
1007     gui_mch_free_font(gui.norm_font);
1008     gui.norm_font = font;
1010     // NOTE: MacVim keeps separate track of the normal and wide fonts.
1011     // Unless the user changes 'guifontwide' manually, they are based on
1012     // the same (normal) font.  Also note that each time the normal font is
1013     // set, the advancement may change so the wide font needs to be updated
1014     // as well (so that it is always twice the width of the normal font).
1015     [[MMBackend sharedInstance] setFont:font wide:NO];
1016     [[MMBackend sharedInstance] setFont:(NOFONT != gui.wide_font ? gui.wide_font
1017                                                                  : font)
1018                                    wide:YES];
1020     return OK;
1025  * Set the current text font.
1026  */
1027     void
1028 gui_mch_set_font(GuiFont font)
1030     // Font selection is done inside MacVim...nothing here to do.
1035  * Return GuiFont in allocated memory.  The caller must free it using
1036  * gui_mch_free_font().
1037  */
1038     GuiFont
1039 gui_macvim_font_with_name(char_u *name)
1041     if (!name)
1042         return (GuiFont)[[NSString alloc] initWithFormat:@"%@:%d",
1043                                         MMDefaultFontName, MMDefaultFontSize];
1045     NSString *fontName = [NSString stringWithVimString:name];
1046     int size = MMDefaultFontSize;
1047     BOOL parseFailed = NO;
1049     NSArray *components = [fontName componentsSeparatedByString:@":"];
1050     if ([components count] == 2) {
1051         NSString *sizeString = [components lastObject];
1052         if ([sizeString length] > 0
1053                 && [sizeString characterAtIndex:0] == 'h') {
1054             sizeString = [sizeString substringFromIndex:1];
1055             if ([sizeString length] > 0) {
1056                 size = (int)round([sizeString floatValue]);
1057                 fontName = [components objectAtIndex:0];
1058             }
1059         } else {
1060             parseFailed = YES;
1061         }
1062     } else if ([components count] > 2) {
1063         parseFailed = YES;
1064     }
1066     if (!parseFailed) {
1067         // Replace underscores with spaces.
1068         fontName = [[fontName componentsSeparatedByString:@"_"]
1069                                  componentsJoinedByString:@" "];
1070     }
1072     if (!parseFailed && [fontName length] > 0) {
1073         if (size < MMMinFontSize) size = MMMinFontSize;
1074         if (size > MMMaxFontSize) size = MMMaxFontSize;
1076         // If the default font is requested we don't check if NSFont can load
1077         // it since the font most likely isn't loaded anyway (it may only be
1078         // available to the MacVim binary).  If it is not the default font we
1079         // ask NSFont if it can load it.
1080         if ([fontName isEqualToString:MMDefaultFontName]
1081                 || [NSFont fontWithName:fontName size:size])
1082             return [[NSString alloc] initWithFormat:@"%@:%d", fontName, size];
1083     }
1085     return NOFONT;
1088 // -- Scrollbars ------------------------------------------------------------
1091     void
1092 gui_mch_create_scrollbar(
1093         scrollbar_T *sb,
1094         int orient)     /* SBAR_VERT or SBAR_HORIZ */
1096     [[MMBackend sharedInstance] 
1097             createScrollbarWithIdentifier:sb->ident type:sb->type];
1101     void
1102 gui_mch_destroy_scrollbar(scrollbar_T *sb)
1104     [[MMBackend sharedInstance] 
1105             destroyScrollbarWithIdentifier:sb->ident];
1109     void
1110 gui_mch_enable_scrollbar(
1111         scrollbar_T     *sb,
1112         int             flag)
1114     [[MMBackend sharedInstance] 
1115             showScrollbarWithIdentifier:sb->ident state:flag];
1119     void
1120 gui_mch_set_scrollbar_pos(
1121         scrollbar_T *sb,
1122         int x,
1123         int y,
1124         int w,
1125         int h)
1127     int pos = y;
1128     int len = h;
1129     if (SBAR_BOTTOM == sb->type) {
1130         pos = x;
1131         len = w; 
1132     }
1134     [[MMBackend sharedInstance] 
1135             setScrollbarPosition:pos length:len identifier:sb->ident];
1139     void
1140 gui_mch_set_scrollbar_thumb(
1141         scrollbar_T *sb,
1142         long val,
1143         long size,
1144         long max)
1146     [[MMBackend sharedInstance] 
1147             setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
1151 // -- Cursor ----------------------------------------------------------------
1155  * Draw a cursor without focus.
1156  */
1157     void
1158 gui_mch_draw_hollow_cursor(guicolor_T color)
1160     return [[MMBackend sharedInstance]
1161         drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
1162                fraction:100 color:color];
1167  * Draw part of a cursor, only w pixels wide, and h pixels high.
1168  */
1169     void
1170 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
1172     // HACK!  'w' and 'h' are always 1 since we do not tell Vim about the exact
1173     // font dimensions.  Thus these parameters are useless.  Instead we look at
1174     // the shape_table to determine the shape and size of the cursor (just like
1175     // gui_update_cursor() does).
1177 #ifdef FEAT_RIGHTLEFT
1178     // If 'rl' is set the insert mode cursor must be drawn on the right-hand
1179     // side of a text cell.
1180     int rl = curwin ? curwin->w_p_rl : FALSE;
1181 #else
1182     int rl = FALSE;
1183 #endif
1184     int idx = get_shape_idx(FALSE);
1185     int shape = MMInsertionPointBlock;
1186     switch (shape_table[idx].shape) {
1187         case SHAPE_HOR:
1188             shape = MMInsertionPointHorizontal;
1189             break;
1190         case SHAPE_VER:
1191             shape = rl ? MMInsertionPointVerticalRight
1192                        : MMInsertionPointVertical;
1193             break;
1194     }
1196     return [[MMBackend sharedInstance]
1197         drawCursorAtRow:gui.row column:gui.col shape:shape
1198                fraction:shape_table[idx].percentage color:color];
1203  * Cursor blink functions.
1205  * This is a simple state machine:
1206  * BLINK_NONE   not blinking at all
1207  * BLINK_OFF    blinking, cursor is not shown
1208  * BLINK_ON blinking, cursor is shown
1209  */
1210     void
1211 gui_mch_set_blinking(long wait, long on, long off)
1213     [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1218  * Start the cursor blinking.  If it was already blinking, this restarts the
1219  * waiting time and shows the cursor.
1220  */
1221     void
1222 gui_mch_start_blink(void)
1224     [[MMBackend sharedInstance] startBlink];
1229  * Stop the cursor blinking.  Show the cursor if it wasn't shown.
1230  */
1231     void
1232 gui_mch_stop_blink(void)
1234     [[MMBackend sharedInstance] stopBlink];
1238 // -- Mouse -----------------------------------------------------------------
1242  * Get current mouse coordinates in text window.
1243  */
1244     void
1245 gui_mch_getmouse(int *x, int *y)
1247     //NSLog(@"gui_mch_getmouse()");
1251     void
1252 gui_mch_setmouse(int x, int y)
1254     //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1258     void
1259 mch_set_mouse_shape(int shape)
1261     [[MMBackend sharedInstance] setMouseShape:shape];
1267 // -- Input Method ----------------------------------------------------------
1269 #if defined(USE_IM_CONTROL)
1271     void
1272 im_set_position(int row, int col)
1274     // The pre-edit area is a popup window which is displayed by MMTextView.
1275     [[MMBackend sharedInstance] setPreEditRow:row column:col];
1279     void
1280 im_set_active(int active)
1282     // Set roman or the system script if 'active' is TRUE or FALSE,
1283     // respectively.
1284     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1286     if (!p_imdisable && smRoman != systemScript)
1287         KeyScript(active ? smKeySysScript : smKeyRoman);
1291     int
1292 im_get_status(void)
1294     // IM is active whenever the current script is the system script and the
1295     // system script isn't roman.  (Hence IM can only be active when using
1296     // non-roman scripts.)
1297     SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
1298     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1300     return currentScript != smRoman && currentScript == systemScript;
1303 #endif // defined(USE_IM_CONTROL)
1308 // -- Find & Replace dialog -------------------------------------------------
1310 #ifdef FIND_REPLACE_DIALOG
1312     static void
1313 macvim_find_and_replace(char_u *arg, BOOL replace)
1315     // TODO: Specialized dialog for find without replace?
1316     int wholeWord = FALSE;
1317     int matchCase = !p_ic;
1318     char_u *text  = get_find_dialog_text(arg, &wholeWord, &matchCase);
1320     int flags = 0;
1321     if (wholeWord) flags |= FRD_WHOLE_WORD;
1322     if (matchCase) flags |= FRD_MATCH_CASE;
1324     NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
1325             [NSString stringWithVimString:text],    @"text",
1326             [NSNumber numberWithInt:flags],         @"flags",
1327             nil];
1329     [[MMBackend sharedInstance] queueMessage:ShowFindReplaceDialogMsgID
1330                                   properties:args];
1333     void
1334 gui_mch_find_dialog(exarg_T *eap)
1336     macvim_find_and_replace(eap->arg, NO);
1339     void
1340 gui_mch_replace_dialog(exarg_T *eap)
1342     macvim_find_and_replace(eap->arg, YES);
1345 #endif // FIND_REPLACE_DIALOG
1350 // -- Unsorted --------------------------------------------------------------
1353     void
1354 ex_macaction(eap)
1355     exarg_T     *eap;
1357     if (!gui.in_use) {
1358         EMSG(_("E???: Command only available in GUI mode"));
1359         return;
1360     }
1362     char_u *arg = eap->arg;
1363 #ifdef FEAT_MBYTE
1364     arg = CONVERT_TO_UTF8(arg);
1365 #endif
1367     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1368     NSString *name = [NSString stringWithUTF8String:(char*)arg];
1369     if (actionDict && [actionDict objectForKey:name] != nil) {
1370         [[MMBackend sharedInstance] executeActionWithName:name];
1371     } else {
1372         EMSG2(_("E???: Invalid action: %s"), eap->arg);
1373     }
1375 #ifdef FEAT_MBYTE
1376     arg = CONVERT_TO_UTF8(arg);
1377 #endif
1382  * Adjust gui.char_height (after 'linespace' was changed).
1383  */
1384     int
1385 gui_mch_adjust_charheight(void)
1387     [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1388     return OK;
1392     void
1393 gui_mch_beep(void)
1395     NSBeep();
1400 #ifdef FEAT_BROWSE
1402  * Pop open a file browser and return the file selected, in allocated memory,
1403  * or NULL if Cancel is hit.
1404  *  saving  - TRUE if the file will be saved to, FALSE if it will be opened.
1405  *  title   - Title message for the file browser dialog.
1406  *  dflt    - Default name of file.
1407  *  ext     - Default extension to be added to files without extensions.
1408  *  initdir - directory in which to open the browser (NULL = current dir)
1409  *  filter  - Filter for matched files to choose from.
1410  *  Has a format like this:
1411  *  "C Files (*.c)\0*.c\0"
1412  *  "All Files\0*.*\0\0"
1413  *  If these two strings were concatenated, then a choice of two file
1414  *  filters will be selectable to the user.  Then only matching files will
1415  *  be shown in the browser.  If NULL, the default allows all files.
1417  *  *NOTE* - the filter string must be terminated with TWO nulls.
1418  */
1419     char_u *
1420 gui_mch_browse(
1421     int saving,
1422     char_u *title,
1423     char_u *dflt,
1424     char_u *ext,
1425     char_u *initdir,
1426     char_u *filter)
1428     //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1429     //        " filter=%s", saving, title, dflt, ext, initdir, filter);
1431     // Ensure no data is on the output queue before presenting the dialog.
1432     gui_macvim_force_flush();
1434     NSMutableDictionary *attr = [NSMutableDictionary
1435         dictionaryWithObject:[NSNumber numberWithBool:saving]
1436                       forKey:@"saving"];
1437     if (initdir)
1438         [attr setObject:[NSString stringWithVimString:initdir] forKey:@"dir"];
1440     char_u *s = (char_u*)[[MMBackend sharedInstance]
1441                             browseForFileWithAttributes:attr];
1443     return s;
1445 #endif /* FEAT_BROWSE */
1449     int
1450 gui_mch_dialog(
1451     int         type,
1452     char_u      *title,
1453     char_u      *message,
1454     char_u      *buttons,
1455     int         dfltbutton,
1456     char_u      *textfield)
1458     //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1459     //        "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1460     //        dfltbutton, textfield);
1462     // Ensure no data is on the output queue before presenting the dialog.
1463     gui_macvim_force_flush();
1465     int style = NSInformationalAlertStyle;
1466     if (VIM_WARNING == type) style = NSWarningAlertStyle;
1467     else if (VIM_ERROR == type) style = NSCriticalAlertStyle;
1469     NSMutableDictionary *attr = [NSMutableDictionary
1470                         dictionaryWithObject:[NSNumber numberWithInt:style]
1471                                       forKey:@"alertStyle"];
1473     if (buttons) {
1474         // 'buttons' is a string of '\n'-separated button titles 
1475         NSString *string = [NSString stringWithVimString:buttons];
1476         NSArray *array = [string componentsSeparatedByString:@"\n"];
1477         [attr setObject:array forKey:@"buttonTitles"];
1478     }
1480     NSString *messageText = nil;
1481     if (title)
1482         messageText = [NSString stringWithVimString:title];
1484     if (message) {
1485         NSString *informativeText = [NSString stringWithVimString:message];
1486         if (!messageText) {
1487             // HACK! If there is a '\n\n' or '\n' sequence in the message, then
1488             // make the part up to there into the title.  We only do this
1489             // because Vim has lots of dialogs without a title and they look
1490             // ugly that way.
1491             // TODO: Fix the actual dialog texts.
1492             NSRange eolRange = [informativeText rangeOfString:@"\n\n"];
1493             if (NSNotFound == eolRange.location)
1494                 eolRange = [informativeText rangeOfString:@"\n"];
1495             if (NSNotFound != eolRange.location) {
1496                 messageText = [informativeText substringToIndex:
1497                                                         eolRange.location];
1498                 informativeText = [informativeText substringFromIndex:
1499                                                         NSMaxRange(eolRange)];
1500             }
1501         }
1503         [attr setObject:informativeText forKey:@"informativeText"];
1504     }
1506     if (messageText)
1507         [attr setObject:messageText forKey:@"messageText"];
1509     if (textfield) {
1510         NSString *string = [NSString stringWithVimString:textfield];
1511         [attr setObject:string forKey:@"textFieldString"];
1512     }
1514     return [[MMBackend sharedInstance] showDialogWithAttributes:attr
1515                                                     textField:(char*)textfield];
1519     void
1520 gui_mch_flash(int msec)
1526  * Return the Pixel value (color) for the given color name.  This routine was
1527  * pretty much taken from example code in the Silicon Graphics OSF/Motif
1528  * Programmer's Guide.
1529  * Return INVALCOLOR when failed.
1530  */
1531     guicolor_T
1532 gui_mch_get_color(char_u *name)
1534 #ifdef FEAT_MBYTE
1535     name = CONVERT_TO_UTF8(name);
1536 #endif
1538     NSString *key = [NSString stringWithUTF8String:(char*)name];
1539     guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1541 #ifdef FEAT_MBYTE
1542     CONVERT_TO_UTF8_FREE(name);
1543 #endif
1545     return col;
1550  * Return the RGB value of a pixel as long.
1551  */
1552     long_u
1553 gui_mch_get_rgb(guicolor_T pixel)
1555     // This is only implemented so that vim can guess the correct value for
1556     // 'background' (which otherwise defaults to 'dark'); it is not used for
1557     // anything else (as far as I know).
1558     // The implementation is simple since colors are stored in an int as
1559     // "rrggbb".
1560     return pixel;
1565  * Get the screen dimensions.
1566  * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1567  * Is there no way to find out how wide the borders really are?
1568  * TODO: Add live udate of those value on suspend/resume.
1569  */
1570     void
1571 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1573     //NSLog(@"gui_mch_get_screen_dimensions()");
1574     *screen_w = Columns;
1575     *screen_h = Rows;
1580  * Get the position of the top left corner of the window.
1581  */
1582     int
1583 gui_mch_get_winpos(int *x, int *y)
1585     *x = *y = 0;
1586     return OK;
1591  * Return OK if the key with the termcap name "name" is supported.
1592  */
1593     int
1594 gui_mch_haskey(char_u *name)
1596     BOOL ok = NO;
1598 #ifdef FEAT_MBYTE
1599     name = CONVERT_TO_UTF8(name);
1600 #endif
1602     NSString *value = [NSString stringWithUTF8String:(char*)name];
1603     if (value)
1604         ok =  [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1606 #ifdef FEAT_MBYTE
1607     CONVERT_TO_UTF8_FREE(name);
1608 #endif
1610     return ok;
1615  * Iconify the GUI window.
1616  */
1617     void
1618 gui_mch_iconify(void)
1623 #if defined(FEAT_EVAL) || defined(PROTO)
1625  * Bring the Vim window to the foreground.
1626  */
1627     void
1628 gui_mch_set_foreground(void)
1630     [[MMBackend sharedInstance] activate];
1632 #endif
1636     void
1637 gui_mch_set_shellsize(
1638     int         width,
1639     int         height,
1640     int         min_width,
1641     int         min_height,
1642     int         base_width,
1643     int         base_height,
1644     int         direction)
1646     //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1647     //        " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1648     //        width, height, min_width, min_height, base_width, base_height,
1649     //        direction);
1650     [[MMBackend sharedInstance] setRows:height columns:width];
1654     void
1655 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1660  * Set the position of the top left corner of the window to the given
1661  * coordinates.
1662  */
1663     void
1664 gui_mch_set_winpos(int x, int y)
1669 #ifdef FEAT_TITLE
1671  * Set the window title and icon.
1672  * (The icon is not taken care of).
1673  */
1674     void
1675 gui_mch_settitle(char_u *title, char_u *icon)
1677     //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1679 #ifdef FEAT_MBYTE
1680     title = CONVERT_TO_UTF8(title);
1681 #endif
1683     MMBackend *backend = [MMBackend sharedInstance];
1684     [backend setWindowTitle:(char*)title];
1686     // TODO: Convert filename to UTF-8?
1687     if (curbuf)
1688         [backend setDocumentFilename:(char*)curbuf->b_ffname];
1690 #ifdef FEAT_MBYTE
1691     CONVERT_TO_UTF8_FREE(title);
1692 #endif
1694 #endif
1697     void
1698 gui_mch_toggle_tearoffs(int enable)
1704     void
1705 gui_mch_enter_fullscreen(int fuoptions_flags, guicolor_T bg)
1707     [[MMBackend sharedInstance] enterFullscreen:fuoptions_flags background:bg];
1711     void
1712 gui_mch_leave_fullscreen()
1714     [[MMBackend sharedInstance] leaveFullscreen];
1718     void
1719 gui_mch_fuopt_update()
1721     if (!gui.in_use)
1722         return;
1724     guicolor_T fg, bg;
1725     if (fuoptions_flags & FUOPT_BGCOLOR_HLGROUP) {
1726         syn_id2colors(fuoptions_bgcolor, &fg, &bg);
1727     } else {
1728         bg = fuoptions_bgcolor;
1729     }
1731     [[MMBackend sharedInstance] setFullscreenBackgroundColor:bg];
1735     void
1736 gui_macvim_update_modified_flag()
1738     [[MMBackend sharedInstance] updateModifiedFlag];
1742  * Add search pattern 'pat' to the OS X find pasteboard.  This allows other
1743  * apps access the last pattern searched for (hitting <D-g> in another app will
1744  * initiate a search for the same pattern).
1745  */
1746     void
1747 gui_macvim_add_to_find_pboard(char_u *pat)
1749     if (!pat) return;
1751 #ifdef FEAT_MBYTE
1752     pat = CONVERT_TO_UTF8(pat);
1753 #endif
1754     NSString *s = [NSString stringWithUTF8String:(char*)pat];
1755 #ifdef FEAT_MBYTE
1756     CONVERT_TO_UTF8_FREE(pat);
1757 #endif
1759     if (!s) return;
1761     NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
1762     [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1763     [pb setString:s forType:NSStringPboardType];
1766     void
1767 gui_macvim_set_antialias(int antialias)
1769     [[MMBackend sharedInstance] setAntialias:antialias];
1773     void
1774 gui_macvim_wait_for_startup()
1776     MMBackend *backend = [MMBackend sharedInstance];
1777     if ([backend waitForAck])
1778         [backend waitForConnectionAcknowledgement];
1781 void gui_macvim_get_window_layout(int *count, int *layout)
1783     if (!(count && layout)) return;
1785     // NOTE: Only set 'layout' if the backend has requested a != 0 layout, else
1786     // any command line arguments (-p/-o) would be ignored.
1787     int window_layout = [[MMBackend sharedInstance] initialWindowLayout];
1788     if (window_layout > 0 && window_layout < 4) {
1789         // The window_layout numbers must match the WIN_* defines in main.c.
1790         *count = 0;
1791         *layout = window_layout;
1792     }
1796 // -- Client/Server ---------------------------------------------------------
1798 #ifdef MAC_CLIENTSERVER
1801 // NOTE: Client/Server is only fully supported with a GUI.  Theoretically it
1802 // would be possible to make the server code work with terminal Vim, but it
1803 // would require that a run-loop is set up and checked.  This should not be
1804 // difficult to implement, simply call gui_mch_update() at opportune moments
1805 // and it will take care of the run-loop.  Another (bigger) problem with
1806 // supporting servers in terminal mode is that the server listing code talks to
1807 // MacVim (the GUI) to figure out which servers are running.
1812  * Register connection with 'name'.  The actual connection is named something
1813  * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1814  */
1815     void
1816 serverRegisterName(char_u *name)
1818 #ifdef FEAT_MBYTE
1819     name = CONVERT_TO_UTF8(name);
1820 #endif
1822     NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1823     [[MMBackend sharedInstance] registerServerWithName:svrName];
1825 #ifdef FEAT_MBYTE
1826     CONVERT_TO_UTF8_FREE(name);
1827 #endif
1832  * Send to an instance of Vim.
1833  * Returns 0 for OK, negative for an error.
1834  */
1835     int
1836 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1837         int *port, int asExpr, int silent)
1839 #ifdef FEAT_MBYTE
1840     name = CONVERT_TO_UTF8(name);
1841     cmd = CONVERT_TO_UTF8(cmd);
1842 #endif
1844     BOOL ok = [[MMBackend sharedInstance]
1845             sendToServer:[NSString stringWithUTF8String:(char*)name]
1846                   string:[NSString stringWithUTF8String:(char*)cmd]
1847                    reply:result
1848                     port:port
1849               expression:asExpr
1850                   silent:silent];
1852 #ifdef FEAT_MBYTE
1853     CONVERT_TO_UTF8_FREE(name);
1854     CONVERT_TO_UTF8_FREE(cmd);
1855 #endif
1857     return ok ? 0 : -1;
1862  * Ask MacVim for the names of all Vim servers.
1863  */
1864     char_u *
1865 serverGetVimNames(void)
1867     char_u *names = NULL;
1868     NSArray *list = [[MMBackend sharedInstance] serverList];
1870     if (list) {
1871         NSString *string = [list componentsJoinedByString:@"\n"];
1872         names = [string vimStringSave];
1873     }
1875     return names;
1880  * 'str' is a hex int representing the send port of the connection.
1881  */
1882     int
1883 serverStrToPort(char_u *str)
1885     int port = 0;
1887     sscanf((char *)str, "0x%x", &port);
1888     if (!port)
1889         EMSG2(_("E573: Invalid server id used: %s"), str);
1891     return port;
1896  * Check for replies from server with send port 'port'.
1897  * Return TRUE and a non-malloc'ed string if there is.  Else return FALSE.
1898  */
1899     int
1900 serverPeekReply(int port, char_u **str)
1902     NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1903     int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1905     if (str && len > 0) {
1906         *str = (char_u*)[reply UTF8String];
1908 #ifdef FEAT_MBYTE
1909         if (input_conv.vc_type != CONV_NONE) {
1910             char_u *s = string_convert(&input_conv, *str, &len);
1912             if (len > 0) {
1913                 // HACK! Since 's' needs to be freed we cannot simply set
1914                 // '*str = s' or memory will leak.  Instead, create a dummy
1915                 // NSData and return its 'bytes' pointer, then autorelease the
1916                 // NSData.
1917                 NSData *data = [NSData dataWithBytes:s length:len+1];
1918                 *str = (char_u*)[data bytes];
1919             }
1921             vim_free(s);
1922         }
1923 #endif
1924     }
1926     return reply != nil;
1931  * Wait for replies from server with send port 'port'.
1932  * Return 0 and the malloc'ed string when a reply is available.
1933  * Return -1 on error.
1934  */
1935     int
1936 serverReadReply(int port, char_u **str)
1938     NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1939     if (reply && str) {
1940         *str = [reply vimStringSave];
1941         return 0;
1942     }
1944     return -1;
1949  * Send a reply string (notification) to client with port given by "serverid".
1950  * Return -1 if the window is invalid.
1951  */
1952     int
1953 serverSendReply(char_u *serverid, char_u *reply)
1955     int retval = -1;
1956     int port = serverStrToPort(serverid);
1957     if (port > 0 && reply) {
1958 #ifdef FEAT_MBYTE
1959         reply = CONVERT_TO_UTF8(reply);
1960 #endif
1961         BOOL ok = [[MMBackend sharedInstance]
1962                 sendReply:[NSString stringWithUTF8String:(char*)reply]
1963                    toPort:port];
1964         retval = ok ? 0 : -1;
1965 #ifdef FEAT_MBYTE
1966         CONVERT_TO_UTF8_FREE(reply);
1967 #endif
1968     }
1970     return retval;
1973 #endif // MAC_CLIENTSERVER
1978 // -- ODB Editor Support ----------------------------------------------------
1980 #ifdef FEAT_ODB_EDITOR
1982  * The ODB Editor protocol works like this:
1983  * - An external program (the server) asks MacVim to open a file and associates
1984  *   three things with this file: (1) a server id (a four character code that
1985  *   identifies the server), (2) a path that can be used as window title for
1986  *   the file (optional), (3) an arbitrary token (optional)
1987  * - When a file is saved or closed, MacVim should tell the server about which
1988  *   file was modified and also pass back the token
1990  * All communication between MacVim and the server goes via Apple Events.
1991  */
1993     static OSErr
1994 odb_event(buf_T *buf, const AEEventID action)
1996     if (!(buf->b_odb_server_id && buf->b_ffname))
1997         return noErr;
1999     NSAppleEventDescriptor *targetDesc = [NSAppleEventDescriptor
2000             descriptorWithDescriptorType:typeApplSignature
2001                                    bytes:&buf->b_odb_server_id
2002                                   length:sizeof(OSType)];
2004     // TODO: Convert b_ffname to UTF-8?
2005     NSString *path = [NSString stringWithUTF8String:(char*)buf->b_ffname];
2006     NSData *pathData = [[[NSURL fileURLWithPath:path] absoluteString]
2007             dataUsingEncoding:NSUTF8StringEncoding];
2008     NSAppleEventDescriptor *pathDesc = [NSAppleEventDescriptor
2009             descriptorWithDescriptorType:typeFileURL data:pathData];
2011     NSAppleEventDescriptor *event = [NSAppleEventDescriptor
2012             appleEventWithEventClass:kODBEditorSuite
2013                              eventID:action
2014                     targetDescriptor:targetDesc
2015                             returnID:kAutoGenerateReturnID
2016                        transactionID:kAnyTransactionID];
2018     [event setParamDescriptor:pathDesc forKeyword:keyDirectObject];
2020     if (buf->b_odb_token)
2021         [event setParamDescriptor:buf->b_odb_token forKeyword:keySenderToken];
2023     return AESendMessage([event aeDesc], NULL, kAENoReply | kAENeverInteract,
2024             kAEDefaultTimeout);
2027     OSErr
2028 odb_buffer_close(buf_T *buf)
2030     OSErr err = noErr;
2031     if (buf) {
2032         err = odb_event(buf, kAEClosedFile);
2034         buf->b_odb_server_id = 0;
2036         if (buf->b_odb_token) {
2037             [(NSAppleEventDescriptor *)(buf->b_odb_token) release];
2038             buf->b_odb_token = NULL;
2039         }
2041         if (buf->b_odb_fname) {
2042             vim_free(buf->b_odb_fname);
2043             buf->b_odb_fname = NULL;
2044         }
2045     }
2047     return err;
2050     OSErr
2051 odb_post_buffer_write(buf_T *buf)
2053     return buf ? odb_event(buf, kAEModifiedFile) : noErr;
2056     void
2057 odb_end(void)
2059     buf_T *buf;
2060     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2061         odb_buffer_close(buf);
2064 #endif // FEAT_ODB_EDITOR
2067     char_u *
2068 get_macaction_name(expand_T *xp, int idx)
2070     static char_u *str = NULL;
2071     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
2073     if (nil == actionDict || idx < 0 || idx >= [actionDict count])
2074         return NULL;
2076     NSString *string = [[actionDict allKeys] objectAtIndex:idx];
2077     if (!string)
2078         return NULL;
2080     char_u *plainStr = (char_u*)[string UTF8String];
2082 #ifdef FEAT_MBYTE
2083     if (str) {
2084         vim_free(str);
2085         str = NULL;
2086     }
2087     if (input_conv.vc_type != CONV_NONE) {
2088         int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
2089         str = string_convert(&input_conv, plainStr, &len);
2090         plainStr = str;
2091     }
2092 #endif
2094     return plainStr;
2098     int
2099 is_valid_macaction(char_u *action)
2101     int isValid = NO;
2102     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
2103     if (actionDict) {
2104 #ifdef FEAT_MBYTE
2105         action = CONVERT_TO_UTF8(action);
2106 #endif
2107         NSString *string = [NSString stringWithUTF8String:(char*)action];
2108         isValid = (nil != [actionDict objectForKey:string]);
2109 #ifdef FEAT_MBYTE
2110         CONVERT_TO_UTF8_FREE(action);
2111 #endif
2112     }
2114     return isValid;
2117 static int specialKeyToNSKey(int key)
2119     if (!IS_SPECIAL(key))
2120         return key;
2122     static struct {
2123         int special;
2124         int nskey;
2125     } sp2ns[] = {
2126         { K_UP, NSUpArrowFunctionKey },
2127         { K_DOWN, NSDownArrowFunctionKey },
2128         { K_LEFT, NSLeftArrowFunctionKey },
2129         { K_RIGHT, NSRightArrowFunctionKey },
2130         { K_F1, NSF1FunctionKey },
2131         { K_F2, NSF2FunctionKey },
2132         { K_F3, NSF3FunctionKey },
2133         { K_F4, NSF4FunctionKey },
2134         { K_F5, NSF5FunctionKey },
2135         { K_F6, NSF6FunctionKey },
2136         { K_F7, NSF7FunctionKey },
2137         { K_F8, NSF8FunctionKey },
2138         { K_F9, NSF9FunctionKey },
2139         { K_F10, NSF10FunctionKey },
2140         { K_F11, NSF11FunctionKey },
2141         { K_F12, NSF12FunctionKey },
2142         { K_F13, NSF13FunctionKey },
2143         { K_F14, NSF14FunctionKey },
2144         { K_F15, NSF15FunctionKey },
2145         { K_F16, NSF16FunctionKey },
2146         { K_F17, NSF17FunctionKey },
2147         { K_F18, NSF18FunctionKey },
2148         { K_F19, NSF19FunctionKey },
2149         { K_F20, NSF20FunctionKey },
2150         { K_F21, NSF21FunctionKey },
2151         { K_F22, NSF22FunctionKey },
2152         { K_F23, NSF23FunctionKey },
2153         { K_F24, NSF24FunctionKey },
2154         { K_F25, NSF25FunctionKey },
2155         { K_F26, NSF26FunctionKey },
2156         { K_F27, NSF27FunctionKey },
2157         { K_F28, NSF28FunctionKey },
2158         { K_F29, NSF29FunctionKey },
2159         { K_F30, NSF30FunctionKey },
2160         { K_F31, NSF31FunctionKey },
2161         { K_F32, NSF32FunctionKey },
2162         { K_F33, NSF33FunctionKey },
2163         { K_F34, NSF34FunctionKey },
2164         { K_F35, NSF35FunctionKey },
2165         { K_DEL, NSBackspaceCharacter },
2166         { K_BS, NSDeleteCharacter },
2167         { K_HOME, NSHomeFunctionKey },
2168         { K_END, NSEndFunctionKey },
2169         { K_PAGEUP, NSPageUpFunctionKey },
2170         { K_PAGEDOWN, NSPageDownFunctionKey }
2171     };
2173     int i;
2174     for (i = 0; i < sizeof(sp2ns)/sizeof(sp2ns[0]); ++i) {
2175         if (sp2ns[i].special == key)
2176             return sp2ns[i].nskey;
2177     }
2179     return 0;
2182 static int vimModMaskToEventModifierFlags(int mods)
2184     int flags = 0;
2186     if (mods & MOD_MASK_SHIFT)
2187         flags |= NSShiftKeyMask;
2188     if (mods & MOD_MASK_CTRL)
2189         flags |= NSControlKeyMask;
2190     if (mods & MOD_MASK_ALT)
2191         flags |= NSAlternateKeyMask;
2192     if (mods & MOD_MASK_CMD)
2193         flags |= NSCommandKeyMask;
2195     return flags;