Changed DiffText and Constant highlight groups
[MacVim/jjgod.git] / src / MacVim / gui_macvim.m
blob4ce6b7002f85a8bc84c41eda993e618263b2a25b
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];
148 /* Force flush output to MacVim.  Do not call this method unless absolutely
149  * necessary (use gui_mch_flush() instead). */
150     void
151 gui_macvim_force_flush(void)
153     [[MMBackend sharedInstance] flushQueue:YES];
158  * GUI input routine called by gui_wait_for_chars().  Waits for a character
159  * from the keyboard.
160  *  wtime == -1     Wait forever.
161  *  wtime == 0      This should never happen.
162  *  wtime > 0       Wait wtime milliseconds for a character.
163  * Returns OK if a character was found to be available within the given time,
164  * or FAIL otherwise.
165  */
166     int
167 gui_mch_wait_for_chars(int wtime)
169     // NOTE! In all likelihood Vim will take a nap when waitForInput: is
170     // called, so force a flush of the command queue here.
171     [[MMBackend sharedInstance] flushQueue:YES];
173     return [[MMBackend sharedInstance] waitForInput:wtime];
177 // -- Drawing ---------------------------------------------------------------
181  * Clear the whole text window.
182  */
183     void
184 gui_mch_clear_all(void)
186     [[MMBackend sharedInstance] clearAll];
191  * Clear a rectangular region of the screen from text pos (row1, col1) to
192  * (row2, col2) inclusive.
193  */
194     void
195 gui_mch_clear_block(int row1, int col1, int row2, int col2)
197     [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
198                                                     toRow:row2 column:col2];
203  * Delete the given number of lines from the given row, scrolling up any
204  * text further down within the scroll region.
205  */
206     void
207 gui_mch_delete_lines(int row, int num_lines)
209     [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
210             scrollBottom:gui.scroll_region_bot
211                     left:gui.scroll_region_left
212                    right:gui.scroll_region_right];
216     void
217 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
219 #if MM_ENABLE_CONV
220     char_u *conv_str = NULL;
221     if (output_conv.vc_type != CONV_NONE) {
222         conv_str = string_convert(&output_conv, s, &len);
223         if (conv_str)
224             s = conv_str;
225     }
226 #endif
228     [[MMBackend sharedInstance] replaceString:(char*)s length:len
229             row:row column:col flags:flags];
231 #if MM_ENABLE_CONV
232     if (conv_str)
233         vim_free(conv_str);
234 #endif
238     int
239 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
241     //
242     // Output chars until a wide char found.  If a wide char is found, output a
243     // zero-width space after it so that a wide char looks like two chars to
244     // MMTextStorage.  This way 1 char corresponds to 1 column.
245     //
247     int c;
248     int cn;
249     int cl;
250     int i;
251     int start = 0;
252     int endcol = col;
253     int startcol = col;
254     BOOL outPad = NO;
255     MMBackend *backend = [MMBackend sharedInstance];
256     static char ZeroWidthSpace[] = { 0xe2, 0x80, 0x8b };
257 #if MM_ENABLE_CONV
258     char_u *conv_str = NULL;
260     if (output_conv.vc_type != CONV_NONE) {
261         conv_str = string_convert(&output_conv, s, &len);
262         if (conv_str)
263             s = conv_str;
264     }
265 #endif
267     for (i = 0; i < len; i += cl) {
268         c = utf_ptr2char(s + i);
269         cl = utf_ptr2len(s + i);
270         cn = utf_char2cells(c);
272         if (!utf_iscomposing(c)) {
273             if (outPad) {
274                 outPad = NO;
275 #if 0
276                 NSString *string = [[NSString alloc]
277                         initWithBytesNoCopy:(void*)(s+start)
278                                      length:i-start
279                                    encoding:NSUTF8StringEncoding
280                                freeWhenDone:NO];
281                 NSLog(@"Flushing string=%@ len=%d row=%d col=%d end=%d",
282                         string, i-start, row, startcol, endcol);
283                 [string release];
284 #endif
285                 [backend replaceString:(char*)(s+start) length:i-start
286                         row:row column:startcol flags:flags];
287                 start = i;
288                 startcol = endcol;
289 #if 0
290                 NSLog(@"Padding len=%d row=%d col=%d", sizeof(ZeroWidthSpace),
291                         row, endcol-1);
292 #endif
293                 [backend replaceString:ZeroWidthSpace
294                              length:sizeof(ZeroWidthSpace)
295                         row:row column:endcol-1 flags:flags];
296             }
298             endcol += cn;
299         }
301         if (cn > 1) {
302 #if 0
303             NSLog(@"Wide char detected! (char=%C hex=%x cells=%d)", c, c, cn);
304 #endif
305             outPad = YES;
306         }
307     }
309 #if 0
310     if (row < 1) {
311         NSString *string = [[NSString alloc]
312                 initWithBytesNoCopy:(void*)(s+start)
313                              length:len-start
314                            encoding:NSUTF8StringEncoding
315                        freeWhenDone:NO];
316         NSLog(@"Output string=%@ len=%d row=%d col=%d", string, len-start, row,
317                 startcol);
318         [string release];
319     }
320 #endif
322     // Output remaining characters.
323     [backend replaceString:(char*)(s+start) length:len-start
324             row:row column:startcol flags:flags];
326     if (outPad) {
327 #if 0
328         NSLog(@"Padding len=%d row=%d col=%d", sizeof(ZeroWidthSpace), row,
329                 endcol-1);
330 #endif
331         [backend replaceString:ZeroWidthSpace
332                      length:sizeof(ZeroWidthSpace)
333                 row:row column:endcol-1 flags:flags];
334     }
336 #if MM_ENABLE_CONV
337     if (conv_str)
338         vim_free(conv_str);
339 #endif
341     return endcol - col;
346  * Insert the given number of lines before the given row, scrolling down any
347  * following text within the scroll region.
348  */
349     void
350 gui_mch_insert_lines(int row, int num_lines)
352     [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
353             scrollBottom:gui.scroll_region_bot
354                     left:gui.scroll_region_left
355                    right:gui.scroll_region_right];
360  * Set the current text foreground color.
361  */
362     void
363 gui_mch_set_fg_color(guicolor_T color)
365     [[MMBackend sharedInstance] setForegroundColor:color];
370  * Set the current text background color.
371  */
372     void
373 gui_mch_set_bg_color(guicolor_T color)
375     [[MMBackend sharedInstance] setBackgroundColor:color];
380  * Set the current text special color (used for underlines).
381  */
382     void
383 gui_mch_set_sp_color(guicolor_T color)
385     [[MMBackend sharedInstance] setSpecialColor:color];
390  * Set default colors.
391  */
392     void
393 gui_mch_def_colors()
395     MMBackend *backend = [MMBackend sharedInstance];
397     // The default colors are taken from system values
398     gui.def_norm_pixel = gui.norm_pixel = 
399         [backend lookupColorWithKey:@"MacTextColor"];
400     gui.def_back_pixel = gui.back_pixel = 
401         [backend lookupColorWithKey:@"MacTextBackgroundColor"];
406  * Called when the foreground or background color has been changed.
407  */
408     void
409 gui_mch_new_colors(void)
411     gui.def_back_pixel = gui.back_pixel;
412     gui.def_norm_pixel = gui.norm_pixel;
414     //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
415     //        gui.def_norm_pixel);
417     [[MMBackend sharedInstance]
418         setDefaultColorsBackground:gui.def_back_pixel
419                         foreground:gui.def_norm_pixel];
423 // -- Tabline ---------------------------------------------------------------
427  * Set the current tab to "nr".  First tab is 1.
428  */
429     void
430 gui_mch_set_curtab(int nr)
432     [[MMBackend sharedInstance] selectTab:nr];
437  * Return TRUE when tabline is displayed.
438  */
439     int
440 gui_mch_showing_tabline(void)
442     return [[MMBackend sharedInstance] tabBarVisible];
446  * Update the labels of the tabline.
447  */
448     void
449 gui_mch_update_tabline(void)
451     [[MMBackend sharedInstance] updateTabBar];
455  * Show or hide the tabline.
456  */
457     void
458 gui_mch_show_tabline(int showit)
460     [[MMBackend sharedInstance] showTabBar:showit];
464 // -- Clipboard -------------------------------------------------------------
467     void
468 clip_mch_lose_selection(VimClipboard *cbd)
473     int
474 clip_mch_own_selection(VimClipboard *cbd)
476     return 0;
480     void
481 clip_mch_request_selection(VimClipboard *cbd)
483     NSPasteboard *pb = [NSPasteboard generalPasteboard];
484     NSString *pbType = [pb availableTypeFromArray:
485             [NSArray arrayWithObject:NSStringPboardType]];
486     if (pbType) {
487         NSMutableString *string =
488                 [[pb stringForType:NSStringPboardType] mutableCopy];
490         // Replace unrecognized end-of-line sequences with \x0a (line feed).
491         NSRange range = { 0, [string length] };
492         unsigned n = [string replaceOccurrencesOfString:@"\x0d\x0a"
493                                              withString:@"\x0a" options:0
494                                                   range:range];
495         if (0 == n) {
496             n = [string replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
497                                            options:0 range:range];
498         }
499         
500         // Scan for newline character to decide whether the string should be
501         // pasted linewise or characterwise.
502         int type = MCHAR;
503         if (0 < n || NSNotFound != [string rangeOfString:@"\n"].location)
504             type = MLINE;
506         char_u *str = (char_u*)[string UTF8String];
507         int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
509 #if MM_ENABLE_CONV
510         if (input_conv.vc_type != CONV_NONE)
511             str = string_convert(&input_conv, str, &len);
512 #endif
514         if (str)
515             clip_yank_selection(type, str, len, cbd);
517 #if MM_ENABLE_CONV
518         if (input_conv.vc_type != CONV_NONE)
519             vim_free(str);
520 #endif
521     }
526  * Send the current selection to the clipboard.
527  */
528     void
529 clip_mch_set_selection(VimClipboard *cbd)
531     // If the '*' register isn't already filled in, fill it in now.
532     cbd->owned = TRUE;
533     clip_get_selection(cbd);
534     cbd->owned = FALSE;
535     
536     // Get the text to put on the pasteboard.
537     long_u llen = 0; char_u *str = 0;
538     int type = clip_convert_selection(&str, &llen, cbd);
539     if (type < 0)
540         return;
542     // TODO: Avoid overflow.
543     int len = (int)llen;
544 #if MM_ENABLE_CONV
545     if (output_conv.vc_type != CONV_NONE) {
546         char_u *conv_str = string_convert(&output_conv, str, &len);
547         if (conv_str) {
548             vim_free(str);
549             str = conv_str;
550         }
551     }
552 #endif
554     if (len > 0) {
555         NSString *string = [[NSString alloc]
556             initWithBytes:str length:len encoding:NSUTF8StringEncoding];
558         NSPasteboard *pb = [NSPasteboard generalPasteboard];
559         [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType]
560                    owner:nil];
561         [pb setString:string forType:NSStringPboardType];
562         
563         [string release];
564     }
566     vim_free(str);
570 // -- Menu ------------------------------------------------------------------
574  * Add a sub menu to the menu bar.
575  */
576     void
577 gui_mch_add_menu(vimmenu_T *menu, int idx)
579     // HACK!  If menu has no parent, then we set the parent tag to the type of
580     // menu it is.  This will not mix up tag and type because pointers can not
581     // take values close to zero (and the tag is simply the value of the
582     // pointer).
583     int parent = (int)menu->parent;
584     if (!parent) {
585         parent = menu_is_popup(menu->name) ? MenuPopupType :
586                  menu_is_toolbar(menu->name) ? MenuToolbarType :
587                  MenuMenubarType;
588     }
590     char_u *dname = menu->dname;
591 #if MM_ENABLE_CONV
592     dname = CONVERT_TO_UTF8(dname);
593 #endif
595     [[MMBackend sharedInstance]
596             addMenuWithTag:(int)menu parent:parent name:(char*)dname
597                    atIndex:idx];
599 #if MM_ENABLE_CONV
600     CONVERT_TO_UTF8_FREE(dname);
601 #endif
606  * Add a menu item to a menu
607  */
608     void
609 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
611     // NOTE!  If 'iconfile' is not set but 'iconidx' is, use the name of the
612     // menu item.  (Should correspond to a stock item.)
613     char_u *icon = menu->iconfile ? menu->iconfile :
614                  menu->iconidx >= 0 ? menu->dname :
615                  NULL;
616     //char *name = menu_is_separator(menu->name) ? NULL : (char*)menu->dname;
617     char_u *name = menu->dname;
618     char_u *tip = menu->strings[MENU_INDEX_TIP]
619             ? menu->strings[MENU_INDEX_TIP] : menu->actext;
620     char_u *map_str = menu->strings[MENU_INDEX_NORMAL];
622 #if MM_ENABLE_CONV
623     icon = CONVERT_TO_UTF8(icon);
624     name = CONVERT_TO_UTF8(name);
625     tip = CONVERT_TO_UTF8(tip);
626     map_str = CONVERT_TO_UTF8(map_str);
627 #endif
629     // HACK!  Check if menu is mapped to ':macaction actionName:'; if so, pass
630     // the action along so that MacVim can bind the menu item to this action.
631     // This means that if a menu item maps to an action in normal mode, then
632     // all other modes will also use the same action.
633     NSString *action = nil;
634     if (map_str) {
635         NSString *mapping = [NSString stringWithCString:(char*)map_str
636                                                encoding:NSUTF8StringEncoding];
637         NSArray *parts = [mapping componentsSeparatedByString:@" "];
638         if ([parts count] >=2 
639                 && [[parts objectAtIndex:0] hasPrefix:@":maca"]) {
640             action = [parts objectAtIndex:1];
641             action = [action stringByTrimmingCharactersInSet:
642                     [NSCharacterSet whitespaceAndNewlineCharacterSet]];
643             if (!gui_macvim_is_valid_action(action))
644                 action = nil;
645         }
646     }
648     [[MMBackend sharedInstance]
649             addMenuItemWithTag:(int)menu
650                         parent:(int)menu->parent
651                           name:(char*)name
652                            tip:(char*)tip
653                           icon:(char*)icon
654                  keyEquivalent:menu->mac_key
655                      modifiers:menu->mac_mods
656                         action:action
657                        atIndex:idx];
659 #if MM_ENABLE_CONV
660     CONVERT_TO_UTF8_FREE(icon);
661     CONVERT_TO_UTF8_FREE(name);
662     CONVERT_TO_UTF8_FREE(tip);
663     CONVERT_TO_UTF8_FREE(map_str);
664 #endif
669  * Destroy the machine specific menu widget.
670  */
671     void
672 gui_mch_destroy_menu(vimmenu_T *menu)
674     [[MMBackend sharedInstance] removeMenuItemWithTag:(int)menu];
679  * Make a menu either grey or not grey.
680  */
681     void
682 gui_mch_menu_grey(vimmenu_T *menu, int grey)
684     /* Only update menu if the 'grey' state has changed to avoid having to pass
685      * lots of unnecessary data to MacVim.  (Skipping this test makes MacVim
686      * pause noticably on mode changes. */
687     if (menu->was_grey != grey)
688     {
689         menu->was_grey = grey;
690         [[MMBackend sharedInstance]
691                 enableMenuItemWithTag:(int)menu state:!grey];
692     }
697  * Make menu item hidden or not hidden
698  */
699     void
700 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
702     // HACK! There is no (obvious) way to hide a menu item, so simply
703     // enable/disable it instead.
704     gui_mch_menu_grey(menu, hidden);
709  * This is called when user right clicks.
710  */
711     void
712 gui_mch_show_popupmenu(vimmenu_T *menu)
714     char_u *name = menu->name;
715 #if MM_ENABLE_CONV
716     name = CONVERT_TO_UTF8(name);
717 #endif
719     [[MMBackend sharedInstance] showPopupMenuWithName:(char*)name
720                                       atMouseLocation:YES];
722 #if MM_ENABLE_CONV
723     CONVERT_TO_UTF8_FREE(name);
724 #endif
730  * This is called when a :popup command is executed.
731  */
732     void
733 gui_make_popup(char_u *path_name, int mouse_pos)
735 #if MM_ENABLE_CONV
736     path_name = CONVERT_TO_UTF8(path_name);
737 #endif
739     [[MMBackend sharedInstance] showPopupMenuWithName:(char*)path_name
740                                       atMouseLocation:mouse_pos];
742 #if MM_ENABLE_CONV
743     CONVERT_TO_UTF8_FREE(path_name);
744 #endif
749  * This is called after setting all the menus to grey/hidden or not.
750  */
751     void
752 gui_mch_draw_menubar(void)
754     // The (main) menu draws itself in Mac OS X.
758     void
759 gui_mch_enable_menu(int flag)
761     // The (main) menu is always enabled in Mac OS X.
765 #if 0
766     void
767 gui_mch_set_menu_pos(int x, int y, int w, int h)
769     // The (main) menu cannot be moved in Mac OS X.
771 #endif
774     void
775 gui_mch_show_toolbar(int showit)
777     int flags = 0;
778     if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
779     if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
780     if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
782     [[MMBackend sharedInstance] showToolbar:showit flags:flags];
788 // -- Fonts -----------------------------------------------------------------
792  * If a font is not going to be used, free its structure.
793  */
794     void
795 gui_mch_free_font(font)
796     GuiFont     font;
802  * Get a font structure for highlighting.
803  */
804     GuiFont
805 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
807     //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
808     //        giveErrorIfMissing);
809     return 0;
813 #if defined(FEAT_EVAL) || defined(PROTO)
815  * Return the name of font "font" in allocated memory.
816  * Don't know how to get the actual name, thus use the provided name.
817  */
818     char_u *
819 gui_mch_get_fontname(GuiFont font, char_u *name)
821     //NSLog(@"gui_mch_get_fontname(font=%d, name=%s)", font, name);
822     return 0;
824 #endif
828  * Initialise vim to use the font with the given name.  Return FAIL if the font
829  * could not be loaded, OK otherwise.
830  */
831     int
832 gui_mch_init_font(char_u *font_name, int fontset)
834     //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
836     // HACK!  This gets called whenever the user types :set gfn=fontname, so
837     // for now we set the font here.
838     // TODO!  Proper font handling, the way Vim expects it.
840 #if MM_ENABLE_CONV
841     font_name = CONVERT_TO_UTF8(font_name);
842 #endif
844     BOOL ok = [[MMBackend sharedInstance] setFontWithName:(char*)font_name];
846 #if MM_ENABLE_CONV
847     CONVERT_TO_UTF8_FREE(font_name);
848 #endif
850     return ok;
855  * Set the current text font.
856  */
857     void
858 gui_mch_set_font(GuiFont font)
863 // -- Scrollbars ------------------------------------------------------------
866     void
867 gui_mch_create_scrollbar(
868         scrollbar_T *sb,
869         int orient)     /* SBAR_VERT or SBAR_HORIZ */
871     [[MMBackend sharedInstance] 
872             createScrollbarWithIdentifier:sb->ident type:sb->type];
876     void
877 gui_mch_destroy_scrollbar(scrollbar_T *sb)
879     [[MMBackend sharedInstance] 
880             destroyScrollbarWithIdentifier:sb->ident];
884     void
885 gui_mch_enable_scrollbar(
886         scrollbar_T     *sb,
887         int             flag)
889     [[MMBackend sharedInstance] 
890             showScrollbarWithIdentifier:sb->ident state:flag];
894     void
895 gui_mch_set_scrollbar_pos(
896         scrollbar_T *sb,
897         int x,
898         int y,
899         int w,
900         int h)
902     int pos = y;
903     int len = h;
904     if (SBAR_BOTTOM == sb->type) {
905         pos = x;
906         len = w; 
907     }
909     [[MMBackend sharedInstance] 
910             setScrollbarPosition:pos length:len identifier:sb->ident];
914     void
915 gui_mch_set_scrollbar_thumb(
916         scrollbar_T *sb,
917         long val,
918         long size,
919         long max)
921     [[MMBackend sharedInstance] 
922             setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
926 // -- Cursor ----------------------------------------------------------------
930  * Draw a cursor without focus.
931  */
932     void
933 gui_mch_draw_hollow_cursor(guicolor_T color)
935     return [[MMBackend sharedInstance]
936         drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
937                fraction:100 color:color];
942  * Draw part of a cursor, only w pixels wide, and h pixels high.
943  */
944     void
945 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
947     // HACK!  'w' and 'h' are always 1 since we do not tell Vim about the exact
948     // font dimensions.  Thus these parameters are useless.  Instead we look at
949     // the shape_table to determine the shape and size of the cursor (just like
950     // gui_update_cursor() does).
951     int idx = get_shape_idx(FALSE);
952     int shape = MMInsertionPointBlock;
953     switch (shape_table[idx].shape) {
954         case SHAPE_HOR: shape = MMInsertionPointHorizontal; break;
955         case SHAPE_VER: shape = MMInsertionPointVertical; break;
956     }
958     return [[MMBackend sharedInstance]
959         drawCursorAtRow:gui.row column:gui.col shape:shape
960                fraction:shape_table[idx].percentage color:color];
965  * Cursor blink functions.
967  * This is a simple state machine:
968  * BLINK_NONE   not blinking at all
969  * BLINK_OFF    blinking, cursor is not shown
970  * BLINK_ON blinking, cursor is shown
971  */
972     void
973 gui_mch_set_blinking(long wait, long on, long off)
975     [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
980  * Start the cursor blinking.  If it was already blinking, this restarts the
981  * waiting time and shows the cursor.
982  */
983     void
984 gui_mch_start_blink(void)
986     [[MMBackend sharedInstance] startBlink];
991  * Stop the cursor blinking.  Show the cursor if it wasn't shown.
992  */
993     void
994 gui_mch_stop_blink(void)
996     [[MMBackend sharedInstance] stopBlink];
1000 // -- Mouse -----------------------------------------------------------------
1004  * Get current mouse coordinates in text window.
1005  */
1006     void
1007 gui_mch_getmouse(int *x, int *y)
1009     //NSLog(@"gui_mch_getmouse()");
1013     void
1014 gui_mch_setmouse(int x, int y)
1016     //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1020     void
1021 mch_set_mouse_shape(int shape)
1023     [[MMBackend sharedInstance] setMouseShape:shape];
1029 // -- Unsorted --------------------------------------------------------------
1032     void
1033 ex_macaction(eap)
1034     exarg_T     *eap;
1036     if (!gui.in_use) {
1037         EMSG(_("E???: Command only available in GUI mode"));
1038         return;
1039     }
1041     char_u *arg = eap->arg;
1042 #if MM_ENABLE_CONV
1043     arg = CONVERT_TO_UTF8(arg);
1044 #endif
1046     NSString *name = [NSString stringWithCString:(char*)arg
1047                                         encoding:NSUTF8StringEncoding];
1048     if (gui_macvim_is_valid_action(name)) {
1049         [[MMBackend sharedInstance] executeActionWithName:name];
1050     } else {
1051         EMSG2(_("E???: \"%s\" is not a valid action"), eap->arg);
1052     }
1054 #if MM_ENABLE_CONV
1055     arg = CONVERT_TO_UTF8(arg);
1056 #endif
1061  * Adjust gui.char_height (after 'linespace' was changed).
1062  */
1063     int
1064 gui_mch_adjust_charheight(void)
1066     [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1067     return OK;
1071     void
1072 gui_mch_beep(void)
1078 #ifdef FEAT_BROWSE
1080  * Pop open a file browser and return the file selected, in allocated memory,
1081  * or NULL if Cancel is hit.
1082  *  saving  - TRUE if the file will be saved to, FALSE if it will be opened.
1083  *  title   - Title message for the file browser dialog.
1084  *  dflt    - Default name of file.
1085  *  ext     - Default extension to be added to files without extensions.
1086  *  initdir - directory in which to open the browser (NULL = current dir)
1087  *  filter  - Filter for matched files to choose from.
1088  *  Has a format like this:
1089  *  "C Files (*.c)\0*.c\0"
1090  *  "All Files\0*.*\0\0"
1091  *  If these two strings were concatenated, then a choice of two file
1092  *  filters will be selectable to the user.  Then only matching files will
1093  *  be shown in the browser.  If NULL, the default allows all files.
1095  *  *NOTE* - the filter string must be terminated with TWO nulls.
1096  */
1097     char_u *
1098 gui_mch_browse(
1099     int saving,
1100     char_u *title,
1101     char_u *dflt,
1102     char_u *ext,
1103     char_u *initdir,
1104     char_u *filter)
1106     //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1107     //        " filter=%s", saving, title, dflt, ext, initdir, filter);
1109 #if MM_ENABLE_CONV
1110     title = CONVERT_TO_UTF8(title);
1111     initdir = CONVERT_TO_UTF8(initdir);
1112 #endif
1114     char_u *s = (char_u*)[[MMBackend sharedInstance]
1115             browseForFileInDirectory:(char*)initdir title:(char*)title
1116                               saving:saving];
1118 #if MM_ENABLE_CONV
1119     CONVERT_TO_UTF8_FREE(title);
1120     CONVERT_TO_UTF8_FREE(initdir);
1121 #endif
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 #if MM_ENABLE_CONV
1143     title = CONVERT_TO_UTF8(title);
1144     message = CONVERT_TO_UTF8(message);
1145     buttons = CONVERT_TO_UTF8(buttons);
1146     textfield = CONVERT_TO_UTF8(textfield);
1147 #endif
1149     int ret = [[MMBackend sharedInstance]
1150             presentDialogWithType:type
1151                             title:(char*)title
1152                           message:(char*)message
1153                           buttons:(char*)buttons
1154                         textField:(char*)textfield];
1156 #if MM_ENABLE_CONV
1157     CONVERT_TO_UTF8_FREE(title);
1158     CONVERT_TO_UTF8_FREE(message);
1159     CONVERT_TO_UTF8_FREE(buttons);
1160     CONVERT_TO_UTF8_FREE(textfield);
1161 #endif
1163     return ret;
1167     void
1168 gui_mch_flash(int msec)
1174  * Return the Pixel value (color) for the given color name.  This routine was
1175  * pretty much taken from example code in the Silicon Graphics OSF/Motif
1176  * Programmer's Guide.
1177  * Return INVALCOLOR when failed.
1178  */
1179     guicolor_T
1180 gui_mch_get_color(char_u *name)
1182 #if MM_ENABLE_CONV
1183     name = CONVERT_TO_UTF8(name);
1184 #endif
1186     NSString *key = [NSString stringWithUTF8String:(char*)name];
1187     guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1189 #if MM_ENABLE_CONV
1190     CONVERT_TO_UTF8_FREE(name);
1191 #endif
1193     return col;
1198  * Return the RGB value of a pixel as long.
1199  */
1200     long_u
1201 gui_mch_get_rgb(guicolor_T pixel)
1203     // This is only implemented so that vim can guess the correct value for
1204     // 'background' (which otherwise defaults to 'dark'); it is not used for
1205     // anything else (as far as I know).
1206     // The implementation is simple since colors are stored in an int as
1207     // "rrggbb".
1208     return pixel;
1213  * Get the screen dimensions.
1214  * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1215  * Is there no way to find out how wide the borders really are?
1216  * TODO: Add live udate of those value on suspend/resume.
1217  */
1218     void
1219 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1221     //NSLog(@"gui_mch_get_screen_dimensions()");
1222     *screen_w = Columns;
1223     *screen_h = Rows;
1228  * Get the position of the top left corner of the window.
1229  */
1230     int
1231 gui_mch_get_winpos(int *x, int *y)
1233     *x = *y = 0;
1234     return OK;
1239  * Return OK if the key with the termcap name "name" is supported.
1240  */
1241     int
1242 gui_mch_haskey(char_u *name)
1244     BOOL ok = NO;
1246 #if MM_ENABLE_CONV
1247     name = CONVERT_TO_UTF8(name);
1248 #endif
1250     NSString *value = [NSString stringWithUTF8String:(char*)name];
1251     if (value)
1252         ok =  [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1254 #if MM_ENABLE_CONV
1255     CONVERT_TO_UTF8_FREE(name);
1256 #endif
1258     return ok;
1263  * Iconify the GUI window.
1264  */
1265     void
1266 gui_mch_iconify(void)
1272  * Invert a rectangle from row r, column c, for nr rows and nc columns.
1273  */
1274     void
1275 gui_mch_invert_rectangle(int r, int c, int nr, int nc)
1280 #if defined(FEAT_EVAL) || defined(PROTO)
1282  * Bring the Vim window to the foreground.
1283  */
1284     void
1285 gui_mch_set_foreground(void)
1287     [[MMBackend sharedInstance] activate];
1289 #endif
1293     void
1294 gui_mch_set_shellsize(
1295     int         width,
1296     int         height,
1297     int         min_width,
1298     int         min_height,
1299     int         base_width,
1300     int         base_height,
1301     int         direction)
1303     //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1304     //        " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1305     //        width, height, min_width, min_height, base_width, base_height,
1306     //        direction);
1307     [[MMBackend sharedInstance] setRows:height columns:width];
1311     void
1312 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1317  * Set the position of the top left corner of the window to the given
1318  * coordinates.
1319  */
1320     void
1321 gui_mch_set_winpos(int x, int y)
1326 #ifdef FEAT_TITLE
1328  * Set the window title and icon.
1329  * (The icon is not taken care of).
1330  */
1331     void
1332 gui_mch_settitle(char_u *title, char_u *icon)
1334     //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1336 #if MM_ENABLE_CONV
1337     title = CONVERT_TO_UTF8(title);
1338 #endif
1340     [[MMBackend sharedInstance] setWindowTitle:(char*)title];
1342 #if MM_ENABLE_CONV
1343     CONVERT_TO_UTF8_FREE(title);
1344 #endif
1346 #endif
1349     void
1350 gui_mch_toggle_tearoffs(int enable)
1355     static BOOL
1356 gui_macvim_is_valid_action(NSString *action)
1358     static NSDictionary *actionDict = nil;
1360     if (!actionDict) {
1361         NSBundle *mainBundle = [NSBundle mainBundle];
1362         NSString *path = [mainBundle pathForResource:@"Actions"
1363                                               ofType:@"plist"];
1364         if (path) {
1365             actionDict = [[NSDictionary alloc] initWithContentsOfFile:path];
1366         } else {
1367             // Allocate bogus dictionary so that error only pops up once.
1368             actionDict = [NSDictionary new];
1369             EMSG(_("E???: Failed to load action dictionary"));
1370         }
1371     }
1373     return [actionDict objectForKey:action] != nil;
1377     void
1378 gui_mch_enter_fullscreen()
1380     [[MMBackend sharedInstance] enterFullscreen];
1384     void
1385 gui_mch_leave_fullscreen()
1387     [[MMBackend sharedInstance] leaveFullscreen];
1391     void
1392 gui_macvim_update_modified_flag()
1394     [[MMBackend sharedInstance] updateModifiedFlag];
1400 // -- Client/Server ---------------------------------------------------------
1402 #ifdef MAC_CLIENTSERVER
1405 // NOTE: Client/Server is only fully supported with a GUI.  Theoretically it
1406 // would be possible to make the server code work with terminal Vim, but it
1407 // would require that a run-loop is set up and checked.  This should not be
1408 // difficult to implement, simply call gui_mch_update() at opportune moments
1409 // and it will take care of the run-loop.  Another (bigger) problem with
1410 // supporting servers in terminal mode is that the server listing code talks to
1411 // MacVim (the GUI) to figure out which servers are running.
1416  * Register connection with 'name'.  The actual connection is named something
1417  * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1418  */
1419     void
1420 serverRegisterName(char_u *name)
1422 #if MM_ENABLE_CONV
1423     name = CONVERT_TO_UTF8(name);
1424 #endif
1426     NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1427     [[MMBackend sharedInstance] registerServerWithName:svrName];
1429 #if MM_ENABLE_CONV
1430     CONVERT_TO_UTF8_FREE(name);
1431 #endif
1436  * Send to an instance of Vim.
1437  * Returns 0 for OK, negative for an error.
1438  */
1439     int
1440 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1441         int *port, int asExpr, int silent)
1443 #if MM_ENABLE_CONV
1444     name = CONVERT_TO_UTF8(name);
1445     cmd = CONVERT_TO_UTF8(cmd);
1446 #endif
1448     BOOL ok = [[MMBackend sharedInstance]
1449             sendToServer:[NSString stringWithUTF8String:(char*)name]
1450                   string:[NSString stringWithUTF8String:(char*)cmd]
1451                    reply:result
1452                     port:port
1453               expression:asExpr
1454                   silent:silent];
1456 #if MM_ENABLE_CONV
1457     CONVERT_TO_UTF8_FREE(name);
1458     CONVERT_TO_UTF8_FREE(cmd);
1459 #endif
1461     return ok ? 0 : -1;
1466  * Ask MacVim for the names of all Vim servers.
1467  */
1468     char_u *
1469 serverGetVimNames(void)
1471     char_u *names = NULL;
1472     NSArray *list = [[MMBackend sharedInstance] serverList];
1474     if (list) {
1475         NSString *string = [list componentsJoinedByString:@"\n"];
1476         char_u *s = (char_u*)[string UTF8String];
1477 #if MM_ENABLE_CONV
1478         s = CONVERT_FROM_UTF8(s);
1479 #endif
1480         names = vim_strsave(s);
1481 #if MM_ENABLE_CONV
1482         CONVERT_FROM_UTF8_FREE(s);
1483 #endif
1484     }
1486     return names;
1491  * 'str' is a hex int representing the send port of the connection.
1492  */
1493     int
1494 serverStrToPort(char_u *str)
1496     int port = 0;
1498     sscanf((char *)str, "0x%x", &port);
1499     if (!port)
1500         EMSG2(_("E573: Invalid server id used: %s"), str);
1502     return port;
1507  * Check for replies from server with send port 'port'.
1508  * Return TRUE and a non-malloc'ed string if there is.  Else return FALSE.
1509  */
1510     int
1511 serverPeekReply(int port, char_u **str)
1513     NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1514     int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1516     if (str && len > 0) {
1517         *str = (char_u*)[reply UTF8String];
1519 #if MM_ENABLE_CONV
1520         if (input_conv.vc_type != CONV_NONE) {
1521             char_u *s = string_convert(&input_conv, *str, &len);
1523             if (len > 0) {
1524                 // HACK! Since 's' needs to be freed we cannot simply set
1525                 // '*str = s' or memory will leak.  Instead, create a dummy
1526                 // NSData and return its 'bytes' pointer, then autorelease the
1527                 // NSData.
1528                 NSData *data = [NSData dataWithBytes:s length:len+1];
1529                 *str = (char_u*)[data bytes];
1530             }
1532             vim_free(s);
1533         }
1534 #endif
1535     }
1537     return reply != nil;
1542  * Wait for replies from server with send port 'port'.
1543  * Return 0 and the malloc'ed string when a reply is available.
1544  * Return -1 on error.
1545  */
1546     int
1547 serverReadReply(int port, char_u **str)
1549     NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1550     if (reply && str) {
1551         char_u *s = (char_u*)[reply UTF8String];
1552 #if MM_ENABLE_CONV
1553         s = CONVERT_FROM_UTF8(s);
1554 #endif
1555         *str = vim_strsave(s);
1556 #if MM_ENABLE_CONV
1557         CONVERT_FROM_UTF8_FREE(s);
1558 #endif
1559         return 0;
1560     }
1562     return -1;
1567  * Send a reply string (notification) to client with port given by "serverid".
1568  * Return -1 if the window is invalid.
1569  */
1570     int
1571 serverSendReply(char_u *serverid, char_u *reply)
1573     int retval = -1;
1574     int port = serverStrToPort(serverid);
1575     if (port > 0 && reply) {
1576 #if MM_ENABLE_CONV
1577         reply = CONVERT_TO_UTF8(reply);
1578 #endif
1579         BOOL ok = [[MMBackend sharedInstance]
1580                 sendReply:[NSString stringWithUTF8String:(char*)reply]
1581                    toPort:port];
1582         retval = ok ? 0 : -1;
1583 #if MM_ENABLE_CONV
1584         CONVERT_TO_UTF8_FREE(reply);
1585 #endif
1586     }
1588     return retval;
1591 #endif // MAC_CLIENTSERVER