Introduced new options for convbdf that specify how the ascent/descent is allowed...
[kugel-rb.git] / tools / convbdf.c
blob51ae5fb8063628c54ecc4872e126da30220e2c07
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;
665 /* read bdf font bitmaps, return 0 on error */
666 int bdf_read_bitmaps(FILE *fp, struct font* pf)
668 int ofs = 0;
669 int ofr = 0;
670 int i, k, encoding, width;
671 int bbw, bbh, bbx, bby;
672 int proportional = 0;
673 int encodetable = 0;
674 int l;
675 char buf[256];
676 bitmap_t *ch_bitmap;
677 int ch_words;
679 /* reset file pointer */
680 fseek(fp, 0L, SEEK_SET);
682 /* initially mark offsets as not used */
683 for (i=0; i<pf->size; ++i)
684 pf->offset[i] = -1;
686 for (;;) {
687 if (!bdf_getline(fp, buf, sizeof(buf))) {
688 print_error("EOF on file\n");
689 return 0;
691 if (isprefix(buf, "STARTCHAR")) {
692 encoding = width = -1;
693 bbw = pf->fbbw;
694 bbh = pf->fbbh;
695 bbx = pf->fbbx;
696 bby = pf->fbby;
697 continue;
699 if (isprefix(buf, "ENCODING ")) {
700 if (sscanf(buf, "ENCODING %d", &encoding) != 1) {
701 print_error("bad 'ENCODING'\n");
702 return 0;
704 if (encoding < start_char || encoding > limit_char)
705 encoding = -1;
706 continue;
708 if (isprefix(buf, "DWIDTH ")) {
709 if (sscanf(buf, "DWIDTH %d", &width) != 1) {
710 print_error("bad 'DWIDTH'\n");
711 return 0;
713 /* use font boundingbox width if DWIDTH <= 0 */
714 if (width <= 0)
715 width = pf->fbbw - pf->fbbx;
716 continue;
718 if (isprefix(buf, "BBX ")) {
719 if (sscanf(buf, "BBX %d %d %d %d", &bbw, &bbh, &bbx, &bby) != 4) {
720 print_error("bad 'BBX'\n");
721 return 0;
723 continue;
725 if (strequal(buf, "BITMAP") || strequal(buf, "BITMAP ")) {
726 int overflow_asc, overflow_desc;
727 int bbh_orig, bby_orig, y;
729 if (encoding < 0)
730 continue;
732 /* set bits offset in encode map*/
733 if (pf->offset[encoding-pf->firstchar] != -1) {
734 print_error("duplicate encoding for character %d (0x%02x), ignoring duplicate\n",
735 encoding, encoding);
736 continue;
738 pf->offset[encoding-pf->firstchar] = ofs;
739 pf->offrot[encoding-pf->firstchar] = ofr;
741 /* calc char width */
742 bdf_correct_bbx(&width, &bbx);
743 pf->width[encoding-pf->firstchar] = width;
745 ch_bitmap = pf->bits + ofs;
746 ch_words = BITMAP_WORDS(width);
747 memset(ch_bitmap, 0, BITMAP_BYTES(width) * pf->height); /* clear bitmap */
749 #define BM(row,col) (*(ch_bitmap + ((row)*ch_words) + (col)))
750 #define BITMAP_NIBBLES (BITMAP_BITSPERIMAGE/4)
752 bbh_orig = bbh;
753 bby_orig = bby;
755 overflow_asc = bby + bbh - pf->ascent;
756 if (overflow_asc > 0) {
757 pf->num_clipped_ascent++;
758 if (overflow_asc > pf->max_over_ascent) {
759 pf->max_over_ascent = overflow_asc;
761 bbh = MAX(bbh - overflow_asc, 0); /* Clipped -> decrease the height */
762 print_warning(VL_CLIP_CHAR, "character %d goes %d pixel(s)"
763 " beyond the font's ascent, it will be clipped\n",
764 encoding, overflow_asc);
766 overflow_desc = -bby - pf->descent;
767 if (overflow_desc > 0) {
768 pf->num_clipped_descent++;
769 if (overflow_desc > pf->max_over_descent) {
770 pf->max_over_descent = overflow_desc;
772 bby += overflow_desc;
773 bbh = MAX(bbh - overflow_desc, 0); /* Clipped -> decrease the height */
774 print_warning(VL_CLIP_CHAR, "character %d goes %d pixel(s)"
775 " beyond the font's descent, it will be clipped\n",
776 encoding, overflow_desc);
778 if (overflow_asc > 0 || overflow_desc > 0) {
779 pf->num_clipped++;
782 y = bby_orig + bbh_orig; /* 0-based y within the char */
784 /* read bitmaps */
785 for (i=0; ; ++i) {
786 int hexnibbles;
788 if (!bdf_getline(fp, buf, sizeof(buf))) {
789 print_error("EOF reading BITMAP data for character %d\n",
790 encoding);
791 return 0;
793 if (isprefix(buf, "ENDCHAR"))
794 break;
796 y--;
797 if ((y >= pf->ascent) || (y < -pf->descent)) {
798 /* We're beyond the area that Rockbox can render -> clip */
799 --i; /* This line doesn't count */
800 continue;
803 hexnibbles = strlen(buf);
804 for (k=0; k<ch_words; ++k) {
805 int ndx = k * BITMAP_NIBBLES;
806 int padnibbles = hexnibbles - ndx;
807 bitmap_t value;
809 if (padnibbles <= 0)
810 break;
811 if (padnibbles >= (int)BITMAP_NIBBLES)
812 padnibbles = 0;
814 value = bdf_hexval((unsigned char *)buf,
815 ndx, ndx+BITMAP_NIBBLES-1-padnibbles);
816 value <<= padnibbles * BITMAP_NIBBLES;
818 BM(pf->height - pf->descent - bby - bbh + i, k) |=
819 value >> bbx;
820 /* handle overflow into next image word */
821 if (bbx) {
822 BM(pf->height - pf->descent - bby - bbh + i, k+1) =
823 value << (BITMAP_BITSPERIMAGE - bbx);
828 ofs += BITMAP_WORDS(width) * pf->height;
829 ofr += pf->width[encoding-pf->firstchar] * ((pf->height+7)/8);
831 continue;
833 if (strequal(buf, "ENDFONT"))
834 break;
837 /* change unused width values to default char values */
838 for (i=0; i<pf->size; ++i) {
839 int defchar = pf->defaultchar - pf->firstchar;
841 if (pf->offset[i] == -1)
842 pf->width[i] = pf->width[defchar];
845 /* determine whether font doesn't require encode table */
846 #ifdef ROTATE
847 l = 0;
848 for (i=0; i<pf->size; ++i) {
849 if ((int)pf->offrot[i] != l) {
850 encodetable = 1;
851 break;
853 l += pf->maxwidth * ((pf->height + 7) / 8);
855 #else
856 l = 0;
857 for (i=0; i<pf->size; ++i) {
858 if (pf->offset[i] != l) {
859 encodetable = 1;
860 break;
862 l += BITMAP_WORDS(pf->width[i]) * pf->height;
864 #endif
865 if (!encodetable) {
866 free(pf->offset);
867 pf->offset = NULL;
870 /* determine whether font is fixed-width */
871 for (i=0; i<pf->size; ++i) {
872 if (pf->width[i] != pf->maxwidth) {
873 proportional = 1;
874 break;
877 if (!proportional) {
878 free(pf->width);
879 pf->width = NULL;
882 /* reallocate bits array to actual bits used */
883 if (ofs < pf->bits_size) {
884 pf->bits = realloc(pf->bits, ofs * sizeof(bitmap_t));
885 pf->bits_size = ofs;
888 #ifdef ROTATE
889 pf->bits_size = ofr; /* always update, rotated is smaller */
890 #endif
892 return 1;
895 /* read the next non-comment line, returns buf or NULL if EOF */
896 char *bdf_getline(FILE *fp, char *buf, int len)
898 int c;
899 char *b;
901 for (;;) {
902 b = buf;
903 while ((c = getc(fp)) != EOF) {
904 if (c == '\r')
905 continue;
906 if (c == '\n')
907 break;
908 if (b - buf >= (len - 1))
909 break;
910 *b++ = c;
912 *b = '\0';
913 if (c == EOF && b == buf)
914 return NULL;
915 if (b != buf && !isprefix(buf, "COMMENT"))
916 break;
918 return buf;
921 void bdf_correct_bbx(int *width, int *bbx) {
922 if (*bbx < 0) {
923 /* Rockbox can't render overlapping glyphs */
924 *width -= *bbx;
925 *bbx = 0;
929 int bdf_analyze_font(FILE *fp, struct font* pf) {
930 char buf[256];
931 int encoding;
932 int width, bbw, bbh, bbx, bby, overflow;
933 int read_enc = 0, read_width = 0, read_bbx = 0, read_endchar = 1;
934 int ignore_char = 0;
936 /* reset file pointer */
937 fseek(fp, 0L, SEEK_SET);
939 pf->maxwidth = 0;
940 pf->nchars = 0;
941 pf->max_over_ascent = pf->max_over_descent = 0;
943 for (;;) {
945 if (!bdf_getline(fp, buf, sizeof(buf))) {
946 print_error("EOF on file\n");
947 return 0;
949 if (isprefix(buf, "ENDFONT")) {
950 if (!read_endchar) {
951 print_error("No terminating ENDCHAR for character %d\n", encoding);
952 return 0;
954 break;
956 if (isprefix(buf, "STARTCHAR")) {
957 print_trace("Read STARTCHAR, nchars=%d, read_endchar=%d\n", pf->nchars, read_endchar);
958 if (!read_endchar) {
959 print_error("No terminating ENDCHAR for character %d\n", encoding);
960 return 0;
962 read_enc = read_width = read_bbx = read_endchar = 0;
963 continue;
965 if (isprefix(buf, "ENDCHAR")) {
966 if (!read_enc) {
967 print_error("ENCODING is not specified\n");
968 return 0;
970 ignore_char = (encoding < start_char || encoding > limit_char);
971 if (!ignore_char) {
972 if (!read_width || !read_bbx) {
973 print_error("WIDTH or BBX is not specified for character %d\n",
974 encoding);
976 bdf_correct_bbx(&width, &bbx);
977 if (width > pf->maxwidth) {
978 pf->maxwidth = width;
980 overflow = bby + bbh - pf->ascent;
981 if (overflow > pf->max_over_ascent) {
982 pf->max_over_ascent = overflow;
984 overflow = -bby - pf->descent;
985 if (overflow > pf->max_over_descent) {
986 pf->max_over_descent = overflow;
989 pf->nchars++;
990 read_endchar = 1;
991 continue;
993 if (isprefix(buf, "ENCODING ")) {
994 if (sscanf(buf, "ENCODING %d", &encoding) != 1) {
995 print_error("bad 'ENCODING': '%s'\n", buf);
996 return 0;
998 read_enc = 1;
999 continue;
1001 if (isprefix(buf, "DWIDTH ")) {
1002 if (sscanf(buf, "DWIDTH %d", &width) != 1) {
1003 print_error("bad 'DWIDTH': '%s'\n", buf);
1004 return 0;
1006 /* use font boundingbox width if DWIDTH <= 0 */
1007 if (width < 0) {
1008 print_error("Negative char width: %d\n", width);
1009 return 0;
1011 read_width = 1;
1013 if (isprefix(buf, "BBX ")) {
1014 if (sscanf(buf, "BBX %d %d %d %d", &bbw, &bbh, &bbx, &bby) != 4) {
1015 print_error("bad 'BBX': '%s'\n", buf);
1016 return 0;
1018 read_bbx = 1;
1019 continue;
1022 return 1;
1025 int adjust_ascent(int ascent, int overflow, struct stretch *stretch) {
1026 int result;
1027 int px = stretch->value;
1028 if (stretch->percent) {
1029 px = ascent * px / 100;
1032 if (stretch->force) {
1033 result = ascent + px;
1035 else {
1036 result = ascent + MIN(overflow, px);
1038 result = MAX(result, 0);
1039 return result;
1043 /* return hex value of portion of buffer*/
1044 bitmap_t bdf_hexval(unsigned char *buf, int ndx1, int ndx2)
1046 bitmap_t val = 0;
1047 int i, c;
1049 for (i=ndx1; i<=ndx2; ++i) {
1050 c = buf[i];
1051 if (c >= '0' && c <= '9')
1052 c -= '0';
1053 else
1054 if (c >= 'A' && c <= 'F')
1055 c = c - 'A' + 10;
1056 else
1057 if (c >= 'a' && c <= 'f')
1058 c = c - 'a' + 10;
1059 else
1060 c = 0;
1061 val = (val << 4) | c;
1063 return val;
1067 * Take an bitmap_t bitmap and convert to Rockbox format.
1068 * Used for converting font glyphs for the time being.
1069 * Can use for standard X11 and Win32 images as well.
1070 * See format description in lcd-recorder.c
1072 * Doing it this way keeps fonts in standard formats,
1073 * as well as keeping Rockbox hw bitmap format.
1075 int rotleft(unsigned char *dst, /* output buffer */
1076 size_t dstlen, /* buffer size */
1077 bitmap_t *src, unsigned int width, unsigned int height)
1079 unsigned int i,j;
1080 unsigned int src_words; /* # words of input image */
1081 unsigned int dst_mask; /* bit mask for destination */
1082 bitmap_t src_mask; /* bit mask for source */
1084 /* calc words of input image*/
1085 src_words = BITMAP_WORDS(width) * height;
1087 if(((height + 7) / 8) * width > dstlen) {
1088 print_error("%s:%d %d x %d overflows %ld bytes buffer, needs %d\n",
1089 __FILE__, __LINE__, width, height, (unsigned long)dstlen,
1090 ((height + 7) / 8) * width );
1091 return 0;
1094 /* clear background*/
1095 memset(dst, 0, ((height + 7) / 8) * width);
1097 dst_mask = 1;
1099 for (i=0; i < src_words; i++) {
1101 /* calc src input bit*/
1102 src_mask = 1 << (sizeof (bitmap_t) * 8 - 1);
1104 /* for each input column...*/
1105 for(j=0; j < width; j++) {
1107 if (src_mask == 0) /* input word done? */
1109 src_mask = 1 << (sizeof (bitmap_t) * 8 - 1);
1110 i++; /* next input word */
1113 /* if set in input, set in rotated output */
1114 if (src[i] & src_mask)
1115 dst[j] |= dst_mask;
1117 src_mask >>= 1; /* next input bit */
1120 dst_mask <<= 1; /* next output bit (row) */
1121 if (dst_mask > (1 << 7)) /* output bit > 7? */
1123 dst_mask = 1;
1124 dst += width; /* next output byte row */
1127 return ((height + 7) / 8) * width; /* return result size in bytes */
1131 /* generate C source from in-core font*/
1132 int gen_c_source(struct font* pf, char *path)
1134 FILE *ofp;
1135 int i, ofr = 0;
1136 time_t t = time(0);
1137 #ifndef ROTATE
1138 int did_syncmsg = 0;
1139 bitmap_t *ofs = pf->bits;
1140 #endif
1141 char buf[256];
1142 char obuf[256];
1143 char hdr1[] = {
1144 "/* Generated by convbdf on %s. */\n"
1145 "#include \"font.h\"\n"
1146 "#ifdef HAVE_LCD_BITMAP\n"
1147 "\n"
1148 "/* Font information:\n"
1149 " name: %s\n"
1150 " facename: %s\n"
1151 " w x h: %dx%d\n"
1152 " size: %d\n"
1153 " ascent: %d\n"
1154 " descent: %d\n"
1155 " first char: %d (0x%02x)\n"
1156 " last char: %d (0x%02x)\n"
1157 " default char: %d (0x%02x)\n"
1158 " proportional: %s\n"
1159 " %s\n"
1160 "*/\n"
1161 "\n"
1162 "/* Font character bitmap data. */\n"
1163 "static const unsigned char _font_bits[] = {\n"
1166 ofp = fopen(path, "w");
1167 if (!ofp) {
1168 print_error("Can't create %s\n", path);
1169 return 1;
1172 strcpy(buf, ctime(&t));
1173 buf[strlen(buf)-1] = 0;
1175 fprintf(ofp, hdr1, buf,
1176 pf->name,
1177 pf->facename? pf->facename: "",
1178 pf->maxwidth, pf->height,
1179 pf->size,
1180 pf->ascent, pf->descent,
1181 pf->firstchar, pf->firstchar,
1182 pf->firstchar+pf->size-1, pf->firstchar+pf->size-1,
1183 pf->defaultchar, pf->defaultchar,
1184 pf->width? "yes": "no",
1185 pf->copyright? pf->copyright: "");
1187 /* generate bitmaps*/
1188 for (i=0; i<pf->size; ++i) {
1189 int x;
1190 int bitcount = 0;
1191 int width = pf->width ? pf->width[i] : pf->maxwidth;
1192 int height = pf->height;
1193 bitmap_t *bits;
1194 bitmap_t bitvalue=0;
1196 /* Skip missing glyphs */
1197 if (pf->offset && (pf->offset[i] == -1))
1198 continue;
1200 bits = pf->bits + (pf->offset? (int)pf->offset[i]: (pf->height * i));
1202 fprintf(ofp, "\n/* Character %d (0x%02x):\n width %d",
1203 i+pf->firstchar, i+pf->firstchar, width);
1205 if (gen_map) {
1206 fprintf(ofp, "\n +");
1207 for (x=0; x<width; ++x) fprintf(ofp, "-");
1208 fprintf(ofp, "+\n");
1210 x = 0;
1211 while (height > 0) {
1212 if (x == 0) fprintf(ofp, " |");
1214 if (bitcount <= 0) {
1215 bitcount = BITMAP_BITSPERIMAGE;
1216 bitvalue = *bits++;
1219 fprintf(ofp, BITMAP_TESTBIT(bitvalue)? "*": " ");
1221 bitvalue = BITMAP_SHIFTBIT(bitvalue);
1222 --bitcount;
1223 if (++x == width) {
1224 fprintf(ofp, "|\n");
1225 --height;
1226 x = 0;
1227 bitcount = 0;
1230 fprintf(ofp, " +");
1231 for (x=0; x<width; ++x)
1232 fprintf(ofp, "-");
1233 fprintf(ofp, "+ */\n");
1235 else
1236 fprintf(ofp, " */\n");
1238 bits = pf->bits + (pf->offset? (int)pf->offset[i]: (pf->height * i));
1239 #ifdef ROTATE /* pre-rotated into Rockbox bitmap format */
1241 unsigned char bytemap[512];
1242 int y8, ix=0;
1244 int size = rotleft(bytemap, sizeof(bytemap), bits, width,
1245 pf->height);
1246 for (y8=0; y8<pf->height; y8+=8) /* column rows */
1248 for (x=0; x<width; x++) {
1249 fprintf(ofp, "0x%02x, ", bytemap[ix]);
1250 ix++;
1252 fprintf(ofp, "\n");
1255 /* update offrot since bits are now in sorted order */
1256 pf->offrot[i] = ofr;
1257 ofr += size;
1260 #else
1261 for (x=BITMAP_WORDS(width)*pf->height; x>0; --x) {
1262 fprintf(ofp, "0x%04x,\n", *bits);
1263 if (!did_syncmsg && *bits++ != *ofs++) {
1264 print_warning(VL_MISC, "found encoding values in non-sorted order (not an error).\n");
1265 did_syncmsg = 1;
1268 #endif
1270 fprintf(ofp, "};\n\n");
1272 if (pf->offset) {
1273 /* output offset table*/
1274 fprintf(ofp, "/* Character->glyph mapping. */\n"
1275 "static const unsigned short _sysfont_offset[] = {\n");
1277 for (i=0; i<pf->size; ++i) {
1278 if (pf->offset[i] == -1) {
1279 pf->offset[i] = pf->offset[pf->defaultchar - pf->firstchar];
1280 pf->offrot[i] = pf->offrot[pf->defaultchar - pf->firstchar];
1282 fprintf(ofp, " %d,\t/* (0x%02x) */\n",
1283 #ifdef ROTATE
1284 pf->offrot[i], i+pf->firstchar);
1285 #else
1286 pf->offset[i], i+pf->firstchar);
1287 #endif
1289 fprintf(ofp, "};\n\n");
1292 /* output width table for proportional fonts*/
1293 if (pf->width) {
1294 fprintf(ofp, "/* Character width data. */\n"
1295 "static const unsigned char _sysfont_width[] = {\n");
1297 for (i=0; i<pf->size; ++i)
1298 fprintf(ofp, " %d,\t/* (0x%02x) */\n",
1299 pf->width[i], i+pf->firstchar);
1300 fprintf(ofp, "};\n\n");
1303 /* output struct font struct*/
1304 if (pf->offset)
1305 sprintf(obuf, "_sysfont_offset,");
1306 else
1307 sprintf(obuf, "0, /* no encode table */");
1309 if (pf->width)
1310 sprintf(buf, "_sysfont_width, /* width */");
1311 else
1312 sprintf(buf, "0, /* fixed width */");
1314 fprintf(ofp, "/* Exported structure definition. */\n"
1315 "const struct font sysfont = {\n"
1316 " %d, /* maxwidth */\n"
1317 " %d, /* height */\n"
1318 " %d, /* ascent */\n"
1319 " %d, /* firstchar */\n"
1320 " %d, /* size */\n"
1321 " _font_bits, /* bits */\n"
1322 " %s /* offset */\n"
1323 " %s\n"
1324 " %d, /* defaultchar */\n"
1325 " %d /* bits_size */\n"
1326 "};\n"
1327 "#endif /* HAVE_LCD_BITMAP */\n",
1328 pf->maxwidth, pf->height,
1329 pf->ascent,
1330 pf->firstchar,
1331 pf->size,
1332 obuf,
1333 buf,
1334 pf->defaultchar,
1335 pf->bits_size);
1337 return 0;
1340 /* generate C header from in-core font*/
1341 int gen_h_header(struct font* pf, char *path)
1343 FILE *ofp;
1344 time_t t = time(0);
1345 char buf[256];
1346 char *hdr1 =
1347 "/* Generated by convbdf on %s. */\n"
1348 "#ifdef HAVE_LCD_BITMAP\n"
1349 "\n"
1350 "/* Font information*/\n"
1351 "#define SYSFONT_NAME %s\n"
1352 "#define SYSFONT_FACENAME %s\n"
1353 "#define SYSFONT_WIDTH %d\n"
1354 "#define SYSFONT_HEIGHT %d\n"
1355 "#define SYSFONT_SIZE %d\n"
1356 "#define SYSFONT_ASCENT %d\n";
1357 char *hdr2 =
1358 "#define SYSFONT_DESCENT %d\n"
1359 "#define SYSFONT_FIRST_CHAR %d\n"
1360 "#define SYSFONT_LAST_CHAR %d\n"
1361 "#define SYSFONT_DEFAULT_CHAR %d\n"
1362 "#define SYSFONT_PROPORTIONAL %d\n"
1363 "#define SYSFONT_COPYRIGHT %s\n"
1364 "#define SYSFONT_BITS_SIZE %d\n"
1365 "\n"
1366 "#endif\n";
1368 ofp = fopen(path, "w");
1369 if (!ofp) {
1370 print_error("Can't create %s\n", path);
1371 return 1;
1374 strcpy(buf, ctime(&t));
1375 buf[strlen(buf)-1] = 0;
1377 fprintf(ofp, hdr1, buf,
1378 pf->name,
1379 pf->facename? pf->facename: "",
1380 pf->maxwidth,
1381 pf->height,
1382 pf->size,
1383 pf->ascent);
1385 fprintf(ofp, hdr2,
1386 pf->descent,
1387 pf->firstchar,
1388 pf->firstchar+pf->size-1,
1389 pf->defaultchar,
1390 pf->width? 1: 0,
1391 pf->copyright? pf->copyright: "",
1392 pf->bits_size);
1394 return 0;
1397 static int writebyte(FILE *fp, unsigned char c)
1399 return putc(c, fp) != EOF;
1402 static int writeshort(FILE *fp, unsigned short s)
1404 putc(s, fp);
1405 return putc(s>>8, fp) != EOF;
1408 static int writeint(FILE *fp, unsigned int l)
1410 putc(l, fp);
1411 putc(l>>8, fp);
1412 putc(l>>16, fp);
1413 return putc(l>>24, fp) != EOF;
1416 static int writestr(FILE *fp, char *str, int count)
1418 return (int)fwrite(str, 1, count, fp) == count;
1421 #ifndef ROTATE
1422 static int writestrpad(FILE *fp, char *str, int totlen)
1424 int ret;
1426 while (str && *str && totlen > 0) {
1427 if (*str) {
1428 ret = putc(*str++, fp);
1429 --totlen;
1432 while (--totlen >= 0)
1433 ret = putc(' ', fp);
1434 return ret;
1436 #endif
1438 /* generate .fnt format file from in-core font*/
1439 int gen_fnt_file(struct font* pf, char *path)
1441 FILE *ofp;
1442 int i;
1443 #ifdef ROTATE
1444 int ofr = 0;
1445 #endif
1447 ofp = fopen(path, "wb");
1448 if (!ofp) {
1449 print_error("Can't create %s\n", path);
1450 return 1;
1453 /* write magic and version #*/
1454 writestr(ofp, VERSION, 4);
1455 #ifndef ROTATE
1456 /* internal font name*/
1457 writestrpad(ofp, pf->name, 64);
1459 /* copyright*/
1460 writestrpad(ofp, pf->copyright, 256);
1461 #endif
1462 /* font info*/
1463 writeshort(ofp, pf->maxwidth);
1464 writeshort(ofp, pf->height);
1465 writeshort(ofp, pf->ascent);
1466 writeshort(ofp, 0);
1467 writeint(ofp, pf->firstchar);
1468 writeint(ofp, pf->defaultchar);
1469 writeint(ofp, pf->size);
1471 /* variable font data sizes*/
1472 writeint(ofp, pf->bits_size); /* # words of bitmap_t*/
1473 writeint(ofp, pf->offset? pf->size: 0); /* # ints of offset*/
1474 writeint(ofp, pf->width? pf->size: 0); /* # bytes of width*/
1475 /* variable font data*/
1476 #ifdef ROTATE
1477 for (i=0; i<pf->size; ++i)
1479 bitmap_t* bits;
1480 int width = pf->width ? pf->width[i] : pf->maxwidth;
1481 int size;
1482 unsigned char bytemap[512];
1484 /* Skip missing glyphs */
1485 if (pf->offset && (pf->offset[i] == -1))
1486 continue;
1488 bits = pf->bits + (pf->offset? (int)pf->offset[i]: (pf->height * i));
1490 size = rotleft(bytemap, sizeof(bytemap), bits, width, pf->height);
1491 writestr(ofp, (char *)bytemap, size);
1493 /* update offrot since bits are now in sorted order */
1494 pf->offrot[i] = ofr;
1495 ofr += size;
1498 if ( pf->bits_size < 0xFFDB )
1500 /* bitmap offset is small enough, use unsigned short for offset */
1501 if (ftell(ofp) & 1)
1502 writebyte(ofp, 0); /* pad to 16-bit boundary*/
1504 else
1506 /* bitmap offset is large then 64K, use unsigned int for offset */
1507 while (ftell(ofp) & 3)
1508 writebyte(ofp, 0); /* pad to 32-bit boundary*/
1511 if (pf->offset)
1513 for (i=0; i<pf->size; ++i)
1515 if (pf->offset[i] == -1) {
1516 pf->offrot[i] = pf->offrot[pf->defaultchar - pf->firstchar];
1518 if ( pf->bits_size < 0xFFDB )
1519 writeshort(ofp, pf->offrot[i]);
1520 else
1521 writeint(ofp, pf->offrot[i]);
1525 if (pf->width)
1526 for (i=0; i<pf->size; ++i)
1527 writebyte(ofp, pf->width[i]);
1528 #else
1529 for (i=0; i<pf->bits_size; ++i)
1530 writeshort(ofp, pf->bits[i]);
1531 if (ftell(ofp) & 2)
1532 writeshort(ofp, 0); /* pad to 32-bit boundary*/
1534 if (pf->offset)
1535 for (i=0; i<pf->size; ++i) {
1536 if (pf->offset[i] == (unsigned int)-1) {
1537 pf->offset[i] = pf->offset[pf->defaultchar - pf->firstchar];
1539 writeint(ofp, pf->offset[i]);
1542 if (pf->width)
1543 for (i=0; i<pf->size; ++i)
1544 writebyte(ofp, pf->width[i]);
1545 #endif
1546 fclose(ofp);
1547 return 0;