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