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