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