Change ":macmenukey" to ":macmenu"
[MacVim.git] / src / MacVim / gui_macvim.m
blob701712d835a711ab0eaf0042c74a2b1a807b8a55
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 <Foundation/Foundation.h>
17 #import "MMBackend.h"
18 #import "MacVim.h"
19 #import "vim.h"
23 // This constant controls how often [MMBackend update] may get called (see
24 // gui_mch_update()).
25 static NSTimeInterval MMUpdateTimeoutInterval = 0.1f;
27 // NOTE: The default font is bundled with the application.
28 static NSString *MMDefaultFontName = @"DejaVu Sans Mono";
29 static float MMDefaultFontSize = 12.0f;
30 static float MMMinFontSize = 6.0f;
31 static float MMMaxFontSize = 100.0f;
34 static NSFont *gui_macvim_font_with_name(char_u *name);
38 // -- Initialization --------------------------------------------------------
41  * Parse the GUI related command-line arguments.  Any arguments used are
42  * deleted from argv, and *argc is decremented accordingly.  This is called
43  * when vim is started, whether or not the GUI has been started.
44  */
45     void
46 gui_mch_prepare(int *argc, char **argv)
48     //NSLog(@"gui_mch_prepare(argc=%d)", *argc);
50     // Set environment variables $VIM and $VIMRUNTIME
51     // NOTE!  If vim_getenv is called with one of these as parameters before
52     // they have been set here, they will most likely end up with the wrong
53     // values!
54     //
55     // TODO:
56     // - ensure this is called first to avoid above problem
57     // - encoding
59     NSString *path = [[[NSBundle mainBundle] resourcePath]
60         stringByAppendingPathComponent:@"vim"];
61     vim_setenv((char_u*)"VIM", (char_u*)[path UTF8String]);
63     path = [path stringByAppendingPathComponent:@"runtime"];
64     vim_setenv((char_u*)"VIMRUNTIME", (char_u*)[path UTF8String]);
69  * Check if the GUI can be started.  Called before gvimrc is sourced.
70  * Return OK or FAIL.
71  */
72     int
73 gui_mch_init_check(void)
75     //NSLog(@"gui_mch_init_check()");
76     return OK;
81  * Initialise the GUI.  Create all the windows, set up all the call-backs etc.
82  * Returns OK for success, FAIL when the GUI can't be started.
83  */
84     int
85 gui_mch_init(void)
87     //NSLog(@"gui_mch_init()");
89     if (![[MMBackend sharedInstance] checkin]) {
90         // TODO: Kill the process if there is no terminal to fall back on,
91         // otherwise the process will run outputting to the console.
92         return FAIL;
93     }
95     // Force 'termencoding' to utf-8 (changes to 'tenc' are disallowed in
96     // 'option.c', so that ':set termencoding=...' is impossible).
97     set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
99     // Set values so that pixels and characters are in one-to-one
100     // correspondence (assuming all characters have the same dimensions).
101     gui.scrollbar_width = gui.scrollbar_height = 0;
103     gui.char_height = 1;
104     gui.char_width = 1;
105     gui.char_ascent = 0;
107     gui_mch_def_colors();
109     [[MMBackend sharedInstance]
110         setDefaultColorsBackground:gui.back_pixel foreground:gui.norm_pixel];
111     [[MMBackend sharedInstance] setBackgroundColor:gui.back_pixel];
112     [[MMBackend sharedInstance] setForegroundColor:gui.norm_pixel];
114     // NOTE: If this call is left out the cursor is opaque.
115     highlight_gui_started();
117     return OK;
122     void
123 gui_mch_exit(int rc)
125     //NSLog(@"gui_mch_exit(rc=%d)", rc);
127     [[MMBackend sharedInstance] exit];
132  * Open the GUI window which was created by a call to gui_mch_init().
133  */
134     int
135 gui_mch_open(void)
137     //NSLog(@"gui_mch_open()");
139     return [[MMBackend sharedInstance] openVimWindow];
143 // -- Updating --------------------------------------------------------------
147  * Catch up with any queued X events.  This may put keyboard input into the
148  * input buffer, call resize call-backs, trigger timers etc.  If there is
149  * nothing in the X event queue (& no timers pending), then we return
150  * immediately.
151  */
152 #define MM_LOG_UPDATE_STATS 0
153     void
154 gui_mch_update(void)
156     // NOTE: This function can get called A LOT (~1 call/ms) and unfortunately
157     // checking the run loop takes a long time, resulting in noticable slow
158     // downs if it is done every time this function is called.  Therefore we
159     // make sure that it is not done too often.
160     static NSDate *lastUpdateDate = nil;
161 #if MM_LOG_UPDATE_STATS
162     static int skipCount = 0;
163 #endif
165     if (lastUpdateDate && -[lastUpdateDate timeIntervalSinceNow] <
166             MMUpdateTimeoutInterval) {
167 #if MM_LOG_UPDATE_STATS
168         ++skipCount;
169 #endif
170         return;
171     }
173 #if MM_LOG_UPDATE_STATS
174     NSTimeInterval dt = -[lastUpdateDate timeIntervalSinceNow];
175     NSLog(@"Updating (last update %.2f seconds ago, skipped %d updates, "
176             "approx %.1f calls per second)",
177             dt, skipCount, dt > 0 ? skipCount/dt : 0);
178     skipCount = 0;
179 #endif
181     [[MMBackend sharedInstance] update];
183     [lastUpdateDate release];
184     lastUpdateDate = [[NSDate date] retain];
188 /* Flush any output to the screen */
189     void
190 gui_mch_flush(void)
192     [[MMBackend sharedInstance] flushQueue:NO];
196 /* Force flush output to MacVim.  Do not call this method unless absolutely
197  * necessary (use gui_mch_flush() instead). */
198     void
199 gui_macvim_force_flush(void)
201     [[MMBackend sharedInstance] flushQueue:YES];
206  * GUI input routine called by gui_wait_for_chars().  Waits for a character
207  * from the keyboard.
208  *  wtime == -1     Wait forever.
209  *  wtime == 0      This should never happen.
210  *  wtime > 0       Wait wtime milliseconds for a character.
211  * Returns OK if a character was found to be available within the given time,
212  * or FAIL otherwise.
213  */
214     int
215 gui_mch_wait_for_chars(int wtime)
217     // NOTE! In all likelihood Vim will take a nap when waitForInput: is
218     // called, so force a flush of the command queue here.
219     [[MMBackend sharedInstance] flushQueue:YES];
221     return [[MMBackend sharedInstance] waitForInput:wtime];
225 // -- Drawing ---------------------------------------------------------------
229  * Clear the whole text window.
230  */
231     void
232 gui_mch_clear_all(void)
234     [[MMBackend sharedInstance] clearAll];
239  * Clear a rectangular region of the screen from text pos (row1, col1) to
240  * (row2, col2) inclusive.
241  */
242     void
243 gui_mch_clear_block(int row1, int col1, int row2, int col2)
245     [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
246                                                     toRow:row2 column:col2];
251  * Delete the given number of lines from the given row, scrolling up any
252  * text further down within the scroll region.
253  */
254     void
255 gui_mch_delete_lines(int row, int num_lines)
257     [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
258             scrollBottom:gui.scroll_region_bot
259                     left:gui.scroll_region_left
260                    right:gui.scroll_region_right];
264     void
265 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
267 #ifdef FEAT_MBYTE
268     char_u *conv_str = NULL;
269     if (output_conv.vc_type != CONV_NONE) {
270         conv_str = string_convert(&output_conv, s, &len);
271         if (conv_str)
272             s = conv_str;
273     }
274 #endif
276     [[MMBackend sharedInstance] drawString:(char*)s length:len row:row
277                                     column:col cells:len flags:flags];
279 #ifdef FEAT_MBYTE
280     if (conv_str)
281         vim_free(conv_str);
282 #endif
286     int
287 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
289     int c, cn, cl, i;
290     int start = 0;
291     int endcol = col;
292     int startcol = col;
293     BOOL wide = NO;
294     MMBackend *backend = [MMBackend sharedInstance];
295 #ifdef FEAT_MBYTE
296     char_u *conv_str = NULL;
298     if (output_conv.vc_type != CONV_NONE) {
299         conv_str = string_convert(&output_conv, s, &len);
300         if (conv_str)
301             s = conv_str;
302     }
303 #endif
305     // Loop over each character and output text when it changes from normal to
306     // wide and vice versa.
307     for (i = 0; i < len; i += cl) {
308         c = utf_ptr2char(s + i);
309         cl = utf_ptr2len(s + i);
310         cn = utf_char2cells(c);
312         if (!utf_iscomposing(c)) {
313             if ((cn > 1 && !wide) || (cn <= 1 && wide)) {
314                 // Changed from normal to wide or vice versa.
315                 [backend drawString:(char*)(s+start) length:i-start
316                                    row:row column:startcol
317                                  cells:endcol-startcol
318                                  flags:(wide ? flags|DRAW_WIDE : flags)];
320                 start = i;
321                 startcol = endcol;
322             }
324             wide = cn > 1;
325             endcol += cn;
326         }
327     }
329     // Output remaining characters.
330     [backend drawString:(char*)(s+start) length:len-start
331                     row:row column:startcol cells:endcol-startcol
332                   flags:(wide ? flags|DRAW_WIDE : flags)];
334 #ifdef FEAT_MBYTE
335     if (conv_str)
336         vim_free(conv_str);
337 #endif
339     return endcol - col;
344  * Insert the given number of lines before the given row, scrolling down any
345  * following text within the scroll region.
346  */
347     void
348 gui_mch_insert_lines(int row, int num_lines)
350     [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
351             scrollBottom:gui.scroll_region_bot
352                     left:gui.scroll_region_left
353                    right:gui.scroll_region_right];
358  * Set the current text foreground color.
359  */
360     void
361 gui_mch_set_fg_color(guicolor_T color)
363     [[MMBackend sharedInstance] setForegroundColor:color];
368  * Set the current text background color.
369  */
370     void
371 gui_mch_set_bg_color(guicolor_T color)
373     [[MMBackend sharedInstance] setBackgroundColor:color];
378  * Set the current text special color (used for underlines).
379  */
380     void
381 gui_mch_set_sp_color(guicolor_T color)
383     [[MMBackend sharedInstance] setSpecialColor:color];
388  * Set default colors.
389  */
390     void
391 gui_mch_def_colors()
393     MMBackend *backend = [MMBackend sharedInstance];
395     // The default colors are taken from system values
396     gui.def_norm_pixel = gui.norm_pixel = 
397         [backend lookupColorWithKey:@"MacTextColor"];
398     gui.def_back_pixel = gui.back_pixel = 
399         [backend lookupColorWithKey:@"MacTextBackgroundColor"];
404  * Called when the foreground or background color has been changed.
405  */
406     void
407 gui_mch_new_colors(void)
409     gui.def_back_pixel = gui.back_pixel;
410     gui.def_norm_pixel = gui.norm_pixel;
412     //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
413     //        gui.def_norm_pixel);
415     [[MMBackend sharedInstance]
416         setDefaultColorsBackground:gui.def_back_pixel
417                         foreground:gui.def_norm_pixel];
421 // -- Tabline ---------------------------------------------------------------
425  * Set the current tab to "nr".  First tab is 1.
426  */
427     void
428 gui_mch_set_curtab(int nr)
430     [[MMBackend sharedInstance] selectTab:nr];
435  * Return TRUE when tabline is displayed.
436  */
437     int
438 gui_mch_showing_tabline(void)
440     return [[MMBackend sharedInstance] tabBarVisible];
444  * Update the labels of the tabline.
445  */
446     void
447 gui_mch_update_tabline(void)
449     [[MMBackend sharedInstance] updateTabBar];
453  * Show or hide the tabline.
454  */
455     void
456 gui_mch_show_tabline(int showit)
458     [[MMBackend sharedInstance] showTabBar:showit];
462 // -- Clipboard -------------------------------------------------------------
465     void
466 clip_mch_lose_selection(VimClipboard *cbd)
471     int
472 clip_mch_own_selection(VimClipboard *cbd)
474     return 0;
478     void
479 clip_mch_request_selection(VimClipboard *cbd)
481     NSPasteboard *pb = [NSPasteboard generalPasteboard];
482     NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
483             NSStringPboardType, nil];
484     NSString *bestType = [pb availableTypeFromArray:supportedTypes];
485     if (!bestType) return;
487     int motion_type = MCHAR;
488     NSString *string = nil;
490     if ([bestType isEqual:VimPBoardType]) {
491         // This type should consist of an array with two objects:
492         //   1. motion type (NSNumber)
493         //   2. text (NSString)
494         // If this is not the case we fall back on using NSStringPboardType.
495         id plist = [pb propertyListForType:VimPBoardType];
496         if ([plist isKindOfClass:[NSArray class]] && [plist count] == 2) {
497             id obj = [plist objectAtIndex:1];
498             if ([obj isKindOfClass:[NSString class]]) {
499                 motion_type = [[plist objectAtIndex:0] intValue];
500                 string = obj;
501             }
502         }
503     }
505     if (!string) {
506         // Use NSStringPboardType.  The motion type is set to line-wise if the
507         // string contains at least one EOL character, otherwise it is set to
508         // character-wise (block-wise is never used).
509         NSMutableString *mstring =
510                 [[pb stringForType:NSStringPboardType] mutableCopy];
511         if (!mstring) return;
513         // Replace unrecognized end-of-line sequences with \x0a (line feed).
514         NSRange range = { 0, [mstring length] };
515         unsigned n = [mstring replaceOccurrencesOfString:@"\x0d\x0a"
516                                              withString:@"\x0a" options:0
517                                                   range:range];
518         if (0 == n) {
519             n = [mstring replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
520                                            options:0 range:range];
521         }
522         
523         // Scan for newline character to decide whether the string should be
524         // pasted line-wise or character-wise.
525         motion_type = MCHAR;
526         if (0 < n || NSNotFound != [mstring rangeOfString:@"\n"].location)
527             motion_type = MLINE;
529         string = mstring;
530     }
532     if (!(MCHAR == motion_type || MLINE == motion_type || MBLOCK == motion_type
533             || MAUTO == motion_type))
534         motion_type = MCHAR;
536     char_u *str = (char_u*)[string UTF8String];
537     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
539 #ifdef FEAT_MBYTE
540     if (input_conv.vc_type != CONV_NONE)
541         str = string_convert(&input_conv, str, &len);
542 #endif
544     if (str)
545         clip_yank_selection(motion_type, str, len, cbd);
547 #ifdef FEAT_MBYTE
548     if (input_conv.vc_type != CONV_NONE)
549         vim_free(str);
550 #endif
555  * Send the current selection to the clipboard.
556  */
557     void
558 clip_mch_set_selection(VimClipboard *cbd)
560     // If the '*' register isn't already filled in, fill it in now.
561     cbd->owned = TRUE;
562     clip_get_selection(cbd);
563     cbd->owned = FALSE;
564     
565     // Get the text to put on the pasteboard.
566     long_u llen = 0; char_u *str = 0;
567     int motion_type = clip_convert_selection(&str, &llen, cbd);
568     if (motion_type < 0)
569         return;
571     // TODO: Avoid overflow.
572     int len = (int)llen;
573 #ifdef FEAT_MBYTE
574     if (output_conv.vc_type != CONV_NONE) {
575         char_u *conv_str = string_convert(&output_conv, str, &len);
576         if (conv_str) {
577             vim_free(str);
578             str = conv_str;
579         }
580     }
581 #endif
583     if (len > 0) {
584         NSString *string = [[NSString alloc]
585             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
587         // See clip_mch_request_selection() for info on pasteboard types.
588         NSPasteboard *pb = [NSPasteboard generalPasteboard];
589         NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
590                 NSStringPboardType, nil];
591         [pb declareTypes:supportedTypes owner:nil];
593         NSNumber *motion = [NSNumber numberWithInt:motion_type];
594         NSArray *plist = [NSArray arrayWithObjects:motion, string, nil];
595         [pb setPropertyList:plist forType:VimPBoardType];
597         [pb setString:string forType:NSStringPboardType];
598         
599         [string release];
600     }
602     vim_free(str);
606 // -- Menu ------------------------------------------------------------------
610  * Add a sub menu to the menu bar.
611  */
612     void
613 gui_mch_add_menu(vimmenu_T *menu, int idx)
615     // HACK!  If menu has no parent, then we set the parent tag to the type of
616     // menu it is.  This will not mix up tag and type because pointers can not
617     // take values close to zero (and the tag is simply the value of the
618     // pointer).
619     int parent = (int)menu->parent;
620     if (!parent) {
621         parent = menu_is_popup(menu->name) ? MenuPopupType :
622                  menu_is_toolbar(menu->name) ? MenuToolbarType :
623                  MenuMenubarType;
624     }
626     char_u *dname = menu->dname;
627 #ifdef FEAT_MBYTE
628     dname = CONVERT_TO_UTF8(dname);
629 #endif
631     [[MMBackend sharedInstance]
632             addMenuWithTag:(int)menu parent:parent name:(char*)dname
633                    atIndex:idx];
635 #ifdef FEAT_MBYTE
636     CONVERT_TO_UTF8_FREE(dname);
637 #endif
642  * Add a menu item to a menu
643  */
644     void
645 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
647     // NOTE!  If 'iconfile' is not set but 'iconidx' is, use the name of the
648     // menu item.  (Should correspond to a stock item.)
649     char_u *icon = menu->iconfile ? menu->iconfile :
650                  menu->iconidx >= 0 ? menu->dname :
651                  NULL;
652     //char *name = menu_is_separator(menu->name) ? NULL : (char*)menu->dname;
653     char_u *name = menu->dname;
654     char_u *tip = menu->strings[MENU_INDEX_TIP]
655             ? menu->strings[MENU_INDEX_TIP] : menu->actext;
656     char_u *map_str = menu->strings[MENU_INDEX_NORMAL];
657     char_u *mac_action = menu->mac_action;
659 #ifdef FEAT_MBYTE
660     icon = CONVERT_TO_UTF8(icon);
661     name = CONVERT_TO_UTF8(name);
662     tip = CONVERT_TO_UTF8(tip);
663     map_str = CONVERT_TO_UTF8(map_str);
664     mac_action = CONVERT_TO_UTF8(mac_action);
665 #endif
667     [[MMBackend sharedInstance]
668             addMenuItemWithTag:(int)menu
669                         parent:(int)menu->parent
670                           name:(char*)name
671                            tip:(char*)tip
672                           icon:(char*)icon
673                  keyEquivalent:menu->mac_key
674                      modifiers:menu->mac_mods
675                         action:(char*)mac_action
676                    isAlternate:menu->mac_alternate
677                        atIndex:idx];
679 #ifdef FEAT_MBYTE
680     CONVERT_TO_UTF8_FREE(icon);
681     CONVERT_TO_UTF8_FREE(name);
682     CONVERT_TO_UTF8_FREE(tip);
683     CONVERT_TO_UTF8_FREE(map_str);
684     CONVERT_TO_UTF8_FREE(mac_action);
685 #endif
690  * Destroy the machine specific menu widget.
691  */
692     void
693 gui_mch_destroy_menu(vimmenu_T *menu)
695     [[MMBackend sharedInstance] removeMenuItemWithTag:(int)menu];
700  * Make a menu either grey or not grey.
701  */
702     void
703 gui_mch_menu_grey(vimmenu_T *menu, int grey)
705     /* Only update menu if the 'grey' state has changed to avoid having to pass
706      * lots of unnecessary data to MacVim.  (Skipping this test makes MacVim
707      * pause noticably on mode changes. */
708     if (menu->was_grey != grey)
709     {
710         menu->was_grey = grey;
711         [[MMBackend sharedInstance]
712                 enableMenuItemWithTag:(int)menu state:!grey];
713     }
718  * Make menu item hidden or not hidden
719  */
720     void
721 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
723     // HACK! There is no (obvious) way to hide a menu item, so simply
724     // enable/disable it instead.
725     gui_mch_menu_grey(menu, hidden);
730  * This is called when user right clicks.
731  */
732     void
733 gui_mch_show_popupmenu(vimmenu_T *menu)
735     char_u *name = menu->name;
736 #ifdef FEAT_MBYTE
737     name = CONVERT_TO_UTF8(name);
738 #endif
740     [[MMBackend sharedInstance] showPopupMenuWithName:(char*)name
741                                       atMouseLocation:YES];
743 #ifdef FEAT_MBYTE
744     CONVERT_TO_UTF8_FREE(name);
745 #endif
751  * This is called when a :popup command is executed.
752  */
753     void
754 gui_make_popup(char_u *path_name, int mouse_pos)
756 #ifdef FEAT_MBYTE
757     path_name = CONVERT_TO_UTF8(path_name);
758 #endif
760     [[MMBackend sharedInstance] showPopupMenuWithName:(char*)path_name
761                                       atMouseLocation:mouse_pos];
763 #ifdef FEAT_MBYTE
764     CONVERT_TO_UTF8_FREE(path_name);
765 #endif
770  * This is called after setting all the menus to grey/hidden or not.
771  */
772     void
773 gui_mch_draw_menubar(void)
775     // The (main) menu draws itself in Mac OS X.
779     void
780 gui_mch_enable_menu(int flag)
782     // The (main) menu is always enabled in Mac OS X.
786 #if 0
787     void
788 gui_mch_set_menu_pos(int x, int y, int w, int h)
790     // The (main) menu cannot be moved in Mac OS X.
792 #endif
795     void
796 gui_mch_show_toolbar(int showit)
798     int flags = 0;
799     if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
800     if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
801     if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
803     [[MMBackend sharedInstance] showToolbar:showit flags:flags];
809 // -- Fonts -----------------------------------------------------------------
813  * If a font is not going to be used, free its structure.
814  */
815     void
816 gui_mch_free_font(font)
817     GuiFont     font;
819     if (font != NOFONT) {
820         //NSLog(@"gui_mch_free_font(font=0x%x)", font);
821         [(NSFont*)font release];
822     }
827  * Get a font structure for highlighting.
828  */
829     GuiFont
830 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
832     //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
833     //        giveErrorIfMissing);
835     NSFont *font = gui_macvim_font_with_name(name);
836     if (font)
837         return (GuiFont)[font retain];
839     if (giveErrorIfMissing)
840         EMSG2(_(e_font), name);
842     return NOFONT;
846 #if defined(FEAT_EVAL) || defined(PROTO)
848  * Return the name of font "font" in allocated memory.
849  * Don't know how to get the actual name, thus use the provided name.
850  */
851     char_u *
852 gui_mch_get_fontname(GuiFont font, char_u *name)
854     if (name == NULL)
855         return NULL;
856     return vim_strsave(name);
858 #endif
862  * Initialise vim to use the font with the given name.  Return FAIL if the font
863  * could not be loaded, OK otherwise.
864  */
865     int
866 gui_mch_init_font(char_u *font_name, int fontset)
868     //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
870     if (font_name && STRCMP(font_name, "*") == 0) {
871         // :set gfn=* shows the font panel.
872         do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
873         return FAIL;
874     }
876     NSFont *font = gui_macvim_font_with_name(font_name);
877     if (font) {
878         [(NSFont*)gui.norm_font release];
879         gui.norm_font = (GuiFont)[font retain];
881         // NOTE: MacVim keeps separate track of the normal and wide fonts.
882         // Unless the user changes 'guifontwide' manually, they are based on
883         // the same (normal) font.  Also note that each time the normal font is
884         // set, the advancement may change so the wide font needs to be updated
885         // as well (so that it is always twice the width of the normal font).
886         [[MMBackend sharedInstance] setFont:font];
887         [[MMBackend sharedInstance] setWideFont:
888                (NOFONT == gui.wide_font ? font : (NSFont*)gui.wide_font)];
890         return OK;
891     }
893     return FAIL;
898  * Set the current text font.
899  */
900     void
901 gui_mch_set_font(GuiFont font)
903     // Font selection is done inside MacVim...nothing here to do.
907     NSFont *
908 gui_macvim_font_with_name(char_u *name)
910     NSFont *font = nil;
911     NSString *fontName = MMDefaultFontName;
912     float size = MMDefaultFontSize;
913     BOOL parseFailed = NO;
915 #ifdef FEAT_MBYTE
916     name = CONVERT_TO_UTF8(name);
917 #endif
919     if (name) {
920         fontName = [NSString stringWithUTF8String:(char*)name];
922         NSArray *components = [fontName componentsSeparatedByString:@":"];
923         if ([components count] == 2) {
924             NSString *sizeString = [components lastObject];
925             if ([sizeString length] > 0
926                     && [sizeString characterAtIndex:0] == 'h') {
927                 sizeString = [sizeString substringFromIndex:1];
928                 if ([sizeString length] > 0) {
929                     size = [sizeString floatValue];
930                     fontName = [components objectAtIndex:0];
931                 }
932             } else {
933                 parseFailed = YES;
934             }
935         } else if ([components count] > 2) {
936             parseFailed = YES;
937         }
939         if (!parseFailed) {
940             // Replace underscores with spaces.
941             fontName = [[fontName componentsSeparatedByString:@"_"]
942                                      componentsJoinedByString:@" "];
943         }
944     }
946     if (!parseFailed && [fontName length] > 0) {
947         if (size < MMMinFontSize) size = MMMinFontSize;
948         if (size > MMMaxFontSize) size = MMMaxFontSize;
950         font = [NSFont fontWithName:fontName size:size];
952         if (!font && MMDefaultFontName == fontName) {
953             // If for some reason the MacVim default font is not in the app
954             // bundle, then fall back on the system default font.
955             font = [NSFont userFixedPitchFontOfSize:0];
956         }
957     }
959 #ifdef FEAT_MBYTE
960     CONVERT_TO_UTF8_FREE(name);
961 #endif
963     return font;
966 // -- Scrollbars ------------------------------------------------------------
969     void
970 gui_mch_create_scrollbar(
971         scrollbar_T *sb,
972         int orient)     /* SBAR_VERT or SBAR_HORIZ */
974     [[MMBackend sharedInstance] 
975             createScrollbarWithIdentifier:sb->ident type:sb->type];
979     void
980 gui_mch_destroy_scrollbar(scrollbar_T *sb)
982     [[MMBackend sharedInstance] 
983             destroyScrollbarWithIdentifier:sb->ident];
987     void
988 gui_mch_enable_scrollbar(
989         scrollbar_T     *sb,
990         int             flag)
992     [[MMBackend sharedInstance] 
993             showScrollbarWithIdentifier:sb->ident state:flag];
997     void
998 gui_mch_set_scrollbar_pos(
999         scrollbar_T *sb,
1000         int x,
1001         int y,
1002         int w,
1003         int h)
1005     int pos = y;
1006     int len = h;
1007     if (SBAR_BOTTOM == sb->type) {
1008         pos = x;
1009         len = w; 
1010     }
1012     [[MMBackend sharedInstance] 
1013             setScrollbarPosition:pos length:len identifier:sb->ident];
1017     void
1018 gui_mch_set_scrollbar_thumb(
1019         scrollbar_T *sb,
1020         long val,
1021         long size,
1022         long max)
1024     [[MMBackend sharedInstance] 
1025             setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
1029 // -- Cursor ----------------------------------------------------------------
1033  * Draw a cursor without focus.
1034  */
1035     void
1036 gui_mch_draw_hollow_cursor(guicolor_T color)
1038     return [[MMBackend sharedInstance]
1039         drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
1040                fraction:100 color:color];
1045  * Draw part of a cursor, only w pixels wide, and h pixels high.
1046  */
1047     void
1048 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
1050     // HACK!  'w' and 'h' are always 1 since we do not tell Vim about the exact
1051     // font dimensions.  Thus these parameters are useless.  Instead we look at
1052     // the shape_table to determine the shape and size of the cursor (just like
1053     // gui_update_cursor() does).
1054     int idx = get_shape_idx(FALSE);
1055     int shape = MMInsertionPointBlock;
1056     switch (shape_table[idx].shape) {
1057         case SHAPE_HOR: shape = MMInsertionPointHorizontal; break;
1058         case SHAPE_VER: shape = MMInsertionPointVertical; break;
1059     }
1061     return [[MMBackend sharedInstance]
1062         drawCursorAtRow:gui.row column:gui.col shape:shape
1063                fraction:shape_table[idx].percentage color:color];
1068  * Cursor blink functions.
1070  * This is a simple state machine:
1071  * BLINK_NONE   not blinking at all
1072  * BLINK_OFF    blinking, cursor is not shown
1073  * BLINK_ON blinking, cursor is shown
1074  */
1075     void
1076 gui_mch_set_blinking(long wait, long on, long off)
1078     [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1083  * Start the cursor blinking.  If it was already blinking, this restarts the
1084  * waiting time and shows the cursor.
1085  */
1086     void
1087 gui_mch_start_blink(void)
1089     [[MMBackend sharedInstance] startBlink];
1094  * Stop the cursor blinking.  Show the cursor if it wasn't shown.
1095  */
1096     void
1097 gui_mch_stop_blink(void)
1099     [[MMBackend sharedInstance] stopBlink];
1103 // -- Mouse -----------------------------------------------------------------
1107  * Get current mouse coordinates in text window.
1108  */
1109     void
1110 gui_mch_getmouse(int *x, int *y)
1112     //NSLog(@"gui_mch_getmouse()");
1116     void
1117 gui_mch_setmouse(int x, int y)
1119     //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1123     void
1124 mch_set_mouse_shape(int shape)
1126     [[MMBackend sharedInstance] setMouseShape:shape];
1132 // -- Input Method ----------------------------------------------------------
1134 #if defined(USE_IM_CONTROL)
1136     void
1137 im_set_position(int row, int col)
1139     // The pre-edit area is a popup window which is displayed by MMTextView.
1140     [[MMBackend sharedInstance] setPreEditRow:row column:col];
1144     void
1145 im_set_active(int active)
1147     // Set roman or the system script if 'active' is TRUE or FALSE,
1148     // respectively.
1149     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1151     if (!p_imdisable && smRoman != systemScript)
1152         KeyScript(active ? smKeySysScript : smKeyRoman);
1156     int
1157 im_get_status(void)
1159     // IM is active whenever the current script is the system script and the
1160     // system script isn't roman.  (Hence IM can only be active when using
1161     // non-roman scripts.)
1162     SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
1163     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1165     return currentScript != smRoman && currentScript == systemScript;
1168 #endif // defined(USE_IM_CONTROL)
1173 // -- Unsorted --------------------------------------------------------------
1176     void
1177 ex_macaction(eap)
1178     exarg_T     *eap;
1180     if (!gui.in_use) {
1181         EMSG(_("E???: Command only available in GUI mode"));
1182         return;
1183     }
1185     char_u *arg = eap->arg;
1186 #ifdef FEAT_MBYTE
1187     arg = CONVERT_TO_UTF8(arg);
1188 #endif
1190     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1191     NSString *name = [NSString stringWithUTF8String:(char*)arg];
1192     if (actionDict && [actionDict objectForKey:name] != nil) {
1193         [[MMBackend sharedInstance] executeActionWithName:name];
1194     } else {
1195         EMSG2(_("E???: Invalid action: %s"), eap->arg);
1196     }
1198 #ifdef FEAT_MBYTE
1199     arg = CONVERT_TO_UTF8(arg);
1200 #endif
1205  * Adjust gui.char_height (after 'linespace' was changed).
1206  */
1207     int
1208 gui_mch_adjust_charheight(void)
1210     [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1211     return OK;
1215     void
1216 gui_mch_beep(void)
1218     NSBeep();
1223 #ifdef FEAT_BROWSE
1225  * Pop open a file browser and return the file selected, in allocated memory,
1226  * or NULL if Cancel is hit.
1227  *  saving  - TRUE if the file will be saved to, FALSE if it will be opened.
1228  *  title   - Title message for the file browser dialog.
1229  *  dflt    - Default name of file.
1230  *  ext     - Default extension to be added to files without extensions.
1231  *  initdir - directory in which to open the browser (NULL = current dir)
1232  *  filter  - Filter for matched files to choose from.
1233  *  Has a format like this:
1234  *  "C Files (*.c)\0*.c\0"
1235  *  "All Files\0*.*\0\0"
1236  *  If these two strings were concatenated, then a choice of two file
1237  *  filters will be selectable to the user.  Then only matching files will
1238  *  be shown in the browser.  If NULL, the default allows all files.
1240  *  *NOTE* - the filter string must be terminated with TWO nulls.
1241  */
1242     char_u *
1243 gui_mch_browse(
1244     int saving,
1245     char_u *title,
1246     char_u *dflt,
1247     char_u *ext,
1248     char_u *initdir,
1249     char_u *filter)
1251     //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1252     //        " filter=%s", saving, title, dflt, ext, initdir, filter);
1254 #ifdef FEAT_MBYTE
1255     title = CONVERT_TO_UTF8(title);
1256     initdir = CONVERT_TO_UTF8(initdir);
1257 #endif
1259     char_u *s = (char_u*)[[MMBackend sharedInstance]
1260             browseForFileInDirectory:(char*)initdir title:(char*)title
1261                               saving:saving];
1263 #ifdef FEAT_MBYTE
1264     CONVERT_TO_UTF8_FREE(title);
1265     CONVERT_TO_UTF8_FREE(initdir);
1266 #endif
1268     return s;
1270 #endif /* FEAT_BROWSE */
1274     int
1275 gui_mch_dialog(
1276     int         type,
1277     char_u      *title,
1278     char_u      *message,
1279     char_u      *buttons,
1280     int         dfltbutton,
1281     char_u      *textfield)
1283     //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1284     //        "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1285     //        dfltbutton, textfield);
1287 #ifdef FEAT_MBYTE
1288     title = CONVERT_TO_UTF8(title);
1289     message = CONVERT_TO_UTF8(message);
1290     buttons = CONVERT_TO_UTF8(buttons);
1291     textfield = CONVERT_TO_UTF8(textfield);
1292 #endif
1294     int ret = [[MMBackend sharedInstance]
1295             presentDialogWithType:type
1296                             title:(char*)title
1297                           message:(char*)message
1298                           buttons:(char*)buttons
1299                         textField:(char*)textfield];
1301 #ifdef FEAT_MBYTE
1302     CONVERT_TO_UTF8_FREE(title);
1303     CONVERT_TO_UTF8_FREE(message);
1304     CONVERT_TO_UTF8_FREE(buttons);
1305     CONVERT_TO_UTF8_FREE(textfield);
1306 #endif
1308     return ret;
1312     void
1313 gui_mch_flash(int msec)
1319  * Return the Pixel value (color) for the given color name.  This routine was
1320  * pretty much taken from example code in the Silicon Graphics OSF/Motif
1321  * Programmer's Guide.
1322  * Return INVALCOLOR when failed.
1323  */
1324     guicolor_T
1325 gui_mch_get_color(char_u *name)
1327 #ifdef FEAT_MBYTE
1328     name = CONVERT_TO_UTF8(name);
1329 #endif
1331     NSString *key = [NSString stringWithUTF8String:(char*)name];
1332     guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1334 #ifdef FEAT_MBYTE
1335     CONVERT_TO_UTF8_FREE(name);
1336 #endif
1338     return col;
1343  * Return the RGB value of a pixel as long.
1344  */
1345     long_u
1346 gui_mch_get_rgb(guicolor_T pixel)
1348     // This is only implemented so that vim can guess the correct value for
1349     // 'background' (which otherwise defaults to 'dark'); it is not used for
1350     // anything else (as far as I know).
1351     // The implementation is simple since colors are stored in an int as
1352     // "rrggbb".
1353     return pixel;
1358  * Get the screen dimensions.
1359  * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1360  * Is there no way to find out how wide the borders really are?
1361  * TODO: Add live udate of those value on suspend/resume.
1362  */
1363     void
1364 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1366     //NSLog(@"gui_mch_get_screen_dimensions()");
1367     *screen_w = Columns;
1368     *screen_h = Rows;
1373  * Get the position of the top left corner of the window.
1374  */
1375     int
1376 gui_mch_get_winpos(int *x, int *y)
1378     *x = *y = 0;
1379     return OK;
1384  * Return OK if the key with the termcap name "name" is supported.
1385  */
1386     int
1387 gui_mch_haskey(char_u *name)
1389     BOOL ok = NO;
1391 #ifdef FEAT_MBYTE
1392     name = CONVERT_TO_UTF8(name);
1393 #endif
1395     NSString *value = [NSString stringWithUTF8String:(char*)name];
1396     if (value)
1397         ok =  [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1399 #ifdef FEAT_MBYTE
1400     CONVERT_TO_UTF8_FREE(name);
1401 #endif
1403     return ok;
1408  * Iconify the GUI window.
1409  */
1410     void
1411 gui_mch_iconify(void)
1417  * Invert a rectangle from row r, column c, for nr rows and nc columns.
1418  */
1419     void
1420 gui_mch_invert_rectangle(int r, int c, int nr, int nc)
1425 #if defined(FEAT_EVAL) || defined(PROTO)
1427  * Bring the Vim window to the foreground.
1428  */
1429     void
1430 gui_mch_set_foreground(void)
1432     [[MMBackend sharedInstance] activate];
1434 #endif
1438     void
1439 gui_mch_set_shellsize(
1440     int         width,
1441     int         height,
1442     int         min_width,
1443     int         min_height,
1444     int         base_width,
1445     int         base_height,
1446     int         direction)
1448     //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1449     //        " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1450     //        width, height, min_width, min_height, base_width, base_height,
1451     //        direction);
1452     [[MMBackend sharedInstance] setRows:height columns:width];
1456     void
1457 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1462  * Set the position of the top left corner of the window to the given
1463  * coordinates.
1464  */
1465     void
1466 gui_mch_set_winpos(int x, int y)
1471 #ifdef FEAT_TITLE
1473  * Set the window title and icon.
1474  * (The icon is not taken care of).
1475  */
1476     void
1477 gui_mch_settitle(char_u *title, char_u *icon)
1479     //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1481 #ifdef FEAT_MBYTE
1482     title = CONVERT_TO_UTF8(title);
1483 #endif
1485     [[MMBackend sharedInstance] setWindowTitle:(char*)title];
1487 #ifdef FEAT_MBYTE
1488     CONVERT_TO_UTF8_FREE(title);
1489 #endif
1491 #endif
1494     void
1495 gui_mch_toggle_tearoffs(int enable)
1501     void
1502 gui_mch_enter_fullscreen(int fuoptions_flags, guicolor_T bg)
1504     [[MMBackend sharedInstance] enterFullscreen:fuoptions_flags background:bg];
1508     void
1509 gui_mch_leave_fullscreen()
1511     [[MMBackend sharedInstance] leaveFullscreen];
1515     void
1516 gui_macvim_update_modified_flag()
1518     [[MMBackend sharedInstance] updateModifiedFlag];
1522  * Add search pattern 'pat' to the OS X find pasteboard.  This allows other
1523  * apps access the last pattern searched for (hitting <D-g> in another app will
1524  * initiate a search for the same pattern).
1525  */
1526     void
1527 gui_macvim_add_to_find_pboard(char_u *pat)
1529     if (!pat) return;
1531 #ifdef FEAT_MBYTE
1532     pat = CONVERT_TO_UTF8(pat);
1533 #endif
1534     NSString *s = [NSString stringWithUTF8String:(char*)pat];
1535 #ifdef FEAT_MBYTE
1536     CONVERT_TO_UTF8_FREE(pat);
1537 #endif
1539     if (!s) return;
1541     NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
1542     [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1543     [pb setString:s forType:NSStringPboardType];
1546     void
1547 gui_macvim_set_antialias(int antialias)
1549     [[MMBackend sharedInstance] setAntialias:antialias];
1556 // -- Client/Server ---------------------------------------------------------
1558 #ifdef MAC_CLIENTSERVER
1561 // NOTE: Client/Server is only fully supported with a GUI.  Theoretically it
1562 // would be possible to make the server code work with terminal Vim, but it
1563 // would require that a run-loop is set up and checked.  This should not be
1564 // difficult to implement, simply call gui_mch_update() at opportune moments
1565 // and it will take care of the run-loop.  Another (bigger) problem with
1566 // supporting servers in terminal mode is that the server listing code talks to
1567 // MacVim (the GUI) to figure out which servers are running.
1572  * Register connection with 'name'.  The actual connection is named something
1573  * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1574  */
1575     void
1576 serverRegisterName(char_u *name)
1578 #ifdef FEAT_MBYTE
1579     name = CONVERT_TO_UTF8(name);
1580 #endif
1582     NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1583     [[MMBackend sharedInstance] registerServerWithName:svrName];
1585 #ifdef FEAT_MBYTE
1586     CONVERT_TO_UTF8_FREE(name);
1587 #endif
1592  * Send to an instance of Vim.
1593  * Returns 0 for OK, negative for an error.
1594  */
1595     int
1596 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1597         int *port, int asExpr, int silent)
1599 #ifdef FEAT_MBYTE
1600     name = CONVERT_TO_UTF8(name);
1601     cmd = CONVERT_TO_UTF8(cmd);
1602 #endif
1604     BOOL ok = [[MMBackend sharedInstance]
1605             sendToServer:[NSString stringWithUTF8String:(char*)name]
1606                   string:[NSString stringWithUTF8String:(char*)cmd]
1607                    reply:result
1608                     port:port
1609               expression:asExpr
1610                   silent:silent];
1612 #ifdef FEAT_MBYTE
1613     CONVERT_TO_UTF8_FREE(name);
1614     CONVERT_TO_UTF8_FREE(cmd);
1615 #endif
1617     return ok ? 0 : -1;
1622  * Ask MacVim for the names of all Vim servers.
1623  */
1624     char_u *
1625 serverGetVimNames(void)
1627     char_u *names = NULL;
1628     NSArray *list = [[MMBackend sharedInstance] serverList];
1630     if (list) {
1631         NSString *string = [list componentsJoinedByString:@"\n"];
1632         char_u *s = (char_u*)[string UTF8String];
1633 #ifdef FEAT_MBYTE
1634         s = CONVERT_FROM_UTF8(s);
1635 #endif
1636         names = vim_strsave(s);
1637 #ifdef FEAT_MBYTE
1638         CONVERT_FROM_UTF8_FREE(s);
1639 #endif
1640     }
1642     return names;
1647  * 'str' is a hex int representing the send port of the connection.
1648  */
1649     int
1650 serverStrToPort(char_u *str)
1652     int port = 0;
1654     sscanf((char *)str, "0x%x", &port);
1655     if (!port)
1656         EMSG2(_("E573: Invalid server id used: %s"), str);
1658     return port;
1663  * Check for replies from server with send port 'port'.
1664  * Return TRUE and a non-malloc'ed string if there is.  Else return FALSE.
1665  */
1666     int
1667 serverPeekReply(int port, char_u **str)
1669     NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1670     int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1672     if (str && len > 0) {
1673         *str = (char_u*)[reply UTF8String];
1675 #ifdef FEAT_MBYTE
1676         if (input_conv.vc_type != CONV_NONE) {
1677             char_u *s = string_convert(&input_conv, *str, &len);
1679             if (len > 0) {
1680                 // HACK! Since 's' needs to be freed we cannot simply set
1681                 // '*str = s' or memory will leak.  Instead, create a dummy
1682                 // NSData and return its 'bytes' pointer, then autorelease the
1683                 // NSData.
1684                 NSData *data = [NSData dataWithBytes:s length:len+1];
1685                 *str = (char_u*)[data bytes];
1686             }
1688             vim_free(s);
1689         }
1690 #endif
1691     }
1693     return reply != nil;
1698  * Wait for replies from server with send port 'port'.
1699  * Return 0 and the malloc'ed string when a reply is available.
1700  * Return -1 on error.
1701  */
1702     int
1703 serverReadReply(int port, char_u **str)
1705     NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1706     if (reply && str) {
1707         char_u *s = (char_u*)[reply UTF8String];
1708 #ifdef FEAT_MBYTE
1709         s = CONVERT_FROM_UTF8(s);
1710 #endif
1711         *str = vim_strsave(s);
1712 #ifdef FEAT_MBYTE
1713         CONVERT_FROM_UTF8_FREE(s);
1714 #endif
1715         return 0;
1716     }
1718     return -1;
1723  * Send a reply string (notification) to client with port given by "serverid".
1724  * Return -1 if the window is invalid.
1725  */
1726     int
1727 serverSendReply(char_u *serverid, char_u *reply)
1729     int retval = -1;
1730     int port = serverStrToPort(serverid);
1731     if (port > 0 && reply) {
1732 #ifdef FEAT_MBYTE
1733         reply = CONVERT_TO_UTF8(reply);
1734 #endif
1735         BOOL ok = [[MMBackend sharedInstance]
1736                 sendReply:[NSString stringWithUTF8String:(char*)reply]
1737                    toPort:port];
1738         retval = ok ? 0 : -1;
1739 #ifdef FEAT_MBYTE
1740         CONVERT_TO_UTF8_FREE(reply);
1741 #endif
1742     }
1744     return retval;
1747 #endif // MAC_CLIENTSERVER
1752 // -- ODB Editor Support ----------------------------------------------------
1754 #ifdef FEAT_ODB_EDITOR
1756  * The ODB Editor protocol works like this:
1757  * - An external program (the server) asks MacVim to open a file and associates
1758  *   three things with this file: (1) a server id (a four character code that
1759  *   identifies the server), (2) a path that can be used as window title for
1760  *   the file (optional), (3) an arbitrary token (optional)
1761  * - When a file is saved or closed, MacVim should tell the server about which
1762  *   file was modified and also pass back the token
1764  * All communication between MacVim and the server goes via Apple Events.
1765  */
1767     static OSErr
1768 odb_event(buf_T *buf, const AEEventID action)
1770     if (!(buf->b_odb_server_id && buf->b_ffname))
1771         return noErr;
1773     NSAppleEventDescriptor *targetDesc = [NSAppleEventDescriptor
1774             descriptorWithDescriptorType:typeApplSignature
1775                                    bytes:&buf->b_odb_server_id
1776                                   length:sizeof(OSType)];
1778     NSString *path = [NSString stringWithUTF8String:(char*)buf->b_ffname];
1779     NSData *pathData = [[[NSURL fileURLWithPath:path] absoluteString]
1780             dataUsingEncoding:NSUTF8StringEncoding];
1781     NSAppleEventDescriptor *pathDesc = [NSAppleEventDescriptor
1782             descriptorWithDescriptorType:typeFileURL data:pathData];
1784     NSAppleEventDescriptor *event = [NSAppleEventDescriptor
1785             appleEventWithEventClass:kODBEditorSuite
1786                              eventID:action
1787                     targetDescriptor:targetDesc
1788                             returnID:kAutoGenerateReturnID
1789                        transactionID:kAnyTransactionID];
1791     [event setParamDescriptor:pathDesc forKeyword:keyDirectObject];
1793     if (buf->b_odb_token)
1794         [event setParamDescriptor:buf->b_odb_token forKeyword:keySenderToken];
1796     return AESendMessage([event aeDesc], NULL, kAENoReply | kAENeverInteract,
1797             kAEDefaultTimeout);
1800     OSErr
1801 odb_buffer_close(buf_T *buf)
1803     OSErr err = noErr;
1804     if (buf) {
1805         err = odb_event(buf, kAEClosedFile);
1807         buf->b_odb_server_id = 0;
1809         if (buf->b_odb_token) {
1810             [(NSAppleEventDescriptor *)(buf->b_odb_token) release];
1811             buf->b_odb_token = NULL;
1812         }
1814         if (buf->b_odb_fname) {
1815             vim_free(buf->b_odb_fname);
1816             buf->b_odb_fname = NULL;
1817         }
1818     }
1820     return err;
1823     OSErr
1824 odb_post_buffer_write(buf_T *buf)
1826     return buf ? odb_event(buf, kAEModifiedFile) : noErr;
1829     void
1830 odb_end(void)
1832     buf_T *buf;
1833     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1834         odb_buffer_close(buf);
1837 #endif // FEAT_ODB_EDITOR
1840     char_u *
1841 get_macaction_name(expand_T *xp, int idx)
1843     static char_u *str = NULL;
1844     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1846     if (nil == actionDict || idx < 0 || idx >= [actionDict count])
1847         return NULL;
1849     NSString *string = [[actionDict allKeys] objectAtIndex:idx];
1850     if (!string)
1851         return NULL;
1853     char_u *plainStr = (char_u*)[string UTF8String];
1855 #ifdef FEAT_MBYTE
1856     if (str) {
1857         vim_free(str);
1858         str = NULL;
1859     }
1860     if (input_conv.vc_type != CONV_NONE) {
1861         int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1862         str = string_convert(&input_conv, plainStr, &len);
1863         plainStr = str;
1864     }
1865 #endif
1867     return plainStr;
1871     int
1872 is_valid_macaction(char_u *action)
1874     int isValid = NO;
1875     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1876     if (actionDict) {
1877 #ifdef FEAT_MBYTE
1878         action = CONVERT_TO_UTF8(action);
1879 #endif
1880         NSString *string = [NSString stringWithUTF8String:(char*)action];
1881         isValid = (nil != [actionDict objectForKey:string]);
1882 #ifdef FEAT_MBYTE
1883         CONVERT_TO_UTF8_FREE(action);
1884 #endif
1885     }
1887     return isValid;