term: enable switching signals using the second argument of term_exec()
[fbpad.git] / font.c
bloba931a223066ff2ff4fe950763571e0008cc88958
1 #include <fcntl.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <string.h>
6 #include "fbpad.h"
8 struct font {
9 int rows, cols; /* glyph bitmap rows and columns */
10 int n; /* number of font glyphs */
11 int *glyphs; /* glyph unicode character codes */
12 char *data; /* glyph bitmaps */
16 * This tinyfont header is followed by:
18 * glyphs[n] unicode character codes (int)
19 * bitmaps[n] character bitmaps (char[rows * cols])
21 struct tinyfont {
22 char sig[8]; /* tinyfont signature; "tinyfont" */
23 int ver; /* version; 0 */
24 int n; /* number of glyphs */
25 int rows, cols; /* glyph dimensions */
28 static void *xread(int fd, int len)
30 void *buf = malloc(len);
31 if (buf && read(fd, buf, len) == len)
32 return buf;
33 free(buf);
34 return NULL;
37 struct font *font_open(char *path)
39 struct font *font;
40 struct tinyfont head;
41 int fd = open(path, O_RDONLY);
42 if (fd < 0 || read(fd, &head, sizeof(head)) != sizeof(head)) {
43 close(fd);
44 return NULL;
46 font = malloc(sizeof(*font));
47 font->n = head.n;
48 font->rows = head.rows;
49 font->cols = head.cols;
50 font->glyphs = xread(fd, font->n * sizeof(int));
51 font->data = xread(fd, font->n * font->rows * font->cols);
52 close(fd);
53 if (!font->glyphs || !font->data) {
54 font_free(font);
55 return NULL;
57 return font;
60 static int find_glyph(struct font *font, int c)
62 int l = 0;
63 int h = font->n;
64 while (l < h) {
65 int m = (l + h) / 2;
66 if (font->glyphs[m] == c)
67 return m;
68 if (c < font->glyphs[m])
69 h = m;
70 else
71 l = m + 1;
73 return -1;
76 int font_bitmap(struct font *font, void *dst, int c)
78 int i = find_glyph(font, c);
79 int len = font->rows * font->cols;
80 if (i < 0)
81 return 1;
82 memcpy(dst, font->data + i * len, len);
83 return 0;
86 void font_free(struct font *font)
88 if (font->data)
89 free(font->data);
90 if (font->glyphs)
91 free(font->glyphs);
92 free(font);
95 int font_rows(struct font *font)
97 return font->rows;
100 int font_cols(struct font *font)
102 return font->cols;