Improved method to start Vim processes in a login shell
[MacVim.git] / src / MacVim / gui_macvim.m
blob2e8782684bd6be36099a9fbd2c10acbfb3c28cb1
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);
35 static BOOL gui_macvim_is_valid_action(NSString *action);
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]);
70  * Check if the GUI can be started.  Called before gvimrc is sourced.
71  * Return OK or FAIL.
72  */
73     int
74 gui_mch_init_check(void)
76     //NSLog(@"gui_mch_init_check()");
77     return OK;
82  * Initialise the GUI.  Create all the windows, set up all the call-backs etc.
83  * Returns OK for success, FAIL when the GUI can't be started.
84  */
85     int
86 gui_mch_init(void)
88     //NSLog(@"gui_mch_init()");
90     if (![[MMBackend sharedInstance] checkin]) {
91         // TODO: Kill the process if there is no terminal to fall back on,
92         // otherwise the process will run outputting to the console.
93         return FAIL;
94     }
96     // Force 'termencoding' to utf-8 (changes to 'tenc' are disallowed in
97     // 'option.c', so that ':set termencoding=...' is impossible).
98     set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
100     // Set values so that pixels and characters are in one-to-one
101     // correspondence (assuming all characters have the same dimensions).
102     gui.scrollbar_width = gui.scrollbar_height = 0;
104     gui.char_height = 1;
105     gui.char_width = 1;
106     gui.char_ascent = 0;
108     gui_mch_def_colors();
110     [[MMBackend sharedInstance]
111         setDefaultColorsBackground:gui.back_pixel foreground:gui.norm_pixel];
112     [[MMBackend sharedInstance] setBackgroundColor:gui.back_pixel];
113     [[MMBackend sharedInstance] setForegroundColor:gui.norm_pixel];
115     // NOTE: If this call is left out the cursor is opaque.
116     highlight_gui_started();
118     return OK;
123     void
124 gui_mch_exit(int rc)
126     //NSLog(@"gui_mch_exit(rc=%d)", rc);
128     [[MMBackend sharedInstance] exit];
133  * Open the GUI window which was created by a call to gui_mch_init().
134  */
135     int
136 gui_mch_open(void)
138     //NSLog(@"gui_mch_open()");
140     return [[MMBackend sharedInstance] openVimWindow];
144 // -- Updating --------------------------------------------------------------
148  * Catch up with any queued X events.  This may put keyboard input into the
149  * input buffer, call resize call-backs, trigger timers etc.  If there is
150  * nothing in the X event queue (& no timers pending), then we return
151  * immediately.
152  */
153 #define MM_LOG_UPDATE_STATS 0
154     void
155 gui_mch_update(void)
157     // NOTE: This function can get called A LOT (~1 call/ms) and unfortunately
158     // checking the run loop takes a long time, resulting in noticable slow
159     // downs if it is done every time this function is called.  Therefore we
160     // make sure that it is not done too often.
161     static NSDate *lastUpdateDate = nil;
162 #if MM_LOG_UPDATE_STATS
163     static int skipCount = 0;
164 #endif
166     if (lastUpdateDate && -[lastUpdateDate timeIntervalSinceNow] <
167             MMUpdateTimeoutInterval) {
168 #if MM_LOG_UPDATE_STATS
169         ++skipCount;
170 #endif
171         return;
172     }
174 #if MM_LOG_UPDATE_STATS
175     NSTimeInterval dt = -[lastUpdateDate timeIntervalSinceNow];
176     NSLog(@"Updating (last update %.2f seconds ago, skipped %d updates, "
177             "approx %.1f calls per second)",
178             dt, skipCount, dt > 0 ? skipCount/dt : 0);
179     skipCount = 0;
180 #endif
182     [[MMBackend sharedInstance] update];
184     [lastUpdateDate release];
185     lastUpdateDate = [[NSDate date] retain];
189 /* Flush any output to the screen */
190     void
191 gui_mch_flush(void)
193     [[MMBackend sharedInstance] flushQueue:NO];
197 /* Force flush output to MacVim.  Do not call this method unless absolutely
198  * necessary (use gui_mch_flush() instead). */
199     void
200 gui_macvim_force_flush(void)
202     [[MMBackend sharedInstance] flushQueue:YES];
207  * GUI input routine called by gui_wait_for_chars().  Waits for a character
208  * from the keyboard.
209  *  wtime == -1     Wait forever.
210  *  wtime == 0      This should never happen.
211  *  wtime > 0       Wait wtime milliseconds for a character.
212  * Returns OK if a character was found to be available within the given time,
213  * or FAIL otherwise.
214  */
215     int
216 gui_mch_wait_for_chars(int wtime)
218     // NOTE! In all likelihood Vim will take a nap when waitForInput: is
219     // called, so force a flush of the command queue here.
220     [[MMBackend sharedInstance] flushQueue:YES];
222     return [[MMBackend sharedInstance] waitForInput:wtime];
226 // -- Drawing ---------------------------------------------------------------
230  * Clear the whole text window.
231  */
232     void
233 gui_mch_clear_all(void)
235     [[MMBackend sharedInstance] clearAll];
240  * Clear a rectangular region of the screen from text pos (row1, col1) to
241  * (row2, col2) inclusive.
242  */
243     void
244 gui_mch_clear_block(int row1, int col1, int row2, int col2)
246     [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
247                                                     toRow:row2 column:col2];
252  * Delete the given number of lines from the given row, scrolling up any
253  * text further down within the scroll region.
254  */
255     void
256 gui_mch_delete_lines(int row, int num_lines)
258     [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
259             scrollBottom:gui.scroll_region_bot
260                     left:gui.scroll_region_left
261                    right:gui.scroll_region_right];
265     void
266 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
268 #ifdef FEAT_MBYTE
269     char_u *conv_str = NULL;
270     if (output_conv.vc_type != CONV_NONE) {
271         conv_str = string_convert(&output_conv, s, &len);
272         if (conv_str)
273             s = conv_str;
274     }
275 #endif
277     [[MMBackend sharedInstance] drawString:(char*)s length:len row:row
278                                     column:col cells:len flags:flags];
280 #ifdef FEAT_MBYTE
281     if (conv_str)
282         vim_free(conv_str);
283 #endif
287     int
288 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
290     int c, cn, cl, i;
291     int start = 0;
292     int endcol = col;
293     int startcol = col;
294     BOOL wide = NO;
295     MMBackend *backend = [MMBackend sharedInstance];
296 #ifdef FEAT_MBYTE
297     char_u *conv_str = NULL;
299     if (output_conv.vc_type != CONV_NONE) {
300         conv_str = string_convert(&output_conv, s, &len);
301         if (conv_str)
302             s = conv_str;
303     }
304 #endif
306     // Loop over each character and output text when it changes from normal to
307     // wide and vice versa.
308     for (i = 0; i < len; i += cl) {
309         c = utf_ptr2char(s + i);
310         cl = utf_ptr2len(s + i);
311         cn = utf_char2cells(c);
313         if (!utf_iscomposing(c)) {
314             if ((cn > 1 && !wide) || (cn <= 1 && wide)) {
315                 // Changed from normal to wide or vice versa.
316                 [backend drawString:(char*)(s+start) length:i-start
317                                    row:row column:startcol
318                                  cells:endcol-startcol
319                                  flags:(wide ? flags|DRAW_WIDE : flags)];
321                 start = i;
322                 startcol = endcol;
323             }
325             wide = cn > 1;
326             endcol += cn;
327         }
328     }
330     // Output remaining characters.
331     [backend drawString:(char*)(s+start) length:len-start
332                     row:row column:startcol cells:endcol-startcol
333                   flags:(wide ? flags|DRAW_WIDE : flags)];
335 #ifdef FEAT_MBYTE
336     if (conv_str)
337         vim_free(conv_str);
338 #endif
340     return endcol - col;
345  * Insert the given number of lines before the given row, scrolling down any
346  * following text within the scroll region.
347  */
348     void
349 gui_mch_insert_lines(int row, int num_lines)
351     [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
352             scrollBottom:gui.scroll_region_bot
353                     left:gui.scroll_region_left
354                    right:gui.scroll_region_right];
359  * Set the current text foreground color.
360  */
361     void
362 gui_mch_set_fg_color(guicolor_T color)
364     [[MMBackend sharedInstance] setForegroundColor:color];
369  * Set the current text background color.
370  */
371     void
372 gui_mch_set_bg_color(guicolor_T color)
374     [[MMBackend sharedInstance] setBackgroundColor:color];
379  * Set the current text special color (used for underlines).
380  */
381     void
382 gui_mch_set_sp_color(guicolor_T color)
384     [[MMBackend sharedInstance] setSpecialColor:color];
389  * Set default colors.
390  */
391     void
392 gui_mch_def_colors()
394     MMBackend *backend = [MMBackend sharedInstance];
396     // The default colors are taken from system values
397     gui.def_norm_pixel = gui.norm_pixel = 
398         [backend lookupColorWithKey:@"MacTextColor"];
399     gui.def_back_pixel = gui.back_pixel = 
400         [backend lookupColorWithKey:@"MacTextBackgroundColor"];
405  * Called when the foreground or background color has been changed.
406  */
407     void
408 gui_mch_new_colors(void)
410     gui.def_back_pixel = gui.back_pixel;
411     gui.def_norm_pixel = gui.norm_pixel;
413     //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
414     //        gui.def_norm_pixel);
416     [[MMBackend sharedInstance]
417         setDefaultColorsBackground:gui.def_back_pixel
418                         foreground:gui.def_norm_pixel];
422 // -- Tabline ---------------------------------------------------------------
426  * Set the current tab to "nr".  First tab is 1.
427  */
428     void
429 gui_mch_set_curtab(int nr)
431     [[MMBackend sharedInstance] selectTab:nr];
436  * Return TRUE when tabline is displayed.
437  */
438     int
439 gui_mch_showing_tabline(void)
441     return [[MMBackend sharedInstance] tabBarVisible];
445  * Update the labels of the tabline.
446  */
447     void
448 gui_mch_update_tabline(void)
450     [[MMBackend sharedInstance] updateTabBar];
454  * Show or hide the tabline.
455  */
456     void
457 gui_mch_show_tabline(int showit)
459     [[MMBackend sharedInstance] showTabBar:showit];
463 // -- Clipboard -------------------------------------------------------------
466     void
467 clip_mch_lose_selection(VimClipboard *cbd)
472     int
473 clip_mch_own_selection(VimClipboard *cbd)
475     return 0;
479     void
480 clip_mch_request_selection(VimClipboard *cbd)
482     NSPasteboard *pb = [NSPasteboard generalPasteboard];
483     NSString *pbType = [pb availableTypeFromArray:
484             [NSArray arrayWithObject:NSStringPboardType]];
485     if (pbType) {
486         NSMutableString *string =
487                 [[pb stringForType:NSStringPboardType] mutableCopy];
489         // Replace unrecognized end-of-line sequences with \x0a (line feed).
490         NSRange range = { 0, [string length] };
491         unsigned n = [string replaceOccurrencesOfString:@"\x0d\x0a"
492                                              withString:@"\x0a" options:0
493                                                   range:range];
494         if (0 == n) {
495             n = [string replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
496                                            options:0 range:range];
497         }
498         
499         // Scan for newline character to decide whether the string should be
500         // pasted linewise or characterwise.
501         int type = MCHAR;
502         if (0 < n || NSNotFound != [string rangeOfString:@"\n"].location)
503             type = MLINE;
505         char_u *str = (char_u*)[string UTF8String];
506         int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
508 #ifdef FEAT_MBYTE
509         if (input_conv.vc_type != CONV_NONE)
510             str = string_convert(&input_conv, str, &len);
511 #endif
513         if (str)
514             clip_yank_selection(type, str, len, cbd);
516 #ifdef FEAT_MBYTE
517         if (input_conv.vc_type != CONV_NONE)
518             vim_free(str);
519 #endif
520     }
525  * Send the current selection to the clipboard.
526  */
527     void
528 clip_mch_set_selection(VimClipboard *cbd)
530     // If the '*' register isn't already filled in, fill it in now.
531     cbd->owned = TRUE;
532     clip_get_selection(cbd);
533     cbd->owned = FALSE;
534     
535     // Get the text to put on the pasteboard.
536     long_u llen = 0; char_u *str = 0;
537     int type = clip_convert_selection(&str, &llen, cbd);
538     if (type < 0)
539         return;
541     // TODO: Avoid overflow.
542     int len = (int)llen;
543 #ifdef FEAT_MBYTE
544     if (output_conv.vc_type != CONV_NONE) {
545         char_u *conv_str = string_convert(&output_conv, str, &len);
546         if (conv_str) {
547             vim_free(str);
548             str = conv_str;
549         }
550     }
551 #endif
553     if (len > 0) {
554         NSString *string = [[NSString alloc]
555             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
557         NSPasteboard *pb = [NSPasteboard generalPasteboard];
558         [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType]
559                    owner:nil];
560         [pb setString:string forType:NSStringPboardType];
561         
562         [string release];
563     }
565     vim_free(str);
569 // -- Menu ------------------------------------------------------------------
573  * Add a sub menu to the menu bar.
574  */
575     void
576 gui_mch_add_menu(vimmenu_T *menu, int idx)
578     // HACK!  If menu has no parent, then we set the parent tag to the type of
579     // menu it is.  This will not mix up tag and type because pointers can not
580     // take values close to zero (and the tag is simply the value of the
581     // pointer).
582     int parent = (int)menu->parent;
583     if (!parent) {
584         parent = menu_is_popup(menu->name) ? MenuPopupType :
585                  menu_is_toolbar(menu->name) ? MenuToolbarType :
586                  MenuMenubarType;
587     }
589     char_u *dname = menu->dname;
590 #ifdef FEAT_MBYTE
591     dname = CONVERT_TO_UTF8(dname);
592 #endif
594     [[MMBackend sharedInstance]
595             addMenuWithTag:(int)menu parent:parent name:(char*)dname
596                    atIndex:idx];
598 #ifdef FEAT_MBYTE
599     CONVERT_TO_UTF8_FREE(dname);
600 #endif
605  * Add a menu item to a menu
606  */
607     void
608 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
610     // NOTE!  If 'iconfile' is not set but 'iconidx' is, use the name of the
611     // menu item.  (Should correspond to a stock item.)
612     char_u *icon = menu->iconfile ? menu->iconfile :
613                  menu->iconidx >= 0 ? menu->dname :
614                  NULL;
615     //char *name = menu_is_separator(menu->name) ? NULL : (char*)menu->dname;
616     char_u *name = menu->dname;
617     char_u *tip = menu->strings[MENU_INDEX_TIP]
618             ? menu->strings[MENU_INDEX_TIP] : menu->actext;
619     char_u *map_str = menu->strings[MENU_INDEX_NORMAL];
621 #ifdef FEAT_MBYTE
622     icon = CONVERT_TO_UTF8(icon);
623     name = CONVERT_TO_UTF8(name);
624     tip = CONVERT_TO_UTF8(tip);
625     map_str = CONVERT_TO_UTF8(map_str);
626 #endif
628     // HACK!  Check if menu is mapped to ':macaction actionName:'; if so, pass
629     // the action along so that MacVim can bind the menu item to this action.
630     // This means that if a menu item maps to an action in normal mode, then
631     // all other modes will also use the same action.
632     NSString *action = nil;
633     if (map_str) {
634         NSString *mapping = [NSString stringWithCString:(char*)map_str
635                                                encoding:NSUTF8StringEncoding];
636         NSArray *parts = [mapping componentsSeparatedByString:@" "];
637         if ([parts count] >=2 
638                 && [[parts objectAtIndex:0] hasPrefix:@":maca"]) {
639             action = [parts objectAtIndex:1];
640             action = [action stringByTrimmingCharactersInSet:
641                     [NSCharacterSet whitespaceAndNewlineCharacterSet]];
642             if (!gui_macvim_is_valid_action(action))
643                 action = nil;
644         }
645     }
647     [[MMBackend sharedInstance]
648             addMenuItemWithTag:(int)menu
649                         parent:(int)menu->parent
650                           name:(char*)name
651                            tip:(char*)tip
652                           icon:(char*)icon
653                  keyEquivalent:menu->mac_key
654                      modifiers:menu->mac_mods
655                         action:action
656                        atIndex:idx];
658 #ifdef FEAT_MBYTE
659     CONVERT_TO_UTF8_FREE(icon);
660     CONVERT_TO_UTF8_FREE(name);
661     CONVERT_TO_UTF8_FREE(tip);
662     CONVERT_TO_UTF8_FREE(map_str);
663 #endif
668  * Destroy the machine specific menu widget.
669  */
670     void
671 gui_mch_destroy_menu(vimmenu_T *menu)
673     [[MMBackend sharedInstance] removeMenuItemWithTag:(int)menu];
678  * Make a menu either grey or not grey.
679  */
680     void
681 gui_mch_menu_grey(vimmenu_T *menu, int grey)
683     /* Only update menu if the 'grey' state has changed to avoid having to pass
684      * lots of unnecessary data to MacVim.  (Skipping this test makes MacVim
685      * pause noticably on mode changes. */
686     if (menu->was_grey != grey)
687     {
688         menu->was_grey = grey;
689         [[MMBackend sharedInstance]
690                 enableMenuItemWithTag:(int)menu state:!grey];
691     }
696  * Make menu item hidden or not hidden
697  */
698     void
699 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
701     // HACK! There is no (obvious) way to hide a menu item, so simply
702     // enable/disable it instead.
703     gui_mch_menu_grey(menu, hidden);
708  * This is called when user right clicks.
709  */
710     void
711 gui_mch_show_popupmenu(vimmenu_T *menu)
713     char_u *name = menu->name;
714 #ifdef FEAT_MBYTE
715     name = CONVERT_TO_UTF8(name);
716 #endif
718     [[MMBackend sharedInstance] showPopupMenuWithName:(char*)name
719                                       atMouseLocation:YES];
721 #ifdef FEAT_MBYTE
722     CONVERT_TO_UTF8_FREE(name);
723 #endif
729  * This is called when a :popup command is executed.
730  */
731     void
732 gui_make_popup(char_u *path_name, int mouse_pos)
734 #ifdef FEAT_MBYTE
735     path_name = CONVERT_TO_UTF8(path_name);
736 #endif
738     [[MMBackend sharedInstance] showPopupMenuWithName:(char*)path_name
739                                       atMouseLocation:mouse_pos];
741 #ifdef FEAT_MBYTE
742     CONVERT_TO_UTF8_FREE(path_name);
743 #endif
748  * This is called after setting all the menus to grey/hidden or not.
749  */
750     void
751 gui_mch_draw_menubar(void)
753     // The (main) menu draws itself in Mac OS X.
757     void
758 gui_mch_enable_menu(int flag)
760     // The (main) menu is always enabled in Mac OS X.
764 #if 0
765     void
766 gui_mch_set_menu_pos(int x, int y, int w, int h)
768     // The (main) menu cannot be moved in Mac OS X.
770 #endif
773     void
774 gui_mch_show_toolbar(int showit)
776     int flags = 0;
777     if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
778     if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
779     if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
781     [[MMBackend sharedInstance] showToolbar:showit flags:flags];
787 // -- Fonts -----------------------------------------------------------------
791  * If a font is not going to be used, free its structure.
792  */
793     void
794 gui_mch_free_font(font)
795     GuiFont     font;
797     if (font != NOFONT) {
798         //NSLog(@"gui_mch_free_font(font=0x%x)", font);
799         [(NSFont*)font release];
800     }
805  * Get a font structure for highlighting.
806  */
807     GuiFont
808 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
810     //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
811     //        giveErrorIfMissing);
813     NSFont *font = gui_macvim_font_with_name(name);
814     if (font)
815         return (GuiFont)[font retain];
817     if (giveErrorIfMissing)
818         EMSG2(_(e_font), name);
820     return NOFONT;
824 #if defined(FEAT_EVAL) || defined(PROTO)
826  * Return the name of font "font" in allocated memory.
827  * Don't know how to get the actual name, thus use the provided name.
828  */
829     char_u *
830 gui_mch_get_fontname(GuiFont font, char_u *name)
832     if (name == NULL)
833         return NULL;
834     return vim_strsave(name);
836 #endif
840  * Initialise vim to use the font with the given name.  Return FAIL if the font
841  * could not be loaded, OK otherwise.
842  */
843     int
844 gui_mch_init_font(char_u *font_name, int fontset)
846     //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
848     if (font_name && STRCMP(font_name, "*") == 0) {
849         // :set gfn=* shows the font panel.
850         do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
851         return FAIL;
852     }
854     NSFont *font = gui_macvim_font_with_name(font_name);
855     if (font) {
856         [(NSFont*)gui.norm_font release];
857         gui.norm_font = (GuiFont)[font retain];
859         // NOTE: MacVim keeps separate track of the normal and wide fonts.
860         // Unless the user changes 'guifontwide' manually, they are based on
861         // the same (normal) font.  Also note that each time the normal font is
862         // set, the advancement may change so the wide font needs to be updated
863         // as well (so that it is always twice the width of the normal font).
864         [[MMBackend sharedInstance] setFont:font];
865         [[MMBackend sharedInstance] setWideFont:
866                (NOFONT == gui.wide_font ? font : (NSFont*)gui.wide_font)];
868         return OK;
869     }
871     return FAIL;
876  * Set the current text font.
877  */
878     void
879 gui_mch_set_font(GuiFont font)
881     // Font selection is done inside MacVim...nothing here to do.
885     NSFont *
886 gui_macvim_font_with_name(char_u *name)
888     NSFont *font = nil;
889     NSString *fontName = MMDefaultFontName;
890     float size = MMDefaultFontSize;
891     BOOL parseFailed = NO;
893 #ifdef FEAT_MBYTE
894     name = CONVERT_TO_UTF8(name);
895 #endif
897     if (name) {
898         fontName = [NSString stringWithUTF8String:(char*)name];
900         NSArray *components = [fontName componentsSeparatedByString:@":"];
901         if ([components count] == 2) {
902             NSString *sizeString = [components lastObject];
903             if ([sizeString length] > 0
904                     && [sizeString characterAtIndex:0] == 'h') {
905                 sizeString = [sizeString substringFromIndex:1];
906                 if ([sizeString length] > 0) {
907                     size = [sizeString floatValue];
908                     fontName = [components objectAtIndex:0];
909                 }
910             } else {
911                 parseFailed = YES;
912             }
913         } else if ([components count] > 2) {
914             parseFailed = YES;
915         }
917         if (!parseFailed) {
918             // Replace underscores with spaces.
919             fontName = [[fontName componentsSeparatedByString:@"_"]
920                                      componentsJoinedByString:@" "];
921         }
922     }
924     if (!parseFailed && [fontName length] > 0) {
925         if (size < MMMinFontSize) size = MMMinFontSize;
926         if (size > MMMaxFontSize) size = MMMaxFontSize;
928         font = [NSFont fontWithName:fontName size:size];
930         if (!font && MMDefaultFontName == fontName) {
931             // If for some reason the MacVim default font is not in the app
932             // bundle, then fall back on the system default font.
933             font = [NSFont userFixedPitchFontOfSize:0];
934         }
935     }
937 #ifdef FEAT_MBYTE
938     CONVERT_TO_UTF8_FREE(name);
939 #endif
941     return font;
944 // -- Scrollbars ------------------------------------------------------------
947     void
948 gui_mch_create_scrollbar(
949         scrollbar_T *sb,
950         int orient)     /* SBAR_VERT or SBAR_HORIZ */
952     [[MMBackend sharedInstance] 
953             createScrollbarWithIdentifier:sb->ident type:sb->type];
957     void
958 gui_mch_destroy_scrollbar(scrollbar_T *sb)
960     [[MMBackend sharedInstance] 
961             destroyScrollbarWithIdentifier:sb->ident];
965     void
966 gui_mch_enable_scrollbar(
967         scrollbar_T     *sb,
968         int             flag)
970     [[MMBackend sharedInstance] 
971             showScrollbarWithIdentifier:sb->ident state:flag];
975     void
976 gui_mch_set_scrollbar_pos(
977         scrollbar_T *sb,
978         int x,
979         int y,
980         int w,
981         int h)
983     int pos = y;
984     int len = h;
985     if (SBAR_BOTTOM == sb->type) {
986         pos = x;
987         len = w; 
988     }
990     [[MMBackend sharedInstance] 
991             setScrollbarPosition:pos length:len identifier:sb->ident];
995     void
996 gui_mch_set_scrollbar_thumb(
997         scrollbar_T *sb,
998         long val,
999         long size,
1000         long max)
1002     [[MMBackend sharedInstance] 
1003             setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
1007 // -- Cursor ----------------------------------------------------------------
1011  * Draw a cursor without focus.
1012  */
1013     void
1014 gui_mch_draw_hollow_cursor(guicolor_T color)
1016     return [[MMBackend sharedInstance]
1017         drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
1018                fraction:100 color:color];
1023  * Draw part of a cursor, only w pixels wide, and h pixels high.
1024  */
1025     void
1026 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
1028     // HACK!  'w' and 'h' are always 1 since we do not tell Vim about the exact
1029     // font dimensions.  Thus these parameters are useless.  Instead we look at
1030     // the shape_table to determine the shape and size of the cursor (just like
1031     // gui_update_cursor() does).
1032     int idx = get_shape_idx(FALSE);
1033     int shape = MMInsertionPointBlock;
1034     switch (shape_table[idx].shape) {
1035         case SHAPE_HOR: shape = MMInsertionPointHorizontal; break;
1036         case SHAPE_VER: shape = MMInsertionPointVertical; break;
1037     }
1039     return [[MMBackend sharedInstance]
1040         drawCursorAtRow:gui.row column:gui.col shape:shape
1041                fraction:shape_table[idx].percentage color:color];
1046  * Cursor blink functions.
1048  * This is a simple state machine:
1049  * BLINK_NONE   not blinking at all
1050  * BLINK_OFF    blinking, cursor is not shown
1051  * BLINK_ON blinking, cursor is shown
1052  */
1053     void
1054 gui_mch_set_blinking(long wait, long on, long off)
1056     [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1061  * Start the cursor blinking.  If it was already blinking, this restarts the
1062  * waiting time and shows the cursor.
1063  */
1064     void
1065 gui_mch_start_blink(void)
1067     [[MMBackend sharedInstance] startBlink];
1072  * Stop the cursor blinking.  Show the cursor if it wasn't shown.
1073  */
1074     void
1075 gui_mch_stop_blink(void)
1077     [[MMBackend sharedInstance] stopBlink];
1081 // -- Mouse -----------------------------------------------------------------
1085  * Get current mouse coordinates in text window.
1086  */
1087     void
1088 gui_mch_getmouse(int *x, int *y)
1090     //NSLog(@"gui_mch_getmouse()");
1094     void
1095 gui_mch_setmouse(int x, int y)
1097     //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1101     void
1102 mch_set_mouse_shape(int shape)
1104     [[MMBackend sharedInstance] setMouseShape:shape];
1110 // -- Input Method ----------------------------------------------------------
1112 #if defined(USE_IM_CONTROL)
1114     void
1115 im_set_position(int row, int col)
1117     // The pre-edit area is a popup window which is displayed by MMTextView.
1118     [[MMBackend sharedInstance] setPreEditRow:row column:col];
1122     void
1123 im_set_active(int active)
1125     // Set roman or the system script if 'active' is TRUE or FALSE,
1126     // respectively.
1127     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1129     if (!p_imdisable && smRoman != systemScript)
1130         KeyScript(active ? smKeySysScript : smKeyRoman);
1134     int
1135 im_get_status(void)
1137     // IM is active whenever the current script is the system script and the
1138     // system script isn't roman.  (Hence IM can only be active when using
1139     // non-roman scripts.)
1140     SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
1141     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1143     return currentScript != smRoman && currentScript == systemScript;
1146 #endif // defined(USE_IM_CONTROL)
1151 // -- Unsorted --------------------------------------------------------------
1154     void
1155 ex_macaction(eap)
1156     exarg_T     *eap;
1158     if (!gui.in_use) {
1159         EMSG(_("E???: Command only available in GUI mode"));
1160         return;
1161     }
1163     char_u *arg = eap->arg;
1164 #ifdef FEAT_MBYTE
1165     arg = CONVERT_TO_UTF8(arg);
1166 #endif
1168     NSString *name = [NSString stringWithCString:(char*)arg
1169                                         encoding:NSUTF8StringEncoding];
1170     if (gui_macvim_is_valid_action(name)) {
1171         [[MMBackend sharedInstance] executeActionWithName:name];
1172     } else {
1173         EMSG2(_("E???: \"%s\" is not a valid action"), eap->arg);
1174     }
1176 #ifdef FEAT_MBYTE
1177     arg = CONVERT_TO_UTF8(arg);
1178 #endif
1183  * Adjust gui.char_height (after 'linespace' was changed).
1184  */
1185     int
1186 gui_mch_adjust_charheight(void)
1188     [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1189     return OK;
1193     void
1194 gui_mch_beep(void)
1196     NSBeep();
1201 #ifdef FEAT_BROWSE
1203  * Pop open a file browser and return the file selected, in allocated memory,
1204  * or NULL if Cancel is hit.
1205  *  saving  - TRUE if the file will be saved to, FALSE if it will be opened.
1206  *  title   - Title message for the file browser dialog.
1207  *  dflt    - Default name of file.
1208  *  ext     - Default extension to be added to files without extensions.
1209  *  initdir - directory in which to open the browser (NULL = current dir)
1210  *  filter  - Filter for matched files to choose from.
1211  *  Has a format like this:
1212  *  "C Files (*.c)\0*.c\0"
1213  *  "All Files\0*.*\0\0"
1214  *  If these two strings were concatenated, then a choice of two file
1215  *  filters will be selectable to the user.  Then only matching files will
1216  *  be shown in the browser.  If NULL, the default allows all files.
1218  *  *NOTE* - the filter string must be terminated with TWO nulls.
1219  */
1220     char_u *
1221 gui_mch_browse(
1222     int saving,
1223     char_u *title,
1224     char_u *dflt,
1225     char_u *ext,
1226     char_u *initdir,
1227     char_u *filter)
1229     //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1230     //        " filter=%s", saving, title, dflt, ext, initdir, filter);
1232 #ifdef FEAT_MBYTE
1233     title = CONVERT_TO_UTF8(title);
1234     initdir = CONVERT_TO_UTF8(initdir);
1235 #endif
1237     char_u *s = (char_u*)[[MMBackend sharedInstance]
1238             browseForFileInDirectory:(char*)initdir title:(char*)title
1239                               saving:saving];
1241 #ifdef FEAT_MBYTE
1242     CONVERT_TO_UTF8_FREE(title);
1243     CONVERT_TO_UTF8_FREE(initdir);
1244 #endif
1246     return s;
1248 #endif /* FEAT_BROWSE */
1252     int
1253 gui_mch_dialog(
1254     int         type,
1255     char_u      *title,
1256     char_u      *message,
1257     char_u      *buttons,
1258     int         dfltbutton,
1259     char_u      *textfield)
1261     //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1262     //        "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1263     //        dfltbutton, textfield);
1265 #ifdef FEAT_MBYTE
1266     title = CONVERT_TO_UTF8(title);
1267     message = CONVERT_TO_UTF8(message);
1268     buttons = CONVERT_TO_UTF8(buttons);
1269     textfield = CONVERT_TO_UTF8(textfield);
1270 #endif
1272     int ret = [[MMBackend sharedInstance]
1273             presentDialogWithType:type
1274                             title:(char*)title
1275                           message:(char*)message
1276                           buttons:(char*)buttons
1277                         textField:(char*)textfield];
1279 #ifdef FEAT_MBYTE
1280     CONVERT_TO_UTF8_FREE(title);
1281     CONVERT_TO_UTF8_FREE(message);
1282     CONVERT_TO_UTF8_FREE(buttons);
1283     CONVERT_TO_UTF8_FREE(textfield);
1284 #endif
1286     return ret;
1290     void
1291 gui_mch_flash(int msec)
1297  * Return the Pixel value (color) for the given color name.  This routine was
1298  * pretty much taken from example code in the Silicon Graphics OSF/Motif
1299  * Programmer's Guide.
1300  * Return INVALCOLOR when failed.
1301  */
1302     guicolor_T
1303 gui_mch_get_color(char_u *name)
1305 #ifdef FEAT_MBYTE
1306     name = CONVERT_TO_UTF8(name);
1307 #endif
1309     NSString *key = [NSString stringWithUTF8String:(char*)name];
1310     guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1312 #ifdef FEAT_MBYTE
1313     CONVERT_TO_UTF8_FREE(name);
1314 #endif
1316     return col;
1321  * Return the RGB value of a pixel as long.
1322  */
1323     long_u
1324 gui_mch_get_rgb(guicolor_T pixel)
1326     // This is only implemented so that vim can guess the correct value for
1327     // 'background' (which otherwise defaults to 'dark'); it is not used for
1328     // anything else (as far as I know).
1329     // The implementation is simple since colors are stored in an int as
1330     // "rrggbb".
1331     return pixel;
1336  * Get the screen dimensions.
1337  * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1338  * Is there no way to find out how wide the borders really are?
1339  * TODO: Add live udate of those value on suspend/resume.
1340  */
1341     void
1342 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1344     //NSLog(@"gui_mch_get_screen_dimensions()");
1345     *screen_w = Columns;
1346     *screen_h = Rows;
1351  * Get the position of the top left corner of the window.
1352  */
1353     int
1354 gui_mch_get_winpos(int *x, int *y)
1356     *x = *y = 0;
1357     return OK;
1362  * Return OK if the key with the termcap name "name" is supported.
1363  */
1364     int
1365 gui_mch_haskey(char_u *name)
1367     BOOL ok = NO;
1369 #ifdef FEAT_MBYTE
1370     name = CONVERT_TO_UTF8(name);
1371 #endif
1373     NSString *value = [NSString stringWithUTF8String:(char*)name];
1374     if (value)
1375         ok =  [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1377 #ifdef FEAT_MBYTE
1378     CONVERT_TO_UTF8_FREE(name);
1379 #endif
1381     return ok;
1386  * Iconify the GUI window.
1387  */
1388     void
1389 gui_mch_iconify(void)
1395  * Invert a rectangle from row r, column c, for nr rows and nc columns.
1396  */
1397     void
1398 gui_mch_invert_rectangle(int r, int c, int nr, int nc)
1403 #if defined(FEAT_EVAL) || defined(PROTO)
1405  * Bring the Vim window to the foreground.
1406  */
1407     void
1408 gui_mch_set_foreground(void)
1410     [[MMBackend sharedInstance] activate];
1412 #endif
1416     void
1417 gui_mch_set_shellsize(
1418     int         width,
1419     int         height,
1420     int         min_width,
1421     int         min_height,
1422     int         base_width,
1423     int         base_height,
1424     int         direction)
1426     //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1427     //        " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1428     //        width, height, min_width, min_height, base_width, base_height,
1429     //        direction);
1430     [[MMBackend sharedInstance] setRows:height columns:width];
1434     void
1435 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1440  * Set the position of the top left corner of the window to the given
1441  * coordinates.
1442  */
1443     void
1444 gui_mch_set_winpos(int x, int y)
1449 #ifdef FEAT_TITLE
1451  * Set the window title and icon.
1452  * (The icon is not taken care of).
1453  */
1454     void
1455 gui_mch_settitle(char_u *title, char_u *icon)
1457     //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1459 #ifdef FEAT_MBYTE
1460     title = CONVERT_TO_UTF8(title);
1461 #endif
1463     [[MMBackend sharedInstance] setWindowTitle:(char*)title];
1465 #ifdef FEAT_MBYTE
1466     CONVERT_TO_UTF8_FREE(title);
1467 #endif
1469 #endif
1472     void
1473 gui_mch_toggle_tearoffs(int enable)
1478     static BOOL
1479 gui_macvim_is_valid_action(NSString *action)
1481     static NSDictionary *actionDict = nil;
1483     if (!actionDict) {
1484         NSBundle *mainBundle = [NSBundle mainBundle];
1485         NSString *path = [mainBundle pathForResource:@"Actions"
1486                                               ofType:@"plist"];
1487         if (path) {
1488             actionDict = [[NSDictionary alloc] initWithContentsOfFile:path];
1489         } else {
1490             // Allocate bogus dictionary so that error only pops up once.
1491             actionDict = [NSDictionary new];
1492             EMSG(_("E???: Failed to load action dictionary"));
1493         }
1494     }
1496     return [actionDict objectForKey:action] != nil;
1500     void
1501 gui_mch_enter_fullscreen()
1503     [[MMBackend sharedInstance] enterFullscreen];
1507     void
1508 gui_mch_leave_fullscreen()
1510     [[MMBackend sharedInstance] leaveFullscreen];
1514     void
1515 gui_macvim_update_modified_flag()
1517     [[MMBackend sharedInstance] updateModifiedFlag];
1521  * Add search pattern 'pat' to the OS X find pasteboard.  This allows other
1522  * apps access the last pattern searched for (hitting <D-g> in another app will
1523  * initiate a search for the same pattern).
1524  */
1525     void
1526 gui_macvim_add_to_find_pboard(char_u *pat)
1528     if (!pat) return;
1530 #ifdef FEAT_MBYTE
1531     pat = CONVERT_TO_UTF8(pat);
1532 #endif
1533     NSString *s = [NSString stringWithUTF8String:(char*)pat];
1534 #ifdef FEAT_MBYTE
1535     CONVERT_TO_UTF8_FREE(pat);
1536 #endif
1538     if (!s) return;
1540     NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
1541     [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1542     [pb setString:s forType:NSStringPboardType];
1548 // -- Client/Server ---------------------------------------------------------
1550 #ifdef MAC_CLIENTSERVER
1553 // NOTE: Client/Server is only fully supported with a GUI.  Theoretically it
1554 // would be possible to make the server code work with terminal Vim, but it
1555 // would require that a run-loop is set up and checked.  This should not be
1556 // difficult to implement, simply call gui_mch_update() at opportune moments
1557 // and it will take care of the run-loop.  Another (bigger) problem with
1558 // supporting servers in terminal mode is that the server listing code talks to
1559 // MacVim (the GUI) to figure out which servers are running.
1564  * Register connection with 'name'.  The actual connection is named something
1565  * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1566  */
1567     void
1568 serverRegisterName(char_u *name)
1570 #ifdef FEAT_MBYTE
1571     name = CONVERT_TO_UTF8(name);
1572 #endif
1574     NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1575     [[MMBackend sharedInstance] registerServerWithName:svrName];
1577 #ifdef FEAT_MBYTE
1578     CONVERT_TO_UTF8_FREE(name);
1579 #endif
1584  * Send to an instance of Vim.
1585  * Returns 0 for OK, negative for an error.
1586  */
1587     int
1588 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1589         int *port, int asExpr, int silent)
1591 #ifdef FEAT_MBYTE
1592     name = CONVERT_TO_UTF8(name);
1593     cmd = CONVERT_TO_UTF8(cmd);
1594 #endif
1596     BOOL ok = [[MMBackend sharedInstance]
1597             sendToServer:[NSString stringWithUTF8String:(char*)name]
1598                   string:[NSString stringWithUTF8String:(char*)cmd]
1599                    reply:result
1600                     port:port
1601               expression:asExpr
1602                   silent:silent];
1604 #ifdef FEAT_MBYTE
1605     CONVERT_TO_UTF8_FREE(name);
1606     CONVERT_TO_UTF8_FREE(cmd);
1607 #endif
1609     return ok ? 0 : -1;
1614  * Ask MacVim for the names of all Vim servers.
1615  */
1616     char_u *
1617 serverGetVimNames(void)
1619     char_u *names = NULL;
1620     NSArray *list = [[MMBackend sharedInstance] serverList];
1622     if (list) {
1623         NSString *string = [list componentsJoinedByString:@"\n"];
1624         char_u *s = (char_u*)[string UTF8String];
1625 #ifdef FEAT_MBYTE
1626         s = CONVERT_FROM_UTF8(s);
1627 #endif
1628         names = vim_strsave(s);
1629 #ifdef FEAT_MBYTE
1630         CONVERT_FROM_UTF8_FREE(s);
1631 #endif
1632     }
1634     return names;
1639  * 'str' is a hex int representing the send port of the connection.
1640  */
1641     int
1642 serverStrToPort(char_u *str)
1644     int port = 0;
1646     sscanf((char *)str, "0x%x", &port);
1647     if (!port)
1648         EMSG2(_("E573: Invalid server id used: %s"), str);
1650     return port;
1655  * Check for replies from server with send port 'port'.
1656  * Return TRUE and a non-malloc'ed string if there is.  Else return FALSE.
1657  */
1658     int
1659 serverPeekReply(int port, char_u **str)
1661     NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1662     int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1664     if (str && len > 0) {
1665         *str = (char_u*)[reply UTF8String];
1667 #ifdef FEAT_MBYTE
1668         if (input_conv.vc_type != CONV_NONE) {
1669             char_u *s = string_convert(&input_conv, *str, &len);
1671             if (len > 0) {
1672                 // HACK! Since 's' needs to be freed we cannot simply set
1673                 // '*str = s' or memory will leak.  Instead, create a dummy
1674                 // NSData and return its 'bytes' pointer, then autorelease the
1675                 // NSData.
1676                 NSData *data = [NSData dataWithBytes:s length:len+1];
1677                 *str = (char_u*)[data bytes];
1678             }
1680             vim_free(s);
1681         }
1682 #endif
1683     }
1685     return reply != nil;
1690  * Wait for replies from server with send port 'port'.
1691  * Return 0 and the malloc'ed string when a reply is available.
1692  * Return -1 on error.
1693  */
1694     int
1695 serverReadReply(int port, char_u **str)
1697     NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1698     if (reply && str) {
1699         char_u *s = (char_u*)[reply UTF8String];
1700 #ifdef FEAT_MBYTE
1701         s = CONVERT_FROM_UTF8(s);
1702 #endif
1703         *str = vim_strsave(s);
1704 #ifdef FEAT_MBYTE
1705         CONVERT_FROM_UTF8_FREE(s);
1706 #endif
1707         return 0;
1708     }
1710     return -1;
1715  * Send a reply string (notification) to client with port given by "serverid".
1716  * Return -1 if the window is invalid.
1717  */
1718     int
1719 serverSendReply(char_u *serverid, char_u *reply)
1721     int retval = -1;
1722     int port = serverStrToPort(serverid);
1723     if (port > 0 && reply) {
1724 #ifdef FEAT_MBYTE
1725         reply = CONVERT_TO_UTF8(reply);
1726 #endif
1727         BOOL ok = [[MMBackend sharedInstance]
1728                 sendReply:[NSString stringWithUTF8String:(char*)reply]
1729                    toPort:port];
1730         retval = ok ? 0 : -1;
1731 #ifdef FEAT_MBYTE
1732         CONVERT_TO_UTF8_FREE(reply);
1733 #endif
1734     }
1736     return retval;
1739 #endif // MAC_CLIENTSERVER
1744 // -- ODB Editor Support ----------------------------------------------------
1746 #ifdef FEAT_ODB_EDITOR
1748  * The ODB Editor protocol works like this:
1749  * - An external program (the server) asks MacVim to open a file and associates
1750  *   three things with this file: (1) a server id (a four character code that
1751  *   identifies the server), (2) a path that can be used as window title for
1752  *   the file (optional), (3) an arbitrary token (optional)
1753  * - When a file is saved or closed, MacVim should tell the server about which
1754  *   file was modified and also pass back the token
1756  * All communication between MacVim and the server goes via Apple Events.
1757  */
1759     static OSErr
1760 odb_event(buf_T *buf, const AEEventID action)
1762     if (!(buf->b_odb_server_id && buf->b_ffname))
1763         return noErr;
1765     NSAppleEventDescriptor *targetDesc = [NSAppleEventDescriptor
1766             descriptorWithDescriptorType:typeApplSignature
1767                                    bytes:&buf->b_odb_server_id
1768                                   length:sizeof(OSType)];
1770     NSString *path = [NSString stringWithUTF8String:(char*)buf->b_ffname];
1771     NSData *pathData = [[[NSURL fileURLWithPath:path] absoluteString]
1772             dataUsingEncoding:NSUTF8StringEncoding];
1773     NSAppleEventDescriptor *pathDesc = [NSAppleEventDescriptor
1774             descriptorWithDescriptorType:typeFileURL data:pathData];
1776     NSAppleEventDescriptor *event = [NSAppleEventDescriptor
1777             appleEventWithEventClass:kODBEditorSuite
1778                              eventID:action
1779                     targetDescriptor:targetDesc
1780                             returnID:kAutoGenerateReturnID
1781                        transactionID:kAnyTransactionID];
1783     [event setParamDescriptor:pathDesc forKeyword:keyDirectObject];
1785     if (buf->b_odb_token)
1786         [event setParamDescriptor:buf->b_odb_token forKeyword:keySenderToken];
1788     return AESendMessage([event aeDesc], NULL, kAENoReply | kAENeverInteract,
1789             kAEDefaultTimeout);
1792     OSErr
1793 odb_buffer_close(buf_T *buf)
1795     OSErr err = noErr;
1796     if (buf) {
1797         err = odb_event(buf, kAEClosedFile);
1799         buf->b_odb_server_id = 0;
1801         if (buf->b_odb_token) {
1802             [(NSAppleEventDescriptor *)(buf->b_odb_token) release];
1803             buf->b_odb_token = NULL;
1804         }
1806         if (buf->b_odb_fname) {
1807             vim_free(buf->b_odb_fname);
1808             buf->b_odb_fname = NULL;
1809         }
1810     }
1812     return err;
1815     OSErr
1816 odb_post_buffer_write(buf_T *buf)
1818     return buf ? odb_event(buf, kAEModifiedFile) : noErr;
1821     void
1822 odb_end(void)
1824     buf_T *buf;
1825     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1826         odb_buffer_close(buf);
1829 #endif // FEAT_ODB_EDITOR