Add a TODO mark -- code duplication is ugly
[kugel-rb.git] / tools / convbdf.c
blob6afa79ddc8970e8cc337f4100051a43be60a0dc6
1 /*
2 * Convert BDF files to C source and/or Rockbox .fnt file format
4 * Copyright (c) 2002 by Greg Haerr <greg@censoft.com>
6 * What fun it is converting font data...
8 * 09/17/02 Version 1.0
9 */
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <stdarg.h>
14 #include <time.h>
16 #define ROTATE /* define this for the new, rotated format */
18 /* BEGIN font.h*/
19 /* loadable font magic and version #*/
20 #ifdef ROTATE
21 #define VERSION "RB12" /* newer version */
22 #else
23 #define VERSION "RB11"
24 #endif
27 * bitmap_t helper macros
29 typedef unsigned short bitmap_t; /* bitmap image unit size*/
31 /* Number of words to hold a pixel line of width x pixels */
32 #define BITMAP_BITSPERIMAGE (sizeof(bitmap_t) * 8)
33 #define BITMAP_WORDS(x) (((x)+BITMAP_BITSPERIMAGE-1)/BITMAP_BITSPERIMAGE)
34 #define BITMAP_BYTES(x) (BITMAP_WORDS(x)*sizeof(bitmap_t))
35 #define BITMAP_BITVALUE(n) ((bitmap_t) (((bitmap_t) 1) << (n)))
36 #define BITMAP_FIRSTBIT (BITMAP_BITVALUE(BITMAP_BITSPERIMAGE - 1))
37 #define BITMAP_TESTBIT(m) ((m) & BITMAP_FIRSTBIT)
38 #define BITMAP_SHIFTBIT(m) ((bitmap_t) ((m) << 1))
41 /* builtin C-based proportional/fixed font structure */
42 /* based on The Microwindows Project http://microwindows.org */
43 struct font {
44 int maxwidth; /* max width in pixels */
45 int height; /* height in pixels */
46 int ascent; /* ascent (baseline) height */
47 int firstchar; /* first character in bitmap */
48 int size; /* font size in glyphs ('holes' included) */
49 bitmap_t* bits; /* 16-bit right-padded bitmap data */
50 int* offset; /* offsets into bitmap data */
51 unsigned char* width; /* character widths or NULL if fixed */
52 int defaultchar; /* default char (not glyph index) */
53 int bits_size; /* # words of bitmap_t bits */
55 /* unused by runtime system, read in by convbdf */
56 int nchars; /* number of different glyphs */
57 int nchars_declared; /* number of glyphs as declared in the header */
58 int ascent_declared; /* ascent as declared in the header */
59 int descent_declared; /* descent as declared in the header */
60 unsigned int* offrot; /* offsets into rotated bitmap data */
61 char* name; /* font name */
62 char* facename; /* facename of font */
63 char* copyright; /* copyright info for loadable fonts */
64 int pixel_size;
65 int descent;
66 int fbbw, fbbh, fbbx, fbby;
68 /* Max 'overflow' of a char's ascent (descent) over the font's one */
69 int max_over_ascent, max_over_descent;
71 /* The number of clipped ascents/descents/total */
72 int num_clipped_ascent, num_clipped_descent, num_clipped;
74 /* END font.h*/
76 /* Description of how the ascent/descent is allowed to grow */
77 struct stretch {
78 int value; /* The delta value (in pixels or percents) */
79 int percent; /* Is the value in percents (true) or pixels (false)? */
80 int force; /* MUST the value be set (true) or is it just a max (false) */
83 #define isprefix(buf,str) (!strncmp(buf, str, strlen(str)))
84 #define strequal(s1,s2) (!strcmp(s1, s2))
86 #define MAX(a,b) ((a) > (b) ? (a) : (b))
87 #define MIN(a,b) ((a) < (b) ? (a) : (b))
89 /* Depending on the verbosity level some warnings are printed or not */
90 int verbosity_level = 0;
91 int trace = 0;
93 /* Prints a warning of the specified verbosity level. It will only be
94 really printed if the level is >= the level set in the settings */
95 void print_warning(int level, const char *fmt, ...);
96 void print_error(const char *fmt, ...);
97 void print_info(const char *fmt, ...);
98 void print_trace(const char *fmt, ...);
99 #define VL_CLIP_FONT 1 /* Verbosity level for clip related warnings at font level */
100 #define VL_CLIP_CHAR 2 /* Verbosity level for clip related warnings at char level */
101 #define VL_MISC 1 /* Verbosity level for other warnings */
103 int gen_c = 0;
104 int gen_h = 0;
105 int gen_fnt = 0;
106 int gen_map = 1;
107 int start_char = 0;
108 int limit_char = 65535;
109 int oflag = 0;
110 char outfile[256];
112 struct stretch stretch_ascent = { 0, 0, 1 }; /* Don't allow ascent to grow by default */
113 struct stretch stretch_descent = { 0, 0, 1 }; /* Don't allow descent to grow by default */
116 void usage(void);
117 void getopts(int *pac, char ***pav);
118 int convbdf(char *path);
120 void free_font(struct font* pf);
121 struct font* bdf_read_font(char *path);
122 int bdf_read_header(FILE *fp, struct font* pf);
123 int bdf_read_bitmaps(FILE *fp, struct font* pf);
126 Counts the glyphs and determines the max dimensions of glyphs
127 (fills the fields nchars, maxwidth, max_over_ascent, max_over_descent).
128 Returns 0 on failure or not-0 on success.
130 int bdf_analyze_font(FILE *fp, struct font* pf);
131 void bdf_correct_bbx(int *width, int *bbx); /* Corrects bbx and width if bbx<0 */
133 /* Corrects the ascent and returns the new value (value to use) */
134 int adjust_ascent(int ascent, int overflow, struct stretch *stretch);
136 char * bdf_getline(FILE *fp, char *buf, int len);
137 bitmap_t bdf_hexval(unsigned char *buf, int ndx1, int ndx2);
139 int gen_c_source(struct font* pf, char *path);
140 int gen_h_header(struct font* pf, char *path);
141 int gen_fnt_file(struct font* pf, char *path);
143 void
144 usage(void)
146 /* We use string array because some C compilers issue warnings about too long strings */
147 char *help[] = {
148 "Usage: convbdf [options] [input-files]\n",
149 " convbdf [options] [-o output-file] [single-input-file]\n",
150 "Options:\n",
151 " -c Convert .bdf to .c source file\n",
152 " -h Convert .bdf to .h header file (to create sysfont.h)\n",
153 " -f Convert .bdf to .fnt font file\n",
154 " -s N Start output at character encodings >= N\n",
155 " -l N Limit output to character encodings <= N\n",
156 " -n Don't generate bitmaps as comments in .c file\n",
157 " -a N[%][!] Allow the ascent to grow N pixels/% to avoid glyph clipping\n",
158 " -d N[%][!] Allow the descent to grow N pixels/% to avoid glyph clipping\n",
159 " -v N Verbosity level: 0=quite quiet, 1=more verbose, 2=even more, etc.\n",
160 " -t Print internal tracing messages\n",
161 NULL /* Must be the last element in the array */
164 char **p = help;
165 while (*p != NULL)
166 print_info("%s", *(p++));
170 void parse_ascent_opt(char *val, struct stretch *opt) {
171 char buf[256];
172 char *p;
173 strcpy(buf, val);
175 opt->force = 0;
176 opt->percent = 0;
177 p = buf + strlen(buf);
178 while (p > buf) {
179 p--;
180 if (*p == '%') {
181 opt->percent = 1;
182 *p = '\0';
184 else if (*p == '!') {
185 opt->force = 1;
186 *p = '\0';
188 else {
189 break;
192 opt->value = atoi(buf);
195 /* parse command line options*/
196 void getopts(int *pac, char ***pav)
198 char *p;
199 char **av;
200 int ac;
202 ac = *pac;
203 av = *pav;
204 while (ac > 0 && av[0][0] == '-') {
205 p = &av[0][1];
206 while( *p)
207 switch(*p++) {
208 case ' ': /* multiple -args on av[] */
209 while( *p && *p == ' ')
210 p++;
211 if( *p++ != '-') /* next option must have dash */
212 p = "";
213 break; /* proceed to next option */
214 case 'c': /* generate .c output */
215 gen_c = 1;
216 break;
217 case 'h': /* generate .h output */
218 gen_h = 1;
219 break;
220 case 'f': /* generate .fnt output */
221 gen_fnt = 1;
222 break;
223 case 'n': /* don't gen bitmap comments */
224 gen_map = 0;
225 break;
226 case 'o': /* set output file */
227 oflag = 1;
228 if (*p) {
229 strcpy(outfile, p);
230 while (*p && *p != ' ')
231 p++;
233 else {
234 av++; ac--;
235 if (ac > 0)
236 strcpy(outfile, av[0]);
238 break;
239 case 'l': /* set encoding limit */
240 if (*p) {
241 limit_char = atoi(p);
242 while (*p && *p != ' ')
243 p++;
245 else {
246 av++; ac--;
247 if (ac > 0)
248 limit_char = atoi(av[0]);
250 break;
251 case 's': /* set encoding start */
252 if (*p) {
253 start_char = atoi(p);
254 while (*p && *p != ' ')
255 p++;
257 else {
258 av++; ac--;
259 if (ac > 0)
260 start_char = atoi(av[0]);
262 break;
263 case 'a': /* ascent growth */
264 if (*p) {
265 parse_ascent_opt(p, &stretch_ascent);
266 while (*p && *p != ' ')
267 p++;
269 else {
270 av++; ac--;
271 if (ac > 0)
272 parse_ascent_opt(av[0], &stretch_ascent);
274 break;
275 case 'd': /* descent growth */
276 if (*p) {
277 parse_ascent_opt(p, &stretch_descent);
278 while (*p && *p != ' ')
279 p++;
281 else {
282 av++; ac--;
283 if (ac > 0)
284 parse_ascent_opt(av[0], &stretch_descent);
286 break;
287 case 'v': /* verbosity */
288 if (*p) {
289 verbosity_level = atoi(p);
290 while (*p && *p != ' ')
291 p++;
293 else {
294 av++; ac--;
295 if (ac > 0)
296 verbosity_level = atoi(av[0]);
298 break;
299 case 't': /* tracing */
300 trace = 1;
301 break;
302 default:
303 print_info("Unknown option ignored: %c\n", *(p-1));
305 ++av; --ac;
307 *pac = ac;
308 *pav = av;
311 void print_warning(int level, const char *fmt, ...) {
312 if (verbosity_level >= level) {
313 va_list ap;
314 va_start(ap, fmt);
315 fprintf(stderr, " WARN: ");
316 vfprintf(stderr, fmt, ap);
317 va_end(ap);
321 void print_trace(const char *fmt, ...) {
322 if (trace) {
323 va_list ap;
324 va_start(ap, fmt);
325 fprintf(stderr, "TRACE: ");
326 vfprintf(stderr, fmt, ap);
327 va_end(ap);
331 void print_error(const char *fmt, ...) {
332 va_list ap;
333 va_start(ap, fmt);
334 fprintf(stderr, "ERROR: ");
335 vfprintf(stderr, fmt, ap);
336 va_end(ap);
339 void print_info(const char *fmt, ...) {
340 va_list ap;
341 va_start(ap, fmt);
342 fprintf(stderr, " INFO: ");
343 vfprintf(stderr, fmt, ap);
344 va_end(ap);
347 /* remove directory prefix and file suffix from full path */
348 char *basename(char *path)
350 char *p, *b;
351 static char base[256];
353 /* remove prepended path and extension */
354 b = path;
355 for (p=path; *p; ++p) {
356 if (*p == '/')
357 b = p + 1;
359 strcpy(base, b);
360 for (p=base; *p; ++p) {
361 if (*p == '.') {
362 *p = 0;
363 break;
366 return base;
369 int convbdf(char *path)
371 struct font* pf;
372 int ret = 0;
374 pf = bdf_read_font(path);
375 if (!pf)
376 exit(1);
378 if (gen_c) {
379 if (!oflag) {
380 strcpy(outfile, basename(path));
381 strcat(outfile, ".c");
383 ret |= gen_c_source(pf, outfile);
386 if (gen_h) {
387 if (!oflag) {
388 strcpy(outfile, basename(path));
389 strcat(outfile, ".h");
391 ret |= gen_h_header(pf, outfile);
394 if (gen_fnt) {
395 if (!oflag) {
396 strcpy(outfile, basename(path));
397 strcat(outfile, ".fnt");
399 ret |= gen_fnt_file(pf, outfile);
402 free_font(pf);
403 return ret;
406 int main(int ac, char **av)
408 int ret = 0;
410 ++av; --ac; /* skip av[0] */
411 getopts(&ac, &av); /* read command line options */
413 if (ac < 1 || (!gen_c && !gen_h && !gen_fnt)) {
414 usage();
415 exit(1);
417 if (oflag) {
418 if (ac > 1 || (gen_c && gen_fnt) || (gen_c && gen_h) || (gen_h && gen_fnt)) {
419 usage();
420 exit(1);
424 while (ac > 0) {
425 ret |= convbdf(av[0]);
426 ++av; --ac;
429 exit(ret);
432 /* free font structure */
433 void free_font(struct font* pf)
435 if (!pf)
436 return;
437 if (pf->name)
438 free(pf->name);
439 if (pf->facename)
440 free(pf->facename);
441 if (pf->bits)
442 free(pf->bits);
443 if (pf->offset)
444 free(pf->offset);
445 if (pf->offrot)
446 free(pf->offrot);
447 if (pf->width)
448 free(pf->width);
449 free(pf);
452 /* build incore structure from .bdf file */
453 struct font* bdf_read_font(char *path)
455 FILE *fp;
456 struct font* pf;
458 fp = fopen(path, "rb");
459 if (!fp) {
460 print_error("Error opening file: %s\n", path);
461 return NULL;
464 pf = (struct font*)calloc(1, sizeof(struct font));
465 if (!pf)
466 goto errout;
467 memset(pf, 0, sizeof(struct font));
469 pf->name = strdup(basename(path));
471 if (!bdf_read_header(fp, pf)) {
472 print_error("Error reading font header\n");
473 goto errout;
475 print_trace("Read font header, nchars_decl=%d\n", pf->nchars_declared);
477 if (!bdf_analyze_font(fp, pf)) {
478 print_error("Error analyzing the font\n");
479 goto errout;
481 print_trace("Analyzed font, nchars=%d, maxwidth=%d, asc_over=%d, desc_over=%d\n",
482 pf->nchars, pf->maxwidth, pf->max_over_ascent, pf->max_over_descent);
484 if (pf->nchars != pf->nchars_declared) {
485 print_warning(VL_MISC, "The declared number of chars (%d) "
486 "does not match the real number (%d)\n",
487 pf->nchars_declared, pf->nchars);
490 /* Correct ascent/descent if necessary */
491 pf->ascent = adjust_ascent(pf->ascent_declared, pf->max_over_ascent, &stretch_ascent);
492 if (pf->ascent != pf->ascent_declared) {
493 print_info("Font ascent has been changed from %d to %d\n",
494 pf->ascent_declared, pf->ascent);
496 pf->descent = adjust_ascent(pf->descent, pf->max_over_descent, &stretch_descent);
497 if (pf->descent != pf->descent_declared) {
498 print_info("Font descent has been changed from %d to %d\n",
499 pf->descent_declared, pf->descent);
501 pf->height = pf->ascent + pf->descent;
502 if (pf->height != pf->ascent_declared + pf->descent_declared) {
503 print_warning(VL_CLIP_FONT, "Generated font's height: %d\n", pf->height);
506 /* Alocate memory */
507 pf->bits_size = pf->size * BITMAP_WORDS(pf->maxwidth) * pf->height;
508 pf->bits = (bitmap_t *)malloc(pf->bits_size * sizeof(bitmap_t));
509 pf->offset = (int *)malloc(pf->size * sizeof(int));
510 pf->offrot = (unsigned int *)malloc(pf->size * sizeof(unsigned int));
511 pf->width = (unsigned char *)malloc(pf->size * sizeof(unsigned char));
513 if (!pf->bits || !pf->offset || !pf->offrot || !pf->width) {
514 print_error("no memory for font load\n");
515 goto errout;
518 pf->num_clipped_ascent = pf->num_clipped_descent = pf->num_clipped = 0;
519 pf->max_over_ascent = pf->max_over_descent = 0;
521 if (!bdf_read_bitmaps(fp, pf)) {
522 print_error("Error reading font bitmaps\n");
523 goto errout;
525 print_trace("Read bitmaps\n");
527 if (pf->num_clipped > 0) {
528 print_warning(VL_CLIP_FONT, "%d character(s) out of %d were clipped "
529 "(%d at ascent, %d at descent)\n",
530 pf->num_clipped, pf->nchars,
531 pf->num_clipped_ascent, pf->num_clipped_descent);
532 print_warning(VL_CLIP_FONT, "max overflows: %d pixel(s) at ascent, %d pixel(s) at descent\n",
533 pf->max_over_ascent, pf->max_over_descent);
536 fclose(fp);
537 return pf;
539 errout:
540 fclose(fp);
541 free_font(pf);
542 return NULL;
545 /* read bdf font header information, return 0 on error */
546 int bdf_read_header(FILE *fp, struct font* pf)
548 int encoding;
549 int firstchar = 65535;
550 int lastchar = -1;
551 char buf[256];
552 char facename[256];
553 char copyright[256];
555 /* set certain values to errors for later error checking */
556 pf->defaultchar = -1;
557 pf->ascent = -1;
558 pf->descent = -1;
560 for (;;) {
561 if (!bdf_getline(fp, buf, sizeof(buf))) {
562 print_error("EOF on file\n");
563 return 0;
565 if (isprefix(buf, "FONT ")) { /* not required */
566 if (sscanf(buf, "FONT %[^\n]", facename) != 1) {
567 print_error("bad 'FONT'\n");
568 return 0;
570 pf->facename = strdup(facename);
571 continue;
573 if (isprefix(buf, "COPYRIGHT ")) { /* not required */
574 if (sscanf(buf, "COPYRIGHT \"%[^\"]", copyright) != 1) {
575 print_error("bad 'COPYRIGHT'\n");
576 return 0;
578 pf->copyright = strdup(copyright);
579 continue;
581 if (isprefix(buf, "DEFAULT_CHAR ")) { /* not required */
582 if (sscanf(buf, "DEFAULT_CHAR %d", &pf->defaultchar) != 1) {
583 print_error("bad 'DEFAULT_CHAR'\n");
584 return 0;
587 if (isprefix(buf, "FONT_DESCENT ")) {
588 if (sscanf(buf, "FONT_DESCENT %d", &pf->descent_declared) != 1) {
589 print_error("bad 'FONT_DESCENT'\n");
590 return 0;
592 pf->descent = pf->descent_declared; /* For now */
593 continue;
595 if (isprefix(buf, "FONT_ASCENT ")) {
596 if (sscanf(buf, "FONT_ASCENT %d", &pf->ascent_declared) != 1) {
597 print_error("bad 'FONT_ASCENT'\n");
598 return 0;
600 pf->ascent = pf->ascent_declared; /* For now */
601 continue;
603 if (isprefix(buf, "FONTBOUNDINGBOX ")) {
604 if (sscanf(buf, "FONTBOUNDINGBOX %d %d %d %d",
605 &pf->fbbw, &pf->fbbh, &pf->fbbx, &pf->fbby) != 4) {
606 print_error("bad 'FONTBOUNDINGBOX'\n");
607 return 0;
609 continue;
611 if (isprefix(buf, "CHARS ")) {
612 if (sscanf(buf, "CHARS %d", &pf->nchars_declared) != 1) {
613 print_error("bad 'CHARS'\n");
614 return 0;
616 continue;
620 * Reading ENCODING is necessary to get firstchar/lastchar
621 * which is needed to pre-calculate our offset and widths
622 * array sizes.
624 if (isprefix(buf, "ENCODING ")) {
625 if (sscanf(buf, "ENCODING %d", &encoding) != 1) {
626 print_error("bad 'ENCODING'\n");
627 return 0;
629 if (encoding >= 0 &&
630 encoding <= limit_char &&
631 encoding >= start_char) {
633 if (firstchar > encoding)
634 firstchar = encoding;
635 if (lastchar < encoding)
636 lastchar = encoding;
638 continue;
640 if (strequal(buf, "ENDFONT"))
641 break;
644 /* calc font height*/
645 if (pf->ascent < 0 || pf->descent < 0 || firstchar < 0) {
646 print_error("Invalid BDF file, requires FONT_ASCENT/FONT_DESCENT/ENCODING\n");
647 return 0;
649 pf->height = pf->ascent + pf->descent;
651 /* calc default char */
652 if (pf->defaultchar < 0 ||
653 pf->defaultchar < firstchar ||
654 pf->defaultchar > limit_char ||
655 pf->defaultchar > lastchar)
656 pf->defaultchar = firstchar;
658 /* calc font size (offset/width entries) */
659 pf->firstchar = firstchar;
660 pf->size = lastchar - firstchar + 1;
662 return 1;
666 * TODO: rework the code to avoid logics duplication in
667 * bdf_read_bitmaps and bdf_analyze_font
671 /* read bdf font bitmaps, return 0 on error */
672 int bdf_read_bitmaps(FILE *fp, struct font* pf)
674 int ofs = 0;
675 int ofr = 0;
676 int i, k, encoding, width;
677 int bbw, bbh, bbx, bby;
678 int proportional = 0;
679 int encodetable = 0;
680 int l;
681 char buf[256];
682 bitmap_t *ch_bitmap;
683 int ch_words;
685 /* reset file pointer */
686 fseek(fp, 0L, SEEK_SET);
688 /* initially mark offsets as not used */
689 for (i=0; i<pf->size; ++i)
690 pf->offset[i] = -1;
692 for (;;) {
693 if (!bdf_getline(fp, buf, sizeof(buf))) {
694 print_error("EOF on file\n");
695 return 0;
697 if (isprefix(buf, "STARTCHAR")) {
698 encoding = width = -1;
699 bbw = pf->fbbw;
700 bbh = pf->fbbh;
701 bbx = pf->fbbx;
702 bby = pf->fbby;
703 continue;
705 if (isprefix(buf, "ENCODING ")) {
706 if (sscanf(buf, "ENCODING %d", &encoding) != 1) {
707 print_error("bad 'ENCODING'\n");
708 return 0;
710 if (encoding < start_char || encoding > limit_char)
711 encoding = -1;
712 continue;
714 if (isprefix(buf, "DWIDTH ")) {
715 if (sscanf(buf, "DWIDTH %d", &width) != 1) {
716 print_error("bad 'DWIDTH'\n");
717 return 0;
719 /* use font boundingbox width if DWIDTH <= 0 */
720 if (width <= 0)
721 width = pf->fbbw - pf->fbbx;
722 continue;
724 if (isprefix(buf, "BBX ")) {
725 if (sscanf(buf, "BBX %d %d %d %d", &bbw, &bbh, &bbx, &bby) != 4) {
726 print_error("bad 'BBX'\n");
727 return 0;
729 continue;
731 if (strequal(buf, "BITMAP") || strequal(buf, "BITMAP ")) {
732 int overflow_asc, overflow_desc;
733 int bbh_orig, bby_orig, y;
735 if (encoding < 0)
736 continue;
738 /* set bits offset in encode map*/
739 if (pf->offset[encoding-pf->firstchar] != -1) {
740 print_error("duplicate encoding for character %d (0x%02x), ignoring duplicate\n",
741 encoding, encoding);
742 continue;
744 pf->offset[encoding-pf->firstchar] = ofs;
745 pf->offrot[encoding-pf->firstchar] = ofr;
747 /* calc char width */
748 bdf_correct_bbx(&width, &bbx);
749 pf->width[encoding-pf->firstchar] = width;
751 ch_bitmap = pf->bits + ofs;
752 ch_words = BITMAP_WORDS(width);
753 memset(ch_bitmap, 0, BITMAP_BYTES(width) * pf->height); /* clear bitmap */
755 #define BM(row,col) (*(ch_bitmap + ((row)*ch_words) + (col)))
756 #define BITMAP_NIBBLES (BITMAP_BITSPERIMAGE/4)
758 bbh_orig = bbh;
759 bby_orig = bby;
761 overflow_asc = bby + bbh - pf->ascent;
762 if (overflow_asc > 0) {
763 pf->num_clipped_ascent++;
764 if (overflow_asc > pf->max_over_ascent) {
765 pf->max_over_ascent = overflow_asc;
767 bbh = MAX(bbh - overflow_asc, 0); /* Clipped -> decrease the height */
768 print_warning(VL_CLIP_CHAR, "character %d goes %d pixel(s)"
769 " beyond the font's ascent, it will be clipped\n",
770 encoding, overflow_asc);
772 overflow_desc = -bby - pf->descent;
773 if (overflow_desc > 0) {
774 pf->num_clipped_descent++;
775 if (overflow_desc > pf->max_over_descent) {
776 pf->max_over_descent = overflow_desc;
778 bby += overflow_desc;
779 bbh = MAX(bbh - overflow_desc, 0); /* Clipped -> decrease the height */
780 print_warning(VL_CLIP_CHAR, "character %d goes %d pixel(s)"
781 " beyond the font's descent, it will be clipped\n",
782 encoding, overflow_desc);
784 if (overflow_asc > 0 || overflow_desc > 0) {
785 pf->num_clipped++;
788 y = bby_orig + bbh_orig; /* 0-based y within the char */
790 /* read bitmaps */
791 for (i=0; ; ++i) {
792 int hexnibbles;
794 if (!bdf_getline(fp, buf, sizeof(buf))) {
795 print_error("EOF reading BITMAP data for character %d\n",
796 encoding);
797 return 0;
799 if (isprefix(buf, "ENDCHAR"))
800 break;
802 y--;
803 if ((y >= pf->ascent) || (y < -pf->descent)) {
804 /* We're beyond the area that Rockbox can render -> clip */
805 --i; /* This line doesn't count */
806 continue;
809 hexnibbles = strlen(buf);
810 for (k=0; k<ch_words; ++k) {
811 int ndx = k * BITMAP_NIBBLES;
812 int padnibbles = hexnibbles - ndx;
813 bitmap_t value;
815 if (padnibbles <= 0)
816 break;
817 if (padnibbles >= (int)BITMAP_NIBBLES)
818 padnibbles = 0;
820 value = bdf_hexval((unsigned char *)buf,
821 ndx, ndx+BITMAP_NIBBLES-1-padnibbles);
822 value <<= padnibbles * BITMAP_NIBBLES;
824 BM(pf->height - pf->descent - bby - bbh + i, k) |=
825 value >> bbx;
826 /* handle overflow into next image word */
827 if (bbx) {
828 BM(pf->height - pf->descent - bby - bbh + i, k+1) =
829 value << (BITMAP_BITSPERIMAGE - bbx);
834 ofs += BITMAP_WORDS(width) * pf->height;
835 ofr += pf->width[encoding-pf->firstchar] * ((pf->height+7)/8);
837 continue;
839 if (strequal(buf, "ENDFONT"))
840 break;
843 /* change unused width values to default char values */
844 for (i=0; i<pf->size; ++i) {
845 int defchar = pf->defaultchar - pf->firstchar;
847 if (pf->offset[i] == -1)
848 pf->width[i] = pf->width[defchar];
851 /* determine whether font doesn't require encode table */
852 #ifdef ROTATE
853 l = 0;
854 for (i=0; i<pf->size; ++i) {
855 if ((int)pf->offrot[i] != l) {
856 encodetable = 1;
857 break;
859 l += pf->maxwidth * ((pf->height + 7) / 8);
861 #else
862 l = 0;
863 for (i=0; i<pf->size; ++i) {
864 if (pf->offset[i] != l) {
865 encodetable = 1;
866 break;
868 l += BITMAP_WORDS(pf->width[i]) * pf->height;
870 #endif
871 if (!encodetable) {
872 free(pf->offset);
873 pf->offset = NULL;
876 /* determine whether font is fixed-width */
877 for (i=0; i<pf->size; ++i) {
878 if (pf->width[i] != pf->maxwidth) {
879 proportional = 1;
880 break;
883 if (!proportional) {
884 free(pf->width);
885 pf->width = NULL;
888 /* reallocate bits array to actual bits used */
889 if (ofs < pf->bits_size) {
890 pf->bits = realloc(pf->bits, ofs * sizeof(bitmap_t));
891 pf->bits_size = ofs;
894 #ifdef ROTATE
895 pf->bits_size = ofr; /* always update, rotated is smaller */
896 #endif
898 return 1;
901 /* read the next non-comment line, returns buf or NULL if EOF */
902 char *bdf_getline(FILE *fp, char *buf, int len)
904 int c;
905 char *b;
907 for (;;) {
908 b = buf;
909 while ((c = getc(fp)) != EOF) {
910 if (c == '\r')
911 continue;
912 if (c == '\n')
913 break;
914 if (b - buf >= (len - 1))
915 break;
916 *b++ = c;
918 *b = '\0';
919 if (c == EOF && b == buf)
920 return NULL;
921 if (b != buf && !isprefix(buf, "COMMENT"))
922 break;
924 return buf;
927 void bdf_correct_bbx(int *width, int *bbx) {
928 if (*bbx < 0) {
929 /* Rockbox can't render overlapping glyphs */
930 *width -= *bbx;
931 *bbx = 0;
935 int bdf_analyze_font(FILE *fp, struct font* pf) {
936 char buf[256];
937 int encoding;
938 int width, bbw, bbh, bbx, bby, overflow;
939 int read_enc = 0, read_width = 0, read_bbx = 0, read_endchar = 1;
940 int ignore_char = 0;
942 /* reset file pointer */
943 fseek(fp, 0L, SEEK_SET);
945 pf->maxwidth = 0;
946 pf->nchars = 0;
947 pf->max_over_ascent = pf->max_over_descent = 0;
949 for (;;) {
951 if (!bdf_getline(fp, buf, sizeof(buf))) {
952 print_error("EOF on file\n");
953 return 0;
955 if (isprefix(buf, "ENDFONT")) {
956 if (!read_endchar) {
957 print_error("No terminating ENDCHAR for character %d\n", encoding);
958 return 0;
960 break;
962 if (isprefix(buf, "STARTCHAR")) {
963 print_trace("Read STARTCHAR, nchars=%d, read_endchar=%d\n", pf->nchars, read_endchar);
964 if (!read_endchar) {
965 print_error("No terminating ENDCHAR for character %d\n", encoding);
966 return 0;
968 read_enc = read_width = read_bbx = read_endchar = 0;
969 continue;
971 if (isprefix(buf, "ENDCHAR")) {
972 if (!read_enc) {
973 print_error("ENCODING is not specified\n");
974 return 0;
976 ignore_char = (encoding < start_char || encoding > limit_char);
977 if (!ignore_char) {
978 if (!read_width || !read_bbx) {
979 print_error("WIDTH or BBX is not specified for character %d\n",
980 encoding);
982 bdf_correct_bbx(&width, &bbx);
983 if (width > pf->maxwidth) {
984 pf->maxwidth = width;
986 overflow = bby + bbh - pf->ascent;
987 if (overflow > pf->max_over_ascent) {
988 pf->max_over_ascent = overflow;
990 overflow = -bby - pf->descent;
991 if (overflow > pf->max_over_descent) {
992 pf->max_over_descent = overflow;
995 pf->nchars++;
996 read_endchar = 1;
997 continue;
999 if (isprefix(buf, "ENCODING ")) {
1000 if (sscanf(buf, "ENCODING %d", &encoding) != 1) {
1001 print_error("bad 'ENCODING': '%s'\n", buf);
1002 return 0;
1004 read_enc = 1;
1005 continue;
1007 if (isprefix(buf, "DWIDTH ")) {
1008 if (sscanf(buf, "DWIDTH %d", &width) != 1) {
1009 print_error("bad 'DWIDTH': '%s'\n", buf);
1010 return 0;
1012 /* use font boundingbox width if DWIDTH <= 0 */
1013 if (width < 0) {
1014 print_error("Negative char width: %d\n", width);
1015 return 0;
1017 read_width = 1;
1019 if (isprefix(buf, "BBX ")) {
1020 if (sscanf(buf, "BBX %d %d %d %d", &bbw, &bbh, &bbx, &bby) != 4) {
1021 print_error("bad 'BBX': '%s'\n", buf);
1022 return 0;
1024 read_bbx = 1;
1025 continue;
1028 return 1;
1031 int adjust_ascent(int ascent, int overflow, struct stretch *stretch) {
1032 int result;
1033 int px = stretch->value;
1034 if (stretch->percent) {
1035 px = ascent * px / 100;
1038 if (stretch->force) {
1039 result = ascent + px;
1041 else {
1042 result = ascent + MIN(overflow, px);
1044 result = MAX(result, 0);
1045 return result;
1049 /* return hex value of portion of buffer*/
1050 bitmap_t bdf_hexval(unsigned char *buf, int ndx1, int ndx2)
1052 bitmap_t val = 0;
1053 int i, c;
1055 for (i=ndx1; i<=ndx2; ++i) {
1056 c = buf[i];
1057 if (c >= '0' && c <= '9')
1058 c -= '0';
1059 else
1060 if (c >= 'A' && c <= 'F')
1061 c = c - 'A' + 10;
1062 else
1063 if (c >= 'a' && c <= 'f')
1064 c = c - 'a' + 10;
1065 else
1066 c = 0;
1067 val = (val << 4) | c;
1069 return val;
1073 * Take an bitmap_t bitmap and convert to Rockbox format.
1074 * Used for converting font glyphs for the time being.
1075 * Can use for standard X11 and Win32 images as well.
1076 * See format description in lcd-recorder.c
1078 * Doing it this way keeps fonts in standard formats,
1079 * as well as keeping Rockbox hw bitmap format.
1081 int rotleft(unsigned char *dst, /* output buffer */
1082 size_t dstlen, /* buffer size */
1083 bitmap_t *src, unsigned int width, unsigned int height)
1085 unsigned int i,j;
1086 unsigned int src_words; /* # words of input image */
1087 unsigned int dst_mask; /* bit mask for destination */
1088 bitmap_t src_mask; /* bit mask for source */
1090 /* calc words of input image*/
1091 src_words = BITMAP_WORDS(width) * height;
1093 if(((height + 7) / 8) * width > dstlen) {
1094 print_error("%s:%d %d x %d overflows %ld bytes buffer, needs %d\n",
1095 __FILE__, __LINE__, width, height, (unsigned long)dstlen,
1096 ((height + 7) / 8) * width );
1097 return 0;
1100 /* clear background*/
1101 memset(dst, 0, ((height + 7) / 8) * width);
1103 dst_mask = 1;
1105 for (i=0; i < src_words; i++) {
1107 /* calc src input bit*/
1108 src_mask = 1 << (sizeof (bitmap_t) * 8 - 1);
1110 /* for each input column...*/
1111 for(j=0; j < width; j++) {
1113 if (src_mask == 0) /* input word done? */
1115 src_mask = 1 << (sizeof (bitmap_t) * 8 - 1);
1116 i++; /* next input word */
1119 /* if set in input, set in rotated output */
1120 if (src[i] & src_mask)
1121 dst[j] |= dst_mask;
1123 src_mask >>= 1; /* next input bit */
1126 dst_mask <<= 1; /* next output bit (row) */
1127 if (dst_mask > (1 << 7)) /* output bit > 7? */
1129 dst_mask = 1;
1130 dst += width; /* next output byte row */
1133 return ((height + 7) / 8) * width; /* return result size in bytes */
1137 /* generate C source from in-core font*/
1138 int gen_c_source(struct font* pf, char *path)
1140 FILE *ofp;
1141 int i, ofr = 0;
1142 time_t t = time(0);
1143 #ifndef ROTATE
1144 int did_syncmsg = 0;
1145 bitmap_t *ofs = pf->bits;
1146 #endif
1147 char buf[256];
1148 char obuf[256];
1149 char hdr1[] = {
1150 "/* Generated by convbdf on %s. */\n"
1151 "#include \"font.h\"\n"
1152 "#ifdef HAVE_LCD_BITMAP\n"
1153 "\n"
1154 "/* Font information:\n"
1155 " name: %s\n"
1156 " facename: %s\n"
1157 " w x h: %dx%d\n"
1158 " size: %d\n"
1159 " ascent: %d\n"
1160 " descent: %d\n"
1161 " first char: %d (0x%02x)\n"
1162 " last char: %d (0x%02x)\n"
1163 " default char: %d (0x%02x)\n"
1164 " proportional: %s\n"
1165 " %s\n"
1166 "*/\n"
1167 "\n"
1168 "/* Font character bitmap data. */\n"
1169 "static const unsigned char _font_bits[] = {\n"
1172 ofp = fopen(path, "w");
1173 if (!ofp) {
1174 print_error("Can't create %s\n", path);
1175 return 1;
1178 strcpy(buf, ctime(&t));
1179 buf[strlen(buf)-1] = 0;
1181 fprintf(ofp, hdr1, buf,
1182 pf->name,
1183 pf->facename? pf->facename: "",
1184 pf->maxwidth, pf->height,
1185 pf->size,
1186 pf->ascent, pf->descent,
1187 pf->firstchar, pf->firstchar,
1188 pf->firstchar+pf->size-1, pf->firstchar+pf->size-1,
1189 pf->defaultchar, pf->defaultchar,
1190 pf->width? "yes": "no",
1191 pf->copyright? pf->copyright: "");
1193 /* generate bitmaps*/
1194 for (i=0; i<pf->size; ++i) {
1195 int x;
1196 int bitcount = 0;
1197 int width = pf->width ? pf->width[i] : pf->maxwidth;
1198 int height = pf->height;
1199 bitmap_t *bits;
1200 bitmap_t bitvalue=0;
1202 /* Skip missing glyphs */
1203 if (pf->offset && (pf->offset[i] == -1))
1204 continue;
1206 bits = pf->bits + (pf->offset? (int)pf->offset[i]: (pf->height * i));
1208 fprintf(ofp, "\n/* Character %d (0x%02x):\n width %d",
1209 i+pf->firstchar, i+pf->firstchar, width);
1211 if (gen_map) {
1212 fprintf(ofp, "\n +");
1213 for (x=0; x<width; ++x) fprintf(ofp, "-");
1214 fprintf(ofp, "+\n");
1216 x = 0;
1217 while (height > 0) {
1218 if (x == 0) fprintf(ofp, " |");
1220 if (bitcount <= 0) {
1221 bitcount = BITMAP_BITSPERIMAGE;
1222 bitvalue = *bits++;
1225 fprintf(ofp, BITMAP_TESTBIT(bitvalue)? "*": " ");
1227 bitvalue = BITMAP_SHIFTBIT(bitvalue);
1228 --bitcount;
1229 if (++x == width) {
1230 fprintf(ofp, "|\n");
1231 --height;
1232 x = 0;
1233 bitcount = 0;
1236 fprintf(ofp, " +");
1237 for (x=0; x<width; ++x)
1238 fprintf(ofp, "-");
1239 fprintf(ofp, "+ */\n");
1241 else
1242 fprintf(ofp, " */\n");
1244 bits = pf->bits + (pf->offset? (int)pf->offset[i]: (pf->height * i));
1245 #ifdef ROTATE /* pre-rotated into Rockbox bitmap format */
1247 unsigned char bytemap[512];
1248 int y8, ix=0;
1250 int size = rotleft(bytemap, sizeof(bytemap), bits, width,
1251 pf->height);
1252 for (y8=0; y8<pf->height; y8+=8) /* column rows */
1254 for (x=0; x<width; x++) {
1255 fprintf(ofp, "0x%02x, ", bytemap[ix]);
1256 ix++;
1258 fprintf(ofp, "\n");
1261 /* update offrot since bits are now in sorted order */
1262 pf->offrot[i] = ofr;
1263 ofr += size;
1266 #else
1267 for (x=BITMAP_WORDS(width)*pf->height; x>0; --x) {
1268 fprintf(ofp, "0x%04x,\n", *bits);
1269 if (!did_syncmsg && *bits++ != *ofs++) {
1270 print_warning(VL_MISC, "found encoding values in non-sorted order (not an error).\n");
1271 did_syncmsg = 1;
1274 #endif
1276 fprintf(ofp, "};\n\n");
1278 if (pf->offset) {
1279 /* output offset table*/
1280 fprintf(ofp, "/* Character->glyph mapping. */\n"
1281 "static const unsigned short _sysfont_offset[] = {\n");
1283 for (i=0; i<pf->size; ++i) {
1284 if (pf->offset[i] == -1) {
1285 pf->offset[i] = pf->offset[pf->defaultchar - pf->firstchar];
1286 pf->offrot[i] = pf->offrot[pf->defaultchar - pf->firstchar];
1288 fprintf(ofp, " %d,\t/* (0x%02x) */\n",
1289 #ifdef ROTATE
1290 pf->offrot[i], i+pf->firstchar);
1291 #else
1292 pf->offset[i], i+pf->firstchar);
1293 #endif
1295 fprintf(ofp, "};\n\n");
1298 /* output width table for proportional fonts*/
1299 if (pf->width) {
1300 fprintf(ofp, "/* Character width data. */\n"
1301 "static const unsigned char _sysfont_width[] = {\n");
1303 for (i=0; i<pf->size; ++i)
1304 fprintf(ofp, " %d,\t/* (0x%02x) */\n",
1305 pf->width[i], i+pf->firstchar);
1306 fprintf(ofp, "};\n\n");
1309 /* output struct font struct*/
1310 if (pf->offset)
1311 sprintf(obuf, "_sysfont_offset,");
1312 else
1313 sprintf(obuf, "0, /* no encode table */");
1315 if (pf->width)
1316 sprintf(buf, "_sysfont_width, /* width */");
1317 else
1318 sprintf(buf, "0, /* fixed width */");
1320 fprintf(ofp, "/* Exported structure definition. */\n"
1321 "const struct font sysfont = {\n"
1322 " %d, /* maxwidth */\n"
1323 " %d, /* height */\n"
1324 " %d, /* ascent */\n"
1325 " %d, /* firstchar */\n"
1326 " %d, /* size */\n"
1327 " _font_bits, /* bits */\n"
1328 " %s /* offset */\n"
1329 " %s\n"
1330 " %d, /* defaultchar */\n"
1331 " %d /* bits_size */\n"
1332 "};\n"
1333 "#endif /* HAVE_LCD_BITMAP */\n",
1334 pf->maxwidth, pf->height,
1335 pf->ascent,
1336 pf->firstchar,
1337 pf->size,
1338 obuf,
1339 buf,
1340 pf->defaultchar,
1341 pf->bits_size);
1343 return 0;
1346 /* generate C header from in-core font*/
1347 int gen_h_header(struct font* pf, char *path)
1349 FILE *ofp;
1350 time_t t = time(0);
1351 char buf[256];
1352 char *hdr1 =
1353 "/* Generated by convbdf on %s. */\n"
1354 "#ifdef HAVE_LCD_BITMAP\n"
1355 "\n"
1356 "/* Font information*/\n"
1357 "#define SYSFONT_NAME %s\n"
1358 "#define SYSFONT_FACENAME %s\n"
1359 "#define SYSFONT_WIDTH %d\n"
1360 "#define SYSFONT_HEIGHT %d\n"
1361 "#define SYSFONT_SIZE %d\n"
1362 "#define SYSFONT_ASCENT %d\n";
1363 char *hdr2 =
1364 "#define SYSFONT_DESCENT %d\n"
1365 "#define SYSFONT_FIRST_CHAR %d\n"
1366 "#define SYSFONT_LAST_CHAR %d\n"
1367 "#define SYSFONT_DEFAULT_CHAR %d\n"
1368 "#define SYSFONT_PROPORTIONAL %d\n"
1369 "#define SYSFONT_COPYRIGHT %s\n"
1370 "#define SYSFONT_BITS_SIZE %d\n"
1371 "\n"
1372 "#endif\n";
1374 ofp = fopen(path, "w");
1375 if (!ofp) {
1376 print_error("Can't create %s\n", path);
1377 return 1;
1380 strcpy(buf, ctime(&t));
1381 buf[strlen(buf)-1] = 0;
1383 fprintf(ofp, hdr1, buf,
1384 pf->name,
1385 pf->facename? pf->facename: "",
1386 pf->maxwidth,
1387 pf->height,
1388 pf->size,
1389 pf->ascent);
1391 fprintf(ofp, hdr2,
1392 pf->descent,
1393 pf->firstchar,
1394 pf->firstchar+pf->size-1,
1395 pf->defaultchar,
1396 pf->width? 1: 0,
1397 pf->copyright? pf->copyright: "",
1398 pf->bits_size);
1400 return 0;
1403 static int writebyte(FILE *fp, unsigned char c)
1405 return putc(c, fp) != EOF;
1408 static int writeshort(FILE *fp, unsigned short s)
1410 putc(s, fp);
1411 return putc(s>>8, fp) != EOF;
1414 static int writeint(FILE *fp, unsigned int l)
1416 putc(l, fp);
1417 putc(l>>8, fp);
1418 putc(l>>16, fp);
1419 return putc(l>>24, fp) != EOF;
1422 static int writestr(FILE *fp, char *str, int count)
1424 return (int)fwrite(str, 1, count, fp) == count;
1427 #ifndef ROTATE
1428 static int writestrpad(FILE *fp, char *str, int totlen)
1430 int ret;
1432 while (str && *str && totlen > 0) {
1433 if (*str) {
1434 ret = putc(*str++, fp);
1435 --totlen;
1438 while (--totlen >= 0)
1439 ret = putc(' ', fp);
1440 return ret;
1442 #endif
1444 /* generate .fnt format file from in-core font*/
1445 int gen_fnt_file(struct font* pf, char *path)
1447 FILE *ofp;
1448 int i;
1449 #ifdef ROTATE
1450 int ofr = 0;
1451 #endif
1453 ofp = fopen(path, "wb");
1454 if (!ofp) {
1455 print_error("Can't create %s\n", path);
1456 return 1;
1459 /* write magic and version #*/
1460 writestr(ofp, VERSION, 4);
1461 #ifndef ROTATE
1462 /* internal font name*/
1463 writestrpad(ofp, pf->name, 64);
1465 /* copyright*/
1466 writestrpad(ofp, pf->copyright, 256);
1467 #endif
1468 /* font info*/
1469 writeshort(ofp, pf->maxwidth);
1470 writeshort(ofp, pf->height);
1471 writeshort(ofp, pf->ascent);
1472 writeshort(ofp, 0);
1473 writeint(ofp, pf->firstchar);
1474 writeint(ofp, pf->defaultchar);
1475 writeint(ofp, pf->size);
1477 /* variable font data sizes*/
1478 writeint(ofp, pf->bits_size); /* # words of bitmap_t*/
1479 writeint(ofp, pf->offset? pf->size: 0); /* # ints of offset*/
1480 writeint(ofp, pf->width? pf->size: 0); /* # bytes of width*/
1481 /* variable font data*/
1482 #ifdef ROTATE
1483 for (i=0; i<pf->size; ++i)
1485 bitmap_t* bits;
1486 int width = pf->width ? pf->width[i] : pf->maxwidth;
1487 int size;
1488 unsigned char bytemap[512];
1490 /* Skip missing glyphs */
1491 if (pf->offset && (pf->offset[i] == -1))
1492 continue;
1494 bits = pf->bits + (pf->offset? (int)pf->offset[i]: (pf->height * i));
1496 size = rotleft(bytemap, sizeof(bytemap), bits, width, pf->height);
1497 writestr(ofp, (char *)bytemap, size);
1499 /* update offrot since bits are now in sorted order */
1500 pf->offrot[i] = ofr;
1501 ofr += size;
1504 if ( pf->bits_size < 0xFFDB )
1506 /* bitmap offset is small enough, use unsigned short for offset */
1507 if (ftell(ofp) & 1)
1508 writebyte(ofp, 0); /* pad to 16-bit boundary*/
1510 else
1512 /* bitmap offset is large then 64K, use unsigned int for offset */
1513 while (ftell(ofp) & 3)
1514 writebyte(ofp, 0); /* pad to 32-bit boundary*/
1517 if (pf->offset)
1519 for (i=0; i<pf->size; ++i)
1521 if (pf->offset[i] == -1) {
1522 pf->offrot[i] = pf->offrot[pf->defaultchar - pf->firstchar];
1524 if ( pf->bits_size < 0xFFDB )
1525 writeshort(ofp, pf->offrot[i]);
1526 else
1527 writeint(ofp, pf->offrot[i]);
1531 if (pf->width)
1532 for (i=0; i<pf->size; ++i)
1533 writebyte(ofp, pf->width[i]);
1534 #else
1535 for (i=0; i<pf->bits_size; ++i)
1536 writeshort(ofp, pf->bits[i]);
1537 if (ftell(ofp) & 2)
1538 writeshort(ofp, 0); /* pad to 32-bit boundary*/
1540 if (pf->offset)
1541 for (i=0; i<pf->size; ++i) {
1542 if (pf->offset[i] == (unsigned int)-1) {
1543 pf->offset[i] = pf->offset[pf->defaultchar - pf->firstchar];
1545 writeint(ofp, pf->offset[i]);
1548 if (pf->width)
1549 for (i=0; i<pf->size; ++i)
1550 writebyte(ofp, pf->width[i]);
1551 #endif
1552 fclose(ofp);
1553 return 0;