Merge branch 'master' of gitlab:wintermute/hackover2013-badge-firmware
[hackover2013-badge-firmware.git] / badge / ui / font.c
1 #include "font.h"
2 #include "sprite.h"
3
4 #ifdef __linux__
5 #include <stdio.h>
6 typedef FILE *FIL;
7 typedef uint8_t FRESULT;
8 typedef unsigned UINT;
9 enum { FR_OK = 0 };
10
11 void f_close(FIL *fd) { fclose(*fd); *fd = NULL; }
12 FRESULT f_lseek(FIL *fd, unsigned pos) { return fseek(*fd, pos, SEEK_SET); }
13 FRESULT f_read(FIL *fd, unsigned char *buffer, size_t buflen, UINT *bytes) {
14 *bytes = fread(buffer, 1, buflen, *fd);
15 return *bytes == 0;
16 }
17
18 #else
19 #include <drivers/fatfs/ff.h>
20 #endif
21
22 static FRESULT open_font_file(FIL *fd) {
23 #ifdef __linux__
24 *fd = fopen("../sprites/font.dat", "r");
25 return fd ? 0 : -1;
26 #else
27 return f_open(fd, "/font.dat", FA_OPEN_EXISTING | FA_READ);
28 #endif
29 }
30
31 static uint8_t badge_framebuffer_render_char_with_fd(badge_framebuffer *fb, int8_t pos_x, int8_t pos_y, char c, FIL *fd) {
32 UINT readbytes;
33 uint8_t buffer[BADGE_FONT_GLYPH_WIDTH];
34
35 if(c == 32) {
36 // intentionally left empty.
37 } else if(c >= 32 &&
38 FR_OK == f_lseek(fd, (c - 33) * BADGE_FONT_GLYPH_WIDTH) &&
39 FR_OK == f_read(fd, buffer, sizeof(buffer), &readbytes)) {
40 badge_sprite sp = { BADGE_FONT_GLYPH_WIDTH, BADGE_FONT_HEIGHT, buffer };
41 badge_framebuffer_blt(fb, pos_x, pos_y, &sp, 0);
42 } else {
43 return -1;
44 }
45
46 return 0;
47 }
48
49 uint8_t badge_framebuffer_render_char(badge_framebuffer *fb, int8_t pos_x, int8_t pos_y, char c) {
50 FIL fd;
51
52 if(FR_OK == open_font_file(&fd)) {
53 badge_framebuffer_render_char_with_fd(fb, pos_x, pos_y, c, &fd);
54 f_close(&fd);
55 return 0;
56 }
57
58 return -1;
59 }
60
61 uint8_t badge_framebuffer_render_text(badge_framebuffer *fb, int8_t pos_x, int8_t pos_y, char const *text) {
62 uint8_t count = 0;
63 FIL fd;
64
65 if(FR_OK == open_font_file(&fd)) {
66 while(*text) {
67 if(0 != badge_framebuffer_render_char_with_fd(fb, pos_x, pos_y, *text, &fd)) {
68 break;
69 }
70
71 ++count;
72 ++text;
73 pos_x += BADGE_FONT_WIDTH;
74 }
75
76 f_close(&fd);
77 }
78
79 return count;
80 }
81
82 static uint8_t badge_framebuffer_render_number_with_fd(badge_framebuffer *fb, int8_t *pos_x, int8_t pos_y, uint8_t number, FIL *fd) {
83 if(number >= 10) {
84 badge_framebuffer_render_number_with_fd(fb, pos_x, pos_y, number / 10, fd);
85 }
86
87 uint8_t err = badge_framebuffer_render_char_with_fd(fb, *pos_x, pos_y, '0' + number % 10, fd);
88
89 if(err != 0) return err;
90
91 *pos_x += BADGE_FONT_WIDTH;
92 return 0;
93 }
94
95 uint8_t badge_framebuffer_render_number(badge_framebuffer *fb, int8_t pos_x, int8_t pos_y, uint8_t number) {
96 FIL fd;
97
98 if(FR_OK == open_font_file(&fd)) {
99 uint8_t err = badge_framebuffer_render_number_with_fd(fb, &pos_x, pos_y, number, &fd);
100
101 if(err != 0) {
102 return err;
103 }
104 }
105
106 return 0;
107 }
This page took 0.043531 seconds and 5 git commands to generate.