Ignore gui_mch_update()
[MacVim.git] / src / MacVim / gui_macvim.m
blob39880d83bb8270ceb7aeff83014cca7490afbaa0
1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
2  *
3  * VIM - Vi IMproved            by Bram Moolenaar
4  *                              MacVim GUI port by Bjorn Winckler
5  *
6  * Do ":help uganda"  in Vim to read copying and usage conditions.
7  * Do ":help credits" in Vim to see a list of people who contributed.
8  * See README.txt for an overview of the Vim source code.
9  */
11  * gui_macvim.m
12  *
13  * Hooks for the Vim gui code.  Mainly passes control on to MMBackend.
14  */
16 #import "MMBackend.h"
17 #import "MacVim.h"
18 #import "vim.h"
19 #import <Foundation/Foundation.h>
23 // NOTE: The default font is bundled with the application.
24 static NSString *MMDefaultFontName = @"DejaVu Sans Mono";
25 static float MMDefaultFontSize = 12.0f;
26 static float MMMinFontSize = 6.0f;
27 static float MMMaxFontSize = 100.0f;
28 static BOOL gui_mch_init_has_finished = NO;
31 static NSFont *gui_macvim_font_with_name(char_u *name);
32 static int specialKeyToNSKey(int key);
33 static int vimModMaskToEventModifierFlags(int mods);
35 NSArray *descriptor_for_menu(vimmenu_T *menu);
36 vimmenu_T *menu_for_descriptor(NSArray *desc);
40 // -- Initialization --------------------------------------------------------
43  * Parse the GUI related command-line arguments.  Any arguments used are
44  * deleted from argv, and *argc is decremented accordingly.  This is called
45  * when vim is started, whether or not the GUI has been started.
46  */
47     void
48 gui_mch_prepare(int *argc, char **argv)
50     //NSLog(@"gui_mch_prepare(argc=%d)", *argc);
52     // Set environment variables $VIM and $VIMRUNTIME
53     // NOTE!  If vim_getenv is called with one of these as parameters before
54     // they have been set here, they will most likely end up with the wrong
55     // values!
56     //
57     // TODO:
58     // - ensure this is called first to avoid above problem
59     // - encoding
61     NSString *path = [[[NSBundle mainBundle] resourcePath]
62         stringByAppendingPathComponent:@"vim"];
63     vim_setenv((char_u*)"VIM", (char_u*)[path UTF8String]);
65     path = [path stringByAppendingPathComponent:@"runtime"];
66     vim_setenv((char_u*)"VIMRUNTIME", (char_u*)[path UTF8String]);
68     int i;
69     for (i = 0; i < *argc; ++i) {
70         if (strncmp(argv[i], "--mmwaitforack", 14) == 0) {
71             [[MMBackend sharedInstance] setWaitForAck:YES];
72             --*argc;
73             if (*argc > i)
74                 mch_memmove(&argv[i], &argv[i+1], (*argc-i) * sizeof(char*));
75             break;
76         }
77     }
82  * Check if the GUI can be started.  Called before gvimrc is sourced.
83  * Return OK or FAIL.
84  */
85     int
86 gui_mch_init_check(void)
88     //NSLog(@"gui_mch_init_check()");
89     return OK;
94  * Initialise the GUI.  Create all the windows, set up all the call-backs etc.
95  * Returns OK for success, FAIL when the GUI can't be started.
96  */
97     int
98 gui_mch_init(void)
100     //NSLog(@"gui_mch_init()");
102     // NOTE! Because OS X has to exec after fork we effectively end up doing
103     // the initialization twice (because this function is called before the
104     // fork).  To avoid all this extra work we check if Vim is about to fork,
105     // and if so do nothing for now.
106     //
107     // TODO: Is this check 100% foolproof?
108     if (gui.dofork && (vim_strchr(p_go, GO_FORG) == NULL))
109         return OK;
111     if (![[MMBackend sharedInstance] checkin]) {
112         // TODO: Kill the process if there is no terminal to fall back on,
113         // otherwise the process will run outputting to the console.
114         return FAIL;
115     }
117     // Force 'termencoding' to utf-8 (changes to 'tenc' are disallowed in
118     // 'option.c', so that ':set termencoding=...' is impossible).
119     set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
121     // Set values so that pixels and characters are in one-to-one
122     // correspondence (assuming all characters have the same dimensions).
123     gui.scrollbar_width = gui.scrollbar_height = 0;
125     gui.char_height = 1;
126     gui.char_width = 1;
127     gui.char_ascent = 0;
129     gui_mch_def_colors();
131     [[MMBackend sharedInstance]
132         setDefaultColorsBackground:gui.back_pixel foreground:gui.norm_pixel];
133     [[MMBackend sharedInstance] setBackgroundColor:gui.back_pixel];
134     [[MMBackend sharedInstance] setForegroundColor:gui.norm_pixel];
136     // NOTE: If this call is left out the cursor is opaque.
137     highlight_gui_started();
139     // Ensure 'linespace' option is passed along to MacVim in case it was set
140     // in [g]vimrc.
141     gui_mch_adjust_charheight();
143     gui_mch_init_has_finished = YES;
145     return OK;
150     void
151 gui_mch_exit(int rc)
153     //NSLog(@"gui_mch_exit(rc=%d)", rc);
155     [[MMBackend sharedInstance] exit];
160  * Open the GUI window which was created by a call to gui_mch_init().
161  */
162     int
163 gui_mch_open(void)
165     //NSLog(@"gui_mch_open()");
167     // This check is to avoid doing extra work when we're about to fork.
168     if (!gui_mch_init_has_finished)
169         return OK;
171     return [[MMBackend sharedInstance] openGUIWindow];
175 // -- Updating --------------------------------------------------------------
179  * Catch up with any queued X events.  This may put keyboard input into the
180  * input buffer, call resize call-backs, trigger timers etc.  If there is
181  * nothing in the X event queue (& no timers pending), then we return
182  * immediately.
183  */
184     void
185 gui_mch_update(void)
187     // This function is called extremely often.  By doing nothing here the
188     // frame-rate is increased dramatically in certain situations.  However,
189     // the downside is that it is often not possible to interrupt Vim with
190     // Ctrl-C when it is busy processing.
194 /* Flush any output to the screen */
195     void
196 gui_mch_flush(void)
198     // This function is called way too often to be useful as a hint for
199     // flushing.  If we were to flush every time it was called the screen would
200     // flicker.
204 /* Force flush output to MacVim.  Do not call this method unless absolutely
205  * necessary. */
206     void
207 gui_macvim_force_flush(void)
209     [[MMBackend sharedInstance] flushQueue:YES];
214  * GUI input routine called by gui_wait_for_chars().  Waits for a character
215  * from the keyboard.
216  *  wtime == -1     Wait forever.
217  *  wtime == 0      This should never happen.
218  *  wtime > 0       Wait wtime milliseconds for a character.
219  * Returns OK if a character was found to be available within the given time,
220  * or FAIL otherwise.
221  */
222     int
223 gui_mch_wait_for_chars(int wtime)
225     // NOTE! In all likelihood Vim will take a nap when waitForInput: is
226     // called, so force a flush of the command queue here.
227     [[MMBackend sharedInstance] flushQueue:YES];
229     return [[MMBackend sharedInstance] waitForInput:wtime];
233 // -- Drawing ---------------------------------------------------------------
237  * Clear the whole text window.
238  */
239     void
240 gui_mch_clear_all(void)
242     [[MMBackend sharedInstance] clearAll];
247  * Clear a rectangular region of the screen from text pos (row1, col1) to
248  * (row2, col2) inclusive.
249  */
250     void
251 gui_mch_clear_block(int row1, int col1, int row2, int col2)
253     [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
254                                                     toRow:row2 column:col2];
259  * Delete the given number of lines from the given row, scrolling up any
260  * text further down within the scroll region.
261  */
262     void
263 gui_mch_delete_lines(int row, int num_lines)
265     [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
266             scrollBottom:gui.scroll_region_bot
267                     left:gui.scroll_region_left
268                    right:gui.scroll_region_right];
272     void
273 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
275 #ifdef FEAT_MBYTE
276     char_u *conv_str = NULL;
277     if (output_conv.vc_type != CONV_NONE) {
278         conv_str = string_convert(&output_conv, s, &len);
279         if (conv_str)
280             s = conv_str;
281     }
282 #endif
284     [[MMBackend sharedInstance] drawString:(char*)s length:len row:row
285                                     column:col cells:len flags:flags];
287 #ifdef FEAT_MBYTE
288     if (conv_str)
289         vim_free(conv_str);
290 #endif
294     int
295 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
297     int c, cn, cl, i;
298     int start = 0;
299     int endcol = col;
300     int startcol = col;
301     BOOL wide = NO;
302     MMBackend *backend = [MMBackend sharedInstance];
303 #ifdef FEAT_MBYTE
304     char_u *conv_str = NULL;
306     if (output_conv.vc_type != CONV_NONE) {
307         conv_str = string_convert(&output_conv, s, &len);
308         if (conv_str)
309             s = conv_str;
310     }
311 #endif
313     // Loop over each character and output text when it changes from normal to
314     // wide and vice versa.
315     for (i = 0; i < len; i += cl) {
316         c = utf_ptr2char(s + i);
317         cl = utf_ptr2len(s + i);
318         cn = utf_char2cells(c);
320         if (!utf_iscomposing(c)) {
321             if ((cn > 1 && !wide) || (cn <= 1 && wide)) {
322                 // Changed from normal to wide or vice versa.
323                 [backend drawString:(char*)(s+start) length:i-start
324                                    row:row column:startcol
325                                  cells:endcol-startcol
326                                  flags:(wide ? flags|DRAW_WIDE : flags)];
328                 start = i;
329                 startcol = endcol;
330             }
332             wide = cn > 1;
333             endcol += cn;
334         }
335     }
337     // Output remaining characters.
338     [backend drawString:(char*)(s+start) length:len-start
339                     row:row column:startcol cells:endcol-startcol
340                   flags:(wide ? flags|DRAW_WIDE : flags)];
342 #ifdef FEAT_MBYTE
343     if (conv_str)
344         vim_free(conv_str);
345 #endif
347     return endcol - col;
352  * Insert the given number of lines before the given row, scrolling down any
353  * following text within the scroll region.
354  */
355     void
356 gui_mch_insert_lines(int row, int num_lines)
358     [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
359             scrollBottom:gui.scroll_region_bot
360                     left:gui.scroll_region_left
361                    right:gui.scroll_region_right];
366  * Set the current text foreground color.
367  */
368     void
369 gui_mch_set_fg_color(guicolor_T color)
371     [[MMBackend sharedInstance] setForegroundColor:color];
376  * Set the current text background color.
377  */
378     void
379 gui_mch_set_bg_color(guicolor_T color)
381     [[MMBackend sharedInstance] setBackgroundColor:color];
386  * Set the current text special color (used for underlines).
387  */
388     void
389 gui_mch_set_sp_color(guicolor_T color)
391     [[MMBackend sharedInstance] setSpecialColor:color];
396  * Set default colors.
397  */
398     void
399 gui_mch_def_colors()
401     MMBackend *backend = [MMBackend sharedInstance];
403     // The default colors are taken from system values
404     gui.def_norm_pixel = gui.norm_pixel = 
405         [backend lookupColorWithKey:@"MacTextColor"];
406     gui.def_back_pixel = gui.back_pixel = 
407         [backend lookupColorWithKey:@"MacTextBackgroundColor"];
412  * Called when the foreground or background color has been changed.
413  */
414     void
415 gui_mch_new_colors(void)
417     gui.def_back_pixel = gui.back_pixel;
418     gui.def_norm_pixel = gui.norm_pixel;
420     //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
421     //        gui.def_norm_pixel);
423     [[MMBackend sharedInstance]
424         setDefaultColorsBackground:gui.def_back_pixel
425                         foreground:gui.def_norm_pixel];
429  * Invert a rectangle from row r, column c, for nr rows and nc columns.
430  */
431     void
432 gui_mch_invert_rectangle(int r, int c, int nr, int nc, int invert)
434     [[MMBackend sharedInstance] drawInvertedRectAtRow:r column:c numRows:nr
435             numColumns:nc invert:invert];
440 // -- Tabline ---------------------------------------------------------------
444  * Set the current tab to "nr".  First tab is 1.
445  */
446     void
447 gui_mch_set_curtab(int nr)
449     [[MMBackend sharedInstance] selectTab:nr];
454  * Return TRUE when tabline is displayed.
455  */
456     int
457 gui_mch_showing_tabline(void)
459     return [[MMBackend sharedInstance] tabBarVisible];
463  * Update the labels of the tabline.
464  */
465     void
466 gui_mch_update_tabline(void)
468     [[MMBackend sharedInstance] updateTabBar];
472  * Show or hide the tabline.
473  */
474     void
475 gui_mch_show_tabline(int showit)
477     [[MMBackend sharedInstance] showTabBar:showit];
481 // -- Clipboard -------------------------------------------------------------
484     void
485 clip_mch_lose_selection(VimClipboard *cbd)
490     int
491 clip_mch_own_selection(VimClipboard *cbd)
493     return 0;
497     void
498 clip_mch_request_selection(VimClipboard *cbd)
500     NSPasteboard *pb = [NSPasteboard generalPasteboard];
501     NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
502             NSStringPboardType, nil];
503     NSString *bestType = [pb availableTypeFromArray:supportedTypes];
504     if (!bestType) return;
506     int motion_type = MCHAR;
507     NSString *string = nil;
509     if ([bestType isEqual:VimPBoardType]) {
510         // This type should consist of an array with two objects:
511         //   1. motion type (NSNumber)
512         //   2. text (NSString)
513         // If this is not the case we fall back on using NSStringPboardType.
514         id plist = [pb propertyListForType:VimPBoardType];
515         if ([plist isKindOfClass:[NSArray class]] && [plist count] == 2) {
516             id obj = [plist objectAtIndex:1];
517             if ([obj isKindOfClass:[NSString class]]) {
518                 motion_type = [[plist objectAtIndex:0] intValue];
519                 string = obj;
520             }
521         }
522     }
524     if (!string) {
525         // Use NSStringPboardType.  The motion type is set to line-wise if the
526         // string contains at least one EOL character, otherwise it is set to
527         // character-wise (block-wise is never used).
528         NSMutableString *mstring =
529                 [[pb stringForType:NSStringPboardType] mutableCopy];
530         if (!mstring) return;
532         // Replace unrecognized end-of-line sequences with \x0a (line feed).
533         NSRange range = { 0, [mstring length] };
534         unsigned n = [mstring replaceOccurrencesOfString:@"\x0d\x0a"
535                                              withString:@"\x0a" options:0
536                                                   range:range];
537         if (0 == n) {
538             n = [mstring replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
539                                            options:0 range:range];
540         }
541         
542         // Scan for newline character to decide whether the string should be
543         // pasted line-wise or character-wise.
544         motion_type = MCHAR;
545         if (0 < n || NSNotFound != [mstring rangeOfString:@"\n"].location)
546             motion_type = MLINE;
548         string = mstring;
549     }
551     if (!(MCHAR == motion_type || MLINE == motion_type || MBLOCK == motion_type
552             || MAUTO == motion_type))
553         motion_type = MCHAR;
555     char_u *str = (char_u*)[string UTF8String];
556     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
558 #ifdef FEAT_MBYTE
559     if (input_conv.vc_type != CONV_NONE)
560         str = string_convert(&input_conv, str, &len);
561 #endif
563     if (str)
564         clip_yank_selection(motion_type, str, len, cbd);
566 #ifdef FEAT_MBYTE
567     if (input_conv.vc_type != CONV_NONE)
568         vim_free(str);
569 #endif
574  * Send the current selection to the clipboard.
575  */
576     void
577 clip_mch_set_selection(VimClipboard *cbd)
579     // If the '*' register isn't already filled in, fill it in now.
580     cbd->owned = TRUE;
581     clip_get_selection(cbd);
582     cbd->owned = FALSE;
583     
584     // Get the text to put on the pasteboard.
585     long_u llen = 0; char_u *str = 0;
586     int motion_type = clip_convert_selection(&str, &llen, cbd);
587     if (motion_type < 0)
588         return;
590     // TODO: Avoid overflow.
591     int len = (int)llen;
592 #ifdef FEAT_MBYTE
593     if (output_conv.vc_type != CONV_NONE) {
594         char_u *conv_str = string_convert(&output_conv, str, &len);
595         if (conv_str) {
596             vim_free(str);
597             str = conv_str;
598         }
599     }
600 #endif
602     if (len > 0) {
603         NSString *string = [[NSString alloc]
604             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
606         // See clip_mch_request_selection() for info on pasteboard types.
607         NSPasteboard *pb = [NSPasteboard generalPasteboard];
608         NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
609                 NSStringPboardType, nil];
610         [pb declareTypes:supportedTypes owner:nil];
612         NSNumber *motion = [NSNumber numberWithInt:motion_type];
613         NSArray *plist = [NSArray arrayWithObjects:motion, string, nil];
614         [pb setPropertyList:plist forType:VimPBoardType];
616         [pb setString:string forType:NSStringPboardType];
617         
618         [string release];
619     }
621     vim_free(str);
625 // -- Menu ------------------------------------------------------------------
629  * A menu descriptor represents the "address" of a menu as an array of strings.
630  * E.g. the menu "File->Close" has descriptor { "File", "Close" }.
631  */
632     NSArray *
633 descriptor_for_menu(vimmenu_T *menu)
635     if (!menu) return nil;
637     NSMutableArray *desc = [NSMutableArray array];
638     while (menu) {
639         NSString *name = [NSString stringWithVimString:menu->dname];
640         [desc insertObject:name atIndex:0];
641         menu = menu->parent;
642     }
644     return desc;
647     vimmenu_T *
648 menu_for_descriptor(NSArray *desc)
650     if (!(desc && [desc count] > 0)) return NULL;
652     vimmenu_T *menu = root_menu;
653     int i, count = [desc count];
655     for (i = 0; i < count; ++i) {
656         NSString *component = [desc objectAtIndex:i];
657         while (menu) {
658             NSString *name = [NSString stringWithVimString:menu->dname];
659             if ([component isEqual:name]) {
660                 if (i+1 == count)
661                     return menu;    // Matched all components, so return menu
662                 menu = menu->children;
663                 break;
664             }
665             menu = menu->next;
666         }
667     }
669     return NULL;
673  * Add a submenu to the menu bar, toolbar, or a popup menu.
674  */
675     void
676 gui_mch_add_menu(vimmenu_T *menu, int idx)
678     NSArray *desc = descriptor_for_menu(menu);
679     [[MMBackend sharedInstance] queueMessage:AddMenuMsgID properties:
680         [NSDictionary dictionaryWithObjectsAndKeys:
681             desc, @"descriptor",
682             [NSNumber numberWithInt:idx], @"index",
683             nil]];
688  * Add a menu item to a menu
689  */
690     void
691 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
693     char_u *tip = menu->strings[MENU_INDEX_TIP]
694             ? menu->strings[MENU_INDEX_TIP] : menu->actext;
695     NSArray *desc = descriptor_for_menu(menu);
696     NSString *keyEquivalent = menu->mac_key
697         ? [NSString stringWithFormat:@"%C", specialKeyToNSKey(menu->mac_key)]
698         : [NSString string];
699     int modifierMask = vimModMaskToEventModifierFlags(menu->mac_mods);
700     char_u *icon = NULL;
702     if (menu_is_toolbar(menu->parent->name)) {
703         char_u fname[MAXPATHL];
705         // TODO: Ensure menu->iconfile exists (if != NULL)
706         icon = menu->iconfile;
707         if (!icon && gui_find_bitmap(menu->name, fname, "bmp") == OK)
708             icon = fname;
709         if (!icon && menu->iconidx >= 0)
710             icon = menu->dname;
711     }
713     [[MMBackend sharedInstance] queueMessage:AddMenuItemMsgID properties:
714         [NSDictionary dictionaryWithObjectsAndKeys:
715             desc, @"descriptor",
716             [NSNumber numberWithInt:idx], @"index",
717             [NSString stringWithVimString:tip], @"tip",
718             [NSString stringWithVimString:icon], @"icon",
719             keyEquivalent, @"keyEquivalent",
720             [NSNumber numberWithInt:modifierMask], @"modifierMask",
721             [NSString stringWithVimString:menu->mac_action], @"action",
722             [NSNumber numberWithBool:menu->mac_alternate], @"isAlternate",
723             nil]];
728  * Destroy the machine specific menu widget.
729  */
730     void
731 gui_mch_destroy_menu(vimmenu_T *menu)
733     NSArray *desc = descriptor_for_menu(menu);
734     [[MMBackend sharedInstance] queueMessage:RemoveMenuItemMsgID properties:
735         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
740  * Make a menu either grey or not grey.
741  */
742     void
743 gui_mch_menu_grey(vimmenu_T *menu, int grey)
745     /* Only update menu if the 'grey' state has changed to avoid having to pass
746      * lots of unnecessary data to MacVim.  (Skipping this test makes MacVim
747      * pause noticably on mode changes. */
748     NSArray *desc = descriptor_for_menu(menu);
749     if (menu->was_grey == grey)
750         return;
752     menu->was_grey = grey;
754     [[MMBackend sharedInstance] queueMessage:EnableMenuItemMsgID properties:
755         [NSDictionary dictionaryWithObjectsAndKeys:
756             desc, @"descriptor",
757             [NSNumber numberWithInt:!grey], @"enable",
758             nil]];
763  * Make menu item hidden or not hidden
764  */
765     void
766 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
768     // HACK! There is no (obvious) way to hide a menu item, so simply
769     // enable/disable it instead.
770     gui_mch_menu_grey(menu, hidden);
775  * This is called when user right clicks.
776  */
777     void
778 gui_mch_show_popupmenu(vimmenu_T *menu)
780     NSArray *desc = descriptor_for_menu(menu);
781     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:
782         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
787  * This is called when a :popup command is executed.
788  */
789     void
790 gui_make_popup(char_u *path_name, int mouse_pos)
792     vimmenu_T *menu = gui_find_menu(path_name);
793     if (!(menu && menu->children)) return;
795     NSArray *desc = descriptor_for_menu(menu);
796     NSDictionary *p = (mouse_pos || NULL == curwin)
797         ? [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]
798         : [NSDictionary dictionaryWithObjectsAndKeys:
799             desc, @"descriptor",
800             [NSNumber numberWithInt:curwin->w_wrow], @"row",
801             [NSNumber numberWithInt:curwin->w_wcol], @"column",
802             nil];
804     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:p];
809  * This is called after setting all the menus to grey/hidden or not.
810  */
811     void
812 gui_mch_draw_menubar(void)
814     // The (main) menu draws itself in Mac OS X.
818     void
819 gui_mch_enable_menu(int flag)
821     // The (main) menu is always enabled in Mac OS X.
825 #if 0
826     void
827 gui_mch_set_menu_pos(int x, int y, int w, int h)
829     // The (main) menu cannot be moved in Mac OS X.
831 #endif
834     void
835 gui_mch_show_toolbar(int showit)
837     int flags = 0;
838     if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
839     if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
840     if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
842     [[MMBackend sharedInstance] showToolbar:showit flags:flags];
848 // -- Fonts -----------------------------------------------------------------
852  * If a font is not going to be used, free its structure.
853  */
854     void
855 gui_mch_free_font(font)
856     GuiFont     font;
858     if (font != NOFONT) {
859         //NSLog(@"gui_mch_free_font(font=0x%x)", font);
860         [(NSFont*)font release];
861     }
866  * Get a font structure for highlighting.
867  */
868     GuiFont
869 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
871     //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
872     //        giveErrorIfMissing);
874     NSFont *font = gui_macvim_font_with_name(name);
875     if (font)
876         return (GuiFont)[font retain];
878     if (giveErrorIfMissing)
879         EMSG2(_(e_font), name);
881     return NOFONT;
885 #if defined(FEAT_EVAL) || defined(PROTO)
887  * Return the name of font "font" in allocated memory.
888  * Don't know how to get the actual name, thus use the provided name.
889  */
890     char_u *
891 gui_mch_get_fontname(GuiFont font, char_u *name)
893     if (name == NULL)
894         return NULL;
895     return vim_strsave(name);
897 #endif
901  * Initialise vim to use the font with the given name.  Return FAIL if the font
902  * could not be loaded, OK otherwise.
903  */
904     int
905 gui_mch_init_font(char_u *font_name, int fontset)
907     //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
909     if (font_name && STRCMP(font_name, "*") == 0) {
910         // :set gfn=* shows the font panel.
911         do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
912         return FAIL;
913     }
915     NSFont *font = gui_macvim_font_with_name(font_name);
916     if (font) {
917         [(NSFont*)gui.norm_font release];
918         gui.norm_font = (GuiFont)[font retain];
920         // NOTE: MacVim keeps separate track of the normal and wide fonts.
921         // Unless the user changes 'guifontwide' manually, they are based on
922         // the same (normal) font.  Also note that each time the normal font is
923         // set, the advancement may change so the wide font needs to be updated
924         // as well (so that it is always twice the width of the normal font).
925         [[MMBackend sharedInstance] setFont:font];
926         [[MMBackend sharedInstance] setWideFont:
927                (NOFONT == gui.wide_font ? font : (NSFont*)gui.wide_font)];
929         return OK;
930     }
932     return FAIL;
937  * Set the current text font.
938  */
939     void
940 gui_mch_set_font(GuiFont font)
942     // Font selection is done inside MacVim...nothing here to do.
946     NSFont *
947 gui_macvim_font_with_name(char_u *name)
949     NSFont *font = nil;
950     NSString *fontName = MMDefaultFontName;
951     float size = MMDefaultFontSize;
952     BOOL parseFailed = NO;
954 #ifdef FEAT_MBYTE
955     name = CONVERT_TO_UTF8(name);
956 #endif
958     if (name) {
959         fontName = [NSString stringWithUTF8String:(char*)name];
961         NSArray *components = [fontName componentsSeparatedByString:@":"];
962         if ([components count] == 2) {
963             NSString *sizeString = [components lastObject];
964             if ([sizeString length] > 0
965                     && [sizeString characterAtIndex:0] == 'h') {
966                 sizeString = [sizeString substringFromIndex:1];
967                 if ([sizeString length] > 0) {
968                     size = [sizeString floatValue];
969                     fontName = [components objectAtIndex:0];
970                 }
971             } else {
972                 parseFailed = YES;
973             }
974         } else if ([components count] > 2) {
975             parseFailed = YES;
976         }
978         if (!parseFailed) {
979             // Replace underscores with spaces.
980             fontName = [[fontName componentsSeparatedByString:@"_"]
981                                      componentsJoinedByString:@" "];
982         }
983     }
985     if (!parseFailed && [fontName length] > 0) {
986         if (size < MMMinFontSize) size = MMMinFontSize;
987         if (size > MMMaxFontSize) size = MMMaxFontSize;
989         font = [NSFont fontWithName:fontName size:size];
991         if (!font && MMDefaultFontName == fontName) {
992             // If for some reason the MacVim default font is not in the app
993             // bundle, then fall back on the system default font.
994             font = [NSFont userFixedPitchFontOfSize:0];
995         }
996     }
998 #ifdef FEAT_MBYTE
999     CONVERT_TO_UTF8_FREE(name);
1000 #endif
1002     return font;
1005 // -- Scrollbars ------------------------------------------------------------
1008     void
1009 gui_mch_create_scrollbar(
1010         scrollbar_T *sb,
1011         int orient)     /* SBAR_VERT or SBAR_HORIZ */
1013     [[MMBackend sharedInstance] 
1014             createScrollbarWithIdentifier:sb->ident type:sb->type];
1018     void
1019 gui_mch_destroy_scrollbar(scrollbar_T *sb)
1021     [[MMBackend sharedInstance] 
1022             destroyScrollbarWithIdentifier:sb->ident];
1026     void
1027 gui_mch_enable_scrollbar(
1028         scrollbar_T     *sb,
1029         int             flag)
1031     [[MMBackend sharedInstance] 
1032             showScrollbarWithIdentifier:sb->ident state:flag];
1036     void
1037 gui_mch_set_scrollbar_pos(
1038         scrollbar_T *sb,
1039         int x,
1040         int y,
1041         int w,
1042         int h)
1044     int pos = y;
1045     int len = h;
1046     if (SBAR_BOTTOM == sb->type) {
1047         pos = x;
1048         len = w; 
1049     }
1051     [[MMBackend sharedInstance] 
1052             setScrollbarPosition:pos length:len identifier:sb->ident];
1056     void
1057 gui_mch_set_scrollbar_thumb(
1058         scrollbar_T *sb,
1059         long val,
1060         long size,
1061         long max)
1063     [[MMBackend sharedInstance] 
1064             setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
1068 // -- Cursor ----------------------------------------------------------------
1072  * Draw a cursor without focus.
1073  */
1074     void
1075 gui_mch_draw_hollow_cursor(guicolor_T color)
1077     return [[MMBackend sharedInstance]
1078         drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
1079                fraction:100 color:color];
1084  * Draw part of a cursor, only w pixels wide, and h pixels high.
1085  */
1086     void
1087 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
1089     // HACK!  'w' and 'h' are always 1 since we do not tell Vim about the exact
1090     // font dimensions.  Thus these parameters are useless.  Instead we look at
1091     // the shape_table to determine the shape and size of the cursor (just like
1092     // gui_update_cursor() does).
1094 #ifdef FEAT_RIGHTLEFT
1095     // If 'rl' is set the insert mode cursor must be drawn on the right-hand
1096     // side of a text cell.
1097     int rl = curwin ? curwin->w_p_rl : FALSE;
1098 #else
1099     int rl = FALSE;
1100 #endif
1101     int idx = get_shape_idx(FALSE);
1102     int shape = MMInsertionPointBlock;
1103     switch (shape_table[idx].shape) {
1104         case SHAPE_HOR:
1105             shape = MMInsertionPointHorizontal;
1106             break;
1107         case SHAPE_VER:
1108             shape = rl ? MMInsertionPointVerticalRight
1109                        : MMInsertionPointVertical;
1110             break;
1111     }
1113     return [[MMBackend sharedInstance]
1114         drawCursorAtRow:gui.row column:gui.col shape:shape
1115                fraction:shape_table[idx].percentage color:color];
1120  * Cursor blink functions.
1122  * This is a simple state machine:
1123  * BLINK_NONE   not blinking at all
1124  * BLINK_OFF    blinking, cursor is not shown
1125  * BLINK_ON blinking, cursor is shown
1126  */
1127     void
1128 gui_mch_set_blinking(long wait, long on, long off)
1130     [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1135  * Start the cursor blinking.  If it was already blinking, this restarts the
1136  * waiting time and shows the cursor.
1137  */
1138     void
1139 gui_mch_start_blink(void)
1141     [[MMBackend sharedInstance] startBlink];
1146  * Stop the cursor blinking.  Show the cursor if it wasn't shown.
1147  */
1148     void
1149 gui_mch_stop_blink(void)
1151     [[MMBackend sharedInstance] stopBlink];
1155 // -- Mouse -----------------------------------------------------------------
1159  * Get current mouse coordinates in text window.
1160  */
1161     void
1162 gui_mch_getmouse(int *x, int *y)
1164     //NSLog(@"gui_mch_getmouse()");
1168     void
1169 gui_mch_setmouse(int x, int y)
1171     //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1175     void
1176 mch_set_mouse_shape(int shape)
1178     [[MMBackend sharedInstance] setMouseShape:shape];
1184 // -- Input Method ----------------------------------------------------------
1186 #if defined(USE_IM_CONTROL)
1188     void
1189 im_set_position(int row, int col)
1191     // The pre-edit area is a popup window which is displayed by MMTextView.
1192     [[MMBackend sharedInstance] setPreEditRow:row column:col];
1196     void
1197 im_set_active(int active)
1199     // Set roman or the system script if 'active' is TRUE or FALSE,
1200     // respectively.
1201     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1203     if (!p_imdisable && smRoman != systemScript)
1204         KeyScript(active ? smKeySysScript : smKeyRoman);
1208     int
1209 im_get_status(void)
1211     // IM is active whenever the current script is the system script and the
1212     // system script isn't roman.  (Hence IM can only be active when using
1213     // non-roman scripts.)
1214     SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
1215     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1217     return currentScript != smRoman && currentScript == systemScript;
1220 #endif // defined(USE_IM_CONTROL)
1225 // -- Unsorted --------------------------------------------------------------
1228     void
1229 ex_macaction(eap)
1230     exarg_T     *eap;
1232     if (!gui.in_use) {
1233         EMSG(_("E???: Command only available in GUI mode"));
1234         return;
1235     }
1237     char_u *arg = eap->arg;
1238 #ifdef FEAT_MBYTE
1239     arg = CONVERT_TO_UTF8(arg);
1240 #endif
1242     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1243     NSString *name = [NSString stringWithUTF8String:(char*)arg];
1244     if (actionDict && [actionDict objectForKey:name] != nil) {
1245         [[MMBackend sharedInstance] executeActionWithName:name];
1246     } else {
1247         EMSG2(_("E???: Invalid action: %s"), eap->arg);
1248     }
1250 #ifdef FEAT_MBYTE
1251     arg = CONVERT_TO_UTF8(arg);
1252 #endif
1257  * Adjust gui.char_height (after 'linespace' was changed).
1258  */
1259     int
1260 gui_mch_adjust_charheight(void)
1262     [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1263     return OK;
1267     void
1268 gui_mch_beep(void)
1270     NSBeep();
1275 #ifdef FEAT_BROWSE
1277  * Pop open a file browser and return the file selected, in allocated memory,
1278  * or NULL if Cancel is hit.
1279  *  saving  - TRUE if the file will be saved to, FALSE if it will be opened.
1280  *  title   - Title message for the file browser dialog.
1281  *  dflt    - Default name of file.
1282  *  ext     - Default extension to be added to files without extensions.
1283  *  initdir - directory in which to open the browser (NULL = current dir)
1284  *  filter  - Filter for matched files to choose from.
1285  *  Has a format like this:
1286  *  "C Files (*.c)\0*.c\0"
1287  *  "All Files\0*.*\0\0"
1288  *  If these two strings were concatenated, then a choice of two file
1289  *  filters will be selectable to the user.  Then only matching files will
1290  *  be shown in the browser.  If NULL, the default allows all files.
1292  *  *NOTE* - the filter string must be terminated with TWO nulls.
1293  */
1294     char_u *
1295 gui_mch_browse(
1296     int saving,
1297     char_u *title,
1298     char_u *dflt,
1299     char_u *ext,
1300     char_u *initdir,
1301     char_u *filter)
1303     //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1304     //        " filter=%s", saving, title, dflt, ext, initdir, filter);
1306     // Ensure no data is on the output queue before presenting the dialog.
1307     gui_macvim_force_flush();
1309     NSMutableDictionary *attr = [NSMutableDictionary
1310         dictionaryWithObject:[NSNumber numberWithBool:saving]
1311                       forKey:@"saving"];
1312     if (initdir)
1313         [attr setObject:[NSString stringWithVimString:initdir] forKey:@"dir"];
1315     char_u *s = (char_u*)[[MMBackend sharedInstance]
1316                             browseForFileWithAttributes:attr];
1318     return s;
1320 #endif /* FEAT_BROWSE */
1324     int
1325 gui_mch_dialog(
1326     int         type,
1327     char_u      *title,
1328     char_u      *message,
1329     char_u      *buttons,
1330     int         dfltbutton,
1331     char_u      *textfield)
1333     //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1334     //        "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1335     //        dfltbutton, textfield);
1337     // Ensure no data is on the output queue before presenting the dialog.
1338     gui_macvim_force_flush();
1340     int style = NSInformationalAlertStyle;
1341     if (VIM_WARNING == type) style = NSWarningAlertStyle;
1342     else if (VIM_ERROR == type) style = NSCriticalAlertStyle;
1344     NSMutableDictionary *attr = [NSMutableDictionary
1345                         dictionaryWithObject:[NSNumber numberWithInt:style]
1346                                       forKey:@"alertStyle"];
1348     if (buttons) {
1349         // 'buttons' is a string of '\n'-separated button titles 
1350         NSString *string = [NSString stringWithVimString:buttons];
1351         NSArray *array = [string componentsSeparatedByString:@"\n"];
1352         [attr setObject:array forKey:@"buttonTitles"];
1353     }
1355     NSString *messageText = nil;
1356     if (title)
1357         messageText = [NSString stringWithVimString:title];
1359     if (message) {
1360         NSString *informativeText = [NSString stringWithVimString:message];
1361         if (!messageText) {
1362             // HACK! If there is a '\n\n' or '\n' sequence in the message, then
1363             // make the part up to there into the title.  We only do this
1364             // because Vim has lots of dialogs without a title and they look
1365             // ugly that way.
1366             // TODO: Fix the actual dialog texts.
1367             NSRange eolRange = [informativeText rangeOfString:@"\n\n"];
1368             if (NSNotFound == eolRange.location)
1369                 eolRange = [informativeText rangeOfString:@"\n"];
1370             if (NSNotFound != eolRange.location) {
1371                 messageText = [informativeText substringToIndex:
1372                                                         eolRange.location];
1373                 informativeText = [informativeText substringFromIndex:
1374                                                         NSMaxRange(eolRange)];
1375             }
1376         }
1378         [attr setObject:informativeText forKey:@"informativeText"];
1379     }
1381     if (messageText)
1382         [attr setObject:messageText forKey:@"messageText"];
1384     if (textfield) {
1385         NSString *string = [NSString stringWithVimString:textfield];
1386         [attr setObject:string forKey:@"textFieldString"];
1387     }
1389     return [[MMBackend sharedInstance] showDialogWithAttributes:attr
1390                                                     textField:(char*)textfield];
1394     void
1395 gui_mch_flash(int msec)
1401  * Return the Pixel value (color) for the given color name.  This routine was
1402  * pretty much taken from example code in the Silicon Graphics OSF/Motif
1403  * Programmer's Guide.
1404  * Return INVALCOLOR when failed.
1405  */
1406     guicolor_T
1407 gui_mch_get_color(char_u *name)
1409 #ifdef FEAT_MBYTE
1410     name = CONVERT_TO_UTF8(name);
1411 #endif
1413     NSString *key = [NSString stringWithUTF8String:(char*)name];
1414     guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1416 #ifdef FEAT_MBYTE
1417     CONVERT_TO_UTF8_FREE(name);
1418 #endif
1420     return col;
1425  * Return the RGB value of a pixel as long.
1426  */
1427     long_u
1428 gui_mch_get_rgb(guicolor_T pixel)
1430     // This is only implemented so that vim can guess the correct value for
1431     // 'background' (which otherwise defaults to 'dark'); it is not used for
1432     // anything else (as far as I know).
1433     // The implementation is simple since colors are stored in an int as
1434     // "rrggbb".
1435     return pixel;
1440  * Get the screen dimensions.
1441  * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1442  * Is there no way to find out how wide the borders really are?
1443  * TODO: Add live udate of those value on suspend/resume.
1444  */
1445     void
1446 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1448     //NSLog(@"gui_mch_get_screen_dimensions()");
1449     *screen_w = Columns;
1450     *screen_h = Rows;
1455  * Get the position of the top left corner of the window.
1456  */
1457     int
1458 gui_mch_get_winpos(int *x, int *y)
1460     *x = *y = 0;
1461     return OK;
1466  * Return OK if the key with the termcap name "name" is supported.
1467  */
1468     int
1469 gui_mch_haskey(char_u *name)
1471     BOOL ok = NO;
1473 #ifdef FEAT_MBYTE
1474     name = CONVERT_TO_UTF8(name);
1475 #endif
1477     NSString *value = [NSString stringWithUTF8String:(char*)name];
1478     if (value)
1479         ok =  [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1481 #ifdef FEAT_MBYTE
1482     CONVERT_TO_UTF8_FREE(name);
1483 #endif
1485     return ok;
1490  * Iconify the GUI window.
1491  */
1492     void
1493 gui_mch_iconify(void)
1498 #if defined(FEAT_EVAL) || defined(PROTO)
1500  * Bring the Vim window to the foreground.
1501  */
1502     void
1503 gui_mch_set_foreground(void)
1505     [[MMBackend sharedInstance] activate];
1507 #endif
1511     void
1512 gui_mch_set_shellsize(
1513     int         width,
1514     int         height,
1515     int         min_width,
1516     int         min_height,
1517     int         base_width,
1518     int         base_height,
1519     int         direction)
1521     //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1522     //        " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1523     //        width, height, min_width, min_height, base_width, base_height,
1524     //        direction);
1525     [[MMBackend sharedInstance] setRows:height columns:width];
1529     void
1530 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1535  * Set the position of the top left corner of the window to the given
1536  * coordinates.
1537  */
1538     void
1539 gui_mch_set_winpos(int x, int y)
1544 #ifdef FEAT_TITLE
1546  * Set the window title and icon.
1547  * (The icon is not taken care of).
1548  */
1549     void
1550 gui_mch_settitle(char_u *title, char_u *icon)
1552     //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1554 #ifdef FEAT_MBYTE
1555     title = CONVERT_TO_UTF8(title);
1556 #endif
1558     MMBackend *backend = [MMBackend sharedInstance];
1559     [backend setWindowTitle:(char*)title];
1561     // TODO: Convert filename to UTF-8?
1562     if (curbuf)
1563         [backend setDocumentFilename:(char*)curbuf->b_ffname];
1565 #ifdef FEAT_MBYTE
1566     CONVERT_TO_UTF8_FREE(title);
1567 #endif
1569 #endif
1572     void
1573 gui_mch_toggle_tearoffs(int enable)
1579     void
1580 gui_mch_enter_fullscreen(int fuoptions_flags, guicolor_T bg)
1582     [[MMBackend sharedInstance] enterFullscreen:fuoptions_flags background:bg];
1586     void
1587 gui_mch_leave_fullscreen()
1589     [[MMBackend sharedInstance] leaveFullscreen];
1593     void
1594 gui_macvim_update_modified_flag()
1596     [[MMBackend sharedInstance] updateModifiedFlag];
1600  * Add search pattern 'pat' to the OS X find pasteboard.  This allows other
1601  * apps access the last pattern searched for (hitting <D-g> in another app will
1602  * initiate a search for the same pattern).
1603  */
1604     void
1605 gui_macvim_add_to_find_pboard(char_u *pat)
1607     if (!pat) return;
1609 #ifdef FEAT_MBYTE
1610     pat = CONVERT_TO_UTF8(pat);
1611 #endif
1612     NSString *s = [NSString stringWithUTF8String:(char*)pat];
1613 #ifdef FEAT_MBYTE
1614     CONVERT_TO_UTF8_FREE(pat);
1615 #endif
1617     if (!s) return;
1619     NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
1620     [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1621     [pb setString:s forType:NSStringPboardType];
1624     void
1625 gui_macvim_set_antialias(int antialias)
1627     [[MMBackend sharedInstance] setAntialias:antialias];
1631     void
1632 gui_macvim_wait_for_startup()
1634     MMBackend *backend = [MMBackend sharedInstance];
1635     if ([backend waitForAck])
1636         [backend waitForConnectionAcknowledgement];
1639 void gui_macvim_get_window_layout(int *count, int *layout)
1641     if (!(count && layout)) return;
1643     // NOTE: Only set 'layout' if the backend has requested a != 0 layout, else
1644     // any command line arguments (-p/-o) would be ignored.
1645     int window_layout = [[MMBackend sharedInstance] initialWindowLayout];
1646     if (window_layout > 0 && window_layout < 4) {
1647         // The window_layout numbers must match the WIN_* defines in main.c.
1648         *count = 0;
1649         *layout = window_layout;
1650     }
1654 // -- Client/Server ---------------------------------------------------------
1656 #ifdef MAC_CLIENTSERVER
1659 // NOTE: Client/Server is only fully supported with a GUI.  Theoretically it
1660 // would be possible to make the server code work with terminal Vim, but it
1661 // would require that a run-loop is set up and checked.  This should not be
1662 // difficult to implement, simply call gui_mch_update() at opportune moments
1663 // and it will take care of the run-loop.  Another (bigger) problem with
1664 // supporting servers in terminal mode is that the server listing code talks to
1665 // MacVim (the GUI) to figure out which servers are running.
1670  * Register connection with 'name'.  The actual connection is named something
1671  * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1672  */
1673     void
1674 serverRegisterName(char_u *name)
1676 #ifdef FEAT_MBYTE
1677     name = CONVERT_TO_UTF8(name);
1678 #endif
1680     NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1681     [[MMBackend sharedInstance] registerServerWithName:svrName];
1683 #ifdef FEAT_MBYTE
1684     CONVERT_TO_UTF8_FREE(name);
1685 #endif
1690  * Send to an instance of Vim.
1691  * Returns 0 for OK, negative for an error.
1692  */
1693     int
1694 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1695         int *port, int asExpr, int silent)
1697 #ifdef FEAT_MBYTE
1698     name = CONVERT_TO_UTF8(name);
1699     cmd = CONVERT_TO_UTF8(cmd);
1700 #endif
1702     BOOL ok = [[MMBackend sharedInstance]
1703             sendToServer:[NSString stringWithUTF8String:(char*)name]
1704                   string:[NSString stringWithUTF8String:(char*)cmd]
1705                    reply:result
1706                     port:port
1707               expression:asExpr
1708                   silent:silent];
1710 #ifdef FEAT_MBYTE
1711     CONVERT_TO_UTF8_FREE(name);
1712     CONVERT_TO_UTF8_FREE(cmd);
1713 #endif
1715     return ok ? 0 : -1;
1720  * Ask MacVim for the names of all Vim servers.
1721  */
1722     char_u *
1723 serverGetVimNames(void)
1725     char_u *names = NULL;
1726     NSArray *list = [[MMBackend sharedInstance] serverList];
1728     if (list) {
1729         NSString *string = [list componentsJoinedByString:@"\n"];
1730         char_u *s = (char_u*)[string UTF8String];
1731 #ifdef FEAT_MBYTE
1732         s = CONVERT_FROM_UTF8(s);
1733 #endif
1734         names = vim_strsave(s);
1735 #ifdef FEAT_MBYTE
1736         CONVERT_FROM_UTF8_FREE(s);
1737 #endif
1738     }
1740     return names;
1745  * 'str' is a hex int representing the send port of the connection.
1746  */
1747     int
1748 serverStrToPort(char_u *str)
1750     int port = 0;
1752     sscanf((char *)str, "0x%x", &port);
1753     if (!port)
1754         EMSG2(_("E573: Invalid server id used: %s"), str);
1756     return port;
1761  * Check for replies from server with send port 'port'.
1762  * Return TRUE and a non-malloc'ed string if there is.  Else return FALSE.
1763  */
1764     int
1765 serverPeekReply(int port, char_u **str)
1767     NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1768     int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1770     if (str && len > 0) {
1771         *str = (char_u*)[reply UTF8String];
1773 #ifdef FEAT_MBYTE
1774         if (input_conv.vc_type != CONV_NONE) {
1775             char_u *s = string_convert(&input_conv, *str, &len);
1777             if (len > 0) {
1778                 // HACK! Since 's' needs to be freed we cannot simply set
1779                 // '*str = s' or memory will leak.  Instead, create a dummy
1780                 // NSData and return its 'bytes' pointer, then autorelease the
1781                 // NSData.
1782                 NSData *data = [NSData dataWithBytes:s length:len+1];
1783                 *str = (char_u*)[data bytes];
1784             }
1786             vim_free(s);
1787         }
1788 #endif
1789     }
1791     return reply != nil;
1796  * Wait for replies from server with send port 'port'.
1797  * Return 0 and the malloc'ed string when a reply is available.
1798  * Return -1 on error.
1799  */
1800     int
1801 serverReadReply(int port, char_u **str)
1803     NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1804     if (reply && str) {
1805         char_u *s = (char_u*)[reply UTF8String];
1806 #ifdef FEAT_MBYTE
1807         s = CONVERT_FROM_UTF8(s);
1808 #endif
1809         *str = vim_strsave(s);
1810 #ifdef FEAT_MBYTE
1811         CONVERT_FROM_UTF8_FREE(s);
1812 #endif
1813         return 0;
1814     }
1816     return -1;
1821  * Send a reply string (notification) to client with port given by "serverid".
1822  * Return -1 if the window is invalid.
1823  */
1824     int
1825 serverSendReply(char_u *serverid, char_u *reply)
1827     int retval = -1;
1828     int port = serverStrToPort(serverid);
1829     if (port > 0 && reply) {
1830 #ifdef FEAT_MBYTE
1831         reply = CONVERT_TO_UTF8(reply);
1832 #endif
1833         BOOL ok = [[MMBackend sharedInstance]
1834                 sendReply:[NSString stringWithUTF8String:(char*)reply]
1835                    toPort:port];
1836         retval = ok ? 0 : -1;
1837 #ifdef FEAT_MBYTE
1838         CONVERT_TO_UTF8_FREE(reply);
1839 #endif
1840     }
1842     return retval;
1845 #endif // MAC_CLIENTSERVER
1850 // -- ODB Editor Support ----------------------------------------------------
1852 #ifdef FEAT_ODB_EDITOR
1854  * The ODB Editor protocol works like this:
1855  * - An external program (the server) asks MacVim to open a file and associates
1856  *   three things with this file: (1) a server id (a four character code that
1857  *   identifies the server), (2) a path that can be used as window title for
1858  *   the file (optional), (3) an arbitrary token (optional)
1859  * - When a file is saved or closed, MacVim should tell the server about which
1860  *   file was modified and also pass back the token
1862  * All communication between MacVim and the server goes via Apple Events.
1863  */
1865     static OSErr
1866 odb_event(buf_T *buf, const AEEventID action)
1868     if (!(buf->b_odb_server_id && buf->b_ffname))
1869         return noErr;
1871     NSAppleEventDescriptor *targetDesc = [NSAppleEventDescriptor
1872             descriptorWithDescriptorType:typeApplSignature
1873                                    bytes:&buf->b_odb_server_id
1874                                   length:sizeof(OSType)];
1876     // TODO: Convert b_ffname to UTF-8?
1877     NSString *path = [NSString stringWithUTF8String:(char*)buf->b_ffname];
1878     NSData *pathData = [[[NSURL fileURLWithPath:path] absoluteString]
1879             dataUsingEncoding:NSUTF8StringEncoding];
1880     NSAppleEventDescriptor *pathDesc = [NSAppleEventDescriptor
1881             descriptorWithDescriptorType:typeFileURL data:pathData];
1883     NSAppleEventDescriptor *event = [NSAppleEventDescriptor
1884             appleEventWithEventClass:kODBEditorSuite
1885                              eventID:action
1886                     targetDescriptor:targetDesc
1887                             returnID:kAutoGenerateReturnID
1888                        transactionID:kAnyTransactionID];
1890     [event setParamDescriptor:pathDesc forKeyword:keyDirectObject];
1892     if (buf->b_odb_token)
1893         [event setParamDescriptor:buf->b_odb_token forKeyword:keySenderToken];
1895     return AESendMessage([event aeDesc], NULL, kAENoReply | kAENeverInteract,
1896             kAEDefaultTimeout);
1899     OSErr
1900 odb_buffer_close(buf_T *buf)
1902     OSErr err = noErr;
1903     if (buf) {
1904         err = odb_event(buf, kAEClosedFile);
1906         buf->b_odb_server_id = 0;
1908         if (buf->b_odb_token) {
1909             [(NSAppleEventDescriptor *)(buf->b_odb_token) release];
1910             buf->b_odb_token = NULL;
1911         }
1913         if (buf->b_odb_fname) {
1914             vim_free(buf->b_odb_fname);
1915             buf->b_odb_fname = NULL;
1916         }
1917     }
1919     return err;
1922     OSErr
1923 odb_post_buffer_write(buf_T *buf)
1925     return buf ? odb_event(buf, kAEModifiedFile) : noErr;
1928     void
1929 odb_end(void)
1931     buf_T *buf;
1932     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1933         odb_buffer_close(buf);
1936 #endif // FEAT_ODB_EDITOR
1939     char_u *
1940 get_macaction_name(expand_T *xp, int idx)
1942     static char_u *str = NULL;
1943     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1945     if (nil == actionDict || idx < 0 || idx >= [actionDict count])
1946         return NULL;
1948     NSString *string = [[actionDict allKeys] objectAtIndex:idx];
1949     if (!string)
1950         return NULL;
1952     char_u *plainStr = (char_u*)[string UTF8String];
1954 #ifdef FEAT_MBYTE
1955     if (str) {
1956         vim_free(str);
1957         str = NULL;
1958     }
1959     if (input_conv.vc_type != CONV_NONE) {
1960         int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1961         str = string_convert(&input_conv, plainStr, &len);
1962         plainStr = str;
1963     }
1964 #endif
1966     return plainStr;
1970     int
1971 is_valid_macaction(char_u *action)
1973     int isValid = NO;
1974     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1975     if (actionDict) {
1976 #ifdef FEAT_MBYTE
1977         action = CONVERT_TO_UTF8(action);
1978 #endif
1979         NSString *string = [NSString stringWithUTF8String:(char*)action];
1980         isValid = (nil != [actionDict objectForKey:string]);
1981 #ifdef FEAT_MBYTE
1982         CONVERT_TO_UTF8_FREE(action);
1983 #endif
1984     }
1986     return isValid;
1989 static int specialKeyToNSKey(int key)
1991     if (!IS_SPECIAL(key))
1992         return key;
1994     static struct {
1995         int special;
1996         int nskey;
1997     } sp2ns[] = {
1998         { K_UP, NSUpArrowFunctionKey },
1999         { K_DOWN, NSDownArrowFunctionKey },
2000         { K_LEFT, NSLeftArrowFunctionKey },
2001         { K_RIGHT, NSRightArrowFunctionKey },
2002         { K_F1, NSF1FunctionKey },
2003         { K_F2, NSF2FunctionKey },
2004         { K_F3, NSF3FunctionKey },
2005         { K_F4, NSF4FunctionKey },
2006         { K_F5, NSF5FunctionKey },
2007         { K_F6, NSF6FunctionKey },
2008         { K_F7, NSF7FunctionKey },
2009         { K_F8, NSF8FunctionKey },
2010         { K_F9, NSF9FunctionKey },
2011         { K_F10, NSF10FunctionKey },
2012         { K_F11, NSF11FunctionKey },
2013         { K_F12, NSF12FunctionKey },
2014         { K_F13, NSF13FunctionKey },
2015         { K_F14, NSF14FunctionKey },
2016         { K_F15, NSF15FunctionKey },
2017         { K_F16, NSF16FunctionKey },
2018         { K_F17, NSF17FunctionKey },
2019         { K_F18, NSF18FunctionKey },
2020         { K_F19, NSF19FunctionKey },
2021         { K_F20, NSF20FunctionKey },
2022         { K_F21, NSF21FunctionKey },
2023         { K_F22, NSF22FunctionKey },
2024         { K_F23, NSF23FunctionKey },
2025         { K_F24, NSF24FunctionKey },
2026         { K_F25, NSF25FunctionKey },
2027         { K_F26, NSF26FunctionKey },
2028         { K_F27, NSF27FunctionKey },
2029         { K_F28, NSF28FunctionKey },
2030         { K_F29, NSF29FunctionKey },
2031         { K_F30, NSF30FunctionKey },
2032         { K_F31, NSF31FunctionKey },
2033         { K_F32, NSF32FunctionKey },
2034         { K_F33, NSF33FunctionKey },
2035         { K_F34, NSF34FunctionKey },
2036         { K_F35, NSF35FunctionKey },
2037         { K_DEL, NSBackspaceCharacter },
2038         { K_BS, NSDeleteCharacter },
2039         { K_HOME, NSHomeFunctionKey },
2040         { K_END, NSEndFunctionKey },
2041         { K_PAGEUP, NSPageUpFunctionKey },
2042         { K_PAGEDOWN, NSPageDownFunctionKey }
2043     };
2045     int i;
2046     for (i = 0; i < sizeof(sp2ns)/sizeof(sp2ns[0]); ++i) {
2047         if (sp2ns[i].special == key)
2048             return sp2ns[i].nskey;
2049     }
2051     return 0;
2054 static int vimModMaskToEventModifierFlags(int mods)
2056     int flags = 0;
2058     if (mods & MOD_MASK_SHIFT)
2059         flags |= NSShiftKeyMask;
2060     if (mods & MOD_MASK_CTRL)
2061         flags |= NSControlKeyMask;
2062     if (mods & MOD_MASK_ALT)
2063         flags |= NSAlternateKeyMask;
2064     if (mods & MOD_MASK_CMD)
2065         flags |= NSCommandKeyMask;
2067     return flags;