-
Notifications
You must be signed in to change notification settings - Fork 8.5k
/
Copy pathAppearances.cpp
1329 lines (1125 loc) · 48.6 KB
/
Appearances.cpp
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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "pch.h"
#include "Appearances.h"
#include <LibraryResources.h>
#include "../WinRTUtils/inc/Utils.h"
#include "EnumEntry.h"
#include "ProfileViewModel.h"
#include "Appearances.g.cpp"
using namespace winrt::Windows::UI::Text;
using namespace winrt::Windows::UI::Xaml;
using namespace winrt::Windows::UI::Xaml::Controls;
using namespace winrt::Windows::UI::Xaml::Data;
using namespace winrt::Windows::UI::Xaml::Navigation;
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::Foundation::Collections;
using namespace winrt::Microsoft::Terminal::Settings::Model;
// These features are enabled by default by DWrite, so if a user adds them,
// we initialize the setting to a value of 1 instead of 0.
static constexpr std::array s_defaultFeatures{
DWRITE_MAKE_FONT_FEATURE_TAG('c', 'a', 'l', 't'),
DWRITE_MAKE_FONT_FEATURE_TAG('c', 'c', 'm', 'p'),
DWRITE_MAKE_FONT_FEATURE_TAG('c', 'l', 'i', 'g'),
DWRITE_MAKE_FONT_FEATURE_TAG('d', 'i', 's', 't'),
DWRITE_MAKE_FONT_FEATURE_TAG('k', 'e', 'r', 'n'),
DWRITE_MAKE_FONT_FEATURE_TAG('l', 'i', 'g', 'a'),
DWRITE_MAKE_FONT_FEATURE_TAG('l', 'o', 'c', 'l'),
DWRITE_MAKE_FONT_FEATURE_TAG('m', 'a', 'r', 'k'),
DWRITE_MAKE_FONT_FEATURE_TAG('m', 'k', 'm', 'k'),
DWRITE_MAKE_FONT_FEATURE_TAG('r', 'l', 'i', 'g'),
DWRITE_MAKE_FONT_FEATURE_TAG('r', 'n', 'r', 'n'),
};
namespace winrt::Microsoft::Terminal::Settings::Editor::implementation
{
struct TagToStringImpl
{
explicit TagToStringImpl(uint32_t tag) noexcept
{
_buffer[0] = static_cast<wchar_t>((tag >> 0) & 0xFF);
_buffer[1] = static_cast<wchar_t>((tag >> 8) & 0xFF);
_buffer[2] = static_cast<wchar_t>((tag >> 16) & 0xFF);
_buffer[3] = static_cast<wchar_t>((tag >> 24) & 0xFF);
_buffer[4] = 0;
}
operator std::wstring_view() const noexcept
{
return { &_buffer[0], 4 };
}
private:
wchar_t _buffer[5];
};
// Turns a DWRITE_MAKE_OPENTYPE_TAG into a string_view...
// (...buffer holder because someone needs to hold onto the data the view refers to.)
static TagToStringImpl tagToString(uint32_t tag) noexcept
{
return TagToStringImpl{ tag };
}
// Turns a string to a DWRITE_MAKE_OPENTYPE_TAG. Returns 0 on failure.
static uint32_t tagFromString(std::wstring_view str) noexcept
{
if (str.size() != 4)
{
return 0;
}
// Check if all 4 characters are printable ASCII.
for (int i = 0; i < 4; ++i)
{
const auto ch = str[i];
if (ch < 0x20 || ch > 0x7E)
{
return 0;
}
}
return DWRITE_MAKE_OPENTYPE_TAG(str[0], str[1], str[2], str[3]);
}
static winrt::hstring getLocalizedStringByIndex(IDWriteLocalizedStrings* strings, UINT32 index)
{
UINT32 length = 0;
THROW_IF_FAILED(strings->GetStringLength(index, &length));
winrt::impl::hstring_builder builder{ length };
THROW_IF_FAILED(strings->GetString(index, builder.data(), length + 1));
return builder.to_hstring();
}
static UINT32 getLocalizedStringIndex(IDWriteLocalizedStrings* strings, const wchar_t* locale, UINT32 fallback)
{
UINT32 index;
BOOL exists;
if (FAILED(strings->FindLocaleName(locale, &index, &exists)) || !exists)
{
index = fallback;
}
return index;
}
Font::Font(winrt::hstring name, winrt::hstring localizedName) :
_Name{ std::move(name) },
_LocalizedName{ std::move(localizedName) }
{
}
bool FontKeyValuePair::SortAscending(const Editor::FontKeyValuePair& lhs, const Editor::FontKeyValuePair& rhs)
{
const auto& a = winrt::get_self<FontKeyValuePair>(lhs)->KeyDisplayStringRef();
const auto& b = winrt::get_self<FontKeyValuePair>(rhs)->KeyDisplayStringRef();
return til::compare_linguistic_insensitive(a, b) < 0;
}
FontKeyValuePair::FontKeyValuePair(winrt::weak_ref<AppearanceViewModel> vm, winrt::hstring keyDisplayString, uint32_t key, float value, bool isFontFeature) :
_vm{ std::move(vm) },
_keyDisplayString{ std::move(keyDisplayString) },
_key{ key },
_value{ value },
_isFontFeature{ isFontFeature }
{
}
uint32_t FontKeyValuePair::Key() const noexcept
{
return _key;
}
winrt::hstring FontKeyValuePair::KeyDisplayString()
{
return KeyDisplayStringRef();
}
// You can't return a const-ref from a WinRT function, because the cppwinrt generated wrapper chokes on it.
// So, now we got two KeyDisplayString() functions, because I refuse to AddRef/Release this for no reason.
// I mean, really it makes no perf. difference, but I'm not kneeling down for an incompetent code generator.
const winrt::hstring& FontKeyValuePair::KeyDisplayStringRef()
{
if (!_keyDisplayString.empty())
{
return _keyDisplayString;
}
const auto tagString = tagToString(_key);
hstring displayString;
if (_isFontFeature)
{
const auto key = fmt::format(FMT_COMPILE(L"Profile_FontFeature_{}"), std::wstring_view{ tagString });
if (HasLibraryResourceWithName(key))
{
displayString = GetLibraryResourceString(key);
displayString = hstring{ fmt::format(FMT_COMPILE(L"{} ({})"), displayString, std::wstring_view{ tagString }) };
}
}
if (displayString.empty())
{
displayString = hstring{ tagString };
}
_keyDisplayString = displayString;
return _keyDisplayString;
}
float FontKeyValuePair::Value() const noexcept
{
return _value;
}
void FontKeyValuePair::Value(float v)
{
if (_value == v)
{
return;
}
_value = v;
if (const auto vm = _vm.get())
{
vm->UpdateFontSetting(this);
}
}
void FontKeyValuePair::SetValueDirect(float v)
{
_value = v;
}
bool FontKeyValuePair::IsFontFeature() const noexcept
{
return _isFontFeature;
}
AppearanceViewModel::AppearanceViewModel(const Model::AppearanceConfig& appearance) :
_appearance{ appearance }
{
// Add a property changed handler to our own property changed event.
// This propagates changes from the settings model to anybody listening to our
// unique view model members.
PropertyChanged([this](auto&&, const PropertyChangedEventArgs& args) {
const auto viewModelProperty{ args.PropertyName() };
if (viewModelProperty == L"BackgroundImagePath")
{
// notify listener that all background image related values might have changed
//
// We need to do this so if someone manually types "desktopWallpaper"
// into the path TextBox, we properly update the checkbox and stored
// _lastBgImagePath. Without this, then we'll permanently hide the text
// box, prevent it from ever being changed again.
_NotifyChanges(L"UseDesktopBGImage", L"BackgroundImageSettingsVisible");
}
});
// Cache the original BG image path. If the user clicks "Use desktop
// wallpaper", then un-checks it, this is the string we'll restore to
// them.
if (BackgroundImagePath() != L"desktopWallpaper")
{
_lastBgImagePath = BackgroundImagePath();
}
}
winrt::hstring AppearanceViewModel::FontFace() const
{
return _appearance.SourceProfile().FontInfo().FontFace();
}
void AppearanceViewModel::FontFace(const winrt::hstring& value)
{
const auto fontInfo = _appearance.SourceProfile().FontInfo();
if (fontInfo.FontFace() == value)
{
return;
}
fontInfo.FontFace(value);
_invalidateFontFaceDependents();
_NotifyChanges(L"HasFontFace", L"FontFace");
}
bool AppearanceViewModel::HasFontFace() const
{
return _appearance.SourceProfile().FontInfo().HasFontFace();
}
void AppearanceViewModel::ClearFontFace()
{
const auto fontInfo = _appearance.SourceProfile().FontInfo();
fontInfo.ClearFontFace();
_invalidateFontFaceDependents();
_NotifyChanges(L"HasFontFace", L"FontFace");
}
Model::FontConfig AppearanceViewModel::FontFaceOverrideSource() const
{
return _appearance.SourceProfile().FontInfo().FontFaceOverrideSource();
}
void AppearanceViewModel::_refreshFontFaceDependents()
{
wil::com_ptr<IDWriteFactory> factory;
THROW_IF_FAILED(DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(factory), reinterpret_cast<::IUnknown**>(factory.addressof())));
wil::com_ptr<IDWriteFontCollection> fontCollection;
THROW_IF_FAILED(factory->GetSystemFontCollection(fontCollection.addressof(), FALSE));
const auto fontFaceSpec = FontFace();
std::wstring missingFonts;
std::wstring proportionalFonts;
std::array<std::vector<Editor::FontKeyValuePair>, 2> fontSettingsRemaining;
BOOL hasPowerlineCharacters = FALSE;
wchar_t localeNameBuffer[LOCALE_NAME_MAX_LENGTH];
const auto localeName = GetUserDefaultLocaleName(localeNameBuffer, LOCALE_NAME_MAX_LENGTH) ? localeNameBuffer : L"en-US";
til::iterate_font_families(fontFaceSpec, [&](wil::zwstring_view name) {
std::wstring* accumulator = nullptr;
try
{
UINT32 index = 0;
BOOL exists = FALSE;
THROW_IF_FAILED(fontCollection->FindFamilyName(name.c_str(), &index, &exists));
// Look ma, no goto!
do
{
if (!exists)
{
accumulator = &missingFonts;
break;
}
wil::com_ptr<IDWriteFontFamily> fontFamily;
THROW_IF_FAILED(fontCollection->GetFontFamily(index, fontFamily.addressof()));
wil::com_ptr<IDWriteFont> font;
THROW_IF_FAILED(fontFamily->GetFirstMatchingFont(DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STRETCH_NORMAL, DWRITE_FONT_STYLE_NORMAL, font.addressof()));
if (!font.query<IDWriteFont1>()->IsMonospacedFont())
{
accumulator = &proportionalFonts;
}
// We're actually checking for the "Extended" PowerLine glyph set.
// They're more fun.
BOOL hasE0B6 = FALSE;
std::ignore = font->HasCharacter(0xE0B6, &hasE0B6);
hasPowerlineCharacters |= hasE0B6;
wil::com_ptr<IDWriteFontFace> fontFace;
THROW_IF_FAILED(font->CreateFontFace(fontFace.addressof()));
_generateFontAxes(fontFace.get(), localeName, fontSettingsRemaining[FontAxesIndex]);
_generateFontFeatures(fontFace.get(), fontSettingsRemaining[FontFeaturesIndex]);
} while (false);
}
catch (...)
{
accumulator = &missingFonts;
LOG_CAUGHT_EXCEPTION();
}
if (accumulator)
{
if (!accumulator->empty())
{
accumulator->append(L", ");
}
accumulator->append(name);
}
});
// Up to this point, our two vectors are sorted by tag value. We want to sort them by display string now,
// because this will result in sorted fontSettingsUsed/Unused lists below.
for (auto& v : fontSettingsRemaining)
{
std::sort(v.begin(), v.end(), FontKeyValuePair::SortAscending);
}
std::array<std::vector<Editor::FontKeyValuePair>, 2> fontSettingsUsed;
const std::array fontSettingsUser{
_appearance.SourceProfile().FontInfo().FontAxes(),
_appearance.SourceProfile().FontInfo().FontFeatures(),
};
// Find all axes and features that are in the user settings, and move them to the used list.
// They'll be displayed as a list in the UI.
for (int i = FontAxesIndex; i <= FontFeaturesIndex; i++)
{
const auto& map = fontSettingsUser[i];
if (!map)
{
continue;
}
for (const auto& [tagString, value] : fontSettingsUser[i])
{
const auto tag = tagFromString(tagString);
if (!tag)
{
continue;
}
auto& remaining = fontSettingsRemaining[i];
const auto it = std::ranges::find_if(remaining, [&](const Editor::FontKeyValuePair& kv) {
return winrt::get_self<FontKeyValuePair>(kv)->Key() == tag;
});
Editor::FontKeyValuePair kv{ nullptr };
if (it != remaining.end())
{
kv = std::move(*it);
remaining.erase(it);
const auto kvImpl = winrt::get_self<FontKeyValuePair>(kv);
kvImpl->SetValueDirect(value);
}
else
{
kv = winrt::make<FontKeyValuePair>(get_weak(), hstring{}, tag, value, i == FontFeaturesIndex);
}
fontSettingsUsed[i].emplace_back(std::move(kv));
}
}
std::array<std::vector<MenuFlyoutItemBase>, 2> fontSettingsUnused;
// All remaining (= unused) axes and features are turned into menu items.
// They'll be displayed as a flyout when clicking the "add item" button.
for (int i = FontAxesIndex; i <= FontFeaturesIndex; i++)
{
for (const auto& kv : fontSettingsRemaining[i])
{
fontSettingsUnused[i].emplace_back(_createFontSettingMenuItem(kv));
}
}
auto& d = _fontFaceDependents.emplace();
d.missingFontFaces = winrt::hstring{ missingFonts };
d.proportionalFontFaces = winrt::hstring{ proportionalFonts };
d.hasPowerlineCharacters = hasPowerlineCharacters;
d.fontSettingsUsed[FontAxesIndex] = winrt::single_threaded_observable_vector(std::move(fontSettingsUsed[FontAxesIndex]));
d.fontSettingsUsed[FontFeaturesIndex] = winrt::single_threaded_observable_vector(std::move(fontSettingsUsed[FontFeaturesIndex]));
d.fontSettingsUnused = std::move(fontSettingsUnused);
_notifyChangesForFontSettings();
}
std::pair<std::vector<Editor::FontKeyValuePair>::const_iterator, bool> AppearanceViewModel::_fontSettingSortedByKeyInsertPosition(const std::vector<Editor::FontKeyValuePair>& vec, uint32_t key)
{
const auto it = std::lower_bound(vec.begin(), vec.end(), key, [](const Editor::FontKeyValuePair& lhs, uint32_t rhs) {
return winrt::get_self<FontKeyValuePair>(lhs)->Key() < rhs;
});
const auto exists = it != vec.end() && winrt::get_self<FontKeyValuePair>(*it)->Key() == key;
return { it, exists };
}
void AppearanceViewModel::_generateFontAxes(IDWriteFontFace* fontFace, const wchar_t* localeName, std::vector<Editor::FontKeyValuePair>& list)
{
const auto fontFace5 = wil::try_com_query<IDWriteFontFace5>(fontFace);
if (!fontFace5)
{
return;
}
const auto axesCount = fontFace5->GetFontAxisValueCount();
if (axesCount == 0)
{
return;
}
std::vector<DWRITE_FONT_AXIS_VALUE> axesVector(axesCount);
THROW_IF_FAILED(fontFace5->GetFontAxisValues(axesVector.data(), axesCount));
wil::com_ptr<IDWriteFontResource> fontResource;
THROW_IF_FAILED(fontFace5->GetFontResource(fontResource.addressof()));
for (UINT32 i = 0; i < axesCount; ++i)
{
wil::com_ptr<IDWriteLocalizedStrings> names;
THROW_IF_FAILED(fontResource->GetAxisNames(i, names.addressof()));
// As per MSDN:
// > The font author may not have supplied names for some font axes.
// > The localized strings will be empty in that case.
if (names->GetCount() == 0)
{
continue;
}
const auto tag = axesVector[i].axisTag;
const auto [it, tagExists] = _fontSettingSortedByKeyInsertPosition(list, tag);
if (tagExists)
{
continue;
}
UINT32 index;
BOOL exists;
if (FAILED(names->FindLocaleName(localeName, &index, &exists)) || !exists)
{
index = 0;
}
const auto idx = getLocalizedStringIndex(names.get(), localeName, 0);
const auto localizedName = getLocalizedStringByIndex(names.get(), idx);
const auto tagString = tagToString(tag);
hstring displayString{ fmt::format(FMT_COMPILE(L"{} ({})"), localizedName, std::wstring_view{ tagString }) };
const auto value = axesVector[i].value;
list.emplace(it, winrt::make<FontKeyValuePair>(get_weak(), std::move(displayString), tag, value, false));
}
}
void AppearanceViewModel::_generateFontFeatures(IDWriteFontFace* fontFace, std::vector<Editor::FontKeyValuePair>& list)
{
wil::com_ptr<IDWriteFactory> factory;
THROW_IF_FAILED(DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(factory), reinterpret_cast<::IUnknown**>(factory.addressof())));
wil::com_ptr<IDWriteTextAnalyzer> textAnalyzer;
THROW_IF_FAILED(factory->CreateTextAnalyzer(textAnalyzer.addressof()));
const auto textAnalyzer2 = textAnalyzer.query<IDWriteTextAnalyzer2>();
static constexpr DWRITE_SCRIPT_ANALYSIS scriptAnalysis{};
UINT32 tagCount;
if (textAnalyzer2->GetTypographicFeatures(fontFace, scriptAnalysis, L"en-US", 0, &tagCount, nullptr) != E_NOT_SUFFICIENT_BUFFER)
{
return;
}
std::vector<DWRITE_FONT_FEATURE_TAG> tags{ tagCount };
if (FAILED(textAnalyzer2->GetTypographicFeatures(fontFace, scriptAnalysis, L"en-US", tagCount, &tagCount, tags.data())))
{
return;
}
for (const auto& tag : tags)
{
const auto [it, tagExists] = _fontSettingSortedByKeyInsertPosition(list, tag);
if (tagExists)
{
continue;
}
const auto dfBeg = s_defaultFeatures.begin();
const auto dfEnd = s_defaultFeatures.end();
const auto isDefaultFeature = std::find(dfBeg, dfEnd, tag) != dfEnd;
const auto value = isDefaultFeature ? 1.0f : 0.0f;
list.emplace(it, winrt::make<FontKeyValuePair>(get_weak(), hstring{}, tag, value, true));
}
}
MenuFlyoutItemBase AppearanceViewModel::_createFontSettingMenuItem(const Editor::FontKeyValuePair& kv)
{
const auto kvImpl = winrt::get_self<FontKeyValuePair>(kv);
MenuFlyoutItem item;
item.Text(kvImpl->KeyDisplayStringRef());
item.Click([weakSelf = get_weak(), kv](const IInspectable& sender, const RoutedEventArgs&) {
if (const auto self = weakSelf.get())
{
self->AddFontKeyValuePair(sender, kv);
}
});
return item;
}
// Call this when all the _fontFaceDependents members have changed.
void AppearanceViewModel::_notifyChangesForFontSettings()
{
_NotifyChanges(L"FontFaceDependents");
_NotifyChanges(L"FontAxes");
_NotifyChanges(L"FontFeatures");
_NotifyChanges(L"HasFontAxes");
_NotifyChanges(L"HasFontFeatures");
}
// Call this when used items moved into unused and vice versa.
// Because this doesn't recreate the IObservableVector instances,
// we don't need to notify the UI about changes to the "FontAxes" property.
void AppearanceViewModel::_notifyChangesForFontSettingsReactive(FontSettingIndex fontSettingsIndex)
{
_NotifyChanges(L"FontFaceDependents");
switch (fontSettingsIndex)
{
case FontAxesIndex:
_NotifyChanges(L"HasFontAxes");
break;
case FontFeaturesIndex:
_NotifyChanges(L"HasFontFeatures");
break;
default:
break;
}
}
double AppearanceViewModel::LineHeight() const
{
const auto fontInfo = _appearance.SourceProfile().FontInfo();
const auto cellHeight = fontInfo.CellHeight();
const auto str = cellHeight.c_str();
auto& errnoRef = errno; // Nonzero cost, pay it once.
errnoRef = 0;
wchar_t* end;
const auto value = std::wcstod(str, &end);
return str == end || errnoRef == ERANGE ? NAN : value;
}
void AppearanceViewModel::LineHeight(const double value)
{
std::wstring str;
if (value >= 0.1 && value <= 10.0)
{
str = fmt::format(FMT_STRING(L"{:.6g}"), value);
}
const auto fontInfo = _appearance.SourceProfile().FontInfo();
if (fontInfo.CellHeight() != str)
{
if (str.empty())
{
fontInfo.ClearCellHeight();
}
else
{
fontInfo.CellHeight(str);
}
_NotifyChanges(L"HasLineHeight", L"LineHeight");
}
}
bool AppearanceViewModel::HasLineHeight() const
{
const auto fontInfo = _appearance.SourceProfile().FontInfo();
return fontInfo.HasCellHeight();
}
void AppearanceViewModel::ClearLineHeight()
{
LineHeight(NAN);
}
Model::FontConfig AppearanceViewModel::LineHeightOverrideSource() const
{
const auto fontInfo = _appearance.SourceProfile().FontInfo();
return fontInfo.CellHeightOverrideSource();
}
void AppearanceViewModel::SetFontWeightFromDouble(double fontWeight)
{
FontWeight(winrt::Microsoft::Terminal::UI::Converters::DoubleToFontWeight(fontWeight));
}
const AppearanceViewModel::FontFaceDependentsData& AppearanceViewModel::FontFaceDependents()
{
if (!_fontFaceDependents)
{
_refreshFontFaceDependents();
}
return *_fontFaceDependents;
}
winrt::hstring AppearanceViewModel::MissingFontFaces()
{
return FontFaceDependents().missingFontFaces;
}
winrt::hstring AppearanceViewModel::ProportionalFontFaces()
{
return FontFaceDependents().proportionalFontFaces;
}
bool AppearanceViewModel::HasPowerlineCharacters()
{
return FontFaceDependents().hasPowerlineCharacters;
}
IObservableVector<Editor::FontKeyValuePair> AppearanceViewModel::FontAxes()
{
return FontFaceDependents().fontSettingsUsed[FontAxesIndex];
}
bool AppearanceViewModel::HasFontAxes() const
{
return _appearance.SourceProfile().FontInfo().HasFontAxes();
}
void AppearanceViewModel::ClearFontAxes()
{
_deleteAllFontKeyValuePairs(FontAxesIndex);
}
Model::FontConfig AppearanceViewModel::FontAxesOverrideSource() const
{
return _appearance.SourceProfile().FontInfo().FontAxesOverrideSource();
}
IObservableVector<Editor::FontKeyValuePair> AppearanceViewModel::FontFeatures()
{
return FontFaceDependents().fontSettingsUsed[FontFeaturesIndex];
}
bool AppearanceViewModel::HasFontFeatures() const
{
return _appearance.SourceProfile().FontInfo().HasFontFeatures();
}
void AppearanceViewModel::ClearFontFeatures()
{
_deleteAllFontKeyValuePairs(FontFeaturesIndex);
}
Model::FontConfig AppearanceViewModel::FontFeaturesOverrideSource() const
{
return _appearance.SourceProfile().FontInfo().FontFeaturesOverrideSource();
}
void AppearanceViewModel::AddFontKeyValuePair(const IInspectable& sender, const Editor::FontKeyValuePair& kv)
{
if (!_fontFaceDependents)
{
return;
}
const auto kvImpl = winrt::get_self<FontKeyValuePair>(kv);
const auto fontSettingsIndex = kvImpl->IsFontFeature() ? FontFeaturesIndex : FontAxesIndex;
auto& d = *_fontFaceDependents;
auto& used = d.fontSettingsUsed[fontSettingsIndex];
auto& unused = d.fontSettingsUnused[fontSettingsIndex];
const auto it = std::ranges::find(unused, sender);
if (it == unused.end())
{
return;
}
// Sync the added value into the user settings model.
UpdateFontSetting(kvImpl);
// Insert the item into the used list, keeping it sorted by the display text.
{
const auto it = std::lower_bound(used.begin(), used.end(), kv, FontKeyValuePair::SortAscending);
used.InsertAt(gsl::narrow<uint32_t>(it - used.begin()), kv);
}
unused.erase(it);
_notifyChangesForFontSettingsReactive(fontSettingsIndex);
}
void AppearanceViewModel::DeleteFontKeyValuePair(const Editor::FontKeyValuePair& kv)
{
if (!_fontFaceDependents)
{
return;
}
const auto kvImpl = winrt::get_self<FontKeyValuePair>(kv);
const auto tag = kvImpl->Key();
const auto tagString = tagToString(tag);
const auto fontSettingsIndex = kvImpl->IsFontFeature() ? FontFeaturesIndex : FontAxesIndex;
auto& d = *_fontFaceDependents;
auto& used = d.fontSettingsUsed[fontSettingsIndex];
const auto fontInfo = _appearance.SourceProfile().FontInfo();
auto fontSettingsUser = kvImpl->IsFontFeature() ? fontInfo.FontFeatures() : fontInfo.FontAxes();
if (!fontSettingsUser)
{
return;
}
const auto it = std::ranges::find(used, kv);
if (it == used.end())
{
return;
}
fontSettingsUser.Remove(std::wstring_view{ tagString });
_addMenuFlyoutItemToUnused(fontSettingsIndex, _createFontSettingMenuItem(*it));
used.RemoveAt(gsl::narrow<uint32_t>(it - used.begin()));
_notifyChangesForFontSettingsReactive(fontSettingsIndex);
}
void AppearanceViewModel::_deleteAllFontKeyValuePairs(FontSettingIndex fontSettingsIndex)
{
const auto fontInfo = _appearance.SourceProfile().FontInfo();
if (fontSettingsIndex == FontFeaturesIndex)
{
fontInfo.ClearFontFeatures();
}
else
{
fontInfo.ClearFontAxes();
}
if (!_fontFaceDependents)
{
return;
}
auto& d = *_fontFaceDependents;
auto& used = d.fontSettingsUsed[fontSettingsIndex];
for (const auto& kv : used)
{
_addMenuFlyoutItemToUnused(fontSettingsIndex, _createFontSettingMenuItem(kv));
}
used.Clear();
_notifyChangesForFontSettingsReactive(fontSettingsIndex);
}
// Inserts the given menu item into the unused list, while keeping it sorted by the display text.
void AppearanceViewModel::_addMenuFlyoutItemToUnused(FontSettingIndex index, MenuFlyoutItemBase item)
{
if (!_fontFaceDependents)
{
return;
}
auto& d = *_fontFaceDependents;
auto& unused = d.fontSettingsUnused[index];
const auto it = std::lower_bound(unused.begin(), unused.end(), item, [](const MenuFlyoutItemBase& lhs, const MenuFlyoutItemBase& rhs) {
const auto& a = lhs.as<MenuFlyoutItem>().Text();
const auto& b = rhs.as<MenuFlyoutItem>().Text();
return til::compare_linguistic_insensitive(a, b) < 0;
});
unused.insert(it, std::move(item));
}
void AppearanceViewModel::UpdateFontSetting(const FontKeyValuePair* kvImpl)
{
const auto tag = kvImpl->Key();
const auto value = kvImpl->Value();
const auto tagString = tagToString(tag);
const auto fontInfo = _appearance.SourceProfile().FontInfo();
auto fontSettingsUser = kvImpl->IsFontFeature() ? fontInfo.FontFeatures() : fontInfo.FontAxes();
if (!fontSettingsUser)
{
fontSettingsUser = winrt::single_threaded_map<hstring, float>();
if (kvImpl->IsFontFeature())
{
fontInfo.FontFeatures(fontSettingsUser);
}
else
{
fontInfo.FontAxes(fontSettingsUser);
}
}
std::ignore = fontSettingsUser.Insert(std::wstring_view{ tagString }, value);
// Pwease call Profiles_Appearance::_onProfilePropertyChanged to make the pweview connyection wewoad. Thanks!! uwu
// ...I hate this.
_NotifyChanges(L"uwu");
}
void AppearanceViewModel::SetBackgroundImageOpacityFromPercentageValue(double percentageValue)
{
BackgroundImageOpacity(static_cast<float>(percentageValue) / 100.0f);
}
void AppearanceViewModel::SetBackgroundImagePath(winrt::hstring path)
{
BackgroundImagePath(path);
}
bool AppearanceViewModel::UseDesktopBGImage()
{
return BackgroundImagePath() == L"desktopWallpaper";
}
void AppearanceViewModel::UseDesktopBGImage(const bool useDesktop)
{
if (useDesktop)
{
// Stash the current value of BackgroundImagePath. If the user
// checks and un-checks the "Use desktop wallpaper" button, we want
// the path that we display in the text box to remain unchanged.
//
// Only stash this value if it's not the special "desktopWallpaper"
// value.
if (BackgroundImagePath() != L"desktopWallpaper")
{
_lastBgImagePath = BackgroundImagePath();
}
BackgroundImagePath(L"desktopWallpaper");
}
else
{
// Restore the path we had previously cached. This might be the
// empty string.
BackgroundImagePath(_lastBgImagePath);
}
}
bool AppearanceViewModel::BackgroundImageSettingsVisible()
{
return !BackgroundImagePath().empty();
}
void AppearanceViewModel::ClearColorScheme()
{
ClearDarkColorSchemeName();
_NotifyChanges(L"CurrentColorScheme");
}
Editor::ColorSchemeViewModel AppearanceViewModel::CurrentColorScheme()
{
const auto schemeName{ DarkColorSchemeName() };
const auto allSchemes{ SchemesList() };
for (const auto& scheme : allSchemes)
{
if (scheme.Name() == schemeName)
{
return scheme;
}
}
// This Appearance points to a color scheme that was renamed or deleted.
// Fallback to the first one in the list.
return allSchemes.GetAt(0);
}
void AppearanceViewModel::CurrentColorScheme(const ColorSchemeViewModel& val)
{
DarkColorSchemeName(val.Name());
LightColorSchemeName(val.Name());
}
DependencyProperty Appearances::_AppearanceProperty{ nullptr };
Appearances::Appearances()
{
InitializeComponent();
{
using namespace winrt::Windows::Globalization::NumberFormatting;
// > .NET rounds to 12 significant digits when displaying doubles, so we will [...]
// ...obviously not do that, because this is an UI element for humans. This prevents
// issues when displaying 32-bit floats, because WinUI is unaware about their existence.
IncrementNumberRounder rounder;
rounder.Increment(1e-6);
for (const auto& box : { _fontSizeBox(), _lineHeightBox() })
{
// BODGY: Depends on WinUI internals.
box.NumberFormatter().as<DecimalFormatter>().NumberRounder(rounder);
}
}
INITIALIZE_BINDABLE_ENUM_SETTING(CursorShape, CursorStyle, winrt::Microsoft::Terminal::Core::CursorStyle, L"Profile_CursorShape", L"Content");
INITIALIZE_BINDABLE_ENUM_SETTING(AdjustIndistinguishableColors, AdjustIndistinguishableColors, winrt::Microsoft::Terminal::Core::AdjustTextMode, L"Profile_AdjustIndistinguishableColors", L"Content");
INITIALIZE_BINDABLE_ENUM_SETTING_REVERSE_ORDER(BackgroundImageStretchMode, BackgroundImageStretchMode, winrt::Windows::UI::Xaml::Media::Stretch, L"Profile_BackgroundImageStretchMode", L"Content");
// manually add Custom FontWeight option. Don't add it to the Map
INITIALIZE_BINDABLE_ENUM_SETTING(FontWeight, FontWeight, uint16_t, L"Profile_FontWeight", L"Content");
_CustomFontWeight = winrt::make<EnumEntry>(RS_(L"Profile_FontWeightCustom/Content"), winrt::box_value<uint16_t>(0u));
_FontWeightList.Append(_CustomFontWeight);
if (!_AppearanceProperty)
{
_AppearanceProperty =
DependencyProperty::Register(
L"Appearance",
xaml_typename<Editor::AppearanceViewModel>(),
xaml_typename<Editor::Appearances>(),
PropertyMetadata{ nullptr, PropertyChangedCallback{ &Appearances::_ViewModelChanged } });
}
// manually keep track of all the Background Image Alignment buttons
_BIAlignmentButtons.at(0) = BIAlign_TopLeft();
_BIAlignmentButtons.at(1) = BIAlign_Top();
_BIAlignmentButtons.at(2) = BIAlign_TopRight();
_BIAlignmentButtons.at(3) = BIAlign_Left();
_BIAlignmentButtons.at(4) = BIAlign_Center();
_BIAlignmentButtons.at(5) = BIAlign_Right();
_BIAlignmentButtons.at(6) = BIAlign_BottomLeft();
_BIAlignmentButtons.at(7) = BIAlign_Bottom();
_BIAlignmentButtons.at(8) = BIAlign_BottomRight();
// apply automation properties to more complex setting controls
for (const auto& biButton : _BIAlignmentButtons)
{
const auto tooltip{ ToolTipService::GetToolTip(biButton) };
Automation::AutomationProperties::SetName(biButton, unbox_value<hstring>(tooltip));
}
const auto showAllFontsCheckboxTooltip{ ToolTipService::GetToolTip(ShowAllFontsCheckbox()) };
Automation::AutomationProperties::SetFullDescription(ShowAllFontsCheckbox(), unbox_value<hstring>(showAllFontsCheckboxTooltip));
const auto backgroundImgCheckboxTooltip{ ToolTipService::GetToolTip(UseDesktopImageCheckBox()) };
Automation::AutomationProperties::SetFullDescription(UseDesktopImageCheckBox(), unbox_value<hstring>(backgroundImgCheckboxTooltip));
INITIALIZE_BINDABLE_ENUM_SETTING(IntenseTextStyle, IntenseTextStyle, winrt::Microsoft::Terminal::Settings::Model::IntenseStyle, L"Appearance_IntenseTextStyle", L"Content");
}
IObservableVector<Editor::Font> Appearances::FilteredFontList()
{
if (!_filteredFonts)
{
_updateFilteredFontList();
}
return _filteredFonts;
}
// Method Description:
// - Determines whether we should show the list of all the fonts, or we should just show monospace fonts
bool Appearances::ShowAllFonts() const noexcept
{
return _ShowAllFonts;
}