xref: /openbsd-src/usr.bin/tmux/grid.c (revision d1df930ffab53da22f3324c32bed7ac5709915e6)
1 /* $OpenBSD: grid.c,v 1.86 2018/07/11 06:51:39 nicm Exp $ */
2 
3 /*
4  * Copyright (c) 2008 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 /*
27  * Grid data. This is the basic data structure that represents what is shown on
28  * screen.
29  *
30  * A grid is a grid of cells (struct grid_cell). Lines are not allocated until
31  * cells in that line are written to. The grid is split into history and
32  * viewable data with the history starting at row (line) 0 and extending to
33  * (hsize - 1); from hsize to hsize + (sy - 1) is the viewable data. All
34  * functions in this file work on absolute coordinates, grid-view.c has
35  * functions which work on the screen data.
36  */
37 
38 /* Default grid cell data. */
39 const struct grid_cell grid_default_cell = {
40 	0, 0, 8, 8, { { ' ' }, 0, 1, 1 }
41 };
42 static const struct grid_cell_entry grid_default_entry = {
43 	0, { .data = { 0, 8, 8, ' ' } }
44 };
45 
46 static void	grid_empty_line(struct grid *, u_int, u_int);
47 
48 /* Store cell in entry. */
49 static void
50 grid_store_cell(struct grid_cell_entry *gce, const struct grid_cell *gc,
51     u_char c)
52 {
53 	gce->flags = gc->flags;
54 
55 	gce->data.fg = gc->fg & 0xff;
56 	if (gc->fg & COLOUR_FLAG_256)
57 		gce->flags |= GRID_FLAG_FG256;
58 
59 	gce->data.bg = gc->bg & 0xff;
60 	if (gc->bg & COLOUR_FLAG_256)
61 		gce->flags |= GRID_FLAG_BG256;
62 
63 	gce->data.attr = gc->attr;
64 	gce->data.data = c;
65 }
66 
67 /* Check if a cell should be extended. */
68 static int
69 grid_need_extended_cell(const struct grid_cell_entry *gce,
70     const struct grid_cell *gc)
71 {
72 	if (gce->flags & GRID_FLAG_EXTENDED)
73 		return (1);
74 	if (gc->attr > 0xff)
75 		return (1);
76 	if (gc->data.size != 1 || gc->data.width != 1)
77 		return (1);
78 	if ((gc->fg & COLOUR_FLAG_RGB) || (gc->bg & COLOUR_FLAG_RGB))
79 		return (1);
80 	return (0);
81 }
82 
83 /* Free up unused extended cells. */
84 static void
85 grid_compact_line(struct grid_line *gl)
86 {
87 	int			 new_extdsize = 0;
88 	struct grid_cell	*new_extddata;
89 	struct grid_cell_entry	*gce;
90 	struct grid_cell	*gc;
91 	u_int			 px, idx;
92 
93 	if (gl->extdsize == 0)
94 		return;
95 
96 	for (px = 0; px < gl->cellsize; px++) {
97 		gce = &gl->celldata[px];
98 		if (gce->flags & GRID_FLAG_EXTENDED)
99 			new_extdsize++;
100 	}
101 
102 	if (new_extdsize == 0) {
103 		free(gl->extddata);
104 		gl->extddata = NULL;
105 		gl->extdsize = 0;
106 		return;
107 	}
108 	new_extddata = xreallocarray(NULL, new_extdsize, sizeof *gl->extddata);
109 
110 	idx = 0;
111 	for (px = 0; px < gl->cellsize; px++) {
112 		gce = &gl->celldata[px];
113 		if (gce->flags & GRID_FLAG_EXTENDED) {
114 			gc = &gl->extddata[gce->offset];
115 			memcpy(&new_extddata[idx], gc, sizeof *gc);
116 			gce->offset = idx++;
117 		}
118 	}
119 
120 	free(gl->extddata);
121 	gl->extddata = new_extddata;
122 	gl->extdsize = new_extdsize;
123 }
124 
125 /* Set cell as extended. */
126 static struct grid_cell *
127 grid_extended_cell(struct grid_line *gl, struct grid_cell_entry *gce,
128     const struct grid_cell *gc)
129 {
130 	struct grid_cell	*gcp;
131 
132 	gl->flags |= GRID_LINE_EXTENDED;
133 
134 	if (~gce->flags & GRID_FLAG_EXTENDED) {
135 		gl->extddata = xreallocarray(gl->extddata, gl->extdsize + 1,
136 		    sizeof *gl->extddata);
137 		gce->offset = gl->extdsize++;
138 		gce->flags = gc->flags | GRID_FLAG_EXTENDED;
139 	}
140 	if (gce->offset >= gl->extdsize)
141 		fatalx("offset too big");
142 
143 	gcp = &gl->extddata[gce->offset];
144 	memcpy(gcp, gc, sizeof *gcp);
145 	return (gcp);
146 }
147 
148 /* Get line data. */
149 struct grid_line *
150 grid_get_line(struct grid *gd, u_int line)
151 {
152 	return (&gd->linedata[line]);
153 }
154 
155 /* Adjust number of lines. */
156 void
157 grid_adjust_lines(struct grid *gd, u_int lines)
158 {
159 	gd->linedata = xreallocarray(gd->linedata, lines, sizeof *gd->linedata);
160 }
161 
162 /* Copy default into a cell. */
163 static void
164 grid_clear_cell(struct grid *gd, u_int px, u_int py, u_int bg)
165 {
166 	struct grid_line	*gl = &gd->linedata[py];
167 	struct grid_cell_entry	*gce = &gl->celldata[px];
168 	struct grid_cell	*gc;
169 
170 	memcpy(gce, &grid_default_entry, sizeof *gce);
171 	if (bg & COLOUR_FLAG_RGB) {
172 		gc = grid_extended_cell(gl, gce, &grid_default_cell);
173 		gc->bg = bg;
174 	} else {
175 		if (bg & COLOUR_FLAG_256)
176 			gce->flags |= GRID_FLAG_BG256;
177 		gce->data.bg = bg;
178 	}
179 }
180 
181 /* Check grid y position. */
182 static int
183 grid_check_y(struct grid *gd, const char* from, u_int py)
184 {
185 	if (py >= gd->hsize + gd->sy) {
186 		log_debug("%s: y out of range: %u", from, py);
187 		return (-1);
188 	}
189 	return (0);
190 }
191 
192 /* Compare grid cells. Return 1 if equal, 0 if not. */
193 int
194 grid_cells_equal(const struct grid_cell *gca, const struct grid_cell *gcb)
195 {
196 	if (gca->fg != gcb->fg || gca->bg != gcb->bg)
197 		return (0);
198 	if (gca->attr != gcb->attr || gca->flags != gcb->flags)
199 		return (0);
200 	if (gca->data.width != gcb->data.width)
201 		return (0);
202 	if (gca->data.size != gcb->data.size)
203 		return (0);
204 	return (memcmp(gca->data.data, gcb->data.data, gca->data.size) == 0);
205 }
206 
207 /* Free one line. */
208 static void
209 grid_free_line(struct grid *gd, u_int py)
210 {
211 	free(gd->linedata[py].celldata);
212 	gd->linedata[py].celldata = NULL;
213 	free(gd->linedata[py].extddata);
214 	gd->linedata[py].extddata = NULL;
215 }
216 
217 /* Free several lines. */
218 static void
219 grid_free_lines(struct grid *gd, u_int py, u_int ny)
220 {
221 	u_int	yy;
222 
223 	for (yy = py; yy < py + ny; yy++)
224 		grid_free_line(gd, yy);
225 }
226 
227 /* Create a new grid. */
228 struct grid *
229 grid_create(u_int sx, u_int sy, u_int hlimit)
230 {
231 	struct grid	*gd;
232 
233 	gd = xmalloc(sizeof *gd);
234 	gd->sx = sx;
235 	gd->sy = sy;
236 
237 	gd->flags = GRID_HISTORY;
238 
239 	gd->hscrolled = 0;
240 	gd->hsize = 0;
241 	gd->hlimit = hlimit;
242 
243 	if (gd->sy != 0)
244 		gd->linedata = xcalloc(gd->sy, sizeof *gd->linedata);
245 	else
246 		gd->linedata = NULL;
247 
248 	return (gd);
249 }
250 
251 /* Destroy grid. */
252 void
253 grid_destroy(struct grid *gd)
254 {
255 	grid_free_lines(gd, 0, gd->hsize + gd->sy);
256 
257 	free(gd->linedata);
258 
259 	free(gd);
260 }
261 
262 /* Compare grids. */
263 int
264 grid_compare(struct grid *ga, struct grid *gb)
265 {
266 	struct grid_line	*gla, *glb;
267 	struct grid_cell	 gca, gcb;
268 	u_int			 xx, yy;
269 
270 	if (ga->sx != gb->sx || ga->sy != gb->sy)
271 		return (1);
272 
273 	for (yy = 0; yy < ga->sy; yy++) {
274 		gla = &ga->linedata[yy];
275 		glb = &gb->linedata[yy];
276 		if (gla->cellsize != glb->cellsize)
277 			return (1);
278 		for (xx = 0; xx < gla->cellsize; xx++) {
279 			grid_get_cell(ga, xx, yy, &gca);
280 			grid_get_cell(gb, xx, yy, &gcb);
281 			if (!grid_cells_equal(&gca, &gcb))
282 				return (1);
283 		}
284 	}
285 
286 	return (0);
287 }
288 
289 /* Trim lines from the history. */
290 static void
291 grid_trim_history(struct grid *gd, u_int ny)
292 {
293 	grid_free_lines(gd, 0, ny);
294 	memmove(&gd->linedata[0], &gd->linedata[ny],
295 	    (gd->hsize + gd->sy - ny) * (sizeof *gd->linedata));
296 }
297 
298 /*
299  * Collect lines from the history if at the limit. Free the top (oldest) 10%
300  * and shift up.
301  */
302 void
303 grid_collect_history(struct grid *gd)
304 {
305 	u_int	ny;
306 
307 	if (gd->hsize == 0 || gd->hsize < gd->hlimit)
308 		return;
309 
310 	ny = gd->hlimit / 10;
311 	if (ny < 1)
312 		ny = 1;
313 	if (ny > gd->hsize)
314 		ny = gd->hsize;
315 
316 	/*
317 	 * Free the lines from 0 to ny then move the remaining lines over
318 	 * them.
319 	 */
320 	grid_trim_history(gd, ny);
321 
322 	gd->hsize -= ny;
323 	if (gd->hscrolled > gd->hsize)
324 		gd->hscrolled = gd->hsize;
325 }
326 
327 /*
328  * Scroll the entire visible screen, moving one line into the history. Just
329  * allocate a new line at the bottom and move the history size indicator.
330  */
331 void
332 grid_scroll_history(struct grid *gd, u_int bg)
333 {
334 	u_int	yy;
335 
336 	yy = gd->hsize + gd->sy;
337 	gd->linedata = xreallocarray(gd->linedata, yy + 1,
338 	    sizeof *gd->linedata);
339 	grid_empty_line(gd, yy, bg);
340 
341 	gd->hscrolled++;
342 	grid_compact_line(&gd->linedata[gd->hsize]);
343 	gd->hsize++;
344 }
345 
346 /* Clear the history. */
347 void
348 grid_clear_history(struct grid *gd)
349 {
350 	grid_trim_history(gd, gd->hsize);
351 
352 	gd->hscrolled = 0;
353 	gd->hsize = 0;
354 
355 	gd->linedata = xreallocarray(gd->linedata, gd->sy,
356 	    sizeof *gd->linedata);
357 }
358 
359 /* Scroll a region up, moving the top line into the history. */
360 void
361 grid_scroll_history_region(struct grid *gd, u_int upper, u_int lower, u_int bg)
362 {
363 	struct grid_line	*gl_history, *gl_upper;
364 	u_int			 yy;
365 
366 	/* Create a space for a new line. */
367 	yy = gd->hsize + gd->sy;
368 	gd->linedata = xreallocarray(gd->linedata, yy + 1,
369 	    sizeof *gd->linedata);
370 
371 	/* Move the entire screen down to free a space for this line. */
372 	gl_history = &gd->linedata[gd->hsize];
373 	memmove(gl_history + 1, gl_history, gd->sy * sizeof *gl_history);
374 
375 	/* Adjust the region and find its start and end. */
376 	upper++;
377 	gl_upper = &gd->linedata[upper];
378 	lower++;
379 
380 	/* Move the line into the history. */
381 	memcpy(gl_history, gl_upper, sizeof *gl_history);
382 
383 	/* Then move the region up and clear the bottom line. */
384 	memmove(gl_upper, gl_upper + 1, (lower - upper) * sizeof *gl_upper);
385 	grid_empty_line(gd, lower, bg);
386 
387 	/* Move the history offset down over the line. */
388 	gd->hscrolled++;
389 	gd->hsize++;
390 }
391 
392 /* Expand line to fit to cell. */
393 static void
394 grid_expand_line(struct grid *gd, u_int py, u_int sx, u_int bg)
395 {
396 	struct grid_line	*gl;
397 	u_int			 xx;
398 
399 	gl = &gd->linedata[py];
400 	if (sx <= gl->cellsize)
401 		return;
402 
403 	if (sx < gd->sx / 4)
404 		sx = gd->sx / 4;
405 	else if (sx < gd->sx / 2)
406 		sx = gd->sx / 2;
407 	else
408 		sx = gd->sx;
409 
410 	gl->celldata = xreallocarray(gl->celldata, sx, sizeof *gl->celldata);
411 	for (xx = gl->cellsize; xx < sx; xx++)
412 		grid_clear_cell(gd, xx, py, bg);
413 	gl->cellsize = sx;
414 }
415 
416 /* Empty a line and set background colour if needed. */
417 static void
418 grid_empty_line(struct grid *gd, u_int py, u_int bg)
419 {
420 	memset(&gd->linedata[py], 0, sizeof gd->linedata[py]);
421 	if (bg != 8)
422 		grid_expand_line(gd, py, gd->sx, bg);
423 }
424 
425 /* Peek at grid line. */
426 const struct grid_line *
427 grid_peek_line(struct grid *gd, u_int py)
428 {
429 	if (grid_check_y(gd, __func__, py) != 0)
430 		return (NULL);
431 	return (&gd->linedata[py]);
432 }
433 
434 /* Get cell from line. */
435 static void
436 grid_get_cell1(struct grid_line *gl, u_int px, struct grid_cell *gc)
437 {
438 	struct grid_cell_entry	*gce = &gl->celldata[px];
439 
440 	if (gce->flags & GRID_FLAG_EXTENDED) {
441 		if (gce->offset >= gl->extdsize)
442 			memcpy(gc, &grid_default_cell, sizeof *gc);
443 		else
444 			memcpy(gc, &gl->extddata[gce->offset], sizeof *gc);
445 		return;
446 	}
447 
448 	gc->flags = gce->flags & ~(GRID_FLAG_FG256|GRID_FLAG_BG256);
449 	gc->attr = gce->data.attr;
450 	gc->fg = gce->data.fg;
451 	if (gce->flags & GRID_FLAG_FG256)
452 		gc->fg |= COLOUR_FLAG_256;
453 	gc->bg = gce->data.bg;
454 	if (gce->flags & GRID_FLAG_BG256)
455 		gc->bg |= COLOUR_FLAG_256;
456 	utf8_set(&gc->data, gce->data.data);
457 }
458 
459 /* Get cell for reading. */
460 void
461 grid_get_cell(struct grid *gd, u_int px, u_int py, struct grid_cell *gc)
462 {
463 	if (grid_check_y(gd, __func__, py) != 0 ||
464 	    px >= gd->linedata[py].cellsize) {
465 		memcpy(gc, &grid_default_cell, sizeof *gc);
466 		return;
467 	}
468 	return (grid_get_cell1(&gd->linedata[py], px, gc));
469 }
470 
471 /* Set cell at relative position. */
472 void
473 grid_set_cell(struct grid *gd, u_int px, u_int py, const struct grid_cell *gc)
474 {
475 	struct grid_line	*gl;
476 	struct grid_cell_entry	*gce;
477 
478 	if (grid_check_y(gd, __func__, py) != 0)
479 		return;
480 
481 	grid_expand_line(gd, py, px + 1, 8);
482 
483 	gl = &gd->linedata[py];
484 	if (px + 1 > gl->cellused)
485 		gl->cellused = px + 1;
486 
487 	gce = &gl->celldata[px];
488 	if (grid_need_extended_cell(gce, gc))
489 		grid_extended_cell(gl, gce, gc);
490 	else
491 		grid_store_cell(gce, gc, gc->data.data[0]);
492 }
493 
494 /* Set cells at relative position. */
495 void
496 grid_set_cells(struct grid *gd, u_int px, u_int py, const struct grid_cell *gc,
497     const char *s, size_t slen)
498 {
499 	struct grid_line	*gl;
500 	struct grid_cell_entry	*gce;
501 	struct grid_cell	*gcp;
502 	u_int			 i;
503 
504 	if (grid_check_y(gd, __func__, py) != 0)
505 		return;
506 
507 	grid_expand_line(gd, py, px + slen, 8);
508 
509 	gl = &gd->linedata[py];
510 	if (px + slen > gl->cellused)
511 		gl->cellused = px + slen;
512 
513 	for (i = 0; i < slen; i++) {
514 		gce = &gl->celldata[px + i];
515 		if (grid_need_extended_cell(gce, gc)) {
516 			gcp = grid_extended_cell(gl, gce, gc);
517 			utf8_set(&gcp->data, s[i]);
518 		} else
519 			grid_store_cell(gce, gc, s[i]);
520 	}
521 }
522 
523 /* Clear area. */
524 void
525 grid_clear(struct grid *gd, u_int px, u_int py, u_int nx, u_int ny, u_int bg)
526 {
527 	u_int	xx, yy;
528 
529 	if (nx == 0 || ny == 0)
530 		return;
531 
532 	if (px == 0 && nx == gd->sx) {
533 		grid_clear_lines(gd, py, ny, bg);
534 		return;
535 	}
536 
537 	if (grid_check_y(gd, __func__, py) != 0)
538 		return;
539 	if (grid_check_y(gd, __func__, py + ny - 1) != 0)
540 		return;
541 
542 	for (yy = py; yy < py + ny; yy++) {
543 		if (px + nx >= gd->sx && px < gd->linedata[yy].cellused)
544 			gd->linedata[yy].cellused = px;
545 		if (px > gd->linedata[yy].cellsize && bg == 8)
546 			continue;
547 		if (px + nx >= gd->linedata[yy].cellsize && bg == 8) {
548 			gd->linedata[yy].cellsize = px;
549 			continue;
550 		}
551 		grid_expand_line(gd, yy, px + nx, 8); /* default bg first */
552 		for (xx = px; xx < px + nx; xx++)
553 			grid_clear_cell(gd, xx, yy, bg);
554 	}
555 }
556 
557 /* Clear lines. This just frees and truncates the lines. */
558 void
559 grid_clear_lines(struct grid *gd, u_int py, u_int ny, u_int bg)
560 {
561 	u_int	yy;
562 
563 	if (ny == 0)
564 		return;
565 
566 	if (grid_check_y(gd, __func__, py) != 0)
567 		return;
568 	if (grid_check_y(gd, __func__, py + ny - 1) != 0)
569 		return;
570 
571 	for (yy = py; yy < py + ny; yy++) {
572 		grid_free_line(gd, yy);
573 		grid_empty_line(gd, yy, bg);
574 	}
575 }
576 
577 /* Move a group of lines. */
578 void
579 grid_move_lines(struct grid *gd, u_int dy, u_int py, u_int ny, u_int bg)
580 {
581 	u_int	yy;
582 
583 	if (ny == 0 || py == dy)
584 		return;
585 
586 	if (grid_check_y(gd, __func__, py) != 0)
587 		return;
588 	if (grid_check_y(gd, __func__, py + ny - 1) != 0)
589 		return;
590 	if (grid_check_y(gd, __func__, dy) != 0)
591 		return;
592 	if (grid_check_y(gd, __func__, dy + ny - 1) != 0)
593 		return;
594 
595 	/* Free any lines which are being replaced. */
596 	for (yy = dy; yy < dy + ny; yy++) {
597 		if (yy >= py && yy < py + ny)
598 			continue;
599 		grid_free_line(gd, yy);
600 	}
601 
602 	memmove(&gd->linedata[dy], &gd->linedata[py],
603 	    ny * (sizeof *gd->linedata));
604 
605 	/*
606 	 * Wipe any lines that have been moved (without freeing them - they are
607 	 * still present).
608 	 */
609 	for (yy = py; yy < py + ny; yy++) {
610 		if (yy < dy || yy >= dy + ny)
611 			grid_empty_line(gd, yy, bg);
612 	}
613 }
614 
615 /* Move a group of cells. */
616 void
617 grid_move_cells(struct grid *gd, u_int dx, u_int px, u_int py, u_int nx,
618     u_int bg)
619 {
620 	struct grid_line	*gl;
621 	u_int			 xx;
622 
623 	if (nx == 0 || px == dx)
624 		return;
625 
626 	if (grid_check_y(gd, __func__, py) != 0)
627 		return;
628 	gl = &gd->linedata[py];
629 
630 	grid_expand_line(gd, py, px + nx, 8);
631 	grid_expand_line(gd, py, dx + nx, 8);
632 	memmove(&gl->celldata[dx], &gl->celldata[px],
633 	    nx * sizeof *gl->celldata);
634 	if (dx + nx > gl->cellused)
635 		gl->cellused = dx + nx;
636 
637 	/* Wipe any cells that have been moved. */
638 	for (xx = px; xx < px + nx; xx++) {
639 		if (xx >= dx && xx < dx + nx)
640 			continue;
641 		grid_clear_cell(gd, xx, py, bg);
642 	}
643 }
644 
645 /* Get ANSI foreground sequence. */
646 static size_t
647 grid_string_cells_fg(const struct grid_cell *gc, int *values)
648 {
649 	size_t	n;
650 	u_char	r, g, b;
651 
652 	n = 0;
653 	if (gc->fg & COLOUR_FLAG_256) {
654 		values[n++] = 38;
655 		values[n++] = 5;
656 		values[n++] = gc->fg & 0xff;
657 	} else if (gc->fg & COLOUR_FLAG_RGB) {
658 		values[n++] = 38;
659 		values[n++] = 2;
660 		colour_split_rgb(gc->fg, &r, &g, &b);
661 		values[n++] = r;
662 		values[n++] = g;
663 		values[n++] = b;
664 	} else {
665 		switch (gc->fg) {
666 		case 0:
667 		case 1:
668 		case 2:
669 		case 3:
670 		case 4:
671 		case 5:
672 		case 6:
673 		case 7:
674 			values[n++] = gc->fg + 30;
675 			break;
676 		case 8:
677 			values[n++] = 39;
678 			break;
679 		case 90:
680 		case 91:
681 		case 92:
682 		case 93:
683 		case 94:
684 		case 95:
685 		case 96:
686 		case 97:
687 			values[n++] = gc->fg;
688 			break;
689 		}
690 	}
691 	return (n);
692 }
693 
694 /* Get ANSI background sequence. */
695 static size_t
696 grid_string_cells_bg(const struct grid_cell *gc, int *values)
697 {
698 	size_t	n;
699 	u_char	r, g, b;
700 
701 	n = 0;
702 	if (gc->bg & COLOUR_FLAG_256) {
703 		values[n++] = 48;
704 		values[n++] = 5;
705 		values[n++] = gc->bg & 0xff;
706 	} else if (gc->bg & COLOUR_FLAG_RGB) {
707 		values[n++] = 48;
708 		values[n++] = 2;
709 		colour_split_rgb(gc->bg, &r, &g, &b);
710 		values[n++] = r;
711 		values[n++] = g;
712 		values[n++] = b;
713 	} else {
714 		switch (gc->bg) {
715 		case 0:
716 		case 1:
717 		case 2:
718 		case 3:
719 		case 4:
720 		case 5:
721 		case 6:
722 		case 7:
723 			values[n++] = gc->bg + 40;
724 			break;
725 		case 8:
726 			values[n++] = 49;
727 			break;
728 		case 100:
729 		case 101:
730 		case 102:
731 		case 103:
732 		case 104:
733 		case 105:
734 		case 106:
735 		case 107:
736 			values[n++] = gc->bg - 10;
737 			break;
738 		}
739 	}
740 	return (n);
741 }
742 
743 /*
744  * Returns ANSI code to set particular attributes (colour, bold and so on)
745  * given a current state.
746  */
747 static void
748 grid_string_cells_code(const struct grid_cell *lastgc,
749     const struct grid_cell *gc, char *buf, size_t len, int escape_c0)
750 {
751 	int	oldc[64], newc[64], s[128];
752 	size_t	noldc, nnewc, n, i;
753 	u_int	attr = gc->attr, lastattr = lastgc->attr;
754 	char	tmp[64];
755 
756 	struct {
757 		u_int	mask;
758 		u_int	code;
759 	} attrs[] = {
760 		{ GRID_ATTR_BRIGHT, 1 },
761 		{ GRID_ATTR_DIM, 2 },
762 		{ GRID_ATTR_ITALICS, 3 },
763 		{ GRID_ATTR_UNDERSCORE, 4 },
764 		{ GRID_ATTR_BLINK, 5 },
765 		{ GRID_ATTR_REVERSE, 7 },
766 		{ GRID_ATTR_HIDDEN, 8 },
767 		{ GRID_ATTR_STRIKETHROUGH, 9 }
768 	};
769 	n = 0;
770 
771 	/* If any attribute is removed, begin with 0. */
772 	for (i = 0; i < nitems(attrs); i++) {
773 		if (!(attr & attrs[i].mask) && (lastattr & attrs[i].mask)) {
774 			s[n++] = 0;
775 			lastattr &= GRID_ATTR_CHARSET;
776 			break;
777 		}
778 	}
779 	/* For each attribute that is newly set, add its code. */
780 	for (i = 0; i < nitems(attrs); i++) {
781 		if ((attr & attrs[i].mask) && !(lastattr & attrs[i].mask))
782 			s[n++] = attrs[i].code;
783 	}
784 
785 	/* Write the attributes. */
786 	*buf = '\0';
787 	if (n > 0) {
788 		if (escape_c0)
789 			strlcat(buf, "\\033[", len);
790 		else
791 			strlcat(buf, "\033[", len);
792 		for (i = 0; i < n; i++) {
793 			if (i + 1 < n)
794 				xsnprintf(tmp, sizeof tmp, "%d;", s[i]);
795 			else
796 				xsnprintf(tmp, sizeof tmp, "%d", s[i]);
797 			strlcat(buf, tmp, len);
798 		}
799 		strlcat(buf, "m", len);
800 	}
801 
802 	/* If the foreground colour changed, write its parameters. */
803 	nnewc = grid_string_cells_fg(gc, newc);
804 	noldc = grid_string_cells_fg(lastgc, oldc);
805 	if (nnewc != noldc ||
806 	    memcmp(newc, oldc, nnewc * sizeof newc[0]) != 0 ||
807 	    (n != 0 && s[0] == 0)) {
808 		if (escape_c0)
809 			strlcat(buf, "\\033[", len);
810 		else
811 			strlcat(buf, "\033[", len);
812 		for (i = 0; i < nnewc; i++) {
813 			if (i + 1 < nnewc)
814 				xsnprintf(tmp, sizeof tmp, "%d;", newc[i]);
815 			else
816 				xsnprintf(tmp, sizeof tmp, "%d", newc[i]);
817 			strlcat(buf, tmp, len);
818 		}
819 		strlcat(buf, "m", len);
820 	}
821 
822 	/* If the background colour changed, append its parameters. */
823 	nnewc = grid_string_cells_bg(gc, newc);
824 	noldc = grid_string_cells_bg(lastgc, oldc);
825 	if (nnewc != noldc ||
826 	    memcmp(newc, oldc, nnewc * sizeof newc[0]) != 0 ||
827 	    (n != 0 && s[0] == 0)) {
828 		if (escape_c0)
829 			strlcat(buf, "\\033[", len);
830 		else
831 			strlcat(buf, "\033[", len);
832 		for (i = 0; i < nnewc; i++) {
833 			if (i + 1 < nnewc)
834 				xsnprintf(tmp, sizeof tmp, "%d;", newc[i]);
835 			else
836 				xsnprintf(tmp, sizeof tmp, "%d", newc[i]);
837 			strlcat(buf, tmp, len);
838 		}
839 		strlcat(buf, "m", len);
840 	}
841 
842 	/* Append shift in/shift out if needed. */
843 	if ((attr & GRID_ATTR_CHARSET) && !(lastattr & GRID_ATTR_CHARSET)) {
844 		if (escape_c0)
845 			strlcat(buf, "\\016", len); /* SO */
846 		else
847 			strlcat(buf, "\016", len);  /* SO */
848 	}
849 	if (!(attr & GRID_ATTR_CHARSET) && (lastattr & GRID_ATTR_CHARSET)) {
850 		if (escape_c0)
851 			strlcat(buf, "\\017", len); /* SI */
852 		else
853 			strlcat(buf, "\017", len);  /* SI */
854 	}
855 }
856 
857 /* Convert cells into a string. */
858 char *
859 grid_string_cells(struct grid *gd, u_int px, u_int py, u_int nx,
860     struct grid_cell **lastgc, int with_codes, int escape_c0, int trim)
861 {
862 	struct grid_cell	 gc;
863 	static struct grid_cell	 lastgc1;
864 	const char		*data;
865 	char			*buf, code[128];
866 	size_t			 len, off, size, codelen;
867 	u_int			 xx;
868 	const struct grid_line	*gl;
869 
870 	if (lastgc != NULL && *lastgc == NULL) {
871 		memcpy(&lastgc1, &grid_default_cell, sizeof lastgc1);
872 		*lastgc = &lastgc1;
873 	}
874 
875 	len = 128;
876 	buf = xmalloc(len);
877 	off = 0;
878 
879 	gl = grid_peek_line(gd, py);
880 	for (xx = px; xx < px + nx; xx++) {
881 		if (gl == NULL || xx >= gl->cellsize)
882 			break;
883 		grid_get_cell(gd, xx, py, &gc);
884 		if (gc.flags & GRID_FLAG_PADDING)
885 			continue;
886 
887 		if (with_codes) {
888 			grid_string_cells_code(*lastgc, &gc, code, sizeof code,
889 			    escape_c0);
890 			codelen = strlen(code);
891 			memcpy(*lastgc, &gc, sizeof **lastgc);
892 		} else
893 			codelen = 0;
894 
895 		data = gc.data.data;
896 		size = gc.data.size;
897 		if (escape_c0 && size == 1 && *data == '\\') {
898 			data = "\\\\";
899 			size = 2;
900 		}
901 
902 		while (len < off + size + codelen + 1) {
903 			buf = xreallocarray(buf, 2, len);
904 			len *= 2;
905 		}
906 
907 		if (codelen != 0) {
908 			memcpy(buf + off, code, codelen);
909 			off += codelen;
910 		}
911 		memcpy(buf + off, data, size);
912 		off += size;
913 	}
914 
915 	if (trim) {
916 		while (off > 0 && buf[off - 1] == ' ')
917 			off--;
918 	}
919 	buf[off] = '\0';
920 
921 	return (buf);
922 }
923 
924 /*
925  * Duplicate a set of lines between two grids. Both source and destination
926  * should be big enough.
927  */
928 void
929 grid_duplicate_lines(struct grid *dst, u_int dy, struct grid *src, u_int sy,
930     u_int ny)
931 {
932 	struct grid_line	*dstl, *srcl;
933 	u_int			 yy;
934 
935 	if (dy + ny > dst->hsize + dst->sy)
936 		ny = dst->hsize + dst->sy - dy;
937 	if (sy + ny > src->hsize + src->sy)
938 		ny = src->hsize + src->sy - sy;
939 	grid_free_lines(dst, dy, ny);
940 
941 	for (yy = 0; yy < ny; yy++) {
942 		srcl = &src->linedata[sy];
943 		dstl = &dst->linedata[dy];
944 
945 		memcpy(dstl, srcl, sizeof *dstl);
946 		if (srcl->cellsize != 0) {
947 			dstl->celldata = xreallocarray(NULL,
948 			    srcl->cellsize, sizeof *dstl->celldata);
949 			memcpy(dstl->celldata, srcl->celldata,
950 			    srcl->cellsize * sizeof *dstl->celldata);
951 		} else
952 			dstl->celldata = NULL;
953 
954 		if (srcl->extdsize != 0) {
955 			dstl->extdsize = srcl->extdsize;
956 			dstl->extddata = xreallocarray(NULL, dstl->extdsize,
957 			    sizeof *dstl->extddata);
958 			memcpy(dstl->extddata, srcl->extddata, dstl->extdsize *
959 			    sizeof *dstl->extddata);
960 		}
961 
962 		sy++;
963 		dy++;
964 	}
965 }
966 
967 /* Mark line as dead. */
968 static void
969 grid_reflow_dead(struct grid_line *gl)
970 {
971 	memset(gl, 0, sizeof *gl);
972 	gl->flags = GRID_LINE_DEAD;
973 }
974 
975 /* Add lines, return the first new one. */
976 static struct grid_line *
977 grid_reflow_add(struct grid *gd, u_int n)
978 {
979 	struct grid_line	*gl;
980 	u_int			 sy = gd->sy + n;
981 
982 	gd->linedata = xreallocarray(gd->linedata, sy, sizeof *gd->linedata);
983 	gl = &gd->linedata[gd->sy];
984 	memset(gl, 0, n * (sizeof *gl));
985 	gd->sy = sy;
986 	return (gl);
987 }
988 
989 /* Move a line across. */
990 static struct grid_line *
991 grid_reflow_move(struct grid *gd, struct grid_line *from)
992 {
993 	struct grid_line	*to;
994 
995 	to = grid_reflow_add(gd, 1);
996 	memcpy(to, from, sizeof *to);
997 	grid_reflow_dead(from);
998 	return (to);
999 }
1000 
1001 /* Join line below onto this one. */
1002 static void
1003 grid_reflow_join(struct grid *target, struct grid *gd, u_int sx, u_int yy,
1004     u_int width, u_int *cy, int already)
1005 {
1006 	struct grid_line	*gl, *from = NULL;
1007 	struct grid_cell	 gc;
1008 	u_int			 lines, left, i, to, line, want = 0;
1009 	u_int			 at;
1010 	int			 wrapped = 1;
1011 
1012 	/*
1013 	 * Add a new target line.
1014 	 */
1015 	if (!already) {
1016 		to = target->sy;
1017 		gl = grid_reflow_move(target, &gd->linedata[yy]);
1018 	} else {
1019 		to = target->sy - 1;
1020 		gl = &target->linedata[to];
1021 	}
1022 	at = gl->cellused;
1023 
1024 	/*
1025 	 * Loop until no more to consume or the target line is full.
1026 	 */
1027 	lines = 0;
1028 	for (;;) {
1029 		/*
1030 		 * If this is now the last line, there is nothing more to be
1031 		 * done.
1032 		 */
1033 		if (yy + 1 + lines == gd->hsize + gd->sy)
1034 			break;
1035 		line = yy + 1 + lines;
1036 
1037 		/* If the next line is empty, skip it. */
1038 		if (~gd->linedata[line].flags & GRID_LINE_WRAPPED)
1039 			wrapped = 0;
1040 		if (gd->linedata[line].cellused == 0) {
1041 			if (!wrapped)
1042 				break;
1043 			lines++;
1044 			continue;
1045 		}
1046 
1047 		/*
1048 		 * Is the destination line now full? Copy the first character
1049 		 * separately because we need to leave "from" set to the last
1050 		 * line if this line is full.
1051 		 */
1052 		grid_get_cell1(&gd->linedata[line], 0, &gc);
1053 		if (width + gc.data.width > sx)
1054 			break;
1055 		width += gc.data.width;
1056 		grid_set_cell(target, at, to, &gc);
1057 		at++;
1058 
1059 		/* Join as much more as possible onto the current line. */
1060 		from = &gd->linedata[line];
1061 		for (want = 1; want < from->cellused; want++) {
1062 			grid_get_cell1(from, want, &gc);
1063 			if (width + gc.data.width > sx)
1064 				break;
1065 			width += gc.data.width;
1066 
1067 			grid_set_cell(target, at, to, &gc);
1068 			at++;
1069 		}
1070 		lines++;
1071 
1072 		/*
1073 		 * If this line wasn't wrapped or we didn't consume the entire
1074 		 * line, don't try to join any further lines.
1075 		 */
1076 		if (!wrapped || want != from->cellused || width == sx)
1077 			break;
1078 	}
1079 	if (lines == 0)
1080 		return;
1081 
1082 	/*
1083 	 * If we didn't consume the entire final line, then remove what we did
1084 	 * consume. If we consumed the entire line and it wasn't wrapped,
1085 	 * remove the wrap flag from this line.
1086 	 */
1087 	left = from->cellused - want;
1088 	if (left != 0) {
1089 		grid_move_cells(gd, 0, want, yy + lines, left, 8);
1090 		from->cellsize = from->cellused = left;
1091 		lines--;
1092 	} else if (!wrapped)
1093 		gl->flags &= ~GRID_LINE_WRAPPED;
1094 
1095 	/* Remove the lines that were completely consumed. */
1096 	for (i = yy + 1; i < yy + 1 + lines; i++) {
1097 		free(gd->linedata[i].celldata);
1098 		free(gd->linedata[i].extddata);
1099 		grid_reflow_dead(&gd->linedata[i]);
1100 	}
1101 
1102 	/* Adjust cursor and scroll positions. */
1103 	if (*cy > to + lines)
1104 		*cy -= lines;
1105 	else if (*cy > to)
1106 		*cy = to;
1107 	if (gd->hscrolled > to + lines)
1108 		gd->hscrolled -= lines;
1109 	else if (gd->hscrolled > to)
1110 		gd->hscrolled = to;
1111 }
1112 
1113 /* Split this line into several new ones */
1114 static void
1115 grid_reflow_split(struct grid *target, struct grid *gd, u_int sx, u_int yy,
1116     u_int at, u_int *cy)
1117 {
1118 	struct grid_line	*gl = &gd->linedata[yy], *first;
1119 	struct grid_cell	 gc;
1120 	u_int			 line, lines, width, i, xx;
1121 	u_int			 used = gl->cellused;
1122 	int			 flags = gl->flags;
1123 
1124 	/* How many lines do we need to insert? We know we need at least two. */
1125 	if (~gl->flags & GRID_LINE_EXTENDED)
1126 		lines = 1 + (gl->cellused - 1) / sx;
1127 	else {
1128 		lines = 2;
1129 		width = 0;
1130 		for (i = at; i < used; i++) {
1131 			grid_get_cell1(gl, i, &gc);
1132 			if (width + gc.data.width > sx) {
1133 				lines++;
1134 				width = 0;
1135 			}
1136 			width += gc.data.width;
1137 		}
1138 	}
1139 
1140 	/* Insert new lines. */
1141 	line = target->sy + 1;
1142 	first = grid_reflow_add(target, lines);
1143 
1144 	/* Copy sections from the original line. */
1145 	width = 0;
1146 	xx = 0;
1147 	for (i = at; i < used; i++) {
1148 		grid_get_cell1(gl, i, &gc);
1149 		if (width + gc.data.width > sx) {
1150 			target->linedata[line].flags |= GRID_LINE_WRAPPED;
1151 
1152 			line++;
1153 			width = 0;
1154 			xx = 0;
1155 		}
1156 		width += gc.data.width;
1157 		grid_set_cell(target, xx, line, &gc);
1158 		xx++;
1159 	}
1160 	if (flags & GRID_LINE_WRAPPED)
1161 		target->linedata[line].flags |= GRID_LINE_WRAPPED;
1162 
1163 	/* Move the remainder of the original line. */
1164 	gl->cellsize = gl->cellused = at;
1165 	gl->flags |= GRID_LINE_WRAPPED;
1166 	memcpy(first, gl, sizeof *first);
1167 	grid_reflow_dead(gl);
1168 
1169 	/* Adjust the cursor and scroll positions. */
1170 	if (yy <= *cy)
1171 		(*cy) += lines - 1;
1172 	if (yy <= gd->hscrolled)
1173 		gd->hscrolled += lines - 1;
1174 
1175 	/*
1176 	 * If the original line had the wrapped flag and there is still space
1177 	 * in the last new line, try to join with the next lines.
1178 	 */
1179 	if (width < sx && (flags & GRID_LINE_WRAPPED))
1180 		grid_reflow_join(target, gd, sx, yy, width, cy, 1);
1181 }
1182 
1183 /* Reflow lines on grid to new width. */
1184 void
1185 grid_reflow(struct grid *gd, u_int sx, u_int *cursor)
1186 {
1187 	struct grid		*target;
1188 	struct grid_line	*gl;
1189 	struct grid_cell	 gc;
1190 	u_int			 yy, cy, width, i, at, first;
1191 	struct timeval		 start, tv;
1192 
1193 	gettimeofday(&start, NULL);
1194 
1195 	log_debug("%s: %u lines, new width %u", __func__, gd->hsize + gd->sy,
1196 	    sx);
1197 	cy = gd->hsize + (*cursor);
1198 
1199 	/*
1200 	 * Create a destination grid. This is just used as a container for the
1201 	 * line data and may not be fully valid.
1202 	 */
1203 	target = grid_create(gd->sx, 0, 0);
1204 
1205 	/*
1206 	 * Loop over each source line.
1207 	 */
1208 	for (yy = 0; yy < gd->hsize + gd->sy; yy++) {
1209 		gl = &gd->linedata[yy];
1210 		if (gl->flags & GRID_LINE_DEAD)
1211 			continue;
1212 
1213 		/*
1214 		 * Work out the width of this line. first is the width of the
1215 		 * first character, at is the point at which the available
1216 		 * width is hit, and width is the full line width.
1217 		 */
1218 		first = at = width = 0;
1219 		if (~gl->flags & GRID_LINE_EXTENDED) {
1220 			first = 1;
1221 			width = gl->cellused;
1222 			if (width > sx)
1223 				at = sx;
1224 			else
1225 				at = width;
1226 		} else {
1227 			for (i = 0; i < gl->cellused; i++) {
1228 				grid_get_cell1(gl, i, &gc);
1229 				if (i == 0)
1230 					first = gc.data.width;
1231 				if (at == 0 && width + gc.data.width > sx)
1232 					at = i;
1233 				width += gc.data.width;
1234 			}
1235 		}
1236 
1237 		/*
1238 		 * If the line is exactly right or the first character is wider
1239 		 * than the targe width, just move it across unchanged.
1240 		 */
1241 		if (width == sx || first > sx) {
1242 			grid_reflow_move(target, gl);
1243 			continue;
1244 		}
1245 
1246 		/*
1247 		 * If the line is too big, it needs to be split, whether or not
1248 		 * it was previously wrapped.
1249 		 */
1250 		if (width > sx) {
1251 			grid_reflow_split(target, gd, sx, yy, at, &cy);
1252 			continue;
1253 		}
1254 
1255 		/*
1256 		 * If the line was previously wrapped, join as much as possible
1257 		 * of the next line.
1258 		 */
1259 		if (gl->flags & GRID_LINE_WRAPPED)
1260 			grid_reflow_join(target, gd, sx, yy, width, &cy, 0);
1261 		else
1262 			grid_reflow_move(target, gl);
1263 	}
1264 
1265 	/*
1266 	 * Replace the old grid with the new.
1267 	 */
1268 	if (target->sy < gd->sy)
1269 		grid_reflow_add(target, gd->sy - target->sy);
1270 	gd->hsize = target->sy - gd->sy;
1271 	free(gd->linedata);
1272 	gd->linedata = target->linedata;
1273 	free(target);
1274 
1275 	/*
1276 	 * Update scrolled and cursor positions.
1277 	 */
1278 	if (gd->hscrolled > gd->hsize)
1279 		gd->hscrolled = gd->hsize;
1280 	if (cy < gd->hsize)
1281 		*cursor = 0;
1282 	else
1283 		*cursor = cy - gd->hsize;
1284 
1285 	gettimeofday(&tv, NULL);
1286 	timersub(&tv, &start, &tv);
1287 	log_debug("%s: now %u lines (in %llu.%06u seconds)", __func__,
1288 	    gd->hsize + gd->sy, (unsigned long long)tv.tv_sec,
1289 	    (u_int)tv.tv_usec);
1290 }
1291