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