OpenTTD Source: src/os/unix/font_unix.cpp Source File

OpenTTD Source 15.3

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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
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
32 static const FcChar8 *ToFcString(const std::string &str)
33{
34 return reinterpret_cast<const FcChar8 *>(str.c_str());
35}
36
42 static const char *FromFcString(const FcChar8 *str)
43{
44 return reinterpret_cast<const char *>(str);
45}
46
53 static 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
131 static int GetPreferredWeightDistance(int weight)
132{
133 /* Prefer a font between normal and medium weight. */
134 static constexpr int PREFERRED_WEIGHT_MIN = FC_WEIGHT_NORMAL;
135 static constexpr int PREFERRED_WEIGHT_MAX = FC_WEIGHT_MEDIUM;
136
137 if (weight < PREFERRED_WEIGHT_MIN) return std::abs(weight - PREFERRED_WEIGHT_MIN);
138 if (weight > PREFERRED_WEIGHT_MAX) return weight - PREFERRED_WEIGHT_MAX;
139 return 0;
140}
141
142bool FontConfigFindFallbackFont(FontCacheSettings *settings, const std::string &language_isocode, MissingGlyphSearcher *callback)
143{
144 bool ret = false;
145
146 if (!FcInit()) return ret;
147
148 auto fc_instance = AutoRelease<FcConfig, FcConfigDestroy>(FcConfigReference(nullptr));
149 assert(fc_instance != nullptr);
150
151 /* Fontconfig doesn't handle full language isocodes, only the part
152 * before the _ of e.g. en_GB is used, so "remove" everything after
153 * the _. */
154 std::string lang = fmt::format(":lang={}", language_isocode.substr(0, language_isocode.find('_')));
155
156 /* First create a pattern to match the wanted language. */
157 auto pat = AutoRelease<FcPattern, FcPatternDestroy>(FcNameParse(ToFcString(lang)));
158 /* We only want to know these attributes. */
159 auto os = AutoRelease<FcObjectSet, FcObjectSetDestroy>(FcObjectSetBuild(FC_FILE, FC_INDEX, FC_SPACING, FC_SLANT, FC_WEIGHT, nullptr));
160 /* Get the list of filenames matching the wanted language. */
161 auto fs = AutoRelease<FcFontSet, FcFontSetDestroy>(FcFontList(nullptr, pat.get(), os.get()));
162
163 if (fs == nullptr) return ret;
164
165 int best_weight = -1;
166 const char *best_font = nullptr;
167 int best_index = 0;
168
169 for (FcPattern *font : std::span(fs->fonts, fs->nfont)) {
170 FcChar8 *file = nullptr;
171 FcResult res = FcPatternGetString(font, FC_FILE, 0, &file);
172 if (res != FcResultMatch || file == nullptr) continue;
173
174 /* Get a font with the right spacing .*/
175 int value = 0;
176 FcPatternGetInteger(font, FC_SPACING, 0, &value);
177 if (callback->Monospace() != (value == FC_MONO) && value != FC_DUAL) continue;
178
179 /* Do not use those that explicitly say they're slanted. */
180 FcPatternGetInteger(font, FC_SLANT, 0, &value);
181 if (value != 0) continue;
182
183 /* We want a font near to medium weight. */
184 FcPatternGetInteger(font, FC_WEIGHT, 0, &value);
185 int weight = GetPreferredWeightDistance(value);
186 if (best_weight != -1 && weight > best_weight) continue;
187
188 /* Possible match based on attributes, get index. */
189 int32_t index;
190 res = FcPatternGetInteger(font, FC_INDEX, 0, &index);
191 if (res != FcResultMatch) continue;
192
193 callback->SetFontNames(settings, FromFcString(file), &index);
194
195 bool missing = callback->FindMissingGlyphs();
196 Debug(fontcache, 1, "Font \"{}\" misses{} glyphs", FromFcString(file), missing ? "" : " no");
197
198 if (!missing) {
199 best_weight = weight;
200 best_font = FromFcString(file);
201 best_index = index;
202 }
203 }
204
205 if (best_font == nullptr) return false;
206
207 callback->SetFontNames(settings, best_font, &best_index);
208 FontCache::LoadFontCaches(callback->Monospace() ? FontSizes{FS_MONO} : FONTSIZES_REQUIRED);
209 return true;
210}
AutoRelease
std::unique_ptr< T, DeleterFromFunc< Tfunc > > AutoRelease
Specialisation of std::unique_ptr for objects which must be deleted by calling a function.
Definition autorelease.hpp:25
EnumBitSet
Enum-as-bit-set wrapper.
Definition enum_type.hpp:177
FontCache::LoadFontCaches
static void LoadFontCaches(FontSizes fontsizes)
(Re)initialize the font cache related things, i.e.
Definition fontcache.cpp:237
MissingGlyphSearcher
A searcher for missing glyphs.
Definition strings_func.h:156
MissingGlyphSearcher::FindMissingGlyphs
bool FindMissingGlyphs()
Check whether there are glyphs missing in the current language.
Definition strings.cpp:2306
MissingGlyphSearcher::SetFontNames
virtual void SetFontNames(struct FontCacheSettings *settings, std::string_view font_name, const void *os_data=nullptr)=0
Set the right font names.
MissingGlyphSearcher::Monospace
virtual bool Monospace()=0
Whether to search for a monospace font or not.
Debug
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
settings
fluid_settings_t * settings
FluidSynth settings handle.
Definition fluidsynth.cpp:25
GetFontByFaceName
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
GetPreferredWeightDistance
static int GetPreferredWeightDistance(int weight)
Get distance between font weight and preferred font weights.
Definition font_unix.cpp:131
FromFcString
static const char * FromFcString(const FcChar8 *str)
Get a C-style string from a FontConfig-style string.
Definition font_unix.cpp:42
ToFcString
static const FcChar8 * ToFcString(const std::string &str)
Get a FontConfig-style string from a std::string.
Definition font_unix.cpp:32
SplitFontFamilyAndStyle
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
font_unix.h
Functions related to detecting/finding the right font.
FONTSIZES_REQUIRED
constexpr FontSizes FONTSIZES_REQUIRED
Mask of font sizes required to be present.
Definition gfx_type.h:264
StrEqualsIgnoreCase
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:323
FontCacheSettings
Settings for the four different fonts.
Definition fontcache.h:180