-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathBaseStyle.cpp
4806 lines (4666 loc) · 216 KB
/
BaseStyle.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) 2020 KeePassXC Team <team@keepassxc.org>
* Copyright (C) 2019 Andrew Richards
*
* Derived from Phantomstyle and relicensed under the GPLv2 or v3.
* https://github.com/randrew/phantomstyle
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 or (at your option)
* version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "BaseStyle.h"
#include "phantomcolor.h"
#include <QAbstractItemView>
#include <QApplication>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QFile>
#include <QHeaderView>
#include <QListView>
#include <QMainWindow>
#include <QMenu>
#include <QPainter>
#include <QPoint>
#include <QPolygon>
#include <QPushButton>
#include <QScrollBar>
#include <QSharedData>
#include <QSlider>
#include <QSpinBox>
#include <QSplitter>
#include <QString>
#include <QStyleOption>
#include <QTableView>
#include <QToolBar>
#include <QToolButton>
#include <QTreeView>
#include <QWindow>
#include <QWizard>
#include <QtMath>
#include <qdrawutil.h>
#include <cmath>
QT_BEGIN_NAMESPACE
Q_GUI_EXPORT int qt_defaultDpiX();
QT_END_NAMESPACE
// Redefine Q_FALLTHROUGH for older Qt versions
#ifndef Q_FALLTHROUGH
#if (defined(Q_CC_GNU) && Q_CC_GNU >= 700) && !defined(Q_CC_INTEL)
#define Q_FALLTHROUGH() __attribute__((fallthrough))
#else
#define Q_FALLTHROUGH() (void)0
#endif
#endif
namespace Phantom
{
namespace
{
constexpr qint16 DefaultFrameWidth = 6;
constexpr qint16 SplitterMaxLength = 25; // Length of splitter handle (not thickness)
constexpr qint16 MenuMinimumWidth = 20; // Smallest width that menu items can have
constexpr qint16 MenuBar_FrameWidth = 6;
constexpr qint16 SpinBox_ButtonWidth = 15;
// These two are currently not based on font, but could be
constexpr qint16 LineEdit_ContentsHPad = 5;
constexpr qint16 ComboBox_NonEditable_ContentsHPad = 7;
constexpr qint16 HeaderSortIndicator_HOffset = 1;
constexpr qint16 HeaderSortIndicator_VOffset = 2;
constexpr qint16 TabBar_InctiveVShift = 0;
constexpr qreal TabBarTab_Rounding = 1.0;
constexpr qreal SpinBox_Rounding = 1.0;
constexpr qreal LineEdit_Rounding = 1.0;
constexpr qreal FrameFocusRect_Rounding = 1.0;
constexpr qreal PushButton_Rounding = 1.0;
constexpr qreal ToolButton_Rounding = 1.0;
constexpr qreal ProgressBar_Rounding = 1.0;
constexpr qreal GroupBox_Rounding = 1.0;
constexpr qreal SliderGroove_Rounding = 1.0;
constexpr qreal SliderHandle_Rounding = 1.0;
constexpr qreal CheckMark_WidthOfHeightScale = 0.8;
constexpr qreal PushButton_HorizontalPaddingFontHeightRatio = 1.0;
constexpr qreal TabBar_HPaddingFontRatio = 1.25;
constexpr qreal TabBar_VPaddingFontRatio = 1.0 / 1.25;
constexpr qreal GroupBox_LabelBottomMarginFontRatio = 1.0 / 4.0;
constexpr qreal ComboBox_ArrowMarginRatio = 1.0 / 3.25;
constexpr qreal MenuBar_HorizontalPaddingFontRatio = 1.0 / 2.0;
constexpr qreal MenuBar_VerticalPaddingFontRatio = 1.0 / 3.0;
constexpr qreal MenuItem_LeftMarginFontRatio = 1.0 / 2.0;
constexpr qreal MenuItem_RightMarginForTextFontRatio = 1.0 / 1.5;
constexpr qreal MenuItem_RightMarginForArrowFontRatio = 1.0 / 4.0;
constexpr qreal MenuItem_VerticalMarginsFontRatio = 1.0 / 5.0;
// Number that's multiplied with a font's height to get the space between a
// menu item's checkbox (or other sign) and its text (or icon).
constexpr qreal MenuItem_CheckRightSpaceFontRatio = 1.0 / 4.0;
constexpr qreal MenuItem_TextMnemonicSpaceFontRatio = 1.5;
constexpr qreal MenuItem_SubMenuArrowSpaceFontRatio = 1.0 / 1.5;
constexpr qreal MenuItem_SubMenuArrowWidthFontRatio = 1.0 / 2.75;
constexpr qreal MenuItem_SeparatorHeightFontRatio = 1.0 / 1.5;
constexpr qreal MenuItem_CheckMarkVerticalInsetFontRatio = 1.0 / 5.0;
constexpr qreal MenuItem_IconRightSpaceFontRatio = 1.0 / 3.0;
constexpr bool BranchesOnEdge = false;
constexpr bool OverhangShadows = false;
constexpr bool IndicatorShadows = false;
constexpr bool MenuExtraBottomMargin = true;
constexpr bool MenuBarLeftMargin = false;
constexpr bool MenuBarDrawBorder = false;
constexpr bool AllowToolBarAutoRaise = true;
// Note that this only applies to the disclosure etc. decorators in tree views.
constexpr bool ShowItemViewDecorationSelected = false;
constexpr bool UseQMenuForComboBoxPopup = true;
constexpr bool ItemView_UseFontHeightForDecorationSize = true;
// Whether or not the non-raised tabs in a tab bar have shininess/highlights to
// them. Setting this to false adds an extra visual hint for distinguishing
// between the current and non-current tabs, but makes the non-current tabs
// appear less clickable. Other ways to increase the visual differences could
// be to increase the color contrast for the background fill color, or increase
// the vertical offset. However, increasing the vertical offset comes with some
// layout challenges, and increasing the color contrast further may visually
// imply an incorrect layout structure. Not sure what's best.
//
// This doesn't disable creating the color/brush resource, even though it's
// currently a compile-time-only option, because it may be changed to be part
// of some dynamic config system for Phantom in the future, or have a
// per-widget style hint associated with it.
const bool TabBar_InactiveTabsHaveSpecular = false;
struct Grad
{
Grad(const QColor& from, const QColor& to)
{
rgbA = Rgb::ofQColor(from);
rgbB = Rgb::ofQColor(to);
lA = rgbA.toHsl().l;
lB = rgbB.toHsl().l;
}
QColor sample(qreal alpha) const
{
Hsl hsl = Rgb::lerp(rgbA, rgbB, alpha).toHsl();
hsl.l = Phantom::lerp(lA, lB, alpha);
return hsl.toQColor();
}
Rgb rgbA, rgbB;
qreal lA, lB;
};
namespace DeriveColors
{
Q_NEVER_INLINE QColor adjustLightness(const QColor& qcolor, qreal ld)
{
Hsl hsl = Hsl::ofQColor(qcolor);
const qreal gamma = 3.0;
hsl.l = std::pow(Phantom::saturate(std::pow(hsl.l, 1.0 / gamma) + ld * 0.8), gamma);
return hsl.toQColor();
}
bool hack_isLightPalette(const QPalette& pal)
{
Hsl hsl0 = Hsl::ofQColor(pal.color(QPalette::WindowText));
Hsl hsl1 = Hsl::ofQColor(pal.color(QPalette::Window));
return hsl0.l < hsl1.l;
}
QColor buttonColor(const QPalette& pal)
{
// temp hack
if (pal.color(QPalette::Button) == pal.color(QPalette::Window))
return adjustLightness(pal.color(QPalette::Button), 0.01);
return pal.color(QPalette::Button);
}
QColor highlightedOutlineOf(const QPalette& pal)
{
return adjustLightness(pal.color(QPalette::Highlight), -0.08);
}
QColor dividerColor(const QColor& underlying)
{
return adjustLightness(underlying, -0.05);
}
QColor lightDividerColor(const QColor& underlying)
{
return adjustLightness(underlying, 0.02);
}
QColor outlineOf(const QPalette& pal)
{
return adjustLightness(pal.color(QPalette::Window), -0.1);
}
QColor gutterColorOf(const QPalette& pal)
{
return adjustLightness(pal.color(QPalette::Window), -0.05);
}
QColor darkGutterColorOf(const QPalette& pal)
{
return adjustLightness(pal.color(QPalette::Window), -0.08);
}
QColor lightShadeOf(const QColor& underlying)
{
return adjustLightness(underlying, 0.08);
}
QColor darkShadeOf(const QColor& underlying)
{
return adjustLightness(underlying, -0.08);
}
QColor overhangShadowOf(const QColor& underlying)
{
return adjustLightness(underlying, -0.05);
}
QColor sliderGutterShadowOf(const QColor& underlying)
{
return adjustLightness(underlying, -0.01);
}
QColor specularOf(const QColor& underlying)
{
return adjustLightness(underlying, 0.01);
}
QColor lightSpecularOf(const QColor& underlying)
{
return adjustLightness(underlying, 0.05);
}
QColor pressedOf(const QColor& color)
{
return adjustLightness(color, -0.05);
}
QColor darkPressedOf(const QColor& color)
{
return adjustLightness(color, -0.08);
}
QColor lightOnOf(const QColor& color)
{
return adjustLightness(color, -0.04);
}
QColor onOf(const QColor& color)
{
return adjustLightness(color, -0.08);
}
QColor indicatorColorOf(const QPalette& palette, QPalette::ColorGroup group = QPalette::Current)
{
if (hack_isLightPalette(palette)) {
qreal adjust = (palette.currentColorGroup() == QPalette::Disabled) ? 0.09 : 0.32;
return adjustLightness(palette.color(group, QPalette::WindowText), adjust);
}
return adjustLightness(palette.color(group, QPalette::WindowText), -0.05);
}
QColor inactiveTabFillColorOf(const QColor& underlying)
{
// used to be -0.01
return adjustLightness(underlying, -0.025);
}
QColor progressBarOutlineColorOf(const QPalette& pal)
{
// Pretty wasteful
Hsl hsl0 = Hsl::ofQColor(pal.color(QPalette::Window));
Hsl hsl1 = Hsl::ofQColor(pal.color(QPalette::Highlight));
hsl1.l = Phantom::saturate(qMin(hsl0.l - 0.1, hsl1.l - 0.2));
return hsl1.toQColor();
}
QColor itemViewMultiSelectionCurrentBorderOf(const QPalette& pal)
{
return adjustLightness(pal.color(QPalette::Highlight), -0.15);
}
QColor itemViewHeaderOnLineColorOf(const QPalette& pal)
{
return hack_isLightPalette(pal)
? highlightedOutlineOf(pal)
: Grad(pal.color(QPalette::WindowText), pal.color(QPalette::Window)).sample(0.5);
}
} // namespace DeriveColors
namespace SwatchColors
{
enum SwatchColor
{
S_none = 0,
S_window,
S_button,
S_base,
S_text,
S_windowText,
S_highlight,
S_highlightedText,
S_scrollbarGutter,
S_scrollbarSlider,
S_window_outline,
S_window_specular,
S_window_divider,
S_window_lighter,
S_window_darker,
S_frame_outline,
S_button_specular,
S_button_pressed,
S_button_on,
S_button_pressed_specular,
S_sliderHandle,
S_sliderHandle_pressed,
S_sliderHandle_specular,
S_sliderHandle_pressed_specular,
S_base_shadow,
S_base_divider,
S_windowText_disabled,
S_highlight_outline,
S_highlight_specular,
S_progressBar_outline,
S_inactiveTabYesFrame,
S_inactiveTabNoFrame,
S_inactiveTabYesFrame_specular,
S_inactiveTabNoFrame_specular,
S_indicator_current,
S_indicator_disabled,
S_itemView_multiSelection_currentBorder,
S_itemView_headerOnLine,
S_scrollbarGutter_disabled,
// Aliases
S_progressBar = S_highlight,
S_progressBar_specular = S_highlight_specular,
S_tabFrame = S_window,
S_tabFrame_specular = S_window_specular,
};
}
using Swatchy = SwatchColors::SwatchColor;
enum
{
Num_SwatchColors = SwatchColors::S_scrollbarGutter_disabled + 1,
Num_ShadowSteps = 3,
};
struct PhSwatch : public QSharedData
{
// The pens store the brushes within them, so storing the brushes here as
// well is redundant. However, QPen::brush() does not return its brush by
// reference, so we'd end up doing a bunch of inc/dec work every time we use
// one. Also, it saves us the indirection of chasing two pointers (Swatch ->
// QPen -> QBrush) every time we want to get a QColor.
QBrush brushes[Num_SwatchColors];
QPen pens[Num_SwatchColors];
QColor scrollbarShadowColors[Num_ShadowSteps];
// Note: the casts to int in the assert macros are to suppress a false
// positive warning for tautological comparison in the clang linter.
inline const QColor& color(Swatchy swatchValue) const
{
Q_ASSERT(swatchValue >= 0 && static_cast<int>(swatchValue) < Num_SwatchColors);
return brushes[swatchValue].color();
}
inline const QBrush& brush(Swatchy swatchValue) const
{
Q_ASSERT(swatchValue >= 0 && static_cast<int>(swatchValue) < Num_SwatchColors);
return brushes[swatchValue];
}
inline const QPen& pen(Swatchy swatchValue) const
{
Q_ASSERT(swatchValue >= 0 && static_cast<int>(swatchValue) < Num_SwatchColors);
return pens[swatchValue];
}
void loadFromQPalette(const QPalette& pal);
};
using PhSwatchPtr = QExplicitlySharedDataPointer<PhSwatch>;
using PhCacheEntry = QPair<uint, PhSwatchPtr>;
enum : int
{
Num_ColorCacheEntries = 10,
};
using PhSwatchCache = QVarLengthArray<PhCacheEntry, Num_ColorCacheEntries>;
Q_NEVER_INLINE void PhSwatch::loadFromQPalette(const QPalette& pal)
{
using namespace SwatchColors;
namespace Dc = DeriveColors;
bool isLight = Dc::hack_isLightPalette(pal);
QColor colors[Num_SwatchColors];
colors[S_none] = QColor();
colors[S_window] = pal.color(QPalette::Window);
colors[S_button] = pal.color(QPalette::Button);
if (colors[S_button] == colors[S_window])
colors[S_button] = Dc::adjustLightness(colors[S_button], 0.01);
colors[S_base] = pal.color(QPalette::Base);
colors[S_text] = pal.color(QPalette::Text);
colors[S_text] = pal.color(QPalette::WindowText);
colors[S_windowText] = pal.color(QPalette::WindowText);
colors[S_highlight] = pal.color(QPalette::Highlight);
colors[S_highlightedText] = pal.color(QPalette::HighlightedText);
colors[S_scrollbarGutter] = isLight ? Dc::gutterColorOf(pal) : Dc::darkGutterColorOf(pal);
colors[S_scrollbarSlider] = isLight ? colors[S_button] : Dc::adjustLightness(colors[S_window], 0.2);
colors[S_window_outline] =
isLight ? Dc::adjustLightness(colors[S_window], -0.1) : Dc::adjustLightness(colors[S_window], 0.03);
colors[S_window_specular] = Dc::specularOf(colors[S_window]);
colors[S_window_divider] =
isLight ? Dc::dividerColor(colors[S_window]) : Dc::lightDividerColor(colors[S_window]);
colors[S_window_lighter] = Dc::lightShadeOf(colors[S_window]);
colors[S_window_darker] = Dc::darkShadeOf(colors[S_window]);
colors[S_frame_outline] = isLight ? colors[S_window_outline] : Dc::adjustLightness(colors[S_window], 0.08);
colors[S_button_specular] =
isLight ? Dc::specularOf(colors[S_button]) : Dc::lightSpecularOf(colors[S_button]);
colors[S_button_pressed] = isLight ? Dc::pressedOf(colors[S_button]) : Dc::darkPressedOf(colors[S_button]);
colors[S_button_on] = isLight ? Dc::lightOnOf(colors[S_button]) : Dc::onOf(colors[S_button]);
colors[S_button_pressed_specular] =
isLight ? Dc::specularOf(colors[S_button_pressed]) : Dc::lightSpecularOf(colors[S_button_pressed]);
colors[S_sliderHandle] = isLight ? colors[S_button] : Dc::adjustLightness(colors[S_button], -0.03);
colors[S_sliderHandle_specular] =
isLight ? Dc::specularOf(colors[S_sliderHandle]) : Dc::lightSpecularOf(colors[S_sliderHandle]);
colors[S_sliderHandle_pressed] =
isLight ? colors[S_button_pressed] : Dc::adjustLightness(colors[S_button_pressed], 0.03);
colors[S_sliderHandle_pressed_specular] = isLight ? Dc::specularOf(colors[S_sliderHandle_pressed])
: Dc::lightSpecularOf(colors[S_sliderHandle_pressed]);
colors[S_base_shadow] = Dc::overhangShadowOf(colors[S_base]);
colors[S_base_divider] = colors[S_window_divider];
colors[S_windowText_disabled] = pal.color(QPalette::Disabled, QPalette::WindowText);
colors[S_highlight_outline] = isLight ? Dc::adjustLightness(colors[S_highlight], -0.02)
: Dc::adjustLightness(colors[S_highlight], 0.05);
colors[S_highlight_specular] = Dc::specularOf(colors[S_highlight]);
colors[S_progressBar_outline] = Dc::progressBarOutlineColorOf(pal);
colors[S_inactiveTabYesFrame] = Dc::inactiveTabFillColorOf(colors[S_tabFrame]);
colors[S_inactiveTabNoFrame] = Dc::inactiveTabFillColorOf(colors[S_window]);
colors[S_inactiveTabYesFrame_specular] = Dc::specularOf(colors[S_inactiveTabYesFrame]);
colors[S_inactiveTabNoFrame_specular] = Dc::specularOf(colors[S_inactiveTabNoFrame]);
colors[S_indicator_current] = Dc::indicatorColorOf(pal, QPalette::Current);
colors[S_indicator_disabled] = Dc::indicatorColorOf(pal, QPalette::Disabled);
colors[S_itemView_multiSelection_currentBorder] = Dc::itemViewMultiSelectionCurrentBorderOf(pal);
colors[S_itemView_headerOnLine] = Dc::itemViewHeaderOnLineColorOf(pal);
colors[S_scrollbarGutter_disabled] = colors[S_window];
brushes[S_none] = Qt::NoBrush;
for (int i = S_none + 1; i < Num_SwatchColors; ++i) {
// todo try to reuse
brushes[i] = colors[i];
}
pens[S_none] = Qt::NoPen;
// QPen::setColor constructs a QBrush behind the scenes, so better to just
// re-use the ones we already made.
for (int i = S_none + 1; i < Num_SwatchColors; ++i) {
pens[i].setBrush(brushes[i]);
// Width is already 1, don't need to set it. Caps and joins already fine at
// their defaults, too.
}
Grad gutterGrad(Dc::sliderGutterShadowOf(colors[S_scrollbarGutter]), colors[S_scrollbarGutter]);
for (int i = 0; i < Num_ShadowSteps; ++i) {
scrollbarShadowColors[i] = gutterGrad.sample(i / static_cast<qreal>(Num_ShadowSteps));
}
}
// This is the "hash" (not really a hash) function we'll use on the happy fast
// path when looking up a PhSwatch for a given QPalette. It's fragile, because
// it uses QPalette::cacheKey(), so it may not match even when the contents
// (currentColorGroup + the RGB colors) of the QPalette are actually a match.
// But it's cheaper to calculate, so we'll store a single one of these "hashes"
// for the head (most recently used) cached PhSwatch, and check to see if it
// matches. This is the most common case, so we can usually save some work by
// doing this. (The second most common case is probably having a different
// ColorGroup but the rest of the contents are the same, but we don't have a
// special path for that.)
inline quint64 fastfragile_hash_qpalette(const QPalette& p)
{
union
{
qint64 i;
quint64 u;
} x;
x.i = p.cacheKey();
// QPalette::ColorGroup has range 0..5 (inclusive), so it only uses 3 bits.
// The high 32 bits in QPalette::cacheKey() are a global incrementing serial
// number for the QPalette creation. We don't store (2^29-1) things in our
// cache, and I doubt that many will ever be created in a real application
// while also retaining some of them across such a broad time range, so it's
// really unlikely that repurposing these top 3 bits to also include the
// QPalette::currentColorGroup() (which the cacheKey doesn't include for some
// reason...) will generate a collision.
//
// This may not be true in the future if the way the QPalette::cacheKey() is
// generated changes. If that happens, change to use the definition of
// `fastfragile_hash_qpalette` below, which is less likely to collide with an
// arbitrarily numbered key but also does more work.
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
x.u = x.u ^ (static_cast<quint64>(p.currentColorGroup()) << (64 - 3));
return x.u;
#else
// Use this definition here if the contents/layout of QPalette::cacheKey()
// (as in, the C++ code in qpalette.cpp) are changed. We'll also put a Qt6
// guard for it, so that it will default to a more safe definition on the
// next guaranteed big breaking change for Qt. A warning will hopefully get
// someone to double-check it at some point in the future.
#warning "Verify contents and layout of QPalette::cacheKey() have not changed"
QtPrivate::QHashCombine c;
uint h = qHash(p.currentColorGroup());
h = c(h, (uint)(x.u & 0xFFFFFFFFu));
h = c(h, (uint)((x.u >> 32) & 0xFFFFFFFFu));
return h;
#endif
}
// This hash function is for when we want an actual accurate hash of a
// QPalette. QPalette's cacheKey() isn't very reliable -- it seems to change to
// a new random number whenever it's modified, with the exception of the
// currentColorGroup being changed. This kind of sucks for us, because it means
// two QPalette's can have the same contents but hash to different values. And
// this actually happens a lot! We'll do the hashing ourselves. Also, we're not
// interested in all of the colors, only some of them, and we ignore
// pens/brushes.
uint accurate_hash_qpalette(const QPalette& p)
{
// Probably shouldn't use this, could replace with our own guy. It's not a
// great hasher anyway.
QtPrivate::QHashCombine c;
uint h = qHash(p.currentColorGroup());
QPalette::ColorRole const roles[] = {QPalette::Window,
QPalette::Button,
QPalette::Base,
QPalette::Text,
QPalette::WindowText,
QPalette::Highlight,
QPalette::HighlightedText};
for (auto role : roles) {
h = c(h, p.color(role).rgb());
}
return h;
}
Q_NEVER_INLINE PhSwatchPtr
deep_getCachedSwatchOfQPalette(PhSwatchCache* cache,
int cacheCount, // Just saving a call to cache->count()
const QPalette& qpalette)
{
// Calculate our hash key from the QPalette's current ColorGroup and the
// actual RGBA values that we use. We have to mix the ColorGroup in
// ourselves, because QPalette does not account for it in the cache key.
uint key = accurate_hash_qpalette(qpalette);
int n = cacheCount;
int idx = -1;
for (int i = 0; i < n; ++i) {
const auto& x = cache->at(i);
if (x.first == key) {
idx = i;
break;
}
}
if (idx == -1) {
PhSwatchPtr ptr;
if (n < Num_ColorCacheEntries) {
ptr = new PhSwatch;
} else {
// Remove the oldest guy from the cache. Remember that because we may
// re-enter QStyle functions multiple times when drawing or calculating
// something, we may have to load several swaitches derived from
// different QPalettes on different stack frames at the same time. But as
// an extra cost-savings measure, we'll check and see if something else
// has a reference to the removed guy. If there aren't any references to
// it, then we'll re-use it directly instead of allocating a new one. (We
// will only ever run into the case where we can't re-use it directly if
// some other stack frame has a reference to it.) This is nice because
// then the QPens and QBrushes don't all also have to reallocate their d
// ptr stuff.
ptr = cache->last().second;
cache->removeLast();
ptr.detach();
}
ptr->loadFromQPalette(qpalette);
cache->prepend(PhCacheEntry(key, ptr));
return ptr;
} else {
if (idx == 0) {
return cache->at(idx).second;
}
PhCacheEntry e = cache->at(idx);
// Using std::move from algorithm could be more efficient here, but I don't
// want to depend on algorithm or write this myself. Small N with a movable
// type means it doesn't really matter in this case.
cache->remove(idx);
cache->prepend(e);
return e.second;
}
}
Q_NEVER_INLINE PhSwatchPtr
getCachedSwatchOfQPalette(PhSwatchCache* cache,
quint64* headSwatchFastKey, // Optimistic fast-path quick hash key
const QPalette& qpalette)
{
quint64 ck = fastfragile_hash_qpalette(qpalette);
int cacheCount = cache->count();
// This hint is counter-productive if we're being called in a way that
// interleaves different QPalettes. But misses to this optimistic path were
// rare in my tests. (Probably not going to amount to any significant
// difference, anyway.)
if (Q_LIKELY(cacheCount > 0 && *headSwatchFastKey == ck)) {
return cache->at(0).second;
}
*headSwatchFastKey = ck;
return deep_getCachedSwatchOfQPalette(cache, cacheCount, qpalette);
}
} // namespace
} // namespace Phantom
class BaseStylePrivate
{
public:
BaseStylePrivate();
// A fast'n'easy hash of QPalette::cacheKey()+QPalette::currentColorGroup()
// of only the head element of swatchCache list. The most common thing that
// happens when deriving a PhSwatch from a QPalette is that we just end up
// re-using the last one that we used. For that case, we can potentially save
// calling `accurate_hash_qpalette()` and instead use the value returned by
// QPalette::cacheKey() (and QPalette::currentColorGroup()) and compare it to
// the last one that we used. If it matches, then we know we can just use the
// head of the cache list without having to do any further checks, which
// saves a few hundred (!) nanoseconds.
//
// However, the `QPalette::cacheKey()` value is fragile and may change even
// if none of the colors in the QPalette have changed. In other words, all of
// the colors in a QPalette may match another QPalette (or a derived
// PhSwatch) even if the `QPalette::cacheKey()` value is different.
//
// So if `QPalette::cacheKey()+currentColorGroup()` doesn't match, then we'll
// use our more accurate `accurate_hash_qpalette()` to get a more accurate
// comparison key, and then search through the cache list to find a matching
// cached PhSwatch. (The more accurate cache key is what we store alongside
// each PhSwatch element, as the `.first` in each QPair. The
// QPalette::cacheKey() that we associate with the PhSwatch in the head
// position, `headSwatchFastKey`, is only stored for our single head element,
// as a special fast case.) If we find it, we'll move it to the head of the
// cache list. If not, we'll make a new one, and put it at the head. Either
// way, the `headSwatchFastKey` will be updated to the
// `fastfragile_qpalette_hash()` of the QPalette that we needed to derive a
// PhSwatch from, so that if we get called with the same QPalette again next
// time (which is probably going to be the case), it'll match and we can take
// the fast path.
quint64 headSwatchFastKey;
Phantom::PhSwatchCache swatchCache;
QPen checkBox_pen_scratch;
};
namespace Phantom
{
namespace
{
// Minimal QPainter save/restore just for pen, brush, and AA render hint. If
// you touch more than that, this won't help you. But if you're only touching
// those things, this will save you some typing from manually storing/saving
// those properties each time.
struct PSave final
{
Q_DISABLE_COPY(PSave)
explicit PSave(QPainter* painter_)
{
Q_ASSERT(painter_);
painter = painter_;
pen = painter_->pen();
brush = painter_->brush();
hintAA = painter_->testRenderHint(QPainter::Antialiasing);
}
Q_NEVER_INLINE void restore()
{
QPainter* p = painter;
if (!p)
return;
bool hintAA_ = hintAA;
// QPainter will check both pen and brush for equality when setting, so we
// should set it unconditionally here.
p->setPen(pen);
p->setBrush(brush);
// But it won't check the render hint to guard against doing extra work.
// We'll do that ourselves. (Though at least for the raster engine, this
// doesn't cause very much work to occur. But it still chases a few
// pointers.)
if (p->testRenderHint(QPainter::Antialiasing) != hintAA_) {
p->setRenderHint(QPainter::Antialiasing, hintAA_);
}
painter = nullptr;
pen = QPen();
brush = QBrush();
hintAA = false;
}
~PSave()
{
restore();
}
private:
QPainter* painter;
QPen pen;
QBrush brush;
bool hintAA;
};
const qreal Pi = M_PI;
qreal dpiScaled(qreal value)
{
#ifdef Q_OS_MAC
// On mac the DPI is always 72 so we should not scale it
return value;
#else
const qreal scale = qt_defaultDpiX() / 96.0;
return value * scale;
#endif
}
struct MenuItemMetrics
{
int fontHeight;
int frameThickness;
int leftMargin;
int rightMarginForText;
int rightMarginForArrow;
int topMargin;
int bottomMargin;
int checkWidth;
int checkRightSpace;
int iconRightSpace;
int mnemonicSpace;
int arrowSpace;
int arrowWidth;
int separatorHeight;
int totalHeight;
static MenuItemMetrics ofFontHeight(int fontHeight);
private:
MenuItemMetrics()
{
}
};
MenuItemMetrics MenuItemMetrics::ofFontHeight(int fontHeight)
{
MenuItemMetrics m;
m.fontHeight = fontHeight;
m.frameThickness = dpiScaled(1.0);
m.leftMargin = static_cast<int>(fontHeight * MenuItem_LeftMarginFontRatio);
m.rightMarginForText = static_cast<int>(fontHeight * MenuItem_RightMarginForTextFontRatio);
m.rightMarginForArrow = static_cast<int>(fontHeight * MenuItem_RightMarginForArrowFontRatio);
m.topMargin = static_cast<int>(fontHeight * MenuItem_VerticalMarginsFontRatio);
m.bottomMargin = static_cast<int>(fontHeight * MenuItem_VerticalMarginsFontRatio);
int checkVMargin = static_cast<int>(fontHeight * MenuItem_CheckMarkVerticalInsetFontRatio);
int checkHeight = fontHeight - checkVMargin * 2;
if (checkHeight < 0)
checkHeight = 0;
m.checkWidth = static_cast<int>(checkHeight * CheckMark_WidthOfHeightScale);
m.checkRightSpace = static_cast<int>(fontHeight * MenuItem_CheckRightSpaceFontRatio);
m.iconRightSpace = static_cast<int>(fontHeight * MenuItem_IconRightSpaceFontRatio);
m.mnemonicSpace = static_cast<int>(fontHeight * MenuItem_TextMnemonicSpaceFontRatio);
m.arrowSpace = static_cast<int>(fontHeight * MenuItem_SubMenuArrowSpaceFontRatio);
m.arrowWidth = static_cast<int>(fontHeight * MenuItem_SubMenuArrowWidthFontRatio);
m.separatorHeight = static_cast<int>(fontHeight * MenuItem_SeparatorHeightFontRatio);
// Odd numbers only
m.separatorHeight = (m.separatorHeight / 2) * 2 + 1;
m.totalHeight = fontHeight + m.frameThickness * 2 + m.topMargin + m.bottomMargin;
return m;
}
QRect menuItemContentRect(const MenuItemMetrics& metrics, QRect itemRect, bool hasArrow)
{
QRect r = itemRect;
int ft = metrics.frameThickness;
int rm = hasArrow ? metrics.rightMarginForArrow : metrics.rightMarginForText;
r.adjust(ft + metrics.leftMargin, ft + metrics.topMargin, -(ft + rm), -(ft + metrics.bottomMargin));
return r.isValid() ? r : QRect();
}
QRect
menuItemCheckRect(const MenuItemMetrics& metrics, Qt::LayoutDirection direction, QRect itemRect, bool hasArrow)
{
QRect r = menuItemContentRect(metrics, itemRect, hasArrow);
int checkVMargin = static_cast<int>(metrics.fontHeight * MenuItem_CheckMarkVerticalInsetFontRatio);
if (checkVMargin < 0)
checkVMargin = 0;
r.setSize(QSize(metrics.checkWidth, metrics.fontHeight));
r.adjust(0, checkVMargin, 0, -checkVMargin);
return QStyle::visualRect(direction, itemRect, r) & itemRect;
}
QRect
menuItemIconRect(const MenuItemMetrics& metrics, Qt::LayoutDirection direction, QRect itemRect, bool hasArrow)
{
QRect r = menuItemContentRect(metrics, itemRect, hasArrow);
r.setX(r.x() + metrics.checkWidth + metrics.checkRightSpace);
r.setSize(QSize(metrics.fontHeight, metrics.fontHeight));
return QStyle::visualRect(direction, itemRect, r) & itemRect;
}
QRect menuItemTextRect(const MenuItemMetrics& metrics,
Qt::LayoutDirection direction,
QRect itemRect,
bool hasArrow,
bool hasIcon,
int tabWidth)
{
QRect r = menuItemContentRect(metrics, itemRect, hasArrow);
r.setX(r.x() + metrics.checkWidth + metrics.checkRightSpace);
if (hasIcon) {
r.setX(r.x() + metrics.fontHeight + metrics.iconRightSpace);
}
r.setWidth(r.width() - tabWidth);
r.setHeight(metrics.fontHeight);
r &= itemRect;
return QStyle::visualRect(direction, itemRect, r);
}
QRect menuItemMnemonicRect(const MenuItemMetrics& metrics,
Qt::LayoutDirection direction,
QRect itemRect,
bool hasArrow,
int tabWidth)
{
QRect r = menuItemContentRect(metrics, itemRect, hasArrow);
int x = r.x() + r.width() - tabWidth;
if (hasArrow)
x -= metrics.arrowSpace + metrics.arrowWidth;
r.setX(x);
r.setHeight(metrics.fontHeight);
r &= itemRect;
return QStyle::visualRect(direction, itemRect, r);
}
QRect menuItemArrowRect(const MenuItemMetrics& metrics, Qt::LayoutDirection direction, QRect itemRect)
{
QRect r = menuItemContentRect(metrics, itemRect, true);
int x = r.x() + r.width() - metrics.arrowWidth;
r.setX(x);
r &= itemRect;
return QStyle::visualRect(direction, itemRect, r);
}
Q_NEVER_INLINE
void progressBarFillRects(const QStyleOptionProgressBar* bar,
// The rect that represents the filled/completed region
QRect& outFilled,
// The rect that represents the incomplete region
QRect& outNonFilled,
// Whether or not the progress bar is indeterminate
bool& outIsIndeterminate)
{
QRect ra = bar->rect;
QRect rb = ra;
bool isHorizontal = bar->orientation != Qt::Vertical;
bool isInverted = bar->invertedAppearance;
bool isIndeterminate = bar->minimum == 0 && bar->maximum == 0;
bool isForward = !isHorizontal || bar->direction != Qt::RightToLeft;
if (isInverted)
isForward = !isForward;
int maxLen = isHorizontal ? ra.width() : ra.height();
const auto availSteps = qMax(Q_INT64_C(1), qint64(bar->maximum) - bar->minimum);
const auto progress = qMax(bar->progress, bar->minimum); // workaround for bug in QProgressBar
const auto progressSteps = qint64(progress) - bar->minimum;
const auto progressBarWidth = progressSteps * maxLen / availSteps;
int barLen = isIndeterminate ? maxLen : progressBarWidth;
if (isHorizontal) {
if (isForward) {
ra.setWidth(barLen);
rb.setX(barLen);
} else {
ra.setX(ra.x() + ra.width() - barLen);
rb.setWidth(rb.width() - barLen);
}
} else {
if (isForward) {
ra.setY(ra.y() + ra.height() - barLen);
rb.setHeight(rb.height() - barLen);
} else {
ra.setHeight(barLen);
rb.setY(barLen);
}
}
outFilled = ra;
outNonFilled = rb;
outIsIndeterminate = isIndeterminate;
}
int calcBigLineSize(int radius)
{
int bigLineSize = radius / 6;
if (bigLineSize < 4)
bigLineSize = 4;
if (bigLineSize > radius / 2)
bigLineSize = radius / 2;
return bigLineSize;
}
Q_NEVER_INLINE QPointF calcRadialPos(const QStyleOptionSlider* dial, qreal offset)
{
const int width = dial->rect.width();
const int height = dial->rect.height();
const int r = qMin(width, height) / 2;
const int currentSliderPosition =
dial->upsideDown ? dial->sliderPosition : (dial->maximum - dial->sliderPosition);
qreal a = 0;
if (dial->maximum == dial->minimum)
a = Pi / 2;
else if (dial->dialWrapping)
a = Pi * 3 / 2 - (currentSliderPosition - dial->minimum) * 2 * Pi / (dial->maximum - dial->minimum);
else
a = (Pi * 8 - (currentSliderPosition - dial->minimum) * 10 * Pi / (dial->maximum - dial->minimum)) / 6;
qreal xc = width / 2.0;
qreal yc = height / 2.0;
qreal len = r - calcBigLineSize(r) - 3;
qreal back = offset * len;
QPointF pos(QPointF(xc + back * qCos(a), yc - back * qSin(a)));
return pos;
}
Q_NEVER_INLINE QPolygonF calcLines(const QStyleOptionSlider* dial)
{
QPolygonF poly;
qreal width = dial->rect.width();
qreal height = dial->rect.height();
qreal r = qMin(width, height) / 2.0;
int bigLineSize = calcBigLineSize(r);
qreal xc = width / 2.0 + 0.5;
qreal yc = height / 2.0 + 0.5;
const int ns = dial->tickInterval;
if (!ns) // Invalid values may be set by Qt Designer.
return poly;
int notches = (dial->maximum + ns - 1 - dial->minimum) / ns;
if (notches <= 0)
return poly;
if (dial->maximum < dial->minimum || dial->maximum - dial->minimum > 1000) {
int maximum = dial->minimum + 1000;
notches = (maximum + ns - 1 - dial->minimum) / ns;
}
poly.resize(2 + 2 * notches);
int smallLineSize = bigLineSize / 2;
for (int i = 0; i <= notches; ++i) {
qreal angle =
dial->dialWrapping ? Pi * 3 / 2 - i * 2 * Pi / notches : (Pi * 8 - i * 10 * Pi / notches) / 6;
qreal s = qSin(angle);
qreal c = qCos(angle);
if (i == 0 || (((ns * i) % (dial->pageStep ? dial->pageStep : 1)) == 0)) {
poly[2 * i] = QPointF(xc + (r - bigLineSize) * c, yc - (r - bigLineSize) * s);
poly[2 * i + 1] = QPointF(xc + r * c, yc - r * s);
} else {
poly[2 * i] = QPointF(xc + (r - 1 - smallLineSize) * c, yc - (r - 1 - smallLineSize) * s);
poly[2 * i + 1] = QPointF(xc + (r - 1) * c, yc - (r - 1) * s);
}
}
return poly;
}
// This will draw a nice and shiny QDial for us. We don't want
// all the shinyness in QWindowsStyle, hence we place it here
Q_NEVER_INLINE void drawDial(const QStyleOptionSlider* option, QPainter* painter)
{
namespace Dc = Phantom::DeriveColors;
const QPalette& pal = option->palette;
QColor buttonColor = Dc::buttonColor(option->palette);
const int width = option->rect.width();
const int height = option->rect.height();
const bool enabled = option->state & QStyle::State_Enabled;
qreal r = qMin(width, height) / 2.0;
r -= r / 50.0;
painter->save();
painter->setRenderHint(QPainter::Antialiasing);
// Draw notches
if (option->subControls & QStyle::SC_DialTickmarks) {
painter->setPen(pal.color(QPalette::Disabled, QPalette::Text));
painter->drawLines(calcLines(option));
}
const qreal d_ = r / 6;
const qreal dx = option->rect.x() + d_ + (width - 2 * r) / 2 + 1;
const qreal dy = option->rect.y() + d_ + (height - 2 * r) / 2 + 1;
QRectF br = QRectF(dx + 0.5, dy + 0.5, int(r * 2 - 2 * d_ - 2), int(r * 2 - 2 * d_ - 2));
if (enabled) {
painter->setBrush(buttonColor);
} else {
painter->setBrush(Qt::NoBrush);
}
painter->setPen(Dc::outlineOf(option->palette));
painter->drawEllipse(br);
painter->setBrush(Qt::NoBrush);
painter->setPen(Dc::specularOf(buttonColor));
painter->drawEllipse(br.adjusted(1, 1, -1, -1));
if (option->state & QStyle::State_HasFocus) {
QColor highlight = pal.highlight().color();
highlight.setHsv(highlight.hue(), qMin(160, highlight.saturation()), qMax(230, highlight.value()));
highlight.setAlpha(127);
painter->setPen(QPen(highlight, 2.0));
painter->setBrush(Qt::NoBrush);
painter->drawEllipse(br.adjusted(-1, -1, 1, 1));
}
QPointF dp = calcRadialPos(option, 0.70);