xref: /openbsd-src/usr.bin/tmux/tty.c (revision 521ba2f2ab0e0e89d1776559874b3ecc227442fc)
1 /* $OpenBSD: tty.c,v 1.431 2023/06/26 07:17:40 nicm Exp $ */
2 
3 /*
4  * Copyright (c) 2007 Nicholas Marriott <nicholas.marriott@gmail.com>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 #include <sys/ioctl.h>
21 
22 #include <netinet/in.h>
23 
24 #include <curses.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <resolv.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <termios.h>
31 #include <unistd.h>
32 
33 #include "tmux.h"
34 
35 static int	tty_log_fd = -1;
36 
37 static void	tty_set_italics(struct tty *);
38 static int	tty_try_colour(struct tty *, int, const char *);
39 static void	tty_force_cursor_colour(struct tty *, int);
40 static void	tty_cursor_pane(struct tty *, const struct tty_ctx *, u_int,
41 		    u_int);
42 static void	tty_cursor_pane_unless_wrap(struct tty *,
43 		    const struct tty_ctx *, u_int, u_int);
44 static void	tty_invalidate(struct tty *);
45 static void	tty_colours(struct tty *, const struct grid_cell *);
46 static void	tty_check_fg(struct tty *, struct colour_palette *,
47     		    struct grid_cell *);
48 static void	tty_check_bg(struct tty *, struct colour_palette *,
49     		    struct grid_cell *);
50 static void	tty_check_us(struct tty *, struct colour_palette *,
51     		    struct grid_cell *);
52 static void	tty_colours_fg(struct tty *, const struct grid_cell *);
53 static void	tty_colours_bg(struct tty *, const struct grid_cell *);
54 static void	tty_colours_us(struct tty *, const struct grid_cell *);
55 
56 static void	tty_region_pane(struct tty *, const struct tty_ctx *, u_int,
57 		    u_int);
58 static void	tty_region(struct tty *, u_int, u_int);
59 static void	tty_margin_pane(struct tty *, const struct tty_ctx *);
60 static void	tty_margin(struct tty *, u_int, u_int);
61 static int	tty_large_region(struct tty *, const struct tty_ctx *);
62 static int	tty_fake_bce(const struct tty *, const struct grid_cell *,
63 		    u_int);
64 static void	tty_redraw_region(struct tty *, const struct tty_ctx *);
65 static void	tty_emulate_repeat(struct tty *, enum tty_code_code,
66 		    enum tty_code_code, u_int);
67 static void	tty_repeat_space(struct tty *, u_int);
68 static void	tty_draw_pane(struct tty *, const struct tty_ctx *, u_int);
69 static void	tty_default_attributes(struct tty *, const struct grid_cell *,
70 		    struct colour_palette *, u_int, struct hyperlinks *);
71 static int	tty_check_overlay(struct tty *, u_int, u_int);
72 static void	tty_check_overlay_range(struct tty *, u_int, u_int, u_int,
73 		    struct overlay_ranges *);
74 
75 #define tty_use_margin(tty) \
76 	(tty->term->flags & TERM_DECSLRM)
77 #define tty_full_width(tty, ctx) \
78 	((ctx)->xoff == 0 && (ctx)->sx >= (tty)->sx)
79 
80 #define TTY_BLOCK_INTERVAL (100000 /* 100 milliseconds */)
81 #define TTY_BLOCK_START(tty) (1 + ((tty)->sx * (tty)->sy) * 8)
82 #define TTY_BLOCK_STOP(tty) (1 + ((tty)->sx * (tty)->sy) / 8)
83 
84 #define TTY_QUERY_TIMEOUT 5
85 
86 void
87 tty_create_log(void)
88 {
89 	char	name[64];
90 
91 	xsnprintf(name, sizeof name, "tmux-out-%ld.log", (long)getpid());
92 
93 	tty_log_fd = open(name, O_WRONLY|O_CREAT|O_TRUNC, 0644);
94 	if (tty_log_fd != -1 && fcntl(tty_log_fd, F_SETFD, FD_CLOEXEC) == -1)
95 		fatal("fcntl failed");
96 }
97 
98 int
99 tty_init(struct tty *tty, struct client *c)
100 {
101 	if (!isatty(c->fd))
102 		return (-1);
103 
104 	memset(tty, 0, sizeof *tty);
105 	tty->client = c;
106 
107 	tty->cstyle = SCREEN_CURSOR_DEFAULT;
108 	tty->ccolour = -1;
109 	tty->fg = tty->bg = -1;
110 
111 	if (tcgetattr(c->fd, &tty->tio) != 0)
112 		return (-1);
113 	return (0);
114 }
115 
116 void
117 tty_resize(struct tty *tty)
118 {
119 	struct client	*c = tty->client;
120 	struct winsize	 ws;
121 	u_int		 sx, sy, xpixel, ypixel;
122 
123 	if (ioctl(c->fd, TIOCGWINSZ, &ws) != -1) {
124 		sx = ws.ws_col;
125 		if (sx == 0) {
126 			sx = 80;
127 			xpixel = 0;
128 		} else
129 			xpixel = ws.ws_xpixel / sx;
130 		sy = ws.ws_row;
131 		if (sy == 0) {
132 			sy = 24;
133 			ypixel = 0;
134 		} else
135 			ypixel = ws.ws_ypixel / sy;
136 	} else {
137 		sx = 80;
138 		sy = 24;
139 		xpixel = 0;
140 		ypixel = 0;
141 	}
142 	log_debug("%s: %s now %ux%u (%ux%u)", __func__, c->name, sx, sy,
143 	    xpixel, ypixel);
144 	tty_set_size(tty, sx, sy, xpixel, ypixel);
145 	tty_invalidate(tty);
146 }
147 
148 void
149 tty_set_size(struct tty *tty, u_int sx, u_int sy, u_int xpixel, u_int ypixel)
150 {
151 	tty->sx = sx;
152 	tty->sy = sy;
153 	tty->xpixel = xpixel;
154 	tty->ypixel = ypixel;
155 }
156 
157 static void
158 tty_read_callback(__unused int fd, __unused short events, void *data)
159 {
160 	struct tty	*tty = data;
161 	struct client	*c = tty->client;
162 	const char	*name = c->name;
163 	size_t		 size = EVBUFFER_LENGTH(tty->in);
164 	int		 nread;
165 
166 	nread = evbuffer_read(tty->in, c->fd, -1);
167 	if (nread == 0 || nread == -1) {
168 		if (nread == 0)
169 			log_debug("%s: read closed", name);
170 		else
171 			log_debug("%s: read error: %s", name, strerror(errno));
172 		event_del(&tty->event_in);
173 		server_client_lost(tty->client);
174 		return;
175 	}
176 	log_debug("%s: read %d bytes (already %zu)", name, nread, size);
177 
178 	while (tty_keys_next(tty))
179 		;
180 }
181 
182 static void
183 tty_timer_callback(__unused int fd, __unused short events, void *data)
184 {
185 	struct tty	*tty = data;
186 	struct client	*c = tty->client;
187 	struct timeval	 tv = { .tv_usec = TTY_BLOCK_INTERVAL };
188 
189 	log_debug("%s: %zu discarded", c->name, tty->discarded);
190 
191 	c->flags |= CLIENT_ALLREDRAWFLAGS;
192 	c->discarded += tty->discarded;
193 
194 	if (tty->discarded < TTY_BLOCK_STOP(tty)) {
195 		tty->flags &= ~TTY_BLOCK;
196 		tty_invalidate(tty);
197 		return;
198 	}
199 	tty->discarded = 0;
200 	evtimer_add(&tty->timer, &tv);
201 }
202 
203 static int
204 tty_block_maybe(struct tty *tty)
205 {
206 	struct client	*c = tty->client;
207 	size_t		 size = EVBUFFER_LENGTH(tty->out);
208 	struct timeval	 tv = { .tv_usec = TTY_BLOCK_INTERVAL };
209 
210 	if (size == 0)
211 		tty->flags &= ~TTY_NOBLOCK;
212 	else if (tty->flags & TTY_NOBLOCK)
213 		return (0);
214 
215 	if (size < TTY_BLOCK_START(tty))
216 		return (0);
217 
218 	if (tty->flags & TTY_BLOCK)
219 		return (1);
220 	tty->flags |= TTY_BLOCK;
221 
222 	log_debug("%s: can't keep up, %zu discarded", c->name, size);
223 
224 	evbuffer_drain(tty->out, size);
225 	c->discarded += size;
226 
227 	tty->discarded = 0;
228 	evtimer_add(&tty->timer, &tv);
229 	return (1);
230 }
231 
232 static void
233 tty_write_callback(__unused int fd, __unused short events, void *data)
234 {
235 	struct tty	*tty = data;
236 	struct client	*c = tty->client;
237 	size_t		 size = EVBUFFER_LENGTH(tty->out);
238 	int		 nwrite;
239 
240 	nwrite = evbuffer_write(tty->out, c->fd);
241 	if (nwrite == -1)
242 		return;
243 	log_debug("%s: wrote %d bytes (of %zu)", c->name, nwrite, size);
244 
245 	if (c->redraw > 0) {
246 		if ((size_t)nwrite >= c->redraw)
247 			c->redraw = 0;
248 		else
249 			c->redraw -= nwrite;
250 		log_debug("%s: waiting for redraw, %zu bytes left", c->name,
251 		    c->redraw);
252 	} else if (tty_block_maybe(tty))
253 		return;
254 
255 	if (EVBUFFER_LENGTH(tty->out) != 0)
256 		event_add(&tty->event_out, NULL);
257 }
258 
259 int
260 tty_open(struct tty *tty, char **cause)
261 {
262 	struct client	*c = tty->client;
263 
264 	tty->term = tty_term_create(tty, c->term_name, c->term_caps,
265 	    c->term_ncaps, &c->term_features, cause);
266 	if (tty->term == NULL) {
267 		tty_close(tty);
268 		return (-1);
269 	}
270 	tty->flags |= TTY_OPENED;
271 
272 	tty->flags &= ~(TTY_NOCURSOR|TTY_FREEZE|TTY_BLOCK|TTY_TIMER);
273 
274 	event_set(&tty->event_in, c->fd, EV_PERSIST|EV_READ,
275 	    tty_read_callback, tty);
276 	tty->in = evbuffer_new();
277 	if (tty->in == NULL)
278 		fatal("out of memory");
279 
280 	event_set(&tty->event_out, c->fd, EV_WRITE, tty_write_callback, tty);
281 	tty->out = evbuffer_new();
282 	if (tty->out == NULL)
283 		fatal("out of memory");
284 
285 	evtimer_set(&tty->timer, tty_timer_callback, tty);
286 
287 	tty_start_tty(tty);
288 	tty_keys_build(tty);
289 
290 	return (0);
291 }
292 
293 static void
294 tty_start_timer_callback(__unused int fd, __unused short events, void *data)
295 {
296 	struct tty	*tty = data;
297 	struct client	*c = tty->client;
298 
299 	log_debug("%s: start timer fired", c->name);
300 	if ((tty->flags & (TTY_HAVEDA|TTY_HAVEDA2|TTY_HAVEXDA)) == 0)
301 		tty_update_features(tty);
302 	tty->flags |= TTY_ALL_REQUEST_FLAGS;
303 }
304 
305 void
306 tty_start_tty(struct tty *tty)
307 {
308 	struct client	*c = tty->client;
309 	struct termios	 tio;
310 	struct timeval	 tv = { .tv_sec = TTY_QUERY_TIMEOUT };
311 
312 	setblocking(c->fd, 0);
313 	event_add(&tty->event_in, NULL);
314 
315 	memcpy(&tio, &tty->tio, sizeof tio);
316 	tio.c_iflag &= ~(IXON|IXOFF|ICRNL|INLCR|IGNCR|IMAXBEL|ISTRIP);
317 	tio.c_iflag |= IGNBRK;
318 	tio.c_oflag &= ~(OPOST|ONLCR|OCRNL|ONLRET);
319 	tio.c_lflag &= ~(IEXTEN|ICANON|ECHO|ECHOE|ECHONL|ECHOCTL|ECHOPRT|
320 	    ECHOKE|ISIG);
321 	tio.c_cc[VMIN] = 1;
322 	tio.c_cc[VTIME] = 0;
323 	if (tcsetattr(c->fd, TCSANOW, &tio) == 0)
324 		tcflush(c->fd, TCOFLUSH);
325 
326 	tty_putcode(tty, TTYC_SMCUP);
327 
328 	tty_putcode(tty, TTYC_SMKX);
329 	tty_putcode(tty, TTYC_CLEAR);
330 
331 	if (tty_acs_needed(tty)) {
332 		log_debug("%s: using capabilities for ACS", c->name);
333 		tty_putcode(tty, TTYC_ENACS);
334 	} else
335 		log_debug("%s: using UTF-8 for ACS", c->name);
336 
337 	tty_putcode(tty, TTYC_CNORM);
338 	if (tty_term_has(tty->term, TTYC_KMOUS)) {
339 		tty_puts(tty, "\033[?1000l\033[?1002l\033[?1003l");
340 		tty_puts(tty, "\033[?1006l\033[?1005l");
341 	}
342 	if (tty_term_has(tty->term, TTYC_ENBP))
343 		tty_putcode(tty, TTYC_ENBP);
344 
345 	evtimer_set(&tty->start_timer, tty_start_timer_callback, tty);
346 	evtimer_add(&tty->start_timer, &tv);
347 
348 	tty->flags |= TTY_STARTED;
349 	tty_invalidate(tty);
350 
351 	if (tty->ccolour != -1)
352 		tty_force_cursor_colour(tty, -1);
353 
354 	tty->mouse_drag_flag = 0;
355 	tty->mouse_drag_update = NULL;
356 	tty->mouse_drag_release = NULL;
357 }
358 
359 void
360 tty_send_requests(struct tty *tty)
361 {
362 	if (~tty->flags & TTY_STARTED)
363 		return;
364 
365 	if (tty->term->flags & TERM_VT100LIKE) {
366 		if (~tty->term->flags & TTY_HAVEDA)
367 			tty_puts(tty, "\033[c");
368 		if (~tty->flags & TTY_HAVEDA2)
369 			tty_puts(tty, "\033[>c");
370 		if (~tty->flags & TTY_HAVEXDA)
371 			tty_puts(tty, "\033[>q");
372 		if (~tty->flags & TTY_HAVEFG)
373 			tty_puts(tty, "\033]10;?\033\\");
374 		if (~tty->flags & TTY_HAVEBG)
375 			tty_puts(tty, "\033]11;?\033\\");
376 	} else
377 		tty->flags |= TTY_ALL_REQUEST_FLAGS;
378 }
379 
380 void
381 tty_stop_tty(struct tty *tty)
382 {
383 	struct client	*c = tty->client;
384 	struct winsize	 ws;
385 
386 	if (!(tty->flags & TTY_STARTED))
387 		return;
388 	tty->flags &= ~TTY_STARTED;
389 
390 	evtimer_del(&tty->start_timer);
391 
392 	event_del(&tty->timer);
393 	tty->flags &= ~TTY_BLOCK;
394 
395 	event_del(&tty->event_in);
396 	event_del(&tty->event_out);
397 
398 	/*
399 	 * Be flexible about error handling and try not kill the server just
400 	 * because the fd is invalid. Things like ssh -t can easily leave us
401 	 * with a dead tty.
402 	 */
403 	if (ioctl(c->fd, TIOCGWINSZ, &ws) == -1)
404 		return;
405 	if (tcsetattr(c->fd, TCSANOW, &tty->tio) == -1)
406 		return;
407 
408 	tty_raw(tty, tty_term_string_ii(tty->term, TTYC_CSR, 0, ws.ws_row - 1));
409 	if (tty_acs_needed(tty))
410 		tty_raw(tty, tty_term_string(tty->term, TTYC_RMACS));
411 	tty_raw(tty, tty_term_string(tty->term, TTYC_SGR0));
412 	tty_raw(tty, tty_term_string(tty->term, TTYC_RMKX));
413 	tty_raw(tty, tty_term_string(tty->term, TTYC_CLEAR));
414 	if (tty->cstyle != SCREEN_CURSOR_DEFAULT) {
415 		if (tty_term_has(tty->term, TTYC_SE))
416 			tty_raw(tty, tty_term_string(tty->term, TTYC_SE));
417 		else if (tty_term_has(tty->term, TTYC_SS))
418 			tty_raw(tty, tty_term_string_i(tty->term, TTYC_SS, 0));
419 	}
420 	if (tty->ccolour != -1)
421 		tty_raw(tty, tty_term_string(tty->term, TTYC_CR));
422 
423 	tty_raw(tty, tty_term_string(tty->term, TTYC_CNORM));
424 	if (tty_term_has(tty->term, TTYC_KMOUS)) {
425 		tty_raw(tty, "\033[?1000l\033[?1002l\033[?1003l");
426 		tty_raw(tty, "\033[?1006l\033[?1005l");
427 	}
428 	if (tty_term_has(tty->term, TTYC_DSBP))
429 		tty_raw(tty, tty_term_string(tty->term, TTYC_DSBP));
430 
431 	if (tty->term->flags & TERM_VT100LIKE)
432 		tty_raw(tty, "\033[?7727l");
433 	tty_raw(tty, tty_term_string(tty->term, TTYC_DSFCS));
434 	tty_raw(tty, tty_term_string(tty->term, TTYC_DSEKS));
435 
436 	if (tty_use_margin(tty))
437 		tty_raw(tty, tty_term_string(tty->term, TTYC_DSMG));
438 	tty_raw(tty, tty_term_string(tty->term, TTYC_RMCUP));
439 
440 	setblocking(c->fd, 1);
441 }
442 
443 void
444 tty_close(struct tty *tty)
445 {
446 	if (event_initialized(&tty->key_timer))
447 		evtimer_del(&tty->key_timer);
448 	tty_stop_tty(tty);
449 
450 	if (tty->flags & TTY_OPENED) {
451 		evbuffer_free(tty->in);
452 		event_del(&tty->event_in);
453 		evbuffer_free(tty->out);
454 		event_del(&tty->event_out);
455 
456 		tty_term_free(tty->term);
457 		tty_keys_free(tty);
458 
459 		tty->flags &= ~TTY_OPENED;
460 	}
461 }
462 
463 void
464 tty_free(struct tty *tty)
465 {
466 	tty_close(tty);
467 }
468 
469 void
470 tty_update_features(struct tty *tty)
471 {
472 	struct client	*c = tty->client;
473 
474 	if (tty_apply_features(tty->term, c->term_features))
475 		tty_term_apply_overrides(tty->term);
476 
477 	if (tty_use_margin(tty))
478 		tty_putcode(tty, TTYC_ENMG);
479 	if (options_get_number(global_options, "extended-keys"))
480 		tty_puts(tty, tty_term_string(tty->term, TTYC_ENEKS));
481 	if (options_get_number(global_options, "focus-events"))
482 		tty_puts(tty, tty_term_string(tty->term, TTYC_ENFCS));
483 	if (tty->term->flags & TERM_VT100LIKE)
484 		tty_puts(tty, "\033[?7727h");
485 
486 	/*
487 	 * Features might have changed since the first draw during attach. For
488 	 * example, this happens when DA responses are received.
489 	 */
490 	server_redraw_client(c);
491 
492 	tty_invalidate(tty);
493 }
494 
495 void
496 tty_raw(struct tty *tty, const char *s)
497 {
498 	struct client	*c = tty->client;
499 	ssize_t		 n, slen;
500 	u_int		 i;
501 
502 	slen = strlen(s);
503 	for (i = 0; i < 5; i++) {
504 		n = write(c->fd, s, slen);
505 		if (n >= 0) {
506 			s += n;
507 			slen -= n;
508 			if (slen == 0)
509 				break;
510 		} else if (n == -1 && errno != EAGAIN)
511 			break;
512 		usleep(100);
513 	}
514 }
515 
516 void
517 tty_putcode(struct tty *tty, enum tty_code_code code)
518 {
519 	tty_puts(tty, tty_term_string(tty->term, code));
520 }
521 
522 void
523 tty_putcode_i(struct tty *tty, enum tty_code_code code, int a)
524 {
525 	if (a < 0)
526 		return;
527 	tty_puts(tty, tty_term_string_i(tty->term, code, a));
528 }
529 
530 void
531 tty_putcode_ii(struct tty *tty, enum tty_code_code code, int a, int b)
532 {
533 	if (a < 0 || b < 0)
534 		return;
535 	tty_puts(tty, tty_term_string_ii(tty->term, code, a, b));
536 }
537 
538 void
539 tty_putcode_iii(struct tty *tty, enum tty_code_code code, int a, int b, int c)
540 {
541 	if (a < 0 || b < 0 || c < 0)
542 		return;
543 	tty_puts(tty, tty_term_string_iii(tty->term, code, a, b, c));
544 }
545 
546 void
547 tty_putcode_s(struct tty *tty, enum tty_code_code code, const char *a)
548 {
549 	if (a != NULL)
550 		tty_puts(tty, tty_term_string_s(tty->term, code, a));
551 }
552 
553 void
554 tty_putcode_ss(struct tty *tty, enum tty_code_code code, const char *a,
555     const char *b)
556 {
557 	if (a != NULL && b != NULL)
558 		tty_puts(tty, tty_term_string_ss(tty->term, code, a, b));
559 }
560 
561 static void
562 tty_add(struct tty *tty, const char *buf, size_t len)
563 {
564 	struct client	*c = tty->client;
565 
566 	if (tty->flags & TTY_BLOCK) {
567 		tty->discarded += len;
568 		return;
569 	}
570 
571 	evbuffer_add(tty->out, buf, len);
572 	log_debug("%s: %.*s", c->name, (int)len, buf);
573 	c->written += len;
574 
575 	if (tty_log_fd != -1)
576 		write(tty_log_fd, buf, len);
577 	if (tty->flags & TTY_STARTED)
578 		event_add(&tty->event_out, NULL);
579 }
580 
581 void
582 tty_puts(struct tty *tty, const char *s)
583 {
584 	if (*s != '\0')
585 		tty_add(tty, s, strlen(s));
586 }
587 
588 void
589 tty_putc(struct tty *tty, u_char ch)
590 {
591 	const char	*acs;
592 
593 	if ((tty->term->flags & TERM_NOAM) &&
594 	    ch >= 0x20 && ch != 0x7f &&
595 	    tty->cy == tty->sy - 1 &&
596 	    tty->cx + 1 >= tty->sx)
597 		return;
598 
599 	if (tty->cell.attr & GRID_ATTR_CHARSET) {
600 		acs = tty_acs_get(tty, ch);
601 		if (acs != NULL)
602 			tty_add(tty, acs, strlen(acs));
603 		else
604 			tty_add(tty, &ch, 1);
605 	} else
606 		tty_add(tty, &ch, 1);
607 
608 	if (ch >= 0x20 && ch != 0x7f) {
609 		if (tty->cx >= tty->sx) {
610 			tty->cx = 1;
611 			if (tty->cy != tty->rlower)
612 				tty->cy++;
613 
614 			/*
615 			 * On !am terminals, force the cursor position to where
616 			 * we think it should be after a line wrap - this means
617 			 * it works on sensible terminals as well.
618 			 */
619 			if (tty->term->flags & TERM_NOAM)
620 				tty_putcode_ii(tty, TTYC_CUP, tty->cy, tty->cx);
621 		} else
622 			tty->cx++;
623 	}
624 }
625 
626 void
627 tty_putn(struct tty *tty, const void *buf, size_t len, u_int width)
628 {
629 	if ((tty->term->flags & TERM_NOAM) &&
630 	    tty->cy == tty->sy - 1 &&
631 	    tty->cx + len >= tty->sx)
632 		len = tty->sx - tty->cx - 1;
633 
634 	tty_add(tty, buf, len);
635 	if (tty->cx + width > tty->sx) {
636 		tty->cx = (tty->cx + width) - tty->sx;
637 		if (tty->cx <= tty->sx)
638 			tty->cy++;
639 		else
640 			tty->cx = tty->cy = UINT_MAX;
641 	} else
642 		tty->cx += width;
643 }
644 
645 static void
646 tty_set_italics(struct tty *tty)
647 {
648 	const char	*s;
649 
650 	if (tty_term_has(tty->term, TTYC_SITM)) {
651 		s = options_get_string(global_options, "default-terminal");
652 		if (strcmp(s, "screen") != 0 && strncmp(s, "screen-", 7) != 0) {
653 			tty_putcode(tty, TTYC_SITM);
654 			return;
655 		}
656 	}
657 	tty_putcode(tty, TTYC_SMSO);
658 }
659 
660 void
661 tty_set_title(struct tty *tty, const char *title)
662 {
663 	if (!tty_term_has(tty->term, TTYC_TSL) ||
664 	    !tty_term_has(tty->term, TTYC_FSL))
665 		return;
666 
667 	tty_putcode(tty, TTYC_TSL);
668 	tty_puts(tty, title);
669 	tty_putcode(tty, TTYC_FSL);
670 }
671 
672 void
673 tty_set_path(struct tty *tty, const char *title)
674 {
675 	if (!tty_term_has(tty->term, TTYC_SWD) ||
676 	    !tty_term_has(tty->term, TTYC_FSL))
677 		return;
678 
679 	tty_putcode(tty, TTYC_SWD);
680 	tty_puts(tty, title);
681 	tty_putcode(tty, TTYC_FSL);
682 }
683 
684 static void
685 tty_force_cursor_colour(struct tty *tty, int c)
686 {
687 	u_char	r, g, b;
688 	char	s[13];
689 
690 	if (c != -1)
691 		c = colour_force_rgb(c);
692 	if (c == tty->ccolour)
693 		return;
694 	if (c == -1)
695 		tty_putcode(tty, TTYC_CR);
696 	else {
697 		colour_split_rgb(c, &r, &g, &b);
698 		xsnprintf(s, sizeof s, "rgb:%02hhx/%02hhx/%02hhx", r, g, b);
699 		tty_putcode_s(tty, TTYC_CS, s);
700 	}
701 	tty->ccolour = c;
702 }
703 
704 static int
705 tty_update_cursor(struct tty *tty, int mode, struct screen *s)
706 {
707 	enum screen_cursor_style	cstyle;
708 	int				ccolour, changed, cmode = mode;
709 
710 	/* Set cursor colour if changed. */
711 	if (s != NULL) {
712 		ccolour = s->ccolour;
713 		if (s->ccolour == -1)
714 			ccolour = s->default_ccolour;
715 		tty_force_cursor_colour(tty, ccolour);
716 	}
717 
718 	/* If cursor is off, set as invisible. */
719 	if (~cmode & MODE_CURSOR) {
720 		if (tty->mode & MODE_CURSOR)
721 			tty_putcode(tty, TTYC_CIVIS);
722 		return (cmode);
723 	}
724 
725 	/* Check if blinking or very visible flag changed or style changed. */
726 	if (s == NULL)
727 		cstyle = tty->cstyle;
728 	else {
729 		cstyle = s->cstyle;
730 		if (cstyle == SCREEN_CURSOR_DEFAULT) {
731 			if (~cmode & MODE_CURSOR_BLINKING_SET) {
732 				if (s->default_mode & MODE_CURSOR_BLINKING)
733 					cmode |= MODE_CURSOR_BLINKING;
734 				else
735 					cmode &= ~MODE_CURSOR_BLINKING;
736 			}
737 			cstyle = s->default_cstyle;
738 		}
739 	}
740 
741 	/* If nothing changed, do nothing. */
742 	changed = cmode ^ tty->mode;
743 	if ((changed & CURSOR_MODES) == 0 && cstyle == tty->cstyle)
744 		return (cmode);
745 
746 	/*
747 	 * Set cursor style. If an explicit style has been set with DECSCUSR,
748 	 * set it if supported, otherwise send cvvis for blinking styles.
749 	 *
750 	 * If no style, has been set (SCREEN_CURSOR_DEFAULT), then send cvvis
751 	 * if either the blinking or very visible flags are set.
752 	 */
753 	tty_putcode(tty, TTYC_CNORM);
754 	switch (cstyle) {
755 	case SCREEN_CURSOR_DEFAULT:
756 		if (tty->cstyle != SCREEN_CURSOR_DEFAULT) {
757 			if (tty_term_has(tty->term, TTYC_SE))
758 				tty_putcode(tty, TTYC_SE);
759 			else
760 				tty_putcode_i(tty, TTYC_SS, 0);
761 		}
762 		if (cmode & (MODE_CURSOR_BLINKING|MODE_CURSOR_VERY_VISIBLE))
763 			tty_putcode(tty, TTYC_CVVIS);
764 		break;
765 	case SCREEN_CURSOR_BLOCK:
766 		if (tty_term_has(tty->term, TTYC_SS)) {
767 			if (cmode & MODE_CURSOR_BLINKING)
768 				tty_putcode_i(tty, TTYC_SS, 1);
769 			else
770 				tty_putcode_i(tty, TTYC_SS, 2);
771 		} else if (cmode & MODE_CURSOR_BLINKING)
772 			tty_putcode(tty, TTYC_CVVIS);
773 		break;
774 	case SCREEN_CURSOR_UNDERLINE:
775 		if (tty_term_has(tty->term, TTYC_SS)) {
776 			if (cmode & MODE_CURSOR_BLINKING)
777 				tty_putcode_i(tty, TTYC_SS, 3);
778 			else
779 				tty_putcode_i(tty, TTYC_SS, 4);
780 		} else if (cmode & MODE_CURSOR_BLINKING)
781 			tty_putcode(tty, TTYC_CVVIS);
782 		break;
783 	case SCREEN_CURSOR_BAR:
784 		if (tty_term_has(tty->term, TTYC_SS)) {
785 			if (cmode & MODE_CURSOR_BLINKING)
786 				tty_putcode_i(tty, TTYC_SS, 5);
787 			else
788 				tty_putcode_i(tty, TTYC_SS, 6);
789 		} else if (cmode & MODE_CURSOR_BLINKING)
790 			tty_putcode(tty, TTYC_CVVIS);
791 		break;
792 	}
793 	tty->cstyle = cstyle;
794 	return (cmode);
795  }
796 
797 void
798 tty_update_mode(struct tty *tty, int mode, struct screen *s)
799 {
800 	struct tty_term	*term = tty->term;
801 	struct client	*c = tty->client;
802 	int		 changed;
803 
804 	if (tty->flags & TTY_NOCURSOR)
805 		mode &= ~MODE_CURSOR;
806 
807 	if (tty_update_cursor(tty, mode, s) & MODE_CURSOR_BLINKING)
808 		mode |= MODE_CURSOR_BLINKING;
809 	else
810 		mode &= ~MODE_CURSOR_BLINKING;
811 
812 	changed = mode ^ tty->mode;
813 	if (log_get_level() != 0 && changed != 0) {
814 		log_debug("%s: current mode %s", c->name,
815 		    screen_mode_to_string(tty->mode));
816 		log_debug("%s: setting mode %s", c->name,
817 		    screen_mode_to_string(mode));
818 	}
819 
820 	if ((changed & ALL_MOUSE_MODES) && tty_term_has(term, TTYC_KMOUS)) {
821 		/*
822 		 * If the mouse modes have changed, clear then all and apply
823 		 * again. There are differences in how terminals track the
824 		 * various bits.
825 		 */
826 		tty_puts(tty, "\033[?1006l\033[?1000l\033[?1002l\033[?1003l");
827 		if (mode & ALL_MOUSE_MODES)
828 			tty_puts(tty, "\033[?1006h");
829 		if (mode & MODE_MOUSE_ALL)
830 			tty_puts(tty, "\033[?1000h\033[?1002h\033[?1003h");
831 		else if (mode & MODE_MOUSE_BUTTON)
832 			tty_puts(tty, "\033[?1000h\033[?1002h");
833 		else if (mode & MODE_MOUSE_STANDARD)
834 			tty_puts(tty, "\033[?1000h");
835 	}
836 	tty->mode = mode;
837 }
838 
839 static void
840 tty_emulate_repeat(struct tty *tty, enum tty_code_code code,
841     enum tty_code_code code1, u_int n)
842 {
843 	if (tty_term_has(tty->term, code))
844 		tty_putcode_i(tty, code, n);
845 	else {
846 		while (n-- > 0)
847 			tty_putcode(tty, code1);
848 	}
849 }
850 
851 static void
852 tty_repeat_space(struct tty *tty, u_int n)
853 {
854 	static char s[500];
855 
856 	if (*s != ' ')
857 		memset(s, ' ', sizeof s);
858 
859 	while (n > sizeof s) {
860 		tty_putn(tty, s, sizeof s, sizeof s);
861 		n -= sizeof s;
862 	}
863 	if (n != 0)
864 		tty_putn(tty, s, n, n);
865 }
866 
867 /* Is this window bigger than the terminal? */
868 int
869 tty_window_bigger(struct tty *tty)
870 {
871 	struct client	*c = tty->client;
872 	struct window	*w = c->session->curw->window;
873 
874 	return (tty->sx < w->sx || tty->sy - status_line_size(c) < w->sy);
875 }
876 
877 /* What offset should this window be drawn at? */
878 int
879 tty_window_offset(struct tty *tty, u_int *ox, u_int *oy, u_int *sx, u_int *sy)
880 {
881 	*ox = tty->oox;
882 	*oy = tty->ooy;
883 	*sx = tty->osx;
884 	*sy = tty->osy;
885 
886 	return (tty->oflag);
887 }
888 
889 /* What offset should this window be drawn at? */
890 static int
891 tty_window_offset1(struct tty *tty, u_int *ox, u_int *oy, u_int *sx, u_int *sy)
892 {
893 	struct client		*c = tty->client;
894 	struct window		*w = c->session->curw->window;
895 	struct window_pane	*wp = server_client_get_pane(c);
896 	u_int			 cx, cy, lines;
897 
898 	lines = status_line_size(c);
899 
900 	if (tty->sx >= w->sx && tty->sy - lines >= w->sy) {
901 		*ox = 0;
902 		*oy = 0;
903 		*sx = w->sx;
904 		*sy = w->sy;
905 
906 		c->pan_window = NULL;
907 		return (0);
908 	}
909 
910 	*sx = tty->sx;
911 	*sy = tty->sy - lines;
912 
913 	if (c->pan_window == w) {
914 		if (*sx >= w->sx)
915 			c->pan_ox = 0;
916 		else if (c->pan_ox + *sx > w->sx)
917 			c->pan_ox = w->sx - *sx;
918 		*ox = c->pan_ox;
919 		if (*sy >= w->sy)
920 			c->pan_oy = 0;
921 		else if (c->pan_oy + *sy > w->sy)
922 			c->pan_oy = w->sy - *sy;
923 		*oy = c->pan_oy;
924 		return (1);
925 	}
926 
927 	if (~wp->screen->mode & MODE_CURSOR) {
928 		*ox = 0;
929 		*oy = 0;
930 	} else {
931 		cx = wp->xoff + wp->screen->cx;
932 		cy = wp->yoff + wp->screen->cy;
933 
934 		if (cx < *sx)
935 			*ox = 0;
936 		else if (cx > w->sx - *sx)
937 			*ox = w->sx - *sx;
938 		else
939 			*ox = cx - *sx / 2;
940 
941 		if (cy < *sy)
942 			*oy = 0;
943 		else if (cy > w->sy - *sy)
944 			*oy = w->sy - *sy;
945 		else
946 			*oy = cy - *sy / 2;
947 	}
948 
949 	c->pan_window = NULL;
950 	return (1);
951 }
952 
953 /* Update stored offsets for a window and redraw if necessary. */
954 void
955 tty_update_window_offset(struct window *w)
956 {
957 	struct client	*c;
958 
959 	TAILQ_FOREACH(c, &clients, entry) {
960 		if (c->session != NULL &&
961 		    c->session->curw != NULL &&
962 		    c->session->curw->window == w)
963 			tty_update_client_offset(c);
964 	}
965 }
966 
967 /* Update stored offsets for a client and redraw if necessary. */
968 void
969 tty_update_client_offset(struct client *c)
970 {
971 	u_int	ox, oy, sx, sy;
972 
973 	if (~c->flags & CLIENT_TERMINAL)
974 		return;
975 
976 	c->tty.oflag = tty_window_offset1(&c->tty, &ox, &oy, &sx, &sy);
977 	if (ox == c->tty.oox &&
978 	    oy == c->tty.ooy &&
979 	    sx == c->tty.osx &&
980 	    sy == c->tty.osy)
981 		return;
982 
983 	log_debug ("%s: %s offset has changed (%u,%u %ux%u -> %u,%u %ux%u)",
984 	    __func__, c->name, c->tty.oox, c->tty.ooy, c->tty.osx, c->tty.osy,
985 	    ox, oy, sx, sy);
986 
987 	c->tty.oox = ox;
988 	c->tty.ooy = oy;
989 	c->tty.osx = sx;
990 	c->tty.osy = sy;
991 
992 	c->flags |= (CLIENT_REDRAWWINDOW|CLIENT_REDRAWSTATUS);
993 }
994 
995 /*
996  * Is the region large enough to be worth redrawing once later rather than
997  * probably several times now? Currently yes if it is more than 50% of the
998  * pane.
999  */
1000 static int
1001 tty_large_region(__unused struct tty *tty, const struct tty_ctx *ctx)
1002 {
1003 	return (ctx->orlower - ctx->orupper >= ctx->sy / 2);
1004 }
1005 
1006 /*
1007  * Return if BCE is needed but the terminal doesn't have it - it'll need to be
1008  * emulated.
1009  */
1010 static int
1011 tty_fake_bce(const struct tty *tty, const struct grid_cell *gc, u_int bg)
1012 {
1013 	if (tty_term_flag(tty->term, TTYC_BCE))
1014 		return (0);
1015 	if (!COLOUR_DEFAULT(bg) || !COLOUR_DEFAULT(gc->bg))
1016 		return (1);
1017 	return (0);
1018 }
1019 
1020 /*
1021  * Redraw scroll region using data from screen (already updated). Used when
1022  * CSR not supported, or window is a pane that doesn't take up the full
1023  * width of the terminal.
1024  */
1025 static void
1026 tty_redraw_region(struct tty *tty, const struct tty_ctx *ctx)
1027 {
1028 	struct client		*c = tty->client;
1029 	u_int			 i;
1030 
1031 	/*
1032 	 * If region is large, schedule a redraw. In most cases this is likely
1033 	 * to be followed by some more scrolling.
1034 	 */
1035 	if (tty_large_region(tty, ctx)) {
1036 		log_debug("%s: %s large redraw", __func__, c->name);
1037 		ctx->redraw_cb(ctx);
1038 		return;
1039 	}
1040 
1041 	for (i = ctx->orupper; i <= ctx->orlower; i++)
1042 		tty_draw_pane(tty, ctx, i);
1043 }
1044 
1045 /* Is this position visible in the pane? */
1046 static int
1047 tty_is_visible(__unused struct tty *tty, const struct tty_ctx *ctx, u_int px,
1048     u_int py, u_int nx, u_int ny)
1049 {
1050 	u_int	xoff = ctx->rxoff + px, yoff = ctx->ryoff + py;
1051 
1052 	if (!ctx->bigger)
1053 		return (1);
1054 
1055 	if (xoff + nx <= ctx->wox || xoff >= ctx->wox + ctx->wsx ||
1056 	    yoff + ny <= ctx->woy || yoff >= ctx->woy + ctx->wsy)
1057 		return (0);
1058 	return (1);
1059 }
1060 
1061 /* Clamp line position to visible part of pane. */
1062 static int
1063 tty_clamp_line(struct tty *tty, const struct tty_ctx *ctx, u_int px, u_int py,
1064     u_int nx, u_int *i, u_int *x, u_int *rx, u_int *ry)
1065 {
1066 	u_int	xoff = ctx->rxoff + px;
1067 
1068 	if (!tty_is_visible(tty, ctx, px, py, nx, 1))
1069 		return (0);
1070 	*ry = ctx->yoff + py - ctx->woy;
1071 
1072 	if (xoff >= ctx->wox && xoff + nx <= ctx->wox + ctx->wsx) {
1073 		/* All visible. */
1074 		*i = 0;
1075 		*x = ctx->xoff + px - ctx->wox;
1076 		*rx = nx;
1077 	} else if (xoff < ctx->wox && xoff + nx > ctx->wox + ctx->wsx) {
1078 		/* Both left and right not visible. */
1079 		*i = ctx->wox;
1080 		*x = 0;
1081 		*rx = ctx->wsx;
1082 	} else if (xoff < ctx->wox) {
1083 		/* Left not visible. */
1084 		*i = ctx->wox - (ctx->xoff + px);
1085 		*x = 0;
1086 		*rx = nx - *i;
1087 	} else {
1088 		/* Right not visible. */
1089 		*i = 0;
1090 		*x = (ctx->xoff + px) - ctx->wox;
1091 		*rx = ctx->wsx - *x;
1092 	}
1093 	if (*rx > nx)
1094 		fatalx("%s: x too big, %u > %u", __func__, *rx, nx);
1095 
1096 	return (1);
1097 }
1098 
1099 /* Clear a line. */
1100 static void
1101 tty_clear_line(struct tty *tty, const struct grid_cell *defaults, u_int py,
1102     u_int px, u_int nx, u_int bg)
1103 {
1104 	struct client		*c = tty->client;
1105 	struct overlay_ranges	 r;
1106 	u_int			 i;
1107 
1108 	log_debug("%s: %s, %u at %u,%u", __func__, c->name, nx, px, py);
1109 
1110 	/* Nothing to clear. */
1111 	if (nx == 0)
1112 		return;
1113 
1114 	/* If genuine BCE is available, can try escape sequences. */
1115 	if (c->overlay_check == NULL && !tty_fake_bce(tty, defaults, bg)) {
1116 		/* Off the end of the line, use EL if available. */
1117 		if (px + nx >= tty->sx && tty_term_has(tty->term, TTYC_EL)) {
1118 			tty_cursor(tty, px, py);
1119 			tty_putcode(tty, TTYC_EL);
1120 			return;
1121 		}
1122 
1123 		/* At the start of the line. Use EL1. */
1124 		if (px == 0 && tty_term_has(tty->term, TTYC_EL1)) {
1125 			tty_cursor(tty, px + nx - 1, py);
1126 			tty_putcode(tty, TTYC_EL1);
1127 			return;
1128 		}
1129 
1130 		/* Section of line. Use ECH if possible. */
1131 		if (tty_term_has(tty->term, TTYC_ECH)) {
1132 			tty_cursor(tty, px, py);
1133 			tty_putcode_i(tty, TTYC_ECH, nx);
1134 			return;
1135 		}
1136 	}
1137 
1138 	/*
1139 	 * Couldn't use an escape sequence, use spaces. Clear only the visible
1140 	 * bit if there is an overlay.
1141 	 */
1142 	tty_check_overlay_range(tty, px, py, nx, &r);
1143 	for (i = 0; i < OVERLAY_MAX_RANGES; i++) {
1144 		if (r.nx[i] == 0)
1145 			continue;
1146 		tty_cursor(tty, r.px[i], py);
1147 		tty_repeat_space(tty, r.nx[i]);
1148 	}
1149 }
1150 
1151 /* Clear a line, adjusting to visible part of pane. */
1152 static void
1153 tty_clear_pane_line(struct tty *tty, const struct tty_ctx *ctx, u_int py,
1154     u_int px, u_int nx, u_int bg)
1155 {
1156 	struct client	*c = tty->client;
1157 	u_int		 i, x, rx, ry;
1158 
1159 	log_debug("%s: %s, %u at %u,%u", __func__, c->name, nx, px, py);
1160 
1161 	if (tty_clamp_line(tty, ctx, px, py, nx, &i, &x, &rx, &ry))
1162 		tty_clear_line(tty, &ctx->defaults, ry, x, rx, bg);
1163 }
1164 
1165 /* Clamp area position to visible part of pane. */
1166 static int
1167 tty_clamp_area(struct tty *tty, const struct tty_ctx *ctx, u_int px, u_int py,
1168     u_int nx, u_int ny, u_int *i, u_int *j, u_int *x, u_int *y, u_int *rx,
1169     u_int *ry)
1170 {
1171 	u_int	xoff = ctx->rxoff + px, yoff = ctx->ryoff + py;
1172 
1173 	if (!tty_is_visible(tty, ctx, px, py, nx, ny))
1174 		return (0);
1175 
1176 	if (xoff >= ctx->wox && xoff + nx <= ctx->wox + ctx->wsx) {
1177 		/* All visible. */
1178 		*i = 0;
1179 		*x = ctx->xoff + px - ctx->wox;
1180 		*rx = nx;
1181 	} else if (xoff < ctx->wox && xoff + nx > ctx->wox + ctx->wsx) {
1182 		/* Both left and right not visible. */
1183 		*i = ctx->wox;
1184 		*x = 0;
1185 		*rx = ctx->wsx;
1186 	} else if (xoff < ctx->wox) {
1187 		/* Left not visible. */
1188 		*i = ctx->wox - (ctx->xoff + px);
1189 		*x = 0;
1190 		*rx = nx - *i;
1191 	} else {
1192 		/* Right not visible. */
1193 		*i = 0;
1194 		*x = (ctx->xoff + px) - ctx->wox;
1195 		*rx = ctx->wsx - *x;
1196 	}
1197 	if (*rx > nx)
1198 		fatalx("%s: x too big, %u > %u", __func__, *rx, nx);
1199 
1200 	if (yoff >= ctx->woy && yoff + ny <= ctx->woy + ctx->wsy) {
1201 		/* All visible. */
1202 		*j = 0;
1203 		*y = ctx->yoff + py - ctx->woy;
1204 		*ry = ny;
1205 	} else if (yoff < ctx->woy && yoff + ny > ctx->woy + ctx->wsy) {
1206 		/* Both top and bottom not visible. */
1207 		*j = ctx->woy;
1208 		*y = 0;
1209 		*ry = ctx->wsy;
1210 	} else if (yoff < ctx->woy) {
1211 		/* Top not visible. */
1212 		*j = ctx->woy - (ctx->yoff + py);
1213 		*y = 0;
1214 		*ry = ny - *j;
1215 	} else {
1216 		/* Bottom not visible. */
1217 		*j = 0;
1218 		*y = (ctx->yoff + py) - ctx->woy;
1219 		*ry = ctx->wsy - *y;
1220 	}
1221 	if (*ry > ny)
1222 		fatalx("%s: y too big, %u > %u", __func__, *ry, ny);
1223 
1224 	return (1);
1225 }
1226 
1227 /* Clear an area, adjusting to visible part of pane. */
1228 static void
1229 tty_clear_area(struct tty *tty, const struct grid_cell *defaults, u_int py,
1230     u_int ny, u_int px, u_int nx, u_int bg)
1231 {
1232 	struct client	*c = tty->client;
1233 	u_int		 yy;
1234 	char		 tmp[64];
1235 
1236 	log_debug("%s: %s, %u,%u at %u,%u", __func__, c->name, nx, ny, px, py);
1237 
1238 	/* Nothing to clear. */
1239 	if (nx == 0 || ny == 0)
1240 		return;
1241 
1242 	/* If genuine BCE is available, can try escape sequences. */
1243 	if (c->overlay_check == NULL && !tty_fake_bce(tty, defaults, bg)) {
1244 		/* Use ED if clearing off the bottom of the terminal. */
1245 		if (px == 0 &&
1246 		    px + nx >= tty->sx &&
1247 		    py + ny >= tty->sy &&
1248 		    tty_term_has(tty->term, TTYC_ED)) {
1249 			tty_cursor(tty, 0, py);
1250 			tty_putcode(tty, TTYC_ED);
1251 			return;
1252 		}
1253 
1254 		/*
1255 		 * On VT420 compatible terminals we can use DECFRA if the
1256 		 * background colour isn't default (because it doesn't work
1257 		 * after SGR 0).
1258 		 */
1259 		if ((tty->term->flags & TERM_DECFRA) && !COLOUR_DEFAULT(bg)) {
1260 			xsnprintf(tmp, sizeof tmp, "\033[32;%u;%u;%u;%u$x",
1261 			    py + 1, px + 1, py + ny, px + nx);
1262 			tty_puts(tty, tmp);
1263 			return;
1264 		}
1265 
1266 		/* Full lines can be scrolled away to clear them. */
1267 		if (px == 0 &&
1268 		    px + nx >= tty->sx &&
1269 		    ny > 2 &&
1270 		    tty_term_has(tty->term, TTYC_CSR) &&
1271 		    tty_term_has(tty->term, TTYC_INDN)) {
1272 			tty_region(tty, py, py + ny - 1);
1273 			tty_margin_off(tty);
1274 			tty_putcode_i(tty, TTYC_INDN, ny);
1275 			return;
1276 		}
1277 
1278 		/*
1279 		 * If margins are supported, can just scroll the area off to
1280 		 * clear it.
1281 		 */
1282 		if (nx > 2 &&
1283 		    ny > 2 &&
1284 		    tty_term_has(tty->term, TTYC_CSR) &&
1285 		    tty_use_margin(tty) &&
1286 		    tty_term_has(tty->term, TTYC_INDN)) {
1287 			tty_region(tty, py, py + ny - 1);
1288 			tty_margin(tty, px, px + nx - 1);
1289 			tty_putcode_i(tty, TTYC_INDN, ny);
1290 			return;
1291 		}
1292 	}
1293 
1294 	/* Couldn't use an escape sequence, loop over the lines. */
1295 	for (yy = py; yy < py + ny; yy++)
1296 		tty_clear_line(tty, defaults, yy, px, nx, bg);
1297 }
1298 
1299 /* Clear an area in a pane. */
1300 static void
1301 tty_clear_pane_area(struct tty *tty, const struct tty_ctx *ctx, u_int py,
1302     u_int ny, u_int px, u_int nx, u_int bg)
1303 {
1304 	u_int	i, j, x, y, rx, ry;
1305 
1306 	if (tty_clamp_area(tty, ctx, px, py, nx, ny, &i, &j, &x, &y, &rx, &ry))
1307 		tty_clear_area(tty, &ctx->defaults, y, ry, x, rx, bg);
1308 }
1309 
1310 static void
1311 tty_draw_pane(struct tty *tty, const struct tty_ctx *ctx, u_int py)
1312 {
1313 	struct screen	*s = ctx->s;
1314 	u_int		 nx = ctx->sx, i, x, rx, ry;
1315 
1316 	log_debug("%s: %s %u %d", __func__, tty->client->name, py, ctx->bigger);
1317 
1318 	if (!ctx->bigger) {
1319 		tty_draw_line(tty, s, 0, py, nx, ctx->xoff, ctx->yoff + py,
1320 		    &ctx->defaults, ctx->palette);
1321 		return;
1322 	}
1323 	if (tty_clamp_line(tty, ctx, 0, py, nx, &i, &x, &rx, &ry)) {
1324 		tty_draw_line(tty, s, i, py, rx, x, ry, &ctx->defaults,
1325 		    ctx->palette);
1326 	}
1327 }
1328 
1329 static const struct grid_cell *
1330 tty_check_codeset(struct tty *tty, const struct grid_cell *gc)
1331 {
1332 	static struct grid_cell	new;
1333 	int			c;
1334 
1335 	/* Characters less than 0x7f are always fine, no matter what. */
1336 	if (gc->data.size == 1 && *gc->data.data < 0x7f)
1337 		return (gc);
1338 
1339 	/* UTF-8 terminal and a UTF-8 character - fine. */
1340 	if (tty->client->flags & CLIENT_UTF8)
1341 		return (gc);
1342 	memcpy(&new, gc, sizeof new);
1343 
1344 	/* See if this can be mapped to an ACS character. */
1345 	c = tty_acs_reverse_get(tty, gc->data.data, gc->data.size);
1346 	if (c != -1) {
1347 		utf8_set(&new.data, c);
1348 		new.attr |= GRID_ATTR_CHARSET;
1349 		return (&new);
1350 	}
1351 
1352 	/* Replace by the right number of underscores. */
1353 	new.data.size = gc->data.width;
1354 	if (new.data.size > UTF8_SIZE)
1355 		new.data.size = UTF8_SIZE;
1356 	memset(new.data.data, '_', new.data.size);
1357 	return (&new);
1358 }
1359 
1360 /*
1361  * Check if a single character is obstructed by the overlay and return a
1362  * boolean.
1363  */
1364 static int
1365 tty_check_overlay(struct tty *tty, u_int px, u_int py)
1366 {
1367 	struct overlay_ranges	r;
1368 
1369 	/*
1370 	 * A unit width range will always return nx[2] == 0 from a check, even
1371 	 * with multiple overlays, so it's sufficient to check just the first
1372 	 * two entries.
1373 	 */
1374 	tty_check_overlay_range(tty, px, py, 1, &r);
1375 	if (r.nx[0] + r.nx[1] == 0)
1376 		return (0);
1377 	return (1);
1378 }
1379 
1380 /* Return parts of the input range which are visible. */
1381 static void
1382 tty_check_overlay_range(struct tty *tty, u_int px, u_int py, u_int nx,
1383     struct overlay_ranges *r)
1384 {
1385 	struct client	*c = tty->client;
1386 
1387 	if (c->overlay_check == NULL) {
1388 		r->px[0] = px;
1389 		r->nx[0] = nx;
1390 		r->px[1] = 0;
1391 		r->nx[1] = 0;
1392 		r->px[2] = 0;
1393 		r->nx[2] = 0;
1394 		return;
1395 	}
1396 
1397 	c->overlay_check(c, c->overlay_data, px, py, nx, r);
1398 }
1399 
1400 void
1401 tty_draw_line(struct tty *tty, struct screen *s, u_int px, u_int py, u_int nx,
1402     u_int atx, u_int aty, const struct grid_cell *defaults,
1403     struct colour_palette *palette)
1404 {
1405 	struct grid		*gd = s->grid;
1406 	struct grid_cell	 gc, last;
1407 	const struct grid_cell	*gcp;
1408 	struct grid_line	*gl;
1409 	struct client		*c = tty->client;
1410 	struct overlay_ranges	 r;
1411 	u_int			 i, j, ux, sx, width, hidden, eux, nxx;
1412 	u_int			 cellsize;
1413 	int			 flags, cleared = 0, wrapped = 0;
1414 	char			 buf[512];
1415 	size_t			 len;
1416 
1417 	log_debug("%s: px=%u py=%u nx=%u atx=%u aty=%u", __func__,
1418 	    px, py, nx, atx, aty);
1419 	log_debug("%s: defaults: fg=%d, bg=%d", __func__, defaults->fg,
1420 	    defaults->bg);
1421 
1422 	/*
1423 	 * py is the line in the screen to draw.
1424 	 * px is the start x and nx is the width to draw.
1425 	 * atx,aty is the line on the terminal to draw it.
1426 	 */
1427 
1428 	flags = (tty->flags & TTY_NOCURSOR);
1429 	tty->flags |= TTY_NOCURSOR;
1430 	tty_update_mode(tty, tty->mode, s);
1431 
1432 	tty_region_off(tty);
1433 	tty_margin_off(tty);
1434 
1435 	/*
1436 	 * Clamp the width to cellsize - note this is not cellused, because
1437 	 * there may be empty background cells after it (from BCE).
1438 	 */
1439 	sx = screen_size_x(s);
1440 	if (nx > sx)
1441 		nx = sx;
1442 	cellsize = grid_get_line(gd, gd->hsize + py)->cellsize;
1443 	if (sx > cellsize)
1444 		sx = cellsize;
1445 	if (sx > tty->sx)
1446 		sx = tty->sx;
1447 	if (sx > nx)
1448 		sx = nx;
1449 	ux = 0;
1450 
1451 	if (py == 0)
1452 		gl = NULL;
1453 	else
1454 		gl = grid_get_line(gd, gd->hsize + py - 1);
1455 	if (gl == NULL ||
1456 	    (~gl->flags & GRID_LINE_WRAPPED) ||
1457 	    atx != 0 ||
1458 	    tty->cx < tty->sx ||
1459 	    nx < tty->sx) {
1460 		if (nx < tty->sx &&
1461 		    atx == 0 &&
1462 		    px + sx != nx &&
1463 		    tty_term_has(tty->term, TTYC_EL1) &&
1464 		    !tty_fake_bce(tty, defaults, 8) &&
1465 		    c->overlay_check == NULL) {
1466 			tty_default_attributes(tty, defaults, palette, 8,
1467 			    s->hyperlinks);
1468 			tty_cursor(tty, nx - 1, aty);
1469 			tty_putcode(tty, TTYC_EL1);
1470 			cleared = 1;
1471 		}
1472 	} else {
1473 		log_debug("%s: wrapped line %u", __func__, aty);
1474 		wrapped = 1;
1475 	}
1476 
1477 	memcpy(&last, &grid_default_cell, sizeof last);
1478 	len = 0;
1479 	width = 0;
1480 
1481 	for (i = 0; i < sx; i++) {
1482 		grid_view_get_cell(gd, px + i, py, &gc);
1483 		gcp = tty_check_codeset(tty, &gc);
1484 		if (len != 0 &&
1485 		    (!tty_check_overlay(tty, atx + ux + width, aty) ||
1486 		    (gcp->attr & GRID_ATTR_CHARSET) ||
1487 		    gcp->flags != last.flags ||
1488 		    gcp->attr != last.attr ||
1489 		    gcp->fg != last.fg ||
1490 		    gcp->bg != last.bg ||
1491 		    gcp->us != last.us ||
1492 		    gcp->link != last.link ||
1493 		    ux + width + gcp->data.width > nx ||
1494 		    (sizeof buf) - len < gcp->data.size)) {
1495 			tty_attributes(tty, &last, defaults, palette,
1496 			    s->hyperlinks);
1497 			if (last.flags & GRID_FLAG_CLEARED) {
1498 				log_debug("%s: %zu cleared", __func__, len);
1499 				tty_clear_line(tty, defaults, aty, atx + ux,
1500 				    width, last.bg);
1501 			} else {
1502 				if (!wrapped || atx != 0 || ux != 0)
1503 					tty_cursor(tty, atx + ux, aty);
1504 				tty_putn(tty, buf, len, width);
1505 			}
1506 			ux += width;
1507 
1508 			len = 0;
1509 			width = 0;
1510 			wrapped = 0;
1511 		}
1512 
1513 		if (gcp->flags & GRID_FLAG_SELECTED)
1514 			screen_select_cell(s, &last, gcp);
1515 		else
1516 			memcpy(&last, gcp, sizeof last);
1517 
1518 		tty_check_overlay_range(tty, atx + ux, aty, gcp->data.width,
1519 		    &r);
1520 		hidden = 0;
1521 		for (j = 0; j < OVERLAY_MAX_RANGES; j++)
1522 			hidden += r.nx[j];
1523 		hidden = gcp->data.width - hidden;
1524 		if (hidden != 0 && hidden == gcp->data.width) {
1525 			if (~gcp->flags & GRID_FLAG_PADDING)
1526 				ux += gcp->data.width;
1527 		} else if (hidden != 0 || ux + gcp->data.width > nx) {
1528 			if (~gcp->flags & GRID_FLAG_PADDING) {
1529 				tty_attributes(tty, &last, defaults, palette,
1530 				    s->hyperlinks);
1531 				for (j = 0; j < OVERLAY_MAX_RANGES; j++) {
1532 					if (r.nx[j] == 0)
1533 						continue;
1534 					/* Effective width drawn so far. */
1535 					eux = r.px[j] - atx;
1536 					if (eux < nx) {
1537 						tty_cursor(tty, r.px[j], aty);
1538 						nxx = nx - eux;
1539 						if (r.nx[j] > nxx)
1540 							r.nx[j] = nxx;
1541 						tty_repeat_space(tty, r.nx[j]);
1542 						ux = eux + r.nx[j];
1543 					}
1544 				}
1545 			}
1546 		} else if (gcp->attr & GRID_ATTR_CHARSET) {
1547 			tty_attributes(tty, &last, defaults, palette,
1548 			    s->hyperlinks);
1549 			tty_cursor(tty, atx + ux, aty);
1550 			for (j = 0; j < gcp->data.size; j++)
1551 				tty_putc(tty, gcp->data.data[j]);
1552 			ux += gcp->data.width;
1553 		} else if (~gcp->flags & GRID_FLAG_PADDING) {
1554 			memcpy(buf + len, gcp->data.data, gcp->data.size);
1555 			len += gcp->data.size;
1556 			width += gcp->data.width;
1557 		}
1558 	}
1559 	if (len != 0 && ((~last.flags & GRID_FLAG_CLEARED) || last.bg != 8)) {
1560 		tty_attributes(tty, &last, defaults, palette, s->hyperlinks);
1561 		if (last.flags & GRID_FLAG_CLEARED) {
1562 			log_debug("%s: %zu cleared (end)", __func__, len);
1563 			tty_clear_line(tty, defaults, aty, atx + ux, width,
1564 			    last.bg);
1565 		} else {
1566 			if (!wrapped || atx != 0 || ux != 0)
1567 				tty_cursor(tty, atx + ux, aty);
1568 			tty_putn(tty, buf, len, width);
1569 		}
1570 		ux += width;
1571 	}
1572 
1573 	if (!cleared && ux < nx) {
1574 		log_debug("%s: %u to end of line (%zu cleared)", __func__,
1575 		    nx - ux, len);
1576 		tty_default_attributes(tty, defaults, palette, 8,
1577 		    s->hyperlinks);
1578 		tty_clear_line(tty, defaults, aty, atx + ux, nx - ux, 8);
1579 	}
1580 
1581 	tty->flags = (tty->flags & ~TTY_NOCURSOR) | flags;
1582 	tty_update_mode(tty, tty->mode, s);
1583 }
1584 
1585 void
1586 tty_sync_start(struct tty *tty)
1587 {
1588 	if (tty->flags & TTY_BLOCK)
1589 		return;
1590 	if (tty->flags & TTY_SYNCING)
1591 		return;
1592 	tty->flags |= TTY_SYNCING;
1593 
1594 	if (tty_term_has(tty->term, TTYC_SYNC)) {
1595 		log_debug("%s sync start", tty->client->name);
1596 		tty_putcode_i(tty, TTYC_SYNC, 1);
1597 	}
1598 }
1599 
1600 void
1601 tty_sync_end(struct tty *tty)
1602 {
1603 	if (tty->flags & TTY_BLOCK)
1604 		return;
1605 	if (~tty->flags & TTY_SYNCING)
1606 		return;
1607 	tty->flags &= ~TTY_SYNCING;
1608 
1609 	if (tty_term_has(tty->term, TTYC_SYNC)) {
1610  		log_debug("%s sync end", tty->client->name);
1611 		tty_putcode_i(tty, TTYC_SYNC, 2);
1612 	}
1613 }
1614 
1615 static int
1616 tty_client_ready(const struct tty_ctx *ctx, struct client *c)
1617 {
1618 	if (c->session == NULL || c->tty.term == NULL)
1619 		return (0);
1620 	if (c->flags & CLIENT_SUSPENDED)
1621 		return (0);
1622 
1623 	/*
1624 	 * If invisible panes are allowed (used for passthrough), don't care if
1625 	 * redrawing or frozen.
1626 	 */
1627 	if (ctx->allow_invisible_panes)
1628 		return (1);
1629 
1630 	if (c->flags & CLIENT_REDRAWWINDOW)
1631 		return (0);
1632 	if (c->tty.flags & TTY_FREEZE)
1633 		return (0);
1634 	return (1);
1635 }
1636 
1637 void
1638 tty_write(void (*cmdfn)(struct tty *, const struct tty_ctx *),
1639     struct tty_ctx *ctx)
1640 {
1641 	struct client	*c;
1642 	int		 state;
1643 
1644 	if (ctx->set_client_cb == NULL)
1645 		return;
1646 	TAILQ_FOREACH(c, &clients, entry) {
1647 		if (tty_client_ready(ctx, c)) {
1648 			state = ctx->set_client_cb(ctx, c);
1649 			if (state == -1)
1650 				break;
1651 			if (state == 0)
1652 				continue;
1653 			cmdfn(&c->tty, ctx);
1654 		}
1655 	}
1656 }
1657 
1658 void
1659 tty_cmd_insertcharacter(struct tty *tty, const struct tty_ctx *ctx)
1660 {
1661 	struct client	*c = tty->client;
1662 
1663 	if (ctx->bigger ||
1664 	    !tty_full_width(tty, ctx) ||
1665 	    tty_fake_bce(tty, &ctx->defaults, ctx->bg) ||
1666 	    (!tty_term_has(tty->term, TTYC_ICH) &&
1667 	    !tty_term_has(tty->term, TTYC_ICH1)) ||
1668 	    c->overlay_check != NULL) {
1669 		tty_draw_pane(tty, ctx, ctx->ocy);
1670 		return;
1671 	}
1672 
1673 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1674 	    ctx->s->hyperlinks);
1675 
1676 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
1677 
1678 	tty_emulate_repeat(tty, TTYC_ICH, TTYC_ICH1, ctx->num);
1679 }
1680 
1681 void
1682 tty_cmd_deletecharacter(struct tty *tty, const struct tty_ctx *ctx)
1683 {
1684 	struct client	*c = tty->client;
1685 
1686 	if (ctx->bigger ||
1687 	    !tty_full_width(tty, ctx) ||
1688 	    tty_fake_bce(tty, &ctx->defaults, ctx->bg) ||
1689 	    (!tty_term_has(tty->term, TTYC_DCH) &&
1690 	    !tty_term_has(tty->term, TTYC_DCH1)) ||
1691 	    c->overlay_check != NULL) {
1692 		tty_draw_pane(tty, ctx, ctx->ocy);
1693 		return;
1694 	}
1695 
1696 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1697 	    ctx->s->hyperlinks);
1698 
1699 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
1700 
1701 	tty_emulate_repeat(tty, TTYC_DCH, TTYC_DCH1, ctx->num);
1702 }
1703 
1704 void
1705 tty_cmd_clearcharacter(struct tty *tty, const struct tty_ctx *ctx)
1706 {
1707 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1708 	    ctx->s->hyperlinks);
1709 
1710 	tty_clear_pane_line(tty, ctx, ctx->ocy, ctx->ocx, ctx->num, ctx->bg);
1711 }
1712 
1713 void
1714 tty_cmd_insertline(struct tty *tty, const struct tty_ctx *ctx)
1715 {
1716 	struct client	*c = tty->client;
1717 
1718 	if (ctx->bigger ||
1719 	    !tty_full_width(tty, ctx) ||
1720 	    tty_fake_bce(tty, &ctx->defaults, ctx->bg) ||
1721 	    !tty_term_has(tty->term, TTYC_CSR) ||
1722 	    !tty_term_has(tty->term, TTYC_IL1) ||
1723 	    ctx->sx == 1 ||
1724 	    ctx->sy == 1 ||
1725 	    c->overlay_check != NULL) {
1726 		tty_redraw_region(tty, ctx);
1727 		return;
1728 	}
1729 
1730 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1731 	    ctx->s->hyperlinks);
1732 
1733 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1734 	tty_margin_off(tty);
1735 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
1736 
1737 	tty_emulate_repeat(tty, TTYC_IL, TTYC_IL1, ctx->num);
1738 	tty->cx = tty->cy = UINT_MAX;
1739 }
1740 
1741 void
1742 tty_cmd_deleteline(struct tty *tty, const struct tty_ctx *ctx)
1743 {
1744 	struct client	*c = tty->client;
1745 
1746 	if (ctx->bigger ||
1747 	    !tty_full_width(tty, ctx) ||
1748 	    tty_fake_bce(tty, &ctx->defaults, ctx->bg) ||
1749 	    !tty_term_has(tty->term, TTYC_CSR) ||
1750 	    !tty_term_has(tty->term, TTYC_DL1) ||
1751 	    ctx->sx == 1 ||
1752 	    ctx->sy == 1 ||
1753 	    c->overlay_check != NULL) {
1754 		tty_redraw_region(tty, ctx);
1755 		return;
1756 	}
1757 
1758 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1759 	    ctx->s->hyperlinks);
1760 
1761 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1762 	tty_margin_off(tty);
1763 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
1764 
1765 	tty_emulate_repeat(tty, TTYC_DL, TTYC_DL1, ctx->num);
1766 	tty->cx = tty->cy = UINT_MAX;
1767 }
1768 
1769 void
1770 tty_cmd_clearline(struct tty *tty, const struct tty_ctx *ctx)
1771 {
1772 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1773 	    ctx->s->hyperlinks);
1774 
1775 	tty_clear_pane_line(tty, ctx, ctx->ocy, 0, ctx->sx, ctx->bg);
1776 }
1777 
1778 void
1779 tty_cmd_clearendofline(struct tty *tty, const struct tty_ctx *ctx)
1780 {
1781 	u_int	nx = ctx->sx - ctx->ocx;
1782 
1783 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1784 	    ctx->s->hyperlinks);
1785 
1786 	tty_clear_pane_line(tty, ctx, ctx->ocy, ctx->ocx, nx, ctx->bg);
1787 }
1788 
1789 void
1790 tty_cmd_clearstartofline(struct tty *tty, const struct tty_ctx *ctx)
1791 {
1792 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1793 	    ctx->s->hyperlinks);
1794 
1795 	tty_clear_pane_line(tty, ctx, ctx->ocy, 0, ctx->ocx + 1, ctx->bg);
1796 }
1797 
1798 void
1799 tty_cmd_reverseindex(struct tty *tty, const struct tty_ctx *ctx)
1800 {
1801 	struct client	*c = tty->client;
1802 
1803 	if (ctx->ocy != ctx->orupper)
1804 		return;
1805 
1806 	if (ctx->bigger ||
1807 	    (!tty_full_width(tty, ctx) && !tty_use_margin(tty)) ||
1808 	    tty_fake_bce(tty, &ctx->defaults, 8) ||
1809 	    !tty_term_has(tty->term, TTYC_CSR) ||
1810 	    (!tty_term_has(tty->term, TTYC_RI) &&
1811 	    !tty_term_has(tty->term, TTYC_RIN)) ||
1812 	    ctx->sx == 1 ||
1813 	    ctx->sy == 1 ||
1814 	    c->overlay_check != NULL) {
1815 		tty_redraw_region(tty, ctx);
1816 		return;
1817 	}
1818 
1819 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1820 	    ctx->s->hyperlinks);
1821 
1822 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1823 	tty_margin_pane(tty, ctx);
1824 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->orupper);
1825 
1826 	if (tty_term_has(tty->term, TTYC_RI))
1827 		tty_putcode(tty, TTYC_RI);
1828 	else
1829 		tty_putcode_i(tty, TTYC_RIN, 1);
1830 }
1831 
1832 void
1833 tty_cmd_linefeed(struct tty *tty, const struct tty_ctx *ctx)
1834 {
1835 	struct client	*c = tty->client;
1836 
1837 	if (ctx->ocy != ctx->orlower)
1838 		return;
1839 
1840 	if (ctx->bigger ||
1841 	    (!tty_full_width(tty, ctx) && !tty_use_margin(tty)) ||
1842 	    tty_fake_bce(tty, &ctx->defaults, 8) ||
1843 	    !tty_term_has(tty->term, TTYC_CSR) ||
1844 	    ctx->sx == 1 ||
1845 	    ctx->sy == 1 ||
1846 	    c->overlay_check != NULL) {
1847 		tty_redraw_region(tty, ctx);
1848 		return;
1849 	}
1850 
1851 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1852 	    ctx->s->hyperlinks);
1853 
1854 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1855 	tty_margin_pane(tty, ctx);
1856 
1857 	/*
1858 	 * If we want to wrap a pane while using margins, the cursor needs to
1859 	 * be exactly on the right of the region. If the cursor is entirely off
1860 	 * the edge - move it back to the right. Some terminals are funny about
1861 	 * this and insert extra spaces, so only use the right if margins are
1862 	 * enabled.
1863 	 */
1864 	if (ctx->xoff + ctx->ocx > tty->rright) {
1865 		if (!tty_use_margin(tty))
1866 			tty_cursor(tty, 0, ctx->yoff + ctx->ocy);
1867 		else
1868 			tty_cursor(tty, tty->rright, ctx->yoff + ctx->ocy);
1869 	} else
1870 		tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
1871 
1872 	tty_putc(tty, '\n');
1873 }
1874 
1875 void
1876 tty_cmd_scrollup(struct tty *tty, const struct tty_ctx *ctx)
1877 {
1878 	struct client	*c = tty->client;
1879 	u_int		 i;
1880 
1881 	if (ctx->bigger ||
1882 	    (!tty_full_width(tty, ctx) && !tty_use_margin(tty)) ||
1883 	    tty_fake_bce(tty, &ctx->defaults, 8) ||
1884 	    !tty_term_has(tty->term, TTYC_CSR) ||
1885 	    ctx->sx == 1 ||
1886 	    ctx->sy == 1 ||
1887 	    c->overlay_check != NULL) {
1888 		tty_redraw_region(tty, ctx);
1889 		return;
1890 	}
1891 
1892 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1893 	    ctx->s->hyperlinks);
1894 
1895 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1896 	tty_margin_pane(tty, ctx);
1897 
1898 	if (ctx->num == 1 || !tty_term_has(tty->term, TTYC_INDN)) {
1899 		if (!tty_use_margin(tty))
1900 			tty_cursor(tty, 0, tty->rlower);
1901 		else
1902 			tty_cursor(tty, tty->rright, tty->rlower);
1903 		for (i = 0; i < ctx->num; i++)
1904 			tty_putc(tty, '\n');
1905 	} else {
1906 		if (tty->cy == UINT_MAX)
1907 			tty_cursor(tty, 0, 0);
1908 		else
1909 			tty_cursor(tty, 0, tty->cy);
1910 		tty_putcode_i(tty, TTYC_INDN, ctx->num);
1911 	}
1912 }
1913 
1914 void
1915 tty_cmd_scrolldown(struct tty *tty, const struct tty_ctx *ctx)
1916 {
1917 	u_int		 i;
1918 	struct client	*c = tty->client;
1919 
1920 	if (ctx->bigger ||
1921 	    (!tty_full_width(tty, ctx) && !tty_use_margin(tty)) ||
1922 	    tty_fake_bce(tty, &ctx->defaults, 8) ||
1923 	    !tty_term_has(tty->term, TTYC_CSR) ||
1924 	    (!tty_term_has(tty->term, TTYC_RI) &&
1925 	    !tty_term_has(tty->term, TTYC_RIN)) ||
1926 	    ctx->sx == 1 ||
1927 	    ctx->sy == 1 ||
1928 	    c->overlay_check != NULL) {
1929 		tty_redraw_region(tty, ctx);
1930 		return;
1931 	}
1932 
1933 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1934 	    ctx->s->hyperlinks);
1935 
1936 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1937 	tty_margin_pane(tty, ctx);
1938 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->orupper);
1939 
1940 	if (tty_term_has(tty->term, TTYC_RIN))
1941 		tty_putcode_i(tty, TTYC_RIN, ctx->num);
1942 	else {
1943 		for (i = 0; i < ctx->num; i++)
1944 			tty_putcode(tty, TTYC_RI);
1945 	}
1946 }
1947 
1948 void
1949 tty_cmd_clearendofscreen(struct tty *tty, const struct tty_ctx *ctx)
1950 {
1951 	u_int	px, py, nx, ny;
1952 
1953 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1954 	    ctx->s->hyperlinks);
1955 
1956 	tty_region_pane(tty, ctx, 0, ctx->sy - 1);
1957 	tty_margin_off(tty);
1958 
1959 	px = 0;
1960 	nx = ctx->sx;
1961 	py = ctx->ocy + 1;
1962 	ny = ctx->sy - ctx->ocy - 1;
1963 
1964 	tty_clear_pane_area(tty, ctx, py, ny, px, nx, ctx->bg);
1965 
1966 	px = ctx->ocx;
1967 	nx = ctx->sx - ctx->ocx;
1968 	py = ctx->ocy;
1969 
1970 	tty_clear_pane_line(tty, ctx, py, px, nx, ctx->bg);
1971 }
1972 
1973 void
1974 tty_cmd_clearstartofscreen(struct tty *tty, const struct tty_ctx *ctx)
1975 {
1976 	u_int	px, py, nx, ny;
1977 
1978 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1979 	    ctx->s->hyperlinks);
1980 
1981 	tty_region_pane(tty, ctx, 0, ctx->sy - 1);
1982 	tty_margin_off(tty);
1983 
1984 	px = 0;
1985 	nx = ctx->sx;
1986 	py = 0;
1987 	ny = ctx->ocy;
1988 
1989 	tty_clear_pane_area(tty, ctx, py, ny, px, nx, ctx->bg);
1990 
1991 	px = 0;
1992 	nx = ctx->ocx + 1;
1993 	py = ctx->ocy;
1994 
1995 	tty_clear_pane_line(tty, ctx, py, px, nx, ctx->bg);
1996 }
1997 
1998 void
1999 tty_cmd_clearscreen(struct tty *tty, const struct tty_ctx *ctx)
2000 {
2001 	u_int	px, py, nx, ny;
2002 
2003 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
2004 	    ctx->s->hyperlinks);
2005 
2006 	tty_region_pane(tty, ctx, 0, ctx->sy - 1);
2007 	tty_margin_off(tty);
2008 
2009 	px = 0;
2010 	nx = ctx->sx;
2011 	py = 0;
2012 	ny = ctx->sy;
2013 
2014 	tty_clear_pane_area(tty, ctx, py, ny, px, nx, ctx->bg);
2015 }
2016 
2017 void
2018 tty_cmd_alignmenttest(struct tty *tty, const struct tty_ctx *ctx)
2019 {
2020 	u_int	i, j;
2021 
2022 	if (ctx->bigger) {
2023 		ctx->redraw_cb(ctx);
2024 		return;
2025 	}
2026 
2027 	tty_attributes(tty, &grid_default_cell, &ctx->defaults, ctx->palette,
2028 	    ctx->s->hyperlinks);
2029 
2030 	tty_region_pane(tty, ctx, 0, ctx->sy - 1);
2031 	tty_margin_off(tty);
2032 
2033 	for (j = 0; j < ctx->sy; j++) {
2034 		tty_cursor_pane(tty, ctx, 0, j);
2035 		for (i = 0; i < ctx->sx; i++)
2036 			tty_putc(tty, 'E');
2037 	}
2038 }
2039 
2040 void
2041 tty_cmd_cell(struct tty *tty, const struct tty_ctx *ctx)
2042 {
2043 	const struct grid_cell	*gcp = ctx->cell;
2044 	struct screen		*s = ctx->s;
2045 	struct overlay_ranges	 r;
2046 	u_int			 px, py, i, vis = 0;
2047 
2048 	px = ctx->xoff + ctx->ocx - ctx->wox;
2049 	py = ctx->yoff + ctx->ocy - ctx->woy;
2050 	if (!tty_is_visible(tty, ctx, ctx->ocx, ctx->ocy, 1, 1) ||
2051 	    (gcp->data.width == 1 && !tty_check_overlay(tty, px, py)))
2052 		return;
2053 
2054 	/* Handle partially obstructed wide characters. */
2055 	if (gcp->data.width > 1) {
2056 		tty_check_overlay_range(tty, px, py, gcp->data.width, &r);
2057 		for (i = 0; i < OVERLAY_MAX_RANGES; i++)
2058 			vis += r.nx[i];
2059 		if (vis < gcp->data.width) {
2060 			tty_draw_line(tty, s, s->cx, s->cy, gcp->data.width,
2061 			    px, py, &ctx->defaults, ctx->palette);
2062 			return;
2063 		}
2064 	}
2065 
2066 	if (ctx->xoff + ctx->ocx - ctx->wox > tty->sx - 1 &&
2067 	    ctx->ocy == ctx->orlower &&
2068 	    tty_full_width(tty, ctx))
2069 		tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
2070 
2071 	tty_margin_off(tty);
2072 	tty_cursor_pane_unless_wrap(tty, ctx, ctx->ocx, ctx->ocy);
2073 
2074 	tty_cell(tty, ctx->cell, &ctx->defaults, ctx->palette,
2075 	    ctx->s->hyperlinks);
2076 }
2077 
2078 void
2079 tty_cmd_cells(struct tty *tty, const struct tty_ctx *ctx)
2080 {
2081 	struct overlay_ranges	 r;
2082 	u_int			 i, px, py, cx;
2083 	char			*cp = ctx->ptr;
2084 
2085 	if (!tty_is_visible(tty, ctx, ctx->ocx, ctx->ocy, ctx->num, 1))
2086 		return;
2087 
2088 	if (ctx->bigger &&
2089 	    (ctx->xoff + ctx->ocx < ctx->wox ||
2090 	    ctx->xoff + ctx->ocx + ctx->num > ctx->wox + ctx->wsx)) {
2091 		if (!ctx->wrapped ||
2092 		    !tty_full_width(tty, ctx) ||
2093 		    (tty->term->flags & TERM_NOAM) ||
2094 		    ctx->xoff + ctx->ocx != 0 ||
2095 		    ctx->yoff + ctx->ocy != tty->cy + 1 ||
2096 		    tty->cx < tty->sx ||
2097 		    tty->cy == tty->rlower)
2098 			tty_draw_pane(tty, ctx, ctx->ocy);
2099 		else
2100 			ctx->redraw_cb(ctx);
2101 		return;
2102 	}
2103 
2104 	tty_margin_off(tty);
2105 	tty_cursor_pane_unless_wrap(tty, ctx, ctx->ocx, ctx->ocy);
2106 	tty_attributes(tty, ctx->cell, &ctx->defaults, ctx->palette, ctx->s->hyperlinks);
2107 
2108 	/* Get tty position from pane position for overlay check. */
2109 	px = ctx->xoff + ctx->ocx - ctx->wox;
2110 	py = ctx->yoff + ctx->ocy - ctx->woy;
2111 
2112 	tty_check_overlay_range(tty, px, py, ctx->num, &r);
2113 	for (i = 0; i < OVERLAY_MAX_RANGES; i++) {
2114 		if (r.nx[i] == 0)
2115 			continue;
2116 		/* Convert back to pane position for printing. */
2117 		cx = r.px[i] - ctx->xoff + ctx->wox;
2118 		tty_cursor_pane_unless_wrap(tty, ctx, cx, ctx->ocy);
2119 		tty_putn(tty, cp + r.px[i] - px, r.nx[i], r.nx[i]);
2120 	}
2121 }
2122 
2123 void
2124 tty_cmd_setselection(struct tty *tty, const struct tty_ctx *ctx)
2125 {
2126 	tty_set_selection(tty, ctx->ptr2, ctx->ptr, ctx->num);
2127 }
2128 
2129 void
2130 tty_set_selection(struct tty *tty, const char *flags, const char *buf,
2131     size_t len)
2132 {
2133 	char	*encoded;
2134 	size_t	 size;
2135 
2136 	if (~tty->flags & TTY_STARTED)
2137 		return;
2138 	if (!tty_term_has(tty->term, TTYC_MS))
2139 		return;
2140 
2141 	size = 4 * ((len + 2) / 3) + 1; /* storage for base64 */
2142 	encoded = xmalloc(size);
2143 
2144 	b64_ntop(buf, len, encoded, size);
2145 	tty->flags |= TTY_NOBLOCK;
2146 	tty_putcode_ss(tty, TTYC_MS, flags, encoded);
2147 
2148 	free(encoded);
2149 }
2150 
2151 void
2152 tty_cmd_rawstring(struct tty *tty, const struct tty_ctx *ctx)
2153 {
2154 	tty->flags |= TTY_NOBLOCK;
2155 	tty_add(tty, ctx->ptr, ctx->num);
2156 	tty_invalidate(tty);
2157 }
2158 
2159 void
2160 tty_cmd_syncstart(struct tty *tty, const struct tty_ctx *ctx)
2161 {
2162 	if (ctx->num == 0x11) {
2163 		/*
2164 		 * This is an overlay and a command that moves the cursor so
2165 		 * start synchronized updates.
2166 		 */
2167 		tty_sync_start(tty);
2168 	} else if (~ctx->num & 0x10) {
2169 		/*
2170 		 * This is a pane. If there is an overlay, always start;
2171 		 * otherwise, only if requested.
2172 		 */
2173 		if (ctx->num || tty->client->overlay_draw != NULL)
2174 			tty_sync_start(tty);
2175 	}
2176 }
2177 
2178 void
2179 tty_cell(struct tty *tty, const struct grid_cell *gc,
2180     const struct grid_cell *defaults, struct colour_palette *palette,
2181     struct hyperlinks *hl)
2182 {
2183 	const struct grid_cell	*gcp;
2184 
2185 	/* Skip last character if terminal is stupid. */
2186 	if ((tty->term->flags & TERM_NOAM) &&
2187 	    tty->cy == tty->sy - 1 &&
2188 	    tty->cx == tty->sx - 1)
2189 		return;
2190 
2191 	/* If this is a padding character, do nothing. */
2192 	if (gc->flags & GRID_FLAG_PADDING)
2193 		return;
2194 
2195 	/* Check the output codeset and apply attributes. */
2196 	gcp = tty_check_codeset(tty, gc);
2197 	tty_attributes(tty, gcp, defaults, palette, hl);
2198 
2199 	/* If it is a single character, write with putc to handle ACS. */
2200 	if (gcp->data.size == 1) {
2201 		tty_attributes(tty, gcp, defaults, palette, hl);
2202 		if (*gcp->data.data < 0x20 || *gcp->data.data == 0x7f)
2203 			return;
2204 		tty_putc(tty, *gcp->data.data);
2205 		return;
2206 	}
2207 
2208 	/* Write the data. */
2209 	tty_putn(tty, gcp->data.data, gcp->data.size, gcp->data.width);
2210 }
2211 
2212 void
2213 tty_reset(struct tty *tty)
2214 {
2215 	struct grid_cell	*gc = &tty->cell;
2216 
2217 	if (!grid_cells_equal(gc, &grid_default_cell)) {
2218 		if (gc->link != 0)
2219 			tty_putcode_ss(tty, TTYC_HLS, "", "");
2220 		if ((gc->attr & GRID_ATTR_CHARSET) && tty_acs_needed(tty))
2221 			tty_putcode(tty, TTYC_RMACS);
2222 		tty_putcode(tty, TTYC_SGR0);
2223 		memcpy(gc, &grid_default_cell, sizeof *gc);
2224 	}
2225 	memcpy(&tty->last_cell, &grid_default_cell, sizeof tty->last_cell);
2226 }
2227 
2228 static void
2229 tty_invalidate(struct tty *tty)
2230 {
2231 	memcpy(&tty->cell, &grid_default_cell, sizeof tty->cell);
2232 	memcpy(&tty->last_cell, &grid_default_cell, sizeof tty->last_cell);
2233 
2234 	tty->cx = tty->cy = UINT_MAX;
2235 	tty->rupper = tty->rleft = UINT_MAX;
2236 	tty->rlower = tty->rright = UINT_MAX;
2237 
2238 	if (tty->flags & TTY_STARTED) {
2239 		if (tty_use_margin(tty))
2240 			tty_putcode(tty, TTYC_ENMG);
2241 		tty_putcode(tty, TTYC_SGR0);
2242 
2243 		tty->mode = ALL_MODES;
2244 		tty_update_mode(tty, MODE_CURSOR, NULL);
2245 
2246 		tty_cursor(tty, 0, 0);
2247 		tty_region_off(tty);
2248 		tty_margin_off(tty);
2249 	} else
2250 		tty->mode = MODE_CURSOR;
2251 }
2252 
2253 /* Turn off margin. */
2254 void
2255 tty_region_off(struct tty *tty)
2256 {
2257 	tty_region(tty, 0, tty->sy - 1);
2258 }
2259 
2260 /* Set region inside pane. */
2261 static void
2262 tty_region_pane(struct tty *tty, const struct tty_ctx *ctx, u_int rupper,
2263     u_int rlower)
2264 {
2265 	tty_region(tty, ctx->yoff + rupper - ctx->woy,
2266 	    ctx->yoff + rlower - ctx->woy);
2267 }
2268 
2269 /* Set region at absolute position. */
2270 static void
2271 tty_region(struct tty *tty, u_int rupper, u_int rlower)
2272 {
2273 	if (tty->rlower == rlower && tty->rupper == rupper)
2274 		return;
2275 	if (!tty_term_has(tty->term, TTYC_CSR))
2276 		return;
2277 
2278 	tty->rupper = rupper;
2279 	tty->rlower = rlower;
2280 
2281 	/*
2282 	 * Some terminals (such as PuTTY) do not correctly reset the cursor to
2283 	 * 0,0 if it is beyond the last column (they do not reset their wrap
2284 	 * flag so further output causes a line feed). As a workaround, do an
2285 	 * explicit move to 0 first.
2286 	 */
2287 	if (tty->cx >= tty->sx) {
2288 		if (tty->cy == UINT_MAX)
2289 			tty_cursor(tty, 0, 0);
2290 		else
2291 			tty_cursor(tty, 0, tty->cy);
2292 	}
2293 
2294 	tty_putcode_ii(tty, TTYC_CSR, tty->rupper, tty->rlower);
2295 	tty->cx = tty->cy = UINT_MAX;
2296 }
2297 
2298 /* Turn off margin. */
2299 void
2300 tty_margin_off(struct tty *tty)
2301 {
2302 	tty_margin(tty, 0, tty->sx - 1);
2303 }
2304 
2305 /* Set margin inside pane. */
2306 static void
2307 tty_margin_pane(struct tty *tty, const struct tty_ctx *ctx)
2308 {
2309 	tty_margin(tty, ctx->xoff - ctx->wox,
2310 	    ctx->xoff + ctx->sx - 1 - ctx->wox);
2311 }
2312 
2313 /* Set margin at absolute position. */
2314 static void
2315 tty_margin(struct tty *tty, u_int rleft, u_int rright)
2316 {
2317 	if (!tty_use_margin(tty))
2318 		return;
2319 	if (tty->rleft == rleft && tty->rright == rright)
2320 		return;
2321 
2322 	tty_putcode_ii(tty, TTYC_CSR, tty->rupper, tty->rlower);
2323 
2324 	tty->rleft = rleft;
2325 	tty->rright = rright;
2326 
2327 	if (rleft == 0 && rright == tty->sx - 1)
2328 		tty_putcode(tty, TTYC_CLMG);
2329 	else
2330 		tty_putcode_ii(tty, TTYC_CMG, rleft, rright);
2331 	tty->cx = tty->cy = UINT_MAX;
2332 }
2333 
2334 /*
2335  * Move the cursor, unless it would wrap itself when the next character is
2336  * printed.
2337  */
2338 static void
2339 tty_cursor_pane_unless_wrap(struct tty *tty, const struct tty_ctx *ctx,
2340     u_int cx, u_int cy)
2341 {
2342 	if (!ctx->wrapped ||
2343 	    !tty_full_width(tty, ctx) ||
2344 	    (tty->term->flags & TERM_NOAM) ||
2345 	    ctx->xoff + cx != 0 ||
2346 	    ctx->yoff + cy != tty->cy + 1 ||
2347 	    tty->cx < tty->sx ||
2348 	    tty->cy == tty->rlower)
2349 		tty_cursor_pane(tty, ctx, cx, cy);
2350 	else
2351 		log_debug("%s: will wrap at %u,%u", __func__, tty->cx, tty->cy);
2352 }
2353 
2354 /* Move cursor inside pane. */
2355 static void
2356 tty_cursor_pane(struct tty *tty, const struct tty_ctx *ctx, u_int cx, u_int cy)
2357 {
2358 	tty_cursor(tty, ctx->xoff + cx - ctx->wox, ctx->yoff + cy - ctx->woy);
2359 }
2360 
2361 /* Move cursor to absolute position. */
2362 void
2363 tty_cursor(struct tty *tty, u_int cx, u_int cy)
2364 {
2365 	struct tty_term	*term = tty->term;
2366 	u_int		 thisx, thisy;
2367 	int		 change;
2368 
2369 	if (tty->flags & TTY_BLOCK)
2370 		return;
2371 
2372 	thisx = tty->cx;
2373 	thisy = tty->cy;
2374 
2375 	/*
2376 	 * If in the automargin space, and want to be there, do not move.
2377 	 * Otherwise, force the cursor to be in range (and complain).
2378 	 */
2379 	if (cx == thisx && cy == thisy && cx == tty->sx)
2380 		return;
2381 	if (cx > tty->sx - 1) {
2382 		log_debug("%s: x too big %u > %u", __func__, cx, tty->sx - 1);
2383 		cx = tty->sx - 1;
2384 	}
2385 
2386 	/* No change. */
2387 	if (cx == thisx && cy == thisy)
2388 		return;
2389 
2390 	/* Currently at the very end of the line - use absolute movement. */
2391 	if (thisx > tty->sx - 1)
2392 		goto absolute;
2393 
2394 	/* Move to home position (0, 0). */
2395 	if (cx == 0 && cy == 0 && tty_term_has(term, TTYC_HOME)) {
2396 		tty_putcode(tty, TTYC_HOME);
2397 		goto out;
2398 	}
2399 
2400 	/* Zero on the next line. */
2401 	if (cx == 0 && cy == thisy + 1 && thisy != tty->rlower &&
2402 	    (!tty_use_margin(tty) || tty->rleft == 0)) {
2403 		tty_putc(tty, '\r');
2404 		tty_putc(tty, '\n');
2405 		goto out;
2406 	}
2407 
2408 	/* Moving column or row. */
2409 	if (cy == thisy) {
2410 		/*
2411 		 * Moving column only, row staying the same.
2412 		 */
2413 
2414 		/* To left edge. */
2415 		if (cx == 0 && (!tty_use_margin(tty) || tty->rleft == 0)) {
2416 			tty_putc(tty, '\r');
2417 			goto out;
2418 		}
2419 
2420 		/* One to the left. */
2421 		if (cx == thisx - 1 && tty_term_has(term, TTYC_CUB1)) {
2422 			tty_putcode(tty, TTYC_CUB1);
2423 			goto out;
2424 		}
2425 
2426 		/* One to the right. */
2427 		if (cx == thisx + 1 && tty_term_has(term, TTYC_CUF1)) {
2428 			tty_putcode(tty, TTYC_CUF1);
2429 			goto out;
2430 		}
2431 
2432 		/* Calculate difference. */
2433 		change = thisx - cx;	/* +ve left, -ve right */
2434 
2435 		/*
2436 		 * Use HPA if change is larger than absolute, otherwise move
2437 		 * the cursor with CUB/CUF.
2438 		 */
2439 		if ((u_int) abs(change) > cx && tty_term_has(term, TTYC_HPA)) {
2440 			tty_putcode_i(tty, TTYC_HPA, cx);
2441 			goto out;
2442 		} else if (change > 0 &&
2443 		    tty_term_has(term, TTYC_CUB) &&
2444 		    !tty_use_margin(tty)) {
2445 			if (change == 2 && tty_term_has(term, TTYC_CUB1)) {
2446 				tty_putcode(tty, TTYC_CUB1);
2447 				tty_putcode(tty, TTYC_CUB1);
2448 				goto out;
2449 			}
2450 			tty_putcode_i(tty, TTYC_CUB, change);
2451 			goto out;
2452 		} else if (change < 0 &&
2453 		    tty_term_has(term, TTYC_CUF) &&
2454 		    !tty_use_margin(tty)) {
2455 			tty_putcode_i(tty, TTYC_CUF, -change);
2456 			goto out;
2457 		}
2458 	} else if (cx == thisx) {
2459 		/*
2460 		 * Moving row only, column staying the same.
2461 		 */
2462 
2463 		/* One above. */
2464 		if (thisy != tty->rupper &&
2465 		    cy == thisy - 1 && tty_term_has(term, TTYC_CUU1)) {
2466 			tty_putcode(tty, TTYC_CUU1);
2467 			goto out;
2468 		}
2469 
2470 		/* One below. */
2471 		if (thisy != tty->rlower &&
2472 		    cy == thisy + 1 && tty_term_has(term, TTYC_CUD1)) {
2473 			tty_putcode(tty, TTYC_CUD1);
2474 			goto out;
2475 		}
2476 
2477 		/* Calculate difference. */
2478 		change = thisy - cy;	/* +ve up, -ve down */
2479 
2480 		/*
2481 		 * Try to use VPA if change is larger than absolute or if this
2482 		 * change would cross the scroll region, otherwise use CUU/CUD.
2483 		 */
2484 		if ((u_int) abs(change) > cy ||
2485 		    (change < 0 && cy - change > tty->rlower) ||
2486 		    (change > 0 && cy - change < tty->rupper)) {
2487 			    if (tty_term_has(term, TTYC_VPA)) {
2488 				    tty_putcode_i(tty, TTYC_VPA, cy);
2489 				    goto out;
2490 			    }
2491 		} else if (change > 0 && tty_term_has(term, TTYC_CUU)) {
2492 			tty_putcode_i(tty, TTYC_CUU, change);
2493 			goto out;
2494 		} else if (change < 0 && tty_term_has(term, TTYC_CUD)) {
2495 			tty_putcode_i(tty, TTYC_CUD, -change);
2496 			goto out;
2497 		}
2498 	}
2499 
2500 absolute:
2501 	/* Absolute movement. */
2502 	tty_putcode_ii(tty, TTYC_CUP, cy, cx);
2503 
2504 out:
2505 	tty->cx = cx;
2506 	tty->cy = cy;
2507 }
2508 
2509 static void
2510 tty_hyperlink(struct tty *tty, const struct grid_cell *gc,
2511     struct hyperlinks *hl)
2512 {
2513 	const char	*uri, *id;
2514 
2515 	if (gc->link == tty->cell.link)
2516 		return;
2517 	tty->cell.link = gc->link;
2518 
2519 	if (hl == NULL)
2520 		return;
2521 
2522 	if (gc->link == 0 || !hyperlinks_get(hl, gc->link, &uri, NULL, &id))
2523 		tty_putcode_ss(tty, TTYC_HLS, "", "");
2524 	else
2525 		tty_putcode_ss(tty, TTYC_HLS, id, uri);
2526 }
2527 
2528 void
2529 tty_attributes(struct tty *tty, const struct grid_cell *gc,
2530     const struct grid_cell *defaults, struct colour_palette *palette,
2531     struct hyperlinks *hl)
2532 {
2533 	struct grid_cell	*tc = &tty->cell, gc2;
2534 	int			 changed;
2535 
2536 	/* Copy cell and update default colours. */
2537 	memcpy(&gc2, gc, sizeof gc2);
2538 	if (~gc->flags & GRID_FLAG_NOPALETTE) {
2539 		if (gc2.fg == 8)
2540 			gc2.fg = defaults->fg;
2541 		if (gc2.bg == 8)
2542 			gc2.bg = defaults->bg;
2543 	}
2544 
2545 	/* Ignore cell if it is the same as the last one. */
2546 	if (gc2.attr == tty->last_cell.attr &&
2547 	    gc2.fg == tty->last_cell.fg &&
2548 	    gc2.bg == tty->last_cell.bg &&
2549 	    gc2.us == tty->last_cell.us &&
2550 		gc2.link == tty->last_cell.link)
2551 		return;
2552 
2553 	/*
2554 	 * If no setab, try to use the reverse attribute as a best-effort for a
2555 	 * non-default background. This is a bit of a hack but it doesn't do
2556 	 * any serious harm and makes a couple of applications happier.
2557 	 */
2558 	if (!tty_term_has(tty->term, TTYC_SETAB)) {
2559 		if (gc2.attr & GRID_ATTR_REVERSE) {
2560 			if (gc2.fg != 7 && !COLOUR_DEFAULT(gc2.fg))
2561 				gc2.attr &= ~GRID_ATTR_REVERSE;
2562 		} else {
2563 			if (gc2.bg != 0 && !COLOUR_DEFAULT(gc2.bg))
2564 				gc2.attr |= GRID_ATTR_REVERSE;
2565 		}
2566 	}
2567 
2568 	/* Fix up the colours if necessary. */
2569 	tty_check_fg(tty, palette, &gc2);
2570 	tty_check_bg(tty, palette, &gc2);
2571 	tty_check_us(tty, palette, &gc2);
2572 
2573 	/*
2574 	 * If any bits are being cleared or the underline colour is now default,
2575 	 * reset everything.
2576 	 */
2577 	if ((tc->attr & ~gc2.attr) || (tc->us != gc2.us && gc2.us == 0))
2578 		tty_reset(tty);
2579 
2580 	/*
2581 	 * Set the colours. This may call tty_reset() (so it comes next) and
2582 	 * may add to (NOT remove) the desired attributes.
2583 	 */
2584 	tty_colours(tty, &gc2);
2585 
2586 	/* Filter out attribute bits already set. */
2587 	changed = gc2.attr & ~tc->attr;
2588 	tc->attr = gc2.attr;
2589 
2590 	/* Set the attributes. */
2591 	if (changed & GRID_ATTR_BRIGHT)
2592 		tty_putcode(tty, TTYC_BOLD);
2593 	if (changed & GRID_ATTR_DIM)
2594 		tty_putcode(tty, TTYC_DIM);
2595 	if (changed & GRID_ATTR_ITALICS)
2596 		tty_set_italics(tty);
2597 	if (changed & GRID_ATTR_ALL_UNDERSCORE) {
2598 		if ((changed & GRID_ATTR_UNDERSCORE) ||
2599 		    !tty_term_has(tty->term, TTYC_SMULX))
2600 			tty_putcode(tty, TTYC_SMUL);
2601 		else if (changed & GRID_ATTR_UNDERSCORE_2)
2602 			tty_putcode_i(tty, TTYC_SMULX, 2);
2603 		else if (changed & GRID_ATTR_UNDERSCORE_3)
2604 			tty_putcode_i(tty, TTYC_SMULX, 3);
2605 		else if (changed & GRID_ATTR_UNDERSCORE_4)
2606 			tty_putcode_i(tty, TTYC_SMULX, 4);
2607 		else if (changed & GRID_ATTR_UNDERSCORE_5)
2608 			tty_putcode_i(tty, TTYC_SMULX, 5);
2609 	}
2610 	if (changed & GRID_ATTR_BLINK)
2611 		tty_putcode(tty, TTYC_BLINK);
2612 	if (changed & GRID_ATTR_REVERSE) {
2613 		if (tty_term_has(tty->term, TTYC_REV))
2614 			tty_putcode(tty, TTYC_REV);
2615 		else if (tty_term_has(tty->term, TTYC_SMSO))
2616 			tty_putcode(tty, TTYC_SMSO);
2617 	}
2618 	if (changed & GRID_ATTR_HIDDEN)
2619 		tty_putcode(tty, TTYC_INVIS);
2620 	if (changed & GRID_ATTR_STRIKETHROUGH)
2621 		tty_putcode(tty, TTYC_SMXX);
2622 	if (changed & GRID_ATTR_OVERLINE)
2623 		tty_putcode(tty, TTYC_SMOL);
2624 	if ((changed & GRID_ATTR_CHARSET) && tty_acs_needed(tty))
2625 		tty_putcode(tty, TTYC_SMACS);
2626 
2627 	/* Set hyperlink if any. */
2628 	tty_hyperlink(tty, gc, hl);
2629 
2630 	memcpy(&tty->last_cell, &gc2, sizeof tty->last_cell);
2631 }
2632 
2633 static void
2634 tty_colours(struct tty *tty, const struct grid_cell *gc)
2635 {
2636 	struct grid_cell	*tc = &tty->cell;
2637 	int			 have_ax;
2638 
2639 	/* No changes? Nothing is necessary. */
2640 	if (gc->fg == tc->fg && gc->bg == tc->bg && gc->us == tc->us)
2641 		return;
2642 
2643 	/*
2644 	 * Is either the default colour? This is handled specially because the
2645 	 * best solution might be to reset both colours to default, in which
2646 	 * case if only one is default need to fall onward to set the other
2647 	 * colour.
2648 	 */
2649 	if (COLOUR_DEFAULT(gc->fg) || COLOUR_DEFAULT(gc->bg)) {
2650 		/*
2651 		 * If don't have AX but do have op, send sgr0 (op can't
2652 		 * actually be used because it is sometimes the same as sgr0
2653 		 * and sometimes isn't). This resets both colours to default.
2654 		 *
2655 		 * Otherwise, try to set the default colour only as needed.
2656 		 */
2657 		have_ax = tty_term_flag(tty->term, TTYC_AX);
2658 		if (!have_ax && tty_term_has(tty->term, TTYC_OP))
2659 			tty_reset(tty);
2660 		else {
2661 			if (COLOUR_DEFAULT(gc->fg) && !COLOUR_DEFAULT(tc->fg)) {
2662 				if (have_ax)
2663 					tty_puts(tty, "\033[39m");
2664 				else if (tc->fg != 7)
2665 					tty_putcode_i(tty, TTYC_SETAF, 7);
2666 				tc->fg = gc->fg;
2667 			}
2668 			if (COLOUR_DEFAULT(gc->bg) && !COLOUR_DEFAULT(tc->bg)) {
2669 				if (have_ax)
2670 					tty_puts(tty, "\033[49m");
2671 				else if (tc->bg != 0)
2672 					tty_putcode_i(tty, TTYC_SETAB, 0);
2673 				tc->bg = gc->bg;
2674 			}
2675 		}
2676 	}
2677 
2678 	/* Set the foreground colour. */
2679 	if (!COLOUR_DEFAULT(gc->fg) && gc->fg != tc->fg)
2680 		tty_colours_fg(tty, gc);
2681 
2682 	/*
2683 	 * Set the background colour. This must come after the foreground as
2684 	 * tty_colour_fg() can call tty_reset().
2685 	 */
2686 	if (!COLOUR_DEFAULT(gc->bg) && gc->bg != tc->bg)
2687 		tty_colours_bg(tty, gc);
2688 
2689 	/* Set the underscore colour. */
2690 	if (gc->us != tc->us)
2691 		tty_colours_us(tty, gc);
2692 }
2693 
2694 static void
2695 tty_check_fg(struct tty *tty, struct colour_palette *palette,
2696     struct grid_cell *gc)
2697 {
2698 	u_char	r, g, b;
2699 	u_int	colours;
2700 	int	c;
2701 
2702 	/*
2703 	 * Perform substitution if this pane has a palette. If the bright
2704 	 * attribute is set and Nobr is not present, use the bright entry in
2705 	 * the palette by changing to the aixterm colour
2706 	 */
2707 	if (~gc->flags & GRID_FLAG_NOPALETTE) {
2708 		c = gc->fg;
2709 		if (c < 8 &&
2710 		    gc->attr & GRID_ATTR_BRIGHT &&
2711 		    !tty_term_has(tty->term, TTYC_NOBR))
2712 			c += 90;
2713 		if ((c = colour_palette_get(palette, c)) != -1)
2714 			gc->fg = c;
2715 	}
2716 
2717 	/* Is this a 24-bit colour? */
2718 	if (gc->fg & COLOUR_FLAG_RGB) {
2719 		/* Not a 24-bit terminal? Translate to 256-colour palette. */
2720 		if (tty->term->flags & TERM_RGBCOLOURS)
2721 			return;
2722 		colour_split_rgb(gc->fg, &r, &g, &b);
2723 		gc->fg = colour_find_rgb(r, g, b);
2724 	}
2725 
2726 	/* How many colours does this terminal have? */
2727 	if (tty->term->flags & TERM_256COLOURS)
2728 		colours = 256;
2729 	else
2730 		colours = tty_term_number(tty->term, TTYC_COLORS);
2731 
2732 	/* Is this a 256-colour colour? */
2733 	if (gc->fg & COLOUR_FLAG_256) {
2734 		/* And not a 256 colour mode? */
2735 		if (colours < 256) {
2736 			gc->fg = colour_256to16(gc->fg);
2737 			if (gc->fg & 8) {
2738 				gc->fg &= 7;
2739 				if (colours >= 16)
2740 					gc->fg += 90;
2741 			}
2742 		}
2743 		return;
2744 	}
2745 
2746 	/* Is this an aixterm colour? */
2747 	if (gc->fg >= 90 && gc->fg <= 97 && colours < 16) {
2748 		gc->fg -= 90;
2749 		gc->attr |= GRID_ATTR_BRIGHT;
2750 	}
2751 }
2752 
2753 static void
2754 tty_check_bg(struct tty *tty, struct colour_palette *palette,
2755     struct grid_cell *gc)
2756 {
2757 	u_char	r, g, b;
2758 	u_int	colours;
2759 	int	c;
2760 
2761 	/* Perform substitution if this pane has a palette. */
2762 	if (~gc->flags & GRID_FLAG_NOPALETTE) {
2763 		if ((c = colour_palette_get(palette, gc->bg)) != -1)
2764 			gc->bg = c;
2765 	}
2766 
2767 	/* Is this a 24-bit colour? */
2768 	if (gc->bg & COLOUR_FLAG_RGB) {
2769 		/* Not a 24-bit terminal? Translate to 256-colour palette. */
2770 		if (tty->term->flags & TERM_RGBCOLOURS)
2771 			return;
2772 		colour_split_rgb(gc->bg, &r, &g, &b);
2773 		gc->bg = colour_find_rgb(r, g, b);
2774 	}
2775 
2776 	/* How many colours does this terminal have? */
2777 	if (tty->term->flags & TERM_256COLOURS)
2778 		colours = 256;
2779 	else
2780 		colours = tty_term_number(tty->term, TTYC_COLORS);
2781 
2782 	/* Is this a 256-colour colour? */
2783 	if (gc->bg & COLOUR_FLAG_256) {
2784 		/*
2785 		 * And not a 256 colour mode? Translate to 16-colour
2786 		 * palette. Bold background doesn't exist portably, so just
2787 		 * discard the bold bit if set.
2788 		 */
2789 		if (colours < 256) {
2790 			gc->bg = colour_256to16(gc->bg);
2791 			if (gc->bg & 8) {
2792 				gc->bg &= 7;
2793 				if (colours >= 16)
2794 					gc->bg += 90;
2795 			}
2796 		}
2797 		return;
2798 	}
2799 
2800 	/* Is this an aixterm colour? */
2801 	if (gc->bg >= 90 && gc->bg <= 97 && colours < 16)
2802 		gc->bg -= 90;
2803 }
2804 
2805 static void
2806 tty_check_us(__unused struct tty *tty, struct colour_palette *palette,
2807     struct grid_cell *gc)
2808 {
2809 	int	c;
2810 
2811 	/* Perform substitution if this pane has a palette. */
2812 	if (~gc->flags & GRID_FLAG_NOPALETTE) {
2813 		if ((c = colour_palette_get(palette, gc->us)) != -1)
2814 			gc->us = c;
2815 	}
2816 
2817 	/* Underscore colour is set as RGB so convert. */
2818 	gc->us = colour_force_rgb (gc->us);
2819 	if (gc->us == -1)
2820 		gc->us = 8;
2821 }
2822 
2823 static void
2824 tty_colours_fg(struct tty *tty, const struct grid_cell *gc)
2825 {
2826 	struct grid_cell	*tc = &tty->cell;
2827 	char			 s[32];
2828 
2829 	/* Is this a 24-bit or 256-colour colour? */
2830 	if (gc->fg & COLOUR_FLAG_RGB || gc->fg & COLOUR_FLAG_256) {
2831 		if (tty_try_colour(tty, gc->fg, "38") == 0)
2832 			goto save;
2833 		/* Should not get here, already converted in tty_check_fg. */
2834 		return;
2835 	}
2836 
2837 	/* Is this an aixterm bright colour? */
2838 	if (gc->fg >= 90 && gc->fg <= 97) {
2839 		if (tty->term->flags & TERM_256COLOURS) {
2840 			xsnprintf(s, sizeof s, "\033[%dm", gc->fg);
2841 			tty_puts(tty, s);
2842 		} else
2843 			tty_putcode_i(tty, TTYC_SETAF, gc->fg - 90 + 8);
2844 		goto save;
2845 	}
2846 
2847 	/* Otherwise set the foreground colour. */
2848 	tty_putcode_i(tty, TTYC_SETAF, gc->fg);
2849 
2850 save:
2851 	/* Save the new values in the terminal current cell. */
2852 	tc->fg = gc->fg;
2853 }
2854 
2855 static void
2856 tty_colours_bg(struct tty *tty, const struct grid_cell *gc)
2857 {
2858 	struct grid_cell	*tc = &tty->cell;
2859 	char			 s[32];
2860 
2861 	/* Is this a 24-bit or 256-colour colour? */
2862 	if (gc->bg & COLOUR_FLAG_RGB || gc->bg & COLOUR_FLAG_256) {
2863 		if (tty_try_colour(tty, gc->bg, "48") == 0)
2864 			goto save;
2865 		/* Should not get here, already converted in tty_check_bg. */
2866 		return;
2867 	}
2868 
2869 	/* Is this an aixterm bright colour? */
2870 	if (gc->bg >= 90 && gc->bg <= 97) {
2871 		if (tty->term->flags & TERM_256COLOURS) {
2872 			xsnprintf(s, sizeof s, "\033[%dm", gc->bg + 10);
2873 			tty_puts(tty, s);
2874 		} else
2875 			tty_putcode_i(tty, TTYC_SETAB, gc->bg - 90 + 8);
2876 		goto save;
2877 	}
2878 
2879 	/* Otherwise set the background colour. */
2880 	tty_putcode_i(tty, TTYC_SETAB, gc->bg);
2881 
2882 save:
2883 	/* Save the new values in the terminal current cell. */
2884 	tc->bg = gc->bg;
2885 }
2886 
2887 static void
2888 tty_colours_us(struct tty *tty, const struct grid_cell *gc)
2889 {
2890 	struct grid_cell	*tc = &tty->cell;
2891 	u_int			 c;
2892 	u_char			 r, g, b;
2893 
2894 	/* Clear underline colour. */
2895 	if (gc->us == 0) {
2896 		tty_putcode(tty, TTYC_OL);
2897 		goto save;
2898 	}
2899 
2900 	/* Must be an RGB colour - this should never happen. */
2901 	if (~gc->us & COLOUR_FLAG_RGB)
2902 		return;
2903 
2904 	/*
2905 	 * Setulc and setal follows the ncurses(3) one argument "direct colour"
2906 	 * capability format. Calculate the colour value.
2907 	 */
2908 	colour_split_rgb(gc->us, &r, &g, &b);
2909 	c = (65536 * r) + (256 * g) + b;
2910 
2911 	/*
2912 	 * Write the colour. Only use setal if the RGB flag is set because the
2913 	 * non-RGB version may be wrong.
2914 	 */
2915 	if (tty_term_has(tty->term, TTYC_SETULC))
2916 		tty_putcode_i(tty, TTYC_SETULC, c);
2917 	else if (tty_term_has(tty->term, TTYC_SETAL) &&
2918 	    tty_term_has(tty->term, TTYC_RGB))
2919 		tty_putcode_i(tty, TTYC_SETAL, c);
2920 
2921 save:
2922 	/* Save the new values in the terminal current cell. */
2923 	tc->us = gc->us;
2924 }
2925 
2926 static int
2927 tty_try_colour(struct tty *tty, int colour, const char *type)
2928 {
2929 	u_char	r, g, b;
2930 
2931 	if (colour & COLOUR_FLAG_256) {
2932 		if (*type == '3' && tty_term_has(tty->term, TTYC_SETAF))
2933 			tty_putcode_i(tty, TTYC_SETAF, colour & 0xff);
2934 		else if (tty_term_has(tty->term, TTYC_SETAB))
2935 			tty_putcode_i(tty, TTYC_SETAB, colour & 0xff);
2936 		return (0);
2937 	}
2938 
2939 	if (colour & COLOUR_FLAG_RGB) {
2940 		colour_split_rgb(colour & 0xffffff, &r, &g, &b);
2941 		if (*type == '3' && tty_term_has(tty->term, TTYC_SETRGBF))
2942 			tty_putcode_iii(tty, TTYC_SETRGBF, r, g, b);
2943 		else if (tty_term_has(tty->term, TTYC_SETRGBB))
2944 			tty_putcode_iii(tty, TTYC_SETRGBB, r, g, b);
2945 		return (0);
2946 	}
2947 
2948 	return (-1);
2949 }
2950 
2951 static void
2952 tty_window_default_style(struct grid_cell *gc, struct window_pane *wp)
2953 {
2954 	memcpy(gc, &grid_default_cell, sizeof *gc);
2955 	gc->fg = wp->palette.fg;
2956 	gc->bg = wp->palette.bg;
2957 }
2958 
2959 void
2960 tty_default_colours(struct grid_cell *gc, struct window_pane *wp)
2961 {
2962 	struct options		*oo = wp->options;
2963 	struct format_tree	*ft;
2964 
2965 	memcpy(gc, &grid_default_cell, sizeof *gc);
2966 
2967 	if (wp->flags & PANE_STYLECHANGED) {
2968 		log_debug("%%%u: style changed", wp->id);
2969 		wp->flags &= ~PANE_STYLECHANGED;
2970 
2971 		ft = format_create(NULL, NULL, FORMAT_PANE|wp->id,
2972 		    FORMAT_NOJOBS);
2973 		format_defaults(ft, NULL, NULL, NULL, wp);
2974 		tty_window_default_style(&wp->cached_active_gc, wp);
2975 		style_add(&wp->cached_active_gc, oo, "window-active-style", ft);
2976 		tty_window_default_style(&wp->cached_gc, wp);
2977 		style_add(&wp->cached_gc, oo, "window-style", ft);
2978 		format_free(ft);
2979 	}
2980 
2981 	if (gc->fg == 8) {
2982 		if (wp == wp->window->active && wp->cached_active_gc.fg != 8)
2983 			gc->fg = wp->cached_active_gc.fg;
2984 		else
2985 			gc->fg = wp->cached_gc.fg;
2986 	}
2987 
2988 	if (gc->bg == 8) {
2989 		if (wp == wp->window->active && wp->cached_active_gc.bg != 8)
2990 			gc->bg = wp->cached_active_gc.bg;
2991 		else
2992 			gc->bg = wp->cached_gc.bg;
2993 	}
2994 }
2995 
2996 static void
2997 tty_default_attributes(struct tty *tty, const struct grid_cell *defaults,
2998     struct colour_palette *palette, u_int bg, struct hyperlinks *hl)
2999 {
3000 	struct grid_cell	gc;
3001 
3002 	memcpy(&gc, &grid_default_cell, sizeof gc);
3003 	gc.bg = bg;
3004 	tty_attributes(tty, &gc, defaults, palette, hl);
3005 }
3006 
3007 static void
3008 tty_clipboard_query_callback(__unused int fd, __unused short events, void *data)
3009 {
3010 	struct tty	*tty = data;
3011 	struct client	*c = tty->client;
3012 
3013 	c->flags &= ~CLIENT_CLIPBOARDBUFFER;
3014 	free(c->clipboard_panes);
3015 	c->clipboard_panes = NULL;
3016 	c->clipboard_npanes = 0;
3017 
3018 	tty->flags &= ~TTY_OSC52QUERY;
3019 }
3020 
3021 void
3022 tty_clipboard_query(struct tty *tty)
3023 {
3024 	struct timeval	 tv = { .tv_sec = TTY_QUERY_TIMEOUT };
3025 
3026 	if ((~tty->flags & TTY_STARTED) || (tty->flags & TTY_OSC52QUERY))
3027 		return;
3028 	tty_putcode_ss(tty, TTYC_MS, "", "?");
3029 
3030 	tty->flags |= TTY_OSC52QUERY;
3031 	evtimer_set(&tty->clipboard_timer, tty_clipboard_query_callback, tty);
3032 	evtimer_add(&tty->clipboard_timer, &tv);
3033 }
3034