bdfload.c revision 999c8572
1/*	$NetBSD: bdfload.c,v 1.17 2022/10/25 12:55:04 macallan Exp $	*/
2
3/*
4 * Copyright (c) 2018 Michael Lorenz
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28/*
29 * a crude BDF loader for wsdisplay
30 */
31
32#include <stdlib.h>
33#include <stdio.h>
34#include <fcntl.h>
35#include <unistd.h>
36#include <string.h>
37#include <errno.h>
38#include <ctype.h>
39#include <sys/ioctl.h>
40#include <err.h>
41
42#include <dev/wscons/wsconsio.h>
43
44/*
45 * wsdisplay_font but with strings embedded and integer fields in
46 * little endian
47 */
48struct wsfthdr {
49	char magic[4];		/* "WSFT" */
50	char name[64];
51	uint32_t firstchar;
52	uint32_t numchars;
53	uint32_t encoding;
54	uint32_t fontwidth;
55	uint32_t fontheight;
56	uint32_t stride;
57	uint32_t bitorder;
58	uint32_t byteorder;
59};
60
61
62const struct encmap {
63	const char *name;
64	int encoding;
65} encmap[] = {
66	{ "cp437",	WSDISPLAY_FONTENC_IBM },
67	{ "ibm",	WSDISPLAY_FONTENC_IBM },
68	{ "iso",	WSDISPLAY_FONTENC_ISO },
69	{ "iso8859",	WSDISPLAY_FONTENC_ISO },
70	{ "iso10646",	WSDISPLAY_FONTENC_ISO },
71	{ "iso-8859-1",	WSDISPLAY_FONTENC_ISO },
72	{ "iso-8859-2",	WSDISPLAY_FONTENC_ISO2 },
73	{ "iso-8859-7",	WSDISPLAY_FONTENC_ISO7 },
74	{ "iso2",	WSDISPLAY_FONTENC_ISO2 },
75	{ "iso7",	WSDISPLAY_FONTENC_ISO7 },
76	{ "iso8859-1",	WSDISPLAY_FONTENC_ISO },
77	{ "iso8859-2",	WSDISPLAY_FONTENC_ISO2 },
78	{ "iso8859-7",	WSDISPLAY_FONTENC_ISO7 },
79	{ "koi8-r",	WSDISPLAY_FONTENC_KOI8_R },
80	{ "koi8r",	WSDISPLAY_FONTENC_KOI8_R },
81	{ "latin-1",	WSDISPLAY_FONTENC_ISO },
82	{ "latin-2",	WSDISPLAY_FONTENC_ISO2 },
83	{ "latin1",	WSDISPLAY_FONTENC_ISO },
84	{ "latin2",	WSDISPLAY_FONTENC_ISO2 },
85	{ "pcvt",	WSDISPLAY_FONTENC_PCVT },
86	{ NULL, -1 }
87};
88
89const char * const encname[] = {
90#define _ENC(_e) [_e] = #_e
91	_ENC(WSDISPLAY_FONTENC_ISO),
92	_ENC(WSDISPLAY_FONTENC_IBM),
93	_ENC(WSDISPLAY_FONTENC_PCVT),
94	_ENC(WSDISPLAY_FONTENC_ISO7),
95	_ENC(WSDISPLAY_FONTENC_ISO2),
96	_ENC(WSDISPLAY_FONTENC_KOI8_R),
97};
98
99
100const char *ofile = NULL;
101int encoding = -1;
102int verbose = 0;
103int dump = 0;
104int header = 0;
105int force = 0;
106char commentbuf[2048] = "";
107int commentptr = 0;
108char fontname[64] = "";
109
110void
111dump_line(char *gptr, int stride)
112{
113	int i, j, msk, c;
114
115	for (i = 0; i < stride; i++) {
116		c = gptr[i];
117		msk = 0x80;
118		for (j = 0; j < 8; j++) {
119			putchar((c & msk) != 0 ? '#' : ' ');
120			msk = msk >> 1;
121		}
122	}
123	printf("\n");
124}
125
126void
127write_wsf(const char *oname, struct wsdisplay_font *f, char *buffer, int buflen)
128{
129	struct wsfthdr h;
130
131	memset(&h, 0, sizeof(h));
132	strncpy(h.magic, "WSFT", sizeof(h.magic));
133	strncpy(h.name, f->name, sizeof(h.name));
134	h.firstchar = htole32(f->firstchar);
135	h.numchars = htole32(f->numchars);
136	h.encoding = htole32(f->encoding);
137	h.fontwidth = htole32(f->fontwidth);
138	h.fontheight = htole32(f->fontheight);
139	h.stride = htole32(f->stride);
140	h.bitorder = htole32(f->bitorder);
141	h.byteorder = htole32(f->byteorder);
142
143	int wsfd = open(ofile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
144	if (wsfd < 0)
145		err(EXIT_FAILURE, "%s", ofile);
146
147	ssize_t nwritten;
148	nwritten = write(wsfd, &h, sizeof(h));
149	if (nwritten < 0)
150		err(EXIT_FAILURE, "%s", ofile);
151	if (nwritten != sizeof(h))
152		errx(EXIT_FAILURE, "%s: partial write", ofile);
153
154	nwritten = write(wsfd, buffer, buflen);
155	if (nwritten < 0)
156		err(EXIT_FAILURE, "%s", ofile);
157	if (nwritten != buflen)
158		errx(EXIT_FAILURE, "%s: partial write", ofile);
159	close(wsfd);
160}
161
162int
163write_header(const char *filename, struct wsdisplay_font *f,
164             char *buffer, int buflen)
165{
166	FILE *output;
167	int i, j, x, y, idx, pxls, left;
168	char name[64], c, msk;
169
170	/* now output as a header file */
171	snprintf(name, sizeof(name), "%s_%dx%d", f->name,
172	    f->fontwidth, f->fontheight);
173	for (i = 0; i < strlen(name); i++) {
174		if (isblank((unsigned char)name[i]))
175			name[i] = '_';
176	}
177	if ((output = fopen(filename, "w")) == NULL) {
178		warn("Can't open output file `%s'", filename);
179		return -1;
180	}
181	if (commentptr > 0) {
182		fprintf(output, "/*\n");
183		fputs(commentbuf, output);
184		fprintf(output, "*/\n\n");
185	}
186
187	fprintf(output, "static u_char %s_data[];\n", name);
188	fprintf(output, "\n");
189	fprintf(output, "static struct wsdisplay_font %s = {\n", name);
190	fprintf(output, "\t\"%s\",\t\t\t/* typeface name */\n", f->name);
191	fprintf(output, "\t%d,\t\t\t\t/* firstchar */\n", f->firstchar);
192	fprintf(output, "\t%d,\t\t\t\t/* numchars */\n", f->numchars);
193	fprintf(output, "\t%d,\t\t\t\t/* encoding */\n", f->encoding);
194	fprintf(output, "\t%d,\t\t\t\t/* fontwidth */\n", f->fontwidth);
195	fprintf(output, "\t%d,\t\t\t\t/* fontheight */\n", f->fontheight);
196	fprintf(output, "\t%d,\t\t\t\t/* stride */\n", f->stride);
197	fprintf(output, "\tWSDISPLAY_FONTORDER_L2R,\t/* bit order */\n");
198	fprintf(output, "\tWSDISPLAY_FONTORDER_L2R,\t/* byte order */\n");
199	fprintf(output, "\t%s_data\t\t/* data */\n", name);
200	fprintf(output, "};\n\n");
201	fprintf(output, "static u_char %s_data[] = {\n", name);
202	for (i = f->firstchar; i < f->firstchar + f->numchars; i++) {
203		fprintf(output, "\t/* %d */\n", i);
204		idx = i * f->stride * f->fontheight;
205		for (y = 0; y < f->fontheight; y++) {
206			for (x = 0; x < f->stride; x++) {
207				fprintf(output, "0x%02x, ",buffer[idx + x]);
208			}
209			fprintf(output, "/* ");
210			pxls = f->fontwidth;
211			for (x = 0; x < f->stride; x++) {
212				c = buffer[idx + x];
213				msk = 0x80;
214				left = pxls > 8 ? 8 : pxls;
215				for (j = 0; j < left; j++) {
216					fprintf(output, "%s",
217					    (c & msk) != 0 ? "[]" : ". ");
218					msk = msk >> 1;
219				}
220				pxls -= 8;
221			}
222			fprintf(output, " */\n");
223
224			idx += f->stride;
225		}
226	}
227	fprintf(output, "};\n");
228	fclose(output);
229	return 0;
230}
231
232void
233interpret(FILE *foo)
234{
235	char line[128], *arg, name[64] = "foo", *buffer, *cbitmap;
236	int buflen = -1;
237	int in_char = 0, current = -1, stride = 0, charsize = 0;
238	int width, height, x, y, num;
239	int first = 255, last = 0;
240	int left, top, lines;
241	int bl = 255, bt = 255, br = -1, bb = -1;
242	struct wsdisplay_font f;
243	int status;
244
245	while (fgets(line, sizeof(line), foo) != NULL) {
246		size_t i = 0, len;
247		/* separate keyword from parameters */
248		len = strlen(line);
249		while (!isspace((unsigned char)line[i]) && i < len) i++;
250		line[i] = 0;
251		arg = &line[i + 1];
252		i = 0;
253		len = strlen(arg);
254		/* get rid of garbage */
255		while ((!iscntrl((unsigned char)arg[i])) && (arg[i] != 0)) {
256			i++;
257		}
258		arg[i] = 0;
259		if (strcmp(line, "FAMILY_NAME") == 0) {
260			/* cut off quotation marks */
261			strlcpy(name, arg + 1, 64);
262			if (verbose) printf("name: %s\n", name);
263		} else if (strcmp(line, "COMMENT") == 0) {
264			commentptr += snprintf(&commentbuf[commentptr],
265			    sizeof(commentbuf) - commentptr, "%s\n", arg);
266		} else if (strcmp(line, "SPACING") == 0) {
267			char spc[16];
268			int res;
269			res = sscanf(arg, "%s", spc);
270			if (res > 0) {
271				if (verbose) printf("spacing %s\n", spc);
272				if ((spc[1] == 'P') && (force == 0)) {
273					warnx("This is a proportional font, "
274					   "results are probably not suitable "
275					   "for console use.");
276					errx(EXIT_FAILURE, "Use -f to override "
277					    "if you want to try it anyway.");
278				}
279			}
280		} else if (strcmp(line, "FONTBOUNDINGBOX") == 0) {
281			int res;
282			res = sscanf(arg, "%d %d %d %d",
283					  &width, &height, &x, &y);
284			stride = (width + 7) >> 3;
285			if (verbose) printf("box %d x %d\n", width, height);
286			if (stride > 2) {
287				errx(EXIT_FAILURE,
288				    "no fonts wider than 16 work for now\n");
289			}
290			charsize = height * stride;
291			buflen = 257 * charsize;
292			buffer = calloc(1, buflen);
293			if (buffer == NULL) {
294				err(EXIT_FAILURE,
295				    "failed to allocate %dKB for glyphs\n",
296				    buflen);
297			}
298			cbitmap = buffer + 256 * charsize;
299		} else if (strcmp(line, "CHARS") == 0) {
300			if (sscanf(arg, "%d", &num) == 1)
301				if (verbose)
302				    printf("number of characters: %d\n", num);
303		} else if (strcmp(line, "STARTCHAR") == 0) {
304			in_char = 1;
305			if (charsize <= 1) err(EXIT_FAILURE,
306			    "syntax error - no valid FONTBOUNDINGBOX\n");
307			memset(cbitmap, 0, charsize);
308		} else if (strcmp(line, "ENDCHAR") == 0) {
309			in_char = 0;
310			/* only commit the glyph if it's in range */
311			if ((current >= 0) && (current < 256)) {
312				memcpy(&buffer[charsize * current],
313				    cbitmap, charsize);
314			}
315			current = -1;
316		} else if (strcmp(line, "ENCODING") == 0) {
317			if (sscanf(arg, "%d", &current) == 1) {
318				if (current >= 0 && current < 256) {
319					if (current < first) first = current;
320					if (current > last) last = current;
321					if (dump) printf("glyph %d\n", current);
322				}
323			}
324		} else if (strcmp(line, "BBX") == 0) {
325			int cx, cy, cwi, che;
326			if (sscanf(arg, "%d %d %d %d", &cwi, &che, &cx, &cy)
327			     == 4) {
328				left = cx;
329				lines = che;
330				top = height + y - che - cy;
331				if (left < bl) bl = left;
332				if (top < bt) bt = top;
333				if ((left + cwi) > br) br = left + cwi;
334				if ((top + che) > bb) bb = top + che;
335				if (dump && verbose)
336					printf("top %d left %d\n", top, left);
337			}
338		} else if (strcmp(line, "BITMAP") == 0) {
339			int i, j, k, l;
340			char num[32];
341			char *gptr = cbitmap;
342			char *bptr = gptr + top;
343			uint16_t *bptr16 = (uint16_t *)gptr;
344			bptr16 += top;
345			/* see if the character is in range */
346			if ((current < 0) || (current > 255)) continue;
347			/* now we read & render the character */
348			for (i = 0; i < lines; i++) {
349				fgets(num, 32, foo);
350				sscanf(num, "%x", &l);
351				if ((stride) == 2 && (strlen(num) < 4))
352					l = l << 8;
353				l = l >> left;
354				if (stride == 1) {
355					*bptr = l;
356					bptr++;
357				} else {
358					*bptr16 = htobe16(l);
359					bptr16++;
360				}
361			}
362			if (dump) {
363				gptr = cbitmap;
364				for (i = 0; i < height; i++) {
365					dump_line(gptr, stride);
366					gptr += stride;
367				}
368			}
369		}
370	}
371	if (verbose) {
372		printf("range %d to %d\n", first, last);
373		printf("encoding: %s\n", encname[encoding]);
374		printf("actual box: %d %d %d %d\n", bl, bt, br, bb);
375	}
376
377	/* now stuff it into a something wsfont understands */
378	f.fontwidth = width /*(width + 3) & ~3*/;
379	f.fontheight = height;
380	f.firstchar = first;
381	f.numchars = last - first + 1;
382	f.stride = stride;
383	f.encoding = encoding;
384	if (fontname[0] == 0) {
385		f.name = name;
386	} else f.name = fontname;
387	f.bitorder = WSDISPLAY_FONTORDER_L2R;
388	f.byteorder = WSDISPLAY_FONTORDER_L2R;
389	f.data = &buffer[first * charsize];
390
391	if (ofile == NULL) {
392		int fdev = open("/dev/wsfont", O_RDWR, 0);
393		if (fdev < 0)
394			err(EXIT_FAILURE, "/dev/wsfont");
395		status = ioctl(fdev, WSDISPLAYIO_LDFONT, &f);
396		if (status != 0)
397			err(EXIT_FAILURE, "WSDISPLAYIO_LDFONT");
398		close(fdev);
399	}
400	else {
401		if (header == 0)
402			write_wsf(ofile, &f, buffer, buflen);
403		else
404			write_header(ofile, &f, buffer, buflen);
405	}
406}
407
408__dead void
409usage()
410{
411	fprintf(stderr, "Usage: %s [-vdhf] [-e encoding] [-N name] "
412	    "[-o ofile.wsf] font.bdf\n", getprogname());
413	exit(EXIT_FAILURE);
414}
415
416int
417main(int argc, char *argv[])
418{
419	FILE *foo;
420	const char *encname = NULL;
421
422	int c;
423	while ((c = getopt(argc, argv, "e:o:N:vdhf")) != -1) {
424		switch (c) {
425
426		/* font encoding */
427		case 'e':
428			if (encname != NULL)
429				usage();
430			encname = optarg;
431			break;
432
433		/* output file name */
434		case 'o':
435			if (ofile != NULL)
436				usage();
437			ofile = optarg;
438			break;
439
440		case 'v':
441			verbose = 1;
442			break;
443
444		case 'd':
445			dump = 1;
446			break;
447
448		case 'h':
449			header = 1;
450			break;
451		case 'f':
452			force = 1;
453			break;
454		case 'N':
455			strncpy(fontname, optarg, 64);
456			break;
457		case '?':	/* FALLTHROUGH */
458		default:
459			usage();
460		}
461	}
462
463	argc -= optind;
464	argv += optind;
465
466	if (encname == NULL) {
467		encoding = WSDISPLAY_FONTENC_ISO;
468	}
469	else {
470		for (const struct encmap *e = encmap; e->name; ++e) {
471			if (strcmp(e->name, encname) == 0) {
472				encoding = e->encoding;
473				break;
474			}
475		}
476	}
477
478	/* get encoding from the bdf file? */
479	if (encoding == -1)
480		encoding = WSDISPLAY_FONTENC_ISO;
481
482	if (argc == 0)
483		usage();
484
485	const char *bdfname = argv[0];
486	foo = fopen(bdfname, "r");
487	if (foo == NULL)
488		err(EXIT_FAILURE, "%s", bdfname);
489
490	interpret(foo);
491	return EXIT_SUCCESS;
492}
493