Add "show hidden files" checkbox to save dialog
[MacVim.git] / src / MacVim / gui_macvim.m
blob5ae2722bb6a01a2c5190444ca37c56ff68c27518
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;
30 static GuiFont gui_macvim_font_with_name(char_u *name);
31 static int specialKeyToNSKey(int key);
32 static int vimModMaskToEventModifierFlags(int mods);
34 NSArray *descriptor_for_menu(vimmenu_T *menu);
35 vimmenu_T *menu_for_descriptor(NSArray *desc);
39 // -- Initialization --------------------------------------------------------
42  * Parse the GUI related command-line arguments.  Any arguments used are
43  * deleted from argv, and *argc is decremented accordingly.  This is called
44  * when vim is started, whether or not the GUI has been started.
45  */
46     void
47 gui_mch_prepare(int *argc, char **argv)
49     //NSLog(@"gui_mch_prepare(argc=%d)", *argc);
51     // Set environment variables $VIM and $VIMRUNTIME
52     // NOTE!  If vim_getenv is called with one of these as parameters before
53     // they have been set here, they will most likely end up with the wrong
54     // values!
55     //
56     // TODO:
57     // - ensure this is called first to avoid above problem
58     // - encoding
60     NSString *path = [[[NSBundle mainBundle] resourcePath]
61         stringByAppendingPathComponent:@"vim"];
62     vim_setenv((char_u*)"VIM", (char_u*)[path UTF8String]);
64     path = [path stringByAppendingPathComponent:@"runtime"];
65     vim_setenv((char_u*)"VIMRUNTIME", (char_u*)[path UTF8String]);
67     int i;
68     for (i = 0; i < *argc; ++i) {
69         if (strncmp(argv[i], "--mmwaitforack", 14) == 0) {
70             [[MMBackend sharedInstance] setWaitForAck:YES];
71             --*argc;
72             if (*argc > i)
73                 mch_memmove(&argv[i], &argv[i+1], (*argc-i) * sizeof(char*));
74             break;
75         }
76     }
81  * Check if the GUI can be started.  Called before gvimrc is sourced.
82  * Return OK or FAIL.
83  */
84     int
85 gui_mch_init_check(void)
87     //NSLog(@"gui_mch_init_check()");
88     return OK;
93  * Initialise the GUI.  Create all the windows, set up all the call-backs etc.
94  * Returns OK for success, FAIL when the GUI can't be started.
95  */
96     int
97 gui_mch_init(void)
99     //NSLog(@"gui_mch_init()");
101     if (![[MMBackend sharedInstance] checkin]) {
102         // TODO: Kill the process if there is no terminal to fall back on,
103         // otherwise the process will run outputting to the console.
104         return FAIL;
105     }
107     // Force 'termencoding' to utf-8 (changes to 'tenc' are disallowed in
108     // 'option.c', so that ':set termencoding=...' is impossible).
109     set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
111     // Set values so that pixels and characters are in one-to-one
112     // correspondence (assuming all characters have the same dimensions).
113     gui.scrollbar_width = gui.scrollbar_height = 0;
115     gui.char_height = 1;
116     gui.char_width = 1;
117     gui.char_ascent = 0;
119     gui_mch_def_colors();
121     [[MMBackend sharedInstance]
122         setDefaultColorsBackground:gui.back_pixel foreground:gui.norm_pixel];
123     [[MMBackend sharedInstance] setBackgroundColor:gui.back_pixel];
124     [[MMBackend sharedInstance] setForegroundColor:gui.norm_pixel];
126     // NOTE: If this call is left out the cursor is opaque.
127     highlight_gui_started();
129     // Ensure 'linespace' option is passed along to MacVim in case it was set
130     // in [g]vimrc.
131     gui_mch_adjust_charheight();
133     return OK;
138     void
139 gui_mch_exit(int rc)
141     //NSLog(@"gui_mch_exit(rc=%d)", rc);
143     [[MMBackend sharedInstance] exit];
148  * Open the GUI window which was created by a call to gui_mch_init().
149  */
150     int
151 gui_mch_open(void)
153     return [[MMBackend sharedInstance] openGUIWindow];
157 // -- Updating --------------------------------------------------------------
161  * Catch up with any queued X events.  This may put keyboard input into the
162  * input buffer, call resize call-backs, trigger timers etc.  If there is
163  * nothing in the X event queue (& no timers pending), then we return
164  * immediately.
165  */
166     void
167 gui_mch_update(void)
169     // This function is called extremely often.  It is tempting to do nothing
170     // here to avoid reduced frame-rates but then it would not be possible to
171     // interrupt Vim by presssing Ctrl-C during lengthy operations (e.g. after
172     // entering "10gs" it would not be possible to bring Vim out of the 10 s
173     // sleep prematurely).  As a compromise we check for Ctrl-C only once per
174     // second.  Note that Cmd-. sends SIGINT so it has higher success rate at
175     // interrupting Vim.
176     static CFAbsoluteTime lastTime = 0;
178     CFAbsoluteTime nowTime = CFAbsoluteTimeGetCurrent();
179     if (nowTime - lastTime > 1.0) {
180         [[MMBackend sharedInstance] update];
181         lastTime = nowTime;
182     }
186 /* Flush any output to the screen */
187     void
188 gui_mch_flush(void)
190     // This function is called way too often to be useful as a hint for
191     // flushing.  If we were to flush every time it was called the screen would
192     // flicker.
196     void
197 gui_macvim_flush(void)
199     // This function counts how many times it is called and only flushes the
200     // draw queue if called sufficiently often.  The first few times it is
201     // called it will flush often, but the more it is called the less likely is
202     // it that anything will be flushed.  (The counter resets itself if the
203     // function isn't called for a second.)
204     //
205     // NOTE: Should only be used in loops where it is impossible to know how
206     // often Vim needs to flush.  It was written to handle output from external
207     // commands (see mch_call_shell() in os_unix.c).
209     static CFAbsoluteTime lastTime = 0;
210     static int delay = 1;
211     static int counter = 0;
212     static int scrolls = 0;
214     CFAbsoluteTime nowTime = CFAbsoluteTimeGetCurrent();
215     CFAbsoluteTime delta = nowTime - lastTime;
216     if (delta > 1.0)
217         delay = 1;
219     // We assume that each call corresponds roughly to one line of output.
220     // When one page has scrolled by we increase the delay before the next
221     // flush.
222     if (++scrolls > gui.num_rows) {
223         delay <<= 1;
224         if (delay > 2048)
225             delay = 2048;
226         scrolls = 0;
227     }
229     if (++counter > delay) {
230         gui_macvim_force_flush();
231         counter = 0;
232     }
234     lastTime = nowTime;
238 /* Force flush output to MacVim.  Do not call this method unless absolutely
239  * necessary. */
240     void
241 gui_macvim_force_flush(void)
243     [[MMBackend sharedInstance] flushQueue:YES];
248  * GUI input routine called by gui_wait_for_chars().  Waits for a character
249  * from the keyboard.
250  *  wtime == -1     Wait forever.
251  *  wtime == 0      This should never happen.
252  *  wtime > 0       Wait wtime milliseconds for a character.
253  * Returns OK if a character was found to be available within the given time,
254  * or FAIL otherwise.
255  */
256     int
257 gui_mch_wait_for_chars(int wtime)
259     // NOTE! In all likelihood Vim will take a nap when waitForInput: is
260     // called, so force a flush of the command queue here.
261     [[MMBackend sharedInstance] flushQueue:YES];
263     return [[MMBackend sharedInstance] waitForInput:wtime];
267 // -- Drawing ---------------------------------------------------------------
271  * Clear the whole text window.
272  */
273     void
274 gui_mch_clear_all(void)
276     [[MMBackend sharedInstance] clearAll];
281  * Clear a rectangular region of the screen from text pos (row1, col1) to
282  * (row2, col2) inclusive.
283  */
284     void
285 gui_mch_clear_block(int row1, int col1, int row2, int col2)
287     [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
288                                                     toRow:row2 column:col2];
293  * Delete the given number of lines from the given row, scrolling up any
294  * text further down within the scroll region.
295  */
296     void
297 gui_mch_delete_lines(int row, int num_lines)
299     [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
300             scrollBottom:gui.scroll_region_bot
301                     left:gui.scroll_region_left
302                    right:gui.scroll_region_right];
306     void
307 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
309 #ifdef FEAT_MBYTE
310     char_u *conv_str = NULL;
311     if (output_conv.vc_type != CONV_NONE) {
312         conv_str = string_convert(&output_conv, s, &len);
313         if (conv_str)
314             s = conv_str;
315     }
316 #endif
318     [[MMBackend sharedInstance] drawString:(char*)s length:len row:row
319                                     column:col cells:len flags:flags];
321 #ifdef FEAT_MBYTE
322     if (conv_str)
323         vim_free(conv_str);
324 #endif
328     int
329 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
331     int c, cn, cl, i;
332     int start = 0;
333     int endcol = col;
334     int startcol = col;
335     BOOL wide = NO;
336     MMBackend *backend = [MMBackend sharedInstance];
337 #ifdef FEAT_MBYTE
338     char_u *conv_str = NULL;
340     if (output_conv.vc_type != CONV_NONE) {
341         conv_str = string_convert(&output_conv, s, &len);
342         if (conv_str)
343             s = conv_str;
344     }
345 #endif
347     // Loop over each character and output text when it changes from normal to
348     // wide and vice versa.
349     for (i = 0; i < len; i += cl) {
350         c = utf_ptr2char(s + i);
351         cn = utf_char2cells(c);
352         cl = utf_ptr2len(s + i);
353         if (0 == cl)
354             len = i;    // len must be wrong (shouldn't happen)
356         if (!utf_iscomposing(c)) {
357             if ((cn > 1 && !wide) || (cn <= 1 && wide)) {
358                 // Changed from normal to wide or vice versa.
359                 [backend drawString:(char*)(s+start) length:i-start
360                                    row:row column:startcol
361                                  cells:endcol-startcol
362                                  flags:(wide ? flags|DRAW_WIDE : flags)];
364                 start = i;
365                 startcol = endcol;
366             }
368             wide = cn > 1;
369             endcol += cn;
370         }
371     }
373     // Output remaining characters.
374     [backend drawString:(char*)(s+start) length:len-start
375                     row:row column:startcol cells:endcol-startcol
376                   flags:(wide ? flags|DRAW_WIDE : flags)];
378 #ifdef FEAT_MBYTE
379     if (conv_str)
380         vim_free(conv_str);
381 #endif
383     return endcol - col;
388  * Insert the given number of lines before the given row, scrolling down any
389  * following text within the scroll region.
390  */
391     void
392 gui_mch_insert_lines(int row, int num_lines)
394     [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
395             scrollBottom:gui.scroll_region_bot
396                     left:gui.scroll_region_left
397                    right:gui.scroll_region_right];
402  * Set the current text foreground color.
403  */
404     void
405 gui_mch_set_fg_color(guicolor_T color)
407     [[MMBackend sharedInstance] setForegroundColor:color];
412  * Set the current text background color.
413  */
414     void
415 gui_mch_set_bg_color(guicolor_T color)
417     [[MMBackend sharedInstance] setBackgroundColor:color];
422  * Set the current text special color (used for underlines).
423  */
424     void
425 gui_mch_set_sp_color(guicolor_T color)
427     [[MMBackend sharedInstance] setSpecialColor:color];
432  * Set default colors.
433  */
434     void
435 gui_mch_def_colors()
437     MMBackend *backend = [MMBackend sharedInstance];
439     // The default colors are taken from system values
440     gui.def_norm_pixel = gui.norm_pixel = 
441         [backend lookupColorWithKey:@"MacTextColor"];
442     gui.def_back_pixel = gui.back_pixel = 
443         [backend lookupColorWithKey:@"MacTextBackgroundColor"];
448  * Called when the foreground or background color has been changed.
449  */
450     void
451 gui_mch_new_colors(void)
453     gui.def_back_pixel = gui.back_pixel;
454     gui.def_norm_pixel = gui.norm_pixel;
456     //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
457     //        gui.def_norm_pixel);
459     [[MMBackend sharedInstance]
460         setDefaultColorsBackground:gui.def_back_pixel
461                         foreground:gui.def_norm_pixel];
465  * Invert a rectangle from row r, column c, for nr rows and nc columns.
466  */
467     void
468 gui_mch_invert_rectangle(int r, int c, int nr, int nc, int invert)
470     [[MMBackend sharedInstance] drawInvertedRectAtRow:r column:c numRows:nr
471             numColumns:nc invert:invert];
476 // -- Tabline ---------------------------------------------------------------
480  * Set the current tab to "nr".  First tab is 1.
481  */
482     void
483 gui_mch_set_curtab(int nr)
485     [[MMBackend sharedInstance] selectTab:nr];
490  * Return TRUE when tabline is displayed.
491  */
492     int
493 gui_mch_showing_tabline(void)
495     return [[MMBackend sharedInstance] tabBarVisible];
499  * Update the labels of the tabline.
500  */
501     void
502 gui_mch_update_tabline(void)
504     [[MMBackend sharedInstance] updateTabBar];
508  * Show or hide the tabline.
509  */
510     void
511 gui_mch_show_tabline(int showit)
513     [[MMBackend sharedInstance] showTabBar:showit];
517 // -- Clipboard -------------------------------------------------------------
520     void
521 clip_mch_lose_selection(VimClipboard *cbd)
526     int
527 clip_mch_own_selection(VimClipboard *cbd)
529     return 0;
533     void
534 clip_mch_request_selection(VimClipboard *cbd)
536     NSPasteboard *pb = [NSPasteboard generalPasteboard];
537     NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
538             NSStringPboardType, nil];
539     NSString *bestType = [pb availableTypeFromArray:supportedTypes];
540     if (!bestType) return;
542     int motion_type = MCHAR;
543     NSString *string = nil;
545     if ([bestType isEqual:VimPBoardType]) {
546         // This type should consist of an array with two objects:
547         //   1. motion type (NSNumber)
548         //   2. text (NSString)
549         // If this is not the case we fall back on using NSStringPboardType.
550         id plist = [pb propertyListForType:VimPBoardType];
551         if ([plist isKindOfClass:[NSArray class]] && [plist count] == 2) {
552             id obj = [plist objectAtIndex:1];
553             if ([obj isKindOfClass:[NSString class]]) {
554                 motion_type = [[plist objectAtIndex:0] intValue];
555                 string = obj;
556             }
557         }
558     }
560     if (!string) {
561         // Use NSStringPboardType.  The motion type is set to line-wise if the
562         // string contains at least one EOL character, otherwise it is set to
563         // character-wise (block-wise is never used).
564         NSMutableString *mstring =
565                 [[pb stringForType:NSStringPboardType] mutableCopy];
566         if (!mstring) return;
568         // Replace unrecognized end-of-line sequences with \x0a (line feed).
569         NSRange range = { 0, [mstring length] };
570         unsigned n = [mstring replaceOccurrencesOfString:@"\x0d\x0a"
571                                              withString:@"\x0a" options:0
572                                                   range:range];
573         if (0 == n) {
574             n = [mstring replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
575                                            options:0 range:range];
576         }
577         
578         // Scan for newline character to decide whether the string should be
579         // pasted line-wise or character-wise.
580         motion_type = MCHAR;
581         if (0 < n || NSNotFound != [mstring rangeOfString:@"\n"].location)
582             motion_type = MLINE;
584         string = mstring;
585     }
587     if (!(MCHAR == motion_type || MLINE == motion_type || MBLOCK == motion_type
588             || MAUTO == motion_type))
589         motion_type = MCHAR;
591     char_u *str = (char_u*)[string UTF8String];
592     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
594 #ifdef FEAT_MBYTE
595     if (input_conv.vc_type != CONV_NONE)
596         str = string_convert(&input_conv, str, &len);
597 #endif
599     if (str)
600         clip_yank_selection(motion_type, str, len, cbd);
602 #ifdef FEAT_MBYTE
603     if (input_conv.vc_type != CONV_NONE)
604         vim_free(str);
605 #endif
610  * Send the current selection to the clipboard.
611  */
612     void
613 clip_mch_set_selection(VimClipboard *cbd)
615     // If the '*' register isn't already filled in, fill it in now.
616     cbd->owned = TRUE;
617     clip_get_selection(cbd);
618     cbd->owned = FALSE;
619     
620     // Get the text to put on the pasteboard.
621     long_u llen = 0; char_u *str = 0;
622     int motion_type = clip_convert_selection(&str, &llen, cbd);
623     if (motion_type < 0)
624         return;
626     // TODO: Avoid overflow.
627     int len = (int)llen;
628 #ifdef FEAT_MBYTE
629     if (output_conv.vc_type != CONV_NONE) {
630         char_u *conv_str = string_convert(&output_conv, str, &len);
631         if (conv_str) {
632             vim_free(str);
633             str = conv_str;
634         }
635     }
636 #endif
638     if (len > 0) {
639         NSString *string = [[NSString alloc]
640             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
642         // See clip_mch_request_selection() for info on pasteboard types.
643         NSPasteboard *pb = [NSPasteboard generalPasteboard];
644         NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
645                 NSStringPboardType, nil];
646         [pb declareTypes:supportedTypes owner:nil];
648         NSNumber *motion = [NSNumber numberWithInt:motion_type];
649         NSArray *plist = [NSArray arrayWithObjects:motion, string, nil];
650         [pb setPropertyList:plist forType:VimPBoardType];
652         [pb setString:string forType:NSStringPboardType];
653         
654         [string release];
655     }
657     vim_free(str);
661 // -- Menu ------------------------------------------------------------------
665  * A menu descriptor represents the "address" of a menu as an array of strings.
666  * E.g. the menu "File->Close" has descriptor { "File", "Close" }.
667  */
668     NSArray *
669 descriptor_for_menu(vimmenu_T *menu)
671     if (!menu) return nil;
673     NSMutableArray *desc = [NSMutableArray array];
674     while (menu) {
675         NSString *name = [NSString stringWithVimString:menu->dname];
676         [desc insertObject:name atIndex:0];
677         menu = menu->parent;
678     }
680     return desc;
683     vimmenu_T *
684 menu_for_descriptor(NSArray *desc)
686     if (!(desc && [desc count] > 0)) return NULL;
688     vimmenu_T *menu = root_menu;
689     int i, count = [desc count];
691     for (i = 0; i < count; ++i) {
692         NSString *component = [desc objectAtIndex:i];
693         while (menu) {
694             NSString *name = [NSString stringWithVimString:menu->dname];
695             if ([component isEqual:name]) {
696                 if (i+1 == count)
697                     return menu;    // Matched all components, so return menu
698                 menu = menu->children;
699                 break;
700             }
701             menu = menu->next;
702         }
703     }
705     return NULL;
709  * Add a submenu to the menu bar, toolbar, or a popup menu.
710  */
711     void
712 gui_mch_add_menu(vimmenu_T *menu, int idx)
714     NSArray *desc = descriptor_for_menu(menu);
715     [[MMBackend sharedInstance] queueMessage:AddMenuMsgID properties:
716         [NSDictionary dictionaryWithObjectsAndKeys:
717             desc, @"descriptor",
718             [NSNumber numberWithInt:idx], @"index",
719             nil]];
723 // Taken from gui_gtk.c (slightly modified)
724     static int
725 lookup_menu_iconfile(char_u *iconfile, char_u *dest)
727     expand_env(iconfile, dest, MAXPATHL);
729     if (mch_isFullName(dest))
730         return vim_fexists(dest);
732     static const char   suffixes[][4] = {"png", "bmp"};
733     char_u              buf[MAXPATHL];
734     unsigned int        i;
736     for (i = 0; i < sizeof(suffixes)/sizeof(suffixes[0]); ++i)
737         if (gui_find_bitmap(dest, buf, (char *)suffixes[i]) == OK) {
738             STRCPY(dest, buf);
739             return TRUE;
740         }
742     return FALSE;
747  * Add a menu item to a menu
748  */
749     void
750 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
752     char_u *tip = menu->strings[MENU_INDEX_TIP]
753             ? menu->strings[MENU_INDEX_TIP] : menu->actext;
754     NSArray *desc = descriptor_for_menu(menu);
755     NSString *keyEquivalent = menu->mac_key
756         ? [NSString stringWithFormat:@"%C", specialKeyToNSKey(menu->mac_key)]
757         : [NSString string];
758     int modifierMask = vimModMaskToEventModifierFlags(menu->mac_mods);
759     char_u *icon = NULL;
761     if (menu_is_toolbar(menu->parent->name)) {
762         char_u fname[MAXPATHL];
764         // Try to use the icon=.. argument
765         if (menu->iconfile && lookup_menu_iconfile(menu->iconfile, fname))
766             icon = fname;
768         // If not found and not builtin specified try using the menu name
769         if (!icon && !menu->icon_builtin
770                                     && lookup_menu_iconfile(menu->name, fname))
771             icon = fname;
773         // Last resort, use display name (usually signals a builtin icon)
774         if (!icon)
775             icon = menu->dname;
776     }
778     [[MMBackend sharedInstance] queueMessage:AddMenuItemMsgID properties:
779         [NSDictionary dictionaryWithObjectsAndKeys:
780             desc, @"descriptor",
781             [NSNumber numberWithInt:idx], @"index",
782             [NSString stringWithVimString:tip], @"tip",
783             [NSString stringWithVimString:icon], @"icon",
784             keyEquivalent, @"keyEquivalent",
785             [NSNumber numberWithInt:modifierMask], @"modifierMask",
786             [NSString stringWithVimString:menu->mac_action], @"action",
787             [NSNumber numberWithBool:menu->mac_alternate], @"isAlternate",
788             nil]];
793  * Destroy the machine specific menu widget.
794  */
795     void
796 gui_mch_destroy_menu(vimmenu_T *menu)
798     NSArray *desc = descriptor_for_menu(menu);
799     [[MMBackend sharedInstance] queueMessage:RemoveMenuItemMsgID properties:
800         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
805  * Make a menu either grey or not grey.
806  */
807     void
808 gui_mch_menu_grey(vimmenu_T *menu, int grey)
810     /* Only update menu if the 'grey' state has changed to avoid having to pass
811      * lots of unnecessary data to MacVim.  (Skipping this test makes MacVim
812      * pause noticably on mode changes. */
813     NSArray *desc = descriptor_for_menu(menu);
814     if (menu->was_grey == grey)
815         return;
817     menu->was_grey = grey;
819     [[MMBackend sharedInstance] queueMessage:EnableMenuItemMsgID properties:
820         [NSDictionary dictionaryWithObjectsAndKeys:
821             desc, @"descriptor",
822             [NSNumber numberWithInt:!grey], @"enable",
823             nil]];
828  * Make menu item hidden or not hidden
829  */
830     void
831 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
833     // HACK! There is no (obvious) way to hide a menu item, so simply
834     // enable/disable it instead.
835     gui_mch_menu_grey(menu, hidden);
840  * This is called when user right clicks.
841  */
842     void
843 gui_mch_show_popupmenu(vimmenu_T *menu)
845     NSArray *desc = descriptor_for_menu(menu);
846     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:
847         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
852  * This is called when a :popup command is executed.
853  */
854     void
855 gui_make_popup(char_u *path_name, int mouse_pos)
857     vimmenu_T *menu = gui_find_menu(path_name);
858     if (!(menu && menu->children)) return;
860     NSArray *desc = descriptor_for_menu(menu);
861     NSDictionary *p = (mouse_pos || NULL == curwin)
862         ? [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]
863         : [NSDictionary dictionaryWithObjectsAndKeys:
864             desc, @"descriptor",
865             [NSNumber numberWithInt:curwin->w_wrow], @"row",
866             [NSNumber numberWithInt:curwin->w_wcol], @"column",
867             nil];
869     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:p];
874  * This is called after setting all the menus to grey/hidden or not.
875  */
876     void
877 gui_mch_draw_menubar(void)
879     // The (main) menu draws itself in Mac OS X.
883     void
884 gui_mch_enable_menu(int flag)
886     // The (main) menu is always enabled in Mac OS X.
890 #if 0
891     void
892 gui_mch_set_menu_pos(int x, int y, int w, int h)
894     // The (main) menu cannot be moved in Mac OS X.
896 #endif
899     void
900 gui_mch_show_toolbar(int showit)
902     int flags = 0;
903     if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
904     if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
905     if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
907     [[MMBackend sharedInstance] showToolbar:showit flags:flags];
913 // -- Fonts -----------------------------------------------------------------
917  * If a font is not going to be used, free its structure.
918  */
919     void
920 gui_mch_free_font(font)
921     GuiFont     font;
923     if (font != NOFONT) {
924         //NSLog(@"gui_mch_free_font(font=0x%x)", font);
925         [(id)font release];
926     }
930     GuiFont
931 gui_mch_retain_font(GuiFont font)
933     return (GuiFont)[(id)font retain];
938  * Get a font structure for highlighting.
939  */
940     GuiFont
941 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
943     //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
944     //        giveErrorIfMissing);
946     GuiFont font = gui_macvim_font_with_name(name);
947     if (font != NOFONT)
948         return font;
950     if (giveErrorIfMissing)
951         EMSG2(_(e_font), name);
953     return NOFONT;
957 #if defined(FEAT_EVAL) || defined(PROTO)
959  * Return the name of font "font" in allocated memory.
960  * TODO: use 'font' instead of 'name'?
961  */
962     char_u *
963 gui_mch_get_fontname(GuiFont font, char_u *name)
965     return name ? vim_strsave(name) : NULL;
967 #endif
971  * Initialise vim to use the font with the given name.  Return FAIL if the font
972  * could not be loaded, OK otherwise.
973  */
974     int
975 gui_mch_init_font(char_u *font_name, int fontset)
977     //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
979     if (font_name && STRCMP(font_name, "*") == 0) {
980         // :set gfn=* shows the font panel.
981         do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
982         return FAIL;
983     }
985     GuiFont font = gui_macvim_font_with_name(font_name);
986     if (font == NOFONT)
987         return FAIL;
989     gui_mch_free_font(gui.norm_font);
990     gui.norm_font = font;
992     // NOTE: MacVim keeps separate track of the normal and wide fonts.
993     // Unless the user changes 'guifontwide' manually, they are based on
994     // the same (normal) font.  Also note that each time the normal font is
995     // set, the advancement may change so the wide font needs to be updated
996     // as well (so that it is always twice the width of the normal font).
997     [[MMBackend sharedInstance] setFont:font wide:NO];
998     [[MMBackend sharedInstance] setFont:(NOFONT != gui.wide_font ? gui.wide_font
999                                                                  : font)
1000                                    wide:YES];
1002     return OK;
1007  * Set the current text font.
1008  */
1009     void
1010 gui_mch_set_font(GuiFont font)
1012     // Font selection is done inside MacVim...nothing here to do.
1017  * Return GuiFont in allocated memory.  The caller must free it using
1018  * gui_mch_free_font().
1019  */
1020     GuiFont
1021 gui_macvim_font_with_name(char_u *name)
1023     if (!name)
1024         return (GuiFont)[[NSString alloc] initWithFormat:@"%@:%d",
1025                                         MMDefaultFontName, MMDefaultFontSize];
1027     NSString *fontName = [NSString stringWithVimString:name];
1028     int size = MMDefaultFontSize;
1029     BOOL parseFailed = NO;
1031     NSArray *components = [fontName componentsSeparatedByString:@":"];
1032     if ([components count] == 2) {
1033         NSString *sizeString = [components lastObject];
1034         if ([sizeString length] > 0
1035                 && [sizeString characterAtIndex:0] == 'h') {
1036             sizeString = [sizeString substringFromIndex:1];
1037             if ([sizeString length] > 0) {
1038                 size = (int)round([sizeString floatValue]);
1039                 fontName = [components objectAtIndex:0];
1040             }
1041         } else {
1042             parseFailed = YES;
1043         }
1044     } else if ([components count] > 2) {
1045         parseFailed = YES;
1046     }
1048     if (!parseFailed) {
1049         // Replace underscores with spaces.
1050         fontName = [[fontName componentsSeparatedByString:@"_"]
1051                                  componentsJoinedByString:@" "];
1052     }
1054     if (!parseFailed && [fontName length] > 0) {
1055         if (size < MMMinFontSize) size = MMMinFontSize;
1056         if (size > MMMaxFontSize) size = MMMaxFontSize;
1058         // If the default font is requested we don't check if NSFont can load
1059         // it since the font most likely isn't loaded anyway (it may only be
1060         // available to the MacVim binary).  If it is not the default font we
1061         // ask NSFont if it can load it.
1062         if ([fontName isEqualToString:MMDefaultFontName]
1063                 || [NSFont fontWithName:fontName size:size])
1064             return [[NSString alloc] initWithFormat:@"%@:%d", fontName, size];
1065     }
1067     return NOFONT;
1070 // -- Scrollbars ------------------------------------------------------------
1073     void
1074 gui_mch_create_scrollbar(
1075         scrollbar_T *sb,
1076         int orient)     /* SBAR_VERT or SBAR_HORIZ */
1078     [[MMBackend sharedInstance] 
1079             createScrollbarWithIdentifier:sb->ident type:sb->type];
1083     void
1084 gui_mch_destroy_scrollbar(scrollbar_T *sb)
1086     [[MMBackend sharedInstance] 
1087             destroyScrollbarWithIdentifier:sb->ident];
1091     void
1092 gui_mch_enable_scrollbar(
1093         scrollbar_T     *sb,
1094         int             flag)
1096     [[MMBackend sharedInstance] 
1097             showScrollbarWithIdentifier:sb->ident state:flag];
1101     void
1102 gui_mch_set_scrollbar_pos(
1103         scrollbar_T *sb,
1104         int x,
1105         int y,
1106         int w,
1107         int h)
1109     int pos = y;
1110     int len = h;
1111     if (SBAR_BOTTOM == sb->type) {
1112         pos = x;
1113         len = w; 
1114     }
1116     [[MMBackend sharedInstance] 
1117             setScrollbarPosition:pos length:len identifier:sb->ident];
1121     void
1122 gui_mch_set_scrollbar_thumb(
1123         scrollbar_T *sb,
1124         long val,
1125         long size,
1126         long max)
1128     [[MMBackend sharedInstance] 
1129             setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
1133 // -- Cursor ----------------------------------------------------------------
1137  * Draw a cursor without focus.
1138  */
1139     void
1140 gui_mch_draw_hollow_cursor(guicolor_T color)
1142     return [[MMBackend sharedInstance]
1143         drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
1144                fraction:100 color:color];
1149  * Draw part of a cursor, only w pixels wide, and h pixels high.
1150  */
1151     void
1152 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
1154     // HACK!  'w' and 'h' are always 1 since we do not tell Vim about the exact
1155     // font dimensions.  Thus these parameters are useless.  Instead we look at
1156     // the shape_table to determine the shape and size of the cursor (just like
1157     // gui_update_cursor() does).
1159 #ifdef FEAT_RIGHTLEFT
1160     // If 'rl' is set the insert mode cursor must be drawn on the right-hand
1161     // side of a text cell.
1162     int rl = curwin ? curwin->w_p_rl : FALSE;
1163 #else
1164     int rl = FALSE;
1165 #endif
1166     int idx = get_shape_idx(FALSE);
1167     int shape = MMInsertionPointBlock;
1168     switch (shape_table[idx].shape) {
1169         case SHAPE_HOR:
1170             shape = MMInsertionPointHorizontal;
1171             break;
1172         case SHAPE_VER:
1173             shape = rl ? MMInsertionPointVerticalRight
1174                        : MMInsertionPointVertical;
1175             break;
1176     }
1178     return [[MMBackend sharedInstance]
1179         drawCursorAtRow:gui.row column:gui.col shape:shape
1180                fraction:shape_table[idx].percentage color:color];
1185  * Cursor blink functions.
1187  * This is a simple state machine:
1188  * BLINK_NONE   not blinking at all
1189  * BLINK_OFF    blinking, cursor is not shown
1190  * BLINK_ON blinking, cursor is shown
1191  */
1192     void
1193 gui_mch_set_blinking(long wait, long on, long off)
1195     [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1200  * Start the cursor blinking.  If it was already blinking, this restarts the
1201  * waiting time and shows the cursor.
1202  */
1203     void
1204 gui_mch_start_blink(void)
1206     [[MMBackend sharedInstance] startBlink];
1211  * Stop the cursor blinking.  Show the cursor if it wasn't shown.
1212  */
1213     void
1214 gui_mch_stop_blink(void)
1216     [[MMBackend sharedInstance] stopBlink];
1220 // -- Mouse -----------------------------------------------------------------
1224  * Get current mouse coordinates in text window.
1225  */
1226     void
1227 gui_mch_getmouse(int *x, int *y)
1229     //NSLog(@"gui_mch_getmouse()");
1233     void
1234 gui_mch_setmouse(int x, int y)
1236     //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1240     void
1241 mch_set_mouse_shape(int shape)
1243     [[MMBackend sharedInstance] setMouseShape:shape];
1249 // -- Input Method ----------------------------------------------------------
1251 #if defined(USE_IM_CONTROL)
1253     void
1254 im_set_position(int row, int col)
1256     // The pre-edit area is a popup window which is displayed by MMTextView.
1257     [[MMBackend sharedInstance] setPreEditRow:row column:col];
1261     void
1262 im_set_active(int active)
1264     // Set roman or the system script if 'active' is TRUE or FALSE,
1265     // respectively.
1266     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1268     if (!p_imdisable && smRoman != systemScript) {
1269         int msgid = active ? ActivateKeyScriptID : DeactivateKeyScriptID;
1270         [[MMBackend sharedInstance] queueMessage:msgid properties:nil];
1271     }
1275     int
1276 im_get_status(void)
1278     // IM is active whenever the current script is the system script and the
1279     // system script isn't roman.  (Hence IM can only be active when using
1280     // non-roman scripts.)
1281     SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
1282     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1284     return currentScript != smRoman && currentScript == systemScript;
1287 #endif // defined(USE_IM_CONTROL)
1292 // -- Find & Replace dialog -------------------------------------------------
1294 #ifdef FIND_REPLACE_DIALOG
1296     static void
1297 macvim_find_and_replace(char_u *arg, BOOL replace)
1299     // TODO: Specialized dialog for find without replace?
1300     int wholeWord = FALSE;
1301     int matchCase = !p_ic;
1302     char_u *text  = get_find_dialog_text(arg, &wholeWord, &matchCase);
1304     int flags = 0;
1305     if (wholeWord) flags |= FRD_WHOLE_WORD;
1306     if (matchCase) flags |= FRD_MATCH_CASE;
1308     NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
1309             [NSString stringWithVimString:text],    @"text",
1310             [NSNumber numberWithInt:flags],         @"flags",
1311             nil];
1313     [[MMBackend sharedInstance] queueMessage:ShowFindReplaceDialogMsgID
1314                                   properties:args];
1317     void
1318 gui_mch_find_dialog(exarg_T *eap)
1320     macvim_find_and_replace(eap->arg, NO);
1323     void
1324 gui_mch_replace_dialog(exarg_T *eap)
1326     macvim_find_and_replace(eap->arg, YES);
1329 #endif // FIND_REPLACE_DIALOG
1334 // -- Unsorted --------------------------------------------------------------
1337     void
1338 ex_macaction(eap)
1339     exarg_T     *eap;
1341     if (!gui.in_use) {
1342         EMSG(_("E???: Command only available in GUI mode"));
1343         return;
1344     }
1346     char_u *arg = eap->arg;
1347 #ifdef FEAT_MBYTE
1348     arg = CONVERT_TO_UTF8(arg);
1349 #endif
1351     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1352     NSString *name = [NSString stringWithUTF8String:(char*)arg];
1353     if (actionDict && [actionDict objectForKey:name] != nil) {
1354         [[MMBackend sharedInstance] executeActionWithName:name];
1355     } else {
1356         EMSG2(_("E???: Invalid action: %s"), eap->arg);
1357     }
1359 #ifdef FEAT_MBYTE
1360     arg = CONVERT_TO_UTF8(arg);
1361 #endif
1366  * Adjust gui.char_height (after 'linespace' was changed).
1367  */
1368     int
1369 gui_mch_adjust_charheight(void)
1371     [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1372     return OK;
1376     void
1377 gui_mch_beep(void)
1379     NSBeep();
1384 #ifdef FEAT_BROWSE
1386  * Pop open a file browser and return the file selected, in allocated memory,
1387  * or NULL if Cancel is hit.
1388  *  saving  - TRUE if the file will be saved to, FALSE if it will be opened.
1389  *  title   - Title message for the file browser dialog.
1390  *  dflt    - Default name of file.
1391  *  ext     - Default extension to be added to files without extensions.
1392  *  initdir - directory in which to open the browser (NULL = current dir)
1393  *  filter  - Filter for matched files to choose from.
1394  *  Has a format like this:
1395  *  "C Files (*.c)\0*.c\0"
1396  *  "All Files\0*.*\0\0"
1397  *  If these two strings were concatenated, then a choice of two file
1398  *  filters will be selectable to the user.  Then only matching files will
1399  *  be shown in the browser.  If NULL, the default allows all files.
1401  *  *NOTE* - the filter string must be terminated with TWO nulls.
1402  */
1403     char_u *
1404 gui_mch_browse(
1405     int saving,
1406     char_u *title,
1407     char_u *dflt,
1408     char_u *ext,
1409     char_u *initdir,
1410     char_u *filter)
1412     //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1413     //        " filter=%s", saving, title, dflt, ext, initdir, filter);
1415     // Ensure no data is on the output queue before presenting the dialog.
1416     gui_macvim_force_flush();
1418     NSMutableDictionary *attr = [NSMutableDictionary
1419         dictionaryWithObject:[NSNumber numberWithBool:saving]
1420                       forKey:@"saving"];
1421     if (initdir)
1422         [attr setObject:[NSString stringWithVimString:initdir] forKey:@"dir"];
1424     char_u *s = (char_u*)[[MMBackend sharedInstance]
1425                             browseForFileWithAttributes:attr];
1427     return s;
1429 #endif /* FEAT_BROWSE */
1433     int
1434 gui_mch_dialog(
1435     int         type,
1436     char_u      *title,
1437     char_u      *message,
1438     char_u      *buttons,
1439     int         dfltbutton,
1440     char_u      *textfield)
1442     //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1443     //        "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1444     //        dfltbutton, textfield);
1446     // Ensure no data is on the output queue before presenting the dialog.
1447     gui_macvim_force_flush();
1449     int style = NSInformationalAlertStyle;
1450     if (VIM_WARNING == type) style = NSWarningAlertStyle;
1451     else if (VIM_ERROR == type) style = NSCriticalAlertStyle;
1453     NSMutableDictionary *attr = [NSMutableDictionary
1454                         dictionaryWithObject:[NSNumber numberWithInt:style]
1455                                       forKey:@"alertStyle"];
1457     if (buttons) {
1458         // 'buttons' is a string of '\n'-separated button titles 
1459         NSString *string = [NSString stringWithVimString:buttons];
1460         NSArray *array = [string componentsSeparatedByString:@"\n"];
1461         [attr setObject:array forKey:@"buttonTitles"];
1462     }
1464     NSString *messageText = nil;
1465     if (title)
1466         messageText = [NSString stringWithVimString:title];
1468     if (message) {
1469         NSString *informativeText = [NSString stringWithVimString:message];
1470         if (!messageText) {
1471             // HACK! If there is a '\n\n' or '\n' sequence in the message, then
1472             // make the part up to there into the title.  We only do this
1473             // because Vim has lots of dialogs without a title and they look
1474             // ugly that way.
1475             // TODO: Fix the actual dialog texts.
1476             NSRange eolRange = [informativeText rangeOfString:@"\n\n"];
1477             if (NSNotFound == eolRange.location)
1478                 eolRange = [informativeText rangeOfString:@"\n"];
1479             if (NSNotFound != eolRange.location) {
1480                 messageText = [informativeText substringToIndex:
1481                                                         eolRange.location];
1482                 informativeText = [informativeText substringFromIndex:
1483                                                         NSMaxRange(eolRange)];
1484             }
1485         }
1487         [attr setObject:informativeText forKey:@"informativeText"];
1488     }
1490     if (messageText)
1491         [attr setObject:messageText forKey:@"messageText"];
1493     if (textfield) {
1494         NSString *string = [NSString stringWithVimString:textfield];
1495         [attr setObject:string forKey:@"textFieldString"];
1496     }
1498     return [[MMBackend sharedInstance] showDialogWithAttributes:attr
1499                                                     textField:(char*)textfield];
1503     void
1504 gui_mch_flash(int msec)
1510  * Return the Pixel value (color) for the given color name.  This routine was
1511  * pretty much taken from example code in the Silicon Graphics OSF/Motif
1512  * Programmer's Guide.
1513  * Return INVALCOLOR when failed.
1514  */
1515     guicolor_T
1516 gui_mch_get_color(char_u *name)
1518 #ifdef FEAT_MBYTE
1519     name = CONVERT_TO_UTF8(name);
1520 #endif
1522     NSString *key = [NSString stringWithUTF8String:(char*)name];
1523     guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1525 #ifdef FEAT_MBYTE
1526     CONVERT_TO_UTF8_FREE(name);
1527 #endif
1529     return col;
1534  * Return the RGB value of a pixel as long.
1535  */
1536     long_u
1537 gui_mch_get_rgb(guicolor_T pixel)
1539     // This is only implemented so that vim can guess the correct value for
1540     // 'background' (which otherwise defaults to 'dark'); it is not used for
1541     // anything else (as far as I know).
1542     // The implementation is simple since colors are stored in an int as
1543     // "rrggbb".
1544     return pixel;
1549  * Get the screen dimensions.
1550  * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1551  * Is there no way to find out how wide the borders really are?
1552  * TODO: Add live udate of those value on suspend/resume.
1553  */
1554     void
1555 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1557     //NSLog(@"gui_mch_get_screen_dimensions()");
1558     *screen_w = Columns;
1559     *screen_h = Rows;
1564  * Get the position of the top left corner of the window.
1565  */
1566     int
1567 gui_mch_get_winpos(int *x, int *y)
1569     *x = *y = 0;
1570     return OK;
1575  * Return OK if the key with the termcap name "name" is supported.
1576  */
1577     int
1578 gui_mch_haskey(char_u *name)
1580     BOOL ok = NO;
1582 #ifdef FEAT_MBYTE
1583     name = CONVERT_TO_UTF8(name);
1584 #endif
1586     NSString *value = [NSString stringWithUTF8String:(char*)name];
1587     if (value)
1588         ok =  [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1590 #ifdef FEAT_MBYTE
1591     CONVERT_TO_UTF8_FREE(name);
1592 #endif
1594     return ok;
1599  * Iconify the GUI window.
1600  */
1601     void
1602 gui_mch_iconify(void)
1607 #if defined(FEAT_EVAL) || defined(PROTO)
1609  * Bring the Vim window to the foreground.
1610  */
1611     void
1612 gui_mch_set_foreground(void)
1614     [[MMBackend sharedInstance] activate];
1616 #endif
1620     void
1621 gui_mch_set_shellsize(
1622     int         width,
1623     int         height,
1624     int         min_width,
1625     int         min_height,
1626     int         base_width,
1627     int         base_height,
1628     int         direction)
1630     //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1631     //        " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1632     //        width, height, min_width, min_height, base_width, base_height,
1633     //        direction);
1634     [[MMBackend sharedInstance] setRows:height columns:width];
1638     void
1639 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1644  * Set the position of the top left corner of the window to the given
1645  * coordinates.
1646  */
1647     void
1648 gui_mch_set_winpos(int x, int y)
1653 #ifdef FEAT_TITLE
1655  * Set the window title and icon.
1656  * (The icon is not taken care of).
1657  */
1658     void
1659 gui_mch_settitle(char_u *title, char_u *icon)
1661     //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1663 #ifdef FEAT_MBYTE
1664     title = CONVERT_TO_UTF8(title);
1665 #endif
1667     MMBackend *backend = [MMBackend sharedInstance];
1668     [backend setWindowTitle:(char*)title];
1670     // TODO: Convert filename to UTF-8?
1671     if (curbuf)
1672         [backend setDocumentFilename:(char*)curbuf->b_ffname];
1674 #ifdef FEAT_MBYTE
1675     CONVERT_TO_UTF8_FREE(title);
1676 #endif
1678 #endif
1681     void
1682 gui_mch_toggle_tearoffs(int enable)
1688     void
1689 gui_mch_enter_fullscreen(int fuoptions_flags, guicolor_T bg)
1691     [[MMBackend sharedInstance] enterFullscreen:fuoptions_flags background:bg];
1695     void
1696 gui_mch_leave_fullscreen()
1698     [[MMBackend sharedInstance] leaveFullscreen];
1702     void
1703 gui_mch_fuopt_update()
1705     if (!gui.in_use)
1706         return;
1708     guicolor_T fg, bg;
1709     if (fuoptions_flags & FUOPT_BGCOLOR_HLGROUP) {
1710         syn_id2colors(fuoptions_bgcolor, &fg, &bg);
1711     } else {
1712         bg = fuoptions_bgcolor;
1713     }
1715     [[MMBackend sharedInstance] setFullscreenBackgroundColor:bg];
1719     void
1720 gui_macvim_update_modified_flag()
1722     [[MMBackend sharedInstance] updateModifiedFlag];
1726  * Add search pattern 'pat' to the OS X find pasteboard.  This allows other
1727  * apps access the last pattern searched for (hitting <D-g> in another app will
1728  * initiate a search for the same pattern).
1729  */
1730     void
1731 gui_macvim_add_to_find_pboard(char_u *pat)
1733     if (!pat) return;
1735 #ifdef FEAT_MBYTE
1736     pat = CONVERT_TO_UTF8(pat);
1737 #endif
1738     NSString *s = [NSString stringWithUTF8String:(char*)pat];
1739 #ifdef FEAT_MBYTE
1740     CONVERT_TO_UTF8_FREE(pat);
1741 #endif
1743     if (!s) return;
1745     NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
1746     [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1747     [pb setString:s forType:NSStringPboardType];
1750     void
1751 gui_macvim_set_antialias(int antialias)
1753     [[MMBackend sharedInstance] setAntialias:antialias];
1757     void
1758 gui_macvim_wait_for_startup()
1760     MMBackend *backend = [MMBackend sharedInstance];
1761     if ([backend waitForAck])
1762         [backend waitForConnectionAcknowledgement];
1765 void gui_macvim_get_window_layout(int *count, int *layout)
1767     if (!(count && layout)) return;
1769     // NOTE: Only set 'layout' if the backend has requested a != 0 layout, else
1770     // any command line arguments (-p/-o) would be ignored.
1771     int window_layout = [[MMBackend sharedInstance] initialWindowLayout];
1772     if (window_layout > 0 && window_layout < 4) {
1773         // The window_layout numbers must match the WIN_* defines in main.c.
1774         *count = 0;
1775         *layout = window_layout;
1776     }
1780 // -- Client/Server ---------------------------------------------------------
1782 #ifdef MAC_CLIENTSERVER
1785 // NOTE: Client/Server is only fully supported with a GUI.  Theoretically it
1786 // would be possible to make the server code work with terminal Vim, but it
1787 // would require that a run-loop is set up and checked.  This should not be
1788 // difficult to implement, simply call gui_mch_update() at opportune moments
1789 // and it will take care of the run-loop.  Another (bigger) problem with
1790 // supporting servers in terminal mode is that the server listing code talks to
1791 // MacVim (the GUI) to figure out which servers are running.
1796  * Register connection with 'name'.  The actual connection is named something
1797  * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1798  */
1799     void
1800 serverRegisterName(char_u *name)
1802 #ifdef FEAT_MBYTE
1803     name = CONVERT_TO_UTF8(name);
1804 #endif
1806     NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1807     [[MMBackend sharedInstance] registerServerWithName:svrName];
1809 #ifdef FEAT_MBYTE
1810     CONVERT_TO_UTF8_FREE(name);
1811 #endif
1816  * Send to an instance of Vim.
1817  * Returns 0 for OK, negative for an error.
1818  */
1819     int
1820 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1821         int *port, int asExpr, int silent)
1823 #ifdef FEAT_MBYTE
1824     name = CONVERT_TO_UTF8(name);
1825     cmd = CONVERT_TO_UTF8(cmd);
1826 #endif
1828     BOOL ok = [[MMBackend sharedInstance]
1829             sendToServer:[NSString stringWithUTF8String:(char*)name]
1830                   string:[NSString stringWithUTF8String:(char*)cmd]
1831                    reply:result
1832                     port:port
1833               expression:asExpr
1834                   silent:silent];
1836 #ifdef FEAT_MBYTE
1837     CONVERT_TO_UTF8_FREE(name);
1838     CONVERT_TO_UTF8_FREE(cmd);
1839 #endif
1841     return ok ? 0 : -1;
1846  * Ask MacVim for the names of all Vim servers.
1847  */
1848     char_u *
1849 serverGetVimNames(void)
1851     char_u *names = NULL;
1852     NSArray *list = [[MMBackend sharedInstance] serverList];
1854     if (list) {
1855         NSString *string = [list componentsJoinedByString:@"\n"];
1856         names = [string vimStringSave];
1857     }
1859     return names;
1864  * 'str' is a hex int representing the send port of the connection.
1865  */
1866     int
1867 serverStrToPort(char_u *str)
1869     int port = 0;
1871     sscanf((char *)str, "0x%x", &port);
1872     if (!port)
1873         EMSG2(_("E573: Invalid server id used: %s"), str);
1875     return port;
1880  * Check for replies from server with send port 'port'.
1881  * Return TRUE and a non-malloc'ed string if there is.  Else return FALSE.
1882  */
1883     int
1884 serverPeekReply(int port, char_u **str)
1886     NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1887     int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1889     if (str && len > 0) {
1890         *str = (char_u*)[reply UTF8String];
1892 #ifdef FEAT_MBYTE
1893         if (input_conv.vc_type != CONV_NONE) {
1894             char_u *s = string_convert(&input_conv, *str, &len);
1896             if (len > 0) {
1897                 // HACK! Since 's' needs to be freed we cannot simply set
1898                 // '*str = s' or memory will leak.  Instead, create a dummy
1899                 // NSData and return its 'bytes' pointer, then autorelease the
1900                 // NSData.
1901                 NSData *data = [NSData dataWithBytes:s length:len+1];
1902                 *str = (char_u*)[data bytes];
1903             }
1905             vim_free(s);
1906         }
1907 #endif
1908     }
1910     return reply != nil;
1915  * Wait for replies from server with send port 'port'.
1916  * Return 0 and the malloc'ed string when a reply is available.
1917  * Return -1 on error.
1918  */
1919     int
1920 serverReadReply(int port, char_u **str)
1922     NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1923     if (reply && str) {
1924         *str = [reply vimStringSave];
1925         return 0;
1926     }
1928     return -1;
1933  * Send a reply string (notification) to client with port given by "serverid".
1934  * Return -1 if the window is invalid.
1935  */
1936     int
1937 serverSendReply(char_u *serverid, char_u *reply)
1939     int retval = -1;
1940     int port = serverStrToPort(serverid);
1941     if (port > 0 && reply) {
1942 #ifdef FEAT_MBYTE
1943         reply = CONVERT_TO_UTF8(reply);
1944 #endif
1945         BOOL ok = [[MMBackend sharedInstance]
1946                 sendReply:[NSString stringWithUTF8String:(char*)reply]
1947                    toPort:port];
1948         retval = ok ? 0 : -1;
1949 #ifdef FEAT_MBYTE
1950         CONVERT_TO_UTF8_FREE(reply);
1951 #endif
1952     }
1954     return retval;
1957 #endif // MAC_CLIENTSERVER
1962 // -- ODB Editor Support ----------------------------------------------------
1964 #ifdef FEAT_ODB_EDITOR
1966  * The ODB Editor protocol works like this:
1967  * - An external program (the server) asks MacVim to open a file and associates
1968  *   three things with this file: (1) a server id (a four character code that
1969  *   identifies the server), (2) a path that can be used as window title for
1970  *   the file (optional), (3) an arbitrary token (optional)
1971  * - When a file is saved or closed, MacVim should tell the server about which
1972  *   file was modified and also pass back the token
1974  * All communication between MacVim and the server goes via Apple Events.
1975  */
1977     static OSErr
1978 odb_event(buf_T *buf, const AEEventID action)
1980     if (!(buf->b_odb_server_id && buf->b_ffname))
1981         return noErr;
1983     NSAppleEventDescriptor *targetDesc = [NSAppleEventDescriptor
1984             descriptorWithDescriptorType:typeApplSignature
1985                                    bytes:&buf->b_odb_server_id
1986                                   length:sizeof(OSType)];
1988     // TODO: Convert b_ffname to UTF-8?
1989     NSString *path = [NSString stringWithUTF8String:(char*)buf->b_ffname];
1990     NSData *pathData = [[[NSURL fileURLWithPath:path] absoluteString]
1991             dataUsingEncoding:NSUTF8StringEncoding];
1992     NSAppleEventDescriptor *pathDesc = [NSAppleEventDescriptor
1993             descriptorWithDescriptorType:typeFileURL data:pathData];
1995     NSAppleEventDescriptor *event = [NSAppleEventDescriptor
1996             appleEventWithEventClass:kODBEditorSuite
1997                              eventID:action
1998                     targetDescriptor:targetDesc
1999                             returnID:kAutoGenerateReturnID
2000                        transactionID:kAnyTransactionID];
2002     [event setParamDescriptor:pathDesc forKeyword:keyDirectObject];
2004     if (buf->b_odb_token)
2005         [event setParamDescriptor:buf->b_odb_token forKeyword:keySenderToken];
2007     return AESendMessage([event aeDesc], NULL, kAENoReply | kAENeverInteract,
2008             kAEDefaultTimeout);
2011     OSErr
2012 odb_buffer_close(buf_T *buf)
2014     OSErr err = noErr;
2015     if (buf) {
2016         err = odb_event(buf, kAEClosedFile);
2018         buf->b_odb_server_id = 0;
2020         if (buf->b_odb_token) {
2021             [(NSAppleEventDescriptor *)(buf->b_odb_token) release];
2022             buf->b_odb_token = NULL;
2023         }
2025         if (buf->b_odb_fname) {
2026             vim_free(buf->b_odb_fname);
2027             buf->b_odb_fname = NULL;
2028         }
2029     }
2031     return err;
2034     OSErr
2035 odb_post_buffer_write(buf_T *buf)
2037     return buf ? odb_event(buf, kAEModifiedFile) : noErr;
2040     void
2041 odb_end(void)
2043     buf_T *buf;
2044     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2045         odb_buffer_close(buf);
2048 #endif // FEAT_ODB_EDITOR
2051     char_u *
2052 get_macaction_name(expand_T *xp, int idx)
2054     static char_u *str = NULL;
2055     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
2057     if (nil == actionDict || idx < 0 || idx >= [actionDict count])
2058         return NULL;
2060     NSString *string = [[actionDict allKeys] objectAtIndex:idx];
2061     if (!string)
2062         return NULL;
2064     char_u *plainStr = (char_u*)[string UTF8String];
2066 #ifdef FEAT_MBYTE
2067     if (str) {
2068         vim_free(str);
2069         str = NULL;
2070     }
2071     if (input_conv.vc_type != CONV_NONE) {
2072         int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
2073         str = string_convert(&input_conv, plainStr, &len);
2074         plainStr = str;
2075     }
2076 #endif
2078     return plainStr;
2082     int
2083 is_valid_macaction(char_u *action)
2085     int isValid = NO;
2086     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
2087     if (actionDict) {
2088 #ifdef FEAT_MBYTE
2089         action = CONVERT_TO_UTF8(action);
2090 #endif
2091         NSString *string = [NSString stringWithUTF8String:(char*)action];
2092         isValid = (nil != [actionDict objectForKey:string]);
2093 #ifdef FEAT_MBYTE
2094         CONVERT_TO_UTF8_FREE(action);
2095 #endif
2096     }
2098     return isValid;
2101 static int specialKeyToNSKey(int key)
2103     if (!IS_SPECIAL(key))
2104         return key;
2106     static struct {
2107         int special;
2108         int nskey;
2109     } sp2ns[] = {
2110         { K_UP, NSUpArrowFunctionKey },
2111         { K_DOWN, NSDownArrowFunctionKey },
2112         { K_LEFT, NSLeftArrowFunctionKey },
2113         { K_RIGHT, NSRightArrowFunctionKey },
2114         { K_F1, NSF1FunctionKey },
2115         { K_F2, NSF2FunctionKey },
2116         { K_F3, NSF3FunctionKey },
2117         { K_F4, NSF4FunctionKey },
2118         { K_F5, NSF5FunctionKey },
2119         { K_F6, NSF6FunctionKey },
2120         { K_F7, NSF7FunctionKey },
2121         { K_F8, NSF8FunctionKey },
2122         { K_F9, NSF9FunctionKey },
2123         { K_F10, NSF10FunctionKey },
2124         { K_F11, NSF11FunctionKey },
2125         { K_F12, NSF12FunctionKey },
2126         { K_F13, NSF13FunctionKey },
2127         { K_F14, NSF14FunctionKey },
2128         { K_F15, NSF15FunctionKey },
2129         { K_F16, NSF16FunctionKey },
2130         { K_F17, NSF17FunctionKey },
2131         { K_F18, NSF18FunctionKey },
2132         { K_F19, NSF19FunctionKey },
2133         { K_F20, NSF20FunctionKey },
2134         { K_F21, NSF21FunctionKey },
2135         { K_F22, NSF22FunctionKey },
2136         { K_F23, NSF23FunctionKey },
2137         { K_F24, NSF24FunctionKey },
2138         { K_F25, NSF25FunctionKey },
2139         { K_F26, NSF26FunctionKey },
2140         { K_F27, NSF27FunctionKey },
2141         { K_F28, NSF28FunctionKey },
2142         { K_F29, NSF29FunctionKey },
2143         { K_F30, NSF30FunctionKey },
2144         { K_F31, NSF31FunctionKey },
2145         { K_F32, NSF32FunctionKey },
2146         { K_F33, NSF33FunctionKey },
2147         { K_F34, NSF34FunctionKey },
2148         { K_F35, NSF35FunctionKey },
2149         { K_DEL, NSBackspaceCharacter },
2150         { K_BS, NSDeleteCharacter },
2151         { K_HOME, NSHomeFunctionKey },
2152         { K_END, NSEndFunctionKey },
2153         { K_PAGEUP, NSPageUpFunctionKey },
2154         { K_PAGEDOWN, NSPageDownFunctionKey }
2155     };
2157     int i;
2158     for (i = 0; i < sizeof(sp2ns)/sizeof(sp2ns[0]); ++i) {
2159         if (sp2ns[i].special == key)
2160             return sp2ns[i].nskey;
2161     }
2163     return 0;
2166 static int vimModMaskToEventModifierFlags(int mods)
2168     int flags = 0;
2170     if (mods & MOD_MASK_SHIFT)
2171         flags |= NSShiftKeyMask;
2172     if (mods & MOD_MASK_CTRL)
2173         flags |= NSControlKeyMask;
2174     if (mods & MOD_MASK_ALT)
2175         flags |= NSAlternateKeyMask;
2176     if (mods & MOD_MASK_CMD)
2177         flags |= NSCommandKeyMask;
2179     return flags;