xref: /illumos-gate/usr/src/cmd/vtfontcvt/vtfontcvt.c (revision 2a1fd0ffe121888d44fdec321c25b53dcfaa9118)
1 /*
2  * Copyright (c) 2009, 2014 The FreeBSD Foundation
3  * All rights reserved.
4  *
5  * This software was developed by Ed Schouten under sponsorship from the
6  * FreeBSD Foundation.
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 #include <sys/types.h>
31 #include <endian.h>
32 #include <sys/param.h>
33 #include <sys/queue.h>
34 
35 #include <assert.h>
36 #include <err.h>
37 #include <stdint.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <stdbool.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include "fnv_hash.h"
44 
45 #define	VFNT_MAPS 4
46 #define	VFNT_MAP_NORMAL 0
47 #define	VFNT_MAP_NORMAL_RH 1
48 #define	VFNT_MAP_BOLD 2
49 #define	VFNT_MAP_BOLD_RH 3
50 
51 extern size_t lz4_compress(void *, void *, size_t, size_t, int);
52 
53 static unsigned int width = 8, wbytes, height = 16;
54 
55 struct bbox {
56 	unsigned int width;	/* pixels */
57 	unsigned int height;
58 	int x;			/* lower left corner x */
59 	int y;			/* lower left corner y */
60 };
61 
62 static struct bbox bbox;	/* font bounding box */
63 static int font_ascent;		/* pixels above baseline */
64 static int font_descent;	/* pixels below baseline */
65 static unsigned int default_char = 0xFFFD;
66 
67 struct glyph {
68 	TAILQ_ENTRY(glyph)	 g_list;
69 	SLIST_ENTRY(glyph)	 g_hash;
70 	uint8_t			*g_data;
71 	unsigned int		 g_index;
72 };
73 
74 #define	FONTCVT_NHASH 4096
75 TAILQ_HEAD(glyph_list, glyph);
76 static SLIST_HEAD(, glyph) glyph_hash[FONTCVT_NHASH];
77 static struct glyph_list glyphs[VFNT_MAPS] = {
78     TAILQ_HEAD_INITIALIZER(glyphs[0]),
79     TAILQ_HEAD_INITIALIZER(glyphs[1]),
80     TAILQ_HEAD_INITIALIZER(glyphs[2]),
81     TAILQ_HEAD_INITIALIZER(glyphs[3]),
82 };
83 static unsigned int glyph_total, glyph_count[4], glyph_unique, glyph_dupe;
84 
85 struct mapping {
86 	TAILQ_ENTRY(mapping)	 m_list;
87 	unsigned int		 m_char;
88 	unsigned int		 m_length;
89 	struct glyph		*m_glyph;
90 };
91 
92 TAILQ_HEAD(mapping_list, mapping);
93 static struct mapping_list maps[VFNT_MAPS] = {
94     TAILQ_HEAD_INITIALIZER(maps[0]),
95     TAILQ_HEAD_INITIALIZER(maps[1]),
96     TAILQ_HEAD_INITIALIZER(maps[2]),
97     TAILQ_HEAD_INITIALIZER(maps[3]),
98 };
99 static unsigned int mapping_total, map_count[4], map_folded_count[4],
100     mapping_unique, mapping_dupe;
101 
102 enum output_format {
103 	VT_FONT,		/* default */
104 	VT_C_SOURCE,		/* C source for built in fonts */
105 	VT_C_COMPRESSED		/* C source with compressed font data */
106 };
107 
108 struct whitelist {
109 	uint32_t c;
110 	uint32_t len;
111 };
112 
113 /*
114  * Compressed font glyph list. To be used with boot loader, we need to have
115  * ascii set and box drawing chars.
116  */
117 static struct whitelist c_list[] = {
118 	{ .c = 0, .len = 0 },		/* deault char */
119 	{ .c = 0x20, .len = 0x5f },
120 	{ .c = 0x2500, .len = 0 },	/* single frame */
121 	{ .c = 0x2502, .len = 0 },
122 	{ .c = 0x250c, .len = 0 },
123 	{ .c = 0x2510, .len = 0 },
124 	{ .c = 0x2514, .len = 0 },
125 	{ .c = 0x2518, .len = 0 },
126 	{ .c = 0x2550, .len = 1 },	/* double frame */
127 	{ .c = 0x2554, .len = 0 },
128 	{ .c = 0x2557, .len = 0 },
129 	{ .c = 0x255a, .len = 0 },
130 	{ .c = 0x255d, .len = 0 },
131 };
132 
133 /*
134  * Uncompressed source. For x86 we need cp437 so the vga text mode
135  * can program font into the vga card.
136  */
137 static struct whitelist s_list[] = {
138 	{ .c = 0, .len = 0 },		/* deault char */
139 	{ .c = 0x20, .len = 0x5f },	/* ascii set */
140 	{ .c = 0xA0, .len = 0x5f },	/* latin 1 */
141 	{ .c = 0x0192, .len = 0 },
142 	{ .c = 0x0332, .len = 0 },	/* composing lower line */
143 	{ .c = 0x0393, .len = 0 },
144 	{ .c = 0x0398, .len = 0 },
145 	{ .c = 0x03A3, .len = 0 },
146 	{ .c = 0x03A6, .len = 0 },
147 	{ .c = 0x03A9, .len = 0 },
148 	{ .c = 0x03B1, .len = 1 },
149 	{ .c = 0x03B4, .len = 0 },
150 	{ .c = 0x03C0, .len = 0 },
151 	{ .c = 0x03C3, .len = 0 },
152 	{ .c = 0x03C4, .len = 0 },
153 	{ .c = 0x207F, .len = 0 },
154 	{ .c = 0x20A7, .len = 0 },
155 	{ .c = 0x2205, .len = 0 },
156 	{ .c = 0x220A, .len = 0 },
157 	{ .c = 0x2219, .len = 1 },
158 	{ .c = 0x221E, .len = 0 },
159 	{ .c = 0x2229, .len = 0 },
160 	{ .c = 0x2248, .len = 0 },
161 	{ .c = 0x2261, .len = 0 },
162 	{ .c = 0x2264, .len = 1 },
163 	{ .c = 0x2310, .len = 0 },
164 	{ .c = 0x2320, .len = 1 },
165 	{ .c = 0x2500, .len = 0 },
166 	{ .c = 0x2502, .len = 0 },
167 	{ .c = 0x250C, .len = 0 },
168 	{ .c = 0x2510, .len = 0 },
169 	{ .c = 0x2514, .len = 0 },
170 	{ .c = 0x2518, .len = 0 },
171 	{ .c = 0x251C, .len = 0 },
172 	{ .c = 0x2524, .len = 0 },
173 	{ .c = 0x252C, .len = 0 },
174 	{ .c = 0x2534, .len = 0 },
175 	{ .c = 0x253C, .len = 0 },
176 	{ .c = 0x2550, .len = 0x1c },
177 	{ .c = 0x2580, .len = 0 },
178 	{ .c = 0x2584, .len = 0 },
179 	{ .c = 0x2588, .len = 0 },
180 	{ .c = 0x258C, .len = 0 },
181 	{ .c = 0x2590, .len = 3 },
182 	{ .c = 0x25A0, .len = 0 },
183 };
184 
185 bool filter = true;
186 enum output_format format = VT_FONT;
187 /* Type for write callback. */
188 typedef size_t (*vt_write)(const void *, size_t, size_t, FILE *);
189 uint8_t *uncompressed;
190 
191 static void
192 usage(void)
193 {
194 
195 	(void) fprintf(stderr, "usage:\tvtfontcvt "
196 	    "[-n] [-f font|source|compressed-source] [-w width] "
197 	    "[-h height]\n\t[-v] -o outfile normal.bdf [bold.bdf]\n");
198 	exit(1);
199 }
200 
201 static void *
202 xmalloc(size_t size)
203 {
204 	void *m;
205 
206 	if ((m = malloc(size)) == NULL)
207 		errx(1, "memory allocation failure");
208 	return (m);
209 }
210 
211 static int
212 add_mapping(struct glyph *gl, unsigned int c, unsigned int map_idx)
213 {
214 	struct mapping *mp, *v;
215 	struct mapping_list *ml;
216 
217 	mapping_total++;
218 
219 	mp = xmalloc(sizeof (*mp));
220 	mp->m_char = c;
221 	mp->m_glyph = gl;
222 	mp->m_length = 0;
223 
224 	ml = &maps[map_idx];
225 	if (TAILQ_LAST(ml, mapping_list) != NULL &&
226 	    TAILQ_LAST(ml, mapping_list)->m_char >= c) {
227 		TAILQ_FOREACH_REVERSE(v, ml, mapping_list, m_list) {
228 			if (v->m_char < c) {
229 				TAILQ_INSERT_AFTER(ml, v, mp, m_list);
230 				break;
231 			} else if (v->m_char == c)
232 				errx(1, "Bad ordering at character %u", c);
233 		}
234 	} else
235 		TAILQ_INSERT_TAIL(ml, mp, m_list);
236 
237 	map_count[map_idx]++;
238 	mapping_unique++;
239 
240 	return (0);
241 }
242 
243 static int
244 dedup_mapping(unsigned int map_idx)
245 {
246 	struct mapping *mp_bold, *mp_normal;
247 	unsigned normal_map_idx = map_idx - VFNT_MAP_BOLD;
248 
249 	assert(map_idx == VFNT_MAP_BOLD || map_idx == VFNT_MAP_BOLD_RH);
250 	mp_normal = TAILQ_FIRST(&maps[normal_map_idx]);
251 	TAILQ_FOREACH(mp_bold, &maps[map_idx], m_list) {
252 		while (mp_normal->m_char < mp_bold->m_char)
253 			mp_normal = TAILQ_NEXT(mp_normal, m_list);
254 		if (mp_bold->m_char != mp_normal->m_char)
255 			errx(1, "Character %u not in normal font!",
256 			    mp_bold->m_char);
257 		if (mp_bold->m_glyph != mp_normal->m_glyph)
258 			continue;
259 
260 		/* No mapping is needed if it's equal to the normal mapping. */
261 		TAILQ_REMOVE(&maps[map_idx], mp_bold, m_list);
262 		free(mp_bold);
263 		mapping_dupe++;
264 	}
265 	return (0);
266 }
267 
268 static struct glyph *
269 add_glyph(const uint8_t *bytes, unsigned int map_idx, int fallback)
270 {
271 	struct glyph *gl;
272 	int hash;
273 
274 	glyph_total++;
275 	glyph_count[map_idx]++;
276 
277 	hash = fnv_32_buf(bytes, wbytes * height, FNV1_32_INIT) % FONTCVT_NHASH;
278 	SLIST_FOREACH(gl, &glyph_hash[hash], g_hash) {
279 		if (memcmp(gl->g_data, bytes, wbytes * height) == 0) {
280 			glyph_dupe++;
281 			return (gl);
282 		}
283 	}
284 
285 	gl = xmalloc(sizeof (*gl));
286 	gl->g_data = xmalloc(wbytes * height);
287 	memcpy(gl->g_data, bytes, wbytes * height);
288 	if (fallback)
289 		TAILQ_INSERT_HEAD(&glyphs[map_idx], gl, g_list);
290 	else
291 		TAILQ_INSERT_TAIL(&glyphs[map_idx], gl, g_list);
292 	SLIST_INSERT_HEAD(&glyph_hash[hash], gl, g_hash);
293 
294 	glyph_unique++;
295 	return (gl);
296 }
297 
298 static bool
299 check_whitelist(unsigned c)
300 {
301 	struct whitelist *w = NULL;
302 	int i, n = 0;
303 
304 	if (filter == false)
305 		return (true);
306 
307 	if (format == VT_C_SOURCE) {
308 		w = s_list;
309 		n = sizeof (s_list) / sizeof (s_list[0]);
310 	}
311 	if (format == VT_C_COMPRESSED) {
312 		w = c_list;
313 		n = sizeof (c_list) / sizeof (c_list[0]);
314 	}
315 	if (w == NULL)
316 		return (true);
317 	for (i = 0; i < n; i++) {
318 		if (c >= w[i].c && c <= w[i].c + w[i].len)
319 			return (true);
320 	}
321 	return (false);
322 }
323 
324 static int
325 add_char(unsigned curchar, unsigned map_idx, uint8_t *bytes, uint8_t *bytes_r)
326 {
327 	struct glyph *gl;
328 
329 	/* Prevent adding two glyphs for default_char */
330 	if (curchar == default_char) {
331 		if (map_idx < VFNT_MAP_BOLD)
332 			gl = add_glyph(bytes, 0, 1);
333 	} else if (filter == false || curchar >= 0x20) {
334 		gl = add_glyph(bytes, map_idx, 0);
335 		if (add_mapping(gl, curchar, map_idx) != 0)
336 			return (1);
337 		if (bytes_r != NULL) {
338 			gl = add_glyph(bytes_r, map_idx + 1, 0);
339 			if (add_mapping(gl, curchar,
340 			    map_idx + 1) != 0)
341 				return (1);
342 		}
343 	}
344 	return (0);
345 }
346 
347 
348 static int
349 parse_bitmap_line(uint8_t *left, uint8_t *right, unsigned int line,
350     unsigned int dwidth)
351 {
352 	uint8_t *p;
353 	unsigned int i, subline;
354 
355 	if (dwidth != width && dwidth != width * 2)
356 		errx(1, "Bitmap with unsupported width %u!", dwidth);
357 
358 	/* Move pixel data right to simplify splitting double characters. */
359 	line >>= (howmany(dwidth, 8) * 8) - dwidth;
360 
361 	for (i = dwidth / width; i > 0; i--) {
362 		p = (i == 2) ? right : left;
363 
364 		subline = line & ((1 << width) - 1);
365 		subline <<= (howmany(width, 8) * 8) - width;
366 
367 		if (wbytes == 1) {
368 			*p = subline;
369 		} else if (wbytes == 2) {
370 			*p++ = subline >> 8;
371 			*p = subline;
372 		} else {
373 			errx(1, "Unsupported wbytes %u!", wbytes);
374 		}
375 
376 		line >>= width;
377 	}
378 
379 	return (0);
380 }
381 
382 static int
383 parse_bdf(FILE *fp, unsigned int map_idx)
384 {
385 	char ln[BUFSIZ];
386 	uint8_t bytes[wbytes * height], bytes_r[wbytes * height];
387 	unsigned int curchar = 0, dwidth = 0, i, line;
388 
389 	memset(bytes, 0, sizeof (bytes));
390 	memset(bytes_r, 0, sizeof (bytes_r));
391 
392 	while (fgets(ln, sizeof (ln), fp) != NULL) {
393 		if (sscanf(ln, "ENCODING %u", &curchar) == 1)
394 			continue;
395 
396 		if (sscanf(ln, "DWIDTH %u", &dwidth) == 1)
397 			continue;
398 
399 		if (strncmp(ln, "BITMAP", 6) == 0) {
400 			for (i = 0; i < height; i++) {
401 				if (fgets(ln, sizeof (ln), fp) == NULL)
402 					errx(1, "Unexpected EOF!");
403 				sscanf(ln, "%x", &line);
404 				if (parse_bitmap_line(bytes + i * wbytes,
405 				    bytes_r + i * wbytes, line, dwidth) != 0)
406 					return (1);
407 			}
408 
409 			if (check_whitelist(curchar) == true) {
410 				if (add_char(curchar, map_idx, bytes,
411 				    dwidth == width * 2 ? bytes_r : NULL) != 0)
412 					return (1);
413 			}
414 		}
415 	}
416 
417 	return (0);
418 }
419 
420 static void
421 set_width(int w)
422 {
423 
424 	if (w <= 0 || w > 128)
425 		errx(1, "invalid width %d", w);
426 	width = w;
427 	wbytes = howmany(width, 8);
428 }
429 
430 static int
431 parse_hex(FILE *fp, unsigned int map_idx)
432 {
433 	char ln[BUFSIZ], *p;
434 	char fmt_str[8];
435 	uint8_t *bytes = NULL, *bytes_r = NULL;
436 	unsigned curchar = 0, i, line, chars_per_row, dwidth;
437 	int rv = 0;
438 
439 	while (fgets(ln, sizeof (ln), fp) != NULL) {
440 		if (strncmp(ln, "# Height: ", 10) == 0) {
441 			if (bytes != NULL) {
442 				errx(1, "malformed input: Height tag after "
443 				    "font data");
444 			}
445 			height = atoi(ln + 10);
446 		} else if (strncmp(ln, "# Width: ", 9) == 0) {
447 			if (bytes != NULL) {
448 				errx(1, "malformed input: Width tag after "
449 				    "font data");
450 			}
451 			set_width(atoi(ln + 9));
452 		} else if (sscanf(ln, "%6x:", &curchar)) {
453 			if (bytes == NULL) {
454 				bytes = xmalloc(wbytes * height);
455 				bytes_r = xmalloc(wbytes * height);
456 			}
457 			/* ln is guaranteed to have a colon here. */
458 			p = strchr(ln, ':') + 1;
459 			chars_per_row = strlen(p) / height;
460 			dwidth = width;
461 			if (chars_per_row / 2 > (width + 7) / 8)
462 				dwidth *= 2; /* Double-width character. */
463 			snprintf(fmt_str, sizeof (fmt_str), "%%%ux",
464 			    chars_per_row);
465 
466 			for (i = 0; i < height; i++) {
467 				sscanf(p, fmt_str, &line);
468 				p += chars_per_row;
469 				if (parse_bitmap_line(bytes + i * wbytes,
470 				    bytes_r + i * wbytes, line, dwidth) != 0) {
471 					rv = 1;
472 					goto out;
473 				}
474 			}
475 
476 			if (add_char(curchar, map_idx, bytes,
477 			    dwidth == width * 2 ? bytes_r : NULL) != 0) {
478 				rv = 1;
479 				goto out;
480 			}
481 		}
482 	}
483 out:
484 	free(bytes);
485 	free(bytes_r);
486 	return (rv);
487 }
488 
489 /* Read BDF header and set the font data. */
490 static int
491 parse_bdf_header(FILE *fp)
492 {
493 	char ln[BUFSIZ];
494 	char spacing = '\0';	/* Should we assume C if not specified? */
495 	int ret;
496 
497 	while (fgets(ln, sizeof (ln), fp) != NULL) {
498 		ret = sscanf(ln, "FONTBOUNDINGBOX %u %u %d %d",
499 		    &bbox.width, &bbox.height, &bbox.x, &bbox.y);
500 		if (ret == 4)
501 			continue;
502 		ret = sscanf(ln, "FONT_ASCENT %u", &font_ascent);
503 		if (ret == 1)
504 			continue;
505 		ret = sscanf(ln, "FONT_DESCENT %u", &font_descent);
506 		if (ret == 1)
507 			continue;
508 		ret = sscanf(ln, "DEFAULT_CHAR %u", &default_char);
509 		if (ret == 1) {
510 			c_list[0].c = default_char;
511 			s_list[0].c = default_char;
512 			continue;
513 		}
514 		ret = sscanf(ln, "SPACING \"%c\"", &spacing);
515 		if (ret == 1)
516 			continue;
517 		if (strncmp("ENDPROPERTIES", ln, 13) == 0)
518 			break;
519 	}
520 	if (spacing != 'C') {
521 		printf("Spacing '%c' is not supported\n", spacing);
522 		return (1);
523 	}
524 	if (bbox.width == 0)
525 		bbox.width = width;
526 	set_width(bbox.width);
527 
528 	if (bbox.height == 0)
529 		bbox.height = height;
530 	height = bbox.height;
531 	return (0);
532 }
533 
534 static int
535 parse_file(const char *filename, unsigned int map_idx)
536 {
537 	FILE *fp;
538 	size_t len;
539 	int rv;
540 
541 	fp = fopen(filename, "r");
542 	if (fp == NULL) {
543 		perror(filename);
544 		return (1);
545 	}
546 	len = strlen(filename);
547 	if (len > 4 && strcasecmp(filename + len - 4, ".hex") == 0) {
548 		rv = parse_hex(fp, map_idx);
549 	} else {
550 		if ((rv = parse_bdf_header(fp)) == 0)
551 			rv = parse_bdf(fp, map_idx);
552 	}
553 	fclose(fp);
554 	return (rv);
555 }
556 
557 static void
558 number_glyphs(void)
559 {
560 	struct glyph *gl;
561 	unsigned int i, idx = 0;
562 
563 	for (i = 0; i < VFNT_MAPS; i++)
564 		TAILQ_FOREACH(gl, &glyphs[i], g_list)
565 			gl->g_index = idx++;
566 }
567 
568 /* Note we only deal with byte stream here. */
569 static size_t
570 write_glyph_source(const void *ptr, size_t size, size_t nitems, FILE *stream)
571 {
572 	const uint8_t *data = ptr;
573 	size_t i;
574 
575 	size *= nitems;
576 	for (i = 0; i < size; i++) {
577 		if ((i % wbytes) == 0) {
578 			if (fprintf(stream, "\n") < 0)
579 				return (0);
580 		}
581 		if (fprintf(stream, "0x%02x, ", data[i]) < 0)
582 			return (0);
583 	}
584 	if (fprintf(stream, "\n") < 0)
585 		nitems = 0;
586 
587 	return (nitems);
588 }
589 
590 /* Write to buffer */
591 static size_t
592 write_glyph_buf(const void *ptr, size_t size, size_t nitems, FILE *stream)
593 {
594 	static size_t index = 0;
595 
596 	size *= nitems;
597 	(void) memmove(uncompressed + index, ptr, size);
598 	index += size;
599 
600 	return (nitems);
601 }
602 
603 static int
604 write_glyphs(FILE *fp, vt_write cb)
605 {
606 	struct glyph *gl;
607 	unsigned int i;
608 
609 	for (i = 0; i < VFNT_MAPS; i++) {
610 		TAILQ_FOREACH(gl, &glyphs[i], g_list)
611 			if (cb(gl->g_data, wbytes * height, 1, fp) != 1)
612 				return (1);
613 	}
614 	return (0);
615 }
616 
617 static void
618 fold_mappings(unsigned int map_idx)
619 {
620 	struct mapping_list *ml = &maps[map_idx];
621 	struct mapping *mn, *mp, *mbase;
622 
623 	mp = mbase = TAILQ_FIRST(ml);
624 	for (mp = mbase = TAILQ_FIRST(ml); mp != NULL; mp = mn) {
625 		mn = TAILQ_NEXT(mp, m_list);
626 		if (mn != NULL && mn->m_char == mp->m_char + 1 &&
627 		    mn->m_glyph->g_index == mp->m_glyph->g_index + 1)
628 			continue;
629 		mbase->m_length = mp->m_char - mbase->m_char + 1;
630 		mbase = mp = mn;
631 		map_folded_count[map_idx]++;
632 	}
633 }
634 
635 struct file_mapping {
636 	uint32_t	source;
637 	uint16_t	destination;
638 	uint16_t	length;
639 } __attribute__((packed));
640 
641 static int
642 write_mappings(FILE *fp, unsigned int map_idx)
643 {
644 	struct mapping_list *ml = &maps[map_idx];
645 	struct mapping *mp;
646 	struct file_mapping fm;
647 	unsigned int i = 0, j = 0;
648 
649 	TAILQ_FOREACH(mp, ml, m_list) {
650 		j++;
651 		if (mp->m_length > 0) {
652 			i += mp->m_length;
653 			fm.source = htobe32(mp->m_char);
654 			fm.destination = htobe16(mp->m_glyph->g_index);
655 			fm.length = htobe16(mp->m_length - 1);
656 			if (fwrite(&fm, sizeof (fm), 1, fp) != 1)
657 				return (1);
658 		}
659 	}
660 	assert(i == j);
661 	return (0);
662 }
663 
664 static int
665 write_source_mappings(FILE *fp, unsigned int map_idx)
666 {
667 	struct mapping_list *ml = &maps[map_idx];
668 	struct mapping *mp;
669 	unsigned int i = 0, j = 0;
670 
671 	TAILQ_FOREACH(mp, ml, m_list) {
672 		j++;
673 		if (mp->m_length > 0) {
674 			i += mp->m_length;
675 			if (fprintf(fp, "\t{ 0x%08x, 0x%04x, 0x%04x },\n",
676 			    mp->m_char, mp->m_glyph->g_index,
677 			    mp->m_length - 1) < 0)
678 				return (1);
679 		}
680 	}
681 	assert(i == j);
682 	return (0);
683 }
684 
685 struct file_header {
686 	uint8_t		magic[8];
687 	uint8_t		width;
688 	uint8_t		height;
689 	uint16_t	pad;
690 	uint32_t	glyph_count;
691 	uint32_t	map_count[4];
692 } __attribute__((packed));
693 
694 static int
695 write_fnt(const char *filename)
696 {
697 	FILE *fp;
698 	struct file_header fh = {
699 		.magic = "VFNT0002",
700 	};
701 
702 	fp = fopen(filename, "wb");
703 	if (fp == NULL) {
704 		perror(filename);
705 		return (1);
706 	}
707 
708 	fh.width = width;
709 	fh.height = height;
710 	fh.glyph_count = htobe32(glyph_unique);
711 	fh.map_count[0] = htobe32(map_folded_count[0]);
712 	fh.map_count[1] = htobe32(map_folded_count[1]);
713 	fh.map_count[2] = htobe32(map_folded_count[2]);
714 	fh.map_count[3] = htobe32(map_folded_count[3]);
715 	if (fwrite(&fh, sizeof (fh), 1, fp) != 1) {
716 		perror(filename);
717 		fclose(fp);
718 		return (1);
719 	}
720 
721 	if (write_glyphs(fp, &fwrite) != 0 ||
722 	    write_mappings(fp, VFNT_MAP_NORMAL) != 0 ||
723 	    write_mappings(fp, 1) != 0 ||
724 	    write_mappings(fp, VFNT_MAP_BOLD) != 0 ||
725 	    write_mappings(fp, 3) != 0) {
726 		perror(filename);
727 		fclose(fp);
728 		return (1);
729 	}
730 
731 	fclose(fp);
732 	return (0);
733 }
734 
735 static int
736 write_fnt_source(bool lz4, const char *filename)
737 {
738 	FILE *fp;
739 	int rv = 1;
740 	size_t uncompressed_size = wbytes * height * glyph_unique;
741 	size_t compressed_size = uncompressed_size;
742 	uint8_t *compressed = NULL;
743 
744 	fp = fopen(filename, "w");
745 	if (fp == NULL) {
746 		perror(filename);
747 		return (1);
748 	}
749 
750 	if (lz4 == true) {
751 		uncompressed = xmalloc(uncompressed_size);
752 		compressed = xmalloc(uncompressed_size);
753 	}
754 	if (fprintf(fp, "/* Generated %ux%u console font source. */\n\n",
755 	    width, height) < 0)
756 		goto done;
757 	if (fprintf(fp, "#include <sys/types.h>\n") < 0)
758 		goto done;
759 	if (fprintf(fp, "#include <sys/param.h>\n") < 0)
760 		goto done;
761 	if (fprintf(fp, "#include <sys/font.h>\n\n") < 0)
762 		goto done;
763 
764 	/* Write font bytes. */
765 	if (fprintf(fp, "static uint8_t FONTDATA_%ux%u[] = {\n",
766 	    width, height) < 0)
767 		goto done;
768 	if (lz4 == true) {
769 		if (write_glyphs(fp, &write_glyph_buf) != 0)
770 			goto done;
771 		compressed_size = lz4_compress(uncompressed, compressed,
772 		    uncompressed_size, compressed_size, 0);
773 		if (write_glyph_source(compressed, compressed_size, 1, fp) != 1)
774 			goto done;
775 		free(uncompressed);
776 		free(compressed);
777 	} else {
778 		if (write_glyphs(fp, &write_glyph_source) != 0)
779 			goto done;
780 	}
781 	if (fprintf(fp, "};\n\n") < 0)
782 		goto done;
783 
784 	/* Write font maps. */
785 	if (!TAILQ_EMPTY(&maps[VFNT_MAP_NORMAL])) {
786 		if (fprintf(fp, "static struct font_map "
787 		    "FONTMAP_NORMAL_%ux%u[] = {\n", width, height) < 0)
788 			goto done;
789 		if (write_source_mappings(fp, VFNT_MAP_NORMAL) != 0)
790 			goto done;
791 		if (fprintf(fp, "};\n\n") < 0)
792 			goto done;
793 	}
794 	if (!TAILQ_EMPTY(&maps[VFNT_MAP_NORMAL_RH])) {
795 		if (fprintf(fp, "static struct font_map "
796 		    "FONTMAP_NORMAL_RH_%ux%u[] = {\n", width, height) < 0)
797 			goto done;
798 		if (write_source_mappings(fp, VFNT_MAP_NORMAL_RH) != 0)
799 			goto done;
800 		if (fprintf(fp, "};\n\n") < 0)
801 			goto done;
802 	}
803 	if (!TAILQ_EMPTY(&maps[VFNT_MAP_BOLD])) {
804 		if (fprintf(fp, "static struct font_map "
805 		    "FONTMAP_BOLD_%ux%u[] = {\n", width, height) < 0)
806 			goto done;
807 		if (write_source_mappings(fp, VFNT_MAP_BOLD) != 0)
808 			goto done;
809 		if (fprintf(fp, "};\n\n") < 0)
810 			goto done;
811 	}
812 	if (!TAILQ_EMPTY(&maps[VFNT_MAP_BOLD_RH])) {
813 		if (fprintf(fp, "static struct font_map "
814 		    "FONTMAP_BOLD_RH_%ux%u[] = {\n", width, height) < 0)
815 			goto done;
816 		if (write_source_mappings(fp, VFNT_MAP_BOLD_RH) != 0)
817 			goto done;
818 		if (fprintf(fp, "};\n\n") < 0)
819 			goto done;
820 	}
821 
822 	/* Write struct font. */
823 	if (fprintf(fp, "struct font font_%ux%u = {\n",
824 	    width, height) < 0)
825 		goto done;
826 	if (fprintf(fp, "\t.vf_map\t= {\n") < 0)
827 		goto done;
828 	if (TAILQ_EMPTY(&maps[VFNT_MAP_NORMAL])) {
829 		if (fprintf(fp, "\t\t\tNULL,\n") < 0)
830 			goto done;
831 	} else {
832 		if (fprintf(fp, "\t\t\tFONTMAP_NORMAL_%ux%u,\n",
833 		    width, height) < 0)
834 			goto done;
835 	}
836 	if (TAILQ_EMPTY(&maps[VFNT_MAP_NORMAL_RH])) {
837 		if (fprintf(fp, "\t\t\tNULL,\n") < 0)
838 			goto done;
839 	} else {
840 		if (fprintf(fp, "\t\t\tFONTMAP_NORMAL_RH_%ux%u,\n",
841 		    width, height) < 0)
842 			goto done;
843 	}
844 	if (TAILQ_EMPTY(&maps[VFNT_MAP_BOLD])) {
845 		if (fprintf(fp, "\t\t\tNULL,\n") < 0)
846 			goto done;
847 	} else {
848 		if (fprintf(fp, "\t\t\tFONTMAP_BOLD_%ux%u,\n",
849 		    width, height) < 0)
850 			goto done;
851 	}
852 	if (TAILQ_EMPTY(&maps[VFNT_MAP_BOLD_RH])) {
853 		if (fprintf(fp, "\t\t\tNULL\n") < 0)
854 			goto done;
855 	} else {
856 		if (fprintf(fp, "\t\t\tFONTMAP_BOLD_RH_%ux%u\n",
857 		    width, height) < 0)
858 			goto done;
859 	}
860 	if (fprintf(fp, "\t\t},\n") < 0)
861 		goto done;
862 	if (lz4 == true) {
863 		if (fprintf(fp, "\t.vf_bytes\t= NULL,\n") < 0)
864 			goto done;
865 	} else {
866 		if (fprintf(fp, "\t.vf_bytes\t= FONTDATA_%ux%u,\n",
867 		    width, height) < 0) {
868 			goto done;
869 		}
870 	}
871 	if (fprintf(fp, "\t.vf_width\t= %u,\n", width) < 0)
872 		goto done;
873 	if (fprintf(fp, "\t.vf_height\t= %u,\n", height) < 0)
874 		goto done;
875 	if (fprintf(fp, "\t.vf_map_count\t= { %u, %u, %u, %u }\n",
876 	    map_folded_count[0], map_folded_count[1], map_folded_count[2],
877 	    map_folded_count[3]) < 0) {
878 		goto done;
879 	}
880 	if (fprintf(fp, "};\n\n") < 0)
881 		goto done;
882 
883 	/* Write bitmap data. */
884 	if (fprintf(fp, "bitmap_data_t font_data_%ux%u = {\n",
885 	    width, height) < 0)
886 		goto done;
887 	if (fprintf(fp, "\t.width\t= %u,\n", width) < 0)
888 		goto done;
889 	if (fprintf(fp, "\t.height\t= %u,\n", height) < 0)
890 		goto done;
891 	if (lz4 == true) {
892 		if (fprintf(fp, "\t.compressed_size\t= %u,\n",
893 		    compressed_size) < 0) {
894 			goto done;
895 		}
896 		if (fprintf(fp, "\t.uncompressed_size\t= %u,\n",
897 		    uncompressed_size) < 0) {
898 			goto done;
899 		}
900 		if (fprintf(fp, "\t.compressed_data\t= FONTDATA_%ux%u,\n",
901 		    width, height) < 0) {
902 			goto done;
903 		}
904 	} else {
905 		if (fprintf(fp, "\t.compressed_size\t= 0,\n") < 0)
906 			goto done;
907 		if (fprintf(fp, "\t.uncompressed_size\t= %u,\n",
908 		    uncompressed_size) < 0) {
909 			goto done;
910 		}
911 		if (fprintf(fp, "\t.compressed_data\t= NULL,\n") < 0)
912 			goto done;
913 	}
914 	if (fprintf(fp, "\t.font = &font_%ux%u\n", width, height) < 0)
915 		goto done;
916 	if (fprintf(fp, "};\n") < 0)
917 		goto done;
918 
919 	rv = 0;
920 done:
921 	if (rv != 0)
922 		perror(filename);
923 	fclose(fp);
924 	return (0);
925 }
926 
927 static void
928 print_font_info(void)
929 {
930 	printf(
931 "Statistics:\n"
932 "- glyph_total:                 %6u\n"
933 "- glyph_normal:                %6u\n"
934 "- glyph_normal_right:          %6u\n"
935 "- glyph_bold:                  %6u\n"
936 "- glyph_bold_right:            %6u\n"
937 "- glyph_unique:                %6u\n"
938 "- glyph_dupe:                  %6u\n"
939 "- mapping_total:               %6u\n"
940 "- mapping_normal:              %6u\n"
941 "- mapping_normal_folded:       %6u\n"
942 "- mapping_normal_right:        %6u\n"
943 "- mapping_normal_right_folded: %6u\n"
944 "- mapping_bold:                %6u\n"
945 "- mapping_bold_folded:         %6u\n"
946 "- mapping_bold_right:          %6u\n"
947 "- mapping_bold_right_folded:   %6u\n"
948 "- mapping_unique:              %6u\n"
949 "- mapping_dupe:                %6u\n",
950 	    glyph_total,
951 	    glyph_count[0],
952 	    glyph_count[1],
953 	    glyph_count[2],
954 	    glyph_count[3],
955 	    glyph_unique, glyph_dupe,
956 	    mapping_total,
957 	    map_count[0], map_folded_count[0],
958 	    map_count[1], map_folded_count[1],
959 	    map_count[2], map_folded_count[2],
960 	    map_count[3], map_folded_count[3],
961 	    mapping_unique, mapping_dupe);
962 }
963 
964 int
965 main(int argc, char *argv[])
966 {
967 	int ch, val, verbose = 0, rv = 0;
968 	char *outfile = NULL;
969 
970 	assert(sizeof (struct file_header) == 32);
971 	assert(sizeof (struct file_mapping) == 8);
972 
973 	while ((ch = getopt(argc, argv, "nf:h:vw:o:")) != -1) {
974 		switch (ch) {
975 		case 'f':
976 			if (strcmp(optarg, "font") == 0)
977 				format = VT_FONT;
978 			else if (strcmp(optarg, "source") == 0)
979 				format = VT_C_SOURCE;
980 			else if (strcmp(optarg, "compressed-source") == 0)
981 				format = VT_C_COMPRESSED;
982 			else
983 				errx(1, "Invalid format: %s", optarg);
984 			break;
985 		case 'h':
986 			val = atoi(optarg);
987 			if (val <= 0 || val > 128)
988 				errx(1, "Invalid height %d", val);
989 			height = val;
990 			break;
991 		case 'n':
992 			filter = false;
993 			break;
994 		case 'o':
995 			outfile = optarg;
996 			break;
997 		case 'v':
998 			verbose = 1;
999 			break;
1000 		case 'w':
1001 			set_width(atoi(optarg));
1002 			break;
1003 		case '?':
1004 		default:
1005 			usage();
1006 		}
1007 	}
1008 	argc -= optind;
1009 	argv += optind;
1010 
1011 	if (outfile == NULL || argc < 1 || argc > 2)
1012 		usage();
1013 
1014 	wbytes = howmany(width, 8);
1015 
1016 	if (parse_file(argv[0], VFNT_MAP_NORMAL) != 0)
1017 		return (1);
1018 	argc--;
1019 	argv++;
1020 	if (argc == 1) {
1021 		if (parse_file(argv[0], VFNT_MAP_BOLD) != 0)
1022 			return (1);
1023 		argc--;
1024 		argv++;
1025 	}
1026 	number_glyphs();
1027 	dedup_mapping(VFNT_MAP_BOLD);
1028 	dedup_mapping(VFNT_MAP_BOLD_RH);
1029 	fold_mappings(0);
1030 	fold_mappings(1);
1031 	fold_mappings(2);
1032 	fold_mappings(3);
1033 
1034 	switch (format) {
1035 	case VT_FONT:
1036 		rv = write_fnt(outfile);
1037 		break;
1038 	case VT_C_SOURCE:
1039 		rv = write_fnt_source(false, outfile);
1040 		break;
1041 	case VT_C_COMPRESSED:
1042 		rv = write_fnt_source(true, outfile);
1043 		break;
1044 	}
1045 
1046 	if (verbose)
1047 		print_font_info();
1048 
1049 	return (rv);
1050 }
1051