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