xref: /freebsd/stand/common/gfx_fb.c (revision 3bcf8e6db8e9b30af0a1d445e6e413a332066434)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright 2020 Toomas Soome
5  * Copyright 2019 OmniOS Community Edition (OmniOSce) Association.
6  * Copyright 2020 RackTop Systems, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 /*
31  * The workhorse here is gfxfb_blt(). It is implemented to mimic UEFI
32  * GOP Blt, and allows us to fill the rectangle on screen, copy
33  * rectangle from video to buffer and buffer to video and video to video.
34  * Such implementation does allow us to have almost identical implementation
35  * for both BIOS VBE and UEFI.
36  *
37  * ALL pixel data is assumed to be 32-bit BGRA (byte order Blue, Green, Red,
38  * Alpha) format, this allows us to only handle RGB data and not to worry
39  * about mixing RGB with indexed colors.
40  * Data exchange between memory buffer and video will translate BGRA
41  * and native format as following:
42  *
43  * 32-bit to/from 32-bit is trivial case.
44  * 32-bit to/from 24-bit is also simple - we just drop the alpha channel.
45  * 32-bit to/from 16-bit is more complicated, because we nee to handle
46  * data loss from 32-bit to 16-bit. While reading/writing from/to video, we
47  * need to apply masks of 16-bit color components. This will preserve
48  * colors for terminal text. For 32-bit truecolor PMG images, we need to
49  * translate 32-bit colors to 15/16 bit colors and this means data loss.
50  * There are different algorithms how to perform such color space reduction,
51  * we are currently using bitwise right shift to reduce color space and so far
52  * this technique seems to be sufficient (see also gfx_fb_putimage(), the
53  * end of for loop).
54  * 32-bit to/from 8-bit is the most troublesome because 8-bit colors are
55  * indexed. From video, we do get color indexes, and we do translate
56  * color index values to RGB. To write to video, we again need to translate
57  * RGB to color index. Additionally, we need to translate between VGA and
58  * console colors.
59  *
60  * Our internal color data is represented using BGRA format. But the hardware
61  * used indexed colors for 8-bit colors (0-255) and for this mode we do
62  * need to perform translation to/from BGRA and index values.
63  *
64  *                   - paletteentry RGB <-> index -
65  * BGRA BUFFER <----/                              \ - VIDEO
66  *                  \                              /
67  *                   -  RGB (16/24/32)            -
68  *
69  * To perform index to RGB translation, we use palette table generated
70  * from when we set up 8-bit mode video. We cannot read palette data from
71  * the hardware, because not all hardware supports reading it.
72  *
73  * BGRA to index is implemented in rgb_to_color_index() by searching
74  * palette array for closest match of RBG values.
75  *
76  * Note: In 8-bit mode, We do store first 16 colors to palette registers
77  * in VGA color order, this serves two purposes; firstly,
78  * if palette update is not supported, we still have correct 16 colors.
79  * Secondly, the kernel does get correct 16 colors when some other boot
80  * loader is used. However, the palette map for 8-bit colors is using
81  * console color ordering - this does allow us to skip translation
82  * from VGA colors to console colors, while we are reading RGB data.
83  */
84 
85 #include <sys/param.h>
86 #include <stand.h>
87 #include <teken.h>
88 #include <gfx_fb.h>
89 #include <sys/font.h>
90 #include <sys/splash.h>
91 #include <sys/linker.h>
92 #include <sys/module.h>
93 #include <sys/stdint.h>
94 #include <sys/endian.h>
95 #include <pnglite.h>
96 #include <bootstrap.h>
97 #include <lz4.h>
98 #if defined(EFI)
99 #include <efi.h>
100 #include <efilib.h>
101 #else
102 #include <vbe.h>
103 #endif
104 
105 #include "modinfo.h"
106 
107 /* VGA text mode does use bold font. */
108 #if !defined(VGA_8X16_FONT)
109 #define	VGA_8X16_FONT		"/boot/fonts/8x16b.fnt"
110 #endif
111 #if !defined(DEFAULT_8X16_FONT)
112 #define	DEFAULT_8X16_FONT	"/boot/fonts/8x16.fnt"
113 #endif
114 
115 /*
116  * Must be sorted by font size in descending order
117  */
118 font_list_t fonts = STAILQ_HEAD_INITIALIZER(fonts);
119 
120 #define	DEFAULT_FONT_DATA	font_data_8x16
121 extern vt_font_bitmap_data_t	font_data_8x16;
122 teken_gfx_t gfx_state = { 0 };
123 
124 static struct {
125 	unsigned char r;	/* Red percentage value. */
126 	unsigned char g;	/* Green percentage value. */
127 	unsigned char b;	/* Blue percentage value. */
128 } color_def[NCOLORS] = {
129 	{0,	0,	0},	/* black */
130 	{50,	0,	0},	/* dark red */
131 	{0,	50,	0},	/* dark green */
132 	{77,	63,	0},	/* dark yellow */
133 	{20,	40,	64},	/* dark blue */
134 	{50,	0,	50},	/* dark magenta */
135 	{0,	50,	50},	/* dark cyan */
136 	{75,	75,	75},	/* light gray */
137 
138 	{18,	20,	21},	/* dark gray */
139 	{100,	0,	0},	/* light red */
140 	{0,	100,	0},	/* light green */
141 	{100,	100,	0},	/* light yellow */
142 	{45,	62,	81},	/* light blue */
143 	{100,	0,	100},	/* light magenta */
144 	{0,	100,	100},	/* light cyan */
145 	{100,	100,	100},	/* white */
146 };
147 uint32_t cmap[NCMAP];
148 
149 /*
150  * Between console's palette and VGA's one:
151  *  - blue and red are swapped (1 <-> 4)
152  *  - yellow and cyan are swapped (3 <-> 6)
153  */
154 const int cons_to_vga_colors[NCOLORS] = {
155 	0,  4,  2,  6,  1,  5,  3,  7,
156 	8, 12, 10, 14,  9, 13, 11, 15
157 };
158 
159 static const int vga_to_cons_colors[NCOLORS] = {
160 	0,  1,  2,  3,  4,  5,  6,  7,
161 	8,  9, 10, 11,  12, 13, 14, 15
162 };
163 
164 /*
165  * It is reported very slow console draw in some systems.
166  * in order to exclude buggy gop->Blt(), we want option
167  * to use direct draw to framebuffer and avoid gop->Blt.
168  * Can be toggled with "gop" command.
169  */
170 bool ignore_gop_blt = false;
171 
172 struct text_pixel *screen_buffer;
173 #if defined(EFI)
174 static EFI_GRAPHICS_OUTPUT_BLT_PIXEL *GlyphBuffer;
175 #else
176 static struct paletteentry *GlyphBuffer;
177 #endif
178 static size_t GlyphBufferSize;
179 
180 static bool insert_font(char *, FONT_FLAGS);
181 static int font_set(struct env_var *, int, const void *);
182 static void * allocate_glyphbuffer(uint32_t, uint32_t);
183 static void gfx_fb_cursor_draw(teken_gfx_t *, const teken_pos_t *, bool);
184 
185 /*
186  * Initialize gfx framework.
187  */
188 void
gfx_framework_init(void)189 gfx_framework_init(void)
190 {
191 	/*
192 	 * Setup font list to have builtin font.
193 	 */
194 	(void) insert_font(NULL, FONT_BUILTIN);
195 	gfx_interp_ref();	/* Draw in the gfx interpreter for this thing */
196 }
197 
198 static uint8_t *
gfx_get_fb_address(void)199 gfx_get_fb_address(void)
200 {
201 	return (ptov((uint32_t)gfx_state.tg_fb.fb_addr));
202 }
203 
204 /*
205  * Utility function to parse gfx mode line strings.
206  */
207 bool
gfx_parse_mode_str(char * str,int * x,int * y,int * depth)208 gfx_parse_mode_str(char *str, int *x, int *y, int *depth)
209 {
210 	char *p, *end;
211 
212 	errno = 0;
213 	p = str;
214 	*x = strtoul(p, &end, 0);
215 	if (*x == 0 || errno != 0)
216 		return (false);
217 	if (*end != 'x')
218 		return (false);
219 	p = end + 1;
220 	*y = strtoul(p, &end, 0);
221 	if (*y == 0 || errno != 0)
222 		return (false);
223 	if (*end != 'x') {
224 		*depth = -1;    /* auto select */
225 	} else {
226 		p = end + 1;
227 		*depth = strtoul(p, &end, 0);
228 		if (*depth == 0 || errno != 0 || *end != '\0')
229 			return (false);
230 	}
231 
232 	return (true);
233 }
234 
235 static uint32_t
rgb_color_map(uint8_t index,uint32_t rmax,int roffset,uint32_t gmax,int goffset,uint32_t bmax,int boffset)236 rgb_color_map(uint8_t index, uint32_t rmax, int roffset,
237     uint32_t gmax, int goffset, uint32_t bmax, int boffset)
238 {
239 	uint32_t color, code, gray, level;
240 
241 	if (index < NCOLORS) {
242 #define	CF(_f, _i) ((_f ## max * color_def[(_i)]._f / 100) << _f ## offset)
243 		return (CF(r, index) | CF(g, index) | CF(b, index));
244 #undef  CF
245         }
246 
247 #define	CF(_f, _c) ((_f ## max & _c) << _f ## offset)
248         /* 6x6x6 color cube */
249         if (index > 15 && index < 232) {
250                 uint32_t red, green, blue;
251 
252                 for (red = 0; red < 6; red++) {
253                         for (green = 0; green < 6; green++) {
254                                 for (blue = 0; blue < 6; blue++) {
255                                         code = 16 + (red * 36) +
256                                             (green * 6) + blue;
257                                         if (code != index)
258                                                 continue;
259                                         red = red ? (red * 40 + 55) : 0;
260                                         green = green ? (green * 40 + 55) : 0;
261                                         blue = blue ? (blue * 40 + 55) : 0;
262                                         color = CF(r, red);
263 					color |= CF(g, green);
264 					color |= CF(b, blue);
265 					return (color);
266                                 }
267                         }
268                 }
269         }
270 
271         /* colors 232-255 are a grayscale ramp */
272         for (gray = 0; gray < 24; gray++) {
273                 level = (gray * 10) + 8;
274                 code = 232 + gray;
275                 if (code == index)
276                         break;
277         }
278         return (CF(r, level) | CF(g, level) | CF(b, level));
279 #undef  CF
280 }
281 
282 /*
283  * Support for color mapping.
284  * For 8, 24 and 32 bit depth, use mask size 8.
285  * 15/16 bit depth needs to use mask size from mode,
286  * or we will lose color information from 32-bit to 15/16 bit translation.
287  */
288 uint32_t
gfx_fb_color_map(uint8_t index)289 gfx_fb_color_map(uint8_t index)
290 {
291 	int rmask, gmask, bmask;
292 	int roff, goff, boff, bpp;
293 
294 	roff = ffs(gfx_state.tg_fb.fb_mask_red) - 1;
295         goff = ffs(gfx_state.tg_fb.fb_mask_green) - 1;
296         boff = ffs(gfx_state.tg_fb.fb_mask_blue) - 1;
297 	bpp = roundup2(gfx_state.tg_fb.fb_bpp, 8) >> 3;
298 
299 	if (bpp == 2)
300 		rmask = gfx_state.tg_fb.fb_mask_red >> roff;
301 	else
302 		rmask = 0xff;
303 
304 	if (bpp == 2)
305 		gmask = gfx_state.tg_fb.fb_mask_green >> goff;
306 	else
307 		gmask = 0xff;
308 
309 	if (bpp == 2)
310 		bmask = gfx_state.tg_fb.fb_mask_blue >> boff;
311 	else
312 		bmask = 0xff;
313 
314 	return (rgb_color_map(index, rmask, 16, gmask, 8, bmask, 0));
315 }
316 
317 /*
318  * Get indexed color from RGB. This function is used to write data to video
319  * memory when the adapter is set to use indexed colors.
320  * Since UEFI does only support 32-bit colors, we do not implement it for
321  * UEFI because there is no need for it and we do not have palette array
322  * for UEFI.
323  */
324 static uint8_t
rgb_to_color_index(uint8_t r,uint8_t g,uint8_t b)325 rgb_to_color_index(uint8_t r, uint8_t g, uint8_t b)
326 {
327 #if !defined(EFI)
328 	uint32_t color, best, dist, k;
329 	int diff;
330 
331 	color = 0;
332 	best = 255 * 255 * 255;
333 	for (k = 0; k < NCMAP; k++) {
334 		diff = r - pe8[k].Red;
335 		dist = diff * diff;
336 		diff = g - pe8[k].Green;
337 		dist += diff * diff;
338 		diff = b - pe8[k].Blue;
339 		dist += diff * diff;
340 
341 		/* Exact match, exit the loop */
342 		if (dist == 0)
343 			break;
344 
345 		if (dist < best) {
346 			color = k;
347 			best = dist;
348 		}
349 	}
350 	if (k == NCMAP)
351 		k = color;
352 	return (k);
353 #else
354 	(void) r;
355 	(void) g;
356 	(void) b;
357 	return (0);
358 #endif
359 }
360 
361 int
generate_cons_palette(uint32_t * palette,int format,uint32_t rmax,int roffset,uint32_t gmax,int goffset,uint32_t bmax,int boffset)362 generate_cons_palette(uint32_t *palette, int format,
363     uint32_t rmax, int roffset, uint32_t gmax, int goffset,
364     uint32_t bmax, int boffset)
365 {
366 	int i;
367 
368 	switch (format) {
369 	case COLOR_FORMAT_VGA:
370 		for (i = 0; i < NCOLORS; i++)
371 			palette[i] = cons_to_vga_colors[i];
372 		for (; i < NCMAP; i++)
373 			palette[i] = i;
374 		break;
375 	case COLOR_FORMAT_RGB:
376 		for (i = 0; i < NCMAP; i++)
377 			palette[i] = rgb_color_map(i, rmax, roffset,
378 			    gmax, goffset, bmax, boffset);
379 		break;
380 	default:
381 		return (ENODEV);
382 	}
383 
384 	return (0);
385 }
386 
387 static void
gfx_mem_wr1(uint8_t * base,size_t size,uint32_t o,uint8_t v)388 gfx_mem_wr1(uint8_t *base, size_t size, uint32_t o, uint8_t v)
389 {
390 
391 	if (o >= size)
392 		return;
393 	*(uint8_t *)(base + o) = v;
394 }
395 
396 static void
gfx_mem_wr2(uint8_t * base,size_t size,uint32_t o,uint16_t v)397 gfx_mem_wr2(uint8_t *base, size_t size, uint32_t o, uint16_t v)
398 {
399 
400 	if (o >= size)
401 		return;
402 	*(uint16_t *)(base + o) = v;
403 }
404 
405 static void
gfx_mem_wr4(uint8_t * base,size_t size,uint32_t o,uint32_t v)406 gfx_mem_wr4(uint8_t *base, size_t size, uint32_t o, uint32_t v)
407 {
408 
409 	if (o >= size)
410 		return;
411 	*(uint32_t *)(base + o) = v;
412 }
413 
gfxfb_blt_fill(void * BltBuffer,uint32_t DestinationX,uint32_t DestinationY,uint32_t Width,uint32_t Height)414 static int gfxfb_blt_fill(void *BltBuffer,
415     uint32_t DestinationX, uint32_t DestinationY,
416     uint32_t Width, uint32_t Height)
417 {
418 #if defined(EFI)
419 	EFI_GRAPHICS_OUTPUT_BLT_PIXEL *p;
420 #else
421 	struct paletteentry *p;
422 #endif
423 	uint32_t data, bpp, pitch, y, x;
424 	int roff, goff, boff;
425 	size_t size;
426 	off_t off;
427 	uint8_t *destination;
428 
429 	if (BltBuffer == NULL)
430 		return (EINVAL);
431 
432 	if (DestinationY + Height > gfx_state.tg_fb.fb_height)
433 		return (EINVAL);
434 
435 	if (DestinationX + Width > gfx_state.tg_fb.fb_width)
436 		return (EINVAL);
437 
438 	if (Width == 0 || Height == 0)
439 		return (EINVAL);
440 
441 	p = BltBuffer;
442 	roff = ffs(gfx_state.tg_fb.fb_mask_red) - 1;
443 	goff = ffs(gfx_state.tg_fb.fb_mask_green) - 1;
444 	boff = ffs(gfx_state.tg_fb.fb_mask_blue) - 1;
445 
446 	if (gfx_state.tg_fb.fb_bpp == 8) {
447 		data = rgb_to_color_index(p->Red, p->Green, p->Blue);
448 	} else {
449 		data = (p->Red &
450 		    (gfx_state.tg_fb.fb_mask_red >> roff)) << roff;
451 		data |= (p->Green &
452 		    (gfx_state.tg_fb.fb_mask_green >> goff)) << goff;
453 		data |= (p->Blue &
454 		    (gfx_state.tg_fb.fb_mask_blue >> boff)) << boff;
455 	}
456 
457 	bpp = roundup2(gfx_state.tg_fb.fb_bpp, 8) >> 3;
458 	pitch = gfx_state.tg_fb.fb_stride * bpp;
459 	destination = gfx_get_fb_address();
460 	size = gfx_state.tg_fb.fb_size;
461 
462 	for (y = DestinationY; y < Height + DestinationY; y++) {
463 		off = y * pitch + DestinationX * bpp;
464 		for (x = 0; x < Width; x++) {
465 			switch (bpp) {
466 			case 1:
467 				gfx_mem_wr1(destination, size, off,
468 				    (data < NCOLORS) ?
469 				    cons_to_vga_colors[data] : data);
470 				break;
471 			case 2:
472 				gfx_mem_wr2(destination, size, off, data);
473 				break;
474 			case 3:
475 				gfx_mem_wr1(destination, size, off,
476 				    (data >> 16) & 0xff);
477 				gfx_mem_wr1(destination, size, off + 1,
478 				    (data >> 8) & 0xff);
479 				gfx_mem_wr1(destination, size, off + 2,
480 				    data & 0xff);
481 				break;
482 			case 4:
483 				gfx_mem_wr4(destination, size, off, data);
484 				break;
485 			default:
486 				return (EINVAL);
487 			}
488 			off += bpp;
489 		}
490 	}
491 
492 	return (0);
493 }
494 
495 static int
gfxfb_blt_video_to_buffer(void * BltBuffer,uint32_t SourceX,uint32_t SourceY,uint32_t DestinationX,uint32_t DestinationY,uint32_t Width,uint32_t Height,uint32_t Delta)496 gfxfb_blt_video_to_buffer(void *BltBuffer, uint32_t SourceX, uint32_t SourceY,
497     uint32_t DestinationX, uint32_t DestinationY,
498     uint32_t Width, uint32_t Height, uint32_t Delta)
499 {
500 #if defined(EFI)
501 	EFI_GRAPHICS_OUTPUT_BLT_PIXEL *p;
502 #else
503 	struct paletteentry *p;
504 #endif
505 	uint32_t x, sy, dy;
506 	uint32_t bpp, pitch, copybytes;
507 	off_t off;
508 	uint8_t *source, *destination, *sb;
509 	uint8_t rm, rp, gm, gp, bm, bp;
510 	bool bgra;
511 
512 	if (BltBuffer == NULL)
513 		return (EINVAL);
514 
515 	if (SourceY + Height >
516 	    gfx_state.tg_fb.fb_height)
517 		return (EINVAL);
518 
519 	if (SourceX + Width > gfx_state.tg_fb.fb_width)
520 		return (EINVAL);
521 
522 	if (Width == 0 || Height == 0)
523 		return (EINVAL);
524 
525 	if (Delta == 0)
526 		Delta = Width * sizeof (*p);
527 
528 	bpp = roundup2(gfx_state.tg_fb.fb_bpp, 8) >> 3;
529 	pitch = gfx_state.tg_fb.fb_stride * bpp;
530 
531 	copybytes = Width * bpp;
532 
533 	rp = ffs(gfx_state.tg_fb.fb_mask_red) - 1;
534 	gp = ffs(gfx_state.tg_fb.fb_mask_green) - 1;
535 	bp = ffs(gfx_state.tg_fb.fb_mask_blue) - 1;
536 	rm = gfx_state.tg_fb.fb_mask_red >> rp;
537 	gm = gfx_state.tg_fb.fb_mask_green >> gp;
538 	bm = gfx_state.tg_fb.fb_mask_blue >> bp;
539 
540 	/* If FB pixel format is BGRA, we can use direct copy. */
541 	bgra = bpp == 4 &&
542 	    ffs(rm) - 1 == 8 && rp == 16 &&
543 	    ffs(gm) - 1 == 8 && gp == 8 &&
544 	    ffs(bm) - 1 == 8 && bp == 0;
545 
546 	for (sy = SourceY, dy = DestinationY; dy < Height + DestinationY;
547 	    sy++, dy++) {
548 		off = sy * pitch + SourceX * bpp;
549 		source = gfx_get_fb_address() + off;
550 		destination = (uint8_t *)BltBuffer + dy * Delta +
551 		    DestinationX * sizeof (*p);
552 
553 		if (bgra) {
554 			bcopy(source, destination, copybytes);
555 		} else {
556 			for (x = 0; x < Width; x++) {
557 				uint32_t c = 0;
558 
559 				p = (void *)(destination + x * sizeof (*p));
560 				sb = source + x * bpp;
561 				switch (bpp) {
562 				case 1:
563 					c = *sb;
564 					break;
565 				case 2:
566 					c = *(uint16_t *)sb;
567 					break;
568 				case 3:
569 					c = sb[0] << 16 | sb[1] << 8 | sb[2];
570 					break;
571 				case 4:
572 					c = *(uint32_t *)sb;
573 					break;
574 				default:
575 					return (EINVAL);
576 				}
577 
578 				if (bpp == 1) {
579 					*(uint32_t *)p = gfx_fb_color_map(
580 					    (c < 16) ?
581 					    vga_to_cons_colors[c] : c);
582 				} else {
583 					p->Red = (c >> rp) & rm;
584 					p->Green = (c >> gp) & gm;
585 					p->Blue = (c >> bp) & bm;
586 					p->Reserved = 0;
587 				}
588 			}
589 		}
590 	}
591 
592 	return (0);
593 }
594 
595 static int
gfxfb_blt_buffer_to_video(void * BltBuffer,uint32_t SourceX,uint32_t SourceY,uint32_t DestinationX,uint32_t DestinationY,uint32_t Width,uint32_t Height,uint32_t Delta)596 gfxfb_blt_buffer_to_video(void *BltBuffer, uint32_t SourceX, uint32_t SourceY,
597     uint32_t DestinationX, uint32_t DestinationY,
598     uint32_t Width, uint32_t Height, uint32_t Delta)
599 {
600 #if defined(EFI)
601 	EFI_GRAPHICS_OUTPUT_BLT_PIXEL *p;
602 #else
603 	struct paletteentry *p;
604 #endif
605 	uint32_t x, sy, dy;
606 	uint32_t bpp, pitch, copybytes;
607 	off_t off;
608 	uint8_t *source, *destination;
609 	uint8_t rm, rp, gm, gp, bm, bp;
610 	bool bgra;
611 
612 	if (BltBuffer == NULL)
613 		return (EINVAL);
614 
615 	if (DestinationY + Height >
616 	    gfx_state.tg_fb.fb_height)
617 		return (EINVAL);
618 
619 	if (DestinationX + Width > gfx_state.tg_fb.fb_width)
620 		return (EINVAL);
621 
622 	if (Width == 0 || Height == 0)
623 		return (EINVAL);
624 
625 	if (Delta == 0)
626 		Delta = Width * sizeof (*p);
627 
628 	bpp = roundup2(gfx_state.tg_fb.fb_bpp, 8) >> 3;
629 	pitch = gfx_state.tg_fb.fb_stride * bpp;
630 
631 	copybytes = Width * bpp;
632 
633 	rp = ffs(gfx_state.tg_fb.fb_mask_red) - 1;
634 	gp = ffs(gfx_state.tg_fb.fb_mask_green) - 1;
635 	bp = ffs(gfx_state.tg_fb.fb_mask_blue) - 1;
636 	rm = gfx_state.tg_fb.fb_mask_red >> rp;
637 	gm = gfx_state.tg_fb.fb_mask_green >> gp;
638 	bm = gfx_state.tg_fb.fb_mask_blue >> bp;
639 
640 	/* If FB pixel format is BGRA, we can use direct copy. */
641 	bgra = bpp == 4 &&
642 	    ffs(rm) - 1 == 8 && rp == 16 &&
643 	    ffs(gm) - 1 == 8 && gp == 8 &&
644 	    ffs(bm) - 1 == 8 && bp == 0;
645 
646 	for (sy = SourceY, dy = DestinationY; sy < Height + SourceY;
647 	    sy++, dy++) {
648 		off = dy * pitch + DestinationX * bpp;
649 		destination = gfx_get_fb_address() + off;
650 
651 		if (bgra) {
652 			source = (uint8_t *)BltBuffer + sy * Delta +
653 			    SourceX * sizeof (*p);
654 			bcopy(source, destination, copybytes);
655 		} else {
656 			for (x = 0; x < Width; x++) {
657 				uint32_t c;
658 
659 				p = (void *)((uint8_t *)BltBuffer +
660 				    sy * Delta +
661 				    (SourceX + x) * sizeof (*p));
662 				if (bpp == 1) {
663 					c = rgb_to_color_index(p->Red,
664 					    p->Green, p->Blue);
665 				} else {
666 					c = (p->Red & rm) << rp |
667 					    (p->Green & gm) << gp |
668 					    (p->Blue & bm) << bp;
669 				}
670 				off = x * bpp;
671 				switch (bpp) {
672 				case 1:
673 					gfx_mem_wr1(destination, copybytes,
674 					    off, (c < 16) ?
675 					    cons_to_vga_colors[c] : c);
676 					break;
677 				case 2:
678 					gfx_mem_wr2(destination, copybytes,
679 					    off, c);
680 					break;
681 				case 3:
682 					gfx_mem_wr1(destination, copybytes,
683 					    off, (c >> 16) & 0xff);
684 					gfx_mem_wr1(destination, copybytes,
685 					    off + 1, (c >> 8) & 0xff);
686 					gfx_mem_wr1(destination, copybytes,
687 					    off + 2, c & 0xff);
688 					break;
689 				case 4:
690 					gfx_mem_wr4(destination, copybytes,
691 					    x * bpp, c);
692 					break;
693 				default:
694 					return (EINVAL);
695 				}
696 			}
697 		}
698 	}
699 
700 	return (0);
701 }
702 
703 static int
gfxfb_blt_video_to_video(uint32_t SourceX,uint32_t SourceY,uint32_t DestinationX,uint32_t DestinationY,uint32_t Width,uint32_t Height)704 gfxfb_blt_video_to_video(uint32_t SourceX, uint32_t SourceY,
705     uint32_t DestinationX, uint32_t DestinationY,
706     uint32_t Width, uint32_t Height)
707 {
708 	uint32_t bpp, copybytes;
709 	int pitch;
710 	uint8_t *source, *destination;
711 	off_t off;
712 
713 	if (SourceY + Height >
714 	    gfx_state.tg_fb.fb_height)
715 		return (EINVAL);
716 
717 	if (SourceX + Width > gfx_state.tg_fb.fb_width)
718 		return (EINVAL);
719 
720 	if (DestinationY + Height >
721 	    gfx_state.tg_fb.fb_height)
722 		return (EINVAL);
723 
724 	if (DestinationX + Width > gfx_state.tg_fb.fb_width)
725 		return (EINVAL);
726 
727 	if (Width == 0 || Height == 0)
728 		return (EINVAL);
729 
730 	bpp = roundup2(gfx_state.tg_fb.fb_bpp, 8) >> 3;
731 	pitch = gfx_state.tg_fb.fb_stride * bpp;
732 
733 	copybytes = Width * bpp;
734 
735 	off = SourceY * pitch + SourceX * bpp;
736 	source = gfx_get_fb_address() + off;
737 	off = DestinationY * pitch + DestinationX * bpp;
738 	destination = gfx_get_fb_address() + off;
739 
740 	if ((uintptr_t)destination > (uintptr_t)source) {
741 		source += Height * pitch;
742 		destination += Height * pitch;
743 		pitch = -pitch;
744 	}
745 
746 	while (Height-- > 0) {
747 		bcopy(source, destination, copybytes);
748 		source += pitch;
749 		destination += pitch;
750 	}
751 
752 	return (0);
753 }
754 
755 static void
gfxfb_shadow_fill(uint32_t * BltBuffer,uint32_t DestinationX,uint32_t DestinationY,uint32_t Width,uint32_t Height)756 gfxfb_shadow_fill(uint32_t *BltBuffer,
757     uint32_t DestinationX, uint32_t DestinationY,
758     uint32_t Width, uint32_t Height)
759 {
760 	uint32_t fbX, fbY;
761 
762 	if (gfx_state.tg_shadow_fb == NULL)
763 		return;
764 
765 	fbX = gfx_state.tg_fb.fb_width;
766 	fbY = gfx_state.tg_fb.fb_height;
767 
768 	if (BltBuffer == NULL)
769 		return;
770 
771 	if (DestinationX + Width > fbX)
772 		Width = fbX - DestinationX;
773 
774 	if (DestinationY + Height > fbY)
775 		Height = fbY - DestinationY;
776 
777 	uint32_t y2 = Height + DestinationY;
778 	for (uint32_t y1 = DestinationY; y1 < y2; y1++) {
779 		uint32_t off = y1 * fbX + DestinationX;
780 
781 		for (uint32_t x = 0; x < Width; x++) {
782 			gfx_state.tg_shadow_fb[off + x] = *BltBuffer;
783 		}
784 	}
785 }
786 
787 int
gfxfb_blt(void * BltBuffer,GFXFB_BLT_OPERATION BltOperation,uint32_t SourceX,uint32_t SourceY,uint32_t DestinationX,uint32_t DestinationY,uint32_t Width,uint32_t Height,uint32_t Delta)788 gfxfb_blt(void *BltBuffer, GFXFB_BLT_OPERATION BltOperation,
789     uint32_t SourceX, uint32_t SourceY,
790     uint32_t DestinationX, uint32_t DestinationY,
791     uint32_t Width, uint32_t Height, uint32_t Delta)
792 {
793 	int rv;
794 #if defined(EFI)
795 	EFI_STATUS status;
796 	EFI_GRAPHICS_OUTPUT *gop = gfx_state.tg_private;
797 	EFI_TPL tpl;
798 
799 	/*
800 	 * We assume Blt() does work, if not, we will need to build exception
801 	 * list case by case. We only have boot services during part of our
802 	 * exectution. Once terminate boot services, these operations cannot be
803 	 * done as they are provided by protocols that disappear when exit
804 	 * boot services.
805 	 */
806 	if (!ignore_gop_blt && gop != NULL && boot_services_active) {
807 		tpl = BS->RaiseTPL(TPL_NOTIFY);
808 		switch (BltOperation) {
809 		case GfxFbBltVideoFill:
810 			gfxfb_shadow_fill(BltBuffer, DestinationX,
811 			    DestinationY, Width, Height);
812 			status = gop->Blt(gop, BltBuffer, EfiBltVideoFill,
813 			    SourceX, SourceY, DestinationX, DestinationY,
814 			    Width, Height, Delta);
815 			break;
816 
817 		case GfxFbBltVideoToBltBuffer:
818 			status = gop->Blt(gop, BltBuffer,
819 			    EfiBltVideoToBltBuffer,
820 			    SourceX, SourceY, DestinationX, DestinationY,
821 			    Width, Height, Delta);
822 			break;
823 
824 		case GfxFbBltBufferToVideo:
825 			status = gop->Blt(gop, BltBuffer, EfiBltBufferToVideo,
826 			    SourceX, SourceY, DestinationX, DestinationY,
827 			    Width, Height, Delta);
828 			break;
829 
830 		case GfxFbBltVideoToVideo:
831 			status = gop->Blt(gop, BltBuffer, EfiBltVideoToVideo,
832 			    SourceX, SourceY, DestinationX, DestinationY,
833 			    Width, Height, Delta);
834 			break;
835 
836 		default:
837 			status = EFI_INVALID_PARAMETER;
838 			break;
839 		}
840 
841 		switch (status) {
842 		case EFI_SUCCESS:
843 			rv = 0;
844 			break;
845 
846 		case EFI_INVALID_PARAMETER:
847 			rv = EINVAL;
848 			break;
849 
850 		case EFI_DEVICE_ERROR:
851 		default:
852 			rv = EIO;
853 			break;
854 		}
855 
856 		BS->RestoreTPL(tpl);
857 		return (rv);
858 	}
859 #endif
860 
861 	switch (BltOperation) {
862 	case GfxFbBltVideoFill:
863 		gfxfb_shadow_fill(BltBuffer, DestinationX, DestinationY,
864 		    Width, Height);
865 		rv = gfxfb_blt_fill(BltBuffer, DestinationX, DestinationY,
866 		    Width, Height);
867 		break;
868 
869 	case GfxFbBltVideoToBltBuffer:
870 		rv = gfxfb_blt_video_to_buffer(BltBuffer, SourceX, SourceY,
871 		    DestinationX, DestinationY, Width, Height, Delta);
872 		break;
873 
874 	case GfxFbBltBufferToVideo:
875 		rv = gfxfb_blt_buffer_to_video(BltBuffer, SourceX, SourceY,
876 		    DestinationX, DestinationY, Width, Height, Delta);
877 		break;
878 
879 	case GfxFbBltVideoToVideo:
880 		rv = gfxfb_blt_video_to_video(SourceX, SourceY,
881 		    DestinationX, DestinationY, Width, Height);
882 		break;
883 
884 	default:
885 		rv = EINVAL;
886 		break;
887 	}
888 	return (rv);
889 }
890 
891 void
gfx_bitblt_bitmap(teken_gfx_t * state,const uint8_t * glyph,const teken_attr_t * a,uint32_t alpha,bool cursor)892 gfx_bitblt_bitmap(teken_gfx_t *state, const uint8_t *glyph,
893     const teken_attr_t *a, uint32_t alpha, bool cursor)
894 {
895 	uint32_t width, height;
896 	uint32_t fgc, bgc, bpl, cc, o;
897 	int bpp, bit, byte;
898 	bool invert = false;
899 
900 	bpp = 4;		/* We only generate BGRA */
901 	width = state->tg_font.vf_width;
902 	height = state->tg_font.vf_height;
903 	bpl = (width + 7) / 8;  /* Bytes per source line. */
904 
905 	fgc = a->ta_fgcolor;
906 	bgc = a->ta_bgcolor;
907 	if (a->ta_format & TF_BOLD)
908 		fgc |= TC_LIGHT;
909 	if (a->ta_format & TF_BLINK)
910 		bgc |= TC_LIGHT;
911 
912 	fgc = gfx_fb_color_map(fgc);
913 	bgc = gfx_fb_color_map(bgc);
914 
915 	if (a->ta_format & TF_REVERSE)
916 		invert = !invert;
917 	if (cursor)
918 		invert = !invert;
919 	if (invert) {
920 		uint32_t tmp;
921 
922 		tmp = fgc;
923 		fgc = bgc;
924 		bgc = tmp;
925 	}
926 
927 	alpha = alpha << 24;
928 	fgc |= alpha;
929 	bgc |= alpha;
930 
931 	for (uint32_t y = 0; y < height; y++) {
932 		for (uint32_t x = 0; x < width; x++) {
933 			byte = y * bpl + x / 8;
934 			bit = 0x80 >> (x % 8);
935 			o = y * width * bpp + x * bpp;
936 			cc = glyph[byte] & bit ? fgc : bgc;
937 
938 			gfx_mem_wr4(state->tg_glyph,
939 			    state->tg_glyph_size, o, cc);
940 		}
941 	}
942 }
943 
944 /*
945  * Draw prepared glyph on terminal point p.
946  */
947 static void
gfx_fb_printchar(teken_gfx_t * state,const teken_pos_t * p)948 gfx_fb_printchar(teken_gfx_t *state, const teken_pos_t *p)
949 {
950 	unsigned x, y, width, height;
951 
952 	width = state->tg_font.vf_width;
953 	height = state->tg_font.vf_height;
954 	x = state->tg_origin.tp_col + p->tp_col * width;
955 	y = state->tg_origin.tp_row + p->tp_row * height;
956 
957 	gfx_fb_cons_display(x, y, width, height, state->tg_glyph);
958 }
959 
960 /*
961  * Store char with its attribute to buffer and put it on screen.
962  */
963 void
gfx_fb_putchar(void * arg,const teken_pos_t * p,teken_char_t c,const teken_attr_t * a)964 gfx_fb_putchar(void *arg, const teken_pos_t *p, teken_char_t c,
965     const teken_attr_t *a)
966 {
967 	teken_gfx_t *state = arg;
968 	const uint8_t *glyph;
969 	int idx;
970 
971 	idx = p->tp_col + p->tp_row * state->tg_tp.tp_col;
972 	if (idx >= state->tg_tp.tp_col * state->tg_tp.tp_row)
973 		return;
974 
975 	/* remove the cursor */
976 	if (state->tg_cursor_visible)
977 		gfx_fb_cursor_draw(state, &state->tg_cursor, false);
978 
979 	screen_buffer[idx].c = c;
980 	screen_buffer[idx].a = *a;
981 
982 	glyph = font_lookup(&state->tg_font, c, a);
983 	gfx_bitblt_bitmap(state, glyph, a, 0xff, false);
984 	gfx_fb_printchar(state, p);
985 
986 	/* display the cursor */
987 	if (state->tg_cursor_visible) {
988 		const teken_pos_t *c;
989 
990 		c = teken_get_cursor(&state->tg_teken);
991 		gfx_fb_cursor_draw(state, c, true);
992 	}
993 }
994 
995 void
gfx_fb_fill(void * arg,const teken_rect_t * r,teken_char_t c,const teken_attr_t * a)996 gfx_fb_fill(void *arg, const teken_rect_t *r, teken_char_t c,
997     const teken_attr_t *a)
998 {
999 	teken_gfx_t *state = arg;
1000 	const uint8_t *glyph;
1001 	teken_pos_t p;
1002 	struct text_pixel *row;
1003 
1004 	TSENTER();
1005 
1006 	/* remove the cursor */
1007 	if (state->tg_cursor_visible)
1008 		gfx_fb_cursor_draw(state, &state->tg_cursor, false);
1009 
1010 	glyph = font_lookup(&state->tg_font, c, a);
1011 	gfx_bitblt_bitmap(state, glyph, a, 0xff, false);
1012 
1013 	for (p.tp_row = r->tr_begin.tp_row; p.tp_row < r->tr_end.tp_row;
1014 	    p.tp_row++) {
1015 		row = &screen_buffer[p.tp_row * state->tg_tp.tp_col];
1016 		for (p.tp_col = r->tr_begin.tp_col;
1017 		    p.tp_col < r->tr_end.tp_col; p.tp_col++) {
1018 			row[p.tp_col].c = c;
1019 			row[p.tp_col].a = *a;
1020 			gfx_fb_printchar(state, &p);
1021 		}
1022 	}
1023 
1024 	/* display the cursor */
1025 	if (state->tg_cursor_visible) {
1026 		const teken_pos_t *c;
1027 
1028 		c = teken_get_cursor(&state->tg_teken);
1029 		gfx_fb_cursor_draw(state, c, true);
1030 	}
1031 
1032 	TSEXIT();
1033 }
1034 
1035 static void
gfx_fb_cursor_draw(teken_gfx_t * state,const teken_pos_t * pos,bool on)1036 gfx_fb_cursor_draw(teken_gfx_t *state, const teken_pos_t *pos, bool on)
1037 {
1038 	const uint8_t *glyph;
1039 	teken_pos_t p;
1040 	int idx;
1041 
1042 	p = *pos;
1043 	if (p.tp_col >= state->tg_tp.tp_col)
1044 		p.tp_col = state->tg_tp.tp_col - 1;
1045 	if (p.tp_row >= state->tg_tp.tp_row)
1046 		p.tp_row = state->tg_tp.tp_row - 1;
1047 	idx = p.tp_col + p.tp_row * state->tg_tp.tp_col;
1048 	if (idx >= state->tg_tp.tp_col * state->tg_tp.tp_row)
1049 		return;
1050 
1051 	glyph = font_lookup(&state->tg_font, screen_buffer[idx].c,
1052 	    &screen_buffer[idx].a);
1053 	gfx_bitblt_bitmap(state, glyph, &screen_buffer[idx].a, 0xff, on);
1054 	gfx_fb_printchar(state, &p);
1055 
1056 	state->tg_cursor = p;
1057 }
1058 
1059 void
gfx_fb_cursor(void * arg,const teken_pos_t * p)1060 gfx_fb_cursor(void *arg, const teken_pos_t *p)
1061 {
1062 	teken_gfx_t *state = arg;
1063 
1064 	/* Switch cursor off in old location and back on in new. */
1065 	if (state->tg_cursor_visible) {
1066 		gfx_fb_cursor_draw(state, &state->tg_cursor, false);
1067 		gfx_fb_cursor_draw(state, p, true);
1068 	}
1069 }
1070 
1071 void
gfx_fb_param(void * arg,int cmd,unsigned int value)1072 gfx_fb_param(void *arg, int cmd, unsigned int value)
1073 {
1074 	teken_gfx_t *state = arg;
1075 	const teken_pos_t *c;
1076 
1077 	switch (cmd) {
1078 	case TP_SETLOCALCURSOR:
1079 		/*
1080 		 * 0 means normal (usually block), 1 means hidden, and
1081 		 * 2 means blinking (always block) for compatibility with
1082 		 * syscons.  We don't support any changes except hiding,
1083 		 * so must map 2 to 0.
1084 		 */
1085 		value = (value == 1) ? 0 : 1;
1086 		/* FALLTHROUGH */
1087 	case TP_SHOWCURSOR:
1088 		c = teken_get_cursor(&state->tg_teken);
1089 		gfx_fb_cursor_draw(state, c, true);
1090 		if (value != 0)
1091 			state->tg_cursor_visible = true;
1092 		else
1093 			state->tg_cursor_visible = false;
1094 		break;
1095 	default:
1096 		/* Not yet implemented */
1097 		break;
1098 	}
1099 }
1100 
1101 bool
is_same_pixel(struct text_pixel * px1,struct text_pixel * px2)1102 is_same_pixel(struct text_pixel *px1, struct text_pixel *px2)
1103 {
1104 	if (px1->c != px2->c)
1105 		return (false);
1106 
1107 	/* Is there image stored? */
1108 	if ((px1->a.ta_format & TF_IMAGE) ||
1109 	    (px2->a.ta_format & TF_IMAGE))
1110 		return (false);
1111 
1112 	if (px1->a.ta_format != px2->a.ta_format)
1113 		return (false);
1114 	if (px1->a.ta_fgcolor != px2->a.ta_fgcolor)
1115 		return (false);
1116 	if (px1->a.ta_bgcolor != px2->a.ta_bgcolor)
1117 		return (false);
1118 
1119 	return (true);
1120 }
1121 
1122 static void
gfx_fb_copy_area(teken_gfx_t * state,const teken_rect_t * s,const teken_pos_t * d)1123 gfx_fb_copy_area(teken_gfx_t *state, const teken_rect_t *s,
1124     const teken_pos_t *d)
1125 {
1126 	uint32_t sx, sy, dx, dy, width, height;
1127 	uint32_t pitch, bytes;
1128 	int step;
1129 
1130 	width = state->tg_font.vf_width;
1131 	height = state->tg_font.vf_height;
1132 
1133 	sx = s->tr_begin.tp_col * width;
1134 	sy = s->tr_begin.tp_row * height;
1135 	dx = d->tp_col * width;
1136 	dy = d->tp_row * height;
1137 
1138 	width *= (s->tr_end.tp_col - s->tr_begin.tp_col + 1);
1139 
1140 	/*
1141 	 * With no shadow fb, use video to video copy.
1142 	 */
1143 	if (state->tg_shadow_fb == NULL) {
1144 		(void) gfxfb_blt(NULL, GfxFbBltVideoToVideo,
1145 		    sx + state->tg_origin.tp_col,
1146 		    sy + state->tg_origin.tp_row,
1147 		    dx + state->tg_origin.tp_col,
1148 		    dy + state->tg_origin.tp_row,
1149 		    width, height, 0);
1150 		return;
1151 	}
1152 
1153 	/*
1154 	 * With shadow fb, we need to copy data on both shadow and video,
1155 	 * to preserve the consistency. We only read data from shadow fb.
1156 	 */
1157 
1158 	step = 1;
1159 	pitch = state->tg_fb.fb_width;
1160 	bytes = width * sizeof (*state->tg_shadow_fb);
1161 
1162 	/*
1163 	 * To handle overlapping areas, set up reverse copy here.
1164 	 */
1165 	if (dy * pitch + dx > sy * pitch + sx) {
1166 		sy += height;
1167 		dy += height;
1168 		step = -step;
1169 	}
1170 
1171 	while (height-- > 0) {
1172 		uint32_t *source = &state->tg_shadow_fb[sy * pitch + sx];
1173 		uint32_t *destination = &state->tg_shadow_fb[dy * pitch + dx];
1174 
1175 		bcopy(source, destination, bytes);
1176 		(void) gfxfb_blt(destination, GfxFbBltBufferToVideo,
1177 		    0, 0, dx + state->tg_origin.tp_col,
1178 		    dy + state->tg_origin.tp_row, width, 1, 0);
1179 
1180 		sy += step;
1181 		dy += step;
1182 	}
1183 }
1184 
1185 static void
gfx_fb_copy_line(teken_gfx_t * state,int ncol,teken_pos_t * s,teken_pos_t * d)1186 gfx_fb_copy_line(teken_gfx_t *state, int ncol, teken_pos_t *s, teken_pos_t *d)
1187 {
1188 	teken_rect_t sr;
1189 	teken_pos_t dp;
1190 	unsigned soffset, doffset;
1191 	bool mark = false;
1192 	int x;
1193 
1194 	soffset = s->tp_col + s->tp_row * state->tg_tp.tp_col;
1195 	doffset = d->tp_col + d->tp_row * state->tg_tp.tp_col;
1196 
1197 	for (x = 0; x < ncol; x++) {
1198 		if (is_same_pixel(&screen_buffer[soffset + x],
1199 		    &screen_buffer[doffset + x])) {
1200 			if (mark) {
1201 				gfx_fb_copy_area(state, &sr, &dp);
1202 				mark = false;
1203 			}
1204 		} else {
1205 			screen_buffer[doffset + x] = screen_buffer[soffset + x];
1206 			if (mark) {
1207 				/* update end point */
1208 				sr.tr_end.tp_col = s->tp_col + x;
1209 			} else {
1210 				/* set up new rectangle */
1211 				mark = true;
1212 				sr.tr_begin.tp_col = s->tp_col + x;
1213 				sr.tr_begin.tp_row = s->tp_row;
1214 				sr.tr_end.tp_col = s->tp_col + x;
1215 				sr.tr_end.tp_row = s->tp_row;
1216 				dp.tp_col = d->tp_col + x;
1217 				dp.tp_row = d->tp_row;
1218 			}
1219 		}
1220 	}
1221 	if (mark) {
1222 		gfx_fb_copy_area(state, &sr, &dp);
1223 	}
1224 }
1225 
1226 void
gfx_fb_copy(void * arg,const teken_rect_t * r,const teken_pos_t * p)1227 gfx_fb_copy(void *arg, const teken_rect_t *r, const teken_pos_t *p)
1228 {
1229 	teken_gfx_t *state = arg;
1230 	unsigned doffset, soffset;
1231 	teken_pos_t d, s;
1232 	int nrow, ncol, y; /* Has to be signed - >= 0 comparison */
1233 
1234 	/*
1235 	 * Copying is a little tricky. We must make sure we do it in
1236 	 * correct order, to make sure we don't overwrite our own data.
1237 	 */
1238 
1239 	nrow = r->tr_end.tp_row - r->tr_begin.tp_row;
1240 	ncol = r->tr_end.tp_col - r->tr_begin.tp_col;
1241 
1242 	if (p->tp_row + nrow > state->tg_tp.tp_row ||
1243 	    p->tp_col + ncol > state->tg_tp.tp_col)
1244 		return;
1245 
1246 	soffset = r->tr_begin.tp_col + r->tr_begin.tp_row * state->tg_tp.tp_col;
1247 	doffset = p->tp_col + p->tp_row * state->tg_tp.tp_col;
1248 
1249 	/* remove the cursor */
1250 	if (state->tg_cursor_visible)
1251 		gfx_fb_cursor_draw(state, &state->tg_cursor, false);
1252 
1253 	/*
1254 	 * Copy line by line.
1255 	 */
1256 	if (doffset <= soffset) {
1257 		s = r->tr_begin;
1258 		d = *p;
1259 		for (y = 0; y < nrow; y++) {
1260 			s.tp_row = r->tr_begin.tp_row + y;
1261 			d.tp_row = p->tp_row + y;
1262 
1263 			gfx_fb_copy_line(state, ncol, &s, &d);
1264 		}
1265 	} else {
1266 		for (y = nrow - 1; y >= 0; y--) {
1267 			s.tp_row = r->tr_begin.tp_row + y;
1268 			d.tp_row = p->tp_row + y;
1269 
1270 			gfx_fb_copy_line(state, ncol, &s, &d);
1271 		}
1272 	}
1273 
1274 	/* display the cursor */
1275 	if (state->tg_cursor_visible) {
1276 		const teken_pos_t *c;
1277 
1278 		c = teken_get_cursor(&state->tg_teken);
1279 		gfx_fb_cursor_draw(state, c, true);
1280 	}
1281 }
1282 
1283 /*
1284  * Implements alpha blending for RGBA data, could use pixels for arguments,
1285  * but byte stream seems more generic.
1286  * The generic alpha blending is:
1287  * blend = alpha * fg + (1.0 - alpha) * bg.
1288  * Since our alpha is not from range [0..1], we scale appropriately.
1289  */
1290 static uint8_t
alpha_blend(uint8_t fg,uint8_t bg,uint8_t alpha)1291 alpha_blend(uint8_t fg, uint8_t bg, uint8_t alpha)
1292 {
1293 	uint16_t blend, h, l;
1294 
1295 	/* trivial corner cases */
1296 	if (alpha == 0)
1297 		return (bg);
1298 	if (alpha == 0xFF)
1299 		return (fg);
1300 	blend = (alpha * fg + (0xFF - alpha) * bg);
1301 	/* Division by 0xFF */
1302 	h = blend >> 8;
1303 	l = blend & 0xFF;
1304 	if (h + l >= 0xFF)
1305 		h++;
1306 	return (h);
1307 }
1308 
1309 /*
1310  * Implements alpha blending for RGBA data, could use pixels for arguments,
1311  * but byte stream seems more generic.
1312  * The generic alpha blending is:
1313  * blend = alpha * fg + (1.0 - alpha) * bg.
1314  * Since our alpha is not from range [0..1], we scale appropriately.
1315  */
1316 static void
bitmap_cpy(void * dst,void * src,uint32_t size)1317 bitmap_cpy(void *dst, void *src, uint32_t size)
1318 {
1319 #if defined(EFI)
1320 	EFI_GRAPHICS_OUTPUT_BLT_PIXEL *ps, *pd;
1321 #else
1322 	struct paletteentry *ps, *pd;
1323 #endif
1324 	uint32_t i;
1325 	uint8_t a;
1326 
1327 	ps = src;
1328 	pd = dst;
1329 
1330 	/*
1331 	 * we only implement alpha blending for depth 32.
1332 	 */
1333 	for (i = 0; i < size; i ++) {
1334 		a = ps[i].Reserved;
1335 		pd[i].Red = alpha_blend(ps[i].Red, pd[i].Red, a);
1336 		pd[i].Green = alpha_blend(ps[i].Green, pd[i].Green, a);
1337 		pd[i].Blue = alpha_blend(ps[i].Blue, pd[i].Blue, a);
1338 		pd[i].Reserved = a;
1339 	}
1340 }
1341 
1342 static void *
allocate_glyphbuffer(uint32_t width,uint32_t height)1343 allocate_glyphbuffer(uint32_t width, uint32_t height)
1344 {
1345 	size_t size;
1346 
1347 	size = sizeof (*GlyphBuffer) * width * height;
1348 	if (size != GlyphBufferSize) {
1349 		free(GlyphBuffer);
1350 		GlyphBuffer = malloc(size);
1351 		if (GlyphBuffer == NULL)
1352 			return (NULL);
1353 		GlyphBufferSize = size;
1354 	}
1355 	return (GlyphBuffer);
1356 }
1357 
1358 void
gfx_fb_cons_display(uint32_t x,uint32_t y,uint32_t width,uint32_t height,void * data)1359 gfx_fb_cons_display(uint32_t x, uint32_t y, uint32_t width, uint32_t height,
1360     void *data)
1361 {
1362 #if defined(EFI)
1363 	EFI_GRAPHICS_OUTPUT_BLT_PIXEL *buf, *p;
1364 #else
1365 	struct paletteentry *buf, *p;
1366 #endif
1367 	size_t size;
1368 
1369 	/*
1370 	 * If we do have shadow fb, we will use shadow to render data,
1371 	 * and copy shadow to video.
1372 	 */
1373 	if (gfx_state.tg_shadow_fb != NULL) {
1374 		uint32_t pitch = gfx_state.tg_fb.fb_width;
1375 
1376 		/* Copy rectangle line by line. */
1377 		p = data;
1378 		for (uint32_t sy = 0; sy < height; sy++) {
1379 			buf = (void *)(gfx_state.tg_shadow_fb +
1380 			    (y - gfx_state.tg_origin.tp_row) * pitch +
1381 			    x - gfx_state.tg_origin.tp_col);
1382 			bitmap_cpy(buf, &p[sy * width], width);
1383 			(void) gfxfb_blt(buf, GfxFbBltBufferToVideo,
1384 			    0, 0, x, y, width, 1, 0);
1385 			y++;
1386 		}
1387 		return;
1388 	}
1389 
1390 	/*
1391 	 * Common data to display is glyph, use preallocated
1392 	 * glyph buffer.
1393 	 */
1394         if (gfx_state.tg_glyph_size != GlyphBufferSize)
1395                 (void) allocate_glyphbuffer(width, height);
1396 
1397 	size = width * height * sizeof(*buf);
1398 	if (size == GlyphBufferSize)
1399 		buf = GlyphBuffer;
1400 	else
1401 		buf = malloc(size);
1402 	if (buf == NULL)
1403 		return;
1404 
1405 	if (gfxfb_blt(buf, GfxFbBltVideoToBltBuffer, x, y, 0, 0,
1406 	    width, height, 0) == 0) {
1407 		bitmap_cpy(buf, data, width * height);
1408 		(void) gfxfb_blt(buf, GfxFbBltBufferToVideo, 0, 0, x, y,
1409 		    width, height, 0);
1410 	}
1411 	if (buf != GlyphBuffer)
1412 		free(buf);
1413 }
1414 
1415 /*
1416  * Public graphics primitives.
1417  */
1418 
1419 static int
isqrt(int num)1420 isqrt(int num)
1421 {
1422 	int res = 0;
1423 	int bit = 1 << 30;
1424 
1425 	/* "bit" starts at the highest power of four <= the argument. */
1426 	while (bit > num)
1427 		bit >>= 2;
1428 
1429 	while (bit != 0) {
1430 		if (num >= res + bit) {
1431 			num -= res + bit;
1432 			res = (res >> 1) + bit;
1433 		} else {
1434 			res >>= 1;
1435 		}
1436 		bit >>= 2;
1437 	}
1438 	return (res);
1439 }
1440 
1441 static uint32_t
gfx_fb_getcolor(void)1442 gfx_fb_getcolor(void)
1443 {
1444 	uint32_t c;
1445 	const teken_attr_t *ap;
1446 
1447 	ap = teken_get_curattr(&gfx_state.tg_teken);
1448         if (ap->ta_format & TF_REVERSE) {
1449 		c = ap->ta_bgcolor;
1450 		if (ap->ta_format & TF_BLINK)
1451 			c |= TC_LIGHT;
1452 	} else {
1453 		c = ap->ta_fgcolor;
1454 		if (ap->ta_format & TF_BOLD)
1455 			c |= TC_LIGHT;
1456 	}
1457 
1458 	return (gfx_fb_color_map(c));
1459 }
1460 
1461 /* set pixel in framebuffer using gfx coordinates */
1462 void
gfx_fb_setpixel(uint32_t x,uint32_t y)1463 gfx_fb_setpixel(uint32_t x, uint32_t y)
1464 {
1465 	uint32_t c;
1466 
1467 	if (gfx_state.tg_fb_type == FB_TEXT)
1468 		return;
1469 
1470 	c = gfx_fb_getcolor();
1471 
1472 	if (x >= gfx_state.tg_fb.fb_width ||
1473 	    y >= gfx_state.tg_fb.fb_height)
1474 		return;
1475 
1476 	gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x, y, 1, 1, 0);
1477 }
1478 
1479 /*
1480  * draw rectangle in framebuffer using gfx coordinates.
1481  */
1482 void
gfx_fb_drawrect(uint32_t x1,uint32_t y1,uint32_t x2,uint32_t y2,uint32_t fill)1483 gfx_fb_drawrect(uint32_t x1, uint32_t y1, uint32_t x2, uint32_t y2,
1484     uint32_t fill)
1485 {
1486 	uint32_t c;
1487 
1488 	if (gfx_state.tg_fb_type == FB_TEXT)
1489 		return;
1490 
1491 	c = gfx_fb_getcolor();
1492 
1493 	if (fill != 0) {
1494 		gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x1, y1, x2 - x1,
1495 		    y2 - y1, 0);
1496 	} else {
1497 		gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x1, y1, x2 - x1, 1, 0);
1498 		gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x1, y2, x2 - x1, 1, 0);
1499 		gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x1, y1, 1, y2 - y1, 0);
1500 		gfxfb_blt(&c, GfxFbBltVideoFill, 0, 0, x2, y1, 1, y2 - y1, 0);
1501 	}
1502 }
1503 
1504 void
gfx_fb_line(uint32_t x0,uint32_t y0,uint32_t x1,uint32_t y1,uint32_t wd)1505 gfx_fb_line(uint32_t x0, uint32_t y0, uint32_t x1, uint32_t y1, uint32_t wd)
1506 {
1507 	int dx, sx, dy, sy;
1508 	int err, e2, x2, y2, ed, width;
1509 
1510 	if (gfx_state.tg_fb_type == FB_TEXT)
1511 		return;
1512 
1513 	width = wd;
1514 	sx = x0 < x1? 1 : -1;
1515 	sy = y0 < y1? 1 : -1;
1516 	dx = x1 > x0? x1 - x0 : x0 - x1;
1517 	dy = y1 > y0? y1 - y0 : y0 - y1;
1518 	err = dx + dy;
1519 	ed = dx + dy == 0 ? 1: isqrt(dx * dx + dy * dy);
1520 
1521 	for (;;) {
1522 		gfx_fb_setpixel(x0, y0);
1523 		e2 = err;
1524 		x2 = x0;
1525 		if ((e2 << 1) >= -dx) {		/* x step */
1526 			e2 += dy;
1527 			y2 = y0;
1528 			while (e2 < ed * width &&
1529 			    (y1 != (uint32_t)y2 || dx > dy)) {
1530 				y2 += sy;
1531 				gfx_fb_setpixel(x0, y2);
1532 				e2 += dx;
1533 			}
1534 			if (x0 == x1)
1535 				break;
1536 			e2 = err;
1537 			err -= dy;
1538 			x0 += sx;
1539 		}
1540 		if ((e2 << 1) <= dy) {		/* y step */
1541 			e2 = dx-e2;
1542 			while (e2 < ed * width &&
1543 			    (x1 != (uint32_t)x2 || dx < dy)) {
1544 				x2 += sx;
1545 				gfx_fb_setpixel(x2, y0);
1546 				e2 += dy;
1547 			}
1548 			if (y0 == y1)
1549 				break;
1550 			err += dx;
1551 			y0 += sy;
1552 		}
1553 	}
1554 }
1555 
1556 /*
1557  * quadratic Bézier curve limited to gradients without sign change.
1558  */
1559 void
gfx_fb_bezier(uint32_t x0,uint32_t y0,uint32_t x1,uint32_t y1,uint32_t x2,uint32_t y2,uint32_t wd)1560 gfx_fb_bezier(uint32_t x0, uint32_t y0, uint32_t x1, uint32_t y1, uint32_t x2,
1561     uint32_t y2, uint32_t wd)
1562 {
1563 	int sx, sy, xx, yy, xy, width;
1564 	int dx, dy, err, curvature;
1565 	int i;
1566 
1567 	if (gfx_state.tg_fb_type == FB_TEXT)
1568 		return;
1569 
1570 	width = wd;
1571 	sx = x2 - x1;
1572 	sy = y2 - y1;
1573 	xx = x0 - x1;
1574 	yy = y0 - y1;
1575 	curvature = xx*sy - yy*sx;
1576 
1577 	if (sx*sx + sy*sy > xx*xx+yy*yy) {
1578 		x2 = x0;
1579 		x0 = sx + x1;
1580 		y2 = y0;
1581 		y0 = sy + y1;
1582 		curvature = -curvature;
1583 	}
1584 	if (curvature != 0) {
1585 		xx += sx;
1586 		sx = x0 < x2? 1 : -1;
1587 		xx *= sx;
1588 		yy += sy;
1589 		sy = y0 < y2? 1 : -1;
1590 		yy *= sy;
1591 		xy = (xx*yy) << 1;
1592 		xx *= xx;
1593 		yy *= yy;
1594 		if (curvature * sx * sy < 0) {
1595 			xx = -xx;
1596 			yy = -yy;
1597 			xy = -xy;
1598 			curvature = -curvature;
1599 		}
1600 		dx = 4 * sy * curvature * (x1 - x0) + xx - xy;
1601 		dy = 4 * sx * curvature * (y0 - y1) + yy - xy;
1602 		xx += xx;
1603 		yy += yy;
1604 		err = dx + dy + xy;
1605 		do {
1606 			for (i = 0; i <= width; i++)
1607 				gfx_fb_setpixel(x0 + i, y0);
1608 			if (x0 == x2 && y0 == y2)
1609 				return;  /* last pixel -> curve finished */
1610 			y1 = 2 * err < dx;
1611 			if (2 * err > dy) {
1612 				x0 += sx;
1613 				dx -= xy;
1614 				dy += yy;
1615 				err += dy;
1616 			}
1617 			if (y1 != 0) {
1618 				y0 += sy;
1619 				dy -= xy;
1620 				dx += xx;
1621 				err += dx;
1622 			}
1623 		} while (dy < dx); /* gradient negates -> algorithm fails */
1624 	}
1625 	gfx_fb_line(x0, y0, x2, y2, width);
1626 }
1627 
1628 /*
1629  * draw rectangle using terminal coordinates and current foreground color.
1630  */
1631 void
gfx_term_drawrect(uint32_t ux1,uint32_t uy1,uint32_t ux2,uint32_t uy2)1632 gfx_term_drawrect(uint32_t ux1, uint32_t uy1, uint32_t ux2, uint32_t uy2)
1633 {
1634 	int x1, y1, x2, y2;
1635 	int xshift, yshift;
1636 	int width, i;
1637 	uint32_t vf_width, vf_height;
1638 	teken_rect_t r;
1639 
1640 	if (gfx_state.tg_fb_type == FB_TEXT)
1641 		return;
1642 
1643 	vf_width = gfx_state.tg_font.vf_width;
1644 	vf_height = gfx_state.tg_font.vf_height;
1645 	width = vf_width / 4;			/* line width */
1646 	xshift = (vf_width - width) / 2;
1647 	yshift = (vf_height - width) / 2;
1648 
1649 	/* Shift coordinates */
1650 	if (ux1 != 0)
1651 		ux1--;
1652 	if (uy1 != 0)
1653 		uy1--;
1654 	ux2--;
1655 	uy2--;
1656 
1657 	/* mark area used in terminal */
1658 	r.tr_begin.tp_col = ux1;
1659 	r.tr_begin.tp_row = uy1;
1660 	r.tr_end.tp_col = ux2 + 1;
1661 	r.tr_end.tp_row = uy2 + 1;
1662 
1663 	term_image_display(&gfx_state, &r);
1664 
1665 	/*
1666 	 * Draw horizontal lines width points thick, shifted from outer edge.
1667 	 */
1668 	x1 = (ux1 + 1) * vf_width + gfx_state.tg_origin.tp_col;
1669 	y1 = uy1 * vf_height + gfx_state.tg_origin.tp_row + yshift;
1670 	x2 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1671 	gfx_fb_drawrect(x1, y1, x2, y1 + width, 1);
1672 	y2 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1673 	y2 += vf_height - yshift - width;
1674 	gfx_fb_drawrect(x1, y2, x2, y2 + width, 1);
1675 
1676 	/*
1677 	 * Draw vertical lines width points thick, shifted from outer edge.
1678 	 */
1679 	x1 = ux1 * vf_width + gfx_state.tg_origin.tp_col + xshift;
1680 	y1 = uy1 * vf_height + gfx_state.tg_origin.tp_row;
1681 	y1 += vf_height;
1682 	y2 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1683 	gfx_fb_drawrect(x1, y1, x1 + width, y2, 1);
1684 	x1 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1685 	x1 += vf_width - xshift - width;
1686 	gfx_fb_drawrect(x1, y1, x1 + width, y2, 1);
1687 
1688 	/* Draw upper left corner. */
1689 	x1 = ux1 * vf_width + gfx_state.tg_origin.tp_col + xshift;
1690 	y1 = uy1 * vf_height + gfx_state.tg_origin.tp_row;
1691 	y1 += vf_height;
1692 
1693 	x2 = ux1 * vf_width + gfx_state.tg_origin.tp_col;
1694 	x2 += vf_width;
1695 	y2 = uy1 * vf_height + gfx_state.tg_origin.tp_row + yshift;
1696 	for (i = 0; i <= width; i++)
1697 		gfx_fb_bezier(x1 + i, y1, x1 + i, y2 + i, x2, y2 + i, width-i);
1698 
1699 	/* Draw lower left corner. */
1700 	x1 = ux1 * vf_width + gfx_state.tg_origin.tp_col;
1701 	x1 += vf_width;
1702 	y1 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1703 	y1 += vf_height - yshift;
1704 	x2 = ux1 * vf_width + gfx_state.tg_origin.tp_col + xshift;
1705 	y2 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1706 	for (i = 0; i <= width; i++)
1707 		gfx_fb_bezier(x1, y1 - i, x2 + i, y1 - i, x2 + i, y2, width-i);
1708 
1709 	/* Draw upper right corner. */
1710 	x1 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1711 	y1 = uy1 * vf_height + gfx_state.tg_origin.tp_row + yshift;
1712 	x2 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1713 	x2 += vf_width - xshift - width;
1714 	y2 = uy1 * vf_height + gfx_state.tg_origin.tp_row;
1715 	y2 += vf_height;
1716 	for (i = 0; i <= width; i++)
1717 		gfx_fb_bezier(x1, y1 + i, x2 + i, y1 + i, x2 + i, y2, width-i);
1718 
1719 	/* Draw lower right corner. */
1720 	x1 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1721 	y1 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1722 	y1 += vf_height - yshift;
1723 	x2 = ux2 * vf_width + gfx_state.tg_origin.tp_col;
1724 	x2 += vf_width - xshift - width;
1725 	y2 = uy2 * vf_height + gfx_state.tg_origin.tp_row;
1726 	for (i = 0; i <= width; i++)
1727 		gfx_fb_bezier(x1, y1 - i, x2 + i, y1 - i, x2 + i, y2, width-i);
1728 }
1729 
1730 int
gfx_fb_putimage(png_t * png,uint32_t ux1,uint32_t uy1,uint32_t ux2,uint32_t uy2,uint32_t flags)1731 gfx_fb_putimage(png_t *png, uint32_t ux1, uint32_t uy1, uint32_t ux2,
1732     uint32_t uy2, uint32_t flags)
1733 {
1734 #if defined(EFI)
1735 	EFI_GRAPHICS_OUTPUT_BLT_PIXEL *p;
1736 #else
1737 	struct paletteentry *p;
1738 #endif
1739 	uint8_t *data;
1740 	uint32_t i, j, x, y, fheight, fwidth;
1741 	int rs, gs, bs;
1742 	uint8_t r, g, b, a;
1743 	bool scale = false;
1744 	bool trace = false;
1745 	teken_rect_t rect;
1746 
1747 	trace = (flags & FL_PUTIMAGE_DEBUG) != 0;
1748 
1749 	if (gfx_state.tg_fb_type == FB_TEXT) {
1750 		if (trace)
1751 			printf("Framebuffer not active.\n");
1752 		return (1);
1753 	}
1754 
1755 	if (png->color_type != PNG_TRUECOLOR_ALPHA) {
1756 		if (trace)
1757 			printf("Not truecolor image.\n");
1758 		return (1);
1759 	}
1760 
1761 	if (ux1 > gfx_state.tg_fb.fb_width ||
1762 	    uy1 > gfx_state.tg_fb.fb_height) {
1763 		if (trace)
1764 			printf("Top left coordinate off screen.\n");
1765 		return (1);
1766 	}
1767 
1768 	if (png->width > UINT16_MAX || png->height > UINT16_MAX) {
1769 		if (trace)
1770 			printf("Image too large.\n");
1771 		return (1);
1772 	}
1773 
1774 	if (png->width < 1 || png->height < 1) {
1775 		if (trace)
1776 			printf("Image too small.\n");
1777 		return (1);
1778 	}
1779 
1780 	/*
1781 	 * If 0 was passed for either ux2 or uy2, then calculate the missing
1782 	 * part of the bottom right coordinate.
1783 	 */
1784 	scale = true;
1785 	if (ux2 == 0 && uy2 == 0) {
1786 		/* Both 0, use the native resolution of the image */
1787 		ux2 = ux1 + png->width;
1788 		uy2 = uy1 + png->height;
1789 		scale = false;
1790 	} else if (ux2 == 0) {
1791 		/* Set ux2 from uy2/uy1 to maintain aspect ratio */
1792 		ux2 = ux1 + (png->width * (uy2 - uy1)) / png->height;
1793 	} else if (uy2 == 0) {
1794 		/* Set uy2 from ux2/ux1 to maintain aspect ratio */
1795 		uy2 = uy1 + (png->height * (ux2 - ux1)) / png->width;
1796 	}
1797 
1798 	if (ux2 > gfx_state.tg_fb.fb_width ||
1799 	    uy2 > gfx_state.tg_fb.fb_height) {
1800 		if (trace)
1801 			printf("Bottom right coordinate off screen.\n");
1802 		return (1);
1803 	}
1804 
1805 	fwidth = ux2 - ux1;
1806 	fheight = uy2 - uy1;
1807 
1808 	/*
1809 	 * If the original image dimensions have been passed explicitly,
1810 	 * disable scaling.
1811 	 */
1812 	if (fwidth == png->width && fheight == png->height)
1813 		scale = false;
1814 
1815 	if (ux1 == 0) {
1816 		/*
1817 		 * No top left X co-ordinate (real coordinates start at 1),
1818 		 * place as far right as it will fit.
1819 		 */
1820 		ux2 = gfx_state.tg_fb.fb_width - gfx_state.tg_origin.tp_col;
1821 		ux1 = ux2 - fwidth;
1822 	}
1823 
1824 	if (uy1 == 0) {
1825 		/*
1826 		 * No top left Y co-ordinate (real coordinates start at 1),
1827 		 * place as far down as it will fit.
1828 		 */
1829 		uy2 = gfx_state.tg_fb.fb_height - gfx_state.tg_origin.tp_row;
1830 		uy1 = uy2 - fheight;
1831 	}
1832 
1833 	if (ux1 >= ux2 || uy1 >= uy2) {
1834 		if (trace)
1835 			printf("Image dimensions reversed.\n");
1836 		return (1);
1837 	}
1838 
1839 	if (fwidth < 2 || fheight < 2) {
1840 		if (trace)
1841 			printf("Target area too small\n");
1842 		return (1);
1843 	}
1844 
1845 	if (trace)
1846 		printf("Image %ux%u -> %ux%u @%ux%u\n",
1847 		    png->width, png->height, fwidth, fheight, ux1, uy1);
1848 
1849 	rect.tr_begin.tp_col = ux1 / gfx_state.tg_font.vf_width;
1850 	rect.tr_begin.tp_row = uy1 / gfx_state.tg_font.vf_height;
1851 	rect.tr_end.tp_col = (ux1 + fwidth) / gfx_state.tg_font.vf_width;
1852 	rect.tr_end.tp_row = (uy1 + fheight) / gfx_state.tg_font.vf_height;
1853 
1854 	/*
1855 	 * mark area used in terminal
1856 	 */
1857 	if (!(flags & FL_PUTIMAGE_NOSCROLL))
1858 		term_image_display(&gfx_state, &rect);
1859 
1860 	if ((flags & FL_PUTIMAGE_BORDER))
1861 		gfx_fb_drawrect(ux1, uy1, ux2, uy2, 0);
1862 
1863 	data = malloc(fwidth * fheight * sizeof(*p));
1864 	p = (void *)data;
1865 	if (data == NULL) {
1866 		if (trace)
1867 			printf("Out of memory.\n");
1868 		return (1);
1869 	}
1870 
1871 	/*
1872 	 * Build image for our framebuffer.
1873 	 */
1874 
1875 	/* Helper to calculate the pixel index from the source png */
1876 #define	GETPIXEL(xx, yy)	(((yy) * png->width + (xx)) * png->bpp)
1877 
1878 	/*
1879 	 * For each of the x and y directions, calculate the number of pixels
1880 	 * in the source image that correspond to a single pixel in the target.
1881 	 * Use fixed-point arithmetic with 16-bits for each of the integer and
1882 	 * fractional parts.
1883 	 */
1884 	const uint32_t wcstep = ((png->width - 1) << 16) / (fwidth - 1);
1885 	const uint32_t hcstep = ((png->height - 1) << 16) / (fheight - 1);
1886 
1887 	rs = 8 - (fls(gfx_state.tg_fb.fb_mask_red) -
1888 	    ffs(gfx_state.tg_fb.fb_mask_red) + 1);
1889 	gs = 8 - (fls(gfx_state.tg_fb.fb_mask_green) -
1890 	    ffs(gfx_state.tg_fb.fb_mask_green) + 1);
1891 	bs = 8 - (fls(gfx_state.tg_fb.fb_mask_blue) -
1892 	    ffs(gfx_state.tg_fb.fb_mask_blue) + 1);
1893 
1894 	uint32_t hc = 0;
1895 	for (y = 0; y < fheight; y++) {
1896 		uint32_t hc2 = (hc >> 9) & 0x7f;
1897 		uint32_t hc1 = 0x80 - hc2;
1898 
1899 		uint32_t offset_y = hc >> 16;
1900 		uint32_t offset_y1 = offset_y + 1;
1901 
1902 		uint32_t wc = 0;
1903 		for (x = 0; x < fwidth; x++) {
1904 			uint32_t wc2 = (wc >> 9) & 0x7f;
1905 			uint32_t wc1 = 0x80 - wc2;
1906 
1907 			uint32_t offset_x = wc >> 16;
1908 			uint32_t offset_x1 = offset_x + 1;
1909 
1910 			/* Target pixel index */
1911 			j = y * fwidth + x;
1912 
1913 			if (!scale) {
1914 				i = GETPIXEL(x, y);
1915 				r = png->image[i];
1916 				g = png->image[i + 1];
1917 				b = png->image[i + 2];
1918 				a = png->image[i + 3];
1919 			} else {
1920 				uint8_t pixel[4];
1921 
1922 				uint32_t p00 = GETPIXEL(offset_x, offset_y);
1923 				uint32_t p01 = GETPIXEL(offset_x, offset_y1);
1924 				uint32_t p10 = GETPIXEL(offset_x1, offset_y);
1925 				uint32_t p11 = GETPIXEL(offset_x1, offset_y1);
1926 
1927 				/*
1928 				 * Given a 2x2 array of pixels in the source
1929 				 * image, combine them to produce a single
1930 				 * value for the pixel in the target image.
1931 				 * Each column of pixels is combined using
1932 				 * a weighted average where the top and bottom
1933 				 * pixels contribute hc1 and hc2 respectively.
1934 				 * The calculation for bottom pixel pB and
1935 				 * top pixel pT is:
1936 				 *   (pT * hc1 + pB * hc2) / (hc1 + hc2)
1937 				 * Once the values are determined for the two
1938 				 * columns of pixels, then the columns are
1939 				 * averaged together in the same way but using
1940 				 * wc1 and wc2 for the weightings.
1941 				 *
1942 				 * Since hc1 and hc2 are chosen so that
1943 				 * hc1 + hc2 == 128 (and same for wc1 + wc2),
1944 				 * the >> 14 below is a quick way to divide by
1945 				 * (hc1 + hc2) * (wc1 + wc2)
1946 				 */
1947 				for (i = 0; i < 4; i++)
1948 					pixel[i] = (
1949 					    (png->image[p00 + i] * hc1 +
1950 					    png->image[p01 + i] * hc2) * wc1 +
1951 					    (png->image[p10 + i] * hc1 +
1952 					    png->image[p11 + i] * hc2) * wc2)
1953 					    >> 14;
1954 
1955 				r = pixel[0];
1956 				g = pixel[1];
1957 				b = pixel[2];
1958 				a = pixel[3];
1959 			}
1960 
1961 			if (trace)
1962 				printf("r/g/b: %x/%x/%x\n", r, g, b);
1963 			/*
1964 			 * Rough colorspace reduction for 15/16 bit colors.
1965 			 */
1966 			p[j].Red = r >> rs;
1967                         p[j].Green = g >> gs;
1968                         p[j].Blue = b >> bs;
1969                         p[j].Reserved = a;
1970 
1971 			wc += wcstep;
1972 		}
1973 		hc += hcstep;
1974 	}
1975 
1976 	gfx_fb_cons_display(ux1, uy1, fwidth, fheight, data);
1977 	free(data);
1978 	return (0);
1979 }
1980 
1981 /*
1982  * Reset font flags to FONT_AUTO.
1983  */
1984 void
reset_font_flags(void)1985 reset_font_flags(void)
1986 {
1987 	struct fontlist *fl;
1988 
1989 	STAILQ_FOREACH(fl, &fonts, font_next) {
1990 		fl->font_flags = FONT_AUTO;
1991 	}
1992 }
1993 
1994 /* Return  w^2 + h^2 or 0, if the dimensions are unknown */
1995 static unsigned
edid_diagonal_squared(void)1996 edid_diagonal_squared(void)
1997 {
1998 	unsigned w, h;
1999 
2000 	if (edid_info == NULL)
2001 		return (0);
2002 
2003 	w = edid_info->display.max_horizontal_image_size;
2004 	h = edid_info->display.max_vertical_image_size;
2005 
2006 	/* If either one is 0, we have aspect ratio, not size */
2007 	if (w == 0 || h == 0)
2008 		return (0);
2009 
2010 	/*
2011 	 * some monitors encode the aspect ratio instead of the physical size.
2012 	 */
2013 	if ((w == 16 && h == 9) || (w == 16 && h == 10) ||
2014 	    (w == 4 && h == 3) || (w == 5 && h == 4))
2015 		return (0);
2016 
2017 	/*
2018 	 * translate cm to inch, note we scale by 100 here.
2019 	 */
2020 	w = w * 100 / 254;
2021 	h = h * 100 / 254;
2022 
2023 	/* Return w^2 + h^2 */
2024 	return (w * w + h * h);
2025 }
2026 
2027 /*
2028  * calculate pixels per inch.
2029  */
2030 static unsigned
gfx_get_ppi(void)2031 gfx_get_ppi(void)
2032 {
2033 	unsigned dp, di;
2034 
2035 	di = edid_diagonal_squared();
2036 	if (di == 0)
2037 		return (0);
2038 
2039 	dp = gfx_state.tg_fb.fb_width *
2040 	    gfx_state.tg_fb.fb_width +
2041 	    gfx_state.tg_fb.fb_height *
2042 	    gfx_state.tg_fb.fb_height;
2043 
2044 	return (isqrt(dp / di));
2045 }
2046 
2047 /*
2048  * Calculate font size from density independent pixels (dp):
2049  * ((16dp * ppi) / 160) * display_factor.
2050  * Here we are using fixed constants: 1dp == 160 ppi and
2051  * display_factor 2.
2052  *
2053  * We are rounding font size up and are searching for font which is
2054  * not smaller than calculated size value.
2055  */
2056 static vt_font_bitmap_data_t *
gfx_get_font(teken_unit_t rows,teken_unit_t cols,teken_unit_t height,teken_unit_t width)2057 gfx_get_font(teken_unit_t rows, teken_unit_t cols, teken_unit_t height,
2058     teken_unit_t width)
2059 {
2060 	unsigned ppi, size;
2061 	vt_font_bitmap_data_t *font = NULL;
2062 	struct fontlist *fl, *next;
2063 
2064 	/* Text mode is not supported here. */
2065 	if (gfx_state.tg_fb_type == FB_TEXT)
2066 		return (NULL);
2067 
2068 	ppi = gfx_get_ppi();
2069 	if (ppi == 0)
2070 		return (NULL);
2071 
2072 	/*
2073 	 * We will search for 16dp font.
2074 	 * We are using scale up by 10 for roundup.
2075 	 */
2076 	size = (16 * ppi * 10) / 160;
2077 	/* Apply display factor 2.  */
2078 	size = roundup(size * 2, 10) / 10;
2079 
2080 	STAILQ_FOREACH(fl, &fonts, font_next) {
2081 		/*
2082 		 * Skip too large fonts.
2083 		 */
2084 		font = fl->font_data;
2085 		if (height / font->vfbd_height < rows ||
2086 		    width / font->vfbd_width < cols)
2087 			continue;
2088 
2089 		next = STAILQ_NEXT(fl, font_next);
2090 
2091 		/*
2092 		 * If this is last font or, if next font is smaller,
2093 		 * we have our font. Make sure, it actually is loaded.
2094 		 */
2095 		if (next == NULL || next->font_data->vfbd_height < size) {
2096 			if (font->vfbd_font == NULL ||
2097 			    fl->font_flags == FONT_RELOAD) {
2098 				if (fl->font_load != NULL &&
2099 				    fl->font_name != NULL)
2100 					font = fl->font_load(fl->font_name);
2101 			}
2102 			break;
2103 		}
2104 		font = NULL;
2105 	}
2106 
2107 	return (font);
2108 }
2109 
2110 static vt_font_bitmap_data_t *
set_font(teken_unit_t * rows,teken_unit_t * cols,teken_unit_t h,teken_unit_t w)2111 set_font(teken_unit_t *rows, teken_unit_t *cols, teken_unit_t h, teken_unit_t w)
2112 {
2113 	vt_font_bitmap_data_t *font = NULL;
2114 	struct fontlist *fl;
2115 	unsigned height = h;
2116 	unsigned width = w;
2117 
2118 	/*
2119 	 * First check for manually loaded font.
2120 	 */
2121 	STAILQ_FOREACH(fl, &fonts, font_next) {
2122 		if (fl->font_flags == FONT_MANUAL) {
2123 			font = fl->font_data;
2124 			if (font->vfbd_font == NULL && fl->font_load != NULL &&
2125 			    fl->font_name != NULL) {
2126 				font = fl->font_load(fl->font_name);
2127 			}
2128 			if (font == NULL || font->vfbd_font == NULL)
2129 				font = NULL;
2130 			break;
2131 		}
2132 	}
2133 
2134 	if (font == NULL)
2135 		font = gfx_get_font(*rows, *cols, h, w);
2136 
2137 	if (font != NULL) {
2138 		*rows = height / font->vfbd_height;
2139 		*cols = width / font->vfbd_width;
2140 		return (font);
2141 	}
2142 
2143 	/*
2144 	 * Find best font for these dimensions, or use default.
2145 	 * If height >= VT_FB_MAX_HEIGHT and width >= VT_FB_MAX_WIDTH,
2146 	 * do not use smaller font than our DEFAULT_FONT_DATA.
2147 	 */
2148 	STAILQ_FOREACH(fl, &fonts, font_next) {
2149 		font = fl->font_data;
2150 		if ((*rows * font->vfbd_height <= height &&
2151 		    *cols * font->vfbd_width <= width) ||
2152 		    (height >= VT_FB_MAX_HEIGHT &&
2153 		    width >= VT_FB_MAX_WIDTH &&
2154 		    font->vfbd_height == DEFAULT_FONT_DATA.vfbd_height &&
2155 		    font->vfbd_width == DEFAULT_FONT_DATA.vfbd_width)) {
2156 			if (font->vfbd_font == NULL ||
2157 			    fl->font_flags == FONT_RELOAD) {
2158 				if (fl->font_load != NULL &&
2159 				    fl->font_name != NULL) {
2160 					font = fl->font_load(fl->font_name);
2161 				}
2162 				if (font == NULL)
2163 					continue;
2164 			}
2165 			*rows = height / font->vfbd_height;
2166 			*cols = width / font->vfbd_width;
2167 			break;
2168 		}
2169 		font = NULL;
2170 	}
2171 
2172 	if (font == NULL) {
2173 		/*
2174 		 * We have fonts sorted smallest last, try it before
2175 		 * falling back to builtin.
2176 		 */
2177 		fl = STAILQ_LAST(&fonts, fontlist, font_next);
2178 		if (fl != NULL && fl->font_load != NULL &&
2179 		    fl->font_name != NULL) {
2180 			font = fl->font_load(fl->font_name);
2181 		}
2182 		if (font == NULL)
2183 			font = &DEFAULT_FONT_DATA;
2184 
2185 		*rows = height / font->vfbd_height;
2186 		*cols = width / font->vfbd_width;
2187 	}
2188 
2189 	return (font);
2190 }
2191 
2192 static void
cons_clear(void)2193 cons_clear(void)
2194 {
2195 	char clear[] = { '\033', 'c' };
2196 
2197 	/* Reset terminal */
2198 	teken_input(&gfx_state.tg_teken, clear, sizeof(clear));
2199 	gfx_state.tg_functions->tf_param(&gfx_state, TP_SHOWCURSOR, 0);
2200 }
2201 
2202 void
setup_font(teken_gfx_t * state,teken_unit_t height,teken_unit_t width)2203 setup_font(teken_gfx_t *state, teken_unit_t height, teken_unit_t width)
2204 {
2205 	vt_font_bitmap_data_t *font_data;
2206 	teken_pos_t *tp = &state->tg_tp;
2207 	char env[8];
2208 	int i;
2209 
2210 	/*
2211 	 * set_font() will select a appropriate sized font for
2212 	 * the number of rows and columns selected.  If we don't
2213 	 * have a font that will fit, then it will use the
2214 	 * default builtin font and adjust the rows and columns
2215 	 * to fit on the screen.
2216 	 */
2217 	font_data = set_font(&tp->tp_row, &tp->tp_col, height, width);
2218 
2219         if (font_data == NULL)
2220 		panic("out of memory");
2221 
2222 	for (i = 0; i < VFNT_MAPS; i++) {
2223 		state->tg_font.vf_map[i] =
2224 		    font_data->vfbd_font->vf_map[i];
2225 		state->tg_font.vf_map_count[i] =
2226 		    font_data->vfbd_font->vf_map_count[i];
2227 	}
2228 
2229 	state->tg_font.vf_bytes = font_data->vfbd_font->vf_bytes;
2230 	state->tg_font.vf_height = font_data->vfbd_font->vf_height;
2231 	state->tg_font.vf_width = font_data->vfbd_font->vf_width;
2232 
2233 	snprintf(env, sizeof (env), "%ux%u",
2234 	    state->tg_font.vf_width, state->tg_font.vf_height);
2235 	env_setenv("screen.font", EV_VOLATILE | EV_NOHOOK,
2236 	    env, font_set, env_nounset);
2237 }
2238 
2239 /* Binary search for the glyph. Return 0 if not found. */
2240 static uint16_t
font_bisearch(const vfnt_map_t * map,uint32_t len,teken_char_t src)2241 font_bisearch(const vfnt_map_t *map, uint32_t len, teken_char_t src)
2242 {
2243 	unsigned min, mid, max;
2244 
2245 	min = 0;
2246 	max = len - 1;
2247 
2248 	/* Empty font map. */
2249 	if (len == 0)
2250 		return (0);
2251 	/* Character below minimal entry. */
2252 	if (src < map[0].vfm_src)
2253 		return (0);
2254 	/* Optimization: ASCII characters occur very often. */
2255 	if (src <= map[0].vfm_src + map[0].vfm_len)
2256 		return (src - map[0].vfm_src + map[0].vfm_dst);
2257 	/* Character above maximum entry. */
2258 	if (src > map[max].vfm_src + map[max].vfm_len)
2259 		return (0);
2260 
2261 	/* Binary search. */
2262 	while (max >= min) {
2263 		mid = (min + max) / 2;
2264 		if (src < map[mid].vfm_src)
2265 			max = mid - 1;
2266 		else if (src > map[mid].vfm_src + map[mid].vfm_len)
2267 			min = mid + 1;
2268 		else
2269 			return (src - map[mid].vfm_src + map[mid].vfm_dst);
2270 	}
2271 
2272 	return (0);
2273 }
2274 
2275 /*
2276  * Return glyph bitmap. If glyph is not found, we will return bitmap
2277  * for the first (offset 0) glyph.
2278  */
2279 uint8_t *
font_lookup(const struct vt_font * vf,teken_char_t c,const teken_attr_t * a)2280 font_lookup(const struct vt_font *vf, teken_char_t c, const teken_attr_t *a)
2281 {
2282 	uint16_t dst;
2283 	size_t stride;
2284 
2285 	/* Substitute bold with normal if not found. */
2286 	if (a->ta_format & TF_BOLD) {
2287 		dst = font_bisearch(vf->vf_map[VFNT_MAP_BOLD],
2288 		    vf->vf_map_count[VFNT_MAP_BOLD], c);
2289 		if (dst != 0)
2290 			goto found;
2291 	}
2292 	dst = font_bisearch(vf->vf_map[VFNT_MAP_NORMAL],
2293 	    vf->vf_map_count[VFNT_MAP_NORMAL], c);
2294 
2295 found:
2296 	stride = howmany(vf->vf_width, 8) * vf->vf_height;
2297 	return (&vf->vf_bytes[dst * stride]);
2298 }
2299 
2300 static int
load_mapping(int fd,struct vt_font * fp,int n)2301 load_mapping(int fd, struct vt_font *fp, int n)
2302 {
2303 	size_t i, size;
2304 	ssize_t rv;
2305 	vfnt_map_t *mp;
2306 
2307 	if (fp->vf_map_count[n] == 0)
2308 		return (0);
2309 
2310 	size = fp->vf_map_count[n] * sizeof(*mp);
2311 	mp = malloc(size);
2312 	if (mp == NULL)
2313 		return (ENOMEM);
2314 	fp->vf_map[n] = mp;
2315 
2316 	rv = read(fd, mp, size);
2317 	if (rv < 0 || (size_t)rv != size) {
2318 		free(fp->vf_map[n]);
2319 		fp->vf_map[n] = NULL;
2320 		return (EIO);
2321 	}
2322 
2323 	for (i = 0; i < fp->vf_map_count[n]; i++) {
2324 		mp[i].vfm_src = be32toh(mp[i].vfm_src);
2325 		mp[i].vfm_dst = be16toh(mp[i].vfm_dst);
2326 		mp[i].vfm_len = be16toh(mp[i].vfm_len);
2327 	}
2328 	return (0);
2329 }
2330 
2331 static int
builtin_mapping(struct vt_font * fp,int n)2332 builtin_mapping(struct vt_font *fp, int n)
2333 {
2334 	size_t size;
2335 	struct vfnt_map *mp;
2336 
2337 	if (n >= VFNT_MAPS)
2338 		return (EINVAL);
2339 
2340 	if (fp->vf_map_count[n] == 0)
2341 		return (0);
2342 
2343 	size = fp->vf_map_count[n] * sizeof(*mp);
2344 	mp = malloc(size);
2345 	if (mp == NULL)
2346 		return (ENOMEM);
2347 	fp->vf_map[n] = mp;
2348 
2349 	memcpy(mp, DEFAULT_FONT_DATA.vfbd_font->vf_map[n], size);
2350 	return (0);
2351 }
2352 
2353 /*
2354  * Load font from builtin or from file.
2355  * We do need special case for builtin because the builtin font glyphs
2356  * are compressed and we do need to uncompress them.
2357  * Having single load_font() for both cases will help us to simplify
2358  * font switch handling.
2359  */
2360 static vt_font_bitmap_data_t *
load_font(char * path)2361 load_font(char *path)
2362 {
2363 	int fd, i;
2364 	uint32_t glyphs;
2365 	struct font_header fh;
2366 	struct fontlist *fl;
2367 	vt_font_bitmap_data_t *bp;
2368 	struct vt_font *fp;
2369 	size_t size;
2370 	ssize_t rv;
2371 
2372 	/* Get our entry from the font list. */
2373 	STAILQ_FOREACH(fl, &fonts, font_next) {
2374 		if (strcmp(fl->font_name, path) == 0)
2375 			break;
2376 	}
2377 	if (fl == NULL)
2378 		return (NULL);	/* Should not happen. */
2379 
2380 	bp = fl->font_data;
2381 	if (bp->vfbd_font != NULL && fl->font_flags != FONT_RELOAD)
2382 		return (bp);
2383 
2384 	fd = -1;
2385 	/*
2386 	 * Special case for builtin font.
2387 	 * Builtin font is the very first font we load, we do not have
2388 	 * previous loads to be released.
2389 	 */
2390 	if (fl->font_flags == FONT_BUILTIN) {
2391 		if ((fp = calloc(1, sizeof(struct vt_font))) == NULL)
2392 			return (NULL);
2393 
2394 		fp->vf_width = DEFAULT_FONT_DATA.vfbd_width;
2395 		fp->vf_height = DEFAULT_FONT_DATA.vfbd_height;
2396 
2397 		fp->vf_bytes = malloc(DEFAULT_FONT_DATA.vfbd_uncompressed_size);
2398 		if (fp->vf_bytes == NULL) {
2399 			free(fp);
2400 			return (NULL);
2401 		}
2402 
2403 		bp->vfbd_uncompressed_size =
2404 		    DEFAULT_FONT_DATA.vfbd_uncompressed_size;
2405 		bp->vfbd_compressed_size =
2406 		    DEFAULT_FONT_DATA.vfbd_compressed_size;
2407 
2408 		if (lz4_decompress(DEFAULT_FONT_DATA.vfbd_compressed_data,
2409 		    fp->vf_bytes,
2410 		    DEFAULT_FONT_DATA.vfbd_compressed_size,
2411 		    DEFAULT_FONT_DATA.vfbd_uncompressed_size, 0) != 0) {
2412 			free(fp->vf_bytes);
2413 			free(fp);
2414 			return (NULL);
2415 		}
2416 
2417 		for (i = 0; i < VFNT_MAPS; i++) {
2418 			fp->vf_map_count[i] =
2419 			    DEFAULT_FONT_DATA.vfbd_font->vf_map_count[i];
2420 			if (builtin_mapping(fp, i) != 0)
2421 				goto free_done;
2422 		}
2423 
2424 		bp->vfbd_font = fp;
2425 		return (bp);
2426 	}
2427 
2428 	fd = open(path, O_RDONLY);
2429 	if (fd < 0)
2430 		return (NULL);
2431 
2432 	size = sizeof(fh);
2433 	rv = read(fd, &fh, size);
2434 	if (rv < 0 || (size_t)rv != size) {
2435 		bp = NULL;
2436 		goto done;
2437 	}
2438 	if (memcmp(fh.fh_magic, FONT_HEADER_MAGIC, sizeof(fh.fh_magic)) != 0) {
2439 		bp = NULL;
2440 		goto done;
2441 	}
2442 	if ((fp = calloc(1, sizeof(struct vt_font))) == NULL) {
2443 		bp = NULL;
2444 		goto done;
2445 	}
2446 	for (i = 0; i < VFNT_MAPS; i++)
2447 		fp->vf_map_count[i] = be32toh(fh.fh_map_count[i]);
2448 
2449 	glyphs = be32toh(fh.fh_glyph_count);
2450 	fp->vf_width = fh.fh_width;
2451 	fp->vf_height = fh.fh_height;
2452 
2453 	size = howmany(fp->vf_width, 8) * fp->vf_height * glyphs;
2454 	bp->vfbd_uncompressed_size = size;
2455 	if ((fp->vf_bytes = malloc(size)) == NULL)
2456 		goto free_done;
2457 
2458 	rv = read(fd, fp->vf_bytes, size);
2459 	if (rv < 0 || (size_t)rv != size)
2460 		goto free_done;
2461 	for (i = 0; i < VFNT_MAPS; i++) {
2462 		if (load_mapping(fd, fp, i) != 0)
2463 			goto free_done;
2464 	}
2465 
2466 	/*
2467 	 * Reset builtin flag now as we have full font loaded.
2468 	 */
2469 	if (fl->font_flags == FONT_BUILTIN)
2470 		fl->font_flags = FONT_AUTO;
2471 
2472 	/*
2473 	 * Release previously loaded entries. We can do this now, as
2474 	 * the new font is loaded. Note, there can be no console
2475 	 * output till the new font is in place and teken is notified.
2476 	 * We do need to keep fl->font_data for glyph dimensions.
2477 	 */
2478 	STAILQ_FOREACH(fl, &fonts, font_next) {
2479 		if (fl->font_data->vfbd_font == NULL)
2480 			continue;
2481 
2482 		for (i = 0; i < VFNT_MAPS; i++)
2483 			free(fl->font_data->vfbd_font->vf_map[i]);
2484 		free(fl->font_data->vfbd_font->vf_bytes);
2485 		free(fl->font_data->vfbd_font);
2486 		fl->font_data->vfbd_font = NULL;
2487 	}
2488 
2489 	bp->vfbd_font = fp;
2490 	bp->vfbd_compressed_size = 0;
2491 
2492 done:
2493 	if (fd != -1)
2494 		close(fd);
2495 	return (bp);
2496 
2497 free_done:
2498 	for (i = 0; i < VFNT_MAPS; i++)
2499 		free(fp->vf_map[i]);
2500 	free(fp->vf_bytes);
2501 	free(fp);
2502 	bp = NULL;
2503 	goto done;
2504 }
2505 
2506 struct name_entry {
2507 	char			*n_name;
2508 	SLIST_ENTRY(name_entry)	n_entry;
2509 };
2510 
2511 SLIST_HEAD(name_list, name_entry);
2512 
2513 /* Read font names from index file. */
2514 static struct name_list *
read_list(char * fonts)2515 read_list(char *fonts)
2516 {
2517 	struct name_list *nl;
2518 	struct name_entry *np;
2519 	char *dir, *ptr;
2520 	char buf[PATH_MAX];
2521 	int fd, len;
2522 
2523 	TSENTER();
2524 
2525 	dir = strdup(fonts);
2526 	if (dir == NULL)
2527 		return (NULL);
2528 
2529 	ptr = strrchr(dir, '/');
2530 	*ptr = '\0';
2531 
2532 	fd = open(fonts, O_RDONLY);
2533 	if (fd < 0)
2534 		return (NULL);
2535 
2536 	nl = malloc(sizeof(*nl));
2537 	if (nl == NULL) {
2538 		close(fd);
2539 		return (nl);
2540 	}
2541 
2542 	SLIST_INIT(nl);
2543 	while ((len = fgetstr(buf, sizeof (buf), fd)) >= 0) {
2544 		if (*buf == '#' || *buf == '\0')
2545 			continue;
2546 
2547 		if (bcmp(buf, "MENU", 4) == 0)
2548 			continue;
2549 
2550 		if (bcmp(buf, "FONT", 4) == 0)
2551 			continue;
2552 
2553 		ptr = strchr(buf, ':');
2554 		if (ptr == NULL)
2555 			continue;
2556 		else
2557 			*ptr = '\0';
2558 
2559 		np = malloc(sizeof(*np));
2560 		if (np == NULL) {
2561 			close(fd);
2562 			return (nl);	/* return what we have */
2563 		}
2564 		if (asprintf(&np->n_name, "%s/%s", dir, buf) < 0) {
2565 			free(np);
2566 			close(fd);
2567 			return (nl);    /* return what we have */
2568 		}
2569 		SLIST_INSERT_HEAD(nl, np, n_entry);
2570 	}
2571 	close(fd);
2572 	TSEXIT();
2573 	return (nl);
2574 }
2575 
2576 /*
2577  * Read the font properties and insert new entry into the list.
2578  * The font list is built in descending order.
2579  */
2580 static bool
insert_font(char * name,FONT_FLAGS flags)2581 insert_font(char *name, FONT_FLAGS flags)
2582 {
2583 	struct font_header fh;
2584 	struct fontlist *fp, *previous, *entry, *next;
2585 	size_t size;
2586 	ssize_t rv;
2587 	int fd;
2588 	char *font_name;
2589 
2590 	TSENTER();
2591 
2592 	font_name = NULL;
2593 	if (flags == FONT_BUILTIN) {
2594 		/*
2595 		 * We only install builtin font once, while setting up
2596 		 * initial console. Since this will happen very early,
2597 		 * we assume asprintf will not fail. Once we have access to
2598 		 * files, the builtin font will be replaced by font loaded
2599 		 * from file.
2600 		 */
2601 		if (!STAILQ_EMPTY(&fonts))
2602 			return (false);
2603 
2604 		fh.fh_width = DEFAULT_FONT_DATA.vfbd_width;
2605 		fh.fh_height = DEFAULT_FONT_DATA.vfbd_height;
2606 
2607 		(void) asprintf(&font_name, "%dx%d",
2608 		    DEFAULT_FONT_DATA.vfbd_width,
2609 		    DEFAULT_FONT_DATA.vfbd_height);
2610 	} else {
2611 		fd = open(name, O_RDONLY);
2612 		if (fd < 0)
2613 			return (false);
2614 		rv = read(fd, &fh, sizeof(fh));
2615 		close(fd);
2616 		if (rv < 0 || (size_t)rv != sizeof(fh))
2617 			return (false);
2618 
2619 		if (memcmp(fh.fh_magic, FONT_HEADER_MAGIC,
2620 		    sizeof(fh.fh_magic)) != 0)
2621 			return (false);
2622 		font_name = strdup(name);
2623 	}
2624 
2625 	if (font_name == NULL)
2626 		return (false);
2627 
2628 	/*
2629 	 * If we have an entry with the same glyph dimensions, replace
2630 	 * the file name and mark us. We only support unique dimensions.
2631 	 */
2632 	STAILQ_FOREACH(entry, &fonts, font_next) {
2633 		if (fh.fh_width == entry->font_data->vfbd_width &&
2634 		    fh.fh_height == entry->font_data->vfbd_height) {
2635 			free(entry->font_name);
2636 			entry->font_name = font_name;
2637 			entry->font_flags = FONT_RELOAD;
2638 			TSEXIT();
2639 			return (true);
2640 		}
2641 	}
2642 
2643 	fp = calloc(sizeof(*fp), 1);
2644 	if (fp == NULL) {
2645 		free(font_name);
2646 		return (false);
2647 	}
2648 	fp->font_data = calloc(sizeof(*fp->font_data), 1);
2649 	if (fp->font_data == NULL) {
2650 		free(font_name);
2651 		free(fp);
2652 		return (false);
2653 	}
2654 	fp->font_name = font_name;
2655 	fp->font_flags = flags;
2656 	fp->font_load = load_font;
2657 	fp->font_data->vfbd_width = fh.fh_width;
2658 	fp->font_data->vfbd_height = fh.fh_height;
2659 
2660 	if (STAILQ_EMPTY(&fonts)) {
2661 		STAILQ_INSERT_HEAD(&fonts, fp, font_next);
2662 		TSEXIT();
2663 		return (true);
2664 	}
2665 
2666 	previous = NULL;
2667 	size = fp->font_data->vfbd_width * fp->font_data->vfbd_height;
2668 
2669 	STAILQ_FOREACH(entry, &fonts, font_next) {
2670 		vt_font_bitmap_data_t *bd;
2671 
2672 		bd = entry->font_data;
2673 		/* Should fp be inserted before the entry? */
2674 		if (size > bd->vfbd_width * bd->vfbd_height) {
2675 			if (previous == NULL) {
2676 				STAILQ_INSERT_HEAD(&fonts, fp, font_next);
2677 			} else {
2678 				STAILQ_INSERT_AFTER(&fonts, previous, fp,
2679 				    font_next);
2680 			}
2681 			TSEXIT();
2682 			return (true);
2683 		}
2684 		next = STAILQ_NEXT(entry, font_next);
2685 		if (next == NULL ||
2686 		    size > next->font_data->vfbd_width *
2687 		    next->font_data->vfbd_height) {
2688 			STAILQ_INSERT_AFTER(&fonts, entry, fp, font_next);
2689 			TSEXIT();
2690 			return (true);
2691 		}
2692 		previous = entry;
2693 	}
2694 	TSEXIT();
2695 	return (true);
2696 }
2697 
2698 static int
font_set(struct env_var * ev __unused,int flags __unused,const void * value)2699 font_set(struct env_var *ev __unused, int flags __unused, const void *value)
2700 {
2701 	struct fontlist *fl;
2702 	char *eptr;
2703 	unsigned long x = 0, y = 0;
2704 
2705 	/*
2706 	 * Attempt to extract values from "XxY" string. In case of error,
2707 	 * we have unmaching glyph dimensions and will just output the
2708 	 * available values.
2709 	 */
2710 	if (value != NULL) {
2711 		x = strtoul(value, &eptr, 10);
2712 		if (*eptr == 'x')
2713 			y = strtoul(eptr + 1, &eptr, 10);
2714 	}
2715 	STAILQ_FOREACH(fl, &fonts, font_next) {
2716 		if (fl->font_data->vfbd_width == x &&
2717 		    fl->font_data->vfbd_height == y)
2718 			break;
2719 	}
2720 	if (fl != NULL) {
2721 		/* Reset any FONT_MANUAL flag. */
2722 		reset_font_flags();
2723 
2724 		/* Mark this font manually loaded */
2725 		fl->font_flags = FONT_MANUAL;
2726 		cons_update_mode(gfx_state.tg_fb_type != FB_TEXT);
2727 		return (CMD_OK);
2728 	}
2729 
2730 	printf("Available fonts:\n");
2731 	STAILQ_FOREACH(fl, &fonts, font_next) {
2732 		printf("    %dx%d\n", fl->font_data->vfbd_width,
2733 		    fl->font_data->vfbd_height);
2734 	}
2735 	return (CMD_OK);
2736 }
2737 
2738 void
bios_text_font(bool use_vga_font)2739 bios_text_font(bool use_vga_font)
2740 {
2741 	if (use_vga_font)
2742 		(void) insert_font(VGA_8X16_FONT, FONT_MANUAL);
2743 	else
2744 		(void) insert_font(DEFAULT_8X16_FONT, FONT_MANUAL);
2745 }
2746 
2747 void
autoload_font(bool bios)2748 autoload_font(bool bios)
2749 {
2750 	struct name_list *nl;
2751 	struct name_entry *np;
2752 
2753 	TSENTER();
2754 
2755 	nl = read_list("/boot/fonts/INDEX.fonts");
2756 	if (nl == NULL)
2757 		return;
2758 
2759 	while (!SLIST_EMPTY(nl)) {
2760 		np = SLIST_FIRST(nl);
2761 		SLIST_REMOVE_HEAD(nl, n_entry);
2762 		if (insert_font(np->n_name, FONT_AUTO) == false)
2763 			printf("failed to add font: %s\n", np->n_name);
2764 		free(np->n_name);
2765 		free(np);
2766 	}
2767 
2768 	/*
2769 	 * If vga text mode was requested, load vga.font (8x16 bold) font.
2770 	 */
2771 	if (bios) {
2772 		bios_text_font(true);
2773 	}
2774 
2775 	(void) cons_update_mode(gfx_state.tg_fb_type != FB_TEXT);
2776 
2777 	TSEXIT();
2778 }
2779 
2780 COMMAND_SET(load_font, "loadfont", "load console font from file", command_font);
2781 
2782 static int
command_font(int argc,char * argv[])2783 command_font(int argc, char *argv[])
2784 {
2785 	int i, c, rc;
2786 	struct fontlist *fl;
2787 	vt_font_bitmap_data_t *bd;
2788 	bool list;
2789 
2790 	list = false;
2791 	optind = 1;
2792 	optreset = 1;
2793 	rc = CMD_OK;
2794 
2795 	while ((c = getopt(argc, argv, "l")) != -1) {
2796 		switch (c) {
2797 		case 'l':
2798 			list = true;
2799 			break;
2800 		case '?':
2801 		default:
2802 			return (CMD_ERROR);
2803 		}
2804 	}
2805 
2806 	argc -= optind;
2807 	argv += optind;
2808 
2809 	if (argc > 1 || (list && argc != 0)) {
2810 		printf("Usage: loadfont [-l] | [file.fnt]\n");
2811 		return (CMD_ERROR);
2812 	}
2813 
2814 	if (list) {
2815 		STAILQ_FOREACH(fl, &fonts, font_next) {
2816 			printf("font %s: %dx%d%s\n", fl->font_name,
2817 			    fl->font_data->vfbd_width,
2818 			    fl->font_data->vfbd_height,
2819 			    fl->font_data->vfbd_font == NULL? "" : " loaded");
2820 		}
2821 		return (CMD_OK);
2822 	}
2823 
2824 	/* Clear scren */
2825 	cons_clear();
2826 
2827 	if (argc == 1) {
2828 		char *name = argv[0];
2829 
2830 		if (insert_font(name, FONT_MANUAL) == false) {
2831 			printf("loadfont error: failed to load: %s\n", name);
2832 			return (CMD_ERROR);
2833 		}
2834 
2835 		(void) cons_update_mode(gfx_state.tg_fb_type != FB_TEXT);
2836 		return (CMD_OK);
2837 	}
2838 
2839 	if (argc == 0) {
2840 		/*
2841 		 * Walk entire font list, release any loaded font, and set
2842 		 * autoload flag. The font list does have at least the builtin
2843 		 * default font.
2844 		 */
2845 		STAILQ_FOREACH(fl, &fonts, font_next) {
2846 			if (fl->font_data->vfbd_font != NULL) {
2847 
2848 				bd = fl->font_data;
2849 				/*
2850 				 * Note the setup_font() is releasing
2851 				 * font bytes.
2852 				 */
2853 				for (i = 0; i < VFNT_MAPS; i++)
2854 					free(bd->vfbd_font->vf_map[i]);
2855 				free(fl->font_data->vfbd_font);
2856 				fl->font_data->vfbd_font = NULL;
2857 				fl->font_data->vfbd_uncompressed_size = 0;
2858 				fl->font_flags = FONT_AUTO;
2859 			}
2860 		}
2861 		(void) cons_update_mode(gfx_state.tg_fb_type != FB_TEXT);
2862 	}
2863 	return (rc);
2864 }
2865 
2866 bool
gfx_get_edid_resolution(struct vesa_edid_info * edid,edid_res_list_t * res)2867 gfx_get_edid_resolution(struct vesa_edid_info *edid, edid_res_list_t *res)
2868 {
2869 	struct resolution *rp, *p;
2870 
2871 	/*
2872 	 * Walk detailed timings tables (4).
2873 	 */
2874 	if ((edid->display.supported_features
2875 	    & EDID_FEATURE_PREFERRED_TIMING_MODE) != 0) {
2876 		/* Walk detailed timing descriptors (4) */
2877 		for (int i = 0; i < DET_TIMINGS; i++) {
2878 			/*
2879 			 * Reserved value 0 is not used for display descriptor.
2880 			 */
2881 			if (edid->detailed_timings[i].pixel_clock == 0)
2882 				continue;
2883 			if ((rp = malloc(sizeof(*rp))) == NULL)
2884 				continue;
2885 			rp->width = GET_EDID_INFO_WIDTH(edid, i);
2886 			rp->height = GET_EDID_INFO_HEIGHT(edid, i);
2887 			if (rp->width > 0 && rp->width <= EDID_MAX_PIXELS &&
2888 			    rp->height > 0 && rp->height <= EDID_MAX_LINES)
2889 				TAILQ_INSERT_TAIL(res, rp, next);
2890 			else
2891 				free(rp);
2892 		}
2893 	}
2894 
2895 	/*
2896 	 * Walk standard timings list (8).
2897 	 */
2898 	for (int i = 0; i < STD_TIMINGS; i++) {
2899 		/* Is this field unused? */
2900 		if (edid->standard_timings[i] == 0x0101)
2901 			continue;
2902 
2903 		if ((rp = malloc(sizeof(*rp))) == NULL)
2904 			continue;
2905 
2906 		rp->width = HSIZE(edid->standard_timings[i]);
2907 		switch (RATIO(edid->standard_timings[i])) {
2908 		case RATIO1_1:
2909 			rp->height = HSIZE(edid->standard_timings[i]);
2910 			if (edid->header.version > 1 ||
2911 			    edid->header.revision > 2) {
2912 				rp->height = rp->height * 10 / 16;
2913 			}
2914 			break;
2915 		case RATIO4_3:
2916 			rp->height = HSIZE(edid->standard_timings[i]) * 3 / 4;
2917 			break;
2918 		case RATIO5_4:
2919 			rp->height = HSIZE(edid->standard_timings[i]) * 4 / 5;
2920 			break;
2921 		case RATIO16_9:
2922 			rp->height = HSIZE(edid->standard_timings[i]) * 9 / 16;
2923 			break;
2924 		}
2925 
2926 		/*
2927 		 * Create resolution list in decreasing order, except keep
2928 		 * first entry (preferred timing mode).
2929 		 */
2930 		TAILQ_FOREACH(p, res, next) {
2931 			if (p->width * p->height < rp->width * rp->height) {
2932 				/* Keep preferred mode first */
2933 				if (TAILQ_FIRST(res) == p)
2934 					TAILQ_INSERT_AFTER(res, p, rp, next);
2935 				else
2936 					TAILQ_INSERT_BEFORE(p, rp, next);
2937 				break;
2938 			}
2939 			if (TAILQ_NEXT(p, next) == NULL) {
2940 				TAILQ_INSERT_TAIL(res, rp, next);
2941 				break;
2942 			}
2943 		}
2944 	}
2945 	return (!TAILQ_EMPTY(res));
2946 }
2947 
2948 vm_offset_t
build_font_module(vm_offset_t addr)2949 build_font_module(vm_offset_t addr)
2950 {
2951 	vt_font_bitmap_data_t *bd;
2952 	struct vt_font *fd;
2953 	struct preloaded_file *fp;
2954 	size_t size;
2955 	uint32_t checksum;
2956 	int i;
2957 	struct font_info fi;
2958 	struct fontlist *fl;
2959 	uint64_t fontp;
2960 
2961 	if (STAILQ_EMPTY(&fonts))
2962 		return (addr);
2963 
2964 	/* We can't load first */
2965 	if ((file_findfile(NULL, NULL)) == NULL) {
2966 		printf("Can not load font module: %s\n",
2967 		    "the kernel is not loaded");
2968 		return (addr);
2969 	}
2970 
2971 	/* helper pointers */
2972 	bd = NULL;
2973 	STAILQ_FOREACH(fl, &fonts, font_next) {
2974 		if (gfx_state.tg_font.vf_width == fl->font_data->vfbd_width &&
2975 		    gfx_state.tg_font.vf_height == fl->font_data->vfbd_height) {
2976 			/*
2977 			 * Kernel does have better built in font.
2978 			 */
2979 			if (fl->font_flags == FONT_BUILTIN)
2980 				return (addr);
2981 
2982 			bd = fl->font_data;
2983 			break;
2984 		}
2985 	}
2986 	if (bd == NULL)
2987 		return (addr);
2988 	fd = bd->vfbd_font;
2989 
2990 	fi.fi_width = fd->vf_width;
2991 	checksum = fi.fi_width;
2992 	fi.fi_height = fd->vf_height;
2993 	checksum += fi.fi_height;
2994 	fi.fi_bitmap_size = bd->vfbd_uncompressed_size;
2995 	checksum += fi.fi_bitmap_size;
2996 
2997 	size = roundup2(sizeof (struct font_info), 8);
2998 	for (i = 0; i < VFNT_MAPS; i++) {
2999 		fi.fi_map_count[i] = fd->vf_map_count[i];
3000 		checksum += fi.fi_map_count[i];
3001 		size += fd->vf_map_count[i] * sizeof (struct vfnt_map);
3002 		size += roundup2(size, 8);
3003 	}
3004 	size += bd->vfbd_uncompressed_size;
3005 
3006 	fi.fi_checksum = -checksum;
3007 
3008 	fp = file_findfile(NULL, md_kerntype);
3009 	if (fp == NULL)
3010 		panic("can't find kernel file");
3011 
3012 	fontp = addr;
3013 	addr += archsw.arch_copyin(&fi, addr, sizeof (struct font_info));
3014 	addr = roundup2(addr, 8);
3015 
3016 	/* Copy maps. */
3017 	for (i = 0; i < VFNT_MAPS; i++) {
3018 		if (fd->vf_map_count[i] != 0) {
3019 			addr += archsw.arch_copyin(fd->vf_map[i], addr,
3020 			    fd->vf_map_count[i] * sizeof (struct vfnt_map));
3021 			addr = roundup2(addr, 8);
3022 		}
3023 	}
3024 
3025 	/* Copy the bitmap. */
3026 	addr += archsw.arch_copyin(fd->vf_bytes, addr, fi.fi_bitmap_size);
3027 
3028 	/* Looks OK so far; populate control structure */
3029 	file_addmetadata(fp, MODINFOMD_FONT, sizeof(fontp), &fontp);
3030 	return (addr);
3031 }
3032 
3033 vm_offset_t
build_splash_module(vm_offset_t addr)3034 build_splash_module(vm_offset_t addr)
3035 {
3036 	struct preloaded_file *fp;
3037 	struct splash_info si;
3038 	const char *splash;
3039 	png_t png;
3040 	uint64_t splashp;
3041 	int error;
3042 
3043 	/* We can't load first */
3044 	if ((file_findfile(NULL, NULL)) == NULL) {
3045 		printf("Can not load splash module: %s\n",
3046 		    "the kernel is not loaded");
3047 		return (addr);
3048 	}
3049 
3050 	fp = file_findfile(NULL, md_kerntype);
3051 	if (fp == NULL)
3052 		panic("can't find kernel file");
3053 
3054 	splash = getenv("splash");
3055 	if (splash == NULL)
3056 		return (addr);
3057 
3058 	/* Parse png */
3059 	if ((error = png_open(&png, splash)) != PNG_NO_ERROR) {
3060 		return (addr);
3061 	}
3062 
3063 	si.si_width = png.width;
3064 	si.si_height = png.height;
3065 	si.si_depth = png.bpp;
3066 	splashp = addr;
3067 	addr += archsw.arch_copyin(&si, addr, sizeof (struct splash_info));
3068 	addr = roundup2(addr, 8);
3069 
3070 	/* Copy the bitmap. */
3071 	addr += archsw.arch_copyin(png.image, addr, png.png_datalen);
3072 
3073 	printf("Loading splash ok\n");
3074 	file_addmetadata(fp, MODINFOMD_SPLASH, sizeof(splashp), &splashp);
3075 	return (addr);
3076 }
3077