3b82a3c470ff82cec67702f4940eb40f9ff95b54
[oweals/minetest.git] / src / fontengine.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2014 sapier <sapier at gmx dot net>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19 #include "fontengine.h"
20 #include "log.h"
21 #include "main.h"
22 #include "config.h"
23 #include "porting.h"
24 #include "constants.h"
25 #include "filesys.h"
26
27 #if USE_FREETYPE
28 #include "gettext.h"
29 #include "xCGUITTFont.h"
30 #endif
31
32 /** maximum size distance for getting a "similar" font size */
33 #define MAX_FONT_SIZE_OFFSET 10
34
35 /** reference to access font engine, has to be initialized by main */
36 FontEngine* g_fontengine = NULL;
37
38 /** callback to be used on change of font size setting */
39 static void font_setting_changed(const std::string, void *userdata) {
40         g_fontengine->readSettings();
41 }
42
43 /******************************************************************************/
44 FontEngine::FontEngine(Settings* main_settings, gui::IGUIEnvironment* env) :
45         m_settings(main_settings),
46         m_env(env),
47         m_font_cache(),
48         m_currentMode(FM_Standard),
49         m_lastMode(),
50         m_lastSize(0),
51         m_lastFont(NULL)
52 {
53
54         for (unsigned int i = 0; i < FM_MaxMode; i++) {
55                 m_default_size[i] = (FontMode) FONT_SIZE_UNSPECIFIED;
56         }
57
58         assert(m_settings != NULL);
59         assert(m_env != NULL);
60         assert(m_env->getSkin() != NULL);
61
62         m_currentMode = FM_Simple;
63
64 #if USE_FREETYPE
65         if (g_settings->getBool("freetype")) {
66                 m_default_size[FM_Standard] = m_settings->getU16("font_size");
67                 m_default_size[FM_Fallback] = m_settings->getU16("fallback_font_size");
68                 m_default_size[FM_Mono]     = m_settings->getU16("mono_font_size");
69
70                 if (is_yes(gettext("needs_fallback_font"))) {
71                         m_currentMode = FM_Fallback;
72                 }
73                 else {
74                         m_currentMode = FM_Standard;
75                 }
76         }
77
78         // having freetype but not using it is quite a strange case so we need to do
79         // special handling for it
80         if (m_currentMode == FM_Simple) {
81                 std::stringstream fontsize;
82                 fontsize << DEFAULT_FONT_SIZE;
83                 m_settings->setDefault("font_size", fontsize.str());
84                 m_settings->setDefault("mono_font_size", fontsize.str());
85         }
86 #endif
87
88         m_default_size[FM_Simple]       = m_settings->getU16("font_size");
89         m_default_size[FM_SimpleMono]   = m_settings->getU16("mono_font_size");
90
91         updateSkin();
92
93         if (m_currentMode == FM_Standard) {
94                 m_settings->registerChangedCallback("font_size", font_setting_changed, NULL);
95                 m_settings->registerChangedCallback("font_path", font_setting_changed, NULL);
96                 m_settings->registerChangedCallback("font_shadow", font_setting_changed, NULL);
97                 m_settings->registerChangedCallback("font_shadow_alpha", font_setting_changed, NULL);
98         }
99         else if (m_currentMode == FM_Fallback) {
100                 m_settings->registerChangedCallback("fallback_font_size", font_setting_changed, NULL);
101                 m_settings->registerChangedCallback("fallback_font_path", font_setting_changed, NULL);
102                 m_settings->registerChangedCallback("fallback_font_shadow", font_setting_changed, NULL);
103                 m_settings->registerChangedCallback("fallback_font_shadow_alpha", font_setting_changed, NULL);
104         }
105
106         m_settings->registerChangedCallback("mono_font_path", font_setting_changed, NULL);
107         m_settings->registerChangedCallback("mono_font_size", font_setting_changed, NULL);
108         m_settings->registerChangedCallback("screen_dpi", font_setting_changed, NULL);
109         m_settings->registerChangedCallback("gui_scaling", font_setting_changed, NULL);
110 }
111
112 /******************************************************************************/
113 FontEngine::~FontEngine()
114 {
115         cleanCache();
116 }
117
118 /******************************************************************************/
119 void FontEngine::cleanCache()
120 {
121         for ( unsigned int i = 0; i < FM_MaxMode; i++) {
122
123                 for (std::map<unsigned int, irr::gui::IGUIFont*>::iterator iter
124                                 = m_font_cache[i].begin();
125                                 iter != m_font_cache[i].end(); iter++) {
126                         iter->second->drop();
127                         iter->second = NULL;
128                 }
129                 m_font_cache[i].clear();
130         }
131 }
132
133 /******************************************************************************/
134 irr::gui::IGUIFont* FontEngine::getFont(unsigned int font_size, FontMode mode)
135 {
136         if (mode == FM_Unspecified) {
137                 mode = m_currentMode;
138         }
139         else if ((mode == FM_Mono) && (m_currentMode == FM_Simple)) {
140                 mode = FM_SimpleMono;
141         }
142
143         if (font_size == FONT_SIZE_UNSPECIFIED) {
144                 font_size = m_default_size[mode];
145         }
146
147         if ((font_size == m_lastSize) && (mode == m_lastMode)) {
148                 return m_lastFont;
149         }
150
151         if (m_font_cache[mode].find(font_size) == m_font_cache[mode].end()) {
152                 initFont(font_size, mode);
153         }
154
155         if (m_font_cache[mode].find(font_size) == m_font_cache[mode].end()) {
156                 return NULL;
157         }
158
159         m_lastSize = font_size;
160         m_lastMode = mode;
161         m_lastFont = m_font_cache[mode][font_size];
162
163         return m_font_cache[mode][font_size];
164 }
165
166 /******************************************************************************/
167 unsigned int FontEngine::getTextHeight(unsigned int font_size, FontMode mode)
168 {
169         irr::gui::IGUIFont* font = getFont(font_size, mode);
170
171         // use current skin font as fallback
172         if (font == NULL) {
173                 font = m_env->getSkin()->getFont();
174         }
175         assert(font != NULL);
176
177         return font->getDimension(L"Some unimportant example String").Height;
178 }
179
180 /******************************************************************************/
181 unsigned int FontEngine::getTextWidth(const std::wstring& text,
182                 unsigned int font_size, FontMode mode)
183 {
184         irr::gui::IGUIFont* font = getFont(font_size, mode);
185
186         // use current skin font as fallback
187         if (font == NULL) {
188                 font = m_env->getSkin()->getFont();
189         }
190         assert(font != NULL);
191
192         return font->getDimension(text.c_str()).Width;
193 }
194
195
196 /** get line height for a specific font (including empty room between lines) */
197 unsigned int FontEngine::getLineHeight(unsigned int font_size, FontMode mode)
198 {
199         irr::gui::IGUIFont* font = getFont(font_size, mode);
200
201         // use current skin font as fallback
202         if (font == NULL) {
203                 font = m_env->getSkin()->getFont();
204         }
205         assert(font != NULL);
206
207         return font->getDimension(L"Some unimportant example String").Height
208                         + font->getKerningHeight();
209 }
210
211 /******************************************************************************/
212 unsigned int FontEngine::getDefaultFontSize()
213 {
214         return m_default_size[m_currentMode];
215 }
216
217 /******************************************************************************/
218 void FontEngine::readSettings()
219 {
220 #if USE_FREETYPE
221         if (g_settings->getBool("freetype")) {
222                 m_default_size[FM_Standard] = m_settings->getU16("font_size");
223                 m_default_size[FM_Fallback] = m_settings->getU16("fallback_font_size");
224                 m_default_size[FM_Mono]     = m_settings->getU16("mono_font_size");
225
226                 if (is_yes(gettext("needs_fallback_font"))) {
227                         m_currentMode = FM_Fallback;
228                 }
229                 else {
230                         m_currentMode = FM_Standard;
231                 }
232         }
233 #endif
234         m_default_size[FM_Simple]       = m_settings->getU16("font_size");
235         m_default_size[FM_SimpleMono]   = m_settings->getU16("mono_font_size");
236
237         cleanCache();
238         updateFontCache();
239         updateSkin();
240 }
241
242 /******************************************************************************/
243 void FontEngine::updateSkin()
244 {
245         gui::IGUIFont *font = getFont();
246
247         if (font)
248                 m_env->getSkin()->setFont(font);
249         else
250                 errorstream << "FontEngine: Default font file: " <<
251                                 "\n\t\"" << m_settings->get("font_path") << "\"" <<
252                                 "\n\trequired for current screen configuration was not found" <<
253                                 " or was invalid file format." <<
254                                 "\n\tUsing irrlicht default font." << std::endl;
255
256         // If we did fail to create a font our own make irrlicht find a default one
257         font = m_env->getSkin()->getFont();
258         assert(font);
259
260         u32 text_height = font->getDimension(L"Hello, world!").Height;
261         infostream << "text_height=" << text_height << std::endl;
262 }
263
264 /******************************************************************************/
265 void FontEngine::updateFontCache()
266 {
267         /* the only font to be initialized is default one,
268          * all others are re-initialized on demand */
269         initFont(m_default_size[m_currentMode], m_currentMode);
270
271         /* reset font quick access */
272         m_lastMode = FM_Unspecified;
273         m_lastSize = 0;
274         m_lastFont = NULL;
275 }
276
277 /******************************************************************************/
278 void FontEngine::initFont(unsigned int basesize, FontMode mode)
279 {
280
281         std::string font_config_prefix;
282
283         if (mode == FM_Unspecified) {
284                 mode = m_currentMode;
285         }
286
287         switch (mode) {
288
289                 case FM_Standard:
290                         font_config_prefix = "";
291                         break;
292
293                 case FM_Fallback:
294                         font_config_prefix = "fallback_";
295                         break;
296
297                 case FM_Mono:
298                         font_config_prefix = "mono_";
299                         if (m_currentMode == FM_Simple)
300                                 mode = FM_SimpleMono;
301                         break;
302
303                 case FM_Simple: /* Fallthrough */
304                 case FM_SimpleMono: /* Fallthrough */
305                 default:
306                         font_config_prefix = "";
307
308         }
309
310         if (m_font_cache[mode].find(basesize) != m_font_cache[mode].end())
311                 return;
312
313         if ((mode == FM_Simple) || (mode == FM_SimpleMono)) {
314                 initSimpleFont(basesize, mode);
315                 return;
316         }
317 #if USE_FREETYPE
318         else {
319                 if (! is_yes(m_settings->get("freetype"))) {
320                         return;
321                 }
322                 unsigned int size = floor(
323                                 porting::getDisplayDensity() *
324                                 m_settings->getFloat("gui_scaling") *
325                                 basesize);
326                 u32 font_shadow       = 0;
327                 u32 font_shadow_alpha = 0;
328
329                 try {
330                         font_shadow =
331                                         g_settings->getU16(font_config_prefix + "font_shadow");
332                 } catch (SettingNotFoundException&) {}
333                 try {
334                         font_shadow_alpha =
335                                         g_settings->getU16(font_config_prefix + "font_shadow_alpha");
336                 } catch (SettingNotFoundException&) {}
337
338                 std::string font_path = g_settings->get(font_config_prefix + "font_path");
339
340                 irr::gui::IGUIFont* font = gui::CGUITTFont::createTTFont(m_env,
341                                 font_path.c_str(), size, true, true, font_shadow,
342                                 font_shadow_alpha);
343
344                 if (font != NULL) {
345                         m_font_cache[mode][basesize] = font;
346                 }
347                 else {
348                         errorstream << "FontEngine: failed to load freetype font: "
349                                         << font_path << std::endl;
350                 }
351         }
352 #endif
353 }
354
355 /** initialize a font without freetype */
356 void FontEngine::initSimpleFont(unsigned int basesize, FontMode mode)
357 {
358         assert((mode == FM_Simple) || (mode == FM_SimpleMono));
359
360         std::string font_path = "";
361         if (mode == FM_Simple) {
362                 font_path = m_settings->get("font_path");
363         } else {
364                 font_path = m_settings->get("mono_font_path");
365         }
366         std::string basename = font_path;
367         std::string ending = font_path.substr(font_path.length() -4);
368
369         if (ending == ".ttf") {
370                 errorstream << "FontEngine: Not trying to open \"" << font_path
371                                 << "\" which seems to be a truetype font." << std::endl;
372                 return;
373         }
374
375         if ((ending == ".xml") || (ending == ".png")) {
376                 basename = font_path.substr(0,font_path.length()-4);
377         }
378
379         if (basesize == FONT_SIZE_UNSPECIFIED)
380                 basesize = DEFAULT_FONT_SIZE;
381
382         unsigned int size = floor(
383                         porting::getDisplayDensity() *
384                         m_settings->getFloat("gui_scaling") *
385                         basesize);
386
387         irr::gui::IGUIFont* font = NULL;
388
389         for(unsigned int offset = 0; offset < MAX_FONT_SIZE_OFFSET; offset++) {
390
391                 // try opening positive offset
392                 std::stringstream fontsize_plus_png;
393                 fontsize_plus_png << basename << "_" << (size + offset) << ".png";
394
395                 if (fs::PathExists(fontsize_plus_png.str())) {
396                         font = m_env->getFont(fontsize_plus_png.str().c_str());
397
398                         if (font) {
399                                 verbosestream << "FontEngine: found font: " << fontsize_plus_png.str() << std::endl;
400                                 break;
401                         }
402                 }
403
404                 std::stringstream fontsize_plus_xml;
405                 fontsize_plus_xml << basename << "_" << (size + offset) << ".xml";
406
407                 if (fs::PathExists(fontsize_plus_xml.str())) {
408                         font = m_env->getFont(fontsize_plus_xml.str().c_str());
409
410                         if (font) {
411                                 verbosestream << "FontEngine: found font: " << fontsize_plus_xml.str() << std::endl;
412                                 break;
413                         }
414                 }
415
416                 // try negative offset
417                 std::stringstream fontsize_minus_png;
418                 fontsize_minus_png << basename << "_" << (size - offset) << ".png";
419
420                 if (fs::PathExists(fontsize_minus_png.str())) {
421                         font = m_env->getFont(fontsize_minus_png.str().c_str());
422
423                         if (font) {
424                                 verbosestream << "FontEngine: found font: " << fontsize_minus_png.str() << std::endl;
425                                 break;
426                         }
427                 }
428
429                 std::stringstream fontsize_minus_xml;
430                 fontsize_minus_xml << basename << "_" << (size - offset) << ".xml";
431
432                 if (fs::PathExists(fontsize_minus_xml.str())) {
433                         font = m_env->getFont(fontsize_minus_xml.str().c_str());
434
435                         if (font) {
436                                 verbosestream << "FontEngine: found font: " << fontsize_minus_xml.str() << std::endl;
437                                 break;
438                         }
439                 }
440         }
441
442         // try name direct
443         if (font == NULL) {
444                 if (fs::PathExists(font_path)) {
445                         font = m_env->getFont(font_path.c_str());
446                         if (font)
447                                 verbosestream << "FontEngine: found font: " << font_path << std::endl;
448                 }
449         }
450
451         if (font != NULL) {
452                 font->grab();
453                 m_font_cache[mode][basesize] = font;
454         }
455 }