Shape text using Pango and HarfBuzz; gives us nice ligatures and exotic scripts.
[ccbs] / bigscreen / fonts.cpp
1 #include <cstdio>
2 #include <vector>
3 #include <stdexcept>
4 #include <map>
5 #include <string>
6 #include <harfbuzz/hb.h>
7 #include <harfbuzz/hb-ft.h>
8 #include <harfbuzz/hb-glib.h>
9 #include <harfbuzz/hb-icu.h>
10 #include <pango/pango-context.h>
11 #include <pango/pango-fontmap.h>
12 #include <pango/pangoft2.h>
13 #include "fonts.h"
14 #include "resolution.h"
15 #include "theme.h"
16
17 extern std::map<std::string, std::string> config;
18 std::map<std::string, FT_Face> faces;
19
20 std::vector<std::string> split(const std::string &str, char delim)
21 {
22         std::vector<std::string> ret;
23         std::string s;
24         for (unsigned i = 0; i < str.size(); ++i) {
25                 if (str[i] == delim) {
26                         ret.push_back(s);
27                         s.clear();
28                 } else {
29                         s.push_back(str[i]);
30                 }
31         }
32         if (!s.empty()) {
33                 ret.push_back(s);
34         }
35         return ret;
36 }
37
38 void init_freetype()
39 {
40         FT_Library library;
41         if (FT_Init_FreeType(&library))
42                 throw std::runtime_error("FreeType init failed.");
43
44         // Preload all fonts.
45         for (std::map<std::string, std::string>::const_iterator it = config.begin();
46              it != config.end();
47              ++it) {
48                 const std::string key = it->first;
49                 if (key.size() <= 5 || key.substr(key.size() - 5) != ".font") {
50                         continue;
51                 }
52
53                 std::vector<std::string> font_list = split(it->second, ';');
54                 for (unsigned i = 0; i < font_list.size(); ++i) {
55                         if (faces.count(font_list[i])) {
56                                 // Already preloaded.
57                                 continue;
58                         }
59
60                         FT_Face face;
61                         if (FT_New_Face(library, font_list[i].c_str(), 0, &face)) {
62                                 fprintf(stderr, "Warning: Couldn't open '%s', some glyphs might not be available\n", font_list[i].c_str());
63                         } else {
64                                 faces[font_list[i]] = face;
65                         }
66                 }
67         }
68 }
69
70 // this should really be done somehow else :-)
71 static unsigned screen_width, screen_height;
72 void set_screen_size(unsigned width, unsigned height)
73 {
74         screen_width = width;
75         screen_height = height;
76 }
77
78 void render_glyph(FT_GlyphSlot slot, int glyphx, int glyphy, unsigned char *buf, int r, int g, int b, bool use_lcd)
79 {
80         FT_Bitmap *bm = &(slot->bitmap);
81         for (unsigned y = 0; y < bm->rows; y++) {
82                 int xx;
83                 int dsty = glyphy - slot->bitmap_top + y;
84                 if (dsty < 0 || dsty > signed(screen_height-1)) continue;
85
86                 unsigned char *dst = buf + dsty * screen_width*4 + (glyphx + slot->bitmap_left)*4;
87                 unsigned char *src = bm->buffer + y * bm->pitch;
88                 if (use_lcd) {
89                         int width = (glyphx + slot->bitmap_left + bm->width/3 >= signed(screen_width)) ? ((screen_width-1) - glyphx - slot->bitmap_left) : bm->width/3;
90                         for (xx = 0; xx < width; xx++) {
91                                 *dst = (*dst * (256-src[2]) + b * src[2]) >> 8;
92                                 ++dst;
93                                 *dst = (*dst * (256-src[1]) + g * src[1]) >> 8;
94                                 ++dst;
95                                 *dst = (*dst * (256-src[0]) + r * src[0]) >> 8;
96                                 ++dst;
97                                 *dst++ = 0;
98
99                                 src += 3;
100                         }
101                 } else {
102                         int width = (glyphx + slot->bitmap_left + bm->width >= signed(screen_width)) ? ((screen_width-1) - glyphx - slot->bitmap_left) : bm->width;
103                         for (xx = 0; xx < width; xx++) {
104                                 *dst = (*dst * (256-*src) + b * *src) >> 8;
105                                 ++dst;
106                                 *dst = (*dst * (256-*src) + g * *src) >> 8;
107                                 ++dst;
108                                 *dst = (*dst * (256-*src) + r * *src) >> 8;
109                                 ++dst;
110                                 *dst++ = 0;
111                                 ++src;
112                         }
113                 }
114         }
115 }
116
117 unsigned my_draw_text(const widestring &str, unsigned char *buf, double size, const std::string &theme_element, int xpos, int ypos)
118 {
119         int start_xpos = xpos;
120
121         int r = atoi(get_theme_config(theme_element, "red").c_str());
122         int g = atoi(get_theme_config(theme_element, "green").c_str());
123         int b = atoi(get_theme_config(theme_element, "blue").c_str());
124         bool use_lcd = atoi(get_theme_config("screen", "lcd").c_str());
125
126         // Find font faces.
127         std::vector<FT_Face> fonts;
128         std::vector<std::string> font_list = split(get_theme_config(theme_element, "font"), ';');
129         for (unsigned i = 0; i < font_list.size(); ++i) {
130                 if (faces.count(font_list[i])) {
131                         fonts.push_back(faces[font_list[i]]);
132                 }
133         }
134         
135         for (std::vector<FT_Face>::const_iterator i = fonts.begin(); i != fonts.end(); ++i) {
136                 if (FT_Set_Char_Size(*i, 0, unsigned(size * 64.0), 96 * screen_width/LOGICAL_SCREEN_WIDTH, 96 * screen_height/LOGICAL_SCREEN_HEIGHT))
137                         throw std::runtime_error("Couldn't set font size");
138         }
139
140         // whoop :-P
141         xpos = xpos * screen_width / LOGICAL_SCREEN_WIDTH;
142         ypos = ypos * screen_height / LOGICAL_SCREEN_HEIGHT;
143
144         // Itemize the text into parts that will be shaped and rendered separately.
145         PangoContext *context = pango_context_new();
146         PangoFontMap *fontmap = pango_ft2_font_map_new();
147         pango_context_set_font_map(context, fontmap);
148         PangoAttrList *attrs = pango_attr_list_new();
149         std::string utf8str = str.to_utf8();
150         GList *items = pango_itemize(context, utf8str.data(), 0, utf8str.size(), attrs, NULL);
151         for (GList *item_it = items; item_it != NULL; item_it = item_it->next) {
152                 PangoItem *item = (PangoItem *)(item_it->data);
153                 PangoAnalysis *analysis = &item->analysis;
154
155                 // Try to shape and render it in each of the fonts in turn.
156                 for (std::vector<FT_Face>::const_iterator face_it = fonts.begin(); face_it != fonts.end(); ++face_it) {
157                         // The buffer seemingly needs to be created anew for each try.
158                         hb_buffer_t *hbuf = hb_buffer_create();
159                         hb_buffer_set_unicode_funcs(hbuf, hb_icu_get_unicode_funcs());
160                         hb_direction_t dir = PANGO_GRAVITY_IS_VERTICAL(analysis->gravity) ? HB_DIRECTION_TTB : HB_DIRECTION_LTR;
161                         if (analysis->level % 2)
162                                 dir = HB_DIRECTION_REVERSE(dir);
163                         if (PANGO_GRAVITY_IS_IMPROPER (analysis->gravity))
164                                 dir = HB_DIRECTION_REVERSE(dir);
165
166                         hb_buffer_set_direction(hbuf, dir);
167                         hb_buffer_set_script(hbuf, hb_glib_script_to_script((GUnicodeScript)analysis->script));
168                         hb_buffer_set_language(hbuf, hb_language_from_string(pango_language_to_string(analysis->language), -1));
169                         hb_buffer_add_utf8(hbuf, utf8str.data(), utf8str.size(), item->offset, item->length);
170
171                         // Font-specifics.
172                         FT_Face face = *face_it;
173                         hb_font_t *font = hb_ft_font_create(face, NULL);
174                         hb_shape(font, hbuf, NULL, 0);
175                         unsigned glyph_count;
176                         hb_glyph_info_t *glyph_info = hb_buffer_get_glyph_infos(hbuf, &glyph_count);
177                         hb_glyph_position_t *glyph_pos = hb_buffer_get_glyph_positions(hbuf, &glyph_count);
178
179                         bool found_all = true;
180                         for (unsigned i = 0; i < glyph_count; ++i) {
181                                 if (glyph_info[i].codepoint == 0) {
182                                         found_all = false;
183                                 }
184                                 break;
185                         }
186
187                         if (!found_all) {
188                                 std::string utf8itemstr(&utf8str[item->offset], &utf8str[item->offset + item->length]);
189                                 if (face_it + 1 == fonts.end()) {
190                                         std::fprintf(stderr, "Warning: Could not find any font to render item '%s', rendering in last font anyway\n", utf8itemstr.c_str());
191                                 } else {
192                                         hb_font_destroy(font);
193                                         hb_buffer_destroy(hbuf);
194                                         continue;
195                                 }
196                         }
197
198                         for (unsigned i = 0; i < glyph_count; ++i) {
199                                 if (use_lcd) {
200                                         if (FT_Load_Glyph(face, glyph_info[i].codepoint, FT_LOAD_RENDER | FT_LOAD_TARGET_LCD))
201                                                 throw std::runtime_error("Couldn't load glyph");
202                                 } else {
203                                         if (FT_Load_Glyph(face, glyph_info[i].codepoint, FT_LOAD_RENDER))
204                                                 throw std::runtime_error("Couldn't load glyph");
205                                 }
206
207                                 int glyphx = xpos + glyph_pos[i].x_offset / 64;
208                                 int glyphy = ypos - glyph_pos[i].y_offset / 64;
209
210                                 if (buf != NULL) {
211                                         render_glyph(face->glyph, glyphx, glyphy, buf, r, g, b, use_lcd);
212                                 }
213
214                                 xpos += glyph_pos[i].x_advance / 64;
215                                 ypos -= glyph_pos[i].y_advance / 64;
216                         }
217                         hb_font_destroy(font);
218                         hb_buffer_destroy(hbuf);
219                         break;
220                 }
221                 pango_item_free(item);
222         }
223         g_list_free(items);
224         pango_attr_list_unref(attrs);
225         g_object_unref(fontmap);
226         g_object_unref(context);
227
228         return (xpos - start_xpos) * LOGICAL_SCREEN_WIDTH / screen_width;
229 }
230
231 void my_draw_text_deferred(std::vector<TextDefer> &td, const widestring &str, double size, const std::string &theme_element, const std::string &fresh_theme_element, int xpos, int ypos)
232 {
233         TextDefer newtd;
234         newtd.str = str;
235         newtd.size = size;
236         newtd.xpos = xpos;
237         newtd.ypos = ypos;
238         newtd.theme_element = theme_element;
239         newtd.fresh_theme_element = fresh_theme_element;
240         td.push_back(newtd);
241 }
242
243 void draw_all_deferred_text(unsigned char *buf, std::vector<TextDefer> &current, std::vector<TextDefer> &old)
244 {
245         for (unsigned i = 0; i < current.size(); ++i) {
246                 std::string theme_element;
247                 if (i < old.size() && current[i].str != old[i].str) {
248                         // changed text
249                         theme_element = current[i].fresh_theme_element;
250                 } else {
251                         theme_element = current[i].theme_element;
252                 }       
253                 
254                 my_draw_text(current[i].str, buf, current[i].size, theme_element, current[i].xpos, current[i].ypos);
255         }
256 }
257