xref: /openbsd-src/usr.bin/tmux/grid.c (revision c7e8ea31cd41a963f06f0a8ba93948b06aa6b4a4)
1 /* $OpenBSD: grid.c,v 1.74 2017/05/16 12:57:26 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_expand_line(struct grid *, u_int, u_int, u_int);
47 static void	grid_empty_line(struct grid *, u_int, u_int);
48 
49 static void	grid_reflow_copy(struct grid_line *, u_int, struct grid_line *,
50 		    u_int, u_int);
51 static void	grid_reflow_join(struct grid *, u_int *, struct grid_line *,
52 		    u_int);
53 static void	grid_reflow_split(struct grid *, u_int *, struct grid_line *,
54 		    u_int, u_int);
55 static void	grid_reflow_move(struct grid *, u_int *, struct grid_line *);
56 
57 static size_t	grid_string_cells_fg(const struct grid_cell *, int *);
58 static size_t	grid_string_cells_bg(const struct grid_cell *, int *);
59 static void	grid_string_cells_code(const struct grid_cell *,
60 		    const struct grid_cell *, char *, size_t, int);
61 
62 /* Store cell in entry. */
63 static void
64 grid_store_cell(struct grid_cell_entry *gce, const struct grid_cell *gc,
65     u_char c)
66 {
67 	gce->flags = gc->flags;
68 
69 	gce->data.fg = gc->fg & 0xff;
70 	if (gc->fg & COLOUR_FLAG_256)
71 		gce->flags |= GRID_FLAG_FG256;
72 
73 	gce->data.bg = gc->bg & 0xff;
74 	if (gc->bg & COLOUR_FLAG_256)
75 		gce->flags |= GRID_FLAG_BG256;
76 
77 	gce->data.attr = gc->attr;
78 	gce->data.data = c;
79 }
80 
81 /* Check if a cell should be extended. */
82 static int
83 grid_need_extended_cell(const struct grid_cell_entry *gce,
84     const struct grid_cell *gc)
85 {
86 	if (gce->flags & GRID_FLAG_EXTENDED)
87 		return (1);
88 	if (gc->attr > 0xff)
89 		return (1);
90 	if (gc->data.size != 1 || gc->data.width != 1)
91 		return (1);
92 	if ((gc->fg & COLOUR_FLAG_RGB) || (gc->bg & COLOUR_FLAG_RGB))
93 		return (1);
94 	return (0);
95 }
96 
97 /* Set cell as extended. */
98 static struct grid_cell *
99 grid_extended_cell(struct grid_line *gl, struct grid_cell_entry *gce,
100     const struct grid_cell *gc)
101 {
102 	struct grid_cell	*gcp;
103 
104 	gl->flags |= GRID_LINE_EXTENDED;
105 
106 	if (~gce->flags & GRID_FLAG_EXTENDED) {
107 		gl->extddata = xreallocarray(gl->extddata, gl->extdsize + 1,
108 		    sizeof *gl->extddata);
109 		gce->offset = gl->extdsize++;
110 		gce->flags = gc->flags | GRID_FLAG_EXTENDED;
111 	}
112 	if (gce->offset >= gl->extdsize)
113 		fatalx("offset too big");
114 
115 	gcp = &gl->extddata[gce->offset];
116 	memcpy(gcp, gc, sizeof *gcp);
117 	return (gcp);
118 }
119 
120 /* Copy default into a cell. */
121 static void
122 grid_clear_cell(struct grid *gd, u_int px, u_int py, u_int bg)
123 {
124 	struct grid_line	*gl = &gd->linedata[py];
125 	struct grid_cell_entry	*gce = &gl->celldata[px];
126 	struct grid_cell	*gc;
127 
128 	memcpy(gce, &grid_default_entry, sizeof *gce);
129 	if (bg & COLOUR_FLAG_RGB) {
130 		gc = grid_extended_cell(gl, gce, &grid_default_cell);
131 		gc->bg = bg;
132 	} else {
133 		if (bg & COLOUR_FLAG_256)
134 			gce->flags |= GRID_FLAG_BG256;
135 		gce->data.bg = bg;
136 	}
137 }
138 
139 /* Check grid y position. */
140 static int
141 grid_check_y(struct grid *gd, u_int py)
142 {
143 	if ((py) >= (gd)->hsize + (gd)->sy) {
144 		log_debug("y out of range: %u", py);
145 		return (-1);
146 	}
147 	return (0);
148 }
149 
150 /* Compare grid cells. Return 1 if equal, 0 if not. */
151 int
152 grid_cells_equal(const struct grid_cell *gca, const struct grid_cell *gcb)
153 {
154 	if (gca->fg != gcb->fg || gca->bg != gcb->bg)
155 		return (0);
156 	if (gca->attr != gcb->attr || gca->flags != gcb->flags)
157 		return (0);
158 	if (gca->data.width != gcb->data.width)
159 		return (0);
160 	if (gca->data.size != gcb->data.size)
161 		return (0);
162 	return (memcmp(gca->data.data, gcb->data.data, gca->data.size) == 0);
163 }
164 
165 /* Create a new grid. */
166 struct grid *
167 grid_create(u_int sx, u_int sy, u_int hlimit)
168 {
169 	struct grid	*gd;
170 
171 	gd = xmalloc(sizeof *gd);
172 	gd->sx = sx;
173 	gd->sy = sy;
174 
175 	gd->flags = GRID_HISTORY;
176 
177 	gd->hscrolled = 0;
178 	gd->hsize = 0;
179 	gd->hlimit = hlimit;
180 
181 	gd->linedata = xcalloc(gd->sy, sizeof *gd->linedata);
182 
183 	return (gd);
184 }
185 
186 /* Destroy grid. */
187 void
188 grid_destroy(struct grid *gd)
189 {
190 	struct grid_line	*gl;
191 	u_int			 yy;
192 
193 	for (yy = 0; yy < gd->hsize + gd->sy; yy++) {
194 		gl = &gd->linedata[yy];
195 		free(gl->celldata);
196 		free(gl->extddata);
197 	}
198 
199 	free(gd->linedata);
200 
201 	free(gd);
202 }
203 
204 /* Compare grids. */
205 int
206 grid_compare(struct grid *ga, struct grid *gb)
207 {
208 	struct grid_line	*gla, *glb;
209 	struct grid_cell	 gca, gcb;
210 	u_int			 xx, yy;
211 
212 	if (ga->sx != gb->sx || ga->sy != gb->sy)
213 		return (1);
214 
215 	for (yy = 0; yy < ga->sy; yy++) {
216 		gla = &ga->linedata[yy];
217 		glb = &gb->linedata[yy];
218 		if (gla->cellsize != glb->cellsize)
219 			return (1);
220 		for (xx = 0; xx < gla->cellsize; xx++) {
221 			grid_get_cell(ga, xx, yy, &gca);
222 			grid_get_cell(gb, xx, yy, &gcb);
223 			if (!grid_cells_equal(&gca, &gcb))
224 				return (1);
225 		}
226 	}
227 
228 	return (0);
229 }
230 
231 /*
232  * Collect lines from the history if at the limit. Free the top (oldest) 10%
233  * and shift up.
234  */
235 void
236 grid_collect_history(struct grid *gd, u_int bg)
237 {
238 	u_int	yy;
239 
240 	if (gd->hsize < gd->hlimit)
241 		return;
242 
243 	yy = gd->hlimit / 10;
244 	if (yy < 1)
245 		yy = 1;
246 
247 	grid_move_lines(gd, 0, yy, gd->hsize + gd->sy - yy, bg);
248 	gd->hsize -= yy;
249 	if (gd->hscrolled > gd->hsize)
250 		gd->hscrolled = gd->hsize;
251 }
252 
253 /*
254  * Scroll the entire visible screen, moving one line into the history. Just
255  * allocate a new line at the bottom and move the history size indicator.
256  */
257 void
258 grid_scroll_history(struct grid *gd, u_int bg)
259 {
260 	u_int	yy;
261 
262 	yy = gd->hsize + gd->sy;
263 	gd->linedata = xreallocarray(gd->linedata, yy + 1,
264 	    sizeof *gd->linedata);
265 	grid_empty_line(gd, yy, bg);
266 
267 	gd->hscrolled++;
268 	gd->hsize++;
269 }
270 
271 /* Clear the history. */
272 void
273 grid_clear_history(struct grid *gd)
274 {
275 	grid_clear_lines(gd, 0, gd->hsize, 8);
276 	grid_move_lines(gd, 0, gd->hsize, gd->sy, 8);
277 
278 	gd->hscrolled = 0;
279 	gd->hsize = 0;
280 
281 	gd->linedata = xreallocarray(gd->linedata, gd->sy,
282 	    sizeof *gd->linedata);
283 }
284 
285 /* Scroll a region up, moving the top line into the history. */
286 void
287 grid_scroll_history_region(struct grid *gd, u_int upper, u_int lower, u_int bg)
288 {
289 	struct grid_line	*gl_history, *gl_upper;
290 	u_int			 yy;
291 
292 	/* Create a space for a new line. */
293 	yy = gd->hsize + gd->sy;
294 	gd->linedata = xreallocarray(gd->linedata, yy + 1,
295 	    sizeof *gd->linedata);
296 
297 	/* Move the entire screen down to free a space for this line. */
298 	gl_history = &gd->linedata[gd->hsize];
299 	memmove(gl_history + 1, gl_history, gd->sy * sizeof *gl_history);
300 
301 	/* Adjust the region and find its start and end. */
302 	upper++;
303 	gl_upper = &gd->linedata[upper];
304 	lower++;
305 
306 	/* Move the line into the history. */
307 	memcpy(gl_history, gl_upper, sizeof *gl_history);
308 
309 	/* Then move the region up and clear the bottom line. */
310 	memmove(gl_upper, gl_upper + 1, (lower - upper) * sizeof *gl_upper);
311 	grid_empty_line(gd, lower, bg);
312 
313 	/* Move the history offset down over the line. */
314 	gd->hscrolled++;
315 	gd->hsize++;
316 }
317 
318 /* Expand line to fit to cell. */
319 static void
320 grid_expand_line(struct grid *gd, u_int py, u_int sx, u_int bg)
321 {
322 	struct grid_line	*gl;
323 	u_int			 xx;
324 
325 	gl = &gd->linedata[py];
326 	if (sx <= gl->cellsize)
327 		return;
328 
329 	if (sx < gd->sx / 4)
330 		sx = gd->sx / 4;
331 	else if (sx < gd->sx / 2)
332 		sx = gd->sx / 2;
333 	else
334 		sx = gd->sx;
335 
336 	gl->celldata = xreallocarray(gl->celldata, sx, sizeof *gl->celldata);
337 	for (xx = gl->cellsize; xx < sx; xx++)
338 		grid_clear_cell(gd, xx, py, bg);
339 	gl->cellsize = sx;
340 }
341 
342 /* Empty a line and set background colour if needed. */
343 static void
344 grid_empty_line(struct grid *gd, u_int py, u_int bg)
345 {
346 	memset(&gd->linedata[py], 0, sizeof gd->linedata[py]);
347 	if (bg != 8)
348 		grid_expand_line(gd, py, gd->sx, bg);
349 }
350 
351 /* Peek at grid line. */
352 const struct grid_line *
353 grid_peek_line(struct grid *gd, u_int py)
354 {
355 	if (grid_check_y(gd, py) != 0)
356 		return (NULL);
357 	return (&gd->linedata[py]);
358 }
359 
360 /* Get cell for reading. */
361 void
362 grid_get_cell(struct grid *gd, u_int px, u_int py, struct grid_cell *gc)
363 {
364 	struct grid_line	*gl;
365 	struct grid_cell_entry	*gce;
366 
367 	if (grid_check_y(gd, py) != 0 || px >= gd->linedata[py].cellsize) {
368 		memcpy(gc, &grid_default_cell, sizeof *gc);
369 		return;
370 	}
371 
372 	gl = &gd->linedata[py];
373 	gce = &gl->celldata[px];
374 
375 	if (gce->flags & GRID_FLAG_EXTENDED) {
376 		if (gce->offset >= gl->extdsize)
377 			memcpy(gc, &grid_default_cell, sizeof *gc);
378 		else
379 			memcpy(gc, &gl->extddata[gce->offset], sizeof *gc);
380 		return;
381 	}
382 
383 	gc->flags = gce->flags & ~(GRID_FLAG_FG256|GRID_FLAG_BG256);
384 	gc->attr = gce->data.attr;
385 	gc->fg = gce->data.fg;
386 	if (gce->flags & GRID_FLAG_FG256)
387 		gc->fg |= COLOUR_FLAG_256;
388 	gc->bg = gce->data.bg;
389 	if (gce->flags & GRID_FLAG_BG256)
390 		gc->bg |= COLOUR_FLAG_256;
391 	utf8_set(&gc->data, gce->data.data);
392 }
393 
394 /* Set cell at relative position. */
395 void
396 grid_set_cell(struct grid *gd, u_int px, u_int py, const struct grid_cell *gc)
397 {
398 	struct grid_line	*gl;
399 	struct grid_cell_entry	*gce;
400 
401 	if (grid_check_y(gd, py) != 0)
402 		return;
403 
404 	grid_expand_line(gd, py, px + 1, 8);
405 
406 	gl = &gd->linedata[py];
407 	if (px + 1 > gl->cellused)
408 		gl->cellused = px + 1;
409 
410 	gce = &gl->celldata[px];
411 	if (grid_need_extended_cell(gce, gc))
412 		grid_extended_cell(gl, gce, gc);
413 	else
414 		grid_store_cell(gce, gc, gc->data.data[0]);
415 }
416 
417 /* Set cells at relative position. */
418 void
419 grid_set_cells(struct grid *gd, u_int px, u_int py, const struct grid_cell *gc,
420     const char *s, size_t slen)
421 {
422 	struct grid_line	*gl;
423 	struct grid_cell_entry	*gce;
424 	struct grid_cell	*gcp;
425 	u_int			 i;
426 
427 	if (grid_check_y(gd, py) != 0)
428 		return;
429 
430 	grid_expand_line(gd, py, px + slen, 8);
431 
432 	gl = &gd->linedata[py];
433 	if (px + slen > gl->cellused)
434 		gl->cellused = px + slen;
435 
436 	for (i = 0; i < slen; i++) {
437 		gce = &gl->celldata[px + i];
438 		if (grid_need_extended_cell(gce, gc)) {
439 			gcp = grid_extended_cell(gl, gce, gc);
440 			utf8_set(&gcp->data, s[i]);
441 		} else
442 			grid_store_cell(gce, gc, s[i]);
443 	}
444 }
445 
446 /* Clear area. */
447 void
448 grid_clear(struct grid *gd, u_int px, u_int py, u_int nx, u_int ny, u_int bg)
449 {
450 	u_int	xx, yy;
451 
452 	if (nx == 0 || ny == 0)
453 		return;
454 
455 	if (px == 0 && nx == gd->sx) {
456 		grid_clear_lines(gd, py, ny, bg);
457 		return;
458 	}
459 
460 	if (grid_check_y(gd, py) != 0)
461 		return;
462 	if (grid_check_y(gd, py + ny - 1) != 0)
463 		return;
464 
465 	for (yy = py; yy < py + ny; yy++) {
466 		if (px + nx >= gd->sx && px < gd->linedata[yy].cellused)
467 			gd->linedata[yy].cellused = px;
468 		if (px > gd->linedata[yy].cellsize && bg == 8)
469 			continue;
470 		if (px + nx >= gd->linedata[yy].cellsize && bg == 8) {
471 			gd->linedata[yy].cellsize = px;
472 			continue;
473 		}
474 		grid_expand_line(gd, yy, px + nx, 8); /* default bg first */
475 		for (xx = px; xx < px + nx; xx++)
476 			grid_clear_cell(gd, xx, yy, bg);
477 	}
478 }
479 
480 /* Clear lines. This just frees and truncates the lines. */
481 void
482 grid_clear_lines(struct grid *gd, u_int py, u_int ny, u_int bg)
483 {
484 	struct grid_line	*gl;
485 	u_int			 yy;
486 
487 	if (ny == 0)
488 		return;
489 
490 	if (grid_check_y(gd, py) != 0)
491 		return;
492 	if (grid_check_y(gd, py + ny - 1) != 0)
493 		return;
494 
495 	for (yy = py; yy < py + ny; yy++) {
496 		gl = &gd->linedata[yy];
497 		free(gl->celldata);
498 		free(gl->extddata);
499 		grid_empty_line(gd, yy, bg);
500 	}
501 }
502 
503 /* Move a group of lines. */
504 void
505 grid_move_lines(struct grid *gd, u_int dy, u_int py, u_int ny, u_int bg)
506 {
507 	u_int	yy;
508 
509 	if (ny == 0 || py == dy)
510 		return;
511 
512 	if (grid_check_y(gd, py) != 0)
513 		return;
514 	if (grid_check_y(gd, py + ny - 1) != 0)
515 		return;
516 	if (grid_check_y(gd, dy) != 0)
517 		return;
518 	if (grid_check_y(gd, dy + ny - 1) != 0)
519 		return;
520 
521 	/* Free any lines which are being replaced. */
522 	for (yy = dy; yy < dy + ny; yy++) {
523 		if (yy >= py && yy < py + ny)
524 			continue;
525 		grid_clear_lines(gd, yy, 1, bg);
526 	}
527 
528 	memmove(&gd->linedata[dy], &gd->linedata[py],
529 	    ny * (sizeof *gd->linedata));
530 
531 	/* Wipe any lines that have been moved (without freeing them). */
532 	for (yy = py; yy < py + ny; yy++) {
533 		if (yy < dy || yy >= dy + ny)
534 			grid_empty_line(gd, yy, bg);
535 	}
536 }
537 
538 /* Move a group of cells. */
539 void
540 grid_move_cells(struct grid *gd, u_int dx, u_int px, u_int py, u_int nx,
541     u_int bg)
542 {
543 	struct grid_line	*gl;
544 	u_int			 xx;
545 
546 	if (nx == 0 || px == dx)
547 		return;
548 
549 	if (grid_check_y(gd, py) != 0)
550 		return;
551 	gl = &gd->linedata[py];
552 
553 	grid_expand_line(gd, py, px + nx, 8);
554 	grid_expand_line(gd, py, dx + nx, 8);
555 	memmove(&gl->celldata[dx], &gl->celldata[px],
556 	    nx * sizeof *gl->celldata);
557 	if (dx + nx > gl->cellused)
558 		gl->cellused = dx + nx;
559 
560 	/* Wipe any cells that have been moved. */
561 	for (xx = px; xx < px + nx; xx++) {
562 		if (xx >= dx && xx < dx + nx)
563 			continue;
564 		grid_clear_cell(gd, xx, py, bg);
565 	}
566 }
567 
568 /* Get ANSI foreground sequence. */
569 static size_t
570 grid_string_cells_fg(const struct grid_cell *gc, int *values)
571 {
572 	size_t	n;
573 	u_char	r, g, b;
574 
575 	n = 0;
576 	if (gc->fg & COLOUR_FLAG_256) {
577 		values[n++] = 38;
578 		values[n++] = 5;
579 		values[n++] = gc->fg & 0xff;
580 	} else if (gc->fg & COLOUR_FLAG_RGB) {
581 		values[n++] = 38;
582 		values[n++] = 2;
583 		colour_split_rgb(gc->fg, &r, &g, &b);
584 		values[n++] = r;
585 		values[n++] = g;
586 		values[n++] = b;
587 	} else {
588 		switch (gc->fg) {
589 		case 0:
590 		case 1:
591 		case 2:
592 		case 3:
593 		case 4:
594 		case 5:
595 		case 6:
596 		case 7:
597 			values[n++] = gc->fg + 30;
598 			break;
599 		case 8:
600 			values[n++] = 39;
601 			break;
602 		case 90:
603 		case 91:
604 		case 92:
605 		case 93:
606 		case 94:
607 		case 95:
608 		case 96:
609 		case 97:
610 			values[n++] = gc->fg;
611 			break;
612 		}
613 	}
614 	return (n);
615 }
616 
617 /* Get ANSI background sequence. */
618 static size_t
619 grid_string_cells_bg(const struct grid_cell *gc, int *values)
620 {
621 	size_t	n;
622 	u_char	r, g, b;
623 
624 	n = 0;
625 	if (gc->bg & COLOUR_FLAG_256) {
626 		values[n++] = 48;
627 		values[n++] = 5;
628 		values[n++] = gc->bg & 0xff;
629 	} else if (gc->bg & COLOUR_FLAG_RGB) {
630 		values[n++] = 48;
631 		values[n++] = 2;
632 		colour_split_rgb(gc->bg, &r, &g, &b);
633 		values[n++] = r;
634 		values[n++] = g;
635 		values[n++] = b;
636 	} else {
637 		switch (gc->bg) {
638 		case 0:
639 		case 1:
640 		case 2:
641 		case 3:
642 		case 4:
643 		case 5:
644 		case 6:
645 		case 7:
646 			values[n++] = gc->bg + 40;
647 			break;
648 		case 8:
649 			values[n++] = 49;
650 			break;
651 		case 100:
652 		case 101:
653 		case 102:
654 		case 103:
655 		case 104:
656 		case 105:
657 		case 106:
658 		case 107:
659 			values[n++] = gc->bg - 10;
660 			break;
661 		}
662 	}
663 	return (n);
664 }
665 
666 /*
667  * Returns ANSI code to set particular attributes (colour, bold and so on)
668  * given a current state.
669  */
670 static void
671 grid_string_cells_code(const struct grid_cell *lastgc,
672     const struct grid_cell *gc, char *buf, size_t len, int escape_c0)
673 {
674 	int	oldc[64], newc[64], s[128];
675 	size_t	noldc, nnewc, n, i;
676 	u_int	attr = gc->attr, lastattr = lastgc->attr;
677 	char	tmp[64];
678 
679 	struct {
680 		u_int	mask;
681 		u_int	code;
682 	} attrs[] = {
683 		{ GRID_ATTR_BRIGHT, 1 },
684 		{ GRID_ATTR_DIM, 2 },
685 		{ GRID_ATTR_ITALICS, 3 },
686 		{ GRID_ATTR_UNDERSCORE, 4 },
687 		{ GRID_ATTR_BLINK, 5 },
688 		{ GRID_ATTR_REVERSE, 7 },
689 		{ GRID_ATTR_HIDDEN, 8 },
690 		{ GRID_ATTR_STRIKETHROUGH, 9 }
691 	};
692 	n = 0;
693 
694 	/* If any attribute is removed, begin with 0. */
695 	for (i = 0; i < nitems(attrs); i++) {
696 		if (!(attr & attrs[i].mask) && (lastattr & attrs[i].mask)) {
697 			s[n++] = 0;
698 			lastattr &= GRID_ATTR_CHARSET;
699 			break;
700 		}
701 	}
702 	/* For each attribute that is newly set, add its code. */
703 	for (i = 0; i < nitems(attrs); i++) {
704 		if ((attr & attrs[i].mask) && !(lastattr & attrs[i].mask))
705 			s[n++] = attrs[i].code;
706 	}
707 
708 	/* Write the attributes. */
709 	*buf = '\0';
710 	if (n > 0) {
711 		if (escape_c0)
712 			strlcat(buf, "\\033[", len);
713 		else
714 			strlcat(buf, "\033[", len);
715 		for (i = 0; i < n; i++) {
716 			if (i + 1 < n)
717 				xsnprintf(tmp, sizeof tmp, "%d;", s[i]);
718 			else
719 				xsnprintf(tmp, sizeof tmp, "%d", s[i]);
720 			strlcat(buf, tmp, len);
721 		}
722 		strlcat(buf, "m", len);
723 	}
724 
725 	/* If the foreground colour changed, write its parameters. */
726 	nnewc = grid_string_cells_fg(gc, newc);
727 	noldc = grid_string_cells_fg(lastgc, oldc);
728 	if (nnewc != noldc ||
729 	    memcmp(newc, oldc, nnewc * sizeof newc[0]) != 0 ||
730 	    (n != 0 && s[0] == 0)) {
731 		if (escape_c0)
732 			strlcat(buf, "\\033[", len);
733 		else
734 			strlcat(buf, "\033[", len);
735 		for (i = 0; i < nnewc; i++) {
736 			if (i + 1 < nnewc)
737 				xsnprintf(tmp, sizeof tmp, "%d;", newc[i]);
738 			else
739 				xsnprintf(tmp, sizeof tmp, "%d", newc[i]);
740 			strlcat(buf, tmp, len);
741 		}
742 		strlcat(buf, "m", len);
743 	}
744 
745 	/* If the background colour changed, append its parameters. */
746 	nnewc = grid_string_cells_bg(gc, newc);
747 	noldc = grid_string_cells_bg(lastgc, oldc);
748 	if (nnewc != noldc ||
749 	    memcmp(newc, oldc, nnewc * sizeof newc[0]) != 0 ||
750 	    (n != 0 && s[0] == 0)) {
751 		if (escape_c0)
752 			strlcat(buf, "\\033[", len);
753 		else
754 			strlcat(buf, "\033[", len);
755 		for (i = 0; i < nnewc; i++) {
756 			if (i + 1 < nnewc)
757 				xsnprintf(tmp, sizeof tmp, "%d;", newc[i]);
758 			else
759 				xsnprintf(tmp, sizeof tmp, "%d", newc[i]);
760 			strlcat(buf, tmp, len);
761 		}
762 		strlcat(buf, "m", len);
763 	}
764 
765 	/* Append shift in/shift out if needed. */
766 	if ((attr & GRID_ATTR_CHARSET) && !(lastattr & GRID_ATTR_CHARSET)) {
767 		if (escape_c0)
768 			strlcat(buf, "\\016", len); /* SO */
769 		else
770 			strlcat(buf, "\016", len);  /* SO */
771 	}
772 	if (!(attr & GRID_ATTR_CHARSET) && (lastattr & GRID_ATTR_CHARSET)) {
773 		if (escape_c0)
774 			strlcat(buf, "\\017", len); /* SI */
775 		else
776 			strlcat(buf, "\017", len);  /* SI */
777 	}
778 }
779 
780 /* Convert cells into a string. */
781 char *
782 grid_string_cells(struct grid *gd, u_int px, u_int py, u_int nx,
783     struct grid_cell **lastgc, int with_codes, int escape_c0, int trim)
784 {
785 	struct grid_cell	 gc;
786 	static struct grid_cell	 lastgc1;
787 	const char		*data;
788 	char			*buf, code[128];
789 	size_t			 len, off, size, codelen;
790 	u_int			 xx;
791 	const struct grid_line	*gl;
792 
793 	if (lastgc != NULL && *lastgc == NULL) {
794 		memcpy(&lastgc1, &grid_default_cell, sizeof lastgc1);
795 		*lastgc = &lastgc1;
796 	}
797 
798 	len = 128;
799 	buf = xmalloc(len);
800 	off = 0;
801 
802 	gl = grid_peek_line(gd, py);
803 	for (xx = px; xx < px + nx; xx++) {
804 		if (gl == NULL || xx >= gl->cellsize)
805 			break;
806 		grid_get_cell(gd, xx, py, &gc);
807 		if (gc.flags & GRID_FLAG_PADDING)
808 			continue;
809 
810 		if (with_codes) {
811 			grid_string_cells_code(*lastgc, &gc, code, sizeof code,
812 			    escape_c0);
813 			codelen = strlen(code);
814 			memcpy(*lastgc, &gc, sizeof **lastgc);
815 		} else
816 			codelen = 0;
817 
818 		data = gc.data.data;
819 		size = gc.data.size;
820 		if (escape_c0 && size == 1 && *data == '\\') {
821 			data = "\\\\";
822 			size = 2;
823 		}
824 
825 		while (len < off + size + codelen + 1) {
826 			buf = xreallocarray(buf, 2, len);
827 			len *= 2;
828 		}
829 
830 		if (codelen != 0) {
831 			memcpy(buf + off, code, codelen);
832 			off += codelen;
833 		}
834 		memcpy(buf + off, data, size);
835 		off += size;
836 	}
837 
838 	if (trim) {
839 		while (off > 0 && buf[off - 1] == ' ')
840 			off--;
841 	}
842 	buf[off] = '\0';
843 
844 	return (buf);
845 }
846 
847 /*
848  * Duplicate a set of lines between two grids. If there aren't enough lines in
849  * either source or destination, the number of lines is limited to the number
850  * available.
851  */
852 void
853 grid_duplicate_lines(struct grid *dst, u_int dy, struct grid *src, u_int sy,
854     u_int ny)
855 {
856 	struct grid_line	*dstl, *srcl;
857 	u_int			 yy;
858 
859 	if (dy + ny > dst->hsize + dst->sy)
860 		ny = dst->hsize + dst->sy - dy;
861 	if (sy + ny > src->hsize + src->sy)
862 		ny = src->hsize + src->sy - sy;
863 	grid_clear_lines(dst, dy, ny, 8);
864 
865 	for (yy = 0; yy < ny; yy++) {
866 		srcl = &src->linedata[sy];
867 		dstl = &dst->linedata[dy];
868 
869 		memcpy(dstl, srcl, sizeof *dstl);
870 		if (srcl->cellsize != 0) {
871 			dstl->celldata = xreallocarray(NULL,
872 			    srcl->cellsize, sizeof *dstl->celldata);
873 			memcpy(dstl->celldata, srcl->celldata,
874 			    srcl->cellsize * sizeof *dstl->celldata);
875 		} else
876 			dstl->celldata = NULL;
877 
878 		if (srcl->extdsize != 0) {
879 			dstl->extdsize = srcl->extdsize;
880 			dstl->extddata = xreallocarray(NULL, dstl->extdsize,
881 			    sizeof *dstl->extddata);
882 			memcpy(dstl->extddata, srcl->extddata, dstl->extdsize *
883 			    sizeof *dstl->extddata);
884 		}
885 
886 		sy++;
887 		dy++;
888 	}
889 }
890 
891 /* Copy a section of a line. */
892 static void
893 grid_reflow_copy(struct grid_line *dst_gl, u_int to, struct grid_line *src_gl,
894     u_int from, u_int to_copy)
895 {
896 	struct grid_cell_entry	*gce;
897 	u_int			 i, was;
898 
899 	memcpy(&dst_gl->celldata[to], &src_gl->celldata[from],
900 	    to_copy * sizeof *dst_gl->celldata);
901 
902 	for (i = to; i < to + to_copy; i++) {
903 		gce = &dst_gl->celldata[i];
904 		if (~gce->flags & GRID_FLAG_EXTENDED)
905 			continue;
906 		was = gce->offset;
907 
908 		dst_gl->extddata = xreallocarray(dst_gl->extddata,
909 		    dst_gl->extdsize + 1, sizeof *dst_gl->extddata);
910 		gce->offset = dst_gl->extdsize++;
911 		memcpy(&dst_gl->extddata[gce->offset], &src_gl->extddata[was],
912 		    sizeof *dst_gl->extddata);
913 	}
914 }
915 
916 /* Join line data. */
917 static void
918 grid_reflow_join(struct grid *dst, u_int *py, struct grid_line *src_gl,
919     u_int new_x)
920 {
921 	struct grid_line	*dst_gl = &dst->linedata[(*py) - 1];
922 	u_int			 left, to_copy, ox, nx;
923 
924 	/* How much is left on the old line? */
925 	left = new_x - dst_gl->cellused;
926 
927 	/* Work out how much to append. */
928 	to_copy = src_gl->cellused;
929 	if (to_copy > left)
930 		to_copy = left;
931 	ox = dst_gl->cellused;
932 	nx = ox + to_copy;
933 
934 	/* Resize the destination line. */
935 	dst_gl->celldata = xreallocarray(dst_gl->celldata, nx,
936 	    sizeof *dst_gl->celldata);
937 	dst_gl->cellsize = dst_gl->cellused = nx;
938 
939 	/* Append as much as possible. */
940 	grid_reflow_copy(dst_gl, ox, src_gl, 0, to_copy);
941 
942 	/* If there is any left in the source, split it. */
943 	if (src_gl->cellused > to_copy) {
944 		dst_gl->flags |= GRID_LINE_WRAPPED;
945 
946 		src_gl->cellused -= to_copy;
947 		grid_reflow_split(dst, py, src_gl, new_x, to_copy);
948 	}
949 }
950 
951 /* Split line data. */
952 static void
953 grid_reflow_split(struct grid *dst, u_int *py, struct grid_line *src_gl,
954     u_int new_x, u_int offset)
955 {
956 	struct grid_line	*dst_gl = NULL;
957 	u_int			 to_copy;
958 
959 	/* Loop and copy sections of the source line. */
960 	while (src_gl->cellused > 0) {
961 		/* Create new line. */
962 		if (*py >= dst->hsize + dst->sy)
963 			grid_scroll_history(dst, 8);
964 		dst_gl = &dst->linedata[*py];
965 		(*py)++;
966 
967 		/* How much should we copy? */
968 		to_copy = new_x;
969 		if (to_copy > src_gl->cellused)
970 			to_copy = src_gl->cellused;
971 
972 		/* Expand destination line. */
973 		dst_gl->celldata = xreallocarray(NULL, to_copy,
974 		    sizeof *dst_gl->celldata);
975 		dst_gl->cellsize = dst_gl->cellused = to_copy;
976 		dst_gl->flags |= GRID_LINE_WRAPPED;
977 
978 		/* Copy the data. */
979 		grid_reflow_copy(dst_gl, 0, src_gl, offset, to_copy);
980 
981 		/* Move offset and reduce old line size. */
982 		offset += to_copy;
983 		src_gl->cellused -= to_copy;
984 	}
985 
986 	/* Last line is not wrapped. */
987 	if (dst_gl != NULL)
988 		dst_gl->flags &= ~GRID_LINE_WRAPPED;
989 }
990 
991 /* Move line data. */
992 static void
993 grid_reflow_move(struct grid *dst, u_int *py, struct grid_line *src_gl)
994 {
995 	struct grid_line	*dst_gl;
996 
997 	/* Create new line. */
998 	if (*py >= dst->hsize + dst->sy)
999 		grid_scroll_history(dst, 8);
1000 	dst_gl = &dst->linedata[*py];
1001 	(*py)++;
1002 
1003 	/* Copy the old line. */
1004 	memcpy(dst_gl, src_gl, sizeof *dst_gl);
1005 	dst_gl->flags &= ~GRID_LINE_WRAPPED;
1006 
1007 	/* Clear old line. */
1008 	src_gl->celldata = NULL;
1009 	src_gl->extddata = NULL;
1010 }
1011 
1012 /*
1013  * Reflow lines from src grid into dst grid of width new_x. Returns number of
1014  * lines fewer in the visible area. The source grid is destroyed.
1015  */
1016 u_int
1017 grid_reflow(struct grid *dst, struct grid *src, u_int new_x)
1018 {
1019 	u_int			 py, sy, line;
1020 	int			 previous_wrapped;
1021 	struct grid_line	*src_gl;
1022 
1023 	py = 0;
1024 	sy = src->sy;
1025 
1026 	previous_wrapped = 0;
1027 	for (line = 0; line < sy + src->hsize; line++) {
1028 		src_gl = src->linedata + line;
1029 		if (!previous_wrapped) {
1030 			/* Wasn't wrapped. If smaller, move to destination. */
1031 			if (src_gl->cellused <= new_x)
1032 				grid_reflow_move(dst, &py, src_gl);
1033 			else
1034 				grid_reflow_split(dst, &py, src_gl, new_x, 0);
1035 		} else {
1036 			/* Previous was wrapped. Try to join. */
1037 			grid_reflow_join(dst, &py, src_gl, new_x);
1038 		}
1039 		previous_wrapped = (src_gl->flags & GRID_LINE_WRAPPED);
1040 
1041 		/* This is where we started scrolling. */
1042 		if (line == sy + src->hsize - src->hscrolled - 1)
1043 			dst->hscrolled = 0;
1044 	}
1045 
1046 	grid_destroy(src);
1047 
1048 	if (py > sy)
1049 		return (0);
1050 	return (sy - py);
1051 }
1052