-
Notifications
You must be signed in to change notification settings - Fork 1
/
sunburst.cpp
1782 lines (1475 loc) · 57.1 KB
/
sunburst.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) 2023 Christopher Antos
// License: http://opensource.org/licenses/MIT
#include "main.h"
#include "sunburst.h"
#include "data.h"
#include "DarkMode.h"
#include "TextOnPath/PathTextRenderer.h"
#include <cmath>
static ID2D1Factory* s_pD2DFactory = nullptr;
static IDWriteFactory2* s_pDWriteFactory = nullptr;
#ifdef DEBUG
static bool s_fOklab = false;
bool GetUseOklab() { return s_fOklab; }
void SetUseOklab(bool use) { s_fOklab = use; }
#endif
constexpr FLOAT M_PI = 3.14159265358979323846f;
constexpr FLOAT c_centerRadiusRatio = 0.24f;
constexpr FLOAT c_centerRadiusRatioMax = 0.096125f;
constexpr FLOAT c_centerRadiusRatioNonProp = 0.15f;
constexpr int c_centerRadiusMin = 50;
constexpr int c_centerRadiusMax = 100;
constexpr FLOAT c_rotation = -90.0f;
constexpr size_t c_max_depth = 20;
// constexpr int c_max_thickness = 60; // For proportional area.
constexpr int c_thickness = 25;
constexpr FLOAT c_thicknessRatioNonProp = 0.055f;
constexpr int c_retrograde = 1;
constexpr int c_retrograde_depths = 10;
constexpr WCHAR c_fontface[] = TEXT("Segoe UI");
constexpr FLOAT c_fontsize = 10.0f;
constexpr FLOAT c_headerfontsize = 12.0f;
constexpr FLOAT c_arcfontsize = 8.0f;
constexpr FLOAT c_minArc = 2.5f;
constexpr UINT32 c_minArcTextLength = 1;
constexpr WCHAR c_ellipsis[] = TEXT("...");
constexpr size_t c_ellipsis_len = _countof(c_ellipsis) - 1;
HRESULT InitializeD2D()
{
return D2D1CreateFactory(D2D1_FACTORY_TYPE_MULTI_THREADED, __uuidof(ID2D1Factory), 0, reinterpret_cast<void**>(&s_pD2DFactory));
}
HRESULT InitializeDWrite()
{
return DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory2), reinterpret_cast<IUnknown**>(&s_pDWriteFactory));
}
bool GetD2DFactory(ID2D1Factory** ppFactory)
{
ID2D1Factory* pFactory = s_pD2DFactory;
if (!pFactory)
return false;
pFactory->AddRef();
*ppFactory = pFactory;
return true;
}
bool GetDWriteFactory(IDWriteFactory2** ppFactory)
{
IDWriteFactory2* pFactory = s_pDWriteFactory;
if (!pFactory)
return false;
pFactory->AddRef();
*ppFactory = pFactory;
return true;
}
static FLOAT ArcLength(FLOAT angle, FLOAT radius)
{
return angle * radius * M_PI / 180.0f;
}
//----------------------------------------------------------------------------
// HSLColorType.
template <typename T> T clamp(T value, T min, T max)
{
value = value < min ? min : value;
return value > max ? max : value;
}
namespace colorspace
{
static const FLOAT c_maxHue = 360;
static const FLOAT c_maxSat = 240;
static const FLOAT c_maxLum = 240;
struct HSLColorType
{
HSLColorType() {}
HSLColorType(COLORREF rgb) { FromRGB(rgb); }
void FromRGB( COLORREF rgb );
COLORREF ToRGB() const;
void SetSaturation(FLOAT value);
void SetLuminance(FLOAT value);
void AdjustSaturation(FLOAT delta);
void AdjustLuminance(FLOAT delta);
void FixLuminance();
FLOAT h; // 0..c_maxHue
FLOAT s; // 0..c_maxSat
FLOAT l; // 0..c_maxLum
};
void HSLColorType::FromRGB(const COLORREF rgb)
{
const int minVal = std::min<BYTE>(std::min<BYTE>(GetRValue(rgb), GetGValue(rgb)), GetBValue(rgb));
const int maxVal = std::max<BYTE>(std::max<BYTE>(GetRValue(rgb), GetGValue(rgb)), GetBValue(rgb));
const int sumMinMax = minVal + maxVal;
l = sumMinMax * c_maxLum / 255 / 2;
assert(l >= 0);
assert(l <= c_maxLum);
if (minVal == maxVal)
{
s = 0;
h = 0;
}
else
{
const int delta = maxVal - minVal;
s = delta * c_maxSat;
s /= (sumMinMax <= 255) ? sumMinMax : (510 - sumMinMax);
assert(s >= 0);
assert(s <= c_maxSat);
int offset;
if (maxVal == GetRValue(rgb))
{
h = FLOAT(GetGValue(rgb) - GetBValue(rgb));
offset = 0;
}
else if (maxVal == GetGValue(rgb))
{
h = FLOAT(GetBValue(rgb) - GetRValue(rgb));
offset = 2;
}
else
{
h = FLOAT(GetRValue(rgb) - GetGValue(rgb));
offset = 4;
}
h *= c_maxHue;
h /= delta;
h += c_maxHue * offset;
h /= 6;
if (h >= c_maxHue)
h -= c_maxHue;
if (h < 0)
h += c_maxHue;
assert(h >= 0);
assert(h < c_maxHue);
}
}
static BYTE ToByteValue(FLOAT rm1, FLOAT rm2, FLOAT h)
{
if (h >= c_maxHue)
h -= c_maxHue;
else if (h < 0)
h += c_maxHue;
if (h < c_maxHue / 6)
rm1 = rm1 + (rm2 - rm1) * h / (c_maxHue / 6);
else if (h < c_maxHue / 2)
rm1 = rm2;
else if (h < c_maxHue - (c_maxHue / 3))
rm1 = rm1 + (rm2 - rm1) * ((c_maxHue - (c_maxHue / 3)) - h) / (c_maxHue / 6);
return BYTE((rm1 * 255.0f) + 0.5f);
}
COLORREF HSLColorType::ToRGB() const
{
const FLOAT validHue = clamp<FLOAT>(h, 0, c_maxHue);
const FLOAT validSat = clamp<FLOAT>(s, 0, c_maxSat);
const FLOAT validLum = clamp<FLOAT>(l, 0, c_maxLum);
const FLOAT satRatio = validSat / c_maxSat;
const FLOAT lumRatio = validLum / c_maxLum;
if (!validSat)
{
BYTE const gray = BYTE(validLum * 255 / c_maxLum);
return RGB(gray, gray, gray);
}
FLOAT rm2;
if (validLum <= c_maxLum / 2)
rm2 = lumRatio + (lumRatio * satRatio);
else
rm2 = (lumRatio + satRatio) - (lumRatio * satRatio);
const FLOAT rm1 = (2.0f * lumRatio) - rm2;
return RGB(ToByteValue(rm1, rm2, validHue + (c_maxHue / 3)),
ToByteValue(rm1, rm2, validHue),
ToByteValue(rm1, rm2, validHue - (c_maxHue / 3)));
}
void HSLColorType::SetSaturation(FLOAT value)
{
if (value < 0)
s = 0;
else if (value > c_maxSat)
s = c_maxSat;
else
s = value;
}
void HSLColorType::SetLuminance(FLOAT value)
{
if (value < 0)
l = 0;
else if (value > c_maxLum)
l = c_maxLum;
else
l = value;
}
void HSLColorType::AdjustSaturation(FLOAT delta)
{
s += delta;
if (delta < 0)
s = std::max<FLOAT>(s, 0);
else
s = std::min<FLOAT>(s, c_maxSat);
}
void HSLColorType::AdjustLuminance(FLOAT delta)
{
l += delta;
if (delta < 0)
l = std::max<FLOAT>(l, 0);
else
l = std::min<FLOAT>(l, c_maxLum);
}
void HSLColorType::FixLuminance()
{
// Luminance in the blue/purple range of hue in the HSL color space is
// disproportionate to the rest of the hue range. This attempts to
// compensate -- primarily so that text can have legible contrast.
const float lo = 180.0f;
const float hi = 300.0f;
const float gravity = c_maxLum * 0.65f;
if (h >= lo && h <= hi)
{
constexpr float pi = 3.14159f;
const float hue_cos = cos((h - lo) * 2 * pi / (hi - lo));
const float transform = (1.0f - hue_cos) / 2;
if (l < gravity)
l += transform * (gravity - l) * 0.8f;
else
l += transform * (gravity - l) * 0.6f;
}
}
}; // namespace colorspace
//----------------------------------------------------------------------------
// Oklab color space.
#ifdef DEBUG
namespace colorspace
{
// The Oklab code here is based on https://bottosson.github.io/posts/oklab, in
// the public domain (and also available under the MIT License).
struct Oklab
{
Oklab() = default;
Oklab(COLORREF cr) { from_rgb(cr); }
void from_rgb(COLORREF cr);
COLORREF to_rgb() const;
float L = 0;
float a = 0;
float b = 0;
inline static float rgb_to_linear(BYTE val)
{
float x = float(val) / 255.0f;
return (x > 0.04045f) ? std::pow((x + 0.055f) / 1.055f, 2.4f) : (x / 12.92f);
}
inline static BYTE linear_to_rgb(float val)
{
float x = (val >= 0.0031308f) ? (1.055f * std::pow(val, 1.0f / 2.4f) - 0.055f) : (12.92f * val);
return BYTE(clamp(int(x * 255), 0, 255));
}
void get_Ch(float& C, float& h) const
{
C = sqrtf(a*a + b*b);
#ifdef USE_NATIVE_OKLAB_HUE
h = h * 180.0f / M_PI;
h -= M_PI / 2; // Oklab hue is 45 degrees different from HSL hue.
if (h < 0.0f)
h += 360.0f;
assert(h >= 0.0f);
assert(h <= 360.0f);
#else
HSLColorType hsl(to_rgb());
h = hsl.h;
#endif
}
void set_Ch(float C, float h)
{
assert(h >= 0.0f);
assert(h <= c_maxHue);
#ifdef USE_NATIVE_OKLAB_HUE
h += 45.0f;
if (h >= 180.0f)
h -= 360.0f;
h = h * M_PI / 180.0f;
#else
HSLColorType hsl;
hsl.h = h;
hsl.s = c_maxSat;
hsl.l = c_maxLum / 2;
Oklab tmp(hsl.ToRGB());
h = atan2(tmp.b, tmp.a);
#endif
a = C * cos(h);
b = C * sin(h);
}
};
void Oklab::from_rgb(COLORREF cr)
{
float _r = rgb_to_linear(GetRValue(cr));
float _g = rgb_to_linear(GetGValue(cr));
float _b = rgb_to_linear(GetBValue(cr));
float l = 0.4122214708f * _r + 0.5363325363f * _g + 0.0514459929f * _b;
float m = 0.2119034982f * _r + 0.6806995451f * _g + 0.1073969566f * _b;
float s = 0.0883024619f * _r + 0.2817188376f * _g + 0.6299787005f * _b;
l = std::cbrt(l);
m = std::cbrt(m);
s = std::cbrt(s);
L = 0.2104542553f * l + 0.7936177850f * m - 0.0040720468f * s;
a = 1.9779984951f * l - 2.4285922050f * m + 0.4505937099f * s;
b = 0.0259040371f * l + 0.7827717662f * m - 0.8086757660f * s;
}
COLORREF Oklab::to_rgb() const
{
float l = L + 0.3963377774f * a + 0.2158037573f * b;
float m = L - 0.1055613458f * a - 0.0638541728f * b;
float s = L - 0.0894841775f * a - 1.2914855480f * b;
l = l * l * l;
m = m * m * m;
s = s * s * s;
float _r = +4.0767416621f * l - 3.3077115913f * m + 0.2309699292f * s;
float _g = -1.2684380046f * l + 2.6097574011f * m - 0.3413193965f * s;
float _b = -0.0041960863f * l - 0.7034186147f * m + 1.7076147010f * s;
return RGB(linear_to_rgb(_r), linear_to_rgb(_g), linear_to_rgb(_b));
}
}; // namespace colorspace
#endif
//----------------------------------------------------------------------------
// DirectHwndRenderTarget.
#define ERRJMP(expr) do { hr = (expr); assert(SUCCEEDED(hr)); if (FAILED(hr)) goto LError; } while (false)
#define ERRRET(expr) do { hr = (expr); assert(SUCCEEDED(hr)); if (FAILED(hr)) return hr; } while (false)
HRESULT DirectHwndRenderTarget::Resources::Init(HWND hwnd, const D2D1_SIZE_U& size, const DpiScaler& dpi, bool dark_mode)
{
HRESULT hr = S_OK;
if (!m_spFactory && !GetD2DFactory(&m_spFactory))
return E_UNEXPECTED;
if (!m_spDWriteFactory && !GetDWriteFactory(&m_spDWriteFactory))
return E_UNEXPECTED;
const DpiScaler dpiWithTextScaling(dpi, true);
const FLOAT dpiF = dpi.ScaleF(96);
ERRRET(m_spFactory->CreateHwndRenderTarget(
D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(), dpiF, dpiF, D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE, D2D1_FEATURE_LEVEL_DEFAULT),
D2D1::HwndRenderTargetProperties(hwnd, size),
&m_spTarget));
m_spTarget->SetDpi(dpiF, dpiF);
ERRRET(m_spTarget->CreateSolidColorBrush(D2D1::ColorF(dark_mode ? 0x444444 : 0x000000, 1.0f), &m_spLineBrush));
ERRRET(m_spTarget->CreateSolidColorBrush(D2D1::ColorF(0x444444, 0.5f), &m_spFileLineBrush));
ERRRET(m_spTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 1.0f), &m_spFillBrush));
ERRRET(m_spTarget->CreateSolidColorBrush(D2D1::ColorF(0x000000, 1.0f), &m_spOutlineBrush));
ERRRET(m_spTarget->CreateSolidColorBrush(D2D1::ColorF(0xFFFFFF, 1.0f), &m_spOutlineBrush2));
ERRRET(m_spTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 1.0f), &m_spTextBrush));
const auto rstyle = D2D1::StrokeStyleProperties(D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_LINE_JOIN_ROUND);
ERRRET(m_spFactory->CreateStrokeStyle(rstyle, nullptr, 0, &m_spRoundedStroke));
const auto bstyle = D2D1::StrokeStyleProperties(D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_CAP_STYLE_ROUND, D2D1_LINE_JOIN_BEVEL);
ERRRET(m_spFactory->CreateStrokeStyle(bstyle, nullptr, 0, &m_spBevelStroke));
SPI<IDWriteRenderingParams> spRenderingParams;
ERRRET(m_spDWriteFactory->CreateRenderingParams(&spRenderingParams));
#ifdef THIS_ISNT_WORKING_RIGHT_YET_AND_MIGHT_NOT_BE_NEEDED_ANYWAY
// Custom text rendering param object is created that uses all default
// values except for the rendering mode which is now set to outline. The
// outline mode is much faster in this case as every time text is relaid
// out on the path, it is rasterized as geometry. This saves the extra
// step of trying to find the text bitmaps in the font cache and then
// repopulating the cache with the new ones. Since the text may rotate
// differently from frame to frame, new glyph bitmaps would be generated
// often anyway.
const DWRITE_RENDERING_MODE rendering_mode = DWRITE_RENDERING_MODE_OUTLINE;
#else
const DWRITE_RENDERING_MODE rendering_mode = DWRITE_RENDERING_MODE_NATURAL;
#endif
ERRRET(m_spDWriteFactory->CreateCustomRenderingParams(
spRenderingParams->GetGamma(),
spRenderingParams->GetEnhancedContrast(),
spRenderingParams->GetClearTypeLevel(),
spRenderingParams->GetPixelGeometry(),
rendering_mode,
&m_spRenderingParams));
m_fontSize = FLOAT(-dpiWithTextScaling.PointSizeToHeight(c_fontsize));
ERRRET(m_spDWriteFactory->CreateTextFormat(
c_fontface,
nullptr,
DWRITE_FONT_WEIGHT_REGULAR,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
m_fontSize,
TEXT("en-US"),
&m_spTextFormat));
m_spTextFormat->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
m_headerFontSize = FLOAT(-dpiWithTextScaling.PointSizeToHeight(c_headerfontsize));
ERRRET(m_spDWriteFactory->CreateTextFormat(
c_fontface,
nullptr,
DWRITE_FONT_WEIGHT_BOLD,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
m_headerFontSize,
TEXT("en-US"),
&m_spHeaderTextFormat));
m_spHeaderTextFormat->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
// Intentionally unscaled: it's not important text, and if it's scaled it
// can run over the sunburst chart.
m_appInfoFontSize = FLOAT(-dpi.PointSizeToHeight(c_fontsize));
ERRRET(m_spDWriteFactory->CreateTextFormat(
c_fontface,
nullptr,
DWRITE_FONT_WEIGHT_REGULAR,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
m_appInfoFontSize,
TEXT("en-US"),
&m_spAppInfoTextFormat));
m_spAppInfoTextFormat->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
m_arcFontSize = FLOAT(-dpiWithTextScaling.PointSizeToHeight(c_arcfontsize));
ERRRET(m_spDWriteFactory->CreateTextFormat(
c_fontface,
nullptr,
DWRITE_FONT_WEIGHT_REGULAR,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
m_arcFontSize,
TEXT("en-US"),
&m_spArcTextFormat));
m_spArcTextFormat->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
ERRRET(m_spContext.HrQuery(m_spTarget));
m_spContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE);
m_spContext->SetUnitMode(D2D1_UNIT_MODE_PIXELS);
m_spContext->SetTextRenderingParams(m_spRenderingParams);
m_spPathTextRenderer = new PathTextRenderer(dpi.ScaleF(96));
return S_OK;
}
DirectHwndRenderTarget::DirectHwndRenderTarget()
{
m_resources = std::make_unique<Resources>();
}
DirectHwndRenderTarget::~DirectHwndRenderTarget()
{
assert(!m_hwnd);
}
HRESULT DirectHwndRenderTarget::CreateDeviceResources(const HWND hwnd, const DpiScaler& dpi, bool dark_mode)
{
assert(!m_hwnd || hwnd == m_hwnd);
if (hwnd == m_hwnd && Target())
return S_OK;
m_resources.reset();
m_resources = std::make_unique<Resources>();
m_hwnd = hwnd;
RECT rc;
GetClientRect(m_hwnd, &rc);
const D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
HRESULT hr = m_resources->Init(m_hwnd, size, dpi, dark_mode);
if (FAILED(hr))
{
ReleaseDeviceResources();
return hr;
}
return S_OK;
}
HRESULT DirectHwndRenderTarget::ResizeDeviceResources()
{
if (!m_hwnd || !Target())
return S_OK;
RECT rc;
GetClientRect(m_hwnd, &rc);
D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
HRESULT hr = m_resources->m_spTarget->Resize(size);
if (FAILED(hr))
{
ReleaseDeviceResources();
return hr;
}
return S_OK;
}
void DirectHwndRenderTarget::ReleaseDeviceResources()
{
m_resources = std::make_unique<Resources>();
m_hwnd = 0;
}
static void SetStringWithEllipsis(Shortened& out, const WCHAR* in, size_t len, size_t keep, int ellipsis=1)
{
if (len && IS_HIGH_SURROGATE(in[len - 1]))
len--;
out.m_text.clear();
if (ellipsis < 0)
{
out.m_text.append(c_ellipsis);
out.m_text.append(in + len - keep);
}
else
{
out.m_text.append(in, keep);
if (ellipsis > 0)
out.m_text.append(c_ellipsis);
}
}
bool DirectHwndRenderTarget::CreateTextFormat(FLOAT fontsize, DWRITE_FONT_WEIGHT weight, IDWriteTextFormat** ppTextFormat) const
{
SPI<IDWriteTextFormat> spTextFormat;
if (FAILED(m_resources->m_spDWriteFactory->CreateTextFormat(
c_fontface,
nullptr,
weight,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
fontsize,
TEXT("en-US"),
&spTextFormat)))
return false;
spTextFormat->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
*ppTextFormat = spTextFormat.Transfer();
return true;
}
bool DirectHwndRenderTarget::ShortenText(IDWriteTextFormat* format, const D2D1_RECT_F& rect, const WCHAR* text, const size_t len, FLOAT target, Shortened& out, int ellipsis)
{
if (len <= 0)
return false;
#ifdef DEBUG
{
D2D1_SIZE_F size;
MeasureText(format, rect, text, len, size);
assert(size.width > target);
}
#endif
out.m_text.clear();
out.m_extent = 0.0f;
size_t lo = 0;
size_t hi = len - 1;
Shortened tmp;
while (lo < hi)
{
const size_t mid = (hi + lo) / 2;
D2D1_SIZE_F size;
SetStringWithEllipsis(tmp, text, len, mid, ellipsis);
if (!MeasureText(format, rect, tmp.m_text, size))
return false;
if (size.width < target && tmp.m_extent < size.width)
{
out.m_text = std::move(tmp.m_text);
out.m_extent = size.width;
out.m_orig_offset = mid;
}
if (size.width < target)
lo = mid + 1;
else
hi = mid;
}
return true;
}
bool DirectHwndRenderTarget::MeasureText(IDWriteTextFormat* format, const D2D1_RECT_F& rect, const std::wstring& text, D2D1_SIZE_F& size, IDWriteTextLayout** ppLayout)
{
return MeasureText(format, rect, text.c_str(), text.length(), size, ppLayout);
}
bool DirectHwndRenderTarget::MeasureText(IDWriteTextFormat* format, const D2D1_RECT_F& rect, const WCHAR* text, size_t len, D2D1_SIZE_F& size, IDWriteTextLayout** ppLayout)
{
const FLOAT xExtent = rect.right - rect.left;
const FLOAT yExtent = rect.bottom - rect.top;
SPI<IDWriteTextLayout> spTextLayout;
if (FAILED(DWriteFactory()->CreateTextLayout(text, UINT32(len), format, xExtent, yExtent, &spTextLayout)))
return false;
DWRITE_TEXT_METRICS textMetrics;
if (FAILED(spTextLayout->GetMetrics(&textMetrics)))
return false;
size = D2D1::SizeF(FLOAT(ceil(textMetrics.width)), FLOAT(ceil(textMetrics.height)));
if (ppLayout)
*ppLayout = spTextLayout.Transfer();
return true;
}
bool DirectHwndRenderTarget::WriteText(IDWriteTextFormat* format, FLOAT x, FLOAT y, const D2D1_RECT_F& rect, const std::wstring& text, WriteTextOptions options, IDWriteTextLayout* pLayout)
{
return WriteText(format, x, y, rect, text.c_str(), text.length(), options, pLayout);
}
bool DirectHwndRenderTarget::WriteText(IDWriteTextFormat* format, FLOAT x, FLOAT y, const D2D1_RECT_F& rect, const WCHAR* text, size_t len, WriteTextOptions options, IDWriteTextLayout* pLayout)
{
const FLOAT xExtent = rect.right - rect.left;
const FLOAT yExtent = rect.bottom - rect.top;
SPI<IDWriteTextLayout> _spTextLayout;
if (!pLayout)
{
if (FAILED(DWriteFactory()->CreateTextLayout(text, UINT32(len), format, xExtent, yExtent, &_spTextLayout)))
return false;
pLayout = _spTextLayout;
}
if (options & (WTO_HCENTER|WTO_VCENTER|WTO_RIGHT_ALIGN|WTO_BOTTOM_ALIGN|WTO_REMEMBER_METRICS))
{
DWRITE_TEXT_METRICS textMetrics;
if (FAILED(pLayout->GetMetrics(&textMetrics)))
return false;
const auto size = D2D1::SizeF(FLOAT(ceil(textMetrics.width)), FLOAT(ceil(textMetrics.height)));
if (options & WTO_HCENTER)
x = std::max<FLOAT>(0.0f, FLOAT(floor(rect.left + (xExtent - size.width) / 2)));
if (options & WTO_VCENTER)
y = FLOAT(floor(rect.top + (yExtent - size.height) / 2));
if (options & WTO_RIGHT_ALIGN)
x = rect.right - size.width;
if (options & WTO_BOTTOM_ALIGN)
y = rect.bottom - size.height;
if (options & WTO_REMEMBER_METRICS)
m_resources->m_lastTextSize = size;
}
const auto position = D2D1::Point2F(x, y);
if (options & WTO_REMEMBER_METRICS)
m_resources->m_lastTextPosition = position;
D2D1_DRAW_TEXT_OPTIONS opt = D2D1_DRAW_TEXT_OPTIONS_NONE;
if (options & WTO_CLIP)
opt |= D2D1_DRAW_TEXT_OPTIONS_CLIP;
if (options & WTO_UNDERLINE)
{
DWRITE_TEXT_RANGE range = { 0, UINT32(len) };
pLayout->SetUnderline(true, range);
}
Target()->DrawTextLayout(position, pLayout, TextBrush(), opt);
return true;
}
//----------------------------------------------------------------------------
// SunburstMetrics.
static FLOAT make_center_radius(const DpiScaler& dpi, const FLOAT boundary_radius, const FLOAT max_extent)
{
if (g_show_proportional_area)
{
// winR and maxR use different ratios to accelerate growth of radius
// when resizing the window larger, but with a maximum beyond which it
// stops growing.
const FLOAT winR = std::max<FLOAT>(FLOAT(dpi.Scale(c_centerRadiusMin)), boundary_radius * c_centerRadiusRatio);
const FLOAT maxR = std::max<FLOAT>(FLOAT(dpi.Scale(c_centerRadiusMin)), max_extent * c_centerRadiusRatioMax);
return std::min<FLOAT>(winR, maxR);
}
else
return std::max<FLOAT>(FLOAT(dpi.Scale(c_centerRadiusMin)),
boundary_radius * c_centerRadiusRatioNonProp);
}
SunburstMetrics::SunburstMetrics(const Sunburst& sunburst)
: SunburstMetrics(sunburst.m_dpi, sunburst.m_bounds, sunburst.m_max_extent)
{
}
SunburstMetrics::SunburstMetrics(const DpiScaler& dpi, const D2D1_RECT_F& bounds, FLOAT max_extent)
: stroke(std::max<FLOAT>(FLOAT(dpi.Scale(1)), FLOAT(1)))
, margin(FLOAT(dpi.Scale(5)))
, indicator_thickness(FLOAT(dpi.Scale(4)))
, boundary_radius(FLOAT(std::min<LONG>(LONG(bounds.right - bounds.left), LONG(bounds.bottom - bounds.top)) / 2 - margin))
, center_radius(make_center_radius(dpi, boundary_radius, max_extent))
, max_radius(boundary_radius - (margin + indicator_thickness + margin))
, range_radius(max_radius - center_radius)
, min_arc(dpi.ScaleF(c_minArc))
{
if (g_show_proportional_area)
{
FLOAT radius = center_radius;
// const FLOAT coefficient = 0.18f;
// FLOAT thickness = FLOAT(ceil(std::min<FLOAT>(center_radius * coefficient, 9999999999.9f)));//FLOAT(dpi.Scale(c_max_thickness)))));
const FLOAT coefficient = 0.67f;
FLOAT thickness = FLOAT(ceil(center_radius * coefficient));
for (size_t ii = 0; ii < _countof(thicknesses); ++ii)
{
thicknesses[ii] = thickness;
const FLOAT outer = radius + thickness;
const FLOAT add = sqrt(2 * outer * outer - radius * radius) - outer;
thickness = FLOAT(floor(add));
radius = outer;
}
}
else
{
FLOAT thickness = std::max<FLOAT>(FLOAT(dpi.Scale(c_thickness)),
boundary_radius * c_thicknessRatioNonProp);
const FLOAT retrograde = FLOAT(dpi.Scale(c_retrograde));
for (size_t ii = 0; ii < _countof(thicknesses); ++ii)
thicknesses[ii] = thickness - (retrograde * std::min<size_t>(ii, c_retrograde_depths));
}
}
FLOAT SunburstMetrics::get_thickness(size_t depth) const
{
if (depth < _countof(thicknesses))
return thicknesses[depth];
return g_show_proportional_area ? 0.0f : thicknesses[_countof(thicknesses) - 1];
}
//----------------------------------------------------------------------------
// Sunburst.
Sunburst::Sunburst()
{
}
Sunburst::~Sunburst()
{
}
bool Sunburst::SetBounds(const D2D1_RECT_F& rect, const FLOAT max_extent)
{
static_assert(sizeof(m_bounds) == sizeof(rect), "data size mismatch");
const bool changed = (!!memcmp(&m_bounds, &rect, sizeof(rect)) ||
m_max_extent != max_extent);
m_bounds = rect;
m_max_extent = FLOAT(max_extent);
m_center.x = floor((rect.left + rect.right) / 2.0f);
m_center.y = floor((rect.top + rect.bottom) / 2.0f);
return changed;
}
void Sunburst::MakeArc(std::vector<Arc>& arcs, FLOAT outer_radius, const FLOAT min_arc, const std::shared_ptr<Node>& node, ULONGLONG size, double& sweep, double total, float start, float span, double convert)
{
const bool zero = (total == 0.0f);
Arc arc;
arc.m_start = start + float(zero ? 0.0f : convert * sweep * span / total);
sweep += size;
arc.m_end = start + float(zero ? 0.0f : convert * sweep * span / total);
#ifdef DEBUG
if (arc.m_start > 360.0f || arc.m_end > 360.0f)
DebugBreak();
assert(arc.m_end - arc.m_start <= span);
#endif
if (ArcLength(arc.m_end - arc.m_start, outer_radius) >= min_arc)
{
arc.m_node = node;
arcs.emplace_back(std::move(arc));
}
}
void Sunburst::BuildRings(const SunburstMetrics& mx, const std::vector<std::shared_ptr<DirNode>>& _roots)
{
const std::vector<std::shared_ptr<DirNode>> roots = _roots;
std::vector<double> totals; // Total space (used + free); when FreeSpaceNode is present it's total hardware space.
std::vector<double> used; // Used space; when FreeSpaceNode is present it's used hardware space.
std::vector<double> scale; // Multiplier to scale used content space into used hardware space.
std::vector<float> spans; // Angle span for used space.
m_roots = roots;
m_rings.clear();
m_start_angles.clear();
m_free_angles.clear();
{
bool show_free_space = g_show_free_space;
#ifdef DEBUG
if (g_fake_data == FDM_COLORWHEEL)
{
// This is important to prevent free space in the root, so that
// the color wheel uses the full 360 degrees.
show_free_space = false;
}
#endif
double grand_total = 0;
for (const auto dir : roots)
{
const double size = double(dir->GetSize());
std::shared_ptr<FreeSpaceNode> free = show_free_space ? dir->GetFreeSpace() : nullptr;
if (free)
{
totals.emplace_back(double(free->GetTotalSize()));
used.emplace_back(double(free->GetUsedSize()));
if (size == 0.0f || used.back() == 0.0f)
scale.emplace_back(0.0f);
else if (dir->IsFinished())
scale.emplace_back(used.back() / size);
else
scale.emplace_back(used.back() / std::max<double>(used.back(), size));
}
else
{
totals.emplace_back(size);
used.emplace_back(size);
scale.emplace_back(1.0f);
}
grand_total += totals.back();
}
m_units = AutoUnitScale(ULONGLONG(grand_total));
if (grand_total == 0)
return;
double sweep = 0;
for (size_t ii = 0; ii < roots.size(); ++ii)
{
const float start = float(sweep * 360 / grand_total);
const float mid = float((sweep + used[ii]) * 360 / grand_total);
sweep += totals[ii];
const float end = float(sweep * 360 / grand_total);
m_start_angles.emplace_back(start);
spans.emplace_back(mid - start);
if (show_free_space)
{
std::shared_ptr<FreeSpaceNode> free = m_roots[ii]->GetFreeSpace();
if (free)
{
const float angle = float((sweep - free->GetFreeSize()) * 360 / grand_total);
m_free_angles.emplace_back(angle);
}
else
{
m_free_angles.emplace_back(end);
}
}
}
}
m_rings.emplace_back();
std::vector<Arc>& arcs = m_rings.back();
FLOAT outer_radius = mx.center_radius + mx.get_thickness(0);
const FLOAT min_arc = mx.min_arc;
for (size_t ii = 0; ii < roots.size(); ++ii)
{
std::shared_ptr<DirNode> root = roots[ii];
std::vector<std::shared_ptr<DirNode>> dirs = root->CopyDirs(true/*include_recycle*/);
std::vector<std::shared_ptr<FileNode>> files = root->CopyFiles();
std::shared_ptr<FreeSpaceNode> free = root->GetFreeSpace();
const double total = totals[ii];
const double consumed = used[ii];
const double convert = scale[ii];
const float start = m_start_angles[ii];
const float span = spans[ii];
double sweep = 0;
for (const auto dir : dirs)
MakeArc(arcs, outer_radius, min_arc, std::static_pointer_cast<Node>(dir), dir->GetSize(), sweep, consumed, start, span, convert);
for (const auto file : files)
MakeArc(arcs, outer_radius, min_arc, std::static_pointer_cast<Node>(file), file->GetSize(), sweep, consumed, start, span, convert);
#ifdef USE_FREESPACE_RING
if (free)
{
Arc arc;
arc.m_start = m_free_angles[ii];
arc.m_end = m_start_angles[(ii + 1) % m_roots.size()];
if (arc.m_end < arc.m_start)
arc.m_end += 360.0f;
arc.m_node = free;
arcs.emplace_back(std::move(arc));
}
#endif
}
while (m_rings.size() <= c_max_depth)
{
outer_radius += mx.get_thickness(m_rings.size() + 1);
std::vector<Arc> arcs = NextRing(m_rings.back(), outer_radius, min_arc);
if (arcs.empty())
break;
m_rings.emplace_back(std::move(arcs));
}
#ifdef DEBUG
for (const auto ring : m_rings)
{
float prev = ring.size() ? ring[0].m_start : 0;
for (const auto arc : ring)
{
assert(arc.m_start >= prev);
prev = arc.m_end;
}
}