-
Notifications
You must be signed in to change notification settings - Fork 142
Expand file tree
/
Copy pathColorPicker.cs
More file actions
1488 lines (1293 loc) · 64.5 KB
/
ColorPicker.cs
File metadata and controls
1488 lines (1293 loc) · 64.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using CommunityToolkit.WinUI.Controls.Primitives;
using CommunityToolkit.WinUI.Helpers;
using System.Collections.Specialized;
using Windows.UI;
using ColorSpectrum = Microsoft.UI.Xaml.Controls.Primitives.ColorSpectrum;
using ColorPickerSlider = CommunityToolkit.WinUI.Controls.Primitives.ColorPickerSlider;
#if WINAPPSDK || HAS_UNO && WINUI
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Dispatching;
using Colors = Microsoft.UI.Colors;
#elif WINDOWS_UWP || HAS_UNO && WINUI2
using Windows.System;
using Windows.UI.Xaml.Input;
using Microsoft.UI.Xaml.Controls;
using Colors = Windows.UI.Colors;
#endif
namespace CommunityToolkit.WinUI.Controls;
/// <summary>
/// Presents a color spectrum, a palette of colors, and color channel sliders for user selection of a color.
/// </summary>
[TemplatePart(Name = nameof(ColorPicker.AlphaChannelNumberBox), Type = typeof(NumberBox))]
[TemplatePart(Name = nameof(ColorPicker.AlphaChannelSlider), Type = typeof(ColorPickerSlider))]
[TemplatePart(Name = nameof(ColorPicker.Channel1NumberBox), Type = typeof(NumberBox))]
[TemplatePart(Name = nameof(ColorPicker.Channel1Slider), Type = typeof(ColorPickerSlider))]
[TemplatePart(Name = nameof(ColorPicker.Channel2NumberBox), Type = typeof(NumberBox))]
[TemplatePart(Name = nameof(ColorPicker.Channel2Slider), Type = typeof(ColorPickerSlider))]
[TemplatePart(Name = nameof(ColorPicker.Channel3NumberBox), Type = typeof(NumberBox))]
[TemplatePart(Name = nameof(ColorPicker.Channel3Slider), Type = typeof(ColorPickerSlider))]
[TemplatePart(Name = nameof(ColorPicker.CheckeredBackground1Border), Type = typeof(Border))]
[TemplatePart(Name = nameof(ColorPicker.CheckeredBackground2Border), Type = typeof(Border))]
[TemplatePart(Name = nameof(ColorPicker.CheckeredBackground3Border), Type = typeof(Border))]
[TemplatePart(Name = nameof(ColorPicker.CheckeredBackground4Border), Type = typeof(Border))]
[TemplatePart(Name = nameof(ColorPicker.CheckeredBackground5Border), Type = typeof(Border))]
[TemplatePart(Name = nameof(ColorPicker.CheckeredBackground6Border), Type = typeof(Border))]
[TemplatePart(Name = nameof(ColorPicker.CheckeredBackground7Border), Type = typeof(Border))]
[TemplatePart(Name = nameof(ColorPicker.CheckeredBackground8Border), Type = typeof(Border))]
[TemplatePart(Name = nameof(ColorPicker.CheckeredBackground9Border), Type = typeof(Border))]
[TemplatePart(Name = nameof(ColorPicker.CheckeredBackground10Border), Type = typeof(Border))]
[TemplatePart(Name = nameof(ColorPicker.ColorPanelSelector), Type = typeof(Segmented))]
[TemplatePart(Name = nameof(ColorPicker.ContentContainer), Type = typeof(SwitchPresenter))]
[TemplatePart(Name = nameof(ColorPicker.ColorSpectrumControl), Type = typeof(ColorSpectrum))]
[TemplatePart(Name = nameof(ColorPicker.ColorSpectrumAlphaSlider), Type = typeof(ColorPickerSlider))]
[TemplatePart(Name = nameof(ColorPicker.ColorSpectrumThirdDimensionSlider), Type = typeof(ColorPickerSlider))]
[TemplatePart(Name = nameof(ColorPicker.PaletteItemGridView), Type = typeof(GridView))]
[TemplatePart(Name = nameof(ColorPicker.HexInputTextBox), Type = typeof(TextBox))]
[TemplatePart(Name = nameof(ColorPicker.ColorModeComboBox), Type = typeof(ComboBox))]
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1501:Statement should not be on a single line", Justification = "Inline brackets are used to improve code readability with repeated null checks.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1025:Code should not contain multiple whitespace in a row", Justification = "Whitespace is used to align code in columns for readability.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:Field names should begin with lower-case letter", Justification = "Only template parts start with a capital letter. This differentiates them from other fields.")]
public partial class ColorPicker : Microsoft.UI.Xaml.Controls.ColorPicker
{
internal Color CheckerBackgroundColor { get; set; } = Color.FromArgb(0x19, 0x80, 0x80, 0x80); // Overridden later
/// <summary>
/// The period that scheduled color updates will be applied.
/// This is only used when updating colors using the ScheduleColorUpdate() method.
/// Color changes made directly to the Color property will apply instantly.
/// </summary>
private const int ColorUpdateInterval = 30; // Milliseconds
private long tokenColor;
private bool callbacksConnected = false;
private bool eventsConnected = false;
private bool isInitialized = false;
// Color information for updates
private HsvColor? savedHsvColor = null;
private Color? savedHsvColorRgbEquivalent = null;
private Color? updatedRgbColor = null;
private DispatcherQueueTimer? dispatcherQueueTimer = null;
private Segmented ColorPanelSelector;
private SwitchPresenter ContentContainer;
private ColorSpectrum ColorSpectrumControl;
private ColorPickerSlider ColorSpectrumAlphaSlider;
private ColorPickerSlider ColorSpectrumThirdDimensionSlider;
private GridView PaletteItemGridView;
private TextBox HexInputTextBox;
private ComboBox ColorModeComboBox;
private NumberBox Channel1NumberBox;
private NumberBox Channel2NumberBox;
private NumberBox Channel3NumberBox;
private NumberBox AlphaChannelNumberBox;
private ColorPickerSlider Channel1Slider;
private ColorPickerSlider Channel2Slider;
private ColorPickerSlider Channel3Slider;
private ColorPickerSlider AlphaChannelSlider;
private ColorPreviewer ColorPreviewer;
// Up to 10 checkered backgrounds may be used by name anywhere in the template
private Border CheckeredBackground1Border;
private Border CheckeredBackground2Border;
private Border CheckeredBackground3Border;
private Border CheckeredBackground4Border;
private Border CheckeredBackground5Border;
private Border CheckeredBackground6Border;
private Border CheckeredBackground7Border;
private Border CheckeredBackground8Border;
private Border CheckeredBackground9Border;
private Border CheckeredBackground10Border;
/***************************************************************************************
*
* Constructor/Destructor
*
***************************************************************************************/
/// <summary>
/// Initializes a new instance of the <see cref="ColorPicker"/> class.
/// </summary>
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
public ColorPicker()
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
{
this.DefaultStyleKey = typeof(ColorPicker);
// Workaround for https://github.com/microsoft/microsoft-ui-xaml/issues/3502
this.DefaultStyleResourceUri = new Uri("ms-appx:///CommunityToolkit.WinUI.Controls.ColorPicker/Themes/Generic.xaml");
// Setup collections
this.SetValue(CustomPaletteColorsProperty, new ObservableCollection<Color>());
this.CustomPaletteColors.CollectionChanged += CustomPaletteColors_CollectionChanged;
this.Loaded += ColorPickerButton_Loaded;
// Checkered background color is found only one time for performance
// This may need to change in the future if theme changes should be supported
this.CheckerBackgroundColor = (Color)Application.Current.Resources["SystemListLowColor"];
this.ConnectCallbacks(true);
this.SetDefaultPalette();
this.StartDispatcherQueueTimer();
this.RegisterPropertyChangedCallback(IsColorChannelTextInputVisibleProperty, OnPanelVisibilityChanged);
this.RegisterPropertyChangedCallback(IsColorSpectrumVisibleProperty, OnPanelVisibilityChanged);
}
/// <summary>
/// Finalizes an instance of the <see cref="ColorPicker"/> class.
/// </summary>
~ColorPicker()
{
this.StopDispatcherQueueTimer();
this.CustomPaletteColors.CollectionChanged -= CustomPaletteColors_CollectionChanged;
}
/***************************************************************************************
*
* Methods
*
***************************************************************************************/
/// <summary>
/// Gets whether or not the color is considered empty (all fields zero).
/// In the future Color.IsEmpty will hopefully be added to UWP.
/// </summary>
/// <param name="color">The Windows.UI.Color to calculate with.</param>
/// <returns>Whether the color is considered empty.</returns>
private static bool IsColorEmpty(Color color)
{
return color.A == 0x00 &&
color.R == 0x00 &&
color.G == 0x00 &&
color.B == 0x00;
}
/// <summary>
/// Overrides when a template is applied in order to get the required controls.
/// </summary>
protected override void OnApplyTemplate()
{
// We need to disconnect old events first
this.ConnectEvents(false);
this.ColorPanelSelector = (Segmented)GetTemplateChild(nameof(ColorPanelSelector));
this.ContentContainer = (SwitchPresenter)GetTemplateChild(nameof(ContentContainer));
this.ColorSpectrumControl = (ColorSpectrum)GetTemplateChild(nameof(ColorSpectrumControl));
this.ColorSpectrumAlphaSlider = (ColorPickerSlider)this.GetTemplateChild(nameof(ColorSpectrumAlphaSlider));
this.ColorSpectrumThirdDimensionSlider = (ColorPickerSlider)this.GetTemplateChild(nameof(ColorSpectrumThirdDimensionSlider));
this.PaletteItemGridView = (GridView)GetTemplateChild(nameof(PaletteItemGridView));
this.HexInputTextBox = (TextBox)this.GetTemplateChild(nameof(HexInputTextBox));
this.ColorModeComboBox = (ComboBox)this.GetTemplateChild(nameof(ColorModeComboBox));
this.Channel1NumberBox = (NumberBox)this.GetTemplateChild(nameof(Channel1NumberBox));
this.Channel2NumberBox = (NumberBox)this.GetTemplateChild(nameof(Channel2NumberBox));
this.Channel3NumberBox = (NumberBox)this.GetTemplateChild(nameof(Channel3NumberBox));
this.AlphaChannelNumberBox = (NumberBox)this.GetTemplateChild(nameof(AlphaChannelNumberBox));
this.Channel1Slider = (ColorPickerSlider)this.GetTemplateChild(nameof(Channel1Slider));
this.Channel2Slider = (ColorPickerSlider)this.GetTemplateChild(nameof(Channel2Slider));
this.Channel3Slider = (ColorPickerSlider)this.GetTemplateChild(nameof(Channel3Slider));
this.AlphaChannelSlider = (ColorPickerSlider)this.GetTemplateChild(nameof(AlphaChannelSlider));
this.ColorPreviewer = (ColorPreviewer)this.GetTemplateChild(nameof(ColorPreviewer));
this.CheckeredBackground1Border = (Border)this.GetTemplateChild(nameof(CheckeredBackground1Border));
this.CheckeredBackground2Border = (Border)this.GetTemplateChild(nameof(CheckeredBackground2Border));
this.CheckeredBackground3Border = (Border)this.GetTemplateChild(nameof(CheckeredBackground3Border));
this.CheckeredBackground4Border = (Border)this.GetTemplateChild(nameof(CheckeredBackground4Border));
this.CheckeredBackground5Border = (Border)this.GetTemplateChild(nameof(CheckeredBackground5Border));
this.CheckeredBackground6Border = (Border)this.GetTemplateChild(nameof(CheckeredBackground6Border));
this.CheckeredBackground7Border = (Border)this.GetTemplateChild(nameof(CheckeredBackground7Border));
this.CheckeredBackground8Border = (Border)this.GetTemplateChild(nameof(CheckeredBackground8Border));
this.CheckeredBackground9Border = (Border)this.GetTemplateChild(nameof(CheckeredBackground9Border));
this.CheckeredBackground10Border = (Border)this.GetTemplateChild(nameof(CheckeredBackground10Border));
// Must connect after controls are resolved
this.ConnectEvents(true);
base.OnApplyTemplate();
this.UpdateVisualState(false);
this.ValidateSelectedPanel();
this.isInitialized = true;
this.SetActiveColorRepresentation(ColorRepresentation.Rgba);
this.UpdateColorControlValues(); // TODO: This will also connect events after, can we optimize vs. doing it twice with the ConnectEvents above?
}
/// <summary>
/// Connects or disconnects all dependency property callbacks.
/// </summary>
private void ConnectCallbacks(bool connected)
{
if (connected == true &&
this.callbacksConnected == false)
{
// Add callbacks for dependency properties
this.tokenColor = this.RegisterPropertyChangedCallback(ColorProperty, OnColorChanged);
this.callbacksConnected = true;
}
else if (connected == false &&
this.callbacksConnected == true)
{
// Remove callbacks for dependency properties
this.UnregisterPropertyChangedCallback(ColorProperty, this.tokenColor);
this.callbacksConnected = false;
}
return;
}
/// <summary>
/// Connects or disconnects all control event handlers.
/// </summary>
/// <param name="connected">True to connect event handlers, otherwise false.</param>
private void ConnectEvents(bool connected)
{
if (connected == true &&
this.eventsConnected == false)
{
// Add all events
if (this.ColorPanelSelector != null) { this.ColorPanelSelector.SelectionChanged += this.ColorPanelSelector_SelectionChanged; }
if (this.ColorSpectrumControl != null) { this.ColorSpectrumControl.ColorChanged += ColorSpectrum_ColorChanged; }
if (this.ColorSpectrumControl != null) { this.ColorSpectrumControl.GotFocus += ColorSpectrum_GotFocus; }
if (this.PaletteItemGridView != null) { this.PaletteItemGridView.SelectionChanged += this.PaletteItemGridView_SelectionChanged; }
if (this.HexInputTextBox != null) { this.HexInputTextBox.KeyDown += HexInputTextBox_KeyDown; }
if (this.HexInputTextBox != null) { this.HexInputTextBox.LostFocus += HexInputTextBox_LostFocus; }
if (this.ColorModeComboBox != null) { this.ColorModeComboBox.SelectionChanged += ColorModeComboBox_SelectionChanged; }
if (this.Channel1NumberBox != null) { this.Channel1NumberBox.ValueChanged += ChannelNumberBox_ValueChanged; }
if (this.Channel2NumberBox != null) { this.Channel2NumberBox.ValueChanged += ChannelNumberBox_ValueChanged; }
if (this.Channel3NumberBox != null) { this.Channel3NumberBox.ValueChanged += ChannelNumberBox_ValueChanged; }
if (this.AlphaChannelNumberBox != null) { this.AlphaChannelNumberBox.ValueChanged += ChannelNumberBox_ValueChanged; }
if (this.Channel1Slider != null) { this.Channel1Slider.ValueChanged += ChannelSlider_ValueChanged; }
if (this.Channel2Slider != null) { this.Channel2Slider.ValueChanged += ChannelSlider_ValueChanged; }
if (this.Channel3Slider != null) { this.Channel3Slider.ValueChanged += ChannelSlider_ValueChanged; }
if (this.AlphaChannelSlider != null) { this.AlphaChannelSlider.ValueChanged += ChannelSlider_ValueChanged; }
if (this.ColorSpectrumAlphaSlider != null) { this.ColorSpectrumAlphaSlider.ValueChanged += ChannelSlider_ValueChanged; }
if (this.ColorSpectrumThirdDimensionSlider != null) { this.ColorSpectrumThirdDimensionSlider.ValueChanged += ChannelSlider_ValueChanged; }
if (this.Channel1Slider != null) { this.Channel1Slider.Loaded += ChannelSlider_Loaded; }
if (this.Channel2Slider != null) { this.Channel2Slider.Loaded += ChannelSlider_Loaded; }
if (this.Channel3Slider != null) { this.Channel3Slider.Loaded += ChannelSlider_Loaded; }
if (this.AlphaChannelSlider != null) { this.AlphaChannelSlider.Loaded += ChannelSlider_Loaded; }
if (this.ColorSpectrumAlphaSlider != null) { this.ColorSpectrumAlphaSlider.Loaded += ChannelSlider_Loaded; }
if (this.ColorSpectrumThirdDimensionSlider != null) { this.ColorSpectrumThirdDimensionSlider.Loaded += ChannelSlider_Loaded; }
if (this.ColorPreviewer != null) { this.ColorPreviewer.ColorChangeRequested += ColorPreviewer_ColorChangeRequested; }
if (this.CheckeredBackground1Border != null) { this.CheckeredBackground1Border.Loaded += CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground2Border != null) { this.CheckeredBackground2Border.Loaded += CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground3Border != null) { this.CheckeredBackground3Border.Loaded += CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground4Border != null) { this.CheckeredBackground4Border.Loaded += CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground5Border != null) { this.CheckeredBackground5Border.Loaded += CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground6Border != null) { this.CheckeredBackground6Border.Loaded += CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground7Border != null) { this.CheckeredBackground7Border.Loaded += CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground8Border != null) { this.CheckeredBackground8Border.Loaded += CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground9Border != null) { this.CheckeredBackground9Border.Loaded += CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground10Border != null) { this.CheckeredBackground10Border.Loaded += CheckeredBackgroundBorder_Loaded; }
this.eventsConnected = true;
}
else if (connected == false &&
this.eventsConnected == true)
{
// Remove all events
if (this.ColorPanelSelector != null) { this.ColorPanelSelector.SelectionChanged -= this.ColorPanelSelector_SelectionChanged; }
if (this.ColorSpectrumControl != null) { this.ColorSpectrumControl.ColorChanged -= ColorSpectrum_ColorChanged; }
if (this.ColorSpectrumControl != null) { this.ColorSpectrumControl.GotFocus -= ColorSpectrum_GotFocus; }
if (this.PaletteItemGridView != null) { this.PaletteItemGridView.SelectionChanged -= this.PaletteItemGridView_SelectionChanged; }
if (this.HexInputTextBox != null) { this.HexInputTextBox.KeyDown -= HexInputTextBox_KeyDown; }
if (this.HexInputTextBox != null) { this.HexInputTextBox.LostFocus -= HexInputTextBox_LostFocus; }
if (this.ColorModeComboBox != null) { this.ColorModeComboBox.SelectionChanged -= ColorModeComboBox_SelectionChanged; }
if (this.Channel1NumberBox != null) { this.Channel1NumberBox.ValueChanged -= ChannelNumberBox_ValueChanged; }
if (this.Channel2NumberBox != null) { this.Channel2NumberBox.ValueChanged -= ChannelNumberBox_ValueChanged; }
if (this.Channel3NumberBox != null) { this.Channel3NumberBox.ValueChanged -= ChannelNumberBox_ValueChanged; }
if (this.AlphaChannelNumberBox != null) { this.AlphaChannelNumberBox.ValueChanged -= ChannelNumberBox_ValueChanged; }
if (this.Channel1Slider != null) { this.Channel1Slider.ValueChanged -= ChannelSlider_ValueChanged; }
if (this.Channel2Slider != null) { this.Channel2Slider.ValueChanged -= ChannelSlider_ValueChanged; }
if (this.Channel3Slider != null) { this.Channel3Slider.ValueChanged -= ChannelSlider_ValueChanged; }
if (this.AlphaChannelSlider != null) { this.AlphaChannelSlider.ValueChanged -= ChannelSlider_ValueChanged; }
if (this.ColorSpectrumAlphaSlider != null) { this.ColorSpectrumAlphaSlider.ValueChanged -= ChannelSlider_ValueChanged; }
if (this.ColorSpectrumThirdDimensionSlider != null) { this.ColorSpectrumThirdDimensionSlider.ValueChanged -= ChannelSlider_ValueChanged; }
if (this.Channel1Slider != null) { this.Channel1Slider.Loaded -= ChannelSlider_Loaded; }
if (this.Channel2Slider != null) { this.Channel2Slider.Loaded -= ChannelSlider_Loaded; }
if (this.Channel3Slider != null) { this.Channel3Slider.Loaded -= ChannelSlider_Loaded; }
if (this.AlphaChannelSlider != null) { this.AlphaChannelSlider.Loaded -= ChannelSlider_Loaded; }
if (this.ColorSpectrumAlphaSlider != null) { this.ColorSpectrumAlphaSlider.Loaded -= ChannelSlider_Loaded; }
if (this.ColorSpectrumThirdDimensionSlider != null) { this.ColorSpectrumThirdDimensionSlider.Loaded -= ChannelSlider_Loaded; }
if (this.ColorPreviewer != null) { this.ColorPreviewer.ColorChangeRequested -= ColorPreviewer_ColorChangeRequested; }
if (this.CheckeredBackground1Border != null) { this.CheckeredBackground1Border.Loaded -= CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground2Border != null) { this.CheckeredBackground2Border.Loaded -= CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground3Border != null) { this.CheckeredBackground3Border.Loaded -= CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground4Border != null) { this.CheckeredBackground4Border.Loaded -= CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground5Border != null) { this.CheckeredBackground5Border.Loaded -= CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground6Border != null) { this.CheckeredBackground6Border.Loaded -= CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground7Border != null) { this.CheckeredBackground7Border.Loaded -= CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground8Border != null) { this.CheckeredBackground8Border.Loaded -= CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground9Border != null) { this.CheckeredBackground9Border.Loaded -= CheckeredBackgroundBorder_Loaded; }
if (this.CheckeredBackground10Border != null) { this.CheckeredBackground10Border.Loaded -= CheckeredBackgroundBorder_Loaded; }
this.eventsConnected = false;
}
return;
}
/// <summary>
/// Updates all visual states based on current control properties.
/// </summary>
/// <param name="useTransitions">Whether transitions should occur when changing states.</param>
private void UpdateVisualState(bool useTransitions = true)
{
VisualStateManager.GoToState(this, this.IsEnabled ? "Normal" : "Disabled", useTransitions);
VisualStateManager.GoToState(this, this.GetActiveColorRepresentation() == ColorRepresentation.Hsva ? "HsvSelected" : "RgbSelected", useTransitions);
VisualStateManager.GoToState(this, this.IsColorPaletteVisible ? "ColorPaletteVisible" : "ColorPaletteCollapsed", useTransitions);
// Check if only a single vie is selected and hide the Segmented control
VisualStateManager.GoToState(this, (Truth(IsColorPaletteVisible, IsColorSpectrumVisible, IsColorChannelTextInputVisible) <= 1) ? "ColorPanelSelectorCollapsed" : "ColorPanelSelectorVisible", useTransitions);
}
private static int Truth(params bool[] booleans)
{
return booleans.Count(b => b);
}
/// <summary>
/// Gets the active representation of the color: HSV or RGB.
/// </summary>
private ColorRepresentation GetActiveColorRepresentation()
{
// If the HSV representation control is missing for whatever reason,
// the default will be RGB
if (this.ColorModeComboBox != null &&
this.ColorModeComboBox.SelectedIndex == 1)
{
return ColorRepresentation.Hsva;
}
return ColorRepresentation.Rgba;
}
/// <summary>
/// Sets the active color representation in the UI controls.
/// </summary>
/// <param name="colorRepresentation">The color representation to set.
/// Setting to null (the default) will attempt to keep the current state.</param>
private void SetActiveColorRepresentation(ColorRepresentation? colorRepresentation = null)
{
bool eventsDisconnectedByMethod = false;
if (colorRepresentation == null)
{
// Use the control's current value
colorRepresentation = this.GetActiveColorRepresentation();
}
// Disable events during the update
if (this.eventsConnected)
{
this.ConnectEvents(false);
eventsDisconnectedByMethod = true;
}
// Sync the UI controls and visual state
// The default is always RGBA
if (colorRepresentation == ColorRepresentation.Hsva)
{
this.ColorModeComboBox.SelectedIndex = 1;
}
else
{
this.ColorModeComboBox.SelectedIndex = 0;
}
this.UpdateVisualState(false);
if (eventsDisconnectedByMethod)
{
this.ConnectEvents(true);
}
return;
}
/// <summary>
/// Gets the active third dimension in the color spectrum: Hue, Saturation or Value.
/// </summary>
private ColorChannel GetActiveColorSpectrumThirdDimension()
{
switch (this.ColorSpectrumComponents)
{
case Microsoft.UI.Xaml.Controls.ColorSpectrumComponents.SaturationValue:
case Microsoft.UI.Xaml.Controls.ColorSpectrumComponents.ValueSaturation:
{
// Hue
return ColorChannel.Channel1;
}
case Microsoft.UI.Xaml.Controls.ColorSpectrumComponents.HueValue:
case Microsoft.UI.Xaml.Controls.ColorSpectrumComponents.ValueHue:
{
// Saturation
return ColorChannel.Channel2;
}
case Microsoft.UI.Xaml.Controls.ColorSpectrumComponents.HueSaturation:
case Microsoft.UI.Xaml.Controls.ColorSpectrumComponents.SaturationHue:
{
// Value
return ColorChannel.Channel3;
}
}
return ColorChannel.Alpha; // Error, should never get here
}
/// <summary>
/// Declares a new color to set to the control.
/// Application of this color will be scheduled to avoid overly rapid updates.
/// </summary>
/// <param name="newColor">The new color to set to the control. </param>
private void ScheduleColorUpdate(Color newColor)
{
// Coerce the value as needed
if (this.IsAlphaEnabled == false)
{
newColor = new Color()
{
R = newColor.R,
G = newColor.G,
B = newColor.B,
A = 255
};
}
this.updatedRgbColor = newColor;
return;
}
/// <summary>
/// Updates the color values in all editing controls to match the current color.
/// </summary>
private void UpdateColorControlValues()
{
bool eventsDisconnectedByMethod = false;
Color rgbColor = this.Color;
HsvColor hsvColor;
if (this.isInitialized)
{
// Disable events during the update
if (this.eventsConnected)
{
this.ConnectEvents(false);
eventsDisconnectedByMethod = true;
}
if (this.HexInputTextBox != null)
{
if (this.IsAlphaEnabled)
{
// Remove only the "#" sign
this.HexInputTextBox.Text = rgbColor.ToString().TrimStart('#');
}
else
{
// Remove the "#" sign and alpha hex
this.HexInputTextBox.Text = rgbColor.ToString().TrimStart('#')[2..];
}
}
// Regardless of the active color representation, the spectrum is always HSV
// Therefore, always calculate HSV color here
// Warning: Always maintain/use HSV information in the saved HSV color
// This avoids loss of precision and drift caused by continuously converting to/from RGB
if (this.savedHsvColor == null)
{
hsvColor = rgbColor.ToHsv();
// Round the channels, be sure rounding matches with the scaling next
// Rounding of SVA requires at MINIMUM 2 decimal places
int decimals = 0;
hsvColor = new HsvColor()
{
Hue = Math.Round(hsvColor.Hue, decimals),
Saturation = Math.Round(hsvColor.Saturation, 2 + decimals),
Value = Math.Round(hsvColor.Value, 2 + decimals),
Alpha = Math.Round(hsvColor.Alpha, 2 + decimals)
};
// Must update HSV color
this.savedHsvColor = hsvColor;
this.savedHsvColorRgbEquivalent = rgbColor;
}
else
{
hsvColor = this.savedHsvColor.Value;
}
// Update the color spectrum
// Remember the spectrum is always HSV and must be updated as such to avoid
// conversion errors
if (this.ColorSpectrumControl != null)
{
this.ColorSpectrumControl.HsvColor = new System.Numerics.Vector4()
{
X = Convert.ToSingle(hsvColor.Hue),
Y = Convert.ToSingle(hsvColor.Saturation),
Z = Convert.ToSingle(hsvColor.Value),
W = Convert.ToSingle(hsvColor.Alpha)
};
}
// Update the color spectrum third dimension channel
if (this.ColorSpectrumThirdDimensionSlider != null)
{
// Convert the channels into a usable range for the user
double hue = hsvColor.Hue;
double staturation = hsvColor.Saturation * 100;
double value = hsvColor.Value * 100;
switch (this.GetActiveColorSpectrumThirdDimension())
{
case ColorChannel.Channel1:
{
// Hue
this.ColorSpectrumThirdDimensionSlider.Minimum = 0;
this.ColorSpectrumThirdDimensionSlider.Maximum = 360;
this.ColorSpectrumThirdDimensionSlider.Value = hue;
break;
}
case ColorChannel.Channel2:
{
// Saturation
this.ColorSpectrumThirdDimensionSlider.Minimum = 0;
this.ColorSpectrumThirdDimensionSlider.Maximum = 100;
this.ColorSpectrumThirdDimensionSlider.Value = staturation;
break;
}
case ColorChannel.Channel3:
{
// Value
this.ColorSpectrumThirdDimensionSlider.Minimum = 0;
this.ColorSpectrumThirdDimensionSlider.Maximum = 100;
this.ColorSpectrumThirdDimensionSlider.Value = value;
break;
}
}
}
// Update the preview color
if (this.ColorPreviewer != null)
{
this.ColorPreviewer.HsvColor = hsvColor;
}
// Update all other color channels
if (this.GetActiveColorRepresentation() == ColorRepresentation.Hsva)
{
// Convert the channels into a usable range for the user
double hue = hsvColor.Hue;
double staturation = hsvColor.Saturation * 100;
double value = hsvColor.Value * 100;
double alpha = hsvColor.Alpha * 100;
// Hue
if (this.Channel1NumberBox != null)
{
this.Channel1NumberBox.Minimum = 0;
this.Channel1NumberBox.Maximum = 360;
this.Channel1NumberBox.Value = hue;
}
if (this.Channel1Slider != null)
{
this.Channel1Slider.Minimum = 0;
this.Channel1Slider.Maximum = 360;
this.Channel1Slider.Value = hue;
}
// Saturation
if (this.Channel2NumberBox != null)
{
this.Channel2NumberBox.Minimum = 0;
this.Channel2NumberBox.Maximum = 100;
this.Channel2NumberBox.Value = staturation;
}
if (this.Channel2Slider != null)
{
this.Channel2Slider.Minimum = 0;
this.Channel2Slider.Maximum = 100;
this.Channel2Slider.Value = staturation;
}
// Value
if (this.Channel3NumberBox != null)
{
this.Channel3NumberBox.Minimum = 0;
this.Channel3NumberBox.Maximum = 100;
this.Channel3NumberBox.Value = value;
}
if (this.Channel3Slider != null)
{
this.Channel3Slider.Minimum = 0;
this.Channel3Slider.Maximum = 100;
this.Channel3Slider.Value = value;
}
// Alpha
if (this.AlphaChannelNumberBox != null)
{
this.AlphaChannelNumberBox.Minimum = 0;
this.AlphaChannelNumberBox.Maximum = 100;
this.AlphaChannelNumberBox.Value = alpha;
}
if (this.AlphaChannelSlider != null)
{
this.AlphaChannelSlider.Minimum = 0;
this.AlphaChannelSlider.Maximum = 100;
this.AlphaChannelSlider.Value = alpha;
}
// Color spectrum alpha
if (this.ColorSpectrumAlphaSlider != null)
{
this.ColorSpectrumAlphaSlider.Minimum = 0;
this.ColorSpectrumAlphaSlider.Maximum = 100;
this.ColorSpectrumAlphaSlider.Value = alpha;
}
}
else
{
// Red
if (this.Channel1NumberBox != null)
{
this.Channel1NumberBox.Minimum = 0;
this.Channel1NumberBox.Maximum = 255;
this.Channel1NumberBox.Value = Convert.ToDouble(rgbColor.R);
}
if (this.Channel1Slider != null)
{
this.Channel1Slider.Minimum = 0;
this.Channel1Slider.Maximum = 255;
this.Channel1Slider.Value = Convert.ToDouble(rgbColor.R);
}
// Green
if (this.Channel2NumberBox != null)
{
this.Channel2NumberBox.Minimum = 0;
this.Channel2NumberBox.Maximum = 255;
this.Channel2NumberBox.Value = Convert.ToDouble(rgbColor.G);
}
if (this.Channel2Slider != null)
{
this.Channel2Slider.Minimum = 0;
this.Channel2Slider.Maximum = 255;
this.Channel2Slider.Value = Convert.ToDouble(rgbColor.G);
}
// Blue
if (this.Channel3NumberBox != null)
{
this.Channel3NumberBox.Minimum = 0;
this.Channel3NumberBox.Maximum = 255;
this.Channel3NumberBox.Value = Convert.ToDouble(rgbColor.B);
}
if (this.Channel3Slider != null)
{
this.Channel3Slider.Minimum = 0;
this.Channel3Slider.Maximum = 255;
this.Channel3Slider.Value = Convert.ToDouble(rgbColor.B);
}
// Alpha
if (this.AlphaChannelNumberBox != null)
{
this.AlphaChannelNumberBox.Minimum = 0;
this.AlphaChannelNumberBox.Maximum = 255;
this.AlphaChannelNumberBox.Value = Convert.ToDouble(rgbColor.A);
}
if (this.AlphaChannelSlider != null)
{
this.AlphaChannelSlider.Minimum = 0;
this.AlphaChannelSlider.Maximum = 255;
this.AlphaChannelSlider.Value = Convert.ToDouble(rgbColor.A);
}
// Color spectrum alpha
if (this.ColorSpectrumAlphaSlider != null)
{
this.ColorSpectrumAlphaSlider.Minimum = 0;
this.ColorSpectrumAlphaSlider.Maximum = 255;
this.ColorSpectrumAlphaSlider.Value = Convert.ToDouble(rgbColor.A);
}
}
if (eventsDisconnectedByMethod)
{
this.ConnectEvents(true);
}
}
return;
}
/// <summary>
/// Sets a new color channel value to the current color.
/// Only the specified color channel will be modified.
/// </summary>
/// <param name="colorRepresentation">The color representation of the given channel.</param>
/// <param name="channel">The specified color channel to modify.</param>
/// <param name="newValue">The new color channel value.</param>
private void SetColorChannel(
ColorRepresentation colorRepresentation,
ColorChannel channel,
double newValue)
{
Color oldRgbColor = this.Color;
Color newRgbColor;
HsvColor oldHsvColor;
if (colorRepresentation == ColorRepresentation.Hsva)
{
// Warning: Always maintain/use HSV information in the saved HSV color
// This avoids loss of precision and drift caused by continuously converting to/from RGB
if (this.savedHsvColor == null)
{
oldHsvColor = oldRgbColor.ToHsv();
}
else
{
oldHsvColor = this.savedHsvColor.Value;
}
double hue = oldHsvColor.Hue;
double saturation = oldHsvColor.Saturation;
double value = oldHsvColor.Value;
double alpha = oldHsvColor.Alpha;
switch (channel)
{
case ColorChannel.Channel1:
{
hue = Math.Clamp(double.IsNaN(newValue) ? 0 : newValue, 0, 360);
break;
}
case ColorChannel.Channel2:
{
saturation = Math.Clamp((double.IsNaN(newValue) ? 0 : newValue) / 100, 0, 1);
break;
}
case ColorChannel.Channel3:
{
value = Math.Clamp((double.IsNaN(newValue) ? 0 : newValue) / 100, 0, 1);
break;
}
case ColorChannel.Alpha:
{
// Unlike color channels, default to no transparency
alpha = Math.Clamp((double.IsNaN(newValue) ? 100 : newValue) / 100, 0, 1);
break;
}
}
var hsv = HsvColor.Create(hue, saturation, value, alpha);
newRgbColor = hsv;
// Must update HSV color
this.savedHsvColor = hsv;
this.savedHsvColorRgbEquivalent = newRgbColor;
}
else
{
byte red = oldRgbColor.R;
byte green = oldRgbColor.G;
byte blue = oldRgbColor.B;
byte alpha = oldRgbColor.A;
switch (channel)
{
case ColorChannel.Channel1:
{
red = Convert.ToByte(Math.Clamp(double.IsNaN(newValue) ? 0 : newValue, 0, 255));
break;
}
case ColorChannel.Channel2:
{
green = Convert.ToByte(Math.Clamp(double.IsNaN(newValue) ? 0 : newValue, 0, 255));
break;
}
case ColorChannel.Channel3:
{
blue = Convert.ToByte(Math.Clamp(double.IsNaN(newValue) ? 0 : newValue, 0, 255));
break;
}
case ColorChannel.Alpha:
{
// Unlike color channels, default to no transparency
alpha = Convert.ToByte(Math.Clamp(double.IsNaN(newValue) ? 255 : newValue, 0, 255));
break;
}
}
newRgbColor = new Color()
{
R = red,
G = green,
B = blue,
A = alpha
};
// Must clear saved HSV color
this.savedHsvColor = null;
this.savedHsvColorRgbEquivalent = null;
}
this.ScheduleColorUpdate(newRgbColor);
return;
}
/// <summary>
/// Updates all channel slider control backgrounds.
/// </summary>
private void UpdateChannelSliderBackgrounds()
{
this.UpdateChannelSliderBackground(this.Channel1Slider);
this.UpdateChannelSliderBackground(this.Channel2Slider);
this.UpdateChannelSliderBackground(this.Channel3Slider);
this.UpdateChannelSliderBackground(this.AlphaChannelSlider);
this.UpdateChannelSliderBackground(this.ColorSpectrumAlphaSlider);
this.UpdateChannelSliderBackground(this.ColorSpectrumThirdDimensionSlider);
return;
}
/// <summary>
/// Updates a specific channel slider control background.
/// </summary>
/// <param name="slider">The color channel slider to update the background for.</param>
private void UpdateChannelSliderBackground(ColorPickerSlider slider)
{
if (slider != null)
{
// Regardless of the active color representation, the sliders always use HSV
// Therefore, always calculate HSV color here
// Warning: Always maintain/use HSV information in the saved HSV color
// This avoids loss of precision and drift caused by continuously converting to/from RGB
if (this.savedHsvColor == null)
{
var rgbColor = this.Color;
// Must update HSV color
this.savedHsvColor = rgbColor.ToHsv();
this.savedHsvColorRgbEquivalent = rgbColor;
}
slider.IsAutoUpdatingEnabled = false;
if (object.ReferenceEquals(slider, this.Channel1Slider))
{
slider.ColorChannel = ColorChannel.Channel1;
slider.ColorRepresentation = this.GetActiveColorRepresentation();
}
else if (object.ReferenceEquals(slider, this.Channel2Slider))
{
slider.ColorChannel = ColorChannel.Channel2;
slider.ColorRepresentation = this.GetActiveColorRepresentation();
}
else if (object.ReferenceEquals(slider, this.Channel3Slider))
{
slider.ColorChannel = ColorChannel.Channel3;
slider.ColorRepresentation = this.GetActiveColorRepresentation();
}
else if (object.ReferenceEquals(slider, this.AlphaChannelSlider))
{
slider.ColorChannel = ColorChannel.Alpha;
slider.ColorRepresentation = this.GetActiveColorRepresentation();
}
else if (object.ReferenceEquals(slider, this.ColorSpectrumAlphaSlider))
{
slider.ColorChannel = ColorChannel.Alpha;
slider.ColorRepresentation = this.GetActiveColorRepresentation();
}
else if (object.ReferenceEquals(slider, this.ColorSpectrumThirdDimensionSlider))
{
slider.ColorChannel = this.GetActiveColorSpectrumThirdDimension();
slider.ColorRepresentation = ColorRepresentation.Hsva; // Always HSV
}
slider.HsvColor = this.savedHsvColor.Value;
slider.UpdateColors();
}
return;
}
/// <summary>
/// Sets the default color palette to the control.
/// </summary>
private void SetDefaultPalette()
{
this.CustomPalette = new FluentColorPalette();
return;
}
/// <summary>
/// Validates and updates the current 'tab' or 'panel' selection.
/// If the currently selected tab is collapsed, the next visible tab will be selected.
/// </summary>
private void ValidateSelectedPanel()
{
object? selectedItem = null;
if (this.ColorPanelSelector != null)
{
if (this.ColorPanelSelector.SelectedItem == null &&
this.ColorPanelSelector.Items.Count > 0)
{
// As a failsafe, forcefully select the first item
selectedItem = this.ColorPanelSelector.Items[0];
}
else
{
selectedItem = this.ColorPanelSelector.SelectedItem;