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