Fix problems with 'fullscreen' and :mksession
[MacVim.git] / src / MacVim / gui_macvim.m
blobed50ab3cd4d2515ddb222e9e79f1b754d7926ea4
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     // Ensure 'linespace' option is passed along to MacVim in case it was set
134     // in [g]vimrc.
135     gui_mch_adjust_charheight();
137     return OK;
142     void
143 gui_mch_exit(int rc)
145     //NSLog(@"gui_mch_exit(rc=%d)", rc);
147     [[MMBackend sharedInstance] exit];
152  * Open the GUI window which was created by a call to gui_mch_init().
153  */
154     int
155 gui_mch_open(void)
157     return [[MMBackend sharedInstance] openGUIWindow];
161 // -- Updating --------------------------------------------------------------
165  * Catch up with any queued X events.  This may put keyboard input into the
166  * input buffer, call resize call-backs, trigger timers etc.  If there is
167  * nothing in the X event queue (& no timers pending), then we return
168  * immediately.
169  */
170 #define MM_LOG_UPDATE_STATS 0
171     void
172 gui_mch_update(void)
174     // NOTE: This function can get called A LOT (~1 call/ms) and unfortunately
175     // checking the run loop takes a long time, resulting in noticable slow
176     // downs if it is done every time this function is called.  Therefore we
177     // make sure that it is not done too often.
178     static NSDate *lastUpdateDate = nil;
179 #if MM_LOG_UPDATE_STATS
180     static int skipCount = 0;
181 #endif
183     if (lastUpdateDate && -[lastUpdateDate timeIntervalSinceNow] <
184             MMUpdateTimeoutInterval) {
185 #if MM_LOG_UPDATE_STATS
186         ++skipCount;
187 #endif
188         return;
189     }
191 #if MM_LOG_UPDATE_STATS
192     NSTimeInterval dt = -[lastUpdateDate timeIntervalSinceNow];
193     NSLog(@"Updating (last update %.2f seconds ago, skipped %d updates, "
194             "approx %.1f calls per second)",
195             dt, skipCount, dt > 0 ? skipCount/dt : 0);
196     skipCount = 0;
197 #endif
199     [[MMBackend sharedInstance] update];
201     [lastUpdateDate release];
202     lastUpdateDate = [[NSDate date] retain];
206 /* Flush any output to the screen */
207     void
208 gui_mch_flush(void)
210     [[MMBackend sharedInstance] flushQueue:NO];
214 /* Force flush output to MacVim.  Do not call this method unless absolutely
215  * necessary (use gui_mch_flush() instead). */
216     void
217 gui_macvim_force_flush(void)
219     [[MMBackend sharedInstance] flushQueue:YES];
224  * GUI input routine called by gui_wait_for_chars().  Waits for a character
225  * from the keyboard.
226  *  wtime == -1     Wait forever.
227  *  wtime == 0      This should never happen.
228  *  wtime > 0       Wait wtime milliseconds for a character.
229  * Returns OK if a character was found to be available within the given time,
230  * or FAIL otherwise.
231  */
232     int
233 gui_mch_wait_for_chars(int wtime)
235     // NOTE! In all likelihood Vim will take a nap when waitForInput: is
236     // called, so force a flush of the command queue here.
237     [[MMBackend sharedInstance] flushQueue:YES];
239     return [[MMBackend sharedInstance] waitForInput:wtime];
243 // -- Drawing ---------------------------------------------------------------
247  * Clear the whole text window.
248  */
249     void
250 gui_mch_clear_all(void)
252     [[MMBackend sharedInstance] clearAll];
257  * Clear a rectangular region of the screen from text pos (row1, col1) to
258  * (row2, col2) inclusive.
259  */
260     void
261 gui_mch_clear_block(int row1, int col1, int row2, int col2)
263     [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
264                                                     toRow:row2 column:col2];
269  * Delete the given number of lines from the given row, scrolling up any
270  * text further down within the scroll region.
271  */
272     void
273 gui_mch_delete_lines(int row, int num_lines)
275     [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
276             scrollBottom:gui.scroll_region_bot
277                     left:gui.scroll_region_left
278                    right:gui.scroll_region_right];
282     void
283 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
285 #ifdef FEAT_MBYTE
286     char_u *conv_str = NULL;
287     if (output_conv.vc_type != CONV_NONE) {
288         conv_str = string_convert(&output_conv, s, &len);
289         if (conv_str)
290             s = conv_str;
291     }
292 #endif
294     [[MMBackend sharedInstance] drawString:(char*)s length:len row:row
295                                     column:col cells:len flags:flags];
297 #ifdef FEAT_MBYTE
298     if (conv_str)
299         vim_free(conv_str);
300 #endif
304     int
305 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
307     int c, cn, cl, i;
308     int start = 0;
309     int endcol = col;
310     int startcol = col;
311     BOOL wide = NO;
312     MMBackend *backend = [MMBackend sharedInstance];
313 #ifdef FEAT_MBYTE
314     char_u *conv_str = NULL;
316     if (output_conv.vc_type != CONV_NONE) {
317         conv_str = string_convert(&output_conv, s, &len);
318         if (conv_str)
319             s = conv_str;
320     }
321 #endif
323     // Loop over each character and output text when it changes from normal to
324     // wide and vice versa.
325     for (i = 0; i < len; i += cl) {
326         c = utf_ptr2char(s + i);
327         cl = utf_ptr2len(s + i);
328         cn = utf_char2cells(c);
330         if (!utf_iscomposing(c)) {
331             if ((cn > 1 && !wide) || (cn <= 1 && wide)) {
332                 // Changed from normal to wide or vice versa.
333                 [backend drawString:(char*)(s+start) length:i-start
334                                    row:row column:startcol
335                                  cells:endcol-startcol
336                                  flags:(wide ? flags|DRAW_WIDE : flags)];
338                 start = i;
339                 startcol = endcol;
340             }
342             wide = cn > 1;
343             endcol += cn;
344         }
345     }
347     // Output remaining characters.
348     [backend drawString:(char*)(s+start) length:len-start
349                     row:row column:startcol cells:endcol-startcol
350                   flags:(wide ? flags|DRAW_WIDE : flags)];
352 #ifdef FEAT_MBYTE
353     if (conv_str)
354         vim_free(conv_str);
355 #endif
357     return endcol - col;
362  * Insert the given number of lines before the given row, scrolling down any
363  * following text within the scroll region.
364  */
365     void
366 gui_mch_insert_lines(int row, int num_lines)
368     [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
369             scrollBottom:gui.scroll_region_bot
370                     left:gui.scroll_region_left
371                    right:gui.scroll_region_right];
376  * Set the current text foreground color.
377  */
378     void
379 gui_mch_set_fg_color(guicolor_T color)
381     [[MMBackend sharedInstance] setForegroundColor:color];
386  * Set the current text background color.
387  */
388     void
389 gui_mch_set_bg_color(guicolor_T color)
391     [[MMBackend sharedInstance] setBackgroundColor:color];
396  * Set the current text special color (used for underlines).
397  */
398     void
399 gui_mch_set_sp_color(guicolor_T color)
401     [[MMBackend sharedInstance] setSpecialColor:color];
406  * Set default colors.
407  */
408     void
409 gui_mch_def_colors()
411     MMBackend *backend = [MMBackend sharedInstance];
413     // The default colors are taken from system values
414     gui.def_norm_pixel = gui.norm_pixel = 
415         [backend lookupColorWithKey:@"MacTextColor"];
416     gui.def_back_pixel = gui.back_pixel = 
417         [backend lookupColorWithKey:@"MacTextBackgroundColor"];
422  * Called when the foreground or background color has been changed.
423  */
424     void
425 gui_mch_new_colors(void)
427     gui.def_back_pixel = gui.back_pixel;
428     gui.def_norm_pixel = gui.norm_pixel;
430     //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
431     //        gui.def_norm_pixel);
433     [[MMBackend sharedInstance]
434         setDefaultColorsBackground:gui.def_back_pixel
435                         foreground:gui.def_norm_pixel];
439  * Invert a rectangle from row r, column c, for nr rows and nc columns.
440  */
441     void
442 gui_mch_invert_rectangle(int r, int c, int nr, int nc, int invert)
444     [[MMBackend sharedInstance] drawInvertedRectAtRow:r column:c numRows:nr
445             numColumns:nc invert:invert];
450 // -- Tabline ---------------------------------------------------------------
454  * Set the current tab to "nr".  First tab is 1.
455  */
456     void
457 gui_mch_set_curtab(int nr)
459     [[MMBackend sharedInstance] selectTab:nr];
464  * Return TRUE when tabline is displayed.
465  */
466     int
467 gui_mch_showing_tabline(void)
469     return [[MMBackend sharedInstance] tabBarVisible];
473  * Update the labels of the tabline.
474  */
475     void
476 gui_mch_update_tabline(void)
478     [[MMBackend sharedInstance] updateTabBar];
482  * Show or hide the tabline.
483  */
484     void
485 gui_mch_show_tabline(int showit)
487     [[MMBackend sharedInstance] showTabBar:showit];
491 // -- Clipboard -------------------------------------------------------------
494     void
495 clip_mch_lose_selection(VimClipboard *cbd)
500     int
501 clip_mch_own_selection(VimClipboard *cbd)
503     return 0;
507     void
508 clip_mch_request_selection(VimClipboard *cbd)
510     NSPasteboard *pb = [NSPasteboard generalPasteboard];
511     NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
512             NSStringPboardType, nil];
513     NSString *bestType = [pb availableTypeFromArray:supportedTypes];
514     if (!bestType) return;
516     int motion_type = MCHAR;
517     NSString *string = nil;
519     if ([bestType isEqual:VimPBoardType]) {
520         // This type should consist of an array with two objects:
521         //   1. motion type (NSNumber)
522         //   2. text (NSString)
523         // If this is not the case we fall back on using NSStringPboardType.
524         id plist = [pb propertyListForType:VimPBoardType];
525         if ([plist isKindOfClass:[NSArray class]] && [plist count] == 2) {
526             id obj = [plist objectAtIndex:1];
527             if ([obj isKindOfClass:[NSString class]]) {
528                 motion_type = [[plist objectAtIndex:0] intValue];
529                 string = obj;
530             }
531         }
532     }
534     if (!string) {
535         // Use NSStringPboardType.  The motion type is set to line-wise if the
536         // string contains at least one EOL character, otherwise it is set to
537         // character-wise (block-wise is never used).
538         NSMutableString *mstring =
539                 [[pb stringForType:NSStringPboardType] mutableCopy];
540         if (!mstring) return;
542         // Replace unrecognized end-of-line sequences with \x0a (line feed).
543         NSRange range = { 0, [mstring length] };
544         unsigned n = [mstring replaceOccurrencesOfString:@"\x0d\x0a"
545                                              withString:@"\x0a" options:0
546                                                   range:range];
547         if (0 == n) {
548             n = [mstring replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
549                                            options:0 range:range];
550         }
551         
552         // Scan for newline character to decide whether the string should be
553         // pasted line-wise or character-wise.
554         motion_type = MCHAR;
555         if (0 < n || NSNotFound != [mstring rangeOfString:@"\n"].location)
556             motion_type = MLINE;
558         string = mstring;
559     }
561     if (!(MCHAR == motion_type || MLINE == motion_type || MBLOCK == motion_type
562             || MAUTO == motion_type))
563         motion_type = MCHAR;
565     char_u *str = (char_u*)[string UTF8String];
566     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
568 #ifdef FEAT_MBYTE
569     if (input_conv.vc_type != CONV_NONE)
570         str = string_convert(&input_conv, str, &len);
571 #endif
573     if (str)
574         clip_yank_selection(motion_type, str, len, cbd);
576 #ifdef FEAT_MBYTE
577     if (input_conv.vc_type != CONV_NONE)
578         vim_free(str);
579 #endif
584  * Send the current selection to the clipboard.
585  */
586     void
587 clip_mch_set_selection(VimClipboard *cbd)
589     // If the '*' register isn't already filled in, fill it in now.
590     cbd->owned = TRUE;
591     clip_get_selection(cbd);
592     cbd->owned = FALSE;
593     
594     // Get the text to put on the pasteboard.
595     long_u llen = 0; char_u *str = 0;
596     int motion_type = clip_convert_selection(&str, &llen, cbd);
597     if (motion_type < 0)
598         return;
600     // TODO: Avoid overflow.
601     int len = (int)llen;
602 #ifdef FEAT_MBYTE
603     if (output_conv.vc_type != CONV_NONE) {
604         char_u *conv_str = string_convert(&output_conv, str, &len);
605         if (conv_str) {
606             vim_free(str);
607             str = conv_str;
608         }
609     }
610 #endif
612     if (len > 0) {
613         NSString *string = [[NSString alloc]
614             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
616         // See clip_mch_request_selection() for info on pasteboard types.
617         NSPasteboard *pb = [NSPasteboard generalPasteboard];
618         NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
619                 NSStringPboardType, nil];
620         [pb declareTypes:supportedTypes owner:nil];
622         NSNumber *motion = [NSNumber numberWithInt:motion_type];
623         NSArray *plist = [NSArray arrayWithObjects:motion, string, nil];
624         [pb setPropertyList:plist forType:VimPBoardType];
626         [pb setString:string forType:NSStringPboardType];
627         
628         [string release];
629     }
631     vim_free(str);
635 // -- Menu ------------------------------------------------------------------
639  * A menu descriptor represents the "address" of a menu as an array of strings.
640  * E.g. the menu "File->Close" has descriptor { "File", "Close" }.
641  */
642     NSArray *
643 descriptor_for_menu(vimmenu_T *menu)
645     if (!menu) return nil;
647     NSMutableArray *desc = [NSMutableArray array];
648     while (menu) {
649         NSString *name = [NSString stringWithVimString:menu->dname];
650         [desc insertObject:name atIndex:0];
651         menu = menu->parent;
652     }
654     return desc;
657     vimmenu_T *
658 menu_for_descriptor(NSArray *desc)
660     if (!(desc && [desc count] > 0)) return NULL;
662     vimmenu_T *menu = root_menu;
663     int i, count = [desc count];
665     for (i = 0; i < count; ++i) {
666         NSString *component = [desc objectAtIndex:i];
667         while (menu) {
668             NSString *name = [NSString stringWithVimString:menu->dname];
669             if ([component isEqual:name]) {
670                 if (i+1 == count)
671                     return menu;    // Matched all components, so return menu
672                 menu = menu->children;
673                 break;
674             }
675             menu = menu->next;
676         }
677     }
679     return NULL;
683  * Add a submenu to the menu bar, toolbar, or a popup menu.
684  */
685     void
686 gui_mch_add_menu(vimmenu_T *menu, int idx)
688     NSArray *desc = descriptor_for_menu(menu);
689     [[MMBackend sharedInstance] queueMessage:AddMenuMsgID properties:
690         [NSDictionary dictionaryWithObjectsAndKeys:
691             desc, @"descriptor",
692             [NSNumber numberWithInt:idx], @"index",
693             nil]];
698  * Add a menu item to a menu
699  */
700     void
701 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
703     char_u *tip = menu->strings[MENU_INDEX_TIP]
704             ? menu->strings[MENU_INDEX_TIP] : menu->actext;
705     NSArray *desc = descriptor_for_menu(menu);
706     NSString *keyEquivalent = menu->mac_key
707         ? [NSString stringWithFormat:@"%C", specialKeyToNSKey(menu->mac_key)]
708         : [NSString string];
709     int modifierMask = vimModMaskToEventModifierFlags(menu->mac_mods);
710     char_u *icon = NULL;
712     if (menu_is_toolbar(menu->parent->name)) {
713         char_u fname[MAXPATHL];
715         // TODO: Ensure menu->iconfile exists (if != NULL)
716         icon = menu->iconfile;
717         if (!icon && gui_find_bitmap(menu->name, fname, "bmp") == OK)
718             icon = fname;
719         if (!icon && menu->iconidx >= 0)
720             icon = menu->dname;
721     }
723     [[MMBackend sharedInstance] queueMessage:AddMenuItemMsgID properties:
724         [NSDictionary dictionaryWithObjectsAndKeys:
725             desc, @"descriptor",
726             [NSNumber numberWithInt:idx], @"index",
727             [NSString stringWithVimString:tip], @"tip",
728             [NSString stringWithVimString:icon], @"icon",
729             keyEquivalent, @"keyEquivalent",
730             [NSNumber numberWithInt:modifierMask], @"modifierMask",
731             [NSString stringWithVimString:menu->mac_action], @"action",
732             [NSNumber numberWithBool:menu->mac_alternate], @"isAlternate",
733             nil]];
738  * Destroy the machine specific menu widget.
739  */
740     void
741 gui_mch_destroy_menu(vimmenu_T *menu)
743     NSArray *desc = descriptor_for_menu(menu);
744     [[MMBackend sharedInstance] queueMessage:RemoveMenuItemMsgID properties:
745         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
750  * Make a menu either grey or not grey.
751  */
752     void
753 gui_mch_menu_grey(vimmenu_T *menu, int grey)
755     /* Only update menu if the 'grey' state has changed to avoid having to pass
756      * lots of unnecessary data to MacVim.  (Skipping this test makes MacVim
757      * pause noticably on mode changes. */
758     NSArray *desc = descriptor_for_menu(menu);
759     if (menu->was_grey == grey)
760         return;
762     menu->was_grey = grey;
764     [[MMBackend sharedInstance] queueMessage:EnableMenuItemMsgID properties:
765         [NSDictionary dictionaryWithObjectsAndKeys:
766             desc, @"descriptor",
767             [NSNumber numberWithInt:!grey], @"enable",
768             nil]];
773  * Make menu item hidden or not hidden
774  */
775     void
776 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
778     // HACK! There is no (obvious) way to hide a menu item, so simply
779     // enable/disable it instead.
780     gui_mch_menu_grey(menu, hidden);
785  * This is called when user right clicks.
786  */
787     void
788 gui_mch_show_popupmenu(vimmenu_T *menu)
790     NSArray *desc = descriptor_for_menu(menu);
791     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:
792         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
797  * This is called when a :popup command is executed.
798  */
799     void
800 gui_make_popup(char_u *path_name, int mouse_pos)
802     vimmenu_T *menu = gui_find_menu(path_name);
803     if (!(menu && menu->children)) return;
805     NSArray *desc = descriptor_for_menu(menu);
806     NSDictionary *p = (mouse_pos || NULL == curwin)
807         ? [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]
808         : [NSDictionary dictionaryWithObjectsAndKeys:
809             desc, @"descriptor",
810             [NSNumber numberWithInt:curwin->w_wrow], @"row",
811             [NSNumber numberWithInt:curwin->w_wcol], @"column",
812             nil];
814     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:p];
819  * This is called after setting all the menus to grey/hidden or not.
820  */
821     void
822 gui_mch_draw_menubar(void)
824     // The (main) menu draws itself in Mac OS X.
828     void
829 gui_mch_enable_menu(int flag)
831     // The (main) menu is always enabled in Mac OS X.
835 #if 0
836     void
837 gui_mch_set_menu_pos(int x, int y, int w, int h)
839     // The (main) menu cannot be moved in Mac OS X.
841 #endif
844     void
845 gui_mch_show_toolbar(int showit)
847     int flags = 0;
848     if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
849     if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
850     if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
852     [[MMBackend sharedInstance] showToolbar:showit flags:flags];
858 // -- Fonts -----------------------------------------------------------------
862  * If a font is not going to be used, free its structure.
863  */
864     void
865 gui_mch_free_font(font)
866     GuiFont     font;
868     if (font != NOFONT) {
869         //NSLog(@"gui_mch_free_font(font=0x%x)", font);
870         [(NSFont*)font release];
871     }
876  * Get a font structure for highlighting.
877  */
878     GuiFont
879 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
881     //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
882     //        giveErrorIfMissing);
884     NSFont *font = gui_macvim_font_with_name(name);
885     if (font)
886         return (GuiFont)[font retain];
888     if (giveErrorIfMissing)
889         EMSG2(_(e_font), name);
891     return NOFONT;
895 #if defined(FEAT_EVAL) || defined(PROTO)
897  * Return the name of font "font" in allocated memory.
898  * Don't know how to get the actual name, thus use the provided name.
899  */
900     char_u *
901 gui_mch_get_fontname(GuiFont font, char_u *name)
903     if (name == NULL)
904         return NULL;
905     return vim_strsave(name);
907 #endif
911  * Initialise vim to use the font with the given name.  Return FAIL if the font
912  * could not be loaded, OK otherwise.
913  */
914     int
915 gui_mch_init_font(char_u *font_name, int fontset)
917     //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
919     if (font_name && STRCMP(font_name, "*") == 0) {
920         // :set gfn=* shows the font panel.
921         do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
922         return FAIL;
923     }
925     NSFont *font = gui_macvim_font_with_name(font_name);
926     if (font) {
927         [(NSFont*)gui.norm_font release];
928         gui.norm_font = (GuiFont)[font retain];
930         // NOTE: MacVim keeps separate track of the normal and wide fonts.
931         // Unless the user changes 'guifontwide' manually, they are based on
932         // the same (normal) font.  Also note that each time the normal font is
933         // set, the advancement may change so the wide font needs to be updated
934         // as well (so that it is always twice the width of the normal font).
935         [[MMBackend sharedInstance] setFont:font];
936         [[MMBackend sharedInstance] setWideFont:
937                (NOFONT == gui.wide_font ? font : (NSFont*)gui.wide_font)];
939         return OK;
940     }
942     return FAIL;
947  * Set the current text font.
948  */
949     void
950 gui_mch_set_font(GuiFont font)
952     // Font selection is done inside MacVim...nothing here to do.
956     NSFont *
957 gui_macvim_font_with_name(char_u *name)
959     NSFont *font = nil;
960     NSString *fontName = MMDefaultFontName;
961     float size = MMDefaultFontSize;
962     BOOL parseFailed = NO;
964 #ifdef FEAT_MBYTE
965     name = CONVERT_TO_UTF8(name);
966 #endif
968     if (name) {
969         fontName = [NSString stringWithUTF8String:(char*)name];
971         NSArray *components = [fontName componentsSeparatedByString:@":"];
972         if ([components count] == 2) {
973             NSString *sizeString = [components lastObject];
974             if ([sizeString length] > 0
975                     && [sizeString characterAtIndex:0] == 'h') {
976                 sizeString = [sizeString substringFromIndex:1];
977                 if ([sizeString length] > 0) {
978                     size = [sizeString floatValue];
979                     fontName = [components objectAtIndex:0];
980                 }
981             } else {
982                 parseFailed = YES;
983             }
984         } else if ([components count] > 2) {
985             parseFailed = YES;
986         }
988         if (!parseFailed) {
989             // Replace underscores with spaces.
990             fontName = [[fontName componentsSeparatedByString:@"_"]
991                                      componentsJoinedByString:@" "];
992         }
993     }
995     if (!parseFailed && [fontName length] > 0) {
996         if (size < MMMinFontSize) size = MMMinFontSize;
997         if (size > MMMaxFontSize) size = MMMaxFontSize;
999         font = [NSFont fontWithName:fontName size:size];
1001         if (!font && MMDefaultFontName == fontName) {
1002             // If for some reason the MacVim default font is not in the app
1003             // bundle, then fall back on the system default font.
1004             font = [NSFont userFixedPitchFontOfSize:0];
1005         }
1006     }
1008 #ifdef FEAT_MBYTE
1009     CONVERT_TO_UTF8_FREE(name);
1010 #endif
1012     return font;
1015 // -- Scrollbars ------------------------------------------------------------
1018     void
1019 gui_mch_create_scrollbar(
1020         scrollbar_T *sb,
1021         int orient)     /* SBAR_VERT or SBAR_HORIZ */
1023     [[MMBackend sharedInstance] 
1024             createScrollbarWithIdentifier:sb->ident type:sb->type];
1028     void
1029 gui_mch_destroy_scrollbar(scrollbar_T *sb)
1031     [[MMBackend sharedInstance] 
1032             destroyScrollbarWithIdentifier:sb->ident];
1036     void
1037 gui_mch_enable_scrollbar(
1038         scrollbar_T     *sb,
1039         int             flag)
1041     [[MMBackend sharedInstance] 
1042             showScrollbarWithIdentifier:sb->ident state:flag];
1046     void
1047 gui_mch_set_scrollbar_pos(
1048         scrollbar_T *sb,
1049         int x,
1050         int y,
1051         int w,
1052         int h)
1054     int pos = y;
1055     int len = h;
1056     if (SBAR_BOTTOM == sb->type) {
1057         pos = x;
1058         len = w; 
1059     }
1061     [[MMBackend sharedInstance] 
1062             setScrollbarPosition:pos length:len identifier:sb->ident];
1066     void
1067 gui_mch_set_scrollbar_thumb(
1068         scrollbar_T *sb,
1069         long val,
1070         long size,
1071         long max)
1073     [[MMBackend sharedInstance] 
1074             setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
1078 // -- Cursor ----------------------------------------------------------------
1082  * Draw a cursor without focus.
1083  */
1084     void
1085 gui_mch_draw_hollow_cursor(guicolor_T color)
1087     return [[MMBackend sharedInstance]
1088         drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
1089                fraction:100 color:color];
1094  * Draw part of a cursor, only w pixels wide, and h pixels high.
1095  */
1096     void
1097 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
1099     // HACK!  'w' and 'h' are always 1 since we do not tell Vim about the exact
1100     // font dimensions.  Thus these parameters are useless.  Instead we look at
1101     // the shape_table to determine the shape and size of the cursor (just like
1102     // gui_update_cursor() does).
1104 #ifdef FEAT_RIGHTLEFT
1105     // If 'rl' is set the insert mode cursor must be drawn on the right-hand
1106     // side of a text cell.
1107     int rl = curwin ? curwin->w_p_rl : FALSE;
1108 #else
1109     int rl = FALSE;
1110 #endif
1111     int idx = get_shape_idx(FALSE);
1112     int shape = MMInsertionPointBlock;
1113     switch (shape_table[idx].shape) {
1114         case SHAPE_HOR:
1115             shape = MMInsertionPointHorizontal;
1116             break;
1117         case SHAPE_VER:
1118             shape = rl ? MMInsertionPointVerticalRight
1119                        : MMInsertionPointVertical;
1120             break;
1121     }
1123     return [[MMBackend sharedInstance]
1124         drawCursorAtRow:gui.row column:gui.col shape:shape
1125                fraction:shape_table[idx].percentage color:color];
1130  * Cursor blink functions.
1132  * This is a simple state machine:
1133  * BLINK_NONE   not blinking at all
1134  * BLINK_OFF    blinking, cursor is not shown
1135  * BLINK_ON blinking, cursor is shown
1136  */
1137     void
1138 gui_mch_set_blinking(long wait, long on, long off)
1140     [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1145  * Start the cursor blinking.  If it was already blinking, this restarts the
1146  * waiting time and shows the cursor.
1147  */
1148     void
1149 gui_mch_start_blink(void)
1151     [[MMBackend sharedInstance] startBlink];
1156  * Stop the cursor blinking.  Show the cursor if it wasn't shown.
1157  */
1158     void
1159 gui_mch_stop_blink(void)
1161     [[MMBackend sharedInstance] stopBlink];
1165 // -- Mouse -----------------------------------------------------------------
1169  * Get current mouse coordinates in text window.
1170  */
1171     void
1172 gui_mch_getmouse(int *x, int *y)
1174     //NSLog(@"gui_mch_getmouse()");
1178     void
1179 gui_mch_setmouse(int x, int y)
1181     //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1185     void
1186 mch_set_mouse_shape(int shape)
1188     [[MMBackend sharedInstance] setMouseShape:shape];
1194 // -- Input Method ----------------------------------------------------------
1196 #if defined(USE_IM_CONTROL)
1198     void
1199 im_set_position(int row, int col)
1201     // The pre-edit area is a popup window which is displayed by MMTextView.
1202     [[MMBackend sharedInstance] setPreEditRow:row column:col];
1206     void
1207 im_set_active(int active)
1209     // Set roman or the system script if 'active' is TRUE or FALSE,
1210     // respectively.
1211     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1213     if (!p_imdisable && smRoman != systemScript)
1214         KeyScript(active ? smKeySysScript : smKeyRoman);
1218     int
1219 im_get_status(void)
1221     // IM is active whenever the current script is the system script and the
1222     // system script isn't roman.  (Hence IM can only be active when using
1223     // non-roman scripts.)
1224     SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
1225     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1227     return currentScript != smRoman && currentScript == systemScript;
1230 #endif // defined(USE_IM_CONTROL)
1235 // -- Unsorted --------------------------------------------------------------
1238     void
1239 ex_macaction(eap)
1240     exarg_T     *eap;
1242     if (!gui.in_use) {
1243         EMSG(_("E???: Command only available in GUI mode"));
1244         return;
1245     }
1247     char_u *arg = eap->arg;
1248 #ifdef FEAT_MBYTE
1249     arg = CONVERT_TO_UTF8(arg);
1250 #endif
1252     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1253     NSString *name = [NSString stringWithUTF8String:(char*)arg];
1254     if (actionDict && [actionDict objectForKey:name] != nil) {
1255         [[MMBackend sharedInstance] executeActionWithName:name];
1256     } else {
1257         EMSG2(_("E???: Invalid action: %s"), eap->arg);
1258     }
1260 #ifdef FEAT_MBYTE
1261     arg = CONVERT_TO_UTF8(arg);
1262 #endif
1267  * Adjust gui.char_height (after 'linespace' was changed).
1268  */
1269     int
1270 gui_mch_adjust_charheight(void)
1272     [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1273     return OK;
1277     void
1278 gui_mch_beep(void)
1280     NSBeep();
1285 #ifdef FEAT_BROWSE
1287  * Pop open a file browser and return the file selected, in allocated memory,
1288  * or NULL if Cancel is hit.
1289  *  saving  - TRUE if the file will be saved to, FALSE if it will be opened.
1290  *  title   - Title message for the file browser dialog.
1291  *  dflt    - Default name of file.
1292  *  ext     - Default extension to be added to files without extensions.
1293  *  initdir - directory in which to open the browser (NULL = current dir)
1294  *  filter  - Filter for matched files to choose from.
1295  *  Has a format like this:
1296  *  "C Files (*.c)\0*.c\0"
1297  *  "All Files\0*.*\0\0"
1298  *  If these two strings were concatenated, then a choice of two file
1299  *  filters will be selectable to the user.  Then only matching files will
1300  *  be shown in the browser.  If NULL, the default allows all files.
1302  *  *NOTE* - the filter string must be terminated with TWO nulls.
1303  */
1304     char_u *
1305 gui_mch_browse(
1306     int saving,
1307     char_u *title,
1308     char_u *dflt,
1309     char_u *ext,
1310     char_u *initdir,
1311     char_u *filter)
1313     //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1314     //        " filter=%s", saving, title, dflt, ext, initdir, filter);
1316     // Ensure no data is on the output queue before presenting the dialog.
1317     gui_macvim_force_flush();
1319     NSMutableDictionary *attr = [NSMutableDictionary
1320         dictionaryWithObject:[NSNumber numberWithBool:saving]
1321                       forKey:@"saving"];
1322     if (initdir)
1323         [attr setObject:[NSString stringWithVimString:initdir] forKey:@"dir"];
1325     char_u *s = (char_u*)[[MMBackend sharedInstance]
1326                             browseForFileWithAttributes:attr];
1328     return s;
1330 #endif /* FEAT_BROWSE */
1334     int
1335 gui_mch_dialog(
1336     int         type,
1337     char_u      *title,
1338     char_u      *message,
1339     char_u      *buttons,
1340     int         dfltbutton,
1341     char_u      *textfield)
1343     //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1344     //        "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1345     //        dfltbutton, textfield);
1347     // Ensure no data is on the output queue before presenting the dialog.
1348     gui_macvim_force_flush();
1350     int style = NSInformationalAlertStyle;
1351     if (VIM_WARNING == type) style = NSWarningAlertStyle;
1352     else if (VIM_ERROR == type) style = NSCriticalAlertStyle;
1354     NSMutableDictionary *attr = [NSMutableDictionary
1355                         dictionaryWithObject:[NSNumber numberWithInt:style]
1356                                       forKey:@"alertStyle"];
1358     if (buttons) {
1359         // 'buttons' is a string of '\n'-separated button titles 
1360         NSString *string = [NSString stringWithVimString:buttons];
1361         NSArray *array = [string componentsSeparatedByString:@"\n"];
1362         [attr setObject:array forKey:@"buttonTitles"];
1363     }
1365     NSString *messageText = nil;
1366     if (title)
1367         messageText = [NSString stringWithVimString:title];
1369     if (message) {
1370         NSString *informativeText = [NSString stringWithVimString:message];
1371         if (!messageText) {
1372             // HACK! If there is a '\n\n' or '\n' sequence in the message, then
1373             // make the part up to there into the title.  We only do this
1374             // because Vim has lots of dialogs without a title and they look
1375             // ugly that way.
1376             // TODO: Fix the actual dialog texts.
1377             NSRange eolRange = [informativeText rangeOfString:@"\n\n"];
1378             if (NSNotFound == eolRange.location)
1379                 eolRange = [informativeText rangeOfString:@"\n"];
1380             if (NSNotFound != eolRange.location) {
1381                 messageText = [informativeText substringToIndex:
1382                                                         eolRange.location];
1383                 informativeText = [informativeText substringFromIndex:
1384                                                         NSMaxRange(eolRange)];
1385             }
1386         }
1388         [attr setObject:informativeText forKey:@"informativeText"];
1389     }
1391     if (messageText)
1392         [attr setObject:messageText forKey:@"messageText"];
1394     if (textfield) {
1395         NSString *string = [NSString stringWithVimString:textfield];
1396         [attr setObject:string forKey:@"textFieldString"];
1397     }
1399     return [[MMBackend sharedInstance] showDialogWithAttributes:attr
1400                                                     textField:(char*)textfield];
1404     void
1405 gui_mch_flash(int msec)
1411  * Return the Pixel value (color) for the given color name.  This routine was
1412  * pretty much taken from example code in the Silicon Graphics OSF/Motif
1413  * Programmer's Guide.
1414  * Return INVALCOLOR when failed.
1415  */
1416     guicolor_T
1417 gui_mch_get_color(char_u *name)
1419 #ifdef FEAT_MBYTE
1420     name = CONVERT_TO_UTF8(name);
1421 #endif
1423     NSString *key = [NSString stringWithUTF8String:(char*)name];
1424     guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1426 #ifdef FEAT_MBYTE
1427     CONVERT_TO_UTF8_FREE(name);
1428 #endif
1430     return col;
1435  * Return the RGB value of a pixel as long.
1436  */
1437     long_u
1438 gui_mch_get_rgb(guicolor_T pixel)
1440     // This is only implemented so that vim can guess the correct value for
1441     // 'background' (which otherwise defaults to 'dark'); it is not used for
1442     // anything else (as far as I know).
1443     // The implementation is simple since colors are stored in an int as
1444     // "rrggbb".
1445     return pixel;
1450  * Get the screen dimensions.
1451  * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1452  * Is there no way to find out how wide the borders really are?
1453  * TODO: Add live udate of those value on suspend/resume.
1454  */
1455     void
1456 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1458     //NSLog(@"gui_mch_get_screen_dimensions()");
1459     *screen_w = Columns;
1460     *screen_h = Rows;
1465  * Get the position of the top left corner of the window.
1466  */
1467     int
1468 gui_mch_get_winpos(int *x, int *y)
1470     *x = *y = 0;
1471     return OK;
1476  * Return OK if the key with the termcap name "name" is supported.
1477  */
1478     int
1479 gui_mch_haskey(char_u *name)
1481     BOOL ok = NO;
1483 #ifdef FEAT_MBYTE
1484     name = CONVERT_TO_UTF8(name);
1485 #endif
1487     NSString *value = [NSString stringWithUTF8String:(char*)name];
1488     if (value)
1489         ok =  [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1491 #ifdef FEAT_MBYTE
1492     CONVERT_TO_UTF8_FREE(name);
1493 #endif
1495     return ok;
1500  * Iconify the GUI window.
1501  */
1502     void
1503 gui_mch_iconify(void)
1508 #if defined(FEAT_EVAL) || defined(PROTO)
1510  * Bring the Vim window to the foreground.
1511  */
1512     void
1513 gui_mch_set_foreground(void)
1515     [[MMBackend sharedInstance] activate];
1517 #endif
1521     void
1522 gui_mch_set_shellsize(
1523     int         width,
1524     int         height,
1525     int         min_width,
1526     int         min_height,
1527     int         base_width,
1528     int         base_height,
1529     int         direction)
1531     //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1532     //        " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1533     //        width, height, min_width, min_height, base_width, base_height,
1534     //        direction);
1535     [[MMBackend sharedInstance] setRows:height columns:width];
1539     void
1540 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1545  * Set the position of the top left corner of the window to the given
1546  * coordinates.
1547  */
1548     void
1549 gui_mch_set_winpos(int x, int y)
1554 #ifdef FEAT_TITLE
1556  * Set the window title and icon.
1557  * (The icon is not taken care of).
1558  */
1559     void
1560 gui_mch_settitle(char_u *title, char_u *icon)
1562     //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1564 #ifdef FEAT_MBYTE
1565     title = CONVERT_TO_UTF8(title);
1566 #endif
1568     MMBackend *backend = [MMBackend sharedInstance];
1569     [backend setWindowTitle:(char*)title];
1571     // TODO: Convert filename to UTF-8?
1572     if (curbuf)
1573         [backend setDocumentFilename:(char*)curbuf->b_ffname];
1575 #ifdef FEAT_MBYTE
1576     CONVERT_TO_UTF8_FREE(title);
1577 #endif
1579 #endif
1582     void
1583 gui_mch_toggle_tearoffs(int enable)
1589     void
1590 gui_mch_enter_fullscreen(int fuoptions_flags, guicolor_T bg)
1592     [[MMBackend sharedInstance] enterFullscreen:fuoptions_flags background:bg];
1596     void
1597 gui_mch_leave_fullscreen()
1599     [[MMBackend sharedInstance] leaveFullscreen];
1603     void
1604 gui_macvim_update_modified_flag()
1606     [[MMBackend sharedInstance] updateModifiedFlag];
1610  * Add search pattern 'pat' to the OS X find pasteboard.  This allows other
1611  * apps access the last pattern searched for (hitting <D-g> in another app will
1612  * initiate a search for the same pattern).
1613  */
1614     void
1615 gui_macvim_add_to_find_pboard(char_u *pat)
1617     if (!pat) return;
1619 #ifdef FEAT_MBYTE
1620     pat = CONVERT_TO_UTF8(pat);
1621 #endif
1622     NSString *s = [NSString stringWithUTF8String:(char*)pat];
1623 #ifdef FEAT_MBYTE
1624     CONVERT_TO_UTF8_FREE(pat);
1625 #endif
1627     if (!s) return;
1629     NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
1630     [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1631     [pb setString:s forType:NSStringPboardType];
1634     void
1635 gui_macvim_set_antialias(int antialias)
1637     [[MMBackend sharedInstance] setAntialias:antialias];
1641     void
1642 gui_macvim_wait_for_startup()
1644     MMBackend *backend = [MMBackend sharedInstance];
1645     if ([backend waitForAck])
1646         [backend waitForConnectionAcknowledgement];
1649 void gui_macvim_get_window_layout(int *count, int *layout)
1651     if (!(count && layout)) return;
1653     // NOTE: Only set 'layout' if the backend has requested a != 0 layout, else
1654     // any command line arguments (-p/-o) would be ignored.
1655     int window_layout = [[MMBackend sharedInstance] initialWindowLayout];
1656     if (window_layout > 0 && window_layout < 4) {
1657         // The window_layout numbers must match the WIN_* defines in main.c.
1658         *count = 0;
1659         *layout = window_layout;
1660     }
1664 // -- Client/Server ---------------------------------------------------------
1666 #ifdef MAC_CLIENTSERVER
1669 // NOTE: Client/Server is only fully supported with a GUI.  Theoretically it
1670 // would be possible to make the server code work with terminal Vim, but it
1671 // would require that a run-loop is set up and checked.  This should not be
1672 // difficult to implement, simply call gui_mch_update() at opportune moments
1673 // and it will take care of the run-loop.  Another (bigger) problem with
1674 // supporting servers in terminal mode is that the server listing code talks to
1675 // MacVim (the GUI) to figure out which servers are running.
1680  * Register connection with 'name'.  The actual connection is named something
1681  * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1682  */
1683     void
1684 serverRegisterName(char_u *name)
1686 #ifdef FEAT_MBYTE
1687     name = CONVERT_TO_UTF8(name);
1688 #endif
1690     NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1691     [[MMBackend sharedInstance] registerServerWithName:svrName];
1693 #ifdef FEAT_MBYTE
1694     CONVERT_TO_UTF8_FREE(name);
1695 #endif
1700  * Send to an instance of Vim.
1701  * Returns 0 for OK, negative for an error.
1702  */
1703     int
1704 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1705         int *port, int asExpr, int silent)
1707 #ifdef FEAT_MBYTE
1708     name = CONVERT_TO_UTF8(name);
1709     cmd = CONVERT_TO_UTF8(cmd);
1710 #endif
1712     BOOL ok = [[MMBackend sharedInstance]
1713             sendToServer:[NSString stringWithUTF8String:(char*)name]
1714                   string:[NSString stringWithUTF8String:(char*)cmd]
1715                    reply:result
1716                     port:port
1717               expression:asExpr
1718                   silent:silent];
1720 #ifdef FEAT_MBYTE
1721     CONVERT_TO_UTF8_FREE(name);
1722     CONVERT_TO_UTF8_FREE(cmd);
1723 #endif
1725     return ok ? 0 : -1;
1730  * Ask MacVim for the names of all Vim servers.
1731  */
1732     char_u *
1733 serverGetVimNames(void)
1735     char_u *names = NULL;
1736     NSArray *list = [[MMBackend sharedInstance] serverList];
1738     if (list) {
1739         NSString *string = [list componentsJoinedByString:@"\n"];
1740         char_u *s = (char_u*)[string UTF8String];
1741 #ifdef FEAT_MBYTE
1742         s = CONVERT_FROM_UTF8(s);
1743 #endif
1744         names = vim_strsave(s);
1745 #ifdef FEAT_MBYTE
1746         CONVERT_FROM_UTF8_FREE(s);
1747 #endif
1748     }
1750     return names;
1755  * 'str' is a hex int representing the send port of the connection.
1756  */
1757     int
1758 serverStrToPort(char_u *str)
1760     int port = 0;
1762     sscanf((char *)str, "0x%x", &port);
1763     if (!port)
1764         EMSG2(_("E573: Invalid server id used: %s"), str);
1766     return port;
1771  * Check for replies from server with send port 'port'.
1772  * Return TRUE and a non-malloc'ed string if there is.  Else return FALSE.
1773  */
1774     int
1775 serverPeekReply(int port, char_u **str)
1777     NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1778     int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1780     if (str && len > 0) {
1781         *str = (char_u*)[reply UTF8String];
1783 #ifdef FEAT_MBYTE
1784         if (input_conv.vc_type != CONV_NONE) {
1785             char_u *s = string_convert(&input_conv, *str, &len);
1787             if (len > 0) {
1788                 // HACK! Since 's' needs to be freed we cannot simply set
1789                 // '*str = s' or memory will leak.  Instead, create a dummy
1790                 // NSData and return its 'bytes' pointer, then autorelease the
1791                 // NSData.
1792                 NSData *data = [NSData dataWithBytes:s length:len+1];
1793                 *str = (char_u*)[data bytes];
1794             }
1796             vim_free(s);
1797         }
1798 #endif
1799     }
1801     return reply != nil;
1806  * Wait for replies from server with send port 'port'.
1807  * Return 0 and the malloc'ed string when a reply is available.
1808  * Return -1 on error.
1809  */
1810     int
1811 serverReadReply(int port, char_u **str)
1813     NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1814     if (reply && str) {
1815         char_u *s = (char_u*)[reply UTF8String];
1816 #ifdef FEAT_MBYTE
1817         s = CONVERT_FROM_UTF8(s);
1818 #endif
1819         *str = vim_strsave(s);
1820 #ifdef FEAT_MBYTE
1821         CONVERT_FROM_UTF8_FREE(s);
1822 #endif
1823         return 0;
1824     }
1826     return -1;
1831  * Send a reply string (notification) to client with port given by "serverid".
1832  * Return -1 if the window is invalid.
1833  */
1834     int
1835 serverSendReply(char_u *serverid, char_u *reply)
1837     int retval = -1;
1838     int port = serverStrToPort(serverid);
1839     if (port > 0 && reply) {
1840 #ifdef FEAT_MBYTE
1841         reply = CONVERT_TO_UTF8(reply);
1842 #endif
1843         BOOL ok = [[MMBackend sharedInstance]
1844                 sendReply:[NSString stringWithUTF8String:(char*)reply]
1845                    toPort:port];
1846         retval = ok ? 0 : -1;
1847 #ifdef FEAT_MBYTE
1848         CONVERT_TO_UTF8_FREE(reply);
1849 #endif
1850     }
1852     return retval;
1855 #endif // MAC_CLIENTSERVER
1860 // -- ODB Editor Support ----------------------------------------------------
1862 #ifdef FEAT_ODB_EDITOR
1864  * The ODB Editor protocol works like this:
1865  * - An external program (the server) asks MacVim to open a file and associates
1866  *   three things with this file: (1) a server id (a four character code that
1867  *   identifies the server), (2) a path that can be used as window title for
1868  *   the file (optional), (3) an arbitrary token (optional)
1869  * - When a file is saved or closed, MacVim should tell the server about which
1870  *   file was modified and also pass back the token
1872  * All communication between MacVim and the server goes via Apple Events.
1873  */
1875     static OSErr
1876 odb_event(buf_T *buf, const AEEventID action)
1878     if (!(buf->b_odb_server_id && buf->b_ffname))
1879         return noErr;
1881     NSAppleEventDescriptor *targetDesc = [NSAppleEventDescriptor
1882             descriptorWithDescriptorType:typeApplSignature
1883                                    bytes:&buf->b_odb_server_id
1884                                   length:sizeof(OSType)];
1886     // TODO: Convert b_ffname to UTF-8?
1887     NSString *path = [NSString stringWithUTF8String:(char*)buf->b_ffname];
1888     NSData *pathData = [[[NSURL fileURLWithPath:path] absoluteString]
1889             dataUsingEncoding:NSUTF8StringEncoding];
1890     NSAppleEventDescriptor *pathDesc = [NSAppleEventDescriptor
1891             descriptorWithDescriptorType:typeFileURL data:pathData];
1893     NSAppleEventDescriptor *event = [NSAppleEventDescriptor
1894             appleEventWithEventClass:kODBEditorSuite
1895                              eventID:action
1896                     targetDescriptor:targetDesc
1897                             returnID:kAutoGenerateReturnID
1898                        transactionID:kAnyTransactionID];
1900     [event setParamDescriptor:pathDesc forKeyword:keyDirectObject];
1902     if (buf->b_odb_token)
1903         [event setParamDescriptor:buf->b_odb_token forKeyword:keySenderToken];
1905     return AESendMessage([event aeDesc], NULL, kAENoReply | kAENeverInteract,
1906             kAEDefaultTimeout);
1909     OSErr
1910 odb_buffer_close(buf_T *buf)
1912     OSErr err = noErr;
1913     if (buf) {
1914         err = odb_event(buf, kAEClosedFile);
1916         buf->b_odb_server_id = 0;
1918         if (buf->b_odb_token) {
1919             [(NSAppleEventDescriptor *)(buf->b_odb_token) release];
1920             buf->b_odb_token = NULL;
1921         }
1923         if (buf->b_odb_fname) {
1924             vim_free(buf->b_odb_fname);
1925             buf->b_odb_fname = NULL;
1926         }
1927     }
1929     return err;
1932     OSErr
1933 odb_post_buffer_write(buf_T *buf)
1935     return buf ? odb_event(buf, kAEModifiedFile) : noErr;
1938     void
1939 odb_end(void)
1941     buf_T *buf;
1942     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1943         odb_buffer_close(buf);
1946 #endif // FEAT_ODB_EDITOR
1949     char_u *
1950 get_macaction_name(expand_T *xp, int idx)
1952     static char_u *str = NULL;
1953     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1955     if (nil == actionDict || idx < 0 || idx >= [actionDict count])
1956         return NULL;
1958     NSString *string = [[actionDict allKeys] objectAtIndex:idx];
1959     if (!string)
1960         return NULL;
1962     char_u *plainStr = (char_u*)[string UTF8String];
1964 #ifdef FEAT_MBYTE
1965     if (str) {
1966         vim_free(str);
1967         str = NULL;
1968     }
1969     if (input_conv.vc_type != CONV_NONE) {
1970         int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1971         str = string_convert(&input_conv, plainStr, &len);
1972         plainStr = str;
1973     }
1974 #endif
1976     return plainStr;
1980     int
1981 is_valid_macaction(char_u *action)
1983     int isValid = NO;
1984     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1985     if (actionDict) {
1986 #ifdef FEAT_MBYTE
1987         action = CONVERT_TO_UTF8(action);
1988 #endif
1989         NSString *string = [NSString stringWithUTF8String:(char*)action];
1990         isValid = (nil != [actionDict objectForKey:string]);
1991 #ifdef FEAT_MBYTE
1992         CONVERT_TO_UTF8_FREE(action);
1993 #endif
1994     }
1996     return isValid;
1999 static int specialKeyToNSKey(int key)
2001     if (!IS_SPECIAL(key))
2002         return key;
2004     static struct {
2005         int special;
2006         int nskey;
2007     } sp2ns[] = {
2008         { K_UP, NSUpArrowFunctionKey },
2009         { K_DOWN, NSDownArrowFunctionKey },
2010         { K_LEFT, NSLeftArrowFunctionKey },
2011         { K_RIGHT, NSRightArrowFunctionKey },
2012         { K_F1, NSF1FunctionKey },
2013         { K_F2, NSF2FunctionKey },
2014         { K_F3, NSF3FunctionKey },
2015         { K_F4, NSF4FunctionKey },
2016         { K_F5, NSF5FunctionKey },
2017         { K_F6, NSF6FunctionKey },
2018         { K_F7, NSF7FunctionKey },
2019         { K_F8, NSF8FunctionKey },
2020         { K_F9, NSF9FunctionKey },
2021         { K_F10, NSF10FunctionKey },
2022         { K_F11, NSF11FunctionKey },
2023         { K_F12, NSF12FunctionKey },
2024         { K_F13, NSF13FunctionKey },
2025         { K_F14, NSF14FunctionKey },
2026         { K_F15, NSF15FunctionKey },
2027         { K_F16, NSF16FunctionKey },
2028         { K_F17, NSF17FunctionKey },
2029         { K_F18, NSF18FunctionKey },
2030         { K_F19, NSF19FunctionKey },
2031         { K_F20, NSF20FunctionKey },
2032         { K_F21, NSF21FunctionKey },
2033         { K_F22, NSF22FunctionKey },
2034         { K_F23, NSF23FunctionKey },
2035         { K_F24, NSF24FunctionKey },
2036         { K_F25, NSF25FunctionKey },
2037         { K_F26, NSF26FunctionKey },
2038         { K_F27, NSF27FunctionKey },
2039         { K_F28, NSF28FunctionKey },
2040         { K_F29, NSF29FunctionKey },
2041         { K_F30, NSF30FunctionKey },
2042         { K_F31, NSF31FunctionKey },
2043         { K_F32, NSF32FunctionKey },
2044         { K_F33, NSF33FunctionKey },
2045         { K_F34, NSF34FunctionKey },
2046         { K_F35, NSF35FunctionKey },
2047         { K_DEL, NSBackspaceCharacter },
2048         { K_BS, NSDeleteCharacter },
2049         { K_HOME, NSHomeFunctionKey },
2050         { K_END, NSEndFunctionKey },
2051         { K_PAGEUP, NSPageUpFunctionKey },
2052         { K_PAGEDOWN, NSPageDownFunctionKey }
2053     };
2055     int i;
2056     for (i = 0; i < sizeof(sp2ns)/sizeof(sp2ns[0]); ++i) {
2057         if (sp2ns[i].special == key)
2058             return sp2ns[i].nskey;
2059     }
2061     return 0;
2064 static int vimModMaskToEventModifierFlags(int mods)
2066     int flags = 0;
2068     if (mods & MOD_MASK_SHIFT)
2069         flags |= NSShiftKeyMask;
2070     if (mods & MOD_MASK_CTRL)
2071         flags |= NSControlKeyMask;
2072     if (mods & MOD_MASK_ALT)
2073         flags |= NSAlternateKeyMask;
2074     if (mods & MOD_MASK_CMD)
2075         flags |= NSCommandKeyMask;
2077     return flags;