KiCad PCB EDA Suite
Loading...
Searching...
No Matches
fontconfig.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2021 Ola Rinta-Koski
5 * Copyright (C) 2023 CERN (www.cern.ch)
6 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
7 *
8 * This program is free software: you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the
10 * Free Software Foundation, either version 3 of the License, or (at your
11 * option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22#include <mutex>
23#include <font/fontconfig.h>
24#include <wx/log.h>
25#include <trace_helpers.h>
26#include <string_utils.h>
27#include <macros.h>
28#include <cstdint>
29#include <reporter.h>
30#include <embedded_files.h>
31
32#ifdef __WIN32__
33#include <windows.h>
34#endif
35
36using namespace fontconfig;
37
38static FONTCONFIG* g_config = nullptr;
39static bool g_fcInitSuccess = false;
40
42static std::mutex g_fontConfigMutex;
43
48{
49 FcPattern* pat;
50};
51
52
54{
55 return wxString::Format( "%d.%d.%d", FC_MAJOR, FC_MINOR, FC_REVISION );
56}
57
58
62
63
65{
66 std::lock_guard lock( g_fontConfigMutex );
67 s_reporter = aReporter;
68}
69
70
76
77
86static void bootstrapFc()
87{
88#if defined( _MSC_VER )
89 __try
90 {
91#endif
92 FcInit();
93 g_fcInitSuccess = true;
94#if defined( _MSC_VER )
95 }
96 __except( GetExceptionCode() == STATUS_IN_PAGE_ERROR ? EXCEPTION_EXECUTE_HANDLER
97 : EXCEPTION_CONTINUE_SEARCH )
98 {
99 g_fcInitSuccess = false;
100
101 // We have documented cases that fontconfig while trying to cache fonts
102 // ends up using freetype to try and get font info
103 // freetype itself reads fonts through memory mapping instead of normal file APIs
104 // there are crashes reading fonts sometimes as a result that return STATUS_IN_PAGE_ERROR
105 }
106#endif
107}
108
109
111{
112 if( !g_config )
113 {
114 bootstrapFc();
115 g_config = new FONTCONFIG();
116 }
117
118 return g_config;
119}
120
121
122bool FONTCONFIG::isLanguageMatch( const wxString& aSearchLang, const wxString& aSupportedLang )
123{
124 if( aSearchLang.Lower() == aSupportedLang.Lower() )
125 return true;
126
127 if( aSupportedLang.empty() )
128 return false;
129
130 if( aSearchLang.empty() )
131 return false;
132
133 wxArrayString supportedLangBits;
134 wxStringSplit( aSupportedLang.Lower(), supportedLangBits, wxS( '-' ) );
135
136 wxArrayString searhcLangBits;
137 wxStringSplit( aSearchLang.Lower(), searhcLangBits, wxS( '-' ) );
138
139 // if either side of the comparison have only one section, then its a broad match but fine
140 // i.e. the haystack is declaring broad support or the search language is broad
141 if( searhcLangBits.size() == 1 || supportedLangBits.size() == 1 )
142 return searhcLangBits[0] == supportedLangBits[0];
143
144 // the full two part comparison should have passed the initial shortcut
145
146 return false;
147}
148
149
150std::string FONTCONFIG::getFcString( FONTCONFIG_PAT& aPat, const char* aObj, int aIdx )
151{
152 FcChar8* str;
153 std::string res;
154
155 if( FcPatternGetString( aPat.pat, aObj, aIdx, &str ) == FcResultMatch )
156 res = std::string( reinterpret_cast<char*>( str ) );
157
158 return res;
159}
160
161
163 std::unordered_map<std::string, std::string>& aFamStringMap )
164{
165 std::string famLang;
166 std::string fam;
167
168 int langIdx = 0;
169
170 do
171 {
172 famLang = getFcString( aPat, FC_FAMILYLANG, langIdx );
173
174 if( famLang.empty() && langIdx != 0 )
175 {
176 break;
177 }
178 else
179 {
180 fam = getFcString( aPat, FC_FAMILY, langIdx );
181 aFamStringMap.insert_or_assign( famLang, fam );
182 }
183 } while( langIdx++ < std::numeric_limits<int8_t>::max() ); //arbitrary to avoid getting stuck for any reason
184}
185
186
187std::string FONTCONFIG::getFamilyStringByLang( FONTCONFIG_PAT& aPat, const wxString& aDesiredLang )
188{
189 std::unordered_map<std::string, std::string> famStrings;
190 getAllFamilyStrings( aPat, famStrings );
191
192 if( famStrings.empty() )
193 return "";
194
195 for( auto const& [key, val] : famStrings )
196 {
197 if( isLanguageMatch( aDesiredLang, From_UTF8( key.c_str() ) ) )
198 return val;
199 }
200
201 // fall back to the first and maybe only available name
202 // most fonts by review don't even bother declaring more than one font family name
203 // and they don't even bother declare the language tag either, they just leave it blank
204 return famStrings.begin()->second;
205}
206
207
208FONTCONFIG::FF_RESULT FONTCONFIG::FindFont( const wxString& aFontName, wxString& aFontFile,
209 int& aFaceIndex, bool aBold, bool aItalic,
210 const std::vector<wxString>* aEmbeddedFiles )
211{
213
214 if( !g_fcInitSuccess )
215 return retval;
216
217 // If the original font name contains any of these, then it is bold, regardless
218 // of whether we are looking for bold or not
219 if( aFontName.Lower().Contains( wxS( "bold" ) ) // also catches ultrabold
220 || aFontName.Lower().Contains( wxS( "heavy" ) )
221 || aFontName.Lower().Contains( wxS( "black" ) ) // also catches extrablack
222 || aFontName.Lower().Contains( wxS( "thick" ) )
223 || aFontName.Lower().Contains( wxS( "dark" ) ) )
224 {
225 aBold = true;
226 }
227
228 FcConfig* config = FcConfigGetCurrent();
229
230 if( aEmbeddedFiles )
231 {
232 for( const wxString& file : *aEmbeddedFiles )
233 FcConfigAppFontAddFile( config, (const FcChar8*) file.c_str().AsChar() );
234 }
235
236 const wxString& qualifiedFontName = aFontName;
237
238 wxScopedCharBuffer const fcBuffer = qualifiedFontName.ToUTF8();
239
240 FcPattern* pat = FcPatternCreate();
241
242 if( aBold )
243 FcPatternAddInteger( pat, FC_WEIGHT, FC_WEIGHT_BOLD );
244
245 if( aItalic )
246 FcPatternAddInteger( pat, FC_SLANT, FC_SLANT_ITALIC );
247
248 FcPatternAddString( pat, FC_FAMILY, (FcChar8*) fcBuffer.data() );
249
250 FcConfigSubstitute( config, pat, FcMatchPattern );
251 FcDefaultSubstitute( pat );
252
253 FcResult r = FcResultNoMatch;
254 FcPattern* font = FcFontMatch( config, pat, &r );
255
256 wxString fontName;
257 bool familyMatched = false;
258
259 if( font )
260 {
261 FcChar8* file = nullptr;
262
263 if( FcPatternGetString( font, FC_FILE, 0, &file ) == FcResultMatch )
264 {
265 aFontFile = wxString::FromUTF8( (char*) file );
266 aFaceIndex = 0;
267
268 wxString styleStr;
269 FcChar8* family = nullptr;
270 FcChar8* style = nullptr;
271
273
274 std::unordered_map<std::string, std::string> famStrings;
275 FONTCONFIG_PAT patHolder{ font };
276
277 getAllFamilyStrings( patHolder, famStrings );
278
279 if( FcPatternGetString( font, FC_FAMILY, 0, &family ) == FcResultMatch )
280 {
281 FcPatternGetInteger( font, FC_INDEX, 0, &aFaceIndex );
282
283 fontName = wxString::FromUTF8( (char*) family );
284
285 if( FcPatternGetString( font, FC_STYLE, 0, &style ) == FcResultMatch )
286 {
287 styleStr = wxString::FromUTF8( (char*) style );
288
289 if( !styleStr.IsEmpty() )
290 {
291 styleStr.Replace( ' ', ':' );
292 fontName += ':' + styleStr;
293 }
294 }
295
296 bool has_bold = false;
297 bool has_ital = false;
298 wxString lower_style = styleStr.Lower();
299
300 if( lower_style.Contains( wxS( "thin" ) )
301 || lower_style.Contains( wxS( "light" ) ) // catches ultra & extra light
302 || lower_style.Contains( wxS( "regular" ) )
303 || lower_style.Contains( wxS( "roman" ) )
304 || lower_style.Contains( wxS( "book" ) ) )
305 {
306 has_bold = false;
307 }
308 else if( lower_style.Contains( wxS( "medium" ) )
309 || lower_style.Contains( wxS( "semibold" ) )
310 || lower_style.Contains( wxS( "demibold" ) ) )
311 {
312 has_bold = aBold;
313 }
314 else if( lower_style.Contains( wxS( "bold" ) ) // also catches ultrabold
315 || lower_style.Contains( wxS( "heavy" ) )
316 || lower_style.Contains( wxS( "black" ) ) // also catches extrablack
317 || lower_style.Contains( wxS( "thick" ) )
318 || lower_style.Contains( wxS( "dark" ) ) )
319 {
320 has_bold = true;
321 }
322
323 if( lower_style.Contains( wxS( "italic" ) )
324 || lower_style.Contains( wxS( "oblique" ) )
325 || lower_style.Contains( wxS( "slant" ) ) )
326 {
327 has_ital = true;
328 }
329
330 for( auto const& [key, val] : famStrings )
331 {
332 wxString searchFont;
333 searchFont = wxString::FromUTF8( (char*) val.data() );
334
335 if( searchFont.Lower().StartsWith( aFontName.Lower() ) )
336 {
337 familyMatched = true;
338
339 if( ( aBold != has_bold ) || ( aItalic != has_ital ) )
341 else
342 retval = FF_RESULT::FF_OK;
343
344 break;
345 }
346 }
347
348 // Fallback families need synthetic styles just as exact family matches do
349 if( ( aBold && !has_bold ) && ( aItalic && !has_ital ) )
351 else if( aBold && !has_bold )
353 else if( aItalic && !has_ital )
355 }
356 }
357
358 FcPatternDestroy( font );
359 }
360
361 if( retval == FF_RESULT::FF_ERROR )
362 {
363 if( s_reporter )
364 s_reporter->Report( wxString::Format( _( "Error loading font '%s'." ), qualifiedFontName ) );
365 }
366 else if( retval == FF_RESULT::FF_SUBSTITUTE || !familyMatched )
367 {
368 fontName.Replace( ':', ' ' );
369
370 // If we missed a case but the matching found the original font name, then we are
371 // not substituting
372 if( fontName.CmpNoCase( qualifiedFontName ) == 0 )
373 {
374 if( retval == FF_RESULT::FF_SUBSTITUTE )
375 retval = FF_RESULT::FF_OK;
376 }
377 else if( s_reporter )
378 {
379 s_reporter->Report( wxString::Format( _( "Font '%s' not found; substituting '%s'." ),
380 qualifiedFontName,
381 fontName ) );
382 }
383 }
384
385 FcPatternDestroy( pat );
386 return retval;
387}
388
389
390void FONTCONFIG::ListFonts( std::vector<std::string>& aFonts, const std::string& aDesiredLang,
391 const std::vector<wxString>* aEmbeddedFiles, bool aForce )
392{
393 if( !g_fcInitSuccess )
394 return;
395
396 // be sure to cache bust if the language changed
397 if( m_fontInfoCache.empty() || m_fontCacheLastLang != aDesiredLang || aForce )
398 {
399 FcConfig* config = FcConfigGetCurrent();
400
401 if( aEmbeddedFiles )
402 {
403 for( const wxString& file : *aEmbeddedFiles )
404 FcConfigAppFontAddFile( config, (const FcChar8*) file.c_str().AsChar() );
405 }
406
407 FcPattern* pat = FcPatternCreate();
408 FcObjectSet* os = FcObjectSetBuild( FC_FAMILY, FC_FAMILYLANG, FC_STYLE, FC_LANG, FC_FILE, FC_OUTLINE, nullptr );
409 FcFontSet* fs = FcFontList( config, pat, os );
410
411 for( int i = 0; fs && i < fs->nfont; ++i )
412 {
413 FcPattern* font = fs->fonts[i];
414 FcChar8* file;
415 FcChar8* style;
416 FcLangSet* langSet;
417 FcBool outline;
418
419 if( FcPatternGetString( font, FC_FILE, 0, &file ) == FcResultMatch
420 && FcPatternGetString( font, FC_STYLE, 0, &style ) == FcResultMatch
421 && FcPatternGetLangSet( font, FC_LANG, 0, &langSet ) == FcResultMatch
422 && FcPatternGetBool( font, FC_OUTLINE, 0, &outline ) == FcResultMatch )
423 {
424 if( !outline )
425 continue;
426
427 FONTCONFIG_PAT patHolder{ font };
428 std::string theFamily = getFamilyStringByLang( patHolder, From_UTF8( aDesiredLang.c_str() ) );
429
430#ifdef __WXMAC__
431 // On Mac (at least) some of the font names are in their own language. If
432 // the OS doesn't support this language then we get a bunch of garbage names
433 // in the font menu.
434 //
435 // GTK, on the other hand, doesn't appear to support wxLocale::IsAvailable(),
436 // so we can't run these checks.
437
438 static std::map<wxString, bool> availableLanguages;
439
440 FcStrSet* langStrSet = FcLangSetGetLangs( langSet );
441 FcStrList* langStrList = FcStrListCreate( langStrSet );
442 FcChar8* langStr = FcStrListNext( langStrList );
443 bool langSupported = false;
444
445 if( !langStr )
446 {
447 // Symbol fonts (Wingdings, etc.) have no language
448 langSupported = true;
449 }
450 else while( langStr )
451 {
452 wxString langWxStr( reinterpret_cast<char *>( langStr ) );
453
454 if( availableLanguages.find( langWxStr ) == availableLanguages.end() )
455 {
456 const wxLanguageInfo* langInfo = wxLocale::FindLanguageInfo( langWxStr );
457 bool available = langInfo && wxLocale::IsAvailable( langInfo->Language );
458
459 availableLanguages[ langWxStr ] = available;
460 }
461
462 if( availableLanguages[ langWxStr ] )
463 {
464 langSupported = true;
465 break;
466 }
467 else
468 {
469 wxLogTrace( traceFonts, wxS( "Font '%s' language '%s' not supported by OS." ),
470 theFamily, langWxStr );
471 }
472
473 langStr = FcStrListNext( langStrList );
474 }
475
476 FcStrListDone( langStrList );
477 FcStrSetDestroy( langStrSet );
478
479 if( !langSupported )
480 continue;
481#endif
482
483 std::string theFile( reinterpret_cast<char *>( file ) );
484 std::string theStyle( reinterpret_cast<char *>( style ) );
485 FONTINFO fontInfo( std::move( theFile ), std::move( theStyle ), theFamily );
486
487 if( theFamily.length() > 0 && theFamily.front() == '.' )
488 continue;
489
490 std::map<std::string, FONTINFO>::iterator it = m_fontInfoCache.find( theFamily );
491
492 if( it == m_fontInfoCache.end() )
493 m_fontInfoCache.emplace( theFamily, fontInfo );
494 else
495 it->second.Children().push_back( fontInfo );
496 }
497 }
498
499 if( fs )
500 FcFontSetDestroy( fs );
501
502 m_fontCacheLastLang = aDesiredLang;
503 }
504
505 for( const std::pair<const std::string, FONTINFO>& entry : m_fontInfoCache )
506 aFonts.push_back( entry.second.Family() );
507}
static REPORTER & GetInstance()
Definition reporter.cpp:207
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:73
static REPORTER * s_reporter
Definition fontconfig.h:94
void getAllFamilyStrings(FONTCONFIG_PAT &aPat, std::unordered_map< std::string, std::string > &aFamStringMap)
Get a list of all family name strings mapped to lang.
static wxString Version()
static void SetReporter(REPORTER *aReporter)
Set the reporter to use for reporting font substitution warnings.
std::map< std::string, FONTINFO > m_fontInfoCache
Definition fontconfig.h:92
FF_RESULT FindFont(const wxString &aFontName, wxString &aFontFile, int &aFaceIndex, bool aBold, bool aItalic, const std::vector< wxString > *aEmbeddedFiles=nullptr)
Given a fully-qualified font name ("Times:Bold:Italic") find the closest matching font and return its...
std::string getFcString(FONTCONFIG_PAT &aPat, const char *aObj, int aIdx)
Wrapper of FcPatternGetString to return a std::string.
std::string getFamilyStringByLang(FONTCONFIG_PAT &APat, const wxString &aDesiredLang)
Get a family name based on desired language.
static REPORTER & GetReporter()
Get the current reporter used for font substitution warnings.
bool isLanguageMatch(const wxString &aSearchLang, const wxString &aSupportedLang)
Match two rfc 3306 language entries, used for when searching for matching family names.
void ListFonts(std::vector< std::string > &aFonts, const std::string &aDesiredLang, const std::vector< wxString > *aEmbeddedFiles=nullptr, bool aForce=false)
List the current available font families.
wxString m_fontCacheLastLang
Definition fontconfig.h:93
#define _(s)
static FONTCONFIG * g_config
FONTCONFIG * Fontconfig()
static void bootstrapFc()
This is simply a wrapper to call FcInit() with SEH for Windows.
static bool g_fcInitSuccess
static std::mutex g_fontConfigMutex
const wxChar *const traceFonts
Flag to enable locale debug output.
This file contains miscellaneous commonly used macros and functions.
wxString From_UTF8(const char *cstring)
void wxStringSplit(const wxString &aText, wxArrayString &aStrings, wxChar aSplitter)
Split aString to a string list separated at aSplitter.
A simple wrapper to avoid exporting fontconfig in the header.
VECTOR3I res
wxLogTrace helper definitions.