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