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