Add support for :winpos
[MacVim.git] / src / MacVim / gui_macvim.m
blob4d5e3b96ba2aee0c32898163004e61280339b8cb
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>
22 // HACK! Used in gui.c to determine which string drawing code to use.
23 int use_gui_macvim_draw_string = 1;
26 // NOTE: The default font is bundled with the application.
27 static NSString *MMDefaultFontName = @"DejaVu Sans Mono";
28 static int MMDefaultFontSize       = 12;
29 static int MMMinFontSize           = 6;
30 static int MMMaxFontSize           = 100;
33 static GuiFont gui_macvim_font_with_name(char_u *name);
34 static int specialKeyToNSKey(int key);
35 static int vimModMaskToEventModifierFlags(int mods);
37 NSArray *descriptor_for_menu(vimmenu_T *menu);
38 vimmenu_T *menu_for_descriptor(NSArray *desc);
42 // -- Initialization --------------------------------------------------------
44     void
45 macvim_early_init()
47     NSBundle *bundle = [NSBundle mainBundle];
48     if (bundle) {
49         // Set environment variables $VIM and $VIMRUNTIME
50         NSString *path = [[bundle resourcePath]
51                                         stringByAppendingPathComponent:@"vim"];
52         vim_setenv((char_u*)"VIM", (char_u*)[path UTF8String]);
54         path = [path stringByAppendingPathComponent:@"runtime"];
55         vim_setenv((char_u*)"VIMRUNTIME", (char_u*)[path UTF8String]);
56     }
58 #if 0   // NOTE: setlocale(LC_ALL, "") seems to work after a restart so this is
59         // not necessary.  The locale used depends on what "Region" is set
60         // inside the "Formats" tab of the "International" System Preferences
61         // pane.
62     // Try to ensure that the locale is set to match that used by NSBundle to
63     // load localized resources.  If there is a mismatch e.g. between the
64     // MacVim menu and other menus, then this code needs to change (nb. the
65     // MacVim menu is set up inside a nib file so the locale used for it is
66     // chosen by NSBundle and the other menus are set up by Vim so their locale
67     // matches whatever we set here).
68     NSLocale *loc = [NSLocale currentLocale];
69     if (loc) {
70         NSString *s = [NSString stringWithFormat:@"%@_%@.UTF-8",
71                                     [loc objectForKey:NSLocaleLanguageCode],
72                                     [loc objectForKey:NSLocaleCountryCode]];
73         setlocale(LC_ALL, [s UTF8String]);
74         fprintf(stderr, "locale=%s\n", [s UTF8String]);
75         fflush(stderr);
76     }
77 #endif
82  * Parse the GUI related command-line arguments.  Any arguments used are
83  * deleted from argv, and *argc is decremented accordingly.  This is called
84  * when vim is started, whether or not the GUI has been started.
85  * NOTE: This function will be called twice if the Vim process forks.
86  */
87     void
88 gui_mch_prepare(int *argc, char **argv)
90     int i;
91     for (i = 0; i < *argc; ++i) {
92         if (strncmp(argv[i], "--mmwaitforack", 14) == 0) {
93             [[MMBackend sharedInstance] setWaitForAck:YES];
94             --*argc;
95             if (*argc > i)
96                 mch_memmove(&argv[i], &argv[i+1], (*argc-i) * sizeof(char*));
97             break;
98         }
99     }
101 #ifdef FEAT_NETBEANS_INTG
102     for (i = 0; i < *argc; ++i) {
103         if (strncmp(argv[i], "-nb", 3) == 0) {
104             usingNetbeans++;
105             netbeansArg = argv[i];
106             --*argc;
107             if (*argc > i)
108                 mch_memmove(&argv[i], &argv[i+1], (*argc-i) * sizeof(char*));
109             break;
110         }
111     }
112 #endif
116 /* Called directly after forking (even if we didn't fork). */
117     void
118 gui_macvim_after_fork_init()
120     ASLInit();
121     ASLogDebug(@"");
123     // Restore autosaved rows & columns
124     CFIndex rows, cols;
125     Boolean rowsValid, colsValid;
126     rows = CFPreferencesGetAppIntegerValue((CFStringRef)MMAutosaveRowsKey,
127                                         kCFPreferencesCurrentApplication,
128                                         &rowsValid);
129     cols = CFPreferencesGetAppIntegerValue((CFStringRef)MMAutosaveColumnsKey,
130                                         kCFPreferencesCurrentApplication,
131                                         &colsValid);
132     if (rowsValid && colsValid
133             && (rows > 4 && rows < 1000 && cols > 29 && cols < 4000)) {
134         gui.num_rows = rows;
135         gui.num_cols = cols;
136     } else {
137         // Use the defaults (typically 80x24), if there are no autosaved rows &
138         // columns.
139         gui.num_rows = Rows;
140         gui.num_cols = Columns;
141     }
143     // Check which code path to take for string drawing.
144     CFIndex val;
145     Boolean keyValid;
146     val = CFPreferencesGetAppIntegerValue((CFStringRef)MMRendererKey,
147                                             kCFPreferencesCurrentApplication,
148                                             &keyValid);
149     if (keyValid) {
150         ASLogInfo(@"Use renderer=%d", val);
151         use_gui_macvim_draw_string = (val != MMRendererCoreText);
152     }
157  * Check if the GUI can be started.  Called before gvimrc is sourced.
158  * Return OK or FAIL.
159  */
160     int
161 gui_mch_init_check(void)
163     return OK;
168  * Initialise the GUI.  Create all the windows, set up all the call-backs etc.
169  * Returns OK for success, FAIL when the GUI can't be started.
170  */
171     int
172 gui_mch_init(void)
174     ASLogDebug(@"");
176     if (![[MMBackend sharedInstance] checkin]) {
177         // TODO: Kill the process if there is no terminal to fall back on,
178         // otherwise the process will run outputting to the console.
179         return FAIL;
180     }
182     // Force 'termencoding' to utf-8 (changes to 'tenc' are disallowed in
183     // 'option.c', so that ':set termencoding=...' is impossible).
184     set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
186     // Set values so that pixels and characters are in one-to-one
187     // correspondence (assuming all characters have the same dimensions).
188     gui.scrollbar_width = gui.scrollbar_height = 0;
190     gui.char_height = 1;
191     gui.char_width = 1;
192     gui.char_ascent = 0;
194     gui_mch_def_colors();
196     [[MMBackend sharedInstance]
197         setDefaultColorsBackground:gui.back_pixel foreground:gui.norm_pixel];
198     [[MMBackend sharedInstance] setBackgroundColor:gui.back_pixel];
199     [[MMBackend sharedInstance] setForegroundColor:gui.norm_pixel];
201     // NOTE: If this call is left out the cursor is opaque.
202     highlight_gui_started();
204     // Ensure 'linespace' option is passed along to MacVim in case it was set
205     // in [g]vimrc.
206     gui_mch_adjust_charheight();
208     return OK;
213     void
214 gui_mch_exit(int rc)
216     ASLogDebug(@"rc=%d", rc);
218     [[MMBackend sharedInstance] exit];
223  * Open the GUI window which was created by a call to gui_mch_init().
224  */
225     int
226 gui_mch_open(void)
228     return [[MMBackend sharedInstance] openGUIWindow];
232 // -- Updating --------------------------------------------------------------
236  * Catch up with any queued X events.  This may put keyboard input into the
237  * input buffer, call resize call-backs, trigger timers etc.  If there is
238  * nothing in the X event queue (& no timers pending), then we return
239  * immediately.
240  */
241     void
242 gui_mch_update(void)
244     // This function is called extremely often.  It is tempting to do nothing
245     // here to avoid reduced frame-rates but then it would not be possible to
246     // interrupt Vim by presssing Ctrl-C during lengthy operations (e.g. after
247     // entering "10gs" it would not be possible to bring Vim out of the 10 s
248     // sleep prematurely).  As a compromise we check for Ctrl-C only once per
249     // second.  Note that Cmd-. sends SIGINT so it has higher success rate at
250     // interrupting Vim.
251     static CFAbsoluteTime lastTime = 0;
253     CFAbsoluteTime nowTime = CFAbsoluteTimeGetCurrent();
254     if (nowTime - lastTime > 1.0) {
255         [[MMBackend sharedInstance] update];
256         lastTime = nowTime;
257     }
261 /* Flush any output to the screen */
262     void
263 gui_mch_flush(void)
265     // This function is called way too often to be useful as a hint for
266     // flushing.  If we were to flush every time it was called the screen would
267     // flicker.
271     void
272 gui_macvim_flush(void)
274     // This function counts how many times it is called and only flushes the
275     // draw queue if called sufficiently often.  The first few times it is
276     // called it will flush often, but the more it is called the less likely is
277     // it that anything will be flushed.  (The counter resets itself if the
278     // function isn't called for a second.)
279     //
280     // NOTE: Should only be used in loops where it is impossible to know how
281     // often Vim needs to flush.  It was written to handle output from external
282     // commands (see mch_call_shell() in os_unix.c).
284     static CFAbsoluteTime lastTime = 0;
285     static int delay = 1;
286     static int counter = 0;
287     static int scrolls = 0;
289     CFAbsoluteTime nowTime = CFAbsoluteTimeGetCurrent();
290     CFAbsoluteTime delta = nowTime - lastTime;
291     if (delta > 1.0)
292         delay = 1;
294     // We assume that each call corresponds roughly to one line of output.
295     // When one page has scrolled by we increase the delay before the next
296     // flush.
297     if (++scrolls > gui.num_rows) {
298         delay <<= 1;
299         if (delay > 2048)
300             delay = 2048;
301         scrolls = 0;
302     }
304     if (++counter > delay) {
305         gui_macvim_force_flush();
306         counter = 0;
307     }
309     lastTime = nowTime;
313 /* Force flush output to MacVim.  Do not call this method unless absolutely
314  * necessary. */
315     void
316 gui_macvim_force_flush(void)
318     [[MMBackend sharedInstance] flushQueue:YES];
323  * GUI input routine called by gui_wait_for_chars().  Waits for a character
324  * from the keyboard.
325  *  wtime == -1     Wait forever.
326  *  wtime == 0      This should never happen.
327  *  wtime > 0       Wait wtime milliseconds for a character.
328  * Returns OK if a character was found to be available within the given time,
329  * or FAIL otherwise.
330  */
331     int
332 gui_mch_wait_for_chars(int wtime)
334     // NOTE! In all likelihood Vim will take a nap when waitForInput: is
335     // called, so force a flush of the command queue here.
336     [[MMBackend sharedInstance] flushQueue:YES];
338     return [[MMBackend sharedInstance] waitForInput:wtime];
342 // -- Drawing ---------------------------------------------------------------
346  * Clear the whole text window.
347  */
348     void
349 gui_mch_clear_all(void)
351     [[MMBackend sharedInstance] clearAll];
356  * Clear a rectangular region of the screen from text pos (row1, col1) to
357  * (row2, col2) inclusive.
358  */
359     void
360 gui_mch_clear_block(int row1, int col1, int row2, int col2)
362     [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
363                                                     toRow:row2 column:col2];
368  * Delete the given number of lines from the given row, scrolling up any
369  * text further down within the scroll region.
370  */
371     void
372 gui_mch_delete_lines(int row, int num_lines)
374     [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
375             scrollBottom:gui.scroll_region_bot
376                     left:gui.scroll_region_left
377                    right:gui.scroll_region_right];
381     void
382 gui_mch_draw_string(int row, int col, char_u *s, int len, int cells, int flags)
384 #ifdef FEAT_MBYTE
385     char_u *conv_str = NULL;
386     if (output_conv.vc_type != CONV_NONE) {
387         conv_str = string_convert(&output_conv, s, &len);
388         if (conv_str)
389             s = conv_str;
390     }
391 #endif
393     [[MMBackend sharedInstance] drawString:s
394                                     length:len
395                                        row:row
396                                     column:col
397                                      cells:cells
398                                      flags:flags];
399 #ifdef FEAT_MBYTE
400     if (conv_str)
401         vim_free(conv_str);
402 #endif
406     int
407 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
409     int c, cn, cl, i;
410     int start = 0;
411     int endcol = col;
412     int startcol = col;
413     BOOL wide = NO;
414     MMBackend *backend = [MMBackend sharedInstance];
415 #ifdef FEAT_MBYTE
416     char_u *conv_str = NULL;
418     if (output_conv.vc_type != CONV_NONE) {
419         conv_str = string_convert(&output_conv, s, &len);
420         if (conv_str)
421             s = conv_str;
422     }
423 #endif
425     // Loop over each character and output text when it changes from normal to
426     // wide and vice versa.
427     for (i = 0; i < len; i += cl) {
428         c = utf_ptr2char(s + i);
429         cn = utf_char2cells(c);
430         cl = utf_ptr2len(s + i);
431         if (0 == cl)
432             len = i;    // len must be wrong (shouldn't happen)
434         if (!utf_iscomposing(c)) {
435             if ((cn > 1 && !wide) || (cn <= 1 && wide)) {
436                 // Changed from normal to wide or vice versa.
437                 [backend drawString:(s+start) length:i-start
438                                    row:row column:startcol
439                                  cells:endcol-startcol
440                                  flags:(wide ? flags|DRAW_WIDE : flags)];
442                 start = i;
443                 startcol = endcol;
444             }
446             wide = cn > 1;
447             endcol += cn;
448         }
449     }
451     // Output remaining characters.
452     [backend drawString:(s+start) length:len-start
453                     row:row column:startcol cells:endcol-startcol
454                   flags:(wide ? flags|DRAW_WIDE : flags)];
456 #ifdef FEAT_MBYTE
457     if (conv_str)
458         vim_free(conv_str);
459 #endif
461     return endcol - col;
466  * Insert the given number of lines before the given row, scrolling down any
467  * following text within the scroll region.
468  */
469     void
470 gui_mch_insert_lines(int row, int num_lines)
472     [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
473             scrollBottom:gui.scroll_region_bot
474                     left:gui.scroll_region_left
475                    right:gui.scroll_region_right];
480  * Set the current text foreground color.
481  */
482     void
483 gui_mch_set_fg_color(guicolor_T color)
485     [[MMBackend sharedInstance] setForegroundColor:color];
490  * Set the current text background color.
491  */
492     void
493 gui_mch_set_bg_color(guicolor_T color)
495     [[MMBackend sharedInstance] setBackgroundColor:color];
500  * Set the current text special color (used for underlines).
501  */
502     void
503 gui_mch_set_sp_color(guicolor_T color)
505     [[MMBackend sharedInstance] setSpecialColor:color];
510  * Set default colors.
511  */
512     void
513 gui_mch_def_colors()
515     MMBackend *backend = [MMBackend sharedInstance];
517     // The default colors are taken from system values
518     gui.def_norm_pixel = gui.norm_pixel = 
519         [backend lookupColorWithKey:@"MacTextColor"];
520     gui.def_back_pixel = gui.back_pixel = 
521         [backend lookupColorWithKey:@"MacTextBackgroundColor"];
526  * Called when the foreground or background color has been changed.
527  */
528     void
529 gui_mch_new_colors(void)
531     gui.def_back_pixel = gui.back_pixel;
532     gui.def_norm_pixel = gui.norm_pixel;
534     ASLogDebug(@"back=%x norm=%x", gui.def_back_pixel, gui.def_norm_pixel);
536     [[MMBackend sharedInstance]
537         setDefaultColorsBackground:gui.def_back_pixel
538                         foreground:gui.def_norm_pixel];
542  * Invert a rectangle from row r, column c, for nr rows and nc columns.
543  */
544     void
545 gui_mch_invert_rectangle(int r, int c, int nr, int nc, int invert)
547     [[MMBackend sharedInstance] drawInvertedRectAtRow:r column:c numRows:nr
548             numColumns:nc invert:invert];
553 // -- Tabline ---------------------------------------------------------------
557  * Set the current tab to "nr".  First tab is 1.
558  */
559     void
560 gui_mch_set_curtab(int nr)
562     [[MMBackend sharedInstance] selectTab:nr];
567  * Return TRUE when tabline is displayed.
568  */
569     int
570 gui_mch_showing_tabline(void)
572     return [[MMBackend sharedInstance] tabBarVisible];
576  * Update the labels of the tabline.
577  */
578     void
579 gui_mch_update_tabline(void)
581     [[MMBackend sharedInstance] updateTabBar];
585  * Show or hide the tabline.
586  */
587     void
588 gui_mch_show_tabline(int showit)
590     [[MMBackend sharedInstance] showTabBar:showit];
594 // -- Clipboard -------------------------------------------------------------
597     void
598 clip_mch_lose_selection(VimClipboard *cbd)
603     int
604 clip_mch_own_selection(VimClipboard *cbd)
606     // This is called whenever there is a new selection and 'guioptions'
607     // contains the "a" flag (automatically copy selection).  Return TRUE, else
608     // the "a" flag does nothing.  Note that there is no concept of "ownership"
609     // of the clipboard in Mac OS X.
610     return TRUE;
614     void
615 clip_mch_request_selection(VimClipboard *cbd)
617     NSPasteboard *pb = [NSPasteboard generalPasteboard];
618     NSArray *supportedTypes = [NSArray arrayWithObjects:VimPboardType,
619             NSStringPboardType, nil];
620     NSString *bestType = [pb availableTypeFromArray:supportedTypes];
621     if (!bestType) return;
623     int motion_type = MCHAR;
624     NSString *string = nil;
626     if ([bestType isEqual:VimPboardType]) {
627         // This type should consist of an array with two objects:
628         //   1. motion type (NSNumber)
629         //   2. text (NSString)
630         // If this is not the case we fall back on using NSStringPboardType.
631         id plist = [pb propertyListForType:VimPboardType];
632         if ([plist isKindOfClass:[NSArray class]] && [plist count] == 2) {
633             id obj = [plist objectAtIndex:1];
634             if ([obj isKindOfClass:[NSString class]]) {
635                 motion_type = [[plist objectAtIndex:0] intValue];
636                 string = obj;
637             }
638         }
639     }
641     if (!string) {
642         // Use NSStringPboardType.  The motion type is set to line-wise if the
643         // string contains at least one EOL character, otherwise it is set to
644         // character-wise (block-wise is never used).
645         NSMutableString *mstring =
646                 [[pb stringForType:NSStringPboardType] mutableCopy];
647         if (!mstring) return;
649         // Replace unrecognized end-of-line sequences with \x0a (line feed).
650         NSRange range = { 0, [mstring length] };
651         unsigned n = [mstring replaceOccurrencesOfString:@"\x0d\x0a"
652                                              withString:@"\x0a" options:0
653                                                   range:range];
654         if (0 == n) {
655             n = [mstring replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
656                                            options:0 range:range];
657         }
658         
659         // Scan for newline character to decide whether the string should be
660         // pasted line-wise or character-wise.
661         motion_type = MCHAR;
662         if (0 < n || NSNotFound != [mstring rangeOfString:@"\n"].location)
663             motion_type = MLINE;
665         string = mstring;
666     }
668     if (!(MCHAR == motion_type || MLINE == motion_type || MBLOCK == motion_type
669             || MAUTO == motion_type))
670         motion_type = MCHAR;
672     char_u *str = (char_u*)[string UTF8String];
673     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
675 #ifdef FEAT_MBYTE
676     if (input_conv.vc_type != CONV_NONE)
677         str = string_convert(&input_conv, str, &len);
678 #endif
680     if (str)
681         clip_yank_selection(motion_type, str, len, cbd);
683 #ifdef FEAT_MBYTE
684     if (input_conv.vc_type != CONV_NONE)
685         vim_free(str);
686 #endif
691  * Send the current selection to the clipboard.
692  */
693     void
694 clip_mch_set_selection(VimClipboard *cbd)
696     // If the '*' register isn't already filled in, fill it in now.
697     cbd->owned = TRUE;
698     clip_get_selection(cbd);
699     cbd->owned = FALSE;
700     
701     // Get the text to put on the pasteboard.
702     long_u llen = 0; char_u *str = 0;
703     int motion_type = clip_convert_selection(&str, &llen, cbd);
704     if (motion_type < 0)
705         return;
707     // TODO: Avoid overflow.
708     int len = (int)llen;
709 #ifdef FEAT_MBYTE
710     if (output_conv.vc_type != CONV_NONE) {
711         char_u *conv_str = string_convert(&output_conv, str, &len);
712         if (conv_str) {
713             vim_free(str);
714             str = conv_str;
715         }
716     }
717 #endif
719     if (len > 0) {
720         NSString *string = [[NSString alloc]
721             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
723         // See clip_mch_request_selection() for info on pasteboard types.
724         NSPasteboard *pb = [NSPasteboard generalPasteboard];
725         NSArray *supportedTypes = [NSArray arrayWithObjects:VimPboardType,
726                 NSStringPboardType, nil];
727         [pb declareTypes:supportedTypes owner:nil];
729         NSNumber *motion = [NSNumber numberWithInt:motion_type];
730         NSArray *plist = [NSArray arrayWithObjects:motion, string, nil];
731         [pb setPropertyList:plist forType:VimPboardType];
733         [pb setString:string forType:NSStringPboardType];
734         
735         [string release];
736     }
738     vim_free(str);
742 // -- Menu ------------------------------------------------------------------
746  * A menu descriptor represents the "address" of a menu as an array of strings.
747  * E.g. the menu "File->Close" has descriptor { "File", "Close" }.
748  */
749     NSArray *
750 descriptor_for_menu(vimmenu_T *menu)
752     if (!menu) return nil;
754     NSMutableArray *desc = [NSMutableArray array];
755     while (menu) {
756         NSString *name = [NSString stringWithVimString:menu->dname];
757         [desc insertObject:name atIndex:0];
758         menu = menu->parent;
759     }
761     return desc;
764     vimmenu_T *
765 menu_for_descriptor(NSArray *desc)
767     if (!(desc && [desc count] > 0)) return NULL;
769     vimmenu_T *menu = root_menu;
770     int i, count = [desc count];
772     for (i = 0; i < count; ++i) {
773         NSString *component = [desc objectAtIndex:i];
774         while (menu) {
775             NSString *name = [NSString stringWithVimString:menu->dname];
776             if ([component isEqual:name]) {
777                 if (i+1 == count)
778                     return menu;    // Matched all components, so return menu
779                 menu = menu->children;
780                 break;
781             }
782             menu = menu->next;
783         }
784     }
786     return NULL;
790  * Add a submenu to the menu bar, toolbar, or a popup menu.
791  */
792     void
793 gui_mch_add_menu(vimmenu_T *menu, int idx)
795     NSArray *desc = descriptor_for_menu(menu);
796     [[MMBackend sharedInstance] queueMessage:AddMenuMsgID properties:
797         [NSDictionary dictionaryWithObjectsAndKeys:
798             desc, @"descriptor",
799             [NSNumber numberWithInt:idx], @"index",
800             nil]];
804 // Taken from gui_gtk.c (slightly modified)
805     static int
806 lookup_menu_iconfile(char_u *iconfile, char_u *dest)
808     expand_env(iconfile, dest, MAXPATHL);
810     if (mch_isFullName(dest))
811         return vim_fexists(dest);
813     static const char   suffixes[][4] = {"png", "bmp"};
814     char_u              buf[MAXPATHL];
815     unsigned int        i;
817     for (i = 0; i < sizeof(suffixes)/sizeof(suffixes[0]); ++i)
818         if (gui_find_bitmap(dest, buf, (char *)suffixes[i]) == OK) {
819             STRCPY(dest, buf);
820             return TRUE;
821         }
823     return FALSE;
828  * Add a menu item to a menu
829  */
830     void
831 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
833     char_u *tip = menu->strings[MENU_INDEX_TIP]
834             ? menu->strings[MENU_INDEX_TIP] : menu->actext;
835     NSArray *desc = descriptor_for_menu(menu);
836     NSString *keyEquivalent = menu->mac_key
837         ? [NSString stringWithFormat:@"%C", specialKeyToNSKey(menu->mac_key)]
838         : [NSString string];
839     int modifierMask = vimModMaskToEventModifierFlags(menu->mac_mods);
840     char_u *icon = NULL;
842     if (menu_is_toolbar(menu->parent->name)) {
843         char_u fname[MAXPATHL];
845         // Try to use the icon=.. argument
846         if (menu->iconfile && lookup_menu_iconfile(menu->iconfile, fname))
847             icon = fname;
849         // If not found and not builtin specified try using the menu name
850         if (!icon && !menu->icon_builtin
851                                     && lookup_menu_iconfile(menu->name, fname))
852             icon = fname;
854         // Still no icon found, try using a builtin icon.  (If this also fails,
855         // then a warning icon will be displayed).
856         if (!icon)
857             icon = lookup_toolbar_item(menu->iconidx);
858     }
860     [[MMBackend sharedInstance] queueMessage:AddMenuItemMsgID properties:
861         [NSDictionary dictionaryWithObjectsAndKeys:
862             desc, @"descriptor",
863             [NSNumber numberWithInt:idx], @"index",
864             [NSString stringWithVimString:tip], @"tip",
865             [NSString stringWithVimString:icon], @"icon",
866             keyEquivalent, @"keyEquivalent",
867             [NSNumber numberWithInt:modifierMask], @"modifierMask",
868             [NSString stringWithVimString:menu->mac_action], @"action",
869             [NSNumber numberWithBool:menu->mac_alternate], @"isAlternate",
870             nil]];
875  * Destroy the machine specific menu widget.
876  */
877     void
878 gui_mch_destroy_menu(vimmenu_T *menu)
880     NSArray *desc = descriptor_for_menu(menu);
881     [[MMBackend sharedInstance] queueMessage:RemoveMenuItemMsgID properties:
882         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
887  * Make a menu either grey or not grey.
888  */
889     void
890 gui_mch_menu_grey(vimmenu_T *menu, int grey)
892     /* Only update menu if the 'grey' state has changed to avoid having to pass
893      * lots of unnecessary data to MacVim.  (Skipping this test makes MacVim
894      * pause noticably on mode changes. */
895     NSArray *desc = descriptor_for_menu(menu);
896     if (menu->was_grey == grey)
897         return;
899     menu->was_grey = grey;
901     [[MMBackend sharedInstance] queueMessage:EnableMenuItemMsgID properties:
902         [NSDictionary dictionaryWithObjectsAndKeys:
903             desc, @"descriptor",
904             [NSNumber numberWithInt:!grey], @"enable",
905             nil]];
910  * Make menu item hidden or not hidden
911  */
912     void
913 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
915     // HACK! There is no (obvious) way to hide a menu item, so simply
916     // enable/disable it instead.
917     gui_mch_menu_grey(menu, hidden);
922  * This is called when user right clicks.
923  */
924     void
925 gui_mch_show_popupmenu(vimmenu_T *menu)
927     NSArray *desc = descriptor_for_menu(menu);
928     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:
929         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
934  * This is called when a :popup command is executed.
935  */
936     void
937 gui_make_popup(char_u *path_name, int mouse_pos)
939     vimmenu_T *menu = gui_find_menu(path_name);
940     if (!(menu && menu->children)) return;
942     NSArray *desc = descriptor_for_menu(menu);
943     NSDictionary *p = (mouse_pos || NULL == curwin)
944         ? [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]
945         : [NSDictionary dictionaryWithObjectsAndKeys:
946             desc, @"descriptor",
947             [NSNumber numberWithInt:curwin->w_wrow], @"row",
948             [NSNumber numberWithInt:curwin->w_wcol], @"column",
949             nil];
951     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:p];
956  * This is called after setting all the menus to grey/hidden or not.
957  */
958     void
959 gui_mch_draw_menubar(void)
961     // The (main) menu draws itself in Mac OS X.
965     void
966 gui_mch_enable_menu(int flag)
968     // The (main) menu is always enabled in Mac OS X.
972 #if 0
973     void
974 gui_mch_set_menu_pos(int x, int y, int w, int h)
976     // The (main) menu cannot be moved in Mac OS X.
978 #endif
981     void
982 gui_mch_show_toolbar(int showit)
984     int flags = 0;
985     if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
986     if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
987     if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
989     [[MMBackend sharedInstance] showToolbar:showit flags:flags];
995 // -- Fonts -----------------------------------------------------------------
999  * If a font is not going to be used, free its structure.
1000  */
1001     void
1002 gui_mch_free_font(font)
1003     GuiFont     font;
1005     if (font != NOFONT) {
1006         ASLogDebug(@"font=0x%x", font);
1007         [(id)font release];
1008     }
1012     GuiFont
1013 gui_mch_retain_font(GuiFont font)
1015     return (GuiFont)[(id)font retain];
1020  * Get a font structure for highlighting.
1021  */
1022     GuiFont
1023 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
1025     ASLogDebug(@"name='%s' giveErrorIfMissing=%d", name, giveErrorIfMissing);
1027     GuiFont font = gui_macvim_font_with_name(name);
1028     if (font != NOFONT)
1029         return font;
1031     if (giveErrorIfMissing)
1032         EMSG2(_(e_font), name);
1034     return NOFONT;
1038 #if defined(FEAT_EVAL) || defined(PROTO)
1040  * Return the name of font "font" in allocated memory.
1041  * TODO: use 'font' instead of 'name'?
1042  */
1043     char_u *
1044 gui_mch_get_fontname(GuiFont font, char_u *name)
1046     return name ? vim_strsave(name) : NULL;
1048 #endif
1052  * Initialise vim to use the font with the given name.  Return FAIL if the font
1053  * could not be loaded, OK otherwise.
1054  */
1055     int
1056 gui_mch_init_font(char_u *font_name, int fontset)
1058     ASLogDebug(@"font_name='%s' fontset=%d", font_name, fontset);
1060     if (font_name && STRCMP(font_name, "*") == 0) {
1061         // :set gfn=* shows the font panel.
1062         do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
1063         return FAIL;
1064     }
1066     GuiFont font = gui_macvim_font_with_name(font_name);
1067     if (font == NOFONT)
1068         return FAIL;
1070     gui_mch_free_font(gui.norm_font);
1071     gui.norm_font = font;
1073     // NOTE: MacVim keeps separate track of the normal and wide fonts.
1074     // Unless the user changes 'guifontwide' manually, they are based on
1075     // the same (normal) font.  Also note that each time the normal font is
1076     // set, the advancement may change so the wide font needs to be updated
1077     // as well (so that it is always twice the width of the normal font).
1078     [[MMBackend sharedInstance] setFont:font wide:NO];
1079     [[MMBackend sharedInstance] setFont:(NOFONT != gui.wide_font ? gui.wide_font
1080                                                                  : font)
1081                                    wide:YES];
1083     return OK;
1088  * Set the current text font.
1089  */
1090     void
1091 gui_mch_set_font(GuiFont font)
1093     // Font selection is done inside MacVim...nothing here to do.
1098  * Return GuiFont in allocated memory.  The caller must free it using
1099  * gui_mch_free_font().
1100  */
1101     GuiFont
1102 gui_macvim_font_with_name(char_u *name)
1104     if (!name)
1105         return (GuiFont)[[NSString alloc] initWithFormat:@"%@:%d",
1106                                         MMDefaultFontName, MMDefaultFontSize];
1108     NSString *fontName = [NSString stringWithVimString:name];
1109     int size = MMDefaultFontSize;
1110     BOOL parseFailed = NO;
1112     NSArray *components = [fontName componentsSeparatedByString:@":"];
1113     if ([components count] == 2) {
1114         NSString *sizeString = [components lastObject];
1115         if ([sizeString length] > 0
1116                 && [sizeString characterAtIndex:0] == 'h') {
1117             sizeString = [sizeString substringFromIndex:1];
1118             if ([sizeString length] > 0) {
1119                 size = (int)round([sizeString floatValue]);
1120                 fontName = [components objectAtIndex:0];
1121             }
1122         } else {
1123             parseFailed = YES;
1124         }
1125     } else if ([components count] > 2) {
1126         parseFailed = YES;
1127     }
1129     if (!parseFailed) {
1130         // Replace underscores with spaces.
1131         fontName = [[fontName componentsSeparatedByString:@"_"]
1132                                  componentsJoinedByString:@" "];
1133     }
1135     if (!parseFailed && [fontName length] > 0) {
1136         if (size < MMMinFontSize) size = MMMinFontSize;
1137         if (size > MMMaxFontSize) size = MMMaxFontSize;
1139         // If the default font is requested we don't check if NSFont can load
1140         // it since the font most likely isn't loaded anyway (it may only be
1141         // available to the MacVim binary).  If it is not the default font we
1142         // ask NSFont if it can load it.
1143         if ([fontName isEqualToString:MMDefaultFontName]
1144                 || [NSFont fontWithName:fontName size:size])
1145             return [[NSString alloc] initWithFormat:@"%@:%d", fontName, size];
1146     }
1148     return NOFONT;
1151 // -- Scrollbars ------------------------------------------------------------
1153 // NOTE: Even though scrollbar identifiers are 'long' we tacitly assume that
1154 // they only use 32 bits (in particular when compiling for 64 bit).  This is
1155 // justified since identifiers are generated from a 32 bit counter in
1156 // gui_create_scrollbar().  However if that code changes we may be in trouble
1157 // (if ever that many scrollbars are allocated...).  The reason behind this is
1158 // that we pass scrollbar identifers over process boundaries so the width of
1159 // the variable needs to be fixed (and why fix at 64 bit when only 32 are
1160 // really used?).
1162     void
1163 gui_mch_create_scrollbar(
1164         scrollbar_T *sb,
1165         int orient)     /* SBAR_VERT or SBAR_HORIZ */
1167     [[MMBackend sharedInstance] 
1168             createScrollbarWithIdentifier:(int32_t)sb->ident type:sb->type];
1172     void
1173 gui_mch_destroy_scrollbar(scrollbar_T *sb)
1175     [[MMBackend sharedInstance] 
1176             destroyScrollbarWithIdentifier:(int32_t)sb->ident];
1180     void
1181 gui_mch_enable_scrollbar(
1182         scrollbar_T     *sb,
1183         int             flag)
1185     [[MMBackend sharedInstance] 
1186             showScrollbarWithIdentifier:(int32_t)sb->ident state:flag];
1190     void
1191 gui_mch_set_scrollbar_pos(
1192         scrollbar_T *sb,
1193         int x,
1194         int y,
1195         int w,
1196         int h)
1198     int pos = y;
1199     int len = h;
1200     if (SBAR_BOTTOM == sb->type) {
1201         pos = x;
1202         len = w; 
1203     }
1205     [[MMBackend sharedInstance] 
1206             setScrollbarPosition:pos length:len identifier:(int32_t)sb->ident];
1210     void
1211 gui_mch_set_scrollbar_thumb(
1212         scrollbar_T *sb,
1213         long val,
1214         long size,
1215         long max)
1217     [[MMBackend sharedInstance] 
1218             setScrollbarThumbValue:val
1219                               size:size
1220                                max:max
1221                         identifier:(int32_t)sb->ident];
1225 // -- Cursor ----------------------------------------------------------------
1229  * Draw a cursor without focus.
1230  */
1231     void
1232 gui_mch_draw_hollow_cursor(guicolor_T color)
1234     return [[MMBackend sharedInstance]
1235         drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
1236                fraction:100 color:color];
1241  * Draw part of a cursor, only w pixels wide, and h pixels high.
1242  */
1243     void
1244 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
1246     // HACK!  'w' and 'h' are always 1 since we do not tell Vim about the exact
1247     // font dimensions.  Thus these parameters are useless.  Instead we look at
1248     // the shape_table to determine the shape and size of the cursor (just like
1249     // gui_update_cursor() does).
1251 #ifdef FEAT_RIGHTLEFT
1252     // If 'rl' is set the insert mode cursor must be drawn on the right-hand
1253     // side of a text cell.
1254     int rl = curwin ? curwin->w_p_rl : FALSE;
1255 #else
1256     int rl = FALSE;
1257 #endif
1258     int idx = get_shape_idx(FALSE);
1259     int shape = MMInsertionPointBlock;
1260     switch (shape_table[idx].shape) {
1261         case SHAPE_HOR:
1262             shape = MMInsertionPointHorizontal;
1263             break;
1264         case SHAPE_VER:
1265             shape = rl ? MMInsertionPointVerticalRight
1266                        : MMInsertionPointVertical;
1267             break;
1268     }
1270     return [[MMBackend sharedInstance]
1271         drawCursorAtRow:gui.row column:gui.col shape:shape
1272                fraction:shape_table[idx].percentage color:color];
1277  * Cursor blink functions.
1279  * This is a simple state machine:
1280  * BLINK_NONE   not blinking at all
1281  * BLINK_OFF    blinking, cursor is not shown
1282  * BLINK_ON blinking, cursor is shown
1283  */
1284     void
1285 gui_mch_set_blinking(long wait, long on, long off)
1287     [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1292  * Start the cursor blinking.  If it was already blinking, this restarts the
1293  * waiting time and shows the cursor.
1294  */
1295     void
1296 gui_mch_start_blink(void)
1298     [[MMBackend sharedInstance] startBlink];
1303  * Stop the cursor blinking.  Show the cursor if it wasn't shown.
1304  */
1305     void
1306 gui_mch_stop_blink(void)
1308     [[MMBackend sharedInstance] stopBlink];
1312 // -- Mouse -----------------------------------------------------------------
1316  * Get current mouse coordinates in text window.
1317  */
1318     void
1319 gui_mch_getmouse(int *x, int *y)
1321     ASLogInfo(@"Not implemented!");
1325     void
1326 gui_mch_setmouse(int x, int y)
1328     ASLogInfo(@"Not implemented!");
1332     void
1333 mch_set_mouse_shape(int shape)
1335     [[MMBackend sharedInstance] setMouseShape:shape];
1341 // -- Input Method ----------------------------------------------------------
1343 #if defined(USE_IM_CONTROL)
1345     void
1346 im_set_position(int row, int col)
1348     // The pre-edit area is a popup window which is displayed by MMTextView.
1349     [[MMBackend sharedInstance] setPreEditRow:row column:col];
1353     void
1354 im_set_control(int enable)
1356     // Tell frontend whether it should notify us when the input method changes
1357     // or not (called when 'imd' is toggled).
1358     int msgid = enable ? EnableImControlMsgID : DisableImControlMsgID;
1359     [[MMBackend sharedInstance] queueMessage:msgid properties:nil];
1363     void
1364 im_set_active(int active)
1366     // Tell frontend to enable/disable IM (called e.g. when the mode changes).
1367     if (!p_imdisable) {
1368         int msgid = active ? ActivateKeyScriptMsgID : DeactivateKeyScriptMsgID;
1369         [[MMBackend sharedInstance] setImState:active];
1370         [[MMBackend sharedInstance] queueMessage:msgid properties:nil];
1371     }
1375     int
1376 im_get_status(void)
1378     return [[MMBackend sharedInstance] imState];
1381 #endif // defined(USE_IM_CONTROL)
1386 // -- Find & Replace dialog -------------------------------------------------
1388 #ifdef FIND_REPLACE_DIALOG
1390     static void
1391 macvim_find_and_replace(char_u *arg, BOOL replace)
1393     // TODO: Specialized dialog for find without replace?
1394     int wholeWord = FALSE;
1395     int matchCase = !p_ic;
1396     char_u *text  = get_find_dialog_text(arg, &wholeWord, &matchCase);
1398     int flags = 0;
1399     if (wholeWord) flags |= FRD_WHOLE_WORD;
1400     if (matchCase) flags |= FRD_MATCH_CASE;
1402     NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
1403             [NSString stringWithVimString:text],    @"text",
1404             [NSNumber numberWithInt:flags],         @"flags",
1405             nil];
1407     [[MMBackend sharedInstance] queueMessage:ShowFindReplaceDialogMsgID
1408                                   properties:args];
1411     void
1412 gui_mch_find_dialog(exarg_T *eap)
1414     macvim_find_and_replace(eap->arg, NO);
1417     void
1418 gui_mch_replace_dialog(exarg_T *eap)
1420     macvim_find_and_replace(eap->arg, YES);
1423 #endif // FIND_REPLACE_DIALOG
1428 // -- Unsorted --------------------------------------------------------------
1431     void
1432 ex_macaction(eap)
1433     exarg_T     *eap;
1435     if (!gui.in_use) {
1436         EMSG(_("E???: Command only available in GUI mode"));
1437         return;
1438     }
1440     char_u *arg = eap->arg;
1441 #ifdef FEAT_MBYTE
1442     arg = CONVERT_TO_UTF8(arg);
1443 #endif
1445     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1446     NSString *name = [NSString stringWithUTF8String:(char*)arg];
1447     if (actionDict && [actionDict objectForKey:name] != nil) {
1448         [[MMBackend sharedInstance] executeActionWithName:name];
1449     } else {
1450         EMSG2(_("E???: Invalid action: %s"), eap->arg);
1451     }
1453 #ifdef FEAT_MBYTE
1454     arg = CONVERT_TO_UTF8(arg);
1455 #endif
1460  * Adjust gui.char_height (after 'linespace' was changed).
1461  */
1462     int
1463 gui_mch_adjust_charheight(void)
1465     [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1466     return OK;
1470     void
1471 gui_mch_beep(void)
1473     NSBeep();
1478 #ifdef FEAT_BROWSE
1480  * Pop open a file browser and return the file selected, in allocated memory,
1481  * or NULL if Cancel is hit.
1482  *  saving  - TRUE if the file will be saved to, FALSE if it will be opened.
1483  *  title   - Title message for the file browser dialog.
1484  *  dflt    - Default name of file.
1485  *  ext     - Default extension to be added to files without extensions.
1486  *  initdir - directory in which to open the browser (NULL = current dir)
1487  *  filter  - Filter for matched files to choose from.
1488  *  Has a format like this:
1489  *  "C Files (*.c)\0*.c\0"
1490  *  "All Files\0*.*\0\0"
1491  *  If these two strings were concatenated, then a choice of two file
1492  *  filters will be selectable to the user.  Then only matching files will
1493  *  be shown in the browser.  If NULL, the default allows all files.
1495  *  *NOTE* - the filter string must be terminated with TWO nulls.
1496  */
1497     char_u *
1498 gui_mch_browse(
1499     int saving,
1500     char_u *title,
1501     char_u *dflt,
1502     char_u *ext,
1503     char_u *initdir,
1504     char_u *filter)
1506     ASLogDebug(@"saving=%d title='%s' dflt='%s' ext='%s' initdir='%s' "
1507                "filter='%s'", saving, title, dflt, ext, initdir, filter);
1509     // Ensure no data is on the output queue before presenting the dialog.
1510     gui_macvim_force_flush();
1512     NSMutableDictionary *attr = [NSMutableDictionary
1513         dictionaryWithObject:[NSNumber numberWithBool:saving]
1514                       forKey:@"saving"];
1515     if (initdir)
1516         [attr setObject:[NSString stringWithVimString:initdir] forKey:@"dir"];
1518     char_u *s = (char_u*)[[MMBackend sharedInstance]
1519                             browseForFileWithAttributes:attr];
1521     return s;
1523 #endif /* FEAT_BROWSE */
1527     int
1528 gui_mch_dialog(
1529     int         type,
1530     char_u      *title,
1531     char_u      *message,
1532     char_u      *buttons,
1533     int         dfltbutton,
1534     char_u      *textfield)
1536     ASLogDebug(@"type=%d title='%s' message='%s' buttons='%s' dfltbutton=%d "
1537                "textfield='%s'", type, title, message, buttons, dfltbutton,
1538                textfield);
1540     // Ensure no data is on the output queue before presenting the dialog.
1541     gui_macvim_force_flush();
1543     int style = NSInformationalAlertStyle;
1544     if (VIM_WARNING == type) style = NSWarningAlertStyle;
1545     else if (VIM_ERROR == type) style = NSCriticalAlertStyle;
1547     NSMutableDictionary *attr = [NSMutableDictionary
1548                         dictionaryWithObject:[NSNumber numberWithInt:style]
1549                                       forKey:@"alertStyle"];
1551     if (buttons) {
1552         // 'buttons' is a string of '\n'-separated button titles 
1553         NSString *string = [NSString stringWithVimString:buttons];
1554         NSArray *array = [string componentsSeparatedByString:@"\n"];
1555         [attr setObject:array forKey:@"buttonTitles"];
1556     }
1558     NSString *messageText = nil;
1559     if (title)
1560         messageText = [NSString stringWithVimString:title];
1562     if (message) {
1563         NSString *informativeText = [NSString stringWithVimString:message];
1564         if (!messageText) {
1565             // HACK! If there is a '\n\n' or '\n' sequence in the message, then
1566             // make the part up to there into the title.  We only do this
1567             // because Vim has lots of dialogs without a title and they look
1568             // ugly that way.
1569             // TODO: Fix the actual dialog texts.
1570             NSRange eolRange = [informativeText rangeOfString:@"\n\n"];
1571             if (NSNotFound == eolRange.location)
1572                 eolRange = [informativeText rangeOfString:@"\n"];
1573             if (NSNotFound != eolRange.location) {
1574                 messageText = [informativeText substringToIndex:
1575                                                         eolRange.location];
1576                 informativeText = [informativeText substringFromIndex:
1577                                                         NSMaxRange(eolRange)];
1578             }
1579         }
1581         [attr setObject:informativeText forKey:@"informativeText"];
1582     }
1584     if (messageText)
1585         [attr setObject:messageText forKey:@"messageText"];
1587     if (textfield) {
1588         NSString *string = [NSString stringWithVimString:textfield];
1589         [attr setObject:string forKey:@"textFieldString"];
1590     }
1592     return [[MMBackend sharedInstance] showDialogWithAttributes:attr
1593                                                     textField:(char*)textfield];
1597     void
1598 gui_mch_flash(int msec)
1604  * Return the Pixel value (color) for the given color name.  This routine was
1605  * pretty much taken from example code in the Silicon Graphics OSF/Motif
1606  * Programmer's Guide.
1607  * Return INVALCOLOR when failed.
1608  */
1609     guicolor_T
1610 gui_mch_get_color(char_u *name)
1612 #ifdef FEAT_MBYTE
1613     name = CONVERT_TO_UTF8(name);
1614 #endif
1616     NSString *key = [NSString stringWithUTF8String:(char*)name];
1617     guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1619 #ifdef FEAT_MBYTE
1620     CONVERT_TO_UTF8_FREE(name);
1621 #endif
1623     return col;
1628  * Return the RGB value of a pixel as long.
1629  */
1630     long_u
1631 gui_mch_get_rgb(guicolor_T pixel)
1633     // This is only implemented so that vim can guess the correct value for
1634     // 'background' (which otherwise defaults to 'dark'); it is not used for
1635     // anything else (as far as I know).
1636     // The implementation is simple since colors are stored in an int as
1637     // "rrggbb".
1638     return pixel;
1643  * Get the screen dimensions.
1644  * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1645  * Is there no way to find out how wide the borders really are?
1646  * TODO: Add live udate of those value on suspend/resume.
1647  */
1648     void
1649 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1651     ASLogDebug(@"Columns=%d Rows=%d", Columns, Rows);
1652     *screen_w = Columns;
1653     *screen_h = Rows;
1658  * Return OK if the key with the termcap name "name" is supported.
1659  */
1660     int
1661 gui_mch_haskey(char_u *name)
1663     return [[MMBackend sharedInstance] hasSpecialKeyWithValue:name];
1668  * Iconify the GUI window.
1669  */
1670     void
1671 gui_mch_iconify(void)
1676 #if defined(FEAT_EVAL) || defined(PROTO)
1678  * Bring the Vim window to the foreground.
1679  */
1680     void
1681 gui_mch_set_foreground(void)
1683     [[MMBackend sharedInstance] activate];
1685 #endif
1689     void
1690 gui_mch_set_shellsize(
1691     int         width,
1692     int         height,
1693     int         min_width,
1694     int         min_height,
1695     int         base_width,
1696     int         base_height,
1697     int         direction)
1699     ASLogDebug(@"width=%d height=%d min_width=%d min_height=%d base_width=%d "
1700                "base_height=%d direction=%d", width, height, min_width,
1701                min_height, base_width, base_height, direction);
1702     [[MMBackend sharedInstance] setRows:height columns:width];
1707  * Set the position of the top left corner of the window to the given
1708  * coordinates.
1709  */
1710     void
1711 gui_mch_set_winpos(int x, int y)
1713     [[MMBackend sharedInstance] setWindowPositionX:x Y:y];
1718  * Get the position of the top left corner of the window.
1719  */
1720     int
1721 gui_mch_get_winpos(int *x, int *y)
1723     [[MMBackend sharedInstance] getWindowPositionX:x Y:y];
1724     return OK;
1728     void
1729 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1734 #ifdef FEAT_TITLE
1736  * Set the window title and icon.
1737  * (The icon is not taken care of).
1738  */
1739     void
1740 gui_mch_settitle(char_u *title, char_u *icon)
1742     ASLogDebug(@"title='%s' icon='%s'", title, icon);
1744 #ifdef FEAT_MBYTE
1745     title = CONVERT_TO_UTF8(title);
1746 #endif
1748     MMBackend *backend = [MMBackend sharedInstance];
1749     [backend setWindowTitle:(char*)title];
1751     // TODO: Convert filename to UTF-8?
1752     if (curbuf)
1753         [backend setDocumentFilename:(char*)curbuf->b_ffname];
1755 #ifdef FEAT_MBYTE
1756     CONVERT_TO_UTF8_FREE(title);
1757 #endif
1759 #endif
1762     void
1763 gui_mch_toggle_tearoffs(int enable)
1769     void
1770 gui_mch_enter_fullscreen(int fuoptions_flags, guicolor_T bg)
1772     [[MMBackend sharedInstance] enterFullscreen:fuoptions_flags background:bg];
1776     void
1777 gui_mch_leave_fullscreen()
1779     [[MMBackend sharedInstance] leaveFullscreen];
1783     void
1784 gui_mch_fuopt_update()
1786     if (!gui.in_use)
1787         return;
1789     guicolor_T fg, bg;
1790     if (fuoptions_flags & FUOPT_BGCOLOR_HLGROUP) {
1791         syn_id2colors(fuoptions_bgcolor, &fg, &bg);
1792     } else {
1793         bg = fuoptions_bgcolor;
1794     }
1796     [[MMBackend sharedInstance] setFullscreenBackgroundColor:bg];
1800     void
1801 gui_macvim_update_modified_flag()
1803     [[MMBackend sharedInstance] updateModifiedFlag];
1807  * Add search pattern 'pat' to the OS X find pasteboard.  This allows other
1808  * apps access the last pattern searched for (hitting <D-g> in another app will
1809  * initiate a search for the same pattern).
1810  */
1811     void
1812 gui_macvim_add_to_find_pboard(char_u *pat)
1814     if (!pat) return;
1816 #ifdef FEAT_MBYTE
1817     pat = CONVERT_TO_UTF8(pat);
1818 #endif
1819     NSString *s = [NSString stringWithUTF8String:(char*)pat];
1820 #ifdef FEAT_MBYTE
1821     CONVERT_TO_UTF8_FREE(pat);
1822 #endif
1824     if (!s) return;
1826     NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
1827     NSArray *supportedTypes = [NSArray arrayWithObjects:VimFindPboardType,
1828             NSStringPboardType, nil];
1829     [pb declareTypes:supportedTypes owner:nil];
1831     // Put two entries on the Find pasteboard:
1832     //   * the pattern Vim uses
1833     //   * same as above but with some backslash escaped characters removed
1834     // The second entry will be used by other applications when taking entries
1835     // off the Find pasteboard, whereas MacVim will use the first if present.
1836     [pb setString:s forType:VimFindPboardType];
1837     [pb setString:[s stringByRemovingFindPatterns] forType:NSStringPboardType];
1840     void
1841 gui_macvim_set_antialias(int antialias)
1843     [[MMBackend sharedInstance] setAntialias:antialias];
1847     void
1848 gui_macvim_wait_for_startup()
1850     MMBackend *backend = [MMBackend sharedInstance];
1851     if ([backend waitForAck])
1852         [backend waitForConnectionAcknowledgement];
1855 void gui_macvim_get_window_layout(int *count, int *layout)
1857     if (!(count && layout)) return;
1859     // NOTE: Only set 'layout' if the backend has requested a != 0 layout, else
1860     // any command line arguments (-p/-o) would be ignored.
1861     int window_layout = [[MMBackend sharedInstance] initialWindowLayout];
1862     if (window_layout > 0 && window_layout < 4) {
1863         // The window_layout numbers must match the WIN_* defines in main.c.
1864         *count = 0;
1865         *layout = window_layout;
1866     }
1870 // -- Client/Server ---------------------------------------------------------
1872 #ifdef MAC_CLIENTSERVER
1875 // NOTE: Client/Server is only fully supported with a GUI.  Theoretically it
1876 // would be possible to make the server code work with terminal Vim, but it
1877 // would require that a run-loop is set up and checked.  This should not be
1878 // difficult to implement, simply call gui_mch_update() at opportune moments
1879 // and it will take care of the run-loop.  Another (bigger) problem with
1880 // supporting servers in terminal mode is that the server listing code talks to
1881 // MacVim (the GUI) to figure out which servers are running.
1886  * Register connection with 'name'.  The actual connection is named something
1887  * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1888  */
1889     void
1890 serverRegisterName(char_u *name)
1892 #ifdef FEAT_MBYTE
1893     name = CONVERT_TO_UTF8(name);
1894 #endif
1896     NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1897     [[MMBackend sharedInstance] registerServerWithName:svrName];
1899 #ifdef FEAT_MBYTE
1900     CONVERT_TO_UTF8_FREE(name);
1901 #endif
1906  * Send to an instance of Vim.
1907  * Returns 0 for OK, negative for an error.
1908  */
1909     int
1910 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1911         int *port, int asExpr, int silent)
1913 #ifdef FEAT_MBYTE
1914     name = CONVERT_TO_UTF8(name);
1915     cmd = CONVERT_TO_UTF8(cmd);
1916 #endif
1918     BOOL ok = [[MMBackend sharedInstance]
1919             sendToServer:[NSString stringWithUTF8String:(char*)name]
1920                   string:[NSString stringWithUTF8String:(char*)cmd]
1921                    reply:result
1922                     port:port
1923               expression:asExpr
1924                   silent:silent];
1926 #ifdef FEAT_MBYTE
1927     CONVERT_TO_UTF8_FREE(name);
1928     CONVERT_TO_UTF8_FREE(cmd);
1929 #endif
1931     return ok ? 0 : -1;
1936  * Ask MacVim for the names of all Vim servers.
1937  */
1938     char_u *
1939 serverGetVimNames(void)
1941     char_u *names = NULL;
1942     NSArray *list = [[MMBackend sharedInstance] serverList];
1944     if (list) {
1945         NSString *string = [list componentsJoinedByString:@"\n"];
1946         names = [string vimStringSave];
1947     }
1949     return names;
1954  * 'str' is a hex int representing the send port of the connection.
1955  */
1956     int
1957 serverStrToPort(char_u *str)
1959     int port = 0;
1961     sscanf((char *)str, "0x%x", &port);
1962     if (!port)
1963         EMSG2(_("E573: Invalid server id used: %s"), str);
1965     return port;
1970  * Check for replies from server with send port 'port'.
1971  * Return TRUE and a non-malloc'ed string if there is.  Else return FALSE.
1972  */
1973     int
1974 serverPeekReply(int port, char_u **str)
1976     NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1977     int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1979     if (str && len > 0) {
1980         *str = (char_u*)[reply UTF8String];
1982 #ifdef FEAT_MBYTE
1983         if (input_conv.vc_type != CONV_NONE) {
1984             char_u *s = string_convert(&input_conv, *str, &len);
1986             if (len > 0) {
1987                 // HACK! Since 's' needs to be freed we cannot simply set
1988                 // '*str = s' or memory will leak.  Instead, create a dummy
1989                 // NSData and return its 'bytes' pointer, then autorelease the
1990                 // NSData.
1991                 NSData *data = [NSData dataWithBytes:s length:len+1];
1992                 *str = (char_u*)[data bytes];
1993             }
1995             vim_free(s);
1996         }
1997 #endif
1998     }
2000     return reply != nil;
2005  * Wait for replies from server with send port 'port'.
2006  * Return 0 and the malloc'ed string when a reply is available.
2007  * Return -1 on error.
2008  */
2009     int
2010 serverReadReply(int port, char_u **str)
2012     NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
2013     if (reply && str) {
2014         *str = [reply vimStringSave];
2015         return 0;
2016     }
2018     return -1;
2023  * Send a reply string (notification) to client with port given by "serverid".
2024  * Return -1 if the window is invalid.
2025  */
2026     int
2027 serverSendReply(char_u *serverid, char_u *reply)
2029     int retval = -1;
2030     int port = serverStrToPort(serverid);
2031     if (port > 0 && reply) {
2032 #ifdef FEAT_MBYTE
2033         reply = CONVERT_TO_UTF8(reply);
2034 #endif
2035         BOOL ok = [[MMBackend sharedInstance]
2036                 sendReply:[NSString stringWithUTF8String:(char*)reply]
2037                    toPort:port];
2038         retval = ok ? 0 : -1;
2039 #ifdef FEAT_MBYTE
2040         CONVERT_TO_UTF8_FREE(reply);
2041 #endif
2042     }
2044     return retval;
2047 #endif // MAC_CLIENTSERVER
2052 // -- ODB Editor Support ----------------------------------------------------
2054 #ifdef FEAT_ODB_EDITOR
2056  * The ODB Editor protocol works like this:
2057  * - An external program (the server) asks MacVim to open a file and associates
2058  *   three things with this file: (1) a server id (a four character code that
2059  *   identifies the server), (2) a path that can be used as window title for
2060  *   the file (optional), (3) an arbitrary token (optional)
2061  * - When a file is saved or closed, MacVim should tell the server about which
2062  *   file was modified and also pass back the token
2064  * All communication between MacVim and the server goes via Apple Events.
2065  */
2067     static int16_t
2068 odb_event(buf_T *buf, const AEEventID action)
2070     if (!(buf->b_odb_server_id && buf->b_ffname))
2071         return noErr;
2073     NSAppleEventDescriptor *targetDesc = [NSAppleEventDescriptor
2074             descriptorWithDescriptorType:typeApplSignature
2075                                    bytes:&buf->b_odb_server_id
2076                                   length:sizeof(uint32_t)];
2078     // TODO: Convert b_ffname to UTF-8?
2079     NSString *path = [NSString stringWithUTF8String:(char*)buf->b_ffname];
2080     NSData *pathData = [[[NSURL fileURLWithPath:path] absoluteString]
2081             dataUsingEncoding:NSUTF8StringEncoding];
2082     NSAppleEventDescriptor *pathDesc = [NSAppleEventDescriptor
2083             descriptorWithDescriptorType:typeFileURL data:pathData];
2085     NSAppleEventDescriptor *event = [NSAppleEventDescriptor
2086             appleEventWithEventClass:kODBEditorSuite
2087                              eventID:action
2088                     targetDescriptor:targetDesc
2089                             returnID:kAutoGenerateReturnID
2090                        transactionID:kAnyTransactionID];
2092     [event setParamDescriptor:pathDesc forKeyword:keyDirectObject];
2094     if (buf->b_odb_token)
2095         [event setParamDescriptor:buf->b_odb_token forKeyword:keySenderToken];
2097     return AESendMessage([event aeDesc], NULL, kAENoReply | kAENeverInteract,
2098             kAEDefaultTimeout);
2101     int16_t
2102 odb_buffer_close(buf_T *buf)
2104     int16_t err = noErr;
2105     if (buf) {
2106         err = odb_event(buf, kAEClosedFile);
2108         buf->b_odb_server_id = 0;
2110         if (buf->b_odb_token) {
2111             [(NSAppleEventDescriptor *)(buf->b_odb_token) release];
2112             buf->b_odb_token = NULL;
2113         }
2115         if (buf->b_odb_fname) {
2116             vim_free(buf->b_odb_fname);
2117             buf->b_odb_fname = NULL;
2118         }
2119     }
2121     return err;
2124     int16_t
2125 odb_post_buffer_write(buf_T *buf)
2127     return buf ? odb_event(buf, kAEModifiedFile) : noErr;
2130     void
2131 odb_end(void)
2133     buf_T *buf;
2134     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2135         odb_buffer_close(buf);
2138 #endif // FEAT_ODB_EDITOR
2141     char_u *
2142 get_macaction_name(expand_T *xp, int idx)
2144     static char_u *str = NULL;
2145     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
2147     if (nil == actionDict || idx < 0 || idx >= [actionDict count])
2148         return NULL;
2150     NSString *string = [[actionDict allKeys] objectAtIndex:idx];
2151     if (!string)
2152         return NULL;
2154     char_u *plainStr = (char_u*)[string UTF8String];
2156 #ifdef FEAT_MBYTE
2157     if (str) {
2158         vim_free(str);
2159         str = NULL;
2160     }
2161     if (input_conv.vc_type != CONV_NONE) {
2162         int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
2163         str = string_convert(&input_conv, plainStr, &len);
2164         plainStr = str;
2165     }
2166 #endif
2168     return plainStr;
2172     int
2173 is_valid_macaction(char_u *action)
2175     int isValid = NO;
2176     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
2177     if (actionDict) {
2178 #ifdef FEAT_MBYTE
2179         action = CONVERT_TO_UTF8(action);
2180 #endif
2181         NSString *string = [NSString stringWithUTF8String:(char*)action];
2182         isValid = (nil != [actionDict objectForKey:string]);
2183 #ifdef FEAT_MBYTE
2184         CONVERT_TO_UTF8_FREE(action);
2185 #endif
2186     }
2188     return isValid;
2191 static int specialKeyToNSKey(int key)
2193     if (!IS_SPECIAL(key))
2194         return key;
2196     static struct {
2197         int special;
2198         int nskey;
2199     } sp2ns[] = {
2200         { K_UP, NSUpArrowFunctionKey },
2201         { K_DOWN, NSDownArrowFunctionKey },
2202         { K_LEFT, NSLeftArrowFunctionKey },
2203         { K_RIGHT, NSRightArrowFunctionKey },
2204         { K_F1, NSF1FunctionKey },
2205         { K_F2, NSF2FunctionKey },
2206         { K_F3, NSF3FunctionKey },
2207         { K_F4, NSF4FunctionKey },
2208         { K_F5, NSF5FunctionKey },
2209         { K_F6, NSF6FunctionKey },
2210         { K_F7, NSF7FunctionKey },
2211         { K_F8, NSF8FunctionKey },
2212         { K_F9, NSF9FunctionKey },
2213         { K_F10, NSF10FunctionKey },
2214         { K_F11, NSF11FunctionKey },
2215         { K_F12, NSF12FunctionKey },
2216         { K_F13, NSF13FunctionKey },
2217         { K_F14, NSF14FunctionKey },
2218         { K_F15, NSF15FunctionKey },
2219         { K_F16, NSF16FunctionKey },
2220         { K_F17, NSF17FunctionKey },
2221         { K_F18, NSF18FunctionKey },
2222         { K_F19, NSF19FunctionKey },
2223         { K_F20, NSF20FunctionKey },
2224         { K_F21, NSF21FunctionKey },
2225         { K_F22, NSF22FunctionKey },
2226         { K_F23, NSF23FunctionKey },
2227         { K_F24, NSF24FunctionKey },
2228         { K_F25, NSF25FunctionKey },
2229         { K_F26, NSF26FunctionKey },
2230         { K_F27, NSF27FunctionKey },
2231         { K_F28, NSF28FunctionKey },
2232         { K_F29, NSF29FunctionKey },
2233         { K_F30, NSF30FunctionKey },
2234         { K_F31, NSF31FunctionKey },
2235         { K_F32, NSF32FunctionKey },
2236         { K_F33, NSF33FunctionKey },
2237         { K_F34, NSF34FunctionKey },
2238         { K_F35, NSF35FunctionKey },
2239         { K_DEL, NSBackspaceCharacter },
2240         { K_BS, NSDeleteCharacter },
2241         { K_HOME, NSHomeFunctionKey },
2242         { K_END, NSEndFunctionKey },
2243         { K_PAGEUP, NSPageUpFunctionKey },
2244         { K_PAGEDOWN, NSPageDownFunctionKey }
2245     };
2247     int i;
2248     for (i = 0; i < sizeof(sp2ns)/sizeof(sp2ns[0]); ++i) {
2249         if (sp2ns[i].special == key)
2250             return sp2ns[i].nskey;
2251     }
2253     return 0;
2256 static int vimModMaskToEventModifierFlags(int mods)
2258     int flags = 0;
2260     if (mods & MOD_MASK_SHIFT)
2261         flags |= NSShiftKeyMask;
2262     if (mods & MOD_MASK_CTRL)
2263         flags |= NSControlKeyMask;
2264     if (mods & MOD_MASK_ALT)
2265         flags |= NSAlternateKeyMask;
2266     if (mods & MOD_MASK_CMD)
2267         flags |= NSCommandKeyMask;
2269     return flags;
2274 // -- NetBeans Support ------------------------------------------------------
2276 #ifdef FEAT_NETBEANS_INTG
2278 /* Set NetBeans socket to CFRunLoop */
2279     void
2280 gui_macvim_set_netbeans_socket(int socket)
2282     [[MMBackend sharedInstance] setNetbeansSocket:socket];
2285 #endif // FEAT_NETBEANS_INTG