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