1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
3 * VIM - Vi IMproved by Bram Moolenaar
4 * MacVim GUI port by Bjorn Winckler
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.
13 * Hooks for the Vim gui code. Mainly passes control on to MMBackend.
16 #import <Foundation/Foundation.h>
23 // This constant controls how often [MMBackend update] may get called (see
25 static NSTimeInterval MMUpdateTimeoutInterval = 0.1f;
27 // NOTE: The default font is bundled with the application.
28 static NSString *MMDefaultFontName = @"DejaVu Sans Mono";
29 static float MMDefaultFontSize = 12.0f;
30 static float MMMinFontSize = 6.0f;
31 static float MMMaxFontSize = 100.0f;
34 static NSFont *gui_macvim_font_with_name(char_u *name);
35 static BOOL gui_macvim_is_valid_action(NSString *action);
39 // -- Initialization --------------------------------------------------------
42 * Parse the GUI related command-line arguments. Any arguments used are
43 * deleted from argv, and *argc is decremented accordingly. This is called
44 * when vim is started, whether or not the GUI has been started.
47 gui_mch_prepare(int *argc, char **argv)
49 //NSLog(@"gui_mch_prepare(argc=%d)", *argc);
51 // Set environment variables $VIM and $VIMRUNTIME
52 // NOTE! If vim_getenv is called with one of these as parameters before
53 // they have been set here, they will most likely end up with the wrong
57 // - ensure this is called first to avoid above problem
60 NSString *path = [[[NSBundle mainBundle] resourcePath]
61 stringByAppendingPathComponent:@"vim"];
62 vim_setenv((char_u*)"VIM", (char_u*)[path UTF8String]);
64 path = [path stringByAppendingPathComponent:@"runtime"];
65 vim_setenv((char_u*)"VIMRUNTIME", (char_u*)[path UTF8String]);
70 * Check if the GUI can be started. Called before gvimrc is sourced.
74 gui_mch_init_check(void)
76 //NSLog(@"gui_mch_init_check()");
82 * Initialise the GUI. Create all the windows, set up all the call-backs etc.
83 * Returns OK for success, FAIL when the GUI can't be started.
88 //NSLog(@"gui_mch_init()");
90 if (![[MMBackend sharedInstance] checkin])
93 // Force 'termencoding' to utf-8 (changes to 'tenc' are disallowed in
94 // 'option.c', so that ':set termencoding=...' is impossible).
95 set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
97 // Set values so that pixels and characters are in one-to-one
98 // correspondence (assuming all characters have the same dimensions).
99 gui.scrollbar_width = gui.scrollbar_height = 0;
105 gui_mch_def_colors();
107 [[MMBackend sharedInstance]
108 setDefaultColorsBackground:gui.back_pixel foreground:gui.norm_pixel];
109 [[MMBackend sharedInstance] setBackgroundColor:gui.back_pixel];
110 [[MMBackend sharedInstance] setForegroundColor:gui.norm_pixel];
112 // NOTE: If this call is left out the cursor is opaque.
113 highlight_gui_started();
123 //NSLog(@"gui_mch_exit(rc=%d)", rc);
125 [[MMBackend sharedInstance] exit];
130 * Open the GUI window which was created by a call to gui_mch_init().
135 //NSLog(@"gui_mch_open()");
137 return [[MMBackend sharedInstance] openVimWindow];
141 // -- Updating --------------------------------------------------------------
145 * Catch up with any queued X events. This may put keyboard input into the
146 * input buffer, call resize call-backs, trigger timers etc. If there is
147 * nothing in the X event queue (& no timers pending), then we return
150 #define MM_LOG_UPDATE_STATS 0
154 // NOTE: This function can get called A LOT (~1 call/ms) and unfortunately
155 // checking the run loop takes a long time, resulting in noticable slow
156 // downs if it is done every time this function is called. Therefore we
157 // make sure that it is not done too often.
158 static NSDate *lastUpdateDate = nil;
159 #if MM_LOG_UPDATE_STATS
160 static int skipCount = 0;
163 if (lastUpdateDate && -[lastUpdateDate timeIntervalSinceNow] <
164 MMUpdateTimeoutInterval) {
165 #if MM_LOG_UPDATE_STATS
171 #if MM_LOG_UPDATE_STATS
172 NSTimeInterval dt = -[lastUpdateDate timeIntervalSinceNow];
173 NSLog(@"Updating (last update %.2f seconds ago, skipped %d updates, "
174 "approx %.1f calls per second)",
175 dt, skipCount, dt > 0 ? skipCount/dt : 0);
179 [[MMBackend sharedInstance] update];
181 [lastUpdateDate release];
182 lastUpdateDate = [[NSDate date] retain];
186 /* Flush any output to the screen */
190 [[MMBackend sharedInstance] flushQueue:NO];
194 /* Force flush output to MacVim. Do not call this method unless absolutely
195 * necessary (use gui_mch_flush() instead). */
197 gui_macvim_force_flush(void)
199 [[MMBackend sharedInstance] flushQueue:YES];
204 * GUI input routine called by gui_wait_for_chars(). Waits for a character
206 * wtime == -1 Wait forever.
207 * wtime == 0 This should never happen.
208 * wtime > 0 Wait wtime milliseconds for a character.
209 * Returns OK if a character was found to be available within the given time,
213 gui_mch_wait_for_chars(int wtime)
215 // NOTE! In all likelihood Vim will take a nap when waitForInput: is
216 // called, so force a flush of the command queue here.
217 [[MMBackend sharedInstance] flushQueue:YES];
219 return [[MMBackend sharedInstance] waitForInput:wtime];
223 // -- Drawing ---------------------------------------------------------------
227 * Clear the whole text window.
230 gui_mch_clear_all(void)
232 [[MMBackend sharedInstance] clearAll];
237 * Clear a rectangular region of the screen from text pos (row1, col1) to
238 * (row2, col2) inclusive.
241 gui_mch_clear_block(int row1, int col1, int row2, int col2)
243 [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
244 toRow:row2 column:col2];
249 * Delete the given number of lines from the given row, scrolling up any
250 * text further down within the scroll region.
253 gui_mch_delete_lines(int row, int num_lines)
255 [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
256 scrollBottom:gui.scroll_region_bot
257 left:gui.scroll_region_left
258 right:gui.scroll_region_right];
263 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
266 char_u *conv_str = NULL;
267 if (output_conv.vc_type != CONV_NONE) {
268 conv_str = string_convert(&output_conv, s, &len);
274 [[MMBackend sharedInstance] drawString:(char*)s length:len row:row
275 column:col cells:len flags:flags];
285 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
292 MMBackend *backend = [MMBackend sharedInstance];
294 char_u *conv_str = NULL;
296 if (output_conv.vc_type != CONV_NONE) {
297 conv_str = string_convert(&output_conv, s, &len);
303 // Loop over each character and output text when it changes from normal to
304 // wide and vice versa.
305 for (i = 0; i < len; i += cl) {
306 c = utf_ptr2char(s + i);
307 cl = utf_ptr2len(s + i);
308 cn = utf_char2cells(c);
310 if (!utf_iscomposing(c)) {
311 if ((cn > 1 && !wide) || (cn <= 1 && wide)) {
312 // Changed from normal to wide or vice versa.
313 [backend drawString:(char*)(s+start) length:i-start
314 row:row column:startcol
315 cells:endcol-startcol
316 flags:(wide ? flags|DRAW_WIDE : flags)];
327 // Output remaining characters.
328 [backend drawString:(char*)(s+start) length:len-start
329 row:row column:startcol cells:endcol-startcol
330 flags:(wide ? flags|DRAW_WIDE : flags)];
342 * Insert the given number of lines before the given row, scrolling down any
343 * following text within the scroll region.
346 gui_mch_insert_lines(int row, int num_lines)
348 [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
349 scrollBottom:gui.scroll_region_bot
350 left:gui.scroll_region_left
351 right:gui.scroll_region_right];
356 * Set the current text foreground color.
359 gui_mch_set_fg_color(guicolor_T color)
361 [[MMBackend sharedInstance] setForegroundColor:color];
366 * Set the current text background color.
369 gui_mch_set_bg_color(guicolor_T color)
371 [[MMBackend sharedInstance] setBackgroundColor:color];
376 * Set the current text special color (used for underlines).
379 gui_mch_set_sp_color(guicolor_T color)
381 [[MMBackend sharedInstance] setSpecialColor:color];
386 * Set default colors.
391 MMBackend *backend = [MMBackend sharedInstance];
393 // The default colors are taken from system values
394 gui.def_norm_pixel = gui.norm_pixel =
395 [backend lookupColorWithKey:@"MacTextColor"];
396 gui.def_back_pixel = gui.back_pixel =
397 [backend lookupColorWithKey:@"MacTextBackgroundColor"];
402 * Called when the foreground or background color has been changed.
405 gui_mch_new_colors(void)
407 gui.def_back_pixel = gui.back_pixel;
408 gui.def_norm_pixel = gui.norm_pixel;
410 //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
411 // gui.def_norm_pixel);
413 [[MMBackend sharedInstance]
414 setDefaultColorsBackground:gui.def_back_pixel
415 foreground:gui.def_norm_pixel];
419 // -- Tabline ---------------------------------------------------------------
423 * Set the current tab to "nr". First tab is 1.
426 gui_mch_set_curtab(int nr)
428 [[MMBackend sharedInstance] selectTab:nr];
433 * Return TRUE when tabline is displayed.
436 gui_mch_showing_tabline(void)
438 return [[MMBackend sharedInstance] tabBarVisible];
442 * Update the labels of the tabline.
445 gui_mch_update_tabline(void)
447 [[MMBackend sharedInstance] updateTabBar];
451 * Show or hide the tabline.
454 gui_mch_show_tabline(int showit)
456 [[MMBackend sharedInstance] showTabBar:showit];
460 // -- Clipboard -------------------------------------------------------------
464 clip_mch_lose_selection(VimClipboard *cbd)
470 clip_mch_own_selection(VimClipboard *cbd)
477 clip_mch_request_selection(VimClipboard *cbd)
479 NSPasteboard *pb = [NSPasteboard generalPasteboard];
480 NSString *pbType = [pb availableTypeFromArray:
481 [NSArray arrayWithObject:NSStringPboardType]];
483 NSMutableString *string =
484 [[pb stringForType:NSStringPboardType] mutableCopy];
486 // Replace unrecognized end-of-line sequences with \x0a (line feed).
487 NSRange range = { 0, [string length] };
488 unsigned n = [string replaceOccurrencesOfString:@"\x0d\x0a"
489 withString:@"\x0a" options:0
492 n = [string replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
493 options:0 range:range];
496 // Scan for newline character to decide whether the string should be
497 // pasted linewise or characterwise.
499 if (0 < n || NSNotFound != [string rangeOfString:@"\n"].location)
502 char_u *str = (char_u*)[string UTF8String];
503 int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
506 if (input_conv.vc_type != CONV_NONE)
507 str = string_convert(&input_conv, str, &len);
511 clip_yank_selection(type, str, len, cbd);
514 if (input_conv.vc_type != CONV_NONE)
522 * Send the current selection to the clipboard.
525 clip_mch_set_selection(VimClipboard *cbd)
527 // If the '*' register isn't already filled in, fill it in now.
529 clip_get_selection(cbd);
532 // Get the text to put on the pasteboard.
533 long_u llen = 0; char_u *str = 0;
534 int type = clip_convert_selection(&str, &llen, cbd);
538 // TODO: Avoid overflow.
541 if (output_conv.vc_type != CONV_NONE) {
542 char_u *conv_str = string_convert(&output_conv, str, &len);
551 NSString *string = [[NSString alloc]
552 initWithBytes:str length:len encoding:NSUTF8StringEncoding];
554 NSPasteboard *pb = [NSPasteboard generalPasteboard];
555 [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType]
557 [pb setString:string forType:NSStringPboardType];
566 // -- Menu ------------------------------------------------------------------
570 * Add a sub menu to the menu bar.
573 gui_mch_add_menu(vimmenu_T *menu, int idx)
575 // HACK! If menu has no parent, then we set the parent tag to the type of
576 // menu it is. This will not mix up tag and type because pointers can not
577 // take values close to zero (and the tag is simply the value of the
579 int parent = (int)menu->parent;
581 parent = menu_is_popup(menu->name) ? MenuPopupType :
582 menu_is_toolbar(menu->name) ? MenuToolbarType :
586 char_u *dname = menu->dname;
588 dname = CONVERT_TO_UTF8(dname);
591 [[MMBackend sharedInstance]
592 addMenuWithTag:(int)menu parent:parent name:(char*)dname
596 CONVERT_TO_UTF8_FREE(dname);
602 * Add a menu item to a menu
605 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
607 // NOTE! If 'iconfile' is not set but 'iconidx' is, use the name of the
608 // menu item. (Should correspond to a stock item.)
609 char_u *icon = menu->iconfile ? menu->iconfile :
610 menu->iconidx >= 0 ? menu->dname :
612 //char *name = menu_is_separator(menu->name) ? NULL : (char*)menu->dname;
613 char_u *name = menu->dname;
614 char_u *tip = menu->strings[MENU_INDEX_TIP]
615 ? menu->strings[MENU_INDEX_TIP] : menu->actext;
616 char_u *map_str = menu->strings[MENU_INDEX_NORMAL];
619 icon = CONVERT_TO_UTF8(icon);
620 name = CONVERT_TO_UTF8(name);
621 tip = CONVERT_TO_UTF8(tip);
622 map_str = CONVERT_TO_UTF8(map_str);
625 // HACK! Check if menu is mapped to ':macaction actionName:'; if so, pass
626 // the action along so that MacVim can bind the menu item to this action.
627 // This means that if a menu item maps to an action in normal mode, then
628 // all other modes will also use the same action.
629 NSString *action = nil;
631 NSString *mapping = [NSString stringWithCString:(char*)map_str
632 encoding:NSUTF8StringEncoding];
633 NSArray *parts = [mapping componentsSeparatedByString:@" "];
634 if ([parts count] >=2
635 && [[parts objectAtIndex:0] hasPrefix:@":maca"]) {
636 action = [parts objectAtIndex:1];
637 action = [action stringByTrimmingCharactersInSet:
638 [NSCharacterSet whitespaceAndNewlineCharacterSet]];
639 if (!gui_macvim_is_valid_action(action))
644 [[MMBackend sharedInstance]
645 addMenuItemWithTag:(int)menu
646 parent:(int)menu->parent
650 keyEquivalent:menu->mac_key
651 modifiers:menu->mac_mods
656 CONVERT_TO_UTF8_FREE(icon);
657 CONVERT_TO_UTF8_FREE(name);
658 CONVERT_TO_UTF8_FREE(tip);
659 CONVERT_TO_UTF8_FREE(map_str);
665 * Destroy the machine specific menu widget.
668 gui_mch_destroy_menu(vimmenu_T *menu)
670 [[MMBackend sharedInstance] removeMenuItemWithTag:(int)menu];
675 * Make a menu either grey or not grey.
678 gui_mch_menu_grey(vimmenu_T *menu, int grey)
680 /* Only update menu if the 'grey' state has changed to avoid having to pass
681 * lots of unnecessary data to MacVim. (Skipping this test makes MacVim
682 * pause noticably on mode changes. */
683 if (menu->was_grey != grey)
685 menu->was_grey = grey;
686 [[MMBackend sharedInstance]
687 enableMenuItemWithTag:(int)menu state:!grey];
693 * Make menu item hidden or not hidden
696 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
698 // HACK! There is no (obvious) way to hide a menu item, so simply
699 // enable/disable it instead.
700 gui_mch_menu_grey(menu, hidden);
705 * This is called when user right clicks.
708 gui_mch_show_popupmenu(vimmenu_T *menu)
710 char_u *name = menu->name;
712 name = CONVERT_TO_UTF8(name);
715 [[MMBackend sharedInstance] showPopupMenuWithName:(char*)name
716 atMouseLocation:YES];
719 CONVERT_TO_UTF8_FREE(name);
726 * This is called when a :popup command is executed.
729 gui_make_popup(char_u *path_name, int mouse_pos)
732 path_name = CONVERT_TO_UTF8(path_name);
735 [[MMBackend sharedInstance] showPopupMenuWithName:(char*)path_name
736 atMouseLocation:mouse_pos];
739 CONVERT_TO_UTF8_FREE(path_name);
745 * This is called after setting all the menus to grey/hidden or not.
748 gui_mch_draw_menubar(void)
750 // The (main) menu draws itself in Mac OS X.
755 gui_mch_enable_menu(int flag)
757 // The (main) menu is always enabled in Mac OS X.
763 gui_mch_set_menu_pos(int x, int y, int w, int h)
765 // The (main) menu cannot be moved in Mac OS X.
771 gui_mch_show_toolbar(int showit)
774 if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
775 if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
776 if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
778 [[MMBackend sharedInstance] showToolbar:showit flags:flags];
784 // -- Fonts -----------------------------------------------------------------
788 * If a font is not going to be used, free its structure.
791 gui_mch_free_font(font)
794 if (font != NOFONT) {
795 //NSLog(@"gui_mch_free_font(font=0x%x)", font);
796 [(NSFont*)font release];
802 * Get a font structure for highlighting.
805 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
807 //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
808 // giveErrorIfMissing);
810 NSFont *font = gui_macvim_font_with_name(name);
812 return (GuiFont)[font retain];
814 if (giveErrorIfMissing)
815 EMSG2(_(e_font), name);
821 #if defined(FEAT_EVAL) || defined(PROTO)
823 * Return the name of font "font" in allocated memory.
824 * Don't know how to get the actual name, thus use the provided name.
827 gui_mch_get_fontname(GuiFont font, char_u *name)
831 return vim_strsave(name);
837 * Initialise vim to use the font with the given name. Return FAIL if the font
838 * could not be loaded, OK otherwise.
841 gui_mch_init_font(char_u *font_name, int fontset)
843 //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
845 if (font_name && STRCMP(font_name, "*") == 0) {
846 // :set gfn=* shows the font panel.
847 do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
851 NSFont *font = gui_macvim_font_with_name(font_name);
853 [(NSFont*)gui.norm_font release];
854 gui.norm_font = (GuiFont)font;
856 // NOTE: MacVim keeps separate track of the normal and wide fonts.
857 // Unless the user changes 'guifontwide' manually, they are based on
858 // the same (normal) font. Also note that each time the normal font is
859 // set, the advancement may change so the wide font needs to be updated
860 // as well (so that it is always twice the width of the normal font).
861 [[MMBackend sharedInstance] setFont:font];
862 [[MMBackend sharedInstance] setWideFont:
863 (NOFONT == gui.wide_font ? font : (NSFont*)gui.wide_font)];
873 * Set the current text font.
876 gui_mch_set_font(GuiFont font)
878 // Font selection is done inside MacVim...nothing here to do.
883 gui_macvim_font_with_name(char_u *name)
886 NSString *fontName = MMDefaultFontName;
887 float size = MMDefaultFontSize;
888 BOOL parseFailed = NO;
891 name = CONVERT_TO_UTF8(name);
895 fontName = [NSString stringWithUTF8String:(char*)name];
897 NSArray *components = [fontName componentsSeparatedByString:@":"];
898 if ([components count] == 2) {
899 NSString *sizeString = [components lastObject];
900 if ([sizeString length] > 0
901 && [sizeString characterAtIndex:0] == 'h') {
902 sizeString = [sizeString substringFromIndex:1];
903 if ([sizeString length] > 0) {
904 size = [sizeString floatValue];
905 fontName = [components objectAtIndex:0];
910 } else if ([components count] > 2) {
915 // Replace underscores with spaces.
916 fontName = [[fontName componentsSeparatedByString:@"_"]
917 componentsJoinedByString:@" "];
921 if (!parseFailed && [fontName length] > 0) {
922 if (size < MMMinFontSize) size = MMMinFontSize;
923 if (size > MMMaxFontSize) size = MMMaxFontSize;
925 font = [NSFont fontWithName:fontName size:size];
927 if (!font && MMDefaultFontName == fontName) {
928 // If for some reason the MacVim default font is not in the app
929 // bundle, then fall back on the system default font.
930 font = [NSFont userFixedPitchFontOfSize:0];
935 CONVERT_TO_UTF8_FREE(name);
941 // -- Scrollbars ------------------------------------------------------------
945 gui_mch_create_scrollbar(
947 int orient) /* SBAR_VERT or SBAR_HORIZ */
949 [[MMBackend sharedInstance]
950 createScrollbarWithIdentifier:sb->ident type:sb->type];
955 gui_mch_destroy_scrollbar(scrollbar_T *sb)
957 [[MMBackend sharedInstance]
958 destroyScrollbarWithIdentifier:sb->ident];
963 gui_mch_enable_scrollbar(
967 [[MMBackend sharedInstance]
968 showScrollbarWithIdentifier:sb->ident state:flag];
973 gui_mch_set_scrollbar_pos(
982 if (SBAR_BOTTOM == sb->type) {
987 [[MMBackend sharedInstance]
988 setScrollbarPosition:pos length:len identifier:sb->ident];
993 gui_mch_set_scrollbar_thumb(
999 [[MMBackend sharedInstance]
1000 setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
1004 // -- Cursor ----------------------------------------------------------------
1008 * Draw a cursor without focus.
1011 gui_mch_draw_hollow_cursor(guicolor_T color)
1013 return [[MMBackend sharedInstance]
1014 drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
1015 fraction:100 color:color];
1020 * Draw part of a cursor, only w pixels wide, and h pixels high.
1023 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
1025 // HACK! 'w' and 'h' are always 1 since we do not tell Vim about the exact
1026 // font dimensions. Thus these parameters are useless. Instead we look at
1027 // the shape_table to determine the shape and size of the cursor (just like
1028 // gui_update_cursor() does).
1029 int idx = get_shape_idx(FALSE);
1030 int shape = MMInsertionPointBlock;
1031 switch (shape_table[idx].shape) {
1032 case SHAPE_HOR: shape = MMInsertionPointHorizontal; break;
1033 case SHAPE_VER: shape = MMInsertionPointVertical; break;
1036 return [[MMBackend sharedInstance]
1037 drawCursorAtRow:gui.row column:gui.col shape:shape
1038 fraction:shape_table[idx].percentage color:color];
1043 * Cursor blink functions.
1045 * This is a simple state machine:
1046 * BLINK_NONE not blinking at all
1047 * BLINK_OFF blinking, cursor is not shown
1048 * BLINK_ON blinking, cursor is shown
1051 gui_mch_set_blinking(long wait, long on, long off)
1053 [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1058 * Start the cursor blinking. If it was already blinking, this restarts the
1059 * waiting time and shows the cursor.
1062 gui_mch_start_blink(void)
1064 [[MMBackend sharedInstance] startBlink];
1069 * Stop the cursor blinking. Show the cursor if it wasn't shown.
1072 gui_mch_stop_blink(void)
1074 [[MMBackend sharedInstance] stopBlink];
1078 // -- Mouse -----------------------------------------------------------------
1082 * Get current mouse coordinates in text window.
1085 gui_mch_getmouse(int *x, int *y)
1087 //NSLog(@"gui_mch_getmouse()");
1092 gui_mch_setmouse(int x, int y)
1094 //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1099 mch_set_mouse_shape(int shape)
1101 [[MMBackend sharedInstance] setMouseShape:shape];
1107 // -- Input Method ----------------------------------------------------------
1109 #if defined(USE_IM_CONTROL)
1112 im_set_position(int row, int col)
1114 // The pre-edit area is a popup window which is displayed by MMTextView.
1115 [[MMBackend sharedInstance] setPreEditRow:row column:col];
1120 im_set_active(int active)
1122 // Set roman or the system script if 'active' is TRUE or FALSE,
1124 SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1126 if (!p_imdisable && smRoman != systemScript)
1127 KeyScript(active ? smKeySysScript : smKeyRoman);
1134 // IM is active whenever the current script is the system script and the
1135 // system script isn't roman. (Hence IM can only be active when using
1136 // non-roman scripts.)
1137 SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
1138 SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1140 return currentScript != smRoman && currentScript == systemScript;
1143 #endif // defined(USE_IM_CONTROL)
1148 // -- Unsorted --------------------------------------------------------------
1156 EMSG(_("E???: Command only available in GUI mode"));
1160 char_u *arg = eap->arg;
1162 arg = CONVERT_TO_UTF8(arg);
1165 NSString *name = [NSString stringWithCString:(char*)arg
1166 encoding:NSUTF8StringEncoding];
1167 if (gui_macvim_is_valid_action(name)) {
1168 [[MMBackend sharedInstance] executeActionWithName:name];
1170 EMSG2(_("E???: \"%s\" is not a valid action"), eap->arg);
1174 arg = CONVERT_TO_UTF8(arg);
1180 * Adjust gui.char_height (after 'linespace' was changed).
1183 gui_mch_adjust_charheight(void)
1185 [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1199 * Pop open a file browser and return the file selected, in allocated memory,
1200 * or NULL if Cancel is hit.
1201 * saving - TRUE if the file will be saved to, FALSE if it will be opened.
1202 * title - Title message for the file browser dialog.
1203 * dflt - Default name of file.
1204 * ext - Default extension to be added to files without extensions.
1205 * initdir - directory in which to open the browser (NULL = current dir)
1206 * filter - Filter for matched files to choose from.
1207 * Has a format like this:
1208 * "C Files (*.c)\0*.c\0"
1209 * "All Files\0*.*\0\0"
1210 * If these two strings were concatenated, then a choice of two file
1211 * filters will be selectable to the user. Then only matching files will
1212 * be shown in the browser. If NULL, the default allows all files.
1214 * *NOTE* - the filter string must be terminated with TWO nulls.
1225 //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1226 // " filter=%s", saving, title, dflt, ext, initdir, filter);
1229 title = CONVERT_TO_UTF8(title);
1230 initdir = CONVERT_TO_UTF8(initdir);
1233 char_u *s = (char_u*)[[MMBackend sharedInstance]
1234 browseForFileInDirectory:(char*)initdir title:(char*)title
1238 CONVERT_TO_UTF8_FREE(title);
1239 CONVERT_TO_UTF8_FREE(initdir);
1244 #endif /* FEAT_BROWSE */
1257 //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1258 // "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1259 // dfltbutton, textfield);
1262 title = CONVERT_TO_UTF8(title);
1263 message = CONVERT_TO_UTF8(message);
1264 buttons = CONVERT_TO_UTF8(buttons);
1265 textfield = CONVERT_TO_UTF8(textfield);
1268 int ret = [[MMBackend sharedInstance]
1269 presentDialogWithType:type
1271 message:(char*)message
1272 buttons:(char*)buttons
1273 textField:(char*)textfield];
1276 CONVERT_TO_UTF8_FREE(title);
1277 CONVERT_TO_UTF8_FREE(message);
1278 CONVERT_TO_UTF8_FREE(buttons);
1279 CONVERT_TO_UTF8_FREE(textfield);
1287 gui_mch_flash(int msec)
1293 * Return the Pixel value (color) for the given color name. This routine was
1294 * pretty much taken from example code in the Silicon Graphics OSF/Motif
1295 * Programmer's Guide.
1296 * Return INVALCOLOR when failed.
1299 gui_mch_get_color(char_u *name)
1302 name = CONVERT_TO_UTF8(name);
1305 NSString *key = [NSString stringWithUTF8String:(char*)name];
1306 guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1309 CONVERT_TO_UTF8_FREE(name);
1317 * Return the RGB value of a pixel as long.
1320 gui_mch_get_rgb(guicolor_T pixel)
1322 // This is only implemented so that vim can guess the correct value for
1323 // 'background' (which otherwise defaults to 'dark'); it is not used for
1324 // anything else (as far as I know).
1325 // The implementation is simple since colors are stored in an int as
1332 * Get the screen dimensions.
1333 * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1334 * Is there no way to find out how wide the borders really are?
1335 * TODO: Add live udate of those value on suspend/resume.
1338 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1340 //NSLog(@"gui_mch_get_screen_dimensions()");
1341 *screen_w = Columns;
1347 * Get the position of the top left corner of the window.
1350 gui_mch_get_winpos(int *x, int *y)
1358 * Return OK if the key with the termcap name "name" is supported.
1361 gui_mch_haskey(char_u *name)
1366 name = CONVERT_TO_UTF8(name);
1369 NSString *value = [NSString stringWithUTF8String:(char*)name];
1371 ok = [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1374 CONVERT_TO_UTF8_FREE(name);
1382 * Iconify the GUI window.
1385 gui_mch_iconify(void)
1391 * Invert a rectangle from row r, column c, for nr rows and nc columns.
1394 gui_mch_invert_rectangle(int r, int c, int nr, int nc)
1399 #if defined(FEAT_EVAL) || defined(PROTO)
1401 * Bring the Vim window to the foreground.
1404 gui_mch_set_foreground(void)
1406 [[MMBackend sharedInstance] activate];
1413 gui_mch_set_shellsize(
1422 //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1423 // " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1424 // width, height, min_width, min_height, base_width, base_height,
1426 [[MMBackend sharedInstance] setRows:height columns:width];
1431 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1436 * Set the position of the top left corner of the window to the given
1440 gui_mch_set_winpos(int x, int y)
1447 * Set the window title and icon.
1448 * (The icon is not taken care of).
1451 gui_mch_settitle(char_u *title, char_u *icon)
1453 //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1456 title = CONVERT_TO_UTF8(title);
1459 [[MMBackend sharedInstance] setWindowTitle:(char*)title];
1462 CONVERT_TO_UTF8_FREE(title);
1469 gui_mch_toggle_tearoffs(int enable)
1475 gui_macvim_is_valid_action(NSString *action)
1477 static NSDictionary *actionDict = nil;
1480 NSBundle *mainBundle = [NSBundle mainBundle];
1481 NSString *path = [mainBundle pathForResource:@"Actions"
1484 actionDict = [[NSDictionary alloc] initWithContentsOfFile:path];
1486 // Allocate bogus dictionary so that error only pops up once.
1487 actionDict = [NSDictionary new];
1488 EMSG(_("E???: Failed to load action dictionary"));
1492 return [actionDict objectForKey:action] != nil;
1497 gui_mch_enter_fullscreen()
1499 [[MMBackend sharedInstance] enterFullscreen];
1504 gui_mch_leave_fullscreen()
1506 [[MMBackend sharedInstance] leaveFullscreen];
1511 gui_macvim_update_modified_flag()
1513 [[MMBackend sharedInstance] updateModifiedFlag];
1519 // -- Client/Server ---------------------------------------------------------
1521 #ifdef MAC_CLIENTSERVER
1524 // NOTE: Client/Server is only fully supported with a GUI. Theoretically it
1525 // would be possible to make the server code work with terminal Vim, but it
1526 // would require that a run-loop is set up and checked. This should not be
1527 // difficult to implement, simply call gui_mch_update() at opportune moments
1528 // and it will take care of the run-loop. Another (bigger) problem with
1529 // supporting servers in terminal mode is that the server listing code talks to
1530 // MacVim (the GUI) to figure out which servers are running.
1535 * Register connection with 'name'. The actual connection is named something
1536 * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1539 serverRegisterName(char_u *name)
1542 name = CONVERT_TO_UTF8(name);
1545 NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1546 [[MMBackend sharedInstance] registerServerWithName:svrName];
1549 CONVERT_TO_UTF8_FREE(name);
1555 * Send to an instance of Vim.
1556 * Returns 0 for OK, negative for an error.
1559 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1560 int *port, int asExpr, int silent)
1563 name = CONVERT_TO_UTF8(name);
1564 cmd = CONVERT_TO_UTF8(cmd);
1567 BOOL ok = [[MMBackend sharedInstance]
1568 sendToServer:[NSString stringWithUTF8String:(char*)name]
1569 string:[NSString stringWithUTF8String:(char*)cmd]
1576 CONVERT_TO_UTF8_FREE(name);
1577 CONVERT_TO_UTF8_FREE(cmd);
1585 * Ask MacVim for the names of all Vim servers.
1588 serverGetVimNames(void)
1590 char_u *names = NULL;
1591 NSArray *list = [[MMBackend sharedInstance] serverList];
1594 NSString *string = [list componentsJoinedByString:@"\n"];
1595 char_u *s = (char_u*)[string UTF8String];
1597 s = CONVERT_FROM_UTF8(s);
1599 names = vim_strsave(s);
1601 CONVERT_FROM_UTF8_FREE(s);
1610 * 'str' is a hex int representing the send port of the connection.
1613 serverStrToPort(char_u *str)
1617 sscanf((char *)str, "0x%x", &port);
1619 EMSG2(_("E573: Invalid server id used: %s"), str);
1626 * Check for replies from server with send port 'port'.
1627 * Return TRUE and a non-malloc'ed string if there is. Else return FALSE.
1630 serverPeekReply(int port, char_u **str)
1632 NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1633 int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1635 if (str && len > 0) {
1636 *str = (char_u*)[reply UTF8String];
1639 if (input_conv.vc_type != CONV_NONE) {
1640 char_u *s = string_convert(&input_conv, *str, &len);
1643 // HACK! Since 's' needs to be freed we cannot simply set
1644 // '*str = s' or memory will leak. Instead, create a dummy
1645 // NSData and return its 'bytes' pointer, then autorelease the
1647 NSData *data = [NSData dataWithBytes:s length:len+1];
1648 *str = (char_u*)[data bytes];
1656 return reply != nil;
1661 * Wait for replies from server with send port 'port'.
1662 * Return 0 and the malloc'ed string when a reply is available.
1663 * Return -1 on error.
1666 serverReadReply(int port, char_u **str)
1668 NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1670 char_u *s = (char_u*)[reply UTF8String];
1672 s = CONVERT_FROM_UTF8(s);
1674 *str = vim_strsave(s);
1676 CONVERT_FROM_UTF8_FREE(s);
1686 * Send a reply string (notification) to client with port given by "serverid".
1687 * Return -1 if the window is invalid.
1690 serverSendReply(char_u *serverid, char_u *reply)
1693 int port = serverStrToPort(serverid);
1694 if (port > 0 && reply) {
1696 reply = CONVERT_TO_UTF8(reply);
1698 BOOL ok = [[MMBackend sharedInstance]
1699 sendReply:[NSString stringWithUTF8String:(char*)reply]
1701 retval = ok ? 0 : -1;
1703 CONVERT_TO_UTF8_FREE(reply);
1710 #endif // MAC_CLIENTSERVER