Optimize speed when 'matchparen' is enabled.
[MacVim/jjgod.git] / src / MacVim / gui_macvim.m
blobb43f7850beccf5e6522f615d87b3bb644df55b05
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 #import <Foundation/Foundation.h>
12 #import "MMBackend.h"
13 #import "MacVim.h"
14 #import "vim.h"
18 // This constant controls how often [MMBackend update] may get called (see
19 // gui_mch_update()).
20 static NSTimeInterval MMUpdateTimeoutInterval = 0.1f;
23 static BOOL gui_macvim_is_valid_action(NSString *action);
27 // -- Initialization --------------------------------------------------------
30  * Parse the GUI related command-line arguments.  Any arguments used are
31  * deleted from argv, and *argc is decremented accordingly.  This is called
32  * when vim is started, whether or not the GUI has been started.
33  */
34     void
35 gui_mch_prepare(int *argc, char **argv)
37     //NSLog(@"gui_mch_prepare(argc=%d)", *argc);
39     // Set environment variables $VIM and $VIMRUNTIME
40     // NOTE!  If vim_getenv is called with one of these as parameters before
41     // they have been set here, they will most likely end up with the wrong
42     // values!
43     //
44     // TODO:
45     // - ensure this is called first to avoid above problem
46     // - encoding
48     NSString *path = [[[NSBundle mainBundle] resourcePath]
49         stringByAppendingPathComponent:@"vim"];
50     vim_setenv((char_u*)"VIM", (char_u*)[path UTF8String]);
52     path = [path stringByAppendingPathComponent:@"runtime"];
53     vim_setenv((char_u*)"VIMRUNTIME", (char_u*)[path UTF8String]);
58  * Check if the GUI can be started.  Called before gvimrc is sourced.
59  * Return OK or FAIL.
60  */
61     int
62 gui_mch_init_check(void)
64     //NSLog(@"gui_mch_init_check()");
65     return OK;
70  * Initialise the GUI.  Create all the windows, set up all the call-backs etc.
71  * Returns OK for success, FAIL when the GUI can't be started.
72  */
73     int
74 gui_mch_init(void)
76     //NSLog(@"gui_mch_init()");
78     if (![[MMBackend sharedInstance] checkin])
79         return FAIL;
81     // Force 'termencoding' to utf-8 (changes to 'tenc' are disallowed in
82     // 'option.c', so that ':set termencoding=...' is impossible).
83     set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
85     // Set values so that pixels and characters are in one-to-one
86     // correspondence (assuming all characters have the same dimensions).
87     gui.scrollbar_width = gui.scrollbar_height = 0;
89     gui.char_height = 1;
90     gui.char_width = 1;
91     gui.char_ascent = 0;
93     gui_mch_def_colors();
95     [[MMBackend sharedInstance]
96         setDefaultColorsBackground:gui.back_pixel foreground:gui.norm_pixel];
97     [[MMBackend sharedInstance] setBackgroundColor:gui.back_pixel];
98     [[MMBackend sharedInstance] setForegroundColor:gui.norm_pixel];
100     // NOTE: If this call is left out the cursor is opaque.
101     highlight_gui_started();
103     return OK;
108     void
109 gui_mch_exit(int rc)
111     //NSLog(@"gui_mch_exit(rc=%d)", rc);
113     [[MMBackend sharedInstance] exit];
118  * Open the GUI window which was created by a call to gui_mch_init().
119  */
120     int
121 gui_mch_open(void)
123     //NSLog(@"gui_mch_open()");
125     return [[MMBackend sharedInstance] openVimWindow];
129 // -- Updating --------------------------------------------------------------
133  * Catch up with any queued X events.  This may put keyboard input into the
134  * input buffer, call resize call-backs, trigger timers etc.  If there is
135  * nothing in the X event queue (& no timers pending), then we return
136  * immediately.
137  */
138 #define MM_LOG_UPDATE_STATS 0
139     void
140 gui_mch_update(void)
142     // NOTE: This function can get called A LOT (~1 call/ms) and unfortunately
143     // checking the run loop takes a long time, resulting in noticable slow
144     // downs if it is done every time this function is called.  Therefore we
145     // make sure that it is not done too often.
146     static NSDate *lastUpdateDate = nil;
147 #if MM_LOG_UPDATE_STATS
148     static int skipCount = 0;
149 #endif
151     if (lastUpdateDate && -[lastUpdateDate timeIntervalSinceNow] <
152             MMUpdateTimeoutInterval) {
153 #if MM_LOG_UPDATE_STATS
154         ++skipCount;
155 #endif
156         return;
157     }
159 #if MM_LOG_UPDATE_STATS
160     NSTimeInterval dt = -[lastUpdateDate timeIntervalSinceNow];
161     NSLog(@"Updating (last update %.2f seconds ago, skipped %d updates, "
162             "approx %.1f calls per second)",
163             dt, skipCount, dt > 0 ? skipCount/dt : 0);
164     skipCount = 0;
165 #endif
167     [[MMBackend sharedInstance] update];
169     [lastUpdateDate release];
170     lastUpdateDate = [[NSDate date] retain];
174 /* Flush any output to the screen */
175     void
176 gui_mch_flush(void)
178     [[MMBackend sharedInstance] flushQueue:NO];
182 /* Force flush output to MacVim.  Do not call this method unless absolutely
183  * necessary (use gui_mch_flush() instead). */
184     void
185 gui_macvim_force_flush(void)
187     [[MMBackend sharedInstance] flushQueue:YES];
192  * GUI input routine called by gui_wait_for_chars().  Waits for a character
193  * from the keyboard.
194  *  wtime == -1     Wait forever.
195  *  wtime == 0      This should never happen.
196  *  wtime > 0       Wait wtime milliseconds for a character.
197  * Returns OK if a character was found to be available within the given time,
198  * or FAIL otherwise.
199  */
200     int
201 gui_mch_wait_for_chars(int wtime)
203     // NOTE! In all likelihood Vim will take a nap when waitForInput: is
204     // called, so force a flush of the command queue here.
205     [[MMBackend sharedInstance] flushQueue:YES];
207     return [[MMBackend sharedInstance] waitForInput:wtime];
211 // -- Drawing ---------------------------------------------------------------
215  * Clear the whole text window.
216  */
217     void
218 gui_mch_clear_all(void)
220     [[MMBackend sharedInstance] clearAll];
225  * Clear a rectangular region of the screen from text pos (row1, col1) to
226  * (row2, col2) inclusive.
227  */
228     void
229 gui_mch_clear_block(int row1, int col1, int row2, int col2)
231     [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
232                                                     toRow:row2 column:col2];
237  * Delete the given number of lines from the given row, scrolling up any
238  * text further down within the scroll region.
239  */
240     void
241 gui_mch_delete_lines(int row, int num_lines)
243     [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
244             scrollBottom:gui.scroll_region_bot
245                     left:gui.scroll_region_left
246                    right:gui.scroll_region_right];
250     void
251 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
253 #if MM_ENABLE_CONV
254     char_u *conv_str = NULL;
255     if (output_conv.vc_type != CONV_NONE) {
256         conv_str = string_convert(&output_conv, s, &len);
257         if (conv_str)
258             s = conv_str;
259     }
260 #endif
262     [[MMBackend sharedInstance] replaceString:(char*)s length:len
263             row:row column:col flags:flags];
265 #if MM_ENABLE_CONV
266     if (conv_str)
267         vim_free(conv_str);
268 #endif
272     int
273 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
275     //
276     // Output chars until a wide char found.  If a wide char is found, output a
277     // zero-width space after it so that a wide char looks like two chars to
278     // MMTextStorage.  This way 1 char corresponds to 1 column.
279     //
281     int c;
282     int cn;
283     int cl;
284     int i;
285     int start = 0;
286     int endcol = col;
287     int startcol = col;
288     BOOL outPad = NO;
289     MMBackend *backend = [MMBackend sharedInstance];
290     static char ZeroWidthSpace[] = { 0xe2, 0x80, 0x8b };
291 #if MM_ENABLE_CONV
292     char_u *conv_str = NULL;
294     if (output_conv.vc_type != CONV_NONE) {
295         conv_str = string_convert(&output_conv, s, &len);
296         if (conv_str)
297             s = conv_str;
298     }
299 #endif
301     for (i = 0; i < len; i += cl) {
302         c = utf_ptr2char(s + i);
303         cl = utf_ptr2len(s + i);
304         cn = utf_char2cells(c);
306         if (!utf_iscomposing(c)) {
307             if (outPad) {
308                 outPad = NO;
309 #if 0
310                 NSString *string = [[NSString alloc]
311                         initWithBytesNoCopy:(void*)(s+start)
312                                      length:i-start
313                                    encoding:NSUTF8StringEncoding
314                                freeWhenDone:NO];
315                 NSLog(@"Flushing string=%@ len=%d row=%d col=%d end=%d",
316                         string, i-start, row, startcol, endcol);
317                 [string release];
318 #endif
319                 [backend replaceString:(char*)(s+start) length:i-start
320                         row:row column:startcol flags:flags];
321                 start = i;
322                 startcol = endcol;
323 #if 0
324                 NSLog(@"Padding len=%d row=%d col=%d", sizeof(ZeroWidthSpace),
325                         row, endcol-1);
326 #endif
327                 [backend replaceString:ZeroWidthSpace
328                              length:sizeof(ZeroWidthSpace)
329                         row:row column:endcol-1 flags:flags];
330             }
332             endcol += cn;
333         }
335         if (cn > 1) {
336 #if 0
337             NSLog(@"Wide char detected! (char=%C hex=%x cells=%d)", c, c, cn);
338 #endif
339             outPad = YES;
340         }
341     }
343 #if 0
344     if (row < 1) {
345         NSString *string = [[NSString alloc]
346                 initWithBytesNoCopy:(void*)(s+start)
347                              length:len-start
348                            encoding:NSUTF8StringEncoding
349                        freeWhenDone:NO];
350         NSLog(@"Output string=%@ len=%d row=%d col=%d", string, len-start, row,
351                 startcol);
352         [string release];
353     }
354 #endif
356     // Output remaining characters.
357     [backend replaceString:(char*)(s+start) length:len-start
358             row:row column:startcol flags:flags];
360     if (outPad) {
361 #if 0
362         NSLog(@"Padding len=%d row=%d col=%d", sizeof(ZeroWidthSpace), row,
363                 endcol-1);
364 #endif
365         [backend replaceString:ZeroWidthSpace
366                      length:sizeof(ZeroWidthSpace)
367                 row:row column:endcol-1 flags:flags];
368     }
370 #if MM_ENABLE_CONV
371     if (conv_str)
372         vim_free(conv_str);
373 #endif
375     return endcol - col;
380  * Insert the given number of lines before the given row, scrolling down any
381  * following text within the scroll region.
382  */
383     void
384 gui_mch_insert_lines(int row, int num_lines)
386     [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
387             scrollBottom:gui.scroll_region_bot
388                     left:gui.scroll_region_left
389                    right:gui.scroll_region_right];
394  * Set the current text foreground color.
395  */
396     void
397 gui_mch_set_fg_color(guicolor_T color)
399     [[MMBackend sharedInstance] setForegroundColor:color];
404  * Set the current text background color.
405  */
406     void
407 gui_mch_set_bg_color(guicolor_T color)
409     [[MMBackend sharedInstance] setBackgroundColor:color];
414  * Set the current text special color (used for underlines).
415  */
416     void
417 gui_mch_set_sp_color(guicolor_T color)
419     [[MMBackend sharedInstance] setSpecialColor:color];
424  * Set default colors.
425  */
426     void
427 gui_mch_def_colors()
429     MMBackend *backend = [MMBackend sharedInstance];
431     // The default colors are taken from system values
432     gui.def_norm_pixel = gui.norm_pixel = 
433         [backend lookupColorWithKey:@"MacTextColor"];
434     gui.def_back_pixel = gui.back_pixel = 
435         [backend lookupColorWithKey:@"MacTextBackgroundColor"];
440  * Called when the foreground or background color has been changed.
441  */
442     void
443 gui_mch_new_colors(void)
445     gui.def_back_pixel = gui.back_pixel;
446     gui.def_norm_pixel = gui.norm_pixel;
448     //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
449     //        gui.def_norm_pixel);
451     [[MMBackend sharedInstance]
452         setDefaultColorsBackground:gui.def_back_pixel
453                         foreground:gui.def_norm_pixel];
457 // -- Tabline ---------------------------------------------------------------
461  * Set the current tab to "nr".  First tab is 1.
462  */
463     void
464 gui_mch_set_curtab(int nr)
466     [[MMBackend sharedInstance] selectTab:nr];
471  * Return TRUE when tabline is displayed.
472  */
473     int
474 gui_mch_showing_tabline(void)
476     return [[MMBackend sharedInstance] tabBarVisible];
480  * Update the labels of the tabline.
481  */
482     void
483 gui_mch_update_tabline(void)
485     [[MMBackend sharedInstance] updateTabBar];
489  * Show or hide the tabline.
490  */
491     void
492 gui_mch_show_tabline(int showit)
494     [[MMBackend sharedInstance] showTabBar:showit];
498 // -- Clipboard -------------------------------------------------------------
501     void
502 clip_mch_lose_selection(VimClipboard *cbd)
507     int
508 clip_mch_own_selection(VimClipboard *cbd)
510     return 0;
514     void
515 clip_mch_request_selection(VimClipboard *cbd)
517     NSPasteboard *pb = [NSPasteboard generalPasteboard];
518     NSString *pbType = [pb availableTypeFromArray:
519             [NSArray arrayWithObject:NSStringPboardType]];
520     if (pbType) {
521         NSMutableString *string =
522                 [[pb stringForType:NSStringPboardType] mutableCopy];
524         // Replace unrecognized end-of-line sequences with \x0a (line feed).
525         NSRange range = { 0, [string length] };
526         unsigned n = [string replaceOccurrencesOfString:@"\x0d\x0a"
527                                              withString:@"\x0a" options:0
528                                                   range:range];
529         if (0 == n) {
530             n = [string replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
531                                            options:0 range:range];
532         }
533         
534         // Scan for newline character to decide whether the string should be
535         // pasted linewise or characterwise.
536         int type = MCHAR;
537         if (0 < n || NSNotFound != [string rangeOfString:@"\n"].location)
538             type = MLINE;
540         char_u *str = (char_u*)[string UTF8String];
541         int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
543 #if MM_ENABLE_CONV
544         if (input_conv.vc_type != CONV_NONE)
545             str = string_convert(&input_conv, str, &len);
546 #endif
548         if (str)
549             clip_yank_selection(type, str, len, cbd);
551 #if MM_ENABLE_CONV
552         if (input_conv.vc_type != CONV_NONE)
553             vim_free(str);
554 #endif
555     }
560  * Send the current selection to the clipboard.
561  */
562     void
563 clip_mch_set_selection(VimClipboard *cbd)
565     // If the '*' register isn't already filled in, fill it in now.
566     cbd->owned = TRUE;
567     clip_get_selection(cbd);
568     cbd->owned = FALSE;
569     
570     // Get the text to put on the pasteboard.
571     long_u llen = 0; char_u *str = 0;
572     int type = clip_convert_selection(&str, &llen, cbd);
573     if (type < 0)
574         return;
576     // TODO: Avoid overflow.
577     int len = (int)llen;
578 #if MM_ENABLE_CONV
579     if (output_conv.vc_type != CONV_NONE) {
580         char_u *conv_str = string_convert(&output_conv, str, &len);
581         if (conv_str) {
582             vim_free(str);
583             str = conv_str;
584         }
585     }
586 #endif
588     if (len > 0) {
589         NSString *string = [[NSString alloc]
590             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
592         NSPasteboard *pb = [NSPasteboard generalPasteboard];
593         [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType]
594                    owner:nil];
595         [pb setString:string forType:NSStringPboardType];
596         
597         [string release];
598     }
600     vim_free(str);
604 // -- Menu ------------------------------------------------------------------
608  * Add a sub menu to the menu bar.
609  */
610     void
611 gui_mch_add_menu(vimmenu_T *menu, int idx)
613     // HACK!  If menu has no parent, then we set the parent tag to the type of
614     // menu it is.  This will not mix up tag and type because pointers can not
615     // take values close to zero (and the tag is simply the value of the
616     // pointer).
617     int parent = (int)menu->parent;
618     if (!parent) {
619         parent = menu_is_popup(menu->name) ? MenuPopupType :
620                  menu_is_toolbar(menu->name) ? MenuToolbarType :
621                  MenuMenubarType;
622     }
624     char_u *dname = menu->dname;
625 #if MM_ENABLE_CONV
626     dname = CONVERT_TO_UTF8(dname);
627 #endif
629     [[MMBackend sharedInstance]
630             addMenuWithTag:(int)menu parent:parent name:(char*)dname
631                    atIndex:idx];
633 #if MM_ENABLE_CONV
634     CONVERT_TO_UTF8_FREE(dname);
635 #endif
640  * Add a menu item to a menu
641  */
642     void
643 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
645     // NOTE!  If 'iconfile' is not set but 'iconidx' is, use the name of the
646     // menu item.  (Should correspond to a stock item.)
647     char_u *icon = menu->iconfile ? menu->iconfile :
648                  menu->iconidx >= 0 ? menu->dname :
649                  NULL;
650     //char *name = menu_is_separator(menu->name) ? NULL : (char*)menu->dname;
651     char_u *name = menu->dname;
652     char_u *tip = menu->strings[MENU_INDEX_TIP]
653             ? menu->strings[MENU_INDEX_TIP] : menu->actext;
654     char_u *map_str = menu->strings[MENU_INDEX_NORMAL];
656 #if MM_ENABLE_CONV
657     icon = CONVERT_TO_UTF8(icon);
658     name = CONVERT_TO_UTF8(name);
659     tip = CONVERT_TO_UTF8(tip);
660     map_str = CONVERT_TO_UTF8(map_str);
661 #endif
663     // HACK!  Check if menu is mapped to ':macaction actionName:'; if so, pass
664     // the action along so that MacVim can bind the menu item to this action.
665     // This means that if a menu item maps to an action in normal mode, then
666     // all other modes will also use the same action.
667     NSString *action = nil;
668     if (map_str) {
669         NSString *mapping = [NSString stringWithCString:(char*)map_str
670                                                encoding:NSUTF8StringEncoding];
671         NSArray *parts = [mapping componentsSeparatedByString:@" "];
672         if ([parts count] >=2 
673                 && [[parts objectAtIndex:0] hasPrefix:@":maca"]) {
674             action = [parts objectAtIndex:1];
675             action = [action stringByTrimmingCharactersInSet:
676                     [NSCharacterSet whitespaceAndNewlineCharacterSet]];
677             if (!gui_macvim_is_valid_action(action))
678                 action = nil;
679         }
680     }
682     [[MMBackend sharedInstance]
683             addMenuItemWithTag:(int)menu
684                         parent:(int)menu->parent
685                           name:(char*)name
686                            tip:(char*)tip
687                           icon:(char*)icon
688                  keyEquivalent:menu->mac_key
689                      modifiers:menu->mac_mods
690                         action:action
691                        atIndex:idx];
693 #if MM_ENABLE_CONV
694     CONVERT_TO_UTF8_FREE(icon);
695     CONVERT_TO_UTF8_FREE(name);
696     CONVERT_TO_UTF8_FREE(tip);
697     CONVERT_TO_UTF8_FREE(map_str);
698 #endif
703  * Destroy the machine specific menu widget.
704  */
705     void
706 gui_mch_destroy_menu(vimmenu_T *menu)
708     [[MMBackend sharedInstance] removeMenuItemWithTag:(int)menu];
713  * Make a menu either grey or not grey.
714  */
715     void
716 gui_mch_menu_grey(vimmenu_T *menu, int grey)
718     /* Only update menu if the 'grey' state has changed to avoid having to pass
719      * lots of unnecessary data to MacVim.  (Skipping this test makes MacVim
720      * pause noticably on mode changes. */
721     if (menu->was_grey != grey)
722     {
723         menu->was_grey = grey;
724         [[MMBackend sharedInstance]
725                 enableMenuItemWithTag:(int)menu state:!grey];
726     }
731  * Make menu item hidden or not hidden
732  */
733     void
734 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
736     // HACK! There is no (obvious) way to hide a menu item, so simply
737     // enable/disable it instead.
738     gui_mch_menu_grey(menu, hidden);
743  * This is called when user right clicks.
744  */
745     void
746 gui_mch_show_popupmenu(vimmenu_T *menu)
748     char_u *name = menu->name;
749 #if MM_ENABLE_CONV
750     name = CONVERT_TO_UTF8(name);
751 #endif
753     [[MMBackend sharedInstance] showPopupMenuWithName:(char*)name
754                                       atMouseLocation:YES];
756 #if MM_ENABLE_CONV
757     CONVERT_TO_UTF8_FREE(name);
758 #endif
764  * This is called when a :popup command is executed.
765  */
766     void
767 gui_make_popup(char_u *path_name, int mouse_pos)
769 #if MM_ENABLE_CONV
770     path_name = CONVERT_TO_UTF8(path_name);
771 #endif
773     [[MMBackend sharedInstance] showPopupMenuWithName:(char*)path_name
774                                       atMouseLocation:mouse_pos];
776 #if MM_ENABLE_CONV
777     CONVERT_TO_UTF8_FREE(path_name);
778 #endif
783  * This is called after setting all the menus to grey/hidden or not.
784  */
785     void
786 gui_mch_draw_menubar(void)
788     // The (main) menu draws itself in Mac OS X.
792     void
793 gui_mch_enable_menu(int flag)
795     // The (main) menu is always enabled in Mac OS X.
799 #if 0
800     void
801 gui_mch_set_menu_pos(int x, int y, int w, int h)
803     // The (main) menu cannot be moved in Mac OS X.
805 #endif
808     void
809 gui_mch_show_toolbar(int showit)
811     int flags = 0;
812     if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
813     if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
814     if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
816     [[MMBackend sharedInstance] showToolbar:showit flags:flags];
822 // -- Fonts -----------------------------------------------------------------
826  * If a font is not going to be used, free its structure.
827  */
828     void
829 gui_mch_free_font(font)
830     GuiFont     font;
836  * Get a font structure for highlighting.
837  */
838     GuiFont
839 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
841     //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
842     //        giveErrorIfMissing);
843     return 0;
847 #if defined(FEAT_EVAL) || defined(PROTO)
849  * Return the name of font "font" in allocated memory.
850  * Don't know how to get the actual name, thus use the provided name.
851  */
852     char_u *
853 gui_mch_get_fontname(GuiFont font, char_u *name)
855     //NSLog(@"gui_mch_get_fontname(font=%d, name=%s)", font, name);
856     return 0;
858 #endif
862  * Initialise vim to use the font with the given name.  Return FAIL if the font
863  * could not be loaded, OK otherwise.
864  */
865     int
866 gui_mch_init_font(char_u *font_name, int fontset)
868     //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
870     // HACK!  This gets called whenever the user types :set gfn=fontname, so
871     // for now we set the font here.
872     // TODO!  Proper font handling, the way Vim expects it.
874 #if MM_ENABLE_CONV
875     font_name = CONVERT_TO_UTF8(font_name);
876 #endif
878     BOOL ok = [[MMBackend sharedInstance] setFontWithName:(char*)font_name];
880 #if MM_ENABLE_CONV
881     CONVERT_TO_UTF8_FREE(font_name);
882 #endif
884     return ok;
889  * Set the current text font.
890  */
891     void
892 gui_mch_set_font(GuiFont font)
897 // -- Scrollbars ------------------------------------------------------------
900     void
901 gui_mch_create_scrollbar(
902         scrollbar_T *sb,
903         int orient)     /* SBAR_VERT or SBAR_HORIZ */
905     [[MMBackend sharedInstance] 
906             createScrollbarWithIdentifier:sb->ident type:sb->type];
910     void
911 gui_mch_destroy_scrollbar(scrollbar_T *sb)
913     [[MMBackend sharedInstance] 
914             destroyScrollbarWithIdentifier:sb->ident];
918     void
919 gui_mch_enable_scrollbar(
920         scrollbar_T     *sb,
921         int             flag)
923     [[MMBackend sharedInstance] 
924             showScrollbarWithIdentifier:sb->ident state:flag];
928     void
929 gui_mch_set_scrollbar_pos(
930         scrollbar_T *sb,
931         int x,
932         int y,
933         int w,
934         int h)
936     int pos = y;
937     int len = h;
938     if (SBAR_BOTTOM == sb->type) {
939         pos = x;
940         len = w; 
941     }
943     [[MMBackend sharedInstance] 
944             setScrollbarPosition:pos length:len identifier:sb->ident];
948     void
949 gui_mch_set_scrollbar_thumb(
950         scrollbar_T *sb,
951         long val,
952         long size,
953         long max)
955     [[MMBackend sharedInstance] 
956             setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
960 // -- Cursor ----------------------------------------------------------------
964  * Draw a cursor without focus.
965  */
966     void
967 gui_mch_draw_hollow_cursor(guicolor_T color)
969     return [[MMBackend sharedInstance]
970         drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
971                fraction:100 color:color];
976  * Draw part of a cursor, only w pixels wide, and h pixels high.
977  */
978     void
979 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
981     // HACK!  'w' and 'h' are always 1 since we do not tell Vim about the exact
982     // font dimensions.  Thus these parameters are useless.  Instead we look at
983     // the shape_table to determine the shape and size of the cursor (just like
984     // gui_update_cursor() does).
985     int idx = get_shape_idx(FALSE);
986     int shape = MMInsertionPointBlock;
987     switch (shape_table[idx].shape) {
988         case SHAPE_HOR: shape = MMInsertionPointHorizontal; break;
989         case SHAPE_VER: shape = MMInsertionPointVertical; break;
990     }
992     return [[MMBackend sharedInstance]
993         drawCursorAtRow:gui.row column:gui.col shape:shape
994                fraction:shape_table[idx].percentage color:color];
999  * Cursor blink functions.
1001  * This is a simple state machine:
1002  * BLINK_NONE   not blinking at all
1003  * BLINK_OFF    blinking, cursor is not shown
1004  * BLINK_ON blinking, cursor is shown
1005  */
1006     void
1007 gui_mch_set_blinking(long wait, long on, long off)
1009     [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1014  * Start the cursor blinking.  If it was already blinking, this restarts the
1015  * waiting time and shows the cursor.
1016  */
1017     void
1018 gui_mch_start_blink(void)
1020     [[MMBackend sharedInstance] startBlink];
1025  * Stop the cursor blinking.  Show the cursor if it wasn't shown.
1026  */
1027     void
1028 gui_mch_stop_blink(void)
1030     [[MMBackend sharedInstance] stopBlink];
1034 // -- Mouse -----------------------------------------------------------------
1038  * Get current mouse coordinates in text window.
1039  */
1040     void
1041 gui_mch_getmouse(int *x, int *y)
1043     //NSLog(@"gui_mch_getmouse()");
1047     void
1048 gui_mch_setmouse(int x, int y)
1050     //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1054     void
1055 mch_set_mouse_shape(int shape)
1057     [[MMBackend sharedInstance] setMouseShape:shape];
1063 // -- Unsorted --------------------------------------------------------------
1066     void
1067 ex_macaction(eap)
1068     exarg_T     *eap;
1070     if (!gui.in_use) {
1071         EMSG(_("E???: Command only available in GUI mode"));
1072         return;
1073     }
1075     char_u *arg = eap->arg;
1076 #if MM_ENABLE_CONV
1077     arg = CONVERT_TO_UTF8(arg);
1078 #endif
1080     NSString *name = [NSString stringWithCString:(char*)arg
1081                                         encoding:NSUTF8StringEncoding];
1082     if (gui_macvim_is_valid_action(name)) {
1083         [[MMBackend sharedInstance] executeActionWithName:name];
1084     } else {
1085         EMSG2(_("E???: \"%s\" is not a valid action"), eap->arg);
1086     }
1088 #if MM_ENABLE_CONV
1089     arg = CONVERT_TO_UTF8(arg);
1090 #endif
1095  * Adjust gui.char_height (after 'linespace' was changed).
1096  */
1097     int
1098 gui_mch_adjust_charheight(void)
1100     [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1101     return OK;
1105     void
1106 gui_mch_beep(void)
1112 #ifdef FEAT_BROWSE
1114  * Pop open a file browser and return the file selected, in allocated memory,
1115  * or NULL if Cancel is hit.
1116  *  saving  - TRUE if the file will be saved to, FALSE if it will be opened.
1117  *  title   - Title message for the file browser dialog.
1118  *  dflt    - Default name of file.
1119  *  ext     - Default extension to be added to files without extensions.
1120  *  initdir - directory in which to open the browser (NULL = current dir)
1121  *  filter  - Filter for matched files to choose from.
1122  *  Has a format like this:
1123  *  "C Files (*.c)\0*.c\0"
1124  *  "All Files\0*.*\0\0"
1125  *  If these two strings were concatenated, then a choice of two file
1126  *  filters will be selectable to the user.  Then only matching files will
1127  *  be shown in the browser.  If NULL, the default allows all files.
1129  *  *NOTE* - the filter string must be terminated with TWO nulls.
1130  */
1131     char_u *
1132 gui_mch_browse(
1133     int saving,
1134     char_u *title,
1135     char_u *dflt,
1136     char_u *ext,
1137     char_u *initdir,
1138     char_u *filter)
1140     //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1141     //        " filter=%s", saving, title, dflt, ext, initdir, filter);
1143 #if MM_ENABLE_CONV
1144     title = CONVERT_TO_UTF8(title);
1145     initdir = CONVERT_TO_UTF8(initdir);
1146 #endif
1148     char_u *s = (char_u*)[[MMBackend sharedInstance]
1149             browseForFileInDirectory:(char*)initdir title:(char*)title
1150                               saving:saving];
1152 #if MM_ENABLE_CONV
1153     CONVERT_TO_UTF8_FREE(title);
1154     CONVERT_TO_UTF8_FREE(initdir);
1155 #endif
1157     return s;
1159 #endif /* FEAT_BROWSE */
1163     int
1164 gui_mch_dialog(
1165     int         type,
1166     char_u      *title,
1167     char_u      *message,
1168     char_u      *buttons,
1169     int         dfltbutton,
1170     char_u      *textfield)
1172     //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1173     //        "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1174     //        dfltbutton, textfield);
1176 #if MM_ENABLE_CONV
1177     title = CONVERT_TO_UTF8(title);
1178     message = CONVERT_TO_UTF8(message);
1179     buttons = CONVERT_TO_UTF8(buttons);
1180     textfield = CONVERT_TO_UTF8(textfield);
1181 #endif
1183     int ret = [[MMBackend sharedInstance]
1184             presentDialogWithType:type
1185                             title:(char*)title
1186                           message:(char*)message
1187                           buttons:(char*)buttons
1188                         textField:(char*)textfield];
1190 #if MM_ENABLE_CONV
1191     CONVERT_TO_UTF8_FREE(title);
1192     CONVERT_TO_UTF8_FREE(message);
1193     CONVERT_TO_UTF8_FREE(buttons);
1194     CONVERT_TO_UTF8_FREE(textfield);
1195 #endif
1197     return ret;
1201     void
1202 gui_mch_flash(int msec)
1208  * Return the Pixel value (color) for the given color name.  This routine was
1209  * pretty much taken from example code in the Silicon Graphics OSF/Motif
1210  * Programmer's Guide.
1211  * Return INVALCOLOR when failed.
1212  */
1213     guicolor_T
1214 gui_mch_get_color(char_u *name)
1216 #if MM_ENABLE_CONV
1217     name = CONVERT_TO_UTF8(name);
1218 #endif
1220     NSString *key = [NSString stringWithUTF8String:(char*)name];
1221     guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1223 #if MM_ENABLE_CONV
1224     CONVERT_TO_UTF8_FREE(name);
1225 #endif
1227     return col;
1232  * Return the RGB value of a pixel as long.
1233  */
1234     long_u
1235 gui_mch_get_rgb(guicolor_T pixel)
1237     // This is only implemented so that vim can guess the correct value for
1238     // 'background' (which otherwise defaults to 'dark'); it is not used for
1239     // anything else (as far as I know).
1240     // The implementation is simple since colors are stored in an int as
1241     // "rrggbb".
1242     return pixel;
1247  * Get the screen dimensions.
1248  * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1249  * Is there no way to find out how wide the borders really are?
1250  * TODO: Add live udate of those value on suspend/resume.
1251  */
1252     void
1253 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1255     //NSLog(@"gui_mch_get_screen_dimensions()");
1256     *screen_w = Columns;
1257     *screen_h = Rows;
1262  * Get the position of the top left corner of the window.
1263  */
1264     int
1265 gui_mch_get_winpos(int *x, int *y)
1267     *x = *y = 0;
1268     return OK;
1273  * Return OK if the key with the termcap name "name" is supported.
1274  */
1275     int
1276 gui_mch_haskey(char_u *name)
1278     BOOL ok = NO;
1280 #if MM_ENABLE_CONV
1281     name = CONVERT_TO_UTF8(name);
1282 #endif
1284     NSString *value = [NSString stringWithUTF8String:(char*)name];
1285     if (value)
1286         ok =  [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1288 #if MM_ENABLE_CONV
1289     CONVERT_TO_UTF8_FREE(name);
1290 #endif
1292     return ok;
1297  * Iconify the GUI window.
1298  */
1299     void
1300 gui_mch_iconify(void)
1306  * Invert a rectangle from row r, column c, for nr rows and nc columns.
1307  */
1308     void
1309 gui_mch_invert_rectangle(int r, int c, int nr, int nc)
1314 #if defined(FEAT_EVAL) || defined(PROTO)
1316  * Bring the Vim window to the foreground.
1317  */
1318     void
1319 gui_mch_set_foreground(void)
1321     [[MMBackend sharedInstance] activate];
1323 #endif
1327     void
1328 gui_mch_set_shellsize(
1329     int         width,
1330     int         height,
1331     int         min_width,
1332     int         min_height,
1333     int         base_width,
1334     int         base_height,
1335     int         direction)
1337     //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1338     //        " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1339     //        width, height, min_width, min_height, base_width, base_height,
1340     //        direction);
1341     [[MMBackend sharedInstance] setRows:height columns:width];
1345     void
1346 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1351  * Set the position of the top left corner of the window to the given
1352  * coordinates.
1353  */
1354     void
1355 gui_mch_set_winpos(int x, int y)
1360 #ifdef FEAT_TITLE
1362  * Set the window title and icon.
1363  * (The icon is not taken care of).
1364  */
1365     void
1366 gui_mch_settitle(char_u *title, char_u *icon)
1368     //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1370 #if MM_ENABLE_CONV
1371     title = CONVERT_TO_UTF8(title);
1372 #endif
1374     [[MMBackend sharedInstance] setWindowTitle:(char*)title];
1376 #if MM_ENABLE_CONV
1377     CONVERT_TO_UTF8_FREE(title);
1378 #endif
1380 #endif
1383     void
1384 gui_mch_toggle_tearoffs(int enable)
1389     static BOOL
1390 gui_macvim_is_valid_action(NSString *action)
1392     static NSDictionary *actionDict = nil;
1394     if (!actionDict) {
1395         NSBundle *mainBundle = [NSBundle mainBundle];
1396         NSString *path = [mainBundle pathForResource:@"Actions"
1397                                               ofType:@"plist"];
1398         if (path) {
1399             actionDict = [[NSDictionary alloc] initWithContentsOfFile:path];
1400         } else {
1401             // Allocate bogus dictionary so that error only pops up once.
1402             actionDict = [NSDictionary new];
1403             EMSG(_("E???: Failed to load action dictionary"));
1404         }
1405     }
1407     return [actionDict objectForKey:action] != nil;
1411     void
1412 gui_mch_enter_fullscreen()
1414     [[MMBackend sharedInstance] enterFullscreen];
1418     void
1419 gui_mch_leave_fullscreen()
1421     [[MMBackend sharedInstance] leaveFullscreen];
1425     void
1426 gui_macvim_update_modified_flag()
1428     [[MMBackend sharedInstance] updateModifiedFlag];
1434 // -- Client/Server ---------------------------------------------------------
1436 #ifdef MAC_CLIENTSERVER
1439 // NOTE: Client/Server is only fully supported with a GUI.  Theoretically it
1440 // would be possible to make the server code work with terminal Vim, but it
1441 // would require that a run-loop is set up and checked.  This should not be
1442 // difficult to implement, simply call gui_mch_update() at opportune moments
1443 // and it will take care of the run-loop.  Another (bigger) problem with
1444 // supporting servers in terminal mode is that the server listing code talks to
1445 // MacVim (the GUI) to figure out which servers are running.
1450  * Register connection with 'name'.  The actual connection is named something
1451  * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1452  */
1453     void
1454 serverRegisterName(char_u *name)
1456 #if MM_ENABLE_CONV
1457     name = CONVERT_TO_UTF8(name);
1458 #endif
1460     NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1461     [[MMBackend sharedInstance] registerServerWithName:svrName];
1463 #if MM_ENABLE_CONV
1464     CONVERT_TO_UTF8_FREE(name);
1465 #endif
1470  * Send to an instance of Vim.
1471  * Returns 0 for OK, negative for an error.
1472  */
1473     int
1474 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1475         int *port, int asExpr, int silent)
1477 #if MM_ENABLE_CONV
1478     name = CONVERT_TO_UTF8(name);
1479     cmd = CONVERT_TO_UTF8(cmd);
1480 #endif
1482     BOOL ok = [[MMBackend sharedInstance]
1483             sendToServer:[NSString stringWithUTF8String:(char*)name]
1484                   string:[NSString stringWithUTF8String:(char*)cmd]
1485                    reply:result
1486                     port:port
1487               expression:asExpr
1488                   silent:silent];
1490 #if MM_ENABLE_CONV
1491     CONVERT_TO_UTF8_FREE(name);
1492     CONVERT_TO_UTF8_FREE(cmd);
1493 #endif
1495     return ok ? 0 : -1;
1500  * Ask MacVim for the names of all Vim servers.
1501  */
1502     char_u *
1503 serverGetVimNames(void)
1505     char_u *names = NULL;
1506     NSArray *list = [[MMBackend sharedInstance] serverList];
1508     if (list) {
1509         NSString *string = [list componentsJoinedByString:@"\n"];
1510         char_u *s = (char_u*)[string UTF8String];
1511 #if MM_ENABLE_CONV
1512         s = CONVERT_FROM_UTF8(s);
1513 #endif
1514         names = vim_strsave(s);
1515 #if MM_ENABLE_CONV
1516         CONVERT_FROM_UTF8_FREE(s);
1517 #endif
1518     }
1520     return names;
1525  * 'str' is a hex int representing the send port of the connection.
1526  */
1527     int
1528 serverStrToPort(char_u *str)
1530     int port = 0;
1532     sscanf((char *)str, "0x%x", &port);
1533     if (!port)
1534         EMSG2(_("E573: Invalid server id used: %s"), str);
1536     return port;
1541  * Check for replies from server with send port 'port'.
1542  * Return TRUE and a non-malloc'ed string if there is.  Else return FALSE.
1543  */
1544     int
1545 serverPeekReply(int port, char_u **str)
1547     NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1548     int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1550     if (str && len > 0) {
1551         *str = (char_u*)[reply UTF8String];
1553 #if MM_ENABLE_CONV
1554         if (input_conv.vc_type != CONV_NONE) {
1555             char_u *s = string_convert(&input_conv, *str, &len);
1557             if (len > 0) {
1558                 // HACK! Since 's' needs to be freed we cannot simply set
1559                 // '*str = s' or memory will leak.  Instead, create a dummy
1560                 // NSData and return its 'bytes' pointer, then autorelease the
1561                 // NSData.
1562                 NSData *data = [NSData dataWithBytes:s length:len+1];
1563                 *str = (char_u*)[data bytes];
1564             }
1566             vim_free(s);
1567         }
1568 #endif
1569     }
1571     return reply != nil;
1576  * Wait for replies from server with send port 'port'.
1577  * Return 0 and the malloc'ed string when a reply is available.
1578  * Return -1 on error.
1579  */
1580     int
1581 serverReadReply(int port, char_u **str)
1583     NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1584     if (reply && str) {
1585         char_u *s = (char_u*)[reply UTF8String];
1586 #if MM_ENABLE_CONV
1587         s = CONVERT_FROM_UTF8(s);
1588 #endif
1589         *str = vim_strsave(s);
1590 #if MM_ENABLE_CONV
1591         CONVERT_FROM_UTF8_FREE(s);
1592 #endif
1593         return 0;
1594     }
1596     return -1;
1601  * Send a reply string (notification) to client with port given by "serverid".
1602  * Return -1 if the window is invalid.
1603  */
1604     int
1605 serverSendReply(char_u *serverid, char_u *reply)
1607     int retval = -1;
1608     int port = serverStrToPort(serverid);
1609     if (port > 0 && reply) {
1610 #if MM_ENABLE_CONV
1611         reply = CONVERT_TO_UTF8(reply);
1612 #endif
1613         BOOL ok = [[MMBackend sharedInstance]
1614                 sendReply:[NSString stringWithUTF8String:(char*)reply]
1615                    toPort:port];
1616         retval = ok ? 0 : -1;
1617 #if MM_ENABLE_CONV
1618         CONVERT_TO_UTF8_FREE(reply);
1619 #endif
1620     }
1622     return retval;
1625 #endif // MAC_CLIENTSERVER