More file opening options (plus quickstart feature)
[MacVim.git] / src / MacVim / gui_macvim.m
blob74b8b7bb71070f4674a12b6d9af7b97f295c81b6
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 // 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 int specialKeyToNSKey(int key);
36 static int vimModMaskToEventModifierFlags(int mods);
38 NSArray *descriptor_for_menu(vimmenu_T *menu);
39 vimmenu_T *menu_for_descriptor(NSArray *desc);
43 // -- Initialization --------------------------------------------------------
46  * Parse the GUI related command-line arguments.  Any arguments used are
47  * deleted from argv, and *argc is decremented accordingly.  This is called
48  * when vim is started, whether or not the GUI has been started.
49  */
50     void
51 gui_mch_prepare(int *argc, char **argv)
53     //NSLog(@"gui_mch_prepare(argc=%d)", *argc);
55     // Set environment variables $VIM and $VIMRUNTIME
56     // NOTE!  If vim_getenv is called with one of these as parameters before
57     // they have been set here, they will most likely end up with the wrong
58     // values!
59     //
60     // TODO:
61     // - ensure this is called first to avoid above problem
62     // - encoding
64     NSString *path = [[[NSBundle mainBundle] resourcePath]
65         stringByAppendingPathComponent:@"vim"];
66     vim_setenv((char_u*)"VIM", (char_u*)[path UTF8String]);
68     path = [path stringByAppendingPathComponent:@"runtime"];
69     vim_setenv((char_u*)"VIMRUNTIME", (char_u*)[path UTF8String]);
71     int i;
72     for (i = 0; i < *argc; ++i) {
73         if (strncmp(argv[i], "--mmwaitforack", 14) == 0) {
74             [[MMBackend sharedInstance] setWaitForAck:YES];
75             --*argc;
76             if (*argc > i)
77                 mch_memmove(&argv[i], &argv[i+1], (*argc-i) * sizeof(char*));
78             break;
79         }
80     }
85  * Check if the GUI can be started.  Called before gvimrc is sourced.
86  * Return OK or FAIL.
87  */
88     int
89 gui_mch_init_check(void)
91     //NSLog(@"gui_mch_init_check()");
92     return OK;
97  * Initialise the GUI.  Create all the windows, set up all the call-backs etc.
98  * Returns OK for success, FAIL when the GUI can't be started.
99  */
100     int
101 gui_mch_init(void)
103     //NSLog(@"gui_mch_init()");
105     if (![[MMBackend sharedInstance] checkin]) {
106         // TODO: Kill the process if there is no terminal to fall back on,
107         // otherwise the process will run outputting to the console.
108         return FAIL;
109     }
111     // Force 'termencoding' to utf-8 (changes to 'tenc' are disallowed in
112     // 'option.c', so that ':set termencoding=...' is impossible).
113     set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
115     // Set values so that pixels and characters are in one-to-one
116     // correspondence (assuming all characters have the same dimensions).
117     gui.scrollbar_width = gui.scrollbar_height = 0;
119     gui.char_height = 1;
120     gui.char_width = 1;
121     gui.char_ascent = 0;
123     gui_mch_def_colors();
125     [[MMBackend sharedInstance]
126         setDefaultColorsBackground:gui.back_pixel foreground:gui.norm_pixel];
127     [[MMBackend sharedInstance] setBackgroundColor:gui.back_pixel];
128     [[MMBackend sharedInstance] setForegroundColor:gui.norm_pixel];
130     // NOTE: If this call is left out the cursor is opaque.
131     highlight_gui_started();
133     return OK;
138     void
139 gui_mch_exit(int rc)
141     //NSLog(@"gui_mch_exit(rc=%d)", rc);
143     [[MMBackend sharedInstance] exit];
148  * Open the GUI window which was created by a call to gui_mch_init().
149  */
150     int
151 gui_mch_open(void)
153     // For preloaded Vim processes we delay opening the GUI window until
154     // gui_macvim_wait_for_startup() is called.  (If for some reason preloading
155     // didn't work as expected, the "normal" behavior can be restored by
156     // disabling preloading.)
158     MMBackend *backend = [MMBackend sharedInstance];
159     if ([backend waitForAck])
160         return OK;
162     return [backend openVimWindow];
166 // -- Updating --------------------------------------------------------------
170  * Catch up with any queued X events.  This may put keyboard input into the
171  * input buffer, call resize call-backs, trigger timers etc.  If there is
172  * nothing in the X event queue (& no timers pending), then we return
173  * immediately.
174  */
175 #define MM_LOG_UPDATE_STATS 0
176     void
177 gui_mch_update(void)
179     // NOTE: This function can get called A LOT (~1 call/ms) and unfortunately
180     // checking the run loop takes a long time, resulting in noticable slow
181     // downs if it is done every time this function is called.  Therefore we
182     // make sure that it is not done too often.
183     static NSDate *lastUpdateDate = nil;
184 #if MM_LOG_UPDATE_STATS
185     static int skipCount = 0;
186 #endif
188     if (lastUpdateDate && -[lastUpdateDate timeIntervalSinceNow] <
189             MMUpdateTimeoutInterval) {
190 #if MM_LOG_UPDATE_STATS
191         ++skipCount;
192 #endif
193         return;
194     }
196 #if MM_LOG_UPDATE_STATS
197     NSTimeInterval dt = -[lastUpdateDate timeIntervalSinceNow];
198     NSLog(@"Updating (last update %.2f seconds ago, skipped %d updates, "
199             "approx %.1f calls per second)",
200             dt, skipCount, dt > 0 ? skipCount/dt : 0);
201     skipCount = 0;
202 #endif
204     [[MMBackend sharedInstance] update];
206     [lastUpdateDate release];
207     lastUpdateDate = [[NSDate date] retain];
211 /* Flush any output to the screen */
212     void
213 gui_mch_flush(void)
215     [[MMBackend sharedInstance] flushQueue:NO];
219 /* Force flush output to MacVim.  Do not call this method unless absolutely
220  * necessary (use gui_mch_flush() instead). */
221     void
222 gui_macvim_force_flush(void)
224     [[MMBackend sharedInstance] flushQueue:YES];
229  * GUI input routine called by gui_wait_for_chars().  Waits for a character
230  * from the keyboard.
231  *  wtime == -1     Wait forever.
232  *  wtime == 0      This should never happen.
233  *  wtime > 0       Wait wtime milliseconds for a character.
234  * Returns OK if a character was found to be available within the given time,
235  * or FAIL otherwise.
236  */
237     int
238 gui_mch_wait_for_chars(int wtime)
240     // NOTE! In all likelihood Vim will take a nap when waitForInput: is
241     // called, so force a flush of the command queue here.
242     [[MMBackend sharedInstance] flushQueue:YES];
244     return [[MMBackend sharedInstance] waitForInput:wtime];
248 // -- Drawing ---------------------------------------------------------------
252  * Clear the whole text window.
253  */
254     void
255 gui_mch_clear_all(void)
257     [[MMBackend sharedInstance] clearAll];
262  * Clear a rectangular region of the screen from text pos (row1, col1) to
263  * (row2, col2) inclusive.
264  */
265     void
266 gui_mch_clear_block(int row1, int col1, int row2, int col2)
268     [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
269                                                     toRow:row2 column:col2];
274  * Delete the given number of lines from the given row, scrolling up any
275  * text further down within the scroll region.
276  */
277     void
278 gui_mch_delete_lines(int row, int num_lines)
280     [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
281             scrollBottom:gui.scroll_region_bot
282                     left:gui.scroll_region_left
283                    right:gui.scroll_region_right];
287     void
288 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
290 #ifdef FEAT_MBYTE
291     char_u *conv_str = NULL;
292     if (output_conv.vc_type != CONV_NONE) {
293         conv_str = string_convert(&output_conv, s, &len);
294         if (conv_str)
295             s = conv_str;
296     }
297 #endif
299     [[MMBackend sharedInstance] drawString:(char*)s length:len row:row
300                                     column:col cells:len flags:flags];
302 #ifdef FEAT_MBYTE
303     if (conv_str)
304         vim_free(conv_str);
305 #endif
309     int
310 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
312     int c, cn, cl, i;
313     int start = 0;
314     int endcol = col;
315     int startcol = col;
316     BOOL wide = NO;
317     MMBackend *backend = [MMBackend sharedInstance];
318 #ifdef FEAT_MBYTE
319     char_u *conv_str = NULL;
321     if (output_conv.vc_type != CONV_NONE) {
322         conv_str = string_convert(&output_conv, s, &len);
323         if (conv_str)
324             s = conv_str;
325     }
326 #endif
328     // Loop over each character and output text when it changes from normal to
329     // wide and vice versa.
330     for (i = 0; i < len; i += cl) {
331         c = utf_ptr2char(s + i);
332         cl = utf_ptr2len(s + i);
333         cn = utf_char2cells(c);
335         if (!utf_iscomposing(c)) {
336             if ((cn > 1 && !wide) || (cn <= 1 && wide)) {
337                 // Changed from normal to wide or vice versa.
338                 [backend drawString:(char*)(s+start) length:i-start
339                                    row:row column:startcol
340                                  cells:endcol-startcol
341                                  flags:(wide ? flags|DRAW_WIDE : flags)];
343                 start = i;
344                 startcol = endcol;
345             }
347             wide = cn > 1;
348             endcol += cn;
349         }
350     }
352     // Output remaining characters.
353     [backend drawString:(char*)(s+start) length:len-start
354                     row:row column:startcol cells:endcol-startcol
355                   flags:(wide ? flags|DRAW_WIDE : flags)];
357 #ifdef FEAT_MBYTE
358     if (conv_str)
359         vim_free(conv_str);
360 #endif
362     return endcol - col;
367  * Insert the given number of lines before the given row, scrolling down any
368  * following text within the scroll region.
369  */
370     void
371 gui_mch_insert_lines(int row, int num_lines)
373     [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
374             scrollBottom:gui.scroll_region_bot
375                     left:gui.scroll_region_left
376                    right:gui.scroll_region_right];
381  * Set the current text foreground color.
382  */
383     void
384 gui_mch_set_fg_color(guicolor_T color)
386     [[MMBackend sharedInstance] setForegroundColor:color];
391  * Set the current text background color.
392  */
393     void
394 gui_mch_set_bg_color(guicolor_T color)
396     [[MMBackend sharedInstance] setBackgroundColor:color];
401  * Set the current text special color (used for underlines).
402  */
403     void
404 gui_mch_set_sp_color(guicolor_T color)
406     [[MMBackend sharedInstance] setSpecialColor:color];
411  * Set default colors.
412  */
413     void
414 gui_mch_def_colors()
416     MMBackend *backend = [MMBackend sharedInstance];
418     // The default colors are taken from system values
419     gui.def_norm_pixel = gui.norm_pixel = 
420         [backend lookupColorWithKey:@"MacTextColor"];
421     gui.def_back_pixel = gui.back_pixel = 
422         [backend lookupColorWithKey:@"MacTextBackgroundColor"];
427  * Called when the foreground or background color has been changed.
428  */
429     void
430 gui_mch_new_colors(void)
432     gui.def_back_pixel = gui.back_pixel;
433     gui.def_norm_pixel = gui.norm_pixel;
435     //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
436     //        gui.def_norm_pixel);
438     [[MMBackend sharedInstance]
439         setDefaultColorsBackground:gui.def_back_pixel
440                         foreground:gui.def_norm_pixel];
444  * Invert a rectangle from row r, column c, for nr rows and nc columns.
445  */
446     void
447 gui_mch_invert_rectangle(int r, int c, int nr, int nc, int invert)
449     [[MMBackend sharedInstance] drawInvertedRectAtRow:r column:c numRows:nr
450             numColumns:nc invert:invert];
455 // -- Tabline ---------------------------------------------------------------
459  * Set the current tab to "nr".  First tab is 1.
460  */
461     void
462 gui_mch_set_curtab(int nr)
464     [[MMBackend sharedInstance] selectTab:nr];
469  * Return TRUE when tabline is displayed.
470  */
471     int
472 gui_mch_showing_tabline(void)
474     return [[MMBackend sharedInstance] tabBarVisible];
478  * Update the labels of the tabline.
479  */
480     void
481 gui_mch_update_tabline(void)
483     [[MMBackend sharedInstance] updateTabBar];
487  * Show or hide the tabline.
488  */
489     void
490 gui_mch_show_tabline(int showit)
492     [[MMBackend sharedInstance] showTabBar:showit];
496 // -- Clipboard -------------------------------------------------------------
499     void
500 clip_mch_lose_selection(VimClipboard *cbd)
505     int
506 clip_mch_own_selection(VimClipboard *cbd)
508     return 0;
512     void
513 clip_mch_request_selection(VimClipboard *cbd)
515     NSPasteboard *pb = [NSPasteboard generalPasteboard];
516     NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
517             NSStringPboardType, nil];
518     NSString *bestType = [pb availableTypeFromArray:supportedTypes];
519     if (!bestType) return;
521     int motion_type = MCHAR;
522     NSString *string = nil;
524     if ([bestType isEqual:VimPBoardType]) {
525         // This type should consist of an array with two objects:
526         //   1. motion type (NSNumber)
527         //   2. text (NSString)
528         // If this is not the case we fall back on using NSStringPboardType.
529         id plist = [pb propertyListForType:VimPBoardType];
530         if ([plist isKindOfClass:[NSArray class]] && [plist count] == 2) {
531             id obj = [plist objectAtIndex:1];
532             if ([obj isKindOfClass:[NSString class]]) {
533                 motion_type = [[plist objectAtIndex:0] intValue];
534                 string = obj;
535             }
536         }
537     }
539     if (!string) {
540         // Use NSStringPboardType.  The motion type is set to line-wise if the
541         // string contains at least one EOL character, otherwise it is set to
542         // character-wise (block-wise is never used).
543         NSMutableString *mstring =
544                 [[pb stringForType:NSStringPboardType] mutableCopy];
545         if (!mstring) return;
547         // Replace unrecognized end-of-line sequences with \x0a (line feed).
548         NSRange range = { 0, [mstring length] };
549         unsigned n = [mstring replaceOccurrencesOfString:@"\x0d\x0a"
550                                              withString:@"\x0a" options:0
551                                                   range:range];
552         if (0 == n) {
553             n = [mstring replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
554                                            options:0 range:range];
555         }
556         
557         // Scan for newline character to decide whether the string should be
558         // pasted line-wise or character-wise.
559         motion_type = MCHAR;
560         if (0 < n || NSNotFound != [mstring rangeOfString:@"\n"].location)
561             motion_type = MLINE;
563         string = mstring;
564     }
566     if (!(MCHAR == motion_type || MLINE == motion_type || MBLOCK == motion_type
567             || MAUTO == motion_type))
568         motion_type = MCHAR;
570     char_u *str = (char_u*)[string UTF8String];
571     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
573 #ifdef FEAT_MBYTE
574     if (input_conv.vc_type != CONV_NONE)
575         str = string_convert(&input_conv, str, &len);
576 #endif
578     if (str)
579         clip_yank_selection(motion_type, str, len, cbd);
581 #ifdef FEAT_MBYTE
582     if (input_conv.vc_type != CONV_NONE)
583         vim_free(str);
584 #endif
589  * Send the current selection to the clipboard.
590  */
591     void
592 clip_mch_set_selection(VimClipboard *cbd)
594     // If the '*' register isn't already filled in, fill it in now.
595     cbd->owned = TRUE;
596     clip_get_selection(cbd);
597     cbd->owned = FALSE;
598     
599     // Get the text to put on the pasteboard.
600     long_u llen = 0; char_u *str = 0;
601     int motion_type = clip_convert_selection(&str, &llen, cbd);
602     if (motion_type < 0)
603         return;
605     // TODO: Avoid overflow.
606     int len = (int)llen;
607 #ifdef FEAT_MBYTE
608     if (output_conv.vc_type != CONV_NONE) {
609         char_u *conv_str = string_convert(&output_conv, str, &len);
610         if (conv_str) {
611             vim_free(str);
612             str = conv_str;
613         }
614     }
615 #endif
617     if (len > 0) {
618         NSString *string = [[NSString alloc]
619             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
621         // See clip_mch_request_selection() for info on pasteboard types.
622         NSPasteboard *pb = [NSPasteboard generalPasteboard];
623         NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
624                 NSStringPboardType, nil];
625         [pb declareTypes:supportedTypes owner:nil];
627         NSNumber *motion = [NSNumber numberWithInt:motion_type];
628         NSArray *plist = [NSArray arrayWithObjects:motion, string, nil];
629         [pb setPropertyList:plist forType:VimPBoardType];
631         [pb setString:string forType:NSStringPboardType];
632         
633         [string release];
634     }
636     vim_free(str);
640 // -- Menu ------------------------------------------------------------------
644  * A menu descriptor represents the "address" of a menu as an array of strings.
645  * E.g. the menu "File->Close" has descriptor { "File", "Close" }.
646  */
647     NSArray *
648 descriptor_for_menu(vimmenu_T *menu)
650     if (!menu) return nil;
652     NSMutableArray *desc = [NSMutableArray array];
653     while (menu) {
654         NSString *name = [NSString stringWithVimString:menu->dname];
655         [desc insertObject:name atIndex:0];
656         menu = menu->parent;
657     }
659     return desc;
662     vimmenu_T *
663 menu_for_descriptor(NSArray *desc)
665     if (!(desc && [desc count] > 0)) return NULL;
667     vimmenu_T *menu = root_menu;
668     int i, count = [desc count];
670     for (i = 0; i < count; ++i) {
671         NSString *component = [desc objectAtIndex:i];
672         while (menu) {
673             NSString *name = [NSString stringWithVimString:menu->dname];
674             if ([component isEqual:name]) {
675                 if (i+1 == count)
676                     return menu;    // Matched all components, so return menu
677                 menu = menu->children;
678                 break;
679             }
680             menu = menu->next;
681         }
682     }
684     return NULL;
688  * Add a submenu to the menu bar, toolbar, or a popup menu.
689  */
690     void
691 gui_mch_add_menu(vimmenu_T *menu, int idx)
693     NSArray *desc = descriptor_for_menu(menu);
694     [[MMBackend sharedInstance] queueMessage:AddMenuMsgID properties:
695         [NSDictionary dictionaryWithObjectsAndKeys:
696             desc, @"descriptor",
697             [NSNumber numberWithInt:idx], @"index",
698             nil]];
703  * Add a menu item to a menu
704  */
705     void
706 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
708     char_u *tip = menu->strings[MENU_INDEX_TIP]
709             ? menu->strings[MENU_INDEX_TIP] : menu->actext;
710     NSArray *desc = descriptor_for_menu(menu);
711     NSString *keyEquivalent = menu->mac_key
712         ? [NSString stringWithFormat:@"%C", specialKeyToNSKey(menu->mac_key)]
713         : [NSString string];
714     int modifierMask = vimModMaskToEventModifierFlags(menu->mac_mods);
715     char_u *icon = NULL;
717     if (menu_is_toolbar(menu->parent->name)) {
718         char_u fname[MAXPATHL];
720         // TODO: Ensure menu->iconfile exists (if != NULL)
721         icon = menu->iconfile;
722         if (!icon && gui_find_bitmap(menu->name, fname, "bmp") == OK)
723             icon = fname;
724         if (!icon && menu->iconidx >= 0)
725             icon = menu->dname;
726     }
728     [[MMBackend sharedInstance] queueMessage:AddMenuItemMsgID properties:
729         [NSDictionary dictionaryWithObjectsAndKeys:
730             desc, @"descriptor",
731             [NSNumber numberWithInt:idx], @"index",
732             [NSString stringWithVimString:tip], @"tip",
733             [NSString stringWithVimString:icon], @"icon",
734             keyEquivalent, @"keyEquivalent",
735             [NSNumber numberWithInt:modifierMask], @"modifierMask",
736             [NSString stringWithVimString:menu->mac_action], @"action",
737             [NSNumber numberWithBool:menu->mac_alternate], @"isAlternate",
738             nil]];
743  * Destroy the machine specific menu widget.
744  */
745     void
746 gui_mch_destroy_menu(vimmenu_T *menu)
748     NSArray *desc = descriptor_for_menu(menu);
749     [[MMBackend sharedInstance] queueMessage:RemoveMenuItemMsgID properties:
750         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
755  * Make a menu either grey or not grey.
756  */
757     void
758 gui_mch_menu_grey(vimmenu_T *menu, int grey)
760     /* Only update menu if the 'grey' state has changed to avoid having to pass
761      * lots of unnecessary data to MacVim.  (Skipping this test makes MacVim
762      * pause noticably on mode changes. */
763     NSArray *desc = descriptor_for_menu(menu);
764     if (menu->was_grey == grey)
765         return;
767     menu->was_grey = grey;
769     [[MMBackend sharedInstance] queueMessage:EnableMenuItemMsgID properties:
770         [NSDictionary dictionaryWithObjectsAndKeys:
771             desc, @"descriptor",
772             [NSNumber numberWithInt:!grey], @"enable",
773             nil]];
778  * Make menu item hidden or not hidden
779  */
780     void
781 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
783     // HACK! There is no (obvious) way to hide a menu item, so simply
784     // enable/disable it instead.
785     gui_mch_menu_grey(menu, hidden);
790  * This is called when user right clicks.
791  */
792     void
793 gui_mch_show_popupmenu(vimmenu_T *menu)
795     NSArray *desc = descriptor_for_menu(menu);
796     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:
797         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
802  * This is called when a :popup command is executed.
803  */
804     void
805 gui_make_popup(char_u *path_name, int mouse_pos)
807     vimmenu_T *menu = gui_find_menu(path_name);
808     if (!(menu && menu->children)) return;
810     NSArray *desc = descriptor_for_menu(menu);
811     NSDictionary *p = (mouse_pos || NULL == curwin)
812         ? [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]
813         : [NSDictionary dictionaryWithObjectsAndKeys:
814             desc, @"descriptor",
815             [NSNumber numberWithInt:curwin->w_wrow], @"row",
816             [NSNumber numberWithInt:curwin->w_wcol], @"column",
817             nil];
819     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:p];
824  * This is called after setting all the menus to grey/hidden or not.
825  */
826     void
827 gui_mch_draw_menubar(void)
829     // The (main) menu draws itself in Mac OS X.
833     void
834 gui_mch_enable_menu(int flag)
836     // The (main) menu is always enabled in Mac OS X.
840 #if 0
841     void
842 gui_mch_set_menu_pos(int x, int y, int w, int h)
844     // The (main) menu cannot be moved in Mac OS X.
846 #endif
849     void
850 gui_mch_show_toolbar(int showit)
852     int flags = 0;
853     if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
854     if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
855     if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
857     [[MMBackend sharedInstance] showToolbar:showit flags:flags];
863 // -- Fonts -----------------------------------------------------------------
867  * If a font is not going to be used, free its structure.
868  */
869     void
870 gui_mch_free_font(font)
871     GuiFont     font;
873     if (font != NOFONT) {
874         //NSLog(@"gui_mch_free_font(font=0x%x)", font);
875         [(NSFont*)font release];
876     }
881  * Get a font structure for highlighting.
882  */
883     GuiFont
884 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
886     //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
887     //        giveErrorIfMissing);
889     NSFont *font = gui_macvim_font_with_name(name);
890     if (font)
891         return (GuiFont)[font retain];
893     if (giveErrorIfMissing)
894         EMSG2(_(e_font), name);
896     return NOFONT;
900 #if defined(FEAT_EVAL) || defined(PROTO)
902  * Return the name of font "font" in allocated memory.
903  * Don't know how to get the actual name, thus use the provided name.
904  */
905     char_u *
906 gui_mch_get_fontname(GuiFont font, char_u *name)
908     if (name == NULL)
909         return NULL;
910     return vim_strsave(name);
912 #endif
916  * Initialise vim to use the font with the given name.  Return FAIL if the font
917  * could not be loaded, OK otherwise.
918  */
919     int
920 gui_mch_init_font(char_u *font_name, int fontset)
922     //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
924     if (font_name && STRCMP(font_name, "*") == 0) {
925         // :set gfn=* shows the font panel.
926         do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
927         return FAIL;
928     }
930     NSFont *font = gui_macvim_font_with_name(font_name);
931     if (font) {
932         [(NSFont*)gui.norm_font release];
933         gui.norm_font = (GuiFont)[font retain];
935         // NOTE: MacVim keeps separate track of the normal and wide fonts.
936         // Unless the user changes 'guifontwide' manually, they are based on
937         // the same (normal) font.  Also note that each time the normal font is
938         // set, the advancement may change so the wide font needs to be updated
939         // as well (so that it is always twice the width of the normal font).
940         [[MMBackend sharedInstance] setFont:font];
941         [[MMBackend sharedInstance] setWideFont:
942                (NOFONT == gui.wide_font ? font : (NSFont*)gui.wide_font)];
944         return OK;
945     }
947     return FAIL;
952  * Set the current text font.
953  */
954     void
955 gui_mch_set_font(GuiFont font)
957     // Font selection is done inside MacVim...nothing here to do.
961     NSFont *
962 gui_macvim_font_with_name(char_u *name)
964     NSFont *font = nil;
965     NSString *fontName = MMDefaultFontName;
966     float size = MMDefaultFontSize;
967     BOOL parseFailed = NO;
969 #ifdef FEAT_MBYTE
970     name = CONVERT_TO_UTF8(name);
971 #endif
973     if (name) {
974         fontName = [NSString stringWithUTF8String:(char*)name];
976         NSArray *components = [fontName componentsSeparatedByString:@":"];
977         if ([components count] == 2) {
978             NSString *sizeString = [components lastObject];
979             if ([sizeString length] > 0
980                     && [sizeString characterAtIndex:0] == 'h') {
981                 sizeString = [sizeString substringFromIndex:1];
982                 if ([sizeString length] > 0) {
983                     size = [sizeString floatValue];
984                     fontName = [components objectAtIndex:0];
985                 }
986             } else {
987                 parseFailed = YES;
988             }
989         } else if ([components count] > 2) {
990             parseFailed = YES;
991         }
993         if (!parseFailed) {
994             // Replace underscores with spaces.
995             fontName = [[fontName componentsSeparatedByString:@"_"]
996                                      componentsJoinedByString:@" "];
997         }
998     }
1000     if (!parseFailed && [fontName length] > 0) {
1001         if (size < MMMinFontSize) size = MMMinFontSize;
1002         if (size > MMMaxFontSize) size = MMMaxFontSize;
1004         font = [NSFont fontWithName:fontName size:size];
1006         if (!font && MMDefaultFontName == fontName) {
1007             // If for some reason the MacVim default font is not in the app
1008             // bundle, then fall back on the system default font.
1009             font = [NSFont userFixedPitchFontOfSize:0];
1010         }
1011     }
1013 #ifdef FEAT_MBYTE
1014     CONVERT_TO_UTF8_FREE(name);
1015 #endif
1017     return font;
1020 // -- Scrollbars ------------------------------------------------------------
1023     void
1024 gui_mch_create_scrollbar(
1025         scrollbar_T *sb,
1026         int orient)     /* SBAR_VERT or SBAR_HORIZ */
1028     [[MMBackend sharedInstance] 
1029             createScrollbarWithIdentifier:sb->ident type:sb->type];
1033     void
1034 gui_mch_destroy_scrollbar(scrollbar_T *sb)
1036     [[MMBackend sharedInstance] 
1037             destroyScrollbarWithIdentifier:sb->ident];
1041     void
1042 gui_mch_enable_scrollbar(
1043         scrollbar_T     *sb,
1044         int             flag)
1046     [[MMBackend sharedInstance] 
1047             showScrollbarWithIdentifier:sb->ident state:flag];
1051     void
1052 gui_mch_set_scrollbar_pos(
1053         scrollbar_T *sb,
1054         int x,
1055         int y,
1056         int w,
1057         int h)
1059     int pos = y;
1060     int len = h;
1061     if (SBAR_BOTTOM == sb->type) {
1062         pos = x;
1063         len = w; 
1064     }
1066     [[MMBackend sharedInstance] 
1067             setScrollbarPosition:pos length:len identifier:sb->ident];
1071     void
1072 gui_mch_set_scrollbar_thumb(
1073         scrollbar_T *sb,
1074         long val,
1075         long size,
1076         long max)
1078     [[MMBackend sharedInstance] 
1079             setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
1083 // -- Cursor ----------------------------------------------------------------
1087  * Draw a cursor without focus.
1088  */
1089     void
1090 gui_mch_draw_hollow_cursor(guicolor_T color)
1092     return [[MMBackend sharedInstance]
1093         drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
1094                fraction:100 color:color];
1099  * Draw part of a cursor, only w pixels wide, and h pixels high.
1100  */
1101     void
1102 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
1104     // HACK!  'w' and 'h' are always 1 since we do not tell Vim about the exact
1105     // font dimensions.  Thus these parameters are useless.  Instead we look at
1106     // the shape_table to determine the shape and size of the cursor (just like
1107     // gui_update_cursor() does).
1109 #ifdef FEAT_RIGHTLEFT
1110     // If 'rl' is set the insert mode cursor must be drawn on the right-hand
1111     // side of a text cell.
1112     int rl = curwin ? curwin->w_p_rl : FALSE;
1113 #else
1114     int rl = FALSE;
1115 #endif
1116     int idx = get_shape_idx(FALSE);
1117     int shape = MMInsertionPointBlock;
1118     switch (shape_table[idx].shape) {
1119         case SHAPE_HOR:
1120             shape = MMInsertionPointHorizontal;
1121             break;
1122         case SHAPE_VER:
1123             shape = rl ? MMInsertionPointVerticalRight
1124                        : MMInsertionPointVertical;
1125             break;
1126     }
1128     return [[MMBackend sharedInstance]
1129         drawCursorAtRow:gui.row column:gui.col shape:shape
1130                fraction:shape_table[idx].percentage color:color];
1135  * Cursor blink functions.
1137  * This is a simple state machine:
1138  * BLINK_NONE   not blinking at all
1139  * BLINK_OFF    blinking, cursor is not shown
1140  * BLINK_ON blinking, cursor is shown
1141  */
1142     void
1143 gui_mch_set_blinking(long wait, long on, long off)
1145     [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1150  * Start the cursor blinking.  If it was already blinking, this restarts the
1151  * waiting time and shows the cursor.
1152  */
1153     void
1154 gui_mch_start_blink(void)
1156     [[MMBackend sharedInstance] startBlink];
1161  * Stop the cursor blinking.  Show the cursor if it wasn't shown.
1162  */
1163     void
1164 gui_mch_stop_blink(void)
1166     [[MMBackend sharedInstance] stopBlink];
1170 // -- Mouse -----------------------------------------------------------------
1174  * Get current mouse coordinates in text window.
1175  */
1176     void
1177 gui_mch_getmouse(int *x, int *y)
1179     //NSLog(@"gui_mch_getmouse()");
1183     void
1184 gui_mch_setmouse(int x, int y)
1186     //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1190     void
1191 mch_set_mouse_shape(int shape)
1193     [[MMBackend sharedInstance] setMouseShape:shape];
1199 // -- Input Method ----------------------------------------------------------
1201 #if defined(USE_IM_CONTROL)
1203     void
1204 im_set_position(int row, int col)
1206     // The pre-edit area is a popup window which is displayed by MMTextView.
1207     [[MMBackend sharedInstance] setPreEditRow:row column:col];
1211     void
1212 im_set_active(int active)
1214     // Set roman or the system script if 'active' is TRUE or FALSE,
1215     // respectively.
1216     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1218     if (!p_imdisable && smRoman != systemScript)
1219         KeyScript(active ? smKeySysScript : smKeyRoman);
1223     int
1224 im_get_status(void)
1226     // IM is active whenever the current script is the system script and the
1227     // system script isn't roman.  (Hence IM can only be active when using
1228     // non-roman scripts.)
1229     SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
1230     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1232     return currentScript != smRoman && currentScript == systemScript;
1235 #endif // defined(USE_IM_CONTROL)
1240 // -- Unsorted --------------------------------------------------------------
1243     void
1244 ex_macaction(eap)
1245     exarg_T     *eap;
1247     if (!gui.in_use) {
1248         EMSG(_("E???: Command only available in GUI mode"));
1249         return;
1250     }
1252     char_u *arg = eap->arg;
1253 #ifdef FEAT_MBYTE
1254     arg = CONVERT_TO_UTF8(arg);
1255 #endif
1257     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1258     NSString *name = [NSString stringWithUTF8String:(char*)arg];
1259     if (actionDict && [actionDict objectForKey:name] != nil) {
1260         [[MMBackend sharedInstance] executeActionWithName:name];
1261     } else {
1262         EMSG2(_("E???: Invalid action: %s"), eap->arg);
1263     }
1265 #ifdef FEAT_MBYTE
1266     arg = CONVERT_TO_UTF8(arg);
1267 #endif
1272  * Adjust gui.char_height (after 'linespace' was changed).
1273  */
1274     int
1275 gui_mch_adjust_charheight(void)
1277     [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1278     return OK;
1282     void
1283 gui_mch_beep(void)
1285     NSBeep();
1290 #ifdef FEAT_BROWSE
1292  * Pop open a file browser and return the file selected, in allocated memory,
1293  * or NULL if Cancel is hit.
1294  *  saving  - TRUE if the file will be saved to, FALSE if it will be opened.
1295  *  title   - Title message for the file browser dialog.
1296  *  dflt    - Default name of file.
1297  *  ext     - Default extension to be added to files without extensions.
1298  *  initdir - directory in which to open the browser (NULL = current dir)
1299  *  filter  - Filter for matched files to choose from.
1300  *  Has a format like this:
1301  *  "C Files (*.c)\0*.c\0"
1302  *  "All Files\0*.*\0\0"
1303  *  If these two strings were concatenated, then a choice of two file
1304  *  filters will be selectable to the user.  Then only matching files will
1305  *  be shown in the browser.  If NULL, the default allows all files.
1307  *  *NOTE* - the filter string must be terminated with TWO nulls.
1308  */
1309     char_u *
1310 gui_mch_browse(
1311     int saving,
1312     char_u *title,
1313     char_u *dflt,
1314     char_u *ext,
1315     char_u *initdir,
1316     char_u *filter)
1318     //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1319     //        " filter=%s", saving, title, dflt, ext, initdir, filter);
1321     // Ensure no data is on the output queue before presenting the dialog.
1322     gui_macvim_force_flush();
1324     NSMutableDictionary *attr = [NSMutableDictionary
1325         dictionaryWithObject:[NSNumber numberWithBool:saving]
1326                       forKey:@"saving"];
1327     if (initdir)
1328         [attr setObject:[NSString stringWithVimString:initdir] forKey:@"dir"];
1330     char_u *s = (char_u*)[[MMBackend sharedInstance]
1331                             browseForFileWithAttributes:attr];
1333     return s;
1335 #endif /* FEAT_BROWSE */
1339     int
1340 gui_mch_dialog(
1341     int         type,
1342     char_u      *title,
1343     char_u      *message,
1344     char_u      *buttons,
1345     int         dfltbutton,
1346     char_u      *textfield)
1348     //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1349     //        "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1350     //        dfltbutton, textfield);
1352     // Ensure no data is on the output queue before presenting the dialog.
1353     gui_macvim_force_flush();
1355     int style = NSInformationalAlertStyle;
1356     if (VIM_WARNING == type) style = NSWarningAlertStyle;
1357     else if (VIM_ERROR == type) style = NSCriticalAlertStyle;
1359     NSMutableDictionary *attr = [NSMutableDictionary
1360                         dictionaryWithObject:[NSNumber numberWithInt:style]
1361                                       forKey:@"alertStyle"];
1363     if (buttons) {
1364         // 'buttons' is a string of '\n'-separated button titles 
1365         NSString *string = [NSString stringWithVimString:buttons];
1366         NSArray *array = [string componentsSeparatedByString:@"\n"];
1367         [attr setObject:array forKey:@"buttonTitles"];
1368     }
1370     NSString *messageText = nil;
1371     if (title)
1372         messageText = [NSString stringWithVimString:title];
1374     if (message) {
1375         NSString *informativeText = [NSString stringWithVimString:message];
1376         if (!messageText) {
1377             // HACK! If there is a '\n\n' or '\n' sequence in the message, then
1378             // make the part up to there into the title.  We only do this
1379             // because Vim has lots of dialogs without a title and they look
1380             // ugly that way.
1381             // TODO: Fix the actual dialog texts.
1382             NSRange eolRange = [informativeText rangeOfString:@"\n\n"];
1383             if (NSNotFound == eolRange.location)
1384                 eolRange = [informativeText rangeOfString:@"\n"];
1385             if (NSNotFound != eolRange.location) {
1386                 messageText = [informativeText substringToIndex:
1387                                                         eolRange.location];
1388                 informativeText = [informativeText substringFromIndex:
1389                                                         NSMaxRange(eolRange)];
1390             }
1391         }
1393         [attr setObject:informativeText forKey:@"informativeText"];
1394     }
1396     if (messageText)
1397         [attr setObject:messageText forKey:@"messageText"];
1399     if (textfield) {
1400         NSString *string = [NSString stringWithVimString:textfield];
1401         [attr setObject:string forKey:@"textFieldString"];
1402     }
1404     return [[MMBackend sharedInstance] showDialogWithAttributes:attr
1405                                                     textField:(char*)textfield];
1409     void
1410 gui_mch_flash(int msec)
1416  * Return the Pixel value (color) for the given color name.  This routine was
1417  * pretty much taken from example code in the Silicon Graphics OSF/Motif
1418  * Programmer's Guide.
1419  * Return INVALCOLOR when failed.
1420  */
1421     guicolor_T
1422 gui_mch_get_color(char_u *name)
1424 #ifdef FEAT_MBYTE
1425     name = CONVERT_TO_UTF8(name);
1426 #endif
1428     NSString *key = [NSString stringWithUTF8String:(char*)name];
1429     guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1431 #ifdef FEAT_MBYTE
1432     CONVERT_TO_UTF8_FREE(name);
1433 #endif
1435     return col;
1440  * Return the RGB value of a pixel as long.
1441  */
1442     long_u
1443 gui_mch_get_rgb(guicolor_T pixel)
1445     // This is only implemented so that vim can guess the correct value for
1446     // 'background' (which otherwise defaults to 'dark'); it is not used for
1447     // anything else (as far as I know).
1448     // The implementation is simple since colors are stored in an int as
1449     // "rrggbb".
1450     return pixel;
1455  * Get the screen dimensions.
1456  * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1457  * Is there no way to find out how wide the borders really are?
1458  * TODO: Add live udate of those value on suspend/resume.
1459  */
1460     void
1461 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1463     //NSLog(@"gui_mch_get_screen_dimensions()");
1464     *screen_w = Columns;
1465     *screen_h = Rows;
1470  * Get the position of the top left corner of the window.
1471  */
1472     int
1473 gui_mch_get_winpos(int *x, int *y)
1475     *x = *y = 0;
1476     return OK;
1481  * Return OK if the key with the termcap name "name" is supported.
1482  */
1483     int
1484 gui_mch_haskey(char_u *name)
1486     BOOL ok = NO;
1488 #ifdef FEAT_MBYTE
1489     name = CONVERT_TO_UTF8(name);
1490 #endif
1492     NSString *value = [NSString stringWithUTF8String:(char*)name];
1493     if (value)
1494         ok =  [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1496 #ifdef FEAT_MBYTE
1497     CONVERT_TO_UTF8_FREE(name);
1498 #endif
1500     return ok;
1505  * Iconify the GUI window.
1506  */
1507     void
1508 gui_mch_iconify(void)
1513 #if defined(FEAT_EVAL) || defined(PROTO)
1515  * Bring the Vim window to the foreground.
1516  */
1517     void
1518 gui_mch_set_foreground(void)
1520     [[MMBackend sharedInstance] activate];
1522 #endif
1526     void
1527 gui_mch_set_shellsize(
1528     int         width,
1529     int         height,
1530     int         min_width,
1531     int         min_height,
1532     int         base_width,
1533     int         base_height,
1534     int         direction)
1536     //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1537     //        " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1538     //        width, height, min_width, min_height, base_width, base_height,
1539     //        direction);
1540     [[MMBackend sharedInstance] setRows:height columns:width];
1544     void
1545 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1550  * Set the position of the top left corner of the window to the given
1551  * coordinates.
1552  */
1553     void
1554 gui_mch_set_winpos(int x, int y)
1559 #ifdef FEAT_TITLE
1561  * Set the window title and icon.
1562  * (The icon is not taken care of).
1563  */
1564     void
1565 gui_mch_settitle(char_u *title, char_u *icon)
1567     //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1569 #ifdef FEAT_MBYTE
1570     title = CONVERT_TO_UTF8(title);
1571 #endif
1573     MMBackend *backend = [MMBackend sharedInstance];
1574     [backend setWindowTitle:(char*)title];
1576     // TODO: Convert filename to UTF-8?
1577     if (curbuf)
1578         [backend setDocumentFilename:(char*)curbuf->b_ffname];
1580 #ifdef FEAT_MBYTE
1581     CONVERT_TO_UTF8_FREE(title);
1582 #endif
1584 #endif
1587     void
1588 gui_mch_toggle_tearoffs(int enable)
1594     void
1595 gui_mch_enter_fullscreen(int fuoptions_flags, guicolor_T bg)
1597     [[MMBackend sharedInstance] enterFullscreen:fuoptions_flags background:bg];
1601     void
1602 gui_mch_leave_fullscreen()
1604     [[MMBackend sharedInstance] leaveFullscreen];
1608     void
1609 gui_macvim_update_modified_flag()
1611     [[MMBackend sharedInstance] updateModifiedFlag];
1615  * Add search pattern 'pat' to the OS X find pasteboard.  This allows other
1616  * apps access the last pattern searched for (hitting <D-g> in another app will
1617  * initiate a search for the same pattern).
1618  */
1619     void
1620 gui_macvim_add_to_find_pboard(char_u *pat)
1622     if (!pat) return;
1624 #ifdef FEAT_MBYTE
1625     pat = CONVERT_TO_UTF8(pat);
1626 #endif
1627     NSString *s = [NSString stringWithUTF8String:(char*)pat];
1628 #ifdef FEAT_MBYTE
1629     CONVERT_TO_UTF8_FREE(pat);
1630 #endif
1632     if (!s) return;
1634     NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
1635     [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1636     [pb setString:s forType:NSStringPboardType];
1639     void
1640 gui_macvim_set_antialias(int antialias)
1642     [[MMBackend sharedInstance] setAntialias:antialias];
1646     void
1647 gui_macvim_wait_for_startup()
1649     MMBackend *backend = [MMBackend sharedInstance];
1650     if ([backend waitForAck])
1651         [backend waitForConnectionAcknowledgement];
1654 void gui_macvim_get_window_layout(int *count, int *layout)
1656     if (!(count && layout)) return;
1658     int window_layout = [[MMBackend sharedInstance] initialWindowLayout];
1659     if (window_layout > 0 && window_layout < 4) {
1660         // The window_layout numbers must match the WIN_* defines in main.c.
1661         *count = 0;
1662         *layout = window_layout;
1663     }
1667 // -- Client/Server ---------------------------------------------------------
1669 #ifdef MAC_CLIENTSERVER
1672 // NOTE: Client/Server is only fully supported with a GUI.  Theoretically it
1673 // would be possible to make the server code work with terminal Vim, but it
1674 // would require that a run-loop is set up and checked.  This should not be
1675 // difficult to implement, simply call gui_mch_update() at opportune moments
1676 // and it will take care of the run-loop.  Another (bigger) problem with
1677 // supporting servers in terminal mode is that the server listing code talks to
1678 // MacVim (the GUI) to figure out which servers are running.
1683  * Register connection with 'name'.  The actual connection is named something
1684  * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1685  */
1686     void
1687 serverRegisterName(char_u *name)
1689 #ifdef FEAT_MBYTE
1690     name = CONVERT_TO_UTF8(name);
1691 #endif
1693     NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1694     [[MMBackend sharedInstance] registerServerWithName:svrName];
1696 #ifdef FEAT_MBYTE
1697     CONVERT_TO_UTF8_FREE(name);
1698 #endif
1703  * Send to an instance of Vim.
1704  * Returns 0 for OK, negative for an error.
1705  */
1706     int
1707 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1708         int *port, int asExpr, int silent)
1710 #ifdef FEAT_MBYTE
1711     name = CONVERT_TO_UTF8(name);
1712     cmd = CONVERT_TO_UTF8(cmd);
1713 #endif
1715     BOOL ok = [[MMBackend sharedInstance]
1716             sendToServer:[NSString stringWithUTF8String:(char*)name]
1717                   string:[NSString stringWithUTF8String:(char*)cmd]
1718                    reply:result
1719                     port:port
1720               expression:asExpr
1721                   silent:silent];
1723 #ifdef FEAT_MBYTE
1724     CONVERT_TO_UTF8_FREE(name);
1725     CONVERT_TO_UTF8_FREE(cmd);
1726 #endif
1728     return ok ? 0 : -1;
1733  * Ask MacVim for the names of all Vim servers.
1734  */
1735     char_u *
1736 serverGetVimNames(void)
1738     char_u *names = NULL;
1739     NSArray *list = [[MMBackend sharedInstance] serverList];
1741     if (list) {
1742         NSString *string = [list componentsJoinedByString:@"\n"];
1743         char_u *s = (char_u*)[string UTF8String];
1744 #ifdef FEAT_MBYTE
1745         s = CONVERT_FROM_UTF8(s);
1746 #endif
1747         names = vim_strsave(s);
1748 #ifdef FEAT_MBYTE
1749         CONVERT_FROM_UTF8_FREE(s);
1750 #endif
1751     }
1753     return names;
1758  * 'str' is a hex int representing the send port of the connection.
1759  */
1760     int
1761 serverStrToPort(char_u *str)
1763     int port = 0;
1765     sscanf((char *)str, "0x%x", &port);
1766     if (!port)
1767         EMSG2(_("E573: Invalid server id used: %s"), str);
1769     return port;
1774  * Check for replies from server with send port 'port'.
1775  * Return TRUE and a non-malloc'ed string if there is.  Else return FALSE.
1776  */
1777     int
1778 serverPeekReply(int port, char_u **str)
1780     NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1781     int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1783     if (str && len > 0) {
1784         *str = (char_u*)[reply UTF8String];
1786 #ifdef FEAT_MBYTE
1787         if (input_conv.vc_type != CONV_NONE) {
1788             char_u *s = string_convert(&input_conv, *str, &len);
1790             if (len > 0) {
1791                 // HACK! Since 's' needs to be freed we cannot simply set
1792                 // '*str = s' or memory will leak.  Instead, create a dummy
1793                 // NSData and return its 'bytes' pointer, then autorelease the
1794                 // NSData.
1795                 NSData *data = [NSData dataWithBytes:s length:len+1];
1796                 *str = (char_u*)[data bytes];
1797             }
1799             vim_free(s);
1800         }
1801 #endif
1802     }
1804     return reply != nil;
1809  * Wait for replies from server with send port 'port'.
1810  * Return 0 and the malloc'ed string when a reply is available.
1811  * Return -1 on error.
1812  */
1813     int
1814 serverReadReply(int port, char_u **str)
1816     NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1817     if (reply && str) {
1818         char_u *s = (char_u*)[reply UTF8String];
1819 #ifdef FEAT_MBYTE
1820         s = CONVERT_FROM_UTF8(s);
1821 #endif
1822         *str = vim_strsave(s);
1823 #ifdef FEAT_MBYTE
1824         CONVERT_FROM_UTF8_FREE(s);
1825 #endif
1826         return 0;
1827     }
1829     return -1;
1834  * Send a reply string (notification) to client with port given by "serverid".
1835  * Return -1 if the window is invalid.
1836  */
1837     int
1838 serverSendReply(char_u *serverid, char_u *reply)
1840     int retval = -1;
1841     int port = serverStrToPort(serverid);
1842     if (port > 0 && reply) {
1843 #ifdef FEAT_MBYTE
1844         reply = CONVERT_TO_UTF8(reply);
1845 #endif
1846         BOOL ok = [[MMBackend sharedInstance]
1847                 sendReply:[NSString stringWithUTF8String:(char*)reply]
1848                    toPort:port];
1849         retval = ok ? 0 : -1;
1850 #ifdef FEAT_MBYTE
1851         CONVERT_TO_UTF8_FREE(reply);
1852 #endif
1853     }
1855     return retval;
1858 #endif // MAC_CLIENTSERVER
1863 // -- ODB Editor Support ----------------------------------------------------
1865 #ifdef FEAT_ODB_EDITOR
1867  * The ODB Editor protocol works like this:
1868  * - An external program (the server) asks MacVim to open a file and associates
1869  *   three things with this file: (1) a server id (a four character code that
1870  *   identifies the server), (2) a path that can be used as window title for
1871  *   the file (optional), (3) an arbitrary token (optional)
1872  * - When a file is saved or closed, MacVim should tell the server about which
1873  *   file was modified and also pass back the token
1875  * All communication between MacVim and the server goes via Apple Events.
1876  */
1878     static OSErr
1879 odb_event(buf_T *buf, const AEEventID action)
1881     if (!(buf->b_odb_server_id && buf->b_ffname))
1882         return noErr;
1884     NSAppleEventDescriptor *targetDesc = [NSAppleEventDescriptor
1885             descriptorWithDescriptorType:typeApplSignature
1886                                    bytes:&buf->b_odb_server_id
1887                                   length:sizeof(OSType)];
1889     // TODO: Convert b_ffname to UTF-8?
1890     NSString *path = [NSString stringWithUTF8String:(char*)buf->b_ffname];
1891     NSData *pathData = [[[NSURL fileURLWithPath:path] absoluteString]
1892             dataUsingEncoding:NSUTF8StringEncoding];
1893     NSAppleEventDescriptor *pathDesc = [NSAppleEventDescriptor
1894             descriptorWithDescriptorType:typeFileURL data:pathData];
1896     NSAppleEventDescriptor *event = [NSAppleEventDescriptor
1897             appleEventWithEventClass:kODBEditorSuite
1898                              eventID:action
1899                     targetDescriptor:targetDesc
1900                             returnID:kAutoGenerateReturnID
1901                        transactionID:kAnyTransactionID];
1903     [event setParamDescriptor:pathDesc forKeyword:keyDirectObject];
1905     if (buf->b_odb_token)
1906         [event setParamDescriptor:buf->b_odb_token forKeyword:keySenderToken];
1908     return AESendMessage([event aeDesc], NULL, kAENoReply | kAENeverInteract,
1909             kAEDefaultTimeout);
1912     OSErr
1913 odb_buffer_close(buf_T *buf)
1915     OSErr err = noErr;
1916     if (buf) {
1917         err = odb_event(buf, kAEClosedFile);
1919         buf->b_odb_server_id = 0;
1921         if (buf->b_odb_token) {
1922             [(NSAppleEventDescriptor *)(buf->b_odb_token) release];
1923             buf->b_odb_token = NULL;
1924         }
1926         if (buf->b_odb_fname) {
1927             vim_free(buf->b_odb_fname);
1928             buf->b_odb_fname = NULL;
1929         }
1930     }
1932     return err;
1935     OSErr
1936 odb_post_buffer_write(buf_T *buf)
1938     return buf ? odb_event(buf, kAEModifiedFile) : noErr;
1941     void
1942 odb_end(void)
1944     buf_T *buf;
1945     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1946         odb_buffer_close(buf);
1949 #endif // FEAT_ODB_EDITOR
1952     char_u *
1953 get_macaction_name(expand_T *xp, int idx)
1955     static char_u *str = NULL;
1956     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1958     if (nil == actionDict || idx < 0 || idx >= [actionDict count])
1959         return NULL;
1961     NSString *string = [[actionDict allKeys] objectAtIndex:idx];
1962     if (!string)
1963         return NULL;
1965     char_u *plainStr = (char_u*)[string UTF8String];
1967 #ifdef FEAT_MBYTE
1968     if (str) {
1969         vim_free(str);
1970         str = NULL;
1971     }
1972     if (input_conv.vc_type != CONV_NONE) {
1973         int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1974         str = string_convert(&input_conv, plainStr, &len);
1975         plainStr = str;
1976     }
1977 #endif
1979     return plainStr;
1983     int
1984 is_valid_macaction(char_u *action)
1986     int isValid = NO;
1987     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1988     if (actionDict) {
1989 #ifdef FEAT_MBYTE
1990         action = CONVERT_TO_UTF8(action);
1991 #endif
1992         NSString *string = [NSString stringWithUTF8String:(char*)action];
1993         isValid = (nil != [actionDict objectForKey:string]);
1994 #ifdef FEAT_MBYTE
1995         CONVERT_TO_UTF8_FREE(action);
1996 #endif
1997     }
1999     return isValid;
2002 static int specialKeyToNSKey(int key)
2004     if (!IS_SPECIAL(key))
2005         return key;
2007     static struct {
2008         int special;
2009         int nskey;
2010     } sp2ns[] = {
2011         { K_UP, NSUpArrowFunctionKey },
2012         { K_DOWN, NSDownArrowFunctionKey },
2013         { K_LEFT, NSLeftArrowFunctionKey },
2014         { K_RIGHT, NSRightArrowFunctionKey },
2015         { K_F1, NSF1FunctionKey },
2016         { K_F2, NSF2FunctionKey },
2017         { K_F3, NSF3FunctionKey },
2018         { K_F4, NSF4FunctionKey },
2019         { K_F5, NSF5FunctionKey },
2020         { K_F6, NSF6FunctionKey },
2021         { K_F7, NSF7FunctionKey },
2022         { K_F8, NSF8FunctionKey },
2023         { K_F9, NSF9FunctionKey },
2024         { K_F10, NSF10FunctionKey },
2025         { K_F11, NSF11FunctionKey },
2026         { K_F12, NSF12FunctionKey },
2027         { K_F13, NSF13FunctionKey },
2028         { K_F14, NSF14FunctionKey },
2029         { K_F15, NSF15FunctionKey },
2030         { K_F16, NSF16FunctionKey },
2031         { K_F17, NSF17FunctionKey },
2032         { K_F18, NSF18FunctionKey },
2033         { K_F19, NSF19FunctionKey },
2034         { K_F20, NSF20FunctionKey },
2035         { K_F21, NSF21FunctionKey },
2036         { K_F22, NSF22FunctionKey },
2037         { K_F23, NSF23FunctionKey },
2038         { K_F24, NSF24FunctionKey },
2039         { K_F25, NSF25FunctionKey },
2040         { K_F26, NSF26FunctionKey },
2041         { K_F27, NSF27FunctionKey },
2042         { K_F28, NSF28FunctionKey },
2043         { K_F29, NSF29FunctionKey },
2044         { K_F30, NSF30FunctionKey },
2045         { K_F31, NSF31FunctionKey },
2046         { K_F32, NSF32FunctionKey },
2047         { K_F33, NSF33FunctionKey },
2048         { K_F34, NSF34FunctionKey },
2049         { K_F35, NSF35FunctionKey },
2050         { K_DEL, NSBackspaceCharacter },
2051         { K_BS, NSDeleteCharacter },
2052         { K_HOME, NSHomeFunctionKey },
2053         { K_END, NSEndFunctionKey },
2054         { K_PAGEUP, NSPageUpFunctionKey },
2055         { K_PAGEDOWN, NSPageDownFunctionKey }
2056     };
2058     int i;
2059     for (i = 0; i < sizeof(sp2ns)/sizeof(sp2ns[0]); ++i) {
2060         if (sp2ns[i].special == key)
2061             return sp2ns[i].nskey;
2062     }
2064     return 0;
2067 static int vimModMaskToEventModifierFlags(int mods)
2069     int flags = 0;
2071     if (mods & MOD_MASK_SHIFT)
2072         flags |= NSShiftKeyMask;
2073     if (mods & MOD_MASK_CTRL)
2074         flags |= NSControlKeyMask;
2075     if (mods & MOD_MASK_ALT)
2076         flags |= NSAlternateKeyMask;
2077     if (mods & MOD_MASK_CMD)
2078         flags |= NSCommandKeyMask;
2080     return flags;