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