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