Got rid of multibyte chars in comment
[MacVim/jjgod.git] / gui_macvim.m
blob2c6f9127ccb246272d25f5e3333ae6cebd110ec6
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     // Force 'termencoding' to utf-8 (changes to 'tenc' are disallowed in
75     // 'option.c', so that ':set termencoding=...' is impossible).
76     set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
78     // Set values so that pixels and characters are in one-to-one
79     // correspondence (assuming all characters have the same dimensions).
80     gui.scrollbar_width = gui.scrollbar_height = 0;
82     gui.char_height = 1;
83     gui.char_width = 1;
84     gui.char_ascent = 0;
86     gui_mch_def_colors();
88     [[MMBackend sharedInstance]
89         setDefaultColorsBackground:gui.back_pixel foreground:gui.norm_pixel];
90     [[MMBackend sharedInstance] setBackgroundColor:gui.back_pixel];
91     [[MMBackend sharedInstance] setForegroundColor:gui.norm_pixel];
93     // NOTE: If this call is left out the cursor is opaque.
94     highlight_gui_started();
96     return OK;
101     void
102 gui_mch_exit(int rc)
104     //NSLog(@"gui_mch_exit(rc=%d)", rc);
106     [[MMBackend sharedInstance] exit];
111  * Open the GUI window which was created by a call to gui_mch_init().
112  */
113     int
114 gui_mch_open(void)
116     //NSLog(@"gui_mch_open()");
118     return [[MMBackend sharedInstance] openVimWindow];
122 // -- Updating --------------------------------------------------------------
126  * Catch up with any queued X events.  This may put keyboard input into the
127  * input buffer, call resize call-backs, trigger timers etc.  If there is
128  * nothing in the X event queue (& no timers pending), then we return
129  * immediately.
130  */
131     void
132 gui_mch_update(void)
134     // TODO: Ensure that this causes no problems.
135     [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
136                              beforeDate:[NSDate distantPast]];
140 /* Flush any output to the screen */
141     void
142 gui_mch_flush(void)
144     [[MMBackend sharedInstance] flushQueue:NO];
149  * GUI input routine called by gui_wait_for_chars().  Waits for a character
150  * from the keyboard.
151  *  wtime == -1     Wait forever.
152  *  wtime == 0      This should never happen.
153  *  wtime > 0       Wait wtime milliseconds for a character.
154  * Returns OK if a character was found to be available within the given time,
155  * or FAIL otherwise.
156  */
157     int
158 gui_mch_wait_for_chars(int wtime)
160     // NOTE! In all likelihood Vim will take a nap when waitForInput: is
161     // called, so force a flush of the command queue here.
162     [[MMBackend sharedInstance] flushQueue:YES];
164     return [[MMBackend sharedInstance] waitForInput:wtime];
168 // -- Drawing ---------------------------------------------------------------
172  * Clear the whole text window.
173  */
174     void
175 gui_mch_clear_all(void)
177     [[MMBackend sharedInstance] clearAll];
182  * Clear a rectangular region of the screen from text pos (row1, col1) to
183  * (row2, col2) inclusive.
184  */
185     void
186 gui_mch_clear_block(int row1, int col1, int row2, int col2)
188     [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
189                                                     toRow:row2 column:col2];
194  * Delete the given number of lines from the given row, scrolling up any
195  * text further down within the scroll region.
196  */
197     void
198 gui_mch_delete_lines(int row, int num_lines)
200     [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
201             scrollBottom:gui.scroll_region_bot
202                     left:gui.scroll_region_left
203                    right:gui.scroll_region_right];
207     void
208 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
210 #if MM_ENABLE_CONV
211     char_u *conv_str = NULL;
212     if (output_conv.vc_type != CONV_NONE) {
213         conv_str = string_convert(&output_conv, s, &len);
214         if (conv_str)
215             s = conv_str;
216     }
217 #endif
219     [[MMBackend sharedInstance] replaceString:(char*)s length:len
220             row:row column:col flags:flags];
222 #if MM_ENABLE_CONV
223     if (conv_str)
224         vim_free(conv_str);
225 #endif
229     int
230 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
232     //
233     // Output chars until a wide char found.  If a wide char is found, output a
234     // zero-width space after it so that a wide char looks like two chars to
235     // MMTextStorage.  This way 1 char corresponds to 1 column.
236     //
238     int c;
239     int cn;
240     int cl;
241     int i;
242     int start = 0;
243     int endcol = col;
244     int startcol = col;
245     BOOL outPad = NO;
246     MMBackend *backend = [MMBackend sharedInstance];
247     static char ZeroWidthSpace[] = { 0xe2, 0x80, 0x8b };
248 #if MM_ENABLE_CONV
249     char_u *conv_str = NULL;
251     if (output_conv.vc_type != CONV_NONE) {
252         conv_str = string_convert(&output_conv, s, &len);
253         if (conv_str)
254             s = conv_str;
255     }
256 #endif
258     for (i = 0; i < len; i += cl) {
259         c = utf_ptr2char(s + i);
260         cl = utf_ptr2len(s + i);
261         cn = utf_char2cells(c);
263         if (!utf_iscomposing(c)) {
264             if (outPad) {
265                 outPad = NO;
266 #if 0
267                 NSString *string = [[NSString alloc]
268                         initWithBytesNoCopy:(void*)(s+start)
269                                      length:i-start
270                                    encoding:NSUTF8StringEncoding
271                                freeWhenDone:NO];
272                 NSLog(@"Flushing string=%@ len=%d row=%d col=%d end=%d",
273                         string, i-start, row, startcol, endcol);
274                 [string release];
275 #endif
276                 [backend replaceString:(char*)(s+start) length:i-start
277                         row:row column:startcol flags:flags];
278                 start = i;
279                 startcol = endcol;
280 #if 0
281                 NSLog(@"Padding len=%d row=%d col=%d", sizeof(ZeroWidthSpace),
282                         row, endcol-1);
283 #endif
284                 [backend replaceString:ZeroWidthSpace
285                              length:sizeof(ZeroWidthSpace)
286                         row:row column:endcol-1 flags:flags];
287             }
289             endcol += cn;
290         }
292         if (cn > 1) {
293 #if 0
294             NSLog(@"Wide char detected! (char=%C hex=%x cells=%d)", c, c, cn);
295 #endif
296             outPad = YES;
297         }
298     }
300 #if 0
301     if (row < 1) {
302         NSString *string = [[NSString alloc]
303                 initWithBytesNoCopy:(void*)(s+start)
304                              length:len-start
305                            encoding:NSUTF8StringEncoding
306                        freeWhenDone:NO];
307         NSLog(@"Output string=%@ len=%d row=%d col=%d", string, len-start, row,
308                 startcol);
309         [string release];
310     }
311 #endif
313     // Output remaining characters.
314     [backend replaceString:(char*)(s+start) length:len-start
315             row:row column:startcol flags:flags];
317     if (outPad) {
318 #if 0
319         NSLog(@"Padding len=%d row=%d col=%d", sizeof(ZeroWidthSpace), row,
320                 endcol-1);
321 #endif
322         [backend replaceString:ZeroWidthSpace
323                      length:sizeof(ZeroWidthSpace)
324                 row:row column:endcol-1 flags:flags];
325     }
327 #if MM_ENABLE_CONV
328     if (conv_str)
329         vim_free(conv_str);
330 #endif
332     return endcol - col;
337  * Insert the given number of lines before the given row, scrolling down any
338  * following text within the scroll region.
339  */
340     void
341 gui_mch_insert_lines(int row, int num_lines)
343     [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
344             scrollBottom:gui.scroll_region_bot
345                     left:gui.scroll_region_left
346                    right:gui.scroll_region_right];
351  * Set the current text foreground color.
352  */
353     void
354 gui_mch_set_fg_color(guicolor_T color)
356     [[MMBackend sharedInstance] setForegroundColor:color];
361  * Set the current text background color.
362  */
363     void
364 gui_mch_set_bg_color(guicolor_T color)
366     [[MMBackend sharedInstance] setBackgroundColor:color];
371  * Set the current text special color (used for underlines).
372  */
373     void
374 gui_mch_set_sp_color(guicolor_T color)
376     [[MMBackend sharedInstance] setSpecialColor:color];
381  * Set default colors.
382  */
383     void
384 gui_mch_def_colors()
386     MMBackend *backend = [MMBackend sharedInstance];
388     // The default colors are taken from system values
389     gui.def_norm_pixel = gui.norm_pixel = 
390         [backend lookupColorWithKey:@"MacTextColor"];
391     gui.def_back_pixel = gui.back_pixel = 
392         [backend lookupColorWithKey:@"MacTextBackgroundColor"];
397  * Called when the foreground or background color has been changed.
398  */
399     void
400 gui_mch_new_colors(void)
402     gui.def_back_pixel = gui.back_pixel;
403     gui.def_norm_pixel = gui.norm_pixel;
405     //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
406     //        gui.def_norm_pixel);
408     [[MMBackend sharedInstance]
409         setDefaultColorsBackground:gui.def_back_pixel
410                         foreground:gui.def_norm_pixel];
414 // -- Tabline ---------------------------------------------------------------
418  * Set the current tab to "nr".  First tab is 1.
419  */
420     void
421 gui_mch_set_curtab(int nr)
423     [[MMBackend sharedInstance] selectTab:nr];
428  * Return TRUE when tabline is displayed.
429  */
430     int
431 gui_mch_showing_tabline(void)
433     return [[MMBackend sharedInstance] tabBarVisible];
437  * Update the labels of the tabline.
438  */
439     void
440 gui_mch_update_tabline(void)
442     [[MMBackend sharedInstance] updateTabBar];
446  * Show or hide the tabline.
447  */
448     void
449 gui_mch_show_tabline(int showit)
451     [[MMBackend sharedInstance] showTabBar:showit];
455 // -- Clipboard -------------------------------------------------------------
458     void
459 clip_mch_lose_selection(VimClipboard *cbd)
464     int
465 clip_mch_own_selection(VimClipboard *cbd)
467     return 0;
471     void
472 clip_mch_request_selection(VimClipboard *cbd)
474     NSPasteboard *pb = [NSPasteboard generalPasteboard];
475     NSString *pbType = [pb availableTypeFromArray:
476             [NSArray arrayWithObject:NSStringPboardType]];
477     if (pbType) {
478         NSMutableString *string =
479                 [[pb stringForType:NSStringPboardType] mutableCopy];
481         // Replace unrecognized end-of-line sequences with \x0a (line feed).
482         NSRange range = { 0, [string length] };
483         unsigned n = [string replaceOccurrencesOfString:@"\x0d\x0a"
484                                              withString:@"\x0a" options:0
485                                                   range:range];
486         if (0 == n) {
487             n = [string replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
488                                            options:0 range:range];
489         }
490         
491         // Scan for newline character to decide whether the string should be
492         // pasted linewise or characterwise.
493         int type = MCHAR;
494         if (0 < n || NSNotFound != [string rangeOfString:@"\n"].location)
495             type = MLINE;
497         char_u *str = (char_u*)[string UTF8String];
498         int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
500 #if MM_ENABLE_CONV
501         if (input_conv.vc_type != CONV_NONE)
502             str = string_convert(&input_conv, str, &len);
503 #endif
505         if (str)
506             clip_yank_selection(type, str, len, cbd);
508 #if MM_ENABLE_CONV
509         if (input_conv.vc_type != CONV_NONE)
510             vim_free(str);
511 #endif
512     }
517  * Send the current selection to the clipboard.
518  */
519     void
520 clip_mch_set_selection(VimClipboard *cbd)
522     // If the '*' register isn't already filled in, fill it in now.
523     cbd->owned = TRUE;
524     clip_get_selection(cbd);
525     cbd->owned = FALSE;
526     
527     // Get the text to put on the pasteboard.
528     long_u llen = 0; char_u *str = 0;
529     int type = clip_convert_selection(&str, &llen, cbd);
530     if (type < 0)
531         return;
533     // TODO: Avoid overflow.
534     int len = (int)llen;
535 #if MM_ENABLE_CONV
536     if (output_conv.vc_type != CONV_NONE) {
537         char_u *conv_str = string_convert(&output_conv, str, &len);
538         if (conv_str) {
539             vim_free(str);
540             str = conv_str;
541         }
542     }
543 #endif
545     if (len > 0) {
546         NSString *string = [[NSString alloc]
547             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
549         NSPasteboard *pb = [NSPasteboard generalPasteboard];
550         [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType]
551                    owner:nil];
552         [pb setString:string forType:NSStringPboardType];
553         
554         [string release];
555     }
557     vim_free(str);
561 // -- Menu ------------------------------------------------------------------
565  * Add a sub menu to the menu bar.
566  */
567     void
568 gui_mch_add_menu(vimmenu_T *menu, int idx)
570     // HACK!  If menu has no parent, then we set the parent tag to the type of
571     // menu it is.  This will not mix up tag and type because pointers can not
572     // take values close to zero (and the tag is simply the value of the
573     // pointer).
574     int parent = (int)menu->parent;
575     if (!parent) {
576         parent = menu_is_popup(menu->name) ? MenuPopupType :
577                  menu_is_toolbar(menu->name) ? MenuToolbarType :
578                  MenuMenubarType;
579     }
581     char_u *dname = menu->dname;
582 #if MM_ENABLE_CONV
583     dname = CONVERT_TO_UTF8(dname);
584 #endif
586     [[MMBackend sharedInstance]
587             addMenuWithTag:(int)menu parent:parent name:(char*)dname
588                    atIndex:idx];
590 #if MM_ENABLE_CONV
591     CONVERT_TO_UTF8_FREE(dname);
592 #endif
597  * Add a menu item to a menu
598  */
599     void
600 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
602     // NOTE!  If 'iconfile' is not set but 'iconidx' is, use the name of the
603     // menu item.  (Should correspond to a stock item.)
604     char_u *icon = menu->iconfile ? menu->iconfile :
605                  menu->iconidx >= 0 ? menu->dname :
606                  NULL;
607     //char *name = menu_is_separator(menu->name) ? NULL : (char*)menu->dname;
608     char_u *name = menu->dname;
609     char_u *tip = menu->strings[MENU_INDEX_TIP]
610             ? menu->strings[MENU_INDEX_TIP] : menu->actext;
611     char_u *map_str = menu->strings[MENU_INDEX_NORMAL];
613 #if MM_ENABLE_CONV
614     icon = CONVERT_TO_UTF8(icon);
615     name = CONVERT_TO_UTF8(name);
616     tip = CONVERT_TO_UTF8(tip);
617     map_str = CONVERT_TO_UTF8(map_str);
618 #endif
620     // HACK!  Check if menu is mapped to ':action actionName:'; if so, pass the
621     // action along so that MacVim can bind the menu item to this action.  This
622     // means that if a menu item maps to an action in normal mode, then all
623     // other modes will also use the same action.
624     NSString *action = nil;
625     if (map_str) {
626         NSString *mapping = [NSString stringWithCString:(char*)map_str
627                                                encoding:NSUTF8StringEncoding];
628         NSArray *parts = [mapping componentsSeparatedByString:@" "];
629         if ([parts count] >=2 
630                 && [[parts objectAtIndex:0] isEqual:@":action"]) {
631             action = [parts objectAtIndex:1];
632             action = [action stringByTrimmingCharactersInSet:
633                     [NSCharacterSet whitespaceAndNewlineCharacterSet]];
634             if (!gui_macvim_is_valid_action(action))
635                 action = nil;
636         }
637     }
639     [[MMBackend sharedInstance]
640             addMenuItemWithTag:(int)menu
641                         parent:(int)menu->parent
642                           name:(char*)name
643                            tip:(char*)tip
644                           icon:(char*)icon
645                  keyEquivalent:menu->ke_key
646                      modifiers:menu->ke_mods
647                         action:action
648                        atIndex:idx];
650 #if MM_ENABLE_CONV
651     CONVERT_TO_UTF8_FREE(icon);
652     CONVERT_TO_UTF8_FREE(name);
653     CONVERT_TO_UTF8_FREE(tip);
654     CONVERT_TO_UTF8_FREE(map_str);
655 #endif
660  * Destroy the machine specific menu widget.
661  */
662     void
663 gui_mch_destroy_menu(vimmenu_T *menu)
665     [[MMBackend sharedInstance] removeMenuItemWithTag:(int)menu];
670  * Make a menu either grey or not grey.
671  */
672     void
673 gui_mch_menu_grey(vimmenu_T *menu, int grey)
675     [[MMBackend sharedInstance]
676             enableMenuItemWithTag:(int)menu state:!grey];
681  * Make menu item hidden or not hidden
682  */
683     void
684 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
686     // HACK! There is no (obvious) way to hide a menu item, so simply
687     // enable/disable it instead.
688     [[MMBackend sharedInstance]
689             enableMenuItemWithTag:(int)menu state:!hidden];
694  * This is called when user right clicks.
695  */
696     void
697 gui_mch_show_popupmenu(vimmenu_T *menu)
699     char_u *name = menu->name;
700 #if MM_ENABLE_CONV
701     name = CONVERT_TO_UTF8(name);
702 #endif
704     [[MMBackend sharedInstance] showPopupMenuWithName:(char*)name
705                                       atMouseLocation:YES];
707 #if MM_ENABLE_CONV
708     CONVERT_TO_UTF8_FREE(name);
709 #endif
715  * This is called when a :popup command is executed.
716  */
717     void
718 gui_make_popup(char_u *path_name, int mouse_pos)
720 #if MM_ENABLE_CONV
721     path_name = CONVERT_TO_UTF8(path_name);
722 #endif
724     [[MMBackend sharedInstance] showPopupMenuWithName:(char*)path_name
725                                       atMouseLocation:mouse_pos];
727 #if MM_ENABLE_CONV
728     CONVERT_TO_UTF8_FREE(path_name);
729 #endif
734  * This is called after setting all the menus to grey/hidden or not.
735  */
736     void
737 gui_mch_draw_menubar(void)
739     // The (main) menu draws itself in Mac OS X.
743     void
744 gui_mch_enable_menu(int flag)
746     // The (main) menu is always enabled in Mac OS X.
750 #if 0
751     void
752 gui_mch_set_menu_pos(int x, int y, int w, int h)
754     // The (main) menu cannot be moved in Mac OS X.
756 #endif
759     void
760 gui_mch_show_toolbar(int showit)
762     int flags = 0;
763     if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
764     if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
765     if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
767     [[MMBackend sharedInstance] showToolbar:showit flags:flags];
773 // -- Fonts -----------------------------------------------------------------
777  * If a font is not going to be used, free its structure.
778  */
779     void
780 gui_mch_free_font(font)
781     GuiFont     font;
787  * Get a font structure for highlighting.
788  */
789     GuiFont
790 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
792     //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
793     //        giveErrorIfMissing);
794     return 0;
798 #if defined(FEAT_EVAL) || defined(PROTO)
800  * Return the name of font "font" in allocated memory.
801  * Don't know how to get the actual name, thus use the provided name.
802  */
803     char_u *
804 gui_mch_get_fontname(GuiFont font, char_u *name)
806     //NSLog(@"gui_mch_get_fontname(font=%d, name=%s)", font, name);
807     return 0;
809 #endif
813  * Initialise vim to use the font with the given name.  Return FAIL if the font
814  * could not be loaded, OK otherwise.
815  */
816     int
817 gui_mch_init_font(char_u *font_name, int fontset)
819     //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
821     // HACK!  This gets called whenever the user types :set gfn=fontname, so
822     // for now we set the font here.
823     // TODO!  Proper font handling, the way Vim expects it.
825 #if MM_ENABLE_CONV
826     font_name = CONVERT_TO_UTF8(font_name);
827 #endif
829     BOOL ok = [[MMBackend sharedInstance] setFontWithName:(char*)font_name];
831 #if MM_ENABLE_CONV
832     CONVERT_TO_UTF8_FREE(font_name);
833 #endif
835     return ok;
840  * Set the current text font.
841  */
842     void
843 gui_mch_set_font(GuiFont font)
848 // -- Scrollbars ------------------------------------------------------------
851     void
852 gui_mch_create_scrollbar(
853         scrollbar_T *sb,
854         int orient)     /* SBAR_VERT or SBAR_HORIZ */
856     [[MMBackend sharedInstance] 
857             createScrollbarWithIdentifier:sb->ident type:sb->type];
861     void
862 gui_mch_destroy_scrollbar(scrollbar_T *sb)
864     [[MMBackend sharedInstance] 
865             destroyScrollbarWithIdentifier:sb->ident];
869     void
870 gui_mch_enable_scrollbar(
871         scrollbar_T     *sb,
872         int             flag)
874     [[MMBackend sharedInstance] 
875             showScrollbarWithIdentifier:sb->ident state:flag];
879     void
880 gui_mch_set_scrollbar_pos(
881         scrollbar_T *sb,
882         int x,
883         int y,
884         int w,
885         int h)
887     int pos = y;
888     int len = h;
889     if (SBAR_BOTTOM == sb->type) {
890         pos = x;
891         len = w; 
892     }
894     [[MMBackend sharedInstance] 
895             setScrollbarPosition:pos length:len identifier:sb->ident];
899     void
900 gui_mch_set_scrollbar_thumb(
901         scrollbar_T *sb,
902         long val,
903         long size,
904         long max)
906     [[MMBackend sharedInstance] 
907             setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
911 // -- Cursor ----------------------------------------------------------------
915  * Draw a cursor without focus.
916  */
917     void
918 gui_mch_draw_hollow_cursor(guicolor_T color)
920     return [[MMBackend sharedInstance]
921         drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
922                fraction:100 color:color];
927  * Draw part of a cursor, only w pixels wide, and h pixels high.
928  */
929     void
930 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
932     // HACK!  'w' and 'h' are always 1 since we do not tell Vim about the exact
933     // font dimensions.  Thus these parameters are useless.  Instead we look at
934     // the shape_table to determine the shape and size of the cursor (just like
935     // gui_update_cursor() does).
936     int idx = get_shape_idx(FALSE);
937     int shape = MMInsertionPointBlock;
938     switch (shape_table[idx].shape) {
939         case SHAPE_HOR: shape = MMInsertionPointHorizontal; break;
940         case SHAPE_VER: shape = MMInsertionPointVertical; break;
941     }
943     return [[MMBackend sharedInstance]
944         drawCursorAtRow:gui.row column:gui.col shape:shape
945                fraction:shape_table[idx].percentage color:color];
950  * Cursor blink functions.
952  * This is a simple state machine:
953  * BLINK_NONE   not blinking at all
954  * BLINK_OFF    blinking, cursor is not shown
955  * BLINK_ON blinking, cursor is shown
956  */
957     void
958 gui_mch_set_blinking(long wait, long on, long off)
960     [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
965  * Start the cursor blinking.  If it was already blinking, this restarts the
966  * waiting time and shows the cursor.
967  */
968     void
969 gui_mch_start_blink(void)
971     [[MMBackend sharedInstance] startBlink];
976  * Stop the cursor blinking.  Show the cursor if it wasn't shown.
977  */
978     void
979 gui_mch_stop_blink(void)
981     [[MMBackend sharedInstance] stopBlink];
985 // -- Mouse -----------------------------------------------------------------
989  * Get current mouse coordinates in text window.
990  */
991     void
992 gui_mch_getmouse(int *x, int *y)
994     //NSLog(@"gui_mch_getmouse()");
998     void
999 gui_mch_setmouse(int x, int y)
1001     //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1005     void
1006 mch_set_mouse_shape(int shape)
1008     [[MMBackend sharedInstance] setMouseShape:shape];
1014 // -- Unsorted --------------------------------------------------------------
1017     void
1018 ex_action(eap)
1019     exarg_T     *eap;
1021     if (!gui.in_use) {
1022         EMSG(_("E???: Command only available in GUI mode"));
1023         return;
1024     }
1026     char_u *arg = eap->arg;
1027 #if MM_ENABLE_CONV
1028     arg = CONVERT_TO_UTF8(arg);
1029 #endif
1031     NSString *name = [NSString stringWithCString:(char*)arg
1032                                         encoding:NSUTF8StringEncoding];
1033     if (gui_macvim_is_valid_action(name)) {
1034         [[MMBackend sharedInstance] executeActionWithName:name];
1035     } else {
1036         EMSG2(_("E???: \"%s\" is not a valid action"), eap->arg);
1037     }
1039 #if MM_ENABLE_CONV
1040     arg = CONVERT_TO_UTF8(arg);
1041 #endif
1046  * Adjust gui.char_height (after 'linespace' was changed).
1047  */
1048     int
1049 gui_mch_adjust_charheight(void)
1051     [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1052     return OK;
1056     void
1057 gui_mch_beep(void)
1063 #ifdef FEAT_BROWSE
1065  * Pop open a file browser and return the file selected, in allocated memory,
1066  * or NULL if Cancel is hit.
1067  *  saving  - TRUE if the file will be saved to, FALSE if it will be opened.
1068  *  title   - Title message for the file browser dialog.
1069  *  dflt    - Default name of file.
1070  *  ext     - Default extension to be added to files without extensions.
1071  *  initdir - directory in which to open the browser (NULL = current dir)
1072  *  filter  - Filter for matched files to choose from.
1073  *  Has a format like this:
1074  *  "C Files (*.c)\0*.c\0"
1075  *  "All Files\0*.*\0\0"
1076  *  If these two strings were concatenated, then a choice of two file
1077  *  filters will be selectable to the user.  Then only matching files will
1078  *  be shown in the browser.  If NULL, the default allows all files.
1080  *  *NOTE* - the filter string must be terminated with TWO nulls.
1081  */
1082     char_u *
1083 gui_mch_browse(
1084     int saving,
1085     char_u *title,
1086     char_u *dflt,
1087     char_u *ext,
1088     char_u *initdir,
1089     char_u *filter)
1091     //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1092     //        " filter=%s", saving, title, dflt, ext, initdir, filter);
1094 #if MM_ENABLE_CONV
1095     title = CONVERT_TO_UTF8(title);
1096     initdir = CONVERT_TO_UTF8(initdir);
1097 #endif
1099     char_u *s = (char_u*)[[MMBackend sharedInstance]
1100             browseForFileInDirectory:(char*)initdir title:(char*)title
1101                               saving:saving];
1103 #if MM_ENABLE_CONV
1104     CONVERT_TO_UTF8_FREE(title);
1105     CONVERT_TO_UTF8_FREE(initdir);
1106 #endif
1108     return s;
1110 #endif /* FEAT_BROWSE */
1114     int
1115 gui_mch_dialog(
1116     int         type,
1117     char_u      *title,
1118     char_u      *message,
1119     char_u      *buttons,
1120     int         dfltbutton,
1121     char_u      *textfield)
1123     //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1124     //        "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1125     //        dfltbutton, textfield);
1127 #if MM_ENABLE_CONV
1128     title = CONVERT_TO_UTF8(title);
1129     message = CONVERT_TO_UTF8(message);
1130     buttons = CONVERT_TO_UTF8(buttons);
1131     textfield = CONVERT_TO_UTF8(textfield);
1132 #endif
1134     int ret = [[MMBackend sharedInstance]
1135             presentDialogWithType:type
1136                             title:(char*)title
1137                           message:(char*)message
1138                           buttons:(char*)buttons
1139                         textField:(char*)textfield];
1141 #if MM_ENABLE_CONV
1142     CONVERT_TO_UTF8_FREE(title);
1143     CONVERT_TO_UTF8_FREE(message);
1144     CONVERT_TO_UTF8_FREE(buttons);
1145     CONVERT_TO_UTF8_FREE(textfield);
1146 #endif
1148     return ret;
1152     void
1153 gui_mch_flash(int msec)
1159  * Return the Pixel value (color) for the given color name.  This routine was
1160  * pretty much taken from example code in the Silicon Graphics OSF/Motif
1161  * Programmer's Guide.
1162  * Return INVALCOLOR when failed.
1163  */
1164     guicolor_T
1165 gui_mch_get_color(char_u *name)
1167 #if MM_ENABLE_CONV
1168     name = CONVERT_TO_UTF8(name);
1169 #endif
1171     NSString *key = [NSString stringWithUTF8String:(char*)name];
1172     guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1174 #if MM_ENABLE_CONV
1175     CONVERT_TO_UTF8_FREE(name);
1176 #endif
1178     return col;
1183  * Return the RGB value of a pixel as long.
1184  */
1185     long_u
1186 gui_mch_get_rgb(guicolor_T pixel)
1188     // This is only implemented so that vim can guess the correct value for
1189     // 'background' (which otherwise defaults to 'dark'); it is not used for
1190     // anything else (as far as I know).
1191     // The implementation is simple since colors are stored in an int as
1192     // "rrggbb".
1193     return pixel;
1198  * Get the screen dimensions.
1199  * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1200  * Is there no way to find out how wide the borders really are?
1201  * TODO: Add live udate of those value on suspend/resume.
1202  */
1203     void
1204 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1206     //NSLog(@"gui_mch_get_screen_dimensions()");
1207     *screen_w = Columns;
1208     *screen_h = Rows;
1213  * Get the position of the top left corner of the window.
1214  */
1215     int
1216 gui_mch_get_winpos(int *x, int *y)
1218     *x = *y = 0;
1219     return OK;
1224  * Return OK if the key with the termcap name "name" is supported.
1225  */
1226     int
1227 gui_mch_haskey(char_u *name)
1229     BOOL ok = NO;
1231 #if MM_ENABLE_CONV
1232     name = CONVERT_TO_UTF8(name);
1233 #endif
1235     NSString *value = [NSString stringWithUTF8String:(char*)name];
1236     if (value)
1237         ok =  [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1239 #if MM_ENABLE_CONV
1240     CONVERT_TO_UTF8_FREE(name);
1241 #endif
1243     return ok;
1248  * Iconify the GUI window.
1249  */
1250     void
1251 gui_mch_iconify(void)
1257  * Invert a rectangle from row r, column c, for nr rows and nc columns.
1258  */
1259     void
1260 gui_mch_invert_rectangle(int r, int c, int nr, int nc)
1265 #if defined(FEAT_EVAL) || defined(PROTO)
1267  * Bring the Vim window to the foreground.
1268  */
1269     void
1270 gui_mch_set_foreground(void)
1272     [[MMBackend sharedInstance] activate];
1274 #endif
1278     void
1279 gui_mch_set_shellsize(
1280     int         width,
1281     int         height,
1282     int         min_width,
1283     int         min_height,
1284     int         base_width,
1285     int         base_height,
1286     int         direction)
1288     //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1289     //        " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1290     //        width, height, min_width, min_height, base_width, base_height,
1291     //        direction);
1292     [[MMBackend sharedInstance] setRows:height columns:width];
1296     void
1297 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1302  * Set the position of the top left corner of the window to the given
1303  * coordinates.
1304  */
1305     void
1306 gui_mch_set_winpos(int x, int y)
1311 #ifdef FEAT_TITLE
1313  * Set the window title and icon.
1314  * (The icon is not taken care of).
1315  */
1316     void
1317 gui_mch_settitle(char_u *title, char_u *icon)
1319     //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1321 #if MM_ENABLE_CONV
1322     title = CONVERT_TO_UTF8(title);
1323 #endif
1325     [[MMBackend sharedInstance] setWindowTitle:(char*)title];
1327 #if MM_ENABLE_CONV
1328     CONVERT_TO_UTF8_FREE(title);
1329 #endif
1331 #endif
1334     void
1335 gui_mch_toggle_tearoffs(int enable)
1340     static BOOL
1341 gui_macvim_is_valid_action(NSString *action)
1343     static NSDictionary *actionDict = nil;
1345     if (!actionDict) {
1346         NSBundle *mainBundle = [NSBundle mainBundle];
1347         NSString *path = [mainBundle pathForResource:@"Actions"
1348                                               ofType:@"plist"];
1349         if (path) {
1350             actionDict = [[NSDictionary alloc] initWithContentsOfFile:path];
1351         } else {
1352             // Allocate bogus dictionary so that error only pops up once.
1353             actionDict = [NSDictionary new];
1354             EMSG(_("E???: Failed to load action dictionary"));
1355         }
1356     }
1358     return [actionDict objectForKey:action] != nil;
1363 // -- Client/Server ---------------------------------------------------------
1365 #ifdef MAC_CLIENTSERVER
1368 // NOTE: Client/Server is only fully supported with a GUI.  Theoretically it
1369 // would be possible to make the server code work with terminal Vim, but it
1370 // would require that a run-loop is set up and checked.  This should not be
1371 // difficult to implement, simply call gui_mch_update() at opportune moments
1372 // and it will take care of the run-loop.  Another (bigger) problem with
1373 // supporting servers in terminal mode is that the server listing code talks to
1374 // MacVim (the GUI) to figure out which servers are running.
1379  * Register connection with 'name'.  The actual connection is named something
1380  * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1381  */
1382     void
1383 serverRegisterName(char_u *name)
1385 #if MM_ENABLE_CONV
1386     name = CONVERT_TO_UTF8(name);
1387 #endif
1389     NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1390     [[MMBackend sharedInstance] registerServerWithName:svrName];
1392 #if MM_ENABLE_CONV
1393     CONVERT_TO_UTF8_FREE(name);
1394 #endif
1399  * Send to an instance of Vim.
1400  * Returns 0 for OK, negative for an error.
1401  */
1402     int
1403 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1404         int *port, int asExpr, int silent)
1406 #if MM_ENABLE_CONV
1407     name = CONVERT_TO_UTF8(name);
1408     cmd = CONVERT_TO_UTF8(cmd);
1409 #endif
1411     BOOL ok = [[MMBackend sharedInstance]
1412             sendToServer:[NSString stringWithUTF8String:(char*)name]
1413                   string:[NSString stringWithUTF8String:(char*)cmd]
1414                    reply:result
1415                     port:port
1416               expression:asExpr
1417                   silent:silent];
1419 #if MM_ENABLE_CONV
1420     CONVERT_TO_UTF8_FREE(name);
1421     CONVERT_TO_UTF8_FREE(cmd);
1422 #endif
1424     return ok ? 0 : -1;
1429  * Ask MacVim for the names of all Vim servers.
1430  */
1431     char_u *
1432 serverGetVimNames(void)
1434     char_u *names = NULL;
1435     NSArray *list = [[MMBackend sharedInstance] serverList];
1437     if (list) {
1438         NSString *string = [list componentsJoinedByString:@"\n"];
1439         char_u *s = (char_u*)[string UTF8String];
1440 #if MM_ENABLE_CONV
1441         s = CONVERT_FROM_UTF8(s);
1442 #endif
1443         names = vim_strsave(s);
1444 #if MM_ENABLE_CONV
1445         CONVERT_FROM_UTF8_FREE(s);
1446 #endif
1447     }
1449     return names;
1454  * 'str' is a hex int representing the send port of the connection.
1455  */
1456     int
1457 serverStrToPort(char_u *str)
1459     int port = 0;
1461     sscanf((char *)str, "0x%x", &port);
1462     if (!port)
1463         EMSG2(_("E573: Invalid server id used: %s"), str);
1465     return port;
1470  * Check for replies from server with send port 'port'.
1471  * Return TRUE and a non-malloc'ed string if there is.  Else return FALSE.
1472  */
1473     int
1474 serverPeekReply(int port, char_u **str)
1476     NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1477     int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1479     if (str && len > 0) {
1480         *str = (char_u*)[reply UTF8String];
1482 #if MM_ENABLE_CONV
1483         if (input_conv.vc_type != CONV_NONE) {
1484             char_u *s = string_convert(&input_conv, *str, &len);
1486             if (len > 0) {
1487                 // HACK! Since 's' needs to be freed we cannot simply set
1488                 // '*str = s' or memory will leak.  Instead, create a dummy
1489                 // NSData and return its 'bytes' pointer, then autorelease the
1490                 // NSData.
1491                 NSData *data = [NSData dataWithBytes:s length:len+1];
1492                 *str = (char_u*)[data bytes];
1493             }
1495             vim_free(s);
1496         }
1497 #endif
1498     }
1500     return reply != nil;
1505  * Wait for replies from server with send port 'port'.
1506  * Return 0 and the malloc'ed string when a reply is available.
1507  * Return -1 on error.
1508  */
1509     int
1510 serverReadReply(int port, char_u **str)
1512     NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1513     if (reply && str) {
1514         char_u *s = (char_u*)[reply UTF8String];
1515 #if MM_ENABLE_CONV
1516         s = CONVERT_FROM_UTF8(s);
1517 #endif
1518         *str = vim_strsave(s);
1519 #if MM_ENABLE_CONV
1520         CONVERT_FROM_UTF8_FREE(s);
1521 #endif
1522         return 0;
1523     }
1525     return -1;
1530  * Send a reply string (notification) to client with port given by "serverid".
1531  * Return -1 if the window is invalid.
1532  */
1533     int
1534 serverSendReply(char_u *serverid, char_u *reply)
1536     int retval = -1;
1537     int port = serverStrToPort(serverid);
1538     if (port > 0 && reply) {
1539 #if MM_ENABLE_CONV
1540         reply = CONVERT_TO_UTF8(reply);
1541 #endif
1542         BOOL ok = [[MMBackend sharedInstance]
1543                 sendReply:[NSString stringWithUTF8String:(char*)reply]
1544                    toPort:port];
1545         retval = ok ? 0 : -1;
1546 #if MM_ENABLE_CONV
1547         CONVERT_TO_UTF8_FREE(reply);
1548 #endif
1549     }
1551     return retval;
1554 #endif // MAC_CLIENTSERVER