OpenTTD Source 20250813-master-g5b5bdd346d
font_unix.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
10#include "../../stdafx.h"
11
12#include "../../misc/autorelease.hpp"
13#include "../../debug.h"
14#include "../../fontcache.h"
15#include "../../string_func.h"
16#include "../../strings_func.h"
17#include "font_unix.h"
18
19#include <fontconfig/fontconfig.h>
20#include <ft2build.h>
21#include FT_FREETYPE_H
22
23#include "../../safeguards.h"
24
25extern FT_Library _ft_library;
26
32static const FcChar8 *ToFcString(const std::string &str)
33{
34 return reinterpret_cast<const FcChar8 *>(str.c_str());
35}
36
42static const char *FromFcString(const FcChar8 *str)
43{
44 return reinterpret_cast<const char *>(str);
45}
46
53static std::tuple<std::string, std::string> SplitFontFamilyAndStyle(std::string_view font_name)
54{
55 auto separator = font_name.find(',');
56 if (separator == std::string_view::npos) return { std::string(font_name), std::string() };
57
58 auto begin = font_name.find_first_not_of("\t ", separator + 1);
59 if (begin == std::string_view::npos) return { std::string(font_name.substr(0, separator)), std::string() };
60
61 return { std::string(font_name.substr(0, separator)), std::string(font_name.substr(begin)) };
62}
63
70FT_Error GetFontByFaceName(std::string_view font_name, FT_Face *face)
71{
72 FT_Error err = FT_Err_Cannot_Open_Resource;
73
74 if (!FcInit()) {
75 ShowInfo("Unable to load font configuration");
76 return err;
77 }
78
79 auto fc_instance = AutoRelease<FcConfig, FcConfigDestroy>(FcConfigReference(nullptr));
80 assert(fc_instance != nullptr);
81
82 /* Split & strip the font's style */
83 auto [font_family, font_style] = SplitFontFamilyAndStyle(font_name);
84
85 /* Resolve the name and populate the information structure */
86 auto pat = AutoRelease<FcPattern, FcPatternDestroy>(FcPatternCreate());
87 if (!font_family.empty()) FcPatternAddString(pat.get(), FC_FAMILY, ToFcString(font_family));
88 if (!font_style.empty()) FcPatternAddString(pat.get(), FC_STYLE, ToFcString(font_style));
89 FcConfigSubstitute(nullptr, pat.get(), FcMatchPattern);
90 FcDefaultSubstitute(pat.get());
91 auto fs = AutoRelease<FcFontSet, FcFontSetDestroy>(FcFontSetCreate());
92 FcResult result;
93 FcPattern *match = FcFontMatch(nullptr, pat.get(), &result);
94
95 if (fs == nullptr || match == nullptr) return err;
96
97 FcFontSetAdd(fs.get(), match);
98
99 for (FcPattern *font : std::span(fs->fonts, fs->nfont)) {
100 FcChar8 *family;
101 FcChar8 *style;
102 FcChar8 *file;
103 int32_t index;
104
105 /* Try the new filename */
106 if (FcPatternGetString(font, FC_FILE, 0, &file) != FcResultMatch) continue;
107 if (FcPatternGetString(font, FC_FAMILY, 0, &family) != FcResultMatch) continue;
108 if (FcPatternGetString(font, FC_STYLE, 0, &style) != FcResultMatch) continue;
109 if (FcPatternGetInteger(font, FC_INDEX, 0, &index) != FcResultMatch) continue;
110
111 /* The correct style? */
112 if (!font_style.empty() && !StrEqualsIgnoreCase(font_style, FromFcString(style))) continue;
113
114 /* Font config takes the best shot, which, if the family name is spelled
115 * wrongly a 'random' font, so check whether the family name is the
116 * same as the supplied name */
117 if (StrEqualsIgnoreCase(font_family, FromFcString(family))) {
118 err = FT_New_Face(_ft_library, FromFcString(file), index, face);
119 if (err == FT_Err_Ok) return err;
120 }
121 }
122
123 return err;
124}
125
126bool FontConfigFindFallbackFont(FontCacheSettings *settings, const std::string &language_isocode, MissingGlyphSearcher *callback)
127{
128 bool ret = false;
129
130 if (!FcInit()) return ret;
131
132 auto fc_instance = AutoRelease<FcConfig, FcConfigDestroy>(FcConfigReference(nullptr));
133 assert(fc_instance != nullptr);
134
135 /* Fontconfig doesn't handle full language isocodes, only the part
136 * before the _ of e.g. en_GB is used, so "remove" everything after
137 * the _. */
138 std::string lang = fmt::format(":lang={}", language_isocode.substr(0, language_isocode.find('_')));
139
140 /* First create a pattern to match the wanted language. */
141 auto pat = AutoRelease<FcPattern, FcPatternDestroy>(FcNameParse(ToFcString(lang)));
142 /* We only want to know these attributes. */
143 auto os = AutoRelease<FcObjectSet, FcObjectSetDestroy>(FcObjectSetBuild(FC_FILE, FC_INDEX, FC_SPACING, FC_SLANT, FC_WEIGHT, nullptr));
144 /* Get the list of filenames matching the wanted language. */
145 auto fs = AutoRelease<FcFontSet, FcFontSetDestroy>(FcFontList(nullptr, pat.get(), os.get()));
146
147 if (fs == nullptr) return ret;
148
149 int best_weight = -1;
150 const char *best_font = nullptr;
151 int best_index = 0;
152
153 for (FcPattern *font : std::span(fs->fonts, fs->nfont)) {
154 FcChar8 *file = nullptr;
155 FcResult res = FcPatternGetString(font, FC_FILE, 0, &file);
156 if (res != FcResultMatch || file == nullptr) continue;
157
158 /* Get a font with the right spacing .*/
159 int value = 0;
160 FcPatternGetInteger(font, FC_SPACING, 0, &value);
161 if (callback->Monospace() != (value == FC_MONO) && value != FC_DUAL) continue;
162
163 /* Do not use those that explicitly say they're slanted. */
164 FcPatternGetInteger(font, FC_SLANT, 0, &value);
165 if (value != 0) continue;
166
167 /* We want the fatter font as they look better at small sizes. */
168 FcPatternGetInteger(font, FC_WEIGHT, 0, &value);
169 if (value <= best_weight) continue;
170
171 /* Possible match based on attributes, get index. */
172 int32_t index;
173 res = FcPatternGetInteger(font, FC_INDEX, 0, &index);
174 if (res != FcResultMatch) continue;
175
176 callback->SetFontNames(settings, FromFcString(file), &index);
177
178 bool missing = callback->FindMissingGlyphs();
179 Debug(fontcache, 1, "Font \"{}\" misses{} glyphs", FromFcString(file), missing ? "" : " no");
180
181 if (!missing) {
182 best_weight = value;
183 best_font = FromFcString(file);
184 best_index = index;
185 }
186 }
187
188 if (best_font == nullptr) return false;
189
190 callback->SetFontNames(settings, best_font, &best_index);
192 return true;
193}
std::unique_ptr< T, DeleterFromFunc< Tfunc > > AutoRelease
Specialisation of std::unique_ptr for objects which must be deleted by calling a function.
Enum-as-bit-set wrapper.
static void LoadFontCaches(FontSizes fontsizes)
(Re)initialize the font cache related things, i.e.
A searcher for missing glyphs.
bool FindMissingGlyphs()
Check whether there are glyphs missing in the current language.
Definition strings.cpp:2278
virtual void SetFontNames(struct FontCacheSettings *settings, std::string_view font_name, const void *os_data=nullptr)=0
Set the right font names.
virtual bool Monospace()=0
Whether to search for a monospace font or not.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
fluid_settings_t * settings
FluidSynth settings handle.
FT_Error GetFontByFaceName(std::string_view font_name, FT_Face *face)
Load a freetype font face with the given font name.
Definition font_unix.cpp:70
static const char * FromFcString(const FcChar8 *str)
Get a C-style string from a FontConfig-style string.
Definition font_unix.cpp:42
static const FcChar8 * ToFcString(const std::string &str)
Get a FontConfig-style string from a std::string.
Definition font_unix.cpp:32
static std::tuple< std::string, std::string > SplitFontFamilyAndStyle(std::string_view font_name)
Split the font name into the font family and style.
Definition font_unix.cpp:53
Functions related to detecting/finding the right font.
constexpr FontSizes FONTSIZES_REQUIRED
Mask of font sizes required to be present.
Definition gfx_type.h:265
bool StrEqualsIgnoreCase(std::string_view str1, std::string_view str2)
Compares two string( view)s for equality, while ignoring the case of the characters.
Definition string.cpp:321
Settings for the four different fonts.
Definition fontcache.h:180