]> git.lizzy.rs Git - minetest.git/blob - src/client/fontengine.cpp
fontengine: Fix crash loading PNG/XML fonts from paths without dot
[minetest.git] / src / client / 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
20 #include "fontengine.h"
21 #include <cmath>
22 #include "client/renderingengine.h"
23 #include "config.h"
24 #include "porting.h"
25 #include "filesys.h"
26 #include "gettext.h"
27
28 #if USE_FREETYPE
29 #include "irrlicht_changes/CGUITTFont.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 &name, void *userdata)
40 {
41         g_fontengine->readSettings();
42 }
43
44 /******************************************************************************/
45 FontEngine::FontEngine(gui::IGUIEnvironment* env) :
46         m_env(env)
47 {
48
49         for (u32 &i : m_default_size) {
50                 i = (FontMode) FONT_SIZE_UNSPECIFIED;
51         }
52
53         assert(g_settings != NULL); // pre-condition
54         assert(m_env != NULL); // pre-condition
55         assert(m_env->getSkin() != NULL); // pre-condition
56
57         readSettings();
58
59         if (m_currentMode != FM_Simple) {
60                 g_settings->registerChangedCallback("font_size", font_setting_changed, NULL);
61                 g_settings->registerChangedCallback("font_bold", font_setting_changed, NULL);
62                 g_settings->registerChangedCallback("font_italic", font_setting_changed, NULL);
63                 g_settings->registerChangedCallback("font_path", font_setting_changed, NULL);
64                 g_settings->registerChangedCallback("font_path_bold", font_setting_changed, NULL);
65                 g_settings->registerChangedCallback("font_path_italic", font_setting_changed, NULL);
66                 g_settings->registerChangedCallback("font_path_bolditalic", font_setting_changed, NULL);
67                 g_settings->registerChangedCallback("font_shadow", font_setting_changed, NULL);
68                 g_settings->registerChangedCallback("font_shadow_alpha", font_setting_changed, NULL);
69                 g_settings->registerChangedCallback("fallback_font_path", font_setting_changed, NULL);
70         }
71
72         g_settings->registerChangedCallback("mono_font_path", font_setting_changed, NULL);
73         g_settings->registerChangedCallback("mono_font_size", font_setting_changed, NULL);
74         g_settings->registerChangedCallback("screen_dpi", font_setting_changed, NULL);
75         g_settings->registerChangedCallback("gui_scaling", font_setting_changed, NULL);
76 }
77
78 /******************************************************************************/
79 FontEngine::~FontEngine()
80 {
81         cleanCache();
82 }
83
84 /******************************************************************************/
85 void FontEngine::cleanCache()
86 {
87         for (auto &font_cache_it : m_font_cache) {
88
89                 for (auto &font_it : font_cache_it) {
90                         font_it.second->drop();
91                         font_it.second = NULL;
92                 }
93                 font_cache_it.clear();
94         }
95 }
96
97 /******************************************************************************/
98 irr::gui::IGUIFont *FontEngine::getFont(FontSpec spec)
99 {
100         return getFont(spec, false);
101 }
102
103 irr::gui::IGUIFont *FontEngine::getFont(FontSpec spec, bool may_fail)
104 {
105         if (spec.mode == FM_Unspecified) {
106                 spec.mode = m_currentMode;
107         } else if (m_currentMode == FM_Simple) {
108                 // Freetype disabled -> Force simple mode
109                 spec.mode = (spec.mode == FM_Mono ||
110                                 spec.mode == FM_SimpleMono) ?
111                                 FM_SimpleMono : FM_Simple;
112                 // Support for those could be added, but who cares?
113                 spec.bold = false;
114                 spec.italic = false;
115         } else if (spec.mode == _FM_Fallback) {
116                 // Fallback font doesn't support these either
117                 spec.bold = false;
118                 spec.italic = false;
119         }
120
121         // Fallback to default size
122         if (spec.size == FONT_SIZE_UNSPECIFIED)
123                 spec.size = m_default_size[spec.mode];
124
125         const auto &cache = m_font_cache[spec.getHash()];
126         auto it = cache.find(spec.size);
127         if (it != cache.end())
128                 return it->second;
129
130         // Font does not yet exist
131         gui::IGUIFont *font = nullptr;
132         if (spec.mode == FM_Simple || spec.mode == FM_SimpleMono)
133                 font = initSimpleFont(spec);
134         else
135                 font = initFont(spec);
136
137         if (!font && !may_fail) {
138                 errorstream << "Minetest cannot continue without a valid font. "
139                         "Please correct the 'font_path' setting or install the font "
140                         "file in the proper location." << std::endl;
141                 abort();
142         }
143
144         m_font_cache[spec.getHash()][spec.size] = font;
145
146         return font;
147 }
148
149 /******************************************************************************/
150 unsigned int FontEngine::getTextHeight(const FontSpec &spec)
151 {
152         irr::gui::IGUIFont *font = getFont(spec);
153
154         // use current skin font as fallback
155         if (font == NULL) {
156                 font = m_env->getSkin()->getFont();
157         }
158         FATAL_ERROR_IF(font == NULL, "Could not get skin font");
159
160         return font->getDimension(L"Some unimportant example String").Height;
161 }
162
163 /******************************************************************************/
164 unsigned int FontEngine::getTextWidth(const std::wstring &text, const FontSpec &spec)
165 {
166         irr::gui::IGUIFont *font = getFont(spec);
167
168         // use current skin font as fallback
169         if (font == NULL) {
170                 font = m_env->getSkin()->getFont();
171         }
172         FATAL_ERROR_IF(font == NULL, "Could not get font");
173
174         return font->getDimension(text.c_str()).Width;
175 }
176
177
178 /** get line height for a specific font (including empty room between lines) */
179 unsigned int FontEngine::getLineHeight(const FontSpec &spec)
180 {
181         irr::gui::IGUIFont *font = getFont(spec);
182
183         // use current skin font as fallback
184         if (font == NULL) {
185                 font = m_env->getSkin()->getFont();
186         }
187         FATAL_ERROR_IF(font == NULL, "Could not get font");
188
189         return font->getDimension(L"Some unimportant example String").Height
190                         + font->getKerningHeight();
191 }
192
193 /******************************************************************************/
194 unsigned int FontEngine::getDefaultFontSize()
195 {
196         return m_default_size[m_currentMode];
197 }
198
199 unsigned int FontEngine::getFontSize(FontMode mode)
200 {
201         if (m_currentMode == FM_Simple) {
202                 if (mode == FM_Mono || mode == FM_SimpleMono)
203                         return m_default_size[FM_SimpleMono];
204                 else
205                         return m_default_size[FM_Simple];
206         }
207
208         if (mode == FM_Unspecified)
209                 return m_default_size[FM_Standard];
210
211         return m_default_size[mode];
212 }
213
214 /******************************************************************************/
215 void FontEngine::readSettings()
216 {
217         if (USE_FREETYPE && g_settings->getBool("freetype")) {
218                 m_default_size[FM_Standard]  = g_settings->getU16("font_size");
219                 m_default_size[_FM_Fallback] = g_settings->getU16("font_size");
220                 m_default_size[FM_Mono]      = g_settings->getU16("mono_font_size");
221
222                 m_default_bold = g_settings->getBool("font_bold");
223                 m_default_italic = g_settings->getBool("font_italic");
224
225         } else {
226                 m_currentMode = FM_Simple;
227         }
228
229         m_default_size[FM_Simple]       = g_settings->getU16("font_size");
230         m_default_size[FM_SimpleMono]   = g_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\"" << g_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 << "FontEngine: measured 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         getFont(FONT_SIZE_UNSPECIFIED, FM_Unspecified);
265 }
266
267 /******************************************************************************/
268 gui::IGUIFont *FontEngine::initFont(const FontSpec &spec)
269 {
270         assert(spec.mode != FM_Unspecified);
271         assert(spec.size != FONT_SIZE_UNSPECIFIED);
272
273         std::string setting_prefix = "";
274         if (spec.mode == FM_Mono)
275                 setting_prefix = "mono_";
276
277         std::string setting_suffix = "";
278         if (spec.bold)
279                 setting_suffix.append("_bold");
280         if (spec.italic)
281                 setting_suffix.append("_italic");
282
283         u32 size = std::floor(RenderingEngine::getDisplayDensity() *
284                         g_settings->getFloat("gui_scaling") * spec.size);
285
286         if (size == 0) {
287                 errorstream << "FontEngine: attempt to use font size 0" << std::endl;
288                 errorstream << "  display density: " << RenderingEngine::getDisplayDensity() << std::endl;
289                 abort();
290         }
291
292         u16 font_shadow       = 0;
293         u16 font_shadow_alpha = 0;
294         g_settings->getU16NoEx(setting_prefix + "font_shadow", font_shadow);
295         g_settings->getU16NoEx(setting_prefix + "font_shadow_alpha",
296                         font_shadow_alpha);
297
298         std::string path_setting;
299         if (spec.mode == _FM_Fallback)
300                 path_setting = "fallback_font_path";
301         else
302                 path_setting = setting_prefix + "font_path" + setting_suffix;
303
304         std::string fallback_settings[] = {
305                 g_settings->get(path_setting),
306                 Settings::getLayer(SL_DEFAULTS)->get(path_setting)
307         };
308
309 #if USE_FREETYPE
310         for (const std::string &font_path : fallback_settings) {
311                 gui::CGUITTFont *font = gui::CGUITTFont::createTTFont(m_env,
312                                 font_path.c_str(), size, true, true, font_shadow,
313                                 font_shadow_alpha);
314
315                 if (!font) {
316                         errorstream << "FontEngine: Cannot load '" << font_path <<
317                                 "'. Trying to fall back to another path." << std::endl;
318                         continue;
319                 }
320
321                 if (spec.mode != _FM_Fallback) {
322                         FontSpec spec2(spec);
323                         spec2.mode = _FM_Fallback;
324                         font->setFallback(getFont(spec2, true));
325                 }
326                 return font;
327         }
328 #else
329         errorstream << "FontEngine: Tried to load TTF font but Minetest was"
330                         " compiled without Freetype." << std::endl;
331 #endif
332         return nullptr;
333 }
334
335 /** initialize a font without freetype */
336 gui::IGUIFont *FontEngine::initSimpleFont(const FontSpec &spec)
337 {
338         assert(spec.mode == FM_Simple || spec.mode == FM_SimpleMono);
339         assert(spec.size != FONT_SIZE_UNSPECIFIED);
340
341         const std::string &font_path = g_settings->get(
342                         (spec.mode == FM_SimpleMono) ? "mono_font_path" : "font_path");
343
344         size_t pos_dot = font_path.find_last_of('.');
345         std::string basename = font_path, ending;
346         if (pos_dot != std::string::npos)
347                 ending = lowercase(font_path.substr(pos_dot));
348
349         if (ending == ".ttf") {
350                 errorstream << "FontEngine: Found font \"" << font_path
351                                 << "\" but freetype is not available." << std::endl;
352                 return nullptr;
353         }
354
355         if (ending == ".xml" || ending == ".png")
356                 basename = font_path.substr(0, pos_dot);
357
358         u32 size = std::floor(
359                         RenderingEngine::getDisplayDensity() *
360                         g_settings->getFloat("gui_scaling") *
361                         spec.size);
362
363         irr::gui::IGUIFont *font = nullptr;
364         std::string font_extensions[] = { ".png", ".xml" };
365
366         // Find nearest matching font scale
367         // Does a "zig-zag motion" (positibe/negative), from 0 to MAX_FONT_SIZE_OFFSET
368         for (s32 zoffset = 0; zoffset < MAX_FONT_SIZE_OFFSET * 2; zoffset++) {
369                 std::stringstream path;
370
371                 // LSB to sign
372                 s32 sign = (zoffset & 1) ? -1 : 1;
373                 s32 offset = zoffset >> 1;
374
375                 for (const std::string &ext : font_extensions) {
376                         path.str(""); // Clear
377                         path << basename << "_" << (size + offset * sign) << ext;
378
379                         if (!fs::PathExists(path.str()))
380                                 continue;
381
382                         font = m_env->getFont(path.str().c_str());
383
384                         if (font) {
385                                 verbosestream << "FontEngine: found font: " << path.str() << std::endl;
386                                 break;
387                         }
388                 }
389
390                 if (font)
391                         break;
392         }
393
394         // try name direct
395         if (font == NULL) {
396                 if (fs::PathExists(font_path)) {
397                         font = m_env->getFont(font_path.c_str());
398                         if (font)
399                                 verbosestream << "FontEngine: found font: " << font_path << std::endl;
400                 }
401         }
402
403         return font;
404 }