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