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