Updated info on Colors.plist
[MacVim/jjgod.git] / gui_macvim.m
blobda212fc937296691e42d419f49d5ab2f01c22287
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"
17 static BOOL gui_macvim_is_valid_action(NSString *action);
20 // -- Initialization --------------------------------------------------------
23  * Parse the GUI related command-line arguments.  Any arguments used are
24  * deleted from argv, and *argc is decremented accordingly.  This is called
25  * when vim is started, whether or not the GUI has been started.
26  */
27     void
28 gui_mch_prepare(int *argc, char **argv)
30     //NSLog(@"gui_mch_prepare(argc=%d)", *argc);
32     // Set environment variables $VIM and $VIMRUNTIME
33     // NOTE!  If vim_getenv is called with one of these as parameters before
34     // they have been set here, they will most likely end up with the wrong
35     // values!
36     //
37     // TODO:
38     // - ensure this is called first to avoid above problem
39     // - encoding
41     NSString *path = [[[NSBundle mainBundle] resourcePath]
42         stringByAppendingPathComponent:@"vim"];
43     vim_setenv((char_u*)"VIM", (char_u*)[path UTF8String]);
45     path = [path stringByAppendingPathComponent:@"runtime"];
46     vim_setenv((char_u*)"VIMRUNTIME", (char_u*)[path UTF8String]);
51  * Check if the GUI can be started.  Called before gvimrc is sourced.
52  * Return OK or FAIL.
53  */
54     int
55 gui_mch_init_check(void)
57     //NSLog(@"gui_mch_init_check()");
58     return OK;
63  * Initialise the GUI.  Create all the windows, set up all the call-backs etc.
64  * Returns OK for success, FAIL when the GUI can't be started.
65  */
66     int
67 gui_mch_init(void)
69     //NSLog(@"gui_mch_init()");
71     if (![[MMBackend sharedInstance] checkin])
72         return FAIL;
74     // HACK!  Force the 'termencoding to utf-8.  For the moment also force
75     // 'encoding', although this will change in the future.  The user can still
76     // change 'encoding'; doing so WILL crash the program.
77     set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
78     set_option_value((char_u *)"encoding", 0L, (char_u *)"utf-8", 0);
80     // Set values so that pixels and characters are in one-to-one
81     // correspondence (assuming all characters have the same dimensions).
82     gui.scrollbar_width = gui.scrollbar_height = 0;
84     gui.char_height = 1;
85     gui.char_width = 1;
86     gui.char_ascent = 0;
88     gui_mch_def_colors();
90     [[MMBackend sharedInstance]
91         setDefaultColorsBackground:gui.back_pixel foreground:gui.norm_pixel];
92     [[MMBackend sharedInstance] setBackgroundColor:gui.back_pixel];
93     [[MMBackend sharedInstance] setForegroundColor:gui.norm_pixel];
95     // NOTE: If this call is left out the cursor is opaque.
96     highlight_gui_started();
98     return OK;
103     void
104 gui_mch_exit(int rc)
106     //NSLog(@"gui_mch_exit(rc=%d)", rc);
108     [[MMBackend sharedInstance] exit];
113  * Open the GUI window which was created by a call to gui_mch_init().
114  */
115     int
116 gui_mch_open(void)
118     //NSLog(@"gui_mch_open()");
120     return [[MMBackend sharedInstance] openVimWindow];
124 // -- Updating --------------------------------------------------------------
128  * Catch up with any queued X events.  This may put keyboard input into the
129  * input buffer, call resize call-backs, trigger timers etc.  If there is
130  * nothing in the X event queue (& no timers pending), then we return
131  * immediately.
132  */
133     void
134 gui_mch_update(void)
136     // TODO: Ensure that this causes no problems.
137     [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
138                              beforeDate:[NSDate distantPast]];
142 /* Flush any output to the screen */
143     void
144 gui_mch_flush(void)
146     [[MMBackend sharedInstance] flushQueue:NO];
151  * GUI input routine called by gui_wait_for_chars().  Waits for a character
152  * from the keyboard.
153  *  wtime == -1     Wait forever.
154  *  wtime == 0      This should never happen.
155  *  wtime > 0       Wait wtime milliseconds for a character.
156  * Returns OK if a character was found to be available within the given time,
157  * or FAIL otherwise.
158  */
159     int
160 gui_mch_wait_for_chars(int wtime)
162     // NOTE! In all likelihood Vim will take a nap when waitForInput: is
163     // called, so force a flush of the command queue here.
164     [[MMBackend sharedInstance] flushQueue:YES];
166     return [[MMBackend sharedInstance] waitForInput:wtime];
170 // -- Drawing ---------------------------------------------------------------
174  * Clear the whole text window.
175  */
176     void
177 gui_mch_clear_all(void)
179     [[MMBackend sharedInstance] clearAll];
184  * Clear a rectangular region of the screen from text pos (row1, col1) to
185  * (row2, col2) inclusive.
186  */
187     void
188 gui_mch_clear_block(int row1, int col1, int row2, int col2)
190     [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
191                                                     toRow:row2 column:col2];
196  * Delete the given number of lines from the given row, scrolling up any
197  * text further down within the scroll region.
198  */
199     void
200 gui_mch_delete_lines(int row, int num_lines)
202     [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
203             scrollBottom:gui.scroll_region_bot
204                     left:gui.scroll_region_left
205                    right:gui.scroll_region_right];
209     void
210 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
212     [[MMBackend sharedInstance] replaceString:(char*)s length:len
213             row:row column:col flags:flags];
217     int
218 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
220 #if 0
221     NSString *string = [[NSString alloc]
222             initWithBytesNoCopy:(void*)s
223                          length:len
224                        encoding:NSUTF8StringEncoding
225                    freeWhenDone:NO];
226     int cells = [string length];
227     [string release];
229     NSLog(@"gui_macvim_draw_string(row=%d, col=%d, len=%d, cells=%d, flags=%d)",
230             row, col, len, cells, flags);
232     [[MMBackend sharedInstance] replaceString:(char*)s length:len
233             row:row column:col flags:flags];
235     return cells;
236 #elif 0
237     int c;
238     int cn;
239     int cl;
240     int i;
241     BOOL wide = NO;
242     int start = 0;
243     int endcol = col;
244     int startcol = col;
245     MMBackend *backend = [MMBackend sharedInstance];
247     for (i = 0; i < len; i += cl) {
248         c = utf_ptr2char(s + i);
249         cl = utf_ptr2len(s + i);
250         cn = utf_char2cells(c);
251         comping = utf_iscomposing(c);
253         if (!comping)
254             endcol += cn;
256         if (cn > 1 && !wide) {
257             // Start of wide characters.
258             wide = YES;
260             // Output non-wide characters.
261             if (start > i) {
262                 NSLog(@"Outputting %d non-wide chars (%d bytes)",
263                         endcol-startcol, start-i);
264                 [backend replaceString:(char*)(s+start) length:start-i
265                         row:row column:startcol flags:flags];
266                 startcol = endcol;
267                 start = i;
268             }
269         } else if (cn <= 1 && !comping && wide) {
270             // End of wide characters.
271             wide = NO;
273             // Output wide characters.
274             if (start > i) {
275                 NSLog(@"Outputting %d wide chars (%d bytes)",
276                         endcol-startcol, start-i);
277                 [backend replaceString:(char*)(s+start) length:start-i
278                         row:row column:startcol flags:(flags|0x80)];
279                 startcol = endcol;
280                 start = i;
281             }
282         }
283     }
285     // Output remaining characters.
286     flags = wide ? flags|0x80 : flags;
287     NSLog(@"Outputting %d %s chars (%d bytes)", endcol-startcol, wide ? "wide"
288             : "non-wide", len-start);
289     [backend replaceString:(char*)(s+start) length:len-start
290             row:row column:startcol flags:flags];
292     return endcol - col;
293 #elif 1
294     //
295     // Output chars until a wide char found.  If a wide char is found, output a
296     // zero-width space after it so that a wide char looks like two chars to
297     // MMTextStorage.  This way 1 char corresponds to 1 column.
298     //
300     int c;
301     int cn;
302     int cl;
303     int i;
304     int start = 0;
305     int endcol = col;
306     int startcol = col;
307     BOOL outPad = NO;
308     MMBackend *backend = [MMBackend sharedInstance];
309     static char ZeroWidthSpace[] = { 0xe2, 0x80, 0x8b };
310 #if MM_ENABLE_CONV
311     char_u *conv_str = NULL;
313     if (output_conv.vc_type != CONV_NONE) {
314         char_u *conv_str = string_convert(&output_conv, s, &len);
315         if (conv_str)
316             s = conv_str;
317     }
318 #endif
320     for (i = 0; i < len; i += cl) {
321         c = utf_ptr2char(s + i);
322         cl = utf_ptr2len(s + i);
323         cn = utf_char2cells(c);
325         if (!utf_iscomposing(c)) {
326             if (outPad) {
327                 outPad = NO;
328 #if 0
329                 NSString *string = [[NSString alloc]
330                         initWithBytesNoCopy:(void*)(s+start)
331                                      length:i-start
332                                    encoding:NSUTF8StringEncoding
333                                freeWhenDone:NO];
334                 NSLog(@"Flushing string=%@ len=%d row=%d col=%d end=%d",
335                         string, i-start, row, startcol, endcol);
336                 [string release];
337 #endif
338                 [backend replaceString:(char*)(s+start) length:i-start
339                         row:row column:startcol flags:flags];
340                 start = i;
341                 startcol = endcol;
342 #if 0
343                 NSLog(@"Padding len=%d row=%d col=%d", sizeof(ZeroWidthSpace),
344                         row, endcol-1);
345 #endif
346                 [backend replaceString:ZeroWidthSpace
347                              length:sizeof(ZeroWidthSpace)
348                         row:row column:endcol-1 flags:flags];
349             }
351             endcol += cn;
352         }
354         if (cn > 1) {
355 #if 0
356             NSLog(@"Wide char detected! (char=%C hex=%x cells=%d)", c, c, cn);
357 #endif
358             outPad = YES;
359         }
360     }
362 #if 0
363     if (row < 1) {
364         NSString *string = [[NSString alloc]
365                 initWithBytesNoCopy:(void*)(s+start)
366                              length:len-start
367                            encoding:NSUTF8StringEncoding
368                        freeWhenDone:NO];
369         NSLog(@"Output string=%@ len=%d row=%d col=%d", string, len-start, row,
370                 startcol);
371         [string release];
372     }
373 #endif
375     // Output remaining characters.
376     [backend replaceString:(char*)(s+start) length:len-start
377             row:row column:startcol flags:flags];
379     if (outPad) {
380 #if 0
381         NSLog(@"Padding len=%d row=%d col=%d", sizeof(ZeroWidthSpace), row,
382                 endcol-1);
383 #endif
384         [backend replaceString:ZeroWidthSpace
385                      length:sizeof(ZeroWidthSpace)
386                 row:row column:endcol-1 flags:flags];
387     }
389 #if MM_ENABLE_CONV
390     if (conv_str)
391         vim_free(conv_str);
392 #endif
394     return endcol - col;
395 #else
396     // This will fail abysmally when wide or composing characters are used.
397     [[MMBackend sharedInstance]
398             replaceString:(char*)s length:len row:row column:col flags:flags];
400     int i, c, cl, cn, cells = 0;
401     for (i = 0; i < len; i += cl) {
402         c = utf_ptr2char(s + i);
403         cl = utf_ptr2len(s + i);
404         cn = utf_char2cells(c);
406         if (!utf_iscomposing(c))
407             cells += cn;
408     }
410     return cells;
411 #endif
416  * Insert the given number of lines before the given row, scrolling down any
417  * following text within the scroll region.
418  */
419     void
420 gui_mch_insert_lines(int row, int num_lines)
422     [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
423             scrollBottom:gui.scroll_region_bot
424                     left:gui.scroll_region_left
425                    right:gui.scroll_region_right];
430  * Set the current text foreground color.
431  */
432     void
433 gui_mch_set_fg_color(guicolor_T color)
435     [[MMBackend sharedInstance] setForegroundColor:color];
440  * Set the current text background color.
441  */
442     void
443 gui_mch_set_bg_color(guicolor_T color)
445     [[MMBackend sharedInstance] setBackgroundColor:color];
450  * Set the current text special color (used for underlines).
451  */
452     void
453 gui_mch_set_sp_color(guicolor_T color)
455     [[MMBackend sharedInstance] setSpecialColor:color];
460  * Set default colors.
461  */
462     void
463 gui_mch_def_colors()
465     MMBackend *backend = [MMBackend sharedInstance];
467     // The default colors are taken from system values
468     gui.def_norm_pixel = gui.norm_pixel = 
469         [backend lookupColorWithKey:@"MacTextColor"];
470     gui.def_back_pixel = gui.back_pixel = 
471         [backend lookupColorWithKey:@"MacTextBackgroundColor"];
473     // Set the text selection color to match the system preferences.
474     // TODO: Is there a better way to do this?
475     do_cmdline_cmd((char_u*)"hi Visual guibg=MacSelectedTextBackgroundColor");
480  * Called when the foreground or background color has been changed.
481  */
482     void
483 gui_mch_new_colors(void)
485     gui.def_back_pixel = gui.back_pixel;
486     gui.def_norm_pixel = gui.norm_pixel;
488     //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
489     //        gui.def_norm_pixel);
491     [[MMBackend sharedInstance]
492         setDefaultColorsBackground:gui.def_back_pixel
493                         foreground:gui.def_norm_pixel];
497 // -- Tabline ---------------------------------------------------------------
501  * Set the current tab to "nr".  First tab is 1.
502  */
503     void
504 gui_mch_set_curtab(int nr)
506     [[MMBackend sharedInstance] selectTab:nr];
511  * Return TRUE when tabline is displayed.
512  */
513     int
514 gui_mch_showing_tabline(void)
516     return [[MMBackend sharedInstance] tabBarVisible];
520  * Update the labels of the tabline.
521  */
522     void
523 gui_mch_update_tabline(void)
525     [[MMBackend sharedInstance] updateTabBar];
529  * Show or hide the tabline.
530  */
531     void
532 gui_mch_show_tabline(int showit)
534     [[MMBackend sharedInstance] showTabBar:showit];
538 // -- Clipboard -------------------------------------------------------------
541     void
542 clip_mch_lose_selection(VimClipboard *cbd)
547     int
548 clip_mch_own_selection(VimClipboard *cbd)
550     return 0;
554     void
555 clip_mch_request_selection(VimClipboard *cbd)
557     NSPasteboard *pb = [NSPasteboard generalPasteboard];
558     NSString *pbType = [pb availableTypeFromArray:
559             [NSArray arrayWithObject:NSStringPboardType]];
560     if (pbType) {
561         NSMutableString *string =
562                 [[pb stringForType:NSStringPboardType] mutableCopy];
564         // Replace unrecognized end-of-line sequences with \x0a (line feed).
565         NSRange range = { 0, [string length] };
566         unsigned n = [string replaceOccurrencesOfString:@"\x0d\x0a"
567                                              withString:@"\x0a" options:0
568                                                   range:range];
569         if (0 == n) {
570             n = [string replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
571                                            options:0 range:range];
572         }
573         
574         // Scan for newline character to decide whether the string should be
575         // pasted linewise or characterwise.
576         int type = MCHAR;
577         if (0 < n || NSNotFound != [string rangeOfString:@"\n"].location)
578             type = MLINE;
580         char_u *str = (char_u*)[string UTF8String];
581         int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
583 #if MM_ENABLE_CONV
584         if (input_conv.vc_type != CONV_NONE) {
585             NSLog(@"Converting from: '%@'", string);
586             char_u *conv_str = string_convert(&input_conv, str, &len);
587             if (conv_str) {
588                 NSLog(@"           to: '%s'", conv_str);
589                 clip_yank_selection(type, conv_str, len, cbd);
590                 vim_free(conv_str);
591                 return;
592             }
593         }
594 #endif
596         clip_yank_selection(type, str, len, cbd);
597     }
602  * Send the current selection to the clipboard.
603  */
604     void
605 clip_mch_set_selection(VimClipboard *cbd)
607     // If the '*' register isn't already filled in, fill it in now.
608     cbd->owned = TRUE;
609     clip_get_selection(cbd);
610     cbd->owned = FALSE;
611     
612     // Get the text to put on the pasteboard.
613     long_u llen = 0; char_u *str = 0;
614     int type = clip_convert_selection(&str, &llen, cbd);
615     if (type < 0)
616         return;
618     // TODO: Avoid overflow.
619     int len = (int)llen;
620 #if MM_ENABLE_CONV
621     if (output_conv.vc_type != CONV_NONE) {
622         char_u *conv_str = string_convert(&output_conv, str, &len);
623         if (conv_str) {
624             vim_free(str);
625             str = conv_str;
626         }
627     }
628 #endif
630     if (len > 0) {
631         NSString *string = [[NSString alloc]
632             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
634         NSPasteboard *pb = [NSPasteboard generalPasteboard];
635         [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType]
636                    owner:nil];
637         [pb setString:string forType:NSStringPboardType];
638         
639         [string release];
640     }
642     vim_free(str);
646 // -- Menu ------------------------------------------------------------------
650  * Add a sub menu to the menu bar.
651  */
652     void
653 gui_mch_add_menu(vimmenu_T *menu, int idx)
655     // HACK!  If menu has no parent, then we set the parent tag to the type of
656     // menu it is.  This will not mix up tag and type because pointers can not
657     // take values close to zero (and the tag is simply the value of the
658     // pointer).
659     int parent = (int)menu->parent;
660     if (!parent) {
661         parent = menu_is_popup(menu->name) ? MenuPopupType :
662                  menu_is_toolbar(menu->name) ? MenuToolbarType :
663                  MenuMenubarType;
664     }
666     [[MMBackend sharedInstance]
667             addMenuWithTag:(int)menu parent:parent name:(char*)menu->dname
668                    atIndex:idx];
673  * Add a menu item to a menu
674  */
675     void
676 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
678     // NOTE!  If 'iconfile' is not set but 'iconidx' is, use the name of the
679     // menu item.  (Should correspond to a stock item.)
680     char *icon = menu->iconfile ? (char*)menu->iconfile :
681                  menu->iconidx >= 0 ? (char*)menu->dname :
682                  NULL;
683     //char *name = menu_is_separator(menu->name) ? NULL : (char*)menu->dname;
684     char *name = (char*)menu->dname;
685     char *tip = menu->strings[MENU_INDEX_TIP]
686             ? (char*)menu->strings[MENU_INDEX_TIP] : (char*)menu->actext;
688     // HACK!  Check if menu is mapped to ':action actionName:'; if so, pass the
689     // action along so that MacVim can bind the menu item to this action.  This
690     // means that if a menu item maps to an action in normal mode, then all
691     // other modes will also use the same action.
692     NSString *action = nil;
693     char_u *map_str = menu->strings[MENU_INDEX_NORMAL];
694     if (map_str) {
695         NSString *mapping = [NSString stringWithCString:(char*)map_str
696                                                encoding:NSUTF8StringEncoding];
697         NSArray *parts = [mapping componentsSeparatedByString:@" "];
698         if ([parts count] >=2 
699                 && [[parts objectAtIndex:0] isEqual:@":action"]) {
700             action = [parts objectAtIndex:1];
701             action = [action stringByTrimmingCharactersInSet:
702                     [NSCharacterSet whitespaceAndNewlineCharacterSet]];
703             if (!gui_macvim_is_valid_action(action))
704                 action = nil;
705         }
706     }
708     [[MMBackend sharedInstance]
709             addMenuItemWithTag:(int)menu
710                         parent:(int)menu->parent
711                           name:name
712                            tip:tip
713                           icon:(char*)icon
714                  keyEquivalent:menu->ke_key
715                      modifiers:menu->ke_mods
716                         action:action
717                        atIndex:idx];
722  * Destroy the machine specific menu widget.
723  */
724     void
725 gui_mch_destroy_menu(vimmenu_T *menu)
727     [[MMBackend sharedInstance] removeMenuItemWithTag:(int)menu];
732  * Make a menu either grey or not grey.
733  */
734     void
735 gui_mch_menu_grey(vimmenu_T *menu, int grey)
737     [[MMBackend sharedInstance]
738             enableMenuItemWithTag:(int)menu state:!grey];
743  * Make menu item hidden or not hidden
744  */
745     void
746 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
748     // HACK! There is no (obvious) way to hide a menu item, so simply
749     // enable/disable it instead.
750     [[MMBackend sharedInstance]
751             enableMenuItemWithTag:(int)menu state:!hidden];
756  * This is called when user right clicks.
757  */
758     void
759 gui_mch_show_popupmenu(vimmenu_T *menu)
761     [[MMBackend sharedInstance] showPopupMenuWithName:(char*)menu->name
762                                       atMouseLocation:YES];
767  * This is called when a :popup command is executed.
768  */
769     void
770 gui_make_popup(char_u *path_name, int mouse_pos)
772     [[MMBackend sharedInstance] showPopupMenuWithName:(char*)path_name
773                                       atMouseLocation:mouse_pos];
778  * This is called after setting all the menus to grey/hidden or not.
779  */
780     void
781 gui_mch_draw_menubar(void)
783     // The (main) menu draws itself in Mac OS X.
787     void
788 gui_mch_enable_menu(int flag)
790     // The (main) menu is always enabled in Mac OS X.
794 #if 0
795     void
796 gui_mch_set_menu_pos(int x, int y, int w, int h)
798     // The (main) menu cannot be moved in Mac OS X.
800 #endif
803     void
804 gui_mch_show_toolbar(int showit)
806     int flags = 0;
807     if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
808     if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
809     if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
811     [[MMBackend sharedInstance] showToolbar:showit flags:flags];
817 // -- Fonts -----------------------------------------------------------------
821  * If a font is not going to be used, free its structure.
822  */
823     void
824 gui_mch_free_font(font)
825     GuiFont     font;
831  * Get a font structure for highlighting.
832  */
833     GuiFont
834 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
836     //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
837     //        giveErrorIfMissing);
838     return 0;
842 #if defined(FEAT_EVAL) || defined(PROTO)
844  * Return the name of font "font" in allocated memory.
845  * Don't know how to get the actual name, thus use the provided name.
846  */
847     char_u *
848 gui_mch_get_fontname(GuiFont font, char_u *name)
850     //NSLog(@"gui_mch_get_fontname(font=%d, name=%s)", font, name);
851     return 0;
853 #endif
857  * Initialise vim to use the font with the given name.  Return FAIL if the font
858  * could not be loaded, OK otherwise.
859  */
860     int
861 gui_mch_init_font(char_u *font_name, int fontset)
863     //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
865     // HACK!  This gets called whenever the user types :set gfn=fontname, so
866     // for now we set the font here.
867     // TODO!  Proper font handling, the way Vim expects it.
868     return [[MMBackend sharedInstance]
869             setFontWithName:(char*)font_name];
874  * Set the current text font.
875  */
876     void
877 gui_mch_set_font(GuiFont font)
882 // -- Scrollbars ------------------------------------------------------------
885     void
886 gui_mch_create_scrollbar(
887         scrollbar_T *sb,
888         int orient)     /* SBAR_VERT or SBAR_HORIZ */
890     [[MMBackend sharedInstance] 
891             createScrollbarWithIdentifier:sb->ident type:sb->type];
895     void
896 gui_mch_destroy_scrollbar(scrollbar_T *sb)
898     [[MMBackend sharedInstance] 
899             destroyScrollbarWithIdentifier:sb->ident];
903     void
904 gui_mch_enable_scrollbar(
905         scrollbar_T     *sb,
906         int             flag)
908     [[MMBackend sharedInstance] 
909             showScrollbarWithIdentifier:sb->ident state:flag];
913     void
914 gui_mch_set_scrollbar_pos(
915         scrollbar_T *sb,
916         int x,
917         int y,
918         int w,
919         int h)
921     int pos = y;
922     int len = h;
923     if (SBAR_BOTTOM == sb->type) {
924         pos = x;
925         len = w; 
926     }
928     [[MMBackend sharedInstance] 
929             setScrollbarPosition:pos length:len identifier:sb->ident];
933     void
934 gui_mch_set_scrollbar_thumb(
935         scrollbar_T *sb,
936         long val,
937         long size,
938         long max)
940     [[MMBackend sharedInstance] 
941             setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
945 // -- Cursor ----------------------------------------------------------------
949  * Draw a cursor without focus.
950  */
951     void
952 gui_mch_draw_hollow_cursor(guicolor_T color)
954     return [[MMBackend sharedInstance]
955         drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
956                fraction:100 color:color];
961  * Draw part of a cursor, only w pixels wide, and h pixels high.
962  */
963     void
964 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
966     // HACK!  'w' and 'h' are always 1 since we do not tell Vim about the exact
967     // font dimensions.  Thus these parameters are useless.  Instead we look at
968     // the shape_table to determine the shape and size of the cursor (just like
969     // gui_update_cursor() does).
970     int idx = get_shape_idx(FALSE);
971     int shape = MMInsertionPointBlock;
972     switch (shape_table[idx].shape) {
973         case SHAPE_HOR: shape = MMInsertionPointHorizontal; break;
974         case SHAPE_VER: shape = MMInsertionPointVertical; break;
975     }
977     return [[MMBackend sharedInstance]
978         drawCursorAtRow:gui.row column:gui.col shape:shape
979                fraction:shape_table[idx].percentage color:color];
984  * Cursor blink functions.
986  * This is a simple state machine:
987  * BLINK_NONE   not blinking at all
988  * BLINK_OFF    blinking, cursor is not shown
989  * BLINK_ON blinking, cursor is shown
990  */
991     void
992 gui_mch_set_blinking(long wait, long on, long off)
994     [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
999  * Start the cursor blinking.  If it was already blinking, this restarts the
1000  * waiting time and shows the cursor.
1001  */
1002     void
1003 gui_mch_start_blink(void)
1005     [[MMBackend sharedInstance] startBlink];
1010  * Stop the cursor blinking.  Show the cursor if it wasn't shown.
1011  */
1012     void
1013 gui_mch_stop_blink(void)
1015     [[MMBackend sharedInstance] stopBlink];
1019 // -- Mouse -----------------------------------------------------------------
1023  * Get current mouse coordinates in text window.
1024  */
1025     void
1026 gui_mch_getmouse(int *x, int *y)
1028     //NSLog(@"gui_mch_getmouse()");
1032     void
1033 gui_mch_setmouse(int x, int y)
1035     //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1039     void
1040 mch_set_mouse_shape(int shape)
1042     [[MMBackend sharedInstance] setMouseShape:shape];
1048 // -- Unsorted --------------------------------------------------------------
1051     void
1052 ex_action(eap)
1053     exarg_T     *eap;
1055     if (!gui.in_use) {
1056         EMSG(_("E???: Command only available in GUI mode"));
1057         return;
1058     }
1060     NSString *name = [NSString stringWithCString:(char*)eap->arg
1061                                         encoding:NSUTF8StringEncoding];
1062     if (gui_macvim_is_valid_action(name)) {
1063         [[MMBackend sharedInstance] executeActionWithName:name];
1064     } else {
1065         EMSG2(_("E???: \"%s\" is not a valid action"), eap->arg);
1066     }
1071  * Adjust gui.char_height (after 'linespace' was changed).
1072  */
1073     int
1074 gui_mch_adjust_charheight(void)
1076     [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1077     return OK;
1081     void
1082 gui_mch_beep(void)
1088 #ifdef FEAT_BROWSE
1090  * Pop open a file browser and return the file selected, in allocated memory,
1091  * or NULL if Cancel is hit.
1092  *  saving  - TRUE if the file will be saved to, FALSE if it will be opened.
1093  *  title   - Title message for the file browser dialog.
1094  *  dflt    - Default name of file.
1095  *  ext     - Default extension to be added to files without extensions.
1096  *  initdir - directory in which to open the browser (NULL = current dir)
1097  *  filter  - Filter for matched files to choose from.
1098  *  Has a format like this:
1099  *  "C Files (*.c)\0*.c\0"
1100  *  "All Files\0*.*\0\0"
1101  *  If these two strings were concatenated, then a choice of two file
1102  *  filters will be selectable to the user.  Then only matching files will
1103  *  be shown in the browser.  If NULL, the default allows all files.
1105  *  *NOTE* - the filter string must be terminated with TWO nulls.
1106  */
1107     char_u *
1108 gui_mch_browse(
1109     int saving,
1110     char_u *title,
1111     char_u *dflt,
1112     char_u *ext,
1113     char_u *initdir,
1114     char_u *filter)
1116     //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1117     //        " filter=%s", saving, title, dflt, ext, initdir, filter);
1119     char_u *s = (char_u*)[[MMBackend sharedInstance]
1120             browseForFileInDirectory:(char*)initdir title:(char*)title
1121                               saving:saving];
1123     return s;
1125 #endif /* FEAT_BROWSE */
1129     int
1130 gui_mch_dialog(
1131     int         type,
1132     char_u      *title,
1133     char_u      *message,
1134     char_u      *buttons,
1135     int         dfltbutton,
1136     char_u      *textfield)
1138     //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1139     //        "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1140     //        dfltbutton, textfield);
1142     return [[MMBackend sharedInstance] presentDialogWithType:type
1143                                                        title:(char*)title
1144                                                      message:(char*)message
1145                                                      buttons:(char*)buttons
1146                                                    textField:(char*)textfield];
1150     void
1151 gui_mch_flash(int msec)
1157  * Return the Pixel value (color) for the given color name.  This routine was
1158  * pretty much taken from example code in the Silicon Graphics OSF/Motif
1159  * Programmer's Guide.
1160  * Return INVALCOLOR when failed.
1161  */
1162     guicolor_T
1163 gui_mch_get_color(char_u *name)
1165     NSString *key = [NSString stringWithUTF8String:(char*)name];
1166     return [[MMBackend sharedInstance] lookupColorWithKey:key];
1171  * Return the RGB value of a pixel as long.
1172  */
1173     long_u
1174 gui_mch_get_rgb(guicolor_T pixel)
1176     // This is only implemented so that vim can guess the correct value for
1177     // 'background' (which otherwise defaults to 'dark'); it is not used for
1178     // anything else (as far as I know).
1179     // The implementation is simple since colors are stored in an int as
1180     // "rrggbb".
1181     return pixel;
1186  * Get the screen dimensions.
1187  * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1188  * Is there no way to find out how wide the borders really are?
1189  * TODO: Add live udate of those value on suspend/resume.
1190  */
1191     void
1192 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1194     //NSLog(@"gui_mch_get_screen_dimensions()");
1195     *screen_w = Columns;
1196     *screen_h = Rows;
1201  * Get the position of the top left corner of the window.
1202  */
1203     int
1204 gui_mch_get_winpos(int *x, int *y)
1206     *x = *y = 0;
1207     return OK;
1212  * Return OK if the key with the termcap name "name" is supported.
1213  */
1214     int
1215 gui_mch_haskey(char_u *name)
1217     NSString *value = [NSString stringWithUTF8String:(char*)name];
1218     if (value)
1219         return [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1221     return NO;
1226  * Iconify the GUI window.
1227  */
1228     void
1229 gui_mch_iconify(void)
1235  * Invert a rectangle from row r, column c, for nr rows and nc columns.
1236  */
1237     void
1238 gui_mch_invert_rectangle(int r, int c, int nr, int nc)
1243 #if defined(FEAT_EVAL) || defined(PROTO)
1245  * Bring the Vim window to the foreground.
1246  */
1247     void
1248 gui_mch_set_foreground(void)
1250     [[MMBackend sharedInstance] activate];
1252 #endif
1256     void
1257 gui_mch_set_shellsize(
1258     int         width,
1259     int         height,
1260     int         min_width,
1261     int         min_height,
1262     int         base_width,
1263     int         base_height,
1264     int         direction)
1266     //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1267     //        " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1268     //        width, height, min_width, min_height, base_width, base_height,
1269     //        direction);
1270     [[MMBackend sharedInstance] setRows:height columns:width];
1274     void
1275 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1280  * Set the position of the top left corner of the window to the given
1281  * coordinates.
1282  */
1283     void
1284 gui_mch_set_winpos(int x, int y)
1289 #ifdef FEAT_TITLE
1291  * Set the window title and icon.
1292  * (The icon is not taken care of).
1293  */
1294     void
1295 gui_mch_settitle(char_u *title, char_u *icon)
1297     //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1299     [[MMBackend sharedInstance] setVimWindowTitle:(char*)title];
1301 #endif
1304     void
1305 gui_mch_toggle_tearoffs(int enable)
1310     static BOOL
1311 gui_macvim_is_valid_action(NSString *action)
1313     static NSDictionary *actionDict = nil;
1315     if (!actionDict) {
1316         NSBundle *mainBundle = [NSBundle mainBundle];
1317         NSString *path = [mainBundle pathForResource:@"Actions"
1318                                               ofType:@"plist"];
1319         if (path) {
1320             actionDict = [[NSDictionary alloc] initWithContentsOfFile:path];
1321         } else {
1322             // Allocate bogus dictionary so that error only pops up once.
1323             actionDict = [NSDictionary new];
1324             EMSG(_("E???: Failed to load action dictionary"));
1325         }
1326     }
1328     return [actionDict objectForKey:action] != nil;
1333 // -- Client/Server ---------------------------------------------------------
1335 #ifdef MAC_CLIENTSERVER
1338 // NOTE: Client/Server is only fully supported with a GUI.  Theoretically it
1339 // would be possible to make the server code work with terminal Vim, but it
1340 // would require that a run-loop is set up and checked.  This should not be
1341 // difficult to implement, simply call gui_mch_update() at opportune moments
1342 // and it will take care of the run-loop.  Another (bigger) problem with
1343 // supporting servers in terminal mode is that the server listing code talks to
1344 // MacVim (the GUI) to figure out which servers are running.
1349  * Register connection with 'name'.  The actual connection is named something
1350  * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1351  */
1352     void
1353 serverRegisterName(char_u *name)
1355     NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1356     [[MMBackend sharedInstance] registerServerWithName:svrName];
1361  * Send to an instance of Vim.
1362  * Returns 0 for OK, negative for an error.
1363  */
1364     int
1365 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1366         int *port, int asExpr, int silent)
1368     BOOL ok = [[MMBackend sharedInstance]
1369             sendToServer:[NSString stringWithUTF8String:(char*)name]
1370                   string:[NSString stringWithUTF8String:(char*)cmd]
1371                    reply:result
1372                     port:port
1373               expression:asExpr
1374                   silent:silent];
1376     return ok ? 0 : -1;
1381  * Ask MacVim for the names of all Vim servers.
1382  */
1383     char_u *
1384 serverGetVimNames(void)
1386     char_u *names = NULL;
1387     NSArray *list = [[MMBackend sharedInstance] serverList];
1389     if (list) {
1390         NSString *string = [list componentsJoinedByString:@"\n"];
1391         names = vim_strsave((char_u*)[string UTF8String]);
1392     }
1394     return names;
1399  * 'str' is a hex int representing the send port of the connection.
1400  */
1401     int
1402 serverStrToPort(char_u *str)
1404     int port = 0;
1406     sscanf((char *)str, "0x%x", &port);
1407     if (!port)
1408         EMSG2(_("E573: Invalid server id used: %s"), str);
1410     return port;
1415  * Check for replies from server with send port 'port'.
1416  * Return TRUE and a non-malloc'ed string if there is.  Else return FALSE.
1417  */
1418     int
1419 serverPeekReply(int port, char_u **str)
1421     NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1422     if (str)
1423         *str = (char_u*)[reply UTF8String];
1425     return reply != nil;
1430  * Wait for replies from server with send port 'port'.
1431  * Return 0 and the malloc'ed string when a reply is available.
1432  * Return -1 on error.
1433  */
1434     int
1435 serverReadReply(int port, char_u **str)
1437     NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1438     if (reply && str) {
1439         *str = vim_strsave((char_u*)[reply UTF8String]);
1440         return 0;
1441     }
1443     return -1;
1448  * Send a reply string (notification) to client with port given by "serverid".
1449  * Return -1 if the window is invalid.
1450  */
1451     int
1452 serverSendReply(char_u *serverid, char_u *reply)
1454     int retval = -1;
1455     int port = serverStrToPort(serverid);
1456     if (port > 0 && reply) {
1457         BOOL ok = [[MMBackend sharedInstance]
1458                 sendReply:[NSString stringWithUTF8String:(char*)reply]
1459                    toPort:port];
1460         retval = ok ? 0 : -1;
1461     }
1463     return retval;
1466 #endif // MAC_CLIENTSERVER