xref: /openbsd-src/usr.bin/tmux/tty.c (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1 /* $OpenBSD: tty.c,v 1.169 2014/04/25 12:45:16 jsg Exp $ */
2 
3 /*
4  * Copyright (c) 2007 Nicholas Marriott <nicm@users.sourceforge.net>
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 <errno.h>
25 #include <fcntl.h>
26 #include <resolv.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <termios.h>
30 #include <unistd.h>
31 
32 #include "tmux.h"
33 
34 void	tty_read_callback(struct bufferevent *, void *);
35 void	tty_error_callback(struct bufferevent *, short, void *);
36 
37 int	tty_try_256(struct tty *, u_char, const char *);
38 
39 void	tty_colours(struct tty *, const struct grid_cell *);
40 void	tty_check_fg(struct tty *, struct grid_cell *);
41 void	tty_check_bg(struct tty *, struct grid_cell *);
42 void	tty_colours_fg(struct tty *, const struct grid_cell *);
43 void	tty_colours_bg(struct tty *, const struct grid_cell *);
44 
45 int	tty_large_region(struct tty *, const struct tty_ctx *);
46 void	tty_redraw_region(struct tty *, const struct tty_ctx *);
47 void	tty_emulate_repeat(
48 	    struct tty *, enum tty_code_code, enum tty_code_code, u_int);
49 void	tty_repeat_space(struct tty *, u_int);
50 void	tty_cell(struct tty *, const struct grid_cell *);
51 
52 #define tty_use_acs(tty) \
53 	(tty_term_has((tty)->term, TTYC_ACSC) && !((tty)->flags & TTY_UTF8))
54 
55 #define tty_pane_full_width(tty, ctx) \
56 	((ctx)->xoff == 0 && screen_size_x((ctx)->wp->screen) >= (tty)->sx)
57 
58 void
59 tty_init(struct tty *tty, struct client *c, int fd, char *term)
60 {
61 	char	*path;
62 
63 	memset(tty, 0, sizeof *tty);
64 	tty->log_fd = -1;
65 
66 	if (term == NULL || *term == '\0')
67 		tty->termname = xstrdup("unknown");
68 	else
69 		tty->termname = xstrdup(term);
70 	tty->fd = fd;
71 	tty->client = c;
72 
73 	if ((path = ttyname(fd)) == NULL)
74 		fatalx("ttyname failed");
75 	tty->path = xstrdup(path);
76 	tty->cstyle = 0;
77 	tty->ccolour = xstrdup("");
78 
79 	tty->flags = 0;
80 	tty->term_flags = 0;
81 }
82 
83 int
84 tty_resize(struct tty *tty)
85 {
86 	struct winsize	ws;
87 	u_int		sx, sy;
88 
89 	if (ioctl(tty->fd, TIOCGWINSZ, &ws) != -1) {
90 		sx = ws.ws_col;
91 		if (sx == 0)
92 			sx = 80;
93 		sy = ws.ws_row;
94 		if (sy == 0)
95 			sy = 24;
96 	} else {
97 		sx = 80;
98 		sy = 24;
99 	}
100 	if (!tty_set_size(tty, sx, sy))
101 		return (0);
102 
103 	tty->cx = UINT_MAX;
104 	tty->cy = UINT_MAX;
105 
106 	tty->rupper = UINT_MAX;
107 	tty->rlower = UINT_MAX;
108 
109 	/*
110 	 * If the terminal has been started, reset the actual scroll region and
111 	 * cursor position, as this may not have happened.
112 	 */
113 	if (tty->flags & TTY_STARTED) {
114 		tty_cursor(tty, 0, 0);
115 		tty_region(tty, 0, tty->sy - 1);
116 	}
117 
118 	return (1);
119 }
120 
121 int
122 tty_set_size(struct tty *tty, u_int sx, u_int sy) {
123 	if (sx == tty->sx && sy == tty->sy)
124 		return (0);
125 	tty->sx = sx;
126 	tty->sy = sy;
127 	return (1);
128 }
129 
130 int
131 tty_open(struct tty *tty, char **cause)
132 {
133 	char	out[64];
134 	int	fd;
135 
136 	if (debug_level > 3) {
137 		xsnprintf(out, sizeof out, "tmux-out-%ld.log", (long) getpid());
138 		fd = open(out, O_WRONLY|O_CREAT|O_TRUNC, 0644);
139 		if (fd != -1 && fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
140 			fatal("fcntl failed");
141 		tty->log_fd = fd;
142 	}
143 
144 	tty->term = tty_term_find(tty->termname, tty->fd, cause);
145 	if (tty->term == NULL) {
146 		tty_close(tty);
147 		return (-1);
148 	}
149 	tty->flags |= TTY_OPENED;
150 
151 	tty->flags &= ~(TTY_NOCURSOR|TTY_FREEZE|TTY_TIMER);
152 
153 	tty->event = bufferevent_new(
154 	    tty->fd, tty_read_callback, NULL, tty_error_callback, tty);
155 
156 	tty_start_tty(tty);
157 
158 	tty_keys_build(tty);
159 
160 	return (0);
161 }
162 
163 void
164 tty_read_callback(unused struct bufferevent *bufev, void *data)
165 {
166 	struct tty	*tty = data;
167 
168 	while (tty_keys_next(tty))
169 		;
170 }
171 
172 void
173 tty_error_callback(
174     unused struct bufferevent *bufev, unused short what, unused void *data)
175 {
176 }
177 
178 void
179 tty_init_termios(int fd, struct termios *orig_tio, struct bufferevent *bufev)
180 {
181 	struct termios	tio;
182 
183 	if (fd == -1 || tcgetattr(fd, orig_tio) != 0)
184 		return;
185 
186 	setblocking(fd, 0);
187 
188 	if (bufev != NULL)
189 		bufferevent_enable(bufev, EV_READ|EV_WRITE);
190 
191 	memcpy(&tio, orig_tio, sizeof tio);
192 	tio.c_iflag &= ~(IXON|IXOFF|ICRNL|INLCR|IGNCR|IMAXBEL|ISTRIP);
193 	tio.c_iflag |= IGNBRK;
194 	tio.c_oflag &= ~(OPOST|ONLCR|OCRNL|ONLRET);
195 	tio.c_lflag &= ~(IEXTEN|ICANON|ECHO|ECHOE|ECHONL|ECHOCTL|
196 	    ECHOPRT|ECHOKE|ISIG);
197 	tio.c_cc[VMIN] = 1;
198 	tio.c_cc[VTIME] = 0;
199 	if (tcsetattr(fd, TCSANOW, &tio) == 0)
200 		tcflush(fd, TCIOFLUSH);
201 }
202 
203 void
204 tty_start_tty(struct tty *tty)
205 {
206 	tty_init_termios(tty->fd, &tty->tio, tty->event);
207 
208 	tty_putcode(tty, TTYC_SMCUP);
209 
210 	tty_putcode(tty, TTYC_SGR0);
211 	memcpy(&tty->cell, &grid_default_cell, sizeof tty->cell);
212 
213 	tty_putcode(tty, TTYC_RMKX);
214 	if (tty_use_acs(tty))
215 		tty_putcode(tty, TTYC_ENACS);
216 	tty_putcode(tty, TTYC_CLEAR);
217 
218 	tty_putcode(tty, TTYC_CNORM);
219 	if (tty_term_has(tty->term, TTYC_KMOUS))
220 		tty_puts(tty, "\033[?1000l\033[?1006l\033[?1005l");
221 
222 	if (tty_term_has(tty->term, TTYC_XT)) {
223 		if (options_get_number(&global_options, "focus-events")) {
224 			tty->flags |= TTY_FOCUS;
225 			tty_puts(tty, "\033[?1004h");
226 		}
227 		tty_puts(tty, "\033[c");
228 	}
229 
230 	tty->cx = UINT_MAX;
231 	tty->cy = UINT_MAX;
232 
233 	tty->rlower = UINT_MAX;
234 	tty->rupper = UINT_MAX;
235 
236 	tty->mode = MODE_CURSOR;
237 
238 	tty->flags |= TTY_STARTED;
239 
240 	tty_force_cursor_colour(tty, "");
241 }
242 
243 void
244 tty_set_class(struct tty *tty, u_int class)
245 {
246 	if (tty->class != 0)
247 		return;
248 	tty->class = class;
249 }
250 
251 void
252 tty_stop_tty(struct tty *tty)
253 {
254 	struct winsize	ws;
255 
256 	if (!(tty->flags & TTY_STARTED))
257 		return;
258 	tty->flags &= ~TTY_STARTED;
259 
260 	bufferevent_disable(tty->event, EV_READ|EV_WRITE);
261 
262 	/*
263 	 * Be flexible about error handling and try not kill the server just
264 	 * because the fd is invalid. Things like ssh -t can easily leave us
265 	 * with a dead tty.
266 	 */
267 	if (ioctl(tty->fd, TIOCGWINSZ, &ws) == -1)
268 		return;
269 	if (tcsetattr(tty->fd, TCSANOW, &tty->tio) == -1)
270 		return;
271 
272 	tty_raw(tty, tty_term_string2(tty->term, TTYC_CSR, 0, ws.ws_row - 1));
273 	if (tty_use_acs(tty))
274 		tty_raw(tty, tty_term_string(tty->term, TTYC_RMACS));
275 	tty_raw(tty, tty_term_string(tty->term, TTYC_SGR0));
276 	tty_raw(tty, tty_term_string(tty->term, TTYC_RMKX));
277 	tty_raw(tty, tty_term_string(tty->term, TTYC_CLEAR));
278 	if (tty_term_has(tty->term, TTYC_SS) && tty->cstyle != 0) {
279 		if (tty_term_has(tty->term, TTYC_SE))
280 			tty_raw(tty, tty_term_string(tty->term, TTYC_SE));
281 		else
282 			tty_raw(tty, tty_term_string1(tty->term, TTYC_SS, 0));
283 	}
284 	tty_raw(tty, tty_term_string(tty->term, TTYC_CR));
285 
286 	tty_raw(tty, tty_term_string(tty->term, TTYC_CNORM));
287 	if (tty_term_has(tty->term, TTYC_KMOUS))
288 		tty_raw(tty, "\033[?1000l\033[?1006l\033[?1005l");
289 
290 	if (tty_term_has(tty->term, TTYC_XT)) {
291 		if (tty->flags & TTY_FOCUS) {
292 			tty->flags &= ~TTY_FOCUS;
293 			tty_puts(tty, "\033[?1004l");
294 		}
295 	}
296 
297 	tty_raw(tty, tty_term_string(tty->term, TTYC_RMCUP));
298 
299 	setblocking(tty->fd, 1);
300 }
301 
302 void
303 tty_close(struct tty *tty)
304 {
305 	if (tty->log_fd != -1) {
306 		close(tty->log_fd);
307 		tty->log_fd = -1;
308 	}
309 
310 	if (event_initialized(&tty->key_timer))
311 		evtimer_del(&tty->key_timer);
312 	tty_stop_tty(tty);
313 
314 	if (tty->flags & TTY_OPENED) {
315 		bufferevent_free(tty->event);
316 
317 		tty_term_free(tty->term);
318 		tty_keys_free(tty);
319 
320 		tty->flags &= ~TTY_OPENED;
321 	}
322 
323 	if (tty->fd != -1) {
324 		close(tty->fd);
325 		tty->fd = -1;
326 	}
327 }
328 
329 void
330 tty_free(struct tty *tty)
331 {
332 	tty_close(tty);
333 
334 	free(tty->ccolour);
335 	if (tty->path != NULL)
336 		free(tty->path);
337 	if (tty->termname != NULL)
338 		free(tty->termname);
339 }
340 
341 void
342 tty_raw(struct tty *tty, const char *s)
343 {
344 	ssize_t	n, slen;
345 	u_int	i;
346 
347 	slen = strlen(s);
348 	for (i = 0; i < 5; i++) {
349 		n = write(tty->fd, s, slen);
350 		if (n >= 0) {
351 			s += n;
352 			slen -= n;
353 			if (slen == 0)
354 				break;
355 		} else if (n == -1 && errno != EAGAIN)
356 			break;
357 		usleep(100);
358 	}
359 }
360 
361 void
362 tty_putcode(struct tty *tty, enum tty_code_code code)
363 {
364 	tty_puts(tty, tty_term_string(tty->term, code));
365 }
366 
367 void
368 tty_putcode1(struct tty *tty, enum tty_code_code code, int a)
369 {
370 	if (a < 0)
371 		return;
372 	tty_puts(tty, tty_term_string1(tty->term, code, a));
373 }
374 
375 void
376 tty_putcode2(struct tty *tty, enum tty_code_code code, int a, int b)
377 {
378 	if (a < 0 || b < 0)
379 		return;
380 	tty_puts(tty, tty_term_string2(tty->term, code, a, b));
381 }
382 
383 void
384 tty_putcode_ptr1(struct tty *tty, enum tty_code_code code, const void *a)
385 {
386 	if (a != NULL)
387 		tty_puts(tty, tty_term_ptr1(tty->term, code, a));
388 }
389 
390 void
391 tty_putcode_ptr2(struct tty *tty, enum tty_code_code code, const void *a,
392     const void *b)
393 {
394 	if (a != NULL && b != NULL)
395 		tty_puts(tty, tty_term_ptr2(tty->term, code, a, b));
396 }
397 
398 void
399 tty_puts(struct tty *tty, const char *s)
400 {
401 	if (*s == '\0')
402 		return;
403 	bufferevent_write(tty->event, s, strlen(s));
404 
405 	if (tty->log_fd != -1)
406 		write(tty->log_fd, s, strlen(s));
407 }
408 
409 void
410 tty_putc(struct tty *tty, u_char ch)
411 {
412 	const char	*acs;
413 	u_int		 sx;
414 
415 	if (tty->cell.attr & GRID_ATTR_CHARSET) {
416 		acs = tty_acs_get(tty, ch);
417 		if (acs != NULL)
418 			bufferevent_write(tty->event, acs, strlen(acs));
419 		else
420 			bufferevent_write(tty->event, &ch, 1);
421 	} else
422 		bufferevent_write(tty->event, &ch, 1);
423 
424 	if (ch >= 0x20 && ch != 0x7f) {
425 		sx = tty->sx;
426 		if (tty->term->flags & TERM_EARLYWRAP)
427 			sx--;
428 
429 		if (tty->cx >= sx) {
430 			tty->cx = 1;
431 			if (tty->cy != tty->rlower)
432 				tty->cy++;
433 		} else
434 			tty->cx++;
435 	}
436 
437 	if (tty->log_fd != -1)
438 		write(tty->log_fd, &ch, 1);
439 }
440 
441 void
442 tty_putn(struct tty *tty, const void *buf, size_t len, u_int width)
443 {
444 	bufferevent_write(tty->event, buf, len);
445 	if (tty->log_fd != -1)
446 		write(tty->log_fd, buf, len);
447 	tty->cx += width;
448 }
449 
450 void
451 tty_set_title(struct tty *tty, const char *title)
452 {
453 	if (!tty_term_has(tty->term, TTYC_TSL) ||
454 	    !tty_term_has(tty->term, TTYC_FSL))
455 		return;
456 
457 	tty_putcode(tty, TTYC_TSL);
458 	tty_puts(tty, title);
459 	tty_putcode(tty, TTYC_FSL);
460 }
461 
462 void
463 tty_force_cursor_colour(struct tty *tty, const char *ccolour)
464 {
465 	if (*ccolour == '\0')
466 		tty_putcode(tty, TTYC_CR);
467 	else
468 		tty_putcode_ptr1(tty, TTYC_CS, ccolour);
469 	free(tty->ccolour);
470 	tty->ccolour = xstrdup(ccolour);
471 }
472 
473 void
474 tty_update_mode(struct tty *tty, int mode, struct screen *s)
475 {
476 	int	changed;
477 
478 	if (strcmp(s->ccolour, tty->ccolour))
479 		tty_force_cursor_colour(tty, s->ccolour);
480 
481 	if (tty->flags & TTY_NOCURSOR)
482 		mode &= ~MODE_CURSOR;
483 
484 	changed = mode ^ tty->mode;
485 	if (changed & MODE_CURSOR) {
486 		if (mode & MODE_CURSOR)
487 			tty_putcode(tty, TTYC_CNORM);
488 		else
489 			tty_putcode(tty, TTYC_CIVIS);
490 	}
491 	if (tty->cstyle != s->cstyle) {
492 		if (tty_term_has(tty->term, TTYC_SS)) {
493 			if (s->cstyle == 0 &&
494 			    tty_term_has(tty->term, TTYC_SE))
495 				tty_putcode(tty, TTYC_SE);
496 			else
497 				tty_putcode1(tty, TTYC_SS, s->cstyle);
498 		}
499 		tty->cstyle = s->cstyle;
500 	}
501 	if (changed & (ALL_MOUSE_MODES|MODE_MOUSE_UTF8)) {
502 		if (mode & ALL_MOUSE_MODES) {
503 			/*
504 			 * Enable the UTF-8 (1005) extension if configured to.
505 			 * Enable the SGR (1006) extension unconditionally, as
506 			 * this is safe from misinterpretation. Do it in this
507 			 * order, because in some terminals it's the last one
508 			 * that takes effect and SGR is the preferred one.
509 			 */
510 			if (mode & MODE_MOUSE_UTF8)
511 				tty_puts(tty, "\033[?1005h");
512 			else
513 				tty_puts(tty, "\033[?1005l");
514 			tty_puts(tty, "\033[?1006h");
515 
516 			if (mode & MODE_MOUSE_ANY)
517 				tty_puts(tty, "\033[?1003h");
518 			else if (mode & MODE_MOUSE_BUTTON)
519 				tty_puts(tty, "\033[?1002h");
520 			else if (mode & MODE_MOUSE_STANDARD)
521 				tty_puts(tty, "\033[?1000h");
522 		} else {
523 			if (tty->mode & MODE_MOUSE_ANY)
524 				tty_puts(tty, "\033[?1003l");
525 			else if (tty->mode & MODE_MOUSE_BUTTON)
526 				tty_puts(tty, "\033[?1002l");
527 			else if (tty->mode & MODE_MOUSE_STANDARD)
528 				tty_puts(tty, "\033[?1000l");
529 
530 			tty_puts(tty, "\033[?1006l");
531 			if (tty->mode & MODE_MOUSE_UTF8)
532 				tty_puts(tty, "\033[?1005l");
533 		}
534 	}
535 	if (changed & MODE_KKEYPAD) {
536 		if (mode & MODE_KKEYPAD)
537 			tty_putcode(tty, TTYC_SMKX);
538 		else
539 			tty_putcode(tty, TTYC_RMKX);
540 	}
541 	if (changed & MODE_BRACKETPASTE) {
542 		if (mode & MODE_BRACKETPASTE)
543 			tty_puts(tty, "\033[?2004h");
544 		else
545 			tty_puts(tty, "\033[?2004l");
546 	}
547 	tty->mode = mode;
548 }
549 
550 void
551 tty_emulate_repeat(struct tty *tty, enum tty_code_code code,
552     enum tty_code_code code1, u_int n)
553 {
554 	if (tty_term_has(tty->term, code))
555 		tty_putcode1(tty, code, n);
556 	else {
557 		while (n-- > 0)
558 			tty_putcode(tty, code1);
559 	}
560 }
561 
562 void
563 tty_repeat_space(struct tty *tty, u_int n)
564 {
565 	while (n-- > 0)
566 		tty_putc(tty, ' ');
567 }
568 
569 /*
570  * Is the region large enough to be worth redrawing once later rather than
571  * probably several times now? Currently yes if it is more than 50% of the
572  * pane.
573  */
574 int
575 tty_large_region(unused struct tty *tty, const struct tty_ctx *ctx)
576 {
577 	struct window_pane	*wp = ctx->wp;
578 
579 	return (ctx->orlower - ctx->orupper >= screen_size_y(wp->screen) / 2);
580 }
581 
582 /*
583  * Redraw scroll region using data from screen (already updated). Used when
584  * CSR not supported, or window is a pane that doesn't take up the full
585  * width of the terminal.
586  */
587 void
588 tty_redraw_region(struct tty *tty, const struct tty_ctx *ctx)
589 {
590 	struct window_pane	*wp = ctx->wp;
591 	struct screen		*s = wp->screen;
592 	u_int		 	 i;
593 
594 	/*
595 	 * If region is large, schedule a window redraw. In most cases this is
596 	 * likely to be followed by some more scrolling.
597 	 */
598 	if (tty_large_region(tty, ctx)) {
599 		wp->flags |= PANE_REDRAW;
600 		return;
601 	}
602 
603 	if (ctx->ocy < ctx->orupper || ctx->ocy > ctx->orlower) {
604 		for (i = ctx->ocy; i < screen_size_y(s); i++)
605 			tty_draw_line(tty, s, i, ctx->xoff, ctx->yoff);
606 	} else {
607 		for (i = ctx->orupper; i <= ctx->orlower; i++)
608 			tty_draw_line(tty, s, i, ctx->xoff, ctx->yoff);
609 	}
610 }
611 
612 void
613 tty_draw_line(struct tty *tty, struct screen *s, u_int py, u_int ox, u_int oy)
614 {
615 	const struct grid_cell	*gc;
616 	struct grid_line	*gl;
617 	struct grid_cell	 tmpgc;
618 	struct utf8_data	 ud;
619 	u_int			 i, sx;
620 
621 	tty_update_mode(tty, tty->mode & ~MODE_CURSOR, s);
622 
623 	sx = screen_size_x(s);
624 	if (sx > s->grid->linedata[s->grid->hsize + py].cellsize)
625 		sx = s->grid->linedata[s->grid->hsize + py].cellsize;
626 	if (sx > tty->sx)
627 		sx = tty->sx;
628 
629 	/*
630 	 * Don't move the cursor to the start permission if it will wrap there
631 	 * itself.
632 	 */
633 	gl = NULL;
634 	if (py != 0)
635 		gl = &s->grid->linedata[s->grid->hsize + py - 1];
636 	if (oy + py == 0 || gl == NULL || !(gl->flags & GRID_LINE_WRAPPED) ||
637 	    tty->cx < tty->sx || ox != 0 ||
638 	    (oy + py != tty->cy + 1 && tty->cy != s->rlower + oy))
639 		tty_cursor(tty, ox, oy + py);
640 
641 	for (i = 0; i < sx; i++) {
642 		gc = grid_view_peek_cell(s->grid, i, py);
643 		if (screen_check_selection(s, i, py)) {
644 			memcpy(&tmpgc, &s->sel.cell, sizeof tmpgc);
645 			grid_cell_get(gc, &ud);
646 			grid_cell_set(&tmpgc, &ud);
647 			tmpgc.flags = gc->flags &
648 			    ~(GRID_FLAG_FG256|GRID_FLAG_BG256);
649 			tmpgc.flags |= s->sel.cell.flags &
650 			    (GRID_FLAG_FG256|GRID_FLAG_BG256);
651 			tty_cell(tty, &tmpgc);
652 		} else
653 			tty_cell(tty, gc);
654 	}
655 
656 	if (sx >= tty->sx) {
657 		tty_update_mode(tty, tty->mode, s);
658 		return;
659 	}
660 	tty_reset(tty);
661 
662 	tty_cursor(tty, ox + sx, oy + py);
663 	if (sx != screen_size_x(s) && ox + screen_size_x(s) >= tty->sx &&
664 	    tty_term_has(tty->term, TTYC_EL))
665 		tty_putcode(tty, TTYC_EL);
666 	else
667 		tty_repeat_space(tty, screen_size_x(s) - sx);
668 	tty_update_mode(tty, tty->mode, s);
669 }
670 
671 void
672 tty_write(
673     void (*cmdfn)(struct tty *, const struct tty_ctx *), struct tty_ctx *ctx)
674 {
675 	struct window_pane	*wp = ctx->wp;
676 	struct client		*c;
677 	u_int		 	 i;
678 
679 	/* wp can be NULL if updating the screen but not the terminal. */
680 	if (wp == NULL)
681 		return;
682 
683 	if (wp->window->flags & WINDOW_REDRAW || wp->flags & PANE_REDRAW)
684 		return;
685 	if (!window_pane_visible(wp) || wp->flags & PANE_DROP)
686 		return;
687 
688 	for (i = 0; i < ARRAY_LENGTH(&clients); i++) {
689 		c = ARRAY_ITEM(&clients, i);
690 		if (c == NULL || c->session == NULL || c->tty.term == NULL)
691 			continue;
692 		if (c->flags & CLIENT_SUSPENDED)
693 			continue;
694 		if (c->tty.flags & TTY_FREEZE)
695 			continue;
696 		if (c->session->curw->window != wp->window)
697 			continue;
698 
699 		ctx->xoff = wp->xoff;
700 		ctx->yoff = wp->yoff;
701 		if (status_at_line(c) == 0)
702 			ctx->yoff++;
703 
704 		cmdfn(&c->tty, ctx);
705 	}
706 }
707 
708 void
709 tty_cmd_insertcharacter(struct tty *tty, const struct tty_ctx *ctx)
710 {
711 	struct window_pane	*wp = ctx->wp;
712 
713 	if (!tty_pane_full_width(tty, ctx)) {
714 		tty_draw_line(tty, wp->screen, ctx->ocy, ctx->xoff, ctx->yoff);
715 		return;
716 	}
717 
718 	tty_reset(tty);
719 
720 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
721 
722 	if (tty_term_has(tty->term, TTYC_ICH) ||
723 	    tty_term_has(tty->term, TTYC_ICH1))
724 		tty_emulate_repeat(tty, TTYC_ICH, TTYC_ICH1, ctx->num);
725 	else
726 		tty_draw_line(tty, wp->screen, ctx->ocy, ctx->xoff, ctx->yoff);
727 }
728 
729 void
730 tty_cmd_deletecharacter(struct tty *tty, const struct tty_ctx *ctx)
731 {
732 	struct window_pane	*wp = ctx->wp;
733 
734 	if (!tty_pane_full_width(tty, ctx) ||
735 	    (!tty_term_has(tty->term, TTYC_DCH) &&
736 	    !tty_term_has(tty->term, TTYC_DCH1))) {
737 		tty_draw_line(tty, wp->screen, ctx->ocy, ctx->xoff, ctx->yoff);
738 		return;
739 	}
740 
741 	tty_reset(tty);
742 
743 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
744 
745 	if (tty_term_has(tty->term, TTYC_DCH) ||
746 	    tty_term_has(tty->term, TTYC_DCH1))
747 		tty_emulate_repeat(tty, TTYC_DCH, TTYC_DCH1, ctx->num);
748 }
749 
750 void
751 tty_cmd_clearcharacter(struct tty *tty, const struct tty_ctx *ctx)
752 {
753 	u_int	i;
754 
755 	tty_reset(tty);
756 
757 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
758 
759 	if (tty_term_has(tty->term, TTYC_ECH))
760 		tty_putcode1(tty, TTYC_ECH, ctx->num);
761 	else {
762 		for (i = 0; i < ctx->num; i++)
763 			tty_putc(tty, ' ');
764 	}
765 }
766 
767 void
768 tty_cmd_insertline(struct tty *tty, const struct tty_ctx *ctx)
769 {
770 	if (!tty_pane_full_width(tty, ctx) ||
771 	    !tty_term_has(tty->term, TTYC_CSR) ||
772 	    !tty_term_has(tty->term, TTYC_IL1)) {
773 		tty_redraw_region(tty, ctx);
774 		return;
775 	}
776 
777 	tty_reset(tty);
778 
779 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
780 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
781 
782 	tty_emulate_repeat(tty, TTYC_IL, TTYC_IL1, ctx->num);
783 }
784 
785 void
786 tty_cmd_deleteline(struct tty *tty, const struct tty_ctx *ctx)
787 {
788 	if (!tty_pane_full_width(tty, ctx) ||
789 	    !tty_term_has(tty->term, TTYC_CSR) ||
790 	    !tty_term_has(tty->term, TTYC_DL1)) {
791 		tty_redraw_region(tty, ctx);
792 		return;
793 	}
794 
795 	tty_reset(tty);
796 
797 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
798 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
799 
800 	tty_emulate_repeat(tty, TTYC_DL, TTYC_DL1, ctx->num);
801 }
802 
803 void
804 tty_cmd_clearline(struct tty *tty, const struct tty_ctx *ctx)
805 {
806 	struct window_pane	*wp = ctx->wp;
807 	struct screen		*s = wp->screen;
808 
809 	tty_reset(tty);
810 
811 	tty_cursor_pane(tty, ctx, 0, ctx->ocy);
812 
813 	if (tty_pane_full_width(tty, ctx) && tty_term_has(tty->term, TTYC_EL))
814 		tty_putcode(tty, TTYC_EL);
815 	else
816 		tty_repeat_space(tty, screen_size_x(s));
817 }
818 
819 void
820 tty_cmd_clearendofline(struct tty *tty, const struct tty_ctx *ctx)
821 {
822 	struct window_pane	*wp = ctx->wp;
823 	struct screen		*s = wp->screen;
824 
825 	tty_reset(tty);
826 
827 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
828 
829 	if (tty_pane_full_width(tty, ctx) && tty_term_has(tty->term, TTYC_EL))
830 		tty_putcode(tty, TTYC_EL);
831 	else
832 		tty_repeat_space(tty, screen_size_x(s) - ctx->ocx);
833 }
834 
835 void
836 tty_cmd_clearstartofline(struct tty *tty, const struct tty_ctx *ctx)
837 {
838 	tty_reset(tty);
839 
840 	if (ctx->xoff == 0 && tty_term_has(tty->term, TTYC_EL1)) {
841 		tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
842 		tty_putcode(tty, TTYC_EL1);
843 	} else {
844 		tty_cursor_pane(tty, ctx, 0, ctx->ocy);
845 		tty_repeat_space(tty, ctx->ocx + 1);
846 	}
847 }
848 
849 void
850 tty_cmd_reverseindex(struct tty *tty, const struct tty_ctx *ctx)
851 {
852 	if (ctx->ocy != ctx->orupper)
853 		return;
854 
855 	if (!tty_pane_full_width(tty, ctx) ||
856 	    !tty_term_has(tty->term, TTYC_CSR) ||
857 	    !tty_term_has(tty->term, TTYC_RI)) {
858 		tty_redraw_region(tty, ctx);
859 		return;
860 	}
861 
862 	tty_reset(tty);
863 
864 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
865 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->orupper);
866 
867 	tty_putcode(tty, TTYC_RI);
868 }
869 
870 void
871 tty_cmd_linefeed(struct tty *tty, const struct tty_ctx *ctx)
872 {
873 	struct window_pane	*wp = ctx->wp;
874 
875 	if (ctx->ocy != ctx->orlower)
876 		return;
877 
878 	if (!tty_pane_full_width(tty, ctx) ||
879 	    !tty_term_has(tty->term, TTYC_CSR)) {
880 		if (tty_large_region(tty, ctx))
881 			wp->flags |= PANE_REDRAW;
882 		else
883 			tty_redraw_region(tty, ctx);
884 		return;
885 	}
886 
887 	/*
888 	 * If this line wrapped naturally (ctx->num is nonzero), don't do
889 	 * anything - the cursor can just be moved to the last cell and wrap
890 	 * naturally.
891 	 */
892 	if (ctx->num && !(tty->term->flags & TERM_EARLYWRAP))
893 		return;
894 
895 	tty_reset(tty);
896 
897 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
898 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
899 
900 	tty_putc(tty, '\n');
901 }
902 
903 void
904 tty_cmd_clearendofscreen(struct tty *tty, const struct tty_ctx *ctx)
905 {
906 	struct window_pane	*wp = ctx->wp;
907 	struct screen		*s = wp->screen;
908 	u_int		 	 i, j;
909 
910 	tty_reset(tty);
911 
912 	tty_region_pane(tty, ctx, 0, screen_size_y(s) - 1);
913 	tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
914 
915 	if (tty_pane_full_width(tty, ctx) && tty_term_has(tty->term, TTYC_EL)) {
916 		tty_putcode(tty, TTYC_EL);
917 		if (ctx->ocy != screen_size_y(s) - 1) {
918 			tty_cursor_pane(tty, ctx, 0, ctx->ocy + 1);
919 			for (i = ctx->ocy + 1; i < screen_size_y(s); i++) {
920 				tty_putcode(tty, TTYC_EL);
921 				if (i == screen_size_y(s) - 1)
922 					continue;
923 				tty_emulate_repeat(tty, TTYC_CUD, TTYC_CUD1, 1);
924 				tty->cy++;
925 			}
926 		}
927 	} else {
928 		tty_repeat_space(tty, screen_size_x(s) - ctx->ocx);
929 		for (j = ctx->ocy + 1; j < screen_size_y(s); j++) {
930 			tty_cursor_pane(tty, ctx, 0, j);
931 			tty_repeat_space(tty, screen_size_x(s));
932 		}
933 	}
934 }
935 
936 void
937 tty_cmd_clearstartofscreen(struct tty *tty, const struct tty_ctx *ctx)
938 {
939 	struct window_pane	*wp = ctx->wp;
940 	struct screen		*s = wp->screen;
941 	u_int		 	 i, j;
942 
943 	tty_reset(tty);
944 
945 	tty_region_pane(tty, ctx, 0, screen_size_y(s) - 1);
946 	tty_cursor_pane(tty, ctx, 0, 0);
947 
948 	if (tty_pane_full_width(tty, ctx) && tty_term_has(tty->term, TTYC_EL)) {
949 		for (i = 0; i < ctx->ocy; i++) {
950 			tty_putcode(tty, TTYC_EL);
951 			tty_emulate_repeat(tty, TTYC_CUD, TTYC_CUD1, 1);
952 			tty->cy++;
953 		}
954 	} else {
955 		for (j = 0; j < ctx->ocy; j++) {
956 			tty_cursor_pane(tty, ctx, 0, j);
957 			tty_repeat_space(tty, screen_size_x(s));
958 		}
959 	}
960 	tty_repeat_space(tty, ctx->ocx + 1);
961 }
962 
963 void
964 tty_cmd_clearscreen(struct tty *tty, const struct tty_ctx *ctx)
965 {
966 	struct window_pane	*wp = ctx->wp;
967 	struct screen		*s = wp->screen;
968 	u_int		 	 i, j;
969 
970 	tty_reset(tty);
971 
972 	tty_region_pane(tty, ctx, 0, screen_size_y(s) - 1);
973 	tty_cursor_pane(tty, ctx, 0, 0);
974 
975 	if (tty_pane_full_width(tty, ctx) && tty_term_has(tty->term, TTYC_EL)) {
976 		for (i = 0; i < screen_size_y(s); i++) {
977 			tty_putcode(tty, TTYC_EL);
978 			if (i != screen_size_y(s) - 1) {
979 				tty_emulate_repeat(tty, TTYC_CUD, TTYC_CUD1, 1);
980 				tty->cy++;
981 			}
982 		}
983 	} else {
984 		for (j = 0; j < screen_size_y(s); j++) {
985 			tty_cursor_pane(tty, ctx, 0, j);
986 			tty_repeat_space(tty, screen_size_x(s));
987 		}
988 	}
989 }
990 
991 void
992 tty_cmd_alignmenttest(struct tty *tty, const struct tty_ctx *ctx)
993 {
994 	struct window_pane	*wp = ctx->wp;
995 	struct screen		*s = wp->screen;
996 	u_int			 i, j;
997 
998 	tty_reset(tty);
999 
1000 	tty_region_pane(tty, ctx, 0, screen_size_y(s) - 1);
1001 
1002 	for (j = 0; j < screen_size_y(s); j++) {
1003 		tty_cursor_pane(tty, ctx, 0, j);
1004 		for (i = 0; i < screen_size_x(s); i++)
1005 			tty_putc(tty, 'E');
1006 	}
1007 }
1008 
1009 void
1010 tty_cmd_cell(struct tty *tty, const struct tty_ctx *ctx)
1011 {
1012 	struct window_pane	*wp = ctx->wp;
1013 	struct screen		*s = wp->screen;
1014 	u_int			 cx;
1015 	u_int			 width;
1016 
1017 	tty_region_pane(tty, ctx, ctx->orupper, ctx->orlower);
1018 
1019 	/* Is the cursor in the very last position? */
1020 	width = grid_cell_width(ctx->cell);
1021 	if (ctx->ocx > wp->sx - width) {
1022 		if (ctx->xoff != 0 || wp->sx != tty->sx) {
1023 			/*
1024 			 * The pane doesn't fill the entire line, the linefeed
1025 			 * will already have happened, so just move the cursor.
1026 			 */
1027 			if (ctx->ocy != wp->yoff + wp->screen->rlower)
1028 				tty_cursor_pane(tty, ctx, 0, ctx->ocy + 1);
1029 			else
1030 				tty_cursor_pane(tty, ctx, 0, ctx->ocy);
1031 		} else if (tty->cx < tty->sx) {
1032 			/*
1033 			 * The cursor isn't in the last position already, so
1034 			 * move as far left as possible and redraw the last
1035 			 * cell to move into the last position.
1036 			 */
1037 			cx = screen_size_x(s) - grid_cell_width(&ctx->last_cell);
1038 			tty_cursor_pane(tty, ctx, cx, ctx->ocy);
1039 			tty_cell(tty, &ctx->last_cell);
1040 		}
1041 	} else
1042 		tty_cursor_pane(tty, ctx, ctx->ocx, ctx->ocy);
1043 
1044 	tty_cell(tty, ctx->cell);
1045 }
1046 
1047 void
1048 tty_cmd_utf8character(struct tty *tty, const struct tty_ctx *ctx)
1049 {
1050 	struct window_pane	*wp = ctx->wp;
1051 
1052 	/*
1053 	 * Cannot rely on not being a partial character, so just redraw the
1054 	 * whole line.
1055 	 */
1056 	tty_draw_line(tty, wp->screen, ctx->ocy, ctx->xoff, ctx->yoff);
1057 }
1058 
1059 void
1060 tty_cmd_setselection(struct tty *tty, const struct tty_ctx *ctx)
1061 {
1062 	char	*buf;
1063 	size_t	 off;
1064 
1065 	if (!tty_term_has(tty->term, TTYC_MS))
1066 		return;
1067 
1068 	off = 4 * ((ctx->num + 2) / 3) + 1; /* storage for base64 */
1069 	buf = xmalloc(off);
1070 
1071 	b64_ntop(ctx->ptr, ctx->num, buf, off);
1072 	tty_putcode_ptr2(tty, TTYC_MS, "", buf);
1073 
1074 	free(buf);
1075 }
1076 
1077 void
1078 tty_cmd_rawstring(struct tty *tty, const struct tty_ctx *ctx)
1079 {
1080 	u_int	 i;
1081 	u_char	*str = ctx->ptr;
1082 
1083 	for (i = 0; i < ctx->num; i++)
1084 		tty_putc(tty, str[i]);
1085 
1086 	tty->cx = tty->cy = UINT_MAX;
1087 	tty->rupper = tty->rlower = UINT_MAX;
1088 
1089 	tty_reset(tty);
1090 	tty_cursor(tty, 0, 0);
1091 }
1092 
1093 void
1094 tty_cell(struct tty *tty, const struct grid_cell *gc)
1095 {
1096 	struct utf8_data	ud;
1097 	u_int			i;
1098 
1099 	/* Skip last character if terminal is stupid. */
1100 	if (tty->term->flags & TERM_EARLYWRAP &&
1101 	    tty->cy == tty->sy - 1 && tty->cx == tty->sx - 1)
1102 		return;
1103 
1104 	/* If this is a padding character, do nothing. */
1105 	if (gc->flags & GRID_FLAG_PADDING)
1106 		return;
1107 
1108 	/* Set the attributes. */
1109 	tty_attributes(tty, gc);
1110 
1111 	/* Get the cell and if ASCII write with putc to do ACS translation. */
1112 	grid_cell_get(gc, &ud);
1113 	if (ud.size == 1) {
1114 		if (*ud.data < 0x20 || *ud.data == 0x7f)
1115 			return;
1116 		tty_putc(tty, *ud.data);
1117 		return;
1118 	}
1119 
1120 	/* If not UTF-8, write _. */
1121 	if (!(tty->flags & TTY_UTF8)) {
1122 		for (i = 0; i < ud.width; i++)
1123 			tty_putc(tty, '_');
1124 		return;
1125 	}
1126 
1127 	/* Write the data. */
1128 	tty_putn(tty, ud.data, ud.size, ud.width);
1129 }
1130 
1131 void
1132 tty_reset(struct tty *tty)
1133 {
1134 	struct grid_cell	*gc = &tty->cell;
1135 
1136 	if (memcmp(gc, &grid_default_cell, sizeof *gc) == 0)
1137 		return;
1138 
1139 	if ((gc->attr & GRID_ATTR_CHARSET) && tty_use_acs(tty))
1140 		tty_putcode(tty, TTYC_RMACS);
1141 	tty_putcode(tty, TTYC_SGR0);
1142 	memcpy(gc, &grid_default_cell, sizeof *gc);
1143 }
1144 
1145 /* Set region inside pane. */
1146 void
1147 tty_region_pane(
1148     struct tty *tty, const struct tty_ctx *ctx, u_int rupper, u_int rlower)
1149 {
1150 	tty_region(tty, ctx->yoff + rupper, ctx->yoff + rlower);
1151 }
1152 
1153 /* Set region at absolute position. */
1154 void
1155 tty_region(struct tty *tty, u_int rupper, u_int rlower)
1156 {
1157 	if (tty->rlower == rlower && tty->rupper == rupper)
1158 		return;
1159 	if (!tty_term_has(tty->term, TTYC_CSR))
1160 		return;
1161 
1162 	tty->rupper = rupper;
1163 	tty->rlower = rlower;
1164 
1165 	/*
1166 	 * Some terminals (such as PuTTY) do not correctly reset the cursor to
1167 	 * 0,0 if it is beyond the last column (they do not reset their wrap
1168 	 * flag so further output causes a line feed). As a workaround, do an
1169 	 * explicit move to 0 first.
1170 	 */
1171 	if (tty->cx >= tty->sx)
1172 		tty_cursor(tty, 0, tty->cy);
1173 
1174 	tty_putcode2(tty, TTYC_CSR, tty->rupper, tty->rlower);
1175 	tty_cursor(tty, 0, 0);
1176 }
1177 
1178 /* Move cursor inside pane. */
1179 void
1180 tty_cursor_pane(struct tty *tty, const struct tty_ctx *ctx, u_int cx, u_int cy)
1181 {
1182 	tty_cursor(tty, ctx->xoff + cx, ctx->yoff + cy);
1183 }
1184 
1185 /* Move cursor to absolute position. */
1186 void
1187 tty_cursor(struct tty *tty, u_int cx, u_int cy)
1188 {
1189 	struct tty_term	*term = tty->term;
1190 	u_int		 thisx, thisy;
1191 	int		 change;
1192 
1193 	if (cx > tty->sx - 1)
1194 		cx = tty->sx - 1;
1195 
1196 	thisx = tty->cx;
1197 	thisy = tty->cy;
1198 
1199 	/* No change. */
1200 	if (cx == thisx && cy == thisy)
1201 		return;
1202 
1203 	/* Very end of the line, just use absolute movement. */
1204 	if (thisx > tty->sx - 1)
1205 		goto absolute;
1206 
1207 	/* Move to home position (0, 0). */
1208 	if (cx == 0 && cy == 0 && tty_term_has(term, TTYC_HOME)) {
1209 		tty_putcode(tty, TTYC_HOME);
1210 		goto out;
1211 	}
1212 
1213 	/* Zero on the next line. */
1214 	if (cx == 0 && cy == thisy + 1 && thisy != tty->rlower) {
1215 		tty_putc(tty, '\r');
1216 		tty_putc(tty, '\n');
1217 		goto out;
1218 	}
1219 
1220 	/* Moving column or row. */
1221 	if (cy == thisy) {
1222 		/*
1223 		 * Moving column only, row staying the same.
1224 		 */
1225 
1226 		/* To left edge. */
1227 		if (cx == 0)	{
1228 			tty_putc(tty, '\r');
1229 			goto out;
1230 		}
1231 
1232 		/* One to the left. */
1233 		if (cx == thisx - 1 && tty_term_has(term, TTYC_CUB1)) {
1234 			tty_putcode(tty, TTYC_CUB1);
1235 			goto out;
1236 		}
1237 
1238 		/* One to the right. */
1239 		if (cx == thisx + 1 && tty_term_has(term, TTYC_CUF1)) {
1240 			tty_putcode(tty, TTYC_CUF1);
1241 			goto out;
1242 		}
1243 
1244 		/* Calculate difference. */
1245 		change = thisx - cx;	/* +ve left, -ve right */
1246 
1247 		/*
1248 		 * Use HPA if change is larger than absolute, otherwise move
1249 		 * the cursor with CUB/CUF.
1250 		 */
1251 		if ((u_int) abs(change) > cx && tty_term_has(term, TTYC_HPA)) {
1252 			tty_putcode1(tty, TTYC_HPA, cx);
1253 			goto out;
1254 		} else if (change > 0 && tty_term_has(term, TTYC_CUB)) {
1255 			tty_putcode1(tty, TTYC_CUB, change);
1256 			goto out;
1257 		} else if (change < 0 && tty_term_has(term, TTYC_CUF)) {
1258 			tty_putcode1(tty, TTYC_CUF, -change);
1259 			goto out;
1260 		}
1261 	} else if (cx == thisx) {
1262 		/*
1263 		 * Moving row only, column staying the same.
1264 		 */
1265 
1266 		/* One above. */
1267 		if (thisy != tty->rupper &&
1268 		    cy == thisy - 1 && tty_term_has(term, TTYC_CUU1)) {
1269 			tty_putcode(tty, TTYC_CUU1);
1270 			goto out;
1271 		}
1272 
1273 		/* One below. */
1274 		if (thisy != tty->rlower &&
1275 		    cy == thisy + 1 && tty_term_has(term, TTYC_CUD1)) {
1276 			tty_putcode(tty, TTYC_CUD1);
1277 			goto out;
1278 		}
1279 
1280 		/* Calculate difference. */
1281 		change = thisy - cy;	/* +ve up, -ve down */
1282 
1283 		/*
1284 		 * Try to use VPA if change is larger than absolute or if this
1285 		 * change would cross the scroll region, otherwise use CUU/CUD.
1286 		 */
1287 		if ((u_int) abs(change) > cy ||
1288 		    (change < 0 && cy - change > tty->rlower) ||
1289 		    (change > 0 && cy - change < tty->rupper)) {
1290 			    if (tty_term_has(term, TTYC_VPA)) {
1291 				    tty_putcode1(tty, TTYC_VPA, cy);
1292 				    goto out;
1293 			    }
1294 		} else if (change > 0 && tty_term_has(term, TTYC_CUU)) {
1295 			tty_putcode1(tty, TTYC_CUU, change);
1296 			goto out;
1297 		} else if (change < 0 && tty_term_has(term, TTYC_CUD)) {
1298 			tty_putcode1(tty, TTYC_CUD, -change);
1299 			goto out;
1300 		}
1301 	}
1302 
1303 absolute:
1304 	/* Absolute movement. */
1305 	tty_putcode2(tty, TTYC_CUP, cy, cx);
1306 
1307 out:
1308 	tty->cx = cx;
1309 	tty->cy = cy;
1310 }
1311 
1312 void
1313 tty_attributes(struct tty *tty, const struct grid_cell *gc)
1314 {
1315 	struct grid_cell	*tc = &tty->cell, gc2;
1316 	u_char			 changed;
1317 
1318 	memcpy(&gc2, gc, sizeof gc2);
1319 
1320 	/*
1321 	 * If no setab, try to use the reverse attribute as a best-effort for a
1322 	 * non-default background. This is a bit of a hack but it doesn't do
1323 	 * any serious harm and makes a couple of applications happier.
1324 	 */
1325 	if (!tty_term_has(tty->term, TTYC_SETAB)) {
1326 		if (gc2.attr & GRID_ATTR_REVERSE) {
1327 			if (gc2.fg != 7 && gc2.fg != 8)
1328 				gc2.attr &= ~GRID_ATTR_REVERSE;
1329 		} else {
1330 			if (gc2.bg != 0 && gc2.bg != 8)
1331 				gc2.attr |= GRID_ATTR_REVERSE;
1332 		}
1333 	}
1334 
1335 	/* Fix up the colours if necessary. */
1336 	tty_check_fg(tty, &gc2);
1337 	tty_check_bg(tty, &gc2);
1338 
1339 	/* If any bits are being cleared, reset everything. */
1340 	if (tc->attr & ~gc2.attr)
1341 		tty_reset(tty);
1342 
1343 	/*
1344 	 * Set the colours. This may call tty_reset() (so it comes next) and
1345 	 * may add to (NOT remove) the desired attributes by changing new_attr.
1346 	 */
1347 	tty_colours(tty, &gc2);
1348 
1349 	/* Filter out attribute bits already set. */
1350 	changed = gc2.attr & ~tc->attr;
1351 	tc->attr = gc2.attr;
1352 
1353 	/* Set the attributes. */
1354 	if (changed & GRID_ATTR_BRIGHT)
1355 		tty_putcode(tty, TTYC_BOLD);
1356 	if (changed & GRID_ATTR_DIM)
1357 		tty_putcode(tty, TTYC_DIM);
1358 	if (changed & GRID_ATTR_ITALICS) {
1359 		if (tty_term_has(tty->term, TTYC_SITM))
1360 			tty_putcode(tty, TTYC_SITM);
1361 		else
1362 			tty_putcode(tty, TTYC_SMSO);
1363 	}
1364 	if (changed & GRID_ATTR_UNDERSCORE)
1365 		tty_putcode(tty, TTYC_SMUL);
1366 	if (changed & GRID_ATTR_BLINK)
1367 		tty_putcode(tty, TTYC_BLINK);
1368 	if (changed & GRID_ATTR_REVERSE) {
1369 		if (tty_term_has(tty->term, TTYC_REV))
1370 			tty_putcode(tty, TTYC_REV);
1371 		else if (tty_term_has(tty->term, TTYC_SMSO))
1372 			tty_putcode(tty, TTYC_SMSO);
1373 	}
1374 	if (changed & GRID_ATTR_HIDDEN)
1375 		tty_putcode(tty, TTYC_INVIS);
1376 	if ((changed & GRID_ATTR_CHARSET) && tty_use_acs(tty))
1377 		tty_putcode(tty, TTYC_SMACS);
1378 }
1379 
1380 void
1381 tty_colours(struct tty *tty, const struct grid_cell *gc)
1382 {
1383 	struct grid_cell	*tc = &tty->cell;
1384 	u_char			 fg = gc->fg, bg = gc->bg, flags = gc->flags;
1385 	int			 have_ax, fg_default, bg_default;
1386 
1387 	/* No changes? Nothing is necessary. */
1388 	if (fg == tc->fg && bg == tc->bg &&
1389 	    ((flags ^ tc->flags) & (GRID_FLAG_FG256|GRID_FLAG_BG256)) == 0)
1390 		return;
1391 
1392 	/*
1393 	 * Is either the default colour? This is handled specially because the
1394 	 * best solution might be to reset both colours to default, in which
1395 	 * case if only one is default need to fall onward to set the other
1396 	 * colour.
1397 	 */
1398 	fg_default = (fg == 8 && !(flags & GRID_FLAG_FG256));
1399 	bg_default = (bg == 8 && !(flags & GRID_FLAG_BG256));
1400 	if (fg_default || bg_default) {
1401 		/*
1402 		 * If don't have AX but do have op, send sgr0 (op can't
1403 		 * actually be used because it is sometimes the same as sgr0
1404 		 * and sometimes isn't). This resets both colours to default.
1405 		 *
1406 		 * Otherwise, try to set the default colour only as needed.
1407 		 */
1408 		have_ax = tty_term_has(tty->term, TTYC_AX);
1409 		if (!have_ax && tty_term_has(tty->term, TTYC_OP))
1410 			tty_reset(tty);
1411 		else {
1412 			if (fg_default &&
1413 			    (tc->fg != 8 || tc->flags & GRID_FLAG_FG256)) {
1414 				if (have_ax)
1415 					tty_puts(tty, "\033[39m");
1416 				else if (tc->fg != 7 ||
1417 				    tc->flags & GRID_FLAG_FG256)
1418 					tty_putcode1(tty, TTYC_SETAF, 7);
1419 				tc->fg = 8;
1420 				tc->flags &= ~GRID_FLAG_FG256;
1421 			}
1422 			if (bg_default &&
1423 			    (tc->bg != 8 || tc->flags & GRID_FLAG_BG256)) {
1424 				if (have_ax)
1425 					tty_puts(tty, "\033[49m");
1426 				else if (tc->bg != 0 ||
1427 				    tc->flags & GRID_FLAG_BG256)
1428 					tty_putcode1(tty, TTYC_SETAB, 0);
1429 				tc->bg = 8;
1430 				tc->flags &= ~GRID_FLAG_BG256;
1431 			}
1432 		}
1433 	}
1434 
1435 	/* Set the foreground colour. */
1436 	if (!fg_default && (fg != tc->fg ||
1437 	    ((flags & GRID_FLAG_FG256) != (tc->flags & GRID_FLAG_FG256))))
1438 		tty_colours_fg(tty, gc);
1439 
1440 	/*
1441 	 * Set the background colour. This must come after the foreground as
1442 	 * tty_colour_fg() can call tty_reset().
1443 	 */
1444 	if (!bg_default && (bg != tc->bg ||
1445 	    ((flags & GRID_FLAG_BG256) != (tc->flags & GRID_FLAG_BG256))))
1446 		tty_colours_bg(tty, gc);
1447 }
1448 
1449 void
1450 tty_check_fg(struct tty *tty, struct grid_cell *gc)
1451 {
1452 	u_int	colours;
1453 
1454 	/* Is this a 256-colour colour? */
1455 	if (gc->flags & GRID_FLAG_FG256) {
1456 		/* And not a 256 colour mode? */
1457 		if (!(tty->term->flags & TERM_256COLOURS) &&
1458 		    !(tty->term_flags & TERM_256COLOURS)) {
1459 			gc->fg = colour_256to16(gc->fg);
1460 			if (gc->fg & 8) {
1461 				gc->fg &= 7;
1462 				gc->attr |= GRID_ATTR_BRIGHT;
1463 			} else
1464 				gc->attr &= ~GRID_ATTR_BRIGHT;
1465 			gc->flags &= ~GRID_FLAG_FG256;
1466 		}
1467 		return;
1468 	}
1469 
1470 	/* Is this an aixterm colour? */
1471 	colours = tty_term_number(tty->term, TTYC_COLORS);
1472 	if (gc->fg >= 90 && gc->fg <= 97 && colours < 16) {
1473 		gc->fg -= 90;
1474 		gc->attr |= GRID_ATTR_BRIGHT;
1475 	}
1476 }
1477 
1478 void
1479 tty_check_bg(struct tty *tty, struct grid_cell *gc)
1480 {
1481 	u_int	colours;
1482 
1483 	/* Is this a 256-colour colour? */
1484 	if (gc->flags & GRID_FLAG_BG256) {
1485 		/*
1486 		 * And not a 256 colour mode? Translate to 16-colour
1487 		 * palette. Bold background doesn't exist portably, so just
1488 		 * discard the bold bit if set.
1489 		 */
1490 		if (!(tty->term->flags & TERM_256COLOURS) &&
1491 		    !(tty->term_flags & TERM_256COLOURS)) {
1492 			gc->bg = colour_256to16(gc->bg);
1493 			if (gc->bg & 8)
1494 				gc->bg &= 7;
1495 			gc->attr &= ~GRID_ATTR_BRIGHT;
1496 			gc->flags &= ~GRID_FLAG_BG256;
1497 		}
1498 		return;
1499 	}
1500 
1501 	/* Is this an aixterm colour? */
1502 	colours = tty_term_number(tty->term, TTYC_COLORS);
1503 	if (gc->bg >= 90 && gc->bg <= 97 && colours < 16) {
1504 		gc->bg -= 90;
1505 		gc->attr |= GRID_ATTR_BRIGHT;
1506 	}
1507 }
1508 
1509 void
1510 tty_colours_fg(struct tty *tty, const struct grid_cell *gc)
1511 {
1512 	struct grid_cell	*tc = &tty->cell;
1513 	u_char			 fg = gc->fg;
1514 	char			 s[32];
1515 
1516 	/* Is this a 256-colour colour? */
1517 	if (gc->flags & GRID_FLAG_FG256) {
1518 		/* Try as 256 colours. */
1519 		if (tty_try_256(tty, fg, "38") == 0)
1520 			goto save_fg;
1521 		/* Else already handled by tty_check_fg. */
1522 		return;
1523 	}
1524 
1525 	/* Is this an aixterm bright colour? */
1526 	if (fg >= 90 && fg <= 97) {
1527 		xsnprintf(s, sizeof s, "\033[%dm", fg);
1528 		tty_puts(tty, s);
1529 		goto save_fg;
1530 	}
1531 
1532 	/* Otherwise set the foreground colour. */
1533 	tty_putcode1(tty, TTYC_SETAF, fg);
1534 
1535 save_fg:
1536 	/* Save the new values in the terminal current cell. */
1537 	tc->fg = fg;
1538 	tc->flags &= ~GRID_FLAG_FG256;
1539 	tc->flags |= gc->flags & GRID_FLAG_FG256;
1540 }
1541 
1542 void
1543 tty_colours_bg(struct tty *tty, const struct grid_cell *gc)
1544 {
1545 	struct grid_cell	*tc = &tty->cell;
1546 	u_char			 bg = gc->bg;
1547 	char			 s[32];
1548 
1549 	/* Is this a 256-colour colour? */
1550 	if (gc->flags & GRID_FLAG_BG256) {
1551 		/* Try as 256 colours. */
1552 		if (tty_try_256(tty, bg, "48") == 0)
1553 			goto save_bg;
1554 		/* Else already handled by tty_check_bg. */
1555 		return;
1556 	}
1557 
1558 	/* Is this an aixterm bright colour? */
1559 	if (bg >= 90 && bg <= 97) {
1560 		/* 16 colour terminals or above only. */
1561 		if (tty_term_number(tty->term, TTYC_COLORS) >= 16) {
1562 			xsnprintf(s, sizeof s, "\033[%dm", bg + 10);
1563 			tty_puts(tty, s);
1564 			goto save_bg;
1565 		}
1566 		bg -= 90;
1567 		/* no such thing as a bold background */
1568 	}
1569 
1570 	/* Otherwise set the background colour. */
1571 	tty_putcode1(tty, TTYC_SETAB, bg);
1572 
1573 save_bg:
1574 	/* Save the new values in the terminal current cell. */
1575 	tc->bg = bg;
1576 	tc->flags &= ~GRID_FLAG_BG256;
1577 	tc->flags |= gc->flags & GRID_FLAG_BG256;
1578 }
1579 
1580 int
1581 tty_try_256(struct tty *tty, u_char colour, const char *type)
1582 {
1583 	char	s[32];
1584 
1585 	/*
1586 	 * If the terminfo entry has 256 colours, assume that setaf and setab
1587 	 * work correctly.
1588 	 */
1589 	if (tty->term->flags & TERM_256COLOURS) {
1590 		if (*type == '3')
1591 			tty_putcode1(tty, TTYC_SETAF, colour);
1592 		else
1593 			tty_putcode1(tty, TTYC_SETAB, colour);
1594 		return (0);
1595 	}
1596 
1597 	/*
1598 	 * If the user has specified -2 to the client, setaf and setab may not
1599 	 * work, so send the usual sequence.
1600 	 */
1601 	if (tty->term_flags & TERM_256COLOURS) {
1602 		xsnprintf(s, sizeof s, "\033[%s;5;%hhum", type, colour);
1603 		tty_puts(tty, s);
1604 		return (0);
1605 	}
1606 
1607 	return (-1);
1608 }
1609 
1610 void
1611 tty_bell(struct tty *tty)
1612 {
1613 	tty_putcode(tty, TTYC_BEL);
1614 }
1615