xref: /netbsd-src/external/bsd/tmux/dist/tty.c (revision f3cfa6f6ce31685c6c4a758bc430e69eb99f50a4)
1 /* $OpenBSD$ */
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 *, struct window_pane *);
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 *, const struct window_pane *,
49 		    struct grid_cell *);
50 static void	tty_check_bg(struct tty *, const struct window_pane *,
51 		    struct grid_cell *);
52 static void	tty_colours_fg(struct tty *, const struct grid_cell *);
53 static void	tty_colours_bg(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 window_pane *,
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_cell(struct tty *, const struct grid_cell *,
68 		    const struct window_pane *);
69 static void	tty_default_colours(struct grid_cell *,
70 		    const struct window_pane *);
71 static void	tty_default_attributes(struct tty *, const struct window_pane *,
72 		    u_int);
73 
74 #define tty_use_margin(tty) \
75 	((tty)->term_type == TTY_VT420)
76 
77 #define tty_pane_full_width(tty, ctx) \
78 	((ctx)->xoff == 0 && screen_size_x((ctx)->wp->screen) >= (tty)->sx)
79 
80 #define TTY_BLOCK_INTERVAL (100000 /* 100 milliseconds */)
81 #define TTY_BLOCK_START(tty) (1 + ((tty)->sx * (tty)->sy) * 8)
82 #define TTY_BLOCK_STOP(tty) (1 + ((tty)->sx * (tty)->sy) / 8)
83 
84 void
85 tty_create_log(void)
86 {
87 	char	name[64];
88 
89 	xsnprintf(name, sizeof name, "tmux-out-%ld.log", (long)getpid());
90 
91 	tty_log_fd = open(name, O_WRONLY|O_CREAT|O_TRUNC, 0644);
92 	if (tty_log_fd != -1 && fcntl(tty_log_fd, F_SETFD, FD_CLOEXEC) == -1)
93 		fatal("fcntl failed");
94 }
95 
96 int
97 tty_init(struct tty *tty, struct client *c, int fd, char *term)
98 {
99 	if (!isatty(fd))
100 		return (-1);
101 
102 	memset(tty, 0, sizeof *tty);
103 
104 	if (term == NULL || *term == '\0')
105 		tty->term_name = xstrdup("unknown");
106 	else
107 		tty->term_name = xstrdup(term);
108 
109 	tty->fd = fd;
110 	tty->client = c;
111 
112 	tty->cstyle = 0;
113 	tty->ccolour = xstrdup("");
114 
115 	tty->flags = 0;
116 
117 	tty->term_flags = 0;
118 	tty->term_type = TTY_UNKNOWN;
119 
120 	return (0);
121 }
122 
123 void
124 tty_resize(struct tty *tty)
125 {
126 	struct client	*c = tty->client;
127 	struct winsize	 ws;
128 	u_int		 sx, sy;
129 
130 	if (ioctl(tty->fd, TIOCGWINSZ, &ws) != -1) {
131 		sx = ws.ws_col;
132 		if (sx == 0)
133 			sx = 80;
134 		sy = ws.ws_row;
135 		if (sy == 0)
136 			sy = 24;
137 	} else {
138 		sx = 80;
139 		sy = 24;
140 	}
141 	log_debug("%s: %s now %ux%u", __func__, c->name, sx, sy);
142 	tty_set_size(tty, sx, sy);
143 	tty_invalidate(tty);
144 }
145 
146 void
147 tty_set_size(struct tty *tty, u_int sx, u_int sy)
148 {
149 	tty->sx = sx;
150 	tty->sy = sy;
151 }
152 
153 static void
154 tty_read_callback(__unused int fd, __unused short events, void *data)
155 {
156 	struct tty	*tty = data;
157 	struct client	*c = tty->client;
158 	size_t		 size = EVBUFFER_LENGTH(tty->in);
159 	int		 nread;
160 
161 	nread = evbuffer_read(tty->in, tty->fd, -1);
162 	if (nread == 0 || nread == -1) {
163 		event_del(&tty->event_in);
164 		server_client_lost(tty->client);
165 		return;
166 	}
167 	log_debug("%s: read %d bytes (already %zu)", c->name, nread, size);
168 
169 	while (tty_keys_next(tty))
170 		;
171 }
172 
173 static void
174 tty_timer_callback(__unused int fd, __unused short events, void *data)
175 {
176 	struct tty	*tty = data;
177 	struct client	*c = tty->client;
178 	struct timeval	 tv = { .tv_usec = TTY_BLOCK_INTERVAL };
179 
180 	log_debug("%s: %zu discarded", c->name, tty->discarded);
181 
182 	c->flags |= CLIENT_REDRAW;
183 	c->discarded += tty->discarded;
184 
185 	if (tty->discarded < TTY_BLOCK_STOP(tty)) {
186 		tty->flags &= ~TTY_BLOCK;
187 		tty_invalidate(tty);
188 		return;
189 	}
190 	tty->discarded = 0;
191 	evtimer_add(&tty->timer, &tv);
192 }
193 
194 static int
195 tty_block_maybe(struct tty *tty)
196 {
197 	struct client	*c = tty->client;
198 	size_t		 size = EVBUFFER_LENGTH(tty->out);
199 	struct timeval	 tv = { .tv_usec = TTY_BLOCK_INTERVAL };
200 
201 	if (size < TTY_BLOCK_START(tty))
202 		return (0);
203 
204 	if (tty->flags & TTY_BLOCK)
205 		return (1);
206 	tty->flags |= TTY_BLOCK;
207 
208 	log_debug("%s: can't keep up, %zu discarded", c->name, size);
209 
210 	evbuffer_drain(tty->out, size);
211 	c->discarded += size;
212 
213 	tty->discarded = 0;
214 	evtimer_add(&tty->timer, &tv);
215 	return (1);
216 }
217 
218 static void
219 tty_write_callback(__unused int fd, __unused short events, void *data)
220 {
221 	struct tty	*tty = data;
222 	struct client	*c = tty->client;
223 	size_t		 size = EVBUFFER_LENGTH(tty->out);
224 	int		 nwrite;
225 
226 	nwrite = evbuffer_write(tty->out, tty->fd);
227 	if (nwrite == -1)
228 		return;
229 	log_debug("%s: wrote %d bytes (of %zu)", c->name, nwrite, size);
230 
231 	if (c->redraw > 0) {
232 		if ((size_t)nwrite >= c->redraw)
233 			c->redraw = 0;
234 		else
235 			c->redraw -= nwrite;
236 		log_debug("%s: waiting for redraw, %zu bytes left", c->name,
237 		    c->redraw);
238 	} else if (tty_block_maybe(tty))
239 		return;
240 
241 	if (EVBUFFER_LENGTH(tty->out) != 0)
242 		event_add(&tty->event_out, NULL);
243 }
244 
245 int
246 tty_open(struct tty *tty, char **cause)
247 {
248 	tty->term = tty_term_find(tty->term_name, tty->fd, cause);
249 	if (tty->term == NULL) {
250 		tty_close(tty);
251 		return (-1);
252 	}
253 	tty->flags |= TTY_OPENED;
254 
255 	tty->flags &= ~(TTY_NOCURSOR|TTY_FREEZE|TTY_BLOCK|TTY_TIMER);
256 
257 	event_set(&tty->event_in, tty->fd, EV_PERSIST|EV_READ,
258 	    tty_read_callback, tty);
259 	tty->in = evbuffer_new();
260 
261 	event_set(&tty->event_out, tty->fd, EV_WRITE, tty_write_callback, tty);
262 	tty->out = evbuffer_new();
263 
264 	evtimer_set(&tty->timer, tty_timer_callback, tty);
265 
266 	tty_start_tty(tty);
267 
268 	tty_keys_build(tty);
269 
270 	return (0);
271 }
272 
273 void
274 tty_start_tty(struct tty *tty)
275 {
276 	struct client	*c = tty->client;
277 	struct termios	 tio;
278 
279 	if (tty->fd != -1 && tcgetattr(tty->fd, &tty->tio) == 0) {
280 		setblocking(tty->fd, 0);
281 		event_add(&tty->event_in, NULL);
282 
283 		memcpy(&tio, &tty->tio, sizeof tio);
284 		tio.c_iflag &= ~(IXON|IXOFF|ICRNL|INLCR|IGNCR|IMAXBEL|ISTRIP);
285 		tio.c_iflag |= IGNBRK;
286 		tio.c_oflag &= ~(OPOST|ONLCR|OCRNL|ONLRET);
287 		tio.c_lflag &= ~(IEXTEN|ICANON|ECHO|ECHOE|ECHONL|ECHOCTL|
288 		    ECHOPRT|ECHOKE|ISIG);
289 		tio.c_cc[VMIN] = 1;
290 		tio.c_cc[VTIME] = 0;
291 		if (tcsetattr(tty->fd, TCSANOW, &tio) == 0)
292 			tcflush(tty->fd, TCIOFLUSH);
293 	}
294 
295 	tty_putcode(tty, TTYC_SMCUP);
296 
297 	tty_putcode(tty, TTYC_SMKX);
298 	tty_putcode(tty, TTYC_CLEAR);
299 
300 	if (tty_acs_needed(tty)) {
301 		log_debug("%s: using capabilities for ACS", c->name);
302 		tty_putcode(tty, TTYC_ENACS);
303 	} else
304 		log_debug("%s: using UTF-8 for ACS", c->name);
305 
306 	tty_putcode(tty, TTYC_CNORM);
307 	if (tty_term_has(tty->term, TTYC_KMOUS))
308 		tty_puts(tty, "\033[?1000l\033[?1002l\033[?1006l\033[?1005l");
309 
310 	if (tty_term_flag(tty->term, TTYC_XT)) {
311 		if (options_get_number(global_options, "focus-events")) {
312 			tty->flags |= TTY_FOCUS;
313 			tty_puts(tty, "\033[?1004h");
314 		}
315 		tty_puts(tty, "\033[c");
316 	}
317 
318 	tty->flags |= TTY_STARTED;
319 	tty_invalidate(tty);
320 
321 	tty_force_cursor_colour(tty, "");
322 
323 	tty->mouse_drag_flag = 0;
324 	tty->mouse_drag_update = NULL;
325 	tty->mouse_drag_release = NULL;
326 }
327 
328 void
329 tty_stop_tty(struct tty *tty)
330 {
331 	struct winsize	ws;
332 
333 	if (!(tty->flags & TTY_STARTED))
334 		return;
335 	tty->flags &= ~TTY_STARTED;
336 
337 	event_del(&tty->timer);
338 	tty->flags &= ~TTY_BLOCK;
339 
340 	event_del(&tty->event_in);
341 	event_del(&tty->event_out);
342 
343 	/*
344 	 * Be flexible about error handling and try not kill the server just
345 	 * because the fd is invalid. Things like ssh -t can easily leave us
346 	 * with a dead tty.
347 	 */
348 	if (ioctl(tty->fd, TIOCGWINSZ, &ws) == -1)
349 		return;
350 	if (tcsetattr(tty->fd, TCSANOW, &tty->tio) == -1)
351 		return;
352 
353 	tty_raw(tty, tty_term_string2(tty->term, TTYC_CSR, 0, ws.ws_row - 1));
354 	if (tty_acs_needed(tty))
355 		tty_raw(tty, tty_term_string(tty->term, TTYC_RMACS));
356 	tty_raw(tty, tty_term_string(tty->term, TTYC_SGR0));
357 	tty_raw(tty, tty_term_string(tty->term, TTYC_RMKX));
358 	tty_raw(tty, tty_term_string(tty->term, TTYC_CLEAR));
359 	if (tty_term_has(tty->term, TTYC_SS) && tty->cstyle != 0) {
360 		if (tty_term_has(tty->term, TTYC_SE))
361 			tty_raw(tty, tty_term_string(tty->term, TTYC_SE));
362 		else
363 			tty_raw(tty, tty_term_string1(tty->term, TTYC_SS, 0));
364 	}
365 	if (tty->mode & MODE_BRACKETPASTE)
366 		tty_raw(tty, "\033[?2004l");
367 	tty_raw(tty, tty_term_string(tty->term, TTYC_CR));
368 
369 	tty_raw(tty, tty_term_string(tty->term, TTYC_CNORM));
370 	if (tty_term_has(tty->term, TTYC_KMOUS))
371 		tty_raw(tty, "\033[?1000l\033[?1002l\033[?1006l\033[?1005l");
372 
373 	if (tty_term_flag(tty->term, TTYC_XT)) {
374 		if (tty->flags & TTY_FOCUS) {
375 			tty->flags &= ~TTY_FOCUS;
376 			tty_raw(tty, "\033[?1004l");
377 		}
378 	}
379 
380 	if (tty_use_margin(tty))
381 		tty_raw(tty, "\033[?69l"); /* DECLRMM */
382 	tty_raw(tty, tty_term_string(tty->term, TTYC_RMCUP));
383 
384 	setblocking(tty->fd, 1);
385 }
386 
387 void
388 tty_close(struct tty *tty)
389 {
390 	if (event_initialized(&tty->key_timer))
391 		evtimer_del(&tty->key_timer);
392 	tty_stop_tty(tty);
393 
394 	if (tty->flags & TTY_OPENED) {
395 		evbuffer_free(tty->in);
396 		event_del(&tty->event_in);
397 		evbuffer_free(tty->out);
398 		event_del(&tty->event_out);
399 
400 		tty_term_free(tty->term);
401 		tty_keys_free(tty);
402 
403 		tty->flags &= ~TTY_OPENED;
404 	}
405 
406 	if (tty->fd != -1) {
407 		close(tty->fd);
408 		tty->fd = -1;
409 	}
410 }
411 
412 void
413 tty_free(struct tty *tty)
414 {
415 	tty_close(tty);
416 
417 	free(tty->ccolour);
418 	free(tty->term_name);
419 }
420 
421 void
422 tty_set_type(struct tty *tty, int type)
423 {
424 	tty->term_type = type;
425 
426 	if (tty_use_margin(tty))
427 		tty_puts(tty, "\033[?69h"); /* DECLRMM */
428 }
429 
430 void
431 tty_raw(struct tty *tty, const char *s)
432 {
433 	ssize_t	n, slen;
434 	u_int	i;
435 
436 	slen = strlen(s);
437 	for (i = 0; i < 5; i++) {
438 		n = write(tty->fd, s, slen);
439 		if (n >= 0) {
440 			s += n;
441 			slen -= n;
442 			if (slen == 0)
443 				break;
444 		} else if (n == -1 && errno != EAGAIN)
445 			break;
446 		usleep(100);
447 	}
448 }
449 
450 void
451 tty_putcode(struct tty *tty, enum tty_code_code code)
452 {
453 	tty_puts(tty, tty_term_string(tty->term, code));
454 }
455 
456 void
457 tty_putcode1(struct tty *tty, enum tty_code_code code, int a)
458 {
459 	if (a < 0)
460 		return;
461 	tty_puts(tty, tty_term_string1(tty->term, code, a));
462 }
463 
464 void
465 tty_putcode2(struct tty *tty, enum tty_code_code code, int a, int b)
466 {
467 	if (a < 0 || b < 0)
468 		return;
469 	tty_puts(tty, tty_term_string2(tty->term, code, a, b));
470 }
471 
472 void
473 tty_putcode3(struct tty *tty, enum tty_code_code code, int a, int b, int c)
474 {
475 	if (a < 0 || b < 0 || c < 0)
476 		return;
477 	tty_puts(tty, tty_term_string3(tty->term, code, a, b, c));
478 }
479 
480 void
481 tty_putcode_ptr1(struct tty *tty, enum tty_code_code code, const void *a)
482 {
483 	if (a != NULL)
484 		tty_puts(tty, tty_term_ptr1(tty->term, code, a));
485 }
486 
487 void
488 tty_putcode_ptr2(struct tty *tty, enum tty_code_code code, const void *a,
489     const void *b)
490 {
491 	if (a != NULL && b != NULL)
492 		tty_puts(tty, tty_term_ptr2(tty->term, code, a, b));
493 }
494 
495 static void
496 tty_add(struct tty *tty, const char *buf, size_t len)
497 {
498 	struct client	*c = tty->client;
499 
500 	if (tty->flags & TTY_BLOCK) {
501 		tty->discarded += len;
502 		return;
503 	}
504 
505 	evbuffer_add(tty->out, buf, len);
506 	log_debug("%s: %.*s", c->name, (int)len, buf);
507 	c->written += len;
508 
509 	if (tty_log_fd != -1)
510 		write(tty_log_fd, buf, len);
511 	if (tty->flags & TTY_STARTED)
512 		event_add(&tty->event_out, NULL);
513 }
514 
515 void
516 tty_puts(struct tty *tty, const char *s)
517 {
518 	if (*s != '\0')
519 		tty_add(tty, s, strlen(s));
520 }
521 
522 void
523 tty_putc(struct tty *tty, u_char ch)
524 {
525 	const char	*acs;
526 
527 	if (tty->cell.attr & GRID_ATTR_CHARSET) {
528 		acs = tty_acs_get(tty, ch);
529 		if (acs != NULL)
530 			tty_add(tty, acs, strlen(acs));
531 		else
532 			tty_add(tty, (char *)&ch, 1);
533 	} else
534 		tty_add(tty, (char *)&ch, 1);
535 
536 	if (ch >= 0x20 && ch != 0x7f) {
537 		if (tty->cx >= tty->sx) {
538 			tty->cx = 1;
539 			if (tty->cy != tty->rlower)
540 				tty->cy++;
541 
542 			/*
543 			 * On !xenl terminals, force the cursor position to
544 			 * where we think it should be after a line wrap - this
545 			 * means it works on sensible terminals as well.
546 			 */
547 			if (tty->term->flags & TERM_EARLYWRAP)
548 				tty_putcode2(tty, TTYC_CUP, tty->cy, tty->cx);
549 		} else
550 			tty->cx++;
551 	}
552 }
553 
554 void
555 tty_putn(struct tty *tty, const void *buf, size_t len, u_int width)
556 {
557 	tty_add(tty, buf, len);
558 	if (tty->cx + width > tty->sx) {
559 		tty->cx = (tty->cx + width) - tty->sx;
560 		if (tty->cx <= tty->sx)
561 			tty->cy++;
562 		else
563 			tty->cx = tty->cy = UINT_MAX;
564 	} else
565 		tty->cx += width;
566 }
567 
568 static void
569 tty_set_italics(struct tty *tty)
570 {
571 	const char	*s;
572 
573 	if (tty_term_has(tty->term, TTYC_SITM)) {
574 		s = options_get_string(global_options, "default-terminal");
575 		if (strcmp(s, "screen") != 0 && strncmp(s, "screen-", 7) != 0) {
576 			tty_putcode(tty, TTYC_SITM);
577 			return;
578 		}
579 	}
580 	tty_putcode(tty, TTYC_SMSO);
581 }
582 
583 void
584 tty_set_title(struct tty *tty, const char *title)
585 {
586 	if (!tty_term_has(tty->term, TTYC_TSL) ||
587 	    !tty_term_has(tty->term, TTYC_FSL))
588 		return;
589 
590 	tty_putcode(tty, TTYC_TSL);
591 	tty_puts(tty, title);
592 	tty_putcode(tty, TTYC_FSL);
593 }
594 
595 static void
596 tty_force_cursor_colour(struct tty *tty, const char *ccolour)
597 {
598 	if (*ccolour == '\0')
599 		tty_putcode(tty, TTYC_CR);
600 	else
601 		tty_putcode_ptr1(tty, TTYC_CS, ccolour);
602 	free(tty->ccolour);
603 	tty->ccolour = xstrdup(ccolour);
604 }
605 
606 void
607 tty_update_mode(struct tty *tty, int mode, struct screen *s)
608 {
609 	int	changed;
610 
611 	if (s != NULL && strcmp(s->ccolour, tty->ccolour) != 0)
612 		tty_force_cursor_colour(tty, s->ccolour);
613 
614 	if (tty->flags & TTY_NOCURSOR)
615 		mode &= ~MODE_CURSOR;
616 
617 	changed = mode ^ tty->mode;
618 	if (changed & MODE_BLINKING) {
619 		if (tty_term_has(tty->term, TTYC_CVVIS))
620 			tty_putcode(tty, TTYC_CVVIS);
621 		else
622 			tty_putcode(tty, TTYC_CNORM);
623 		changed |= MODE_CURSOR;
624 	}
625 	if (changed & MODE_CURSOR) {
626 		if (mode & MODE_CURSOR)
627 			tty_putcode(tty, TTYC_CNORM);
628 		else
629 			tty_putcode(tty, TTYC_CIVIS);
630 	}
631 	if (s != NULL && tty->cstyle != s->cstyle) {
632 		if (tty_term_has(tty->term, TTYC_SS)) {
633 			if (s->cstyle == 0 &&
634 			    tty_term_has(tty->term, TTYC_SE))
635 				tty_putcode(tty, TTYC_SE);
636 			else
637 				tty_putcode1(tty, TTYC_SS, s->cstyle);
638 		}
639 		tty->cstyle = s->cstyle;
640 	}
641 	if (changed & ALL_MOUSE_MODES) {
642 		if (mode & ALL_MOUSE_MODES) {
643 			/*
644 			 * Enable the SGR (1006) extension unconditionally, as
645 			 * it is safe from misinterpretation.
646 			 */
647 			tty_puts(tty, "\033[?1006h");
648 			if (mode & MODE_MOUSE_ALL)
649 				tty_puts(tty, "\033[?1003h");
650 			else if (mode & MODE_MOUSE_BUTTON)
651 				tty_puts(tty, "\033[?1002h");
652 			else if (mode & MODE_MOUSE_STANDARD)
653 				tty_puts(tty, "\033[?1000h");
654 		} else {
655 			if (tty->mode & MODE_MOUSE_ALL)
656 				tty_puts(tty, "\033[?1003l");
657 			else if (tty->mode & MODE_MOUSE_BUTTON)
658 				tty_puts(tty, "\033[?1002l");
659 			else if (tty->mode & MODE_MOUSE_STANDARD)
660 				tty_puts(tty, "\033[?1000l");
661 			tty_puts(tty, "\033[?1006l");
662 		}
663 	}
664 	if (changed & MODE_BRACKETPASTE) {
665 		if (mode & MODE_BRACKETPASTE)
666 			tty_puts(tty, "\033[?2004h");
667 		else
668 			tty_puts(tty, "\033[?2004l");
669 	}
670 	tty->mode = mode;
671 }
672 
673 static void
674 tty_emulate_repeat(struct tty *tty, enum tty_code_code code,
675     enum tty_code_code code1, u_int n)
676 {
677 	if (tty_term_has(tty->term, code))
678 		tty_putcode1(tty, code, n);
679 	else {
680 		while (n-- > 0)
681 			tty_putcode(tty, code1);
682 	}
683 }
684 
685 static void
686 tty_repeat_space(struct tty *tty, u_int n)
687 {
688 	static char s[500];
689 
690 	if (*s != ' ')
691 		memset(s, ' ', sizeof s);
692 
693 	while (n > sizeof s) {
694 		tty_putn(tty, s, sizeof s, sizeof s);
695 		n -= sizeof s;
696 	}
697 	if (n != 0)
698 		tty_putn(tty, s, n, n);
699 }
700 
701 /*
702  * Is the region large enough to be worth redrawing once later rather than
703  * probably several times now? Currently yes if it is more than 50% of the
704  * pane.
705  */
706 static int
707 tty_large_region(__unused struct tty *tty, const struct tty_ctx *ctx)
708 {
709 	struct window_pane	*wp = ctx->wp;
710 
711 	return (ctx->orlower - ctx->orupper >= screen_size_y(wp->screen) / 2);
712 }
713 
714 /*
715  * Return if BCE is needed but the terminal doesn't have it - it'll need to be
716  * emulated.
717  */
718 static int
719 tty_fake_bce(const struct tty *tty, const struct window_pane *wp, u_int bg)
720 {
721 	struct grid_cell	gc;
722 
723 	if (tty_term_flag(tty->term, TTYC_BCE))
724 		return (0);
725 
726 	memcpy(&gc, &grid_default_cell, sizeof gc);
727 	if (wp != NULL)
728 		tty_default_colours(&gc, wp);
729 
730 	if (bg != 8 || gc.bg != 8)
731 		return (1);
732 	return (0);
733 }
734 
735 /*
736  * Redraw scroll region using data from screen (already updated). Used when
737  * CSR not supported, or window is a pane that doesn't take up the full
738  * width of the terminal.
739  */
740 static void
741 tty_redraw_region(struct tty *tty, const struct tty_ctx *ctx)
742 {
743 	struct window_pane	*wp = ctx->wp;
744 	struct screen		*s = wp->screen;
745 	u_int			 i;
746 
747 	/*
748 	 * If region is large, schedule a window redraw. In most cases this is
749 	 * likely to be followed by some more scrolling.
750 	 */
751 	if (tty_large_region(tty, ctx)) {
752 		wp->flags |= PANE_REDRAW;
753 		return;
754 	}
755 
756 	if (ctx->ocy < ctx->orupper || ctx->ocy > ctx->orlower) {
757 		for (i = ctx->ocy; i < screen_size_y(s); i++)
758 			tty_draw_pane(tty, wp, i, ctx->xoff, ctx->yoff);
759 	} else {
760 		for (i = ctx->orupper; i <= ctx->orlower; i++)
761 			tty_draw_pane(tty, wp, i, ctx->xoff, ctx->yoff);
762 	}
763 }
764 
765 static void
766 tty_clear_line(struct tty *tty, const struct window_pane *wp, u_int py,
767     u_int px, u_int nx, u_int bg)
768 {
769 	log_debug("%s: %u at %u,%u", __func__, nx, px, py);
770 
771 	/* Nothing to clear. */
772 	if (nx == 0)
773 		return;
774 
775 	/* If genuine BCE is available, can try escape sequences. */
776 	if (!tty_fake_bce(tty, wp, bg)) {
777 		/* Off the end of the line, use EL if available. */
778 		if (px + nx >= tty->sx && tty_term_has(tty->term, TTYC_EL)) {
779 			tty_cursor(tty, px, py);
780 			tty_putcode(tty, TTYC_EL);
781 			return;
782 		}
783 
784 		/* At the start of the line. Use EL1. */
785 		if (px == 0 && tty_term_has(tty->term, TTYC_EL1)) {
786 			tty_cursor(tty, px + nx - 1, py);
787 			tty_putcode(tty, TTYC_EL1);
788 			return;
789 		}
790 
791 		/* Section of line. Use ECH if possible. */
792 		if (tty_term_has(tty->term, TTYC_ECH)) {
793 			tty_cursor(tty, px, py);
794 			tty_putcode1(tty, TTYC_ECH, nx);
795 			return;
796 		}
797 	}
798 
799 	/* Couldn't use an escape sequence, use spaces. */
800 	tty_cursor(tty, px, py);
801 	tty_repeat_space(tty, nx);
802 }
803 
804 static void
805 tty_clear_area(struct tty *tty, const struct window_pane *wp, u_int py,
806     u_int ny, u_int px, u_int nx, u_int bg)
807 {
808 	u_int	yy;
809 	char	tmp[64];
810 
811 	log_debug("%s: %u,%u at %u,%u", __func__, nx, ny, px, py);
812 
813 	/* Nothing to clear. */
814 	if (nx == 0 || ny == 0)
815 		return;
816 
817 	/* If genuine BCE is available, can try escape sequences. */
818 	if (!tty_fake_bce(tty, wp, bg)) {
819 		/* Use ED if clearing off the bottom of the terminal. */
820 		if (px == 0 &&
821 		    px + nx >= tty->sx &&
822 		    py + ny >= tty->sy &&
823 		    tty_term_has(tty->term, TTYC_ED)) {
824 			tty_cursor(tty, 0, py);
825 			tty_putcode(tty, TTYC_ED);
826 			return;
827 		}
828 
829 		/*
830 		 * On VT420 compatible terminals we can use DECFRA if the
831 		 * background colour isn't default (because it doesn't work
832 		 * after SGR 0).
833 		 */
834 		if (tty->term_type == TTY_VT420 && bg != 8) {
835 			xsnprintf(tmp, sizeof tmp, "\033[32;%u;%u;%u;%u$x",
836 			    py + 1, px + 1, py + ny, px + nx);
837 			tty_puts(tty, tmp);
838 			return;
839 		}
840 
841 		/* Full lines can be scrolled away to clear them. */
842 		if (px == 0 &&
843 		    px + nx >= tty->sx &&
844 		    ny > 2 &&
845 		    tty_term_has(tty->term, TTYC_CSR) &&
846 		    tty_term_has(tty->term, TTYC_INDN)) {
847 			tty_region(tty, py, py + ny - 1);
848 			tty_margin_off(tty);
849 			tty_putcode1(tty, TTYC_INDN, ny);
850 			return;
851 		}
852 
853 		/*
854 		 * If margins are supported, can just scroll the area off to
855 		 * clear it.
856 		 */
857 		if (nx > 2 &&
858 		    ny > 2 &&
859 		    tty_term_has(tty->term, TTYC_CSR) &&
860 		    tty_use_margin(tty) &&
861 		    tty_term_has(tty->term, TTYC_INDN)) {
862 			tty_region(tty, py, py + ny - 1);
863 			tty_margin(tty, px, px + nx - 1);
864 			tty_putcode1(tty, TTYC_INDN, ny);
865 			return;
866 		}
867 	}
868 
869 	/* Couldn't use an escape sequence, loop over the lines. */
870 	for (yy = py; yy < py + ny; yy++)
871 		tty_clear_line(tty, wp, yy, px, nx, bg);
872 }
873 
874 void
875 tty_draw_pane(struct tty *tty, const struct window_pane *wp, u_int py, u_int ox,
876     u_int oy)
877 {
878 	tty_draw_line(tty, wp, wp->screen, py, ox, oy);
879 }
880 
881 static const struct grid_cell *
882 tty_check_codeset(struct tty *tty, const struct grid_cell *gc)
883 {
884 	static struct grid_cell	new;
885 	u_int			n;
886 
887 	/* Characters less than 0x7f are always fine, no matter what. */
888 	if (gc->data.size == 1 && *gc->data.data < 0x7f)
889 		return (gc);
890 
891 	/* UTF-8 terminal and a UTF-8 character - fine. */
892 	if (tty->flags & TTY_UTF8)
893 		return (gc);
894 
895 	/* Replace by the right number of underscores. */
896 	n = gc->data.width;
897 	if (n > UTF8_SIZE)
898 		n = UTF8_SIZE;
899 	memcpy(&new, gc, sizeof new);
900 	new.data.size = n;
901 	memset(new.data.data, '_', n);
902 	return (&new);
903 }
904 
905 void
906 tty_draw_line(struct tty *tty, const struct window_pane *wp,
907     struct screen *s, u_int py, u_int ox, u_int oy)
908 {
909 	struct grid		*gd = s->grid;
910 	struct grid_cell	 gc, last;
911 	const struct grid_cell	*gcp;
912 	u_int			 i, j, ux, sx, nx, width;
913 	int			 flags, cleared = 0;
914 	char			 buf[512];
915 	size_t			 len, old_len;
916 	u_int			 cellsize;
917 
918 	flags = (tty->flags & TTY_NOCURSOR);
919 	tty->flags |= TTY_NOCURSOR;
920 	tty_update_mode(tty, tty->mode, s);
921 
922 	tty_region_off(tty);
923 	tty_margin_off(tty);
924 
925 	/*
926 	 * Clamp the width to cellsize - note this is not cellused, because
927 	 * there may be empty background cells after it (from BCE).
928 	 */
929 	sx = screen_size_x(s);
930 
931 	cellsize = grid_get_line(gd, gd->hsize + py)->cellsize;
932 	if (sx > cellsize)
933 		sx = cellsize;
934 	if (sx > tty->sx)
935 		sx = tty->sx;
936 	ux = 0;
937 
938 	if (wp == NULL ||
939 	    py == 0 ||
940 	    (~grid_get_line(gd, gd->hsize + py - 1)->flags & GRID_LINE_WRAPPED) ||
941 	    ox != 0 ||
942 	    tty->cx < tty->sx ||
943 	    screen_size_x(s) < tty->sx) {
944 		if (screen_size_x(s) < tty->sx &&
945 		    ox == 0 &&
946 		    sx != screen_size_x(s) &&
947 		    tty_term_has(tty->term, TTYC_EL1) &&
948 		    !tty_fake_bce(tty, wp, 8)) {
949 			tty_default_attributes(tty, wp, 8);
950 			tty_cursor(tty, screen_size_x(s) - 1, oy + py);
951 			tty_putcode(tty, TTYC_EL1);
952 			cleared = 1;
953 		}
954 		if (sx != 0)
955 			tty_cursor(tty, ox, oy + py);
956 	} else
957 		log_debug("%s: wrapped line %u", __func__, oy + py);
958 
959 	memcpy(&last, &grid_default_cell, sizeof last);
960 	len = 0;
961 	width = 0;
962 
963 	for (i = 0; i < sx; i++) {
964 		grid_view_get_cell(gd, i, py, &gc);
965 		gcp = tty_check_codeset(tty, &gc);
966 		if (len != 0 &&
967 		    ((gcp->attr & GRID_ATTR_CHARSET) ||
968 		    gcp->flags != last.flags ||
969 		    gcp->attr != last.attr ||
970 		    gcp->fg != last.fg ||
971 		    gcp->bg != last.bg ||
972 		    ux + width + gcp->data.width >= screen_size_x(s) ||
973 		    (sizeof buf) - len < gcp->data.size)) {
974 			tty_attributes(tty, &last, wp);
975 			tty_putn(tty, buf, len, width);
976 			ux += width;
977 
978 			len = 0;
979 			width = 0;
980 		}
981 
982 		if (gcp->flags & GRID_FLAG_SELECTED)
983 			screen_select_cell(s, &last, gcp);
984 		else
985 			memcpy(&last, gcp, sizeof last);
986 		if (ux + gcp->data.width > screen_size_x(s)) {
987 			tty_attributes(tty, &last, wp);
988 			for (j = 0; j < gcp->data.width; j++) {
989 				if (ux + j > screen_size_x(s))
990 					break;
991 				tty_putc(tty, ' ');
992 				ux++;
993 			}
994 		} else if (gcp->attr & GRID_ATTR_CHARSET) {
995 			tty_attributes(tty, &last, wp);
996 			for (j = 0; j < gcp->data.size; j++)
997 				tty_putc(tty, gcp->data.data[j]);
998 			ux += gc.data.width;
999 		} else {
1000 			memcpy(buf + len, gcp->data.data, gcp->data.size);
1001 			len += gcp->data.size;
1002 			width += gcp->data.width;
1003 		}
1004 	}
1005 	if (len != 0) {
1006 		if (grid_cells_equal(&last, &grid_default_cell)) {
1007 			old_len = len;
1008 			while (len > 0 && buf[len - 1] == ' ') {
1009 				len--;
1010 				width--;
1011 			}
1012 			log_debug("%s: trimmed %zu spaces", __func__,
1013 			    old_len - len);
1014 		}
1015 		if (len != 0) {
1016 			tty_attributes(tty, &last, wp);
1017 			tty_putn(tty, buf, len, width);
1018 			ux += width;
1019 		}
1020 	}
1021 
1022 	if (!cleared && ux < screen_size_x(s)) {
1023 		nx = screen_size_x(s) - ux;
1024 		tty_default_attributes(tty, wp, 8);
1025 		tty_clear_line(tty, wp, oy + py, ox + ux, nx, 8);
1026 	}
1027 
1028 	tty->flags = (tty->flags & ~TTY_NOCURSOR) | flags;
1029 	tty_update_mode(tty, tty->mode, s);
1030 }
1031 
1032 static int
1033 tty_client_ready(struct client *c, struct window_pane *wp)
1034 {
1035 	if (c->session == NULL || c->tty.term == NULL)
1036 		return (0);
1037 	if (c->flags & (CLIENT_REDRAW|CLIENT_SUSPENDED))
1038 		return (0);
1039 	if (c->tty.flags & TTY_FREEZE)
1040 		return (0);
1041 	if (c->session->curw->window != wp->window)
1042 		return (0);
1043 	return (1);
1044 }
1045 
1046 void
1047 tty_write(void (*cmdfn)(struct tty *, const struct tty_ctx *),
1048     struct tty_ctx *ctx)
1049 {
1050 	struct window_pane	*wp = ctx->wp;
1051 	struct client		*c;
1052 
1053 	/* wp can be NULL if updating the screen but not the terminal. */
1054 	if (wp == NULL)
1055 		return;
1056 
1057 	if ((wp->flags & (PANE_REDRAW|PANE_DROP)) || !window_pane_visible(wp))
1058 		return;
1059 
1060 	TAILQ_FOREACH(c, &clients, entry) {
1061 		if (!tty_client_ready(c, wp))
1062 			continue;
1063 
1064 		ctx->xoff = wp->xoff;
1065 		ctx->yoff = wp->yoff;
1066 		if (status_at_line(c) == 0)
1067 			ctx->yoff += status_line_size(c->session);
1068 
1069 		cmdfn(&c->tty, ctx);
1070 	}
1071 }
1072 
1073 void
1074 tty_cmd_insertcharacter(struct tty *tty, const struct tty_ctx *ctx)
1075 {
1076 	struct window_pane	*wp = ctx->wp;
1077 
1078 	if (!tty_pane_full_width(tty, ctx) ||
1079 	    tty_fake_bce(tty, wp, ctx->bg) ||
1080 	    (!tty_term_has(tty->term, TTYC_ICH) &&
1081 	    !tty_term_has(tty->term, TTYC_ICH1))) {
1082 		tty_draw_pane(tty, wp, ctx->ocy, ctx->xoff, ctx->yoff);
1083 		return;
1084 	}
1085 
1086 	tty_default_attributes(tty, wp, ctx->bg);
1087 
1088 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
1089 
1090 	tty_emulate_repeat(tty, TTYC_ICH, TTYC_ICH1, ctx->num);
1091 }
1092 
1093 void
1094 tty_cmd_deletecharacter(struct tty *tty, const struct tty_ctx *ctx)
1095 {
1096 	struct window_pane	*wp = ctx->wp;
1097 
1098 	if (!tty_pane_full_width(tty, ctx) ||
1099 	    tty_fake_bce(tty, wp, ctx->bg) ||
1100 	    (!tty_term_has(tty->term, TTYC_DCH) &&
1101 	    !tty_term_has(tty->term, TTYC_DCH1))) {
1102 		tty_draw_pane(tty, wp, ctx->ocy, ctx->xoff, ctx->yoff);
1103 		return;
1104 	}
1105 
1106 	tty_default_attributes(tty, wp, ctx->bg);
1107 
1108 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
1109 
1110 	tty_emulate_repeat(tty, TTYC_DCH, TTYC_DCH1, ctx->num);
1111 }
1112 
1113 void
1114 tty_cmd_clearcharacter(struct tty *tty, const struct tty_ctx *ctx)
1115 {
1116 	tty_default_attributes(tty, ctx->wp, ctx->bg);
1117 
1118 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
1119 
1120 	if (tty_term_has(tty->term, TTYC_ECH) &&
1121 	    !tty_fake_bce(tty, ctx->wp, 8))
1122 		tty_putcode1(tty, TTYC_ECH, ctx->num);
1123 	else
1124 		tty_repeat_space(tty, ctx->num);
1125 }
1126 
1127 void
1128 tty_cmd_insertline(struct tty *tty, const struct tty_ctx *ctx)
1129 {
1130 	if (!tty_pane_full_width(tty, ctx) ||
1131 	    tty_fake_bce(tty, ctx->wp, ctx->bg) ||
1132 	    !tty_term_has(tty->term, TTYC_CSR) ||
1133 	    !tty_term_has(tty->term, TTYC_IL1)) {
1134 		tty_redraw_region(tty, ctx);
1135 		return;
1136 	}
1137 
1138 	tty_default_attributes(tty, ctx->wp, ctx->bg);
1139 
1140 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1141 	tty_margin_off(tty);
1142 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
1143 
1144 	tty_emulate_repeat(tty, TTYC_IL, TTYC_IL1, ctx->num);
1145 	tty->cx = tty->cy = UINT_MAX;
1146 }
1147 
1148 void
1149 tty_cmd_deleteline(struct tty *tty, const struct tty_ctx *ctx)
1150 {
1151 	if (!tty_pane_full_width(tty, ctx) ||
1152 	    tty_fake_bce(tty, ctx->wp, ctx->bg) ||
1153 	    !tty_term_has(tty->term, TTYC_CSR) ||
1154 	    !tty_term_has(tty->term, TTYC_DL1)) {
1155 		tty_redraw_region(tty, ctx);
1156 		return;
1157 	}
1158 
1159 	tty_default_attributes(tty, ctx->wp, ctx->bg);
1160 
1161 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1162 	tty_margin_off(tty);
1163 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
1164 
1165 	tty_emulate_repeat(tty, TTYC_DL, TTYC_DL1, ctx->num);
1166 	tty->cx = tty->cy = UINT_MAX;
1167 }
1168 
1169 void
1170 tty_cmd_clearline(struct tty *tty, const struct tty_ctx *ctx)
1171 {
1172 	struct window_pane	*wp = ctx->wp;
1173 	u_int			 nx, py = ctx->yoff + ctx->ocy;
1174 
1175 	tty_default_attributes(tty, wp, ctx->bg);
1176 
1177 	nx = screen_size_x(wp->screen);
1178 	tty_clear_line(tty, wp, py, ctx->xoff, nx, ctx->bg);
1179 }
1180 
1181 void
1182 tty_cmd_clearendofline(struct tty *tty, const struct tty_ctx *ctx)
1183 {
1184 	struct window_pane	*wp = ctx->wp;
1185 	u_int			 nx, py = ctx->yoff + ctx->ocy;
1186 
1187 	tty_default_attributes(tty, wp, ctx->bg);
1188 
1189 	nx = screen_size_x(wp->screen) - ctx->ocx;
1190 	tty_clear_line(tty, wp, py, ctx->xoff + ctx->ocx, nx, ctx->bg);
1191 }
1192 
1193 void
1194 tty_cmd_clearstartofline(struct tty *tty, const struct tty_ctx *ctx)
1195 {
1196 	struct window_pane	*wp = ctx->wp;
1197 	u_int			 py = ctx->yoff + ctx->ocy;
1198 
1199 	tty_default_attributes(tty, wp, ctx->bg);
1200 
1201 	tty_clear_line(tty, wp, py, ctx->xoff, ctx->ocx + 1, ctx->bg);
1202 }
1203 
1204 void
1205 tty_cmd_reverseindex(struct tty *tty, const struct tty_ctx *ctx)
1206 {
1207 	struct window_pane	*wp = ctx->wp;
1208 
1209 	if (ctx->ocy != ctx->orupper)
1210 		return;
1211 
1212 	if (!tty_pane_full_width(tty, ctx) ||
1213 	    tty_fake_bce(tty, wp, 8) ||
1214 	    !tty_term_has(tty->term, TTYC_CSR) ||
1215 	    !tty_term_has(tty->term, TTYC_RI)) {
1216 		tty_redraw_region(tty, ctx);
1217 		return;
1218 	}
1219 
1220 	tty_default_attributes(tty, wp, ctx->bg);
1221 
1222 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1223 	tty_margin_off(tty);
1224 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->orupper);
1225 
1226 	tty_putcode(tty, TTYC_RI);
1227 }
1228 
1229 void
1230 tty_cmd_linefeed(struct tty *tty, const struct tty_ctx *ctx)
1231 {
1232 	struct window_pane	*wp = ctx->wp;
1233 
1234 	if (ctx->ocy != ctx->orlower)
1235 		return;
1236 
1237 	if ((!tty_pane_full_width(tty, ctx) && !tty_use_margin(tty)) ||
1238 	    tty_fake_bce(tty, wp, 8) ||
1239 	    !tty_term_has(tty->term, TTYC_CSR)) {
1240 		tty_redraw_region(tty, ctx);
1241 		return;
1242 	}
1243 
1244 	tty_default_attributes(tty, wp, ctx->bg);
1245 
1246 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1247 	tty_margin_pane(tty, ctx);
1248 
1249 	/*
1250 	 * If we want to wrap a pane while using margins, the cursor needs to
1251 	 * be exactly on the right of the region. If the cursor is entirely off
1252 	 * the edge - move it back to the right. Some terminals are funny about
1253 	 * this and insert extra spaces, so only use the right if margins are
1254 	 * enabled.
1255 	 */
1256 	if (ctx->xoff + ctx->ocx > tty->rright) {
1257 		if (!tty_use_margin(tty))
1258 			tty_cursor(tty, 0, ctx->yoff + ctx->ocy);
1259 		else
1260 			tty_cursor(tty, tty->rright, ctx->yoff + ctx->ocy);
1261 	} else
1262 		tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
1263 
1264 	tty_putc(tty, '\n');
1265 }
1266 
1267 void
1268 tty_cmd_scrollup(struct tty *tty, const struct tty_ctx *ctx)
1269 {
1270 	struct window_pane	*wp = ctx->wp;
1271 	u_int			 i;
1272 
1273 	if ((!tty_pane_full_width(tty, ctx) && !tty_use_margin(tty)) ||
1274 	    tty_fake_bce(tty, wp, 8) ||
1275 	    !tty_term_has(tty->term, TTYC_CSR)) {
1276 		tty_redraw_region(tty, ctx);
1277 		return;
1278 	}
1279 
1280 	tty_default_attributes(tty, wp, ctx->bg);
1281 
1282 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1283 	tty_margin_pane(tty, ctx);
1284 
1285 	if (ctx->num == 1 || !tty_term_has(tty->term, TTYC_INDN)) {
1286 		if (!tty_use_margin(tty))
1287 			tty_cursor(tty, 0, tty->rlower);
1288 		else
1289 			tty_cursor(tty, tty->rright, tty->rlower);
1290 		for (i = 0; i < ctx->num; i++)
1291 			tty_putc(tty, '\n');
1292 	} else {
1293 		tty_cursor(tty, 0, tty->cy);
1294 		tty_putcode1(tty, TTYC_INDN, ctx->num);
1295 	}
1296 }
1297 
1298 void
1299 tty_cmd_clearendofscreen(struct tty *tty, const struct tty_ctx *ctx)
1300 {
1301 	struct window_pane	*wp = ctx->wp;
1302 	u_int			 px, py, nx, ny;
1303 
1304 	tty_default_attributes(tty, wp, ctx->bg);
1305 
1306 	tty_region_pane(tty, ctx, 0, screen_size_y(wp->screen) - 1);
1307 	tty_margin_off(tty);
1308 
1309 	px = ctx->xoff;
1310 	nx = screen_size_x(wp->screen);
1311 	py = ctx->yoff + ctx->ocy + 1;
1312 	ny = screen_size_y(wp->screen) - ctx->ocy - 1;
1313 
1314 	tty_clear_area(tty, wp, py, ny, px, nx, ctx->bg);
1315 
1316 	px = ctx->xoff + ctx->ocx;
1317 	nx = screen_size_x(wp->screen) - ctx->ocx;
1318 	py = ctx->yoff + ctx->ocy;
1319 
1320 	tty_clear_line(tty, wp, py, px, nx, ctx->bg);
1321 }
1322 
1323 void
1324 tty_cmd_clearstartofscreen(struct tty *tty, const struct tty_ctx *ctx)
1325 {
1326 	struct window_pane	*wp = ctx->wp;
1327 	u_int			 px, py, nx, ny;
1328 
1329 	tty_default_attributes(tty, wp, ctx->bg);
1330 
1331 	tty_region_pane(tty, ctx, 0, screen_size_y(wp->screen) - 1);
1332 	tty_margin_off(tty);
1333 
1334 	px = ctx->xoff;
1335 	nx = screen_size_x(wp->screen);
1336 	py = ctx->yoff;
1337 	ny = ctx->ocy - 1;
1338 
1339 	tty_clear_area(tty, wp, py, ny, px, nx, ctx->bg);
1340 
1341 	px = ctx->xoff;
1342 	nx = ctx->ocx + 1;
1343 	py = ctx->yoff + ctx->ocy;
1344 
1345 	tty_clear_line(tty, wp, py, px, nx, ctx->bg);
1346 }
1347 
1348 void
1349 tty_cmd_clearscreen(struct tty *tty, const struct tty_ctx *ctx)
1350 {
1351 	struct window_pane	*wp = ctx->wp;
1352 	u_int			 px, py, nx, ny;
1353 
1354 	tty_default_attributes(tty, wp, ctx->bg);
1355 
1356 	tty_region_pane(tty, ctx, 0, screen_size_y(wp->screen) - 1);
1357 	tty_margin_off(tty);
1358 
1359 	px = ctx->xoff;
1360 	nx = screen_size_x(wp->screen);
1361 	py = ctx->yoff;
1362 	ny = screen_size_y(wp->screen);
1363 
1364 	tty_clear_area(tty, wp, py, ny, px, nx, ctx->bg);
1365 }
1366 
1367 void
1368 tty_cmd_alignmenttest(struct tty *tty, const struct tty_ctx *ctx)
1369 {
1370 	struct window_pane	*wp = ctx->wp;
1371 	struct screen		*s = wp->screen;
1372 	u_int			 i, j;
1373 
1374 	tty_attributes(tty, &grid_default_cell, wp);
1375 
1376 	tty_region_pane(tty, ctx, 0, screen_size_y(s) - 1);
1377 	tty_margin_off(tty);
1378 
1379 	for (j = 0; j < screen_size_y(s); j++) {
1380 		tty_cursor_pane(tty, ctx, 0, j);
1381 		for (i = 0; i < screen_size_x(s); i++)
1382 			tty_putc(tty, 'E');
1383 	}
1384 }
1385 
1386 void
1387 tty_cmd_cell(struct tty *tty, const struct tty_ctx *ctx)
1388 {
1389 	if (ctx->xoff + ctx->ocx > tty->sx - 1 && ctx->ocy == ctx->orlower) {
1390 		if (tty_pane_full_width(tty, ctx))
1391 			tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1392 		else
1393 			tty_margin_off(tty);
1394 	}
1395 
1396 	tty_cursor_pane_unless_wrap(tty, ctx, ctx->ocx, ctx->ocy);
1397 
1398 	tty_cell(tty, ctx->cell, ctx->wp);
1399 }
1400 
1401 void
1402 tty_cmd_cells(struct tty *tty, const struct tty_ctx *ctx)
1403 {
1404 	tty_cursor_pane_unless_wrap(tty, ctx, ctx->ocx, ctx->ocy);
1405 
1406 	tty_attributes(tty, ctx->cell, ctx->wp);
1407 	tty_putn(tty, ctx->ptr, ctx->num, ctx->num);
1408 }
1409 
1410 void
1411 tty_cmd_setselection(struct tty *tty, const struct tty_ctx *ctx)
1412 {
1413 	char	*buf;
1414 	size_t	 off;
1415 
1416 	if (!tty_term_has(tty->term, TTYC_MS))
1417 		return;
1418 
1419 	off = 4 * ((ctx->num + 2) / 3) + 1; /* storage for base64 */
1420 	buf = xmalloc(off);
1421 
1422 	b64_ntop(ctx->ptr, ctx->num, buf, off);
1423 	tty_putcode_ptr2(tty, TTYC_MS, "", buf);
1424 
1425 	free(buf);
1426 }
1427 
1428 void
1429 tty_cmd_rawstring(struct tty *tty, const struct tty_ctx *ctx)
1430 {
1431 	tty_add(tty, ctx->ptr, ctx->num);
1432 	tty_invalidate(tty);
1433 }
1434 
1435 static void
1436 tty_cell(struct tty *tty, const struct grid_cell *gc,
1437     const struct window_pane *wp)
1438 {
1439 	const struct grid_cell	*gcp;
1440 
1441 	/* Skip last character if terminal is stupid. */
1442 	if ((tty->term->flags & TERM_EARLYWRAP) &&
1443 	    tty->cy == tty->sy - 1 &&
1444 	    tty->cx == tty->sx - 1)
1445 		return;
1446 
1447 	/* If this is a padding character, do nothing. */
1448 	if (gc->flags & GRID_FLAG_PADDING)
1449 		return;
1450 
1451 	/* Set the attributes. */
1452 	tty_attributes(tty, gc, wp);
1453 
1454 	/* Get the cell and if ASCII write with putc to do ACS translation. */
1455 	gcp = tty_check_codeset(tty, gc);
1456 	if (gcp->data.size == 1) {
1457 		if (*gcp->data.data < 0x20 || *gcp->data.data == 0x7f)
1458 			return;
1459 		tty_putc(tty, *gcp->data.data);
1460 		return;
1461 	}
1462 
1463 	/* Write the data. */
1464 	tty_putn(tty, gcp->data.data, gcp->data.size, gcp->data.width);
1465 }
1466 
1467 void
1468 tty_reset(struct tty *tty)
1469 {
1470 	struct grid_cell	*gc = &tty->cell;
1471 
1472 	if (!grid_cells_equal(gc, &grid_default_cell)) {
1473 		if ((gc->attr & GRID_ATTR_CHARSET) && tty_acs_needed(tty))
1474 			tty_putcode(tty, TTYC_RMACS);
1475 		tty_putcode(tty, TTYC_SGR0);
1476 		memcpy(gc, &grid_default_cell, sizeof *gc);
1477 	}
1478 
1479 	memcpy(&tty->last_cell, &grid_default_cell, sizeof tty->last_cell);
1480 	tty->last_wp = -1;
1481 }
1482 
1483 static void
1484 tty_invalidate(struct tty *tty)
1485 {
1486 	memcpy(&tty->cell, &grid_default_cell, sizeof tty->cell);
1487 
1488 	memcpy(&tty->last_cell, &grid_default_cell, sizeof tty->last_cell);
1489 	tty->last_wp = -1;
1490 
1491 	tty->cx = tty->cy = UINT_MAX;
1492 
1493 	tty->rupper = tty->rleft = UINT_MAX;
1494 	tty->rlower = tty->rright = UINT_MAX;
1495 
1496 	if (tty->flags & TTY_STARTED) {
1497 		tty_putcode(tty, TTYC_SGR0);
1498 
1499 		tty->mode = ALL_MODES;
1500 		tty_update_mode(tty, MODE_CURSOR, NULL);
1501 
1502 		tty_cursor(tty, 0, 0);
1503 		tty_region_off(tty);
1504 		tty_margin_off(tty);
1505 	} else
1506 		tty->mode = MODE_CURSOR;
1507 }
1508 
1509 /* Turn off margin. */
1510 void
1511 tty_region_off(struct tty *tty)
1512 {
1513 	tty_region(tty, 0, tty->sy - 1);
1514 }
1515 
1516 /* Set region inside pane. */
1517 static void
1518 tty_region_pane(struct tty *tty, const struct tty_ctx *ctx, u_int rupper,
1519     u_int rlower)
1520 {
1521 	tty_region(tty, ctx->yoff + rupper, ctx->yoff + rlower);
1522 }
1523 
1524 /* Set region at absolute position. */
1525 static void
1526 tty_region(struct tty *tty, u_int rupper, u_int rlower)
1527 {
1528 	if (tty->rlower == rlower && tty->rupper == rupper)
1529 		return;
1530 	if (!tty_term_has(tty->term, TTYC_CSR))
1531 		return;
1532 
1533 	tty->rupper = rupper;
1534 	tty->rlower = rlower;
1535 
1536 	/*
1537 	 * Some terminals (such as PuTTY) do not correctly reset the cursor to
1538 	 * 0,0 if it is beyond the last column (they do not reset their wrap
1539 	 * flag so further output causes a line feed). As a workaround, do an
1540 	 * explicit move to 0 first.
1541 	 */
1542 	if (tty->cx >= tty->sx)
1543 		tty_cursor(tty, 0, tty->cy);
1544 
1545 	tty_putcode2(tty, TTYC_CSR, tty->rupper, tty->rlower);
1546 	tty->cx = tty->cy = UINT_MAX;
1547 }
1548 
1549 /* Turn off margin. */
1550 void
1551 tty_margin_off(struct tty *tty)
1552 {
1553 	tty_margin(tty, 0, tty->sx - 1);
1554 }
1555 
1556 /* Set margin inside pane. */
1557 static void
1558 tty_margin_pane(struct tty *tty, const struct tty_ctx *ctx)
1559 {
1560 	tty_margin(tty, ctx->xoff, ctx->xoff + ctx->wp->sx - 1);
1561 }
1562 
1563 /* Set margin at absolute position. */
1564 static void
1565 tty_margin(struct tty *tty, u_int rleft, u_int rright)
1566 {
1567 	char s[64];
1568 
1569 	if (!tty_use_margin(tty))
1570 		return;
1571 	if (tty->rleft == rleft && tty->rright == rright)
1572 		return;
1573 
1574 	tty_putcode2(tty, TTYC_CSR, tty->rupper, tty->rlower);
1575 
1576 	tty->rleft = rleft;
1577 	tty->rright = rright;
1578 
1579 	if (rleft == 0 && rright == tty->sx - 1)
1580 		snprintf(s, sizeof s, "\033[s");
1581 	else
1582 		snprintf(s, sizeof s, "\033[%u;%us", rleft + 1, rright + 1);
1583 	tty_puts(tty, s);
1584 	tty->cx = tty->cy = UINT_MAX;
1585 }
1586 
1587 /*
1588  * Move the cursor, unless it would wrap itself when the next character is
1589  * printed.
1590  */
1591 static void
1592 tty_cursor_pane_unless_wrap(struct tty *tty, const struct tty_ctx *ctx,
1593     u_int cx, u_int cy)
1594 {
1595 	if (!ctx->wrapped ||
1596 	    !tty_pane_full_width(tty, ctx) ||
1597 	    (tty->term->flags & TERM_EARLYWRAP) ||
1598 	    ctx->xoff + cx != 0 ||
1599 	    ctx->yoff + cy != tty->cy + 1 ||
1600 	    tty->cx < tty->sx ||
1601 	    tty->cy == tty->rlower)
1602 		tty_cursor_pane(tty, ctx, cx, cy);
1603 	else
1604 		log_debug("%s: will wrap at %u,%u", __func__, tty->cx, tty->cy);
1605 }
1606 
1607 /* Move cursor inside pane. */
1608 static void
1609 tty_cursor_pane(struct tty *tty, const struct tty_ctx *ctx, u_int cx, u_int cy)
1610 {
1611 	tty_cursor(tty, ctx->xoff + cx, ctx->yoff + cy);
1612 }
1613 
1614 /* Move cursor to absolute position. */
1615 void
1616 tty_cursor(struct tty *tty, u_int cx, u_int cy)
1617 {
1618 	struct tty_term	*term = tty->term;
1619 	u_int		 thisx, thisy;
1620 	int		 change;
1621 
1622 	if (cx > tty->sx - 1)
1623 		cx = tty->sx - 1;
1624 
1625 	thisx = tty->cx;
1626 	thisy = tty->cy;
1627 
1628 	/* No change. */
1629 	if (cx == thisx && cy == thisy)
1630 		return;
1631 
1632 	/* Very end of the line, just use absolute movement. */
1633 	if (thisx > tty->sx - 1)
1634 		goto absolute;
1635 
1636 	/* Move to home position (0, 0). */
1637 	if (cx == 0 && cy == 0 && tty_term_has(term, TTYC_HOME)) {
1638 		tty_putcode(tty, TTYC_HOME);
1639 		goto out;
1640 	}
1641 
1642 	/* Zero on the next line. */
1643 	if (cx == 0 && cy == thisy + 1 && thisy != tty->rlower &&
1644 	    (!tty_use_margin(tty) || tty->rleft == 0)) {
1645 		tty_putc(tty, '\r');
1646 		tty_putc(tty, '\n');
1647 		goto out;
1648 	}
1649 
1650 	/* Moving column or row. */
1651 	if (cy == thisy) {
1652 		/*
1653 		 * Moving column only, row staying the same.
1654 		 */
1655 
1656 		/* To left edge. */
1657 		if (cx == 0 && (!tty_use_margin(tty) || tty->rleft == 0)) {
1658 			tty_putc(tty, '\r');
1659 			goto out;
1660 		}
1661 
1662 		/* One to the left. */
1663 		if (cx == thisx - 1 && tty_term_has(term, TTYC_CUB1)) {
1664 			tty_putcode(tty, TTYC_CUB1);
1665 			goto out;
1666 		}
1667 
1668 		/* One to the right. */
1669 		if (cx == thisx + 1 && tty_term_has(term, TTYC_CUF1)) {
1670 			tty_putcode(tty, TTYC_CUF1);
1671 			goto out;
1672 		}
1673 
1674 		/* Calculate difference. */
1675 		change = thisx - cx;	/* +ve left, -ve right */
1676 
1677 		/*
1678 		 * Use HPA if change is larger than absolute, otherwise move
1679 		 * the cursor with CUB/CUF.
1680 		 */
1681 		if ((u_int) abs(change) > cx && tty_term_has(term, TTYC_HPA)) {
1682 			tty_putcode1(tty, TTYC_HPA, cx);
1683 			goto out;
1684 		} else if (change > 0 && tty_term_has(term, TTYC_CUB)) {
1685 			if (change == 2 && tty_term_has(term, TTYC_CUB1)) {
1686 				tty_putcode(tty, TTYC_CUB1);
1687 				tty_putcode(tty, TTYC_CUB1);
1688 				goto out;
1689 			}
1690 			tty_putcode1(tty, TTYC_CUB, change);
1691 			goto out;
1692 		} else if (change < 0 && tty_term_has(term, TTYC_CUF)) {
1693 			tty_putcode1(tty, TTYC_CUF, -change);
1694 			goto out;
1695 		}
1696 	} else if (cx == thisx) {
1697 		/*
1698 		 * Moving row only, column staying the same.
1699 		 */
1700 
1701 		/* One above. */
1702 		if (thisy != tty->rupper &&
1703 		    cy == thisy - 1 && tty_term_has(term, TTYC_CUU1)) {
1704 			tty_putcode(tty, TTYC_CUU1);
1705 			goto out;
1706 		}
1707 
1708 		/* One below. */
1709 		if (thisy != tty->rlower &&
1710 		    cy == thisy + 1 && tty_term_has(term, TTYC_CUD1)) {
1711 			tty_putcode(tty, TTYC_CUD1);
1712 			goto out;
1713 		}
1714 
1715 		/* Calculate difference. */
1716 		change = thisy - cy;	/* +ve up, -ve down */
1717 
1718 		/*
1719 		 * Try to use VPA if change is larger than absolute or if this
1720 		 * change would cross the scroll region, otherwise use CUU/CUD.
1721 		 */
1722 		if ((u_int) abs(change) > cy ||
1723 		    (change < 0 && cy - change > tty->rlower) ||
1724 		    (change > 0 && cy - change < tty->rupper)) {
1725 			    if (tty_term_has(term, TTYC_VPA)) {
1726 				    tty_putcode1(tty, TTYC_VPA, cy);
1727 				    goto out;
1728 			    }
1729 		} else if (change > 0 && tty_term_has(term, TTYC_CUU)) {
1730 			tty_putcode1(tty, TTYC_CUU, change);
1731 			goto out;
1732 		} else if (change < 0 && tty_term_has(term, TTYC_CUD)) {
1733 			tty_putcode1(tty, TTYC_CUD, -change);
1734 			goto out;
1735 		}
1736 	}
1737 
1738 absolute:
1739 	/* Absolute movement. */
1740 	tty_putcode2(tty, TTYC_CUP, cy, cx);
1741 
1742 out:
1743 	tty->cx = cx;
1744 	tty->cy = cy;
1745 }
1746 
1747 void
1748 tty_attributes(struct tty *tty, const struct grid_cell *gc,
1749     const struct window_pane *wp)
1750 {
1751 	struct grid_cell	*tc = &tty->cell, gc2;
1752 	int			 changed;
1753 
1754 	/* Ignore cell if it is the same as the last one. */
1755 	if (wp != NULL &&
1756 	    (int)wp->id == tty->last_wp &&
1757 	    ~(wp->window->flags & WINDOW_STYLECHANGED) &&
1758 	    gc->attr == tty->last_cell.attr &&
1759 	    gc->fg == tty->last_cell.fg &&
1760 	    gc->bg == tty->last_cell.bg)
1761 		return;
1762 	tty->last_wp = (wp != NULL ? (int)wp->id : -1);
1763 	memcpy(&tty->last_cell, gc, sizeof tty->last_cell);
1764 
1765 	/* Copy cell and update default colours. */
1766 	memcpy(&gc2, gc, sizeof gc2);
1767 	if (wp != NULL)
1768 		tty_default_colours(&gc2, wp);
1769 
1770 	/*
1771 	 * If no setab, try to use the reverse attribute as a best-effort for a
1772 	 * non-default background. This is a bit of a hack but it doesn't do
1773 	 * any serious harm and makes a couple of applications happier.
1774 	 */
1775 	if (!tty_term_has(tty->term, TTYC_SETAB)) {
1776 		if (gc2.attr & GRID_ATTR_REVERSE) {
1777 			if (gc2.fg != 7 && gc2.fg != 8)
1778 				gc2.attr &= ~GRID_ATTR_REVERSE;
1779 		} else {
1780 			if (gc2.bg != 0 && gc2.bg != 8)
1781 				gc2.attr |= GRID_ATTR_REVERSE;
1782 		}
1783 	}
1784 
1785 	/* Fix up the colours if necessary. */
1786 	tty_check_fg(tty, wp, &gc2);
1787 	tty_check_bg(tty, wp, &gc2);
1788 
1789 	/* If any bits are being cleared, reset everything. */
1790 	if (tc->attr & ~gc2.attr)
1791 		tty_reset(tty);
1792 
1793 	/*
1794 	 * Set the colours. This may call tty_reset() (so it comes next) and
1795 	 * may add to (NOT remove) the desired attributes by changing new_attr.
1796 	 */
1797 	tty_colours(tty, &gc2);
1798 
1799 	/* Filter out attribute bits already set. */
1800 	changed = gc2.attr & ~tc->attr;
1801 	tc->attr = gc2.attr;
1802 
1803 	/* Set the attributes. */
1804 	if (changed & GRID_ATTR_BRIGHT)
1805 		tty_putcode(tty, TTYC_BOLD);
1806 	if (changed & GRID_ATTR_DIM)
1807 		tty_putcode(tty, TTYC_DIM);
1808 	if (changed & GRID_ATTR_ITALICS)
1809 		tty_set_italics(tty);
1810 	if (changed & GRID_ATTR_UNDERSCORE)
1811 		tty_putcode(tty, TTYC_SMUL);
1812 	if (changed & GRID_ATTR_BLINK)
1813 		tty_putcode(tty, TTYC_BLINK);
1814 	if (changed & GRID_ATTR_REVERSE) {
1815 		if (tty_term_has(tty->term, TTYC_REV))
1816 			tty_putcode(tty, TTYC_REV);
1817 		else if (tty_term_has(tty->term, TTYC_SMSO))
1818 			tty_putcode(tty, TTYC_SMSO);
1819 	}
1820 	if (changed & GRID_ATTR_HIDDEN)
1821 		tty_putcode(tty, TTYC_INVIS);
1822 	if (changed & GRID_ATTR_STRIKETHROUGH)
1823 		tty_putcode(tty, TTYC_SMXX);
1824 	if ((changed & GRID_ATTR_CHARSET) && tty_acs_needed(tty))
1825 		tty_putcode(tty, TTYC_SMACS);
1826 }
1827 
1828 static void
1829 tty_colours(struct tty *tty, const struct grid_cell *gc)
1830 {
1831 	struct grid_cell	*tc = &tty->cell;
1832 	int			 have_ax;
1833 
1834 	/* No changes? Nothing is necessary. */
1835 	if (gc->fg == tc->fg && gc->bg == tc->bg)
1836 		return;
1837 
1838 	/*
1839 	 * Is either the default colour? This is handled specially because the
1840 	 * best solution might be to reset both colours to default, in which
1841 	 * case if only one is default need to fall onward to set the other
1842 	 * colour.
1843 	 */
1844 	if (gc->fg == 8 || gc->bg == 8) {
1845 		/*
1846 		 * If don't have AX but do have op, send sgr0 (op can't
1847 		 * actually be used because it is sometimes the same as sgr0
1848 		 * and sometimes isn't). This resets both colours to default.
1849 		 *
1850 		 * Otherwise, try to set the default colour only as needed.
1851 		 */
1852 		have_ax = tty_term_flag(tty->term, TTYC_AX);
1853 		if (!have_ax && tty_term_has(tty->term, TTYC_OP))
1854 			tty_reset(tty);
1855 		else {
1856 			if (gc->fg == 8 && tc->fg != 8) {
1857 				if (have_ax)
1858 					tty_puts(tty, "\033[39m");
1859 				else if (tc->fg != 7)
1860 					tty_putcode1(tty, TTYC_SETAF, 7);
1861 				tc->fg = 8;
1862 			}
1863 			if (gc->bg == 8 && tc->bg != 8) {
1864 				if (have_ax)
1865 					tty_puts(tty, "\033[49m");
1866 				else if (tc->bg != 0)
1867 					tty_putcode1(tty, TTYC_SETAB, 0);
1868 				tc->bg = 8;
1869 			}
1870 		}
1871 	}
1872 
1873 	/* Set the foreground colour. */
1874 	if (gc->fg != 8 && gc->fg != tc->fg)
1875 		tty_colours_fg(tty, gc);
1876 
1877 	/*
1878 	 * Set the background colour. This must come after the foreground as
1879 	 * tty_colour_fg() can call tty_reset().
1880 	 */
1881 	if (gc->bg != 8 && gc->bg != tc->bg)
1882 		tty_colours_bg(tty, gc);
1883 }
1884 
1885 static void
1886 tty_check_fg(struct tty *tty, const struct window_pane *wp,
1887     struct grid_cell *gc)
1888 {
1889 	u_char	r, g, b;
1890 	u_int	colours;
1891 	int	c;
1892 
1893 	/*
1894 	 * Perform substitution if this pane has a palette. If the bright
1895 	 * attribute is set, use the bright entry in the palette by changing to
1896 	 * the aixterm colour.
1897 	 */
1898 	if (~gc->flags & GRID_FLAG_NOPALETTE) {
1899 		c = gc->fg;
1900 		if (c < 8 && gc->attr & GRID_ATTR_BRIGHT)
1901 			c += 90;
1902 		if ((c = window_pane_get_palette(wp, c)) != -1)
1903 			gc->fg = c;
1904 	}
1905 
1906 	/* Is this a 24-bit colour? */
1907 	if (gc->fg & COLOUR_FLAG_RGB) {
1908 		/* Not a 24-bit terminal? Translate to 256-colour palette. */
1909 		if (!tty_term_has(tty->term, TTYC_SETRGBF)) {
1910 			colour_split_rgb(gc->fg, &r, &g, &b);
1911 			gc->fg = colour_find_rgb(r, g, b);
1912 		} else
1913 			return;
1914 	}
1915 
1916 	/* How many colours does this terminal have? */
1917 	if ((tty->term->flags|tty->term_flags) & TERM_256COLOURS)
1918 		colours = 256;
1919 	else
1920 		colours = tty_term_number(tty->term, TTYC_COLORS);
1921 
1922 	/* Is this a 256-colour colour? */
1923 	if (gc->fg & COLOUR_FLAG_256) {
1924 		/* And not a 256 colour mode? */
1925 		if (colours != 256) {
1926 			gc->fg = colour_256to16(gc->fg);
1927 			if (gc->fg & 8) {
1928 				gc->fg &= 7;
1929 				if (colours >= 16)
1930 					gc->fg += 90;
1931 				else
1932 					gc->attr |= GRID_ATTR_BRIGHT;
1933 			} else
1934 				gc->attr &= ~GRID_ATTR_BRIGHT;
1935 		}
1936 		return;
1937 	}
1938 
1939 	/* Is this an aixterm colour? */
1940 	if (gc->fg >= 90 && gc->fg <= 97 && colours < 16) {
1941 		gc->fg -= 90;
1942 		gc->attr |= GRID_ATTR_BRIGHT;
1943 	}
1944 }
1945 
1946 static void
1947 tty_check_bg(struct tty *tty, const struct window_pane *wp,
1948     struct grid_cell *gc)
1949 {
1950 	u_char	r, g, b;
1951 	u_int	colours;
1952 	int	c;
1953 
1954 	/* Perform substitution if this pane has a palette. */
1955 	if (~gc->flags & GRID_FLAG_NOPALETTE) {
1956 		if ((c = window_pane_get_palette(wp, gc->bg)) != -1)
1957 			gc->bg = c;
1958 	}
1959 
1960 	/* Is this a 24-bit colour? */
1961 	if (gc->bg & COLOUR_FLAG_RGB) {
1962 		/* Not a 24-bit terminal? Translate to 256-colour palette. */
1963 		if (!tty_term_has(tty->term, TTYC_SETRGBB)) {
1964 			colour_split_rgb(gc->bg, &r, &g, &b);
1965 			gc->bg = colour_find_rgb(r, g, b);
1966 		} else
1967 			return;
1968 	}
1969 
1970 	/* How many colours does this terminal have? */
1971 	if ((tty->term->flags|tty->term_flags) & TERM_256COLOURS)
1972 		colours = 256;
1973 	else
1974 		colours = tty_term_number(tty->term, TTYC_COLORS);
1975 
1976 	/* Is this a 256-colour colour? */
1977 	if (gc->bg & COLOUR_FLAG_256) {
1978 		/*
1979 		 * And not a 256 colour mode? Translate to 16-colour
1980 		 * palette. Bold background doesn't exist portably, so just
1981 		 * discard the bold bit if set.
1982 		 */
1983 		if (colours != 256) {
1984 			gc->bg = colour_256to16(gc->bg);
1985 			if (gc->bg & 8) {
1986 				gc->bg &= 7;
1987 				if (colours >= 16)
1988 					gc->fg += 90;
1989 			}
1990 		}
1991 		return;
1992 	}
1993 
1994 	/* Is this an aixterm colour? */
1995 	if (gc->bg >= 90 && gc->bg <= 97 && colours < 16)
1996 		gc->bg -= 90;
1997 }
1998 
1999 static void
2000 tty_colours_fg(struct tty *tty, const struct grid_cell *gc)
2001 {
2002 	struct grid_cell	*tc = &tty->cell;
2003 	char			 s[32];
2004 
2005 	/* Is this a 24-bit or 256-colour colour? */
2006 	if (gc->fg & COLOUR_FLAG_RGB || gc->fg & COLOUR_FLAG_256) {
2007 		if (tty_try_colour(tty, gc->fg, "38") == 0)
2008 			goto save_fg;
2009 		/* Should not get here, already converted in tty_check_fg. */
2010 		return;
2011 	}
2012 
2013 	/* Is this an aixterm bright colour? */
2014 	if (gc->fg >= 90 && gc->fg <= 97) {
2015 		xsnprintf(s, sizeof s, "\033[%dm", gc->fg);
2016 		tty_puts(tty, s);
2017 		goto save_fg;
2018 	}
2019 
2020 	/* Otherwise set the foreground colour. */
2021 	tty_putcode1(tty, TTYC_SETAF, gc->fg);
2022 
2023 save_fg:
2024 	/* Save the new values in the terminal current cell. */
2025 	tc->fg = gc->fg;
2026 }
2027 
2028 static void
2029 tty_colours_bg(struct tty *tty, const struct grid_cell *gc)
2030 {
2031 	struct grid_cell	*tc = &tty->cell;
2032 	char			 s[32];
2033 
2034 	/* Is this a 24-bit or 256-colour colour? */
2035 	if (gc->bg & COLOUR_FLAG_RGB || gc->bg & COLOUR_FLAG_256) {
2036 		if (tty_try_colour(tty, gc->bg, "48") == 0)
2037 			goto save_bg;
2038 		/* Should not get here, already converted in tty_check_bg. */
2039 		return;
2040 	}
2041 
2042 	/* Is this an aixterm bright colour? */
2043 	if (gc->bg >= 90 && gc->bg <= 97) {
2044 		xsnprintf(s, sizeof s, "\033[%dm", gc->bg + 10);
2045 		tty_puts(tty, s);
2046 		goto save_bg;
2047 	}
2048 
2049 	/* Otherwise set the background colour. */
2050 	tty_putcode1(tty, TTYC_SETAB, gc->bg);
2051 
2052 save_bg:
2053 	/* Save the new values in the terminal current cell. */
2054 	tc->bg = gc->bg;
2055 }
2056 
2057 static int
2058 tty_try_colour(struct tty *tty, int colour, const char *type)
2059 {
2060 	u_char	r, g, b;
2061 	char	s[32];
2062 
2063 	if (colour & COLOUR_FLAG_256) {
2064 		/*
2065 		 * If the user has specified -2 to the client (meaning
2066 		 * TERM_256COLOURS is set), setaf and setab may not work (or
2067 		 * they may not want to use them), so send the usual sequence.
2068 		 *
2069 		 * Also if RGB is set, setaf and setab do not support the 256
2070 		 * colour palette so use the sequences directly there too.
2071 		 */
2072 		if ((tty->term_flags & TERM_256COLOURS) ||
2073 		    tty_term_has(tty->term, TTYC_RGB))
2074 			goto fallback_256;
2075 
2076 		/*
2077 		 * If the terminfo entry has 256 colours and setaf and setab
2078 		 * exist, assume that they work correctly.
2079 		 */
2080 		if (tty->term->flags & TERM_256COLOURS) {
2081 			if (*type == '3') {
2082 				if (!tty_term_has(tty->term, TTYC_SETAF))
2083 					goto fallback_256;
2084 				tty_putcode1(tty, TTYC_SETAF, colour & 0xff);
2085 			} else {
2086 				if (!tty_term_has(tty->term, TTYC_SETAB))
2087 					goto fallback_256;
2088 				tty_putcode1(tty, TTYC_SETAB, colour & 0xff);
2089 			}
2090 			return (0);
2091 		}
2092 		goto fallback_256;
2093 	}
2094 
2095 	if (colour & COLOUR_FLAG_RGB) {
2096 		if (*type == '3') {
2097 			if (!tty_term_has(tty->term, TTYC_SETRGBF))
2098 				return (-1);
2099 			colour_split_rgb(colour & 0xffffff, &r, &g, &b);
2100 			tty_putcode3(tty, TTYC_SETRGBF, r, g, b);
2101 		} else {
2102 			if (!tty_term_has(tty->term, TTYC_SETRGBB))
2103 				return (-1);
2104 			colour_split_rgb(colour & 0xffffff, &r, &g, &b);
2105 			tty_putcode3(tty, TTYC_SETRGBB, r, g, b);
2106 		}
2107 		return (0);
2108 	}
2109 
2110 	return (-1);
2111 
2112 fallback_256:
2113 	xsnprintf(s, sizeof s, "\033[%s;5;%dm", type, colour & 0xff);
2114 	log_debug("%s: 256 colour fallback: %s", tty->client->name, s);
2115 	tty_puts(tty, s);
2116 	return (0);
2117 }
2118 
2119 static void
2120 tty_default_colours(struct grid_cell *gc, const struct window_pane *wp)
2121 {
2122 	struct window		*w = wp->window;
2123 	struct options		*oo = w->options;
2124 	const struct grid_cell	*agc, *pgc, *wgc;
2125 	int			 c;
2126 
2127 	if (w->flags & WINDOW_STYLECHANGED) {
2128 		w->flags &= ~WINDOW_STYLECHANGED;
2129 		agc = options_get_style(oo, "window-active-style");
2130 		memcpy(&w->active_style, agc, sizeof w->active_style);
2131 		wgc = options_get_style(oo, "window-style");
2132 		memcpy(&w->style, wgc, sizeof w->style);
2133 	} else {
2134 		agc = &w->active_style;
2135 		wgc = &w->style;
2136 	}
2137 	pgc = &wp->colgc;
2138 
2139 	if (gc->fg == 8) {
2140 		if (pgc->fg != 8)
2141 			gc->fg = pgc->fg;
2142 		else if (wp == w->active && agc->fg != 8)
2143 			gc->fg = agc->fg;
2144 		else
2145 			gc->fg = wgc->fg;
2146 
2147 		if (gc->fg != 8 &&
2148 		    (c = window_pane_get_palette(wp, gc->fg)) != -1)
2149 			gc->fg = c;
2150 	}
2151 
2152 	if (gc->bg == 8) {
2153 		if (pgc->bg != 8)
2154 			gc->bg = pgc->bg;
2155 		else if (wp == w->active && agc->bg != 8)
2156 			gc->bg = agc->bg;
2157 		else
2158 			gc->bg = wgc->bg;
2159 
2160 		if (gc->bg != 8 &&
2161 		    (c = window_pane_get_palette(wp, gc->bg)) != -1)
2162 			gc->bg = c;
2163 	}
2164 }
2165 
2166 static void
2167 tty_default_attributes(struct tty *tty, const struct window_pane *wp, u_int bg)
2168 {
2169 	static struct grid_cell gc;
2170 
2171 	memcpy(&gc, &grid_default_cell, sizeof gc);
2172 	gc.bg = bg;
2173 	tty_attributes(tty, &gc, wp);
2174 }
2175