Add Find & Replace dialog box
[MacVim.git] / src / MacVim / gui_macvim.m
blob6fd98048386f558e17cc5eb4edbe63fd703d6692
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.  It is tempting to do nothing
188     // here to avoid reduced frame-rates but then it would not be possible to
189     // interrupt Vim by presssing Ctrl-C during lengthy operations (e.g. after
190     // entering "10gs" it would not be possible to bring Vim out of the 10 s
191     // sleep prematurely).  As a compromise we check for Ctrl-C only once per
192     // second.
193     static CFAbsoluteTime lastTime = 0;
195     CFAbsoluteTime nowTime = CFAbsoluteTimeGetCurrent();
196     if (nowTime - lastTime > 1.0) {
197         [[MMBackend sharedInstance] update];
198         lastTime = nowTime;
199     }
203 /* Flush any output to the screen */
204     void
205 gui_mch_flush(void)
207     // This function is called way too often to be useful as a hint for
208     // flushing.  If we were to flush every time it was called the screen would
209     // flicker.
213 /* Force flush output to MacVim.  Do not call this method unless absolutely
214  * necessary. */
215     void
216 gui_macvim_force_flush(void)
218     [[MMBackend sharedInstance] flushQueue:YES];
223  * GUI input routine called by gui_wait_for_chars().  Waits for a character
224  * from the keyboard.
225  *  wtime == -1     Wait forever.
226  *  wtime == 0      This should never happen.
227  *  wtime > 0       Wait wtime milliseconds for a character.
228  * Returns OK if a character was found to be available within the given time,
229  * or FAIL otherwise.
230  */
231     int
232 gui_mch_wait_for_chars(int wtime)
234     // NOTE! In all likelihood Vim will take a nap when waitForInput: is
235     // called, so force a flush of the command queue here.
236     [[MMBackend sharedInstance] flushQueue:YES];
238     return [[MMBackend sharedInstance] waitForInput:wtime];
242 // -- Drawing ---------------------------------------------------------------
246  * Clear the whole text window.
247  */
248     void
249 gui_mch_clear_all(void)
251     [[MMBackend sharedInstance] clearAll];
256  * Clear a rectangular region of the screen from text pos (row1, col1) to
257  * (row2, col2) inclusive.
258  */
259     void
260 gui_mch_clear_block(int row1, int col1, int row2, int col2)
262     [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
263                                                     toRow:row2 column:col2];
268  * Delete the given number of lines from the given row, scrolling up any
269  * text further down within the scroll region.
270  */
271     void
272 gui_mch_delete_lines(int row, int num_lines)
274     [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
275             scrollBottom:gui.scroll_region_bot
276                     left:gui.scroll_region_left
277                    right:gui.scroll_region_right];
281     void
282 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
284 #ifdef FEAT_MBYTE
285     char_u *conv_str = NULL;
286     if (output_conv.vc_type != CONV_NONE) {
287         conv_str = string_convert(&output_conv, s, &len);
288         if (conv_str)
289             s = conv_str;
290     }
291 #endif
293     [[MMBackend sharedInstance] drawString:(char*)s length:len row:row
294                                     column:col cells:len flags:flags];
296 #ifdef FEAT_MBYTE
297     if (conv_str)
298         vim_free(conv_str);
299 #endif
303     int
304 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
306     int c, cn, cl, i;
307     int start = 0;
308     int endcol = col;
309     int startcol = col;
310     BOOL wide = NO;
311     MMBackend *backend = [MMBackend sharedInstance];
312 #ifdef FEAT_MBYTE
313     char_u *conv_str = NULL;
315     if (output_conv.vc_type != CONV_NONE) {
316         conv_str = string_convert(&output_conv, s, &len);
317         if (conv_str)
318             s = conv_str;
319     }
320 #endif
322     // Loop over each character and output text when it changes from normal to
323     // wide and vice versa.
324     for (i = 0; i < len; i += cl) {
325         c = utf_ptr2char(s + i);
326         cl = utf_ptr2len(s + i);
327         cn = utf_char2cells(c);
329         if (!utf_iscomposing(c)) {
330             if ((cn > 1 && !wide) || (cn <= 1 && wide)) {
331                 // Changed from normal to wide or vice versa.
332                 [backend drawString:(char*)(s+start) length:i-start
333                                    row:row column:startcol
334                                  cells:endcol-startcol
335                                  flags:(wide ? flags|DRAW_WIDE : flags)];
337                 start = i;
338                 startcol = endcol;
339             }
341             wide = cn > 1;
342             endcol += cn;
343         }
344     }
346     // Output remaining characters.
347     [backend drawString:(char*)(s+start) length:len-start
348                     row:row column:startcol cells:endcol-startcol
349                   flags:(wide ? flags|DRAW_WIDE : flags)];
351 #ifdef FEAT_MBYTE
352     if (conv_str)
353         vim_free(conv_str);
354 #endif
356     return endcol - col;
361  * Insert the given number of lines before the given row, scrolling down any
362  * following text within the scroll region.
363  */
364     void
365 gui_mch_insert_lines(int row, int num_lines)
367     [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
368             scrollBottom:gui.scroll_region_bot
369                     left:gui.scroll_region_left
370                    right:gui.scroll_region_right];
375  * Set the current text foreground color.
376  */
377     void
378 gui_mch_set_fg_color(guicolor_T color)
380     [[MMBackend sharedInstance] setForegroundColor:color];
385  * Set the current text background color.
386  */
387     void
388 gui_mch_set_bg_color(guicolor_T color)
390     [[MMBackend sharedInstance] setBackgroundColor:color];
395  * Set the current text special color (used for underlines).
396  */
397     void
398 gui_mch_set_sp_color(guicolor_T color)
400     [[MMBackend sharedInstance] setSpecialColor:color];
405  * Set default colors.
406  */
407     void
408 gui_mch_def_colors()
410     MMBackend *backend = [MMBackend sharedInstance];
412     // The default colors are taken from system values
413     gui.def_norm_pixel = gui.norm_pixel = 
414         [backend lookupColorWithKey:@"MacTextColor"];
415     gui.def_back_pixel = gui.back_pixel = 
416         [backend lookupColorWithKey:@"MacTextBackgroundColor"];
421  * Called when the foreground or background color has been changed.
422  */
423     void
424 gui_mch_new_colors(void)
426     gui.def_back_pixel = gui.back_pixel;
427     gui.def_norm_pixel = gui.norm_pixel;
429     //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
430     //        gui.def_norm_pixel);
432     [[MMBackend sharedInstance]
433         setDefaultColorsBackground:gui.def_back_pixel
434                         foreground:gui.def_norm_pixel];
438  * Invert a rectangle from row r, column c, for nr rows and nc columns.
439  */
440     void
441 gui_mch_invert_rectangle(int r, int c, int nr, int nc, int invert)
443     [[MMBackend sharedInstance] drawInvertedRectAtRow:r column:c numRows:nr
444             numColumns:nc invert:invert];
449 // -- Tabline ---------------------------------------------------------------
453  * Set the current tab to "nr".  First tab is 1.
454  */
455     void
456 gui_mch_set_curtab(int nr)
458     [[MMBackend sharedInstance] selectTab:nr];
463  * Return TRUE when tabline is displayed.
464  */
465     int
466 gui_mch_showing_tabline(void)
468     return [[MMBackend sharedInstance] tabBarVisible];
472  * Update the labels of the tabline.
473  */
474     void
475 gui_mch_update_tabline(void)
477     [[MMBackend sharedInstance] updateTabBar];
481  * Show or hide the tabline.
482  */
483     void
484 gui_mch_show_tabline(int showit)
486     [[MMBackend sharedInstance] showTabBar:showit];
490 // -- Clipboard -------------------------------------------------------------
493     void
494 clip_mch_lose_selection(VimClipboard *cbd)
499     int
500 clip_mch_own_selection(VimClipboard *cbd)
502     return 0;
506     void
507 clip_mch_request_selection(VimClipboard *cbd)
509     NSPasteboard *pb = [NSPasteboard generalPasteboard];
510     NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
511             NSStringPboardType, nil];
512     NSString *bestType = [pb availableTypeFromArray:supportedTypes];
513     if (!bestType) return;
515     int motion_type = MCHAR;
516     NSString *string = nil;
518     if ([bestType isEqual:VimPBoardType]) {
519         // This type should consist of an array with two objects:
520         //   1. motion type (NSNumber)
521         //   2. text (NSString)
522         // If this is not the case we fall back on using NSStringPboardType.
523         id plist = [pb propertyListForType:VimPBoardType];
524         if ([plist isKindOfClass:[NSArray class]] && [plist count] == 2) {
525             id obj = [plist objectAtIndex:1];
526             if ([obj isKindOfClass:[NSString class]]) {
527                 motion_type = [[plist objectAtIndex:0] intValue];
528                 string = obj;
529             }
530         }
531     }
533     if (!string) {
534         // Use NSStringPboardType.  The motion type is set to line-wise if the
535         // string contains at least one EOL character, otherwise it is set to
536         // character-wise (block-wise is never used).
537         NSMutableString *mstring =
538                 [[pb stringForType:NSStringPboardType] mutableCopy];
539         if (!mstring) return;
541         // Replace unrecognized end-of-line sequences with \x0a (line feed).
542         NSRange range = { 0, [mstring length] };
543         unsigned n = [mstring replaceOccurrencesOfString:@"\x0d\x0a"
544                                              withString:@"\x0a" options:0
545                                                   range:range];
546         if (0 == n) {
547             n = [mstring replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
548                                            options:0 range:range];
549         }
550         
551         // Scan for newline character to decide whether the string should be
552         // pasted line-wise or character-wise.
553         motion_type = MCHAR;
554         if (0 < n || NSNotFound != [mstring rangeOfString:@"\n"].location)
555             motion_type = MLINE;
557         string = mstring;
558     }
560     if (!(MCHAR == motion_type || MLINE == motion_type || MBLOCK == motion_type
561             || MAUTO == motion_type))
562         motion_type = MCHAR;
564     char_u *str = (char_u*)[string UTF8String];
565     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
567 #ifdef FEAT_MBYTE
568     if (input_conv.vc_type != CONV_NONE)
569         str = string_convert(&input_conv, str, &len);
570 #endif
572     if (str)
573         clip_yank_selection(motion_type, str, len, cbd);
575 #ifdef FEAT_MBYTE
576     if (input_conv.vc_type != CONV_NONE)
577         vim_free(str);
578 #endif
583  * Send the current selection to the clipboard.
584  */
585     void
586 clip_mch_set_selection(VimClipboard *cbd)
588     // If the '*' register isn't already filled in, fill it in now.
589     cbd->owned = TRUE;
590     clip_get_selection(cbd);
591     cbd->owned = FALSE;
592     
593     // Get the text to put on the pasteboard.
594     long_u llen = 0; char_u *str = 0;
595     int motion_type = clip_convert_selection(&str, &llen, cbd);
596     if (motion_type < 0)
597         return;
599     // TODO: Avoid overflow.
600     int len = (int)llen;
601 #ifdef FEAT_MBYTE
602     if (output_conv.vc_type != CONV_NONE) {
603         char_u *conv_str = string_convert(&output_conv, str, &len);
604         if (conv_str) {
605             vim_free(str);
606             str = conv_str;
607         }
608     }
609 #endif
611     if (len > 0) {
612         NSString *string = [[NSString alloc]
613             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
615         // See clip_mch_request_selection() for info on pasteboard types.
616         NSPasteboard *pb = [NSPasteboard generalPasteboard];
617         NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
618                 NSStringPboardType, nil];
619         [pb declareTypes:supportedTypes owner:nil];
621         NSNumber *motion = [NSNumber numberWithInt:motion_type];
622         NSArray *plist = [NSArray arrayWithObjects:motion, string, nil];
623         [pb setPropertyList:plist forType:VimPBoardType];
625         [pb setString:string forType:NSStringPboardType];
626         
627         [string release];
628     }
630     vim_free(str);
634 // -- Menu ------------------------------------------------------------------
638  * A menu descriptor represents the "address" of a menu as an array of strings.
639  * E.g. the menu "File->Close" has descriptor { "File", "Close" }.
640  */
641     NSArray *
642 descriptor_for_menu(vimmenu_T *menu)
644     if (!menu) return nil;
646     NSMutableArray *desc = [NSMutableArray array];
647     while (menu) {
648         NSString *name = [NSString stringWithVimString:menu->dname];
649         [desc insertObject:name atIndex:0];
650         menu = menu->parent;
651     }
653     return desc;
656     vimmenu_T *
657 menu_for_descriptor(NSArray *desc)
659     if (!(desc && [desc count] > 0)) return NULL;
661     vimmenu_T *menu = root_menu;
662     int i, count = [desc count];
664     for (i = 0; i < count; ++i) {
665         NSString *component = [desc objectAtIndex:i];
666         while (menu) {
667             NSString *name = [NSString stringWithVimString:menu->dname];
668             if ([component isEqual:name]) {
669                 if (i+1 == count)
670                     return menu;    // Matched all components, so return menu
671                 menu = menu->children;
672                 break;
673             }
674             menu = menu->next;
675         }
676     }
678     return NULL;
682  * Add a submenu to the menu bar, toolbar, or a popup menu.
683  */
684     void
685 gui_mch_add_menu(vimmenu_T *menu, int idx)
687     NSArray *desc = descriptor_for_menu(menu);
688     [[MMBackend sharedInstance] queueMessage:AddMenuMsgID properties:
689         [NSDictionary dictionaryWithObjectsAndKeys:
690             desc, @"descriptor",
691             [NSNumber numberWithInt:idx], @"index",
692             nil]];
697  * Add a menu item to a menu
698  */
699     void
700 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
702     char_u *tip = menu->strings[MENU_INDEX_TIP]
703             ? menu->strings[MENU_INDEX_TIP] : menu->actext;
704     NSArray *desc = descriptor_for_menu(menu);
705     NSString *keyEquivalent = menu->mac_key
706         ? [NSString stringWithFormat:@"%C", specialKeyToNSKey(menu->mac_key)]
707         : [NSString string];
708     int modifierMask = vimModMaskToEventModifierFlags(menu->mac_mods);
709     char_u *icon = NULL;
711     if (menu_is_toolbar(menu->parent->name)) {
712         char_u fname[MAXPATHL];
714         // TODO: Ensure menu->iconfile exists (if != NULL)
715         icon = menu->iconfile;
716         if (!icon && gui_find_bitmap(menu->name, fname, "bmp") == OK)
717             icon = fname;
718         if (!icon && menu->iconidx >= 0)
719             icon = menu->dname;
720     }
722     [[MMBackend sharedInstance] queueMessage:AddMenuItemMsgID properties:
723         [NSDictionary dictionaryWithObjectsAndKeys:
724             desc, @"descriptor",
725             [NSNumber numberWithInt:idx], @"index",
726             [NSString stringWithVimString:tip], @"tip",
727             [NSString stringWithVimString:icon], @"icon",
728             keyEquivalent, @"keyEquivalent",
729             [NSNumber numberWithInt:modifierMask], @"modifierMask",
730             [NSString stringWithVimString:menu->mac_action], @"action",
731             [NSNumber numberWithBool:menu->mac_alternate], @"isAlternate",
732             nil]];
737  * Destroy the machine specific menu widget.
738  */
739     void
740 gui_mch_destroy_menu(vimmenu_T *menu)
742     NSArray *desc = descriptor_for_menu(menu);
743     [[MMBackend sharedInstance] queueMessage:RemoveMenuItemMsgID properties:
744         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
749  * Make a menu either grey or not grey.
750  */
751     void
752 gui_mch_menu_grey(vimmenu_T *menu, int grey)
754     /* Only update menu if the 'grey' state has changed to avoid having to pass
755      * lots of unnecessary data to MacVim.  (Skipping this test makes MacVim
756      * pause noticably on mode changes. */
757     NSArray *desc = descriptor_for_menu(menu);
758     if (menu->was_grey == grey)
759         return;
761     menu->was_grey = grey;
763     [[MMBackend sharedInstance] queueMessage:EnableMenuItemMsgID properties:
764         [NSDictionary dictionaryWithObjectsAndKeys:
765             desc, @"descriptor",
766             [NSNumber numberWithInt:!grey], @"enable",
767             nil]];
772  * Make menu item hidden or not hidden
773  */
774     void
775 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
777     // HACK! There is no (obvious) way to hide a menu item, so simply
778     // enable/disable it instead.
779     gui_mch_menu_grey(menu, hidden);
784  * This is called when user right clicks.
785  */
786     void
787 gui_mch_show_popupmenu(vimmenu_T *menu)
789     NSArray *desc = descriptor_for_menu(menu);
790     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:
791         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
796  * This is called when a :popup command is executed.
797  */
798     void
799 gui_make_popup(char_u *path_name, int mouse_pos)
801     vimmenu_T *menu = gui_find_menu(path_name);
802     if (!(menu && menu->children)) return;
804     NSArray *desc = descriptor_for_menu(menu);
805     NSDictionary *p = (mouse_pos || NULL == curwin)
806         ? [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]
807         : [NSDictionary dictionaryWithObjectsAndKeys:
808             desc, @"descriptor",
809             [NSNumber numberWithInt:curwin->w_wrow], @"row",
810             [NSNumber numberWithInt:curwin->w_wcol], @"column",
811             nil];
813     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:p];
818  * This is called after setting all the menus to grey/hidden or not.
819  */
820     void
821 gui_mch_draw_menubar(void)
823     // The (main) menu draws itself in Mac OS X.
827     void
828 gui_mch_enable_menu(int flag)
830     // The (main) menu is always enabled in Mac OS X.
834 #if 0
835     void
836 gui_mch_set_menu_pos(int x, int y, int w, int h)
838     // The (main) menu cannot be moved in Mac OS X.
840 #endif
843     void
844 gui_mch_show_toolbar(int showit)
846     int flags = 0;
847     if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
848     if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
849     if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
851     [[MMBackend sharedInstance] showToolbar:showit flags:flags];
857 // -- Fonts -----------------------------------------------------------------
861  * If a font is not going to be used, free its structure.
862  */
863     void
864 gui_mch_free_font(font)
865     GuiFont     font;
867     if (font != NOFONT) {
868         //NSLog(@"gui_mch_free_font(font=0x%x)", font);
869         [(NSFont*)font release];
870     }
875  * Get a font structure for highlighting.
876  */
877     GuiFont
878 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
880     //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
881     //        giveErrorIfMissing);
883     NSFont *font = gui_macvim_font_with_name(name);
884     if (font)
885         return (GuiFont)[font retain];
887     if (giveErrorIfMissing)
888         EMSG2(_(e_font), name);
890     return NOFONT;
894 #if defined(FEAT_EVAL) || defined(PROTO)
896  * Return the name of font "font" in allocated memory.
897  * Don't know how to get the actual name, thus use the provided name.
898  */
899     char_u *
900 gui_mch_get_fontname(GuiFont font, char_u *name)
902     if (name == NULL)
903         return NULL;
904     return vim_strsave(name);
906 #endif
910  * Initialise vim to use the font with the given name.  Return FAIL if the font
911  * could not be loaded, OK otherwise.
912  */
913     int
914 gui_mch_init_font(char_u *font_name, int fontset)
916     //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
918     if (font_name && STRCMP(font_name, "*") == 0) {
919         // :set gfn=* shows the font panel.
920         do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
921         return FAIL;
922     }
924     NSFont *font = gui_macvim_font_with_name(font_name);
925     if (font) {
926         [(NSFont*)gui.norm_font release];
927         gui.norm_font = (GuiFont)[font retain];
929         // NOTE: MacVim keeps separate track of the normal and wide fonts.
930         // Unless the user changes 'guifontwide' manually, they are based on
931         // the same (normal) font.  Also note that each time the normal font is
932         // set, the advancement may change so the wide font needs to be updated
933         // as well (so that it is always twice the width of the normal font).
934         [[MMBackend sharedInstance] setFont:font];
935         [[MMBackend sharedInstance] setWideFont:
936                (NOFONT == gui.wide_font ? font : (NSFont*)gui.wide_font)];
938         return OK;
939     }
941     return FAIL;
946  * Set the current text font.
947  */
948     void
949 gui_mch_set_font(GuiFont font)
951     // Font selection is done inside MacVim...nothing here to do.
955     NSFont *
956 gui_macvim_font_with_name(char_u *name)
958     NSFont *font = nil;
959     NSString *fontName = MMDefaultFontName;
960     float size = MMDefaultFontSize;
961     BOOL parseFailed = NO;
963 #ifdef FEAT_MBYTE
964     name = CONVERT_TO_UTF8(name);
965 #endif
967     if (name) {
968         fontName = [NSString stringWithUTF8String:(char*)name];
970         NSArray *components = [fontName componentsSeparatedByString:@":"];
971         if ([components count] == 2) {
972             NSString *sizeString = [components lastObject];
973             if ([sizeString length] > 0
974                     && [sizeString characterAtIndex:0] == 'h') {
975                 sizeString = [sizeString substringFromIndex:1];
976                 if ([sizeString length] > 0) {
977                     size = [sizeString floatValue];
978                     fontName = [components objectAtIndex:0];
979                 }
980             } else {
981                 parseFailed = YES;
982             }
983         } else if ([components count] > 2) {
984             parseFailed = YES;
985         }
987         if (!parseFailed) {
988             // Replace underscores with spaces.
989             fontName = [[fontName componentsSeparatedByString:@"_"]
990                                      componentsJoinedByString:@" "];
991         }
992     }
994     if (!parseFailed && [fontName length] > 0) {
995         if (size < MMMinFontSize) size = MMMinFontSize;
996         if (size > MMMaxFontSize) size = MMMaxFontSize;
998         font = [NSFont fontWithName:fontName size:size];
1000         if (!font && MMDefaultFontName == fontName) {
1001             // If for some reason the MacVim default font is not in the app
1002             // bundle, then fall back on the system default font.
1003             font = [NSFont userFixedPitchFontOfSize:0];
1004         }
1005     }
1007 #ifdef FEAT_MBYTE
1008     CONVERT_TO_UTF8_FREE(name);
1009 #endif
1011     return font;
1014 // -- Scrollbars ------------------------------------------------------------
1017     void
1018 gui_mch_create_scrollbar(
1019         scrollbar_T *sb,
1020         int orient)     /* SBAR_VERT or SBAR_HORIZ */
1022     [[MMBackend sharedInstance] 
1023             createScrollbarWithIdentifier:sb->ident type:sb->type];
1027     void
1028 gui_mch_destroy_scrollbar(scrollbar_T *sb)
1030     [[MMBackend sharedInstance] 
1031             destroyScrollbarWithIdentifier:sb->ident];
1035     void
1036 gui_mch_enable_scrollbar(
1037         scrollbar_T     *sb,
1038         int             flag)
1040     [[MMBackend sharedInstance] 
1041             showScrollbarWithIdentifier:sb->ident state:flag];
1045     void
1046 gui_mch_set_scrollbar_pos(
1047         scrollbar_T *sb,
1048         int x,
1049         int y,
1050         int w,
1051         int h)
1053     int pos = y;
1054     int len = h;
1055     if (SBAR_BOTTOM == sb->type) {
1056         pos = x;
1057         len = w; 
1058     }
1060     [[MMBackend sharedInstance] 
1061             setScrollbarPosition:pos length:len identifier:sb->ident];
1065     void
1066 gui_mch_set_scrollbar_thumb(
1067         scrollbar_T *sb,
1068         long val,
1069         long size,
1070         long max)
1072     [[MMBackend sharedInstance] 
1073             setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
1077 // -- Cursor ----------------------------------------------------------------
1081  * Draw a cursor without focus.
1082  */
1083     void
1084 gui_mch_draw_hollow_cursor(guicolor_T color)
1086     return [[MMBackend sharedInstance]
1087         drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
1088                fraction:100 color:color];
1093  * Draw part of a cursor, only w pixels wide, and h pixels high.
1094  */
1095     void
1096 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
1098     // HACK!  'w' and 'h' are always 1 since we do not tell Vim about the exact
1099     // font dimensions.  Thus these parameters are useless.  Instead we look at
1100     // the shape_table to determine the shape and size of the cursor (just like
1101     // gui_update_cursor() does).
1103 #ifdef FEAT_RIGHTLEFT
1104     // If 'rl' is set the insert mode cursor must be drawn on the right-hand
1105     // side of a text cell.
1106     int rl = curwin ? curwin->w_p_rl : FALSE;
1107 #else
1108     int rl = FALSE;
1109 #endif
1110     int idx = get_shape_idx(FALSE);
1111     int shape = MMInsertionPointBlock;
1112     switch (shape_table[idx].shape) {
1113         case SHAPE_HOR:
1114             shape = MMInsertionPointHorizontal;
1115             break;
1116         case SHAPE_VER:
1117             shape = rl ? MMInsertionPointVerticalRight
1118                        : MMInsertionPointVertical;
1119             break;
1120     }
1122     return [[MMBackend sharedInstance]
1123         drawCursorAtRow:gui.row column:gui.col shape:shape
1124                fraction:shape_table[idx].percentage color:color];
1129  * Cursor blink functions.
1131  * This is a simple state machine:
1132  * BLINK_NONE   not blinking at all
1133  * BLINK_OFF    blinking, cursor is not shown
1134  * BLINK_ON blinking, cursor is shown
1135  */
1136     void
1137 gui_mch_set_blinking(long wait, long on, long off)
1139     [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1144  * Start the cursor blinking.  If it was already blinking, this restarts the
1145  * waiting time and shows the cursor.
1146  */
1147     void
1148 gui_mch_start_blink(void)
1150     [[MMBackend sharedInstance] startBlink];
1155  * Stop the cursor blinking.  Show the cursor if it wasn't shown.
1156  */
1157     void
1158 gui_mch_stop_blink(void)
1160     [[MMBackend sharedInstance] stopBlink];
1164 // -- Mouse -----------------------------------------------------------------
1168  * Get current mouse coordinates in text window.
1169  */
1170     void
1171 gui_mch_getmouse(int *x, int *y)
1173     //NSLog(@"gui_mch_getmouse()");
1177     void
1178 gui_mch_setmouse(int x, int y)
1180     //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1184     void
1185 mch_set_mouse_shape(int shape)
1187     [[MMBackend sharedInstance] setMouseShape:shape];
1193 // -- Input Method ----------------------------------------------------------
1195 #if defined(USE_IM_CONTROL)
1197     void
1198 im_set_position(int row, int col)
1200     // The pre-edit area is a popup window which is displayed by MMTextView.
1201     [[MMBackend sharedInstance] setPreEditRow:row column:col];
1205     void
1206 im_set_active(int active)
1208     // Set roman or the system script if 'active' is TRUE or FALSE,
1209     // respectively.
1210     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1212     if (!p_imdisable && smRoman != systemScript)
1213         KeyScript(active ? smKeySysScript : smKeyRoman);
1217     int
1218 im_get_status(void)
1220     // IM is active whenever the current script is the system script and the
1221     // system script isn't roman.  (Hence IM can only be active when using
1222     // non-roman scripts.)
1223     SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
1224     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1226     return currentScript != smRoman && currentScript == systemScript;
1229 #endif // defined(USE_IM_CONTROL)
1234 // -- Find & Replace dialog -------------------------------------------------
1236 #ifdef FIND_REPLACE_DIALOG
1238     static void
1239 macvim_find_and_replace(char_u *arg, BOOL replace)
1241     // TODO: Specialized dialog for find without replace?
1242     int wholeWord = FALSE;
1243     int matchCase = !p_ic;
1244     char_u *text  = get_find_dialog_text(arg, &wholeWord, &matchCase);
1246     int flags = 0;
1247     if (wholeWord) flags |= FRD_WHOLE_WORD;
1248     if (matchCase) flags |= FRD_MATCH_CASE;
1250     NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
1251             [NSString stringWithVimString:text],    @"text",
1252             [NSNumber numberWithInt:flags],         @"flags",
1253             nil];
1255     [[MMBackend sharedInstance] queueMessage:ShowFindReplaceDialogMsgID
1256                                   properties:args];
1259     void
1260 gui_mch_find_dialog(exarg_T *eap)
1262     macvim_find_and_replace(eap->arg, NO);
1265     void
1266 gui_mch_replace_dialog(exarg_T *eap)
1268     macvim_find_and_replace(eap->arg, YES);
1271 #endif // FIND_REPLACE_DIALOG
1276 // -- Unsorted --------------------------------------------------------------
1279     void
1280 ex_macaction(eap)
1281     exarg_T     *eap;
1283     if (!gui.in_use) {
1284         EMSG(_("E???: Command only available in GUI mode"));
1285         return;
1286     }
1288     char_u *arg = eap->arg;
1289 #ifdef FEAT_MBYTE
1290     arg = CONVERT_TO_UTF8(arg);
1291 #endif
1293     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1294     NSString *name = [NSString stringWithUTF8String:(char*)arg];
1295     if (actionDict && [actionDict objectForKey:name] != nil) {
1296         [[MMBackend sharedInstance] executeActionWithName:name];
1297     } else {
1298         EMSG2(_("E???: Invalid action: %s"), eap->arg);
1299     }
1301 #ifdef FEAT_MBYTE
1302     arg = CONVERT_TO_UTF8(arg);
1303 #endif
1308  * Adjust gui.char_height (after 'linespace' was changed).
1309  */
1310     int
1311 gui_mch_adjust_charheight(void)
1313     [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1314     return OK;
1318     void
1319 gui_mch_beep(void)
1321     NSBeep();
1326 #ifdef FEAT_BROWSE
1328  * Pop open a file browser and return the file selected, in allocated memory,
1329  * or NULL if Cancel is hit.
1330  *  saving  - TRUE if the file will be saved to, FALSE if it will be opened.
1331  *  title   - Title message for the file browser dialog.
1332  *  dflt    - Default name of file.
1333  *  ext     - Default extension to be added to files without extensions.
1334  *  initdir - directory in which to open the browser (NULL = current dir)
1335  *  filter  - Filter for matched files to choose from.
1336  *  Has a format like this:
1337  *  "C Files (*.c)\0*.c\0"
1338  *  "All Files\0*.*\0\0"
1339  *  If these two strings were concatenated, then a choice of two file
1340  *  filters will be selectable to the user.  Then only matching files will
1341  *  be shown in the browser.  If NULL, the default allows all files.
1343  *  *NOTE* - the filter string must be terminated with TWO nulls.
1344  */
1345     char_u *
1346 gui_mch_browse(
1347     int saving,
1348     char_u *title,
1349     char_u *dflt,
1350     char_u *ext,
1351     char_u *initdir,
1352     char_u *filter)
1354     //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1355     //        " filter=%s", saving, title, dflt, ext, initdir, filter);
1357     // Ensure no data is on the output queue before presenting the dialog.
1358     gui_macvim_force_flush();
1360     NSMutableDictionary *attr = [NSMutableDictionary
1361         dictionaryWithObject:[NSNumber numberWithBool:saving]
1362                       forKey:@"saving"];
1363     if (initdir)
1364         [attr setObject:[NSString stringWithVimString:initdir] forKey:@"dir"];
1366     char_u *s = (char_u*)[[MMBackend sharedInstance]
1367                             browseForFileWithAttributes:attr];
1369     return s;
1371 #endif /* FEAT_BROWSE */
1375     int
1376 gui_mch_dialog(
1377     int         type,
1378     char_u      *title,
1379     char_u      *message,
1380     char_u      *buttons,
1381     int         dfltbutton,
1382     char_u      *textfield)
1384     //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1385     //        "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1386     //        dfltbutton, textfield);
1388     // Ensure no data is on the output queue before presenting the dialog.
1389     gui_macvim_force_flush();
1391     int style = NSInformationalAlertStyle;
1392     if (VIM_WARNING == type) style = NSWarningAlertStyle;
1393     else if (VIM_ERROR == type) style = NSCriticalAlertStyle;
1395     NSMutableDictionary *attr = [NSMutableDictionary
1396                         dictionaryWithObject:[NSNumber numberWithInt:style]
1397                                       forKey:@"alertStyle"];
1399     if (buttons) {
1400         // 'buttons' is a string of '\n'-separated button titles 
1401         NSString *string = [NSString stringWithVimString:buttons];
1402         NSArray *array = [string componentsSeparatedByString:@"\n"];
1403         [attr setObject:array forKey:@"buttonTitles"];
1404     }
1406     NSString *messageText = nil;
1407     if (title)
1408         messageText = [NSString stringWithVimString:title];
1410     if (message) {
1411         NSString *informativeText = [NSString stringWithVimString:message];
1412         if (!messageText) {
1413             // HACK! If there is a '\n\n' or '\n' sequence in the message, then
1414             // make the part up to there into the title.  We only do this
1415             // because Vim has lots of dialogs without a title and they look
1416             // ugly that way.
1417             // TODO: Fix the actual dialog texts.
1418             NSRange eolRange = [informativeText rangeOfString:@"\n\n"];
1419             if (NSNotFound == eolRange.location)
1420                 eolRange = [informativeText rangeOfString:@"\n"];
1421             if (NSNotFound != eolRange.location) {
1422                 messageText = [informativeText substringToIndex:
1423                                                         eolRange.location];
1424                 informativeText = [informativeText substringFromIndex:
1425                                                         NSMaxRange(eolRange)];
1426             }
1427         }
1429         [attr setObject:informativeText forKey:@"informativeText"];
1430     }
1432     if (messageText)
1433         [attr setObject:messageText forKey:@"messageText"];
1435     if (textfield) {
1436         NSString *string = [NSString stringWithVimString:textfield];
1437         [attr setObject:string forKey:@"textFieldString"];
1438     }
1440     return [[MMBackend sharedInstance] showDialogWithAttributes:attr
1441                                                     textField:(char*)textfield];
1445     void
1446 gui_mch_flash(int msec)
1452  * Return the Pixel value (color) for the given color name.  This routine was
1453  * pretty much taken from example code in the Silicon Graphics OSF/Motif
1454  * Programmer's Guide.
1455  * Return INVALCOLOR when failed.
1456  */
1457     guicolor_T
1458 gui_mch_get_color(char_u *name)
1460 #ifdef FEAT_MBYTE
1461     name = CONVERT_TO_UTF8(name);
1462 #endif
1464     NSString *key = [NSString stringWithUTF8String:(char*)name];
1465     guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1467 #ifdef FEAT_MBYTE
1468     CONVERT_TO_UTF8_FREE(name);
1469 #endif
1471     return col;
1476  * Return the RGB value of a pixel as long.
1477  */
1478     long_u
1479 gui_mch_get_rgb(guicolor_T pixel)
1481     // This is only implemented so that vim can guess the correct value for
1482     // 'background' (which otherwise defaults to 'dark'); it is not used for
1483     // anything else (as far as I know).
1484     // The implementation is simple since colors are stored in an int as
1485     // "rrggbb".
1486     return pixel;
1491  * Get the screen dimensions.
1492  * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1493  * Is there no way to find out how wide the borders really are?
1494  * TODO: Add live udate of those value on suspend/resume.
1495  */
1496     void
1497 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1499     //NSLog(@"gui_mch_get_screen_dimensions()");
1500     *screen_w = Columns;
1501     *screen_h = Rows;
1506  * Get the position of the top left corner of the window.
1507  */
1508     int
1509 gui_mch_get_winpos(int *x, int *y)
1511     *x = *y = 0;
1512     return OK;
1517  * Return OK if the key with the termcap name "name" is supported.
1518  */
1519     int
1520 gui_mch_haskey(char_u *name)
1522     BOOL ok = NO;
1524 #ifdef FEAT_MBYTE
1525     name = CONVERT_TO_UTF8(name);
1526 #endif
1528     NSString *value = [NSString stringWithUTF8String:(char*)name];
1529     if (value)
1530         ok =  [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1532 #ifdef FEAT_MBYTE
1533     CONVERT_TO_UTF8_FREE(name);
1534 #endif
1536     return ok;
1541  * Iconify the GUI window.
1542  */
1543     void
1544 gui_mch_iconify(void)
1549 #if defined(FEAT_EVAL) || defined(PROTO)
1551  * Bring the Vim window to the foreground.
1552  */
1553     void
1554 gui_mch_set_foreground(void)
1556     [[MMBackend sharedInstance] activate];
1558 #endif
1562     void
1563 gui_mch_set_shellsize(
1564     int         width,
1565     int         height,
1566     int         min_width,
1567     int         min_height,
1568     int         base_width,
1569     int         base_height,
1570     int         direction)
1572     //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1573     //        " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1574     //        width, height, min_width, min_height, base_width, base_height,
1575     //        direction);
1576     [[MMBackend sharedInstance] setRows:height columns:width];
1580     void
1581 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1586  * Set the position of the top left corner of the window to the given
1587  * coordinates.
1588  */
1589     void
1590 gui_mch_set_winpos(int x, int y)
1595 #ifdef FEAT_TITLE
1597  * Set the window title and icon.
1598  * (The icon is not taken care of).
1599  */
1600     void
1601 gui_mch_settitle(char_u *title, char_u *icon)
1603     //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1605 #ifdef FEAT_MBYTE
1606     title = CONVERT_TO_UTF8(title);
1607 #endif
1609     MMBackend *backend = [MMBackend sharedInstance];
1610     [backend setWindowTitle:(char*)title];
1612     // TODO: Convert filename to UTF-8?
1613     if (curbuf)
1614         [backend setDocumentFilename:(char*)curbuf->b_ffname];
1616 #ifdef FEAT_MBYTE
1617     CONVERT_TO_UTF8_FREE(title);
1618 #endif
1620 #endif
1623     void
1624 gui_mch_toggle_tearoffs(int enable)
1630     void
1631 gui_mch_enter_fullscreen(int fuoptions_flags, guicolor_T bg)
1633     [[MMBackend sharedInstance] enterFullscreen:fuoptions_flags background:bg];
1637     void
1638 gui_mch_leave_fullscreen()
1640     [[MMBackend sharedInstance] leaveFullscreen];
1644     void
1645 gui_mch_fuopt_update()
1647     guicolor_T fg, bg;
1648     if (fuoptions_flags & FUOPT_BGCOLOR_HLGROUP) {
1649         syn_id2colors(fuoptions_bgcolor, &fg, &bg);
1650     } else {
1651         bg = fuoptions_bgcolor;
1652     }
1654     [[MMBackend sharedInstance] setFullscreenBackgroundColor:bg];
1658     void
1659 gui_macvim_update_modified_flag()
1661     [[MMBackend sharedInstance] updateModifiedFlag];
1665  * Add search pattern 'pat' to the OS X find pasteboard.  This allows other
1666  * apps access the last pattern searched for (hitting <D-g> in another app will
1667  * initiate a search for the same pattern).
1668  */
1669     void
1670 gui_macvim_add_to_find_pboard(char_u *pat)
1672     if (!pat) return;
1674 #ifdef FEAT_MBYTE
1675     pat = CONVERT_TO_UTF8(pat);
1676 #endif
1677     NSString *s = [NSString stringWithUTF8String:(char*)pat];
1678 #ifdef FEAT_MBYTE
1679     CONVERT_TO_UTF8_FREE(pat);
1680 #endif
1682     if (!s) return;
1684     NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
1685     [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1686     [pb setString:s forType:NSStringPboardType];
1689     void
1690 gui_macvim_set_antialias(int antialias)
1692     [[MMBackend sharedInstance] setAntialias:antialias];
1696     void
1697 gui_macvim_wait_for_startup()
1699     MMBackend *backend = [MMBackend sharedInstance];
1700     if ([backend waitForAck])
1701         [backend waitForConnectionAcknowledgement];
1704 void gui_macvim_get_window_layout(int *count, int *layout)
1706     if (!(count && layout)) return;
1708     // NOTE: Only set 'layout' if the backend has requested a != 0 layout, else
1709     // any command line arguments (-p/-o) would be ignored.
1710     int window_layout = [[MMBackend sharedInstance] initialWindowLayout];
1711     if (window_layout > 0 && window_layout < 4) {
1712         // The window_layout numbers must match the WIN_* defines in main.c.
1713         *count = 0;
1714         *layout = window_layout;
1715     }
1719 // -- Client/Server ---------------------------------------------------------
1721 #ifdef MAC_CLIENTSERVER
1724 // NOTE: Client/Server is only fully supported with a GUI.  Theoretically it
1725 // would be possible to make the server code work with terminal Vim, but it
1726 // would require that a run-loop is set up and checked.  This should not be
1727 // difficult to implement, simply call gui_mch_update() at opportune moments
1728 // and it will take care of the run-loop.  Another (bigger) problem with
1729 // supporting servers in terminal mode is that the server listing code talks to
1730 // MacVim (the GUI) to figure out which servers are running.
1735  * Register connection with 'name'.  The actual connection is named something
1736  * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1737  */
1738     void
1739 serverRegisterName(char_u *name)
1741 #ifdef FEAT_MBYTE
1742     name = CONVERT_TO_UTF8(name);
1743 #endif
1745     NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1746     [[MMBackend sharedInstance] registerServerWithName:svrName];
1748 #ifdef FEAT_MBYTE
1749     CONVERT_TO_UTF8_FREE(name);
1750 #endif
1755  * Send to an instance of Vim.
1756  * Returns 0 for OK, negative for an error.
1757  */
1758     int
1759 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1760         int *port, int asExpr, int silent)
1762 #ifdef FEAT_MBYTE
1763     name = CONVERT_TO_UTF8(name);
1764     cmd = CONVERT_TO_UTF8(cmd);
1765 #endif
1767     BOOL ok = [[MMBackend sharedInstance]
1768             sendToServer:[NSString stringWithUTF8String:(char*)name]
1769                   string:[NSString stringWithUTF8String:(char*)cmd]
1770                    reply:result
1771                     port:port
1772               expression:asExpr
1773                   silent:silent];
1775 #ifdef FEAT_MBYTE
1776     CONVERT_TO_UTF8_FREE(name);
1777     CONVERT_TO_UTF8_FREE(cmd);
1778 #endif
1780     return ok ? 0 : -1;
1785  * Ask MacVim for the names of all Vim servers.
1786  */
1787     char_u *
1788 serverGetVimNames(void)
1790     char_u *names = NULL;
1791     NSArray *list = [[MMBackend sharedInstance] serverList];
1793     if (list) {
1794         NSString *string = [list componentsJoinedByString:@"\n"];
1795         names = [string vimStringSave];
1796     }
1798     return names;
1803  * 'str' is a hex int representing the send port of the connection.
1804  */
1805     int
1806 serverStrToPort(char_u *str)
1808     int port = 0;
1810     sscanf((char *)str, "0x%x", &port);
1811     if (!port)
1812         EMSG2(_("E573: Invalid server id used: %s"), str);
1814     return port;
1819  * Check for replies from server with send port 'port'.
1820  * Return TRUE and a non-malloc'ed string if there is.  Else return FALSE.
1821  */
1822     int
1823 serverPeekReply(int port, char_u **str)
1825     NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1826     int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1828     if (str && len > 0) {
1829         *str = (char_u*)[reply UTF8String];
1831 #ifdef FEAT_MBYTE
1832         if (input_conv.vc_type != CONV_NONE) {
1833             char_u *s = string_convert(&input_conv, *str, &len);
1835             if (len > 0) {
1836                 // HACK! Since 's' needs to be freed we cannot simply set
1837                 // '*str = s' or memory will leak.  Instead, create a dummy
1838                 // NSData and return its 'bytes' pointer, then autorelease the
1839                 // NSData.
1840                 NSData *data = [NSData dataWithBytes:s length:len+1];
1841                 *str = (char_u*)[data bytes];
1842             }
1844             vim_free(s);
1845         }
1846 #endif
1847     }
1849     return reply != nil;
1854  * Wait for replies from server with send port 'port'.
1855  * Return 0 and the malloc'ed string when a reply is available.
1856  * Return -1 on error.
1857  */
1858     int
1859 serverReadReply(int port, char_u **str)
1861     NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1862     if (reply && str) {
1863         *str = [reply vimStringSave];
1864         return 0;
1865     }
1867     return -1;
1872  * Send a reply string (notification) to client with port given by "serverid".
1873  * Return -1 if the window is invalid.
1874  */
1875     int
1876 serverSendReply(char_u *serverid, char_u *reply)
1878     int retval = -1;
1879     int port = serverStrToPort(serverid);
1880     if (port > 0 && reply) {
1881 #ifdef FEAT_MBYTE
1882         reply = CONVERT_TO_UTF8(reply);
1883 #endif
1884         BOOL ok = [[MMBackend sharedInstance]
1885                 sendReply:[NSString stringWithUTF8String:(char*)reply]
1886                    toPort:port];
1887         retval = ok ? 0 : -1;
1888 #ifdef FEAT_MBYTE
1889         CONVERT_TO_UTF8_FREE(reply);
1890 #endif
1891     }
1893     return retval;
1896 #endif // MAC_CLIENTSERVER
1901 // -- ODB Editor Support ----------------------------------------------------
1903 #ifdef FEAT_ODB_EDITOR
1905  * The ODB Editor protocol works like this:
1906  * - An external program (the server) asks MacVim to open a file and associates
1907  *   three things with this file: (1) a server id (a four character code that
1908  *   identifies the server), (2) a path that can be used as window title for
1909  *   the file (optional), (3) an arbitrary token (optional)
1910  * - When a file is saved or closed, MacVim should tell the server about which
1911  *   file was modified and also pass back the token
1913  * All communication between MacVim and the server goes via Apple Events.
1914  */
1916     static OSErr
1917 odb_event(buf_T *buf, const AEEventID action)
1919     if (!(buf->b_odb_server_id && buf->b_ffname))
1920         return noErr;
1922     NSAppleEventDescriptor *targetDesc = [NSAppleEventDescriptor
1923             descriptorWithDescriptorType:typeApplSignature
1924                                    bytes:&buf->b_odb_server_id
1925                                   length:sizeof(OSType)];
1927     // TODO: Convert b_ffname to UTF-8?
1928     NSString *path = [NSString stringWithUTF8String:(char*)buf->b_ffname];
1929     NSData *pathData = [[[NSURL fileURLWithPath:path] absoluteString]
1930             dataUsingEncoding:NSUTF8StringEncoding];
1931     NSAppleEventDescriptor *pathDesc = [NSAppleEventDescriptor
1932             descriptorWithDescriptorType:typeFileURL data:pathData];
1934     NSAppleEventDescriptor *event = [NSAppleEventDescriptor
1935             appleEventWithEventClass:kODBEditorSuite
1936                              eventID:action
1937                     targetDescriptor:targetDesc
1938                             returnID:kAutoGenerateReturnID
1939                        transactionID:kAnyTransactionID];
1941     [event setParamDescriptor:pathDesc forKeyword:keyDirectObject];
1943     if (buf->b_odb_token)
1944         [event setParamDescriptor:buf->b_odb_token forKeyword:keySenderToken];
1946     return AESendMessage([event aeDesc], NULL, kAENoReply | kAENeverInteract,
1947             kAEDefaultTimeout);
1950     OSErr
1951 odb_buffer_close(buf_T *buf)
1953     OSErr err = noErr;
1954     if (buf) {
1955         err = odb_event(buf, kAEClosedFile);
1957         buf->b_odb_server_id = 0;
1959         if (buf->b_odb_token) {
1960             [(NSAppleEventDescriptor *)(buf->b_odb_token) release];
1961             buf->b_odb_token = NULL;
1962         }
1964         if (buf->b_odb_fname) {
1965             vim_free(buf->b_odb_fname);
1966             buf->b_odb_fname = NULL;
1967         }
1968     }
1970     return err;
1973     OSErr
1974 odb_post_buffer_write(buf_T *buf)
1976     return buf ? odb_event(buf, kAEModifiedFile) : noErr;
1979     void
1980 odb_end(void)
1982     buf_T *buf;
1983     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1984         odb_buffer_close(buf);
1987 #endif // FEAT_ODB_EDITOR
1990     char_u *
1991 get_macaction_name(expand_T *xp, int idx)
1993     static char_u *str = NULL;
1994     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1996     if (nil == actionDict || idx < 0 || idx >= [actionDict count])
1997         return NULL;
1999     NSString *string = [[actionDict allKeys] objectAtIndex:idx];
2000     if (!string)
2001         return NULL;
2003     char_u *plainStr = (char_u*)[string UTF8String];
2005 #ifdef FEAT_MBYTE
2006     if (str) {
2007         vim_free(str);
2008         str = NULL;
2009     }
2010     if (input_conv.vc_type != CONV_NONE) {
2011         int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
2012         str = string_convert(&input_conv, plainStr, &len);
2013         plainStr = str;
2014     }
2015 #endif
2017     return plainStr;
2021     int
2022 is_valid_macaction(char_u *action)
2024     int isValid = NO;
2025     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
2026     if (actionDict) {
2027 #ifdef FEAT_MBYTE
2028         action = CONVERT_TO_UTF8(action);
2029 #endif
2030         NSString *string = [NSString stringWithUTF8String:(char*)action];
2031         isValid = (nil != [actionDict objectForKey:string]);
2032 #ifdef FEAT_MBYTE
2033         CONVERT_TO_UTF8_FREE(action);
2034 #endif
2035     }
2037     return isValid;
2040 static int specialKeyToNSKey(int key)
2042     if (!IS_SPECIAL(key))
2043         return key;
2045     static struct {
2046         int special;
2047         int nskey;
2048     } sp2ns[] = {
2049         { K_UP, NSUpArrowFunctionKey },
2050         { K_DOWN, NSDownArrowFunctionKey },
2051         { K_LEFT, NSLeftArrowFunctionKey },
2052         { K_RIGHT, NSRightArrowFunctionKey },
2053         { K_F1, NSF1FunctionKey },
2054         { K_F2, NSF2FunctionKey },
2055         { K_F3, NSF3FunctionKey },
2056         { K_F4, NSF4FunctionKey },
2057         { K_F5, NSF5FunctionKey },
2058         { K_F6, NSF6FunctionKey },
2059         { K_F7, NSF7FunctionKey },
2060         { K_F8, NSF8FunctionKey },
2061         { K_F9, NSF9FunctionKey },
2062         { K_F10, NSF10FunctionKey },
2063         { K_F11, NSF11FunctionKey },
2064         { K_F12, NSF12FunctionKey },
2065         { K_F13, NSF13FunctionKey },
2066         { K_F14, NSF14FunctionKey },
2067         { K_F15, NSF15FunctionKey },
2068         { K_F16, NSF16FunctionKey },
2069         { K_F17, NSF17FunctionKey },
2070         { K_F18, NSF18FunctionKey },
2071         { K_F19, NSF19FunctionKey },
2072         { K_F20, NSF20FunctionKey },
2073         { K_F21, NSF21FunctionKey },
2074         { K_F22, NSF22FunctionKey },
2075         { K_F23, NSF23FunctionKey },
2076         { K_F24, NSF24FunctionKey },
2077         { K_F25, NSF25FunctionKey },
2078         { K_F26, NSF26FunctionKey },
2079         { K_F27, NSF27FunctionKey },
2080         { K_F28, NSF28FunctionKey },
2081         { K_F29, NSF29FunctionKey },
2082         { K_F30, NSF30FunctionKey },
2083         { K_F31, NSF31FunctionKey },
2084         { K_F32, NSF32FunctionKey },
2085         { K_F33, NSF33FunctionKey },
2086         { K_F34, NSF34FunctionKey },
2087         { K_F35, NSF35FunctionKey },
2088         { K_DEL, NSBackspaceCharacter },
2089         { K_BS, NSDeleteCharacter },
2090         { K_HOME, NSHomeFunctionKey },
2091         { K_END, NSEndFunctionKey },
2092         { K_PAGEUP, NSPageUpFunctionKey },
2093         { K_PAGEDOWN, NSPageDownFunctionKey }
2094     };
2096     int i;
2097     for (i = 0; i < sizeof(sp2ns)/sizeof(sp2ns[0]); ++i) {
2098         if (sp2ns[i].special == key)
2099             return sp2ns[i].nskey;
2100     }
2102     return 0;
2105 static int vimModMaskToEventModifierFlags(int mods)
2107     int flags = 0;
2109     if (mods & MOD_MASK_SHIFT)
2110         flags |= NSShiftKeyMask;
2111     if (mods & MOD_MASK_CTRL)
2112         flags |= NSControlKeyMask;
2113     if (mods & MOD_MASK_ALT)
2114         flags |= NSAlternateKeyMask;
2115     if (mods & MOD_MASK_CMD)
2116         flags |= NSCommandKeyMask;
2118     return flags;