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