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 along
19 * with this program. If not, see <http://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
60{
61};
62
63
65{
66 std::lock_guard lock( g_fontConfigMutex );
67 s_reporter = aReporter;
68}
69
70
79static void bootstrapFc()
80{
81#if defined( _MSC_VER )
82 __try
83 {
84#endif
85 FcInit();
86 g_fcInitSuccess = true;
87#if defined( _MSC_VER )
88 }
89 __except( GetExceptionCode() == STATUS_IN_PAGE_ERROR ? EXCEPTION_EXECUTE_HANDLER
90 : EXCEPTION_CONTINUE_SEARCH )
91 {
92 g_fcInitSuccess = false;
93
94 // We have documented cases that fontconfig while trying to cache fonts
95 // ends up using freetype to try and get font info
96 // freetype itself reads fonts through memory mapping instead of normal file APIs
97 // there are crashes reading fonts sometimes as a result that return STATUS_IN_PAGE_ERROR
98 }
99#endif
100}
101
102
104{
105 if( !g_config )
106 {
107 bootstrapFc();
108 g_config = new FONTCONFIG();
109 }
110
111 return g_config;
112}
113
114
115bool FONTCONFIG::isLanguageMatch( const wxString& aSearchLang, const wxString& aSupportedLang )
116{
117 if( aSearchLang.Lower() == aSupportedLang.Lower() )
118 return true;
119
120 if( aSupportedLang.empty() )
121 return false;
122
123 if( aSearchLang.empty() )
124 return false;
125
126 wxArrayString supportedLangBits;
127 wxStringSplit( aSupportedLang.Lower(), supportedLangBits, wxS( '-' ) );
128
129 wxArrayString searhcLangBits;
130 wxStringSplit( aSearchLang.Lower(), searhcLangBits, wxS( '-' ) );
131
132 // if either side of the comparison have only one section, then its a broad match but fine
133 // i.e. the haystack is declaring broad support or the search language is broad
134 if( searhcLangBits.size() == 1 || supportedLangBits.size() == 1 )
135 {
136 return searhcLangBits[0] == supportedLangBits[0];
137 }
138
139 // the full two part comparison should have passed the initial shortcut
140
141 return false;
142}
143
144
145std::string FONTCONFIG::getFcString( FONTCONFIG_PAT& aPat, const char* aObj, int aIdx )
146{
147 FcChar8* str;
148 std::string res;
149
150 if( FcPatternGetString( aPat.pat, aObj, aIdx, &str ) == FcResultMatch )
151 res = std::string( reinterpret_cast<char*>( str ) );
152
153 return res;
154}
155
156
158 std::unordered_map<std::string, std::string>& aFamStringMap )
159{
160 std::string famLang;
161 std::string fam;
162
163 int langIdx = 0;
164
165 do
166 {
167 famLang = getFcString( aPat, FC_FAMILYLANG, langIdx );
168
169 if( famLang.empty() && langIdx != 0 )
170 {
171 break;
172 }
173 else
174 {
175 fam = getFcString( aPat, FC_FAMILY, langIdx );
176 aFamStringMap.insert_or_assign( famLang, fam );
177 }
178 } while( langIdx++ < std::numeric_limits<
179 int8_t>::max() ); //arbitrary to avoid getting stuck for any reason
180}
181
182
183std::string FONTCONFIG::getFamilyStringByLang( FONTCONFIG_PAT& aPat, const wxString& aDesiredLang )
184{
185 std::unordered_map<std::string, std::string> famStrings;
186 getAllFamilyStrings( aPat, famStrings );
187
188 if( famStrings.empty() )
189 return "";
190
191 for( auto const& [key, val] : famStrings )
192 {
193 if( isLanguageMatch( aDesiredLang, From_UTF8( key.c_str() ) ) )
194 {
195 return val;
196 }
197 }
198
199 // fall back to the first and maybe only available name
200 // most fonts by review don't even bother declaring more than one font family name
201 // and they don't even bother declare the language tag either, they just leave it blank
202 return famStrings.begin()->second;
203}
204
205
206FONTCONFIG::FF_RESULT FONTCONFIG::FindFont( const wxString& aFontName, wxString& aFontFile,
207 int& aFaceIndex, bool aBold, bool aItalic,
208 const std::vector<wxString>* aEmbeddedFiles )
209{
211
212 if( !g_fcInitSuccess )
213 return retval;
214
215 // If the original font name contains any of these, then it is bold, regardless
216 // of whether we are looking for bold or not
217 if( aFontName.Lower().Contains( wxS( "bold" ) ) // also catches ultrabold
218 || aFontName.Lower().Contains( wxS( "heavy" ) )
219 || aFontName.Lower().Contains( wxS( "black" ) ) // also catches extrablack
220 || aFontName.Lower().Contains( wxS( "thick" ) )
221 || aFontName.Lower().Contains( wxS( "dark" ) ) )
222 {
223 aBold = true;
224 }
225
226 FcConfig* config = FcConfigGetCurrent();
227
228 if( aEmbeddedFiles )
229 {
230 for( const auto& file : *aEmbeddedFiles )
231 {
232 FcConfigAppFontAddFile( config, (const FcChar8*) file.c_str().AsChar() );
233 }
234 }
235
236 wxString qualifiedFontName = aFontName;
237
238 wxScopedCharBuffer const fcBuffer = qualifiedFontName.ToUTF8();
239
240 FcPattern* pat = FcPatternCreate();
241
242 if( aBold )
243 FcPatternAddString( pat, FC_STYLE, (const FcChar8*) "Bold" );
244
245 if( aItalic )
246 FcPatternAddString( pat, FC_STYLE, (const FcChar8*) "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
258 if( font )
259 {
260 FcChar8* file = nullptr;
261
262 if( FcPatternGetString( font, FC_FILE, 0, &file ) == FcResultMatch )
263 {
264 aFontFile = wxString::FromUTF8( (char*) file );
265 aFaceIndex = 0;
266
267 wxString styleStr;
268 FcChar8* family = nullptr;
269 FcChar8* style = nullptr;
270
272
273 std::unordered_map<std::string, std::string> famStrings;
274 FONTCONFIG_PAT patHolder{ font };
275
276 getAllFamilyStrings( patHolder, famStrings );
277
278 if( FcPatternGetString( font, FC_FAMILY, 0, &family ) == FcResultMatch )
279 {
280 FcPatternGetInteger( font, FC_INDEX, 0, &aFaceIndex );
281
282 fontName = wxString::FromUTF8( (char*) family );
283
284 if( FcPatternGetString( font, FC_STYLE, 0, &style ) == FcResultMatch )
285 {
286 styleStr = wxString::FromUTF8( (char*) style );
287
288 if( !styleStr.IsEmpty() )
289 {
290 styleStr.Replace( ' ', ':' );
291 fontName += ':' + styleStr;
292 }
293 }
294
295 bool has_bold = false;
296 bool has_ital = false;
297 wxString lower_style = styleStr.Lower();
298
299 if( lower_style.Contains( wxS( "thin" ) )
300 || lower_style.Contains( wxS( "light" ) ) // catches ultra & extra light
301 || lower_style.Contains( wxS( "regular" ) )
302 || lower_style.Contains( wxS( "roman" ) )
303 || lower_style.Contains( wxS( "book" ) ) )
304 {
305 has_bold = false;
306 }
307 else if( lower_style.Contains( wxS( "medium" ) )
308 || lower_style.Contains( wxS( "semibold" ) )
309 || lower_style.Contains( wxS( "demibold" ) ) )
310 {
311 has_bold = aBold;
312 }
313 else if( lower_style.Contains( wxS( "bold" ) ) // also catches ultrabold
314 || lower_style.Contains( wxS( "heavy" ) )
315 || lower_style.Contains( wxS( "black" ) ) // also catches extrablack
316 || lower_style.Contains( wxS( "thick" ) )
317 || lower_style.Contains( wxS( "dark" ) ) )
318 {
319 has_bold = true;
320 }
321
322 if( lower_style.Contains( wxS( "italic" ) )
323 || lower_style.Contains( wxS( "oblique" ) )
324 || lower_style.Contains( wxS( "slant" ) ) )
325 {
326 has_ital = true;
327 }
328
329 for( auto const& [key, val] : famStrings )
330 {
331 wxString searchFont;
332 searchFont = wxString::FromUTF8( (char*) val.data() );
333
334 if( searchFont.Lower().StartsWith( aFontName.Lower() ) )
335 {
336 if( ( aBold && !has_bold ) && ( aItalic && !has_ital ) )
338 else if( aBold && !has_bold )
340 else if( aItalic && !has_ital )
342 else if( ( aBold != has_bold ) || ( aItalic != has_ital ) )
344 else
345 retval = FF_RESULT::FF_OK;
346
347 break;
348 }
349 }
350 }
351 }
352
353 FcPatternDestroy( font );
354 }
355
356 if( retval == FF_RESULT::FF_ERROR )
357 {
358 if( s_reporter )
359 s_reporter->Report( wxString::Format( _( "Error loading font '%s'." ),
360 qualifiedFontName ) );
361 }
362 else if( retval == FF_RESULT::FF_SUBSTITUTE )
363 {
364 fontName.Replace( ':', ' ' );
365
366 // If we missed a case but the matching found the original font name, then we are
367 // not substituting
368 if( fontName.CmpNoCase( qualifiedFontName ) == 0 )
369 retval = FF_RESULT::FF_OK;
370 else if( s_reporter )
371 s_reporter->Report( wxString::Format( _( "Font '%s' not found; substituting '%s'." ),
372 qualifiedFontName, fontName ) );
373 }
374
375 FcPatternDestroy( pat );
376 return retval;
377}
378
379
380void FONTCONFIG::ListFonts( std::vector<std::string>& aFonts, const std::string& aDesiredLang,
381 const std::vector<wxString>* aEmbeddedFiles, bool aForce )
382{
383 if( !g_fcInitSuccess )
384 return;
385
386 // be sure to cache bust if the language changed
387 if( m_fontInfoCache.empty() || m_fontCacheLastLang != aDesiredLang || aForce )
388 {
389 FcConfig* config = FcConfigGetCurrent();
390
391 if( aEmbeddedFiles )
392 {
393 for( const auto& file : *aEmbeddedFiles )
394 {
395 FcConfigAppFontAddFile( config, (const FcChar8*) file.c_str().AsChar() );
396 }
397 }
398
399 FcPattern* pat = FcPatternCreate();
400 FcObjectSet* os = FcObjectSetBuild( FC_FAMILY, FC_FAMILYLANG, FC_STYLE, FC_LANG, FC_FILE,
401 FC_OUTLINE, nullptr );
402 FcFontSet* fs = FcFontList( config, pat, os );
403
404 for( int i = 0; fs && i < fs->nfont; ++i )
405 {
406 FcPattern* font = fs->fonts[i];
407 FcChar8* file;
408 FcChar8* style;
409 FcLangSet* langSet;
410 FcBool outline;
411
412 if( FcPatternGetString( font, FC_FILE, 0, &file ) == FcResultMatch
413 && FcPatternGetString( font, FC_STYLE, 0, &style ) == FcResultMatch
414 && FcPatternGetLangSet( font, FC_LANG, 0, &langSet ) == FcResultMatch
415 && FcPatternGetBool( font, FC_OUTLINE, 0, &outline ) == FcResultMatch )
416 {
417 if( !outline )
418 continue;
419
420 FONTCONFIG_PAT patHolder{ font };
421 std::string theFamily =
422 getFamilyStringByLang( patHolder, From_UTF8( aDesiredLang.c_str() ) );
423
424#ifdef __WXMAC__
425 // On Mac (at least) some of the font names are in their own language. If
426 // the OS doesn't support this language then we get a bunch of garbage names
427 // in the font menu.
428 //
429 // GTK, on the other hand, doesn't appear to support wxLocale::IsAvailable(),
430 // so we can't run these checks.
431
432 static std::map<wxString, bool> availableLanguages;
433
434 FcStrSet* langStrSet = FcLangSetGetLangs( langSet );
435 FcStrList* langStrList = FcStrListCreate( langStrSet );
436 FcChar8* langStr = FcStrListNext( langStrList );
437 bool langSupported = false;
438
439 if( !langStr )
440 {
441 // Symbol fonts (Wingdings, etc.) have no language
442 langSupported = true;
443 }
444 else while( langStr )
445 {
446 wxString langWxStr( reinterpret_cast<char *>( langStr ) );
447
448 if( availableLanguages.find( langWxStr ) == availableLanguages.end() )
449 {
450 const wxLanguageInfo* langInfo = wxLocale::FindLanguageInfo( langWxStr );
451 bool available = langInfo && wxLocale::IsAvailable( langInfo->Language );
452
453 availableLanguages[ langWxStr ] = available;
454 }
455
456 if( availableLanguages[ langWxStr ] )
457 {
458 langSupported = true;
459 break;
460 }
461 else
462 {
463 wxLogTrace( traceFonts,
464 wxS( "Font '%s' language '%s' not supported by OS." ),
465 theFamily, langWxStr );
466 }
467
468 langStr = FcStrListNext( langStrList );
469 }
470
471 FcStrListDone( langStrList );
472 FcStrSetDestroy( langStrSet );
473
474 if( !langSupported )
475 continue;
476#endif
477
478 std::string theFile( reinterpret_cast<char *>( file ) );
479 std::string theStyle( reinterpret_cast<char *>( style ) );
480 FONTINFO fontInfo( std::move( theFile ), std::move( theStyle ), theFamily );
481
482 if( theFamily.length() > 0 && theFamily.front() == '.' )
483 continue;
484
485 std::map<std::string, FONTINFO>::iterator it = m_fontInfoCache.find( theFamily );
486
487 if( it == m_fontInfoCache.end() )
488 m_fontInfoCache.emplace( theFamily, fontInfo );
489 else
490 it->second.Children().push_back( fontInfo );
491 }
492 }
493
494 if( fs )
495 FcFontSetDestroy( fs );
496
497 m_fontCacheLastLang = aDesiredLang;
498 }
499
500 for( const std::pair<const std::string, FONTINFO>& entry : m_fontInfoCache )
501 aFonts.push_back( entry.second.Family() );
502}
503
A pure virtual class used to derive REPORTER objects from.
Definition: reporter.h:73
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)
Report a string with a given severity.
Definition: reporter.h:102
static REPORTER * s_reporter
Definition: fontconfig.h:87
void getAllFamilyStrings(FONTCONFIG_PAT &aPat, std::unordered_map< std::string, std::string > &aFamStringMap)
Get a list of all family name strings mapped to lang.
Definition: fontconfig.cpp:157
static wxString Version()
Definition: fontconfig.cpp:53
static void SetReporter(REPORTER *aReporter)
Set the reporter to use for reporting font substitution warnings.
Definition: fontconfig.cpp:64
std::map< std::string, FONTINFO > m_fontInfoCache
Definition: fontconfig.h:85
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...
Definition: fontconfig.cpp:206
std::string getFcString(FONTCONFIG_PAT &aPat, const char *aObj, int aIdx)
Wrapper of FcPatternGetString to return a std::string.
Definition: fontconfig.cpp:145
std::string getFamilyStringByLang(FONTCONFIG_PAT &APat, const wxString &aDesiredLang)
Get a family name based on desired language.
Definition: fontconfig.cpp:183
bool isLanguageMatch(const wxString &aSearchLang, const wxString &aSupportedLang)
Match two rfc 3306 language entries, used for when searching for matching family names.
Definition: fontconfig.cpp:115
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.
Definition: fontconfig.cpp:380
wxString m_fontCacheLastLang
Definition: fontconfig.h:86
#define _(s)
static FONTCONFIG * g_config
Definition: fontconfig.cpp:38
FONTCONFIG * Fontconfig()
Definition: fontconfig.cpp:103
static void bootstrapFc()
This is simply a wrapper to call FcInit() with SEH for Windows.
Definition: fontconfig.cpp:79
static bool g_fcInitSuccess
Definition: fontconfig.cpp:39
static std::mutex g_fontConfigMutex
Definition: fontconfig.cpp:42
const wxChar *const traceFonts
Flag to enable locale debug output.
This file contains miscellaneous commonly used macros and functions.
static WX_STRING_REPORTER s_reporter
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.
Definition: fontconfig.cpp:48
VECTOR3I res
wxLogTrace helper definitions.