Dialogs are always displayed in the default run loop mode
[MacVim.git] / src / MacVim / gui_macvim.m
blob4476d8b577ff60166d37736c439648a073866fdf
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);
41 @interface NSString (VimStrings)
42 + (id)stringWithVimString:(char_u *)s;
43 @end
47 // -- Initialization --------------------------------------------------------
50  * Parse the GUI related command-line arguments.  Any arguments used are
51  * deleted from argv, and *argc is decremented accordingly.  This is called
52  * when vim is started, whether or not the GUI has been started.
53  */
54     void
55 gui_mch_prepare(int *argc, char **argv)
57     //NSLog(@"gui_mch_prepare(argc=%d)", *argc);
59     // Set environment variables $VIM and $VIMRUNTIME
60     // NOTE!  If vim_getenv is called with one of these as parameters before
61     // they have been set here, they will most likely end up with the wrong
62     // values!
63     //
64     // TODO:
65     // - ensure this is called first to avoid above problem
66     // - encoding
68     NSString *path = [[[NSBundle mainBundle] resourcePath]
69         stringByAppendingPathComponent:@"vim"];
70     vim_setenv((char_u*)"VIM", (char_u*)[path UTF8String]);
72     path = [path stringByAppendingPathComponent:@"runtime"];
73     vim_setenv((char_u*)"VIMRUNTIME", (char_u*)[path UTF8String]);
78  * Check if the GUI can be started.  Called before gvimrc is sourced.
79  * Return OK or FAIL.
80  */
81     int
82 gui_mch_init_check(void)
84     //NSLog(@"gui_mch_init_check()");
85     return OK;
90  * Initialise the GUI.  Create all the windows, set up all the call-backs etc.
91  * Returns OK for success, FAIL when the GUI can't be started.
92  */
93     int
94 gui_mch_init(void)
96     //NSLog(@"gui_mch_init()");
98     if (![[MMBackend sharedInstance] checkin]) {
99         // TODO: Kill the process if there is no terminal to fall back on,
100         // otherwise the process will run outputting to the console.
101         return FAIL;
102     }
104     // Force 'termencoding' to utf-8 (changes to 'tenc' are disallowed in
105     // 'option.c', so that ':set termencoding=...' is impossible).
106     set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
108     // Set values so that pixels and characters are in one-to-one
109     // correspondence (assuming all characters have the same dimensions).
110     gui.scrollbar_width = gui.scrollbar_height = 0;
112     gui.char_height = 1;
113     gui.char_width = 1;
114     gui.char_ascent = 0;
116     gui_mch_def_colors();
118     [[MMBackend sharedInstance]
119         setDefaultColorsBackground:gui.back_pixel foreground:gui.norm_pixel];
120     [[MMBackend sharedInstance] setBackgroundColor:gui.back_pixel];
121     [[MMBackend sharedInstance] setForegroundColor:gui.norm_pixel];
123     // NOTE: If this call is left out the cursor is opaque.
124     highlight_gui_started();
126     return OK;
131     void
132 gui_mch_exit(int rc)
134     //NSLog(@"gui_mch_exit(rc=%d)", rc);
136     [[MMBackend sharedInstance] exit];
141  * Open the GUI window which was created by a call to gui_mch_init().
142  */
143     int
144 gui_mch_open(void)
146     //NSLog(@"gui_mch_open()");
148     return [[MMBackend sharedInstance] openVimWindow];
152 // -- Updating --------------------------------------------------------------
156  * Catch up with any queued X events.  This may put keyboard input into the
157  * input buffer, call resize call-backs, trigger timers etc.  If there is
158  * nothing in the X event queue (& no timers pending), then we return
159  * immediately.
160  */
161 #define MM_LOG_UPDATE_STATS 0
162     void
163 gui_mch_update(void)
165     // NOTE: This function can get called A LOT (~1 call/ms) and unfortunately
166     // checking the run loop takes a long time, resulting in noticable slow
167     // downs if it is done every time this function is called.  Therefore we
168     // make sure that it is not done too often.
169     static NSDate *lastUpdateDate = nil;
170 #if MM_LOG_UPDATE_STATS
171     static int skipCount = 0;
172 #endif
174     if (lastUpdateDate && -[lastUpdateDate timeIntervalSinceNow] <
175             MMUpdateTimeoutInterval) {
176 #if MM_LOG_UPDATE_STATS
177         ++skipCount;
178 #endif
179         return;
180     }
182 #if MM_LOG_UPDATE_STATS
183     NSTimeInterval dt = -[lastUpdateDate timeIntervalSinceNow];
184     NSLog(@"Updating (last update %.2f seconds ago, skipped %d updates, "
185             "approx %.1f calls per second)",
186             dt, skipCount, dt > 0 ? skipCount/dt : 0);
187     skipCount = 0;
188 #endif
190     [[MMBackend sharedInstance] update];
192     [lastUpdateDate release];
193     lastUpdateDate = [[NSDate date] retain];
197 /* Flush any output to the screen */
198     void
199 gui_mch_flush(void)
201     [[MMBackend sharedInstance] flushQueue:NO];
205 /* Force flush output to MacVim.  Do not call this method unless absolutely
206  * necessary (use gui_mch_flush() instead). */
207     void
208 gui_macvim_force_flush(void)
210     [[MMBackend sharedInstance] flushQueue:YES];
215  * GUI input routine called by gui_wait_for_chars().  Waits for a character
216  * from the keyboard.
217  *  wtime == -1     Wait forever.
218  *  wtime == 0      This should never happen.
219  *  wtime > 0       Wait wtime milliseconds for a character.
220  * Returns OK if a character was found to be available within the given time,
221  * or FAIL otherwise.
222  */
223     int
224 gui_mch_wait_for_chars(int wtime)
226     // NOTE! In all likelihood Vim will take a nap when waitForInput: is
227     // called, so force a flush of the command queue here.
228     [[MMBackend sharedInstance] flushQueue:YES];
230     return [[MMBackend sharedInstance] waitForInput:wtime];
234 // -- Drawing ---------------------------------------------------------------
238  * Clear the whole text window.
239  */
240     void
241 gui_mch_clear_all(void)
243     [[MMBackend sharedInstance] clearAll];
248  * Clear a rectangular region of the screen from text pos (row1, col1) to
249  * (row2, col2) inclusive.
250  */
251     void
252 gui_mch_clear_block(int row1, int col1, int row2, int col2)
254     [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
255                                                     toRow:row2 column:col2];
260  * Delete the given number of lines from the given row, scrolling up any
261  * text further down within the scroll region.
262  */
263     void
264 gui_mch_delete_lines(int row, int num_lines)
266     [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
267             scrollBottom:gui.scroll_region_bot
268                     left:gui.scroll_region_left
269                    right:gui.scroll_region_right];
273     void
274 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
276 #ifdef FEAT_MBYTE
277     char_u *conv_str = NULL;
278     if (output_conv.vc_type != CONV_NONE) {
279         conv_str = string_convert(&output_conv, s, &len);
280         if (conv_str)
281             s = conv_str;
282     }
283 #endif
285     [[MMBackend sharedInstance] drawString:(char*)s length:len row:row
286                                     column:col cells:len flags:flags];
288 #ifdef FEAT_MBYTE
289     if (conv_str)
290         vim_free(conv_str);
291 #endif
295     int
296 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
298     int c, cn, cl, i;
299     int start = 0;
300     int endcol = col;
301     int startcol = col;
302     BOOL wide = NO;
303     MMBackend *backend = [MMBackend sharedInstance];
304 #ifdef FEAT_MBYTE
305     char_u *conv_str = NULL;
307     if (output_conv.vc_type != CONV_NONE) {
308         conv_str = string_convert(&output_conv, s, &len);
309         if (conv_str)
310             s = conv_str;
311     }
312 #endif
314     // Loop over each character and output text when it changes from normal to
315     // wide and vice versa.
316     for (i = 0; i < len; i += cl) {
317         c = utf_ptr2char(s + i);
318         cl = utf_ptr2len(s + i);
319         cn = utf_char2cells(c);
321         if (!utf_iscomposing(c)) {
322             if ((cn > 1 && !wide) || (cn <= 1 && wide)) {
323                 // Changed from normal to wide or vice versa.
324                 [backend drawString:(char*)(s+start) length:i-start
325                                    row:row column:startcol
326                                  cells:endcol-startcol
327                                  flags:(wide ? flags|DRAW_WIDE : flags)];
329                 start = i;
330                 startcol = endcol;
331             }
333             wide = cn > 1;
334             endcol += cn;
335         }
336     }
338     // Output remaining characters.
339     [backend drawString:(char*)(s+start) length:len-start
340                     row:row column:startcol cells:endcol-startcol
341                   flags:(wide ? flags|DRAW_WIDE : flags)];
343 #ifdef FEAT_MBYTE
344     if (conv_str)
345         vim_free(conv_str);
346 #endif
348     return endcol - col;
353  * Insert the given number of lines before the given row, scrolling down any
354  * following text within the scroll region.
355  */
356     void
357 gui_mch_insert_lines(int row, int num_lines)
359     [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
360             scrollBottom:gui.scroll_region_bot
361                     left:gui.scroll_region_left
362                    right:gui.scroll_region_right];
367  * Set the current text foreground color.
368  */
369     void
370 gui_mch_set_fg_color(guicolor_T color)
372     [[MMBackend sharedInstance] setForegroundColor:color];
377  * Set the current text background color.
378  */
379     void
380 gui_mch_set_bg_color(guicolor_T color)
382     [[MMBackend sharedInstance] setBackgroundColor:color];
387  * Set the current text special color (used for underlines).
388  */
389     void
390 gui_mch_set_sp_color(guicolor_T color)
392     [[MMBackend sharedInstance] setSpecialColor:color];
397  * Set default colors.
398  */
399     void
400 gui_mch_def_colors()
402     MMBackend *backend = [MMBackend sharedInstance];
404     // The default colors are taken from system values
405     gui.def_norm_pixel = gui.norm_pixel = 
406         [backend lookupColorWithKey:@"MacTextColor"];
407     gui.def_back_pixel = gui.back_pixel = 
408         [backend lookupColorWithKey:@"MacTextBackgroundColor"];
413  * Called when the foreground or background color has been changed.
414  */
415     void
416 gui_mch_new_colors(void)
418     gui.def_back_pixel = gui.back_pixel;
419     gui.def_norm_pixel = gui.norm_pixel;
421     //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
422     //        gui.def_norm_pixel);
424     [[MMBackend sharedInstance]
425         setDefaultColorsBackground:gui.def_back_pixel
426                         foreground:gui.def_norm_pixel];
430  * Invert a rectangle from row r, column c, for nr rows and nc columns.
431  */
432     void
433 gui_mch_invert_rectangle(int r, int c, int nr, int nc, int invert)
435     [[MMBackend sharedInstance] drawInvertedRectAtRow:r column:c numRows:nr
436             numColumns:nc invert:invert];
441 // -- Tabline ---------------------------------------------------------------
445  * Set the current tab to "nr".  First tab is 1.
446  */
447     void
448 gui_mch_set_curtab(int nr)
450     [[MMBackend sharedInstance] selectTab:nr];
455  * Return TRUE when tabline is displayed.
456  */
457     int
458 gui_mch_showing_tabline(void)
460     return [[MMBackend sharedInstance] tabBarVisible];
464  * Update the labels of the tabline.
465  */
466     void
467 gui_mch_update_tabline(void)
469     [[MMBackend sharedInstance] updateTabBar];
473  * Show or hide the tabline.
474  */
475     void
476 gui_mch_show_tabline(int showit)
478     [[MMBackend sharedInstance] showTabBar:showit];
482 // -- Clipboard -------------------------------------------------------------
485     void
486 clip_mch_lose_selection(VimClipboard *cbd)
491     int
492 clip_mch_own_selection(VimClipboard *cbd)
494     return 0;
498     void
499 clip_mch_request_selection(VimClipboard *cbd)
501     NSPasteboard *pb = [NSPasteboard generalPasteboard];
502     NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
503             NSStringPboardType, nil];
504     NSString *bestType = [pb availableTypeFromArray:supportedTypes];
505     if (!bestType) return;
507     int motion_type = MCHAR;
508     NSString *string = nil;
510     if ([bestType isEqual:VimPBoardType]) {
511         // This type should consist of an array with two objects:
512         //   1. motion type (NSNumber)
513         //   2. text (NSString)
514         // If this is not the case we fall back on using NSStringPboardType.
515         id plist = [pb propertyListForType:VimPBoardType];
516         if ([plist isKindOfClass:[NSArray class]] && [plist count] == 2) {
517             id obj = [plist objectAtIndex:1];
518             if ([obj isKindOfClass:[NSString class]]) {
519                 motion_type = [[plist objectAtIndex:0] intValue];
520                 string = obj;
521             }
522         }
523     }
525     if (!string) {
526         // Use NSStringPboardType.  The motion type is set to line-wise if the
527         // string contains at least one EOL character, otherwise it is set to
528         // character-wise (block-wise is never used).
529         NSMutableString *mstring =
530                 [[pb stringForType:NSStringPboardType] mutableCopy];
531         if (!mstring) return;
533         // Replace unrecognized end-of-line sequences with \x0a (line feed).
534         NSRange range = { 0, [mstring length] };
535         unsigned n = [mstring replaceOccurrencesOfString:@"\x0d\x0a"
536                                              withString:@"\x0a" options:0
537                                                   range:range];
538         if (0 == n) {
539             n = [mstring replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
540                                            options:0 range:range];
541         }
542         
543         // Scan for newline character to decide whether the string should be
544         // pasted line-wise or character-wise.
545         motion_type = MCHAR;
546         if (0 < n || NSNotFound != [mstring rangeOfString:@"\n"].location)
547             motion_type = MLINE;
549         string = mstring;
550     }
552     if (!(MCHAR == motion_type || MLINE == motion_type || MBLOCK == motion_type
553             || MAUTO == motion_type))
554         motion_type = MCHAR;
556     char_u *str = (char_u*)[string UTF8String];
557     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
559 #ifdef FEAT_MBYTE
560     if (input_conv.vc_type != CONV_NONE)
561         str = string_convert(&input_conv, str, &len);
562 #endif
564     if (str)
565         clip_yank_selection(motion_type, str, len, cbd);
567 #ifdef FEAT_MBYTE
568     if (input_conv.vc_type != CONV_NONE)
569         vim_free(str);
570 #endif
575  * Send the current selection to the clipboard.
576  */
577     void
578 clip_mch_set_selection(VimClipboard *cbd)
580     // If the '*' register isn't already filled in, fill it in now.
581     cbd->owned = TRUE;
582     clip_get_selection(cbd);
583     cbd->owned = FALSE;
584     
585     // Get the text to put on the pasteboard.
586     long_u llen = 0; char_u *str = 0;
587     int motion_type = clip_convert_selection(&str, &llen, cbd);
588     if (motion_type < 0)
589         return;
591     // TODO: Avoid overflow.
592     int len = (int)llen;
593 #ifdef FEAT_MBYTE
594     if (output_conv.vc_type != CONV_NONE) {
595         char_u *conv_str = string_convert(&output_conv, str, &len);
596         if (conv_str) {
597             vim_free(str);
598             str = conv_str;
599         }
600     }
601 #endif
603     if (len > 0) {
604         NSString *string = [[NSString alloc]
605             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
607         // See clip_mch_request_selection() for info on pasteboard types.
608         NSPasteboard *pb = [NSPasteboard generalPasteboard];
609         NSArray *supportedTypes = [NSArray arrayWithObjects:VimPBoardType,
610                 NSStringPboardType, nil];
611         [pb declareTypes:supportedTypes owner:nil];
613         NSNumber *motion = [NSNumber numberWithInt:motion_type];
614         NSArray *plist = [NSArray arrayWithObjects:motion, string, nil];
615         [pb setPropertyList:plist forType:VimPBoardType];
617         [pb setString:string forType:NSStringPboardType];
618         
619         [string release];
620     }
622     vim_free(str);
626 // -- Menu ------------------------------------------------------------------
630  * A menu descriptor represents the "address" of a menu as an array of strings.
631  * E.g. the menu "File->Close" has descriptor { "File", "Close" }.
632  */
633     NSArray *
634 descriptor_for_menu(vimmenu_T *menu)
636     if (!menu) return nil;
638     NSMutableArray *desc = [NSMutableArray array];
639     while (menu) {
640         NSString *name = [NSString stringWithVimString:menu->dname];
641         [desc insertObject:name atIndex:0];
642         menu = menu->parent;
643     }
645     return desc;
648     vimmenu_T *
649 menu_for_descriptor(NSArray *desc)
651     if (!(desc && [desc count] > 0)) return NULL;
653     vimmenu_T *menu = root_menu;
654     int i, count = [desc count];
656     for (i = 0; i < count; ++i) {
657         NSString *component = [desc objectAtIndex:i];
658         while (menu) {
659             NSString *name = [NSString stringWithVimString:menu->dname];
660             if ([component isEqual:name]) {
661                 if (i+1 == count)
662                     return menu;    // Matched all components, so return menu
663                 menu = menu->children;
664                 break;
665             }
666             menu = menu->next;
667         }
668     }
670     return NULL;
674  * Add a submenu to the menu bar, toolbar, or a popup menu.
675  */
676     void
677 gui_mch_add_menu(vimmenu_T *menu, int idx)
679     NSArray *desc = descriptor_for_menu(menu);
680     [[MMBackend sharedInstance] queueMessage:AddMenuMsgID properties:
681         [NSDictionary dictionaryWithObjectsAndKeys:
682             desc, @"descriptor",
683             [NSNumber numberWithInt:idx], @"index",
684             nil]];
689  * Add a menu item to a menu
690  */
691     void
692 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
694     char_u *tip = menu->strings[MENU_INDEX_TIP]
695             ? menu->strings[MENU_INDEX_TIP] : menu->actext;
696     NSArray *desc = descriptor_for_menu(menu);
697     NSString *keyEquivalent = menu->mac_key
698         ? [NSString stringWithFormat:@"%C", specialKeyToNSKey(menu->mac_key)]
699         : [NSString string];
700     int modifierMask = vimModMaskToEventModifierFlags(menu->mac_mods);
701     char_u *icon = NULL;
703     if (menu_is_toolbar(menu->parent->name)) {
704         char_u fname[MAXPATHL];
706         // TODO: Ensure menu->iconfile exists (if != NULL)
707         icon = menu->iconfile;
708         if (!icon && gui_find_bitmap(menu->name, fname, "bmp") == OK)
709             icon = fname;
710         if (!icon && menu->iconidx >= 0)
711             icon = menu->dname;
712     }
714     [[MMBackend sharedInstance] queueMessage:AddMenuItemMsgID properties:
715         [NSDictionary dictionaryWithObjectsAndKeys:
716             desc, @"descriptor",
717             [NSNumber numberWithInt:idx], @"index",
718             [NSString stringWithVimString:tip], @"tip",
719             [NSString stringWithVimString:icon], @"icon",
720             keyEquivalent, @"keyEquivalent",
721             [NSNumber numberWithInt:modifierMask], @"modifierMask",
722             [NSString stringWithVimString:menu->mac_action], @"action",
723             [NSNumber numberWithBool:menu->mac_alternate], @"isAlternate",
724             nil]];
729  * Destroy the machine specific menu widget.
730  */
731     void
732 gui_mch_destroy_menu(vimmenu_T *menu)
734     NSArray *desc = descriptor_for_menu(menu);
735     [[MMBackend sharedInstance] queueMessage:RemoveMenuItemMsgID properties:
736         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
741  * Make a menu either grey or not grey.
742  */
743     void
744 gui_mch_menu_grey(vimmenu_T *menu, int grey)
746     /* Only update menu if the 'grey' state has changed to avoid having to pass
747      * lots of unnecessary data to MacVim.  (Skipping this test makes MacVim
748      * pause noticably on mode changes. */
749     NSArray *desc = descriptor_for_menu(menu);
750     if (menu->was_grey == grey)
751         return;
753     menu->was_grey = grey;
755     [[MMBackend sharedInstance] queueMessage:EnableMenuItemMsgID properties:
756         [NSDictionary dictionaryWithObjectsAndKeys:
757             desc, @"descriptor",
758             [NSNumber numberWithInt:!grey], @"enable",
759             nil]];
764  * Make menu item hidden or not hidden
765  */
766     void
767 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
769     // HACK! There is no (obvious) way to hide a menu item, so simply
770     // enable/disable it instead.
771     gui_mch_menu_grey(menu, hidden);
776  * This is called when user right clicks.
777  */
778     void
779 gui_mch_show_popupmenu(vimmenu_T *menu)
781     NSArray *desc = descriptor_for_menu(menu);
782     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:
783         [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]];
788  * This is called when a :popup command is executed.
789  */
790     void
791 gui_make_popup(char_u *path_name, int mouse_pos)
793     vimmenu_T *menu = gui_find_menu(path_name);
794     if (!(menu && menu->children)) return;
796     NSArray *desc = descriptor_for_menu(menu);
797     NSDictionary *p = (mouse_pos || NULL == curwin)
798         ? [NSDictionary dictionaryWithObject:desc forKey:@"descriptor"]
799         : [NSDictionary dictionaryWithObjectsAndKeys:
800             desc, @"descriptor",
801             [NSNumber numberWithInt:curwin->w_wrow], @"row",
802             [NSNumber numberWithInt:curwin->w_wcol], @"column",
803             nil];
805     [[MMBackend sharedInstance] queueMessage:ShowPopupMenuMsgID properties:p];
810  * This is called after setting all the menus to grey/hidden or not.
811  */
812     void
813 gui_mch_draw_menubar(void)
815     // The (main) menu draws itself in Mac OS X.
819     void
820 gui_mch_enable_menu(int flag)
822     // The (main) menu is always enabled in Mac OS X.
826 #if 0
827     void
828 gui_mch_set_menu_pos(int x, int y, int w, int h)
830     // The (main) menu cannot be moved in Mac OS X.
832 #endif
835     void
836 gui_mch_show_toolbar(int showit)
838     int flags = 0;
839     if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
840     if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
841     if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
843     [[MMBackend sharedInstance] showToolbar:showit flags:flags];
849 // -- Fonts -----------------------------------------------------------------
853  * If a font is not going to be used, free its structure.
854  */
855     void
856 gui_mch_free_font(font)
857     GuiFont     font;
859     if (font != NOFONT) {
860         //NSLog(@"gui_mch_free_font(font=0x%x)", font);
861         [(NSFont*)font release];
862     }
867  * Get a font structure for highlighting.
868  */
869     GuiFont
870 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
872     //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
873     //        giveErrorIfMissing);
875     NSFont *font = gui_macvim_font_with_name(name);
876     if (font)
877         return (GuiFont)[font retain];
879     if (giveErrorIfMissing)
880         EMSG2(_(e_font), name);
882     return NOFONT;
886 #if defined(FEAT_EVAL) || defined(PROTO)
888  * Return the name of font "font" in allocated memory.
889  * Don't know how to get the actual name, thus use the provided name.
890  */
891     char_u *
892 gui_mch_get_fontname(GuiFont font, char_u *name)
894     if (name == NULL)
895         return NULL;
896     return vim_strsave(name);
898 #endif
902  * Initialise vim to use the font with the given name.  Return FAIL if the font
903  * could not be loaded, OK otherwise.
904  */
905     int
906 gui_mch_init_font(char_u *font_name, int fontset)
908     //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
910     if (font_name && STRCMP(font_name, "*") == 0) {
911         // :set gfn=* shows the font panel.
912         do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
913         return FAIL;
914     }
916     NSFont *font = gui_macvim_font_with_name(font_name);
917     if (font) {
918         [(NSFont*)gui.norm_font release];
919         gui.norm_font = (GuiFont)[font retain];
921         // NOTE: MacVim keeps separate track of the normal and wide fonts.
922         // Unless the user changes 'guifontwide' manually, they are based on
923         // the same (normal) font.  Also note that each time the normal font is
924         // set, the advancement may change so the wide font needs to be updated
925         // as well (so that it is always twice the width of the normal font).
926         [[MMBackend sharedInstance] setFont:font];
927         [[MMBackend sharedInstance] setWideFont:
928                (NOFONT == gui.wide_font ? font : (NSFont*)gui.wide_font)];
930         return OK;
931     }
933     return FAIL;
938  * Set the current text font.
939  */
940     void
941 gui_mch_set_font(GuiFont font)
943     // Font selection is done inside MacVim...nothing here to do.
947     NSFont *
948 gui_macvim_font_with_name(char_u *name)
950     NSFont *font = nil;
951     NSString *fontName = MMDefaultFontName;
952     float size = MMDefaultFontSize;
953     BOOL parseFailed = NO;
955 #ifdef FEAT_MBYTE
956     name = CONVERT_TO_UTF8(name);
957 #endif
959     if (name) {
960         fontName = [NSString stringWithUTF8String:(char*)name];
962         NSArray *components = [fontName componentsSeparatedByString:@":"];
963         if ([components count] == 2) {
964             NSString *sizeString = [components lastObject];
965             if ([sizeString length] > 0
966                     && [sizeString characterAtIndex:0] == 'h') {
967                 sizeString = [sizeString substringFromIndex:1];
968                 if ([sizeString length] > 0) {
969                     size = [sizeString floatValue];
970                     fontName = [components objectAtIndex:0];
971                 }
972             } else {
973                 parseFailed = YES;
974             }
975         } else if ([components count] > 2) {
976             parseFailed = YES;
977         }
979         if (!parseFailed) {
980             // Replace underscores with spaces.
981             fontName = [[fontName componentsSeparatedByString:@"_"]
982                                      componentsJoinedByString:@" "];
983         }
984     }
986     if (!parseFailed && [fontName length] > 0) {
987         if (size < MMMinFontSize) size = MMMinFontSize;
988         if (size > MMMaxFontSize) size = MMMaxFontSize;
990         font = [NSFont fontWithName:fontName size:size];
992         if (!font && MMDefaultFontName == fontName) {
993             // If for some reason the MacVim default font is not in the app
994             // bundle, then fall back on the system default font.
995             font = [NSFont userFixedPitchFontOfSize:0];
996         }
997     }
999 #ifdef FEAT_MBYTE
1000     CONVERT_TO_UTF8_FREE(name);
1001 #endif
1003     return font;
1006 // -- Scrollbars ------------------------------------------------------------
1009     void
1010 gui_mch_create_scrollbar(
1011         scrollbar_T *sb,
1012         int orient)     /* SBAR_VERT or SBAR_HORIZ */
1014     [[MMBackend sharedInstance] 
1015             createScrollbarWithIdentifier:sb->ident type:sb->type];
1019     void
1020 gui_mch_destroy_scrollbar(scrollbar_T *sb)
1022     [[MMBackend sharedInstance] 
1023             destroyScrollbarWithIdentifier:sb->ident];
1027     void
1028 gui_mch_enable_scrollbar(
1029         scrollbar_T     *sb,
1030         int             flag)
1032     [[MMBackend sharedInstance] 
1033             showScrollbarWithIdentifier:sb->ident state:flag];
1037     void
1038 gui_mch_set_scrollbar_pos(
1039         scrollbar_T *sb,
1040         int x,
1041         int y,
1042         int w,
1043         int h)
1045     int pos = y;
1046     int len = h;
1047     if (SBAR_BOTTOM == sb->type) {
1048         pos = x;
1049         len = w; 
1050     }
1052     [[MMBackend sharedInstance] 
1053             setScrollbarPosition:pos length:len identifier:sb->ident];
1057     void
1058 gui_mch_set_scrollbar_thumb(
1059         scrollbar_T *sb,
1060         long val,
1061         long size,
1062         long max)
1064     [[MMBackend sharedInstance] 
1065             setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
1069 // -- Cursor ----------------------------------------------------------------
1073  * Draw a cursor without focus.
1074  */
1075     void
1076 gui_mch_draw_hollow_cursor(guicolor_T color)
1078     return [[MMBackend sharedInstance]
1079         drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
1080                fraction:100 color:color];
1085  * Draw part of a cursor, only w pixels wide, and h pixels high.
1086  */
1087     void
1088 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
1090     // HACK!  'w' and 'h' are always 1 since we do not tell Vim about the exact
1091     // font dimensions.  Thus these parameters are useless.  Instead we look at
1092     // the shape_table to determine the shape and size of the cursor (just like
1093     // gui_update_cursor() does).
1095 #ifdef FEAT_RIGHTLEFT
1096     // If 'rl' is set the insert mode cursor must be drawn on the right-hand
1097     // side of a text cell.
1098     int rl = curwin ? curwin->w_p_rl : FALSE;
1099 #else
1100     int rl = FALSE;
1101 #endif
1102     int idx = get_shape_idx(FALSE);
1103     int shape = MMInsertionPointBlock;
1104     switch (shape_table[idx].shape) {
1105         case SHAPE_HOR:
1106             shape = MMInsertionPointHorizontal;
1107             break;
1108         case SHAPE_VER:
1109             shape = rl ? MMInsertionPointVerticalRight
1110                        : MMInsertionPointVertical;
1111             break;
1112     }
1114     return [[MMBackend sharedInstance]
1115         drawCursorAtRow:gui.row column:gui.col shape:shape
1116                fraction:shape_table[idx].percentage color:color];
1121  * Cursor blink functions.
1123  * This is a simple state machine:
1124  * BLINK_NONE   not blinking at all
1125  * BLINK_OFF    blinking, cursor is not shown
1126  * BLINK_ON blinking, cursor is shown
1127  */
1128     void
1129 gui_mch_set_blinking(long wait, long on, long off)
1131     [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1136  * Start the cursor blinking.  If it was already blinking, this restarts the
1137  * waiting time and shows the cursor.
1138  */
1139     void
1140 gui_mch_start_blink(void)
1142     [[MMBackend sharedInstance] startBlink];
1147  * Stop the cursor blinking.  Show the cursor if it wasn't shown.
1148  */
1149     void
1150 gui_mch_stop_blink(void)
1152     [[MMBackend sharedInstance] stopBlink];
1156 // -- Mouse -----------------------------------------------------------------
1160  * Get current mouse coordinates in text window.
1161  */
1162     void
1163 gui_mch_getmouse(int *x, int *y)
1165     //NSLog(@"gui_mch_getmouse()");
1169     void
1170 gui_mch_setmouse(int x, int y)
1172     //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1176     void
1177 mch_set_mouse_shape(int shape)
1179     [[MMBackend sharedInstance] setMouseShape:shape];
1185 // -- Input Method ----------------------------------------------------------
1187 #if defined(USE_IM_CONTROL)
1189     void
1190 im_set_position(int row, int col)
1192     // The pre-edit area is a popup window which is displayed by MMTextView.
1193     [[MMBackend sharedInstance] setPreEditRow:row column:col];
1197     void
1198 im_set_active(int active)
1200     // Set roman or the system script if 'active' is TRUE or FALSE,
1201     // respectively.
1202     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1204     if (!p_imdisable && smRoman != systemScript)
1205         KeyScript(active ? smKeySysScript : smKeyRoman);
1209     int
1210 im_get_status(void)
1212     // IM is active whenever the current script is the system script and the
1213     // system script isn't roman.  (Hence IM can only be active when using
1214     // non-roman scripts.)
1215     SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
1216     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1218     return currentScript != smRoman && currentScript == systemScript;
1221 #endif // defined(USE_IM_CONTROL)
1226 // -- Unsorted --------------------------------------------------------------
1229     void
1230 ex_macaction(eap)
1231     exarg_T     *eap;
1233     if (!gui.in_use) {
1234         EMSG(_("E???: Command only available in GUI mode"));
1235         return;
1236     }
1238     char_u *arg = eap->arg;
1239 #ifdef FEAT_MBYTE
1240     arg = CONVERT_TO_UTF8(arg);
1241 #endif
1243     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1244     NSString *name = [NSString stringWithUTF8String:(char*)arg];
1245     if (actionDict && [actionDict objectForKey:name] != nil) {
1246         [[MMBackend sharedInstance] executeActionWithName:name];
1247     } else {
1248         EMSG2(_("E???: Invalid action: %s"), eap->arg);
1249     }
1251 #ifdef FEAT_MBYTE
1252     arg = CONVERT_TO_UTF8(arg);
1253 #endif
1258  * Adjust gui.char_height (after 'linespace' was changed).
1259  */
1260     int
1261 gui_mch_adjust_charheight(void)
1263     [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1264     return OK;
1268     void
1269 gui_mch_beep(void)
1271     NSBeep();
1276 #ifdef FEAT_BROWSE
1278  * Pop open a file browser and return the file selected, in allocated memory,
1279  * or NULL if Cancel is hit.
1280  *  saving  - TRUE if the file will be saved to, FALSE if it will be opened.
1281  *  title   - Title message for the file browser dialog.
1282  *  dflt    - Default name of file.
1283  *  ext     - Default extension to be added to files without extensions.
1284  *  initdir - directory in which to open the browser (NULL = current dir)
1285  *  filter  - Filter for matched files to choose from.
1286  *  Has a format like this:
1287  *  "C Files (*.c)\0*.c\0"
1288  *  "All Files\0*.*\0\0"
1289  *  If these two strings were concatenated, then a choice of two file
1290  *  filters will be selectable to the user.  Then only matching files will
1291  *  be shown in the browser.  If NULL, the default allows all files.
1293  *  *NOTE* - the filter string must be terminated with TWO nulls.
1294  */
1295     char_u *
1296 gui_mch_browse(
1297     int saving,
1298     char_u *title,
1299     char_u *dflt,
1300     char_u *ext,
1301     char_u *initdir,
1302     char_u *filter)
1304     //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1305     //        " filter=%s", saving, title, dflt, ext, initdir, filter);
1307     // Ensure no data is on the output queue before presenting the dialog.
1308     gui_macvim_force_flush();
1310     NSMutableDictionary *attr = [NSMutableDictionary
1311         dictionaryWithObject:[NSNumber numberWithBool:saving]
1312                       forKey:@"saving"];
1313     if (initdir)
1314         [attr setObject:[NSString stringWithVimString:initdir] forKey:@"dir"];
1316     char_u *s = (char_u*)[[MMBackend sharedInstance]
1317                             browseForFileWithAttributes:attr];
1319     return s;
1321 #endif /* FEAT_BROWSE */
1325     int
1326 gui_mch_dialog(
1327     int         type,
1328     char_u      *title,
1329     char_u      *message,
1330     char_u      *buttons,
1331     int         dfltbutton,
1332     char_u      *textfield)
1334     //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1335     //        "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1336     //        dfltbutton, textfield);
1338     // Ensure no data is on the output queue before presenting the dialog.
1339     gui_macvim_force_flush();
1341     int style = NSInformationalAlertStyle;
1342     if (VIM_WARNING == type) style = NSWarningAlertStyle;
1343     else if (VIM_ERROR == type) style = NSCriticalAlertStyle;
1345     NSMutableDictionary *attr = [NSMutableDictionary
1346                         dictionaryWithObject:[NSNumber numberWithInt:style]
1347                                       forKey:@"alertStyle"];
1349     if (buttons) {
1350         // 'buttons' is a string of '\n'-separated button titles 
1351         NSString *string = [NSString stringWithVimString:buttons];
1352         NSArray *array = [string componentsSeparatedByString:@"\n"];
1353         [attr setObject:array forKey:@"buttonTitles"];
1354     }
1356     NSString *messageText = nil;
1357     if (title)
1358         messageText = [NSString stringWithVimString:title];
1360     if (message) {
1361         NSString *informativeText = [NSString stringWithVimString:message];
1362         if (!messageText) {
1363             // HACK! If there is a '\n\n' or '\n' sequence in the message, then
1364             // make the part up to there into the title.  We only do this
1365             // because Vim has lots of dialogs without a title and they look
1366             // ugly that way.
1367             // TODO: Fix the actual dialog texts.
1368             NSRange eolRange = [informativeText rangeOfString:@"\n\n"];
1369             if (NSNotFound == eolRange.location)
1370                 eolRange = [informativeText rangeOfString:@"\n"];
1371             if (NSNotFound != eolRange.location) {
1372                 messageText = [informativeText substringToIndex:
1373                                                         eolRange.location];
1374                 informativeText = [informativeText substringFromIndex:
1375                                                         NSMaxRange(eolRange)];
1376             }
1377         }
1379         [attr setObject:informativeText forKey:@"informativeText"];
1380     }
1382     if (messageText)
1383         [attr setObject:messageText forKey:@"messageText"];
1385     if (textfield) {
1386         NSString *string = [NSString stringWithVimString:textfield];
1387         [attr setObject:string forKey:@"textFieldString"];
1388     }
1390     return [[MMBackend sharedInstance] showDialogWithAttributes:attr
1391                                                     textField:(char*)textfield];
1395     void
1396 gui_mch_flash(int msec)
1402  * Return the Pixel value (color) for the given color name.  This routine was
1403  * pretty much taken from example code in the Silicon Graphics OSF/Motif
1404  * Programmer's Guide.
1405  * Return INVALCOLOR when failed.
1406  */
1407     guicolor_T
1408 gui_mch_get_color(char_u *name)
1410 #ifdef FEAT_MBYTE
1411     name = CONVERT_TO_UTF8(name);
1412 #endif
1414     NSString *key = [NSString stringWithUTF8String:(char*)name];
1415     guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1417 #ifdef FEAT_MBYTE
1418     CONVERT_TO_UTF8_FREE(name);
1419 #endif
1421     return col;
1426  * Return the RGB value of a pixel as long.
1427  */
1428     long_u
1429 gui_mch_get_rgb(guicolor_T pixel)
1431     // This is only implemented so that vim can guess the correct value for
1432     // 'background' (which otherwise defaults to 'dark'); it is not used for
1433     // anything else (as far as I know).
1434     // The implementation is simple since colors are stored in an int as
1435     // "rrggbb".
1436     return pixel;
1441  * Get the screen dimensions.
1442  * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1443  * Is there no way to find out how wide the borders really are?
1444  * TODO: Add live udate of those value on suspend/resume.
1445  */
1446     void
1447 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1449     //NSLog(@"gui_mch_get_screen_dimensions()");
1450     *screen_w = Columns;
1451     *screen_h = Rows;
1456  * Get the position of the top left corner of the window.
1457  */
1458     int
1459 gui_mch_get_winpos(int *x, int *y)
1461     *x = *y = 0;
1462     return OK;
1467  * Return OK if the key with the termcap name "name" is supported.
1468  */
1469     int
1470 gui_mch_haskey(char_u *name)
1472     BOOL ok = NO;
1474 #ifdef FEAT_MBYTE
1475     name = CONVERT_TO_UTF8(name);
1476 #endif
1478     NSString *value = [NSString stringWithUTF8String:(char*)name];
1479     if (value)
1480         ok =  [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1482 #ifdef FEAT_MBYTE
1483     CONVERT_TO_UTF8_FREE(name);
1484 #endif
1486     return ok;
1491  * Iconify the GUI window.
1492  */
1493     void
1494 gui_mch_iconify(void)
1499 #if defined(FEAT_EVAL) || defined(PROTO)
1501  * Bring the Vim window to the foreground.
1502  */
1503     void
1504 gui_mch_set_foreground(void)
1506     [[MMBackend sharedInstance] activate];
1508 #endif
1512     void
1513 gui_mch_set_shellsize(
1514     int         width,
1515     int         height,
1516     int         min_width,
1517     int         min_height,
1518     int         base_width,
1519     int         base_height,
1520     int         direction)
1522     //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1523     //        " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1524     //        width, height, min_width, min_height, base_width, base_height,
1525     //        direction);
1526     [[MMBackend sharedInstance] setRows:height columns:width];
1530     void
1531 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1536  * Set the position of the top left corner of the window to the given
1537  * coordinates.
1538  */
1539     void
1540 gui_mch_set_winpos(int x, int y)
1545 #ifdef FEAT_TITLE
1547  * Set the window title and icon.
1548  * (The icon is not taken care of).
1549  */
1550     void
1551 gui_mch_settitle(char_u *title, char_u *icon)
1553     //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1555 #ifdef FEAT_MBYTE
1556     title = CONVERT_TO_UTF8(title);
1557 #endif
1559     MMBackend *backend = [MMBackend sharedInstance];
1560     [backend setWindowTitle:(char*)title];
1562     // TODO: Convert filename to UTF-8?
1563     if (curbuf)
1564         [backend setDocumentFilename:(char*)curbuf->b_ffname];
1566 #ifdef FEAT_MBYTE
1567     CONVERT_TO_UTF8_FREE(title);
1568 #endif
1570 #endif
1573     void
1574 gui_mch_toggle_tearoffs(int enable)
1580     void
1581 gui_mch_enter_fullscreen(int fuoptions_flags, guicolor_T bg)
1583     [[MMBackend sharedInstance] enterFullscreen:fuoptions_flags background:bg];
1587     void
1588 gui_mch_leave_fullscreen()
1590     [[MMBackend sharedInstance] leaveFullscreen];
1594     void
1595 gui_macvim_update_modified_flag()
1597     [[MMBackend sharedInstance] updateModifiedFlag];
1601  * Add search pattern 'pat' to the OS X find pasteboard.  This allows other
1602  * apps access the last pattern searched for (hitting <D-g> in another app will
1603  * initiate a search for the same pattern).
1604  */
1605     void
1606 gui_macvim_add_to_find_pboard(char_u *pat)
1608     if (!pat) return;
1610 #ifdef FEAT_MBYTE
1611     pat = CONVERT_TO_UTF8(pat);
1612 #endif
1613     NSString *s = [NSString stringWithUTF8String:(char*)pat];
1614 #ifdef FEAT_MBYTE
1615     CONVERT_TO_UTF8_FREE(pat);
1616 #endif
1618     if (!s) return;
1620     NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
1621     [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1622     [pb setString:s forType:NSStringPboardType];
1625     void
1626 gui_macvim_set_antialias(int antialias)
1628     [[MMBackend sharedInstance] setAntialias:antialias];
1635 // -- Client/Server ---------------------------------------------------------
1637 #ifdef MAC_CLIENTSERVER
1640 // NOTE: Client/Server is only fully supported with a GUI.  Theoretically it
1641 // would be possible to make the server code work with terminal Vim, but it
1642 // would require that a run-loop is set up and checked.  This should not be
1643 // difficult to implement, simply call gui_mch_update() at opportune moments
1644 // and it will take care of the run-loop.  Another (bigger) problem with
1645 // supporting servers in terminal mode is that the server listing code talks to
1646 // MacVim (the GUI) to figure out which servers are running.
1651  * Register connection with 'name'.  The actual connection is named something
1652  * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1653  */
1654     void
1655 serverRegisterName(char_u *name)
1657 #ifdef FEAT_MBYTE
1658     name = CONVERT_TO_UTF8(name);
1659 #endif
1661     NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1662     [[MMBackend sharedInstance] registerServerWithName:svrName];
1664 #ifdef FEAT_MBYTE
1665     CONVERT_TO_UTF8_FREE(name);
1666 #endif
1671  * Send to an instance of Vim.
1672  * Returns 0 for OK, negative for an error.
1673  */
1674     int
1675 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1676         int *port, int asExpr, int silent)
1678 #ifdef FEAT_MBYTE
1679     name = CONVERT_TO_UTF8(name);
1680     cmd = CONVERT_TO_UTF8(cmd);
1681 #endif
1683     BOOL ok = [[MMBackend sharedInstance]
1684             sendToServer:[NSString stringWithUTF8String:(char*)name]
1685                   string:[NSString stringWithUTF8String:(char*)cmd]
1686                    reply:result
1687                     port:port
1688               expression:asExpr
1689                   silent:silent];
1691 #ifdef FEAT_MBYTE
1692     CONVERT_TO_UTF8_FREE(name);
1693     CONVERT_TO_UTF8_FREE(cmd);
1694 #endif
1696     return ok ? 0 : -1;
1701  * Ask MacVim for the names of all Vim servers.
1702  */
1703     char_u *
1704 serverGetVimNames(void)
1706     char_u *names = NULL;
1707     NSArray *list = [[MMBackend sharedInstance] serverList];
1709     if (list) {
1710         NSString *string = [list componentsJoinedByString:@"\n"];
1711         char_u *s = (char_u*)[string UTF8String];
1712 #ifdef FEAT_MBYTE
1713         s = CONVERT_FROM_UTF8(s);
1714 #endif
1715         names = vim_strsave(s);
1716 #ifdef FEAT_MBYTE
1717         CONVERT_FROM_UTF8_FREE(s);
1718 #endif
1719     }
1721     return names;
1726  * 'str' is a hex int representing the send port of the connection.
1727  */
1728     int
1729 serverStrToPort(char_u *str)
1731     int port = 0;
1733     sscanf((char *)str, "0x%x", &port);
1734     if (!port)
1735         EMSG2(_("E573: Invalid server id used: %s"), str);
1737     return port;
1742  * Check for replies from server with send port 'port'.
1743  * Return TRUE and a non-malloc'ed string if there is.  Else return FALSE.
1744  */
1745     int
1746 serverPeekReply(int port, char_u **str)
1748     NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1749     int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1751     if (str && len > 0) {
1752         *str = (char_u*)[reply UTF8String];
1754 #ifdef FEAT_MBYTE
1755         if (input_conv.vc_type != CONV_NONE) {
1756             char_u *s = string_convert(&input_conv, *str, &len);
1758             if (len > 0) {
1759                 // HACK! Since 's' needs to be freed we cannot simply set
1760                 // '*str = s' or memory will leak.  Instead, create a dummy
1761                 // NSData and return its 'bytes' pointer, then autorelease the
1762                 // NSData.
1763                 NSData *data = [NSData dataWithBytes:s length:len+1];
1764                 *str = (char_u*)[data bytes];
1765             }
1767             vim_free(s);
1768         }
1769 #endif
1770     }
1772     return reply != nil;
1777  * Wait for replies from server with send port 'port'.
1778  * Return 0 and the malloc'ed string when a reply is available.
1779  * Return -1 on error.
1780  */
1781     int
1782 serverReadReply(int port, char_u **str)
1784     NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1785     if (reply && str) {
1786         char_u *s = (char_u*)[reply UTF8String];
1787 #ifdef FEAT_MBYTE
1788         s = CONVERT_FROM_UTF8(s);
1789 #endif
1790         *str = vim_strsave(s);
1791 #ifdef FEAT_MBYTE
1792         CONVERT_FROM_UTF8_FREE(s);
1793 #endif
1794         return 0;
1795     }
1797     return -1;
1802  * Send a reply string (notification) to client with port given by "serverid".
1803  * Return -1 if the window is invalid.
1804  */
1805     int
1806 serverSendReply(char_u *serverid, char_u *reply)
1808     int retval = -1;
1809     int port = serverStrToPort(serverid);
1810     if (port > 0 && reply) {
1811 #ifdef FEAT_MBYTE
1812         reply = CONVERT_TO_UTF8(reply);
1813 #endif
1814         BOOL ok = [[MMBackend sharedInstance]
1815                 sendReply:[NSString stringWithUTF8String:(char*)reply]
1816                    toPort:port];
1817         retval = ok ? 0 : -1;
1818 #ifdef FEAT_MBYTE
1819         CONVERT_TO_UTF8_FREE(reply);
1820 #endif
1821     }
1823     return retval;
1826 #endif // MAC_CLIENTSERVER
1831 // -- ODB Editor Support ----------------------------------------------------
1833 #ifdef FEAT_ODB_EDITOR
1835  * The ODB Editor protocol works like this:
1836  * - An external program (the server) asks MacVim to open a file and associates
1837  *   three things with this file: (1) a server id (a four character code that
1838  *   identifies the server), (2) a path that can be used as window title for
1839  *   the file (optional), (3) an arbitrary token (optional)
1840  * - When a file is saved or closed, MacVim should tell the server about which
1841  *   file was modified and also pass back the token
1843  * All communication between MacVim and the server goes via Apple Events.
1844  */
1846     static OSErr
1847 odb_event(buf_T *buf, const AEEventID action)
1849     if (!(buf->b_odb_server_id && buf->b_ffname))
1850         return noErr;
1852     NSAppleEventDescriptor *targetDesc = [NSAppleEventDescriptor
1853             descriptorWithDescriptorType:typeApplSignature
1854                                    bytes:&buf->b_odb_server_id
1855                                   length:sizeof(OSType)];
1857     // TODO: Convert b_ffname to UTF-8?
1858     NSString *path = [NSString stringWithUTF8String:(char*)buf->b_ffname];
1859     NSData *pathData = [[[NSURL fileURLWithPath:path] absoluteString]
1860             dataUsingEncoding:NSUTF8StringEncoding];
1861     NSAppleEventDescriptor *pathDesc = [NSAppleEventDescriptor
1862             descriptorWithDescriptorType:typeFileURL data:pathData];
1864     NSAppleEventDescriptor *event = [NSAppleEventDescriptor
1865             appleEventWithEventClass:kODBEditorSuite
1866                              eventID:action
1867                     targetDescriptor:targetDesc
1868                             returnID:kAutoGenerateReturnID
1869                        transactionID:kAnyTransactionID];
1871     [event setParamDescriptor:pathDesc forKeyword:keyDirectObject];
1873     if (buf->b_odb_token)
1874         [event setParamDescriptor:buf->b_odb_token forKeyword:keySenderToken];
1876     return AESendMessage([event aeDesc], NULL, kAENoReply | kAENeverInteract,
1877             kAEDefaultTimeout);
1880     OSErr
1881 odb_buffer_close(buf_T *buf)
1883     OSErr err = noErr;
1884     if (buf) {
1885         err = odb_event(buf, kAEClosedFile);
1887         buf->b_odb_server_id = 0;
1889         if (buf->b_odb_token) {
1890             [(NSAppleEventDescriptor *)(buf->b_odb_token) release];
1891             buf->b_odb_token = NULL;
1892         }
1894         if (buf->b_odb_fname) {
1895             vim_free(buf->b_odb_fname);
1896             buf->b_odb_fname = NULL;
1897         }
1898     }
1900     return err;
1903     OSErr
1904 odb_post_buffer_write(buf_T *buf)
1906     return buf ? odb_event(buf, kAEModifiedFile) : noErr;
1909     void
1910 odb_end(void)
1912     buf_T *buf;
1913     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1914         odb_buffer_close(buf);
1917 #endif // FEAT_ODB_EDITOR
1920     char_u *
1921 get_macaction_name(expand_T *xp, int idx)
1923     static char_u *str = NULL;
1924     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1926     if (nil == actionDict || idx < 0 || idx >= [actionDict count])
1927         return NULL;
1929     NSString *string = [[actionDict allKeys] objectAtIndex:idx];
1930     if (!string)
1931         return NULL;
1933     char_u *plainStr = (char_u*)[string UTF8String];
1935 #ifdef FEAT_MBYTE
1936     if (str) {
1937         vim_free(str);
1938         str = NULL;
1939     }
1940     if (input_conv.vc_type != CONV_NONE) {
1941         int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1942         str = string_convert(&input_conv, plainStr, &len);
1943         plainStr = str;
1944     }
1945 #endif
1947     return plainStr;
1951     int
1952 is_valid_macaction(char_u *action)
1954     int isValid = NO;
1955     NSDictionary *actionDict = [[MMBackend sharedInstance] actionDict];
1956     if (actionDict) {
1957 #ifdef FEAT_MBYTE
1958         action = CONVERT_TO_UTF8(action);
1959 #endif
1960         NSString *string = [NSString stringWithUTF8String:(char*)action];
1961         isValid = (nil != [actionDict objectForKey:string]);
1962 #ifdef FEAT_MBYTE
1963         CONVERT_TO_UTF8_FREE(action);
1964 #endif
1965     }
1967     return isValid;
1970 static int specialKeyToNSKey(int key)
1972     if (!IS_SPECIAL(key))
1973         return key;
1975     static struct {
1976         int special;
1977         int nskey;
1978     } sp2ns[] = {
1979         { K_UP, NSUpArrowFunctionKey },
1980         { K_DOWN, NSDownArrowFunctionKey },
1981         { K_LEFT, NSLeftArrowFunctionKey },
1982         { K_RIGHT, NSRightArrowFunctionKey },
1983         { K_F1, NSF1FunctionKey },
1984         { K_F2, NSF2FunctionKey },
1985         { K_F3, NSF3FunctionKey },
1986         { K_F4, NSF4FunctionKey },
1987         { K_F5, NSF5FunctionKey },
1988         { K_F6, NSF6FunctionKey },
1989         { K_F7, NSF7FunctionKey },
1990         { K_F8, NSF8FunctionKey },
1991         { K_F9, NSF9FunctionKey },
1992         { K_F10, NSF10FunctionKey },
1993         { K_F11, NSF11FunctionKey },
1994         { K_F12, NSF12FunctionKey },
1995         { K_F13, NSF13FunctionKey },
1996         { K_F14, NSF14FunctionKey },
1997         { K_F15, NSF15FunctionKey },
1998         { K_F16, NSF16FunctionKey },
1999         { K_F17, NSF17FunctionKey },
2000         { K_F18, NSF18FunctionKey },
2001         { K_F19, NSF19FunctionKey },
2002         { K_F20, NSF20FunctionKey },
2003         { K_F21, NSF21FunctionKey },
2004         { K_F22, NSF22FunctionKey },
2005         { K_F23, NSF23FunctionKey },
2006         { K_F24, NSF24FunctionKey },
2007         { K_F25, NSF25FunctionKey },
2008         { K_F26, NSF26FunctionKey },
2009         { K_F27, NSF27FunctionKey },
2010         { K_F28, NSF28FunctionKey },
2011         { K_F29, NSF29FunctionKey },
2012         { K_F30, NSF30FunctionKey },
2013         { K_F31, NSF31FunctionKey },
2014         { K_F32, NSF32FunctionKey },
2015         { K_F33, NSF33FunctionKey },
2016         { K_F34, NSF34FunctionKey },
2017         { K_F35, NSF35FunctionKey },
2018         { K_DEL, NSBackspaceCharacter },
2019         { K_BS, NSDeleteCharacter },
2020         { K_HOME, NSHomeFunctionKey },
2021         { K_END, NSEndFunctionKey },
2022         { K_PAGEUP, NSPageUpFunctionKey },
2023         { K_PAGEDOWN, NSPageDownFunctionKey }
2024     };
2026     int i;
2027     for (i = 0; i < sizeof(sp2ns)/sizeof(sp2ns[0]); ++i) {
2028         if (sp2ns[i].special == key)
2029             return sp2ns[i].nskey;
2030     }
2032     return 0;
2035 static int vimModMaskToEventModifierFlags(int mods)
2037     int flags = 0;
2039     if (mods & MOD_MASK_SHIFT)
2040         flags |= NSShiftKeyMask;
2041     if (mods & MOD_MASK_CTRL)
2042         flags |= NSControlKeyMask;
2043     if (mods & MOD_MASK_ALT)
2044         flags |= NSAlternateKeyMask;
2045     if (mods & MOD_MASK_CMD)
2046         flags |= NSCommandKeyMask;
2048     return flags;
2054 @implementation NSString (VimStrings)
2055 + (id)stringWithVimString:(char_u *)s
2057     // This method ensures a non-nil string is returned.  If 's' cannot be
2058     // converted to a utf-8 string it is assumed to be latin-1.  If conversion
2059     // still fails an empty NSString is returned.
2060     NSString *string = nil;
2061     if (s) {
2062 #ifdef FEAT_MBYTE
2063         s = CONVERT_TO_UTF8(s);
2064 #endif
2065         string = [NSString stringWithUTF8String:(char*)s];
2066         if (!string) {
2067             // HACK! Apparently 's' is not a valid utf-8 string, maybe it is
2068             // latin-1?
2069             string = [NSString stringWithCString:(char*)s
2070                                         encoding:NSISOLatin1StringEncoding];
2071         }
2072 #ifdef FEAT_MBYTE
2073         CONVERT_TO_UTF8_FREE(s);
2074 #endif
2075     }
2077     return string != nil ? string : [NSString string];
2079 @end