Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qcoretextfontdatabase.mm
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:data-parser
4
5#include "qglobal.h"
6
7#include <sys/param.h>
8
9#if defined(Q_OS_MACOS)
10#import <AppKit/AppKit.h>
11#import <IOKit/graphics/IOGraphicsLib.h>
12#elif defined(QT_PLATFORM_UIKIT)
13#import <UIKit/UIFont.h>
14#endif
15
16#include <QtCore/qelapsedtimer.h>
17#include <QtCore/private/qcore_mac_p.h>
18
21#if QT_CONFIG(settings)
22#include <QtCore/QSettings>
23#endif
24#include <QtCore/QtEndian>
25#ifndef QT_NO_FREETYPE
26#include <QtGui/private/qfontengine_ft_p.h>
27#endif
28
29#include <QtGui/qpa/qwindowsysteminterface.h>
30
32
33using namespace Qt::StringLiterals;
34
35QT_IMPL_METATYPE_EXTERN_TAGGED(QCFType<CGFontRef>, QCFType_CGFontRef)
36QT_IMPL_METATYPE_EXTERN_TAGGED(QCFType<CFURLRef>, QCFType_CFURLRef)
37
38// this could become a list of all languages used for each writing
39// system, instead of using the single most common language.
40static const char languageForWritingSystem[][8] = {
41 "", // Any
42 "en", // Latin
43 "el", // Greek
44 "ru", // Cyrillic
45 "hy", // Armenian
46 "he", // Hebrew
47 "ar", // Arabic
48 "syr", // Syriac
49 "div", // Thaana
50 "hi", // Devanagari
51 "bn", // Bengali
52 "pa", // Gurmukhi
53 "gu", // Gujarati
54 "or", // Oriya
55 "ta", // Tamil
56 "te", // Telugu
57 "kn", // Kannada
58 "ml", // Malayalam
59 "si", // Sinhala
60 "th", // Thai
61 "lo", // Lao
62 "bo", // Tibetan
63 "my", // Myanmar
64 "ka", // Georgian
65 "km", // Khmer
66 "zh-Hans", // SimplifiedChinese
67 "zh-Hant", // TraditionalChinese
68 "ja", // Japanese
69 "ko", // Korean
70 "vi", // Vietnamese
71 "", // Symbol
72 "sga", // Ogham
73 "non", // Runic
74 "man" // N'Ko
75};
76enum { LanguageCount = sizeof languageForWritingSystem / sizeof *languageForWritingSystem };
77
78QCoreTextFontDatabase::QCoreTextFontDatabase()
79 : m_hasPopulatedAliases(false)
80{
81#if defined(Q_OS_MACOS)
82 m_fontSetObserver = QMacNotificationObserver(nil, NSFontSetChangedNotification, [] {
83 qCDebug(lcQpaFonts) << "Fonts have changed";
84 QPlatformFontDatabase::repopulateFontDatabase();
85 });
86#endif
87}
88
89QCoreTextFontDatabase::~QCoreTextFontDatabase()
90{
91 qDeleteAll(m_themeFonts);
92}
93
94CTFontDescriptorRef descriptorForFamily(const QString &familyName)
95{
96 return CTFontDescriptorCreateWithAttributes(CFDictionaryRef(@{
97 (id)kCTFontFamilyNameAttribute: familyName.toNSString()
98 }));
99}
100void QCoreTextFontDatabase::populateFontDatabase()
101{
102 QMacAutoReleasePool pool;
103
104 qCDebug(lcQpaFonts) << "Populating font database...";
105 QElapsedTimer elapsed;
106 if (lcQpaFonts().isDebugEnabled())
107 elapsed.start();
108
109 QCFType<CFArrayRef> familyNames = CTFontManagerCopyAvailableFontFamilyNames();
110 for (NSString *familyName in familyNames.as<const NSArray *>())
111 QPlatformFontDatabase::registerFontFamily(QString::fromNSString(familyName));
112
113 // Some fonts has special handling since macOS Catalina: It is available
114 // on the platform, so that it may be used by applications directly, but does not
115 // get enumerated. Since there are no alternatives, we hardcode it.
116 if (QOperatingSystemVersion::current() >= QOperatingSystemVersion::MacOSCatalina
117 && !qEnvironmentVariableIsSet("QT_NO_HARDCODED_FALLBACK_FONTS")) {
118 m_hardcodedFallbackFonts[QChar::Script_Adlam] = QStringLiteral("Noto Sans Adlam");
119 m_hardcodedFallbackFonts[QChar::Script_Ahom] = QStringLiteral("Noto Serif Ahom");
120 m_hardcodedFallbackFonts[QChar::Script_Avestan] = QStringLiteral("Noto Sans Avestan");
121 m_hardcodedFallbackFonts[QChar::Script_Balinese] = QStringLiteral("Noto Serif Balinese");
122 m_hardcodedFallbackFonts[QChar::Script_Bamum] = QStringLiteral("Noto Sans Bamum");
123 m_hardcodedFallbackFonts[QChar::Script_BassaVah] = QStringLiteral("Noto Sans Bassa Vah");
124 m_hardcodedFallbackFonts[QChar::Script_Batak] = QStringLiteral("Noto Sans Batak");
125 m_hardcodedFallbackFonts[QChar::Script_Bhaiksuki] = QStringLiteral("Noto Sans Bhaiksuki");
126 m_hardcodedFallbackFonts[QChar::Script_Brahmi] = QStringLiteral("Noto Sans Brahmi");
127 m_hardcodedFallbackFonts[QChar::Script_Buginese] = QStringLiteral("Noto Sans Buginese");
128 m_hardcodedFallbackFonts[QChar::Script_Buhid] = QStringLiteral("Noto Sans Buhid");
129 m_hardcodedFallbackFonts[QChar::Script_Carian] = QStringLiteral("Noto Sans Carian");
130 m_hardcodedFallbackFonts[QChar::Script_CaucasianAlbanian] = QStringLiteral("Noto Sans Caucasian Albanian");
131 m_hardcodedFallbackFonts[QChar::Script_Chakma] = QStringLiteral("Noto Sans Chakma");
132 m_hardcodedFallbackFonts[QChar::Script_Cham] = QStringLiteral("Noto Sans Cham");
133 m_hardcodedFallbackFonts[QChar::Script_Coptic] = QStringLiteral("Noto Sans Coptic");
134 m_hardcodedFallbackFonts[QChar::Script_Cuneiform] = QStringLiteral("Noto Sans Cuneiform");
135 m_hardcodedFallbackFonts[QChar::Script_Cypriot] = QStringLiteral("Noto Sans Cypriot");
136 m_hardcodedFallbackFonts[QChar::Script_Duployan] = QStringLiteral("Noto Sans Duployan");
137 m_hardcodedFallbackFonts[QChar::Script_EgyptianHieroglyphs] = QStringLiteral("Noto Sans Egyptian Hieroglyphs");
138 m_hardcodedFallbackFonts[QChar::Script_Elbasan] = QStringLiteral("Noto Sans Elbasan");
139 m_hardcodedFallbackFonts[QChar::Script_Glagolitic] = QStringLiteral("Noto Sans Glagolitic");
140 m_hardcodedFallbackFonts[QChar::Script_Gothic] = QStringLiteral("Noto Sans Gothic");
141 m_hardcodedFallbackFonts[QChar::Script_HanifiRohingya] = QStringLiteral("Noto Sans Hanifi Rohingya");
142 m_hardcodedFallbackFonts[QChar::Script_Hanunoo] = QStringLiteral("Noto Sans Hanunoo");
143 m_hardcodedFallbackFonts[QChar::Script_Hatran] = QStringLiteral("Noto Sans Hatran");
144 m_hardcodedFallbackFonts[QChar::Script_ImperialAramaic] = QStringLiteral("Noto Sans Imperial Aramaic");
145 m_hardcodedFallbackFonts[QChar::Script_InscriptionalPahlavi] = QStringLiteral("Noto Sans Inscriptional Pahlavi");
146 m_hardcodedFallbackFonts[QChar::Script_InscriptionalParthian] = QStringLiteral("Noto Sans Inscriptional Parthian");
147 m_hardcodedFallbackFonts[QChar::Script_Javanese] = QStringLiteral("Noto Sans Javanese");
148 m_hardcodedFallbackFonts[QChar::Script_Kaithi] = QStringLiteral("Noto Sans Kaithi");
149 m_hardcodedFallbackFonts[QChar::Script_KayahLi] = QStringLiteral("Noto Sans Kayah Li");
150 m_hardcodedFallbackFonts[QChar::Script_Kharoshthi] = QStringLiteral("Noto Sans Kharoshthi");
151 m_hardcodedFallbackFonts[QChar::Script_Khojki] = QStringLiteral("Noto Sans Khojki");
152 m_hardcodedFallbackFonts[QChar::Script_Khudawadi] = QStringLiteral("Noto Sans Khudawadi");
153 m_hardcodedFallbackFonts[QChar::Script_Lepcha] = QStringLiteral("Noto Sans Lepcha");
154 m_hardcodedFallbackFonts[QChar::Script_Limbu] = QStringLiteral("Noto Sans Limbu");
155 m_hardcodedFallbackFonts[QChar::Script_LinearA] = QStringLiteral("Noto Sans Linear A");
156 m_hardcodedFallbackFonts[QChar::Script_LinearB] = QStringLiteral("Noto Sans Linear B");
157 m_hardcodedFallbackFonts[QChar::Script_Lisu] = QStringLiteral("Noto Sans Lisu");
158 m_hardcodedFallbackFonts[QChar::Script_Lycian] = QStringLiteral("Noto Sans Lycian");
159 m_hardcodedFallbackFonts[QChar::Script_Lydian] = QStringLiteral("Noto Sans Lydian");
160 m_hardcodedFallbackFonts[QChar::Script_Mahajani] = QStringLiteral("Noto Sans Mahajani");
161 m_hardcodedFallbackFonts[QChar::Script_Mandaic] = QStringLiteral("Noto Sans Mandaic");
162 m_hardcodedFallbackFonts[QChar::Script_Manichaean] = QStringLiteral("Noto Sans Manichaean");
163 m_hardcodedFallbackFonts[QChar::Script_Marchen] = QStringLiteral("Noto Sans Marchen");
164 m_hardcodedFallbackFonts[QChar::Script_MendeKikakui] = QStringLiteral("Noto Sans Mende Kikakui");
165 m_hardcodedFallbackFonts[QChar::Script_MeroiticCursive] = QStringLiteral("Noto Sans Meroitic");
166 m_hardcodedFallbackFonts[QChar::Script_MeroiticHieroglyphs] = QStringLiteral("Noto Sans Meroitic");
167 m_hardcodedFallbackFonts[QChar::Script_Miao] = QStringLiteral("Noto Sans Miao");
168 m_hardcodedFallbackFonts[QChar::Script_Modi] = QStringLiteral("Noto Sans Modi");
169 m_hardcodedFallbackFonts[QChar::Script_Mongolian] = QStringLiteral("Noto Sans Mongolian");
170 m_hardcodedFallbackFonts[QChar::Script_Mro] = QStringLiteral("Noto Sans Mro");
171 m_hardcodedFallbackFonts[QChar::Script_MeeteiMayek] = QStringLiteral("Noto Sans Meetei Mayek");
172 m_hardcodedFallbackFonts[QChar::Script_Multani] = QStringLiteral("Noto Sans Multani");
173 m_hardcodedFallbackFonts[QChar::Script_Nabataean] = QStringLiteral("Noto Sans Nabataean");
174 m_hardcodedFallbackFonts[QChar::Script_Newa] = QStringLiteral("Noto Sans Newa");
175 m_hardcodedFallbackFonts[QChar::Script_NewTaiLue] = QStringLiteral("Noto Sans New Tai Lue");
176 m_hardcodedFallbackFonts[QChar::Script_Nko] = QStringLiteral("Noto Sans Nko");
177 m_hardcodedFallbackFonts[QChar::Script_OlChiki] = QStringLiteral("Noto Sans Ol Chiki");
178 m_hardcodedFallbackFonts[QChar::Script_OldHungarian] = QStringLiteral("Noto Sans Old Hungarian");
179 m_hardcodedFallbackFonts[QChar::Script_OldItalic] = QStringLiteral("Noto Sans Old Italic");
180 m_hardcodedFallbackFonts[QChar::Script_OldNorthArabian] = QStringLiteral("Noto Sans Old North Arabian");
181 m_hardcodedFallbackFonts[QChar::Script_OldPermic] = QStringLiteral("Noto Sans Old Permic");
182 m_hardcodedFallbackFonts[QChar::Script_OldPersian] = QStringLiteral("Noto Sans Old Persian");
183 m_hardcodedFallbackFonts[QChar::Script_OldSouthArabian] = QStringLiteral("Noto Sans Old South Arabian");
184 m_hardcodedFallbackFonts[QChar::Script_OldTurkic] = QStringLiteral("Noto Sans Old Turkic");
185 m_hardcodedFallbackFonts[QChar::Script_Osage] = QStringLiteral("Noto Sans Osage");
186 m_hardcodedFallbackFonts[QChar::Script_Osmanya] = QStringLiteral("Noto Sans Osmanya");
187 m_hardcodedFallbackFonts[QChar::Script_PahawhHmong] = QStringLiteral("Noto Sans Pahawh Hmong");
188 m_hardcodedFallbackFonts[QChar::Script_Palmyrene] = QStringLiteral("Noto Sans Palmyrene");
189 m_hardcodedFallbackFonts[QChar::Script_PauCinHau] = QStringLiteral("Noto Sans Pau Cin Hau");
190 m_hardcodedFallbackFonts[QChar::Script_PhagsPa] = QStringLiteral("Noto Sans PhagsPa");
191 m_hardcodedFallbackFonts[QChar::Script_Phoenician] = QStringLiteral("Noto Sans Phoenician");
192 m_hardcodedFallbackFonts[QChar::Script_PsalterPahlavi] = QStringLiteral("Noto Sans Psalter Pahlavi");
193 m_hardcodedFallbackFonts[QChar::Script_Rejang] = QStringLiteral("Noto Sans Rejang");
194 m_hardcodedFallbackFonts[QChar::Script_Samaritan] = QStringLiteral("Noto Sans Samaritan");
195 m_hardcodedFallbackFonts[QChar::Script_Saurashtra] = QStringLiteral("Noto Sans Saurashtra");
196 m_hardcodedFallbackFonts[QChar::Script_Sharada] = QStringLiteral("Noto Sans Sharada");
197 m_hardcodedFallbackFonts[QChar::Script_Siddham] = QStringLiteral("Noto Sans Siddham");
198 m_hardcodedFallbackFonts[QChar::Script_SoraSompeng] = QStringLiteral("Noto Sans Sora Sompeng");
199 m_hardcodedFallbackFonts[QChar::Script_Sundanese] = QStringLiteral("Noto Sans Sundanese");
200 m_hardcodedFallbackFonts[QChar::Script_SylotiNagri] = QStringLiteral("Noto Sans Syloti Nagri");
201 m_hardcodedFallbackFonts[QChar::Script_Tagalog] = QStringLiteral("Noto Sans Tagalog");
202 m_hardcodedFallbackFonts[QChar::Script_Tagbanwa] = QStringLiteral("Noto Sans Tagbanwa");
203 m_hardcodedFallbackFonts[QChar::Script_Takri] = QStringLiteral("Noto Sans Takri");
204 m_hardcodedFallbackFonts[QChar::Script_TaiLe] = QStringLiteral("Noto Sans Tai Le");
205 m_hardcodedFallbackFonts[QChar::Script_TaiTham] = QStringLiteral("Noto Sans Tai Tham");
206 m_hardcodedFallbackFonts[QChar::Script_TaiViet] = QStringLiteral("Noto Sans Tai Viet");
207 m_hardcodedFallbackFonts[QChar::Script_Thaana] = QStringLiteral("Noto Sans Thaana");
208 m_hardcodedFallbackFonts[QChar::Script_Tifinagh] = QStringLiteral("Noto Sans Tifinagh");
209 m_hardcodedFallbackFonts[QChar::Script_Tirhuta] = QStringLiteral("Noto Sans Tirhuta");
210 m_hardcodedFallbackFonts[QChar::Script_Ugaritic] = QStringLiteral("Noto Sans Ugaritic");
211 m_hardcodedFallbackFonts[QChar::Script_Vai] = QStringLiteral("Noto Sans Vai");
212 m_hardcodedFallbackFonts[QChar::Script_WarangCiti] = QStringLiteral("Noto Sans Warang Citi");
213 m_hardcodedFallbackFonts[QChar::Script_Wancho] = QStringLiteral("Noto Sans Wancho");
214 m_hardcodedFallbackFonts[QChar::Script_Yi] = QStringLiteral("Noto Sans Yi");
215 }
216
217 qCDebug(lcQpaFonts) << "Populating available families took" << elapsed.restart() << "ms";
218
219 populateThemeFonts();
220
221 for (auto familyName : m_systemFontDescriptors.keys()) {
222 for (auto fontDescriptor : m_systemFontDescriptors.value(familyName))
223 populateFromDescriptor(fontDescriptor, familyName);
224 }
225
226 // The font database now has a reference to the original descriptors
227 m_systemFontDescriptors.clear();
228
229 qCDebug(lcQpaFonts) << "Populating system descriptors took" << elapsed.restart() << "ms";
230
231 Q_ASSERT(!m_hasPopulatedAliases);
232}
233
234bool QCoreTextFontDatabase::populateFamilyAliases(const QString &missingFamily)
235{
236#if defined(Q_OS_MACOS)
237 if (isFamilyPopulated(missingFamily)) {
238 // We got here because one of the other properties of the font mismatched,
239 // for example the style, so there's no point in populating font aliases.
240 return false;
241 }
242
243 if (m_hasPopulatedAliases)
244 return false;
245
246 // There's no API to go from a localized family name to its non-localized
247 // name, so we have to resort to enumerating all the available fonts and
248 // doing a reverse lookup.
249
250 qCDebug(lcQpaFonts) << "Populating family aliases...";
251 QElapsedTimer elapsed;
252 elapsed.start();
253
254 QString nonLocalizedMatch;
255 QCFType<CFArrayRef> familyNames = CTFontManagerCopyAvailableFontFamilyNames();
256 NSFontManager *fontManager = NSFontManager.sharedFontManager;
257 for (NSString *familyName in familyNames.as<const NSArray *>()) {
258 NSString *localizedFamilyName = [fontManager localizedNameForFamily:familyName face:nil];
259 if (![localizedFamilyName isEqual:familyName]) {
260 QString nonLocalizedFamily = QString::fromNSString(familyName);
261 QString localizedFamily = QString::fromNSString(localizedFamilyName);
262 QPlatformFontDatabase::registerAliasToFontFamily(nonLocalizedFamily, localizedFamily);
263 if (localizedFamily == missingFamily)
264 nonLocalizedMatch = nonLocalizedFamily;
265 }
266 }
267 m_hasPopulatedAliases = true;
268
269 if (lcQpaFonts().isWarningEnabled()) {
270 QString warningMessage;
271 QDebug msg(&warningMessage);
272
273 msg << "Populating font family aliases took" << elapsed.restart() << "ms.";
274 if (!nonLocalizedMatch.isNull())
275 msg << "Replace uses of" << missingFamily << "with its non-localized name" << nonLocalizedMatch;
276 else
277 msg << "Replace uses of missing font family" << missingFamily << "with one that exists";
278 msg << "to avoid this cost.";
279
280 qCWarning(lcQpaFonts) << qPrintable(warningMessage);
281 }
282
283 return true;
284#else
285 Q_UNUSED(missingFamily);
286 return false;
287#endif
288}
289
291{
292 return descriptorForFamily(QString::fromLatin1(familyName));
293}
294
295void QCoreTextFontDatabase::populateFamily(const QString &familyName)
296{
297 qCDebug(lcQpaFonts) << "Populating family" << familyName;
298
299 // A single family might match several different fonts with different styles.
300 // We need to add them all so that the font database has the full picture,
301 // as once a family has been populated we will not populate it again.
302 QCFType<CTFontDescriptorRef> familyDescriptor = descriptorForFamily(familyName);
303 QCFType<CFArrayRef> matchingFonts = CTFontDescriptorCreateMatchingFontDescriptors(familyDescriptor, nullptr);
304 if (!matchingFonts) {
305 qCWarning(lcQpaFonts) << "QCoreTextFontDatabase: Found no matching fonts for family" << familyName;
306 return;
307 }
308
309 const int numFonts = CFArrayGetCount(matchingFonts);
310 for (int i = 0; i < numFonts; ++i)
311 populateFromDescriptor(CTFontDescriptorRef(CFArrayGetValueAtIndex(matchingFonts, i)), familyName);
312}
313
314void QCoreTextFontDatabase::invalidate()
315{
316 qCDebug(lcQpaFonts) << "Invalidating font database";
317 m_hasPopulatedAliases = false;
318
319 qDeleteAll(m_themeFonts);
320 m_themeFonts.clear();
321 QWindowSystemInterface::handleThemeChange<QWindowSystemInterface::SynchronousDelivery>();
322}
323
336
337#ifndef QT_NO_DEBUG_STREAM
338Q_DECL_UNUSED static inline QDebug operator<<(QDebug debug, const FontDescription &fd)
339{
340 QDebugStateSaver saver(debug);
341 return debug.nospace() << "FontDescription("
342 << "familyName=" << QString(fd.familyName)
343 << ", styleName=" << QString(fd.styleName)
344 << ", foundry=" << fd.foundryName
345 << ", weight=" << fd.weight
346 << ", style=" << fd.style
347 << ", stretch=" << fd.stretch
348 << ", pointSize=" << fd.pointSize
349 << ", fixedPitch=" << fd.fixedPitch
350 << ", writingSystems=" << fd.writingSystems
351 << ")";
352}
353#endif
354
355static void getFontDescription(CTFontDescriptorRef font, FontDescription *fd)
356{
357 QCFType<CFDictionaryRef> styles = (CFDictionaryRef) CTFontDescriptorCopyAttribute(font, kCTFontTraitsAttribute);
358
359 fd->foundryName = QStringLiteral("CoreText");
360 fd->familyName = (CFStringRef) CTFontDescriptorCopyAttribute(font, kCTFontFamilyNameAttribute);
361 fd->styleName = (CFStringRef)CTFontDescriptorCopyAttribute(font, kCTFontStyleNameAttribute);
362 fd->weight = QFont::Normal;
363 fd->style = QFont::StyleNormal;
364 fd->stretch = QFont::Unstretched;
365 fd->fixedPitch = false;
366 fd->colorFont = false;
367
368
369
370 if (QCFType<CTFontRef> tempFont = CTFontCreateWithFontDescriptor(font, 0.0, 0)) {
371 uint tag = QFont::Tag("OS/2").value();
372 CTFontRef tempFontRef = tempFont;
373 void *userData = reinterpret_cast<void *>(&tempFontRef);
374 uint length = 128;
375 QVarLengthArray<uchar, 128> os2Table(length);
376 if (QCoreTextFontEngine::ct_getSfntTable(userData, tag, os2Table.data(), &length) && length >= 86) {
377 if (length > uint(os2Table.length())) {
378 os2Table.resize(length);
379 if (!QCoreTextFontEngine::ct_getSfntTable(userData, tag, os2Table.data(), &length))
380 Q_UNREACHABLE();
381 Q_ASSERT(length >= 86);
382 }
383 fd->writingSystems = QPlatformFontDatabase::writingSystemsFromOS2Table(reinterpret_cast<const char *>(os2Table.data()), length);
384 }
385 }
386
387 if (styles) {
388 if (CFNumberRef weightValue = (CFNumberRef) CFDictionaryGetValue(styles, kCTFontWeightTrait)) {
389 double normalizedWeight;
390 if (CFNumberGetValue(weightValue, kCFNumberFloat64Type, &normalizedWeight))
391 fd->weight = QCoreTextFontEngine::qtWeightFromCFWeight(float(normalizedWeight));
392 }
393 if (CFNumberRef italic = (CFNumberRef) CFDictionaryGetValue(styles, kCTFontSlantTrait)) {
394 double d;
395 if (CFNumberGetValue(italic, kCFNumberDoubleType, &d)) {
396 if (d > 0.0)
397 fd->style = QFont::StyleItalic;
398 }
399 }
400 if (CFNumberRef symbolic = (CFNumberRef) CFDictionaryGetValue(styles, kCTFontSymbolicTrait)) {
401 int d;
402 if (CFNumberGetValue(symbolic, kCFNumberSInt32Type, &d)) {
403 if (d & kCTFontColorGlyphsTrait)
404 fd->colorFont = true;
405
406 if (d & kCTFontMonoSpaceTrait)
407 fd->fixedPitch = true;
408 if (d & kCTFontExpandedTrait)
409 fd->stretch = QFont::Expanded;
410 else if (d & kCTFontCondensedTrait)
411 fd->stretch = QFont::Condensed;
412 }
413 }
414 }
415
416 if (QCFType<CFNumberRef> size = (CFNumberRef) CTFontDescriptorCopyAttribute(font, kCTFontSizeAttribute)) {
417 if (CFNumberIsFloatType(size)) {
418 double d;
419 CFNumberGetValue(size, kCFNumberDoubleType, &d);
420 fd->pointSize = d;
421 } else {
422 int i;
423 CFNumberGetValue(size, kCFNumberIntType, &i);
424 fd->pointSize = i;
425 }
426 }
427
428 if (QCFType<CFArrayRef> languages = (CFArrayRef) CTFontDescriptorCopyAttribute(font, kCTFontLanguagesAttribute)) {
429 CFIndex length = CFArrayGetCount(languages);
430 for (int i = 1; i < LanguageCount; ++i) {
431 if (!*languageForWritingSystem[i])
432 continue;
433 QCFString lang = CFStringCreateWithCString(NULL, languageForWritingSystem[i], kCFStringEncodingASCII);
434 if (CFArrayContainsValue(languages, CFRangeMake(0, length), lang))
435 fd->writingSystems.setSupported(QFontDatabase::WritingSystem(i));
436 }
437 }
438}
439
440void QCoreTextFontDatabase::populateFromDescriptor(CTFontDescriptorRef font, const QString &familyName, QFontDatabasePrivate::ApplicationFont *applicationFont)
441{
442 FontDescription fd;
443 getFontDescription(font, &fd);
444
445 // Note: The familyName we are registering, and the family name of the font descriptor, may not
446 // match, as CTFontDescriptorCreateMatchingFontDescriptors will return descriptors for replacement
447 // fonts if a font family does not have any fonts available on the system.
448 QString family = !familyName.isNull() ? familyName : static_cast<QString>(fd.familyName);
449
450 if (applicationFont != nullptr) {
451 QFontDatabasePrivate::ApplicationFont::Properties properties;
452 properties.familyName = family;
453 properties.styleName = fd.styleName;
454 properties.weight = fd.weight;
455 properties.stretch = fd.stretch;
456 properties.style = fd.style;
457
458 applicationFont->properties.append(properties);
459 }
460
461 CFRetain(font);
462 QPlatformFontDatabase::registerFont(family, fd.styleName, fd.foundryName, fd.weight, fd.style, fd.stretch,
463 true /* antialiased */, true /* scalable */, 0 /* pixelSize, ignored as font is scalable */,
464 fd.fixedPitch, fd.colorFont, fd.writingSystems, (void *)font);
465}
466
467static NSString * const kQtFontDataAttribute = @"QtFontDataAttribute";
468
469template <typename T>
470T *descriptorAttribute(CTFontDescriptorRef descriptor, CFStringRef name)
471{
472 return [static_cast<T *>(CTFontDescriptorCopyAttribute(descriptor, name)) autorelease];
473}
474
475void QCoreTextFontDatabase::releaseHandle(void *handle)
476{
477 CTFontDescriptorRef descriptor = static_cast<CTFontDescriptorRef>(handle);
478 if (NSValue *fontDataValue = descriptorAttribute<NSValue>(descriptor, (CFStringRef)kQtFontDataAttribute)) {
479 QByteArray *fontData = static_cast<QByteArray *>(fontDataValue.pointerValue);
480 delete fontData;
481 }
482 CFRelease(descriptor);
483}
484
485extern CGAffineTransform qt_transform_from_fontdef(const QFontDef &fontDef);
486
487template <>
488QFontEngine *QCoreTextFontDatabaseEngineFactory<QCoreTextFontEngine>::fontEngine(const QFontDef &fontDef, void *usrPtr)
489{
490 QMacAutoReleasePool pool;
491
492 QCFType<CTFontDescriptorRef> descriptor = QCFType<CTFontDescriptorRef>::constructFromGet(
493 static_cast<CTFontDescriptorRef>(usrPtr));
494
495 // Since we do not pass in the destination DPI to CoreText when making
496 // the font, we need to pass in a point size which is scaled to include
497 // the DPI. The default DPI for the screen is 72, thus the scale factor
498 // is destinationDpi / 72, but since pixelSize = pointSize / 72 * dpi,
499 // the pixelSize is actually the scaled point size for the destination
500 // DPI, and we can use that directly.
501 qreal scaledPointSize = fontDef.pixelSize;
502
503 CGAffineTransform matrix = qt_transform_from_fontdef(fontDef);
504
505 if (!fontDef.variableAxisValues.isEmpty()) {
506 QCFType<CFMutableDictionaryRef> variations = CFDictionaryCreateMutable(nullptr,
507 fontDef.variableAxisValues.size(),
508 &kCFTypeDictionaryKeyCallBacks,
509 &kCFTypeDictionaryValueCallBacks);
510 for (auto it = fontDef.variableAxisValues.constBegin();
511 it != fontDef.variableAxisValues.constEnd();
512 ++it) {
513 const quint32 tag = it.key().value();
514 const float value = it.value();
515 QCFType<CFNumberRef> tagRef = CFNumberCreate(nullptr, kCFNumberIntType, &tag);
516 QCFType<CFNumberRef> valueRef = CFNumberCreate(nullptr, kCFNumberFloatType, &value);
517
518 CFDictionarySetValue(variations, tagRef, valueRef);
519 }
520 QCFType<CFDictionaryRef> attributes = CFDictionaryCreate(nullptr,
521 (const void **) &kCTFontVariationAttribute,
522 (const void **) &variations,
523 1,
524 &kCFTypeDictionaryKeyCallBacks,
525 &kCFTypeDictionaryValueCallBacks);
526 descriptor = CTFontDescriptorCreateCopyWithAttributes(descriptor, attributes);
527 }
528
529 if (QCFType<CTFontRef> font = CTFontCreateWithFontDescriptor(descriptor, scaledPointSize, &matrix))
530 return new QCoreTextFontEngine(font, fontDef);
531
532 return nullptr;
533}
534
535#ifndef QT_NO_FREETYPE
536template <>
537QFontEngine *QCoreTextFontDatabaseEngineFactory<QFontEngineFT>::fontEngine(const QFontDef &fontDef, void *usrPtr)
538{
539 QMacAutoReleasePool pool;
540
541 CTFontDescriptorRef descriptor = static_cast<CTFontDescriptorRef>(usrPtr);
542
543 if (NSValue *fontDataValue = descriptorAttribute<NSValue>(descriptor, (CFStringRef)kQtFontDataAttribute)) {
544 QByteArray *fontData = static_cast<QByteArray *>(fontDataValue.pointerValue);
545 return QFontEngineFT::create(*fontData, fontDef.pixelSize,
546 static_cast<QFont::HintingPreference>(fontDef.hintingPreference), fontDef.variableAxisValues);
547 } else if (NSURL *url = descriptorAttribute<NSURL>(descriptor, kCTFontURLAttribute)) {
548 QFontEngine::FaceId faceId;
549
550 Q_ASSERT(url.fileURL);
551 QString faceFileName{QString::fromNSString(url.path)};
552 faceId.filename = faceFileName.toUtf8();
553
554 QString styleName = QCFString(CTFontDescriptorCopyAttribute(descriptor, kCTFontStyleNameAttribute));
555 faceId.index = QFreetypeFace::getFaceIndexByStyleName(faceFileName, styleName);
556
557 faceId.variableAxes = fontDef.variableAxisValues;
558
559 return QFontEngineFT::create(fontDef, faceId);
560 }
561 // We end up here with a descriptor does not contain Qt font data or kCTFontURLAttribute.
562 // Since the FT engine can't deal with a descriptor with just a NSFontNameAttribute,
563 // we should return nullptr.
564 return nullptr;
565}
566#endif
567
568template <class T>
569QFontEngine *QCoreTextFontDatabaseEngineFactory<T>::fontEngine(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference)
570{
571 return T::create(fontData, pixelSize, hintingPreference, {});
572}
573
574// Explicitly instantiate so that we don't need the plugin to involve FreeType
575template class QCoreTextFontDatabaseEngineFactory<QCoreTextFontEngine>;
576#ifndef QT_NO_FREETYPE
577template class QCoreTextFontDatabaseEngineFactory<QFontEngineFT>;
578#endif
579
580CFArrayRef fallbacksForDescriptor(CTFontDescriptorRef descriptor)
581{
582 QCFType<CTFontRef> font = CTFontCreateWithFontDescriptor(descriptor, 0.0, nullptr);
583 if (!font) {
584 qCWarning(lcQpaFonts) << "Failed to create fallback font for" << descriptor;
585 return nullptr;
586 }
587
588 CFArrayRef cascadeList = CFArrayRef(CTFontCopyDefaultCascadeListForLanguages(font,
589 (CFArrayRef)NSLocale.preferredLanguages));
590
591 if (!cascadeList) {
592 qCWarning(lcQpaFonts) << "Failed to create fallback cascade list for" << descriptor;
593 return nullptr;
594 }
595
596 return cascadeList;
597}
598
599CFArrayRef QCoreTextFontDatabase::fallbacksForFamily(const QString &family)
600{
601 if (family.isEmpty())
602 return nullptr;
603
604 QCFType<CTFontDescriptorRef> fontDescriptor = descriptorForFamily(family);
605 if (!fontDescriptor) {
606 qCWarning(lcQpaFonts) << "Failed to create fallback font descriptor for" << family;
607 return nullptr;
608 }
609
610 // If the font is not available we want to fall back to the style hint.
611 // By creating a matching font descriptor we can verify whether the font
612 // is available or not, and avoid CTFontCreateWithFontDescriptor picking
613 // a default font for us based on incomplete information.
614 fontDescriptor = CTFontDescriptorCreateMatchingFontDescriptor(fontDescriptor, 0);
615 if (!fontDescriptor)
616 return nullptr;
617
618 return fallbacksForDescriptor(fontDescriptor);
619}
620
622{
623 static const CGFloat kDefaultSizeForRequestedUIType = 0.0;
624 QCFType<CTFontRef> ctFont = CTFontCreateUIFontForLanguage(
625 uiType, kDefaultSizeForRequestedUIType, nullptr);
626 return CTFontCopyFontDescriptor(ctFont);
627}
628
629CTFontDescriptorRef descriptorForStyle(QFont::StyleHint styleHint)
630{
631 switch (styleHint) {
632 case QFont::SansSerif: return descriptorForFamily("Helvetica");
633 case QFont::Serif: return descriptorForFamily("Times New Roman");
634 case QFont::Monospace: return descriptorForFamily("Menlo");
635#ifdef Q_OS_MACOS
636 case QFont::Cursive: return descriptorForFamily("Apple Chancery");
637#endif
638 case QFont::Fantasy: return descriptorForFamily("Zapfino");
639 case QFont::TypeWriter: return descriptorForFamily("American Typewriter");
640 case QFont::AnyStyle: Q_FALLTHROUGH();
641 case QFont::System: return descriptorForFontType(kCTFontUIFontSystem);
642 default: return nullptr; // No matching font on this platform
643 }
644}
645
646QStringList QCoreTextFontDatabase::fallbacksForScript(QFontDatabasePrivate::ExtendedScript script) const
647{
648 if (script == QFontDatabasePrivate::Script_Emoji)
649 return QStringList{} << QStringLiteral(".Apple Color Emoji UI");
650 else
651 return QStringList{};
652}
653
654QStringList QCoreTextFontDatabase::fallbacksForFamily(const QString &family,
655 QFont::Style style,
656 QFont::StyleHint styleHint,
657 QFontDatabasePrivate::ExtendedScript script) const
658{
659 Q_UNUSED(style);
660
661 qCDebug(lcQpaFonts).nospace() << "Resolving fallbacks families for"
662 << (!family.isEmpty() ? qPrintable(" family '%1' with"_L1.arg(family)) : "")
663 << " style hint " << styleHint;
664
665 QMacAutoReleasePool pool;
666
667 QStringList fallbackList = fallbacksForScript(script);
668
669 QCFType<CFArrayRef> fallbackFonts = fallbacksForFamily(family);
670 if (!fallbackFonts || !CFArrayGetCount(fallbackFonts)) {
671 // We were not able to find a fallback for the specific family,
672 // or the family was empty, so we fall back to the style hint.
673 if (!family.isEmpty())
674 qCDebug(lcQpaFonts) << "No fallbacks found. Using style hint instead";
675
676 if (QCFType<CTFontDescriptorRef> styleDescriptor = descriptorForStyle(styleHint)) {
677 CFMutableArrayRef tmp = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
678 CFArrayAppendValue(tmp, styleDescriptor);
679 QCFType<CFArrayRef> styleFallbacks = fallbacksForDescriptor(styleDescriptor);
680 CFArrayAppendArray(tmp, styleFallbacks, CFRangeMake(0, CFArrayGetCount(styleFallbacks)));
681 fallbackFonts = tmp;
682 }
683 }
684
685 if (!fallbackFonts)
686 return fallbackList;
687
688 const int numberOfFallbacks = CFArrayGetCount(fallbackFonts);
689 for (int i = 0; i < numberOfFallbacks; ++i) {
690 auto fallbackDescriptor = CTFontDescriptorRef(CFArrayGetValueAtIndex(fallbackFonts, i));
691 auto fallbackFamilyName = QCFString(CTFontDescriptorCopyAttribute(fallbackDescriptor, kCTFontFamilyNameAttribute));
692
693 if (!isFamilyPopulated(fallbackFamilyName)) {
694 // We need to populate, or at least register the fallback fonts,
695 // otherwise the Qt font database may not know they exist.
696 if (isPrivateFontFamily(fallbackFamilyName))
697 const_cast<QCoreTextFontDatabase *>(this)->populateFromDescriptor(fallbackDescriptor);
698 else
699 registerFontFamily(fallbackFamilyName);
700 }
701
702 fallbackList.append(fallbackFamilyName);
703 }
704
705 // Some fallback fonts will have have an order in the list returned
706 // by Core Text that would indicate they should be preferred for e.g.
707 // Arabic, or Emoji, while in reality only supporting a tiny subset
708 // of the required glyphs, or representing them by question marks.
709 // Move these to the end, so that the proper fonts are preferred.
710 for (const char *family : { ".Apple Symbols Fallback", ".Noto Sans Universal" }) {
711 int index = fallbackList.indexOf(QLatin1StringView(family));
712 if (index >= 0)
713 fallbackList.move(index, fallbackList.size() - 1);
714 }
715
716#if defined(Q_OS_MACOS)
717 // Since we are only returning a list of default fonts for the current language, we do not
718 // cover all Unicode completely. This was especially an issue for some of the common script
719 // symbols such as mathematical symbols, currency or geometric shapes. To minimize the risk
720 // of missing glyphs, we add Arial Unicode MS as a final fail safe, since this covers most
721 // of Unicode 2.1.
722 if (!fallbackList.contains(QStringLiteral("Arial Unicode MS")))
723 fallbackList.append(QStringLiteral("Arial Unicode MS"));
724 // Since some symbols (specifically Braille) are not in Arial Unicode MS, we
725 // add Apple Symbols to cover those too.
726 if (!fallbackList.contains(QStringLiteral("Apple Symbols")))
727 fallbackList.append(QStringLiteral("Apple Symbols"));
728 // Some Noto* fonts are not automatically enumerated by system, despite being the main
729 // fonts for their writing system.
730 if (script < int(QChar::ScriptCount)) {
731 QString hardcodedFont = m_hardcodedFallbackFonts.value(QChar::Script(script));
732 if (!hardcodedFont.isEmpty() && !fallbackList.contains(hardcodedFont)) {
733 if (!isFamilyPopulated(hardcodedFont)) {
734 if (!m_privateFamilies.contains(hardcodedFont)) {
735 QCFType<CTFontDescriptorRef> familyDescriptor = descriptorForFamily(hardcodedFont);
736 QCFType<CFArrayRef> matchingFonts = CTFontDescriptorCreateMatchingFontDescriptors(familyDescriptor, nullptr);
737 if (matchingFonts) {
738 const int numFonts = CFArrayGetCount(matchingFonts);
739 for (int i = 0; i < numFonts; ++i)
740 const_cast<QCoreTextFontDatabase *>(this)->populateFromDescriptor(CTFontDescriptorRef(CFArrayGetValueAtIndex(matchingFonts, i)),
741 hardcodedFont);
742
743 fallbackList.append(hardcodedFont);
744 }
745
746 // Register as private family even if the font is not found, in order to avoid
747 // redoing the check later. In later calls, the font will then just be ignored.
748 m_privateFamilies.insert(hardcodedFont);
749 }
750 } else {
751 fallbackList.append(hardcodedFont);
752 }
753 }
754 }
755#endif
756
757 extern QStringList qt_sort_families_by_writing_system(QFontDatabasePrivate::ExtendedScript, const QStringList &);
758 fallbackList = qt_sort_families_by_writing_system(script, fallbackList);
759
760 qCDebug(lcQpaFonts).nospace() << "Fallback families ordered by script " << script << ": " << fallbackList;
761
762 return fallbackList;
763}
764
765QStringList QCoreTextFontDatabase::addApplicationFont(const QByteArray &fontData, const QString &fileName, QFontDatabasePrivate::ApplicationFont *applicationFont)
766{
767 QCFType<CFArrayRef> fonts;
768
769 if (!fontData.isEmpty()) {
770 QCFType<CFDataRef> fontDataReference = fontData.toRawCFData();
771 if (QCFType<CFArrayRef> descriptors = CTFontManagerCreateFontDescriptorsFromData(fontDataReference)) {
772 CFMutableArrayRef array = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
773 const int count = CFArrayGetCount(descriptors);
774
775 for (int i = 0; i < count; ++i) {
776 CTFontDescriptorRef descriptor = CTFontDescriptorRef(CFArrayGetValueAtIndex(descriptors, i));
777
778 // There's no way to get the data back out of a font descriptor created with
779 // CTFontManagerCreateFontDescriptorFromData, so we attach the data manually.
780 NSDictionary *attributes = @{ kQtFontDataAttribute : [NSValue valueWithPointer:new QByteArray(fontData)] };
781 QCFType<CTFontDescriptorRef> copiedDescriptor = CTFontDescriptorCreateCopyWithAttributes(descriptor, (CFDictionaryRef)attributes);
782 CFArrayAppendValue(array, copiedDescriptor);
783 }
784
785 fonts = array;
786 }
787 } else {
788 QCFType<CFURLRef> fontURL = QUrl::fromLocalFile(fileName).toCFURL();
789 fonts = CTFontManagerCreateFontDescriptorsFromURL(fontURL);
790 }
791
792 if (!fonts)
793 return QStringList();
794
795 QStringList families;
796 const int numFonts = CFArrayGetCount(fonts);
797 for (int i = 0; i < numFonts; ++i) {
798 CTFontDescriptorRef fontDescriptor = CTFontDescriptorRef(CFArrayGetValueAtIndex(fonts, i));
799 populateFromDescriptor(fontDescriptor, QString(), applicationFont);
800 QCFType<CFStringRef> familyName = CFStringRef(CTFontDescriptorCopyAttribute(fontDescriptor, kCTFontFamilyNameAttribute));
801 families.append(QString::fromCFString(familyName));
802 }
803
804 // Note: We don't do font matching via CoreText for application fonts, so we don't
805 // need to enable font matching for them via CTFontManagerEnableFontDescriptors.
806
807 return families;
808}
809
810bool QCoreTextFontDatabase::isPrivateFontFamily(const QString &family) const
811{
812 if (family.startsWith(u'.') || family == "LastResort"_L1 || m_privateFamilies.contains(family))
813 return true;
814
815 return QPlatformFontDatabase::isPrivateFontFamily(family);
816}
817
818static CTFontUIFontType fontTypeFromTheme(QPlatformTheme::Font f)
819{
820 switch (f) {
821 case QPlatformTheme::SystemFont:
822 return kCTFontUIFontSystem;
823
824 case QPlatformTheme::MenuFont:
825 case QPlatformTheme::MenuBarFont:
826 case QPlatformTheme::MenuItemFont:
827 return kCTFontUIFontMenuItem;
828
829 case QPlatformTheme::MessageBoxFont:
830 return kCTFontUIFontEmphasizedSystem;
831
832 case QPlatformTheme::LabelFont:
833 return kCTFontUIFontSystem;
834
835 case QPlatformTheme::TipLabelFont:
836 return kCTFontUIFontToolTip;
837
838 case QPlatformTheme::StatusBarFont:
839 return kCTFontUIFontSystem;
840
841 case QPlatformTheme::TitleBarFont:
842 return kCTFontUIFontWindowTitle;
843
844 case QPlatformTheme::MdiSubWindowTitleFont:
845 return kCTFontUIFontSystem;
846
847 case QPlatformTheme::DockWidgetTitleFont:
848 return kCTFontUIFontSmallSystem;
849
850 case QPlatformTheme::PushButtonFont:
851 return kCTFontUIFontPushButton;
852
853 case QPlatformTheme::CheckBoxFont:
854 case QPlatformTheme::RadioButtonFont:
855 return kCTFontUIFontSystem;
856
857 case QPlatformTheme::ToolButtonFont:
858 return kCTFontUIFontSmallToolbar;
859
860 case QPlatformTheme::ItemViewFont:
861 return kCTFontUIFontSystem;
862
863 case QPlatformTheme::ListViewFont:
864 return kCTFontUIFontViews;
865
866 case QPlatformTheme::HeaderViewFont:
867 return kCTFontUIFontSmallSystem;
868
869 case QPlatformTheme::ListBoxFont:
870 return kCTFontUIFontViews;
871
872 case QPlatformTheme::ComboMenuItemFont:
873 return kCTFontUIFontSystem;
874
875 case QPlatformTheme::ComboLineEditFont:
876 return kCTFontUIFontViews;
877
878 case QPlatformTheme::SmallFont:
879 return kCTFontUIFontSmallSystem;
880
881 case QPlatformTheme::MiniFont:
882 return kCTFontUIFontMiniSystem;
883
884 case QPlatformTheme::FixedFont:
885 return kCTFontUIFontUserFixedPitch;
886
887 default:
888 return kCTFontUIFontSystem;
889 }
890}
891
892static CTFontDescriptorRef fontDescriptorFromTheme(QPlatformTheme::Font f)
893{
894#if defined(QT_PLATFORM_UIKIT)
895 // Use Dynamic Type to resolve theme fonts if possible, to get
896 // correct font sizes and style based on user configuration.
897 NSString *textStyle = 0;
898 switch (f) {
899 case QPlatformTheme::TitleBarFont:
900 case QPlatformTheme::HeaderViewFont:
901 textStyle = UIFontTextStyleHeadline;
902 break;
903 case QPlatformTheme::MdiSubWindowTitleFont:
904 textStyle = UIFontTextStyleSubheadline;
905 break;
906 case QPlatformTheme::TipLabelFont:
907 case QPlatformTheme::SmallFont:
908 textStyle = UIFontTextStyleFootnote;
909 break;
910 case QPlatformTheme::MiniFont:
911 textStyle = UIFontTextStyleCaption2;
912 break;
913 case QPlatformTheme::FixedFont:
914 // Fall back to regular code path, as iOS doesn't provide
915 // an appropriate text style for this theme font.
916 break;
917 default:
918 textStyle = UIFontTextStyleBody;
919 break;
920 }
921
922 if (textStyle) {
923 UIFontDescriptor *desc = [UIFontDescriptor preferredFontDescriptorWithTextStyle:textStyle];
924 return static_cast<CTFontDescriptorRef>(CFBridgingRetain(desc));
925 }
926#endif // QT_PLATFORM_UIKIT
927
928 // macOS default case and iOS fallback case
929 return descriptorForFontType(fontTypeFromTheme(f));
930}
931
932void QCoreTextFontDatabase::populateThemeFonts()
933{
934 QMacAutoReleasePool pool;
935
936 if (!m_themeFonts.isEmpty())
937 return;
938
939 QElapsedTimer elapsed;
940 if (lcQpaFonts().isDebugEnabled())
941 elapsed.start();
942
943 qCDebug(lcQpaFonts) << "Populating theme fonts...";
944
945 for (long f = QPlatformTheme::SystemFont; f < QPlatformTheme::NFonts; f++) {
946 QPlatformTheme::Font themeFont = static_cast<QPlatformTheme::Font>(f);
947 QCFType<CTFontDescriptorRef> fontDescriptor = fontDescriptorFromTheme(themeFont);
948 FontDescription fd;
949 getFontDescription(fontDescriptor, &fd);
950
951 // We might get here from QFontDatabase::systemFont() or QPlatformTheme::font(),
952 // before the font database has initialized itself and populated all available
953 // families. As a result, we can't populate the descriptor at this time, as that
954 // would result in the font database having > 0 families, which would result in
955 // skipping the initialization and population of all other font families. Instead
956 // we store the descriptors for later and populate them during populateFontDatabase().
957
958 bool haveRegisteredFamily = m_systemFontDescriptors.contains(fd.familyName);
959 qCDebug(lcQpaFonts) << "Got" << (haveRegisteredFamily ? "already registered" : "unseen")
960 << "family" << fd.familyName << "for" << themeFont;
961
962 if (!haveRegisteredFamily) {
963 // We need to register all weights and variants of the theme font,
964 // as the user might tweak the returned QFont before use.
965 QList<QCFType<CTFontDescriptorRef>> themeFontVariants;
966
967 auto addFontVariants = [&](CTFontDescriptorRef descriptor) {
968 QCFType<CFArrayRef> matchingDescriptors = CTFontDescriptorCreateMatchingFontDescriptors(descriptor, nullptr);
969 const int matchingDescriptorsCount = matchingDescriptors ? CFArrayGetCount(matchingDescriptors) : 0;
970 qCDebug(lcQpaFonts) << "Enumerating font variants based on" << id(descriptor)
971 << "resulted in" << matchingDescriptorsCount << "matching descriptors"
972 << matchingDescriptors.as<NSArray*>();
973
974 for (int i = 0; i < matchingDescriptorsCount; ++i) {
975 auto matchingDescriptor = CTFontDescriptorRef(CFArrayGetValueAtIndex(matchingDescriptors, i));
976 themeFontVariants.append(QCFType<CTFontDescriptorRef>::constructFromGet(matchingDescriptor));
977 }
978 };
979
980 // Try populating the font variants based on its UI design trait, if available
981 auto fontTraits = QCFType<CFDictionaryRef>(CTFontDescriptorCopyAttribute(fontDescriptor, kCTFontTraitsAttribute));
982 static const NSString *kUIFontDesignTrait = @"NSCTFontUIFontDesignTrait";
983 if (id uiFontDesignTrait = fontTraits.as<NSDictionary*>()[kUIFontDesignTrait]) {
984 QCFType<CTFontDescriptorRef> designTraitDescriptor = CTFontDescriptorCreateWithAttributes(
985 CFDictionaryRef(@{ (id)kCTFontTraitsAttribute: @{ kUIFontDesignTrait: uiFontDesignTrait }
986 }));
987 addFontVariants(designTraitDescriptor);
988 }
989
990 if (themeFontVariants.isEmpty()) {
991 // Fall back to populating variants based on the family name alone
992 QCFType<CTFontDescriptorRef> familyDescriptor = descriptorForFamily(fd.familyName);
993 addFontVariants(familyDescriptor);
994 }
995
996 if (themeFontVariants.isEmpty()) {
997 qCDebug(lcQpaFonts) << "No theme font variants found, falling back to single variant descriptor";
998 themeFontVariants.append(fontDescriptor);
999 }
1000
1001 m_systemFontDescriptors.insert(fd.familyName, themeFontVariants);
1002 }
1003
1004 QFont *font = new QFont(fd.familyName, fd.pointSize, fd.weight, fd.style == QFont::StyleItalic);
1005 m_themeFonts.insert(themeFont, font);
1006 }
1007
1008 qCDebug(lcQpaFonts) << "Populating theme fonts took" << elapsed.restart() << "ms";
1009}
1010
1011QFont *QCoreTextFontDatabase::themeFont(QPlatformTheme::Font f) const
1012{
1013 // The code paths via QFontDatabase::systemFont() or QPlatformTheme::font()
1014 // do not ensure that the font database has been populated, so we need to
1015 // manually populate the theme fonts lazily here just in case.
1016 const_cast<QCoreTextFontDatabase*>(this)->populateThemeFonts();
1017
1018 return m_themeFonts.value(f, nullptr);
1019}
1020
1021QFont QCoreTextFontDatabase::defaultFont() const
1022{
1023 return QFont(*themeFont(QPlatformTheme::SystemFont));
1024}
1025
1026bool QCoreTextFontDatabase::fontsAlwaysScalable() const
1027{
1028 return true;
1029}
1030
1031QList<int> QCoreTextFontDatabase::standardSizes() const
1032{
1033 QList<int> ret;
1034 static const unsigned short standard[] =
1035 { 9, 10, 11, 12, 13, 14, 18, 24, 36, 48, 64, 72, 96, 144, 288, 0 };
1036 ret.reserve(int(sizeof(standard) / sizeof(standard[0])));
1037 const unsigned short *sizes = standard;
1038 while (*sizes) ret << *sizes++;
1039 return ret;
1040}
1041
1042bool QCoreTextFontDatabase::supportsColrv0Fonts() const
1043{
1044 return true;
1045}
1046
1047bool QCoreTextFontDatabase::supportsVariableApplicationFonts() const
1048{
1049 return true;
1050}
1051
1052QT_END_NAMESPACE
Combined button and popup list for selecting options.
CFArrayRef fallbacksForDescriptor(CTFontDescriptorRef descriptor)
CGAffineTransform qt_transform_from_fontdef(const QFontDef &fontDef)
static NSString *const kQtFontDataAttribute
static Q_DECL_UNUSED QDebug operator<<(QDebug debug, const FontDescription &fd)
CTFontDescriptorRef descriptorForFamily(const QString &familyName)
static void getFontDescription(CTFontDescriptorRef font, FontDescription *fd)
static CTFontUIFontType fontTypeFromTheme(QPlatformTheme::Font f)
static CTFontDescriptorRef fontDescriptorFromTheme(QPlatformTheme::Font f)
CTFontDescriptorRef descriptorForFamily(const char *familyName)
CTFontDescriptorRef descriptorForFontType(CTFontUIFontType uiType)
T * descriptorAttribute(CTFontDescriptorRef descriptor, CFStringRef name)
CTFontDescriptorRef descriptorForStyle(QFont::StyleHint styleHint)
QSupportedWritingSystems writingSystems