xref: /vim-8.2.3635/src/gui.c (revision f193fffd)
1 /* vi:set ts=8 sts=4 sw=4:
2  *
3  * VIM - Vi IMproved		by Bram Moolenaar
4  *				GUI/Motif support by Robert Webb
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  */
10 
11 #include "vim.h"
12 
13 /* Structure containing all the GUI information */
14 gui_T gui;
15 
16 #if defined(FEAT_MBYTE) && !defined(HAVE_GTK2)
17 static void set_guifontwide __ARGS((char_u *font_name));
18 #endif
19 static void gui_check_pos __ARGS((void));
20 static void gui_position_components __ARGS((int));
21 static void gui_outstr __ARGS((char_u *, int));
22 static int gui_screenchar __ARGS((int off, int flags, guicolor_T fg, guicolor_T bg, int back));
23 #ifdef HAVE_GTK2
24 static int gui_screenstr __ARGS((int off, int len, int flags, guicolor_T fg, guicolor_T bg, int back));
25 #endif
26 static void gui_delete_lines __ARGS((int row, int count));
27 static void gui_insert_lines __ARGS((int row, int count));
28 static void fill_mouse_coord __ARGS((char_u *p, int col, int row));
29 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
30 static int gui_has_tabline __ARGS((void));
31 #endif
32 static void gui_do_scrollbar __ARGS((win_T *wp, int which, int enable));
33 static colnr_T scroll_line_len __ARGS((linenr_T lnum));
34 static void gui_update_horiz_scrollbar __ARGS((int));
35 static void gui_set_fg_color __ARGS((char_u *name));
36 static void gui_set_bg_color __ARGS((char_u *name));
37 static win_T *xy2win __ARGS((int x, int y));
38 
39 static int can_update_cursor = TRUE; /* can display the cursor */
40 
41 /*
42  * The Athena scrollbars can move the thumb to after the end of the scrollbar,
43  * this makes the thumb indicate the part of the text that is shown.  Motif
44  * can't do this.
45  */
46 #if defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_MAC)
47 # define SCROLL_PAST_END
48 #endif
49 
50 /*
51  * gui_start -- Called when user wants to start the GUI.
52  *
53  * Careful: This function can be called recursively when there is a ":gui"
54  * command in the .gvimrc file.  Only the first call should fork, not the
55  * recursive call.
56  */
57     void
58 gui_start()
59 {
60     char_u	*old_term;
61 #if defined(UNIX) && !defined(__BEOS__) && !defined(MACOS_X)
62 # define MAY_FORK
63     int		dofork = TRUE;
64 #endif
65     static int	recursive = 0;
66 
67     old_term = vim_strsave(T_NAME);
68 
69     /*
70      * Set_termname() will call gui_init() to start the GUI.
71      * Set the "starting" flag, to indicate that the GUI will start.
72      *
73      * We don't want to open the GUI shell until after we've read .gvimrc,
74      * otherwise we don't know what font we will use, and hence we don't know
75      * what size the shell should be.  So if there are errors in the .gvimrc
76      * file, they will have to go to the terminal: Set full_screen to FALSE.
77      * full_screen will be set to TRUE again by a successful termcapinit().
78      */
79     settmode(TMODE_COOK);		/* stop RAW mode */
80     if (full_screen)
81 	cursor_on();			/* needed for ":gui" in .vimrc */
82     gui.starting = TRUE;
83     full_screen = FALSE;
84 
85 #ifdef MAY_FORK
86     if (!gui.dofork || vim_strchr(p_go, GO_FORG) || recursive)
87 	dofork = FALSE;
88 #endif
89     ++recursive;
90 
91     termcapinit((char_u *)"builtin_gui");
92     gui.starting = recursive - 1;
93 
94     if (!gui.in_use)			/* failed to start GUI */
95     {
96 	termcapinit(old_term);		/* back to old term settings */
97 	settmode(TMODE_RAW);		/* restart RAW mode */
98 #ifdef FEAT_TITLE
99 	set_title_defaults();		/* set 'title' and 'icon' again */
100 #endif
101     }
102 
103     vim_free(old_term);
104 
105 #if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_X11)
106     if (gui.in_use)
107 	/* Display error messages in a dialog now. */
108 	display_errors();
109 #endif
110 
111 #if defined(MAY_FORK) && !defined(__QNXNTO__)
112     /*
113      * Quit the current process and continue in the child.
114      * Makes "gvim file" disconnect from the shell it was started in.
115      * Don't do this when Vim was started with "-f" or the 'f' flag is present
116      * in 'guioptions'.
117      */
118     if (gui.in_use && dofork)
119     {
120 	int	pipefd[2];	/* pipe between parent and child */
121 	int	pipe_error;
122 	char	dummy;
123 	pid_t	pid = -1;
124 
125 	/* Setup a pipe between the child and the parent, so that the parent
126 	 * knows when the child has done the setsid() call and is allowed to
127 	 * exit. */
128 	pipe_error = (pipe(pipefd) < 0);
129 	pid = fork();
130 	if (pid > 0)	    /* Parent */
131 	{
132 	    /* Give the child some time to do the setsid(), otherwise the
133 	     * exit() may kill the child too (when starting gvim from inside a
134 	     * gvim). */
135 	    if (pipe_error)
136 		ui_delay(300L, TRUE);
137 	    else
138 	    {
139 		/* The read returns when the child closes the pipe (or when
140 		 * the child dies for some reason). */
141 		close(pipefd[1]);
142 		(void)read(pipefd[0], &dummy, (size_t)1);
143 		close(pipefd[0]);
144 	    }
145 
146 	    /* When swapping screens we may need to go to the next line, e.g.,
147 	     * after a hit-enter prompt and using ":gui". */
148 	    if (newline_on_exit)
149 		mch_errmsg("\r\n");
150 
151 	    /*
152 	     * The parent must skip the normal exit() processing, the child
153 	     * will do it.  For example, GTK messes up signals when exiting.
154 	     */
155 	    _exit(0);
156 	}
157 
158 # if defined(HAVE_SETSID) || defined(HAVE_SETPGID)
159 	/*
160 	 * Change our process group.  On some systems/shells a CTRL-C in the
161 	 * shell where Vim was started would otherwise kill gvim!
162 	 */
163 	if (pid == 0)	    /* child */
164 #  if defined(HAVE_SETSID)
165 	    (void)setsid();
166 #  else
167 	    (void)setpgid(0, 0);
168 #  endif
169 # endif
170 	if (!pipe_error)
171 	{
172 	    close(pipefd[0]);
173 	    close(pipefd[1]);
174 	}
175 
176 # if defined(FEAT_GUI_GNOME) && defined(FEAT_SESSION)
177 	/* Tell the session manager our new PID */
178 	gui_mch_forked();
179 # endif
180     }
181 #else
182 # if defined(__QNXNTO__)
183     if (gui.in_use && dofork)
184 	procmgr_daemon(0, PROCMGR_DAEMON_KEEPUMASK | PROCMGR_DAEMON_NOCHDIR |
185 		PROCMGR_DAEMON_NOCLOSE | PROCMGR_DAEMON_NODEVNULL);
186 # endif
187 #endif
188 
189 #ifdef FEAT_AUTOCMD
190     /* If the GUI started successfully, trigger the GUIEnter event */
191     if (gui.in_use)
192 	apply_autocmds(EVENT_GUIENTER, NULL, NULL, FALSE, curbuf);
193 #endif
194 
195     --recursive;
196 }
197 
198 /*
199  * Call this when vim starts up, whether or not the GUI is started
200  */
201     void
202 gui_prepare(argc, argv)
203     int	    *argc;
204     char    **argv;
205 {
206     gui.in_use = FALSE;		    /* No GUI yet (maybe later) */
207     gui.starting = FALSE;	    /* No GUI yet (maybe later) */
208     gui_mch_prepare(argc, argv);
209 }
210 
211 /*
212  * Try initializing the GUI and check if it can be started.
213  * Used from main() to check early if "vim -g" can start the GUI.
214  * Used from gui_init() to prepare for starting the GUI.
215  * Returns FAIL or OK.
216  */
217     int
218 gui_init_check()
219 {
220     static int result = MAYBE;
221 
222     if (result != MAYBE)
223     {
224 	if (result == FAIL)
225 	    EMSG(_("E229: Cannot start the GUI"));
226 	return result;
227     }
228 
229     gui.shell_created = FALSE;
230     gui.dying = FALSE;
231     gui.in_focus = TRUE;		/* so the guicursor setting works */
232     gui.dragged_sb = SBAR_NONE;
233     gui.dragged_wp = NULL;
234     gui.pointer_hidden = FALSE;
235     gui.col = 0;
236     gui.row = 0;
237     gui.num_cols = Columns;
238     gui.num_rows = Rows;
239 
240     gui.cursor_is_valid = FALSE;
241     gui.scroll_region_top = 0;
242     gui.scroll_region_bot = Rows - 1;
243     gui.scroll_region_left = 0;
244     gui.scroll_region_right = Columns - 1;
245     gui.highlight_mask = HL_NORMAL;
246     gui.char_width = 1;
247     gui.char_height = 1;
248     gui.char_ascent = 0;
249     gui.border_width = 0;
250 
251     gui.norm_font = NOFONT;
252 #ifndef HAVE_GTK2
253     gui.bold_font = NOFONT;
254     gui.ital_font = NOFONT;
255     gui.boldital_font = NOFONT;
256 # ifdef FEAT_XFONTSET
257     gui.fontset = NOFONTSET;
258 # endif
259 #endif
260 
261 #ifdef FEAT_MENU
262 # ifndef HAVE_GTK2
263 #  ifdef FONTSET_ALWAYS
264     gui.menu_fontset = NOFONTSET;
265 #  else
266     gui.menu_font = NOFONT;
267 #  endif
268 # endif
269     gui.menu_is_active = TRUE;	    /* default: include menu */
270 # ifndef FEAT_GUI_GTK
271     gui.menu_height = MENU_DEFAULT_HEIGHT;
272     gui.menu_width = 0;
273 # endif
274 #endif
275 #if defined(FEAT_TOOLBAR) && (defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA))
276     gui.toolbar_height = 0;
277 #endif
278 #if defined(FEAT_FOOTER) && defined(FEAT_GUI_MOTIF)
279     gui.footer_height = 0;
280 #endif
281 #ifdef FEAT_BEVAL_TIP
282     gui.tooltip_fontset = NOFONTSET;
283 #endif
284 
285     gui.scrollbar_width = gui.scrollbar_height = SB_DEFAULT_WIDTH;
286     gui.prev_wrap = -1;
287 
288 #ifdef ALWAYS_USE_GUI
289     result = OK;
290 #else
291     result = gui_mch_init_check();
292 #endif
293     return result;
294 }
295 
296 /*
297  * This is the call which starts the GUI.
298  */
299     void
300 gui_init()
301 {
302     win_T	*wp;
303     static int	recursive = 0;
304 
305     /*
306      * It's possible to use ":gui" in a .gvimrc file.  The first halve of this
307      * function will then be executed at the first call, the rest by the
308      * recursive call.  This allow the shell to be opened halfway reading a
309      * gvimrc file.
310      */
311     if (!recursive)
312     {
313 	++recursive;
314 
315 	clip_init(TRUE);
316 
317 	/* If can't initialize, don't try doing the rest */
318 	if (gui_init_check() == FAIL)
319 	{
320 	    --recursive;
321 	    clip_init(FALSE);
322 	    return;
323 	}
324 
325 	/*
326 	 * Reset 'paste'.  It's useful in the terminal, but not in the GUI.  It
327 	 * breaks the Paste toolbar button.
328 	 */
329 	set_option_value((char_u *)"paste", 0L, NULL, 0);
330 
331 	/*
332 	 * Set up system-wide default menus.
333 	 */
334 #if defined(SYS_MENU_FILE) && defined(FEAT_MENU)
335 	if (vim_strchr(p_go, GO_NOSYSMENU) == NULL)
336 	{
337 	    sys_menu = TRUE;
338 	    do_source((char_u *)SYS_MENU_FILE, FALSE, DOSO_NONE);
339 	    sys_menu = FALSE;
340 	}
341 #endif
342 
343 	/*
344 	 * Switch on the mouse by default, unless the user changed it already.
345 	 * This can then be changed in the .gvimrc.
346 	 */
347 	if (!option_was_set((char_u *)"mouse"))
348 	    set_string_option_direct((char_u *)"mouse", -1,
349 					   (char_u *)"a", OPT_FREE, SID_NONE);
350 
351 	/*
352 	 * If -U option given, use only the initializations from that file and
353 	 * nothing else.  Skip all initializations for "-U NONE" or "-u NORC".
354 	 */
355 	if (use_gvimrc != NULL)
356 	{
357 	    if (STRCMP(use_gvimrc, "NONE") != 0
358 		    && STRCMP(use_gvimrc, "NORC") != 0
359 		    && do_source(use_gvimrc, FALSE, DOSO_NONE) != OK)
360 		EMSG2(_("E230: Cannot read from \"%s\""), use_gvimrc);
361 	}
362 	else
363 	{
364 	    /*
365 	     * Get system wide defaults for gvim, only when file name defined.
366 	     */
367 #ifdef SYS_GVIMRC_FILE
368 	    do_source((char_u *)SYS_GVIMRC_FILE, FALSE, DOSO_NONE);
369 #endif
370 
371 	    /*
372 	     * Try to read GUI initialization commands from the following
373 	     * places:
374 	     * - environment variable GVIMINIT
375 	     * - the user gvimrc file (~/.gvimrc)
376 	     * - the second user gvimrc file ($VIM/.gvimrc for Dos)
377 	     * - the third user gvimrc file ($VIM/.gvimrc for Amiga)
378 	     * The first that exists is used, the rest is ignored.
379 	     */
380 	    if (process_env((char_u *)"GVIMINIT", FALSE) == FAIL
381 		 && do_source((char_u *)USR_GVIMRC_FILE, TRUE,
382 							  DOSO_GVIMRC) == FAIL
383 #ifdef USR_GVIMRC_FILE2
384 		 && do_source((char_u *)USR_GVIMRC_FILE2, TRUE,
385 							  DOSO_GVIMRC) == FAIL
386 #endif
387 				)
388 	    {
389 #ifdef USR_GVIMRC_FILE3
390 		(void)do_source((char_u *)USR_GVIMRC_FILE3, TRUE, DOSO_GVIMRC);
391 #endif
392 	    }
393 
394 	    /*
395 	     * Read initialization commands from ".gvimrc" in current
396 	     * directory.  This is only done if the 'exrc' option is set.
397 	     * Because of security reasons we disallow shell and write
398 	     * commands now, except for unix if the file is owned by the user
399 	     * or 'secure' option has been reset in environment of global
400 	     * ".gvimrc".
401 	     * Only do this if GVIMRC_FILE is not the same as USR_GVIMRC_FILE,
402 	     * USR_GVIMRC_FILE2, USR_GVIMRC_FILE3 or SYS_GVIMRC_FILE.
403 	     */
404 	    if (p_exrc)
405 	    {
406 #ifdef UNIX
407 		{
408 		    struct stat s;
409 
410 		    /* if ".gvimrc" file is not owned by user, set 'secure'
411 		     * mode */
412 		    if (mch_stat(GVIMRC_FILE, &s) || s.st_uid != getuid())
413 			secure = p_secure;
414 		}
415 #else
416 		secure = p_secure;
417 #endif
418 
419 		if (       fullpathcmp((char_u *)USR_GVIMRC_FILE,
420 				     (char_u *)GVIMRC_FILE, FALSE) != FPC_SAME
421 #ifdef SYS_GVIMRC_FILE
422 			&& fullpathcmp((char_u *)SYS_GVIMRC_FILE,
423 				     (char_u *)GVIMRC_FILE, FALSE) != FPC_SAME
424 #endif
425 #ifdef USR_GVIMRC_FILE2
426 			&& fullpathcmp((char_u *)USR_GVIMRC_FILE2,
427 				     (char_u *)GVIMRC_FILE, FALSE) != FPC_SAME
428 #endif
429 #ifdef USR_GVIMRC_FILE3
430 			&& fullpathcmp((char_u *)USR_GVIMRC_FILE3,
431 				     (char_u *)GVIMRC_FILE, FALSE) != FPC_SAME
432 #endif
433 			)
434 		    do_source((char_u *)GVIMRC_FILE, TRUE, DOSO_GVIMRC);
435 
436 		if (secure == 2)
437 		    need_wait_return = TRUE;
438 		secure = 0;
439 	    }
440 	}
441 
442 	if (need_wait_return || msg_didany)
443 	    wait_return(TRUE);
444 
445 	--recursive;
446     }
447 
448     /* If recursive call opened the shell, return here from the first call */
449     if (gui.in_use)
450 	return;
451 
452     /*
453      * Create the GUI shell.
454      */
455     gui.in_use = TRUE;		/* Must be set after menus have been set up */
456     if (gui_mch_init() == FAIL)
457 	goto error;
458 
459     /* Avoid a delay for an error message that was printed in the terminal
460      * where Vim was started. */
461     emsg_on_display = FALSE;
462     msg_scrolled = 0;
463     clear_sb_text();
464     need_wait_return = FALSE;
465     msg_didany = FALSE;
466 
467     /*
468      * Check validity of any generic resources that may have been loaded.
469      */
470     if (gui.border_width < 0)
471 	gui.border_width = 0;
472 
473     /*
474      * Set up the fonts.  First use a font specified with "-fn" or "-font".
475      */
476     if (font_argument != NULL)
477 	set_option_value((char_u *)"gfn", 0L, (char_u *)font_argument, 0);
478     if (
479 #ifdef FEAT_XFONTSET
480 	    (*p_guifontset == NUL
481 	     || gui_init_font(p_guifontset, TRUE) == FAIL) &&
482 #endif
483 	    gui_init_font(*p_guifont == NUL ? hl_get_font_name()
484 						  : p_guifont, FALSE) == FAIL)
485     {
486 	EMSG(_("E665: Cannot start GUI, no valid font found"));
487 	goto error2;
488     }
489 #ifdef FEAT_MBYTE
490     if (gui_get_wide_font() == FAIL)
491 	EMSG(_("E231: 'guifontwide' invalid"));
492 #endif
493 
494     gui.num_cols = Columns;
495     gui.num_rows = Rows;
496     gui_reset_scroll_region();
497 
498     /* Create initial scrollbars */
499     FOR_ALL_WINDOWS(wp)
500     {
501 	gui_create_scrollbar(&wp->w_scrollbars[SBAR_LEFT], SBAR_LEFT, wp);
502 	gui_create_scrollbar(&wp->w_scrollbars[SBAR_RIGHT], SBAR_RIGHT, wp);
503     }
504     gui_create_scrollbar(&gui.bottom_sbar, SBAR_BOTTOM, NULL);
505 
506 #ifdef FEAT_MENU
507     gui_create_initial_menus(root_menu);
508 #endif
509 #ifdef FEAT_SUN_WORKSHOP
510     if (usingSunWorkShop)
511 	workshop_init();
512 #endif
513 #ifdef FEAT_SIGN_ICONS
514     sign_gui_started();
515 #endif
516 
517     /* Configure the desired menu and scrollbars */
518     gui_init_which_components(NULL);
519 
520     /* All components of the GUI have been created now */
521     gui.shell_created = TRUE;
522 
523 #ifndef FEAT_GUI_GTK
524     /* Set the shell size, adjusted for the screen size.  For GTK this only
525      * works after the shell has been opened, thus it is further down. */
526     gui_set_shellsize(FALSE, TRUE, RESIZE_BOTH);
527 #endif
528 #if defined(FEAT_GUI_MOTIF) && defined(FEAT_MENU)
529     /* Need to set the size of the menubar after all the menus have been
530      * created. */
531     gui_mch_compute_menu_height((Widget)0);
532 #endif
533 
534     /*
535      * Actually open the GUI shell.
536      */
537     if (gui_mch_open() != FAIL)
538     {
539 #ifdef FEAT_TITLE
540 	maketitle();
541 	resettitle();
542 #endif
543 	init_gui_options();
544 #ifdef FEAT_ARABIC
545 	/* Our GUI can't do bidi. */
546 	p_tbidi = FALSE;
547 #endif
548 #if defined(FEAT_GUI_GTK)
549 	/* Give GTK+ a chance to put all widget's into place. */
550 	gui_mch_update();
551 
552 # ifdef FEAT_MENU
553 	/* If there is no 'm' in 'guioptions' we need to remove the menu now.
554 	 * It was still there to make F10 work. */
555 	if (vim_strchr(p_go, GO_MENUS) == NULL)
556 	{
557 	    --gui.starting;
558 	    gui_mch_enable_menu(FALSE);
559 	    ++gui.starting;
560 	    gui_mch_update();
561 	}
562 # endif
563 
564 	/* Now make sure the shell fits on the screen. */
565 	gui_set_shellsize(FALSE, TRUE, RESIZE_BOTH);
566 #endif
567 	/* When 'lines' was set while starting up the topframe may have to be
568 	 * resized. */
569 	win_new_shellsize();
570 
571 #ifdef FEAT_BEVAL
572 	/* Always create the Balloon Evaluation area, but disable it when
573 	 * 'ballooneval' is off */
574 # ifdef FEAT_GUI_GTK
575 	balloonEval = gui_mch_create_beval_area(gui.drawarea, NULL,
576 						     &general_beval_cb, NULL);
577 # else
578 #  if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA)
579 	{
580 	    extern Widget	textArea;
581 	    balloonEval = gui_mch_create_beval_area(textArea, NULL,
582 						     &general_beval_cb, NULL);
583 	}
584 #  else
585 #   ifdef FEAT_GUI_W32
586 	balloonEval = gui_mch_create_beval_area(NULL, NULL,
587 						     &general_beval_cb, NULL);
588 #   endif
589 #  endif
590 # endif
591 	if (!p_beval)
592 	    gui_mch_disable_beval_area(balloonEval);
593 #endif
594 
595 #ifdef FEAT_NETBEANS_INTG
596 	if (starting == 0 && usingNetbeans)
597 	    /* Tell the client that it can start sending commands. */
598 	    netbeans_startup_done();
599 #endif
600 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
601 	if (!im_xim_isvalid_imactivate())
602 	    EMSG(_("E599: Value of 'imactivatekey' is invalid"));
603 #endif
604 	/* When 'cmdheight' was set during startup it may not have taken
605 	 * effect yet. */
606 	if (p_ch != 1L)
607 	    command_height();
608 
609 	return;
610     }
611 
612 error2:
613 #ifdef FEAT_GUI_X11
614     /* undo gui_mch_init() */
615     gui_mch_uninit();
616 #endif
617 
618 error:
619     gui.in_use = FALSE;
620     clip_init(FALSE);
621 }
622 
623 
624     void
625 gui_exit(rc)
626     int		rc;
627 {
628 #ifndef __BEOS__
629     /* don't free the fonts, it leads to a BUS error
630      * [email protected] Jul 99 */
631     free_highlight_fonts();
632 #endif
633     gui.in_use = FALSE;
634     gui_mch_exit(rc);
635 }
636 
637 #if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_X11) || defined(FEAT_GUI_MSWIN) \
638 	|| defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(PROTO)
639 /*
640  * Called when the GUI shell is closed by the user.  If there are no changed
641  * files Vim exits, otherwise there will be a dialog to ask the user what to
642  * do.
643  * When this function returns, Vim should NOT exit!
644  */
645     void
646 gui_shell_closed()
647 {
648     cmdmod_T	    save_cmdmod;
649 
650     save_cmdmod = cmdmod;
651 
652     /* Only exit when there are no changed files */
653     exiting = TRUE;
654 # ifdef FEAT_BROWSE
655     cmdmod.browse = TRUE;
656 # endif
657 # if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
658     cmdmod.confirm = TRUE;
659 # endif
660     /* If there are changed buffers, present the user with a dialog if
661      * possible, otherwise give an error message. */
662     if (!check_changed_any(FALSE))
663 	getout(0);
664 
665     exiting = FALSE;
666     cmdmod = save_cmdmod;
667     setcursor();		/* position cursor */
668     out_flush();
669 }
670 #endif
671 
672 /*
673  * Set the font.  "font_list" is a a comma separated list of font names.  The
674  * first font name that works is used.  If none is found, use the default
675  * font.
676  * If "fontset" is TRUE, the "font_list" is used as one name for the fontset.
677  * Return OK when able to set the font.  When it failed FAIL is returned and
678  * the fonts are unchanged.
679  */
680 /*ARGSUSED*/
681     int
682 gui_init_font(font_list, fontset)
683     char_u	*font_list;
684     int		fontset;
685 {
686 #define FONTLEN 320
687     char_u	font_name[FONTLEN];
688     int		font_list_empty = FALSE;
689     int		ret = FAIL;
690 
691     if (!gui.in_use)
692 	return FAIL;
693 
694     font_name[0] = NUL;
695     if (*font_list == NUL)
696 	font_list_empty = TRUE;
697     else
698     {
699 #ifdef FEAT_XFONTSET
700 	/* When using a fontset, the whole list of fonts is one name. */
701 	if (fontset)
702 	    ret = gui_mch_init_font(font_list, TRUE);
703 	else
704 #endif
705 	    while (*font_list != NUL)
706 	    {
707 		/* Isolate one comma separated font name. */
708 		(void)copy_option_part(&font_list, font_name, FONTLEN, ",");
709 
710 		/* Careful!!!  The Win32 version of gui_mch_init_font(), when
711 		 * called with "*" will change p_guifont to the selected font
712 		 * name, which frees the old value.  This makes font_list
713 		 * invalid.  Thus when OK is returned here, font_list must no
714 		 * longer be used! */
715 		if (gui_mch_init_font(font_name, FALSE) == OK)
716 		{
717 #if defined(FEAT_MBYTE) && !defined(HAVE_GTK2)
718 		    /* If it's a Unicode font, try setting 'guifontwide' to a
719 		     * similar double-width font. */
720 		    if ((p_guifontwide == NULL || *p_guifontwide == NUL)
721 				&& strstr((char *)font_name, "10646") != NULL)
722 			set_guifontwide(font_name);
723 #endif
724 		    ret = OK;
725 		    break;
726 		}
727 	    }
728     }
729 
730     if (ret != OK
731 	    && STRCMP(font_list, "*") != 0
732 	    && (font_list_empty || gui.norm_font == NOFONT))
733     {
734 	/*
735 	 * Couldn't load any font in 'font_list', keep the current font if
736 	 * there is one.  If 'font_list' is empty, or if there is no current
737 	 * font, tell gui_mch_init_font() to try to find a font we can load.
738 	 */
739 	ret = gui_mch_init_font(NULL, FALSE);
740     }
741 
742     if (ret == OK)
743     {
744 #ifndef HAVE_GTK2
745 	/* Set normal font as current font */
746 # ifdef FEAT_XFONTSET
747 	if (gui.fontset != NOFONTSET)
748 	    gui_mch_set_fontset(gui.fontset);
749 	else
750 # endif
751 	    gui_mch_set_font(gui.norm_font);
752 #endif
753 	gui_set_shellsize(FALSE,
754 #ifdef MSWIN
755 		TRUE
756 #else
757 		FALSE
758 #endif
759 		, RESIZE_BOTH);
760     }
761 
762     return ret;
763 }
764 
765 #if defined(FEAT_MBYTE) || defined(PROTO)
766 # ifndef HAVE_GTK2
767 /*
768  * Try setting 'guifontwide' to a font twice as wide as "name".
769  */
770     static void
771 set_guifontwide(name)
772     char_u	*name;
773 {
774     int		i = 0;
775     char_u	wide_name[FONTLEN + 10]; /* room for 2 * width and '*' */
776     char_u	*wp = NULL;
777     char_u	*p;
778     GuiFont	font;
779 
780     wp = wide_name;
781     for (p = name; *p != NUL; ++p)
782     {
783 	*wp++ = *p;
784 	if (*p == '-')
785 	{
786 	    ++i;
787 	    if (i == 6)		/* font type: change "--" to "-*-" */
788 	    {
789 		if (p[1] == '-')
790 		    *wp++ = '*';
791 	    }
792 	    else if (i == 12)	/* found the width */
793 	    {
794 		++p;
795 		i = getdigits(&p);
796 		if (i != 0)
797 		{
798 		    /* Double the width specification. */
799 		    sprintf((char *)wp, "%d%s", i * 2, p);
800 		    font = gui_mch_get_font(wide_name, FALSE);
801 		    if (font != NOFONT)
802 		    {
803 			gui_mch_free_font(gui.wide_font);
804 			gui.wide_font = font;
805 			set_string_option_direct((char_u *)"gfw", -1,
806 						      wide_name, OPT_FREE, 0);
807 		    }
808 		}
809 		break;
810 	    }
811 	}
812     }
813 }
814 # endif /* !HAVE_GTK2 */
815 
816 /*
817  * Get the font for 'guifontwide'.
818  * Return FAIL for an invalid font name.
819  */
820     int
821 gui_get_wide_font()
822 {
823     GuiFont	font = NOFONT;
824     char_u	font_name[FONTLEN];
825     char_u	*p;
826 
827     if (!gui.in_use)	    /* Can't allocate font yet, assume it's OK. */
828 	return OK;	    /* Will give an error message later. */
829 
830     if (p_guifontwide != NULL && *p_guifontwide != NUL)
831     {
832 	for (p = p_guifontwide; *p != NUL; )
833 	{
834 	    /* Isolate one comma separated font name. */
835 	    (void)copy_option_part(&p, font_name, FONTLEN, ",");
836 	    font = gui_mch_get_font(font_name, FALSE);
837 	    if (font != NOFONT)
838 		break;
839 	}
840 	if (font == NOFONT)
841 	    return FAIL;
842     }
843 
844     gui_mch_free_font(gui.wide_font);
845 #ifdef HAVE_GTK2
846     /* Avoid unnecessary overhead if 'guifontwide' is equal to 'guifont'. */
847     if (font != NOFONT && gui.norm_font != NOFONT
848 			 && pango_font_description_equal(font, gui.norm_font))
849     {
850 	gui.wide_font = NOFONT;
851 	gui_mch_free_font(font);
852     }
853     else
854 #endif
855 	gui.wide_font = font;
856     return OK;
857 }
858 #endif
859 
860     void
861 gui_set_cursor(row, col)
862     int	    row;
863     int	    col;
864 {
865     gui.row = row;
866     gui.col = col;
867 }
868 
869 /*
870  * gui_check_pos - check if the cursor is on the screen.
871  */
872     static void
873 gui_check_pos()
874 {
875     if (gui.row >= screen_Rows)
876 	gui.row = screen_Rows - 1;
877     if (gui.col >= screen_Columns)
878 	gui.col = screen_Columns - 1;
879     if (gui.cursor_row >= screen_Rows || gui.cursor_col >= screen_Columns)
880 	gui.cursor_is_valid = FALSE;
881 }
882 
883 /*
884  * Redraw the cursor if necessary or when forced.
885  * Careful: The contents of ScreenLines[] must match what is on the screen,
886  * otherwise this goes wrong.  May need to call out_flush() first.
887  */
888     void
889 gui_update_cursor(force, clear_selection)
890     int		force;		/* when TRUE, update even when not moved */
891     int		clear_selection;/* clear selection under cursor */
892 {
893     int		cur_width = 0;
894     int		cur_height = 0;
895     int		old_hl_mask;
896     int		idx;
897     int		id;
898     guicolor_T	cfg, cbg, cc;	/* cursor fore-/background color */
899     int		cattr;		/* cursor attributes */
900     int		attr;
901     attrentry_T *aep = NULL;
902 
903     /* Don't update the cursor when halfway busy scrolling.
904      * ScreenLines[] isn't valid then. */
905     if (!can_update_cursor)
906 	return;
907 
908     gui_check_pos();
909     if (!gui.cursor_is_valid || force
910 		    || gui.row != gui.cursor_row || gui.col != gui.cursor_col)
911     {
912 	gui_undraw_cursor();
913 	if (gui.row < 0)
914 	    return;
915 #ifdef USE_IM_CONTROL
916 	if (gui.row != gui.cursor_row || gui.col != gui.cursor_col)
917 	    im_set_position(gui.row, gui.col);
918 #endif
919 	gui.cursor_row = gui.row;
920 	gui.cursor_col = gui.col;
921 
922 	/* Only write to the screen after ScreenLines[] has been initialized */
923 	if (!screen_cleared || ScreenLines == NULL)
924 	    return;
925 
926 	/* Clear the selection if we are about to write over it */
927 	if (clear_selection)
928 	    clip_may_clear_selection(gui.row, gui.row);
929 	/* Check that the cursor is inside the shell (resizing may have made
930 	 * it invalid) */
931 	if (gui.row >= screen_Rows || gui.col >= screen_Columns)
932 	    return;
933 
934 	gui.cursor_is_valid = TRUE;
935 
936 	/*
937 	 * How the cursor is drawn depends on the current mode.
938 	 */
939 	idx = get_shape_idx(FALSE);
940 	if (State & LANGMAP)
941 	    id = shape_table[idx].id_lm;
942 	else
943 	    id = shape_table[idx].id;
944 
945 	/* get the colors and attributes for the cursor.  Default is inverted */
946 	cfg = INVALCOLOR;
947 	cbg = INVALCOLOR;
948 	cattr = HL_INVERSE;
949 	gui_mch_set_blinking(shape_table[idx].blinkwait,
950 			     shape_table[idx].blinkon,
951 			     shape_table[idx].blinkoff);
952 	if (id > 0)
953 	{
954 	    cattr = syn_id2colors(id, &cfg, &cbg);
955 #if defined(USE_IM_CONTROL) || defined(FEAT_HANGULIN)
956 	    {
957 		static int iid;
958 		guicolor_T fg, bg;
959 
960 		if (im_get_status())
961 		{
962 		    iid = syn_name2id((char_u *)"CursorIM");
963 		    if (iid > 0)
964 		    {
965 			syn_id2colors(iid, &fg, &bg);
966 			if (bg != INVALCOLOR)
967 			    cbg = bg;
968 			if (fg != INVALCOLOR)
969 			    cfg = fg;
970 		    }
971 		}
972 	    }
973 #endif
974 	}
975 
976 	/*
977 	 * Get the attributes for the character under the cursor.
978 	 * When no cursor color was given, use the character color.
979 	 */
980 	attr = ScreenAttrs[LineOffset[gui.row] + gui.col];
981 	if (attr > HL_ALL)
982 	    aep = syn_gui_attr2entry(attr);
983 	if (aep != NULL)
984 	{
985 	    attr = aep->ae_attr;
986 	    if (cfg == INVALCOLOR)
987 		cfg = ((attr & HL_INVERSE)  ? aep->ae_u.gui.bg_color
988 					    : aep->ae_u.gui.fg_color);
989 	    if (cbg == INVALCOLOR)
990 		cbg = ((attr & HL_INVERSE)  ? aep->ae_u.gui.fg_color
991 					    : aep->ae_u.gui.bg_color);
992 	}
993 	if (cfg == INVALCOLOR)
994 	    cfg = (attr & HL_INVERSE) ? gui.back_pixel : gui.norm_pixel;
995 	if (cbg == INVALCOLOR)
996 	    cbg = (attr & HL_INVERSE) ? gui.norm_pixel : gui.back_pixel;
997 
998 #ifdef FEAT_XIM
999 	if (aep != NULL)
1000 	{
1001 	    xim_bg_color = ((attr & HL_INVERSE) ? aep->ae_u.gui.fg_color
1002 						: aep->ae_u.gui.bg_color);
1003 	    xim_fg_color = ((attr & HL_INVERSE) ? aep->ae_u.gui.bg_color
1004 						: aep->ae_u.gui.fg_color);
1005 	    if (xim_bg_color == INVALCOLOR)
1006 		xim_bg_color = (attr & HL_INVERSE) ? gui.norm_pixel
1007 						   : gui.back_pixel;
1008 	    if (xim_fg_color == INVALCOLOR)
1009 		xim_fg_color = (attr & HL_INVERSE) ? gui.back_pixel
1010 						   : gui.norm_pixel;
1011 	}
1012 	else
1013 	{
1014 	    xim_bg_color = (attr & HL_INVERSE) ? gui.norm_pixel
1015 					       : gui.back_pixel;
1016 	    xim_fg_color = (attr & HL_INVERSE) ? gui.back_pixel
1017 					       : gui.norm_pixel;
1018 	}
1019 #endif
1020 
1021 	attr &= ~HL_INVERSE;
1022 	if (cattr & HL_INVERSE)
1023 	{
1024 	    cc = cbg;
1025 	    cbg = cfg;
1026 	    cfg = cc;
1027 	}
1028 	cattr &= ~HL_INVERSE;
1029 
1030 	/*
1031 	 * When we don't have window focus, draw a hollow cursor.
1032 	 */
1033 	if (!gui.in_focus)
1034 	{
1035 	    gui_mch_draw_hollow_cursor(cbg);
1036 	    return;
1037 	}
1038 
1039 	old_hl_mask = gui.highlight_mask;
1040 	if (shape_table[idx].shape == SHAPE_BLOCK
1041 #ifdef FEAT_HANGULIN
1042 		|| composing_hangul
1043 #endif
1044 	   )
1045 	{
1046 	    /*
1047 	     * Draw the text character with the cursor colors.	Use the
1048 	     * character attributes plus the cursor attributes.
1049 	     */
1050 	    gui.highlight_mask = (cattr | attr);
1051 #ifdef FEAT_HANGULIN
1052 	    if (composing_hangul)
1053 		(void)gui_outstr_nowrap(composing_hangul_buffer, 2,
1054 			GUI_MON_IS_CURSOR | GUI_MON_NOCLEAR, cfg, cbg, 0);
1055 	    else
1056 #endif
1057 		(void)gui_screenchar(LineOffset[gui.row] + gui.col,
1058 			GUI_MON_IS_CURSOR | GUI_MON_NOCLEAR, cfg, cbg, 0);
1059 	}
1060 	else
1061 	{
1062 #if defined(FEAT_MBYTE) && defined(FEAT_RIGHTLEFT)
1063 	    int	    col_off = FALSE;
1064 #endif
1065 	    /*
1066 	     * First draw the partial cursor, then overwrite with the text
1067 	     * character, using a transparent background.
1068 	     */
1069 	    if (shape_table[idx].shape == SHAPE_VER)
1070 	    {
1071 		cur_height = gui.char_height;
1072 		cur_width = (gui.char_width * shape_table[idx].percentage
1073 								  + 99) / 100;
1074 	    }
1075 	    else
1076 	    {
1077 		cur_height = (gui.char_height * shape_table[idx].percentage
1078 								  + 99) / 100;
1079 		cur_width = gui.char_width;
1080 	    }
1081 #ifdef FEAT_MBYTE
1082 	    if (has_mbyte && (*mb_off2cells)(LineOffset[gui.row] + gui.col) > 1)
1083 	    {
1084 		/* Double wide character. */
1085 		if (shape_table[idx].shape != SHAPE_VER)
1086 		    cur_width += gui.char_width;
1087 # ifdef FEAT_RIGHTLEFT
1088 		if (CURSOR_BAR_RIGHT)
1089 		{
1090 		    /* gui.col points to the left halve of the character but
1091 		     * the vertical line needs to be on the right halve.
1092 		     * A double-wide horizontal line is also drawn from the
1093 		     * right halve in gui_mch_draw_part_cursor(). */
1094 		    col_off = TRUE;
1095 		    ++gui.col;
1096 		}
1097 # endif
1098 	    }
1099 #endif
1100 	    gui_mch_draw_part_cursor(cur_width, cur_height, cbg);
1101 #if defined(FEAT_MBYTE) && defined(FEAT_RIGHTLEFT)
1102 	    if (col_off)
1103 		--gui.col;
1104 #endif
1105 
1106 #ifndef FEAT_GUI_MSWIN	    /* doesn't seem to work for MSWindows */
1107 	    gui.highlight_mask = ScreenAttrs[LineOffset[gui.row] + gui.col];
1108 	    (void)gui_screenchar(LineOffset[gui.row] + gui.col,
1109 		    GUI_MON_TRS_CURSOR | GUI_MON_NOCLEAR,
1110 		    (guicolor_T)0, (guicolor_T)0, 0);
1111 #endif
1112 	}
1113 	gui.highlight_mask = old_hl_mask;
1114     }
1115 }
1116 
1117 #if defined(FEAT_MENU) || defined(PROTO)
1118     void
1119 gui_position_menu()
1120 {
1121 # if !defined(FEAT_GUI_GTK) && !defined(FEAT_GUI_MOTIF)
1122     if (gui.menu_is_active && gui.in_use)
1123 	gui_mch_set_menu_pos(0, 0, gui.menu_width, gui.menu_height);
1124 # endif
1125 }
1126 #endif
1127 
1128 /*
1129  * Position the various GUI components (text area, menu).  The vertical
1130  * scrollbars are NOT handled here.  See gui_update_scrollbars().
1131  */
1132 /*ARGSUSED*/
1133     static void
1134 gui_position_components(total_width)
1135     int	    total_width;
1136 {
1137     int	    text_area_x;
1138     int	    text_area_y;
1139     int	    text_area_width;
1140     int	    text_area_height;
1141 
1142     /* avoid that moving components around generates events */
1143     ++hold_gui_events;
1144 
1145     text_area_x = 0;
1146     if (gui.which_scrollbars[SBAR_LEFT])
1147 	text_area_x += gui.scrollbar_width;
1148 
1149     text_area_y = 0;
1150 #if defined(FEAT_MENU) && !(defined(FEAT_GUI_GTK) || defined(FEAT_GUI_PHOTON))
1151     gui.menu_width = total_width;
1152     if (gui.menu_is_active)
1153 	text_area_y += gui.menu_height;
1154 #endif
1155 #if defined(FEAT_TOOLBAR) && defined(FEAT_GUI_MSWIN)
1156     if (vim_strchr(p_go, GO_TOOLBAR) != NULL)
1157 	text_area_y = TOOLBAR_BUTTON_HEIGHT + TOOLBAR_BORDER_HEIGHT;
1158 #endif
1159 
1160 # if defined(FEAT_GUI_TABLINE) && (defined(FEAT_GUI_MSWIN) \
1161 	|| defined(FEAT_GUI_MOTIF))
1162     if (gui_has_tabline())
1163 	text_area_y += gui.tabline_height;
1164 #endif
1165 
1166 #if defined(FEAT_TOOLBAR) && (defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA))
1167     if (vim_strchr(p_go, GO_TOOLBAR) != NULL)
1168     {
1169 # ifdef FEAT_GUI_ATHENA
1170 	gui_mch_set_toolbar_pos(0, text_area_y,
1171 				gui.menu_width, gui.toolbar_height);
1172 # endif
1173 	text_area_y += gui.toolbar_height;
1174     }
1175 #endif
1176 
1177     text_area_width = gui.num_cols * gui.char_width + gui.border_offset * 2;
1178     text_area_height = gui.num_rows * gui.char_height + gui.border_offset * 2;
1179 
1180     gui_mch_set_text_area_pos(text_area_x,
1181 			      text_area_y,
1182 			      text_area_width,
1183 			      text_area_height
1184 #if defined(FEAT_XIM) && !defined(HAVE_GTK2)
1185 				  + xim_get_status_area_height()
1186 #endif
1187 			      );
1188 #ifdef FEAT_MENU
1189     gui_position_menu();
1190 #endif
1191     if (gui.which_scrollbars[SBAR_BOTTOM])
1192 	gui_mch_set_scrollbar_pos(&gui.bottom_sbar,
1193 				  text_area_x,
1194 				  text_area_y + text_area_height,
1195 				  text_area_width,
1196 				  gui.scrollbar_height);
1197     gui.left_sbar_x = 0;
1198     gui.right_sbar_x = text_area_x + text_area_width;
1199 
1200     --hold_gui_events;
1201 }
1202 
1203 /*
1204  * Get the width of the widgets and decorations to the side of the text area.
1205  */
1206     int
1207 gui_get_base_width()
1208 {
1209     int	    base_width;
1210 
1211     base_width = 2 * gui.border_offset;
1212     if (gui.which_scrollbars[SBAR_LEFT])
1213 	base_width += gui.scrollbar_width;
1214     if (gui.which_scrollbars[SBAR_RIGHT])
1215 	base_width += gui.scrollbar_width;
1216     return base_width;
1217 }
1218 
1219 /*
1220  * Get the height of the widgets and decorations above and below the text area.
1221  */
1222     int
1223 gui_get_base_height()
1224 {
1225     int	    base_height;
1226 
1227     base_height = 2 * gui.border_offset;
1228     if (gui.which_scrollbars[SBAR_BOTTOM])
1229 	base_height += gui.scrollbar_height;
1230 #ifdef FEAT_GUI_GTK
1231     /* We can't take the sizes properly into account until anything is
1232      * realized.  Therefore we recalculate all the values here just before
1233      * setting the size. (--mdcki) */
1234 #else
1235 # ifdef FEAT_MENU
1236     if (gui.menu_is_active)
1237 	base_height += gui.menu_height;
1238 # endif
1239 # ifdef FEAT_TOOLBAR
1240     if (vim_strchr(p_go, GO_TOOLBAR) != NULL)
1241 #  if defined(FEAT_GUI_MSWIN) && defined(FEAT_TOOLBAR)
1242 	base_height += (TOOLBAR_BUTTON_HEIGHT + TOOLBAR_BORDER_HEIGHT);
1243 #  else
1244 	base_height += gui.toolbar_height;
1245 #  endif
1246 # endif
1247 # if defined(FEAT_GUI_TABLINE) && (defined(FEAT_GUI_MSWIN) \
1248 	|| defined(FEAT_GUI_MOTIF))
1249     if (gui_has_tabline())
1250 	base_height += gui.tabline_height;
1251 # endif
1252 # ifdef FEAT_FOOTER
1253     if (vim_strchr(p_go, GO_FOOTER) != NULL)
1254 	base_height += gui.footer_height;
1255 # endif
1256 # if defined(FEAT_GUI_MOTIF) && defined(FEAT_MENU)
1257     base_height += gui_mch_text_area_extra_height();
1258 # endif
1259 #endif
1260     return base_height;
1261 }
1262 
1263 /*
1264  * Should be called after the GUI shell has been resized.  Its arguments are
1265  * the new width and height of the shell in pixels.
1266  */
1267     void
1268 gui_resize_shell(pixel_width, pixel_height)
1269     int		pixel_width;
1270     int		pixel_height;
1271 {
1272     static int	busy = FALSE;
1273 
1274     if (!gui.shell_created)	    /* ignore when still initializing */
1275 	return;
1276 
1277     /*
1278      * Can't resize the screen while it is being redrawn.  Remember the new
1279      * size and handle it later.
1280      */
1281     if (updating_screen || busy)
1282     {
1283 	new_pixel_width = pixel_width;
1284 	new_pixel_height = pixel_height;
1285 	return;
1286     }
1287 
1288 again:
1289     busy = TRUE;
1290 
1291     /* Flush pending output before redrawing */
1292     out_flush();
1293 
1294     gui.num_cols = (pixel_width - gui_get_base_width()) / gui.char_width;
1295     gui.num_rows = (pixel_height - gui_get_base_height()
1296 #if !defined(FEAT_GUI_PHOTON) && !defined(FEAT_GUI_MSWIN)
1297 				    + (gui.char_height / 2)
1298 #endif
1299 					) / gui.char_height;
1300 
1301     gui_position_components(pixel_width);
1302 
1303     gui_reset_scroll_region();
1304     /*
1305      * At the "more" and ":confirm" prompt there is no redraw, put the cursor
1306      * at the last line here (why does it have to be one row too low?).
1307      */
1308     if (State == ASKMORE || State == CONFIRM)
1309 	gui.row = gui.num_rows;
1310 
1311     /* Only comparing Rows and Columns may be sufficient, but let's stay on
1312      * the safe side. */
1313     if (gui.num_rows != screen_Rows || gui.num_cols != screen_Columns
1314 	    || gui.num_rows != Rows || gui.num_cols != Columns)
1315 	shell_resized();
1316 
1317     gui_update_scrollbars(TRUE);
1318     gui_update_cursor(FALSE, TRUE);
1319 #if defined(FEAT_XIM) && !defined(HAVE_GTK2)
1320     xim_set_status_area();
1321 #endif
1322 
1323     busy = FALSE;
1324 
1325     /*
1326      * We could have been called again while redrawing the screen.
1327      * Need to do it all again with the latest size then.
1328      */
1329     if (new_pixel_height)
1330     {
1331 	pixel_width = new_pixel_width;
1332 	pixel_height = new_pixel_height;
1333 	new_pixel_width = 0;
1334 	new_pixel_height = 0;
1335 	goto again;
1336     }
1337 }
1338 
1339 /*
1340  * Check if gui_resize_shell() must be called.
1341  */
1342     void
1343 gui_may_resize_shell()
1344 {
1345     int		h, w;
1346 
1347     if (new_pixel_height)
1348     {
1349 	/* careful: gui_resize_shell() may postpone the resize again if we
1350 	 * were called indirectly by it */
1351 	w = new_pixel_width;
1352 	h = new_pixel_height;
1353 	new_pixel_width = 0;
1354 	new_pixel_height = 0;
1355 	gui_resize_shell(w, h);
1356     }
1357 }
1358 
1359     int
1360 gui_get_shellsize()
1361 {
1362     Rows = gui.num_rows;
1363     Columns = gui.num_cols;
1364     return OK;
1365 }
1366 
1367 /*
1368  * Set the size of the Vim shell according to Rows and Columns.
1369  * If "fit_to_display" is TRUE then the size may be reduced to fit the window
1370  * on the screen.
1371  */
1372 /*ARGSUSED*/
1373     void
1374 gui_set_shellsize(mustset, fit_to_display, direction)
1375     int		mustset;		/* set by the user */
1376     int		fit_to_display;
1377     int		direction;		/* RESIZE_HOR, RESIZE_VER */
1378 {
1379     int		base_width;
1380     int		base_height;
1381     int		width;
1382     int		height;
1383     int		min_width;
1384     int		min_height;
1385     int		screen_w;
1386     int		screen_h;
1387 
1388     if (!gui.shell_created)
1389 	return;
1390 
1391 #ifdef MSWIN
1392     /* If not setting to a user specified size and maximized, calculate the
1393      * number of characters that fit in the maximized window. */
1394     if (!mustset && gui_mch_maximized())
1395     {
1396 	gui_mch_newfont();
1397 	return;
1398     }
1399 #endif
1400 
1401     base_width = gui_get_base_width();
1402     base_height = gui_get_base_height();
1403 #ifdef USE_SUN_WORKSHOP
1404     if (!mustset && usingSunWorkShop
1405 				&& workshop_get_width_height(&width, &height))
1406     {
1407 	Columns = (width - base_width + gui.char_width - 1) / gui.char_width;
1408 	Rows = (height - base_height + gui.char_height - 1) / gui.char_height;
1409     }
1410     else
1411 #endif
1412     {
1413 	width = Columns * gui.char_width + base_width;
1414 	height = Rows * gui.char_height + base_height;
1415     }
1416 
1417     if (fit_to_display)
1418     {
1419 	gui_mch_get_screen_dimensions(&screen_w, &screen_h);
1420 	if ((direction & RESIZE_HOR) && width > screen_w)
1421 	{
1422 	    Columns = (screen_w - base_width) / gui.char_width;
1423 	    if (Columns < MIN_COLUMNS)
1424 		Columns = MIN_COLUMNS;
1425 	    width = Columns * gui.char_width + base_width;
1426 	}
1427 	if ((direction & RESIZE_VERT) && height > screen_h)
1428 	{
1429 	    Rows = (screen_h - base_height) / gui.char_height;
1430 	    check_shellsize();
1431 	    height = Rows * gui.char_height + base_height;
1432 	}
1433     }
1434     gui.num_cols = Columns;
1435     gui.num_rows = Rows;
1436 
1437     min_width = base_width + MIN_COLUMNS * gui.char_width;
1438     min_height = base_height + MIN_LINES * gui.char_height;
1439 # ifdef FEAT_WINDOWS
1440     min_height += tabline_height() * gui.char_height;
1441 # endif
1442 
1443     gui_mch_set_shellsize(width, height, min_width, min_height,
1444 					  base_width, base_height, direction);
1445     if (fit_to_display)
1446     {
1447 	int	    x, y;
1448 
1449 	/* Some window managers put the Vim window left of/above the screen. */
1450 	gui_mch_update();
1451 	if (gui_mch_get_winpos(&x, &y) == OK && (x < 0 || y < 0))
1452 	    gui_mch_set_winpos(x < 0 ? 0 : x, y < 0 ? 0 : y);
1453     }
1454 
1455     gui_position_components(width);
1456     gui_update_scrollbars(TRUE);
1457     gui_reset_scroll_region();
1458 }
1459 
1460 /*
1461  * Called when Rows and/or Columns has changed.
1462  */
1463     void
1464 gui_new_shellsize()
1465 {
1466     gui_reset_scroll_region();
1467 }
1468 
1469 /*
1470  * Make scroll region cover whole screen.
1471  */
1472     void
1473 gui_reset_scroll_region()
1474 {
1475     gui.scroll_region_top = 0;
1476     gui.scroll_region_bot = gui.num_rows - 1;
1477     gui.scroll_region_left = 0;
1478     gui.scroll_region_right = gui.num_cols - 1;
1479 }
1480 
1481     void
1482 gui_start_highlight(mask)
1483     int	    mask;
1484 {
1485     if (mask > HL_ALL)		    /* highlight code */
1486 	gui.highlight_mask = mask;
1487     else			    /* mask */
1488 	gui.highlight_mask |= mask;
1489 }
1490 
1491     void
1492 gui_stop_highlight(mask)
1493     int	    mask;
1494 {
1495     if (mask > HL_ALL)		    /* highlight code */
1496 	gui.highlight_mask = HL_NORMAL;
1497     else			    /* mask */
1498 	gui.highlight_mask &= ~mask;
1499 }
1500 
1501 /*
1502  * Clear a rectangular region of the screen from text pos (row1, col1) to
1503  * (row2, col2) inclusive.
1504  */
1505     void
1506 gui_clear_block(row1, col1, row2, col2)
1507     int	    row1;
1508     int	    col1;
1509     int	    row2;
1510     int	    col2;
1511 {
1512     /* Clear the selection if we are about to write over it */
1513     clip_may_clear_selection(row1, row2);
1514 
1515     gui_mch_clear_block(row1, col1, row2, col2);
1516 
1517     /* Invalidate cursor if it was in this block */
1518     if (       gui.cursor_row >= row1 && gui.cursor_row <= row2
1519 	    && gui.cursor_col >= col1 && gui.cursor_col <= col2)
1520 	gui.cursor_is_valid = FALSE;
1521 }
1522 
1523 /*
1524  * Write code to update the cursor later.  This avoids the need to flush the
1525  * output buffer before calling gui_update_cursor().
1526  */
1527     void
1528 gui_update_cursor_later()
1529 {
1530     OUT_STR(IF_EB("\033|s", ESC_STR "|s"));
1531 }
1532 
1533     void
1534 gui_write(s, len)
1535     char_u	*s;
1536     int		len;
1537 {
1538     char_u	*p;
1539     int		arg1 = 0, arg2 = 0;
1540     /* this doesn't make sense, disabled until someone can explain why it
1541      * would be needed */
1542 #if 0 && (defined(RISCOS) || defined(WIN16))
1543     int		force_cursor = TRUE;	/* JK230798, stop Vim being smart or
1544 					   our redraw speed will suffer */
1545 #else
1546     int		force_cursor = FALSE;	/* force cursor update */
1547 #endif
1548     int		force_scrollbar = FALSE;
1549     static win_T	*old_curwin = NULL;
1550 
1551 /* #define DEBUG_GUI_WRITE */
1552 #ifdef DEBUG_GUI_WRITE
1553     {
1554 	int i;
1555 	char_u *str;
1556 
1557 	printf("gui_write(%d):\n    ", len);
1558 	for (i = 0; i < len; i++)
1559 	    if (s[i] == ESC)
1560 	    {
1561 		if (i != 0)
1562 		    printf("\n    ");
1563 		printf("<ESC>");
1564 	    }
1565 	    else
1566 	    {
1567 		str = transchar_byte(s[i]);
1568 		if (str[0] && str[1])
1569 		    printf("<%s>", (char *)str);
1570 		else
1571 		    printf("%s", (char *)str);
1572 	    }
1573 	printf("\n");
1574     }
1575 #endif
1576     while (len)
1577     {
1578 	if (s[0] == ESC && s[1] == '|')
1579 	{
1580 	    p = s + 2;
1581 	    if (VIM_ISDIGIT(*p))
1582 	    {
1583 		arg1 = getdigits(&p);
1584 		if (p > s + len)
1585 		    break;
1586 		if (*p == ';')
1587 		{
1588 		    ++p;
1589 		    arg2 = getdigits(&p);
1590 		    if (p > s + len)
1591 			break;
1592 		}
1593 	    }
1594 	    switch (*p)
1595 	    {
1596 		case 'C':	/* Clear screen */
1597 		    clip_scroll_selection(9999);
1598 		    gui_mch_clear_all();
1599 		    gui.cursor_is_valid = FALSE;
1600 		    force_scrollbar = TRUE;
1601 		    break;
1602 		case 'M':	/* Move cursor */
1603 		    gui_set_cursor(arg1, arg2);
1604 		    break;
1605 		case 's':	/* force cursor (shape) update */
1606 		    force_cursor = TRUE;
1607 		    break;
1608 		case 'R':	/* Set scroll region */
1609 		    if (arg1 < arg2)
1610 		    {
1611 			gui.scroll_region_top = arg1;
1612 			gui.scroll_region_bot = arg2;
1613 		    }
1614 		    else
1615 		    {
1616 			gui.scroll_region_top = arg2;
1617 			gui.scroll_region_bot = arg1;
1618 		    }
1619 		    break;
1620 #ifdef FEAT_VERTSPLIT
1621 		case 'V':	/* Set vertical scroll region */
1622 		    if (arg1 < arg2)
1623 		    {
1624 			gui.scroll_region_left = arg1;
1625 			gui.scroll_region_right = arg2;
1626 		    }
1627 		    else
1628 		    {
1629 			gui.scroll_region_left = arg2;
1630 			gui.scroll_region_right = arg1;
1631 		    }
1632 		    break;
1633 #endif
1634 		case 'd':	/* Delete line */
1635 		    gui_delete_lines(gui.row, 1);
1636 		    break;
1637 		case 'D':	/* Delete lines */
1638 		    gui_delete_lines(gui.row, arg1);
1639 		    break;
1640 		case 'i':	/* Insert line */
1641 		    gui_insert_lines(gui.row, 1);
1642 		    break;
1643 		case 'I':	/* Insert lines */
1644 		    gui_insert_lines(gui.row, arg1);
1645 		    break;
1646 		case '$':	/* Clear to end-of-line */
1647 		    gui_clear_block(gui.row, gui.col, gui.row,
1648 							    (int)Columns - 1);
1649 		    break;
1650 		case 'h':	/* Turn on highlighting */
1651 		    gui_start_highlight(arg1);
1652 		    break;
1653 		case 'H':	/* Turn off highlighting */
1654 		    gui_stop_highlight(arg1);
1655 		    break;
1656 		case 'f':	/* flash the window (visual bell) */
1657 		    gui_mch_flash(arg1 == 0 ? 20 : arg1);
1658 		    break;
1659 		default:
1660 		    p = s + 1;	/* Skip the ESC */
1661 		    break;
1662 	    }
1663 	    len -= (int)(++p - s);
1664 	    s = p;
1665 	}
1666 	else if (
1667 #ifdef EBCDIC
1668 		CtrlChar(s[0]) != 0	/* Ctrl character */
1669 #else
1670 		s[0] < 0x20		/* Ctrl character */
1671 #endif
1672 #ifdef FEAT_SIGN_ICONS
1673 		&& s[0] != SIGN_BYTE
1674 # ifdef FEAT_NETBEANS_INTG
1675 		&& s[0] != MULTISIGN_BYTE
1676 # endif
1677 #endif
1678 		)
1679 	{
1680 	    if (s[0] == '\n')		/* NL */
1681 	    {
1682 		gui.col = 0;
1683 		if (gui.row < gui.scroll_region_bot)
1684 		    gui.row++;
1685 		else
1686 		    gui_delete_lines(gui.scroll_region_top, 1);
1687 	    }
1688 	    else if (s[0] == '\r')	/* CR */
1689 	    {
1690 		gui.col = 0;
1691 	    }
1692 	    else if (s[0] == '\b')	/* Backspace */
1693 	    {
1694 		if (gui.col)
1695 		    --gui.col;
1696 	    }
1697 	    else if (s[0] == Ctrl_L)	/* cursor-right */
1698 	    {
1699 		++gui.col;
1700 	    }
1701 	    else if (s[0] == Ctrl_G)	/* Beep */
1702 	    {
1703 		gui_mch_beep();
1704 	    }
1705 	    /* Other Ctrl character: shouldn't happen! */
1706 
1707 	    --len;	/* Skip this char */
1708 	    ++s;
1709 	}
1710 	else
1711 	{
1712 	    p = s;
1713 	    while (len > 0 && (
1714 #ifdef EBCDIC
1715 			CtrlChar(*p) == 0
1716 #else
1717 			*p >= 0x20
1718 #endif
1719 #ifdef FEAT_SIGN_ICONS
1720 			|| *p == SIGN_BYTE
1721 # ifdef FEAT_NETBEANS_INTG
1722 			|| *p == MULTISIGN_BYTE
1723 # endif
1724 #endif
1725 			))
1726 	    {
1727 		len--;
1728 		p++;
1729 	    }
1730 	    gui_outstr(s, (int)(p - s));
1731 	    s = p;
1732 	}
1733     }
1734 
1735     /* Postponed update of the cursor (won't work if "can_update_cursor" isn't
1736      * set). */
1737     if (force_cursor)
1738 	gui_update_cursor(TRUE, TRUE);
1739 
1740     /* When switching to another window the dragging must have stopped.
1741      * Required for GTK, dragged_sb isn't reset. */
1742     if (old_curwin != curwin)
1743 	gui.dragged_sb = SBAR_NONE;
1744 
1745     /* Update the scrollbars after clearing the screen or when switched
1746      * to another window.
1747      * Update the horizontal scrollbar always, it's difficult to check all
1748      * situations where it might change. */
1749     if (force_scrollbar || old_curwin != curwin)
1750 	gui_update_scrollbars(force_scrollbar);
1751     else
1752 	gui_update_horiz_scrollbar(FALSE);
1753     old_curwin = curwin;
1754 
1755     /*
1756      * We need to make sure this is cleared since Athena doesn't tell us when
1757      * he is done dragging.  Do the same for GTK.
1758      */
1759 #if defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_GTK)
1760     gui.dragged_sb = SBAR_NONE;
1761 #endif
1762 
1763     gui_mch_flush();		    /* In case vim decides to take a nap */
1764 }
1765 
1766 /*
1767  * When ScreenLines[] is invalid, updating the cursor should not be done, it
1768  * produces wrong results.  Call gui_dont_update_cursor() before that code and
1769  * gui_can_update_cursor() afterwards.
1770  */
1771     void
1772 gui_dont_update_cursor()
1773 {
1774     if (gui.in_use)
1775     {
1776 	/* Undraw the cursor now, we probably can't do it after the change. */
1777 	gui_undraw_cursor();
1778 	can_update_cursor = FALSE;
1779     }
1780 }
1781 
1782     void
1783 gui_can_update_cursor()
1784 {
1785     can_update_cursor = TRUE;
1786     /* No need to update the cursor right now, there is always more output
1787      * after scrolling. */
1788 }
1789 
1790     static void
1791 gui_outstr(s, len)
1792     char_u  *s;
1793     int	    len;
1794 {
1795     int	    this_len;
1796 #ifdef FEAT_MBYTE
1797     int	    cells;
1798 #endif
1799 
1800     if (len == 0)
1801 	return;
1802 
1803     if (len < 0)
1804 	len = (int)STRLEN(s);
1805 
1806     while (len > 0)
1807     {
1808 #ifdef FEAT_MBYTE
1809 	if (has_mbyte)
1810 	{
1811 	    /* Find out how many chars fit in the current line. */
1812 	    cells = 0;
1813 	    for (this_len = 0; this_len < len; )
1814 	    {
1815 		cells += (*mb_ptr2cells)(s + this_len);
1816 		if (gui.col + cells > Columns)
1817 		    break;
1818 		this_len += (*mb_ptr2len)(s + this_len);
1819 	    }
1820 	    if (this_len > len)
1821 		this_len = len;	    /* don't include following composing char */
1822 	}
1823 	else
1824 #endif
1825 	    if (gui.col + len > Columns)
1826 	    this_len = Columns - gui.col;
1827 	else
1828 	    this_len = len;
1829 
1830 	(void)gui_outstr_nowrap(s, this_len,
1831 					  0, (guicolor_T)0, (guicolor_T)0, 0);
1832 	s += this_len;
1833 	len -= this_len;
1834 #ifdef FEAT_MBYTE
1835 	/* fill up for a double-width char that doesn't fit. */
1836 	if (len > 0 && gui.col < Columns)
1837 	    (void)gui_outstr_nowrap((char_u *)" ", 1,
1838 					  0, (guicolor_T)0, (guicolor_T)0, 0);
1839 #endif
1840 	/* The cursor may wrap to the next line. */
1841 	if (gui.col >= Columns)
1842 	{
1843 	    gui.col = 0;
1844 	    gui.row++;
1845 	}
1846     }
1847 }
1848 
1849 /*
1850  * Output one character (may be one or two display cells).
1851  * Caller must check for valid "off".
1852  * Returns FAIL or OK, just like gui_outstr_nowrap().
1853  */
1854     static int
1855 gui_screenchar(off, flags, fg, bg, back)
1856     int		off;	    /* Offset from start of screen */
1857     int		flags;
1858     guicolor_T	fg, bg;	    /* colors for cursor */
1859     int		back;	    /* backup this many chars when using bold trick */
1860 {
1861 #ifdef FEAT_MBYTE
1862     char_u	buf[MB_MAXBYTES + 1];
1863 
1864     /* Don't draw right halve of a double-width UTF-8 char. "cannot happen" */
1865     if (enc_utf8 && ScreenLines[off] == 0)
1866 	return OK;
1867 
1868     if (enc_utf8 && ScreenLinesUC[off] != 0)
1869 	/* Draw UTF-8 multi-byte character. */
1870 	return gui_outstr_nowrap(buf, utfc_char2bytes(off, buf),
1871 							 flags, fg, bg, back);
1872 
1873     if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e)
1874     {
1875 	buf[0] = ScreenLines[off];
1876 	buf[1] = ScreenLines2[off];
1877 	return gui_outstr_nowrap(buf, 2, flags, fg, bg, back);
1878     }
1879 
1880     /* Draw non-multi-byte character or DBCS character. */
1881     return gui_outstr_nowrap(ScreenLines + off,
1882 	    enc_dbcs ? (*mb_ptr2len)(ScreenLines + off) : 1,
1883 							 flags, fg, bg, back);
1884 #else
1885     return gui_outstr_nowrap(ScreenLines + off, 1, flags, fg, bg, back);
1886 #endif
1887 }
1888 
1889 #ifdef HAVE_GTK2
1890 /*
1891  * Output the string at the given screen position.  This is used in place
1892  * of gui_screenchar() where possible because Pango needs as much context
1893  * as possible to work nicely.  It's a lot faster as well.
1894  */
1895     static int
1896 gui_screenstr(off, len, flags, fg, bg, back)
1897     int		off;	    /* Offset from start of screen */
1898     int		len;	    /* string length in screen cells */
1899     int		flags;
1900     guicolor_T	fg, bg;	    /* colors for cursor */
1901     int		back;	    /* backup this many chars when using bold trick */
1902 {
1903     char_u  *buf;
1904     int	    outlen = 0;
1905     int	    i;
1906     int	    retval;
1907 
1908     if (len <= 0) /* "cannot happen"? */
1909 	return OK;
1910 
1911     if (enc_utf8)
1912     {
1913 	buf = alloc((unsigned)(len * MB_MAXBYTES + 1));
1914 	if (buf == NULL)
1915 	    return OK; /* not much we could do here... */
1916 
1917 	for (i = off; i < off + len; ++i)
1918 	{
1919 	    if (ScreenLines[i] == 0)
1920 		continue; /* skip second half of double-width char */
1921 
1922 	    if (ScreenLinesUC[i] == 0)
1923 		buf[outlen++] = ScreenLines[i];
1924 	    else
1925 		outlen += utfc_char2bytes(i, buf + outlen);
1926 	}
1927 
1928 	buf[outlen] = NUL; /* only to aid debugging */
1929 	retval = gui_outstr_nowrap(buf, outlen, flags, fg, bg, back);
1930 	vim_free(buf);
1931 
1932 	return retval;
1933     }
1934     else if (enc_dbcs == DBCS_JPNU)
1935     {
1936 	buf = alloc((unsigned)(len * 2 + 1));
1937 	if (buf == NULL)
1938 	    return OK; /* not much we could do here... */
1939 
1940 	for (i = off; i < off + len; ++i)
1941 	{
1942 	    buf[outlen++] = ScreenLines[i];
1943 
1944 	    /* handle double-byte single-width char */
1945 	    if (ScreenLines[i] == 0x8e)
1946 		buf[outlen++] = ScreenLines2[i];
1947 	    else if (MB_BYTE2LEN(ScreenLines[i]) == 2)
1948 		buf[outlen++] = ScreenLines[++i];
1949 	}
1950 
1951 	buf[outlen] = NUL; /* only to aid debugging */
1952 	retval = gui_outstr_nowrap(buf, outlen, flags, fg, bg, back);
1953 	vim_free(buf);
1954 
1955 	return retval;
1956     }
1957     else
1958     {
1959 	return gui_outstr_nowrap(&ScreenLines[off], len,
1960 				 flags, fg, bg, back);
1961     }
1962 }
1963 #endif /* HAVE_GTK2 */
1964 
1965 /*
1966  * Output the given string at the current cursor position.  If the string is
1967  * too long to fit on the line, then it is truncated.
1968  * "flags":
1969  * GUI_MON_IS_CURSOR should only be used when this function is being called to
1970  * actually draw (an inverted) cursor.
1971  * GUI_MON_TRS_CURSOR is used to draw the cursor text with a transparant
1972  * background.
1973  * GUI_MON_NOCLEAR is used to avoid clearing the selection when drawing over
1974  * it.
1975  * Returns OK, unless "back" is non-zero and using the bold trick, then return
1976  * FAIL (the caller should start drawing "back" chars back).
1977  */
1978     int
1979 gui_outstr_nowrap(s, len, flags, fg, bg, back)
1980     char_u	*s;
1981     int		len;
1982     int		flags;
1983     guicolor_T	fg, bg;	    /* colors for cursor */
1984     int		back;	    /* backup this many chars when using bold trick */
1985 {
1986     long_u	highlight_mask;
1987     long_u	hl_mask_todo;
1988     guicolor_T	fg_color;
1989     guicolor_T	bg_color;
1990     guicolor_T	sp_color;
1991 #if !defined(MSWIN16_FASTTEXT) && !defined(HAVE_GTK2)
1992     GuiFont	font = NOFONT;
1993 # ifdef FEAT_XFONTSET
1994     GuiFontset	fontset = NOFONTSET;
1995 # endif
1996 #endif
1997     attrentry_T	*aep = NULL;
1998     int		draw_flags;
1999     int		col = gui.col;
2000 #ifdef FEAT_SIGN_ICONS
2001     int		draw_sign = FALSE;
2002 # ifdef FEAT_NETBEANS_INTG
2003     int		multi_sign = FALSE;
2004 # endif
2005 #endif
2006 
2007     if (len < 0)
2008 	len = (int)STRLEN(s);
2009     if (len == 0)
2010 	return OK;
2011 
2012 #ifdef FEAT_SIGN_ICONS
2013     if (*s == SIGN_BYTE
2014 # ifdef FEAT_NETBEANS_INTG
2015 	  || *s == MULTISIGN_BYTE
2016 # endif
2017     )
2018     {
2019 # ifdef FEAT_NETBEANS_INTG
2020 	if (*s == MULTISIGN_BYTE)
2021 	    multi_sign = TRUE;
2022 # endif
2023 	/* draw spaces instead */
2024 	s = (char_u *)"  ";
2025 	if (len == 1 && col > 0)
2026 	    --col;
2027 	len = 2;
2028 	draw_sign = TRUE;
2029 	highlight_mask = 0;
2030     }
2031     else
2032 #endif
2033     if (gui.highlight_mask > HL_ALL)
2034     {
2035 	aep = syn_gui_attr2entry(gui.highlight_mask);
2036 	if (aep == NULL)	    /* highlighting not set */
2037 	    highlight_mask = 0;
2038 	else
2039 	    highlight_mask = aep->ae_attr;
2040     }
2041     else
2042 	highlight_mask = gui.highlight_mask;
2043     hl_mask_todo = highlight_mask;
2044 
2045 #if !defined(MSWIN16_FASTTEXT) && !defined(HAVE_GTK2)
2046     /* Set the font */
2047     if (aep != NULL && aep->ae_u.gui.font != NOFONT)
2048 	font = aep->ae_u.gui.font;
2049 # ifdef FEAT_XFONTSET
2050     else if (aep != NULL && aep->ae_u.gui.fontset != NOFONTSET)
2051 	fontset = aep->ae_u.gui.fontset;
2052 # endif
2053     else
2054     {
2055 # ifdef FEAT_XFONTSET
2056 	if (gui.fontset != NOFONTSET)
2057 	    fontset = gui.fontset;
2058 	else
2059 # endif
2060 	    if (hl_mask_todo & (HL_BOLD | HL_STANDOUT))
2061 	{
2062 	    if ((hl_mask_todo & HL_ITALIC) && gui.boldital_font != NOFONT)
2063 	    {
2064 		font = gui.boldital_font;
2065 		hl_mask_todo &= ~(HL_BOLD | HL_STANDOUT | HL_ITALIC);
2066 	    }
2067 	    else if (gui.bold_font != NOFONT)
2068 	    {
2069 		font = gui.bold_font;
2070 		hl_mask_todo &= ~(HL_BOLD | HL_STANDOUT);
2071 	    }
2072 	    else
2073 		font = gui.norm_font;
2074 	}
2075 	else if ((hl_mask_todo & HL_ITALIC) && gui.ital_font != NOFONT)
2076 	{
2077 	    font = gui.ital_font;
2078 	    hl_mask_todo &= ~HL_ITALIC;
2079 	}
2080 	else
2081 	    font = gui.norm_font;
2082     }
2083 # ifdef FEAT_XFONTSET
2084     if (fontset != NOFONTSET)
2085 	gui_mch_set_fontset(fontset);
2086     else
2087 # endif
2088 	gui_mch_set_font(font);
2089 #endif
2090 
2091     draw_flags = 0;
2092 
2093     /* Set the color */
2094     bg_color = gui.back_pixel;
2095     if ((flags & GUI_MON_IS_CURSOR) && gui.in_focus)
2096     {
2097 	draw_flags |= DRAW_CURSOR;
2098 	fg_color = fg;
2099 	bg_color = bg;
2100 	sp_color = fg;
2101     }
2102     else if (aep != NULL)
2103     {
2104 	fg_color = aep->ae_u.gui.fg_color;
2105 	if (fg_color == INVALCOLOR)
2106 	    fg_color = gui.norm_pixel;
2107 	bg_color = aep->ae_u.gui.bg_color;
2108 	if (bg_color == INVALCOLOR)
2109 	    bg_color = gui.back_pixel;
2110 	sp_color = aep->ae_u.gui.sp_color;
2111 	if (sp_color == INVALCOLOR)
2112 	    sp_color = fg_color;
2113     }
2114     else
2115     {
2116 	fg_color = gui.norm_pixel;
2117 	sp_color = fg_color;
2118     }
2119 
2120     if (highlight_mask & (HL_INVERSE | HL_STANDOUT))
2121     {
2122 #if defined(AMIGA) || defined(RISCOS)
2123 	gui_mch_set_colors(bg_color, fg_color);
2124 #else
2125 	gui_mch_set_fg_color(bg_color);
2126 	gui_mch_set_bg_color(fg_color);
2127 #endif
2128     }
2129     else
2130     {
2131 #if defined(AMIGA) || defined(RISCOS)
2132 	gui_mch_set_colors(fg_color, bg_color);
2133 #else
2134 	gui_mch_set_fg_color(fg_color);
2135 	gui_mch_set_bg_color(bg_color);
2136 #endif
2137     }
2138     gui_mch_set_sp_color(sp_color);
2139 
2140     /* Clear the selection if we are about to write over it */
2141     if (!(flags & GUI_MON_NOCLEAR))
2142 	clip_may_clear_selection(gui.row, gui.row);
2143 
2144 
2145 #ifndef MSWIN16_FASTTEXT
2146     /* If there's no bold font, then fake it */
2147     if (hl_mask_todo & (HL_BOLD | HL_STANDOUT))
2148 	draw_flags |= DRAW_BOLD;
2149 #endif
2150 
2151     /*
2152      * When drawing bold or italic characters the spill-over from the left
2153      * neighbor may be destroyed.  Let the caller backup to start redrawing
2154      * just after a blank.
2155      */
2156     if (back != 0 && ((draw_flags & DRAW_BOLD) || (highlight_mask & HL_ITALIC)))
2157 	return FAIL;
2158 
2159 #if defined(RISCOS) || defined(HAVE_GTK2)
2160     /* If there's no italic font, then fake it.
2161      * For GTK2, we don't need a different font for italic style. */
2162     if (hl_mask_todo & HL_ITALIC)
2163 	draw_flags |= DRAW_ITALIC;
2164 
2165     /* Do we underline the text? */
2166     if (hl_mask_todo & HL_UNDERLINE)
2167 	draw_flags |= DRAW_UNDERL;
2168 #else
2169     /* Do we underline the text? */
2170     if ((hl_mask_todo & HL_UNDERLINE)
2171 # ifndef MSWIN16_FASTTEXT
2172 	    || (hl_mask_todo & HL_ITALIC)
2173 # endif
2174        )
2175 	draw_flags |= DRAW_UNDERL;
2176 #endif
2177     /* Do we undercurl the text? */
2178     if (hl_mask_todo & HL_UNDERCURL)
2179 	draw_flags |= DRAW_UNDERC;
2180 
2181     /* Do we draw transparantly? */
2182     if (flags & GUI_MON_TRS_CURSOR)
2183 	draw_flags |= DRAW_TRANSP;
2184 
2185     /*
2186      * Draw the text.
2187      */
2188 #ifdef HAVE_GTK2
2189     /* The value returned is the length in display cells */
2190     len = gui_gtk2_draw_string(gui.row, col, s, len, draw_flags);
2191 #else
2192 # ifdef FEAT_MBYTE
2193     if (enc_utf8)
2194     {
2195 	int	start;		/* index of bytes to be drawn */
2196 	int	cells;		/* cellwidth of bytes to be drawn */
2197 	int	thislen;	/* length of bytes to be drawin */
2198 	int	cn;		/* cellwidth of current char */
2199 	int	i;		/* index of current char */
2200 	int	c;		/* current char value */
2201 	int	cl;		/* byte length of current char */
2202 	int	comping;	/* current char is composing */
2203 	int	scol = col;	/* screen column */
2204 	int	dowide;		/* use 'guifontwide' */
2205 
2206 	/* Break the string at a composing character, it has to be drawn on
2207 	 * top of the previous character. */
2208 	start = 0;
2209 	cells = 0;
2210 	for (i = 0; i < len; i += cl)
2211 	{
2212 	    c = utf_ptr2char(s + i);
2213 	    cn = utf_char2cells(c);
2214 	    if (cn > 1
2215 #  ifdef FEAT_XFONTSET
2216 		    && fontset == NOFONTSET
2217 #  endif
2218 		    && gui.wide_font != NOFONT)
2219 		dowide = TRUE;
2220 	    else
2221 		dowide = FALSE;
2222 	    comping = utf_iscomposing(c);
2223 	    if (!comping)	/* count cells from non-composing chars */
2224 		cells += cn;
2225 	    cl = utf_ptr2len(s + i);
2226 	    if (cl == 0)	/* hit end of string */
2227 		len = i + cl;	/* len must be wrong "cannot happen" */
2228 
2229 	    /* print the string so far if it's the last character or there is
2230 	     * a composing character. */
2231 	    if (i + cl >= len || (comping && i > start) || dowide
2232 #  if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
2233 		    || (cn > 1
2234 #   ifdef FEAT_XFONTSET
2235 			/* No fontset: At least draw char after wide char at
2236 			 * right position. */
2237 			&& fontset == NOFONTSET
2238 #   endif
2239 		       )
2240 #  endif
2241 	       )
2242 	    {
2243 		if (comping || dowide)
2244 		    thislen = i - start;
2245 		else
2246 		    thislen = i - start + cl;
2247 		if (thislen > 0)
2248 		{
2249 		    gui_mch_draw_string(gui.row, scol, s + start, thislen,
2250 								  draw_flags);
2251 		    start += thislen;
2252 		}
2253 		scol += cells;
2254 		cells = 0;
2255 		if (dowide)
2256 		{
2257 		    gui_mch_set_font(gui.wide_font);
2258 		    gui_mch_draw_string(gui.row, scol - cn,
2259 						   s + start, cl, draw_flags);
2260 		    gui_mch_set_font(font);
2261 		    start += cl;
2262 		}
2263 
2264 #  if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
2265 		/* No fontset: draw a space to fill the gap after a wide char
2266 		 * */
2267 		if (cn > 1 && (draw_flags & DRAW_TRANSP) == 0
2268 #   ifdef FEAT_XFONTSET
2269 			&& fontset == NOFONTSET
2270 #   endif
2271 			&& !dowide)
2272 		    gui_mch_draw_string(gui.row, scol - 1, (char_u *)" ",
2273 							       1, draw_flags);
2274 #  endif
2275 	    }
2276 	    /* Draw a composing char on top of the previous char. */
2277 	    if (comping)
2278 	    {
2279 #  if (defined(__APPLE_CC__) || defined(__MRC__)) && TARGET_API_MAC_CARBON
2280 		/* Carbon ATSUI autodraws composing char over previous char */
2281 		gui_mch_draw_string(gui.row, scol, s + i, cl,
2282 						    draw_flags | DRAW_TRANSP);
2283 #  else
2284 		gui_mch_draw_string(gui.row, scol - cn, s + i, cl,
2285 						    draw_flags | DRAW_TRANSP);
2286 #  endif
2287 		start = i + cl;
2288 	    }
2289 	}
2290 	/* The stuff below assumes "len" is the length in screen columns. */
2291 	len = scol - col;
2292     }
2293     else
2294 # endif
2295     {
2296 	gui_mch_draw_string(gui.row, col, s, len, draw_flags);
2297 # ifdef FEAT_MBYTE
2298 	if (enc_dbcs == DBCS_JPNU)
2299 	{
2300 	    int		clen = 0;
2301 	    int		i;
2302 
2303 	    /* Get the length in display cells, this can be different from the
2304 	     * number of bytes for "euc-jp". */
2305 	    for (i = 0; i < len; i += (*mb_ptr2len)(s + i))
2306 		clen += (*mb_ptr2cells)(s + i);
2307 	    len = clen;
2308 	}
2309 # endif
2310     }
2311 #endif /* !HAVE_GTK2 */
2312 
2313     if (!(flags & (GUI_MON_IS_CURSOR | GUI_MON_TRS_CURSOR)))
2314 	gui.col = col + len;
2315 
2316     /* May need to invert it when it's part of the selection. */
2317     if (flags & GUI_MON_NOCLEAR)
2318 	clip_may_redraw_selection(gui.row, col, len);
2319 
2320     if (!(flags & (GUI_MON_IS_CURSOR | GUI_MON_TRS_CURSOR)))
2321     {
2322 	/* Invalidate the old physical cursor position if we wrote over it */
2323 	if (gui.cursor_row == gui.row
2324 		&& gui.cursor_col >= col
2325 		&& gui.cursor_col < col + len)
2326 	    gui.cursor_is_valid = FALSE;
2327     }
2328 
2329 #ifdef FEAT_SIGN_ICONS
2330     if (draw_sign)
2331 	/* Draw the sign on top of the spaces. */
2332 	gui_mch_drawsign(gui.row, col, gui.highlight_mask);
2333 # ifdef FEAT_NETBEANS_INTG
2334     if (multi_sign)
2335 	netbeans_draw_multisign_indicator(gui.row);
2336 # endif
2337 #endif
2338 
2339     return OK;
2340 }
2341 
2342 /*
2343  * Un-draw the cursor.	Actually this just redraws the character at the given
2344  * position.  The character just before it too, for when it was in bold.
2345  */
2346     void
2347 gui_undraw_cursor()
2348 {
2349     if (gui.cursor_is_valid)
2350     {
2351 #ifdef FEAT_HANGULIN
2352 	if (composing_hangul
2353 		    && gui.col == gui.cursor_col && gui.row == gui.cursor_row)
2354 	    (void)gui_outstr_nowrap(composing_hangul_buffer, 2,
2355 		    GUI_MON_IS_CURSOR | GUI_MON_NOCLEAR,
2356 		    gui.norm_pixel, gui.back_pixel, 0);
2357 	else
2358 	{
2359 #endif
2360 	if (gui_redraw_block(gui.cursor_row, gui.cursor_col,
2361 			      gui.cursor_row, gui.cursor_col, GUI_MON_NOCLEAR)
2362 		&& gui.cursor_col > 0)
2363 	    (void)gui_redraw_block(gui.cursor_row, gui.cursor_col - 1,
2364 			 gui.cursor_row, gui.cursor_col - 1, GUI_MON_NOCLEAR);
2365 #ifdef FEAT_HANGULIN
2366 	    if (composing_hangul)
2367 		(void)gui_redraw_block(gui.cursor_row, gui.cursor_col + 1,
2368 			gui.cursor_row, gui.cursor_col + 1, GUI_MON_NOCLEAR);
2369 	}
2370 #endif
2371 	/* Cursor_is_valid is reset when the cursor is undrawn, also reset it
2372 	 * here in case it wasn't needed to undraw it. */
2373 	gui.cursor_is_valid = FALSE;
2374     }
2375 }
2376 
2377     void
2378 gui_redraw(x, y, w, h)
2379     int		x;
2380     int		y;
2381     int		w;
2382     int		h;
2383 {
2384     int		row1, col1, row2, col2;
2385 
2386     row1 = Y_2_ROW(y);
2387     col1 = X_2_COL(x);
2388     row2 = Y_2_ROW(y + h - 1);
2389     col2 = X_2_COL(x + w - 1);
2390 
2391     (void)gui_redraw_block(row1, col1, row2, col2, GUI_MON_NOCLEAR);
2392 
2393     /*
2394      * We may need to redraw the cursor, but don't take it upon us to change
2395      * its location after a scroll.
2396      * (maybe be more strict even and test col too?)
2397      * These things may be outside the update/clipping region and reality may
2398      * not reflect Vims internal ideas if these operations are clipped away.
2399      */
2400     if (gui.row == gui.cursor_row)
2401 	gui_update_cursor(TRUE, TRUE);
2402 }
2403 
2404 /*
2405  * Draw a rectangular block of characters, from row1 to row2 (inclusive) and
2406  * from col1 to col2 (inclusive).
2407  * Return TRUE when the character before the first drawn character has
2408  * different attributes (may have to be redrawn too).
2409  */
2410     int
2411 gui_redraw_block(row1, col1, row2, col2, flags)
2412     int		row1;
2413     int		col1;
2414     int		row2;
2415     int		col2;
2416     int		flags;	/* flags for gui_outstr_nowrap() */
2417 {
2418     int		old_row, old_col;
2419     long_u	old_hl_mask;
2420     int		off;
2421     sattr_T	first_attr;
2422     int		idx, len;
2423     int		back, nback;
2424     int		retval = FALSE;
2425 #ifdef FEAT_MBYTE
2426     int		orig_col1, orig_col2;
2427 #endif
2428 
2429     /* Don't try to update when ScreenLines is not valid */
2430     if (!screen_cleared || ScreenLines == NULL)
2431 	return retval;
2432 
2433     /* Don't try to draw outside the shell! */
2434     /* Check everything, strange values may be caused by a big border width */
2435     col1 = check_col(col1);
2436     col2 = check_col(col2);
2437     row1 = check_row(row1);
2438     row2 = check_row(row2);
2439 
2440     /* Remember where our cursor was */
2441     old_row = gui.row;
2442     old_col = gui.col;
2443     old_hl_mask = gui.highlight_mask;
2444 #ifdef FEAT_MBYTE
2445     orig_col1 = col1;
2446     orig_col2 = col2;
2447 #endif
2448 
2449     for (gui.row = row1; gui.row <= row2; gui.row++)
2450     {
2451 #ifdef FEAT_MBYTE
2452 	/* When only half of a double-wide character is in the block, include
2453 	 * the other half. */
2454 	col1 = orig_col1;
2455 	col2 = orig_col2;
2456 	off = LineOffset[gui.row];
2457 	if (enc_dbcs != 0)
2458 	{
2459 	    if (col1 > 0)
2460 		col1 -= dbcs_screen_head_off(ScreenLines + off,
2461 						    ScreenLines + off + col1);
2462 	    col2 += dbcs_screen_tail_off(ScreenLines + off,
2463 						    ScreenLines + off + col2);
2464 	}
2465 	else if (enc_utf8)
2466 	{
2467 	    if (ScreenLines[off + col1] == 0)
2468 		--col1;
2469 # ifdef HAVE_GTK2
2470 	    if (col2 + 1 < Columns && ScreenLines[off + col2 + 1] == 0)
2471 		++col2;
2472 # endif
2473 	}
2474 #endif
2475 	gui.col = col1;
2476 	off = LineOffset[gui.row] + gui.col;
2477 	len = col2 - col1 + 1;
2478 
2479 	/* Find how many chars back this highlighting starts, or where a space
2480 	 * is.  Needed for when the bold trick is used */
2481 	for (back = 0; back < col1; ++back)
2482 	    if (ScreenAttrs[off - 1 - back] != ScreenAttrs[off]
2483 		    || ScreenLines[off - 1 - back] == ' ')
2484 		break;
2485 	retval = (col1 > 0 && ScreenAttrs[off - 1] != 0 && back == 0
2486 					      && ScreenLines[off - 1] != ' ');
2487 
2488 	/* Break it up in strings of characters with the same attributes. */
2489 	/* Print UTF-8 characters individually. */
2490 	while (len > 0)
2491 	{
2492 	    first_attr = ScreenAttrs[off];
2493 	    gui.highlight_mask = first_attr;
2494 #if defined(FEAT_MBYTE) && !defined(HAVE_GTK2)
2495 	    if (enc_utf8 && ScreenLinesUC[off] != 0)
2496 	    {
2497 		/* output multi-byte character separately */
2498 		nback = gui_screenchar(off, flags,
2499 					  (guicolor_T)0, (guicolor_T)0, back);
2500 		if (gui.col < Columns && ScreenLines[off + 1] == 0)
2501 		    idx = 2;
2502 		else
2503 		    idx = 1;
2504 	    }
2505 	    else if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e)
2506 	    {
2507 		/* output double-byte, single-width character separately */
2508 		nback = gui_screenchar(off, flags,
2509 					  (guicolor_T)0, (guicolor_T)0, back);
2510 		idx = 1;
2511 	    }
2512 	    else
2513 #endif
2514 	    {
2515 #ifdef HAVE_GTK2
2516 		for (idx = 0; idx < len; ++idx)
2517 		{
2518 		    if (enc_utf8 && ScreenLines[off + idx] == 0)
2519 			continue; /* skip second half of double-width char */
2520 		    if (ScreenAttrs[off + idx] != first_attr)
2521 			break;
2522 		}
2523 		/* gui_screenstr() takes care of multibyte chars */
2524 		nback = gui_screenstr(off, idx, flags,
2525 				      (guicolor_T)0, (guicolor_T)0, back);
2526 #else
2527 		for (idx = 0; idx < len && ScreenAttrs[off + idx] == first_attr;
2528 									idx++)
2529 		{
2530 # ifdef FEAT_MBYTE
2531 		    /* Stop at a multi-byte Unicode character. */
2532 		    if (enc_utf8 && ScreenLinesUC[off + idx] != 0)
2533 			break;
2534 		    if (enc_dbcs == DBCS_JPNU)
2535 		    {
2536 			/* Stop at a double-byte single-width char. */
2537 			if (ScreenLines[off + idx] == 0x8e)
2538 			    break;
2539 			if (len > 1 && (*mb_ptr2len)(ScreenLines
2540 							    + off + idx) == 2)
2541 			    ++idx;  /* skip second byte of double-byte char */
2542 		    }
2543 # endif
2544 		}
2545 		nback = gui_outstr_nowrap(ScreenLines + off, idx, flags,
2546 					  (guicolor_T)0, (guicolor_T)0, back);
2547 #endif
2548 	    }
2549 	    if (nback == FAIL)
2550 	    {
2551 		/* Must back up to start drawing where a bold or italic word
2552 		 * starts. */
2553 		off -= back;
2554 		len += back;
2555 		gui.col -= back;
2556 	    }
2557 	    else
2558 	    {
2559 		off += idx;
2560 		len -= idx;
2561 	    }
2562 	    back = 0;
2563 	}
2564     }
2565 
2566     /* Put the cursor back where it was */
2567     gui.row = old_row;
2568     gui.col = old_col;
2569     gui.highlight_mask = (int)old_hl_mask;
2570 
2571     return retval;
2572 }
2573 
2574     static void
2575 gui_delete_lines(row, count)
2576     int	    row;
2577     int	    count;
2578 {
2579     if (count <= 0)
2580 	return;
2581 
2582     if (row + count > gui.scroll_region_bot)
2583 	/* Scrolled out of region, just blank the lines out */
2584 	gui_clear_block(row, gui.scroll_region_left,
2585 			      gui.scroll_region_bot, gui.scroll_region_right);
2586     else
2587     {
2588 	gui_mch_delete_lines(row, count);
2589 
2590 	/* If the cursor was in the deleted lines it's now gone.  If the
2591 	 * cursor was in the scrolled lines adjust its position. */
2592 	if (gui.cursor_row >= row
2593 		&& gui.cursor_col >= gui.scroll_region_left
2594 		&& gui.cursor_col <= gui.scroll_region_right)
2595 	{
2596 	    if (gui.cursor_row < row + count)
2597 		gui.cursor_is_valid = FALSE;
2598 	    else if (gui.cursor_row <= gui.scroll_region_bot)
2599 		gui.cursor_row -= count;
2600 	}
2601     }
2602 }
2603 
2604     static void
2605 gui_insert_lines(row, count)
2606     int	    row;
2607     int	    count;
2608 {
2609     if (count <= 0)
2610 	return;
2611 
2612     if (row + count > gui.scroll_region_bot)
2613 	/* Scrolled out of region, just blank the lines out */
2614 	gui_clear_block(row, gui.scroll_region_left,
2615 			      gui.scroll_region_bot, gui.scroll_region_right);
2616     else
2617     {
2618 	gui_mch_insert_lines(row, count);
2619 
2620 	if (gui.cursor_row >= gui.row
2621 		&& gui.cursor_col >= gui.scroll_region_left
2622 		&& gui.cursor_col <= gui.scroll_region_right)
2623 	{
2624 	    if (gui.cursor_row <= gui.scroll_region_bot - count)
2625 		gui.cursor_row += count;
2626 	    else if (gui.cursor_row <= gui.scroll_region_bot)
2627 		gui.cursor_is_valid = FALSE;
2628 	}
2629     }
2630 }
2631 
2632 /*
2633  * The main GUI input routine.	Waits for a character from the keyboard.
2634  * wtime == -1	    Wait forever.
2635  * wtime == 0	    Don't wait.
2636  * wtime > 0	    Wait wtime milliseconds for a character.
2637  * Returns OK if a character was found to be available within the given time,
2638  * or FAIL otherwise.
2639  */
2640     int
2641 gui_wait_for_chars(wtime)
2642     long    wtime;
2643 {
2644     int	    retval;
2645 
2646     /*
2647      * If we're going to wait a bit, update the menus and mouse shape for the
2648      * current State.
2649      */
2650     if (wtime != 0)
2651     {
2652 #ifdef FEAT_MENU
2653 	gui_update_menus(0);
2654 #endif
2655     }
2656 
2657     gui_mch_update();
2658     if (input_available())	/* Got char, return immediately */
2659 	return OK;
2660     if (wtime == 0)	/* Don't wait for char */
2661 	return FAIL;
2662 
2663     /* Before waiting, flush any output to the screen. */
2664     gui_mch_flush();
2665 
2666     if (wtime > 0)
2667     {
2668 	/* Blink when waiting for a character.	Probably only does something
2669 	 * for showmatch() */
2670 	gui_mch_start_blink();
2671 	retval = gui_mch_wait_for_chars(wtime);
2672 	gui_mch_stop_blink();
2673 	return retval;
2674     }
2675 
2676     /*
2677      * While we are waiting indefenitely for a character, blink the cursor.
2678      */
2679     gui_mch_start_blink();
2680 
2681     retval = FAIL;
2682     /*
2683      * We may want to trigger the CursorHold event.  First wait for
2684      * 'updatetime' and if nothing is typed within that time put the
2685      * K_CURSORHOLD key in the input buffer.
2686      */
2687     if (gui_mch_wait_for_chars(p_ut) == OK)
2688 	retval = OK;
2689 #ifdef FEAT_AUTOCMD
2690     else if (trigger_cursorhold())
2691     {
2692 	char_u	buf[3];
2693 
2694 	/* Put K_CURSORHOLD in the input buffer. */
2695 	buf[0] = CSI;
2696 	buf[1] = KS_EXTRA;
2697 	buf[2] = (int)KE_CURSORHOLD;
2698 	add_to_input_buf(buf, 3);
2699 
2700 	retval = OK;
2701     }
2702 #endif
2703 
2704     if (retval == FAIL)
2705     {
2706 	/* Blocking wait. */
2707 	before_blocking();
2708 	retval = gui_mch_wait_for_chars(-1L);
2709     }
2710 
2711     gui_mch_stop_blink();
2712     return retval;
2713 }
2714 
2715 /*
2716  * Fill buffer with mouse coordinates encoded for check_termcode().
2717  */
2718     static void
2719 fill_mouse_coord(p, col, row)
2720     char_u	*p;
2721     int		col;
2722     int		row;
2723 {
2724     p[0] = (char_u)(col / 128 + ' ' + 1);
2725     p[1] = (char_u)(col % 128 + ' ' + 1);
2726     p[2] = (char_u)(row / 128 + ' ' + 1);
2727     p[3] = (char_u)(row % 128 + ' ' + 1);
2728 }
2729 
2730 /*
2731  * Generic mouse support function.  Add a mouse event to the input buffer with
2732  * the given properties.
2733  *  button	    --- may be any of MOUSE_LEFT, MOUSE_MIDDLE, MOUSE_RIGHT,
2734  *			MOUSE_X1, MOUSE_X2
2735  *			MOUSE_DRAG, or MOUSE_RELEASE.
2736  *			MOUSE_4 and MOUSE_5 are used for a scroll wheel.
2737  *  x, y	    --- Coordinates of mouse in pixels.
2738  *  repeated_click  --- TRUE if this click comes only a short time after a
2739  *			previous click.
2740  *  modifiers	    --- Bit field which may be any of the following modifiers
2741  *			or'ed together: MOUSE_SHIFT | MOUSE_CTRL | MOUSE_ALT.
2742  * This function will ignore drag events where the mouse has not moved to a new
2743  * character.
2744  */
2745     void
2746 gui_send_mouse_event(button, x, y, repeated_click, modifiers)
2747     int	    button;
2748     int	    x;
2749     int	    y;
2750     int	    repeated_click;
2751     int_u   modifiers;
2752 {
2753     static int	    prev_row = 0, prev_col = 0;
2754     static int	    prev_button = -1;
2755     static int	    num_clicks = 1;
2756     char_u	    string[10];
2757     enum key_extra  button_char;
2758     int		    row, col;
2759 #ifdef FEAT_CLIPBOARD
2760     int		    checkfor;
2761     int		    did_clip = FALSE;
2762 #endif
2763 
2764     /*
2765      * Scrolling may happen at any time, also while a selection is present.
2766      */
2767     switch (button)
2768     {
2769 	case MOUSE_X1:
2770 	    button_char = KE_X1MOUSE;
2771 	    goto button_set;
2772 	case MOUSE_X2:
2773 	    button_char = KE_X2MOUSE;
2774 	    goto button_set;
2775 	case MOUSE_4:
2776 	    button_char = KE_MOUSEDOWN;
2777 	    goto button_set;
2778 	case MOUSE_5:
2779 	    button_char = KE_MOUSEUP;
2780 button_set:
2781 	    {
2782 		/* Don't put events in the input queue now. */
2783 		if (hold_gui_events)
2784 		    return;
2785 
2786 		string[3] = CSI;
2787 		string[4] = KS_EXTRA;
2788 		string[5] = (int)button_char;
2789 
2790 		/* Pass the pointer coordinates of the scroll event so that we
2791 		 * know which window to scroll. */
2792 		row = gui_xy2colrow(x, y, &col);
2793 		string[6] = (char_u)(col / 128 + ' ' + 1);
2794 		string[7] = (char_u)(col % 128 + ' ' + 1);
2795 		string[8] = (char_u)(row / 128 + ' ' + 1);
2796 		string[9] = (char_u)(row % 128 + ' ' + 1);
2797 
2798 		if (modifiers == 0)
2799 		    add_to_input_buf(string + 3, 7);
2800 		else
2801 		{
2802 		    string[0] = CSI;
2803 		    string[1] = KS_MODIFIER;
2804 		    string[2] = 0;
2805 		    if (modifiers & MOUSE_SHIFT)
2806 			string[2] |= MOD_MASK_SHIFT;
2807 		    if (modifiers & MOUSE_CTRL)
2808 			string[2] |= MOD_MASK_CTRL;
2809 		    if (modifiers & MOUSE_ALT)
2810 			string[2] |= MOD_MASK_ALT;
2811 		    add_to_input_buf(string, 10);
2812 		}
2813 		return;
2814 	    }
2815     }
2816 
2817 #ifdef FEAT_CLIPBOARD
2818     /* If a clipboard selection is in progress, handle it */
2819     if (clip_star.state == SELECT_IN_PROGRESS)
2820     {
2821 	clip_process_selection(button, X_2_COL(x), Y_2_ROW(y), repeated_click);
2822 	return;
2823     }
2824 
2825     /* Determine which mouse settings to look for based on the current mode */
2826     switch (get_real_state())
2827     {
2828 	case NORMAL_BUSY:
2829 	case OP_PENDING:
2830 	case NORMAL:		checkfor = MOUSE_NORMAL;	break;
2831 	case VISUAL:		checkfor = MOUSE_VISUAL;	break;
2832 	case SELECTMODE:	checkfor = MOUSE_VISUAL;	break;
2833 	case REPLACE:
2834 	case REPLACE+LANGMAP:
2835 #ifdef FEAT_VREPLACE
2836 	case VREPLACE:
2837 	case VREPLACE+LANGMAP:
2838 #endif
2839 	case INSERT:
2840 	case INSERT+LANGMAP:	checkfor = MOUSE_INSERT;	break;
2841 	case ASKMORE:
2842 	case HITRETURN:		/* At the more- and hit-enter prompt pass the
2843 				   mouse event for a click on or below the
2844 				   message line. */
2845 				if (Y_2_ROW(y) >= msg_row)
2846 				    checkfor = MOUSE_NORMAL;
2847 				else
2848 				    checkfor = MOUSE_RETURN;
2849 				break;
2850 
2851 	    /*
2852 	     * On the command line, use the clipboard selection on all lines
2853 	     * but the command line.  But not when pasting.
2854 	     */
2855 	case CMDLINE:
2856 	case CMDLINE+LANGMAP:
2857 	    if (Y_2_ROW(y) < cmdline_row && button != MOUSE_MIDDLE)
2858 		checkfor = MOUSE_NONE;
2859 	    else
2860 		checkfor = MOUSE_COMMAND;
2861 	    break;
2862 
2863 	default:
2864 	    checkfor = MOUSE_NONE;
2865 	    break;
2866     };
2867 
2868     /*
2869      * Allow clipboard selection of text on the command line in "normal"
2870      * modes.  Don't do this when dragging the status line, or extending a
2871      * Visual selection.
2872      */
2873     if ((State == NORMAL || State == NORMAL_BUSY || (State & INSERT))
2874 	    && Y_2_ROW(y) >= topframe->fr_height
2875 	    && button != MOUSE_DRAG
2876 # ifdef FEAT_MOUSESHAPE
2877 	    && !drag_status_line
2878 #  ifdef FEAT_VERTSPLIT
2879 	    && !drag_sep_line
2880 #  endif
2881 # endif
2882 	    )
2883 	checkfor = MOUSE_NONE;
2884 
2885     /*
2886      * Use modeless selection when holding CTRL and SHIFT pressed.
2887      */
2888     if ((modifiers & MOUSE_CTRL) && (modifiers & MOUSE_SHIFT))
2889 	checkfor = MOUSE_NONEF;
2890 
2891     /*
2892      * In Ex mode, always use modeless selection.
2893      */
2894     if (exmode_active)
2895 	checkfor = MOUSE_NONE;
2896 
2897     /*
2898      * If the mouse settings say to not use the mouse, use the modeless
2899      * selection.  But if Visual is active, assume that only the Visual area
2900      * will be selected.
2901      * Exception: On the command line, both the selection is used and a mouse
2902      * key is send.
2903      */
2904     if (!mouse_has(checkfor) || checkfor == MOUSE_COMMAND)
2905     {
2906 #ifdef FEAT_VISUAL
2907 	/* Don't do modeless selection in Visual mode. */
2908 	if (checkfor != MOUSE_NONEF && VIsual_active && (State & NORMAL))
2909 	    return;
2910 #endif
2911 
2912 	/*
2913 	 * When 'mousemodel' is "popup", shift-left is translated to right.
2914 	 * But not when also using Ctrl.
2915 	 */
2916 	if (mouse_model_popup() && button == MOUSE_LEFT
2917 		&& (modifiers & MOUSE_SHIFT) && !(modifiers & MOUSE_CTRL))
2918 	{
2919 	    button = MOUSE_RIGHT;
2920 	    modifiers &= ~ MOUSE_SHIFT;
2921 	}
2922 
2923 	/* If the selection is done, allow the right button to extend it.
2924 	 * If the selection is cleared, allow the right button to start it
2925 	 * from the cursor position. */
2926 	if (button == MOUSE_RIGHT)
2927 	{
2928 	    if (clip_star.state == SELECT_CLEARED)
2929 	    {
2930 		if (State & CMDLINE)
2931 		{
2932 		    col = msg_col;
2933 		    row = msg_row;
2934 		}
2935 		else
2936 		{
2937 		    col = curwin->w_wcol;
2938 		    row = curwin->w_wrow + W_WINROW(curwin);
2939 		}
2940 		clip_start_selection(col, row, FALSE);
2941 	    }
2942 	    clip_process_selection(button, X_2_COL(x), Y_2_ROW(y),
2943 							      repeated_click);
2944 	    did_clip = TRUE;
2945 	}
2946 	/* Allow the left button to start the selection */
2947 	else if (button ==
2948 # ifdef RISCOS
2949 		/* Only start a drag on a drag event. Otherwise
2950 		 * we don't get a release event. */
2951 		    MOUSE_DRAG
2952 # else
2953 		    MOUSE_LEFT
2954 # endif
2955 				)
2956 	{
2957 	    clip_start_selection(X_2_COL(x), Y_2_ROW(y), repeated_click);
2958 	    did_clip = TRUE;
2959 	}
2960 # ifdef RISCOS
2961 	else if (button == MOUSE_LEFT)
2962 	{
2963 	    clip_clear_selection();
2964 	    did_clip = TRUE;
2965 	}
2966 # endif
2967 
2968 	/* Always allow pasting */
2969 	if (button != MOUSE_MIDDLE)
2970 	{
2971 	    if (!mouse_has(checkfor) || button == MOUSE_RELEASE)
2972 		return;
2973 	    if (checkfor != MOUSE_COMMAND)
2974 		button = MOUSE_LEFT;
2975 	}
2976 	repeated_click = FALSE;
2977     }
2978 
2979     if (clip_star.state != SELECT_CLEARED && !did_clip)
2980 	clip_clear_selection();
2981 #endif
2982 
2983     /* Don't put events in the input queue now. */
2984     if (hold_gui_events)
2985 	return;
2986 
2987     row = gui_xy2colrow(x, y, &col);
2988 
2989     /*
2990      * If we are dragging and the mouse hasn't moved far enough to be on a
2991      * different character, then don't send an event to vim.
2992      */
2993     if (button == MOUSE_DRAG)
2994     {
2995 	if (row == prev_row && col == prev_col)
2996 	    return;
2997 	/* Dragging above the window, set "row" to -1 to cause a scroll. */
2998 	if (y < 0)
2999 	    row = -1;
3000     }
3001 
3002     /*
3003      * If topline has changed (window scrolled) since the last click, reset
3004      * repeated_click, because we don't want starting Visual mode when
3005      * clicking on a different character in the text.
3006      */
3007     if (curwin->w_topline != gui_prev_topline
3008 #ifdef FEAT_DIFF
3009 	    || curwin->w_topfill != gui_prev_topfill
3010 #endif
3011 	    )
3012 	repeated_click = FALSE;
3013 
3014     string[0] = CSI;	/* this sequence is recognized by check_termcode() */
3015     string[1] = KS_MOUSE;
3016     string[2] = KE_FILLER;
3017     if (button != MOUSE_DRAG && button != MOUSE_RELEASE)
3018     {
3019 	if (repeated_click)
3020 	{
3021 	    /*
3022 	     * Handle multiple clicks.	They only count if the mouse is still
3023 	     * pointing at the same character.
3024 	     */
3025 	    if (button != prev_button || row != prev_row || col != prev_col)
3026 		num_clicks = 1;
3027 	    else if (++num_clicks > 4)
3028 		num_clicks = 1;
3029 	}
3030 	else
3031 	    num_clicks = 1;
3032 	prev_button = button;
3033 	gui_prev_topline = curwin->w_topline;
3034 #ifdef FEAT_DIFF
3035 	gui_prev_topfill = curwin->w_topfill;
3036 #endif
3037 
3038 	string[3] = (char_u)(button | 0x20);
3039 	SET_NUM_MOUSE_CLICKS(string[3], num_clicks);
3040     }
3041     else
3042 	string[3] = (char_u)button;
3043 
3044     string[3] |= modifiers;
3045     fill_mouse_coord(string + 4, col, row);
3046     add_to_input_buf(string, 8);
3047 
3048     if (row < 0)
3049 	prev_row = 0;
3050     else
3051 	prev_row = row;
3052     prev_col = col;
3053 
3054     /*
3055      * We need to make sure this is cleared since Athena doesn't tell us when
3056      * he is done dragging.  Neither does GTK+ 2 -- at least for now.
3057      */
3058 #if defined(FEAT_GUI_ATHENA) || defined(HAVE_GTK2)
3059     gui.dragged_sb = SBAR_NONE;
3060 #endif
3061 }
3062 
3063 /*
3064  * Convert x and y coordinate to column and row in text window.
3065  * Corrects for multi-byte character.
3066  * returns column in "*colp" and row as return value;
3067  */
3068     int
3069 gui_xy2colrow(x, y, colp)
3070     int		x;
3071     int		y;
3072     int		*colp;
3073 {
3074     int		col = check_col(X_2_COL(x));
3075     int		row = check_row(Y_2_ROW(y));
3076 
3077 #ifdef FEAT_MBYTE
3078     *colp = mb_fix_col(col, row);
3079 #else
3080     *colp = col;
3081 #endif
3082     return row;
3083 }
3084 
3085 #if defined(FEAT_MENU) || defined(PROTO)
3086 /*
3087  * Callback function for when a menu entry has been selected.
3088  */
3089     void
3090 gui_menu_cb(menu)
3091     vimmenu_T *menu;
3092 {
3093     char_u  bytes[sizeof(long_u)];
3094 
3095     /* Don't put events in the input queue now. */
3096     if (hold_gui_events)
3097 	return;
3098 
3099     bytes[0] = CSI;
3100     bytes[1] = KS_MENU;
3101     bytes[2] = KE_FILLER;
3102     add_to_input_buf(bytes, 3);
3103     add_long_to_buf((long_u)menu, bytes);
3104     add_to_input_buf_csi(bytes, sizeof(long_u));
3105 }
3106 #endif
3107 
3108 static int	prev_which_scrollbars[3];
3109 
3110 /*
3111  * Set which components are present.
3112  * If "oldval" is not NULL, "oldval" is the previous value, the new value is
3113  * in p_go.
3114  */
3115 /*ARGSUSED*/
3116     void
3117 gui_init_which_components(oldval)
3118     char_u	*oldval;
3119 {
3120 #ifdef FEAT_MENU
3121     static int	prev_menu_is_active = -1;
3122 #endif
3123 #ifdef FEAT_TOOLBAR
3124     static int	prev_toolbar = -1;
3125     int		using_toolbar = FALSE;
3126 #endif
3127 #ifdef FEAT_GUI_TABLINE
3128     int		using_tabline;
3129 #endif
3130 #ifdef FEAT_FOOTER
3131     static int	prev_footer = -1;
3132     int		using_footer = FALSE;
3133 #endif
3134 #if defined(FEAT_MENU) && !defined(WIN16)
3135     static int	prev_tearoff = -1;
3136     int		using_tearoff = FALSE;
3137 #endif
3138 
3139     char_u	*p;
3140     int		i;
3141 #ifdef FEAT_MENU
3142     int		grey_old, grey_new;
3143     char_u	*temp;
3144 #endif
3145     win_T	*wp;
3146     int		need_set_size;
3147     int		fix_size;
3148 
3149 #ifdef FEAT_MENU
3150     if (oldval != NULL && gui.in_use)
3151     {
3152 	/*
3153 	 * Check if the menu's go from grey to non-grey or vise versa.
3154 	 */
3155 	grey_old = (vim_strchr(oldval, GO_GREY) != NULL);
3156 	grey_new = (vim_strchr(p_go, GO_GREY) != NULL);
3157 	if (grey_old != grey_new)
3158 	{
3159 	    temp = p_go;
3160 	    p_go = oldval;
3161 	    gui_update_menus(MENU_ALL_MODES);
3162 	    p_go = temp;
3163 	}
3164     }
3165     gui.menu_is_active = FALSE;
3166 #endif
3167 
3168     for (i = 0; i < 3; i++)
3169 	gui.which_scrollbars[i] = FALSE;
3170     for (p = p_go; *p; p++)
3171 	switch (*p)
3172 	{
3173 	    case GO_LEFT:
3174 		gui.which_scrollbars[SBAR_LEFT] = TRUE;
3175 		break;
3176 	    case GO_RIGHT:
3177 		gui.which_scrollbars[SBAR_RIGHT] = TRUE;
3178 		break;
3179 #ifdef FEAT_VERTSPLIT
3180 	    case GO_VLEFT:
3181 		if (win_hasvertsplit())
3182 		    gui.which_scrollbars[SBAR_LEFT] = TRUE;
3183 		break;
3184 	    case GO_VRIGHT:
3185 		if (win_hasvertsplit())
3186 		    gui.which_scrollbars[SBAR_RIGHT] = TRUE;
3187 		break;
3188 #endif
3189 	    case GO_BOT:
3190 		gui.which_scrollbars[SBAR_BOTTOM] = TRUE;
3191 		break;
3192 #ifdef FEAT_MENU
3193 	    case GO_MENUS:
3194 		gui.menu_is_active = TRUE;
3195 		break;
3196 #endif
3197 	    case GO_GREY:
3198 		/* make menu's have grey items, ignored here */
3199 		break;
3200 #ifdef FEAT_TOOLBAR
3201 	    case GO_TOOLBAR:
3202 		using_toolbar = TRUE;
3203 		break;
3204 #endif
3205 #ifdef FEAT_FOOTER
3206 	    case GO_FOOTER:
3207 		using_footer = TRUE;
3208 		break;
3209 #endif
3210 	    case GO_TEAROFF:
3211 #if defined(FEAT_MENU) && !defined(WIN16)
3212 		using_tearoff = TRUE;
3213 #endif
3214 		break;
3215 	    default:
3216 		/* Ignore options that are not supported */
3217 		break;
3218 	}
3219 
3220     if (gui.in_use)
3221     {
3222 	need_set_size = 0;
3223 	fix_size = FALSE;
3224 
3225 #ifdef FEAT_GUI_TABLINE
3226 	/* Update the GUI tab line, it may appear or disappear.  This may
3227 	 * cause the non-GUI tab line to disappear or appear. */
3228 	using_tabline = gui_has_tabline();
3229 	if (!gui_mch_showing_tabline() != !using_tabline)
3230 	{
3231 	    /* We don't want a resize event change "Rows" here, save and
3232 	     * restore it.  Resizing is handled below. */
3233 	    i = Rows;
3234 	    gui_update_tabline();
3235 	    Rows = i;
3236 	    need_set_size = RESIZE_VERT;
3237 	    if (using_tabline)
3238 		fix_size = TRUE;
3239 	    if (!gui_use_tabline())
3240 		redraw_tabline = TRUE;    /* may draw non-GUI tab line */
3241 	}
3242 #endif
3243 
3244 	for (i = 0; i < 3; i++)
3245 	{
3246 	    /* The scrollbar needs to be updated when it is shown/unshown and
3247 	     * when switching tab pages.  But the size only changes when it's
3248 	     * shown/unshown.  Thus we need two places to remember whether a
3249 	     * scrollbar is there or not. */
3250 	    if (gui.which_scrollbars[i] != prev_which_scrollbars[i]
3251 #ifdef FEAT_WINDOWS
3252 		    || gui.which_scrollbars[i]
3253 					!= curtab->tp_prev_which_scrollbars[i]
3254 #endif
3255 		    )
3256 	    {
3257 		if (i == SBAR_BOTTOM)
3258 		    gui_mch_enable_scrollbar(&gui.bottom_sbar,
3259 						     gui.which_scrollbars[i]);
3260 		else
3261 		{
3262 		    FOR_ALL_WINDOWS(wp)
3263 		    {
3264 			gui_do_scrollbar(wp, i, gui.which_scrollbars[i]);
3265 		    }
3266 		}
3267 		if (gui.which_scrollbars[i] != prev_which_scrollbars[i])
3268 		{
3269 		    if (i == SBAR_BOTTOM)
3270 			need_set_size = RESIZE_VERT;
3271 		    else
3272 			need_set_size = RESIZE_HOR;
3273 		    if (gui.which_scrollbars[i])
3274 			fix_size = TRUE;
3275 		}
3276 	    }
3277 #ifdef FEAT_WINDOWS
3278 	    curtab->tp_prev_which_scrollbars[i] = gui.which_scrollbars[i];
3279 #endif
3280 	    prev_which_scrollbars[i] = gui.which_scrollbars[i];
3281 	}
3282 
3283 #ifdef FEAT_MENU
3284 	if (gui.menu_is_active != prev_menu_is_active)
3285 	{
3286 	    /* We don't want a resize event change "Rows" here, save and
3287 	     * restore it.  Resizing is handled below. */
3288 	    i = Rows;
3289 	    gui_mch_enable_menu(gui.menu_is_active);
3290 	    Rows = i;
3291 	    prev_menu_is_active = gui.menu_is_active;
3292 	    need_set_size = RESIZE_VERT;
3293 	    if (gui.menu_is_active)
3294 		fix_size = TRUE;
3295 	}
3296 #endif
3297 
3298 #ifdef FEAT_TOOLBAR
3299 	if (using_toolbar != prev_toolbar)
3300 	{
3301 	    gui_mch_show_toolbar(using_toolbar);
3302 	    prev_toolbar = using_toolbar;
3303 	    need_set_size = RESIZE_VERT;
3304 	    if (using_toolbar)
3305 		fix_size = TRUE;
3306 	}
3307 #endif
3308 #ifdef FEAT_FOOTER
3309 	if (using_footer != prev_footer)
3310 	{
3311 	    gui_mch_enable_footer(using_footer);
3312 	    prev_footer = using_footer;
3313 	    need_set_size = RESIZE_VERT;
3314 	    if (using_footer)
3315 		fix_size = TRUE;
3316 	}
3317 #endif
3318 #if defined(FEAT_MENU) && !defined(WIN16) && !(defined(WIN3264) && !defined(FEAT_TEAROFF))
3319 	if (using_tearoff != prev_tearoff)
3320 	{
3321 	    gui_mch_toggle_tearoffs(using_tearoff);
3322 	    prev_tearoff = using_tearoff;
3323 	}
3324 #endif
3325 	if (need_set_size)
3326 	{
3327 #ifdef FEAT_GUI_GTK
3328 	    long    c = Columns;
3329 #endif
3330 	    /* Adjust the size of the window to make the text area keep the
3331 	     * same size and to avoid that part of our window is off-screen
3332 	     * and a scrollbar can't be used, for example. */
3333 	    gui_set_shellsize(FALSE, fix_size, need_set_size);
3334 
3335 #ifdef FEAT_GUI_GTK
3336 	    /* GTK has the annoying habit of sending us resize events when
3337 	     * changing the window size ourselves.  This mostly happens when
3338 	     * waiting for a character to arrive, quite unpredictably, and may
3339 	     * change Columns and Rows when we don't want it.  Wait for a
3340 	     * character here to avoid this effect.
3341 	     * If you remove this, please test this command for resizing
3342 	     * effects (with optional left scrollbar): ":vsp|q|vsp|q|vsp|q".
3343 	     * Don't do this while starting up though.
3344 	     * And don't change Rows, it may have be reduced intentionally
3345 	     * when adding menu/toolbar/tabline. */
3346 	    if (!gui.starting)
3347 		(void)char_avail();
3348 	    Columns = c;
3349 #endif
3350 	}
3351 #ifdef FEAT_WINDOWS
3352 	/* When the console tabline appears or disappears the window positions
3353 	 * change. */
3354 	if (firstwin->w_winrow != tabline_height())
3355 	    shell_new_rows();	/* recompute window positions and heights */
3356 #endif
3357     }
3358 }
3359 
3360 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
3361 /*
3362  * Return TRUE if the GUI is taking care of the tabline.
3363  * It may still be hidden if 'showtabline' is zero.
3364  */
3365     int
3366 gui_use_tabline()
3367 {
3368     return gui.in_use && vim_strchr(p_go, GO_TABLINE) != NULL;
3369 }
3370 
3371 /*
3372  * Return TRUE if the GUI is showing the tabline.
3373  * This uses 'showtabline'.
3374  */
3375     static int
3376 gui_has_tabline()
3377 {
3378     if (!gui_use_tabline()
3379 	    || p_stal == 0
3380 	    || (p_stal == 1 && first_tabpage->tp_next == NULL))
3381 	return FALSE;
3382     return TRUE;
3383 }
3384 
3385 /*
3386  * Update the tabline.
3387  * This may display/undisplay the tabline and update the labels.
3388  */
3389     void
3390 gui_update_tabline()
3391 {
3392     int	    showit = gui_has_tabline();
3393     int	    shown = gui_mch_showing_tabline();
3394 
3395     if (!gui.starting && starting == 0)
3396     {
3397 	if (!showit != !shown)
3398 	    gui_mch_show_tabline(showit);
3399 	if (showit != 0)
3400 	    gui_mch_update_tabline();
3401 
3402 	/* When the tabs change from hidden to shown or from shown to
3403 	 * hidden the size of the text area should remain the same. */
3404 	if (!showit != !shown)
3405 	    gui_set_shellsize(FALSE, showit, RESIZE_VERT);
3406     }
3407 }
3408 
3409 /*
3410  * Get the label or tooltip for tab page "tp" into NameBuff[].
3411  */
3412     void
3413 get_tabline_label(tp, tooltip)
3414     tabpage_T	*tp;
3415     int		tooltip;	/* TRUE: get tooltip */
3416 {
3417     int		modified = FALSE;
3418     char_u	buf[40];
3419     int		wincount;
3420     win_T	*wp;
3421     char_u	*opt;
3422 
3423     /* Use 'guitablabel' or 'guitabtooltip' if it's set. */
3424     opt = (tooltip ? p_gtt : p_gtl);
3425     if (*opt != NUL)
3426     {
3427 	int	use_sandbox = FALSE;
3428 	int	save_called_emsg = called_emsg;
3429 	char_u	res[MAXPATHL];
3430 	tabpage_T *save_curtab;
3431 	char_u	*opt_name = (char_u *)(tooltip ? "guitabtooltip"
3432 							     : "guitablabel");
3433 
3434 	called_emsg = FALSE;
3435 
3436 	printer_page_num = tabpage_index(tp);
3437 # ifdef FEAT_EVAL
3438 	set_vim_var_nr(VV_LNUM, printer_page_num);
3439 	use_sandbox = was_set_insecurely(opt_name, 0);
3440 # endif
3441 	/* It's almost as going to the tabpage, but without autocommands. */
3442 	curtab->tp_firstwin = firstwin;
3443 	curtab->tp_lastwin = lastwin;
3444 	curtab->tp_curwin = curwin;
3445 	save_curtab = curtab;
3446 	curtab = tp;
3447 	topframe = curtab->tp_topframe;
3448 	firstwin = curtab->tp_firstwin;
3449 	lastwin = curtab->tp_lastwin;
3450 	curwin = curtab->tp_curwin;
3451 	curbuf = curwin->w_buffer;
3452 
3453 	/* Can't use NameBuff directly, build_stl_str_hl() uses it. */
3454 	build_stl_str_hl(curwin, res, MAXPATHL, opt, use_sandbox,
3455 						 0, (int)Columns, NULL, NULL);
3456 	STRCPY(NameBuff, res);
3457 
3458 	/* Back to the original curtab. */
3459 	curtab = save_curtab;
3460 	topframe = curtab->tp_topframe;
3461 	firstwin = curtab->tp_firstwin;
3462 	lastwin = curtab->tp_lastwin;
3463 	curwin = curtab->tp_curwin;
3464 	curbuf = curwin->w_buffer;
3465 
3466 	if (called_emsg)
3467 	    set_string_option_direct(opt_name, -1,
3468 					   (char_u *)"", OPT_FREE, SID_ERROR);
3469 	called_emsg |= save_called_emsg;
3470     }
3471     else
3472     {
3473 	/* Get the buffer name into NameBuff[] and shorten it. */
3474 	get_trans_bufname(tp == curtab ? curbuf : tp->tp_curwin->w_buffer);
3475 	if (!tooltip)
3476 	    shorten_dir(NameBuff);
3477 
3478 	wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
3479 	for (wincount = 0; wp != NULL; wp = wp->w_next, ++wincount)
3480 	    if (bufIsChanged(wp->w_buffer))
3481 		modified = TRUE;
3482 	if (modified || wincount > 1)
3483 	{
3484 	    if (wincount > 1)
3485 		vim_snprintf((char *)buf, sizeof(buf), "%d", wincount);
3486 	    else
3487 		buf[0] = NUL;
3488 	    if (modified)
3489 		STRCAT(buf, "+");
3490 	    STRCAT(buf, " ");
3491 	    mch_memmove(NameBuff + STRLEN(buf), NameBuff, STRLEN(NameBuff) + 1);
3492 	    mch_memmove(NameBuff, buf, STRLEN(buf));
3493 	}
3494     }
3495 }
3496 
3497 /*
3498  * Send the event for clicking to select tab page "nr".
3499  * Returns TRUE if it was done, FALSE when skipped because we are already at
3500  * that tab page or the cmdline window is open.
3501  */
3502     int
3503 send_tabline_event(nr)
3504     int	    nr;
3505 {
3506     char_u string[3];
3507 
3508     if (nr == tabpage_index(curtab))
3509 	return FALSE;
3510 
3511     /* Don't put events in the input queue now. */
3512     if (hold_gui_events
3513 # ifdef FEAT_CMDWIN
3514 	    || cmdwin_type != 0
3515 # endif
3516 	    )
3517     {
3518 	/* Set it back to the current tab page. */
3519 	gui_mch_set_curtab(tabpage_index(curtab));
3520 	return FALSE;
3521     }
3522 
3523     string[0] = CSI;
3524     string[1] = KS_TABLINE;
3525     string[2] = KE_FILLER;
3526     add_to_input_buf(string, 3);
3527     string[0] = nr;
3528     add_to_input_buf_csi(string, 1);
3529     return TRUE;
3530 }
3531 
3532 /*
3533  * Send a tabline menu event
3534  */
3535     void
3536 send_tabline_menu_event(tabidx, event)
3537     int	    tabidx;
3538     int	    event;
3539 {
3540     char_u	    string[3];
3541 
3542     /* Don't put events in the input queue now. */
3543     if (hold_gui_events)
3544 	return;
3545 
3546     string[0] = CSI;
3547     string[1] = KS_TABMENU;
3548     string[2] = KE_FILLER;
3549     add_to_input_buf(string, 3);
3550     string[0] = tabidx;
3551     string[1] = (char_u)(long)event;
3552     add_to_input_buf_csi(string, 2);
3553 }
3554 
3555 #endif
3556 
3557 /*
3558  * Scrollbar stuff:
3559  */
3560 
3561 #if defined(FEAT_WINDOWS) || defined(PROTO)
3562 /*
3563  * Remove all scrollbars.  Used before switching to another tab page.
3564  */
3565     void
3566 gui_remove_scrollbars()
3567 {
3568     int	    i;
3569     win_T   *wp;
3570 
3571     for (i = 0; i < 3; i++)
3572     {
3573 	if (i == SBAR_BOTTOM)
3574 	    gui_mch_enable_scrollbar(&gui.bottom_sbar, FALSE);
3575 	else
3576 	{
3577 	    FOR_ALL_WINDOWS(wp)
3578 	    {
3579 		gui_do_scrollbar(wp, i, FALSE);
3580 	    }
3581 	}
3582 	curtab->tp_prev_which_scrollbars[i] = -1;
3583     }
3584 }
3585 #endif
3586 
3587     void
3588 gui_create_scrollbar(sb, type, wp)
3589     scrollbar_T	*sb;
3590     int		type;
3591     win_T	*wp;
3592 {
3593     static int	sbar_ident = 0;
3594 
3595     sb->ident = sbar_ident++;	/* No check for too big, but would it happen? */
3596     sb->wp = wp;
3597     sb->type = type;
3598     sb->value = 0;
3599 #ifdef FEAT_GUI_ATHENA
3600     sb->pixval = 0;
3601 #endif
3602     sb->size = 1;
3603     sb->max = 1;
3604     sb->top = 0;
3605     sb->height = 0;
3606 #ifdef FEAT_VERTSPLIT
3607     sb->width = 0;
3608 #endif
3609     sb->status_height = 0;
3610     gui_mch_create_scrollbar(sb, (wp == NULL) ? SBAR_HORIZ : SBAR_VERT);
3611 }
3612 
3613 /*
3614  * Find the scrollbar with the given index.
3615  */
3616     scrollbar_T *
3617 gui_find_scrollbar(ident)
3618     long	ident;
3619 {
3620     win_T	*wp;
3621 
3622     if (gui.bottom_sbar.ident == ident)
3623 	return &gui.bottom_sbar;
3624     FOR_ALL_WINDOWS(wp)
3625     {
3626 	if (wp->w_scrollbars[SBAR_LEFT].ident == ident)
3627 	    return &wp->w_scrollbars[SBAR_LEFT];
3628 	if (wp->w_scrollbars[SBAR_RIGHT].ident == ident)
3629 	    return &wp->w_scrollbars[SBAR_RIGHT];
3630     }
3631     return NULL;
3632 }
3633 
3634 /*
3635  * For most systems: Put a code in the input buffer for a dragged scrollbar.
3636  *
3637  * For Win32, Macintosh and GTK+ 2:
3638  * Scrollbars seem to grab focus and vim doesn't read the input queue until
3639  * you stop dragging the scrollbar.  We get here each time the scrollbar is
3640  * dragged another pixel, but as far as the rest of vim goes, it thinks
3641  * we're just hanging in the call to DispatchMessage() in
3642  * process_message().  The DispatchMessage() call that hangs was passed a
3643  * mouse button click event in the scrollbar window. -- webb.
3644  *
3645  * Solution: Do the scrolling right here.  But only when allowed.
3646  * Ignore the scrollbars while executing an external command or when there
3647  * are still characters to be processed.
3648  */
3649     void
3650 gui_drag_scrollbar(sb, value, still_dragging)
3651     scrollbar_T	*sb;
3652     long	value;
3653     int		still_dragging;
3654 {
3655 #ifdef FEAT_WINDOWS
3656     win_T	*wp;
3657 #endif
3658     int		sb_num;
3659 #ifdef USE_ON_FLY_SCROLL
3660     colnr_T	old_leftcol = curwin->w_leftcol;
3661 # ifdef FEAT_SCROLLBIND
3662     linenr_T	old_topline = curwin->w_topline;
3663 # endif
3664 # ifdef FEAT_DIFF
3665     int		old_topfill = curwin->w_topfill;
3666 # endif
3667 #else
3668     char_u	bytes[sizeof(long_u)];
3669     int		byte_count;
3670 #endif
3671 
3672     if (sb == NULL)
3673 	return;
3674 
3675     /* Don't put events in the input queue now. */
3676     if (hold_gui_events)
3677 	return;
3678 
3679 #ifdef FEAT_CMDWIN
3680     if (cmdwin_type != 0 && sb->wp != curwin)
3681 	return;
3682 #endif
3683 
3684     if (still_dragging)
3685     {
3686 	if (sb->wp == NULL)
3687 	    gui.dragged_sb = SBAR_BOTTOM;
3688 	else if (sb == &sb->wp->w_scrollbars[SBAR_LEFT])
3689 	    gui.dragged_sb = SBAR_LEFT;
3690 	else
3691 	    gui.dragged_sb = SBAR_RIGHT;
3692 	gui.dragged_wp = sb->wp;
3693     }
3694     else
3695     {
3696 	gui.dragged_sb = SBAR_NONE;
3697 #ifdef HAVE_GTK2
3698 	/* Keep the "dragged_wp" value until after the scrolling, for when the
3699 	 * moust button is released.  GTK2 doesn't send the button-up event. */
3700 	gui.dragged_wp = NULL;
3701 #endif
3702     }
3703 
3704     /* Vertical sbar info is kept in the first sbar (the left one) */
3705     if (sb->wp != NULL)
3706 	sb = &sb->wp->w_scrollbars[0];
3707 
3708     /*
3709      * Check validity of value
3710      */
3711     if (value < 0)
3712 	value = 0;
3713 #ifdef SCROLL_PAST_END
3714     else if (value > sb->max)
3715 	value = sb->max;
3716 #else
3717     if (value > sb->max - sb->size + 1)
3718 	value = sb->max - sb->size + 1;
3719 #endif
3720 
3721     sb->value = value;
3722 
3723 #ifdef USE_ON_FLY_SCROLL
3724     /* When not allowed to do the scrolling right now, return. */
3725     if (dont_scroll || input_available())
3726 	return;
3727 #endif
3728 
3729 #ifdef FEAT_RIGHTLEFT
3730     if (sb->wp == NULL && curwin->w_p_rl)
3731     {
3732 	value = sb->max + 1 - sb->size - value;
3733 	if (value < 0)
3734 	    value = 0;
3735     }
3736 #endif
3737 
3738     if (sb->wp != NULL)		/* vertical scrollbar */
3739     {
3740 	sb_num = 0;
3741 #ifdef FEAT_WINDOWS
3742 	for (wp = firstwin; wp != sb->wp && wp != NULL; wp = wp->w_next)
3743 	    sb_num++;
3744 	if (wp == NULL)
3745 	    return;
3746 #else
3747 	if (sb->wp != curwin)
3748 	    return;
3749 #endif
3750 
3751 #ifdef USE_ON_FLY_SCROLL
3752 	current_scrollbar = sb_num;
3753 	scrollbar_value = value;
3754 	if (State & NORMAL)
3755 	{
3756 	    gui_do_scroll();
3757 	    setcursor();
3758 	}
3759 	else if (State & INSERT)
3760 	{
3761 	    ins_scroll();
3762 	    setcursor();
3763 	}
3764 	else if (State & CMDLINE)
3765 	{
3766 	    if (msg_scrolled == 0)
3767 	    {
3768 		gui_do_scroll();
3769 		redrawcmdline();
3770 	    }
3771 	}
3772 # ifdef FEAT_FOLDING
3773 	/* Value may have been changed for closed fold. */
3774 	sb->value = sb->wp->w_topline - 1;
3775 # endif
3776 
3777 	/* When dragging one scrollbar and there is another one at the other
3778 	 * side move the thumb of that one too. */
3779 	if (gui.which_scrollbars[SBAR_RIGHT] && gui.which_scrollbars[SBAR_LEFT])
3780 	    gui_mch_set_scrollbar_thumb(
3781 		    &sb->wp->w_scrollbars[
3782 			    sb == &sb->wp->w_scrollbars[SBAR_RIGHT]
3783 						    ? SBAR_LEFT : SBAR_RIGHT],
3784 		    sb->value, sb->size, sb->max);
3785 
3786 #else
3787 	bytes[0] = CSI;
3788 	bytes[1] = KS_VER_SCROLLBAR;
3789 	bytes[2] = KE_FILLER;
3790 	bytes[3] = (char_u)sb_num;
3791 	byte_count = 4;
3792 #endif
3793     }
3794     else
3795     {
3796 #ifdef USE_ON_FLY_SCROLL
3797 	scrollbar_value = value;
3798 
3799 	if (State & NORMAL)
3800 	    gui_do_horiz_scroll();
3801 	else if (State & INSERT)
3802 	    ins_horscroll();
3803 	else if (State & CMDLINE)
3804 	{
3805 	    if (msg_scrolled == 0)
3806 	    {
3807 		gui_do_horiz_scroll();
3808 		redrawcmdline();
3809 	    }
3810 	}
3811 	if (old_leftcol != curwin->w_leftcol)
3812 	{
3813 	    updateWindow(curwin);   /* update window, status and cmdline */
3814 	    setcursor();
3815 	}
3816 #else
3817 	bytes[0] = CSI;
3818 	bytes[1] = KS_HOR_SCROLLBAR;
3819 	bytes[2] = KE_FILLER;
3820 	byte_count = 3;
3821 #endif
3822     }
3823 
3824 #ifdef USE_ON_FLY_SCROLL
3825 # ifdef FEAT_SCROLLBIND
3826     /*
3827      * synchronize other windows, as necessary according to 'scrollbind'
3828      */
3829     if (curwin->w_p_scb
3830 	    && ((sb->wp == NULL && curwin->w_leftcol != old_leftcol)
3831 		|| (sb->wp == curwin && (curwin->w_topline != old_topline
3832 #  ifdef FEAT_DIFF
3833 					   || curwin->w_topfill != old_topfill
3834 #  endif
3835 			))))
3836     {
3837 	do_check_scrollbind(TRUE);
3838 	/* need to update the window right here */
3839 	for (wp = firstwin; wp != NULL; wp = wp->w_next)
3840 	    if (wp->w_redr_type > 0)
3841 		updateWindow(wp);
3842 	setcursor();
3843     }
3844 # endif
3845     out_flush();
3846     gui_update_cursor(FALSE, TRUE);
3847 #else
3848     add_to_input_buf(bytes, byte_count);
3849     add_long_to_buf((long_u)value, bytes);
3850     add_to_input_buf_csi(bytes, sizeof(long_u));
3851 #endif
3852 }
3853 
3854 /*
3855  * Scrollbar stuff:
3856  */
3857 
3858     void
3859 gui_update_scrollbars(force)
3860     int		force;	    /* Force all scrollbars to get updated */
3861 {
3862     win_T	*wp;
3863     scrollbar_T	*sb;
3864     long	val, size, max;		/* need 32 bits here */
3865     int		which_sb;
3866     int		h, y;
3867 #ifdef FEAT_VERTSPLIT
3868     static win_T *prev_curwin = NULL;
3869 #endif
3870 
3871     /* Update the horizontal scrollbar */
3872     gui_update_horiz_scrollbar(force);
3873 
3874 #ifndef WIN3264
3875     /* Return straight away if there is neither a left nor right scrollbar.
3876      * On MS-Windows this is required anyway for scrollwheel messages. */
3877     if (!gui.which_scrollbars[SBAR_LEFT] && !gui.which_scrollbars[SBAR_RIGHT])
3878 	return;
3879 #endif
3880 
3881     /*
3882      * Don't want to update a scrollbar while we're dragging it.  But if we
3883      * have both a left and right scrollbar, and we drag one of them, we still
3884      * need to update the other one.
3885      */
3886     if (!force && (gui.dragged_sb == SBAR_LEFT || gui.dragged_sb == SBAR_RIGHT)
3887 	    && gui.which_scrollbars[SBAR_LEFT]
3888 	    && gui.which_scrollbars[SBAR_RIGHT])
3889     {
3890 	/*
3891 	 * If we have two scrollbars and one of them is being dragged, just
3892 	 * copy the scrollbar position from the dragged one to the other one.
3893 	 */
3894 	which_sb = SBAR_LEFT + SBAR_RIGHT - gui.dragged_sb;
3895 	if (gui.dragged_wp != NULL)
3896 	    gui_mch_set_scrollbar_thumb(
3897 		    &gui.dragged_wp->w_scrollbars[which_sb],
3898 		    gui.dragged_wp->w_scrollbars[0].value,
3899 		    gui.dragged_wp->w_scrollbars[0].size,
3900 		    gui.dragged_wp->w_scrollbars[0].max);
3901     }
3902 
3903     /* avoid that moving components around generates events */
3904     ++hold_gui_events;
3905 
3906     for (wp = firstwin; wp != NULL; wp = W_NEXT(wp))
3907     {
3908 	if (wp->w_buffer == NULL)	/* just in case */
3909 	    continue;
3910 	/* Skip a scrollbar that is being dragged. */
3911 	if (!force && (gui.dragged_sb == SBAR_LEFT
3912 					     || gui.dragged_sb == SBAR_RIGHT)
3913 		&& gui.dragged_wp == wp)
3914 	    continue;
3915 
3916 #ifdef SCROLL_PAST_END
3917 	max = wp->w_buffer->b_ml.ml_line_count - 1;
3918 #else
3919 	max = wp->w_buffer->b_ml.ml_line_count + wp->w_height - 2;
3920 #endif
3921 	if (max < 0)			/* empty buffer */
3922 	    max = 0;
3923 	val = wp->w_topline - 1;
3924 	size = wp->w_height;
3925 #ifdef SCROLL_PAST_END
3926 	if (val > max)			/* just in case */
3927 	    val = max;
3928 #else
3929 	if (size > max + 1)		/* just in case */
3930 	    size = max + 1;
3931 	if (val > max - size + 1)
3932 	    val = max - size + 1;
3933 #endif
3934 	if (val < 0)			/* minimal value is 0 */
3935 	    val = 0;
3936 
3937 	/*
3938 	 * Scrollbar at index 0 (the left one) contains all the information.
3939 	 * It would be the same info for left and right so we just store it for
3940 	 * one of them.
3941 	 */
3942 	sb = &wp->w_scrollbars[0];
3943 
3944 	/*
3945 	 * Note: no check for valid w_botline.	If it's not valid the
3946 	 * scrollbars will be updated later anyway.
3947 	 */
3948 	if (size < 1 || wp->w_botline - 2 > max)
3949 	{
3950 	    /*
3951 	     * This can happen during changing files.  Just don't update the
3952 	     * scrollbar for now.
3953 	     */
3954 	    sb->height = 0;	    /* Force update next time */
3955 	    if (gui.which_scrollbars[SBAR_LEFT])
3956 		gui_do_scrollbar(wp, SBAR_LEFT, FALSE);
3957 	    if (gui.which_scrollbars[SBAR_RIGHT])
3958 		gui_do_scrollbar(wp, SBAR_RIGHT, FALSE);
3959 	    continue;
3960 	}
3961 	if (force || sb->height != wp->w_height
3962 #ifdef FEAT_WINDOWS
3963 	    || sb->top != wp->w_winrow
3964 	    || sb->status_height != wp->w_status_height
3965 # ifdef FEAT_VERTSPLIT
3966 	    || sb->width != wp->w_width
3967 	    || prev_curwin != curwin
3968 # endif
3969 #endif
3970 	    )
3971 	{
3972 	    /* Height, width or position of scrollbar has changed.  For
3973 	     * vertical split: curwin changed. */
3974 	    sb->height = wp->w_height;
3975 #ifdef FEAT_WINDOWS
3976 	    sb->top = wp->w_winrow;
3977 	    sb->status_height = wp->w_status_height;
3978 # ifdef FEAT_VERTSPLIT
3979 	    sb->width = wp->w_width;
3980 # endif
3981 #endif
3982 
3983 	    /* Calculate height and position in pixels */
3984 	    h = (sb->height + sb->status_height) * gui.char_height;
3985 	    y = sb->top * gui.char_height + gui.border_offset;
3986 #if defined(FEAT_MENU) && !defined(FEAT_GUI_GTK) && !defined(FEAT_GUI_MOTIF) && !defined(FEAT_GUI_PHOTON)
3987 	    if (gui.menu_is_active)
3988 		y += gui.menu_height;
3989 #endif
3990 
3991 #if defined(FEAT_TOOLBAR) && (defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_ATHENA))
3992 	    if (vim_strchr(p_go, GO_TOOLBAR) != NULL)
3993 # ifdef FEAT_GUI_ATHENA
3994 		y += gui.toolbar_height;
3995 # else
3996 #  ifdef FEAT_GUI_MSWIN
3997 		y += TOOLBAR_BUTTON_HEIGHT + TOOLBAR_BORDER_HEIGHT;
3998 #  endif
3999 # endif
4000 #endif
4001 
4002 #if defined(FEAT_GUI_TABLINE) && defined(FEAT_GUI_MSWIN)
4003 	    if (gui_has_tabline())
4004 		y += gui.tabline_height;
4005 #endif
4006 
4007 #ifdef FEAT_WINDOWS
4008 	    if (wp->w_winrow == 0)
4009 #endif
4010 	    {
4011 		/* Height of top scrollbar includes width of top border */
4012 		h += gui.border_offset;
4013 		y -= gui.border_offset;
4014 	    }
4015 	    if (gui.which_scrollbars[SBAR_LEFT])
4016 	    {
4017 		gui_mch_set_scrollbar_pos(&wp->w_scrollbars[SBAR_LEFT],
4018 					  gui.left_sbar_x, y,
4019 					  gui.scrollbar_width, h);
4020 		gui_do_scrollbar(wp, SBAR_LEFT, TRUE);
4021 	    }
4022 	    if (gui.which_scrollbars[SBAR_RIGHT])
4023 	    {
4024 		gui_mch_set_scrollbar_pos(&wp->w_scrollbars[SBAR_RIGHT],
4025 					  gui.right_sbar_x, y,
4026 					  gui.scrollbar_width, h);
4027 		gui_do_scrollbar(wp, SBAR_RIGHT, TRUE);
4028 	    }
4029 	}
4030 
4031 	/* Reduce the number of calls to gui_mch_set_scrollbar_thumb() by
4032 	 * checking if the thumb moved at least a pixel.  Only do this for
4033 	 * Athena, most other GUIs require the update anyway to make the
4034 	 * arrows work. */
4035 #ifdef FEAT_GUI_ATHENA
4036 	if (max == 0)
4037 	    y = 0;
4038 	else
4039 	    y = (val * (sb->height + 2) * gui.char_height + max / 2) / max;
4040 	if (force || sb->pixval != y || sb->size != size || sb->max != max)
4041 #else
4042 	if (force || sb->value != val || sb->size != size || sb->max != max)
4043 #endif
4044 	{
4045 	    /* Thumb of scrollbar has moved */
4046 	    sb->value = val;
4047 #ifdef FEAT_GUI_ATHENA
4048 	    sb->pixval = y;
4049 #endif
4050 	    sb->size = size;
4051 	    sb->max = max;
4052 	    if (gui.which_scrollbars[SBAR_LEFT]
4053 		    && (gui.dragged_sb != SBAR_LEFT || gui.dragged_wp != wp))
4054 		gui_mch_set_scrollbar_thumb(&wp->w_scrollbars[SBAR_LEFT],
4055 					    val, size, max);
4056 	    if (gui.which_scrollbars[SBAR_RIGHT]
4057 		    && (gui.dragged_sb != SBAR_RIGHT || gui.dragged_wp != wp))
4058 		gui_mch_set_scrollbar_thumb(&wp->w_scrollbars[SBAR_RIGHT],
4059 					    val, size, max);
4060 	}
4061     }
4062 #ifdef FEAT_VERTSPLIT
4063     prev_curwin = curwin;
4064 #endif
4065     --hold_gui_events;
4066 }
4067 
4068 /*
4069  * Enable or disable a scrollbar.
4070  * Check for scrollbars for vertically split windows which are not enabled
4071  * sometimes.
4072  */
4073     static void
4074 gui_do_scrollbar(wp, which, enable)
4075     win_T	*wp;
4076     int		which;	    /* SBAR_LEFT or SBAR_RIGHT */
4077     int		enable;	    /* TRUE to enable scrollbar */
4078 {
4079 #ifdef FEAT_VERTSPLIT
4080     int		midcol = curwin->w_wincol + curwin->w_width / 2;
4081     int		has_midcol = (wp->w_wincol <= midcol
4082 				     && wp->w_wincol + wp->w_width >= midcol);
4083 
4084     /* Only enable scrollbars that contain the middle column of the current
4085      * window. */
4086     if (gui.which_scrollbars[SBAR_RIGHT] != gui.which_scrollbars[SBAR_LEFT])
4087     {
4088 	/* Scrollbars only on one side.  Don't enable scrollbars that don't
4089 	 * contain the middle column of the current window. */
4090 	if (!has_midcol)
4091 	    enable = FALSE;
4092     }
4093     else
4094     {
4095 	/* Scrollbars on both sides.  Don't enable scrollbars that neither
4096 	 * contain the middle column of the current window nor are on the far
4097 	 * side. */
4098 	if (midcol > Columns / 2)
4099 	{
4100 	    if (which == SBAR_LEFT ? wp->w_wincol != 0 : !has_midcol)
4101 		enable = FALSE;
4102 	}
4103 	else
4104 	{
4105 	    if (which == SBAR_RIGHT ? wp->w_wincol + wp->w_width != Columns
4106 								: !has_midcol)
4107 		enable = FALSE;
4108 	}
4109     }
4110 #endif
4111     gui_mch_enable_scrollbar(&wp->w_scrollbars[which], enable);
4112 }
4113 
4114 /*
4115  * Scroll a window according to the values set in the globals current_scrollbar
4116  * and scrollbar_value.  Return TRUE if the cursor in the current window moved
4117  * or FALSE otherwise.
4118  */
4119     int
4120 gui_do_scroll()
4121 {
4122     win_T	*wp, *save_wp;
4123     int		i;
4124     long	nlines;
4125     pos_T	old_cursor;
4126     linenr_T	old_topline;
4127 #ifdef FEAT_DIFF
4128     int		old_topfill;
4129 #endif
4130 
4131     for (wp = firstwin, i = 0; i < current_scrollbar; wp = W_NEXT(wp), i++)
4132 	if (wp == NULL)
4133 	    break;
4134     if (wp == NULL)
4135 	/* Couldn't find window */
4136 	return FALSE;
4137 
4138     /*
4139      * Compute number of lines to scroll.  If zero, nothing to do.
4140      */
4141     nlines = (long)scrollbar_value + 1 - (long)wp->w_topline;
4142     if (nlines == 0)
4143 	return FALSE;
4144 
4145     save_wp = curwin;
4146     old_topline = wp->w_topline;
4147 #ifdef FEAT_DIFF
4148     old_topfill = wp->w_topfill;
4149 #endif
4150     old_cursor = wp->w_cursor;
4151     curwin = wp;
4152     curbuf = wp->w_buffer;
4153     if (nlines < 0)
4154 	scrolldown(-nlines, gui.dragged_wp == NULL);
4155     else
4156 	scrollup(nlines, gui.dragged_wp == NULL);
4157     /* Reset dragged_wp after using it.  "dragged_sb" will have been reset for
4158      * the mouse-up event already, but we still want it to behave like when
4159      * dragging.  But not the next click in an arrow. */
4160     if (gui.dragged_sb == SBAR_NONE)
4161 	gui.dragged_wp = NULL;
4162 
4163     if (old_topline != wp->w_topline
4164 #ifdef FEAT_DIFF
4165 	    || old_topfill != wp->w_topfill
4166 #endif
4167 	    )
4168     {
4169 	if (p_so != 0)
4170 	{
4171 	    cursor_correct();		/* fix window for 'so' */
4172 	    update_topline();		/* avoid up/down jump */
4173 	}
4174 	if (old_cursor.lnum != wp->w_cursor.lnum)
4175 	    coladvance(wp->w_curswant);
4176 #ifdef FEAT_SCROLLBIND
4177 	wp->w_scbind_pos = wp->w_topline;
4178 #endif
4179     }
4180 
4181     /* Make sure wp->w_leftcol and wp->w_skipcol are correct. */
4182     validate_cursor();
4183 
4184     curwin = save_wp;
4185     curbuf = save_wp->w_buffer;
4186 
4187     /*
4188      * Don't call updateWindow() when nothing has changed (it will overwrite
4189      * the status line!).
4190      */
4191     if (old_topline != wp->w_topline
4192 	    || wp->w_redr_type != 0
4193 #ifdef FEAT_DIFF
4194 	    || old_topfill != wp->w_topfill
4195 #endif
4196 	    )
4197     {
4198 	redraw_win_later(wp, VALID);
4199 	updateWindow(wp);   /* update window, status line, and cmdline */
4200     }
4201 
4202     return (wp == curwin && !equalpos(curwin->w_cursor, old_cursor));
4203 }
4204 
4205 
4206 /*
4207  * Horizontal scrollbar stuff:
4208  */
4209 
4210 /*
4211  * Return length of line "lnum" for horizontal scrolling.
4212  */
4213     static colnr_T
4214 scroll_line_len(lnum)
4215     linenr_T	lnum;
4216 {
4217     char_u	*p;
4218     colnr_T	col;
4219     int		w;
4220 
4221     p = ml_get(lnum);
4222     col = 0;
4223     if (*p != NUL)
4224 	for (;;)
4225 	{
4226 	    w = chartabsize(p, col);
4227 	    mb_ptr_adv(p);
4228 	    if (*p == NUL)		/* don't count the last character */
4229 		break;
4230 	    col += w;
4231 	}
4232     return col;
4233 }
4234 
4235 /* Remember which line is currently the longest, so that we don't have to
4236  * search for it when scrolling horizontally. */
4237 static linenr_T longest_lnum = 0;
4238 
4239     static void
4240 gui_update_horiz_scrollbar(force)
4241     int		force;
4242 {
4243     long	value, size, max;	/* need 32 bit ints here */
4244 
4245     if (!gui.which_scrollbars[SBAR_BOTTOM])
4246 	return;
4247 
4248     if (!force && gui.dragged_sb == SBAR_BOTTOM)
4249 	return;
4250 
4251     if (!force && curwin->w_p_wrap && gui.prev_wrap)
4252 	return;
4253 
4254     /*
4255      * It is possible for the cursor to be invalid if we're in the middle of
4256      * something (like changing files).  If so, don't do anything for now.
4257      */
4258     if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
4259     {
4260 	gui.bottom_sbar.value = -1;
4261 	return;
4262     }
4263 
4264     size = W_WIDTH(curwin);
4265     if (curwin->w_p_wrap)
4266     {
4267 	value = 0;
4268 #ifdef SCROLL_PAST_END
4269 	max = 0;
4270 #else
4271 	max = W_WIDTH(curwin) - 1;
4272 #endif
4273     }
4274     else
4275     {
4276 	value = curwin->w_leftcol;
4277 
4278 	/* Calculate maximum for horizontal scrollbar.  Check for reasonable
4279 	 * line numbers, topline and botline can be invalid when displaying is
4280 	 * postponed. */
4281 	if (vim_strchr(p_go, GO_HORSCROLL) == NULL
4282 		&& curwin->w_topline <= curwin->w_cursor.lnum
4283 		&& curwin->w_botline > curwin->w_cursor.lnum
4284 		&& curwin->w_botline <= curbuf->b_ml.ml_line_count + 1)
4285 	{
4286 	    linenr_T	lnum;
4287 	    colnr_T	n;
4288 
4289 	    /* Use maximum of all visible lines.  Remember the lnum of the
4290 	     * longest line, clostest to the cursor line.  Used when scrolling
4291 	     * below. */
4292 	    max = 0;
4293 	    for (lnum = curwin->w_topline; lnum < curwin->w_botline; ++lnum)
4294 	    {
4295 		n = scroll_line_len(lnum);
4296 		if (n > (colnr_T)max)
4297 		{
4298 		    max = n;
4299 		    longest_lnum = lnum;
4300 		}
4301 		else if (n == (colnr_T)max
4302 			&& abs((int)(lnum - curwin->w_cursor.lnum))
4303 			   < abs((int)(longest_lnum - curwin->w_cursor.lnum)))
4304 		    longest_lnum = lnum;
4305 	    }
4306 	}
4307 	else
4308 	    /* Use cursor line only. */
4309 	    max = scroll_line_len(curwin->w_cursor.lnum);
4310 #ifdef FEAT_VIRTUALEDIT
4311 	if (virtual_active())
4312 	{
4313 	    /* May move the cursor even further to the right. */
4314 	    if (curwin->w_virtcol >= (colnr_T)max)
4315 		max = curwin->w_virtcol;
4316 	}
4317 #endif
4318 
4319 #ifndef SCROLL_PAST_END
4320 	max += W_WIDTH(curwin) - 1;
4321 #endif
4322 	/* The line number isn't scrolled, thus there is less space when
4323 	 * 'number' is set (also for 'foldcolumn'). */
4324 	size -= curwin_col_off();
4325 #ifndef SCROLL_PAST_END
4326 	max -= curwin_col_off();
4327 #endif
4328     }
4329 
4330 #ifndef SCROLL_PAST_END
4331     if (value > max - size + 1)
4332 	value = max - size + 1;	    /* limit the value to allowable range */
4333 #endif
4334 
4335 #ifdef FEAT_RIGHTLEFT
4336     if (curwin->w_p_rl)
4337     {
4338 	value = max + 1 - size - value;
4339 	if (value < 0)
4340 	{
4341 	    size += value;
4342 	    value = 0;
4343 	}
4344     }
4345 #endif
4346     if (!force && value == gui.bottom_sbar.value && size == gui.bottom_sbar.size
4347 						&& max == gui.bottom_sbar.max)
4348 	return;
4349 
4350     gui.bottom_sbar.value = value;
4351     gui.bottom_sbar.size = size;
4352     gui.bottom_sbar.max = max;
4353     gui.prev_wrap = curwin->w_p_wrap;
4354 
4355     gui_mch_set_scrollbar_thumb(&gui.bottom_sbar, value, size, max);
4356 }
4357 
4358 /*
4359  * Do a horizontal scroll.  Return TRUE if the cursor moved, FALSE otherwise.
4360  */
4361     int
4362 gui_do_horiz_scroll()
4363 {
4364     /* no wrapping, no scrolling */
4365     if (curwin->w_p_wrap)
4366 	return FALSE;
4367 
4368     if (curwin->w_leftcol == scrollbar_value)
4369 	return FALSE;
4370 
4371     curwin->w_leftcol = (colnr_T)scrollbar_value;
4372 
4373     /* When the line of the cursor is too short, move the cursor to the
4374      * longest visible line.  Do a sanity check on "longest_lnum", just in
4375      * case. */
4376     if (vim_strchr(p_go, GO_HORSCROLL) == NULL
4377 	    && longest_lnum >= curwin->w_topline
4378 	    && longest_lnum < curwin->w_botline
4379 	    && !virtual_active())
4380     {
4381 	if (scrollbar_value > scroll_line_len(curwin->w_cursor.lnum))
4382 	{
4383 	    curwin->w_cursor.lnum = longest_lnum;
4384 	    curwin->w_cursor.col = 0;
4385 	}
4386     }
4387 
4388     return leftcol_changed();
4389 }
4390 
4391 /*
4392  * Check that none of the colors are the same as the background color
4393  */
4394     void
4395 gui_check_colors()
4396 {
4397     if (gui.norm_pixel == gui.back_pixel || gui.norm_pixel == INVALCOLOR)
4398     {
4399 	gui_set_bg_color((char_u *)"White");
4400 	if (gui.norm_pixel == gui.back_pixel || gui.norm_pixel == INVALCOLOR)
4401 	    gui_set_fg_color((char_u *)"Black");
4402     }
4403 }
4404 
4405     static void
4406 gui_set_fg_color(name)
4407     char_u	*name;
4408 {
4409     gui.norm_pixel = gui_get_color(name);
4410     hl_set_fg_color_name(vim_strsave(name));
4411 }
4412 
4413     static void
4414 gui_set_bg_color(name)
4415     char_u	*name;
4416 {
4417     gui.back_pixel = gui_get_color(name);
4418     hl_set_bg_color_name(vim_strsave(name));
4419 }
4420 
4421 /*
4422  * Allocate a color by name.
4423  * Returns INVALCOLOR and gives an error message when failed.
4424  */
4425     guicolor_T
4426 gui_get_color(name)
4427     char_u	*name;
4428 {
4429     guicolor_T	t;
4430 
4431     if (*name == NUL)
4432 	return INVALCOLOR;
4433     t = gui_mch_get_color(name);
4434 
4435     if (t == INVALCOLOR
4436 #if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
4437 	    && gui.in_use
4438 #endif
4439 	    )
4440 	EMSG2(_("E254: Cannot allocate color %s"), name);
4441     return t;
4442 }
4443 
4444 /*
4445  * Return the grey value of a color (range 0-255).
4446  */
4447     int
4448 gui_get_lightness(pixel)
4449     guicolor_T	pixel;
4450 {
4451     long_u	rgb = gui_mch_get_rgb(pixel);
4452 
4453     return  (int)(  (((rgb >> 16) & 0xff) * 299)
4454 	           + (((rgb >> 8) & 0xff) * 587)
4455 	           +  ((rgb	  & 0xff) * 114)) / 1000;
4456 }
4457 
4458 #if defined(FEAT_GUI_X11) || defined(PROTO)
4459     void
4460 gui_new_scrollbar_colors()
4461 {
4462     win_T	*wp;
4463 
4464     /* Nothing to do if GUI hasn't started yet. */
4465     if (!gui.in_use)
4466 	return;
4467 
4468     FOR_ALL_WINDOWS(wp)
4469     {
4470 	gui_mch_set_scrollbar_colors(&(wp->w_scrollbars[SBAR_LEFT]));
4471 	gui_mch_set_scrollbar_colors(&(wp->w_scrollbars[SBAR_RIGHT]));
4472     }
4473     gui_mch_set_scrollbar_colors(&gui.bottom_sbar);
4474 }
4475 #endif
4476 
4477 /*
4478  * Call this when focus has changed.
4479  */
4480     void
4481 gui_focus_change(in_focus)
4482     int		in_focus;
4483 {
4484 /*
4485  * Skip this code to avoid drawing the cursor when debugging and switching
4486  * between the debugger window and gvim.
4487  */
4488 #if 1
4489     gui.in_focus = in_focus;
4490     out_flush();		/* make sure output has been written */
4491     gui_update_cursor(TRUE, FALSE);
4492 
4493 # ifdef FEAT_XIM
4494     xim_set_focus(in_focus);
4495 # endif
4496 
4497     ui_focus_change(in_focus);
4498 #endif
4499 }
4500 
4501 /*
4502  * Called when the mouse moved (but not when dragging).
4503  */
4504     void
4505 gui_mouse_moved(x, y)
4506     int		x;
4507     int		y;
4508 {
4509     win_T	*wp;
4510     char_u	st[6];
4511 
4512     /* Ignore this while still starting up. */
4513     if (!gui.in_use || gui.starting)
4514 	return;
4515 
4516 #ifdef FEAT_MOUSESHAPE
4517     /* Get window pointer, and update mouse shape as well. */
4518     wp = xy2win(x, y);
4519 #endif
4520 
4521     /* Only handle this when 'mousefocus' set and ... */
4522     if (p_mousef
4523 	    && !hold_gui_events		/* not holding events */
4524 	    && (State & (NORMAL|INSERT))/* Normal/Visual/Insert mode */
4525 	    && State != HITRETURN	/* but not hit-return prompt */
4526 	    && msg_scrolled == 0	/* no scrolled message */
4527 	    && !need_mouse_correct	/* not moving the pointer */
4528 	    && gui.in_focus)		/* gvim in focus */
4529     {
4530 	/* Don't move the mouse when it's left or right of the Vim window */
4531 	if (x < 0 || x > Columns * gui.char_width)
4532 	    return;
4533 #ifndef FEAT_MOUSESHAPE
4534 	wp = xy2win(x, y);
4535 #endif
4536 	if (wp == curwin || wp == NULL)
4537 	    return;	/* still in the same old window, or none at all */
4538 
4539 	/*
4540 	 * format a mouse click on status line input
4541 	 * ala gui_send_mouse_event(0, x, y, 0, 0);
4542 	 * Trick: Use a column number -1, so that get_pseudo_mouse_code() will
4543 	 * generate a K_LEFTMOUSE_NM key code.
4544 	 */
4545 	if (finish_op)
4546 	{
4547 	    /* abort the current operator first */
4548 	    st[0] = ESC;
4549 	    add_to_input_buf(st, 1);
4550 	}
4551 	st[0] = CSI;
4552 	st[1] = KS_MOUSE;
4553 	st[2] = KE_FILLER;
4554 	st[3] = (char_u)MOUSE_LEFT;
4555 	fill_mouse_coord(st + 4,
4556 #ifdef FEAT_VERTSPLIT
4557 		wp->w_wincol == 0 ? -1 : wp->w_wincol + MOUSE_COLOFF,
4558 #else
4559 		-1,
4560 #endif
4561 		wp->w_height + W_WINROW(wp));
4562 
4563 	add_to_input_buf(st, 8);
4564 	st[3] = (char_u)MOUSE_RELEASE;
4565 	add_to_input_buf(st, 8);
4566 #ifdef FEAT_GUI_GTK
4567 	/* Need to wake up the main loop */
4568 	if (gtk_main_level() > 0)
4569 	    gtk_main_quit();
4570 #endif
4571     }
4572 }
4573 
4574 /*
4575  * Called when mouse should be moved to window with focus.
4576  */
4577     void
4578 gui_mouse_correct()
4579 {
4580     int		x, y;
4581     win_T	*wp = NULL;
4582 
4583     need_mouse_correct = FALSE;
4584 
4585     if (!(gui.in_use && p_mousef))
4586 	return;
4587 
4588     gui_mch_getmouse(&x, &y);
4589     /* Don't move the mouse when it's left or right of the Vim window */
4590     if (x < 0 || x > Columns * gui.char_width)
4591 	return;
4592     if (y >= 0)
4593 	wp = xy2win(x, y);
4594     if (wp != curwin && wp != NULL)	/* If in other than current window */
4595     {
4596 	validate_cline_row();
4597 	gui_mch_setmouse((int)W_ENDCOL(curwin) * gui.char_width - 3,
4598 		(W_WINROW(curwin) + curwin->w_wrow) * gui.char_height
4599 						     + (gui.char_height) / 2);
4600     }
4601 }
4602 
4603 /*
4604  * Find window where the mouse pointer "y" coordinate is in.
4605  */
4606 /*ARGSUSED*/
4607     static win_T *
4608 xy2win(x, y)
4609     int		x;
4610     int		y;
4611 {
4612 #ifdef FEAT_WINDOWS
4613     int		row;
4614     int		col;
4615     win_T	*wp;
4616 
4617     row = Y_2_ROW(y);
4618     col = X_2_COL(x);
4619     if (row < 0 || col < 0)		/* before first window */
4620 	return NULL;
4621     wp = mouse_find_win(&row, &col);
4622 # ifdef FEAT_MOUSESHAPE
4623     if (State == HITRETURN || State == ASKMORE)
4624     {
4625 	if (Y_2_ROW(y) >= msg_row)
4626 	    update_mouseshape(SHAPE_IDX_MOREL);
4627 	else
4628 	    update_mouseshape(SHAPE_IDX_MORE);
4629     }
4630     else if (row > wp->w_height)	/* below status line */
4631 	update_mouseshape(SHAPE_IDX_CLINE);
4632 #  ifdef FEAT_VERTSPLIT
4633     else if (!(State & CMDLINE) && W_VSEP_WIDTH(wp) > 0 && col == wp->w_width
4634 	    && (row != wp->w_height || !stl_connected(wp)) && msg_scrolled == 0)
4635 	update_mouseshape(SHAPE_IDX_VSEP);
4636 #  endif
4637     else if (!(State & CMDLINE) && W_STATUS_HEIGHT(wp) > 0
4638 				  && row == wp->w_height && msg_scrolled == 0)
4639 	update_mouseshape(SHAPE_IDX_STATUS);
4640     else
4641 	update_mouseshape(-2);
4642 # endif
4643     return wp;
4644 #else
4645     return firstwin;
4646 #endif
4647 }
4648 
4649 /*
4650  * ":gui" and ":gvim": Change from the terminal version to the GUI version.
4651  * File names may be given to redefine the args list.
4652  */
4653     void
4654 ex_gui(eap)
4655     exarg_T	*eap;
4656 {
4657     char_u	*arg = eap->arg;
4658 
4659     /*
4660      * Check for "-f" argument: foreground, don't fork.
4661      * Also don't fork when started with "gvim -f".
4662      * Do fork when using "gui -b".
4663      */
4664     if (arg[0] == '-'
4665 	    && (arg[1] == 'f' || arg[1] == 'b')
4666 	    && (arg[2] == NUL || vim_iswhite(arg[2])))
4667     {
4668 	gui.dofork = (arg[1] == 'b');
4669 	eap->arg = skipwhite(eap->arg + 2);
4670     }
4671     if (!gui.in_use)
4672     {
4673 	/* Clear the command.  Needed for when forking+exiting, to avoid part
4674 	 * of the argument ending up after the shell prompt. */
4675 	msg_clr_eos_force();
4676 	gui_start();
4677     }
4678     if (!ends_excmd(*eap->arg))
4679 	ex_next(eap);
4680 }
4681 
4682 #if ((defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK) || defined(FEAT_GUI_W32) \
4683 	|| defined(FEAT_GUI_PHOTON)) && defined(FEAT_TOOLBAR)) || defined(PROTO)
4684 /*
4685  * This is shared between Athena, Motif and GTK.
4686  */
4687 static void gfp_setname __ARGS((char_u *fname, void *cookie));
4688 
4689 /*
4690  * Callback function for do_in_runtimepath().
4691  */
4692     static void
4693 gfp_setname(fname, cookie)
4694     char_u	*fname;
4695     void	*cookie;
4696 {
4697     char_u	*gfp_buffer = cookie;
4698 
4699     if (STRLEN(fname) >= MAXPATHL)
4700 	*gfp_buffer = NUL;
4701     else
4702 	STRCPY(gfp_buffer, fname);
4703 }
4704 
4705 /*
4706  * Find the path of bitmap "name" with extension "ext" in 'runtimepath'.
4707  * Return FAIL for failure and OK if buffer[MAXPATHL] contains the result.
4708  */
4709     int
4710 gui_find_bitmap(name, buffer, ext)
4711     char_u	*name;
4712     char_u	*buffer;
4713     char	*ext;
4714 {
4715     if (STRLEN(name) > MAXPATHL - 14)
4716 	return FAIL;
4717     vim_snprintf((char *)buffer, MAXPATHL, "bitmaps/%s.%s", name, ext);
4718     if (do_in_runtimepath(buffer, FALSE, gfp_setname, buffer) == FAIL
4719 							    || *buffer == NUL)
4720 	return FAIL;
4721     return OK;
4722 }
4723 
4724 # if !defined(HAVE_GTK2) || defined(PROTO)
4725 /*
4726  * Given the name of the "icon=" argument, try finding the bitmap file for the
4727  * icon.  If it is an absolute path name, use it as it is.  Otherwise append
4728  * "ext" and search for it in 'runtimepath'.
4729  * The result is put in "buffer[MAXPATHL]".  If something fails "buffer"
4730  * contains "name".
4731  */
4732     void
4733 gui_find_iconfile(name, buffer, ext)
4734     char_u	*name;
4735     char_u	*buffer;
4736     char	*ext;
4737 {
4738     char_u	buf[MAXPATHL + 1];
4739 
4740     expand_env(name, buffer, MAXPATHL);
4741     if (!mch_isFullName(buffer) && gui_find_bitmap(buffer, buf, ext) == OK)
4742 	STRCPY(buffer, buf);
4743 }
4744 # endif
4745 #endif
4746 
4747 #if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_X11) || defined(PROTO)
4748     void
4749 display_errors()
4750 {
4751     char_u	*p;
4752 
4753     if (isatty(2))
4754 	fflush(stderr);
4755     else if (error_ga.ga_data != NULL)
4756     {
4757 	/* avoid putting up a message box with blanks only */
4758 	for (p = (char_u *)error_ga.ga_data; *p != NUL; ++p)
4759 	    if (!isspace(*p))
4760 	    {
4761 		/* Truncate a very long message, it will go off-screen. */
4762 		if (STRLEN(p) > 2000)
4763 		    STRCPY(p + 2000 - 14, "...(truncated)");
4764 		(void)do_dialog(VIM_ERROR, (char_u *)_("Error"),
4765 					      p, (char_u *)_("&Ok"), 1, NULL);
4766 		break;
4767 	    }
4768 	ga_clear(&error_ga);
4769     }
4770 }
4771 #endif
4772 
4773 #if defined(NO_CONSOLE_INPUT) || defined(PROTO)
4774 /*
4775  * Return TRUE if still starting up and there is no place to enter text.
4776  * For GTK and X11 we check if stderr is not a tty, which means we were
4777  * (probably) started from the desktop.  Also check stdin, "vim >& file" does
4778  * allow typing on stdin.
4779  */
4780     int
4781 no_console_input()
4782 {
4783     return ((!gui.in_use || gui.starting)
4784 # ifndef NO_CONSOLE
4785 	    && !isatty(0) && !isatty(2)
4786 # endif
4787 	    );
4788 }
4789 #endif
4790 
4791 #if defined(FIND_REPLACE_DIALOG) || defined(FEAT_SUN_WORKSHOP) \
4792 	|| defined(PROTO)
4793 /*
4794  * Update the current window and the screen.
4795  */
4796     void
4797 gui_update_screen()
4798 {
4799     update_topline();
4800     validate_cursor();
4801     update_screen(0);	/* may need to update the screen */
4802     setcursor();
4803     out_flush();		/* make sure output has been written */
4804     gui_update_cursor(TRUE, FALSE);
4805     gui_mch_flush();
4806 }
4807 #endif
4808 
4809 #if defined(FIND_REPLACE_DIALOG) || defined(PROTO)
4810 static void concat_esc __ARGS((garray_T *gap, char_u *text, int what));
4811 
4812 /*
4813  * Get the text to use in a find/replace dialog.  Uses the last search pattern
4814  * if the argument is empty.
4815  * Returns an allocated string.
4816  */
4817     char_u *
4818 get_find_dialog_text(arg, wwordp, mcasep)
4819     char_u	*arg;
4820     int		*wwordp;	/* return: TRUE if \< \> found */
4821     int		*mcasep;	/* return: TRUE if \C found */
4822 {
4823     char_u	*text;
4824 
4825     if (*arg == NUL)
4826 	text = last_search_pat();
4827     else
4828 	text = arg;
4829     if (text != NULL)
4830     {
4831 	text = vim_strsave(text);
4832 	if (text != NULL)
4833 	{
4834 	    int len = (int)STRLEN(text);
4835 	    int i;
4836 
4837 	    /* Remove "\V" */
4838 	    if (len >= 2 && STRNCMP(text, "\\V", 2) == 0)
4839 	    {
4840 		mch_memmove(text, text + 2, (size_t)(len - 1));
4841 		len -= 2;
4842 	    }
4843 
4844 	    /* Recognize "\c" and "\C" and remove. */
4845 	    if (len >= 2 && *text == '\\' && (text[1] == 'c' || text[1] == 'C'))
4846 	    {
4847 		*mcasep = (text[1] == 'C');
4848 		mch_memmove(text, text + 2, (size_t)(len - 1));
4849 		len -= 2;
4850 	    }
4851 
4852 	    /* Recognize "\<text\>" and remove. */
4853 	    if (len >= 4
4854 		    && STRNCMP(text, "\\<", 2) == 0
4855 		    && STRNCMP(text + len - 2, "\\>", 2) == 0)
4856 	    {
4857 		*wwordp = TRUE;
4858 		mch_memmove(text, text + 2, (size_t)(len - 4));
4859 		text[len - 4] = NUL;
4860 	    }
4861 
4862 	    /* Recognize "\/" or "\?" and remove. */
4863 	    for (i = 0; i + 1 < len; ++i)
4864 		if (text[i] == '\\' && (text[i + 1] == '/'
4865 						       || text[i + 1] == '?'))
4866 		{
4867 		    mch_memmove(text + i, text + i + 1, (size_t)(len - i));
4868 		    --len;
4869 		}
4870 	}
4871     }
4872     return text;
4873 }
4874 
4875 /*
4876  * Concatenate "text" to grow array "gap", escaping "what" with a backslash.
4877  */
4878     static void
4879 concat_esc(gap, text, what)
4880     garray_T	*gap;
4881     char_u	*text;
4882     int		what;
4883 {
4884     while (*text != NUL)
4885     {
4886 #ifdef FEAT_MBYTE
4887 	int l = (*mb_ptr2len)(text);
4888 
4889 	if (l > 1)
4890 	{
4891 	    while (--l >= 0)
4892 		ga_append(gap, *text++);
4893 	    continue;
4894 	}
4895 #endif
4896 	if (*text == what)
4897 	    ga_append(gap, '\\');
4898 	ga_append(gap, *text);
4899 	++text;
4900     }
4901 }
4902 
4903 /*
4904  * Handle the press of a button in the find-replace dialog.
4905  * Return TRUE when something was added to the input buffer.
4906  */
4907     int
4908 gui_do_findrepl(flags, find_text, repl_text, down)
4909     int		flags;		/* one of FRD_REPLACE, FRD_FINDNEXT, etc. */
4910     char_u	*find_text;
4911     char_u	*repl_text;
4912     int		down;		/* Search downwards. */
4913 {
4914     garray_T	ga;
4915     int		i;
4916     int		type = (flags & FRD_TYPE_MASK);
4917     char_u	*p;
4918     regmatch_T	regmatch;
4919     int		save_did_emsg = did_emsg;
4920 
4921     ga_init2(&ga, 1, 100);
4922     if (type == FRD_REPLACEALL)
4923 	ga_concat(&ga, (char_u *)"%s/");
4924 
4925     ga_concat(&ga, (char_u *)"\\V");
4926     if (flags & FRD_MATCH_CASE)
4927 	ga_concat(&ga, (char_u *)"\\C");
4928     else
4929 	ga_concat(&ga, (char_u *)"\\c");
4930     if (flags & FRD_WHOLE_WORD)
4931 	ga_concat(&ga, (char_u *)"\\<");
4932     if (type == FRD_REPLACEALL || down)
4933 	concat_esc(&ga, find_text, '/');	/* escape slashes */
4934     else
4935 	concat_esc(&ga, find_text, '?');	/* escape '?' */
4936     if (flags & FRD_WHOLE_WORD)
4937 	ga_concat(&ga, (char_u *)"\\>");
4938 
4939     if (type == FRD_REPLACEALL)
4940     {
4941 	ga_concat(&ga, (char_u *)"/");
4942 						/* escape / and \ */
4943 	p = vim_strsave_escaped(repl_text, (char_u *)"/\\");
4944 	if (p != NULL)
4945 	    ga_concat(&ga, p);
4946 	vim_free(p);
4947 	ga_concat(&ga, (char_u *)"/g");
4948     }
4949     ga_append(&ga, NUL);
4950 
4951     if (type == FRD_REPLACE)
4952     {
4953 	/* Do the replacement when the text at the cursor matches.  Thus no
4954 	 * replacement is done if the cursor was moved! */
4955 	regmatch.regprog = vim_regcomp(ga.ga_data, RE_MAGIC + RE_STRING);
4956 	regmatch.rm_ic = 0;
4957 	if (regmatch.regprog != NULL)
4958 	{
4959 	    p = ml_get_cursor();
4960 	    if (vim_regexec_nl(&regmatch, p, (colnr_T)0)
4961 						   && regmatch.startp[0] == p)
4962 	    {
4963 		/* Clear the command line to remove any old "No match"
4964 		 * error. */
4965 		msg_end_prompt();
4966 
4967 		if (u_save_cursor() == OK)
4968 		{
4969 		    /* A button was pressed thus undo should be synced. */
4970 		    u_sync(FALSE);
4971 
4972 		    del_bytes((long)(regmatch.endp[0] - regmatch.startp[0]),
4973 								FALSE, FALSE);
4974 		    ins_str(repl_text);
4975 		}
4976 	    }
4977 	    else
4978 		MSG(_("No match at cursor, finding next"));
4979 	    vim_free(regmatch.regprog);
4980 	}
4981     }
4982 
4983     if (type == FRD_REPLACEALL)
4984     {
4985 	/* A button was pressed, thus undo should be synced. */
4986 	u_sync(FALSE);
4987 	do_cmdline_cmd(ga.ga_data);
4988     }
4989     else
4990     {
4991 	/* Search for the next match. */
4992 	i = msg_scroll;
4993 	do_search(NULL, down ? '/' : '?', ga.ga_data, 1L,
4994 						    SEARCH_MSG + SEARCH_MARK);
4995 	msg_scroll = i;	    /* don't let an error message set msg_scroll */
4996     }
4997 
4998     /* Don't want to pass did_emsg to other code, it may cause disabling
4999      * syntax HL if we were busy redrawing. */
5000     did_emsg = save_did_emsg;
5001 
5002     if (State & (NORMAL | INSERT))
5003     {
5004 	gui_update_screen();		/* update the screen */
5005 	msg_didout = 0;			/* overwrite any message */
5006 	need_wait_return = FALSE;	/* don't wait for return */
5007     }
5008 
5009     vim_free(ga.ga_data);
5010     return (ga.ga_len > 0);
5011 }
5012 
5013 #endif
5014 
5015 #if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
5016 	|| defined(FEAT_GUI_MSWIN) \
5017 	|| defined(FEAT_GUI_MAC) \
5018 	|| defined(PROTO)
5019 
5020 #ifdef FEAT_WINDOWS
5021 static void gui_wingoto_xy __ARGS((int x, int y));
5022 
5023 /*
5024  * Jump to the window at specified point (x, y).
5025  */
5026     static void
5027 gui_wingoto_xy(x, y)
5028     int x;
5029     int y;
5030 {
5031     int		row = Y_2_ROW(y);
5032     int		col = X_2_COL(x);
5033     win_T	*wp;
5034 
5035     if (row >= 0 && col >= 0)
5036     {
5037 	wp = mouse_find_win(&row, &col);
5038 	if (wp != NULL && wp != curwin)
5039 	    win_goto(wp);
5040     }
5041 }
5042 #endif
5043 
5044 /*
5045  * Process file drop.  Mouse cursor position, key modifiers, name of files
5046  * and count of files are given.  Argument "fnames[count]" has full pathnames
5047  * of dropped files, they will be freed in this function, and caller can't use
5048  * fnames after call this function.
5049  */
5050 /*ARGSUSED*/
5051     void
5052 gui_handle_drop(x, y, modifiers, fnames, count)
5053     int		x;
5054     int		y;
5055     int_u	modifiers;
5056     char_u	**fnames;
5057     int		count;
5058 {
5059     int		i;
5060     char_u	*p;
5061 
5062     /*
5063      * When the cursor is at the command line, add the file names to the
5064      * command line, don't edit the files.
5065      */
5066     if (State & CMDLINE)
5067     {
5068 	shorten_filenames(fnames, count);
5069 	for (i = 0; i < count; ++i)
5070 	{
5071 	    if (fnames[i] != NULL)
5072 	    {
5073 		if (i > 0)
5074 		    add_to_input_buf((char_u*)" ", 1);
5075 
5076 		/* We don't know what command is used thus we can't be sure
5077 		 * about which characters need to be escaped.  Only escape the
5078 		 * most common ones. */
5079 # ifdef BACKSLASH_IN_FILENAME
5080 		p = vim_strsave_escaped(fnames[i], (char_u *)" \t\"|");
5081 # else
5082 		p = vim_strsave_escaped(fnames[i], (char_u *)"\\ \t\"|");
5083 # endif
5084 		if (p != NULL)
5085 		    add_to_input_buf(p, (int)STRLEN(p));
5086 		vim_free(p);
5087 		vim_free(fnames[i]);
5088 	    }
5089 	}
5090 	vim_free(fnames);
5091     }
5092     else
5093     {
5094 	/* Go to the window under mouse cursor, then shorten given "fnames" by
5095 	 * current window, because a window can have local current dir. */
5096 # ifdef FEAT_WINDOWS
5097 	gui_wingoto_xy(x, y);
5098 # endif
5099 	shorten_filenames(fnames, count);
5100 
5101 	/* If Shift held down, remember the first item. */
5102 	if ((modifiers & MOUSE_SHIFT) != 0)
5103 	    p = vim_strsave(fnames[0]);
5104 	else
5105 	    p = NULL;
5106 
5107 	/* Handle the drop, :edit or :split to get to the file.  This also
5108 	 * frees fnames[].  Skip this if there is only one item it's a
5109 	 * directory and Shift is held down. */
5110 	if (count == 1 && (modifiers & MOUSE_SHIFT) != 0
5111 						     && mch_isdir(fnames[0]))
5112 	{
5113 	    vim_free(fnames[0]);
5114 	    vim_free(fnames);
5115 	}
5116 	else
5117 	    handle_drop(count, fnames, (modifiers & MOUSE_CTRL) != 0);
5118 
5119 	/* If Shift held down, change to first file's directory.  If the first
5120 	 * item is a directory, change to that directory (and let the explorer
5121 	 * plugin show the contents). */
5122 	if (p != NULL)
5123 	{
5124 	    if (mch_isdir(p))
5125 	    {
5126 		if (mch_chdir((char *)p) == 0)
5127 		    shorten_fnames(TRUE);
5128 	    }
5129 	    else if (vim_chdirfile(p) == OK)
5130 		shorten_fnames(TRUE);
5131 	    vim_free(p);
5132 	}
5133 
5134 	/* Update the screen display */
5135 	update_screen(NOT_VALID);
5136 # ifdef FEAT_MENU
5137 	gui_update_menus(0);
5138 # endif
5139 	setcursor();
5140 	out_flush();
5141 	gui_update_cursor(FALSE, FALSE);
5142 	gui_mch_flush();
5143     }
5144 }
5145 #endif
5146