xref: /openbsd-src/usr.bin/tmux/screen-write.c (revision 7c0ec4b8992567abb1e1536622dc789a9a39d9f1)
1 /* $OpenBSD: screen-write.c,v 1.226 2024/08/21 04:17:09 nicm Exp $ */
2 
3 /*
4  * Copyright (c) 2007 Nicholas Marriott <nicholas.marriott@gmail.com>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 
21 #include <stdlib.h>
22 #include <string.h>
23 
24 #include "tmux.h"
25 
26 static struct screen_write_citem *screen_write_collect_trim(
27 		    struct screen_write_ctx *, u_int, u_int, u_int, int *);
28 static void	screen_write_collect_clear(struct screen_write_ctx *, u_int,
29 		    u_int);
30 static void	screen_write_collect_scroll(struct screen_write_ctx *, u_int);
31 static void	screen_write_collect_flush(struct screen_write_ctx *, int,
32 		    const char *);
33 static int	screen_write_overwrite(struct screen_write_ctx *,
34 		    struct grid_cell *, u_int);
35 static int	screen_write_combine(struct screen_write_ctx *,
36 		    const struct grid_cell *);
37 
38 struct screen_write_citem {
39 	u_int				x;
40 	int				wrapped;
41 
42 	enum { TEXT, CLEAR }		type;
43 	u_int				used;
44 	u_int				bg;
45 
46 	struct grid_cell		gc;
47 
48 	TAILQ_ENTRY(screen_write_citem) entry;
49 };
50 struct screen_write_cline {
51 	char				*data;
52 	TAILQ_HEAD(, screen_write_citem) items;
53 };
54 TAILQ_HEAD(, screen_write_citem)  screen_write_citem_freelist =
55     TAILQ_HEAD_INITIALIZER(screen_write_citem_freelist);
56 
57 static struct screen_write_citem *
58 screen_write_get_citem(void)
59 {
60     struct screen_write_citem	*ci;
61 
62     ci = TAILQ_FIRST(&screen_write_citem_freelist);
63     if (ci != NULL) {
64         TAILQ_REMOVE(&screen_write_citem_freelist, ci, entry);
65         memset(ci, 0, sizeof *ci);
66         return (ci);
67     }
68     return (xcalloc(1, sizeof *ci));
69 }
70 
71 static void
72 screen_write_free_citem(struct screen_write_citem *ci)
73 {
74     TAILQ_INSERT_TAIL(&screen_write_citem_freelist, ci, entry);
75 }
76 
77 static void
78 screen_write_offset_timer(__unused int fd, __unused short events, void *data)
79 {
80 	struct window	*w = data;
81 
82 	tty_update_window_offset(w);
83 }
84 
85 /* Set cursor position. */
86 static void
87 screen_write_set_cursor(struct screen_write_ctx *ctx, int cx, int cy)
88 {
89 	struct window_pane	*wp = ctx->wp;
90 	struct window		*w;
91 	struct screen		*s = ctx->s;
92 	struct timeval		 tv = { .tv_usec = 10000 };
93 
94 	if (cx != -1 && (u_int)cx == s->cx && cy != -1 && (u_int)cy == s->cy)
95 		return;
96 
97 	if (cx != -1) {
98 		if ((u_int)cx > screen_size_x(s)) /* allow last column */
99 			cx = screen_size_x(s) - 1;
100 		s->cx = cx;
101 	}
102 	if (cy != -1) {
103 		if ((u_int)cy > screen_size_y(s) - 1)
104 			cy = screen_size_y(s) - 1;
105 		s->cy = cy;
106 	}
107 
108 	if (wp == NULL)
109 		return;
110 	w = wp->window;
111 
112 	if (!event_initialized(&w->offset_timer))
113 		evtimer_set(&w->offset_timer, screen_write_offset_timer, w);
114 	if (!evtimer_pending(&w->offset_timer, NULL))
115 		evtimer_add(&w->offset_timer, &tv);
116 }
117 
118 /* Do a full redraw. */
119 static void
120 screen_write_redraw_cb(const struct tty_ctx *ttyctx)
121 {
122 	struct window_pane	*wp = ttyctx->arg;
123 
124 	if (wp != NULL)
125 		wp->flags |= PANE_REDRAW;
126 }
127 
128 /* Update context for client. */
129 static int
130 screen_write_set_client_cb(struct tty_ctx *ttyctx, struct client *c)
131 {
132 	struct window_pane	*wp = ttyctx->arg;
133 
134 	if (ttyctx->allow_invisible_panes) {
135 		if (session_has(c->session, wp->window))
136 			return (1);
137 		return (0);
138 	}
139 
140 	if (c->session->curw->window != wp->window)
141 		return (0);
142 	if (wp->layout_cell == NULL)
143 		return (0);
144 
145 	if (wp->flags & (PANE_REDRAW|PANE_DROP))
146 		return (-1);
147 	if (c->flags & CLIENT_REDRAWPANES) {
148 		/*
149 		 * Redraw is already deferred to redraw another pane - redraw
150 		 * this one also when that happens.
151 		 */
152 		log_debug("%s: adding %%%u to deferred redraw", __func__,
153 		    wp->id);
154 		wp->flags |= PANE_REDRAW;
155 		return (-1);
156 	}
157 
158 	ttyctx->bigger = tty_window_offset(&c->tty, &ttyctx->wox, &ttyctx->woy,
159 	    &ttyctx->wsx, &ttyctx->wsy);
160 
161 	ttyctx->xoff = ttyctx->rxoff = wp->xoff;
162 	ttyctx->yoff = ttyctx->ryoff = wp->yoff;
163 
164 	if (status_at_line(c) == 0)
165 		ttyctx->yoff += status_line_size(c);
166 
167 	return (1);
168 }
169 
170 /* Set up context for TTY command. */
171 static void
172 screen_write_initctx(struct screen_write_ctx *ctx, struct tty_ctx *ttyctx,
173     int sync)
174 {
175 	struct screen	*s = ctx->s;
176 
177 	memset(ttyctx, 0, sizeof *ttyctx);
178 
179 	ttyctx->s = s;
180 	ttyctx->sx = screen_size_x(s);
181 	ttyctx->sy = screen_size_y(s);
182 
183 	ttyctx->ocx = s->cx;
184 	ttyctx->ocy = s->cy;
185 	ttyctx->orlower = s->rlower;
186 	ttyctx->orupper = s->rupper;
187 
188 	memcpy(&ttyctx->defaults, &grid_default_cell, sizeof ttyctx->defaults);
189 	if (ctx->init_ctx_cb != NULL) {
190 		ctx->init_ctx_cb(ctx, ttyctx);
191 		if (ttyctx->palette != NULL) {
192 			if (ttyctx->defaults.fg == 8)
193 				ttyctx->defaults.fg = ttyctx->palette->fg;
194 			if (ttyctx->defaults.bg == 8)
195 				ttyctx->defaults.bg = ttyctx->palette->bg;
196 		}
197 	} else {
198 		ttyctx->redraw_cb = screen_write_redraw_cb;
199 		if (ctx->wp != NULL) {
200 			tty_default_colours(&ttyctx->defaults, ctx->wp);
201 			ttyctx->palette = &ctx->wp->palette;
202 			ttyctx->set_client_cb = screen_write_set_client_cb;
203 			ttyctx->arg = ctx->wp;
204 		}
205 	}
206 
207 	if (~ctx->flags & SCREEN_WRITE_SYNC) {
208 		/*
209 		 * For the active pane or for an overlay (no pane), we want to
210 		 * only use synchronized updates if requested (commands that
211 		 * move the cursor); for other panes, always use it, since the
212 		 * cursor will have to move.
213 		 */
214 		if (ctx->wp != NULL) {
215 			if (ctx->wp != ctx->wp->window->active)
216 				ttyctx->num = 1;
217 			else
218 				ttyctx->num = sync;
219 		} else
220 			ttyctx->num = 0x10|sync;
221 		tty_write(tty_cmd_syncstart, ttyctx);
222 		ctx->flags |= SCREEN_WRITE_SYNC;
223 	}
224 }
225 
226 /* Make write list. */
227 void
228 screen_write_make_list(struct screen *s)
229 {
230 	u_int	y;
231 
232 	s->write_list = xcalloc(screen_size_y(s), sizeof *s->write_list);
233 	for (y = 0; y < screen_size_y(s); y++)
234 		TAILQ_INIT(&s->write_list[y].items);
235 }
236 
237 /* Free write list. */
238 void
239 screen_write_free_list(struct screen *s)
240 {
241 	u_int	y;
242 
243 	for (y = 0; y < screen_size_y(s); y++)
244 		free(s->write_list[y].data);
245 	free(s->write_list);
246 }
247 
248 /* Set up for writing. */
249 static void
250 screen_write_init(struct screen_write_ctx *ctx, struct screen *s)
251 {
252 	memset(ctx, 0, sizeof *ctx);
253 
254 	ctx->s = s;
255 
256 	if (ctx->s->write_list == NULL)
257 		screen_write_make_list(ctx->s);
258 	ctx->item = screen_write_get_citem();
259 
260 	ctx->scrolled = 0;
261 	ctx->bg = 8;
262 }
263 
264 /* Initialize writing with a pane. */
265 void
266 screen_write_start_pane(struct screen_write_ctx *ctx, struct window_pane *wp,
267     struct screen *s)
268 {
269 	if (s == NULL)
270 		s = wp->screen;
271 	screen_write_init(ctx, s);
272 	ctx->wp = wp;
273 
274 	if (log_get_level() != 0) {
275 		log_debug("%s: size %ux%u, pane %%%u (at %u,%u)",
276 		    __func__, screen_size_x(ctx->s), screen_size_y(ctx->s),
277 		    wp->id, wp->xoff, wp->yoff);
278 	}
279 }
280 
281 /* Initialize writing with a callback. */
282 void
283 screen_write_start_callback(struct screen_write_ctx *ctx, struct screen *s,
284     screen_write_init_ctx_cb cb, void *arg)
285 {
286 	screen_write_init(ctx, s);
287 
288 	ctx->init_ctx_cb = cb;
289 	ctx->arg = arg;
290 
291 	if (log_get_level() != 0) {
292 		log_debug("%s: size %ux%u, with callback", __func__,
293 		    screen_size_x(ctx->s), screen_size_y(ctx->s));
294 	}
295 }
296 
297 /* Initialize writing. */
298 void
299 screen_write_start(struct screen_write_ctx *ctx, struct screen *s)
300 {
301 	screen_write_init(ctx, s);
302 
303 	if (log_get_level() != 0) {
304 		log_debug("%s: size %ux%u, no pane", __func__,
305 		    screen_size_x(ctx->s), screen_size_y(ctx->s));
306 	}
307 }
308 
309 /* Finish writing. */
310 void
311 screen_write_stop(struct screen_write_ctx *ctx)
312 {
313 	screen_write_collect_end(ctx);
314 	screen_write_collect_flush(ctx, 0, __func__);
315 
316 	screen_write_free_citem(ctx->item);
317 }
318 
319 /* Reset screen state. */
320 void
321 screen_write_reset(struct screen_write_ctx *ctx)
322 {
323 	struct screen	*s = ctx->s;
324 
325 	screen_reset_tabs(s);
326 	screen_write_scrollregion(ctx, 0, screen_size_y(s) - 1);
327 
328 	s->mode = MODE_CURSOR|MODE_WRAP;
329 
330 	if (options_get_number(global_options, "extended-keys") == 2)
331 		s->mode = (s->mode & ~EXTENDED_KEY_MODES)|MODE_KEYS_EXTENDED;
332 
333 	screen_write_clearscreen(ctx, 8);
334 	screen_write_set_cursor(ctx, 0, 0);
335 }
336 
337 /* Write character. */
338 void
339 screen_write_putc(struct screen_write_ctx *ctx, const struct grid_cell *gcp,
340     u_char ch)
341 {
342 	struct grid_cell	gc;
343 
344 	memcpy(&gc, gcp, sizeof gc);
345 
346 	utf8_set(&gc.data, ch);
347 	screen_write_cell(ctx, &gc);
348 }
349 
350 /* Calculate string length. */
351 size_t
352 screen_write_strlen(const char *fmt, ...)
353 {
354 	va_list			ap;
355 	char   	       	       *msg;
356 	struct utf8_data	ud;
357 	u_char 	      	       *ptr;
358 	size_t			left, size = 0;
359 	enum utf8_state		more;
360 
361 	va_start(ap, fmt);
362 	xvasprintf(&msg, fmt, ap);
363 	va_end(ap);
364 
365 	ptr = msg;
366 	while (*ptr != '\0') {
367 		if (*ptr > 0x7f && utf8_open(&ud, *ptr) == UTF8_MORE) {
368 			ptr++;
369 
370 			left = strlen(ptr);
371 			if (left < (size_t)ud.size - 1)
372 				break;
373 			while ((more = utf8_append(&ud, *ptr)) == UTF8_MORE)
374 				ptr++;
375 			ptr++;
376 
377 			if (more == UTF8_DONE)
378 				size += ud.width;
379 		} else {
380 			if (*ptr > 0x1f && *ptr < 0x7f)
381 				size++;
382 			ptr++;
383 		}
384 	}
385 
386 	free(msg);
387 	return (size);
388 }
389 
390 /* Write string wrapped over lines. */
391 int
392 screen_write_text(struct screen_write_ctx *ctx, u_int cx, u_int width,
393     u_int lines, int more, const struct grid_cell *gcp, const char *fmt, ...)
394 {
395 	struct screen		*s = ctx->s;
396 	va_list			 ap;
397 	char			*tmp;
398 	u_int			 cy = s->cy, i, end, next, idx = 0, at, left;
399 	struct utf8_data	*text;
400 	struct grid_cell	 gc;
401 
402 	memcpy(&gc, gcp, sizeof gc);
403 
404 	va_start(ap, fmt);
405 	xvasprintf(&tmp, fmt, ap);
406 	va_end(ap);
407 
408 	text = utf8_fromcstr(tmp);
409 	free(tmp);
410 
411 	left = (cx + width) - s->cx;
412 	for (;;) {
413 		/* Find the end of what can fit on the line. */
414 		at = 0;
415 		for (end = idx; text[end].size != 0; end++) {
416 			if (text[end].size == 1 && text[end].data[0] == '\n')
417 				break;
418 			if (at + text[end].width > left)
419 				break;
420 			at += text[end].width;
421 		}
422 
423 		/*
424 		 * If we're on a space, that's the end. If not, walk back to
425 		 * try and find one.
426 		 */
427 		if (text[end].size == 0)
428 			next = end;
429 		else if (text[end].size == 1 && text[end].data[0] == '\n')
430 			next = end + 1;
431 		else if (text[end].size == 1 && text[end].data[0] == ' ')
432 			next = end + 1;
433 		else {
434 			for (i = end; i > idx; i--) {
435 				if (text[i].size == 1 && text[i].data[0] == ' ')
436 					break;
437 			}
438 			if (i != idx) {
439 				next = i + 1;
440 				end = i;
441 			} else
442 				next = end;
443 		}
444 
445 		/* Print the line. */
446 		for (i = idx; i < end; i++) {
447 			utf8_copy(&gc.data, &text[i]);
448 			screen_write_cell(ctx, &gc);
449 		}
450 
451 		/* If at the bottom, stop. */
452 		idx = next;
453 		if (s->cy == cy + lines - 1 || text[idx].size == 0)
454 			break;
455 
456 		screen_write_cursormove(ctx, cx, s->cy + 1, 0);
457 		left = width;
458 	}
459 
460 	/*
461 	 * Fail if on the last line and there is more to come or at the end, or
462 	 * if the text was not entirely consumed.
463 	 */
464 	if ((s->cy == cy + lines - 1 && (!more || s->cx == cx + width)) ||
465 	    text[idx].size != 0) {
466 		free(text);
467 		return (0);
468 	}
469 	free(text);
470 
471 	/*
472 	 * If no more to come, move to the next line. Otherwise, leave on
473 	 * the same line (except if at the end).
474 	 */
475 	if (!more || s->cx == cx + width)
476 		screen_write_cursormove(ctx, cx, s->cy + 1, 0);
477 	return (1);
478 }
479 
480 /* Write simple string (no maximum length). */
481 void
482 screen_write_puts(struct screen_write_ctx *ctx, const struct grid_cell *gcp,
483     const char *fmt, ...)
484 {
485 	va_list	ap;
486 
487 	va_start(ap, fmt);
488 	screen_write_vnputs(ctx, -1, gcp, fmt, ap);
489 	va_end(ap);
490 }
491 
492 /* Write string with length limit (-1 for unlimited). */
493 void
494 screen_write_nputs(struct screen_write_ctx *ctx, ssize_t maxlen,
495     const struct grid_cell *gcp, const char *fmt, ...)
496 {
497 	va_list	ap;
498 
499 	va_start(ap, fmt);
500 	screen_write_vnputs(ctx, maxlen, gcp, fmt, ap);
501 	va_end(ap);
502 }
503 
504 void
505 screen_write_vnputs(struct screen_write_ctx *ctx, ssize_t maxlen,
506     const struct grid_cell *gcp, const char *fmt, va_list ap)
507 {
508 	struct grid_cell	gc;
509 	struct utf8_data       *ud = &gc.data;
510 	char   		       *msg;
511 	u_char 		       *ptr;
512 	size_t		 	left, size = 0;
513 	enum utf8_state		more;
514 
515 	memcpy(&gc, gcp, sizeof gc);
516 	xvasprintf(&msg, fmt, ap);
517 
518 	ptr = msg;
519 	while (*ptr != '\0') {
520 		if (*ptr > 0x7f && utf8_open(ud, *ptr) == UTF8_MORE) {
521 			ptr++;
522 
523 			left = strlen(ptr);
524 			if (left < (size_t)ud->size - 1)
525 				break;
526 			while ((more = utf8_append(ud, *ptr)) == UTF8_MORE)
527 				ptr++;
528 			ptr++;
529 
530 			if (more != UTF8_DONE)
531 				continue;
532 			if (maxlen > 0 && size + ud->width > (size_t)maxlen) {
533 				while (size < (size_t)maxlen) {
534 					screen_write_putc(ctx, &gc, ' ');
535 					size++;
536 				}
537 				break;
538 			}
539 			size += ud->width;
540 			screen_write_cell(ctx, &gc);
541 		} else {
542 			if (maxlen > 0 && size + 1 > (size_t)maxlen)
543 				break;
544 
545 			if (*ptr == '\001')
546 				gc.attr ^= GRID_ATTR_CHARSET;
547 			else if (*ptr == '\n') {
548 				screen_write_linefeed(ctx, 0, 8);
549 				screen_write_carriagereturn(ctx);
550 			} else if (*ptr > 0x1f && *ptr < 0x7f) {
551 				size++;
552 				screen_write_putc(ctx, &gc, *ptr);
553 			}
554 			ptr++;
555 		}
556 	}
557 
558 	free(msg);
559 }
560 
561 /*
562  * Copy from another screen but without the selection stuff. Assumes the target
563  * region is already big enough.
564  */
565 void
566 screen_write_fast_copy(struct screen_write_ctx *ctx, struct screen *src,
567     u_int px, u_int py, u_int nx, u_int ny)
568 {
569 	struct screen		*s = ctx->s;
570 	struct grid		*gd = src->grid;
571 	struct grid_cell	 gc;
572 	u_int		 	 xx, yy, cx, cy;
573 
574 	if (nx == 0 || ny == 0)
575 		return;
576 
577 	cy = s->cy;
578 	for (yy = py; yy < py + ny; yy++) {
579 		if (yy >= gd->hsize + gd->sy)
580 			break;
581 		cx = s->cx;
582 		for (xx = px; xx < px + nx; xx++) {
583 			if (xx >= grid_get_line(gd, yy)->cellsize)
584 				break;
585 			grid_get_cell(gd, xx, yy, &gc);
586 			if (xx + gc.data.width > px + nx)
587 				break;
588 			grid_view_set_cell(ctx->s->grid, cx, cy, &gc);
589 			cx++;
590 		}
591 		cy++;
592 	}
593 }
594 
595 /* Select character set for drawing border lines. */
596 static void
597 screen_write_box_border_set(enum box_lines lines, int cell_type,
598     struct grid_cell *gc)
599 {
600 	switch (lines) {
601         case BOX_LINES_NONE:
602 		break;
603         case BOX_LINES_DOUBLE:
604                 gc->attr &= ~GRID_ATTR_CHARSET;
605                 utf8_copy(&gc->data, tty_acs_double_borders(cell_type));
606 		break;
607         case BOX_LINES_HEAVY:
608                 gc->attr &= ~GRID_ATTR_CHARSET;
609                 utf8_copy(&gc->data, tty_acs_heavy_borders(cell_type));
610 		break;
611         case BOX_LINES_ROUNDED:
612                 gc->attr &= ~GRID_ATTR_CHARSET;
613                 utf8_copy(&gc->data, tty_acs_rounded_borders(cell_type));
614 		break;
615         case BOX_LINES_SIMPLE:
616                 gc->attr &= ~GRID_ATTR_CHARSET;
617                 utf8_set(&gc->data, SIMPLE_BORDERS[cell_type]);
618                 break;
619         case BOX_LINES_PADDED:
620                 gc->attr &= ~GRID_ATTR_CHARSET;
621                 utf8_set(&gc->data, PADDED_BORDERS[cell_type]);
622                 break;
623 	case BOX_LINES_SINGLE:
624 	case BOX_LINES_DEFAULT:
625 		gc->attr |= GRID_ATTR_CHARSET;
626 		utf8_set(&gc->data, CELL_BORDERS[cell_type]);
627 		break;
628 	}
629 }
630 
631 /* Draw a horizontal line on screen. */
632 void
633 screen_write_hline(struct screen_write_ctx *ctx, u_int nx, int left, int right,
634    enum box_lines lines, const struct grid_cell *border_gc)
635 {
636 	struct screen		*s = ctx->s;
637 	struct grid_cell	 gc;
638 	u_int			 cx, cy, i;
639 
640 	cx = s->cx;
641 	cy = s->cy;
642 
643 	if (border_gc != NULL)
644 		memcpy(&gc, border_gc, sizeof gc);
645 	else
646 		memcpy(&gc, &grid_default_cell, sizeof gc);
647 	gc.attr |= GRID_ATTR_CHARSET;
648 
649 	if (left)
650 		screen_write_box_border_set(lines, CELL_LEFTJOIN, &gc);
651 	else
652 		screen_write_box_border_set(lines, CELL_LEFTRIGHT, &gc);
653 	screen_write_cell(ctx, &gc);
654 
655 	screen_write_box_border_set(lines, CELL_LEFTRIGHT, &gc);
656 	for (i = 1; i < nx - 1; i++)
657 		screen_write_cell(ctx, &gc);
658 
659 	if (right)
660 		screen_write_box_border_set(lines, CELL_RIGHTJOIN, &gc);
661 	else
662 		screen_write_box_border_set(lines, CELL_LEFTRIGHT, &gc);
663 	screen_write_cell(ctx, &gc);
664 
665 	screen_write_set_cursor(ctx, cx, cy);
666 }
667 
668 /* Draw a vertical line on screen. */
669 void
670 screen_write_vline(struct screen_write_ctx *ctx, u_int ny, int top, int bottom)
671 {
672 	struct screen		*s = ctx->s;
673 	struct grid_cell	 gc;
674 	u_int			 cx, cy, i;
675 
676 	cx = s->cx;
677 	cy = s->cy;
678 
679 	memcpy(&gc, &grid_default_cell, sizeof gc);
680 	gc.attr |= GRID_ATTR_CHARSET;
681 
682 	screen_write_putc(ctx, &gc, top ? 'w' : 'x');
683 	for (i = 1; i < ny - 1; i++) {
684 		screen_write_set_cursor(ctx, cx, cy + i);
685 		screen_write_putc(ctx, &gc, 'x');
686 	}
687 	screen_write_set_cursor(ctx, cx, cy + ny - 1);
688 	screen_write_putc(ctx, &gc, bottom ? 'v' : 'x');
689 
690 	screen_write_set_cursor(ctx, cx, cy);
691 }
692 
693 /* Draw a menu on screen. */
694 void
695 screen_write_menu(struct screen_write_ctx *ctx, struct menu *menu, int choice,
696     enum box_lines lines, const struct grid_cell *menu_gc,
697     const struct grid_cell *border_gc, const struct grid_cell *choice_gc)
698 {
699 	struct screen		*s = ctx->s;
700 	struct grid_cell	 default_gc;
701 	const struct grid_cell	*gc = &default_gc;
702 	u_int			 cx, cy, i, j, width = menu->width;
703 	const char		*name;
704 
705 	cx = s->cx;
706 	cy = s->cy;
707 
708 	memcpy(&default_gc, menu_gc, sizeof default_gc);
709 
710 	screen_write_box(ctx, menu->width + 4, menu->count + 2, lines,
711 	    border_gc, menu->title);
712 
713 	for (i = 0; i < menu->count; i++) {
714 		name = menu->items[i].name;
715 		if (name == NULL) {
716 			screen_write_cursormove(ctx, cx, cy + 1 + i, 0);
717 			screen_write_hline(ctx, width + 4, 1, 1, lines,
718 			    border_gc);
719 			continue;
720 		}
721 
722 		if (choice >= 0 && i == (u_int)choice && *name != '-')
723 			gc = choice_gc;
724 
725 		screen_write_cursormove(ctx, cx + 1, cy + 1 + i, 0);
726 		for (j = 0; j < width + 2; j++)
727 			screen_write_putc(ctx, gc, ' ');
728 
729 		screen_write_cursormove(ctx, cx + 2, cy + 1 + i, 0);
730 		if (*name == '-') {
731 			default_gc.attr |= GRID_ATTR_DIM;
732 			format_draw(ctx, gc, width, name + 1, NULL, 0);
733 			default_gc.attr &= ~GRID_ATTR_DIM;
734 			continue;
735 		}
736 
737 		format_draw(ctx, gc, width, name, NULL, 0);
738 		gc = &default_gc;
739 	}
740 
741 	screen_write_set_cursor(ctx, cx, cy);
742 }
743 
744 /* Draw a box on screen. */
745 void
746 screen_write_box(struct screen_write_ctx *ctx, u_int nx, u_int ny,
747     enum box_lines lines, const struct grid_cell *gcp, const char *title)
748 {
749 	struct screen		*s = ctx->s;
750 	struct grid_cell         gc;
751 	u_int			 cx, cy, i;
752 
753 	cx = s->cx;
754 	cy = s->cy;
755 
756 	if (gcp != NULL)
757 		memcpy(&gc, gcp, sizeof gc);
758 	else
759 		memcpy(&gc, &grid_default_cell, sizeof gc);
760 
761 	gc.attr |= GRID_ATTR_CHARSET;
762 	gc.flags |= GRID_FLAG_NOPALETTE;
763 
764 	/* Draw top border */
765 	screen_write_box_border_set(lines, CELL_TOPLEFT, &gc);
766 	screen_write_cell(ctx, &gc);
767 	screen_write_box_border_set(lines, CELL_LEFTRIGHT, &gc);
768 	for (i = 1; i < nx - 1; i++)
769 		screen_write_cell(ctx, &gc);
770 	screen_write_box_border_set(lines, CELL_TOPRIGHT, &gc);
771 	screen_write_cell(ctx, &gc);
772 
773 	/* Draw bottom border */
774 	screen_write_set_cursor(ctx, cx, cy + ny - 1);
775 	screen_write_box_border_set(lines, CELL_BOTTOMLEFT, &gc);
776 	screen_write_cell(ctx, &gc);
777 	screen_write_box_border_set(lines, CELL_LEFTRIGHT, &gc);
778 	for (i = 1; i < nx - 1; i++)
779 		screen_write_cell(ctx, &gc);
780 	screen_write_box_border_set(lines, CELL_BOTTOMRIGHT, &gc);
781 	screen_write_cell(ctx, &gc);
782 
783 	/* Draw sides */
784 	screen_write_box_border_set(lines, CELL_TOPBOTTOM, &gc);
785 	for (i = 1; i < ny - 1; i++) {
786 		/* left side */
787 		screen_write_set_cursor(ctx, cx, cy + i);
788 		screen_write_cell(ctx, &gc);
789 		/* right side */
790 		screen_write_set_cursor(ctx, cx + nx - 1, cy + i);
791 		screen_write_cell(ctx, &gc);
792 	}
793 
794 	if (title != NULL) {
795 		gc.attr &= ~GRID_ATTR_CHARSET;
796 		screen_write_cursormove(ctx, cx + 2, cy, 0);
797 		format_draw(ctx, &gc, nx - 4, title, NULL, 0);
798 	}
799 
800 	screen_write_set_cursor(ctx, cx, cy);
801 }
802 
803 /*
804  * Write a preview version of a window. Assumes target area is big enough and
805  * already cleared.
806  */
807 void
808 screen_write_preview(struct screen_write_ctx *ctx, struct screen *src, u_int nx,
809     u_int ny)
810 {
811 	struct screen		*s = ctx->s;
812 	struct grid_cell	 gc;
813 	u_int			 cx, cy, px, py;
814 
815 	cx = s->cx;
816 	cy = s->cy;
817 
818 	/*
819 	 * If the cursor is on, pick the area around the cursor, otherwise use
820 	 * the top left.
821 	 */
822 	if (src->mode & MODE_CURSOR) {
823 		px = src->cx;
824 		if (px < nx / 3)
825 			px = 0;
826 		else
827 			px = px - nx / 3;
828 		if (px + nx > screen_size_x(src)) {
829 			if (nx > screen_size_x(src))
830 				px = 0;
831 			else
832 				px = screen_size_x(src) - nx;
833 		}
834 		py = src->cy;
835 		if (py < ny / 3)
836 			py = 0;
837 		else
838 			py = py - ny / 3;
839 		if (py + ny > screen_size_y(src)) {
840 			if (ny > screen_size_y(src))
841 				py = 0;
842 			else
843 				py = screen_size_y(src) - ny;
844 		}
845 	} else {
846 		px = 0;
847 		py = 0;
848 	}
849 
850 	screen_write_fast_copy(ctx, src, px, src->grid->hsize + py, nx, ny);
851 
852 	if (src->mode & MODE_CURSOR) {
853 		grid_view_get_cell(src->grid, src->cx, src->cy, &gc);
854 		gc.attr |= GRID_ATTR_REVERSE;
855 		screen_write_set_cursor(ctx, cx + (src->cx - px),
856 		    cy + (src->cy - py));
857 		screen_write_cell(ctx, &gc);
858 	}
859 }
860 
861 /* Set a mode. */
862 void
863 screen_write_mode_set(struct screen_write_ctx *ctx, int mode)
864 {
865 	struct screen	*s = ctx->s;
866 
867 	s->mode |= mode;
868 
869 	if (log_get_level() != 0)
870 		log_debug("%s: %s", __func__, screen_mode_to_string(mode));
871 }
872 
873 /* Clear a mode. */
874 void
875 screen_write_mode_clear(struct screen_write_ctx *ctx, int mode)
876 {
877 	struct screen	*s = ctx->s;
878 
879 	s->mode &= ~mode;
880 
881 	if (log_get_level() != 0)
882 		log_debug("%s: %s", __func__, screen_mode_to_string(mode));
883 }
884 
885 /* Cursor up by ny. */
886 void
887 screen_write_cursorup(struct screen_write_ctx *ctx, u_int ny)
888 {
889 	struct screen	*s = ctx->s;
890 	u_int		 cx = s->cx, cy = s->cy;
891 
892 	if (ny == 0)
893 		ny = 1;
894 
895 	if (cy < s->rupper) {
896 		/* Above region. */
897 		if (ny > cy)
898 			ny = cy;
899 	} else {
900 		/* Below region. */
901 		if (ny > cy - s->rupper)
902 			ny = cy - s->rupper;
903 	}
904 	if (cx == screen_size_x(s))
905 		cx--;
906 
907 	cy -= ny;
908 
909 	screen_write_set_cursor(ctx, cx, cy);
910 }
911 
912 /* Cursor down by ny. */
913 void
914 screen_write_cursordown(struct screen_write_ctx *ctx, u_int ny)
915 {
916 	struct screen	*s = ctx->s;
917 	u_int		 cx = s->cx, cy = s->cy;
918 
919 	if (ny == 0)
920 		ny = 1;
921 
922 	if (cy > s->rlower) {
923 		/* Below region. */
924 		if (ny > screen_size_y(s) - 1 - cy)
925 			ny = screen_size_y(s) - 1 - cy;
926 	} else {
927 		/* Above region. */
928 		if (ny > s->rlower - cy)
929 			ny = s->rlower - cy;
930 	}
931 	if (cx == screen_size_x(s))
932 	    cx--;
933 	else if (ny == 0)
934 		return;
935 
936 	cy += ny;
937 
938 	screen_write_set_cursor(ctx, cx, cy);
939 }
940 
941 /* Cursor right by nx. */
942 void
943 screen_write_cursorright(struct screen_write_ctx *ctx, u_int nx)
944 {
945 	struct screen	*s = ctx->s;
946 	u_int		 cx = s->cx, cy = s->cy;
947 
948 	if (nx == 0)
949 		nx = 1;
950 
951 	if (nx > screen_size_x(s) - 1 - cx)
952 		nx = screen_size_x(s) - 1 - cx;
953 	if (nx == 0)
954 		return;
955 
956 	cx += nx;
957 
958 	screen_write_set_cursor(ctx, cx, cy);
959 }
960 
961 /* Cursor left by nx. */
962 void
963 screen_write_cursorleft(struct screen_write_ctx *ctx, u_int nx)
964 {
965 	struct screen	*s = ctx->s;
966 	u_int		 cx = s->cx, cy = s->cy;
967 
968 	if (nx == 0)
969 		nx = 1;
970 
971 	if (nx > cx)
972 		nx = cx;
973 	if (nx == 0)
974 		return;
975 
976 	cx -= nx;
977 
978 	screen_write_set_cursor(ctx, cx, cy);
979 }
980 
981 /* Backspace; cursor left unless at start of wrapped line when can move up. */
982 void
983 screen_write_backspace(struct screen_write_ctx *ctx)
984 {
985 	struct screen		*s = ctx->s;
986 	struct grid_line	*gl;
987 	u_int			 cx = s->cx, cy = s->cy;
988 
989 	if (cx == 0) {
990 		if (cy == 0)
991 			return;
992 		gl = grid_get_line(s->grid, s->grid->hsize + cy - 1);
993 		if (gl->flags & GRID_LINE_WRAPPED) {
994 			cy--;
995 			cx = screen_size_x(s) - 1;
996 		}
997 	} else
998 		cx--;
999 
1000 	screen_write_set_cursor(ctx, cx, cy);
1001 }
1002 
1003 /* VT100 alignment test. */
1004 void
1005 screen_write_alignmenttest(struct screen_write_ctx *ctx)
1006 {
1007 	struct screen		*s = ctx->s;
1008 	struct tty_ctx	 	 ttyctx;
1009 	struct grid_cell       	 gc;
1010 	u_int			 xx, yy;
1011 
1012 	memcpy(&gc, &grid_default_cell, sizeof gc);
1013 	utf8_set(&gc.data, 'E');
1014 
1015 	for (yy = 0; yy < screen_size_y(s); yy++) {
1016 		for (xx = 0; xx < screen_size_x(s); xx++)
1017 			grid_view_set_cell(s->grid, xx, yy, &gc);
1018 	}
1019 
1020 	screen_write_set_cursor(ctx, 0, 0);
1021 
1022 	s->rupper = 0;
1023 	s->rlower = screen_size_y(s) - 1;
1024 
1025 	screen_write_initctx(ctx, &ttyctx, 1);
1026 
1027 	screen_write_collect_clear(ctx, 0, screen_size_y(s) - 1);
1028 	tty_write(tty_cmd_alignmenttest, &ttyctx);
1029 }
1030 
1031 /* Insert nx characters. */
1032 void
1033 screen_write_insertcharacter(struct screen_write_ctx *ctx, u_int nx, u_int bg)
1034 {
1035 	struct screen	*s = ctx->s;
1036 	struct tty_ctx	 ttyctx;
1037 
1038 	if (nx == 0)
1039 		nx = 1;
1040 
1041 	if (nx > screen_size_x(s) - s->cx)
1042 		nx = screen_size_x(s) - s->cx;
1043 	if (nx == 0)
1044 		return;
1045 
1046 	if (s->cx > screen_size_x(s) - 1)
1047 		return;
1048 
1049 	screen_write_initctx(ctx, &ttyctx, 0);
1050 	ttyctx.bg = bg;
1051 
1052 	grid_view_insert_cells(s->grid, s->cx, s->cy, nx, bg);
1053 
1054 	screen_write_collect_flush(ctx, 0, __func__);
1055 	ttyctx.num = nx;
1056 	tty_write(tty_cmd_insertcharacter, &ttyctx);
1057 }
1058 
1059 /* Delete nx characters. */
1060 void
1061 screen_write_deletecharacter(struct screen_write_ctx *ctx, u_int nx, u_int bg)
1062 {
1063 	struct screen	*s = ctx->s;
1064 	struct tty_ctx	 ttyctx;
1065 
1066 	if (nx == 0)
1067 		nx = 1;
1068 
1069 	if (nx > screen_size_x(s) - s->cx)
1070 		nx = screen_size_x(s) - s->cx;
1071 	if (nx == 0)
1072 		return;
1073 
1074 	if (s->cx > screen_size_x(s) - 1)
1075 		return;
1076 
1077 	screen_write_initctx(ctx, &ttyctx, 0);
1078 	ttyctx.bg = bg;
1079 
1080 	grid_view_delete_cells(s->grid, s->cx, s->cy, nx, bg);
1081 
1082 	screen_write_collect_flush(ctx, 0, __func__);
1083 	ttyctx.num = nx;
1084 	tty_write(tty_cmd_deletecharacter, &ttyctx);
1085 }
1086 
1087 /* Clear nx characters. */
1088 void
1089 screen_write_clearcharacter(struct screen_write_ctx *ctx, u_int nx, u_int bg)
1090 {
1091 	struct screen	*s = ctx->s;
1092 	struct tty_ctx	 ttyctx;
1093 
1094 	if (nx == 0)
1095 		nx = 1;
1096 
1097 	if (nx > screen_size_x(s) - s->cx)
1098 		nx = screen_size_x(s) - s->cx;
1099 	if (nx == 0)
1100 		return;
1101 
1102 	if (s->cx > screen_size_x(s) - 1)
1103 		return;
1104 
1105 	screen_write_initctx(ctx, &ttyctx, 0);
1106 	ttyctx.bg = bg;
1107 
1108 	grid_view_clear(s->grid, s->cx, s->cy, nx, 1, bg);
1109 
1110 	screen_write_collect_flush(ctx, 0, __func__);
1111 	ttyctx.num = nx;
1112 	tty_write(tty_cmd_clearcharacter, &ttyctx);
1113 }
1114 
1115 /* Insert ny lines. */
1116 void
1117 screen_write_insertline(struct screen_write_ctx *ctx, u_int ny, u_int bg)
1118 {
1119 	struct screen	*s = ctx->s;
1120 	struct grid	*gd = s->grid;
1121 	struct tty_ctx	 ttyctx;
1122 
1123 	if (ny == 0)
1124 		ny = 1;
1125 
1126 	if (s->cy < s->rupper || s->cy > s->rlower) {
1127 		if (ny > screen_size_y(s) - s->cy)
1128 			ny = screen_size_y(s) - s->cy;
1129 		if (ny == 0)
1130 			return;
1131 
1132 		screen_write_initctx(ctx, &ttyctx, 1);
1133 		ttyctx.bg = bg;
1134 
1135 		grid_view_insert_lines(gd, s->cy, ny, bg);
1136 
1137 		screen_write_collect_flush(ctx, 0, __func__);
1138 		ttyctx.num = ny;
1139 		tty_write(tty_cmd_insertline, &ttyctx);
1140 		return;
1141 	}
1142 
1143 	if (ny > s->rlower + 1 - s->cy)
1144 		ny = s->rlower + 1 - s->cy;
1145 	if (ny == 0)
1146 		return;
1147 
1148 	screen_write_initctx(ctx, &ttyctx, 1);
1149 	ttyctx.bg = bg;
1150 
1151 	if (s->cy < s->rupper || s->cy > s->rlower)
1152 		grid_view_insert_lines(gd, s->cy, ny, bg);
1153 	else
1154 		grid_view_insert_lines_region(gd, s->rlower, s->cy, ny, bg);
1155 
1156 	screen_write_collect_flush(ctx, 0, __func__);
1157 
1158 	ttyctx.num = ny;
1159 	tty_write(tty_cmd_insertline, &ttyctx);
1160 }
1161 
1162 /* Delete ny lines. */
1163 void
1164 screen_write_deleteline(struct screen_write_ctx *ctx, u_int ny, u_int bg)
1165 {
1166 	struct screen	*s = ctx->s;
1167 	struct grid	*gd = s->grid;
1168 	struct tty_ctx	 ttyctx;
1169 
1170 	if (ny == 0)
1171 		ny = 1;
1172 
1173 	if (s->cy < s->rupper || s->cy > s->rlower) {
1174 		if (ny > screen_size_y(s) - s->cy)
1175 			ny = screen_size_y(s) - s->cy;
1176 		if (ny == 0)
1177 			return;
1178 
1179 		screen_write_initctx(ctx, &ttyctx, 1);
1180 		ttyctx.bg = bg;
1181 
1182 		grid_view_delete_lines(gd, s->cy, ny, bg);
1183 
1184 		screen_write_collect_flush(ctx, 0, __func__);
1185 		ttyctx.num = ny;
1186 		tty_write(tty_cmd_deleteline, &ttyctx);
1187 		return;
1188 	}
1189 
1190 	if (ny > s->rlower + 1 - s->cy)
1191 		ny = s->rlower + 1 - s->cy;
1192 	if (ny == 0)
1193 		return;
1194 
1195 	screen_write_initctx(ctx, &ttyctx, 1);
1196 	ttyctx.bg = bg;
1197 
1198 	if (s->cy < s->rupper || s->cy > s->rlower)
1199 		grid_view_delete_lines(gd, s->cy, ny, bg);
1200 	else
1201 		grid_view_delete_lines_region(gd, s->rlower, s->cy, ny, bg);
1202 
1203 	screen_write_collect_flush(ctx, 0, __func__);
1204 	ttyctx.num = ny;
1205 	tty_write(tty_cmd_deleteline, &ttyctx);
1206 }
1207 
1208 /* Clear line at cursor. */
1209 void
1210 screen_write_clearline(struct screen_write_ctx *ctx, u_int bg)
1211 {
1212 	struct screen			*s = ctx->s;
1213 	struct grid_line		*gl;
1214 	u_int				 sx = screen_size_x(s);
1215 	struct screen_write_citem	*ci = ctx->item;
1216 
1217 	gl = grid_get_line(s->grid, s->grid->hsize + s->cy);
1218 	if (gl->cellsize == 0 && COLOUR_DEFAULT(bg))
1219 		return;
1220 
1221 	grid_view_clear(s->grid, 0, s->cy, sx, 1, bg);
1222 
1223 	screen_write_collect_clear(ctx, s->cy, 1);
1224 	ci->x = 0;
1225 	ci->used = sx;
1226 	ci->type = CLEAR;
1227 	ci->bg = bg;
1228 	TAILQ_INSERT_TAIL(&ctx->s->write_list[s->cy].items, ci, entry);
1229 	ctx->item = screen_write_get_citem();
1230 }
1231 
1232 /* Clear to end of line from cursor. */
1233 void
1234 screen_write_clearendofline(struct screen_write_ctx *ctx, u_int bg)
1235 {
1236 	struct screen			*s = ctx->s;
1237 	struct grid_line		*gl;
1238 	u_int				 sx = screen_size_x(s);
1239 	struct screen_write_citem	*ci = ctx->item, *before;
1240 
1241 	if (s->cx == 0) {
1242 		screen_write_clearline(ctx, bg);
1243 		return;
1244 	}
1245 
1246 	gl = grid_get_line(s->grid, s->grid->hsize + s->cy);
1247 	if (s->cx > sx - 1 || (s->cx >= gl->cellsize && COLOUR_DEFAULT(bg)))
1248 		return;
1249 
1250 	grid_view_clear(s->grid, s->cx, s->cy, sx - s->cx, 1, bg);
1251 
1252  	before = screen_write_collect_trim(ctx, s->cy, s->cx, sx - s->cx, NULL);
1253 	ci->x = s->cx;
1254 	ci->used = sx - s->cx;
1255 	ci->type = CLEAR;
1256 	ci->bg = bg;
1257 	if (before == NULL)
1258 		TAILQ_INSERT_TAIL(&ctx->s->write_list[s->cy].items, ci, entry);
1259 	else
1260 		TAILQ_INSERT_BEFORE(before, ci, entry);
1261 	ctx->item = screen_write_get_citem();
1262 }
1263 
1264 /* Clear to start of line from cursor. */
1265 void
1266 screen_write_clearstartofline(struct screen_write_ctx *ctx, u_int bg)
1267 {
1268 	struct screen			 *s = ctx->s;
1269 	u_int				 sx = screen_size_x(s);
1270 	struct screen_write_citem	*ci = ctx->item, *before;
1271 
1272 	if (s->cx >= sx - 1) {
1273 		screen_write_clearline(ctx, bg);
1274 		return;
1275 	}
1276 
1277 	if (s->cx > sx - 1)
1278 		grid_view_clear(s->grid, 0, s->cy, sx, 1, bg);
1279 	else
1280 		grid_view_clear(s->grid, 0, s->cy, s->cx + 1, 1, bg);
1281 
1282 	before = screen_write_collect_trim(ctx, s->cy, 0, s->cx + 1, NULL);
1283 	ci->x = 0;
1284 	ci->used = s->cx + 1;
1285 	ci->type = CLEAR;
1286 	ci->bg = bg;
1287 	if (before == NULL)
1288 		TAILQ_INSERT_TAIL(&ctx->s->write_list[s->cy].items, ci, entry);
1289 	else
1290 		TAILQ_INSERT_BEFORE(before, ci, entry);
1291 	ctx->item = screen_write_get_citem();
1292 }
1293 
1294 /* Move cursor to px,py. */
1295 void
1296 screen_write_cursormove(struct screen_write_ctx *ctx, int px, int py,
1297     int origin)
1298 {
1299 	struct screen	*s = ctx->s;
1300 
1301 	if (origin && py != -1 && (s->mode & MODE_ORIGIN)) {
1302 		if ((u_int)py > s->rlower - s->rupper)
1303 			py = s->rlower;
1304 		else
1305 			py += s->rupper;
1306 	}
1307 
1308 	if (px != -1 && (u_int)px > screen_size_x(s) - 1)
1309 		px = screen_size_x(s) - 1;
1310 	if (py != -1 && (u_int)py > screen_size_y(s) - 1)
1311 		py = screen_size_y(s) - 1;
1312 
1313 	log_debug("%s: from %u,%u to %u,%u", __func__, s->cx, s->cy, px, py);
1314 	screen_write_set_cursor(ctx, px, py);
1315 }
1316 
1317 /* Reverse index (up with scroll). */
1318 void
1319 screen_write_reverseindex(struct screen_write_ctx *ctx, u_int bg)
1320 {
1321 	struct screen	*s = ctx->s;
1322 	struct tty_ctx	 ttyctx;
1323 
1324 	if (s->cy == s->rupper) {
1325 		grid_view_scroll_region_down(s->grid, s->rupper, s->rlower, bg);
1326 		screen_write_collect_flush(ctx, 0, __func__);
1327 
1328 		screen_write_initctx(ctx, &ttyctx, 1);
1329 		ttyctx.bg = bg;
1330 
1331 		tty_write(tty_cmd_reverseindex, &ttyctx);
1332 	} else if (s->cy > 0)
1333 		screen_write_set_cursor(ctx, -1, s->cy - 1);
1334 
1335 }
1336 
1337 /* Set scroll region. */
1338 void
1339 screen_write_scrollregion(struct screen_write_ctx *ctx, u_int rupper,
1340     u_int rlower)
1341 {
1342 	struct screen	*s = ctx->s;
1343 
1344 	if (rupper > screen_size_y(s) - 1)
1345 		rupper = screen_size_y(s) - 1;
1346 	if (rlower > screen_size_y(s) - 1)
1347 		rlower = screen_size_y(s) - 1;
1348 	if (rupper >= rlower)	/* cannot be one line */
1349 		return;
1350 
1351 	screen_write_collect_flush(ctx, 0, __func__);
1352 
1353 	/* Cursor moves to top-left. */
1354 	screen_write_set_cursor(ctx, 0, 0);
1355 
1356 	s->rupper = rupper;
1357 	s->rlower = rlower;
1358 }
1359 
1360 /* Line feed. */
1361 void
1362 screen_write_linefeed(struct screen_write_ctx *ctx, int wrapped, u_int bg)
1363 {
1364 	struct screen		*s = ctx->s;
1365 	struct grid		*gd = s->grid;
1366 	struct grid_line	*gl;
1367 
1368 	gl = grid_get_line(gd, gd->hsize + s->cy);
1369 	if (wrapped)
1370 		gl->flags |= GRID_LINE_WRAPPED;
1371 
1372 	log_debug("%s: at %u,%u (region %u-%u)", __func__, s->cx, s->cy,
1373 	    s->rupper, s->rlower);
1374 
1375 	if (bg != ctx->bg) {
1376 		screen_write_collect_flush(ctx, 1, __func__);
1377 		ctx->bg = bg;
1378 	}
1379 
1380 	if (s->cy == s->rlower) {
1381 		grid_view_scroll_region_up(gd, s->rupper, s->rlower, bg);
1382 		screen_write_collect_scroll(ctx, bg);
1383 		ctx->scrolled++;
1384 	} else if (s->cy < screen_size_y(s) - 1)
1385 		screen_write_set_cursor(ctx, -1, s->cy + 1);
1386 }
1387 
1388 /* Scroll up. */
1389 void
1390 screen_write_scrollup(struct screen_write_ctx *ctx, u_int lines, u_int bg)
1391 {
1392 	struct screen	*s = ctx->s;
1393 	struct grid	*gd = s->grid;
1394 	u_int		 i;
1395 
1396 	if (lines == 0)
1397 		lines = 1;
1398 	else if (lines > s->rlower - s->rupper + 1)
1399 		lines = s->rlower - s->rupper + 1;
1400 
1401 	if (bg != ctx->bg) {
1402 		screen_write_collect_flush(ctx, 1, __func__);
1403 		ctx->bg = bg;
1404 	}
1405 
1406 	for (i = 0; i < lines; i++) {
1407 		grid_view_scroll_region_up(gd, s->rupper, s->rlower, bg);
1408 		screen_write_collect_scroll(ctx, bg);
1409 	}
1410 	ctx->scrolled += lines;
1411 }
1412 
1413 /* Scroll down. */
1414 void
1415 screen_write_scrolldown(struct screen_write_ctx *ctx, u_int lines, u_int bg)
1416 {
1417 	struct screen	*s = ctx->s;
1418 	struct grid	*gd = s->grid;
1419 	struct tty_ctx	 ttyctx;
1420 	u_int		 i;
1421 
1422 	screen_write_initctx(ctx, &ttyctx, 1);
1423 	ttyctx.bg = bg;
1424 
1425 	if (lines == 0)
1426 		lines = 1;
1427 	else if (lines > s->rlower - s->rupper + 1)
1428 		lines = s->rlower - s->rupper + 1;
1429 
1430 	for (i = 0; i < lines; i++)
1431 		grid_view_scroll_region_down(gd, s->rupper, s->rlower, bg);
1432 
1433 	screen_write_collect_flush(ctx, 0, __func__);
1434 	ttyctx.num = lines;
1435 	tty_write(tty_cmd_scrolldown, &ttyctx);
1436 }
1437 
1438 /* Carriage return (cursor to start of line). */
1439 void
1440 screen_write_carriagereturn(struct screen_write_ctx *ctx)
1441 {
1442 	screen_write_set_cursor(ctx, 0, -1);
1443 }
1444 
1445 /* Clear to end of screen from cursor. */
1446 void
1447 screen_write_clearendofscreen(struct screen_write_ctx *ctx, u_int bg)
1448 {
1449 	struct screen	*s = ctx->s;
1450 	struct grid	*gd = s->grid;
1451 	struct tty_ctx	 ttyctx;
1452 	u_int		 sx = screen_size_x(s), sy = screen_size_y(s);
1453 
1454 	screen_write_initctx(ctx, &ttyctx, 1);
1455 	ttyctx.bg = bg;
1456 
1457 	/* Scroll into history if it is enabled and clearing entire screen. */
1458 	if (s->cx == 0 &&
1459 	    s->cy == 0 &&
1460 	    (gd->flags & GRID_HISTORY) &&
1461 	    ctx->wp != NULL &&
1462 	    options_get_number(ctx->wp->options, "scroll-on-clear"))
1463 		grid_view_clear_history(gd, bg);
1464 	else {
1465 		if (s->cx <= sx - 1)
1466 			grid_view_clear(gd, s->cx, s->cy, sx - s->cx, 1, bg);
1467 		grid_view_clear(gd, 0, s->cy + 1, sx, sy - (s->cy + 1), bg);
1468 	}
1469 
1470 	screen_write_collect_clear(ctx, s->cy + 1, sy - (s->cy + 1));
1471 	screen_write_collect_flush(ctx, 0, __func__);
1472 	tty_write(tty_cmd_clearendofscreen, &ttyctx);
1473 }
1474 
1475 /* Clear to start of screen. */
1476 void
1477 screen_write_clearstartofscreen(struct screen_write_ctx *ctx, u_int bg)
1478 {
1479 	struct screen	*s = ctx->s;
1480 	struct tty_ctx	 ttyctx;
1481 	u_int		 sx = screen_size_x(s);
1482 
1483 	screen_write_initctx(ctx, &ttyctx, 1);
1484 	ttyctx.bg = bg;
1485 
1486 	if (s->cy > 0)
1487 		grid_view_clear(s->grid, 0, 0, sx, s->cy, bg);
1488 	if (s->cx > sx - 1)
1489 		grid_view_clear(s->grid, 0, s->cy, sx, 1, bg);
1490 	else
1491 		grid_view_clear(s->grid, 0, s->cy, s->cx + 1, 1, bg);
1492 
1493 	screen_write_collect_clear(ctx, 0, s->cy);
1494 	screen_write_collect_flush(ctx, 0, __func__);
1495 	tty_write(tty_cmd_clearstartofscreen, &ttyctx);
1496 }
1497 
1498 /* Clear entire screen. */
1499 void
1500 screen_write_clearscreen(struct screen_write_ctx *ctx, u_int bg)
1501 {
1502 	struct screen	*s = ctx->s;
1503 	struct tty_ctx	 ttyctx;
1504 	u_int		 sx = screen_size_x(s), sy = screen_size_y(s);
1505 
1506 	screen_write_initctx(ctx, &ttyctx, 1);
1507 	ttyctx.bg = bg;
1508 
1509 	/* Scroll into history if it is enabled. */
1510 	if ((s->grid->flags & GRID_HISTORY) &&
1511 	    ctx->wp != NULL &&
1512 	    options_get_number(ctx->wp->options, "scroll-on-clear"))
1513 		grid_view_clear_history(s->grid, bg);
1514 	else
1515 		grid_view_clear(s->grid, 0, 0, sx, sy, bg);
1516 
1517 	screen_write_collect_clear(ctx, 0, sy);
1518 	tty_write(tty_cmd_clearscreen, &ttyctx);
1519 }
1520 
1521 /* Clear entire history. */
1522 void
1523 screen_write_clearhistory(struct screen_write_ctx *ctx)
1524 {
1525 	grid_clear_history(ctx->s->grid);
1526 }
1527 
1528 /* Force a full redraw. */
1529 void
1530 screen_write_fullredraw(struct screen_write_ctx *ctx)
1531 {
1532 	struct tty_ctx	 ttyctx;
1533 
1534 	screen_write_collect_flush(ctx, 0, __func__);
1535 
1536 	screen_write_initctx(ctx, &ttyctx, 1);
1537 	if (ttyctx.redraw_cb != NULL)
1538 		ttyctx.redraw_cb(&ttyctx);
1539 }
1540 
1541 /* Trim collected items. */
1542 static struct screen_write_citem *
1543 screen_write_collect_trim(struct screen_write_ctx *ctx, u_int y, u_int x,
1544     u_int used, int *wrapped)
1545 {
1546 	struct screen_write_cline	*cl = &ctx->s->write_list[y];
1547 	struct screen_write_citem	*ci, *ci2, *tmp, *before = NULL;
1548 	u_int				 sx = x, ex = x + used - 1;
1549 	u_int				 csx, cex;
1550 
1551 	if (TAILQ_EMPTY(&cl->items))
1552 		return (NULL);
1553 	TAILQ_FOREACH_SAFE(ci, &cl->items, entry, tmp) {
1554 		csx = ci->x;
1555 		cex = ci->x + ci->used - 1;
1556 
1557 		/* Item is entirely before. */
1558 		if (cex < sx) {
1559 			log_debug("%s: %p %u-%u before %u-%u", __func__, ci,
1560 			    csx, cex, sx, ex);
1561 			continue;
1562 		}
1563 
1564 		/* Item is entirely after. */
1565 		if (csx > ex) {
1566 			log_debug("%s: %p %u-%u after %u-%u", __func__, ci,
1567 			    csx, cex, sx, ex);
1568 			before = ci;
1569 			break;
1570 		}
1571 
1572 		/* Item is entirely inside. */
1573 		if (csx >= sx && cex <= ex) {
1574 			log_debug("%s: %p %u-%u inside %u-%u", __func__, ci,
1575 			    csx, cex, sx, ex);
1576 			TAILQ_REMOVE(&cl->items, ci, entry);
1577 			screen_write_free_citem(ci);
1578 			if (csx == 0 && ci->wrapped && wrapped != NULL)
1579 				*wrapped = 1;
1580 			continue;
1581 		}
1582 
1583 		/* Item under the start. */
1584 		if (csx < sx && cex >= sx && cex <= ex) {
1585 			log_debug("%s: %p %u-%u start %u-%u", __func__, ci,
1586 			    csx, cex, sx, ex);
1587 			ci->used = sx - csx;
1588 			log_debug("%s: %p now %u-%u", __func__, ci, ci->x,
1589 			    ci->x + ci->used + 1);
1590 			continue;
1591 		}
1592 
1593 		/* Item covers the end. */
1594 		if (cex > ex && csx >= sx && csx <= ex) {
1595 			log_debug("%s: %p %u-%u end %u-%u", __func__, ci,
1596 			    csx, cex, sx, ex);
1597 			ci->x = ex + 1;
1598 			ci->used = cex - ex;
1599 			log_debug("%s: %p now %u-%u", __func__, ci, ci->x,
1600 			    ci->x + ci->used + 1);
1601 			before = ci;
1602 			break;
1603 		}
1604 
1605 		/* Item must cover both sides. */
1606 		log_debug("%s: %p %u-%u under %u-%u", __func__, ci,
1607 		    csx, cex, sx, ex);
1608 		ci2 = screen_write_get_citem();
1609 		ci2->type = ci->type;
1610 		ci2->bg = ci->bg;
1611 		memcpy(&ci2->gc, &ci->gc, sizeof ci2->gc);
1612 		TAILQ_INSERT_AFTER(&cl->items, ci, ci2, entry);
1613 
1614 		ci->used = sx - csx;
1615 		ci2->x = ex + 1;
1616 		ci2->used = cex - ex;
1617 
1618 		log_debug("%s: %p now %u-%u (%p) and %u-%u (%p)", __func__, ci,
1619 		    ci->x, ci->x + ci->used - 1, ci, ci2->x,
1620 		    ci2->x + ci2->used - 1, ci2);
1621 		before = ci2;
1622 		break;
1623 	}
1624 	return (before);
1625 }
1626 
1627 /* Clear collected lines. */
1628 static void
1629 screen_write_collect_clear(struct screen_write_ctx *ctx, u_int y, u_int n)
1630 {
1631 	struct screen_write_cline	*cl;
1632 	u_int				 i;
1633 
1634 	for (i = y; i < y + n; i++) {
1635 		cl = &ctx->s->write_list[i];
1636 		TAILQ_CONCAT(&screen_write_citem_freelist, &cl->items, entry);
1637 	}
1638 }
1639 
1640 /* Scroll collected lines up. */
1641 static void
1642 screen_write_collect_scroll(struct screen_write_ctx *ctx, u_int bg)
1643 {
1644 	struct screen			*s = ctx->s;
1645 	struct screen_write_cline	*cl;
1646 	u_int				 y;
1647 	char				*saved;
1648 	struct screen_write_citem	*ci;
1649 
1650 	log_debug("%s: at %u,%u (region %u-%u)", __func__, s->cx, s->cy,
1651 	    s->rupper, s->rlower);
1652 
1653 	screen_write_collect_clear(ctx, s->rupper, 1);
1654 	saved = ctx->s->write_list[s->rupper].data;
1655 	for (y = s->rupper; y < s->rlower; y++) {
1656 		cl = &ctx->s->write_list[y + 1];
1657 		TAILQ_CONCAT(&ctx->s->write_list[y].items, &cl->items, entry);
1658 		ctx->s->write_list[y].data = cl->data;
1659 	}
1660 	ctx->s->write_list[s->rlower].data = saved;
1661 
1662 	ci = screen_write_get_citem();
1663 	ci->x = 0;
1664 	ci->used = screen_size_x(s);
1665 	ci->type = CLEAR;
1666 	ci->bg = bg;
1667 	TAILQ_INSERT_TAIL(&ctx->s->write_list[s->rlower].items, ci, entry);
1668 }
1669 
1670 /* Flush collected lines. */
1671 static void
1672 screen_write_collect_flush(struct screen_write_ctx *ctx, int scroll_only,
1673     const char *from)
1674 {
1675 	struct screen			*s = ctx->s;
1676 	struct screen_write_citem	*ci, *tmp;
1677 	struct screen_write_cline	*cl;
1678 	u_int				 y, cx, cy, last, items = 0;
1679 	struct tty_ctx			 ttyctx;
1680 
1681 	if (ctx->scrolled != 0) {
1682 		log_debug("%s: scrolled %u (region %u-%u)", __func__,
1683 		    ctx->scrolled, s->rupper, s->rlower);
1684 		if (ctx->scrolled > s->rlower - s->rupper + 1)
1685 			ctx->scrolled = s->rlower - s->rupper + 1;
1686 
1687 		screen_write_initctx(ctx, &ttyctx, 1);
1688 		ttyctx.num = ctx->scrolled;
1689 		ttyctx.bg = ctx->bg;
1690 		tty_write(tty_cmd_scrollup, &ttyctx);
1691 	}
1692 	ctx->scrolled = 0;
1693 	ctx->bg = 8;
1694 
1695 	if (scroll_only)
1696 		return;
1697 
1698 	cx = s->cx; cy = s->cy;
1699 	for (y = 0; y < screen_size_y(s); y++) {
1700 		cl = &ctx->s->write_list[y];
1701 		last = UINT_MAX;
1702 		TAILQ_FOREACH_SAFE(ci, &cl->items, entry, tmp) {
1703 			if (last != UINT_MAX && ci->x <= last) {
1704 				fatalx("collect list not in order: %u <= %u",
1705 				    ci->x, last);
1706 			}
1707 			screen_write_set_cursor(ctx, ci->x, y);
1708 			if (ci->type == CLEAR) {
1709 				screen_write_initctx(ctx, &ttyctx, 1);
1710 				ttyctx.bg = ci->bg;
1711 				ttyctx.num = ci->used;
1712 				tty_write(tty_cmd_clearcharacter, &ttyctx);
1713 			} else {
1714 				screen_write_initctx(ctx, &ttyctx, 0);
1715 				ttyctx.cell = &ci->gc;
1716 				ttyctx.wrapped = ci->wrapped;
1717 				ttyctx.ptr = cl->data + ci->x;
1718 				ttyctx.num = ci->used;
1719 				tty_write(tty_cmd_cells, &ttyctx);
1720 			}
1721 			items++;
1722 
1723 			TAILQ_REMOVE(&cl->items, ci, entry);
1724 			screen_write_free_citem(ci);
1725 			last = ci->x;
1726 		}
1727 	}
1728 	s->cx = cx; s->cy = cy;
1729 
1730 	log_debug("%s: flushed %u items (%s)", __func__, items, from);
1731 }
1732 
1733 /* Finish and store collected cells. */
1734 void
1735 screen_write_collect_end(struct screen_write_ctx *ctx)
1736 {
1737 	struct screen			*s = ctx->s;
1738 	struct screen_write_citem	*ci = ctx->item, *before;
1739 	struct screen_write_cline	*cl = &s->write_list[s->cy];
1740 	struct grid_cell		 gc;
1741 	u_int				 xx;
1742 	int				 wrapped = ci->wrapped;
1743 
1744 	if (ci->used == 0)
1745 		return;
1746 
1747 	before = screen_write_collect_trim(ctx, s->cy, s->cx, ci->used,
1748 	    &wrapped);
1749 	ci->x = s->cx;
1750 	ci->wrapped = wrapped;
1751 	if (before == NULL)
1752 		TAILQ_INSERT_TAIL(&cl->items, ci, entry);
1753 	else
1754 		TAILQ_INSERT_BEFORE(before, ci, entry);
1755 	ctx->item = screen_write_get_citem();
1756 
1757 	log_debug("%s: %u %.*s (at %u,%u)", __func__, ci->used,
1758 	    (int)ci->used, cl->data + ci->x, s->cx, s->cy);
1759 
1760 	if (s->cx != 0) {
1761 		for (xx = s->cx; xx > 0; xx--) {
1762 			grid_view_get_cell(s->grid, xx, s->cy, &gc);
1763 			if (~gc.flags & GRID_FLAG_PADDING)
1764 				break;
1765 			grid_view_set_cell(s->grid, xx, s->cy,
1766 			    &grid_default_cell);
1767 		}
1768 		if (gc.data.width > 1) {
1769 			grid_view_set_cell(s->grid, xx, s->cy,
1770 			    &grid_default_cell);
1771 		}
1772 	}
1773 
1774 	grid_view_set_cells(s->grid, s->cx, s->cy, &ci->gc, cl->data + ci->x,
1775 	    ci->used);
1776 	screen_write_set_cursor(ctx, s->cx + ci->used, -1);
1777 
1778 	for (xx = s->cx; xx < screen_size_x(s); xx++) {
1779 		grid_view_get_cell(s->grid, xx, s->cy, &gc);
1780 		if (~gc.flags & GRID_FLAG_PADDING)
1781 			break;
1782 		grid_view_set_cell(s->grid, xx, s->cy, &grid_default_cell);
1783 	}
1784 }
1785 
1786 /* Write cell data, collecting if necessary. */
1787 void
1788 screen_write_collect_add(struct screen_write_ctx *ctx,
1789     const struct grid_cell *gc)
1790 {
1791 	struct screen			*s = ctx->s;
1792 	struct screen_write_citem	*ci;
1793 	u_int				 sx = screen_size_x(s);
1794 	int				 collect;
1795 
1796 	/*
1797 	 * Don't need to check that the attributes and whatnot are still the
1798 	 * same - input_parse will end the collection when anything that isn't
1799 	 * a plain character is encountered.
1800 	 */
1801 
1802 	collect = 1;
1803 	if (gc->data.width != 1 || gc->data.size != 1 || *gc->data.data >= 0x7f)
1804 		collect = 0;
1805 	else if (gc->attr & GRID_ATTR_CHARSET)
1806 		collect = 0;
1807 	else if (~s->mode & MODE_WRAP)
1808 		collect = 0;
1809 	else if (s->mode & MODE_INSERT)
1810 		collect = 0;
1811 	else if (s->sel != NULL)
1812 		collect = 0;
1813 	if (!collect) {
1814 		screen_write_collect_end(ctx);
1815 		screen_write_collect_flush(ctx, 0, __func__);
1816 		screen_write_cell(ctx, gc);
1817 		return;
1818 	}
1819 
1820 	if (s->cx > sx - 1 || ctx->item->used > sx - 1 - s->cx)
1821 		screen_write_collect_end(ctx);
1822 	ci = ctx->item; /* may have changed */
1823 
1824 	if (s->cx > sx - 1) {
1825 		log_debug("%s: wrapped at %u,%u", __func__, s->cx, s->cy);
1826 		ci->wrapped = 1;
1827 		screen_write_linefeed(ctx, 1, 8);
1828 		screen_write_set_cursor(ctx, 0, -1);
1829 	}
1830 
1831 	if (ci->used == 0)
1832 		memcpy(&ci->gc, gc, sizeof ci->gc);
1833 	if (ctx->s->write_list[s->cy].data == NULL)
1834 		ctx->s->write_list[s->cy].data = xmalloc(screen_size_x(ctx->s));
1835 	ctx->s->write_list[s->cy].data[s->cx + ci->used++] = gc->data.data[0];
1836 }
1837 
1838 /* Write cell data. */
1839 void
1840 screen_write_cell(struct screen_write_ctx *ctx, const struct grid_cell *gc)
1841 {
1842 	struct screen		*s = ctx->s;
1843 	struct grid		*gd = s->grid;
1844 	const struct utf8_data	*ud = &gc->data;
1845 	struct grid_line	*gl;
1846 	struct grid_cell_entry	*gce;
1847 	struct grid_cell 	 tmp_gc, now_gc;
1848 	struct tty_ctx		 ttyctx;
1849 	u_int			 sx = screen_size_x(s), sy = screen_size_y(s);
1850 	u_int		 	 width = ud->width, xx, not_wrap;
1851 	int			 selected, skip = 1;
1852 
1853 	/* Ignore padding cells. */
1854 	if (gc->flags & GRID_FLAG_PADDING)
1855 		return;
1856 
1857 	/* Get the previous cell to check for combining. */
1858 	if (screen_write_combine(ctx, gc) != 0)
1859 		return;
1860 
1861 	/* Flush any existing scrolling. */
1862 	screen_write_collect_flush(ctx, 1, __func__);
1863 
1864 	/* If this character doesn't fit, ignore it. */
1865 	if ((~s->mode & MODE_WRAP) &&
1866 	    width > 1 &&
1867 	    (width > sx || (s->cx != sx && s->cx > sx - width)))
1868 		return;
1869 
1870 	/* If in insert mode, make space for the cells. */
1871 	if (s->mode & MODE_INSERT) {
1872 		grid_view_insert_cells(s->grid, s->cx, s->cy, width, 8);
1873 		skip = 0;
1874 	}
1875 
1876 	/* Check this will fit on the current line and wrap if not. */
1877 	if ((s->mode & MODE_WRAP) && s->cx > sx - width) {
1878 		log_debug("%s: wrapped at %u,%u", __func__, s->cx, s->cy);
1879 		screen_write_linefeed(ctx, 1, 8);
1880 		screen_write_set_cursor(ctx, 0, -1);
1881 		screen_write_collect_flush(ctx, 1, __func__);
1882 	}
1883 
1884 	/* Sanity check cursor position. */
1885 	if (s->cx > sx - width || s->cy > sy - 1)
1886 		return;
1887 	screen_write_initctx(ctx, &ttyctx, 0);
1888 
1889 	/* Handle overwriting of UTF-8 characters. */
1890 	gl = grid_get_line(s->grid, s->grid->hsize + s->cy);
1891 	if (gl->flags & GRID_LINE_EXTENDED) {
1892 		grid_view_get_cell(gd, s->cx, s->cy, &now_gc);
1893 		if (screen_write_overwrite(ctx, &now_gc, width))
1894 			skip = 0;
1895 	}
1896 
1897 	/*
1898 	 * If the new character is UTF-8 wide, fill in padding cells. Have
1899 	 * already ensured there is enough room.
1900 	 */
1901 	for (xx = s->cx + 1; xx < s->cx + width; xx++) {
1902 		log_debug("%s: new padding at %u,%u", __func__, xx, s->cy);
1903 		grid_view_set_padding(gd, xx, s->cy);
1904 		skip = 0;
1905 	}
1906 
1907 	/* If no change, do not draw. */
1908 	if (skip) {
1909 		if (s->cx >= gl->cellsize)
1910 			skip = grid_cells_equal(gc, &grid_default_cell);
1911 		else {
1912 			gce = &gl->celldata[s->cx];
1913 			if (gce->flags & GRID_FLAG_EXTENDED)
1914 				skip = 0;
1915 			else if (gc->flags != gce->flags)
1916 				skip = 0;
1917 			else if (gc->attr != gce->data.attr)
1918 				skip = 0;
1919 			else if (gc->fg != gce->data.fg)
1920 				skip = 0;
1921 			else if (gc->bg != gce->data.bg)
1922 				skip = 0;
1923 			else if (gc->data.width != 1)
1924 				skip = 0;
1925 			else if (gc->data.size != 1)
1926 				skip = 0;
1927 			else if (gce->data.data != gc->data.data[0])
1928 				skip = 0;
1929 		}
1930 	}
1931 
1932 	/* Update the selected flag and set the cell. */
1933 	selected = screen_check_selection(s, s->cx, s->cy);
1934 	if (selected && (~gc->flags & GRID_FLAG_SELECTED)) {
1935 		memcpy(&tmp_gc, gc, sizeof tmp_gc);
1936 		tmp_gc.flags |= GRID_FLAG_SELECTED;
1937 		grid_view_set_cell(gd, s->cx, s->cy, &tmp_gc);
1938 	} else if (!selected && (gc->flags & GRID_FLAG_SELECTED)) {
1939 		memcpy(&tmp_gc, gc, sizeof tmp_gc);
1940 		tmp_gc.flags &= ~GRID_FLAG_SELECTED;
1941 		grid_view_set_cell(gd, s->cx, s->cy, &tmp_gc);
1942 	} else if (!skip)
1943 		grid_view_set_cell(gd, s->cx, s->cy, gc);
1944 	if (selected)
1945 		skip = 0;
1946 
1947 	/*
1948 	 * Move the cursor. If not wrapping, stick at the last character and
1949 	 * replace it.
1950 	 */
1951 	not_wrap = !(s->mode & MODE_WRAP);
1952 	if (s->cx <= sx - not_wrap - width)
1953 		screen_write_set_cursor(ctx, s->cx + width, -1);
1954 	else
1955 		screen_write_set_cursor(ctx,  sx - not_wrap, -1);
1956 
1957 	/* Create space for character in insert mode. */
1958 	if (s->mode & MODE_INSERT) {
1959 		screen_write_collect_flush(ctx, 0, __func__);
1960 		ttyctx.num = width;
1961 		tty_write(tty_cmd_insertcharacter, &ttyctx);
1962 	}
1963 
1964 	/* Write to the screen. */
1965 	if (!skip) {
1966 		if (selected) {
1967 			screen_select_cell(s, &tmp_gc, gc);
1968 			ttyctx.cell = &tmp_gc;
1969 		} else
1970 			ttyctx.cell = gc;
1971 		tty_write(tty_cmd_cell, &ttyctx);
1972 	}
1973 }
1974 
1975 /* Combine a UTF-8 zero-width character onto the previous if necessary. */
1976 static int
1977 screen_write_combine(struct screen_write_ctx *ctx, const struct grid_cell *gc)
1978 {
1979 	struct screen		*s = ctx->s;
1980 	struct grid		*gd = s->grid;
1981 	const struct utf8_data	*ud = &gc->data;
1982 	u_int			 n, cx = s->cx, cy = s->cy;
1983 	struct grid_cell	 last;
1984 	struct tty_ctx		 ttyctx;
1985 	int			 force_wide = 0, zero_width = 0;
1986 
1987 	/*
1988 	 * Is this character which makes no sense without being combined? If
1989 	 * this is true then flag it here and discard the character (return 1)
1990 	 * if we cannot combine it.
1991 	 */
1992 	if (utf8_is_zwj(ud))
1993 		zero_width = 1;
1994 	else if (utf8_is_vs(ud))
1995 		zero_width = force_wide = 1;
1996 	else if (ud->width == 0)
1997 		zero_width = 1;
1998 
1999 	/* Cannot combine empty character or at left. */
2000 	if (ud->size < 2 || cx == 0)
2001 		return (zero_width);
2002 	log_debug("%s: character %.*s at %u,%u (width %u)", __func__,
2003 	    (int)ud->size, ud->data, cx, cy, ud->width);
2004 
2005 	/* Find the cell to combine with. */
2006 	n = 1;
2007 	grid_view_get_cell(gd, cx - n, cy, &last);
2008 	if (cx != 1 && (last.flags & GRID_FLAG_PADDING)) {
2009 		n = 2;
2010 		grid_view_get_cell(gd, cx - n, cy, &last);
2011 	}
2012 	if (n != last.data.width || (last.flags & GRID_FLAG_PADDING))
2013 		return (zero_width);
2014 
2015 	/*
2016 	 * Check if we need to combine characters. This could be zero width
2017 	 * (set above), a modifier character (with an existing Unicode
2018 	 * character) or a previous ZWJ.
2019 	 */
2020 	if (!zero_width) {
2021 		if (utf8_is_modifier(ud)) {
2022 			if (last.data.size < 2)
2023 				return (0);
2024 			force_wide = 1;
2025 		} else if (!utf8_has_zwj(&last.data))
2026 			return (0);
2027 	}
2028 
2029 	/* Check if this combined character would be too long. */
2030 	if (last.data.size + ud->size > sizeof last.data.data)
2031 		return (0);
2032 
2033 	/* Combining; flush any pending output. */
2034 	screen_write_collect_flush(ctx, 0, __func__);
2035 
2036 	log_debug("%s: %.*s -> %.*s at %u,%u (offset %u, width %u)", __func__,
2037 	    (int)ud->size, ud->data, (int)last.data.size, last.data.data,
2038 	    cx - n, cy, n, last.data.width);
2039 
2040 	/* Append the data. */
2041 	memcpy(last.data.data + last.data.size, ud->data, ud->size);
2042 	last.data.size += ud->size;
2043 
2044 	/* Force the width to 2 for modifiers and variation selector. */
2045 	if (last.data.width == 1 && force_wide) {
2046 		last.data.width = 2;
2047 		n = 2;
2048 		cx++;
2049 	} else
2050 		force_wide = 0;
2051 
2052 	/* Set the new cell. */
2053 	grid_view_set_cell(gd, cx - n, cy, &last);
2054 	if (force_wide)
2055 		grid_view_set_padding(gd, cx - 1, cy);
2056 
2057 	/*
2058 	 * Redraw the combined cell. If forcing the cell to width 2, reset the
2059 	 * cached cursor position in the tty, since we don't really know
2060 	 * whether the terminal thought the character was width 1 or width 2
2061 	 * and what it is going to do now.
2062 	 */
2063 	screen_write_set_cursor(ctx, cx - n, cy);
2064 	screen_write_initctx(ctx, &ttyctx, 0);
2065 	ttyctx.cell = &last;
2066 	ttyctx.num = force_wide; /* reset cached cursor position */
2067 	tty_write(tty_cmd_cell, &ttyctx);
2068 	screen_write_set_cursor(ctx, cx, cy);
2069 
2070 	return (1);
2071 }
2072 
2073 /*
2074  * UTF-8 wide characters are a bit of an annoyance. They take up more than one
2075  * cell on the screen, so following cells must not be drawn by marking them as
2076  * padding.
2077  *
2078  * So far, so good. The problem is, when overwriting a padding cell, or a UTF-8
2079  * character, it is necessary to also overwrite any other cells which covered
2080  * by the same character.
2081  */
2082 static int
2083 screen_write_overwrite(struct screen_write_ctx *ctx, struct grid_cell *gc,
2084     u_int width)
2085 {
2086 	struct screen		*s = ctx->s;
2087 	struct grid		*gd = s->grid;
2088 	struct grid_cell	 tmp_gc;
2089 	u_int			 xx;
2090 	int			 done = 0;
2091 
2092 	if (gc->flags & GRID_FLAG_PADDING) {
2093 		/*
2094 		 * A padding cell, so clear any following and leading padding
2095 		 * cells back to the character. Don't overwrite the current
2096 		 * cell as that happens later anyway.
2097 		 */
2098 		xx = s->cx + 1;
2099 		while (--xx > 0) {
2100 			grid_view_get_cell(gd, xx, s->cy, &tmp_gc);
2101 			if (~tmp_gc.flags & GRID_FLAG_PADDING)
2102 				break;
2103 			log_debug("%s: padding at %u,%u", __func__, xx, s->cy);
2104 			grid_view_set_cell(gd, xx, s->cy, &grid_default_cell);
2105 		}
2106 
2107 		/* Overwrite the character at the start of this padding. */
2108 		log_debug("%s: character at %u,%u", __func__, xx, s->cy);
2109 		grid_view_set_cell(gd, xx, s->cy, &grid_default_cell);
2110 		done = 1;
2111 	}
2112 
2113 	/*
2114 	 * Overwrite any padding cells that belong to any UTF-8 characters
2115 	 * we'll be overwriting with the current character.
2116 	 */
2117 	if (width != 1 ||
2118 	    gc->data.width != 1 ||
2119 	    gc->flags & GRID_FLAG_PADDING) {
2120 		xx = s->cx + width - 1;
2121 		while (++xx < screen_size_x(s)) {
2122 			grid_view_get_cell(gd, xx, s->cy, &tmp_gc);
2123 			if (~tmp_gc.flags & GRID_FLAG_PADDING)
2124 				break;
2125 			log_debug("%s: overwrite at %u,%u", __func__, xx,
2126 			    s->cy);
2127 			grid_view_set_cell(gd, xx, s->cy, &grid_default_cell);
2128 			done = 1;
2129 		}
2130 	}
2131 
2132 	return (done);
2133 }
2134 
2135 /* Set external clipboard. */
2136 void
2137 screen_write_setselection(struct screen_write_ctx *ctx, const char *flags,
2138     u_char *str, u_int len)
2139 {
2140 	struct tty_ctx	ttyctx;
2141 
2142 	screen_write_initctx(ctx, &ttyctx, 0);
2143 	ttyctx.ptr = str;
2144 	ttyctx.ptr2 = (void *)flags;
2145 	ttyctx.num = len;
2146 
2147 	tty_write(tty_cmd_setselection, &ttyctx);
2148 }
2149 
2150 /* Write unmodified string. */
2151 void
2152 screen_write_rawstring(struct screen_write_ctx *ctx, u_char *str, u_int len,
2153     int allow_invisible_panes)
2154 {
2155 	struct tty_ctx	ttyctx;
2156 
2157 	screen_write_initctx(ctx, &ttyctx, 0);
2158 	ttyctx.ptr = str;
2159 	ttyctx.num = len;
2160 	ttyctx.allow_invisible_panes = allow_invisible_panes;
2161 
2162 	tty_write(tty_cmd_rawstring, &ttyctx);
2163 }
2164 
2165 /* Turn alternate screen on. */
2166 void
2167 screen_write_alternateon(struct screen_write_ctx *ctx, struct grid_cell *gc,
2168     int cursor)
2169 {
2170 	struct tty_ctx		 ttyctx;
2171 	struct window_pane	*wp = ctx->wp;
2172 
2173 	if (wp != NULL && !options_get_number(wp->options, "alternate-screen"))
2174 		return;
2175 
2176 	screen_write_collect_flush(ctx, 0, __func__);
2177 	screen_alternate_on(ctx->s, gc, cursor);
2178 
2179 	screen_write_initctx(ctx, &ttyctx, 1);
2180 	if (ttyctx.redraw_cb != NULL)
2181 		ttyctx.redraw_cb(&ttyctx);
2182 }
2183 
2184 /* Turn alternate screen off. */
2185 void
2186 screen_write_alternateoff(struct screen_write_ctx *ctx, struct grid_cell *gc,
2187     int cursor)
2188 {
2189 	struct tty_ctx		 ttyctx;
2190 	struct window_pane	*wp = ctx->wp;
2191 
2192 	if (wp != NULL && !options_get_number(wp->options, "alternate-screen"))
2193 		return;
2194 
2195 	screen_write_collect_flush(ctx, 0, __func__);
2196 	screen_alternate_off(ctx->s, gc, cursor);
2197 
2198 	screen_write_initctx(ctx, &ttyctx, 1);
2199 	if (ttyctx.redraw_cb != NULL)
2200 		ttyctx.redraw_cb(&ttyctx);
2201 }
2202