Add IM control support
[MacVim/jjgod.git] / src / MacVim / gui_macvim.m
blob839b8383e65c18a1e0876ae2789e567a68848804
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 <Foundation/Foundation.h>
17 #import "MMBackend.h"
18 #import "MacVim.h"
19 #import "vim.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 BOOL gui_macvim_is_valid_action(NSString *action);
39 // -- Initialization --------------------------------------------------------
42  * Parse the GUI related command-line arguments.  Any arguments used are
43  * deleted from argv, and *argc is decremented accordingly.  This is called
44  * when vim is started, whether or not the GUI has been started.
45  */
46     void
47 gui_mch_prepare(int *argc, char **argv)
49     //NSLog(@"gui_mch_prepare(argc=%d)", *argc);
51     // Set environment variables $VIM and $VIMRUNTIME
52     // NOTE!  If vim_getenv is called with one of these as parameters before
53     // they have been set here, they will most likely end up with the wrong
54     // values!
55     //
56     // TODO:
57     // - ensure this is called first to avoid above problem
58     // - encoding
60     NSString *path = [[[NSBundle mainBundle] resourcePath]
61         stringByAppendingPathComponent:@"vim"];
62     vim_setenv((char_u*)"VIM", (char_u*)[path UTF8String]);
64     path = [path stringByAppendingPathComponent:@"runtime"];
65     vim_setenv((char_u*)"VIMRUNTIME", (char_u*)[path UTF8String]);
70  * Check if the GUI can be started.  Called before gvimrc is sourced.
71  * Return OK or FAIL.
72  */
73     int
74 gui_mch_init_check(void)
76     //NSLog(@"gui_mch_init_check()");
77     return OK;
82  * Initialise the GUI.  Create all the windows, set up all the call-backs etc.
83  * Returns OK for success, FAIL when the GUI can't be started.
84  */
85     int
86 gui_mch_init(void)
88     //NSLog(@"gui_mch_init()");
90     if (![[MMBackend sharedInstance] checkin])
91         return FAIL;
93     // Force 'termencoding' to utf-8 (changes to 'tenc' are disallowed in
94     // 'option.c', so that ':set termencoding=...' is impossible).
95     set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
97     // Set values so that pixels and characters are in one-to-one
98     // correspondence (assuming all characters have the same dimensions).
99     gui.scrollbar_width = gui.scrollbar_height = 0;
101     gui.char_height = 1;
102     gui.char_width = 1;
103     gui.char_ascent = 0;
105     gui_mch_def_colors();
107     [[MMBackend sharedInstance]
108         setDefaultColorsBackground:gui.back_pixel foreground:gui.norm_pixel];
109     [[MMBackend sharedInstance] setBackgroundColor:gui.back_pixel];
110     [[MMBackend sharedInstance] setForegroundColor:gui.norm_pixel];
112     // NOTE: If this call is left out the cursor is opaque.
113     highlight_gui_started();
115     return OK;
120     void
121 gui_mch_exit(int rc)
123     //NSLog(@"gui_mch_exit(rc=%d)", rc);
125     [[MMBackend sharedInstance] exit];
130  * Open the GUI window which was created by a call to gui_mch_init().
131  */
132     int
133 gui_mch_open(void)
135     //NSLog(@"gui_mch_open()");
137     return [[MMBackend sharedInstance] openVimWindow];
141 // -- Updating --------------------------------------------------------------
145  * Catch up with any queued X events.  This may put keyboard input into the
146  * input buffer, call resize call-backs, trigger timers etc.  If there is
147  * nothing in the X event queue (& no timers pending), then we return
148  * immediately.
149  */
150 #define MM_LOG_UPDATE_STATS 0
151     void
152 gui_mch_update(void)
154     // NOTE: This function can get called A LOT (~1 call/ms) and unfortunately
155     // checking the run loop takes a long time, resulting in noticable slow
156     // downs if it is done every time this function is called.  Therefore we
157     // make sure that it is not done too often.
158     static NSDate *lastUpdateDate = nil;
159 #if MM_LOG_UPDATE_STATS
160     static int skipCount = 0;
161 #endif
163     if (lastUpdateDate && -[lastUpdateDate timeIntervalSinceNow] <
164             MMUpdateTimeoutInterval) {
165 #if MM_LOG_UPDATE_STATS
166         ++skipCount;
167 #endif
168         return;
169     }
171 #if MM_LOG_UPDATE_STATS
172     NSTimeInterval dt = -[lastUpdateDate timeIntervalSinceNow];
173     NSLog(@"Updating (last update %.2f seconds ago, skipped %d updates, "
174             "approx %.1f calls per second)",
175             dt, skipCount, dt > 0 ? skipCount/dt : 0);
176     skipCount = 0;
177 #endif
179     [[MMBackend sharedInstance] update];
181     [lastUpdateDate release];
182     lastUpdateDate = [[NSDate date] retain];
186 /* Flush any output to the screen */
187     void
188 gui_mch_flush(void)
190     [[MMBackend sharedInstance] flushQueue:NO];
194 /* Force flush output to MacVim.  Do not call this method unless absolutely
195  * necessary (use gui_mch_flush() instead). */
196     void
197 gui_macvim_force_flush(void)
199     [[MMBackend sharedInstance] flushQueue:YES];
204  * GUI input routine called by gui_wait_for_chars().  Waits for a character
205  * from the keyboard.
206  *  wtime == -1     Wait forever.
207  *  wtime == 0      This should never happen.
208  *  wtime > 0       Wait wtime milliseconds for a character.
209  * Returns OK if a character was found to be available within the given time,
210  * or FAIL otherwise.
211  */
212     int
213 gui_mch_wait_for_chars(int wtime)
215     // NOTE! In all likelihood Vim will take a nap when waitForInput: is
216     // called, so force a flush of the command queue here.
217     [[MMBackend sharedInstance] flushQueue:YES];
219     return [[MMBackend sharedInstance] waitForInput:wtime];
223 // -- Drawing ---------------------------------------------------------------
227  * Clear the whole text window.
228  */
229     void
230 gui_mch_clear_all(void)
232     [[MMBackend sharedInstance] clearAll];
237  * Clear a rectangular region of the screen from text pos (row1, col1) to
238  * (row2, col2) inclusive.
239  */
240     void
241 gui_mch_clear_block(int row1, int col1, int row2, int col2)
243     [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
244                                                     toRow:row2 column:col2];
249  * Delete the given number of lines from the given row, scrolling up any
250  * text further down within the scroll region.
251  */
252     void
253 gui_mch_delete_lines(int row, int num_lines)
255     [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
256             scrollBottom:gui.scroll_region_bot
257                     left:gui.scroll_region_left
258                    right:gui.scroll_region_right];
262     void
263 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
265 #ifdef FEAT_MBYTE
266     char_u *conv_str = NULL;
267     if (output_conv.vc_type != CONV_NONE) {
268         conv_str = string_convert(&output_conv, s, &len);
269         if (conv_str)
270             s = conv_str;
271     }
272 #endif
274     [[MMBackend sharedInstance] drawString:(char*)s length:len row:row
275                                     column:col cells:len flags:flags];
277 #ifdef FEAT_MBYTE
278     if (conv_str)
279         vim_free(conv_str);
280 #endif
284     int
285 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
287     int c, cn, cl, i;
288     int start = 0;
289     int endcol = col;
290     int startcol = col;
291     BOOL wide = NO;
292     MMBackend *backend = [MMBackend sharedInstance];
293 #ifdef FEAT_MBYTE
294     char_u *conv_str = NULL;
296     if (output_conv.vc_type != CONV_NONE) {
297         conv_str = string_convert(&output_conv, s, &len);
298         if (conv_str)
299             s = conv_str;
300     }
301 #endif
303     // Loop over each character and output text when it changes from normal to
304     // wide and vice versa.
305     for (i = 0; i < len; i += cl) {
306         c = utf_ptr2char(s + i);
307         cl = utf_ptr2len(s + i);
308         cn = utf_char2cells(c);
310         if (!utf_iscomposing(c)) {
311             if ((cn > 1 && !wide) || (cn <= 1 && wide)) {
312                 // Changed from normal to wide or vice versa.
313                 [backend drawString:(char*)(s+start) length:i-start
314                                    row:row column:startcol
315                                  cells:endcol-startcol
316                                  flags:(wide ? flags|DRAW_WIDE : flags)];
318                 start = i;
319                 startcol = endcol;
320             }
322             wide = cn > 1;
323             endcol += cn;
324         }
325     }
327     // Output remaining characters.
328     [backend drawString:(char*)(s+start) length:len-start
329                     row:row column:startcol cells:endcol-startcol
330                   flags:(wide ? flags|DRAW_WIDE : flags)];
332 #ifdef FEAT_MBYTE
333     if (conv_str)
334         vim_free(conv_str);
335 #endif
337     return endcol - col;
342  * Insert the given number of lines before the given row, scrolling down any
343  * following text within the scroll region.
344  */
345     void
346 gui_mch_insert_lines(int row, int num_lines)
348     [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
349             scrollBottom:gui.scroll_region_bot
350                     left:gui.scroll_region_left
351                    right:gui.scroll_region_right];
356  * Set the current text foreground color.
357  */
358     void
359 gui_mch_set_fg_color(guicolor_T color)
361     [[MMBackend sharedInstance] setForegroundColor:color];
366  * Set the current text background color.
367  */
368     void
369 gui_mch_set_bg_color(guicolor_T color)
371     [[MMBackend sharedInstance] setBackgroundColor:color];
376  * Set the current text special color (used for underlines).
377  */
378     void
379 gui_mch_set_sp_color(guicolor_T color)
381     [[MMBackend sharedInstance] setSpecialColor:color];
386  * Set default colors.
387  */
388     void
389 gui_mch_def_colors()
391     MMBackend *backend = [MMBackend sharedInstance];
393     // The default colors are taken from system values
394     gui.def_norm_pixel = gui.norm_pixel = 
395         [backend lookupColorWithKey:@"MacTextColor"];
396     gui.def_back_pixel = gui.back_pixel = 
397         [backend lookupColorWithKey:@"MacTextBackgroundColor"];
402  * Called when the foreground or background color has been changed.
403  */
404     void
405 gui_mch_new_colors(void)
407     gui.def_back_pixel = gui.back_pixel;
408     gui.def_norm_pixel = gui.norm_pixel;
410     //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
411     //        gui.def_norm_pixel);
413     [[MMBackend sharedInstance]
414         setDefaultColorsBackground:gui.def_back_pixel
415                         foreground:gui.def_norm_pixel];
419 // -- Tabline ---------------------------------------------------------------
423  * Set the current tab to "nr".  First tab is 1.
424  */
425     void
426 gui_mch_set_curtab(int nr)
428     [[MMBackend sharedInstance] selectTab:nr];
433  * Return TRUE when tabline is displayed.
434  */
435     int
436 gui_mch_showing_tabline(void)
438     return [[MMBackend sharedInstance] tabBarVisible];
442  * Update the labels of the tabline.
443  */
444     void
445 gui_mch_update_tabline(void)
447     [[MMBackend sharedInstance] updateTabBar];
451  * Show or hide the tabline.
452  */
453     void
454 gui_mch_show_tabline(int showit)
456     [[MMBackend sharedInstance] showTabBar:showit];
460 // -- Clipboard -------------------------------------------------------------
463     void
464 clip_mch_lose_selection(VimClipboard *cbd)
469     int
470 clip_mch_own_selection(VimClipboard *cbd)
472     return 0;
476     void
477 clip_mch_request_selection(VimClipboard *cbd)
479     NSPasteboard *pb = [NSPasteboard generalPasteboard];
480     NSString *pbType = [pb availableTypeFromArray:
481             [NSArray arrayWithObject:NSStringPboardType]];
482     if (pbType) {
483         NSMutableString *string =
484                 [[pb stringForType:NSStringPboardType] mutableCopy];
486         // Replace unrecognized end-of-line sequences with \x0a (line feed).
487         NSRange range = { 0, [string length] };
488         unsigned n = [string replaceOccurrencesOfString:@"\x0d\x0a"
489                                              withString:@"\x0a" options:0
490                                                   range:range];
491         if (0 == n) {
492             n = [string replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
493                                            options:0 range:range];
494         }
495         
496         // Scan for newline character to decide whether the string should be
497         // pasted linewise or characterwise.
498         int type = MCHAR;
499         if (0 < n || NSNotFound != [string rangeOfString:@"\n"].location)
500             type = MLINE;
502         char_u *str = (char_u*)[string UTF8String];
503         int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
505 #ifdef FEAT_MBYTE
506         if (input_conv.vc_type != CONV_NONE)
507             str = string_convert(&input_conv, str, &len);
508 #endif
510         if (str)
511             clip_yank_selection(type, str, len, cbd);
513 #ifdef FEAT_MBYTE
514         if (input_conv.vc_type != CONV_NONE)
515             vim_free(str);
516 #endif
517     }
522  * Send the current selection to the clipboard.
523  */
524     void
525 clip_mch_set_selection(VimClipboard *cbd)
527     // If the '*' register isn't already filled in, fill it in now.
528     cbd->owned = TRUE;
529     clip_get_selection(cbd);
530     cbd->owned = FALSE;
531     
532     // Get the text to put on the pasteboard.
533     long_u llen = 0; char_u *str = 0;
534     int type = clip_convert_selection(&str, &llen, cbd);
535     if (type < 0)
536         return;
538     // TODO: Avoid overflow.
539     int len = (int)llen;
540 #ifdef FEAT_MBYTE
541     if (output_conv.vc_type != CONV_NONE) {
542         char_u *conv_str = string_convert(&output_conv, str, &len);
543         if (conv_str) {
544             vim_free(str);
545             str = conv_str;
546         }
547     }
548 #endif
550     if (len > 0) {
551         NSString *string = [[NSString alloc]
552             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
554         NSPasteboard *pb = [NSPasteboard generalPasteboard];
555         [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType]
556                    owner:nil];
557         [pb setString:string forType:NSStringPboardType];
558         
559         [string release];
560     }
562     vim_free(str);
566 // -- Menu ------------------------------------------------------------------
570  * Add a sub menu to the menu bar.
571  */
572     void
573 gui_mch_add_menu(vimmenu_T *menu, int idx)
575     // HACK!  If menu has no parent, then we set the parent tag to the type of
576     // menu it is.  This will not mix up tag and type because pointers can not
577     // take values close to zero (and the tag is simply the value of the
578     // pointer).
579     int parent = (int)menu->parent;
580     if (!parent) {
581         parent = menu_is_popup(menu->name) ? MenuPopupType :
582                  menu_is_toolbar(menu->name) ? MenuToolbarType :
583                  MenuMenubarType;
584     }
586     char_u *dname = menu->dname;
587 #ifdef FEAT_MBYTE
588     dname = CONVERT_TO_UTF8(dname);
589 #endif
591     [[MMBackend sharedInstance]
592             addMenuWithTag:(int)menu parent:parent name:(char*)dname
593                    atIndex:idx];
595 #ifdef FEAT_MBYTE
596     CONVERT_TO_UTF8_FREE(dname);
597 #endif
602  * Add a menu item to a menu
603  */
604     void
605 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
607     // NOTE!  If 'iconfile' is not set but 'iconidx' is, use the name of the
608     // menu item.  (Should correspond to a stock item.)
609     char_u *icon = menu->iconfile ? menu->iconfile :
610                  menu->iconidx >= 0 ? menu->dname :
611                  NULL;
612     //char *name = menu_is_separator(menu->name) ? NULL : (char*)menu->dname;
613     char_u *name = menu->dname;
614     char_u *tip = menu->strings[MENU_INDEX_TIP]
615             ? menu->strings[MENU_INDEX_TIP] : menu->actext;
616     char_u *map_str = menu->strings[MENU_INDEX_NORMAL];
618 #ifdef FEAT_MBYTE
619     icon = CONVERT_TO_UTF8(icon);
620     name = CONVERT_TO_UTF8(name);
621     tip = CONVERT_TO_UTF8(tip);
622     map_str = CONVERT_TO_UTF8(map_str);
623 #endif
625     // HACK!  Check if menu is mapped to ':macaction actionName:'; if so, pass
626     // the action along so that MacVim can bind the menu item to this action.
627     // This means that if a menu item maps to an action in normal mode, then
628     // all other modes will also use the same action.
629     NSString *action = nil;
630     if (map_str) {
631         NSString *mapping = [NSString stringWithCString:(char*)map_str
632                                                encoding:NSUTF8StringEncoding];
633         NSArray *parts = [mapping componentsSeparatedByString:@" "];
634         if ([parts count] >=2 
635                 && [[parts objectAtIndex:0] hasPrefix:@":maca"]) {
636             action = [parts objectAtIndex:1];
637             action = [action stringByTrimmingCharactersInSet:
638                     [NSCharacterSet whitespaceAndNewlineCharacterSet]];
639             if (!gui_macvim_is_valid_action(action))
640                 action = nil;
641         }
642     }
644     [[MMBackend sharedInstance]
645             addMenuItemWithTag:(int)menu
646                         parent:(int)menu->parent
647                           name:(char*)name
648                            tip:(char*)tip
649                           icon:(char*)icon
650                  keyEquivalent:menu->mac_key
651                      modifiers:menu->mac_mods
652                         action:action
653                        atIndex:idx];
655 #ifdef FEAT_MBYTE
656     CONVERT_TO_UTF8_FREE(icon);
657     CONVERT_TO_UTF8_FREE(name);
658     CONVERT_TO_UTF8_FREE(tip);
659     CONVERT_TO_UTF8_FREE(map_str);
660 #endif
665  * Destroy the machine specific menu widget.
666  */
667     void
668 gui_mch_destroy_menu(vimmenu_T *menu)
670     [[MMBackend sharedInstance] removeMenuItemWithTag:(int)menu];
675  * Make a menu either grey or not grey.
676  */
677     void
678 gui_mch_menu_grey(vimmenu_T *menu, int grey)
680     /* Only update menu if the 'grey' state has changed to avoid having to pass
681      * lots of unnecessary data to MacVim.  (Skipping this test makes MacVim
682      * pause noticably on mode changes. */
683     if (menu->was_grey != grey)
684     {
685         menu->was_grey = grey;
686         [[MMBackend sharedInstance]
687                 enableMenuItemWithTag:(int)menu state:!grey];
688     }
693  * Make menu item hidden or not hidden
694  */
695     void
696 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
698     // HACK! There is no (obvious) way to hide a menu item, so simply
699     // enable/disable it instead.
700     gui_mch_menu_grey(menu, hidden);
705  * This is called when user right clicks.
706  */
707     void
708 gui_mch_show_popupmenu(vimmenu_T *menu)
710     char_u *name = menu->name;
711 #ifdef FEAT_MBYTE
712     name = CONVERT_TO_UTF8(name);
713 #endif
715     [[MMBackend sharedInstance] showPopupMenuWithName:(char*)name
716                                       atMouseLocation:YES];
718 #ifdef FEAT_MBYTE
719     CONVERT_TO_UTF8_FREE(name);
720 #endif
726  * This is called when a :popup command is executed.
727  */
728     void
729 gui_make_popup(char_u *path_name, int mouse_pos)
731 #ifdef FEAT_MBYTE
732     path_name = CONVERT_TO_UTF8(path_name);
733 #endif
735     [[MMBackend sharedInstance] showPopupMenuWithName:(char*)path_name
736                                       atMouseLocation:mouse_pos];
738 #ifdef FEAT_MBYTE
739     CONVERT_TO_UTF8_FREE(path_name);
740 #endif
745  * This is called after setting all the menus to grey/hidden or not.
746  */
747     void
748 gui_mch_draw_menubar(void)
750     // The (main) menu draws itself in Mac OS X.
754     void
755 gui_mch_enable_menu(int flag)
757     // The (main) menu is always enabled in Mac OS X.
761 #if 0
762     void
763 gui_mch_set_menu_pos(int x, int y, int w, int h)
765     // The (main) menu cannot be moved in Mac OS X.
767 #endif
770     void
771 gui_mch_show_toolbar(int showit)
773     int flags = 0;
774     if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
775     if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
776     if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
778     [[MMBackend sharedInstance] showToolbar:showit flags:flags];
784 // -- Fonts -----------------------------------------------------------------
788  * If a font is not going to be used, free its structure.
789  */
790     void
791 gui_mch_free_font(font)
792     GuiFont     font;
794     if (font != NOFONT) {
795         //NSLog(@"gui_mch_free_font(font=0x%x)", font);
796         [(NSFont*)font release];
797     }
802  * Get a font structure for highlighting.
803  */
804     GuiFont
805 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
807     //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
808     //        giveErrorIfMissing);
810     NSFont *font = gui_macvim_font_with_name(name);
811     if (font)
812         return (GuiFont)[font retain];
814     if (giveErrorIfMissing)
815         EMSG2(_(e_font), name);
817     return NOFONT;
821 #if defined(FEAT_EVAL) || defined(PROTO)
823  * Return the name of font "font" in allocated memory.
824  * Don't know how to get the actual name, thus use the provided name.
825  */
826     char_u *
827 gui_mch_get_fontname(GuiFont font, char_u *name)
829     if (name == NULL)
830         return NULL;
831     return vim_strsave(name);
833 #endif
837  * Initialise vim to use the font with the given name.  Return FAIL if the font
838  * could not be loaded, OK otherwise.
839  */
840     int
841 gui_mch_init_font(char_u *font_name, int fontset)
843     //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
845     if (font_name && STRCMP(font_name, "*") == 0) {
846         // :set gfn=* shows the font panel.
847         do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
848         return FAIL;
849     }
851     NSFont *font = gui_macvim_font_with_name(font_name);
852     if (font) {
853         [(NSFont*)gui.norm_font release];
854         gui.norm_font = (GuiFont)font;
856         // NOTE: MacVim keeps separate track of the normal and wide fonts.
857         // Unless the user changes 'guifontwide' manually, they are based on
858         // the same (normal) font.  Also note that each time the normal font is
859         // set, the advancement may change so the wide font needs to be updated
860         // as well (so that it is always twice the width of the normal font).
861         [[MMBackend sharedInstance] setFont:font];
862         [[MMBackend sharedInstance] setWideFont:
863                (NOFONT == gui.wide_font ? font : (NSFont*)gui.wide_font)];
865         return OK;
866     }
868     return FAIL;
873  * Set the current text font.
874  */
875     void
876 gui_mch_set_font(GuiFont font)
878     // Font selection is done inside MacVim...nothing here to do.
882     NSFont *
883 gui_macvim_font_with_name(char_u *name)
885     NSFont *font = nil;
886     NSString *fontName = MMDefaultFontName;
887     float size = MMDefaultFontSize;
888     BOOL parseFailed = NO;
890 #ifdef FEAT_MBYTE
891     name = CONVERT_TO_UTF8(name);
892 #endif
894     if (name) {
895         fontName = [NSString stringWithUTF8String:(char*)name];
897         NSArray *components = [fontName componentsSeparatedByString:@":"];
898         if ([components count] == 2) {
899             NSString *sizeString = [components lastObject];
900             if ([sizeString length] > 0
901                     && [sizeString characterAtIndex:0] == 'h') {
902                 sizeString = [sizeString substringFromIndex:1];
903                 if ([sizeString length] > 0) {
904                     size = [sizeString floatValue];
905                     fontName = [components objectAtIndex:0];
906                 }
907             } else {
908                 parseFailed = YES;
909             }
910         } else if ([components count] > 2) {
911             parseFailed = YES;
912         }
914         if (!parseFailed) {
915             // Replace underscores with spaces.
916             fontName = [[fontName componentsSeparatedByString:@"_"]
917                                      componentsJoinedByString:@" "];
918         }
919     }
921     if (!parseFailed && [fontName length] > 0) {
922         if (size < MMMinFontSize) size = MMMinFontSize;
923         if (size > MMMaxFontSize) size = MMMaxFontSize;
925         font = [NSFont fontWithName:fontName size:size];
927         if (!font && MMDefaultFontName == fontName) {
928             // If for some reason the MacVim default font is not in the app
929             // bundle, then fall back on the system default font.
930             font = [NSFont userFixedPitchFontOfSize:0];
931         }
932     }
934 #ifdef FEAT_MBYTE
935     CONVERT_TO_UTF8_FREE(name);
936 #endif
938     return font;
941 // -- Scrollbars ------------------------------------------------------------
944     void
945 gui_mch_create_scrollbar(
946         scrollbar_T *sb,
947         int orient)     /* SBAR_VERT or SBAR_HORIZ */
949     [[MMBackend sharedInstance] 
950             createScrollbarWithIdentifier:sb->ident type:sb->type];
954     void
955 gui_mch_destroy_scrollbar(scrollbar_T *sb)
957     [[MMBackend sharedInstance] 
958             destroyScrollbarWithIdentifier:sb->ident];
962     void
963 gui_mch_enable_scrollbar(
964         scrollbar_T     *sb,
965         int             flag)
967     [[MMBackend sharedInstance] 
968             showScrollbarWithIdentifier:sb->ident state:flag];
972     void
973 gui_mch_set_scrollbar_pos(
974         scrollbar_T *sb,
975         int x,
976         int y,
977         int w,
978         int h)
980     int pos = y;
981     int len = h;
982     if (SBAR_BOTTOM == sb->type) {
983         pos = x;
984         len = w; 
985     }
987     [[MMBackend sharedInstance] 
988             setScrollbarPosition:pos length:len identifier:sb->ident];
992     void
993 gui_mch_set_scrollbar_thumb(
994         scrollbar_T *sb,
995         long val,
996         long size,
997         long max)
999     [[MMBackend sharedInstance] 
1000             setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
1004 // -- Cursor ----------------------------------------------------------------
1008  * Draw a cursor without focus.
1009  */
1010     void
1011 gui_mch_draw_hollow_cursor(guicolor_T color)
1013     return [[MMBackend sharedInstance]
1014         drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
1015                fraction:100 color:color];
1020  * Draw part of a cursor, only w pixels wide, and h pixels high.
1021  */
1022     void
1023 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
1025     // HACK!  'w' and 'h' are always 1 since we do not tell Vim about the exact
1026     // font dimensions.  Thus these parameters are useless.  Instead we look at
1027     // the shape_table to determine the shape and size of the cursor (just like
1028     // gui_update_cursor() does).
1029     int idx = get_shape_idx(FALSE);
1030     int shape = MMInsertionPointBlock;
1031     switch (shape_table[idx].shape) {
1032         case SHAPE_HOR: shape = MMInsertionPointHorizontal; break;
1033         case SHAPE_VER: shape = MMInsertionPointVertical; break;
1034     }
1036     return [[MMBackend sharedInstance]
1037         drawCursorAtRow:gui.row column:gui.col shape:shape
1038                fraction:shape_table[idx].percentage color:color];
1043  * Cursor blink functions.
1045  * This is a simple state machine:
1046  * BLINK_NONE   not blinking at all
1047  * BLINK_OFF    blinking, cursor is not shown
1048  * BLINK_ON blinking, cursor is shown
1049  */
1050     void
1051 gui_mch_set_blinking(long wait, long on, long off)
1053     [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1058  * Start the cursor blinking.  If it was already blinking, this restarts the
1059  * waiting time and shows the cursor.
1060  */
1061     void
1062 gui_mch_start_blink(void)
1064     [[MMBackend sharedInstance] startBlink];
1069  * Stop the cursor blinking.  Show the cursor if it wasn't shown.
1070  */
1071     void
1072 gui_mch_stop_blink(void)
1074     [[MMBackend sharedInstance] stopBlink];
1078 // -- Mouse -----------------------------------------------------------------
1082  * Get current mouse coordinates in text window.
1083  */
1084     void
1085 gui_mch_getmouse(int *x, int *y)
1087     //NSLog(@"gui_mch_getmouse()");
1091     void
1092 gui_mch_setmouse(int x, int y)
1094     //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1098     void
1099 mch_set_mouse_shape(int shape)
1101     [[MMBackend sharedInstance] setMouseShape:shape];
1107 // -- Input Method ----------------------------------------------------------
1109 #if defined(USE_IM_CONTROL)
1111     void
1112 im_set_position(int row, int col)
1114     // The pre-edit area is a popup window which is displayed by MMTextView.
1115     [[MMBackend sharedInstance] setPreEditRow:row column:col];
1119     void
1120 im_set_active(int active)
1122     // Set roman or the system script if 'active' is TRUE or FALSE,
1123     // respectively.
1124     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1126     if (!p_imdisable && smRoman != systemScript)
1127         KeyScript(active ? smKeySysScript : smKeyRoman);
1131     int
1132 im_get_status(void)
1134     // IM is active whenever the current script is the system script and the
1135     // system script isn't roman.  (Hence IM can only be active when using
1136     // non-roman scripts.)
1137     SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
1138     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1140     return currentScript != smRoman && currentScript == systemScript;
1143 #endif // defined(USE_IM_CONTROL)
1148 // -- Unsorted --------------------------------------------------------------
1151     void
1152 ex_macaction(eap)
1153     exarg_T     *eap;
1155     if (!gui.in_use) {
1156         EMSG(_("E???: Command only available in GUI mode"));
1157         return;
1158     }
1160     char_u *arg = eap->arg;
1161 #ifdef FEAT_MBYTE
1162     arg = CONVERT_TO_UTF8(arg);
1163 #endif
1165     NSString *name = [NSString stringWithCString:(char*)arg
1166                                         encoding:NSUTF8StringEncoding];
1167     if (gui_macvim_is_valid_action(name)) {
1168         [[MMBackend sharedInstance] executeActionWithName:name];
1169     } else {
1170         EMSG2(_("E???: \"%s\" is not a valid action"), eap->arg);
1171     }
1173 #ifdef FEAT_MBYTE
1174     arg = CONVERT_TO_UTF8(arg);
1175 #endif
1180  * Adjust gui.char_height (after 'linespace' was changed).
1181  */
1182     int
1183 gui_mch_adjust_charheight(void)
1185     [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1186     return OK;
1190     void
1191 gui_mch_beep(void)
1197 #ifdef FEAT_BROWSE
1199  * Pop open a file browser and return the file selected, in allocated memory,
1200  * or NULL if Cancel is hit.
1201  *  saving  - TRUE if the file will be saved to, FALSE if it will be opened.
1202  *  title   - Title message for the file browser dialog.
1203  *  dflt    - Default name of file.
1204  *  ext     - Default extension to be added to files without extensions.
1205  *  initdir - directory in which to open the browser (NULL = current dir)
1206  *  filter  - Filter for matched files to choose from.
1207  *  Has a format like this:
1208  *  "C Files (*.c)\0*.c\0"
1209  *  "All Files\0*.*\0\0"
1210  *  If these two strings were concatenated, then a choice of two file
1211  *  filters will be selectable to the user.  Then only matching files will
1212  *  be shown in the browser.  If NULL, the default allows all files.
1214  *  *NOTE* - the filter string must be terminated with TWO nulls.
1215  */
1216     char_u *
1217 gui_mch_browse(
1218     int saving,
1219     char_u *title,
1220     char_u *dflt,
1221     char_u *ext,
1222     char_u *initdir,
1223     char_u *filter)
1225     //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1226     //        " filter=%s", saving, title, dflt, ext, initdir, filter);
1228 #ifdef FEAT_MBYTE
1229     title = CONVERT_TO_UTF8(title);
1230     initdir = CONVERT_TO_UTF8(initdir);
1231 #endif
1233     char_u *s = (char_u*)[[MMBackend sharedInstance]
1234             browseForFileInDirectory:(char*)initdir title:(char*)title
1235                               saving:saving];
1237 #ifdef FEAT_MBYTE
1238     CONVERT_TO_UTF8_FREE(title);
1239     CONVERT_TO_UTF8_FREE(initdir);
1240 #endif
1242     return s;
1244 #endif /* FEAT_BROWSE */
1248     int
1249 gui_mch_dialog(
1250     int         type,
1251     char_u      *title,
1252     char_u      *message,
1253     char_u      *buttons,
1254     int         dfltbutton,
1255     char_u      *textfield)
1257     //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1258     //        "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1259     //        dfltbutton, textfield);
1261 #ifdef FEAT_MBYTE
1262     title = CONVERT_TO_UTF8(title);
1263     message = CONVERT_TO_UTF8(message);
1264     buttons = CONVERT_TO_UTF8(buttons);
1265     textfield = CONVERT_TO_UTF8(textfield);
1266 #endif
1268     int ret = [[MMBackend sharedInstance]
1269             presentDialogWithType:type
1270                             title:(char*)title
1271                           message:(char*)message
1272                           buttons:(char*)buttons
1273                         textField:(char*)textfield];
1275 #ifdef FEAT_MBYTE
1276     CONVERT_TO_UTF8_FREE(title);
1277     CONVERT_TO_UTF8_FREE(message);
1278     CONVERT_TO_UTF8_FREE(buttons);
1279     CONVERT_TO_UTF8_FREE(textfield);
1280 #endif
1282     return ret;
1286     void
1287 gui_mch_flash(int msec)
1293  * Return the Pixel value (color) for the given color name.  This routine was
1294  * pretty much taken from example code in the Silicon Graphics OSF/Motif
1295  * Programmer's Guide.
1296  * Return INVALCOLOR when failed.
1297  */
1298     guicolor_T
1299 gui_mch_get_color(char_u *name)
1301 #ifdef FEAT_MBYTE
1302     name = CONVERT_TO_UTF8(name);
1303 #endif
1305     NSString *key = [NSString stringWithUTF8String:(char*)name];
1306     guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1308 #ifdef FEAT_MBYTE
1309     CONVERT_TO_UTF8_FREE(name);
1310 #endif
1312     return col;
1317  * Return the RGB value of a pixel as long.
1318  */
1319     long_u
1320 gui_mch_get_rgb(guicolor_T pixel)
1322     // This is only implemented so that vim can guess the correct value for
1323     // 'background' (which otherwise defaults to 'dark'); it is not used for
1324     // anything else (as far as I know).
1325     // The implementation is simple since colors are stored in an int as
1326     // "rrggbb".
1327     return pixel;
1332  * Get the screen dimensions.
1333  * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1334  * Is there no way to find out how wide the borders really are?
1335  * TODO: Add live udate of those value on suspend/resume.
1336  */
1337     void
1338 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1340     //NSLog(@"gui_mch_get_screen_dimensions()");
1341     *screen_w = Columns;
1342     *screen_h = Rows;
1347  * Get the position of the top left corner of the window.
1348  */
1349     int
1350 gui_mch_get_winpos(int *x, int *y)
1352     *x = *y = 0;
1353     return OK;
1358  * Return OK if the key with the termcap name "name" is supported.
1359  */
1360     int
1361 gui_mch_haskey(char_u *name)
1363     BOOL ok = NO;
1365 #ifdef FEAT_MBYTE
1366     name = CONVERT_TO_UTF8(name);
1367 #endif
1369     NSString *value = [NSString stringWithUTF8String:(char*)name];
1370     if (value)
1371         ok =  [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1373 #ifdef FEAT_MBYTE
1374     CONVERT_TO_UTF8_FREE(name);
1375 #endif
1377     return ok;
1382  * Iconify the GUI window.
1383  */
1384     void
1385 gui_mch_iconify(void)
1391  * Invert a rectangle from row r, column c, for nr rows and nc columns.
1392  */
1393     void
1394 gui_mch_invert_rectangle(int r, int c, int nr, int nc)
1399 #if defined(FEAT_EVAL) || defined(PROTO)
1401  * Bring the Vim window to the foreground.
1402  */
1403     void
1404 gui_mch_set_foreground(void)
1406     [[MMBackend sharedInstance] activate];
1408 #endif
1412     void
1413 gui_mch_set_shellsize(
1414     int         width,
1415     int         height,
1416     int         min_width,
1417     int         min_height,
1418     int         base_width,
1419     int         base_height,
1420     int         direction)
1422     //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1423     //        " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1424     //        width, height, min_width, min_height, base_width, base_height,
1425     //        direction);
1426     [[MMBackend sharedInstance] setRows:height columns:width];
1430     void
1431 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1436  * Set the position of the top left corner of the window to the given
1437  * coordinates.
1438  */
1439     void
1440 gui_mch_set_winpos(int x, int y)
1445 #ifdef FEAT_TITLE
1447  * Set the window title and icon.
1448  * (The icon is not taken care of).
1449  */
1450     void
1451 gui_mch_settitle(char_u *title, char_u *icon)
1453     //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1455 #ifdef FEAT_MBYTE
1456     title = CONVERT_TO_UTF8(title);
1457 #endif
1459     [[MMBackend sharedInstance] setWindowTitle:(char*)title];
1461 #ifdef FEAT_MBYTE
1462     CONVERT_TO_UTF8_FREE(title);
1463 #endif
1465 #endif
1468     void
1469 gui_mch_toggle_tearoffs(int enable)
1474     static BOOL
1475 gui_macvim_is_valid_action(NSString *action)
1477     static NSDictionary *actionDict = nil;
1479     if (!actionDict) {
1480         NSBundle *mainBundle = [NSBundle mainBundle];
1481         NSString *path = [mainBundle pathForResource:@"Actions"
1482                                               ofType:@"plist"];
1483         if (path) {
1484             actionDict = [[NSDictionary alloc] initWithContentsOfFile:path];
1485         } else {
1486             // Allocate bogus dictionary so that error only pops up once.
1487             actionDict = [NSDictionary new];
1488             EMSG(_("E???: Failed to load action dictionary"));
1489         }
1490     }
1492     return [actionDict objectForKey:action] != nil;
1496     void
1497 gui_mch_enter_fullscreen()
1499     [[MMBackend sharedInstance] enterFullscreen];
1503     void
1504 gui_mch_leave_fullscreen()
1506     [[MMBackend sharedInstance] leaveFullscreen];
1510     void
1511 gui_macvim_update_modified_flag()
1513     [[MMBackend sharedInstance] updateModifiedFlag];
1519 // -- Client/Server ---------------------------------------------------------
1521 #ifdef MAC_CLIENTSERVER
1524 // NOTE: Client/Server is only fully supported with a GUI.  Theoretically it
1525 // would be possible to make the server code work with terminal Vim, but it
1526 // would require that a run-loop is set up and checked.  This should not be
1527 // difficult to implement, simply call gui_mch_update() at opportune moments
1528 // and it will take care of the run-loop.  Another (bigger) problem with
1529 // supporting servers in terminal mode is that the server listing code talks to
1530 // MacVim (the GUI) to figure out which servers are running.
1535  * Register connection with 'name'.  The actual connection is named something
1536  * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1537  */
1538     void
1539 serverRegisterName(char_u *name)
1541 #ifdef FEAT_MBYTE
1542     name = CONVERT_TO_UTF8(name);
1543 #endif
1545     NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1546     [[MMBackend sharedInstance] registerServerWithName:svrName];
1548 #ifdef FEAT_MBYTE
1549     CONVERT_TO_UTF8_FREE(name);
1550 #endif
1555  * Send to an instance of Vim.
1556  * Returns 0 for OK, negative for an error.
1557  */
1558     int
1559 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1560         int *port, int asExpr, int silent)
1562 #ifdef FEAT_MBYTE
1563     name = CONVERT_TO_UTF8(name);
1564     cmd = CONVERT_TO_UTF8(cmd);
1565 #endif
1567     BOOL ok = [[MMBackend sharedInstance]
1568             sendToServer:[NSString stringWithUTF8String:(char*)name]
1569                   string:[NSString stringWithUTF8String:(char*)cmd]
1570                    reply:result
1571                     port:port
1572               expression:asExpr
1573                   silent:silent];
1575 #ifdef FEAT_MBYTE
1576     CONVERT_TO_UTF8_FREE(name);
1577     CONVERT_TO_UTF8_FREE(cmd);
1578 #endif
1580     return ok ? 0 : -1;
1585  * Ask MacVim for the names of all Vim servers.
1586  */
1587     char_u *
1588 serverGetVimNames(void)
1590     char_u *names = NULL;
1591     NSArray *list = [[MMBackend sharedInstance] serverList];
1593     if (list) {
1594         NSString *string = [list componentsJoinedByString:@"\n"];
1595         char_u *s = (char_u*)[string UTF8String];
1596 #ifdef FEAT_MBYTE
1597         s = CONVERT_FROM_UTF8(s);
1598 #endif
1599         names = vim_strsave(s);
1600 #ifdef FEAT_MBYTE
1601         CONVERT_FROM_UTF8_FREE(s);
1602 #endif
1603     }
1605     return names;
1610  * 'str' is a hex int representing the send port of the connection.
1611  */
1612     int
1613 serverStrToPort(char_u *str)
1615     int port = 0;
1617     sscanf((char *)str, "0x%x", &port);
1618     if (!port)
1619         EMSG2(_("E573: Invalid server id used: %s"), str);
1621     return port;
1626  * Check for replies from server with send port 'port'.
1627  * Return TRUE and a non-malloc'ed string if there is.  Else return FALSE.
1628  */
1629     int
1630 serverPeekReply(int port, char_u **str)
1632     NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1633     int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1635     if (str && len > 0) {
1636         *str = (char_u*)[reply UTF8String];
1638 #ifdef FEAT_MBYTE
1639         if (input_conv.vc_type != CONV_NONE) {
1640             char_u *s = string_convert(&input_conv, *str, &len);
1642             if (len > 0) {
1643                 // HACK! Since 's' needs to be freed we cannot simply set
1644                 // '*str = s' or memory will leak.  Instead, create a dummy
1645                 // NSData and return its 'bytes' pointer, then autorelease the
1646                 // NSData.
1647                 NSData *data = [NSData dataWithBytes:s length:len+1];
1648                 *str = (char_u*)[data bytes];
1649             }
1651             vim_free(s);
1652         }
1653 #endif
1654     }
1656     return reply != nil;
1661  * Wait for replies from server with send port 'port'.
1662  * Return 0 and the malloc'ed string when a reply is available.
1663  * Return -1 on error.
1664  */
1665     int
1666 serverReadReply(int port, char_u **str)
1668     NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1669     if (reply && str) {
1670         char_u *s = (char_u*)[reply UTF8String];
1671 #ifdef FEAT_MBYTE
1672         s = CONVERT_FROM_UTF8(s);
1673 #endif
1674         *str = vim_strsave(s);
1675 #ifdef FEAT_MBYTE
1676         CONVERT_FROM_UTF8_FREE(s);
1677 #endif
1678         return 0;
1679     }
1681     return -1;
1686  * Send a reply string (notification) to client with port given by "serverid".
1687  * Return -1 if the window is invalid.
1688  */
1689     int
1690 serverSendReply(char_u *serverid, char_u *reply)
1692     int retval = -1;
1693     int port = serverStrToPort(serverid);
1694     if (port > 0 && reply) {
1695 #ifdef FEAT_MBYTE
1696         reply = CONVERT_TO_UTF8(reply);
1697 #endif
1698         BOOL ok = [[MMBackend sharedInstance]
1699                 sendReply:[NSString stringWithUTF8String:(char*)reply]
1700                    toPort:port];
1701         retval = ok ? 0 : -1;
1702 #ifdef FEAT_MBYTE
1703         CONVERT_TO_UTF8_FREE(reply);
1704 #endif
1705     }
1707     return retval;
1710 #endif // MAC_CLIENTSERVER