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