xref: /openbsd-src/usr.bin/tmux/grid.c (revision c90a81c56dcebd6a1b73fe4aff9b03385b8e63b3)
1 /* $OpenBSD: grid.c,v 1.88 2018/10/25 15:13:38 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 (!COLOUR_DEFAULT(bg))
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 	struct grid_line	*gl;
528 	u_int			 xx, yy;
529 
530 	if (nx == 0 || ny == 0)
531 		return;
532 
533 	if (px == 0 && nx == gd->sx) {
534 		grid_clear_lines(gd, py, ny, bg);
535 		return;
536 	}
537 
538 	if (grid_check_y(gd, __func__, py) != 0)
539 		return;
540 	if (grid_check_y(gd, __func__, py + ny - 1) != 0)
541 		return;
542 
543 	for (yy = py; yy < py + ny; yy++) {
544 		gl = &gd->linedata[yy];
545 		if (px + nx >= gd->sx && px < gl->cellused)
546 			gl->cellused = px;
547 		if (px > gl->cellsize && COLOUR_DEFAULT(bg))
548 			continue;
549 		if (px + nx >= gl->cellsize && COLOUR_DEFAULT(bg)) {
550 			gl->cellsize = px;
551 			continue;
552 		}
553 		grid_expand_line(gd, yy, px + nx, 8); /* default bg first */
554 		for (xx = px; xx < px + nx; xx++)
555 			grid_clear_cell(gd, xx, yy, bg);
556 	}
557 }
558 
559 /* Clear lines. This just frees and truncates the lines. */
560 void
561 grid_clear_lines(struct grid *gd, u_int py, u_int ny, u_int bg)
562 {
563 	u_int	yy;
564 
565 	if (ny == 0)
566 		return;
567 
568 	if (grid_check_y(gd, __func__, py) != 0)
569 		return;
570 	if (grid_check_y(gd, __func__, py + ny - 1) != 0)
571 		return;
572 
573 	for (yy = py; yy < py + ny; yy++) {
574 		grid_free_line(gd, yy);
575 		grid_empty_line(gd, yy, bg);
576 	}
577 }
578 
579 /* Move a group of lines. */
580 void
581 grid_move_lines(struct grid *gd, u_int dy, u_int py, u_int ny, u_int bg)
582 {
583 	u_int	yy;
584 
585 	if (ny == 0 || py == dy)
586 		return;
587 
588 	if (grid_check_y(gd, __func__, py) != 0)
589 		return;
590 	if (grid_check_y(gd, __func__, py + ny - 1) != 0)
591 		return;
592 	if (grid_check_y(gd, __func__, dy) != 0)
593 		return;
594 	if (grid_check_y(gd, __func__, dy + ny - 1) != 0)
595 		return;
596 
597 	/* Free any lines which are being replaced. */
598 	for (yy = dy; yy < dy + ny; yy++) {
599 		if (yy >= py && yy < py + ny)
600 			continue;
601 		grid_free_line(gd, yy);
602 	}
603 
604 	memmove(&gd->linedata[dy], &gd->linedata[py],
605 	    ny * (sizeof *gd->linedata));
606 
607 	/*
608 	 * Wipe any lines that have been moved (without freeing them - they are
609 	 * still present).
610 	 */
611 	for (yy = py; yy < py + ny; yy++) {
612 		if (yy < dy || yy >= dy + ny)
613 			grid_empty_line(gd, yy, bg);
614 	}
615 }
616 
617 /* Move a group of cells. */
618 void
619 grid_move_cells(struct grid *gd, u_int dx, u_int px, u_int py, u_int nx,
620     u_int bg)
621 {
622 	struct grid_line	*gl;
623 	u_int			 xx;
624 
625 	if (nx == 0 || px == dx)
626 		return;
627 
628 	if (grid_check_y(gd, __func__, py) != 0)
629 		return;
630 	gl = &gd->linedata[py];
631 
632 	grid_expand_line(gd, py, px + nx, 8);
633 	grid_expand_line(gd, py, dx + nx, 8);
634 	memmove(&gl->celldata[dx], &gl->celldata[px],
635 	    nx * sizeof *gl->celldata);
636 	if (dx + nx > gl->cellused)
637 		gl->cellused = dx + nx;
638 
639 	/* Wipe any cells that have been moved. */
640 	for (xx = px; xx < px + nx; xx++) {
641 		if (xx >= dx && xx < dx + nx)
642 			continue;
643 		grid_clear_cell(gd, xx, py, bg);
644 	}
645 }
646 
647 /* Get ANSI foreground sequence. */
648 static size_t
649 grid_string_cells_fg(const struct grid_cell *gc, int *values)
650 {
651 	size_t	n;
652 	u_char	r, g, b;
653 
654 	n = 0;
655 	if (gc->fg & COLOUR_FLAG_256) {
656 		values[n++] = 38;
657 		values[n++] = 5;
658 		values[n++] = gc->fg & 0xff;
659 	} else if (gc->fg & COLOUR_FLAG_RGB) {
660 		values[n++] = 38;
661 		values[n++] = 2;
662 		colour_split_rgb(gc->fg, &r, &g, &b);
663 		values[n++] = r;
664 		values[n++] = g;
665 		values[n++] = b;
666 	} else {
667 		switch (gc->fg) {
668 		case 0:
669 		case 1:
670 		case 2:
671 		case 3:
672 		case 4:
673 		case 5:
674 		case 6:
675 		case 7:
676 			values[n++] = gc->fg + 30;
677 			break;
678 		case 8:
679 			values[n++] = 39;
680 			break;
681 		case 90:
682 		case 91:
683 		case 92:
684 		case 93:
685 		case 94:
686 		case 95:
687 		case 96:
688 		case 97:
689 			values[n++] = gc->fg;
690 			break;
691 		}
692 	}
693 	return (n);
694 }
695 
696 /* Get ANSI background sequence. */
697 static size_t
698 grid_string_cells_bg(const struct grid_cell *gc, int *values)
699 {
700 	size_t	n;
701 	u_char	r, g, b;
702 
703 	n = 0;
704 	if (gc->bg & COLOUR_FLAG_256) {
705 		values[n++] = 48;
706 		values[n++] = 5;
707 		values[n++] = gc->bg & 0xff;
708 	} else if (gc->bg & COLOUR_FLAG_RGB) {
709 		values[n++] = 48;
710 		values[n++] = 2;
711 		colour_split_rgb(gc->bg, &r, &g, &b);
712 		values[n++] = r;
713 		values[n++] = g;
714 		values[n++] = b;
715 	} else {
716 		switch (gc->bg) {
717 		case 0:
718 		case 1:
719 		case 2:
720 		case 3:
721 		case 4:
722 		case 5:
723 		case 6:
724 		case 7:
725 			values[n++] = gc->bg + 40;
726 			break;
727 		case 8:
728 			values[n++] = 49;
729 			break;
730 		case 100:
731 		case 101:
732 		case 102:
733 		case 103:
734 		case 104:
735 		case 105:
736 		case 106:
737 		case 107:
738 			values[n++] = gc->bg - 10;
739 			break;
740 		}
741 	}
742 	return (n);
743 }
744 
745 /*
746  * Returns ANSI code to set particular attributes (colour, bold and so on)
747  * given a current state.
748  */
749 static void
750 grid_string_cells_code(const struct grid_cell *lastgc,
751     const struct grid_cell *gc, char *buf, size_t len, int escape_c0)
752 {
753 	int	oldc[64], newc[64], s[128];
754 	size_t	noldc, nnewc, n, i;
755 	u_int	attr = gc->attr, lastattr = lastgc->attr;
756 	char	tmp[64];
757 
758 	struct {
759 		u_int	mask;
760 		u_int	code;
761 	} attrs[] = {
762 		{ GRID_ATTR_BRIGHT, 1 },
763 		{ GRID_ATTR_DIM, 2 },
764 		{ GRID_ATTR_ITALICS, 3 },
765 		{ GRID_ATTR_UNDERSCORE, 4 },
766 		{ GRID_ATTR_BLINK, 5 },
767 		{ GRID_ATTR_REVERSE, 7 },
768 		{ GRID_ATTR_HIDDEN, 8 },
769 		{ GRID_ATTR_STRIKETHROUGH, 9 },
770 		{ GRID_ATTR_UNDERSCORE_2, 42 },
771 		{ GRID_ATTR_UNDERSCORE_3, 43 },
772 		{ GRID_ATTR_UNDERSCORE_4, 44 },
773 		{ GRID_ATTR_UNDERSCORE_5, 45 },
774 	};
775 	n = 0;
776 
777 	/* If any attribute is removed, begin with 0. */
778 	for (i = 0; i < nitems(attrs); i++) {
779 		if (!(attr & attrs[i].mask) && (lastattr & attrs[i].mask)) {
780 			s[n++] = 0;
781 			lastattr &= GRID_ATTR_CHARSET;
782 			break;
783 		}
784 	}
785 	/* For each attribute that is newly set, add its code. */
786 	for (i = 0; i < nitems(attrs); i++) {
787 		if ((attr & attrs[i].mask) && !(lastattr & attrs[i].mask))
788 			s[n++] = attrs[i].code;
789 	}
790 
791 	/* Write the attributes. */
792 	*buf = '\0';
793 	if (n > 0) {
794 		if (escape_c0)
795 			strlcat(buf, "\\033[", len);
796 		else
797 			strlcat(buf, "\033[", len);
798 		for (i = 0; i < n; i++) {
799 			if (s[i] < 10)
800 				xsnprintf(tmp, sizeof tmp, "%d", s[i]);
801 			else {
802 				xsnprintf(tmp, sizeof tmp, "%d:%d", s[i] / 10,
803 				    s[i] % 10);
804 			}
805 			strlcat(buf, tmp, len);
806 			if (i + 1 < n)
807 				strlcat(buf, ";", len);
808 		}
809 		strlcat(buf, "m", len);
810 	}
811 
812 	/* If the foreground colour changed, write its parameters. */
813 	nnewc = grid_string_cells_fg(gc, newc);
814 	noldc = grid_string_cells_fg(lastgc, oldc);
815 	if (nnewc != noldc ||
816 	    memcmp(newc, oldc, nnewc * sizeof newc[0]) != 0 ||
817 	    (n != 0 && s[0] == 0)) {
818 		if (escape_c0)
819 			strlcat(buf, "\\033[", len);
820 		else
821 			strlcat(buf, "\033[", len);
822 		for (i = 0; i < nnewc; i++) {
823 			if (i + 1 < nnewc)
824 				xsnprintf(tmp, sizeof tmp, "%d;", newc[i]);
825 			else
826 				xsnprintf(tmp, sizeof tmp, "%d", newc[i]);
827 			strlcat(buf, tmp, len);
828 		}
829 		strlcat(buf, "m", len);
830 	}
831 
832 	/* If the background colour changed, append its parameters. */
833 	nnewc = grid_string_cells_bg(gc, newc);
834 	noldc = grid_string_cells_bg(lastgc, oldc);
835 	if (nnewc != noldc ||
836 	    memcmp(newc, oldc, nnewc * sizeof newc[0]) != 0 ||
837 	    (n != 0 && s[0] == 0)) {
838 		if (escape_c0)
839 			strlcat(buf, "\\033[", len);
840 		else
841 			strlcat(buf, "\033[", len);
842 		for (i = 0; i < nnewc; i++) {
843 			if (i + 1 < nnewc)
844 				xsnprintf(tmp, sizeof tmp, "%d;", newc[i]);
845 			else
846 				xsnprintf(tmp, sizeof tmp, "%d", newc[i]);
847 			strlcat(buf, tmp, len);
848 		}
849 		strlcat(buf, "m", len);
850 	}
851 
852 	/* Append shift in/shift out if needed. */
853 	if ((attr & GRID_ATTR_CHARSET) && !(lastattr & GRID_ATTR_CHARSET)) {
854 		if (escape_c0)
855 			strlcat(buf, "\\016", len); /* SO */
856 		else
857 			strlcat(buf, "\016", len);  /* SO */
858 	}
859 	if (!(attr & GRID_ATTR_CHARSET) && (lastattr & GRID_ATTR_CHARSET)) {
860 		if (escape_c0)
861 			strlcat(buf, "\\017", len); /* SI */
862 		else
863 			strlcat(buf, "\017", len);  /* SI */
864 	}
865 }
866 
867 /* Convert cells into a string. */
868 char *
869 grid_string_cells(struct grid *gd, u_int px, u_int py, u_int nx,
870     struct grid_cell **lastgc, int with_codes, int escape_c0, int trim)
871 {
872 	struct grid_cell	 gc;
873 	static struct grid_cell	 lastgc1;
874 	const char		*data;
875 	char			*buf, code[128];
876 	size_t			 len, off, size, codelen;
877 	u_int			 xx;
878 	const struct grid_line	*gl;
879 
880 	if (lastgc != NULL && *lastgc == NULL) {
881 		memcpy(&lastgc1, &grid_default_cell, sizeof lastgc1);
882 		*lastgc = &lastgc1;
883 	}
884 
885 	len = 128;
886 	buf = xmalloc(len);
887 	off = 0;
888 
889 	gl = grid_peek_line(gd, py);
890 	for (xx = px; xx < px + nx; xx++) {
891 		if (gl == NULL || xx >= gl->cellsize)
892 			break;
893 		grid_get_cell(gd, xx, py, &gc);
894 		if (gc.flags & GRID_FLAG_PADDING)
895 			continue;
896 
897 		if (with_codes) {
898 			grid_string_cells_code(*lastgc, &gc, code, sizeof code,
899 			    escape_c0);
900 			codelen = strlen(code);
901 			memcpy(*lastgc, &gc, sizeof **lastgc);
902 		} else
903 			codelen = 0;
904 
905 		data = gc.data.data;
906 		size = gc.data.size;
907 		if (escape_c0 && size == 1 && *data == '\\') {
908 			data = "\\\\";
909 			size = 2;
910 		}
911 
912 		while (len < off + size + codelen + 1) {
913 			buf = xreallocarray(buf, 2, len);
914 			len *= 2;
915 		}
916 
917 		if (codelen != 0) {
918 			memcpy(buf + off, code, codelen);
919 			off += codelen;
920 		}
921 		memcpy(buf + off, data, size);
922 		off += size;
923 	}
924 
925 	if (trim) {
926 		while (off > 0 && buf[off - 1] == ' ')
927 			off--;
928 	}
929 	buf[off] = '\0';
930 
931 	return (buf);
932 }
933 
934 /*
935  * Duplicate a set of lines between two grids. Both source and destination
936  * should be big enough.
937  */
938 void
939 grid_duplicate_lines(struct grid *dst, u_int dy, struct grid *src, u_int sy,
940     u_int ny)
941 {
942 	struct grid_line	*dstl, *srcl;
943 	u_int			 yy;
944 
945 	if (dy + ny > dst->hsize + dst->sy)
946 		ny = dst->hsize + dst->sy - dy;
947 	if (sy + ny > src->hsize + src->sy)
948 		ny = src->hsize + src->sy - sy;
949 	grid_free_lines(dst, dy, ny);
950 
951 	for (yy = 0; yy < ny; yy++) {
952 		srcl = &src->linedata[sy];
953 		dstl = &dst->linedata[dy];
954 
955 		memcpy(dstl, srcl, sizeof *dstl);
956 		if (srcl->cellsize != 0) {
957 			dstl->celldata = xreallocarray(NULL,
958 			    srcl->cellsize, sizeof *dstl->celldata);
959 			memcpy(dstl->celldata, srcl->celldata,
960 			    srcl->cellsize * sizeof *dstl->celldata);
961 		} else
962 			dstl->celldata = NULL;
963 
964 		if (srcl->extdsize != 0) {
965 			dstl->extdsize = srcl->extdsize;
966 			dstl->extddata = xreallocarray(NULL, dstl->extdsize,
967 			    sizeof *dstl->extddata);
968 			memcpy(dstl->extddata, srcl->extddata, dstl->extdsize *
969 			    sizeof *dstl->extddata);
970 		}
971 
972 		sy++;
973 		dy++;
974 	}
975 }
976 
977 /* Mark line as dead. */
978 static void
979 grid_reflow_dead(struct grid_line *gl)
980 {
981 	memset(gl, 0, sizeof *gl);
982 	gl->flags = GRID_LINE_DEAD;
983 }
984 
985 /* Add lines, return the first new one. */
986 static struct grid_line *
987 grid_reflow_add(struct grid *gd, u_int n)
988 {
989 	struct grid_line	*gl;
990 	u_int			 sy = gd->sy + n;
991 
992 	gd->linedata = xreallocarray(gd->linedata, sy, sizeof *gd->linedata);
993 	gl = &gd->linedata[gd->sy];
994 	memset(gl, 0, n * (sizeof *gl));
995 	gd->sy = sy;
996 	return (gl);
997 }
998 
999 /* Move a line across. */
1000 static struct grid_line *
1001 grid_reflow_move(struct grid *gd, struct grid_line *from)
1002 {
1003 	struct grid_line	*to;
1004 
1005 	to = grid_reflow_add(gd, 1);
1006 	memcpy(to, from, sizeof *to);
1007 	grid_reflow_dead(from);
1008 	return (to);
1009 }
1010 
1011 /* Join line below onto this one. */
1012 static void
1013 grid_reflow_join(struct grid *target, struct grid *gd, u_int sx, u_int yy,
1014     u_int width, u_int *cy, int already)
1015 {
1016 	struct grid_line	*gl, *from = NULL;
1017 	struct grid_cell	 gc;
1018 	u_int			 lines, left, i, to, line, want = 0;
1019 	u_int			 at;
1020 	int			 wrapped = 1;
1021 
1022 	/*
1023 	 * Add a new target line.
1024 	 */
1025 	if (!already) {
1026 		to = target->sy;
1027 		gl = grid_reflow_move(target, &gd->linedata[yy]);
1028 	} else {
1029 		to = target->sy - 1;
1030 		gl = &target->linedata[to];
1031 	}
1032 	at = gl->cellused;
1033 
1034 	/*
1035 	 * Loop until no more to consume or the target line is full.
1036 	 */
1037 	lines = 0;
1038 	for (;;) {
1039 		/*
1040 		 * If this is now the last line, there is nothing more to be
1041 		 * done.
1042 		 */
1043 		if (yy + 1 + lines == gd->hsize + gd->sy)
1044 			break;
1045 		line = yy + 1 + lines;
1046 
1047 		/* If the next line is empty, skip it. */
1048 		if (~gd->linedata[line].flags & GRID_LINE_WRAPPED)
1049 			wrapped = 0;
1050 		if (gd->linedata[line].cellused == 0) {
1051 			if (!wrapped)
1052 				break;
1053 			lines++;
1054 			continue;
1055 		}
1056 
1057 		/*
1058 		 * Is the destination line now full? Copy the first character
1059 		 * separately because we need to leave "from" set to the last
1060 		 * line if this line is full.
1061 		 */
1062 		grid_get_cell1(&gd->linedata[line], 0, &gc);
1063 		if (width + gc.data.width > sx)
1064 			break;
1065 		width += gc.data.width;
1066 		grid_set_cell(target, at, to, &gc);
1067 		at++;
1068 
1069 		/* Join as much more as possible onto the current line. */
1070 		from = &gd->linedata[line];
1071 		for (want = 1; want < from->cellused; want++) {
1072 			grid_get_cell1(from, want, &gc);
1073 			if (width + gc.data.width > sx)
1074 				break;
1075 			width += gc.data.width;
1076 
1077 			grid_set_cell(target, at, to, &gc);
1078 			at++;
1079 		}
1080 		lines++;
1081 
1082 		/*
1083 		 * If this line wasn't wrapped or we didn't consume the entire
1084 		 * line, don't try to join any further lines.
1085 		 */
1086 		if (!wrapped || want != from->cellused || width == sx)
1087 			break;
1088 	}
1089 	if (lines == 0)
1090 		return;
1091 
1092 	/*
1093 	 * If we didn't consume the entire final line, then remove what we did
1094 	 * consume. If we consumed the entire line and it wasn't wrapped,
1095 	 * remove the wrap flag from this line.
1096 	 */
1097 	left = from->cellused - want;
1098 	if (left != 0) {
1099 		grid_move_cells(gd, 0, want, yy + lines, left, 8);
1100 		from->cellsize = from->cellused = left;
1101 		lines--;
1102 	} else if (!wrapped)
1103 		gl->flags &= ~GRID_LINE_WRAPPED;
1104 
1105 	/* Remove the lines that were completely consumed. */
1106 	for (i = yy + 1; i < yy + 1 + lines; i++) {
1107 		free(gd->linedata[i].celldata);
1108 		free(gd->linedata[i].extddata);
1109 		grid_reflow_dead(&gd->linedata[i]);
1110 	}
1111 
1112 	/* Adjust cursor and scroll positions. */
1113 	if (*cy > to + lines)
1114 		*cy -= lines;
1115 	else if (*cy > to)
1116 		*cy = to;
1117 	if (gd->hscrolled > to + lines)
1118 		gd->hscrolled -= lines;
1119 	else if (gd->hscrolled > to)
1120 		gd->hscrolled = to;
1121 }
1122 
1123 /* Split this line into several new ones */
1124 static void
1125 grid_reflow_split(struct grid *target, struct grid *gd, u_int sx, u_int yy,
1126     u_int at, u_int *cy)
1127 {
1128 	struct grid_line	*gl = &gd->linedata[yy], *first;
1129 	struct grid_cell	 gc;
1130 	u_int			 line, lines, width, i, xx;
1131 	u_int			 used = gl->cellused;
1132 	int			 flags = gl->flags;
1133 
1134 	/* How many lines do we need to insert? We know we need at least two. */
1135 	if (~gl->flags & GRID_LINE_EXTENDED)
1136 		lines = 1 + (gl->cellused - 1) / sx;
1137 	else {
1138 		lines = 2;
1139 		width = 0;
1140 		for (i = at; i < used; i++) {
1141 			grid_get_cell1(gl, i, &gc);
1142 			if (width + gc.data.width > sx) {
1143 				lines++;
1144 				width = 0;
1145 			}
1146 			width += gc.data.width;
1147 		}
1148 	}
1149 
1150 	/* Insert new lines. */
1151 	line = target->sy + 1;
1152 	first = grid_reflow_add(target, lines);
1153 
1154 	/* Copy sections from the original line. */
1155 	width = 0;
1156 	xx = 0;
1157 	for (i = at; i < used; i++) {
1158 		grid_get_cell1(gl, i, &gc);
1159 		if (width + gc.data.width > sx) {
1160 			target->linedata[line].flags |= GRID_LINE_WRAPPED;
1161 
1162 			line++;
1163 			width = 0;
1164 			xx = 0;
1165 		}
1166 		width += gc.data.width;
1167 		grid_set_cell(target, xx, line, &gc);
1168 		xx++;
1169 	}
1170 	if (flags & GRID_LINE_WRAPPED)
1171 		target->linedata[line].flags |= GRID_LINE_WRAPPED;
1172 
1173 	/* Move the remainder of the original line. */
1174 	gl->cellsize = gl->cellused = at;
1175 	gl->flags |= GRID_LINE_WRAPPED;
1176 	memcpy(first, gl, sizeof *first);
1177 	grid_reflow_dead(gl);
1178 
1179 	/* Adjust the cursor and scroll positions. */
1180 	if (yy <= *cy)
1181 		(*cy) += lines - 1;
1182 	if (yy <= gd->hscrolled)
1183 		gd->hscrolled += lines - 1;
1184 
1185 	/*
1186 	 * If the original line had the wrapped flag and there is still space
1187 	 * in the last new line, try to join with the next lines.
1188 	 */
1189 	if (width < sx && (flags & GRID_LINE_WRAPPED))
1190 		grid_reflow_join(target, gd, sx, yy, width, cy, 1);
1191 }
1192 
1193 /* Reflow lines on grid to new width. */
1194 void
1195 grid_reflow(struct grid *gd, u_int sx, u_int *cursor)
1196 {
1197 	struct grid		*target;
1198 	struct grid_line	*gl;
1199 	struct grid_cell	 gc;
1200 	u_int			 yy, cy, width, i, at, first;
1201 	struct timeval		 start, tv;
1202 
1203 	gettimeofday(&start, NULL);
1204 
1205 	log_debug("%s: %u lines, new width %u", __func__, gd->hsize + gd->sy,
1206 	    sx);
1207 	cy = gd->hsize + (*cursor);
1208 
1209 	/*
1210 	 * Create a destination grid. This is just used as a container for the
1211 	 * line data and may not be fully valid.
1212 	 */
1213 	target = grid_create(gd->sx, 0, 0);
1214 
1215 	/*
1216 	 * Loop over each source line.
1217 	 */
1218 	for (yy = 0; yy < gd->hsize + gd->sy; yy++) {
1219 		gl = &gd->linedata[yy];
1220 		if (gl->flags & GRID_LINE_DEAD)
1221 			continue;
1222 
1223 		/*
1224 		 * Work out the width of this line. first is the width of the
1225 		 * first character, at is the point at which the available
1226 		 * width is hit, and width is the full line width.
1227 		 */
1228 		first = at = width = 0;
1229 		if (~gl->flags & GRID_LINE_EXTENDED) {
1230 			first = 1;
1231 			width = gl->cellused;
1232 			if (width > sx)
1233 				at = sx;
1234 			else
1235 				at = width;
1236 		} else {
1237 			for (i = 0; i < gl->cellused; i++) {
1238 				grid_get_cell1(gl, i, &gc);
1239 				if (i == 0)
1240 					first = gc.data.width;
1241 				if (at == 0 && width + gc.data.width > sx)
1242 					at = i;
1243 				width += gc.data.width;
1244 			}
1245 		}
1246 
1247 		/*
1248 		 * If the line is exactly right or the first character is wider
1249 		 * than the targe width, just move it across unchanged.
1250 		 */
1251 		if (width == sx || first > sx) {
1252 			grid_reflow_move(target, gl);
1253 			continue;
1254 		}
1255 
1256 		/*
1257 		 * If the line is too big, it needs to be split, whether or not
1258 		 * it was previously wrapped.
1259 		 */
1260 		if (width > sx) {
1261 			grid_reflow_split(target, gd, sx, yy, at, &cy);
1262 			continue;
1263 		}
1264 
1265 		/*
1266 		 * If the line was previously wrapped, join as much as possible
1267 		 * of the next line.
1268 		 */
1269 		if (gl->flags & GRID_LINE_WRAPPED)
1270 			grid_reflow_join(target, gd, sx, yy, width, &cy, 0);
1271 		else
1272 			grid_reflow_move(target, gl);
1273 	}
1274 
1275 	/*
1276 	 * Replace the old grid with the new.
1277 	 */
1278 	if (target->sy < gd->sy)
1279 		grid_reflow_add(target, gd->sy - target->sy);
1280 	gd->hsize = target->sy - gd->sy;
1281 	free(gd->linedata);
1282 	gd->linedata = target->linedata;
1283 	free(target);
1284 
1285 	/*
1286 	 * Update scrolled and cursor positions.
1287 	 */
1288 	if (gd->hscrolled > gd->hsize)
1289 		gd->hscrolled = gd->hsize;
1290 	if (cy < gd->hsize)
1291 		*cursor = 0;
1292 	else
1293 		*cursor = cy - gd->hsize;
1294 
1295 	gettimeofday(&tv, NULL);
1296 	timersub(&tv, &start, &tv);
1297 	log_debug("%s: now %u lines (in %llu.%06u seconds)", __func__,
1298 	    gd->hsize + gd->sy, (unsigned long long)tv.tv_sec,
1299 	    (u_int)tv.tv_usec);
1300 }
1301