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