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