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