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