xref: /netbsd-src/external/bsd/tmux/dist/tty.c (revision 890b6d91a44b7fcb2dfbcbc1e93463086e462d2d)
1 /* $OpenBSD$ */
2 
3 /*
4  * Copyright (c) 2007 Nicholas Marriott <nicholas.marriott@gmail.com>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 #include <sys/ioctl.h>
21 
22 #include <netinet/in.h>
23 
24 #include <curses.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <resolv.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <termios.h>
31 #include <time.h>
32 #include <unistd.h>
33 
34 #include "tmux.h"
35 
36 static int	tty_log_fd = -1;
37 
38 static void	tty_set_italics(struct tty *);
39 static int	tty_try_colour(struct tty *, int, const char *);
40 static void	tty_force_cursor_colour(struct tty *, int);
41 static void	tty_cursor_pane(struct tty *, const struct tty_ctx *, u_int,
42 		    u_int);
43 static void	tty_cursor_pane_unless_wrap(struct tty *,
44 		    const struct tty_ctx *, u_int, u_int);
45 static void	tty_invalidate(struct tty *);
46 static void	tty_colours(struct tty *, const struct grid_cell *);
47 static void	tty_check_fg(struct tty *, struct colour_palette *,
48     		    struct grid_cell *);
49 static void	tty_check_bg(struct tty *, struct colour_palette *,
50     		    struct grid_cell *);
51 static void	tty_check_us(struct tty *, struct colour_palette *,
52     		    struct grid_cell *);
53 static void	tty_colours_fg(struct tty *, const struct grid_cell *);
54 static void	tty_colours_bg(struct tty *, const struct grid_cell *);
55 static void	tty_colours_us(struct tty *, const struct grid_cell *);
56 
57 static void	tty_region_pane(struct tty *, const struct tty_ctx *, u_int,
58 		    u_int);
59 static void	tty_region(struct tty *, u_int, u_int);
60 static void	tty_margin_pane(struct tty *, const struct tty_ctx *);
61 static void	tty_margin(struct tty *, u_int, u_int);
62 static int	tty_large_region(struct tty *, const struct tty_ctx *);
63 static int	tty_fake_bce(const struct tty *, const struct grid_cell *,
64 		    u_int);
65 static void	tty_redraw_region(struct tty *, const struct tty_ctx *);
66 static void	tty_emulate_repeat(struct tty *, enum tty_code_code,
67 		    enum tty_code_code, u_int);
68 static void	tty_repeat_space(struct tty *, u_int);
69 static void	tty_draw_pane(struct tty *, const struct tty_ctx *, u_int);
70 static void	tty_default_attributes(struct tty *, const struct grid_cell *,
71 		    struct colour_palette *, u_int, struct hyperlinks *);
72 static int	tty_check_overlay(struct tty *, u_int, u_int);
73 static void	tty_check_overlay_range(struct tty *, u_int, u_int, u_int,
74 		    struct overlay_ranges *);
75 
76 #ifdef ENABLE_SIXEL
77 static void	tty_write_one(void (*)(struct tty *, const struct tty_ctx *),
78 		    struct client *, struct tty_ctx *);
79 #endif
80 
81 #define tty_use_margin(tty) \
82 	(tty->term->flags & TERM_DECSLRM)
83 #define tty_full_width(tty, ctx) \
84 	((ctx)->xoff == 0 && (ctx)->sx >= (tty)->sx)
85 
86 #define TTY_BLOCK_INTERVAL (100000 /* 100 milliseconds */)
87 #define TTY_BLOCK_START(tty) (1 + ((tty)->sx * (tty)->sy) * 8)
88 #define TTY_BLOCK_STOP(tty) (1 + ((tty)->sx * (tty)->sy) / 8)
89 
90 #define TTY_QUERY_TIMEOUT 5
91 #define TTY_REQUEST_LIMIT 30
92 
93 void
94 tty_create_log(void)
95 {
96 	char	name[64];
97 
98 	xsnprintf(name, sizeof name, "tmux-out-%ld.log", (long)getpid());
99 
100 	tty_log_fd = open(name, O_WRONLY|O_CREAT|O_TRUNC, 0644);
101 	if (tty_log_fd != -1 && fcntl(tty_log_fd, F_SETFD, FD_CLOEXEC) == -1)
102 		fatal("fcntl failed");
103 }
104 
105 int
106 tty_init(struct tty *tty, struct client *c)
107 {
108 	if (!isatty(c->fd))
109 		return (-1);
110 
111 	memset(tty, 0, sizeof *tty);
112 	tty->client = c;
113 
114 	tty->cstyle = SCREEN_CURSOR_DEFAULT;
115 	tty->ccolour = -1;
116 	tty->fg = tty->bg = -1;
117 
118 	if (tcgetattr(c->fd, &tty->tio) != 0)
119 		return (-1);
120 	return (0);
121 }
122 
123 void
124 tty_resize(struct tty *tty)
125 {
126 	struct client	*c = tty->client;
127 	struct winsize	 ws;
128 	u_int		 sx, sy, xpixel, ypixel;
129 
130 	if (ioctl(c->fd, TIOCGWINSZ, &ws) != -1) {
131 		sx = ws.ws_col;
132 		if (sx == 0) {
133 			sx = 80;
134 			xpixel = 0;
135 		} else
136 			xpixel = ws.ws_xpixel / sx;
137 		sy = ws.ws_row;
138 		if (sy == 0) {
139 			sy = 24;
140 			ypixel = 0;
141 		} else
142 			ypixel = ws.ws_ypixel / sy;
143 	} else {
144 		sx = 80;
145 		sy = 24;
146 		xpixel = 0;
147 		ypixel = 0;
148 	}
149 	log_debug("%s: %s now %ux%u (%ux%u)", __func__, c->name, sx, sy,
150 	    xpixel, ypixel);
151 	tty_set_size(tty, sx, sy, xpixel, ypixel);
152 	tty_invalidate(tty);
153 }
154 
155 void
156 tty_set_size(struct tty *tty, u_int sx, u_int sy, u_int xpixel, u_int ypixel)
157 {
158 	tty->sx = sx;
159 	tty->sy = sy;
160 	tty->xpixel = xpixel;
161 	tty->ypixel = ypixel;
162 }
163 
164 static void
165 tty_read_callback(__unused int fd, __unused short events, void *data)
166 {
167 	struct tty	*tty = data;
168 	struct client	*c = tty->client;
169 	const char	*name = c->name;
170 	size_t		 size = EVBUFFER_LENGTH(tty->in);
171 	int		 nread;
172 
173 	nread = evbuffer_read(tty->in, c->fd, -1);
174 	if (nread == 0 || nread == -1) {
175 		if (nread == 0)
176 			log_debug("%s: read closed", name);
177 		else
178 			log_debug("%s: read error: %s", name, strerror(errno));
179 		event_del(&tty->event_in);
180 		server_client_lost(tty->client);
181 		return;
182 	}
183 	log_debug("%s: read %d bytes (already %zu)", name, nread, size);
184 
185 	while (tty_keys_next(tty))
186 		;
187 }
188 
189 static void
190 tty_timer_callback(__unused int fd, __unused short events, void *data)
191 {
192 	struct tty	*tty = data;
193 	struct client	*c = tty->client;
194 	struct timeval	 tv = { .tv_usec = TTY_BLOCK_INTERVAL };
195 
196 	log_debug("%s: %zu discarded", c->name, tty->discarded);
197 
198 	c->flags |= CLIENT_ALLREDRAWFLAGS;
199 	c->discarded += tty->discarded;
200 
201 	if (tty->discarded < TTY_BLOCK_STOP(tty)) {
202 		tty->flags &= ~TTY_BLOCK;
203 		tty_invalidate(tty);
204 		return;
205 	}
206 	tty->discarded = 0;
207 	evtimer_add(&tty->timer, &tv);
208 }
209 
210 static int
211 tty_block_maybe(struct tty *tty)
212 {
213 	struct client	*c = tty->client;
214 	size_t		 size = EVBUFFER_LENGTH(tty->out);
215 	struct timeval	 tv = { .tv_usec = TTY_BLOCK_INTERVAL };
216 
217 	if (size == 0)
218 		tty->flags &= ~TTY_NOBLOCK;
219 	else if (tty->flags & TTY_NOBLOCK)
220 		return (0);
221 
222 	if (size < TTY_BLOCK_START(tty))
223 		return (0);
224 
225 	if (tty->flags & TTY_BLOCK)
226 		return (1);
227 	tty->flags |= TTY_BLOCK;
228 
229 	log_debug("%s: can't keep up, %zu discarded", c->name, size);
230 
231 	evbuffer_drain(tty->out, size);
232 	c->discarded += size;
233 
234 	tty->discarded = 0;
235 	evtimer_add(&tty->timer, &tv);
236 	return (1);
237 }
238 
239 static void
240 tty_write_callback(__unused int fd, __unused short events, void *data)
241 {
242 	struct tty	*tty = data;
243 	struct client	*c = tty->client;
244 	size_t		 size = EVBUFFER_LENGTH(tty->out);
245 	int		 nwrite;
246 
247 	nwrite = evbuffer_write(tty->out, c->fd);
248 	if (nwrite == -1)
249 		return;
250 	log_debug("%s: wrote %d bytes (of %zu)", c->name, nwrite, size);
251 
252 	if (c->redraw > 0) {
253 		if ((size_t)nwrite >= c->redraw)
254 			c->redraw = 0;
255 		else
256 			c->redraw -= nwrite;
257 		log_debug("%s: waiting for redraw, %zu bytes left", c->name,
258 		    c->redraw);
259 	} else if (tty_block_maybe(tty))
260 		return;
261 
262 	if (EVBUFFER_LENGTH(tty->out) != 0)
263 		event_add(&tty->event_out, NULL);
264 }
265 
266 int
267 tty_open(struct tty *tty, char **cause)
268 {
269 	struct client	*c = tty->client;
270 
271 	tty->term = tty_term_create(tty, c->term_name, c->term_caps,
272 	    c->term_ncaps, &c->term_features, cause);
273 	if (tty->term == NULL) {
274 		tty_close(tty);
275 		return (-1);
276 	}
277 	tty->flags |= TTY_OPENED;
278 
279 	tty->flags &= ~(TTY_NOCURSOR|TTY_FREEZE|TTY_BLOCK|TTY_TIMER);
280 
281 	event_set(&tty->event_in, c->fd, EV_PERSIST|EV_READ,
282 	    tty_read_callback, tty);
283 	tty->in = evbuffer_new();
284 	if (tty->in == NULL)
285 		fatal("out of memory");
286 
287 	event_set(&tty->event_out, c->fd, EV_WRITE, tty_write_callback, tty);
288 	tty->out = evbuffer_new();
289 	if (tty->out == NULL)
290 		fatal("out of memory");
291 
292 	evtimer_set(&tty->timer, tty_timer_callback, tty);
293 
294 	tty_start_tty(tty);
295 	tty_keys_build(tty);
296 
297 	return (0);
298 }
299 
300 static void
301 tty_start_timer_callback(__unused int fd, __unused short events, void *data)
302 {
303 	struct tty	*tty = data;
304 	struct client	*c = tty->client;
305 
306 	log_debug("%s: start timer fired", c->name);
307 	if ((tty->flags & (TTY_HAVEDA|TTY_HAVEDA2|TTY_HAVEXDA)) == 0)
308 		tty_update_features(tty);
309 	tty->flags |= TTY_ALL_REQUEST_FLAGS;
310 }
311 
312 void
313 tty_start_tty(struct tty *tty)
314 {
315 	struct client	*c = tty->client;
316 	struct termios	 tio;
317 	struct timeval	 tv = { .tv_sec = TTY_QUERY_TIMEOUT };
318 
319 	setblocking(c->fd, 0);
320 	event_add(&tty->event_in, NULL);
321 
322 	memcpy(&tio, &tty->tio, sizeof tio);
323 	tio.c_iflag &= ~(IXON|IXOFF|ICRNL|INLCR|IGNCR|IMAXBEL|ISTRIP);
324 	tio.c_iflag |= IGNBRK;
325 	tio.c_oflag &= ~(OPOST|ONLCR|OCRNL|ONLRET);
326 	tio.c_lflag &= ~(IEXTEN|ICANON|ECHO|ECHOE|ECHONL|ECHOCTL|ECHOPRT|
327 	    ECHOKE|ISIG);
328 	tio.c_cc[VMIN] = 1;
329 	tio.c_cc[VTIME] = 0;
330 	if (tcsetattr(c->fd, TCSANOW, &tio) == 0)
331 		tcflush(c->fd, TCOFLUSH);
332 
333 	tty_putcode(tty, TTYC_SMCUP);
334 
335 	tty_putcode(tty, TTYC_SMKX);
336 	tty_putcode(tty, TTYC_CLEAR);
337 
338 	if (tty_acs_needed(tty)) {
339 		log_debug("%s: using capabilities for ACS", c->name);
340 		tty_putcode(tty, TTYC_ENACS);
341 	} else
342 		log_debug("%s: using UTF-8 for ACS", c->name);
343 
344 	tty_putcode(tty, TTYC_CNORM);
345 	if (tty_term_has(tty->term, TTYC_KMOUS)) {
346 		tty_puts(tty, "\033[?1000l\033[?1002l\033[?1003l");
347 		tty_puts(tty, "\033[?1006l\033[?1005l");
348 	}
349 	if (tty_term_has(tty->term, TTYC_ENBP))
350 		tty_putcode(tty, TTYC_ENBP);
351 
352 	evtimer_set(&tty->start_timer, tty_start_timer_callback, tty);
353 	evtimer_add(&tty->start_timer, &tv);
354 
355 	tty->flags |= TTY_STARTED;
356 	tty_invalidate(tty);
357 
358 	if (tty->ccolour != -1)
359 		tty_force_cursor_colour(tty, -1);
360 
361 	tty->mouse_drag_flag = 0;
362 	tty->mouse_drag_update = NULL;
363 	tty->mouse_drag_release = NULL;
364 }
365 
366 void
367 tty_send_requests(struct tty *tty)
368 {
369 	if (~tty->flags & TTY_STARTED)
370 		return;
371 
372 	if (tty->term->flags & TERM_VT100LIKE) {
373 		if (~tty->term->flags & TTY_HAVEDA)
374 			tty_puts(tty, "\033[c");
375 		if (~tty->flags & TTY_HAVEDA2)
376 			tty_puts(tty, "\033[>c");
377 		if (~tty->flags & TTY_HAVEXDA)
378 			tty_puts(tty, "\033[>q");
379 		tty_puts(tty, "\033]10;?\033\\");
380 		tty_puts(tty, "\033]11;?\033\\");
381 	} else
382 		tty->flags |= TTY_ALL_REQUEST_FLAGS;
383 	tty->last_requests = time(NULL);
384 }
385 
386 void
387 tty_repeat_requests(struct tty *tty)
388 {
389 	time_t	t = time(NULL);
390 
391 	if (~tty->flags & TTY_STARTED)
392 		return;
393 
394 	if (t - tty->last_requests <= TTY_REQUEST_LIMIT)
395 		return;
396 	tty->last_requests = t;
397 
398 	if (tty->term->flags & TERM_VT100LIKE) {
399 		tty_puts(tty, "\033]10;?\033\\");
400 		tty_puts(tty, "\033]11;?\033\\");
401 	}
402 }
403 
404 void
405 tty_stop_tty(struct tty *tty)
406 {
407 	struct client	*c = tty->client;
408 	struct winsize	 ws;
409 
410 	if (!(tty->flags & TTY_STARTED))
411 		return;
412 	tty->flags &= ~TTY_STARTED;
413 
414 	evtimer_del(&tty->start_timer);
415 
416 	event_del(&tty->timer);
417 	tty->flags &= ~TTY_BLOCK;
418 
419 	event_del(&tty->event_in);
420 	event_del(&tty->event_out);
421 
422 	/*
423 	 * Be flexible about error handling and try not kill the server just
424 	 * because the fd is invalid. Things like ssh -t can easily leave us
425 	 * with a dead tty.
426 	 */
427 	if (ioctl(c->fd, TIOCGWINSZ, &ws) == -1)
428 		return;
429 	if (tcsetattr(c->fd, TCSANOW, &tty->tio) == -1)
430 		return;
431 
432 	tty_raw(tty, tty_term_string_ii(tty->term, TTYC_CSR, 0, ws.ws_row - 1));
433 	if (tty_acs_needed(tty))
434 		tty_raw(tty, tty_term_string(tty->term, TTYC_RMACS));
435 	tty_raw(tty, tty_term_string(tty->term, TTYC_SGR0));
436 	tty_raw(tty, tty_term_string(tty->term, TTYC_RMKX));
437 	tty_raw(tty, tty_term_string(tty->term, TTYC_CLEAR));
438 	if (tty->cstyle != SCREEN_CURSOR_DEFAULT) {
439 		if (tty_term_has(tty->term, TTYC_SE))
440 			tty_raw(tty, tty_term_string(tty->term, TTYC_SE));
441 		else if (tty_term_has(tty->term, TTYC_SS))
442 			tty_raw(tty, tty_term_string_i(tty->term, TTYC_SS, 0));
443 	}
444 	if (tty->ccolour != -1)
445 		tty_raw(tty, tty_term_string(tty->term, TTYC_CR));
446 
447 	tty_raw(tty, tty_term_string(tty->term, TTYC_CNORM));
448 	if (tty_term_has(tty->term, TTYC_KMOUS)) {
449 		tty_raw(tty, "\033[?1000l\033[?1002l\033[?1003l");
450 		tty_raw(tty, "\033[?1006l\033[?1005l");
451 	}
452 	if (tty_term_has(tty->term, TTYC_DSBP))
453 		tty_raw(tty, tty_term_string(tty->term, TTYC_DSBP));
454 
455 	if (tty->term->flags & TERM_VT100LIKE)
456 		tty_raw(tty, "\033[?7727l");
457 	tty_raw(tty, tty_term_string(tty->term, TTYC_DSFCS));
458 	tty_raw(tty, tty_term_string(tty->term, TTYC_DSEKS));
459 
460 	if (tty_use_margin(tty))
461 		tty_raw(tty, tty_term_string(tty->term, TTYC_DSMG));
462 	tty_raw(tty, tty_term_string(tty->term, TTYC_RMCUP));
463 
464 	setblocking(c->fd, 1);
465 }
466 
467 void
468 tty_close(struct tty *tty)
469 {
470 	if (event_initialized(&tty->key_timer))
471 		evtimer_del(&tty->key_timer);
472 	tty_stop_tty(tty);
473 
474 	if (tty->flags & TTY_OPENED) {
475 		evbuffer_free(tty->in);
476 		event_del(&tty->event_in);
477 		evbuffer_free(tty->out);
478 		event_del(&tty->event_out);
479 
480 		tty_term_free(tty->term);
481 		tty_keys_free(tty);
482 
483 		tty->flags &= ~TTY_OPENED;
484 	}
485 }
486 
487 void
488 tty_free(struct tty *tty)
489 {
490 	tty_close(tty);
491 }
492 
493 void
494 tty_update_features(struct tty *tty)
495 {
496 	struct client	*c = tty->client;
497 
498 	if (tty_apply_features(tty->term, c->term_features))
499 		tty_term_apply_overrides(tty->term);
500 
501 	if (tty_use_margin(tty))
502 		tty_putcode(tty, TTYC_ENMG);
503 	if (options_get_number(global_options, "extended-keys"))
504 		tty_puts(tty, tty_term_string(tty->term, TTYC_ENEKS));
505 	if (options_get_number(global_options, "focus-events"))
506 		tty_puts(tty, tty_term_string(tty->term, TTYC_ENFCS));
507 	if (tty->term->flags & TERM_VT100LIKE)
508 		tty_puts(tty, "\033[?7727h");
509 
510 	/*
511 	 * Features might have changed since the first draw during attach. For
512 	 * example, this happens when DA responses are received.
513 	 */
514 	server_redraw_client(c);
515 
516 	tty_invalidate(tty);
517 }
518 
519 void
520 tty_raw(struct tty *tty, const char *s)
521 {
522 	struct client	*c = tty->client;
523 	ssize_t		 n, slen;
524 	u_int		 i;
525 
526 	slen = strlen(s);
527 	for (i = 0; i < 5; i++) {
528 		n = write(c->fd, s, slen);
529 		if (n >= 0) {
530 			s += n;
531 			slen -= n;
532 			if (slen == 0)
533 				break;
534 		} else if (n == -1 && errno != EAGAIN)
535 			break;
536 		usleep(100);
537 	}
538 }
539 
540 void
541 tty_putcode(struct tty *tty, enum tty_code_code code)
542 {
543 	tty_puts(tty, tty_term_string(tty->term, code));
544 }
545 
546 void
547 tty_putcode_i(struct tty *tty, enum tty_code_code code, int a)
548 {
549 	if (a < 0)
550 		return;
551 	tty_puts(tty, tty_term_string_i(tty->term, code, a));
552 }
553 
554 void
555 tty_putcode_ii(struct tty *tty, enum tty_code_code code, int a, int b)
556 {
557 	if (a < 0 || b < 0)
558 		return;
559 	tty_puts(tty, tty_term_string_ii(tty->term, code, a, b));
560 }
561 
562 void
563 tty_putcode_iii(struct tty *tty, enum tty_code_code code, int a, int b, int c)
564 {
565 	if (a < 0 || b < 0 || c < 0)
566 		return;
567 	tty_puts(tty, tty_term_string_iii(tty->term, code, a, b, c));
568 }
569 
570 void
571 tty_putcode_s(struct tty *tty, enum tty_code_code code, const char *a)
572 {
573 	if (a != NULL)
574 		tty_puts(tty, tty_term_string_s(tty->term, code, a));
575 }
576 
577 void
578 tty_putcode_ss(struct tty *tty, enum tty_code_code code, const char *a,
579     const char *b)
580 {
581 	if (a != NULL && b != NULL)
582 		tty_puts(tty, tty_term_string_ss(tty->term, code, a, b));
583 }
584 
585 static void
586 tty_add(struct tty *tty, const char *buf, size_t len)
587 {
588 	struct client	*c = tty->client;
589 
590 	if (tty->flags & TTY_BLOCK) {
591 		tty->discarded += len;
592 		return;
593 	}
594 
595 	evbuffer_add(tty->out, buf, len);
596 	log_debug("%s: %.*s", c->name, (int)len, buf);
597 	c->written += len;
598 
599 	if (tty_log_fd != -1)
600 		write(tty_log_fd, buf, len);
601 	if (tty->flags & TTY_STARTED)
602 		event_add(&tty->event_out, NULL);
603 }
604 
605 void
606 tty_puts(struct tty *tty, const char *s)
607 {
608 	if (*s != '\0')
609 		tty_add(tty, s, strlen(s));
610 }
611 
612 void
613 tty_putc(struct tty *tty, u_char ch)
614 {
615 	const char	*acs;
616 
617 	if ((tty->term->flags & TERM_NOAM) &&
618 	    ch >= 0x20 && ch != 0x7f &&
619 	    tty->cy == tty->sy - 1 &&
620 	    tty->cx + 1 >= tty->sx)
621 		return;
622 
623 	if (tty->cell.attr & GRID_ATTR_CHARSET) {
624 		acs = tty_acs_get(tty, ch);
625 		if (acs != NULL)
626 			tty_add(tty, acs, strlen(acs));
627 		else
628 			tty_add(tty, (char *)&ch, 1);
629 	} else
630 		tty_add(tty, (char *)&ch, 1);
631 
632 	if (ch >= 0x20 && ch != 0x7f) {
633 		if (tty->cx >= tty->sx) {
634 			tty->cx = 1;
635 			if (tty->cy != tty->rlower)
636 				tty->cy++;
637 
638 			/*
639 			 * On !am terminals, force the cursor position to where
640 			 * we think it should be after a line wrap - this means
641 			 * it works on sensible terminals as well.
642 			 */
643 			if (tty->term->flags & TERM_NOAM)
644 				tty_putcode_ii(tty, TTYC_CUP, tty->cy, tty->cx);
645 		} else
646 			tty->cx++;
647 	}
648 }
649 
650 void
651 tty_putn(struct tty *tty, const void *buf, size_t len, u_int width)
652 {
653 	if ((tty->term->flags & TERM_NOAM) &&
654 	    tty->cy == tty->sy - 1 &&
655 	    tty->cx + len >= tty->sx)
656 		len = tty->sx - tty->cx - 1;
657 
658 	tty_add(tty, buf, len);
659 	if (tty->cx + width > tty->sx) {
660 		tty->cx = (tty->cx + width) - tty->sx;
661 		if (tty->cx <= tty->sx)
662 			tty->cy++;
663 		else
664 			tty->cx = tty->cy = UINT_MAX;
665 	} else
666 		tty->cx += width;
667 }
668 
669 static void
670 tty_set_italics(struct tty *tty)
671 {
672 	const char	*s;
673 
674 	if (tty_term_has(tty->term, TTYC_SITM)) {
675 		s = options_get_string(global_options, "default-terminal");
676 		if (strcmp(s, "screen") != 0 && strncmp(s, "screen-", 7) != 0) {
677 			tty_putcode(tty, TTYC_SITM);
678 			return;
679 		}
680 	}
681 	tty_putcode(tty, TTYC_SMSO);
682 }
683 
684 void
685 tty_set_title(struct tty *tty, const char *title)
686 {
687 	if (!tty_term_has(tty->term, TTYC_TSL) ||
688 	    !tty_term_has(tty->term, TTYC_FSL))
689 		return;
690 
691 	tty_putcode(tty, TTYC_TSL);
692 	tty_puts(tty, title);
693 	tty_putcode(tty, TTYC_FSL);
694 }
695 
696 void
697 tty_set_path(struct tty *tty, const char *title)
698 {
699 	if (!tty_term_has(tty->term, TTYC_SWD) ||
700 	    !tty_term_has(tty->term, TTYC_FSL))
701 		return;
702 
703 	tty_putcode(tty, TTYC_SWD);
704 	tty_puts(tty, title);
705 	tty_putcode(tty, TTYC_FSL);
706 }
707 
708 static void
709 tty_force_cursor_colour(struct tty *tty, int c)
710 {
711 	u_char	r, g, b;
712 	char	s[13];
713 
714 	if (c != -1)
715 		c = colour_force_rgb(c);
716 	if (c == tty->ccolour)
717 		return;
718 	if (c == -1)
719 		tty_putcode(tty, TTYC_CR);
720 	else {
721 		colour_split_rgb(c, &r, &g, &b);
722 		xsnprintf(s, sizeof s, "rgb:%02hhx/%02hhx/%02hhx", r, g, b);
723 		tty_putcode_s(tty, TTYC_CS, s);
724 	}
725 	tty->ccolour = c;
726 }
727 
728 static int
729 tty_update_cursor(struct tty *tty, int mode, struct screen *s)
730 {
731 	enum screen_cursor_style	cstyle;
732 	int				ccolour, changed, cmode = mode;
733 
734 	/* Set cursor colour if changed. */
735 	if (s != NULL) {
736 		ccolour = s->ccolour;
737 		if (s->ccolour == -1)
738 			ccolour = s->default_ccolour;
739 		tty_force_cursor_colour(tty, ccolour);
740 	}
741 
742 	/* If cursor is off, set as invisible. */
743 	if (~cmode & MODE_CURSOR) {
744 		if (tty->mode & MODE_CURSOR)
745 			tty_putcode(tty, TTYC_CIVIS);
746 		return (cmode);
747 	}
748 
749 	/* Check if blinking or very visible flag changed or style changed. */
750 	if (s == NULL)
751 		cstyle = tty->cstyle;
752 	else {
753 		cstyle = s->cstyle;
754 		if (cstyle == SCREEN_CURSOR_DEFAULT) {
755 			if (~cmode & MODE_CURSOR_BLINKING_SET) {
756 				if (s->default_mode & MODE_CURSOR_BLINKING)
757 					cmode |= MODE_CURSOR_BLINKING;
758 				else
759 					cmode &= ~MODE_CURSOR_BLINKING;
760 			}
761 			cstyle = s->default_cstyle;
762 		}
763 	}
764 
765 	/* If nothing changed, do nothing. */
766 	changed = cmode ^ tty->mode;
767 	if ((changed & CURSOR_MODES) == 0 && cstyle == tty->cstyle)
768 		return (cmode);
769 
770 	/*
771 	 * Set cursor style. If an explicit style has been set with DECSCUSR,
772 	 * set it if supported, otherwise send cvvis for blinking styles.
773 	 *
774 	 * If no style, has been set (SCREEN_CURSOR_DEFAULT), then send cvvis
775 	 * if either the blinking or very visible flags are set.
776 	 */
777 	tty_putcode(tty, TTYC_CNORM);
778 	switch (cstyle) {
779 	case SCREEN_CURSOR_DEFAULT:
780 		if (tty->cstyle != SCREEN_CURSOR_DEFAULT) {
781 			if (tty_term_has(tty->term, TTYC_SE))
782 				tty_putcode(tty, TTYC_SE);
783 			else
784 				tty_putcode_i(tty, TTYC_SS, 0);
785 		}
786 		if (cmode & (MODE_CURSOR_BLINKING|MODE_CURSOR_VERY_VISIBLE))
787 			tty_putcode(tty, TTYC_CVVIS);
788 		break;
789 	case SCREEN_CURSOR_BLOCK:
790 		if (tty_term_has(tty->term, TTYC_SS)) {
791 			if (cmode & MODE_CURSOR_BLINKING)
792 				tty_putcode_i(tty, TTYC_SS, 1);
793 			else
794 				tty_putcode_i(tty, TTYC_SS, 2);
795 		} else if (cmode & MODE_CURSOR_BLINKING)
796 			tty_putcode(tty, TTYC_CVVIS);
797 		break;
798 	case SCREEN_CURSOR_UNDERLINE:
799 		if (tty_term_has(tty->term, TTYC_SS)) {
800 			if (cmode & MODE_CURSOR_BLINKING)
801 				tty_putcode_i(tty, TTYC_SS, 3);
802 			else
803 				tty_putcode_i(tty, TTYC_SS, 4);
804 		} else if (cmode & MODE_CURSOR_BLINKING)
805 			tty_putcode(tty, TTYC_CVVIS);
806 		break;
807 	case SCREEN_CURSOR_BAR:
808 		if (tty_term_has(tty->term, TTYC_SS)) {
809 			if (cmode & MODE_CURSOR_BLINKING)
810 				tty_putcode_i(tty, TTYC_SS, 5);
811 			else
812 				tty_putcode_i(tty, TTYC_SS, 6);
813 		} else if (cmode & MODE_CURSOR_BLINKING)
814 			tty_putcode(tty, TTYC_CVVIS);
815 		break;
816 	}
817 	tty->cstyle = cstyle;
818 	return (cmode);
819  }
820 
821 void
822 tty_update_mode(struct tty *tty, int mode, struct screen *s)
823 {
824 	struct tty_term	*term = tty->term;
825 	struct client	*c = tty->client;
826 	int		 changed;
827 
828 	if (tty->flags & TTY_NOCURSOR)
829 		mode &= ~MODE_CURSOR;
830 
831 	if (tty_update_cursor(tty, mode, s) & MODE_CURSOR_BLINKING)
832 		mode |= MODE_CURSOR_BLINKING;
833 	else
834 		mode &= ~MODE_CURSOR_BLINKING;
835 
836 	changed = mode ^ tty->mode;
837 	if (log_get_level() != 0 && changed != 0) {
838 		log_debug("%s: current mode %s", c->name,
839 		    screen_mode_to_string(tty->mode));
840 		log_debug("%s: setting mode %s", c->name,
841 		    screen_mode_to_string(mode));
842 	}
843 
844 	if ((changed & ALL_MOUSE_MODES) && tty_term_has(term, TTYC_KMOUS)) {
845 		/*
846 		 * If the mouse modes have changed, clear then all and apply
847 		 * again. There are differences in how terminals track the
848 		 * various bits.
849 		 */
850 		tty_puts(tty, "\033[?1006l\033[?1000l\033[?1002l\033[?1003l");
851 		if (mode & ALL_MOUSE_MODES)
852 			tty_puts(tty, "\033[?1006h");
853 		if (mode & MODE_MOUSE_ALL)
854 			tty_puts(tty, "\033[?1000h\033[?1002h\033[?1003h");
855 		else if (mode & MODE_MOUSE_BUTTON)
856 			tty_puts(tty, "\033[?1000h\033[?1002h");
857 		else if (mode & MODE_MOUSE_STANDARD)
858 			tty_puts(tty, "\033[?1000h");
859 	}
860 	tty->mode = mode;
861 }
862 
863 static void
864 tty_emulate_repeat(struct tty *tty, enum tty_code_code code,
865     enum tty_code_code code1, u_int n)
866 {
867 	if (tty_term_has(tty->term, code))
868 		tty_putcode_i(tty, code, n);
869 	else {
870 		while (n-- > 0)
871 			tty_putcode(tty, code1);
872 	}
873 }
874 
875 static void
876 tty_repeat_space(struct tty *tty, u_int n)
877 {
878 	static char s[500];
879 
880 	if (*s != ' ')
881 		memset(s, ' ', sizeof s);
882 
883 	while (n > sizeof s) {
884 		tty_putn(tty, s, sizeof s, sizeof s);
885 		n -= sizeof s;
886 	}
887 	if (n != 0)
888 		tty_putn(tty, s, n, n);
889 }
890 
891 /* Is this window bigger than the terminal? */
892 int
893 tty_window_bigger(struct tty *tty)
894 {
895 	struct client	*c = tty->client;
896 	struct window	*w = c->session->curw->window;
897 
898 	return (tty->sx < w->sx || tty->sy - status_line_size(c) < w->sy);
899 }
900 
901 /* What offset should this window be drawn at? */
902 int
903 tty_window_offset(struct tty *tty, u_int *ox, u_int *oy, u_int *sx, u_int *sy)
904 {
905 	*ox = tty->oox;
906 	*oy = tty->ooy;
907 	*sx = tty->osx;
908 	*sy = tty->osy;
909 
910 	return (tty->oflag);
911 }
912 
913 /* What offset should this window be drawn at? */
914 static int
915 tty_window_offset1(struct tty *tty, u_int *ox, u_int *oy, u_int *sx, u_int *sy)
916 {
917 	struct client		*c = tty->client;
918 	struct window		*w = c->session->curw->window;
919 	struct window_pane	*wp = server_client_get_pane(c);
920 	u_int			 cx, cy, lines;
921 
922 	lines = status_line_size(c);
923 
924 	if (tty->sx >= w->sx && tty->sy - lines >= w->sy) {
925 		*ox = 0;
926 		*oy = 0;
927 		*sx = w->sx;
928 		*sy = w->sy;
929 
930 		c->pan_window = NULL;
931 		return (0);
932 	}
933 
934 	*sx = tty->sx;
935 	*sy = tty->sy - lines;
936 
937 	if (c->pan_window == w) {
938 		if (*sx >= w->sx)
939 			c->pan_ox = 0;
940 		else if (c->pan_ox + *sx > w->sx)
941 			c->pan_ox = w->sx - *sx;
942 		*ox = c->pan_ox;
943 		if (*sy >= w->sy)
944 			c->pan_oy = 0;
945 		else if (c->pan_oy + *sy > w->sy)
946 			c->pan_oy = w->sy - *sy;
947 		*oy = c->pan_oy;
948 		return (1);
949 	}
950 
951 	if (~wp->screen->mode & MODE_CURSOR) {
952 		*ox = 0;
953 		*oy = 0;
954 	} else {
955 		cx = wp->xoff + wp->screen->cx;
956 		cy = wp->yoff + wp->screen->cy;
957 
958 		if (cx < *sx)
959 			*ox = 0;
960 		else if (cx > w->sx - *sx)
961 			*ox = w->sx - *sx;
962 		else
963 			*ox = cx - *sx / 2;
964 
965 		if (cy < *sy)
966 			*oy = 0;
967 		else if (cy > w->sy - *sy)
968 			*oy = w->sy - *sy;
969 		else
970 			*oy = cy - *sy / 2;
971 	}
972 
973 	c->pan_window = NULL;
974 	return (1);
975 }
976 
977 /* Update stored offsets for a window and redraw if necessary. */
978 void
979 tty_update_window_offset(struct window *w)
980 {
981 	struct client	*c;
982 
983 	TAILQ_FOREACH(c, &clients, entry) {
984 		if (c->session != NULL &&
985 		    c->session->curw != NULL &&
986 		    c->session->curw->window == w)
987 			tty_update_client_offset(c);
988 	}
989 }
990 
991 /* Update stored offsets for a client and redraw if necessary. */
992 void
993 tty_update_client_offset(struct client *c)
994 {
995 	u_int	ox, oy, sx, sy;
996 
997 	if (~c->flags & CLIENT_TERMINAL)
998 		return;
999 
1000 	c->tty.oflag = tty_window_offset1(&c->tty, &ox, &oy, &sx, &sy);
1001 	if (ox == c->tty.oox &&
1002 	    oy == c->tty.ooy &&
1003 	    sx == c->tty.osx &&
1004 	    sy == c->tty.osy)
1005 		return;
1006 
1007 	log_debug ("%s: %s offset has changed (%u,%u %ux%u -> %u,%u %ux%u)",
1008 	    __func__, c->name, c->tty.oox, c->tty.ooy, c->tty.osx, c->tty.osy,
1009 	    ox, oy, sx, sy);
1010 
1011 	c->tty.oox = ox;
1012 	c->tty.ooy = oy;
1013 	c->tty.osx = sx;
1014 	c->tty.osy = sy;
1015 
1016 	c->flags |= (CLIENT_REDRAWWINDOW|CLIENT_REDRAWSTATUS);
1017 }
1018 
1019 /*
1020  * Is the region large enough to be worth redrawing once later rather than
1021  * probably several times now? Currently yes if it is more than 50% of the
1022  * pane.
1023  */
1024 static int
1025 tty_large_region(__unused struct tty *tty, const struct tty_ctx *ctx)
1026 {
1027 	return (ctx->orlower - ctx->orupper >= ctx->sy / 2);
1028 }
1029 
1030 /*
1031  * Return if BCE is needed but the terminal doesn't have it - it'll need to be
1032  * emulated.
1033  */
1034 static int
1035 tty_fake_bce(const struct tty *tty, const struct grid_cell *gc, u_int bg)
1036 {
1037 	if (tty_term_flag(tty->term, TTYC_BCE))
1038 		return (0);
1039 	if (!COLOUR_DEFAULT(bg) || !COLOUR_DEFAULT(gc->bg))
1040 		return (1);
1041 	return (0);
1042 }
1043 
1044 /*
1045  * Redraw scroll region using data from screen (already updated). Used when
1046  * CSR not supported, or window is a pane that doesn't take up the full
1047  * width of the terminal.
1048  */
1049 static void
1050 tty_redraw_region(struct tty *tty, const struct tty_ctx *ctx)
1051 {
1052 	struct client		*c = tty->client;
1053 	u_int			 i;
1054 
1055 	/*
1056 	 * If region is large, schedule a redraw. In most cases this is likely
1057 	 * to be followed by some more scrolling.
1058 	 */
1059 	if (tty_large_region(tty, ctx)) {
1060 		log_debug("%s: %s large redraw", __func__, c->name);
1061 		ctx->redraw_cb(ctx);
1062 		return;
1063 	}
1064 
1065 	for (i = ctx->orupper; i <= ctx->orlower; i++)
1066 		tty_draw_pane(tty, ctx, i);
1067 }
1068 
1069 /* Is this position visible in the pane? */
1070 static int
1071 tty_is_visible(__unused struct tty *tty, const struct tty_ctx *ctx, u_int px,
1072     u_int py, u_int nx, u_int ny)
1073 {
1074 	u_int	xoff = ctx->rxoff + px, yoff = ctx->ryoff + py;
1075 
1076 	if (!ctx->bigger)
1077 		return (1);
1078 
1079 	if (xoff + nx <= ctx->wox || xoff >= ctx->wox + ctx->wsx ||
1080 	    yoff + ny <= ctx->woy || yoff >= ctx->woy + ctx->wsy)
1081 		return (0);
1082 	return (1);
1083 }
1084 
1085 /* Clamp line position to visible part of pane. */
1086 static int
1087 tty_clamp_line(struct tty *tty, const struct tty_ctx *ctx, u_int px, u_int py,
1088     u_int nx, u_int *i, u_int *x, u_int *rx, u_int *ry)
1089 {
1090 	u_int	xoff = ctx->rxoff + px;
1091 
1092 	if (!tty_is_visible(tty, ctx, px, py, nx, 1))
1093 		return (0);
1094 	*ry = ctx->yoff + py - ctx->woy;
1095 
1096 	if (xoff >= ctx->wox && xoff + nx <= ctx->wox + ctx->wsx) {
1097 		/* All visible. */
1098 		*i = 0;
1099 		*x = ctx->xoff + px - ctx->wox;
1100 		*rx = nx;
1101 	} else if (xoff < ctx->wox && xoff + nx > ctx->wox + ctx->wsx) {
1102 		/* Both left and right not visible. */
1103 		*i = ctx->wox;
1104 		*x = 0;
1105 		*rx = ctx->wsx;
1106 	} else if (xoff < ctx->wox) {
1107 		/* Left not visible. */
1108 		*i = ctx->wox - (ctx->xoff + px);
1109 		*x = 0;
1110 		*rx = nx - *i;
1111 	} else {
1112 		/* Right not visible. */
1113 		*i = 0;
1114 		*x = (ctx->xoff + px) - ctx->wox;
1115 		*rx = ctx->wsx - *x;
1116 	}
1117 	if (*rx > nx)
1118 		fatalx("%s: x too big, %u > %u", __func__, *rx, nx);
1119 
1120 	return (1);
1121 }
1122 
1123 /* Clear a line. */
1124 static void
1125 tty_clear_line(struct tty *tty, const struct grid_cell *defaults, u_int py,
1126     u_int px, u_int nx, u_int bg)
1127 {
1128 	struct client		*c = tty->client;
1129 	struct overlay_ranges	 r;
1130 	u_int			 i;
1131 
1132 	log_debug("%s: %s, %u at %u,%u", __func__, c->name, nx, px, py);
1133 
1134 	/* Nothing to clear. */
1135 	if (nx == 0)
1136 		return;
1137 
1138 	/* If genuine BCE is available, can try escape sequences. */
1139 	if (c->overlay_check == NULL && !tty_fake_bce(tty, defaults, bg)) {
1140 		/* Off the end of the line, use EL if available. */
1141 		if (px + nx >= tty->sx && tty_term_has(tty->term, TTYC_EL)) {
1142 			tty_cursor(tty, px, py);
1143 			tty_putcode(tty, TTYC_EL);
1144 			return;
1145 		}
1146 
1147 		/* At the start of the line. Use EL1. */
1148 		if (px == 0 && tty_term_has(tty->term, TTYC_EL1)) {
1149 			tty_cursor(tty, px + nx - 1, py);
1150 			tty_putcode(tty, TTYC_EL1);
1151 			return;
1152 		}
1153 
1154 		/* Section of line. Use ECH if possible. */
1155 		if (tty_term_has(tty->term, TTYC_ECH)) {
1156 			tty_cursor(tty, px, py);
1157 			tty_putcode_i(tty, TTYC_ECH, nx);
1158 			return;
1159 		}
1160 	}
1161 
1162 	/*
1163 	 * Couldn't use an escape sequence, use spaces. Clear only the visible
1164 	 * bit if there is an overlay.
1165 	 */
1166 	tty_check_overlay_range(tty, px, py, nx, &r);
1167 	for (i = 0; i < OVERLAY_MAX_RANGES; i++) {
1168 		if (r.nx[i] == 0)
1169 			continue;
1170 		tty_cursor(tty, r.px[i], py);
1171 		tty_repeat_space(tty, r.nx[i]);
1172 	}
1173 }
1174 
1175 /* Clear a line, adjusting to visible part of pane. */
1176 static void
1177 tty_clear_pane_line(struct tty *tty, const struct tty_ctx *ctx, u_int py,
1178     u_int px, u_int nx, u_int bg)
1179 {
1180 	struct client	*c = tty->client;
1181 	u_int		 i, x, rx, ry;
1182 
1183 	log_debug("%s: %s, %u at %u,%u", __func__, c->name, nx, px, py);
1184 
1185 	if (tty_clamp_line(tty, ctx, px, py, nx, &i, &x, &rx, &ry))
1186 		tty_clear_line(tty, &ctx->defaults, ry, x, rx, bg);
1187 }
1188 
1189 /* Clamp area position to visible part of pane. */
1190 static int
1191 tty_clamp_area(struct tty *tty, const struct tty_ctx *ctx, u_int px, u_int py,
1192     u_int nx, u_int ny, u_int *i, u_int *j, u_int *x, u_int *y, u_int *rx,
1193     u_int *ry)
1194 {
1195 	u_int	xoff = ctx->rxoff + px, yoff = ctx->ryoff + py;
1196 
1197 	if (!tty_is_visible(tty, ctx, px, py, nx, ny))
1198 		return (0);
1199 
1200 	if (xoff >= ctx->wox && xoff + nx <= ctx->wox + ctx->wsx) {
1201 		/* All visible. */
1202 		*i = 0;
1203 		*x = ctx->xoff + px - ctx->wox;
1204 		*rx = nx;
1205 	} else if (xoff < ctx->wox && xoff + nx > ctx->wox + ctx->wsx) {
1206 		/* Both left and right not visible. */
1207 		*i = ctx->wox;
1208 		*x = 0;
1209 		*rx = ctx->wsx;
1210 	} else if (xoff < ctx->wox) {
1211 		/* Left not visible. */
1212 		*i = ctx->wox - (ctx->xoff + px);
1213 		*x = 0;
1214 		*rx = nx - *i;
1215 	} else {
1216 		/* Right not visible. */
1217 		*i = 0;
1218 		*x = (ctx->xoff + px) - ctx->wox;
1219 		*rx = ctx->wsx - *x;
1220 	}
1221 	if (*rx > nx)
1222 		fatalx("%s: x too big, %u > %u", __func__, *rx, nx);
1223 
1224 	if (yoff >= ctx->woy && yoff + ny <= ctx->woy + ctx->wsy) {
1225 		/* All visible. */
1226 		*j = 0;
1227 		*y = ctx->yoff + py - ctx->woy;
1228 		*ry = ny;
1229 	} else if (yoff < ctx->woy && yoff + ny > ctx->woy + ctx->wsy) {
1230 		/* Both top and bottom not visible. */
1231 		*j = ctx->woy;
1232 		*y = 0;
1233 		*ry = ctx->wsy;
1234 	} else if (yoff < ctx->woy) {
1235 		/* Top not visible. */
1236 		*j = ctx->woy - (ctx->yoff + py);
1237 		*y = 0;
1238 		*ry = ny - *j;
1239 	} else {
1240 		/* Bottom not visible. */
1241 		*j = 0;
1242 		*y = (ctx->yoff + py) - ctx->woy;
1243 		*ry = ctx->wsy - *y;
1244 	}
1245 	if (*ry > ny)
1246 		fatalx("%s: y too big, %u > %u", __func__, *ry, ny);
1247 
1248 	return (1);
1249 }
1250 
1251 /* Clear an area, adjusting to visible part of pane. */
1252 static void
1253 tty_clear_area(struct tty *tty, const struct grid_cell *defaults, u_int py,
1254     u_int ny, u_int px, u_int nx, u_int bg)
1255 {
1256 	struct client	*c = tty->client;
1257 	u_int		 yy;
1258 	char		 tmp[64];
1259 
1260 	log_debug("%s: %s, %u,%u at %u,%u", __func__, c->name, nx, ny, px, py);
1261 
1262 	/* Nothing to clear. */
1263 	if (nx == 0 || ny == 0)
1264 		return;
1265 
1266 	/* If genuine BCE is available, can try escape sequences. */
1267 	if (c->overlay_check == NULL && !tty_fake_bce(tty, defaults, bg)) {
1268 		/* Use ED if clearing off the bottom of the terminal. */
1269 		if (px == 0 &&
1270 		    px + nx >= tty->sx &&
1271 		    py + ny >= tty->sy &&
1272 		    tty_term_has(tty->term, TTYC_ED)) {
1273 			tty_cursor(tty, 0, py);
1274 			tty_putcode(tty, TTYC_ED);
1275 			return;
1276 		}
1277 
1278 		/*
1279 		 * On VT420 compatible terminals we can use DECFRA if the
1280 		 * background colour isn't default (because it doesn't work
1281 		 * after SGR 0).
1282 		 */
1283 		if ((tty->term->flags & TERM_DECFRA) && !COLOUR_DEFAULT(bg)) {
1284 			xsnprintf(tmp, sizeof tmp, "\033[32;%u;%u;%u;%u$x",
1285 			    py + 1, px + 1, py + ny, px + nx);
1286 			tty_puts(tty, tmp);
1287 			return;
1288 		}
1289 
1290 		/* Full lines can be scrolled away to clear them. */
1291 		if (px == 0 &&
1292 		    px + nx >= tty->sx &&
1293 		    ny > 2 &&
1294 		    tty_term_has(tty->term, TTYC_CSR) &&
1295 		    tty_term_has(tty->term, TTYC_INDN)) {
1296 			tty_region(tty, py, py + ny - 1);
1297 			tty_margin_off(tty);
1298 			tty_putcode_i(tty, TTYC_INDN, ny);
1299 			return;
1300 		}
1301 
1302 		/*
1303 		 * If margins are supported, can just scroll the area off to
1304 		 * clear it.
1305 		 */
1306 		if (nx > 2 &&
1307 		    ny > 2 &&
1308 		    tty_term_has(tty->term, TTYC_CSR) &&
1309 		    tty_use_margin(tty) &&
1310 		    tty_term_has(tty->term, TTYC_INDN)) {
1311 			tty_region(tty, py, py + ny - 1);
1312 			tty_margin(tty, px, px + nx - 1);
1313 			tty_putcode_i(tty, TTYC_INDN, ny);
1314 			return;
1315 		}
1316 	}
1317 
1318 	/* Couldn't use an escape sequence, loop over the lines. */
1319 	for (yy = py; yy < py + ny; yy++)
1320 		tty_clear_line(tty, defaults, yy, px, nx, bg);
1321 }
1322 
1323 /* Clear an area in a pane. */
1324 static void
1325 tty_clear_pane_area(struct tty *tty, const struct tty_ctx *ctx, u_int py,
1326     u_int ny, u_int px, u_int nx, u_int bg)
1327 {
1328 	u_int	i, j, x, y, rx, ry;
1329 
1330 	if (tty_clamp_area(tty, ctx, px, py, nx, ny, &i, &j, &x, &y, &rx, &ry))
1331 		tty_clear_area(tty, &ctx->defaults, y, ry, x, rx, bg);
1332 }
1333 
1334 static void
1335 tty_draw_pane(struct tty *tty, const struct tty_ctx *ctx, u_int py)
1336 {
1337 	struct screen	*s = ctx->s;
1338 	u_int		 nx = ctx->sx, i, x, rx, ry;
1339 
1340 	log_debug("%s: %s %u %d", __func__, tty->client->name, py, ctx->bigger);
1341 
1342 	if (!ctx->bigger) {
1343 		tty_draw_line(tty, s, 0, py, nx, ctx->xoff, ctx->yoff + py,
1344 		    &ctx->defaults, ctx->palette);
1345 		return;
1346 	}
1347 	if (tty_clamp_line(tty, ctx, 0, py, nx, &i, &x, &rx, &ry)) {
1348 		tty_draw_line(tty, s, i, py, rx, x, ry, &ctx->defaults,
1349 		    ctx->palette);
1350 	}
1351 }
1352 
1353 static const struct grid_cell *
1354 tty_check_codeset(struct tty *tty, const struct grid_cell *gc)
1355 {
1356 	static struct grid_cell	new;
1357 	int			c;
1358 
1359 	/* Characters less than 0x7f are always fine, no matter what. */
1360 	if (gc->data.size == 1 && *gc->data.data < 0x7f)
1361 		return (gc);
1362 
1363 	/* UTF-8 terminal and a UTF-8 character - fine. */
1364 	if (tty->client->flags & CLIENT_UTF8)
1365 		return (gc);
1366 	memcpy(&new, gc, sizeof new);
1367 
1368 	/* See if this can be mapped to an ACS character. */
1369 	c = tty_acs_reverse_get(tty, (const char *)gc->data.data, gc->data.size);
1370 	if (c != -1) {
1371 		utf8_set(&new.data, c);
1372 		new.attr |= GRID_ATTR_CHARSET;
1373 		return (&new);
1374 	}
1375 
1376 	/* Replace by the right number of underscores. */
1377 	new.data.size = gc->data.width;
1378 	if (new.data.size > UTF8_SIZE)
1379 		new.data.size = UTF8_SIZE;
1380 	memset(new.data.data, '_', new.data.size);
1381 	return (&new);
1382 }
1383 
1384 /*
1385  * Check if a single character is obstructed by the overlay and return a
1386  * boolean.
1387  */
1388 static int
1389 tty_check_overlay(struct tty *tty, u_int px, u_int py)
1390 {
1391 	struct overlay_ranges	r;
1392 
1393 	/*
1394 	 * A unit width range will always return nx[2] == 0 from a check, even
1395 	 * with multiple overlays, so it's sufficient to check just the first
1396 	 * two entries.
1397 	 */
1398 	tty_check_overlay_range(tty, px, py, 1, &r);
1399 	if (r.nx[0] + r.nx[1] == 0)
1400 		return (0);
1401 	return (1);
1402 }
1403 
1404 /* Return parts of the input range which are visible. */
1405 static void
1406 tty_check_overlay_range(struct tty *tty, u_int px, u_int py, u_int nx,
1407     struct overlay_ranges *r)
1408 {
1409 	struct client	*c = tty->client;
1410 
1411 	if (c->overlay_check == NULL) {
1412 		r->px[0] = px;
1413 		r->nx[0] = nx;
1414 		r->px[1] = 0;
1415 		r->nx[1] = 0;
1416 		r->px[2] = 0;
1417 		r->nx[2] = 0;
1418 		return;
1419 	}
1420 
1421 	c->overlay_check(c, c->overlay_data, px, py, nx, r);
1422 }
1423 
1424 void
1425 tty_draw_line(struct tty *tty, struct screen *s, u_int px, u_int py, u_int nx,
1426     u_int atx, u_int aty, const struct grid_cell *defaults,
1427     struct colour_palette *palette)
1428 {
1429 	struct grid		*gd = s->grid;
1430 	struct grid_cell	 gc, last;
1431 	const struct grid_cell	*gcp;
1432 	struct grid_line	*gl;
1433 	struct client		*c = tty->client;
1434 	struct overlay_ranges	 r;
1435 	u_int			 i, j, ux, sx, width, hidden, eux, nxx;
1436 	u_int			 cellsize;
1437 	int			 flags, cleared = 0, wrapped = 0;
1438 	char			 buf[512];
1439 	size_t			 len;
1440 
1441 	log_debug("%s: px=%u py=%u nx=%u atx=%u aty=%u", __func__,
1442 	    px, py, nx, atx, aty);
1443 	log_debug("%s: defaults: fg=%d, bg=%d", __func__, defaults->fg,
1444 	    defaults->bg);
1445 
1446 	/*
1447 	 * py is the line in the screen to draw.
1448 	 * px is the start x and nx is the width to draw.
1449 	 * atx,aty is the line on the terminal to draw it.
1450 	 */
1451 
1452 	flags = (tty->flags & TTY_NOCURSOR);
1453 	tty->flags |= TTY_NOCURSOR;
1454 	tty_update_mode(tty, tty->mode, s);
1455 
1456 	tty_region_off(tty);
1457 	tty_margin_off(tty);
1458 
1459 	/*
1460 	 * Clamp the width to cellsize - note this is not cellused, because
1461 	 * there may be empty background cells after it (from BCE).
1462 	 */
1463 	sx = screen_size_x(s);
1464 	if (nx > sx)
1465 		nx = sx;
1466 	cellsize = grid_get_line(gd, gd->hsize + py)->cellsize;
1467 	if (sx > cellsize)
1468 		sx = cellsize;
1469 	if (sx > tty->sx)
1470 		sx = tty->sx;
1471 	if (sx > nx)
1472 		sx = nx;
1473 	ux = 0;
1474 
1475 	if (py == 0)
1476 		gl = NULL;
1477 	else
1478 		gl = grid_get_line(gd, gd->hsize + py - 1);
1479 	if (gl == NULL ||
1480 	    (~gl->flags & GRID_LINE_WRAPPED) ||
1481 	    atx != 0 ||
1482 	    tty->cx < tty->sx ||
1483 	    nx < tty->sx) {
1484 		if (nx < tty->sx &&
1485 		    atx == 0 &&
1486 		    px + sx != nx &&
1487 		    tty_term_has(tty->term, TTYC_EL1) &&
1488 		    !tty_fake_bce(tty, defaults, 8) &&
1489 		    c->overlay_check == NULL) {
1490 			tty_default_attributes(tty, defaults, palette, 8,
1491 			    s->hyperlinks);
1492 			tty_cursor(tty, nx - 1, aty);
1493 			tty_putcode(tty, TTYC_EL1);
1494 			cleared = 1;
1495 		}
1496 	} else {
1497 		log_debug("%s: wrapped line %u", __func__, aty);
1498 		wrapped = 1;
1499 	}
1500 
1501 	memcpy(&last, &grid_default_cell, sizeof last);
1502 	len = 0;
1503 	width = 0;
1504 
1505 	for (i = 0; i < sx; i++) {
1506 		grid_view_get_cell(gd, px + i, py, &gc);
1507 		gcp = tty_check_codeset(tty, &gc);
1508 		if (len != 0 &&
1509 		    (!tty_check_overlay(tty, atx + ux + width, aty) ||
1510 		    (gcp->attr & GRID_ATTR_CHARSET) ||
1511 		    gcp->flags != last.flags ||
1512 		    gcp->attr != last.attr ||
1513 		    gcp->fg != last.fg ||
1514 		    gcp->bg != last.bg ||
1515 		    gcp->us != last.us ||
1516 		    gcp->link != last.link ||
1517 		    ux + width + gcp->data.width > nx ||
1518 		    (sizeof buf) - len < gcp->data.size)) {
1519 			tty_attributes(tty, &last, defaults, palette,
1520 			    s->hyperlinks);
1521 			if (last.flags & GRID_FLAG_CLEARED) {
1522 				log_debug("%s: %zu cleared", __func__, len);
1523 				tty_clear_line(tty, defaults, aty, atx + ux,
1524 				    width, last.bg);
1525 			} else {
1526 				if (!wrapped || atx != 0 || ux != 0)
1527 					tty_cursor(tty, atx + ux, aty);
1528 				tty_putn(tty, buf, len, width);
1529 			}
1530 			ux += width;
1531 
1532 			len = 0;
1533 			width = 0;
1534 			wrapped = 0;
1535 		}
1536 
1537 		if (gcp->flags & GRID_FLAG_SELECTED)
1538 			screen_select_cell(s, &last, gcp);
1539 		else
1540 			memcpy(&last, gcp, sizeof last);
1541 
1542 		tty_check_overlay_range(tty, atx + ux, aty, gcp->data.width,
1543 		    &r);
1544 		hidden = 0;
1545 		for (j = 0; j < OVERLAY_MAX_RANGES; j++)
1546 			hidden += r.nx[j];
1547 		hidden = gcp->data.width - hidden;
1548 		if (hidden != 0 && hidden == gcp->data.width) {
1549 			if (~gcp->flags & GRID_FLAG_PADDING)
1550 				ux += gcp->data.width;
1551 		} else if (hidden != 0 || ux + gcp->data.width > nx) {
1552 			if (~gcp->flags & GRID_FLAG_PADDING) {
1553 				tty_attributes(tty, &last, defaults, palette,
1554 				    s->hyperlinks);
1555 				for (j = 0; j < OVERLAY_MAX_RANGES; j++) {
1556 					if (r.nx[j] == 0)
1557 						continue;
1558 					/* Effective width drawn so far. */
1559 					eux = r.px[j] - atx;
1560 					if (eux < nx) {
1561 						tty_cursor(tty, r.px[j], aty);
1562 						nxx = nx - eux;
1563 						if (r.nx[j] > nxx)
1564 							r.nx[j] = nxx;
1565 						tty_repeat_space(tty, r.nx[j]);
1566 						ux = eux + r.nx[j];
1567 					}
1568 				}
1569 			}
1570 		} else if (gcp->attr & GRID_ATTR_CHARSET) {
1571 			tty_attributes(tty, &last, defaults, palette,
1572 			    s->hyperlinks);
1573 			tty_cursor(tty, atx + ux, aty);
1574 			for (j = 0; j < gcp->data.size; j++)
1575 				tty_putc(tty, gcp->data.data[j]);
1576 			ux += gcp->data.width;
1577 		} else if (~gcp->flags & GRID_FLAG_PADDING) {
1578 			memcpy(buf + len, gcp->data.data, gcp->data.size);
1579 			len += gcp->data.size;
1580 			width += gcp->data.width;
1581 		}
1582 	}
1583 	if (len != 0 && ((~last.flags & GRID_FLAG_CLEARED) || last.bg != 8)) {
1584 		tty_attributes(tty, &last, defaults, palette, s->hyperlinks);
1585 		if (last.flags & GRID_FLAG_CLEARED) {
1586 			log_debug("%s: %zu cleared (end)", __func__, len);
1587 			tty_clear_line(tty, defaults, aty, atx + ux, width,
1588 			    last.bg);
1589 		} else {
1590 			if (!wrapped || atx != 0 || ux != 0)
1591 				tty_cursor(tty, atx + ux, aty);
1592 			tty_putn(tty, buf, len, width);
1593 		}
1594 		ux += width;
1595 	}
1596 
1597 	if (!cleared && ux < nx) {
1598 		log_debug("%s: %u to end of line (%zu cleared)", __func__,
1599 		    nx - ux, len);
1600 		tty_default_attributes(tty, defaults, palette, 8,
1601 		    s->hyperlinks);
1602 		tty_clear_line(tty, defaults, aty, atx + ux, nx - ux, 8);
1603 	}
1604 
1605 	tty->flags = (tty->flags & ~TTY_NOCURSOR) | flags;
1606 	tty_update_mode(tty, tty->mode, s);
1607 }
1608 
1609 #ifdef ENABLE_SIXEL
1610 /* Update context for client. */
1611 static int
1612 tty_set_client_cb(struct tty_ctx *ttyctx, struct client *c)
1613 {
1614 	struct window_pane	*wp = ttyctx->arg;
1615 
1616 	if (c->session->curw->window != wp->window)
1617 		return (0);
1618 	if (wp->layout_cell == NULL)
1619 		return (0);
1620 
1621 	/* Set the properties relevant to the current client. */
1622 	ttyctx->bigger = tty_window_offset(&c->tty, &ttyctx->wox, &ttyctx->woy,
1623 	    &ttyctx->wsx, &ttyctx->wsy);
1624 
1625 	ttyctx->yoff = ttyctx->ryoff = wp->yoff;
1626 	if (status_at_line(c) == 0)
1627 		ttyctx->yoff += status_line_size(c);
1628 
1629 	return (1);
1630 }
1631 
1632 void
1633 tty_draw_images(struct client *c, struct window_pane *wp, struct screen *s)
1634 {
1635 	struct image	*im;
1636 	struct tty_ctx	 ttyctx;
1637 
1638 	TAILQ_FOREACH(im, &s->images, entry) {
1639 		memset(&ttyctx, 0, sizeof ttyctx);
1640 
1641 		/* Set the client independent properties. */
1642 		ttyctx.ocx = im->px;
1643 		ttyctx.ocy = im->py;
1644 
1645 		ttyctx.orlower = s->rlower;
1646 		ttyctx.orupper = s->rupper;
1647 
1648 		ttyctx.xoff = ttyctx.rxoff = wp->xoff;
1649 		ttyctx.sx = wp->sx;
1650 		ttyctx.sy = wp->sy;
1651 
1652 		ttyctx.ptr = im;
1653 		ttyctx.arg = wp;
1654 		ttyctx.set_client_cb = tty_set_client_cb;
1655 		ttyctx.allow_invisible_panes = 1;
1656 		tty_write_one(tty_cmd_sixelimage, c, &ttyctx);
1657 	}
1658 }
1659 #endif
1660 
1661 void
1662 tty_sync_start(struct tty *tty)
1663 {
1664 	if (tty->flags & TTY_BLOCK)
1665 		return;
1666 	if (tty->flags & TTY_SYNCING)
1667 		return;
1668 	tty->flags |= TTY_SYNCING;
1669 
1670 	if (tty_term_has(tty->term, TTYC_SYNC)) {
1671 		log_debug("%s sync start", tty->client->name);
1672 		tty_putcode_i(tty, TTYC_SYNC, 1);
1673 	}
1674 }
1675 
1676 void
1677 tty_sync_end(struct tty *tty)
1678 {
1679 	if (tty->flags & TTY_BLOCK)
1680 		return;
1681 	if (~tty->flags & TTY_SYNCING)
1682 		return;
1683 	tty->flags &= ~TTY_SYNCING;
1684 
1685 	if (tty_term_has(tty->term, TTYC_SYNC)) {
1686  		log_debug("%s sync end", tty->client->name);
1687 		tty_putcode_i(tty, TTYC_SYNC, 2);
1688 	}
1689 }
1690 
1691 static int
1692 tty_client_ready(const struct tty_ctx *ctx, struct client *c)
1693 {
1694 	if (c->session == NULL || c->tty.term == NULL)
1695 		return (0);
1696 	if (c->flags & CLIENT_SUSPENDED)
1697 		return (0);
1698 
1699 	/*
1700 	 * If invisible panes are allowed (used for passthrough), don't care if
1701 	 * redrawing or frozen.
1702 	 */
1703 	if (ctx->allow_invisible_panes)
1704 		return (1);
1705 
1706 	if (c->flags & CLIENT_REDRAWWINDOW)
1707 		return (0);
1708 	if (c->tty.flags & TTY_FREEZE)
1709 		return (0);
1710 	return (1);
1711 }
1712 
1713 void
1714 tty_write(void (*cmdfn)(struct tty *, const struct tty_ctx *),
1715     struct tty_ctx *ctx)
1716 {
1717 	struct client	*c;
1718 	int		 state;
1719 
1720 	if (ctx->set_client_cb == NULL)
1721 		return;
1722 	TAILQ_FOREACH(c, &clients, entry) {
1723 		if (tty_client_ready(ctx, c)) {
1724 			state = ctx->set_client_cb(ctx, c);
1725 			if (state == -1)
1726 				break;
1727 			if (state == 0)
1728 				continue;
1729 			cmdfn(&c->tty, ctx);
1730 		}
1731 	}
1732 }
1733 
1734 #ifdef ENABLE_SIXEL
1735 /* Only write to the incoming tty instead of every client. */
1736 static void
1737 tty_write_one(void (*cmdfn)(struct tty *, const struct tty_ctx *),
1738     struct client *c, struct tty_ctx *ctx)
1739 {
1740 	if (ctx->set_client_cb == NULL)
1741 		return;
1742 	if ((ctx->set_client_cb(ctx, c)) == 1)
1743 		cmdfn(&c->tty, ctx);
1744 }
1745 #endif
1746 
1747 void
1748 tty_cmd_insertcharacter(struct tty *tty, const struct tty_ctx *ctx)
1749 {
1750 	struct client	*c = tty->client;
1751 
1752 	if (ctx->bigger ||
1753 	    !tty_full_width(tty, ctx) ||
1754 	    tty_fake_bce(tty, &ctx->defaults, ctx->bg) ||
1755 	    (!tty_term_has(tty->term, TTYC_ICH) &&
1756 	    !tty_term_has(tty->term, TTYC_ICH1)) ||
1757 	    c->overlay_check != NULL) {
1758 		tty_draw_pane(tty, ctx, ctx->ocy);
1759 		return;
1760 	}
1761 
1762 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1763 	    ctx->s->hyperlinks);
1764 
1765 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
1766 
1767 	tty_emulate_repeat(tty, TTYC_ICH, TTYC_ICH1, ctx->num);
1768 }
1769 
1770 void
1771 tty_cmd_deletecharacter(struct tty *tty, const struct tty_ctx *ctx)
1772 {
1773 	struct client	*c = tty->client;
1774 
1775 	if (ctx->bigger ||
1776 	    !tty_full_width(tty, ctx) ||
1777 	    tty_fake_bce(tty, &ctx->defaults, ctx->bg) ||
1778 	    (!tty_term_has(tty->term, TTYC_DCH) &&
1779 	    !tty_term_has(tty->term, TTYC_DCH1)) ||
1780 	    c->overlay_check != NULL) {
1781 		tty_draw_pane(tty, ctx, ctx->ocy);
1782 		return;
1783 	}
1784 
1785 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1786 	    ctx->s->hyperlinks);
1787 
1788 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
1789 
1790 	tty_emulate_repeat(tty, TTYC_DCH, TTYC_DCH1, ctx->num);
1791 }
1792 
1793 void
1794 tty_cmd_clearcharacter(struct tty *tty, const struct tty_ctx *ctx)
1795 {
1796 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1797 	    ctx->s->hyperlinks);
1798 
1799 	tty_clear_pane_line(tty, ctx, ctx->ocy, ctx->ocx, ctx->num, ctx->bg);
1800 }
1801 
1802 void
1803 tty_cmd_insertline(struct tty *tty, const struct tty_ctx *ctx)
1804 {
1805 	struct client	*c = tty->client;
1806 
1807 	if (ctx->bigger ||
1808 	    !tty_full_width(tty, ctx) ||
1809 	    tty_fake_bce(tty, &ctx->defaults, ctx->bg) ||
1810 	    !tty_term_has(tty->term, TTYC_CSR) ||
1811 	    !tty_term_has(tty->term, TTYC_IL1) ||
1812 	    ctx->sx == 1 ||
1813 	    ctx->sy == 1 ||
1814 	    c->overlay_check != NULL) {
1815 		tty_redraw_region(tty, ctx);
1816 		return;
1817 	}
1818 
1819 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1820 	    ctx->s->hyperlinks);
1821 
1822 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1823 	tty_margin_off(tty);
1824 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
1825 
1826 	tty_emulate_repeat(tty, TTYC_IL, TTYC_IL1, ctx->num);
1827 	tty->cx = tty->cy = UINT_MAX;
1828 }
1829 
1830 void
1831 tty_cmd_deleteline(struct tty *tty, const struct tty_ctx *ctx)
1832 {
1833 	struct client	*c = tty->client;
1834 
1835 	if (ctx->bigger ||
1836 	    !tty_full_width(tty, ctx) ||
1837 	    tty_fake_bce(tty, &ctx->defaults, ctx->bg) ||
1838 	    !tty_term_has(tty->term, TTYC_CSR) ||
1839 	    !tty_term_has(tty->term, TTYC_DL1) ||
1840 	    ctx->sx == 1 ||
1841 	    ctx->sy == 1 ||
1842 	    c->overlay_check != NULL) {
1843 		tty_redraw_region(tty, ctx);
1844 		return;
1845 	}
1846 
1847 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1848 	    ctx->s->hyperlinks);
1849 
1850 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1851 	tty_margin_off(tty);
1852 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
1853 
1854 	tty_emulate_repeat(tty, TTYC_DL, TTYC_DL1, ctx->num);
1855 	tty->cx = tty->cy = UINT_MAX;
1856 }
1857 
1858 void
1859 tty_cmd_clearline(struct tty *tty, const struct tty_ctx *ctx)
1860 {
1861 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1862 	    ctx->s->hyperlinks);
1863 
1864 	tty_clear_pane_line(tty, ctx, ctx->ocy, 0, ctx->sx, ctx->bg);
1865 }
1866 
1867 void
1868 tty_cmd_clearendofline(struct tty *tty, const struct tty_ctx *ctx)
1869 {
1870 	u_int	nx = ctx->sx - ctx->ocx;
1871 
1872 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1873 	    ctx->s->hyperlinks);
1874 
1875 	tty_clear_pane_line(tty, ctx, ctx->ocy, ctx->ocx, nx, ctx->bg);
1876 }
1877 
1878 void
1879 tty_cmd_clearstartofline(struct tty *tty, const struct tty_ctx *ctx)
1880 {
1881 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1882 	    ctx->s->hyperlinks);
1883 
1884 	tty_clear_pane_line(tty, ctx, ctx->ocy, 0, ctx->ocx + 1, ctx->bg);
1885 }
1886 
1887 void
1888 tty_cmd_reverseindex(struct tty *tty, const struct tty_ctx *ctx)
1889 {
1890 	struct client	*c = tty->client;
1891 
1892 	if (ctx->ocy != ctx->orupper)
1893 		return;
1894 
1895 	if (ctx->bigger ||
1896 	    (!tty_full_width(tty, ctx) && !tty_use_margin(tty)) ||
1897 	    tty_fake_bce(tty, &ctx->defaults, 8) ||
1898 	    !tty_term_has(tty->term, TTYC_CSR) ||
1899 	    (!tty_term_has(tty->term, TTYC_RI) &&
1900 	    !tty_term_has(tty->term, TTYC_RIN)) ||
1901 	    ctx->sx == 1 ||
1902 	    ctx->sy == 1 ||
1903 	    c->overlay_check != NULL) {
1904 		tty_redraw_region(tty, ctx);
1905 		return;
1906 	}
1907 
1908 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1909 	    ctx->s->hyperlinks);
1910 
1911 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1912 	tty_margin_pane(tty, ctx);
1913 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->orupper);
1914 
1915 	if (tty_term_has(tty->term, TTYC_RI))
1916 		tty_putcode(tty, TTYC_RI);
1917 	else
1918 		tty_putcode_i(tty, TTYC_RIN, 1);
1919 }
1920 
1921 void
1922 tty_cmd_linefeed(struct tty *tty, const struct tty_ctx *ctx)
1923 {
1924 	struct client	*c = tty->client;
1925 
1926 	if (ctx->ocy != ctx->orlower)
1927 		return;
1928 
1929 	if (ctx->bigger ||
1930 	    (!tty_full_width(tty, ctx) && !tty_use_margin(tty)) ||
1931 	    tty_fake_bce(tty, &ctx->defaults, 8) ||
1932 	    !tty_term_has(tty->term, TTYC_CSR) ||
1933 	    ctx->sx == 1 ||
1934 	    ctx->sy == 1 ||
1935 	    c->overlay_check != NULL) {
1936 		tty_redraw_region(tty, ctx);
1937 		return;
1938 	}
1939 
1940 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1941 	    ctx->s->hyperlinks);
1942 
1943 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1944 	tty_margin_pane(tty, ctx);
1945 
1946 	/*
1947 	 * If we want to wrap a pane while using margins, the cursor needs to
1948 	 * be exactly on the right of the region. If the cursor is entirely off
1949 	 * the edge - move it back to the right. Some terminals are funny about
1950 	 * this and insert extra spaces, so only use the right if margins are
1951 	 * enabled.
1952 	 */
1953 	if (ctx->xoff + ctx->ocx > tty->rright) {
1954 		if (!tty_use_margin(tty))
1955 			tty_cursor(tty, 0, ctx->yoff + ctx->ocy);
1956 		else
1957 			tty_cursor(tty, tty->rright, ctx->yoff + ctx->ocy);
1958 	} else
1959 		tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
1960 
1961 	tty_putc(tty, '\n');
1962 }
1963 
1964 void
1965 tty_cmd_scrollup(struct tty *tty, const struct tty_ctx *ctx)
1966 {
1967 	struct client	*c = tty->client;
1968 	u_int		 i;
1969 
1970 	if (ctx->bigger ||
1971 	    (!tty_full_width(tty, ctx) && !tty_use_margin(tty)) ||
1972 	    tty_fake_bce(tty, &ctx->defaults, 8) ||
1973 	    !tty_term_has(tty->term, TTYC_CSR) ||
1974 	    ctx->sx == 1 ||
1975 	    ctx->sy == 1 ||
1976 	    c->overlay_check != NULL) {
1977 		tty_redraw_region(tty, ctx);
1978 		return;
1979 	}
1980 
1981 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
1982 	    ctx->s->hyperlinks);
1983 
1984 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1985 	tty_margin_pane(tty, ctx);
1986 
1987 	if (ctx->num == 1 || !tty_term_has(tty->term, TTYC_INDN)) {
1988 		if (!tty_use_margin(tty))
1989 			tty_cursor(tty, 0, tty->rlower);
1990 		else
1991 			tty_cursor(tty, tty->rright, tty->rlower);
1992 		for (i = 0; i < ctx->num; i++)
1993 			tty_putc(tty, '\n');
1994 	} else {
1995 		if (tty->cy == UINT_MAX)
1996 			tty_cursor(tty, 0, 0);
1997 		else
1998 			tty_cursor(tty, 0, tty->cy);
1999 		tty_putcode_i(tty, TTYC_INDN, ctx->num);
2000 	}
2001 }
2002 
2003 void
2004 tty_cmd_scrolldown(struct tty *tty, const struct tty_ctx *ctx)
2005 {
2006 	u_int		 i;
2007 	struct client	*c = tty->client;
2008 
2009 	if (ctx->bigger ||
2010 	    (!tty_full_width(tty, ctx) && !tty_use_margin(tty)) ||
2011 	    tty_fake_bce(tty, &ctx->defaults, 8) ||
2012 	    !tty_term_has(tty->term, TTYC_CSR) ||
2013 	    (!tty_term_has(tty->term, TTYC_RI) &&
2014 	    !tty_term_has(tty->term, TTYC_RIN)) ||
2015 	    ctx->sx == 1 ||
2016 	    ctx->sy == 1 ||
2017 	    c->overlay_check != NULL) {
2018 		tty_redraw_region(tty, ctx);
2019 		return;
2020 	}
2021 
2022 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
2023 	    ctx->s->hyperlinks);
2024 
2025 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
2026 	tty_margin_pane(tty, ctx);
2027 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->orupper);
2028 
2029 	if (tty_term_has(tty->term, TTYC_RIN))
2030 		tty_putcode_i(tty, TTYC_RIN, ctx->num);
2031 	else {
2032 		for (i = 0; i < ctx->num; i++)
2033 			tty_putcode(tty, TTYC_RI);
2034 	}
2035 }
2036 
2037 void
2038 tty_cmd_clearendofscreen(struct tty *tty, const struct tty_ctx *ctx)
2039 {
2040 	u_int	px, py, nx, ny;
2041 
2042 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
2043 	    ctx->s->hyperlinks);
2044 
2045 	tty_region_pane(tty, ctx, 0, ctx->sy - 1);
2046 	tty_margin_off(tty);
2047 
2048 	px = 0;
2049 	nx = ctx->sx;
2050 	py = ctx->ocy + 1;
2051 	ny = ctx->sy - ctx->ocy - 1;
2052 
2053 	tty_clear_pane_area(tty, ctx, py, ny, px, nx, ctx->bg);
2054 
2055 	px = ctx->ocx;
2056 	nx = ctx->sx - ctx->ocx;
2057 	py = ctx->ocy;
2058 
2059 	tty_clear_pane_line(tty, ctx, py, px, nx, ctx->bg);
2060 }
2061 
2062 void
2063 tty_cmd_clearstartofscreen(struct tty *tty, const struct tty_ctx *ctx)
2064 {
2065 	u_int	px, py, nx, ny;
2066 
2067 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
2068 	    ctx->s->hyperlinks);
2069 
2070 	tty_region_pane(tty, ctx, 0, ctx->sy - 1);
2071 	tty_margin_off(tty);
2072 
2073 	px = 0;
2074 	nx = ctx->sx;
2075 	py = 0;
2076 	ny = ctx->ocy;
2077 
2078 	tty_clear_pane_area(tty, ctx, py, ny, px, nx, ctx->bg);
2079 
2080 	px = 0;
2081 	nx = ctx->ocx + 1;
2082 	py = ctx->ocy;
2083 
2084 	tty_clear_pane_line(tty, ctx, py, px, nx, ctx->bg);
2085 }
2086 
2087 void
2088 tty_cmd_clearscreen(struct tty *tty, const struct tty_ctx *ctx)
2089 {
2090 	u_int	px, py, nx, ny;
2091 
2092 	tty_default_attributes(tty, &ctx->defaults, ctx->palette, ctx->bg,
2093 	    ctx->s->hyperlinks);
2094 
2095 	tty_region_pane(tty, ctx, 0, ctx->sy - 1);
2096 	tty_margin_off(tty);
2097 
2098 	px = 0;
2099 	nx = ctx->sx;
2100 	py = 0;
2101 	ny = ctx->sy;
2102 
2103 	tty_clear_pane_area(tty, ctx, py, ny, px, nx, ctx->bg);
2104 }
2105 
2106 void
2107 tty_cmd_alignmenttest(struct tty *tty, const struct tty_ctx *ctx)
2108 {
2109 	u_int	i, j;
2110 
2111 	if (ctx->bigger) {
2112 		ctx->redraw_cb(ctx);
2113 		return;
2114 	}
2115 
2116 	tty_attributes(tty, &grid_default_cell, &ctx->defaults, ctx->palette,
2117 	    ctx->s->hyperlinks);
2118 
2119 	tty_region_pane(tty, ctx, 0, ctx->sy - 1);
2120 	tty_margin_off(tty);
2121 
2122 	for (j = 0; j < ctx->sy; j++) {
2123 		tty_cursor_pane(tty, ctx, 0, j);
2124 		for (i = 0; i < ctx->sx; i++)
2125 			tty_putc(tty, 'E');
2126 	}
2127 }
2128 
2129 void
2130 tty_cmd_cell(struct tty *tty, const struct tty_ctx *ctx)
2131 {
2132 	const struct grid_cell	*gcp = ctx->cell;
2133 	struct screen		*s = ctx->s;
2134 	struct overlay_ranges	 r;
2135 	u_int			 px, py, i, vis = 0;
2136 
2137 	px = ctx->xoff + ctx->ocx - ctx->wox;
2138 	py = ctx->yoff + ctx->ocy - ctx->woy;
2139 	if (!tty_is_visible(tty, ctx, ctx->ocx, ctx->ocy, 1, 1) ||
2140 	    (gcp->data.width == 1 && !tty_check_overlay(tty, px, py)))
2141 		return;
2142 
2143 	/* Handle partially obstructed wide characters. */
2144 	if (gcp->data.width > 1) {
2145 		tty_check_overlay_range(tty, px, py, gcp->data.width, &r);
2146 		for (i = 0; i < OVERLAY_MAX_RANGES; i++)
2147 			vis += r.nx[i];
2148 		if (vis < gcp->data.width) {
2149 			tty_draw_line(tty, s, s->cx, s->cy, gcp->data.width,
2150 			    px, py, &ctx->defaults, ctx->palette);
2151 			return;
2152 		}
2153 	}
2154 
2155 	if (ctx->xoff + ctx->ocx - ctx->wox > tty->sx - 1 &&
2156 	    ctx->ocy == ctx->orlower &&
2157 	    tty_full_width(tty, ctx))
2158 		tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
2159 
2160 	tty_margin_off(tty);
2161 	tty_cursor_pane_unless_wrap(tty, ctx, ctx->ocx, ctx->ocy);
2162 
2163 	tty_cell(tty, ctx->cell, &ctx->defaults, ctx->palette,
2164 	    ctx->s->hyperlinks);
2165 
2166 	if (ctx->num == 1)
2167 		tty_invalidate(tty);
2168 }
2169 
2170 void
2171 tty_cmd_cells(struct tty *tty, const struct tty_ctx *ctx)
2172 {
2173 	struct overlay_ranges	 r;
2174 	u_int			 i, px, py, cx;
2175 	char			*cp = ctx->ptr;
2176 
2177 	if (!tty_is_visible(tty, ctx, ctx->ocx, ctx->ocy, ctx->num, 1))
2178 		return;
2179 
2180 	if (ctx->bigger &&
2181 	    (ctx->xoff + ctx->ocx < ctx->wox ||
2182 	    ctx->xoff + ctx->ocx + ctx->num > ctx->wox + ctx->wsx)) {
2183 		if (!ctx->wrapped ||
2184 		    !tty_full_width(tty, ctx) ||
2185 		    (tty->term->flags & TERM_NOAM) ||
2186 		    ctx->xoff + ctx->ocx != 0 ||
2187 		    ctx->yoff + ctx->ocy != tty->cy + 1 ||
2188 		    tty->cx < tty->sx ||
2189 		    tty->cy == tty->rlower)
2190 			tty_draw_pane(tty, ctx, ctx->ocy);
2191 		else
2192 			ctx->redraw_cb(ctx);
2193 		return;
2194 	}
2195 
2196 	tty_margin_off(tty);
2197 	tty_cursor_pane_unless_wrap(tty, ctx, ctx->ocx, ctx->ocy);
2198 	tty_attributes(tty, ctx->cell, &ctx->defaults, ctx->palette, ctx->s->hyperlinks);
2199 
2200 	/* Get tty position from pane position for overlay check. */
2201 	px = ctx->xoff + ctx->ocx - ctx->wox;
2202 	py = ctx->yoff + ctx->ocy - ctx->woy;
2203 
2204 	tty_check_overlay_range(tty, px, py, ctx->num, &r);
2205 	for (i = 0; i < OVERLAY_MAX_RANGES; i++) {
2206 		if (r.nx[i] == 0)
2207 			continue;
2208 		/* Convert back to pane position for printing. */
2209 		cx = r.px[i] - ctx->xoff + ctx->wox;
2210 		tty_cursor_pane_unless_wrap(tty, ctx, cx, ctx->ocy);
2211 		tty_putn(tty, cp + r.px[i] - px, r.nx[i], r.nx[i]);
2212 	}
2213 }
2214 
2215 void
2216 tty_cmd_setselection(struct tty *tty, const struct tty_ctx *ctx)
2217 {
2218 	tty_set_selection(tty, ctx->ptr2, ctx->ptr, ctx->num);
2219 }
2220 
2221 void
2222 tty_set_selection(struct tty *tty, const char *flags, const char *buf,
2223     size_t len)
2224 {
2225 	char	*encoded;
2226 	size_t	 size;
2227 
2228 	if (~tty->flags & TTY_STARTED)
2229 		return;
2230 	if (!tty_term_has(tty->term, TTYC_MS))
2231 		return;
2232 
2233 	size = 4 * ((len + 2) / 3) + 1; /* storage for base64 */
2234 	encoded = xmalloc(size);
2235 
2236 	b64_ntop(buf, len, encoded, size);
2237 	tty->flags |= TTY_NOBLOCK;
2238 	tty_putcode_ss(tty, TTYC_MS, flags, encoded);
2239 
2240 	free(encoded);
2241 }
2242 
2243 void
2244 tty_cmd_rawstring(struct tty *tty, const struct tty_ctx *ctx)
2245 {
2246 	tty->flags |= TTY_NOBLOCK;
2247 	tty_add(tty, ctx->ptr, ctx->num);
2248 	tty_invalidate(tty);
2249 }
2250 
2251 #ifdef ENABLE_SIXEL
2252 void
2253 tty_cmd_sixelimage(struct tty *tty, const struct tty_ctx *ctx)
2254 {
2255 	struct image		*im = ctx->ptr;
2256 	struct sixel_image	*si = im->data;
2257 	struct sixel_image	*new;
2258 	char			*data;
2259 	size_t			 size;
2260 	u_int			 cx = ctx->ocx, cy = ctx->ocy, sx, sy;
2261 	u_int			 i, j, x, y, rx, ry;
2262 	int			 fallback = 0;
2263 
2264 	if ((~tty->term->flags & TERM_SIXEL) &&
2265             !tty_term_has(tty->term, TTYC_SXL))
2266 		fallback = 1;
2267 	if (tty->xpixel == 0 || tty->ypixel == 0)
2268 		fallback = 1;
2269 
2270 	sixel_size_in_cells(si, &sx, &sy);
2271 	log_debug("%s: image is %ux%u", __func__, sx, sy);
2272 	if (!tty_clamp_area(tty, ctx, cx, cy, sx, sy, &i, &j, &x, &y, &rx, &ry))
2273 		return;
2274 	log_debug("%s: clamping to %u,%u-%u,%u", __func__, i, j, rx, ry);
2275 
2276 	if (fallback == 1) {
2277 		data = xstrdup(im->fallback);
2278 		size = strlen(data);
2279 	} else {
2280 		new = sixel_scale(si, tty->xpixel, tty->ypixel, i, j, rx, ry, 0);
2281 		if (new == NULL)
2282 			return;
2283 
2284 		data = sixel_print(new, si, &size);
2285 	}
2286 	if (data != NULL) {
2287 		log_debug("%s: %zu bytes: %s", __func__, size, data);
2288 		tty_region_off(tty);
2289 		tty_margin_off(tty);
2290 		tty_cursor(tty, x, y);
2291 
2292 		tty->flags |= TTY_NOBLOCK;
2293 		tty_add(tty, data, size);
2294 		tty_invalidate(tty);
2295 		free(data);
2296 	}
2297 
2298 	if (fallback == 0)
2299 		sixel_free(new);
2300 }
2301 #endif
2302 
2303 void
2304 tty_cmd_syncstart(struct tty *tty, const struct tty_ctx *ctx)
2305 {
2306 	if (ctx->num == 0x11) {
2307 		/*
2308 		 * This is an overlay and a command that moves the cursor so
2309 		 * start synchronized updates.
2310 		 */
2311 		tty_sync_start(tty);
2312 	} else if (~ctx->num & 0x10) {
2313 		/*
2314 		 * This is a pane. If there is an overlay, always start;
2315 		 * otherwise, only if requested.
2316 		 */
2317 		if (ctx->num || tty->client->overlay_draw != NULL)
2318 			tty_sync_start(tty);
2319 	}
2320 }
2321 
2322 void
2323 tty_cell(struct tty *tty, const struct grid_cell *gc,
2324     const struct grid_cell *defaults, struct colour_palette *palette,
2325     struct hyperlinks *hl)
2326 {
2327 	const struct grid_cell	*gcp;
2328 
2329 	/* Skip last character if terminal is stupid. */
2330 	if ((tty->term->flags & TERM_NOAM) &&
2331 	    tty->cy == tty->sy - 1 &&
2332 	    tty->cx == tty->sx - 1)
2333 		return;
2334 
2335 	/* If this is a padding character, do nothing. */
2336 	if (gc->flags & GRID_FLAG_PADDING)
2337 		return;
2338 
2339 	/* Check the output codeset and apply attributes. */
2340 	gcp = tty_check_codeset(tty, gc);
2341 	tty_attributes(tty, gcp, defaults, palette, hl);
2342 
2343 	/* If it is a single character, write with putc to handle ACS. */
2344 	if (gcp->data.size == 1) {
2345 		tty_attributes(tty, gcp, defaults, palette, hl);
2346 		if (*gcp->data.data < 0x20 || *gcp->data.data == 0x7f)
2347 			return;
2348 		tty_putc(tty, *gcp->data.data);
2349 		return;
2350 	}
2351 
2352 	/* Write the data. */
2353 	tty_putn(tty, gcp->data.data, gcp->data.size, gcp->data.width);
2354 }
2355 
2356 void
2357 tty_reset(struct tty *tty)
2358 {
2359 	struct grid_cell	*gc = &tty->cell;
2360 
2361 	if (!grid_cells_equal(gc, &grid_default_cell)) {
2362 		if (gc->link != 0)
2363 			tty_putcode_ss(tty, TTYC_HLS, "", "");
2364 		if ((gc->attr & GRID_ATTR_CHARSET) && tty_acs_needed(tty))
2365 			tty_putcode(tty, TTYC_RMACS);
2366 		tty_putcode(tty, TTYC_SGR0);
2367 		memcpy(gc, &grid_default_cell, sizeof *gc);
2368 	}
2369 	memcpy(&tty->last_cell, &grid_default_cell, sizeof tty->last_cell);
2370 }
2371 
2372 static void
2373 tty_invalidate(struct tty *tty)
2374 {
2375 	memcpy(&tty->cell, &grid_default_cell, sizeof tty->cell);
2376 	memcpy(&tty->last_cell, &grid_default_cell, sizeof tty->last_cell);
2377 
2378 	tty->cx = tty->cy = UINT_MAX;
2379 	tty->rupper = tty->rleft = UINT_MAX;
2380 	tty->rlower = tty->rright = UINT_MAX;
2381 
2382 	if (tty->flags & TTY_STARTED) {
2383 		if (tty_use_margin(tty))
2384 			tty_putcode(tty, TTYC_ENMG);
2385 		tty_putcode(tty, TTYC_SGR0);
2386 
2387 		tty->mode = ALL_MODES;
2388 		tty_update_mode(tty, MODE_CURSOR, NULL);
2389 
2390 		tty_cursor(tty, 0, 0);
2391 		tty_region_off(tty);
2392 		tty_margin_off(tty);
2393 	} else
2394 		tty->mode = MODE_CURSOR;
2395 }
2396 
2397 /* Turn off margin. */
2398 void
2399 tty_region_off(struct tty *tty)
2400 {
2401 	tty_region(tty, 0, tty->sy - 1);
2402 }
2403 
2404 /* Set region inside pane. */
2405 static void
2406 tty_region_pane(struct tty *tty, const struct tty_ctx *ctx, u_int rupper,
2407     u_int rlower)
2408 {
2409 	tty_region(tty, ctx->yoff + rupper - ctx->woy,
2410 	    ctx->yoff + rlower - ctx->woy);
2411 }
2412 
2413 /* Set region at absolute position. */
2414 static void
2415 tty_region(struct tty *tty, u_int rupper, u_int rlower)
2416 {
2417 	if (tty->rlower == rlower && tty->rupper == rupper)
2418 		return;
2419 	if (!tty_term_has(tty->term, TTYC_CSR))
2420 		return;
2421 
2422 	tty->rupper = rupper;
2423 	tty->rlower = rlower;
2424 
2425 	/*
2426 	 * Some terminals (such as PuTTY) do not correctly reset the cursor to
2427 	 * 0,0 if it is beyond the last column (they do not reset their wrap
2428 	 * flag so further output causes a line feed). As a workaround, do an
2429 	 * explicit move to 0 first.
2430 	 */
2431 	if (tty->cx >= tty->sx) {
2432 		if (tty->cy == UINT_MAX)
2433 			tty_cursor(tty, 0, 0);
2434 		else
2435 			tty_cursor(tty, 0, tty->cy);
2436 	}
2437 
2438 	tty_putcode_ii(tty, TTYC_CSR, tty->rupper, tty->rlower);
2439 	tty->cx = tty->cy = UINT_MAX;
2440 }
2441 
2442 /* Turn off margin. */
2443 void
2444 tty_margin_off(struct tty *tty)
2445 {
2446 	tty_margin(tty, 0, tty->sx - 1);
2447 }
2448 
2449 /* Set margin inside pane. */
2450 static void
2451 tty_margin_pane(struct tty *tty, const struct tty_ctx *ctx)
2452 {
2453 	tty_margin(tty, ctx->xoff - ctx->wox,
2454 	    ctx->xoff + ctx->sx - 1 - ctx->wox);
2455 }
2456 
2457 /* Set margin at absolute position. */
2458 static void
2459 tty_margin(struct tty *tty, u_int rleft, u_int rright)
2460 {
2461 	if (!tty_use_margin(tty))
2462 		return;
2463 	if (tty->rleft == rleft && tty->rright == rright)
2464 		return;
2465 
2466 	tty_putcode_ii(tty, TTYC_CSR, tty->rupper, tty->rlower);
2467 
2468 	tty->rleft = rleft;
2469 	tty->rright = rright;
2470 
2471 	if (rleft == 0 && rright == tty->sx - 1)
2472 		tty_putcode(tty, TTYC_CLMG);
2473 	else
2474 		tty_putcode_ii(tty, TTYC_CMG, rleft, rright);
2475 	tty->cx = tty->cy = UINT_MAX;
2476 }
2477 
2478 /*
2479  * Move the cursor, unless it would wrap itself when the next character is
2480  * printed.
2481  */
2482 static void
2483 tty_cursor_pane_unless_wrap(struct tty *tty, const struct tty_ctx *ctx,
2484     u_int cx, u_int cy)
2485 {
2486 	if (!ctx->wrapped ||
2487 	    !tty_full_width(tty, ctx) ||
2488 	    (tty->term->flags & TERM_NOAM) ||
2489 	    ctx->xoff + cx != 0 ||
2490 	    ctx->yoff + cy != tty->cy + 1 ||
2491 	    tty->cx < tty->sx ||
2492 	    tty->cy == tty->rlower)
2493 		tty_cursor_pane(tty, ctx, cx, cy);
2494 	else
2495 		log_debug("%s: will wrap at %u,%u", __func__, tty->cx, tty->cy);
2496 }
2497 
2498 /* Move cursor inside pane. */
2499 static void
2500 tty_cursor_pane(struct tty *tty, const struct tty_ctx *ctx, u_int cx, u_int cy)
2501 {
2502 	tty_cursor(tty, ctx->xoff + cx - ctx->wox, ctx->yoff + cy - ctx->woy);
2503 }
2504 
2505 /* Move cursor to absolute position. */
2506 void
2507 tty_cursor(struct tty *tty, u_int cx, u_int cy)
2508 {
2509 	struct tty_term	*term = tty->term;
2510 	u_int		 thisx, thisy;
2511 	int		 change;
2512 
2513 	if (tty->flags & TTY_BLOCK)
2514 		return;
2515 
2516 	thisx = tty->cx;
2517 	thisy = tty->cy;
2518 
2519 	/*
2520 	 * If in the automargin space, and want to be there, do not move.
2521 	 * Otherwise, force the cursor to be in range (and complain).
2522 	 */
2523 	if (cx == thisx && cy == thisy && cx == tty->sx)
2524 		return;
2525 	if (cx > tty->sx - 1) {
2526 		log_debug("%s: x too big %u > %u", __func__, cx, tty->sx - 1);
2527 		cx = tty->sx - 1;
2528 	}
2529 
2530 	/* No change. */
2531 	if (cx == thisx && cy == thisy)
2532 		return;
2533 
2534 	/* Currently at the very end of the line - use absolute movement. */
2535 	if (thisx > tty->sx - 1)
2536 		goto absolute;
2537 
2538 	/* Move to home position (0, 0). */
2539 	if (cx == 0 && cy == 0 && tty_term_has(term, TTYC_HOME)) {
2540 		tty_putcode(tty, TTYC_HOME);
2541 		goto out;
2542 	}
2543 
2544 	/* Zero on the next line. */
2545 	if (cx == 0 && cy == thisy + 1 && thisy != tty->rlower &&
2546 	    (!tty_use_margin(tty) || tty->rleft == 0)) {
2547 		tty_putc(tty, '\r');
2548 		tty_putc(tty, '\n');
2549 		goto out;
2550 	}
2551 
2552 	/* Moving column or row. */
2553 	if (cy == thisy) {
2554 		/*
2555 		 * Moving column only, row staying the same.
2556 		 */
2557 
2558 		/* To left edge. */
2559 		if (cx == 0 && (!tty_use_margin(tty) || tty->rleft == 0)) {
2560 			tty_putc(tty, '\r');
2561 			goto out;
2562 		}
2563 
2564 		/* One to the left. */
2565 		if (cx == thisx - 1 && tty_term_has(term, TTYC_CUB1)) {
2566 			tty_putcode(tty, TTYC_CUB1);
2567 			goto out;
2568 		}
2569 
2570 		/* One to the right. */
2571 		if (cx == thisx + 1 && tty_term_has(term, TTYC_CUF1)) {
2572 			tty_putcode(tty, TTYC_CUF1);
2573 			goto out;
2574 		}
2575 
2576 		/* Calculate difference. */
2577 		change = thisx - cx;	/* +ve left, -ve right */
2578 
2579 		/*
2580 		 * Use HPA if change is larger than absolute, otherwise move
2581 		 * the cursor with CUB/CUF.
2582 		 */
2583 		if ((u_int) abs(change) > cx && tty_term_has(term, TTYC_HPA)) {
2584 			tty_putcode_i(tty, TTYC_HPA, cx);
2585 			goto out;
2586 		} else if (change > 0 &&
2587 		    tty_term_has(term, TTYC_CUB) &&
2588 		    !tty_use_margin(tty)) {
2589 			if (change == 2 && tty_term_has(term, TTYC_CUB1)) {
2590 				tty_putcode(tty, TTYC_CUB1);
2591 				tty_putcode(tty, TTYC_CUB1);
2592 				goto out;
2593 			}
2594 			tty_putcode_i(tty, TTYC_CUB, change);
2595 			goto out;
2596 		} else if (change < 0 &&
2597 		    tty_term_has(term, TTYC_CUF) &&
2598 		    !tty_use_margin(tty)) {
2599 			tty_putcode_i(tty, TTYC_CUF, -change);
2600 			goto out;
2601 		}
2602 	} else if (cx == thisx) {
2603 		/*
2604 		 * Moving row only, column staying the same.
2605 		 */
2606 
2607 		/* One above. */
2608 		if (thisy != tty->rupper &&
2609 		    cy == thisy - 1 && tty_term_has(term, TTYC_CUU1)) {
2610 			tty_putcode(tty, TTYC_CUU1);
2611 			goto out;
2612 		}
2613 
2614 		/* One below. */
2615 		if (thisy != tty->rlower &&
2616 		    cy == thisy + 1 && tty_term_has(term, TTYC_CUD1)) {
2617 			tty_putcode(tty, TTYC_CUD1);
2618 			goto out;
2619 		}
2620 
2621 		/* Calculate difference. */
2622 		change = thisy - cy;	/* +ve up, -ve down */
2623 
2624 		/*
2625 		 * Try to use VPA if change is larger than absolute or if this
2626 		 * change would cross the scroll region, otherwise use CUU/CUD.
2627 		 */
2628 		if ((u_int) abs(change) > cy ||
2629 		    (change < 0 && cy - change > tty->rlower) ||
2630 		    (change > 0 && cy - change < tty->rupper)) {
2631 			    if (tty_term_has(term, TTYC_VPA)) {
2632 				    tty_putcode_i(tty, TTYC_VPA, cy);
2633 				    goto out;
2634 			    }
2635 		} else if (change > 0 && tty_term_has(term, TTYC_CUU)) {
2636 			tty_putcode_i(tty, TTYC_CUU, change);
2637 			goto out;
2638 		} else if (change < 0 && tty_term_has(term, TTYC_CUD)) {
2639 			tty_putcode_i(tty, TTYC_CUD, -change);
2640 			goto out;
2641 		}
2642 	}
2643 
2644 absolute:
2645 	/* Absolute movement. */
2646 	tty_putcode_ii(tty, TTYC_CUP, cy, cx);
2647 
2648 out:
2649 	tty->cx = cx;
2650 	tty->cy = cy;
2651 }
2652 
2653 static void
2654 tty_hyperlink(struct tty *tty, const struct grid_cell *gc,
2655     struct hyperlinks *hl)
2656 {
2657 	const char	*uri, *id;
2658 
2659 	if (gc->link == tty->cell.link)
2660 		return;
2661 	tty->cell.link = gc->link;
2662 
2663 	if (hl == NULL)
2664 		return;
2665 
2666 	if (gc->link == 0 || !hyperlinks_get(hl, gc->link, &uri, NULL, &id))
2667 		tty_putcode_ss(tty, TTYC_HLS, "", "");
2668 	else
2669 		tty_putcode_ss(tty, TTYC_HLS, id, uri);
2670 }
2671 
2672 void
2673 tty_attributes(struct tty *tty, const struct grid_cell *gc,
2674     const struct grid_cell *defaults, struct colour_palette *palette,
2675     struct hyperlinks *hl)
2676 {
2677 	struct grid_cell	*tc = &tty->cell, gc2;
2678 	int			 changed;
2679 
2680 	/* Copy cell and update default colours. */
2681 	memcpy(&gc2, gc, sizeof gc2);
2682 	if (~gc->flags & GRID_FLAG_NOPALETTE) {
2683 		if (gc2.fg == 8)
2684 			gc2.fg = defaults->fg;
2685 		if (gc2.bg == 8)
2686 			gc2.bg = defaults->bg;
2687 	}
2688 
2689 	/* Ignore cell if it is the same as the last one. */
2690 	if (gc2.attr == tty->last_cell.attr &&
2691 	    gc2.fg == tty->last_cell.fg &&
2692 	    gc2.bg == tty->last_cell.bg &&
2693 	    gc2.us == tty->last_cell.us &&
2694 		gc2.link == tty->last_cell.link)
2695 		return;
2696 
2697 	/*
2698 	 * If no setab, try to use the reverse attribute as a best-effort for a
2699 	 * non-default background. This is a bit of a hack but it doesn't do
2700 	 * any serious harm and makes a couple of applications happier.
2701 	 */
2702 	if (!tty_term_has(tty->term, TTYC_SETAB)) {
2703 		if (gc2.attr & GRID_ATTR_REVERSE) {
2704 			if (gc2.fg != 7 && !COLOUR_DEFAULT(gc2.fg))
2705 				gc2.attr &= ~GRID_ATTR_REVERSE;
2706 		} else {
2707 			if (gc2.bg != 0 && !COLOUR_DEFAULT(gc2.bg))
2708 				gc2.attr |= GRID_ATTR_REVERSE;
2709 		}
2710 	}
2711 
2712 	/* Fix up the colours if necessary. */
2713 	tty_check_fg(tty, palette, &gc2);
2714 	tty_check_bg(tty, palette, &gc2);
2715 	tty_check_us(tty, palette, &gc2);
2716 
2717 	/*
2718 	 * If any bits are being cleared or the underline colour is now default,
2719 	 * reset everything.
2720 	 */
2721 	if ((tc->attr & ~gc2.attr) || (tc->us != gc2.us && gc2.us == 0))
2722 		tty_reset(tty);
2723 
2724 	/*
2725 	 * Set the colours. This may call tty_reset() (so it comes next) and
2726 	 * may add to (NOT remove) the desired attributes.
2727 	 */
2728 	tty_colours(tty, &gc2);
2729 
2730 	/* Filter out attribute bits already set. */
2731 	changed = gc2.attr & ~tc->attr;
2732 	tc->attr = gc2.attr;
2733 
2734 	/* Set the attributes. */
2735 	if (changed & GRID_ATTR_BRIGHT)
2736 		tty_putcode(tty, TTYC_BOLD);
2737 	if (changed & GRID_ATTR_DIM)
2738 		tty_putcode(tty, TTYC_DIM);
2739 	if (changed & GRID_ATTR_ITALICS)
2740 		tty_set_italics(tty);
2741 	if (changed & GRID_ATTR_ALL_UNDERSCORE) {
2742 		if ((changed & GRID_ATTR_UNDERSCORE) ||
2743 		    !tty_term_has(tty->term, TTYC_SMULX))
2744 			tty_putcode(tty, TTYC_SMUL);
2745 		else if (changed & GRID_ATTR_UNDERSCORE_2)
2746 			tty_putcode_i(tty, TTYC_SMULX, 2);
2747 		else if (changed & GRID_ATTR_UNDERSCORE_3)
2748 			tty_putcode_i(tty, TTYC_SMULX, 3);
2749 		else if (changed & GRID_ATTR_UNDERSCORE_4)
2750 			tty_putcode_i(tty, TTYC_SMULX, 4);
2751 		else if (changed & GRID_ATTR_UNDERSCORE_5)
2752 			tty_putcode_i(tty, TTYC_SMULX, 5);
2753 	}
2754 	if (changed & GRID_ATTR_BLINK)
2755 		tty_putcode(tty, TTYC_BLINK);
2756 	if (changed & GRID_ATTR_REVERSE) {
2757 		if (tty_term_has(tty->term, TTYC_REV))
2758 			tty_putcode(tty, TTYC_REV);
2759 		else if (tty_term_has(tty->term, TTYC_SMSO))
2760 			tty_putcode(tty, TTYC_SMSO);
2761 	}
2762 	if (changed & GRID_ATTR_HIDDEN)
2763 		tty_putcode(tty, TTYC_INVIS);
2764 	if (changed & GRID_ATTR_STRIKETHROUGH)
2765 		tty_putcode(tty, TTYC_SMXX);
2766 	if (changed & GRID_ATTR_OVERLINE)
2767 		tty_putcode(tty, TTYC_SMOL);
2768 	if ((changed & GRID_ATTR_CHARSET) && tty_acs_needed(tty))
2769 		tty_putcode(tty, TTYC_SMACS);
2770 
2771 	/* Set hyperlink if any. */
2772 	tty_hyperlink(tty, gc, hl);
2773 
2774 	memcpy(&tty->last_cell, &gc2, sizeof tty->last_cell);
2775 }
2776 
2777 static void
2778 tty_colours(struct tty *tty, const struct grid_cell *gc)
2779 {
2780 	struct grid_cell	*tc = &tty->cell;
2781 
2782 	/* No changes? Nothing is necessary. */
2783 	if (gc->fg == tc->fg && gc->bg == tc->bg && gc->us == tc->us)
2784 		return;
2785 
2786 	/*
2787 	 * Is either the default colour? This is handled specially because the
2788 	 * best solution might be to reset both colours to default, in which
2789 	 * case if only one is default need to fall onward to set the other
2790 	 * colour.
2791 	 */
2792 	if (COLOUR_DEFAULT(gc->fg) || COLOUR_DEFAULT(gc->bg)) {
2793 		/*
2794 		 * If don't have AX, send sgr0. This resets both colours to default.
2795 		 * Otherwise, try to set the default colour only as needed.
2796 		 */
2797 		if (!tty_term_flag(tty->term, TTYC_AX))
2798 			tty_reset(tty);
2799 		else {
2800 			if (COLOUR_DEFAULT(gc->fg) && !COLOUR_DEFAULT(tc->fg)) {
2801 				tty_puts(tty, "\033[39m");
2802 				tc->fg = gc->fg;
2803 			}
2804 			if (COLOUR_DEFAULT(gc->bg) && !COLOUR_DEFAULT(tc->bg)) {
2805 				tty_puts(tty, "\033[49m");
2806 				tc->bg = gc->bg;
2807 			}
2808 		}
2809 	}
2810 
2811 	/* Set the foreground colour. */
2812 	if (!COLOUR_DEFAULT(gc->fg) && gc->fg != tc->fg)
2813 		tty_colours_fg(tty, gc);
2814 
2815 	/*
2816 	 * Set the background colour. This must come after the foreground as
2817 	 * tty_colours_fg() can call tty_reset().
2818 	 */
2819 	if (!COLOUR_DEFAULT(gc->bg) && gc->bg != tc->bg)
2820 		tty_colours_bg(tty, gc);
2821 
2822 	/* Set the underscore colour. */
2823 	if (gc->us != tc->us)
2824 		tty_colours_us(tty, gc);
2825 }
2826 
2827 static void
2828 tty_check_fg(struct tty *tty, struct colour_palette *palette,
2829     struct grid_cell *gc)
2830 {
2831 	u_char	r, g, b;
2832 	u_int	colours;
2833 	int	c;
2834 
2835 	/*
2836 	 * Perform substitution if this pane has a palette. If the bright
2837 	 * attribute is set and Nobr is not present, use the bright entry in
2838 	 * the palette by changing to the aixterm colour
2839 	 */
2840 	if (~gc->flags & GRID_FLAG_NOPALETTE) {
2841 		c = gc->fg;
2842 		if (c < 8 &&
2843 		    gc->attr & GRID_ATTR_BRIGHT &&
2844 		    !tty_term_has(tty->term, TTYC_NOBR))
2845 			c += 90;
2846 		if ((c = colour_palette_get(palette, c)) != -1)
2847 			gc->fg = c;
2848 	}
2849 
2850 	/* Is this a 24-bit colour? */
2851 	if (gc->fg & COLOUR_FLAG_RGB) {
2852 		/* Not a 24-bit terminal? Translate to 256-colour palette. */
2853 		if (tty->term->flags & TERM_RGBCOLOURS)
2854 			return;
2855 		colour_split_rgb(gc->fg, &r, &g, &b);
2856 		gc->fg = colour_find_rgb(r, g, b);
2857 	}
2858 
2859 	/* How many colours does this terminal have? */
2860 	if (tty->term->flags & TERM_256COLOURS)
2861 		colours = 256;
2862 	else
2863 		colours = tty_term_number(tty->term, TTYC_COLORS);
2864 
2865 	/* Is this a 256-colour colour? */
2866 	if (gc->fg & COLOUR_FLAG_256) {
2867 		/* And not a 256 colour mode? */
2868 		if (colours < 256) {
2869 			gc->fg = colour_256to16(gc->fg);
2870 			if (gc->fg & 8) {
2871 				gc->fg &= 7;
2872 				if (colours >= 16)
2873 					gc->fg += 90;
2874 			}
2875 		}
2876 		return;
2877 	}
2878 
2879 	/* Is this an aixterm colour? */
2880 	if (gc->fg >= 90 && gc->fg <= 97 && colours < 16) {
2881 		gc->fg -= 90;
2882 		gc->attr |= GRID_ATTR_BRIGHT;
2883 	}
2884 }
2885 
2886 static void
2887 tty_check_bg(struct tty *tty, struct colour_palette *palette,
2888     struct grid_cell *gc)
2889 {
2890 	u_char	r, g, b;
2891 	u_int	colours;
2892 	int	c;
2893 
2894 	/* Perform substitution if this pane has a palette. */
2895 	if (~gc->flags & GRID_FLAG_NOPALETTE) {
2896 		if ((c = colour_palette_get(palette, gc->bg)) != -1)
2897 			gc->bg = c;
2898 	}
2899 
2900 	/* Is this a 24-bit colour? */
2901 	if (gc->bg & COLOUR_FLAG_RGB) {
2902 		/* Not a 24-bit terminal? Translate to 256-colour palette. */
2903 		if (tty->term->flags & TERM_RGBCOLOURS)
2904 			return;
2905 		colour_split_rgb(gc->bg, &r, &g, &b);
2906 		gc->bg = colour_find_rgb(r, g, b);
2907 	}
2908 
2909 	/* How many colours does this terminal have? */
2910 	if (tty->term->flags & TERM_256COLOURS)
2911 		colours = 256;
2912 	else
2913 		colours = tty_term_number(tty->term, TTYC_COLORS);
2914 
2915 	/* Is this a 256-colour colour? */
2916 	if (gc->bg & COLOUR_FLAG_256) {
2917 		/*
2918 		 * And not a 256 colour mode? Translate to 16-colour
2919 		 * palette. Bold background doesn't exist portably, so just
2920 		 * discard the bold bit if set.
2921 		 */
2922 		if (colours < 256) {
2923 			gc->bg = colour_256to16(gc->bg);
2924 			if (gc->bg & 8) {
2925 				gc->bg &= 7;
2926 				if (colours >= 16)
2927 					gc->bg += 90;
2928 			}
2929 		}
2930 		return;
2931 	}
2932 
2933 	/* Is this an aixterm colour? */
2934 	if (gc->bg >= 90 && gc->bg <= 97 && colours < 16)
2935 		gc->bg -= 90;
2936 }
2937 
2938 static void
2939 tty_check_us(__unused struct tty *tty, struct colour_palette *palette,
2940     struct grid_cell *gc)
2941 {
2942 	int	c;
2943 
2944 	/* Perform substitution if this pane has a palette. */
2945 	if (~gc->flags & GRID_FLAG_NOPALETTE) {
2946 		if ((c = colour_palette_get(palette, gc->us)) != -1)
2947 			gc->us = c;
2948 	}
2949 
2950 	/* Convert underscore colour if only RGB can be supported. */
2951 	if (!tty_term_has(tty->term, TTYC_SETULC1)) {
2952 		    if ((c = colour_force_rgb (gc->us)) == -1)
2953 			    gc->us = 8;
2954 		    else
2955 			    gc->us = c;
2956 	}
2957 }
2958 
2959 static void
2960 tty_colours_fg(struct tty *tty, const struct grid_cell *gc)
2961 {
2962 	struct grid_cell	*tc = &tty->cell;
2963 	char			 s[32];
2964 
2965 	/*
2966 	 * If the current colour is an aixterm bright colour and the new is not,
2967 	 * reset because some terminals do not clear bright correctly.
2968 	 */
2969 	if (tty->cell.fg >= 90 &&
2970 	    tty->cell.bg <= 97 &&
2971 	    (gc->fg < 90 || gc->fg > 97))
2972 		tty_reset(tty);
2973 
2974 	/* Is this a 24-bit or 256-colour colour? */
2975 	if (gc->fg & COLOUR_FLAG_RGB || gc->fg & COLOUR_FLAG_256) {
2976 		if (tty_try_colour(tty, gc->fg, "38") == 0)
2977 			goto save;
2978 		/* Should not get here, already converted in tty_check_fg. */
2979 		return;
2980 	}
2981 
2982 	/* Is this an aixterm bright colour? */
2983 	if (gc->fg >= 90 && gc->fg <= 97) {
2984 		if (tty->term->flags & TERM_256COLOURS) {
2985 			xsnprintf(s, sizeof s, "\033[%dm", gc->fg);
2986 			tty_puts(tty, s);
2987 		} else
2988 			tty_putcode_i(tty, TTYC_SETAF, gc->fg - 90 + 8);
2989 		goto save;
2990 	}
2991 
2992 	/* Otherwise set the foreground colour. */
2993 	tty_putcode_i(tty, TTYC_SETAF, gc->fg);
2994 
2995 save:
2996 	/* Save the new values in the terminal current cell. */
2997 	tc->fg = gc->fg;
2998 }
2999 
3000 static void
3001 tty_colours_bg(struct tty *tty, const struct grid_cell *gc)
3002 {
3003 	struct grid_cell	*tc = &tty->cell;
3004 	char			 s[32];
3005 
3006 	/* Is this a 24-bit or 256-colour colour? */
3007 	if (gc->bg & COLOUR_FLAG_RGB || gc->bg & COLOUR_FLAG_256) {
3008 		if (tty_try_colour(tty, gc->bg, "48") == 0)
3009 			goto save;
3010 		/* Should not get here, already converted in tty_check_bg. */
3011 		return;
3012 	}
3013 
3014 	/* Is this an aixterm bright colour? */
3015 	if (gc->bg >= 90 && gc->bg <= 97) {
3016 		if (tty->term->flags & TERM_256COLOURS) {
3017 			xsnprintf(s, sizeof s, "\033[%dm", gc->bg + 10);
3018 			tty_puts(tty, s);
3019 		} else
3020 			tty_putcode_i(tty, TTYC_SETAB, gc->bg - 90 + 8);
3021 		goto save;
3022 	}
3023 
3024 	/* Otherwise set the background colour. */
3025 	tty_putcode_i(tty, TTYC_SETAB, gc->bg);
3026 
3027 save:
3028 	/* Save the new values in the terminal current cell. */
3029 	tc->bg = gc->bg;
3030 }
3031 
3032 static void
3033 tty_colours_us(struct tty *tty, const struct grid_cell *gc)
3034 {
3035 	struct grid_cell	*tc = &tty->cell;
3036 	u_int			 c;
3037 	u_char			 r, g, b;
3038 
3039 	/* Clear underline colour. */
3040 	if (COLOUR_DEFAULT(gc->us)) {
3041 		tty_putcode(tty, TTYC_OL);
3042 		goto save;
3043 	}
3044 
3045 	/*
3046 	 * If this is not an RGB colour, use Setulc1 if it exists, otherwise
3047 	 * convert.
3048 	 */
3049 	if (~gc->us & COLOUR_FLAG_RGB) {
3050 		c = gc->us;
3051 		if ((~c & COLOUR_FLAG_256) && (c >= 90 && c <= 97))
3052 			c -= 82;
3053 		tty_putcode_i(tty, TTYC_SETULC1, c & ~COLOUR_FLAG_256);
3054 		return;
3055 	}
3056 
3057 	/*
3058 	 * Setulc and setal follows the ncurses(3) one argument "direct colour"
3059 	 * capability format. Calculate the colour value.
3060 	 */
3061 	colour_split_rgb(gc->us, &r, &g, &b);
3062 	c = (65536 * r) + (256 * g) + b;
3063 
3064 	/*
3065 	 * Write the colour. Only use setal if the RGB flag is set because the
3066 	 * non-RGB version may be wrong.
3067 	 */
3068 	if (tty_term_has(tty->term, TTYC_SETULC))
3069 		tty_putcode_i(tty, TTYC_SETULC, c);
3070 	else if (tty_term_has(tty->term, TTYC_SETAL) &&
3071 	    tty_term_has(tty->term, TTYC_RGB))
3072 		tty_putcode_i(tty, TTYC_SETAL, c);
3073 
3074 save:
3075 	/* Save the new values in the terminal current cell. */
3076 	tc->us = gc->us;
3077 }
3078 
3079 static int
3080 tty_try_colour(struct tty *tty, int colour, const char *type)
3081 {
3082 	u_char	r, g, b;
3083 
3084 	if (colour & COLOUR_FLAG_256) {
3085 		if (*type == '3' && tty_term_has(tty->term, TTYC_SETAF))
3086 			tty_putcode_i(tty, TTYC_SETAF, colour & 0xff);
3087 		else if (tty_term_has(tty->term, TTYC_SETAB))
3088 			tty_putcode_i(tty, TTYC_SETAB, colour & 0xff);
3089 		return (0);
3090 	}
3091 
3092 	if (colour & COLOUR_FLAG_RGB) {
3093 		colour_split_rgb(colour & 0xffffff, &r, &g, &b);
3094 		if (*type == '3' && tty_term_has(tty->term, TTYC_SETRGBF))
3095 			tty_putcode_iii(tty, TTYC_SETRGBF, r, g, b);
3096 		else if (tty_term_has(tty->term, TTYC_SETRGBB))
3097 			tty_putcode_iii(tty, TTYC_SETRGBB, r, g, b);
3098 		return (0);
3099 	}
3100 
3101 	return (-1);
3102 }
3103 
3104 static void
3105 tty_window_default_style(struct grid_cell *gc, struct window_pane *wp)
3106 {
3107 	memcpy(gc, &grid_default_cell, sizeof *gc);
3108 	gc->fg = wp->palette.fg;
3109 	gc->bg = wp->palette.bg;
3110 }
3111 
3112 void
3113 tty_default_colours(struct grid_cell *gc, struct window_pane *wp)
3114 {
3115 	struct options		*oo = wp->options;
3116 	struct format_tree	*ft;
3117 
3118 	memcpy(gc, &grid_default_cell, sizeof *gc);
3119 
3120 	if (wp->flags & PANE_STYLECHANGED) {
3121 		log_debug("%%%u: style changed", wp->id);
3122 		wp->flags &= ~PANE_STYLECHANGED;
3123 
3124 		ft = format_create(NULL, NULL, FORMAT_PANE|wp->id,
3125 		    FORMAT_NOJOBS);
3126 		format_defaults(ft, NULL, NULL, NULL, wp);
3127 		tty_window_default_style(&wp->cached_active_gc, wp);
3128 		style_add(&wp->cached_active_gc, oo, "window-active-style", ft);
3129 		tty_window_default_style(&wp->cached_gc, wp);
3130 		style_add(&wp->cached_gc, oo, "window-style", ft);
3131 		format_free(ft);
3132 	}
3133 
3134 	if (gc->fg == 8) {
3135 		if (wp == wp->window->active && wp->cached_active_gc.fg != 8)
3136 			gc->fg = wp->cached_active_gc.fg;
3137 		else
3138 			gc->fg = wp->cached_gc.fg;
3139 	}
3140 
3141 	if (gc->bg == 8) {
3142 		if (wp == wp->window->active && wp->cached_active_gc.bg != 8)
3143 			gc->bg = wp->cached_active_gc.bg;
3144 		else
3145 			gc->bg = wp->cached_gc.bg;
3146 	}
3147 }
3148 
3149 static void
3150 tty_default_attributes(struct tty *tty, const struct grid_cell *defaults,
3151     struct colour_palette *palette, u_int bg, struct hyperlinks *hl)
3152 {
3153 	struct grid_cell	gc;
3154 
3155 	memcpy(&gc, &grid_default_cell, sizeof gc);
3156 	gc.bg = bg;
3157 	tty_attributes(tty, &gc, defaults, palette, hl);
3158 }
3159 
3160 static void
3161 tty_clipboard_query_callback(__unused int fd, __unused short events, void *data)
3162 {
3163 	struct tty	*tty = data;
3164 	struct client	*c = tty->client;
3165 
3166 	c->flags &= ~CLIENT_CLIPBOARDBUFFER;
3167 	free(c->clipboard_panes);
3168 	c->clipboard_panes = NULL;
3169 	c->clipboard_npanes = 0;
3170 
3171 	tty->flags &= ~TTY_OSC52QUERY;
3172 }
3173 
3174 void
3175 tty_clipboard_query(struct tty *tty)
3176 {
3177 	struct timeval	 tv = { .tv_sec = TTY_QUERY_TIMEOUT };
3178 
3179 	if ((~tty->flags & TTY_STARTED) || (tty->flags & TTY_OSC52QUERY))
3180 		return;
3181 	tty_putcode_ss(tty, TTYC_MS, "", "?");
3182 
3183 	tty->flags |= TTY_OSC52QUERY;
3184 	evtimer_set(&tty->clipboard_timer, tty_clipboard_query_callback, tty);
3185 	evtimer_add(&tty->clipboard_timer, &tv);
3186 }
3187