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