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]) {
91 // TODO: Kill the process if there is no terminal to fall back on,
92 // otherwise the process will run outputting to the console.
96 // Force 'termencoding' to utf-8 (changes to 'tenc' are disallowed in
97 // 'option.c', so that ':set termencoding=...' is impossible).
98 set_option_value((char_u *)"termencoding", 0L, (char_u *)"utf-8", 0);
100 // Set values so that pixels and characters are in one-to-one
101 // correspondence (assuming all characters have the same dimensions).
102 gui.scrollbar_width = gui.scrollbar_height = 0;
108 gui_mch_def_colors();
110 [[MMBackend sharedInstance]
111 setDefaultColorsBackground:gui.back_pixel foreground:gui.norm_pixel];
112 [[MMBackend sharedInstance] setBackgroundColor:gui.back_pixel];
113 [[MMBackend sharedInstance] setForegroundColor:gui.norm_pixel];
115 // NOTE: If this call is left out the cursor is opaque.
116 highlight_gui_started();
126 //NSLog(@"gui_mch_exit(rc=%d)", rc);
128 [[MMBackend sharedInstance] exit];
133 * Open the GUI window which was created by a call to gui_mch_init().
138 //NSLog(@"gui_mch_open()");
140 return [[MMBackend sharedInstance] openVimWindow];
144 // -- Updating --------------------------------------------------------------
148 * Catch up with any queued X events. This may put keyboard input into the
149 * input buffer, call resize call-backs, trigger timers etc. If there is
150 * nothing in the X event queue (& no timers pending), then we return
153 #define MM_LOG_UPDATE_STATS 0
157 // NOTE: This function can get called A LOT (~1 call/ms) and unfortunately
158 // checking the run loop takes a long time, resulting in noticable slow
159 // downs if it is done every time this function is called. Therefore we
160 // make sure that it is not done too often.
161 static NSDate *lastUpdateDate = nil;
162 #if MM_LOG_UPDATE_STATS
163 static int skipCount = 0;
166 if (lastUpdateDate && -[lastUpdateDate timeIntervalSinceNow] <
167 MMUpdateTimeoutInterval) {
168 #if MM_LOG_UPDATE_STATS
174 #if MM_LOG_UPDATE_STATS
175 NSTimeInterval dt = -[lastUpdateDate timeIntervalSinceNow];
176 NSLog(@"Updating (last update %.2f seconds ago, skipped %d updates, "
177 "approx %.1f calls per second)",
178 dt, skipCount, dt > 0 ? skipCount/dt : 0);
182 [[MMBackend sharedInstance] update];
184 [lastUpdateDate release];
185 lastUpdateDate = [[NSDate date] retain];
189 /* Flush any output to the screen */
193 [[MMBackend sharedInstance] flushQueue:NO];
197 /* Force flush output to MacVim. Do not call this method unless absolutely
198 * necessary (use gui_mch_flush() instead). */
200 gui_macvim_force_flush(void)
202 [[MMBackend sharedInstance] flushQueue:YES];
207 * GUI input routine called by gui_wait_for_chars(). Waits for a character
209 * wtime == -1 Wait forever.
210 * wtime == 0 This should never happen.
211 * wtime > 0 Wait wtime milliseconds for a character.
212 * Returns OK if a character was found to be available within the given time,
216 gui_mch_wait_for_chars(int wtime)
218 // NOTE! In all likelihood Vim will take a nap when waitForInput: is
219 // called, so force a flush of the command queue here.
220 [[MMBackend sharedInstance] flushQueue:YES];
222 return [[MMBackend sharedInstance] waitForInput:wtime];
226 // -- Drawing ---------------------------------------------------------------
230 * Clear the whole text window.
233 gui_mch_clear_all(void)
235 [[MMBackend sharedInstance] clearAll];
240 * Clear a rectangular region of the screen from text pos (row1, col1) to
241 * (row2, col2) inclusive.
244 gui_mch_clear_block(int row1, int col1, int row2, int col2)
246 [[MMBackend sharedInstance] clearBlockFromRow:row1 column:col1
247 toRow:row2 column:col2];
252 * Delete the given number of lines from the given row, scrolling up any
253 * text further down within the scroll region.
256 gui_mch_delete_lines(int row, int num_lines)
258 [[MMBackend sharedInstance] deleteLinesFromRow:row count:num_lines
259 scrollBottom:gui.scroll_region_bot
260 left:gui.scroll_region_left
261 right:gui.scroll_region_right];
266 gui_mch_draw_string(int row, int col, char_u *s, int len, int flags)
269 char_u *conv_str = NULL;
270 if (output_conv.vc_type != CONV_NONE) {
271 conv_str = string_convert(&output_conv, s, &len);
277 [[MMBackend sharedInstance] drawString:(char*)s length:len row:row
278 column:col cells:len flags:flags];
288 gui_macvim_draw_string(int row, int col, char_u *s, int len, int flags)
295 MMBackend *backend = [MMBackend sharedInstance];
297 char_u *conv_str = NULL;
299 if (output_conv.vc_type != CONV_NONE) {
300 conv_str = string_convert(&output_conv, s, &len);
306 // Loop over each character and output text when it changes from normal to
307 // wide and vice versa.
308 for (i = 0; i < len; i += cl) {
309 c = utf_ptr2char(s + i);
310 cl = utf_ptr2len(s + i);
311 cn = utf_char2cells(c);
313 if (!utf_iscomposing(c)) {
314 if ((cn > 1 && !wide) || (cn <= 1 && wide)) {
315 // Changed from normal to wide or vice versa.
316 [backend drawString:(char*)(s+start) length:i-start
317 row:row column:startcol
318 cells:endcol-startcol
319 flags:(wide ? flags|DRAW_WIDE : flags)];
330 // Output remaining characters.
331 [backend drawString:(char*)(s+start) length:len-start
332 row:row column:startcol cells:endcol-startcol
333 flags:(wide ? flags|DRAW_WIDE : flags)];
345 * Insert the given number of lines before the given row, scrolling down any
346 * following text within the scroll region.
349 gui_mch_insert_lines(int row, int num_lines)
351 [[MMBackend sharedInstance] insertLinesFromRow:row count:num_lines
352 scrollBottom:gui.scroll_region_bot
353 left:gui.scroll_region_left
354 right:gui.scroll_region_right];
359 * Set the current text foreground color.
362 gui_mch_set_fg_color(guicolor_T color)
364 [[MMBackend sharedInstance] setForegroundColor:color];
369 * Set the current text background color.
372 gui_mch_set_bg_color(guicolor_T color)
374 [[MMBackend sharedInstance] setBackgroundColor:color];
379 * Set the current text special color (used for underlines).
382 gui_mch_set_sp_color(guicolor_T color)
384 [[MMBackend sharedInstance] setSpecialColor:color];
389 * Set default colors.
394 MMBackend *backend = [MMBackend sharedInstance];
396 // The default colors are taken from system values
397 gui.def_norm_pixel = gui.norm_pixel =
398 [backend lookupColorWithKey:@"MacTextColor"];
399 gui.def_back_pixel = gui.back_pixel =
400 [backend lookupColorWithKey:@"MacTextBackgroundColor"];
405 * Called when the foreground or background color has been changed.
408 gui_mch_new_colors(void)
410 gui.def_back_pixel = gui.back_pixel;
411 gui.def_norm_pixel = gui.norm_pixel;
413 //NSLog(@"gui_mch_new_colors(back=%x, norm=%x)", gui.def_back_pixel,
414 // gui.def_norm_pixel);
416 [[MMBackend sharedInstance]
417 setDefaultColorsBackground:gui.def_back_pixel
418 foreground:gui.def_norm_pixel];
422 // -- Tabline ---------------------------------------------------------------
426 * Set the current tab to "nr". First tab is 1.
429 gui_mch_set_curtab(int nr)
431 [[MMBackend sharedInstance] selectTab:nr];
436 * Return TRUE when tabline is displayed.
439 gui_mch_showing_tabline(void)
441 return [[MMBackend sharedInstance] tabBarVisible];
445 * Update the labels of the tabline.
448 gui_mch_update_tabline(void)
450 [[MMBackend sharedInstance] updateTabBar];
454 * Show or hide the tabline.
457 gui_mch_show_tabline(int showit)
459 [[MMBackend sharedInstance] showTabBar:showit];
463 // -- Clipboard -------------------------------------------------------------
467 clip_mch_lose_selection(VimClipboard *cbd)
473 clip_mch_own_selection(VimClipboard *cbd)
480 clip_mch_request_selection(VimClipboard *cbd)
482 NSPasteboard *pb = [NSPasteboard generalPasteboard];
483 NSString *pbType = [pb availableTypeFromArray:
484 [NSArray arrayWithObject:NSStringPboardType]];
486 NSMutableString *string =
487 [[pb stringForType:NSStringPboardType] mutableCopy];
489 // Replace unrecognized end-of-line sequences with \x0a (line feed).
490 NSRange range = { 0, [string length] };
491 unsigned n = [string replaceOccurrencesOfString:@"\x0d\x0a"
492 withString:@"\x0a" options:0
495 n = [string replaceOccurrencesOfString:@"\x0d" withString:@"\x0a"
496 options:0 range:range];
499 // Scan for newline character to decide whether the string should be
500 // pasted linewise or characterwise.
502 if (0 < n || NSNotFound != [string rangeOfString:@"\n"].location)
505 char_u *str = (char_u*)[string UTF8String];
506 int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
509 if (input_conv.vc_type != CONV_NONE)
510 str = string_convert(&input_conv, str, &len);
514 clip_yank_selection(type, str, len, cbd);
517 if (input_conv.vc_type != CONV_NONE)
525 * Send the current selection to the clipboard.
528 clip_mch_set_selection(VimClipboard *cbd)
530 // If the '*' register isn't already filled in, fill it in now.
532 clip_get_selection(cbd);
535 // Get the text to put on the pasteboard.
536 long_u llen = 0; char_u *str = 0;
537 int type = clip_convert_selection(&str, &llen, cbd);
541 // TODO: Avoid overflow.
544 if (output_conv.vc_type != CONV_NONE) {
545 char_u *conv_str = string_convert(&output_conv, str, &len);
554 NSString *string = [[NSString alloc]
555 initWithBytes:str length:len encoding:NSUTF8StringEncoding];
557 NSPasteboard *pb = [NSPasteboard generalPasteboard];
558 [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType]
560 [pb setString:string forType:NSStringPboardType];
569 // -- Menu ------------------------------------------------------------------
573 * Add a sub menu to the menu bar.
576 gui_mch_add_menu(vimmenu_T *menu, int idx)
578 // HACK! If menu has no parent, then we set the parent tag to the type of
579 // menu it is. This will not mix up tag and type because pointers can not
580 // take values close to zero (and the tag is simply the value of the
582 int parent = (int)menu->parent;
584 parent = menu_is_popup(menu->name) ? MenuPopupType :
585 menu_is_toolbar(menu->name) ? MenuToolbarType :
589 char_u *dname = menu->dname;
591 dname = CONVERT_TO_UTF8(dname);
594 [[MMBackend sharedInstance]
595 addMenuWithTag:(int)menu parent:parent name:(char*)dname
599 CONVERT_TO_UTF8_FREE(dname);
605 * Add a menu item to a menu
608 gui_mch_add_menu_item(vimmenu_T *menu, int idx)
610 // NOTE! If 'iconfile' is not set but 'iconidx' is, use the name of the
611 // menu item. (Should correspond to a stock item.)
612 char_u *icon = menu->iconfile ? menu->iconfile :
613 menu->iconidx >= 0 ? menu->dname :
615 //char *name = menu_is_separator(menu->name) ? NULL : (char*)menu->dname;
616 char_u *name = menu->dname;
617 char_u *tip = menu->strings[MENU_INDEX_TIP]
618 ? menu->strings[MENU_INDEX_TIP] : menu->actext;
619 char_u *map_str = menu->strings[MENU_INDEX_NORMAL];
622 icon = CONVERT_TO_UTF8(icon);
623 name = CONVERT_TO_UTF8(name);
624 tip = CONVERT_TO_UTF8(tip);
625 map_str = CONVERT_TO_UTF8(map_str);
628 // HACK! Check if menu is mapped to ':macaction actionName:'; if so, pass
629 // the action along so that MacVim can bind the menu item to this action.
630 // This means that if a menu item maps to an action in normal mode, then
631 // all other modes will also use the same action.
632 NSString *action = nil;
634 NSString *mapping = [NSString stringWithCString:(char*)map_str
635 encoding:NSUTF8StringEncoding];
636 NSArray *parts = [mapping componentsSeparatedByString:@" "];
637 if ([parts count] >=2
638 && [[parts objectAtIndex:0] hasPrefix:@":maca"]) {
639 action = [parts objectAtIndex:1];
640 action = [action stringByTrimmingCharactersInSet:
641 [NSCharacterSet whitespaceAndNewlineCharacterSet]];
642 if (!gui_macvim_is_valid_action(action))
647 [[MMBackend sharedInstance]
648 addMenuItemWithTag:(int)menu
649 parent:(int)menu->parent
653 keyEquivalent:menu->mac_key
654 modifiers:menu->mac_mods
659 CONVERT_TO_UTF8_FREE(icon);
660 CONVERT_TO_UTF8_FREE(name);
661 CONVERT_TO_UTF8_FREE(tip);
662 CONVERT_TO_UTF8_FREE(map_str);
668 * Destroy the machine specific menu widget.
671 gui_mch_destroy_menu(vimmenu_T *menu)
673 [[MMBackend sharedInstance] removeMenuItemWithTag:(int)menu];
678 * Make a menu either grey or not grey.
681 gui_mch_menu_grey(vimmenu_T *menu, int grey)
683 /* Only update menu if the 'grey' state has changed to avoid having to pass
684 * lots of unnecessary data to MacVim. (Skipping this test makes MacVim
685 * pause noticably on mode changes. */
686 if (menu->was_grey != grey)
688 menu->was_grey = grey;
689 [[MMBackend sharedInstance]
690 enableMenuItemWithTag:(int)menu state:!grey];
696 * Make menu item hidden or not hidden
699 gui_mch_menu_hidden(vimmenu_T *menu, int hidden)
701 // HACK! There is no (obvious) way to hide a menu item, so simply
702 // enable/disable it instead.
703 gui_mch_menu_grey(menu, hidden);
708 * This is called when user right clicks.
711 gui_mch_show_popupmenu(vimmenu_T *menu)
713 char_u *name = menu->name;
715 name = CONVERT_TO_UTF8(name);
718 [[MMBackend sharedInstance] showPopupMenuWithName:(char*)name
719 atMouseLocation:YES];
722 CONVERT_TO_UTF8_FREE(name);
729 * This is called when a :popup command is executed.
732 gui_make_popup(char_u *path_name, int mouse_pos)
735 path_name = CONVERT_TO_UTF8(path_name);
738 [[MMBackend sharedInstance] showPopupMenuWithName:(char*)path_name
739 atMouseLocation:mouse_pos];
742 CONVERT_TO_UTF8_FREE(path_name);
748 * This is called after setting all the menus to grey/hidden or not.
751 gui_mch_draw_menubar(void)
753 // The (main) menu draws itself in Mac OS X.
758 gui_mch_enable_menu(int flag)
760 // The (main) menu is always enabled in Mac OS X.
766 gui_mch_set_menu_pos(int x, int y, int w, int h)
768 // The (main) menu cannot be moved in Mac OS X.
774 gui_mch_show_toolbar(int showit)
777 if (toolbar_flags & TOOLBAR_TEXT) flags |= ToolbarLabelFlag;
778 if (toolbar_flags & TOOLBAR_ICONS) flags |= ToolbarIconFlag;
779 if (tbis_flags & (TBIS_MEDIUM|TBIS_LARGE)) flags |= ToolbarSizeRegularFlag;
781 [[MMBackend sharedInstance] showToolbar:showit flags:flags];
787 // -- Fonts -----------------------------------------------------------------
791 * If a font is not going to be used, free its structure.
794 gui_mch_free_font(font)
797 if (font != NOFONT) {
798 //NSLog(@"gui_mch_free_font(font=0x%x)", font);
799 [(NSFont*)font release];
805 * Get a font structure for highlighting.
808 gui_mch_get_font(char_u *name, int giveErrorIfMissing)
810 //NSLog(@"gui_mch_get_font(name=%s, giveErrorIfMissing=%d)", name,
811 // giveErrorIfMissing);
813 NSFont *font = gui_macvim_font_with_name(name);
815 return (GuiFont)[font retain];
817 if (giveErrorIfMissing)
818 EMSG2(_(e_font), name);
824 #if defined(FEAT_EVAL) || defined(PROTO)
826 * Return the name of font "font" in allocated memory.
827 * Don't know how to get the actual name, thus use the provided name.
830 gui_mch_get_fontname(GuiFont font, char_u *name)
834 return vim_strsave(name);
840 * Initialise vim to use the font with the given name. Return FAIL if the font
841 * could not be loaded, OK otherwise.
844 gui_mch_init_font(char_u *font_name, int fontset)
846 //NSLog(@"gui_mch_init_font(font_name=%s, fontset=%d)", font_name, fontset);
848 if (font_name && STRCMP(font_name, "*") == 0) {
849 // :set gfn=* shows the font panel.
850 do_cmdline_cmd((char_u*)":macaction orderFrontFontPanel:");
854 NSFont *font = gui_macvim_font_with_name(font_name);
856 [(NSFont*)gui.norm_font release];
857 gui.norm_font = (GuiFont)[font retain];
859 // NOTE: MacVim keeps separate track of the normal and wide fonts.
860 // Unless the user changes 'guifontwide' manually, they are based on
861 // the same (normal) font. Also note that each time the normal font is
862 // set, the advancement may change so the wide font needs to be updated
863 // as well (so that it is always twice the width of the normal font).
864 [[MMBackend sharedInstance] setFont:font];
865 [[MMBackend sharedInstance] setWideFont:
866 (NOFONT == gui.wide_font ? font : (NSFont*)gui.wide_font)];
876 * Set the current text font.
879 gui_mch_set_font(GuiFont font)
881 // Font selection is done inside MacVim...nothing here to do.
886 gui_macvim_font_with_name(char_u *name)
889 NSString *fontName = MMDefaultFontName;
890 float size = MMDefaultFontSize;
891 BOOL parseFailed = NO;
894 name = CONVERT_TO_UTF8(name);
898 fontName = [NSString stringWithUTF8String:(char*)name];
900 NSArray *components = [fontName componentsSeparatedByString:@":"];
901 if ([components count] == 2) {
902 NSString *sizeString = [components lastObject];
903 if ([sizeString length] > 0
904 && [sizeString characterAtIndex:0] == 'h') {
905 sizeString = [sizeString substringFromIndex:1];
906 if ([sizeString length] > 0) {
907 size = [sizeString floatValue];
908 fontName = [components objectAtIndex:0];
913 } else if ([components count] > 2) {
918 // Replace underscores with spaces.
919 fontName = [[fontName componentsSeparatedByString:@"_"]
920 componentsJoinedByString:@" "];
924 if (!parseFailed && [fontName length] > 0) {
925 if (size < MMMinFontSize) size = MMMinFontSize;
926 if (size > MMMaxFontSize) size = MMMaxFontSize;
928 font = [NSFont fontWithName:fontName size:size];
930 if (!font && MMDefaultFontName == fontName) {
931 // If for some reason the MacVim default font is not in the app
932 // bundle, then fall back on the system default font.
933 font = [NSFont userFixedPitchFontOfSize:0];
938 CONVERT_TO_UTF8_FREE(name);
944 // -- Scrollbars ------------------------------------------------------------
948 gui_mch_create_scrollbar(
950 int orient) /* SBAR_VERT or SBAR_HORIZ */
952 [[MMBackend sharedInstance]
953 createScrollbarWithIdentifier:sb->ident type:sb->type];
958 gui_mch_destroy_scrollbar(scrollbar_T *sb)
960 [[MMBackend sharedInstance]
961 destroyScrollbarWithIdentifier:sb->ident];
966 gui_mch_enable_scrollbar(
970 [[MMBackend sharedInstance]
971 showScrollbarWithIdentifier:sb->ident state:flag];
976 gui_mch_set_scrollbar_pos(
985 if (SBAR_BOTTOM == sb->type) {
990 [[MMBackend sharedInstance]
991 setScrollbarPosition:pos length:len identifier:sb->ident];
996 gui_mch_set_scrollbar_thumb(
1002 [[MMBackend sharedInstance]
1003 setScrollbarThumbValue:val size:size max:max identifier:sb->ident];
1007 // -- Cursor ----------------------------------------------------------------
1011 * Draw a cursor without focus.
1014 gui_mch_draw_hollow_cursor(guicolor_T color)
1016 return [[MMBackend sharedInstance]
1017 drawCursorAtRow:gui.row column:gui.col shape:MMInsertionPointHollow
1018 fraction:100 color:color];
1023 * Draw part of a cursor, only w pixels wide, and h pixels high.
1026 gui_mch_draw_part_cursor(int w, int h, guicolor_T color)
1028 // HACK! 'w' and 'h' are always 1 since we do not tell Vim about the exact
1029 // font dimensions. Thus these parameters are useless. Instead we look at
1030 // the shape_table to determine the shape and size of the cursor (just like
1031 // gui_update_cursor() does).
1032 int idx = get_shape_idx(FALSE);
1033 int shape = MMInsertionPointBlock;
1034 switch (shape_table[idx].shape) {
1035 case SHAPE_HOR: shape = MMInsertionPointHorizontal; break;
1036 case SHAPE_VER: shape = MMInsertionPointVertical; break;
1039 return [[MMBackend sharedInstance]
1040 drawCursorAtRow:gui.row column:gui.col shape:shape
1041 fraction:shape_table[idx].percentage color:color];
1046 * Cursor blink functions.
1048 * This is a simple state machine:
1049 * BLINK_NONE not blinking at all
1050 * BLINK_OFF blinking, cursor is not shown
1051 * BLINK_ON blinking, cursor is shown
1054 gui_mch_set_blinking(long wait, long on, long off)
1056 [[MMBackend sharedInstance] setBlinkWait:wait on:on off:off];
1061 * Start the cursor blinking. If it was already blinking, this restarts the
1062 * waiting time and shows the cursor.
1065 gui_mch_start_blink(void)
1067 [[MMBackend sharedInstance] startBlink];
1072 * Stop the cursor blinking. Show the cursor if it wasn't shown.
1075 gui_mch_stop_blink(void)
1077 [[MMBackend sharedInstance] stopBlink];
1081 // -- Mouse -----------------------------------------------------------------
1085 * Get current mouse coordinates in text window.
1088 gui_mch_getmouse(int *x, int *y)
1090 //NSLog(@"gui_mch_getmouse()");
1095 gui_mch_setmouse(int x, int y)
1097 //NSLog(@"gui_mch_setmouse(x=%d, y=%d)", x, y);
1102 mch_set_mouse_shape(int shape)
1104 [[MMBackend sharedInstance] setMouseShape:shape];
1110 // -- Input Method ----------------------------------------------------------
1112 #if defined(USE_IM_CONTROL)
1115 im_set_position(int row, int col)
1117 // The pre-edit area is a popup window which is displayed by MMTextView.
1118 [[MMBackend sharedInstance] setPreEditRow:row column:col];
1123 im_set_active(int active)
1125 // Set roman or the system script if 'active' is TRUE or FALSE,
1127 SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1129 if (!p_imdisable && smRoman != systemScript)
1130 KeyScript(active ? smKeySysScript : smKeyRoman);
1137 // IM is active whenever the current script is the system script and the
1138 // system script isn't roman. (Hence IM can only be active when using
1139 // non-roman scripts.)
1140 SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
1141 SInt32 systemScript = GetScriptManagerVariable(smSysScript);
1143 return currentScript != smRoman && currentScript == systemScript;
1146 #endif // defined(USE_IM_CONTROL)
1151 // -- Unsorted --------------------------------------------------------------
1159 EMSG(_("E???: Command only available in GUI mode"));
1163 char_u *arg = eap->arg;
1165 arg = CONVERT_TO_UTF8(arg);
1168 NSString *name = [NSString stringWithCString:(char*)arg
1169 encoding:NSUTF8StringEncoding];
1170 if (gui_macvim_is_valid_action(name)) {
1171 [[MMBackend sharedInstance] executeActionWithName:name];
1173 EMSG2(_("E???: \"%s\" is not a valid action"), eap->arg);
1177 arg = CONVERT_TO_UTF8(arg);
1183 * Adjust gui.char_height (after 'linespace' was changed).
1186 gui_mch_adjust_charheight(void)
1188 [[MMBackend sharedInstance] adjustLinespace:p_linespace];
1203 * Pop open a file browser and return the file selected, in allocated memory,
1204 * or NULL if Cancel is hit.
1205 * saving - TRUE if the file will be saved to, FALSE if it will be opened.
1206 * title - Title message for the file browser dialog.
1207 * dflt - Default name of file.
1208 * ext - Default extension to be added to files without extensions.
1209 * initdir - directory in which to open the browser (NULL = current dir)
1210 * filter - Filter for matched files to choose from.
1211 * Has a format like this:
1212 * "C Files (*.c)\0*.c\0"
1213 * "All Files\0*.*\0\0"
1214 * If these two strings were concatenated, then a choice of two file
1215 * filters will be selectable to the user. Then only matching files will
1216 * be shown in the browser. If NULL, the default allows all files.
1218 * *NOTE* - the filter string must be terminated with TWO nulls.
1229 //NSLog(@"gui_mch_browse(saving=%d, title=%s, dflt=%s, ext=%s, initdir=%s,"
1230 // " filter=%s", saving, title, dflt, ext, initdir, filter);
1233 title = CONVERT_TO_UTF8(title);
1234 initdir = CONVERT_TO_UTF8(initdir);
1237 char_u *s = (char_u*)[[MMBackend sharedInstance]
1238 browseForFileInDirectory:(char*)initdir title:(char*)title
1242 CONVERT_TO_UTF8_FREE(title);
1243 CONVERT_TO_UTF8_FREE(initdir);
1248 #endif /* FEAT_BROWSE */
1261 //NSLog(@"gui_mch_dialog(type=%d title=%s message=%s buttons=%s "
1262 // "dfltbutton=%d textfield=%s)", type, title, message, buttons,
1263 // dfltbutton, textfield);
1266 title = CONVERT_TO_UTF8(title);
1267 message = CONVERT_TO_UTF8(message);
1268 buttons = CONVERT_TO_UTF8(buttons);
1269 textfield = CONVERT_TO_UTF8(textfield);
1272 int ret = [[MMBackend sharedInstance]
1273 presentDialogWithType:type
1275 message:(char*)message
1276 buttons:(char*)buttons
1277 textField:(char*)textfield];
1280 CONVERT_TO_UTF8_FREE(title);
1281 CONVERT_TO_UTF8_FREE(message);
1282 CONVERT_TO_UTF8_FREE(buttons);
1283 CONVERT_TO_UTF8_FREE(textfield);
1291 gui_mch_flash(int msec)
1297 * Return the Pixel value (color) for the given color name. This routine was
1298 * pretty much taken from example code in the Silicon Graphics OSF/Motif
1299 * Programmer's Guide.
1300 * Return INVALCOLOR when failed.
1303 gui_mch_get_color(char_u *name)
1306 name = CONVERT_TO_UTF8(name);
1309 NSString *key = [NSString stringWithUTF8String:(char*)name];
1310 guicolor_T col = [[MMBackend sharedInstance] lookupColorWithKey:key];
1313 CONVERT_TO_UTF8_FREE(name);
1321 * Return the RGB value of a pixel as long.
1324 gui_mch_get_rgb(guicolor_T pixel)
1326 // This is only implemented so that vim can guess the correct value for
1327 // 'background' (which otherwise defaults to 'dark'); it is not used for
1328 // anything else (as far as I know).
1329 // The implementation is simple since colors are stored in an int as
1336 * Get the screen dimensions.
1337 * Allow 10 pixels for horizontal borders, 40 for vertical borders.
1338 * Is there no way to find out how wide the borders really are?
1339 * TODO: Add live udate of those value on suspend/resume.
1342 gui_mch_get_screen_dimensions(int *screen_w, int *screen_h)
1344 //NSLog(@"gui_mch_get_screen_dimensions()");
1345 *screen_w = Columns;
1351 * Get the position of the top left corner of the window.
1354 gui_mch_get_winpos(int *x, int *y)
1362 * Return OK if the key with the termcap name "name" is supported.
1365 gui_mch_haskey(char_u *name)
1370 name = CONVERT_TO_UTF8(name);
1373 NSString *value = [NSString stringWithUTF8String:(char*)name];
1375 ok = [[MMBackend sharedInstance] hasSpecialKeyWithValue:value];
1378 CONVERT_TO_UTF8_FREE(name);
1386 * Iconify the GUI window.
1389 gui_mch_iconify(void)
1395 * Invert a rectangle from row r, column c, for nr rows and nc columns.
1398 gui_mch_invert_rectangle(int r, int c, int nr, int nc)
1403 #if defined(FEAT_EVAL) || defined(PROTO)
1405 * Bring the Vim window to the foreground.
1408 gui_mch_set_foreground(void)
1410 [[MMBackend sharedInstance] activate];
1417 gui_mch_set_shellsize(
1426 //NSLog(@"gui_mch_set_shellsize(width=%d, height=%d, min_width=%d,"
1427 // " min_height=%d, base_width=%d, base_height=%d, direction=%d)",
1428 // width, height, min_width, min_height, base_width, base_height,
1430 [[MMBackend sharedInstance] setRows:height columns:width];
1435 gui_mch_set_text_area_pos(int x, int y, int w, int h)
1440 * Set the position of the top left corner of the window to the given
1444 gui_mch_set_winpos(int x, int y)
1451 * Set the window title and icon.
1452 * (The icon is not taken care of).
1455 gui_mch_settitle(char_u *title, char_u *icon)
1457 //NSLog(@"gui_mch_settitle(title=%s, icon=%s)", title, icon);
1460 title = CONVERT_TO_UTF8(title);
1463 [[MMBackend sharedInstance] setWindowTitle:(char*)title];
1466 CONVERT_TO_UTF8_FREE(title);
1473 gui_mch_toggle_tearoffs(int enable)
1479 gui_macvim_is_valid_action(NSString *action)
1481 static NSDictionary *actionDict = nil;
1484 NSBundle *mainBundle = [NSBundle mainBundle];
1485 NSString *path = [mainBundle pathForResource:@"Actions"
1488 actionDict = [[NSDictionary alloc] initWithContentsOfFile:path];
1490 // Allocate bogus dictionary so that error only pops up once.
1491 actionDict = [NSDictionary new];
1492 EMSG(_("E???: Failed to load action dictionary"));
1496 return [actionDict objectForKey:action] != nil;
1501 gui_mch_enter_fullscreen()
1503 [[MMBackend sharedInstance] enterFullscreen];
1508 gui_mch_leave_fullscreen()
1510 [[MMBackend sharedInstance] leaveFullscreen];
1515 gui_macvim_update_modified_flag()
1517 [[MMBackend sharedInstance] updateModifiedFlag];
1521 * Add search pattern 'pat' to the OS X find pasteboard. This allows other
1522 * apps access the last pattern searched for (hitting <D-g> in another app will
1523 * initiate a search for the same pattern).
1526 gui_macvim_add_to_find_pboard(char_u *pat)
1530 // HACK: Do not call Cocoa during a fork or bad things (TM) will happen.
1531 if (gui.dofork) return;
1534 pat = CONVERT_TO_UTF8(pat);
1536 NSString *s = [NSString stringWithUTF8String:(char*)pat];
1538 CONVERT_TO_UTF8_FREE(pat);
1543 NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSFindPboard];
1544 [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1545 [pb setString:s forType:NSStringPboardType];
1551 // -- Client/Server ---------------------------------------------------------
1553 #ifdef MAC_CLIENTSERVER
1556 // NOTE: Client/Server is only fully supported with a GUI. Theoretically it
1557 // would be possible to make the server code work with terminal Vim, but it
1558 // would require that a run-loop is set up and checked. This should not be
1559 // difficult to implement, simply call gui_mch_update() at opportune moments
1560 // and it will take care of the run-loop. Another (bigger) problem with
1561 // supporting servers in terminal mode is that the server listing code talks to
1562 // MacVim (the GUI) to figure out which servers are running.
1567 * Register connection with 'name'. The actual connection is named something
1568 * like 'org.vim.MacVim.VIM3', whereas the server is called 'VIM3'.
1571 serverRegisterName(char_u *name)
1574 name = CONVERT_TO_UTF8(name);
1577 NSString *svrName = [NSString stringWithUTF8String:(char*)name];
1578 [[MMBackend sharedInstance] registerServerWithName:svrName];
1581 CONVERT_TO_UTF8_FREE(name);
1587 * Send to an instance of Vim.
1588 * Returns 0 for OK, negative for an error.
1591 serverSendToVim(char_u *name, char_u *cmd, char_u **result,
1592 int *port, int asExpr, int silent)
1595 name = CONVERT_TO_UTF8(name);
1596 cmd = CONVERT_TO_UTF8(cmd);
1599 BOOL ok = [[MMBackend sharedInstance]
1600 sendToServer:[NSString stringWithUTF8String:(char*)name]
1601 string:[NSString stringWithUTF8String:(char*)cmd]
1608 CONVERT_TO_UTF8_FREE(name);
1609 CONVERT_TO_UTF8_FREE(cmd);
1617 * Ask MacVim for the names of all Vim servers.
1620 serverGetVimNames(void)
1622 char_u *names = NULL;
1623 NSArray *list = [[MMBackend sharedInstance] serverList];
1626 NSString *string = [list componentsJoinedByString:@"\n"];
1627 char_u *s = (char_u*)[string UTF8String];
1629 s = CONVERT_FROM_UTF8(s);
1631 names = vim_strsave(s);
1633 CONVERT_FROM_UTF8_FREE(s);
1642 * 'str' is a hex int representing the send port of the connection.
1645 serverStrToPort(char_u *str)
1649 sscanf((char *)str, "0x%x", &port);
1651 EMSG2(_("E573: Invalid server id used: %s"), str);
1658 * Check for replies from server with send port 'port'.
1659 * Return TRUE and a non-malloc'ed string if there is. Else return FALSE.
1662 serverPeekReply(int port, char_u **str)
1664 NSString *reply = [[MMBackend sharedInstance] peekForReplyOnPort:port];
1665 int len = [reply lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1667 if (str && len > 0) {
1668 *str = (char_u*)[reply UTF8String];
1671 if (input_conv.vc_type != CONV_NONE) {
1672 char_u *s = string_convert(&input_conv, *str, &len);
1675 // HACK! Since 's' needs to be freed we cannot simply set
1676 // '*str = s' or memory will leak. Instead, create a dummy
1677 // NSData and return its 'bytes' pointer, then autorelease the
1679 NSData *data = [NSData dataWithBytes:s length:len+1];
1680 *str = (char_u*)[data bytes];
1688 return reply != nil;
1693 * Wait for replies from server with send port 'port'.
1694 * Return 0 and the malloc'ed string when a reply is available.
1695 * Return -1 on error.
1698 serverReadReply(int port, char_u **str)
1700 NSString *reply = [[MMBackend sharedInstance] waitForReplyOnPort:port];
1702 char_u *s = (char_u*)[reply UTF8String];
1704 s = CONVERT_FROM_UTF8(s);
1706 *str = vim_strsave(s);
1708 CONVERT_FROM_UTF8_FREE(s);
1718 * Send a reply string (notification) to client with port given by "serverid".
1719 * Return -1 if the window is invalid.
1722 serverSendReply(char_u *serverid, char_u *reply)
1725 int port = serverStrToPort(serverid);
1726 if (port > 0 && reply) {
1728 reply = CONVERT_TO_UTF8(reply);
1730 BOOL ok = [[MMBackend sharedInstance]
1731 sendReply:[NSString stringWithUTF8String:(char*)reply]
1733 retval = ok ? 0 : -1;
1735 CONVERT_TO_UTF8_FREE(reply);
1742 #endif // MAC_CLIENTSERVER
1747 // -- ODB Editor Support ----------------------------------------------------
1749 #ifdef FEAT_ODB_EDITOR
1751 * The ODB Editor protocol works like this:
1752 * - An external program (the server) asks MacVim to open a file and associates
1753 * three things with this file: (1) a server id (a four character code that
1754 * identifies the server), (2) a path that can be used as window title for
1755 * the file (optional), (3) an arbitrary token (optional)
1756 * - When a file is saved or closed, MacVim should tell the server about which
1757 * file was modified and also pass back the token
1759 * All communication between MacVim and the server goes via Apple Events.
1763 odb_event(buf_T *buf, const AEEventID action)
1765 if (!(buf->b_odb_server_id && buf->b_ffname))
1768 NSAppleEventDescriptor *targetDesc = [NSAppleEventDescriptor
1769 descriptorWithDescriptorType:typeApplSignature
1770 bytes:&buf->b_odb_server_id
1771 length:sizeof(OSType)];
1773 NSString *path = [NSString stringWithUTF8String:(char*)buf->b_ffname];
1774 NSData *pathData = [[[NSURL fileURLWithPath:path] absoluteString]
1775 dataUsingEncoding:NSUTF8StringEncoding];
1776 NSAppleEventDescriptor *pathDesc = [NSAppleEventDescriptor
1777 descriptorWithDescriptorType:typeFileURL data:pathData];
1779 NSAppleEventDescriptor *event = [NSAppleEventDescriptor
1780 appleEventWithEventClass:kODBEditorSuite
1782 targetDescriptor:targetDesc
1783 returnID:kAutoGenerateReturnID
1784 transactionID:kAnyTransactionID];
1786 [event setParamDescriptor:pathDesc forKeyword:keyDirectObject];
1788 if (buf->b_odb_token)
1789 [event setParamDescriptor:buf->b_odb_token forKeyword:keySenderToken];
1791 return AESendMessage([event aeDesc], NULL, kAENoReply | kAENeverInteract,
1796 odb_buffer_close(buf_T *buf)
1800 err = odb_event(buf, kAEClosedFile);
1802 buf->b_odb_server_id = 0;
1804 if (buf->b_odb_token) {
1805 [(NSAppleEventDescriptor *)(buf->b_odb_token) release];
1806 buf->b_odb_token = NULL;
1809 if (buf->b_odb_fname) {
1810 vim_free(buf->b_odb_fname);
1811 buf->b_odb_fname = NULL;
1819 odb_post_buffer_write(buf_T *buf)
1821 return buf ? odb_event(buf, kAEModifiedFile) : noErr;
1828 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1829 odb_buffer_close(buf);
1832 #endif // FEAT_ODB_EDITOR