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