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