forked from bitcoin/bitcoin
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathguiutil_font.cpp
More file actions
837 lines (741 loc) · 27.6 KB
/
Copy pathguiutil_font.cpp
File metadata and controls
837 lines (741 loc) · 27.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
// Copyright (c) 2014-2026 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/guiutil.h>
#include <util/helpers.h>
#include <tinyformat.h>
#include <util/std23.h>
#include <util/system.h>
#include <QApplication>
#include <QDebug>
#include <QFont>
#include <QFontDatabase>
#include <QFontMetrics>
#include <QPointer>
#include <QStringView>
#include <QTextBlock>
#include <QTextCharFormat>
#include <QTextCursor>
#include <QTextEdit>
#include <QWidget>
#include <cmath>
#include <map>
#include <memory>
#include <utility>
namespace {
// TODO: Switch to QUtf8StringView when we switch to Qt 6
constexpr QStringView MONTSERRAT_FONT_STR{u"Montserrat"};
constexpr QStringView OS_FONT_STR{u"SystemDefault"};
constexpr QStringView OS_MONO_FONT_STR{u"SystemMonospace"};
constexpr QStringView ROBOTO_MONO_FONT_STR{u"Roboto Mono"};
constexpr int DEFAULT_FONT_SCALE{0};
constexpr int DEFAULT_FONT_SIZE{12};
constexpr QStringView DEFAULT_FONT{OS_FONT_STR};
constexpr QFont::Weight TARGET_WEIGHT_BOLD{QFont::Medium};
constexpr QFont::Weight TARGET_WEIGHT_NORMAL{
#ifdef Q_OS_MACOS
QFont::ExtraLight
#else
QFont::Light
#endif // Q_OS_MACOS
};
//! Per-widget styling request — what setFont() captures into mapFontUpdates.
struct FontAttrib {
QString m_font;
GUIUtil::FontWeight m_weight_type;
double m_point_size{-1};
bool m_is_italic{false};
};
//! Per-font weight cache (defaults + user-selected bold/normal + supported list).
struct FontInfo {
QFont::Weight m_bold;
QFont::Weight m_bold_default;
QFont::Weight m_normal;
QFont::Weight m_normal_default;
std::vector<QFont::Weight> m_supported_weights;
FontInfo() = delete;
explicit FontInfo(const QString& font_name);
~FontInfo();
private:
QFont::Weight GetBestMatch(const QString& font_name, QFont::Weight target);
void CalcDefaultWeights(const QString& font_name);
void CalcSupportedWeights(const QString& font_name);
};
//! Global font state (active family, scale, per-font cache). File-private —
//! external callers go through the free-function API in qt/guiutil.h.
class FontRegistry {
public:
[[nodiscard]] bool RegisterFont(const QString& font, bool selectable, bool skip_checks = false);
bool IsValidWeight(const QFont::Weight& weight) const;
[[nodiscard]] bool SetFont(const QString& font);
void SetFontScale(int font_scale) { m_font_scale = font_scale; }
void SetWeightBold(const QFont::Weight& bold)
{
assert(m_weights.count(m_font));
m_weights.at(m_font).m_bold = bold;
}
void SetWeightNormal(const QFont::Weight& normal)
{
assert(m_weights.count(m_font));
m_weights.at(m_font).m_normal = normal;
}
double GetScaledFontSize(double size) const { return std::round(size * (1 + (m_font_scale * m_scale_steps)) * 4) / 4.0; }
QString GetFont() const { return m_font; }
int GetFontScale() const { return m_font_scale; }
int GetFontSize() const { return m_font_size; }
QFont::Weight GetWeightBold() const
{
if (auto it = m_weights.find(m_font); it != m_weights.end()) { return it->second.m_bold; }
return TARGET_WEIGHT_BOLD;
}
QFont::Weight GetWeightNormal() const
{
if (auto it = m_weights.find(m_font); it != m_weights.end()) { return it->second.m_normal; }
return TARGET_WEIGHT_NORMAL;
}
QFont::Weight GetWeightBoldDefault() const
{
if (auto it = m_weights.find(m_font); it != m_weights.end()) { return it->second.m_bold_default; }
return TARGET_WEIGHT_BOLD;
}
QFont::Weight GetWeightNormalDefault() const
{
if (auto it = m_weights.find(m_font); it != m_weights.end()) { return it->second.m_normal_default; }
return TARGET_WEIGHT_NORMAL;
}
std::vector<QFont::Weight> GetSupportedWeights() const
{
if (auto it = m_weights.find(m_font); it != m_weights.end()) { return it->second.m_supported_weights; }
return {TARGET_WEIGHT_NORMAL, TARGET_WEIGHT_BOLD};
}
private:
double m_scale_steps{0.01};
QString m_font{DEFAULT_FONT.toUtf8()};
int m_font_scale{DEFAULT_FONT_SCALE};
int m_font_size{DEFAULT_FONT_SIZE};
std::map<QString, FontInfo> m_weights;
};
FontRegistry g_font_registry;
//! Fonts known by the client
std::vector<std::pair<QString, /*selectable=*/bool>> g_fonts_known{
{MONTSERRAT_FONT_STR.toUtf8(), true},
{OS_FONT_STR.toUtf8(), true},
{OS_MONO_FONT_STR.toUtf8(), false},
{ROBOTO_MONO_FONT_STR.toUtf8(), false},
};
//! Instance of font database shared among calls
std::unique_ptr<QFontDatabase> g_font_db{nullptr};
//! loadFonts stores the SystemDefault font in g_default_font to be able to reference it later again
std::unique_ptr<QFont> g_default_font{nullptr};
//! Font scaling information for Qt classes
std::map<std::string, int> mapClassFontUpdates{
{"QMenu", -1},
{"QMessageBox", -1},
{"QTipLabel", -1},
};
//! Contains all widgets and its font attributes (weight, italic, size) with font changes due to GUIUtil::setFont
std::map<QPointer<QWidget>, FontAttrib> mapFontUpdates;
//! Contains QTextEdit widgets with the original base font size and HTML
struct TextEditStyleData {
QString html;
double base_size;
};
std::map<QPointer<QTextEdit>, TextEditStyleData> mapTextEditStyleUpdates;
//! Map between font weights, Montserrat's convention and italic availability
const std::map<QFont::Weight, std::pair<std::string, /*can_italic=*/bool>> mapMontserrat{{
{QFont::Black, {"Black", true}},
{QFont::Bold, {"Bold", true}},
{QFont::DemiBold, {"SemiBold", true}},
{QFont::ExtraBold, {"ExtraBold", true}},
{QFont::ExtraLight, {"ExtraLight", true}},
{QFont::Light, {"Light", true}},
{QFont::Medium, {"Medium", true}},
{QFont::Normal, {"Regular", false}},
{QFont::Thin, {"Thin", true}},
}};
//! Map between font weights and settings representation
const auto mapWeightArgs = []() {
std::map<int, QFont::Weight> kv{
{0, QFont::Thin},
{1, QFont::ExtraLight},
{2, QFont::Light},
{3, QFont::Normal},
{4, QFont::Medium},
{5, QFont::DemiBold},
{6, QFont::Bold},
{7, QFont::ExtraBold},
{8, QFont::Black}
};
std::map<QFont::Weight, int> vk;
for (const auto& [key, val] : kv) {
vk[val] = key;
}
return std::pair{std::move(kv), std::move(vk)};
}();
//! List of Qt classes to ignore when applying fonts
constexpr std::array<std::string_view, 18> vecIgnoreClasses{
"BitcoinGUI",
"QComboBoxPrivateContainer",
"QComboBoxPrivateScroller",
"QDesktopScreenWidget",
"QDesktopWidget",
"QDialog",
"QFrame",
"QGroupBox",
"QListView",
"QMenu",
"QMessageBox",
"QScrollBar",
"QStackedWidget",
"QTipLabel",
"QVBoxLayout",
"QWidget",
"WalletFrame",
"WalletView",
};
//! List of Qt objects to ignore when applying fonts
constexpr std::array<std::string_view, 1> vecIgnoreObjects{
"messagesWidget",
};
//! Weights considered when testing for weights supported by a font
const auto vecWeightConsider = []() {
std::vector<QFont::Weight> ret;
for (const auto& [key, _] : mapWeightArgs.second) {
ret.push_back(key);
}
return ret;
}();
//! Wrapper for tinyformat (strprintf) that converts to QString
template <typename... Args>
QString qstrprintf(const std::string& fmt, const Args&... args)
{
return QString::fromStdString(tfm::format(fmt, args...));
}
bool weightFromArg(int nArg, QFont::Weight& weight)
{
auto it = mapWeightArgs.first.find(nArg);
if (it == mapWeightArgs.first.end()) {
return false;
}
weight = it->second;
return true;
}
int weightToArg(const QFont::Weight weight)
{
assert(mapWeightArgs.second.count(weight));
return mapWeightArgs.second.find(weight)->second;
}
//! Returns a properly weighted QFont object with the selected font
QFont getFont(const FontAttrib& font_attrib)
{
QFont font;
if (!GUIUtil::fontsLoaded()) {
return font;
}
// Resolve weight from FontWeight type
const QFont::Weight weight = (font_attrib.m_weight_type == GUIUtil::FontWeight::Bold)
? g_font_registry.GetWeightBold() : g_font_registry.GetWeightNormal();
if (font_attrib.m_font == MONTSERRAT_FONT_STR) {
assert(mapMontserrat.count(weight));
#ifdef Q_OS_MACOS
font.setFamily(font_attrib.m_font);
font.setStyleName([&]() {
std::string ret{mapMontserrat.at(weight).first};
if (font_attrib.m_is_italic) {
if (ret == "Regular") {
ret = "Italic";
} else {
ret += " Italic";
}
}
return QString::fromStdString(ret);
}());
#else
if (weight == QFont::Normal || weight == QFont::Bold) {
font.setFamily(font_attrib.m_font);
} else {
font.setFamily(qstrprintf("%s %s", font_attrib.m_font.toStdString(), mapMontserrat.at(weight).first));
}
#endif // Q_OS_MACOS
} else if (font_attrib.m_font == OS_FONT_STR) {
font.setFamily(g_default_font->family());
} else if (font_attrib.m_font == OS_MONO_FONT_STR) {
font.setFamily(QFontDatabase::systemFont(QFontDatabase::FixedFont).family());
} else {
font.setFamily(font_attrib.m_font);
}
if (font_attrib.m_font == ROBOTO_MONO_FONT_STR || font_attrib.m_font == OS_MONO_FONT_STR) {
font.setStyleHint(QFont::Monospace);
}
#ifdef Q_OS_MACOS
if (font_attrib.m_font != MONTSERRAT_FONT_STR)
#endif // Q_OS_MACOS
{
font.setWeight(weight);
font.setStyle(font_attrib.m_is_italic ? QFont::StyleItalic : QFont::StyleNormal);
}
if (font_attrib.m_point_size != -1) {
font.setPointSizeF(g_font_registry.GetScaledFontSize(font_attrib.m_point_size));
}
if (gArgs.GetBoolArg("-debug-ui", false)) {
qDebug() << qstrprintf("%s: font size: %d, family: %s, style: %s, weight: %d match %s", __func__,
font.pointSizeF(), font.family().toStdString(), font.styleName().toStdString(),
font.weight(), util::to_string(font.exactMatch()));
}
return font;
}
//! Removes entries from a map where QPointer keys point to deleted objects
template <typename T>
size_t pruneStaleEntities(T& map)
{
size_t removed{0};
auto it = map.begin();
while (it != map.end()) {
if (it->first.isNull()) {
it = map.erase(it);
++removed;
} else {
++it;
}
}
return removed;
}
//! Initializes QTextEdit with HTML and applies font styling
void setFontBodyHTML(QTextEdit* widget, const QString& src, double base_size)
{
if (!GUIUtil::fontsLoaded() || !widget) return;
QFont font{GUIUtil::getScaledFont(base_size, /*bold=*/false)};
widget->setFont(font);
widget->setHtml(src);
QFont font_bold{GUIUtil::getScaledFont(base_size, /*bold=*/true)};
QTextDocument* doc{widget->document()};
for (QTextBlock block{doc->begin()}; block.isValid(); block = block.next()) {
const int heading_level{block.blockFormat().headingLevel()};
double scale_add{0};
switch (heading_level) {
case 1:
scale_add = 0.10;
break;
case 2:
scale_add = 0.04;
break;
case 3:
scale_add = 0.02;
break;
default:
break;
}
for (auto it = block.begin(); !it.atEnd(); ++it) {
QTextFragment fragment{it.fragment()};
if (!fragment.isValid()) {
continue;
}
if (fragment.charFormat().fontWeight() >= QFont::Bold || scale_add > 0) {
QTextCursor cursor(doc);
cursor.setPosition(fragment.position());
cursor.setPosition(fragment.position() + fragment.length(), QTextCursor::KeepAnchor);
QTextCharFormat fmt;
fmt.setFontFamily(font_bold.family());
fmt.setFontWeight(font_bold.weight());
#ifdef Q_OS_MACOS
if (!font_bold.styleName().isEmpty()) {
fmt.setFontStyleName(font_bold.styleName());
}
#endif // Q_OS_MACOS
if (scale_add > 0) {
fmt.setFontPointSize(g_font_registry.GetScaledFontSize(base_size * (1 + scale_add)));
}
cursor.mergeCharFormat(fmt);
}
}
}
}
//! Internal helper to create a font with explicit weight (used for font detection)
QFont getFontWithWeight(const QString& font_name, QFont::Weight weight, double point_size)
{
QFont font;
if (font_name == MONTSERRAT_FONT_STR) {
if (mapMontserrat.count(weight)) {
#ifdef Q_OS_MACOS
font.setFamily(font_name);
font.setStyleName(QString::fromStdString(mapMontserrat.at(weight).first));
#else
if (weight == QFont::Normal || weight == QFont::Bold) {
font.setFamily(font_name);
} else {
font.setFamily(qstrprintf("%s %s", font_name.toStdString(), mapMontserrat.at(weight).first));
}
#endif
}
} else if (font_name == OS_FONT_STR && g_default_font) {
font.setFamily(g_default_font->family());
} else {
font.setFamily(font_name);
}
#ifdef Q_OS_MACOS
if (font_name != MONTSERRAT_FONT_STR)
#endif
{
font.setWeight(weight);
}
font.setPointSizeF(point_size);
return font;
}
FontInfo::FontInfo(const QString& font_name)
{
CalcSupportedWeights(font_name);
CalcDefaultWeights(font_name);
m_bold = m_bold_default;
m_normal = m_normal_default;
}
FontInfo::~FontInfo() = default;
void FontInfo::CalcSupportedWeights(const QString& font_name)
{
auto getTestWidth = [](const QString& font_name, QFont::Weight weight) -> int {
QFont font = getFontWithWeight(font_name, weight, DEFAULT_FONT_SIZE);
return GUIUtil::TextWidth(QFontMetrics(font), ("Check the width of this text to see if the weight change has an impact!"));
};
QFont::Weight prevWeight = vecWeightConsider.front();
bool isFirst = true;
for (const auto& weight : vecWeightConsider) {
if (isFirst) {
isFirst = false;
continue;
}
if (getTestWidth(font_name, prevWeight) != getTestWidth(font_name, weight)) {
if (m_supported_weights.empty()) {
m_supported_weights.push_back(prevWeight);
}
m_supported_weights.push_back(weight);
}
prevWeight = weight;
}
if (m_supported_weights.empty()) {
m_supported_weights.push_back(QFont::Normal);
}
}
QFont::Weight FontInfo::GetBestMatch(const QString& font_name, QFont::Weight target)
{
assert(!m_supported_weights.empty());
QFont::Weight bestWeight = m_supported_weights.front();
int nBestDiff = abs(bestWeight - target);
for (const auto& weight : m_supported_weights) {
int nDiff = abs(weight - target);
if (nDiff < nBestDiff) {
bestWeight = weight;
nBestDiff = nDiff;
}
}
return bestWeight;
}
void FontInfo::CalcDefaultWeights(const QString& font_name)
{
assert(!m_supported_weights.empty());
m_normal_default = GetBestMatch(font_name, TARGET_WEIGHT_NORMAL);
m_bold_default = GetBestMatch(font_name, TARGET_WEIGHT_BOLD);
if (m_normal_default == m_bold_default) {
// If the results are the same use the next possible weight for bold font
auto it = std::find(m_supported_weights.begin(), m_supported_weights.end(), m_normal_default);
if (++it != m_supported_weights.end()) {
m_bold_default = *it;
}
}
}
bool FontRegistry::RegisterFont(const QString& font, bool selectable, bool skip_checks)
{
auto font_it = std::find_if(g_fonts_known.begin(), g_fonts_known.end(),
[&](const auto& p) { return p.first == font; });
if (m_weights.count(font)) {
// Font's already registered — overwrite selectable flag
assert(font_it != g_fonts_known.end());
font_it->second = selectable;
return true;
}
if (!skip_checks) {
if (!g_font_db) { g_font_db = std::make_unique<QFontDatabase>(); }
if (!g_font_db->families().contains(font, Qt::CaseInsensitive)) {
// Font doesn't exist
return false;
}
}
m_weights.emplace(font, FontInfo(font));
if (font_it == g_fonts_known.end()) {
g_fonts_known.emplace_back(font, selectable);
}
return true;
}
bool FontRegistry::SetFont(const QString& font)
{
if (!m_weights.count(font)) {
return false;
}
m_font = font;
return true;
}
bool FontRegistry::IsValidWeight(const QFont::Weight& weight) const
{
const auto supported = GetSupportedWeights();
return std::find(supported.begin(), supported.end(), weight) != supported.end();
}
} // anonymous namespace
namespace GUIUtil {
int defaultFontScale() { return DEFAULT_FONT_SCALE; }
int defaultFontSize() { return DEFAULT_FONT_SIZE; }
QString defaultFontFamily() { return DEFAULT_FONT.toString(); }
bool setActiveFont(const QString& font_name)
{
if (!fontsLoaded()) return false;
const QString name = font_name.isEmpty() ? defaultFontFamily() : font_name;
if (!g_font_registry.RegisterFont(name, /*selectable=*/true)) return false;
if (!g_font_registry.SetFont(name)) return false;
setApplicationFont();
return true;
}
QString activeFont() { return g_font_registry.GetFont(); }
const std::vector<std::pair<QString, bool>>& knownFonts() { return g_fonts_known; }
void setFontScale(int font_scale) { g_font_registry.SetFontScale(font_scale); }
int fontScale() { return g_font_registry.GetFontScale(); }
int currentWeightArg(FontWeight slot)
{
return weightToArg(slot == FontWeight::Bold ? g_font_registry.GetWeightBold()
: g_font_registry.GetWeightNormal());
}
int defaultWeightArg(FontWeight slot)
{
return weightToArg(slot == FontWeight::Bold ? g_font_registry.GetWeightBoldDefault()
: g_font_registry.GetWeightNormalDefault());
}
bool setWeightFromArg(FontWeight slot, int arg)
{
QFont::Weight weight;
if (!weightFromArg(arg, weight) || !g_font_registry.IsValidWeight(weight)) return false;
if (slot == FontWeight::Bold) {
g_font_registry.SetWeightBold(weight);
} else {
g_font_registry.SetWeightNormal(weight);
}
return true;
}
std::vector<int> supportedWeightArgs()
{
std::vector<int> ret;
for (const auto& w : g_font_registry.GetSupportedWeights()) {
ret.push_back(weightToArg(w));
}
return ret;
}
bool loadFonts()
{
// Before any font changes store the applications default font to use it as SystemDefault.
g_default_font = std::make_unique<QFont>(QApplication::font());
std::vector<int> vecFontIds{};
auto importFont = [&vecFontIds](const QString& font_name) -> void {
vecFontIds.push_back(QFontDatabase::addApplicationFont(font_name));
qDebug() << qstrprintf("%s: %s loaded with id %d", __func__, font_name.toStdString(), vecFontIds.back());
};
// Import the embedded Roboto Mono used by fixedPitchFont(use_embedded_font=true)
importFont(":fonts/monospace");
// Import the italic Montserrat variant as it doesn't map to a weight
importFont(qstrprintf(":fonts/%s-Italic", MONTSERRAT_FONT_STR.toUtf8().toStdString()));
// Import the rest of Montserrat variants
for (const auto& [_, val] : mapMontserrat) {
const auto& [variant, can_italic] = val;
importFont(qstrprintf(":fonts/%s-%s", MONTSERRAT_FONT_STR.toUtf8().toStdString(), variant));
if (can_italic) {
importFont(qstrprintf(":fonts/%s-%sItalic", MONTSERRAT_FONT_STR.toUtf8().toStdString(), variant));
}
}
// Fail if an added id is -1 which means QFontDatabase::addApplicationFont failed.
if (std23::ranges::contains(vecFontIds, -1)) {
g_default_font = nullptr;
return false;
}
#ifndef QT_NO_DEBUG
if (!g_font_db) { g_font_db = std::make_unique<QFontDatabase>(); }
// Print debug logs for added fonts fetched by the added ids
for (const auto& i : vecFontIds) {
for (const QString& f : QFontDatabase::applicationFontFamilies(i)) {
qDebug() << qstrprintf("%s: - Font id %d is family: %s", __func__, i, f.toStdString());
for (const QString& style : g_font_db->styles(f)) {
qDebug() << qstrprintf("%s: Style for family %s with id: %d is %s", __func__, f.toStdString(), i,
style.toStdString());
}
}
}
// Print debug logs for added fonts fetched by the family name
for (const QString& f : g_font_db->families()) {
if (f.contains(MONTSERRAT_FONT_STR)) {
for (const QString& style : g_font_db->styles(f)) {
qDebug() << qstrprintf("%s: Family: %s, Style: %s", __func__, f.toStdString(), style.toStdString());
}
}
}
#endif // QT_NO_DEBUG
for (const auto& [fonts, selectable] : g_fonts_known) {
assert(g_font_registry.RegisterFont(fonts, selectable, /*skip_checks=*/true));
}
return true;
}
bool fontsLoaded()
{
return g_default_font != nullptr;
}
void setApplicationFont()
{
if (!fontsLoaded()) {
return;
}
std::unique_ptr<QFont> font;
auto family = g_font_registry.GetFont();
if (family == MONTSERRAT_FONT_STR) {
#ifdef Q_OS_MACOS
font = std::make_unique<QFont>(getFontNormal());
#else
font = std::make_unique<QFont>(family);
font->setWeight(g_font_registry.GetWeightNormal());
#endif
} else if (family == OS_FONT_STR) {
font = std::make_unique<QFont>(*g_default_font);
} else {
font = std::make_unique<QFont>(family);
}
font->setPointSizeF(g_font_registry.GetFontSize());
qApp->setFont(*font);
qDebug() << qstrprintf("%s: %s family: %s, style: %s match: %s", __func__, qApp->font().toString().toStdString(),
qApp->font().family().toStdString(), qApp->font().styleName().toStdString(),
util::to_string(qApp->font().exactMatch()));
}
void setFont(const std::vector<QWidget*>& vecWidgets, const QString& font, FontWeight weight, double point_size, bool is_italic)
{
const FontAttrib font_attrib{font, weight, point_size, is_italic};
for (auto it : vecWidgets) {
auto itFontUpdate = mapFontUpdates.emplace(std::make_pair(it, font_attrib));
if (!itFontUpdate.second) {
itFontUpdate.first->second = font_attrib;
}
}
}
void setFont(const std::vector<QWidget*>& vecWidgets, FontWeight weight, double point_size, bool is_italic)
{
setFont(vecWidgets, g_font_registry.GetFont(), weight, point_size, is_italic);
}
void updateFonts()
{
// Fonts need to be loaded by GUIUtil::loadFonts(), if not just return.
if (!g_default_font) {
return;
}
static std::map<QPointer<QWidget>, double> mapWidgetDefaultFontSizes;
// QPointer becomes nullptr for objects that were deleted.
// Remove them from mapDefaultFontSize and mapFontUpdates
// before proceeding any further.
const size_t nRemovedDefaultFonts{pruneStaleEntities(mapWidgetDefaultFontSizes)};
const size_t nRemovedFontUpdates{pruneStaleEntities(mapFontUpdates)};
const size_t nRemovedTextEditUpdates{pruneStaleEntities(mapTextEditStyleUpdates)};
size_t nUpdatable{0}, nUpdated{0};
std::map<QWidget*, QFont> mapWidgetFonts;
// Loop through all widgets
for (QWidget* w : qApp->allWidgets()) {
if (auto* wt{qobject_cast<QTextEdit*>(w)};
std23::ranges::contains(vecIgnoreClasses, w->metaObject()->className()) ||
std23::ranges::contains(vecIgnoreObjects, w->objectName().toStdString()) ||
(wt && mapTextEditStyleUpdates.count(wt)))
{
// Do not apply styling logic if ignored or handled separately
continue;
}
++nUpdatable;
QFont font = w->font();
assert(font.pointSize() > 0);
font.setFamily(qApp->font().family());
font.setWeight(g_font_registry.GetWeightNormal());
font.setStyleName(qApp->font().styleName());
font.setStyle(qApp->font().style());
// Insert/Get the default font size of the widget
auto itDefault = mapWidgetDefaultFontSizes.emplace(w, font.pointSize());
auto it = mapFontUpdates.find(w);
if (it != mapFontUpdates.end()) {
double nSize = it->second.m_point_size;
if (nSize == -1) {
nSize = itDefault.first->second;
}
font = getFont({it->second.m_font, it->second.m_weight_type, nSize, it->second.m_is_italic});
} else {
font.setPointSizeF(g_font_registry.GetScaledFontSize(itDefault.first->second));
}
if (w->font() != font) {
auto itWidgetFont = mapWidgetFonts.emplace(w, font);
assert(itWidgetFont.second);
++nUpdated;
}
}
qDebug().nospace() << qstrprintf("%s - widget counts: updated/updatable/total(%d/%d/%d), removed items: "
"mapWidgetDefaultFontSizes/mapFontUpdates/mapTextEditStyleUpdates(%d/%d/%d)",
__func__, nUpdated, nUpdatable, qApp->allWidgets().size(), nRemovedDefaultFonts,
nRemovedFontUpdates, nRemovedTextEditUpdates);
// Perform the required font updates
// NOTE: This is done as separate step to avoid scaling issues due to font inheritance
// hence all fonts are calculated and stored in mapWidgetFonts above.
for (auto it : mapWidgetFonts) {
it.first->setFont(it.second);
}
// Scale the global font size for the classes in the map below
for (auto& it : mapClassFontUpdates) {
QFont fontClass = qApp->font(it.first.c_str());
if (it.second == -1) {
it.second = fontClass.pointSize();
}
double dSize = g_font_registry.GetScaledFontSize(it.second);
if (fontClass.pointSizeF() != dSize) {
fontClass.setPointSizeF(dSize);
qApp->setFont(fontClass, it.first.c_str());
}
}
// Update registered QTextEdit widgets
for (const auto& [widget, data] : mapTextEditStyleUpdates) {
setFontBodyHTML(widget, data.html, data.base_size);
}
}
QFont getFontBold()
{
return getFont({g_font_registry.GetFont(), FontWeight::Bold});
}
QFont getFontNormal()
{
return getFont({g_font_registry.GetFont(), FontWeight::Normal});
}
QFont getScaledFont(double baseSize, bool bold, double multiplier)
{
return getFont({
g_font_registry.GetFont(),
bold ? FontWeight::Bold : FontWeight::Normal,
baseSize * multiplier
});
}
QFont fixedPitchFont(bool use_embedded_font)
{
return getFont({
use_embedded_font ? ROBOTO_MONO_FONT_STR.toUtf8() : OS_MONO_FONT_STR.toUtf8(),
FontWeight::Normal
});
}
void setStyledHtml(QTextEdit* widget, const QString& html)
{
if (!widget) return;
double base_size{DEFAULT_FONT_SIZE};
auto it{mapTextEditStyleUpdates.find(widget)};
if (it != mapTextEditStyleUpdates.end()) {
// Widget already registered, preserve stored base_size and update HTML
base_size = it->second.base_size;
it->second.html = html;
} else {
// First registration, capture the widget's native font size
double widget_size{widget->font().pointSizeF()};
if (widget_size > 0) {
base_size = widget_size;
}
mapTextEditStyleUpdates[widget] = {html, base_size};
}
setFontBodyHTML(widget, html, base_size);
}
} // namespace GUIUtil