Skip to main content

waft_winui/controls/
color_picker.rs

1//! ColorPicker.xaml, ColorPicker_themeresources.xaml and ColorPicker.cpp: a colour chosen on a
2//! spectrum, with a slider for the spectrum's third component, an opacity slider, a preview, and
3//! text boxes for the RGB or HSV channels, the opacity and the hex value.
4//!
5//! Template, as the `Vertical` orientation lays it out: `RootGrid` (312 to 392 wide, padded 4
6//! above and below) holds a grid of four Auto rows and four Auto columns. Row 0 is
7//! `ColorSpectrumGrid` (columns *, Auto): the `ColorSpectrum` (256 to 336 square) and
8//! `ColorPreviewRectangleGrid` (44 wide, 12 after the spectrum), whose checkered background,
9//! `ColorPreviewRectangle` and `PreviousColorRectangle` (the lower half while there is a previous
10//! colour) and `BorderRectangle` fill it. Row 1 is `ThirdDimensionSliderGrid`, a 12 tall gradient
11//! of the third component (`ThirdDimensionBackgroundRectangle`) under `ThirdDimensionSlider`.
12//! Row 2 is `AlphaSliderGrid`: a checkered background, the opacity gradient and `AlphaSlider`.
13//! Row 3 is `MoreEntriesPanel`: `MoreButton`, a borderless toggle button, over `TextEntryGrid`
14//! (columns *, 5, *): `ColorRepresentationComboBox` (RGB or HSV), `HexTextBox` beside it, and
15//! below them `RgbPanel` or `HsvPanel`, three text boxes each with a label, and `AlphaPanel`.
16//! The `Horizontal` orientation puts the spectrum, the two sliders (turned vertical) and the
17//! entries side by side in row 0.
18//!
19//! The application owns the colour: `color` is what it passes, and `color_changed` asks for
20//! another, with the colour before. The colour the picker asks for is what the picker reads as
21//! its own until the application next builds it; if the application passed another by then, the
22//! picker shows that one. The picker keeps the hue and saturation it was given while the colour
23//! has none, as WinUI's does, for as long as the application passes back the colours it asks
24//! for.
25
26use super::toggle_button::{ToggleButtonSetters, toggle_button_presenter};
27use crate::after_next_frame;
28use crate::{
29    Brush, COLOR_PICKER_BORDER_THICKNESS, ColorChangedEventArgs, ColorPickerHsvChannel,
30    ColorPickerSlider, ColorSpectrum, ColorSpectrumColorChangedEventArgs, ColorSpectrumComponents,
31    ColorSpectrumShape, ColumnDefinition, ComboBox, ComboBoxItem, CommonState, FluentSymbol,
32    FontIcon, Grid, GridCell, GridLength, Hsv, HsvColor, Margin, Rgb, RowDefinition, SizeObserver,
33    TextBox, ThemeResources, ToggleButton, ToggleButtonBrushes, argb, checkered_background_pixels,
34    color_from_rgba, control_text_style, hex_to_rgb, hex_to_rgba, hsv_to_rgb,
35    image_from_pixel_data, rgb_from_color, rgb_to_hex, rgb_to_hsv, rgba_to_hex, same_color,
36    try_parse_int, wtoi,
37};
38use std::{fmt, rc::Rc};
39use waft_embedder::valo::{
40    GradientStop, Matrix, Paint, PaintStyle, Point, Shader, SpreadMode, Stroke,
41};
42use waft_embedder::{Canvas, Color, FontWeight, Image, Rect, Size, TextAffinity, TextSelection};
43use waft_foundation::{App, Handle, Listenable, Listener, Ref};
44use waft_painting::AlignmentGeometry;
45use waft_rendering::{BoxConstraints, CustomPainter};
46use waft_scheduler::FrameCallback;
47use waft_services::TextEditingValue;
48use waft_widgets::*;
49
50/// Receives XAML `ColorPicker.ColorChanged`.
51pub type ColorPickerColorChangedHandler = Rc<dyn Fn(&mut App, ColorChangedEventArgs)>;
52
53/// `ColorSpectrum`'s `MinWidth` and `MinHeight` in the template.
54const SPECTRUM_MIN_SIZE: f64 = 256.0;
55/// `ColorSpectrum`'s `MaxWidth` and `MaxHeight` in the template.
56const SPECTRUM_MAX_SIZE: f64 = 336.0;
57/// `ColorPreviewRectangleGrid`'s `Width`, and its `Height` while the spectrum is collapsed.
58const PREVIEW_SIZE: f64 = 44.0;
59/// The `Height` of the sliders' background rectangles, and their `Width` when vertical.
60const SLIDER_BACKGROUND_SIZE: f64 = 12.0;
61/// `MoreButton`'s `MinHeight`.
62const MORE_BUTTON_MIN_HEIGHT: f64 = 32.0;
63/// `MoreButton`'s `MinWidth`.
64const MORE_BUTTON_MIN_WIDTH: f64 = 120.0;
65/// `MoreGlyph`'s `FontSize`.
66const MORE_GLYPH_FONT_SIZE: f64 = 12.0;
67/// `Width` of the channel text boxes and the colour model box.
68const TEXT_BOX_WIDTH: f64 = 120.0;
69/// `HexTextBox`'s `Width` in the `Vertical` orientation.
70const HEX_TEXT_BOX_WIDTH: f64 = 132.0;
71/// `MaxLength` of a colour channel's text box.
72const CHANNEL_MAX_LENGTH: i32 = 3;
73/// `AlphaTextBox`'s `MaxLength`.
74const ALPHA_MAX_LENGTH: i32 = 4;
75/// `HexTextBox`'s `MaxLength`, and with alpha enabled (`AlphaEnabled`).
76const HEX_MAX_LENGTH: [i32; 2] = [7, 9];
77/// `TabIndex` an element without one has: `Int32.MaxValue`.
78const DEFAULT_TAB_INDEX: i32 = i32::MAX;
79
80/// XAML `ColorPicker` with the template of `ColorPicker.xaml`.
81#[derive(Clone)]
82pub struct ColorPicker {
83    /// `Color`: white by default.
84    pub color: Color,
85
86    /// `ColorChanged`: asks the application for another colour; the application owns `color`.
87    pub color_changed: ColorPickerColorChangedHandler,
88
89    /// `PreviousColor`: shown beside the colour while set.
90    pub previous_color: Option<Color>,
91
92    /// `IsAlphaEnabled`: whether opacity can be chosen.
93    pub is_alpha_enabled: bool,
94
95    /// `IsColorSpectrumVisible`; true by default.
96    pub is_color_spectrum_visible: bool,
97    /// `IsColorPreviewVisible`; true by default.
98    pub is_color_preview_visible: bool,
99    /// `IsColorSliderVisible`: the third component's slider; true by default.
100    pub is_color_slider_visible: bool,
101    /// `IsAlphaSliderVisible`, while alpha is enabled; true by default.
102    pub is_alpha_slider_visible: bool,
103    /// `IsMoreButtonVisible`: the text entries hide behind a More button, in the vertical
104    /// orientation only.
105    pub is_more_button_visible: bool,
106    /// `IsColorChannelTextInputVisible`; true by default.
107    pub is_color_channel_text_input_visible: bool,
108    /// `IsAlphaTextInputVisible`, while alpha is enabled; true by default.
109    pub is_alpha_text_input_visible: bool,
110    /// `IsHexInputVisible`; true by default.
111    pub is_hex_input_visible: bool,
112
113    /// `MinHue`, from 0 to 359; 0 by default.
114    pub min_hue: i32,
115    /// `MaxHue`, from 0 to 359; 359 by default.
116    pub max_hue: i32,
117    /// `MinSaturation`, from 0 to 100; 0 by default.
118    pub min_saturation: i32,
119    /// `MaxSaturation`, from 0 to 100; 100 by default.
120    pub max_saturation: i32,
121    /// `MinValue`, from 0 to 100; 0 by default.
122    pub min_value: i32,
123    /// `MaxValue`, from 0 to 100; 100 by default.
124    pub max_value: i32,
125
126    /// `ColorSpectrumShape`.
127    pub color_spectrum_shape: ColorSpectrumShape,
128
129    /// `ColorSpectrumComponents`.
130    pub color_spectrum_components: ColorSpectrumComponents,
131
132    /// `Orientation`: [`Axis::Vertical`] by default, or [`Axis::Horizontal`].
133    pub orientation: Axis,
134
135    /// `CornerRadius` of the spectrum, the preview and the opacity slider's background;
136    /// `ControlCornerRadius` by default; the theme's `ControlCornerRadius` when `None`.
137    pub corner_radius: Option<f64>,
138
139    /// `IsEnabled`.
140    pub is_enabled: bool,
141
142    /// Identity retained across parent rebuilds.
143    pub key: Option<KeyRef>,
144}
145
146/// Panics unless `value` is within `0..=max`, as the source throws for the property `name`.
147fn assert_range(name: &str, value: i32, max: i32) {
148    assert!(
149        (0..=max).contains(&value),
150        "{name} must be between 0 and {max}."
151    );
152}
153
154impl ColorPicker {
155    /// Creates a picker showing `color`, which asks for others through `color_changed`.
156    pub fn new(
157        color: Color,
158        color_changed: impl Fn(&mut App, ColorChangedEventArgs) + 'static,
159    ) -> ColorPicker {
160        ColorPicker {
161            color,
162            color_changed: Rc::new(color_changed),
163            previous_color: None,
164            is_alpha_enabled: false,
165            is_color_spectrum_visible: true,
166            is_color_preview_visible: true,
167            is_color_slider_visible: true,
168            is_alpha_slider_visible: true,
169            is_more_button_visible: false,
170            is_color_channel_text_input_visible: true,
171            is_alpha_text_input_visible: true,
172            is_hex_input_visible: true,
173            min_hue: 0,
174            max_hue: 359,
175            min_saturation: 0,
176            max_saturation: 100,
177            min_value: 0,
178            max_value: 100,
179            color_spectrum_shape: ColorSpectrumShape::Box,
180            color_spectrum_components: ColorSpectrumComponents::HueSaturation,
181            orientation: Axis::Vertical,
182            corner_radius: None,
183            is_enabled: true,
184            key: None,
185        }
186    }
187
188    /// Sets PreviousColor.
189    pub fn previous_color(mut self, value: Color) -> Self {
190        self.previous_color = Some(value);
191        self
192    }
193
194    /// Sets IsAlphaEnabled.
195    pub fn is_alpha_enabled(mut self, value: bool) -> Self {
196        self.is_alpha_enabled = value;
197        self
198    }
199
200    /// Sets IsColorSpectrumVisible.
201    pub fn is_color_spectrum_visible(mut self, value: bool) -> Self {
202        self.is_color_spectrum_visible = value;
203        self
204    }
205
206    /// Sets IsColorPreviewVisible.
207    pub fn is_color_preview_visible(mut self, value: bool) -> Self {
208        self.is_color_preview_visible = value;
209        self
210    }
211
212    /// Sets IsColorSliderVisible.
213    pub fn is_color_slider_visible(mut self, value: bool) -> Self {
214        self.is_color_slider_visible = value;
215        self
216    }
217
218    /// Sets IsAlphaSliderVisible.
219    pub fn is_alpha_slider_visible(mut self, value: bool) -> Self {
220        self.is_alpha_slider_visible = value;
221        self
222    }
223
224    /// Sets IsMoreButtonVisible.
225    pub fn is_more_button_visible(mut self, value: bool) -> Self {
226        self.is_more_button_visible = value;
227        self
228    }
229
230    /// Sets IsColorChannelTextInputVisible.
231    pub fn is_color_channel_text_input_visible(mut self, value: bool) -> Self {
232        self.is_color_channel_text_input_visible = value;
233        self
234    }
235
236    /// Sets IsAlphaTextInputVisible.
237    pub fn is_alpha_text_input_visible(mut self, value: bool) -> Self {
238        self.is_alpha_text_input_visible = value;
239        self
240    }
241
242    /// Sets IsHexInputVisible.
243    pub fn is_hex_input_visible(mut self, value: bool) -> Self {
244        self.is_hex_input_visible = value;
245        self
246    }
247
248    /// Sets MinHue.
249    pub fn min_hue(mut self, value: i32) -> Self {
250        assert_range("MinHue", value, 359);
251        self.min_hue = value;
252        self
253    }
254
255    /// Sets MaxHue.
256    pub fn max_hue(mut self, value: i32) -> Self {
257        assert_range("MaxHue", value, 359);
258        self.max_hue = value;
259        self
260    }
261
262    /// Sets MinSaturation.
263    pub fn min_saturation(mut self, value: i32) -> Self {
264        assert_range("MinSaturation", value, 100);
265        self.min_saturation = value;
266        self
267    }
268
269    /// Sets MaxSaturation.
270    pub fn max_saturation(mut self, value: i32) -> Self {
271        assert_range("MaxSaturation", value, 100);
272        self.max_saturation = value;
273        self
274    }
275
276    /// Sets MinValue.
277    pub fn min_value(mut self, value: i32) -> Self {
278        assert_range("MinValue", value, 100);
279        self.min_value = value;
280        self
281    }
282
283    /// Sets MaxValue.
284    pub fn max_value(mut self, value: i32) -> Self {
285        assert_range("MaxValue", value, 100);
286        self.max_value = value;
287        self
288    }
289
290    /// Sets ColorSpectrumShape.
291    pub fn color_spectrum_shape(mut self, value: ColorSpectrumShape) -> Self {
292        self.color_spectrum_shape = value;
293        self
294    }
295
296    /// Sets ColorSpectrumComponents.
297    pub fn color_spectrum_components(mut self, value: ColorSpectrumComponents) -> Self {
298        self.color_spectrum_components = value;
299        self
300    }
301
302    /// Sets `Orientation`: [`Axis::Vertical`] by default, or [`Axis::Horizontal`].
303    pub fn orientation(mut self, value: Axis) -> Self {
304        self.orientation = value;
305        self
306    }
307
308    /// Sets CornerRadius.
309    pub fn corner_radius(mut self, value: f64) -> Self {
310        self.corner_radius = Some(value);
311        self
312    }
313
314    /// Sets IsEnabled.
315    pub fn is_enabled(mut self, value: bool) -> Self {
316        self.is_enabled = value;
317        self
318    }
319
320    /// Sets widget identity.
321    pub fn key(mut self, key: KeyRef) -> Self {
322        self.key = Some(key);
323        self
324    }
325
326    /// `ApplyConstraintsToRgbColor`: `rgb` with its hue, saturation and value clamped to the
327    /// ranges.
328    fn apply_constraints_to_rgb_color(&self, rgb: Rgb) -> Rgb {
329        let mut hsv = rgb_to_hsv(rgb);
330        hsv.h = hsv
331            .h
332            .max(f64::from(self.min_hue))
333            .min(f64::from(self.max_hue));
334        hsv.s = hsv
335            .s
336            .max(f64::from(self.min_saturation) / 100.0)
337            .min(f64::from(self.max_saturation) / 100.0);
338        hsv.v = hsv
339            .v
340            .max(f64::from(self.min_value) / 100.0)
341            .min(f64::from(self.max_value) / 100.0);
342        hsv_to_rgb(hsv)
343    }
344
345    /// The channel `SetThirdDimensionSliderChannel` gives the third dimension's slider: the
346    /// component the spectrum does not lay out.
347    fn third_dimension_channel(&self) -> ColorPickerHsvChannel {
348        match self.color_spectrum_components {
349            ColorSpectrumComponents::ValueSaturation | ColorSpectrumComponents::SaturationValue => {
350                ColorPickerHsvChannel::Hue
351            }
352            ColorSpectrumComponents::HueValue | ColorSpectrumComponents::ValueHue => {
353                ColorPickerHsvChannel::Saturation
354            }
355            ColorSpectrumComponents::HueSaturation | ColorSpectrumComponents::SaturationHue => {
356                ColorPickerHsvChannel::Value
357            }
358        }
359    }
360
361    /// `Minimum` and `Maximum` of the third dimension's slider (`UpdateThirdDimensionSlider`).
362    fn third_dimension_range(&self) -> (i32, i32) {
363        match self.third_dimension_channel() {
364            ColorPickerHsvChannel::Hue => (self.min_hue, self.max_hue),
365            ColorPickerHsvChannel::Saturation => (self.min_saturation, self.max_saturation),
366            _ => (self.min_value, self.max_value),
367        }
368    }
369}
370
371impl fmt::Debug for ColorPicker {
372    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373        f.debug_struct("ColorPicker")
374            .field("color", &self.color)
375            .field("is_alpha_enabled", &self.is_alpha_enabled)
376            .field("orientation", &self.orientation)
377            .field("is_enabled", &self.is_enabled)
378            .finish_non_exhaustive()
379    }
380}
381
382/// `ColorUpdateReason`: what changed the colour, whose control is then not updated from it.
383#[derive(Clone, Copy, Debug, PartialEq, Eq)]
384enum ColorUpdateReason {
385    InitializingColor,
386    ColorPropertyChanged,
387    ColorSpectrumColorChanged,
388    ThirdDimensionSliderChanged,
389    AlphaSliderChanged,
390    RgbTextBoxChanged,
391    HsvTextBoxChanged,
392    AlphaTextBoxChanged,
393    HexTextBoxChanged,
394}
395
396/// The template's text boxes.
397#[derive(Clone, Copy, Debug, PartialEq, Eq)]
398enum ChannelTextBox {
399    Red,
400    Green,
401    Blue,
402    Hue,
403    Saturation,
404    Value,
405    Alpha,
406    Hex,
407}
408
409impl ChannelTextBox {
410    /// Every text box, in the template's order.
411    const ALL: [ChannelTextBox; 8] = [
412        ChannelTextBox::Red,
413        ChannelTextBox::Green,
414        ChannelTextBox::Blue,
415        ChannelTextBox::Hue,
416        ChannelTextBox::Saturation,
417        ChannelTextBox::Value,
418        ChannelTextBox::Alpha,
419        ChannelTextBox::Hex,
420    ];
421
422    fn index(self) -> usize {
423        self as usize
424    }
425
426    /// The label beside the text box.
427    fn label(self) -> &'static str {
428        match self {
429            ChannelTextBox::Red => "Red",
430            ChannelTextBox::Green => "Green",
431            ChannelTextBox::Blue => "Blue",
432            ChannelTextBox::Hue => "Hue",
433            ChannelTextBox::Saturation => "Saturation",
434            ChannelTextBox::Value => "Value",
435            ChannelTextBox::Alpha => "Opacity",
436            ChannelTextBox::Hex => "",
437        }
438    }
439
440    /// The text the template gives the box before the colour is set.
441    fn initial_text(self) -> &'static str {
442        match self {
443            ChannelTextBox::Red | ChannelTextBox::Green | ChannelTextBox::Blue => "255",
444            ChannelTextBox::Hue | ChannelTextBox::Saturation => "0",
445            ChannelTextBox::Value => "100",
446            ChannelTextBox::Alpha => "100%",
447            ChannelTextBox::Hex => "#FFFFFF",
448        }
449    }
450}
451
452/// A text box of the template: its text, its focus and the listener on the focus.
453struct TextBoxPart {
454    controller: Ref<TextEditingController>,
455    focus: Ref<FocusNode>,
456    focus_listener: Listener,
457}
458
459/// The template's visual state groups, each the state `UpdateVisualState` goes to.
460#[derive(Clone, Copy, Debug, PartialEq, Eq)]
461struct VisualStates {
462    /// `ColorSpectrumVisibility`: `ColorSpectrumVisible` or `ColorSpectrumCollapsed`.
463    color_spectrum_visible: bool,
464    /// `ColorPreviewVisibility`.
465    color_preview_visible: bool,
466    /// `PreviousColorVisibility`.
467    previous_color: PreviousColorVisibility,
468    /// `ThirdDimensionSliderVisibility`.
469    third_dimension_slider_visible: bool,
470    /// `AlphaSliderVisibility`.
471    alpha_slider_visible: bool,
472    /// `MoreButtonVisibility`.
473    more_button_visible: bool,
474    /// `TextEntryGridVisibility`: `TextEntryGridVisible` shows the entries and turns the More
475    /// button's chevron up.
476    text_entry_grid_visible: bool,
477    /// `ColorChannelTextInputVisibility`.
478    color_channel_text_input_visible: bool,
479    /// `AlphaTextInputVisibility`.
480    alpha_text_input_visible: bool,
481    /// `ColorRepresentationSelected`.
482    color_representation: ColorRepresentation,
483    /// `HexInputVisibility`.
484    hex_input_visible: bool,
485    /// `AlphaEnabledState`: `AlphaEnabled` lets the hex box take 9 characters.
486    alpha_enabled: bool,
487    /// `Orientation`: [`Axis::Vertical`] or [`Axis::Horizontal`].
488    orientation: Axis,
489}
490
491/// `PreviousColorVisibility`: with the spectrum (`Vertical`) the previous colour is the lower
492/// half of the preview, without it (`Horizontal`) the right half.
493#[derive(Clone, Copy, Debug, PartialEq, Eq)]
494#[allow(clippy::enum_variant_names, reason = "the template's state names")]
495enum PreviousColorVisibility {
496    PreviousColorCollapsedVertical,
497    PreviousColorVisibleVertical,
498    PreviousColorCollapsedHorizontal,
499    PreviousColorVisibleHorizontal,
500}
501
502/// `ColorRepresentationSelected`, the item of `ColorRepresentationComboBox`.
503#[derive(Clone, Copy, Debug, PartialEq, Eq)]
504#[allow(clippy::enum_variant_names, reason = "the template's state names")]
505enum ColorRepresentation {
506    RgbSelected,
507    HsvSelected,
508}
509
510impl StatefulWidget for ColorPicker {
511    type State = ColorPickerState;
512
513    fn key(&self) -> Option<&KeyRef> {
514        self.key.as_ref()
515    }
516
517    fn create_state(&self) -> ColorPickerState {
518        ColorPickerState {
519            state: StateData::new(),
520            color: self.color,
521            current_rgb: Rgb::new(1.0, 1.0, 1.0),
522            current_hsv: Hsv::new(0.0, 1.0, 1.0),
523            current_hex: "#FFFFFFFF".to_owned(),
524            current_alpha: 1.0,
525            previous_string: String::new(),
526            is_focused_text_box_valid: false,
527            text_entry_grid_opened: false,
528            color_representation: 0,
529            spectrum_hsv: HsvColor::WHITE,
530            spectrum_height: None,
531            third_dimension_value: 0.0,
532            alpha_slider_value: 0.0,
533            text_boxes: Vec::new(),
534            traversal_policy: None,
535            preview_size: Size::ZERO,
536            alpha_background_size: Size::ZERO,
537            checker_color: None,
538            preview_checkers: None,
539            alpha_checkers: None,
540            updating_widget: false,
541        }
542    }
543}
544
545/// The parts ColorPicker.cpp keeps of its template, and its colour.
546pub struct ColorPickerState {
547    state: StateData<ColorPicker>,
548
549    /// `Color` as the picker reads it: the colour it last asked for until the application next
550    /// builds it, else the application's.
551    color: Color,
552
553    /// `m_currentRgb`.
554    current_rgb: Rgb,
555    /// `m_currentHsv`.
556    current_hsv: Hsv,
557    /// `m_currentHex`.
558    current_hex: String,
559    /// `m_currentAlpha`.
560    current_alpha: f64,
561
562    /// `m_previousString`: the focused text box's text when it took the focus.
563    previous_string: String,
564    /// `m_isFocusedTextBoxValid`.
565    is_focused_text_box_valid: bool,
566
567    /// `m_textEntryGridOpened`: `MoreButton` is checked.
568    text_entry_grid_opened: bool,
569
570    /// `ColorRepresentationComboBox.SelectedIndex`: 0 for RGB, 1 for HSV.
571    color_representation: usize,
572
573    /// `ColorSpectrum.HsvColor`, as the picker last set it or the spectrum asked for it.
574    spectrum_hsv: HsvColor,
575
576    /// `ColorSpectrum.Height`, which `OnColorSpectrumSizeChanged` keeps at its width.
577    spectrum_height: Option<f64>,
578
579    /// `ThirdDimensionSlider.Value`.
580    third_dimension_value: f64,
581
582    /// `AlphaSlider.Value`.
583    alpha_slider_value: f64,
584
585    /// The text boxes, by `ChannelTextBox::index`.
586    text_boxes: Vec<TextBoxPart>,
587
588    /// Orders the focus by the template's `TabIndex`.
589    traversal_policy: Option<Ref<OrderedTraversalPolicy>>,
590
591    /// `ColorPreviewRectangleGrid`'s size after the last layout.
592    preview_size: Size,
593    /// `AlphaSliderBackgroundRectangle`'s size after the last layout.
594    alpha_background_size: Size,
595    /// `CheckerColorBrush.Color` the checkered backgrounds were made with.
596    checker_color: Option<Color>,
597    /// `ColorPreviewRectangleCheckeredBackgroundImageBrush.ImageSource`.
598    preview_checkers: Option<Image>,
599    /// `AlphaSliderCheckeredBackgroundImageBrush.ImageSource`.
600    alpha_checkers: Option<Image>,
601
602    /// The application's properties are being applied, during which `ColorChanged` waits for the
603    /// end of the frame.
604    updating_widget: bool,
605}
606
607impl ColorPickerState {
608    /// `GetCurrentHsv`.
609    pub(crate) fn current_hsv(self: Handle<Self>, app: &App) -> Hsv {
610        app.get(self).current_hsv
611    }
612
613    fn part(self: Handle<Self>, app: &App, text_box: ChannelTextBox) -> &TextBoxPart {
614        &app.get(self).text_boxes[text_box.index()]
615    }
616
617    fn text(self: Handle<Self>, app: &App, text_box: ChannelTextBox) -> String {
618        let controller = self.part(app, text_box).controller.handle();
619        controller.text_value(app).to_owned()
620    }
621
622    /// `TextBox.Text = text`: the box shows `text` with the caret at the start, when it shows
623    /// other text.
624    fn set_text(self: Handle<Self>, app: &mut App, text_box: ChannelTextBox, text: &str) {
625        let controller = self.part(app, text_box).controller.handle();
626        if controller.text_value(app) != text {
627            controller.set_value(
628                app,
629                TextEditingValue::new()
630                    .text(text)
631                    .selection(TextSelection::collapsed(0, TextAffinity::Downstream)),
632            );
633        }
634    }
635
636    /// `GetCurrentHexValue`.
637    fn current_hex_value(self: Handle<Self>, app: &App) -> String {
638        let state = app.get(self);
639        if self.widget(app).is_alpha_enabled {
640            rgba_to_hex(state.current_rgb, state.current_alpha)
641        } else {
642            rgb_to_hex(state.current_rgb)
643        }
644    }
645
646    /// The current colour from `color`: `OnColorChanged` and `InitializeColor`.
647    fn read_color(self: Handle<Self>, app: &mut App, color: Color) {
648        let rgb = rgb_from_color(color);
649        let state = app.get_mut(self);
650        state.current_rgb = rgb;
651        state.current_alpha = f64::from(argb(color).a) / 255.0;
652        state.current_hsv = rgb_to_hsv(rgb);
653        app.get_mut(self).current_hex = self.current_hex_value(app);
654    }
655
656    /// `UpdateColor` with an RGB colour.
657    fn update_color_rgb(self: Handle<Self>, app: &mut App, rgb: Rgb, reason: ColorUpdateReason) {
658        let state = app.get_mut(self);
659        state.current_rgb = rgb;
660        state.current_hsv = rgb_to_hsv(rgb);
661        app.get_mut(self).current_hex = self.current_hex_value(app);
662        self.set_color_and_update_controls(app, reason);
663    }
664
665    /// `UpdateColor` with an HSV colour.
666    fn update_color_hsv(self: Handle<Self>, app: &mut App, hsv: Hsv, reason: ColorUpdateReason) {
667        let state = app.get_mut(self);
668        state.current_hsv = hsv;
669        state.current_rgb = hsv_to_rgb(hsv);
670        app.get_mut(self).current_hex = self.current_hex_value(app);
671        self.set_color_and_update_controls(app, reason);
672    }
673
674    /// `UpdateColor` with an alpha.
675    fn update_color_alpha(
676        self: Handle<Self>,
677        app: &mut App,
678        alpha: f64,
679        reason: ColorUpdateReason,
680    ) {
681        app.get_mut(self).current_alpha = alpha;
682        app.get_mut(self).current_hex = self.current_hex_value(app);
683        self.set_color_and_update_controls(app, reason);
684    }
685
686    /// `SetColorAndUpdateControls`: `Color` becomes the current colour, which raises
687    /// `ColorChanged` when it changes, and then the controls show it.
688    fn set_color_and_update_controls(self: Handle<Self>, app: &mut App, reason: ColorUpdateReason) {
689        let state = app.get(self);
690        let new = color_from_rgba(state.current_rgb, state.current_alpha);
691        let old = state.color;
692        app.get_mut(self).color = new;
693        if !same_color(old, new) {
694            self.raise_color_changed(app, old, new);
695        }
696        if !app.contains(self) || !self.mounted(app) {
697            return;
698        }
699        self.update_color_controls(app, reason);
700        if !app.get(self).updating_widget {
701            self.set_state(app, |_| {});
702        }
703    }
704
705    /// `OnColorChanged`'s event: `ColorChanged` asks the application for `new`, at once for a
706    /// change the user made, and once the frame is over for one the picker made to what the
707    /// application passed, if the picker still has that colour then.
708    fn raise_color_changed(self: Handle<Self>, app: &mut App, old: Color, new: Color) {
709        let args = ColorChangedEventArgs {
710            old_color: old,
711            new_color: new,
712        };
713        if !app.get(self).updating_widget {
714            let handler = self.widget(app).color_changed.clone();
715            handler(app, args);
716            return;
717        }
718        let view = View::maybe_id_of(app, self.context(app));
719        after_next_frame(
720            app,
721            view,
722            FrameCallback::new(move |app, _| {
723                if !app.contains(self)
724                    || !self.mounted(app)
725                    || !same_color(app.get(self).color, new)
726                {
727                    return;
728                }
729                let handler = self.widget(app).color_changed.clone();
730                handler(app, args);
731            }),
732        );
733    }
734
735    /// `UpdateColorControls`: every control but the one that changed the colour shows it.
736    fn update_color_controls(self: Handle<Self>, app: &mut App, reason: ColorUpdateReason) {
737        let state = app.get(self);
738        let (rgb, hsv, alpha) = (state.current_rgb, state.current_hsv, state.current_alpha);
739        let hex = state.current_hex.clone();
740        if reason != ColorUpdateReason::ColorSpectrumColorChanged {
741            app.get_mut(self).spectrum_hsv = HsvColor::from_hsv(hsv, alpha as f32);
742        }
743        if reason != ColorUpdateReason::ThirdDimensionSliderChanged {
744            self.update_third_dimension_slider(app);
745        }
746        if reason != ColorUpdateReason::AlphaSliderChanged {
747            // `UpdateAlphaSlider`.
748            app.get_mut(self).alpha_slider_value = alpha * 100.0;
749        }
750        if app.get(self).text_boxes.is_empty() {
751            return;
752        }
753        let byte = |channel: f64| ((channel * 255.0).round() as u8).to_string();
754        let percent = |channel: f64| ((channel * 100.0).round() as i32).to_string();
755        if reason != ColorUpdateReason::RgbTextBoxChanged {
756            self.set_text(app, ChannelTextBox::Red, &byte(rgb.r));
757            self.set_text(app, ChannelTextBox::Green, &byte(rgb.g));
758            self.set_text(app, ChannelTextBox::Blue, &byte(rgb.b));
759        }
760        if reason != ColorUpdateReason::HsvTextBoxChanged {
761            self.set_text(
762                app,
763                ChannelTextBox::Hue,
764                &(hsv.h.round() as i32).to_string(),
765            );
766            self.set_text(app, ChannelTextBox::Saturation, &percent(hsv.s));
767            self.set_text(app, ChannelTextBox::Value, &percent(hsv.v));
768        }
769        if reason != ColorUpdateReason::AlphaTextBoxChanged {
770            self.set_text(app, ChannelTextBox::Alpha, &format!("{}%", percent(alpha)));
771        }
772        if reason != ColorUpdateReason::HexTextBoxChanged {
773            self.set_text(app, ChannelTextBox::Hex, &hex);
774        }
775    }
776
777    /// `UpdateThirdDimensionSlider`'s value: the third component of the colour.
778    fn update_third_dimension_slider(self: Handle<Self>, app: &mut App) {
779        let hsv = app.get(self).current_hsv;
780        let value = match self.widget(app).third_dimension_channel() {
781            ColorPickerHsvChannel::Hue => hsv.h,
782            ColorPickerHsvChannel::Saturation => hsv.s * 100.0,
783            _ => hsv.v * 100.0,
784        };
785        app.get_mut(self).third_dimension_value = value;
786    }
787
788    /// `OnColorSpectrumColorChanged`: the colour the spectrum asks for, which the picker passes
789    /// back to it.
790    fn spectrum_color_changed(
791        self: Handle<Self>,
792        app: &mut App,
793        args: ColorSpectrumColorChangedEventArgs,
794    ) {
795        app.get_mut(self).spectrum_hsv = args.hsv_color;
796        self.update_color_hsv(
797            app,
798            args.hsv_color.hsv(),
799            ColorUpdateReason::ColorSpectrumColorChanged,
800        );
801    }
802
803    /// `OnThirdDimensionSliderValueChanged`: the slider's value is the third component.
804    fn third_dimension_slider_changed(self: Handle<Self>, app: &mut App, value: f64) {
805        app.get_mut(self).third_dimension_value = value;
806        let mut hsv = app.get(self).current_hsv;
807        match self.widget(app).third_dimension_channel() {
808            ColorPickerHsvChannel::Hue => hsv.h = value,
809            ColorPickerHsvChannel::Saturation => hsv.s = value / 100.0,
810            _ => hsv.v = value / 100.0,
811        }
812        self.update_color_hsv(app, hsv, ColorUpdateReason::ThirdDimensionSliderChanged);
813    }
814
815    /// `OnAlphaSliderValueChanged`.
816    fn alpha_slider_changed(self: Handle<Self>, app: &mut App, value: f64) {
817        app.get_mut(self).alpha_slider_value = value;
818        self.update_color_alpha(app, value / 100.0, ColorUpdateReason::AlphaSliderChanged);
819    }
820
821    /// `OnMoreButtonChecked` and `OnMoreButtonUnchecked`.
822    fn more_button_checked(self: Handle<Self>, app: &mut App, checked: bool) {
823        self.set_state(app, |state| state.text_entry_grid_opened = checked);
824    }
825
826    /// `OnColorRepresentationComboBoxSelectionChanged`.
827    fn color_representation_changed(self: Handle<Self>, app: &mut App, index: Option<usize>) {
828        if let Some(index) = index {
829            self.set_state(app, |state| state.color_representation = index);
830        }
831    }
832
833    /// `OnTextBoxGotFocus` and `OnTextBoxLostFocus`: arriving focus records the text; leaving
834    /// puts back that text when what was typed is not valid, and then every text box shows the
835    /// colour, clearing what was not applied.
836    fn text_box_focus_changed(self: Handle<Self>, app: &mut App, text_box: ChannelTextBox) {
837        if !app.contains(self) || !self.mounted(app) {
838            return;
839        }
840        if self.part(app, text_box).focus.has_focus(app) {
841            let text = self.text(app, text_box);
842            let state = app.get_mut(self);
843            state.is_focused_text_box_valid = true;
844            state.previous_string = text;
845            return;
846        }
847        if !app.get(self).is_focused_text_box_valid {
848            let previous = app.get(self).previous_string.clone();
849            self.set_text(app, text_box, &previous);
850        }
851        self.update_color_controls(app, ColorUpdateReason::ColorPropertyChanged);
852        self.set_state(app, |_| {});
853    }
854
855    /// The `TextChanging` handlers: valid text changes the colour, other text only marks the
856    /// box invalid.
857    fn text_changed(self: Handle<Self>, app: &mut App, text_box: ChannelTextBox) {
858        match text_box {
859            ChannelTextBox::Red | ChannelTextBox::Green | ChannelTextBox::Blue => {
860                self.rgb_text_changed(app, text_box)
861            }
862            ChannelTextBox::Hue | ChannelTextBox::Saturation | ChannelTextBox::Value => {
863                self.hsv_text_changed(app, text_box)
864            }
865            ChannelTextBox::Alpha => self.alpha_text_changed(app),
866            ChannelTextBox::Hex => self.hex_text_changed(app),
867        }
868    }
869
870    /// `OnRgbTextChanging`: a channel from 0 to 255 makes the colour of the three boxes,
871    /// within the ranges.
872    fn rgb_text_changed(self: Handle<Self>, app: &mut App, text_box: ChannelTextBox) {
873        let valid = try_parse_int(&self.text(app, text_box)).is_some_and(|value| value <= 255);
874        app.get_mut(self).is_focused_text_box_valid = valid;
875        if valid {
876            // `GetRgbColorFromTextBoxes`.
877            let channel = |text_box| f64::from(wtoi(&self.text(app, text_box))) / 255.0;
878            let rgb = Rgb::new(
879                channel(ChannelTextBox::Red),
880                channel(ChannelTextBox::Green),
881                channel(ChannelTextBox::Blue),
882            );
883            let rgb = self.widget(app).apply_constraints_to_rgb_color(rgb);
884            self.update_color_rgb(app, rgb, ColorUpdateReason::RgbTextBoxChanged);
885        }
886    }
887
888    /// `OnHueTextChanging`, `OnSaturationTextChanging` and `OnValueTextChanging`: a component
889    /// within its range makes the colour of the three boxes.
890    fn hsv_text_changed(self: Handle<Self>, app: &mut App, text_box: ChannelTextBox) {
891        let widget = self.widget(app);
892        let (min, max) = match text_box {
893            ChannelTextBox::Hue => (widget.min_hue, widget.max_hue),
894            ChannelTextBox::Saturation => (widget.min_saturation, widget.max_saturation),
895            _ => (widget.min_value, widget.max_value),
896        };
897        // The source compares as unsigned numbers.
898        let valid = try_parse_int(&self.text(app, text_box))
899            .is_some_and(|value| value >= min as u32 && value <= max as u32);
900        app.get_mut(self).is_focused_text_box_valid = valid;
901        if valid {
902            // `GetHsvColorFromTextBoxes`.
903            let component = |text_box| f64::from(wtoi(&self.text(app, text_box)));
904            let hsv = Hsv::new(
905                component(ChannelTextBox::Hue),
906                component(ChannelTextBox::Saturation) / 100.0,
907                component(ChannelTextBox::Value) / 100.0,
908            );
909            self.update_color_hsv(app, hsv, ColorUpdateReason::HsvTextBoxChanged);
910        }
911    }
912
913    /// `OnAlphaTextChanging`: text without a final `%` gets one, the caret staying where it
914    /// was; a percentage from 0 to 100 is the alpha.
915    fn alpha_text_changed(self: Handle<Self>, app: &mut App) {
916        let controller = self.part(app, ChannelTextBox::Alpha).controller.handle();
917        let text = controller.text_value(app).to_owned();
918        if !text.ends_with('%') {
919            let cursor = controller.value(app).selection.end();
920            controller.set_value(
921                app,
922                TextEditingValue::new()
923                    .text(format!("{text}%"))
924                    .selection(TextSelection::collapsed(cursor, TextAffinity::Downstream)),
925            );
926        }
927        let text = controller.text_value(app).to_owned();
928        let alpha = try_parse_int(&text[..text.len() - 1]).filter(|value| *value <= 100);
929        app.get_mut(self).is_focused_text_box_valid = alpha.is_some();
930        if let Some(alpha) = alpha {
931            self.update_color_alpha(
932                app,
933                f64::from(alpha) / 100.0,
934                ColorUpdateReason::AlphaTextBoxChanged,
935            );
936        }
937    }
938
939    /// `OnHexTextChanging`: text without a leading `#` gets one, the caret going to the end;
940    /// a hex colour, with its alpha while alpha is enabled, is the colour within the ranges.
941    fn hex_text_changed(self: Handle<Self>, app: &mut App) {
942        let controller = self.part(app, ChannelTextBox::Hex).controller.handle();
943        let text = controller.text_value(app).to_owned();
944        if !text.starts_with('#') {
945            let text = format!("#{text}");
946            let end = text.encode_utf16().count() as i32;
947            controller.set_value(
948                app,
949                TextEditingValue::new()
950                    .text(text)
951                    .selection(TextSelection::collapsed(end, TextAffinity::Downstream)),
952            );
953        }
954        let text = controller.text_value(app).to_owned();
955        let parsed = if self.widget(app).is_alpha_enabled {
956            hex_to_rgba(&text)
957        } else {
958            hex_to_rgb(&text).map(|rgb| (rgb, 1.0))
959        };
960        app.get_mut(self).is_focused_text_box_valid = parsed.is_some();
961        if let Some((rgb, alpha)) = parsed {
962            let rgb = self.widget(app).apply_constraints_to_rgb_color(rgb);
963            self.update_color_rgb(app, rgb, ColorUpdateReason::HexTextBoxChanged);
964            self.update_color_alpha(app, alpha, ColorUpdateReason::HexTextBoxChanged);
965        }
966    }
967
968    /// `OnColorSpectrumSizeChanged`: the spectrum is as tall as it is wide.
969    fn spectrum_size_changed(self: Handle<Self>, app: &mut App, previous: Size, size: Size) {
970        if app.contains(self) && self.mounted(app) && size.width() != previous.width() {
971            self.set_state(app, |state| state.spectrum_height = Some(size.width()));
972        }
973    }
974
975    /// `OnColorPreviewRectangleGridSizeChanged`.
976    fn preview_size_changed(self: Handle<Self>, app: &mut App, size: Size) {
977        if app.contains(self) && self.mounted(app) && app.get(self).preview_size != size {
978            app.get_mut(self).preview_size = size;
979            self.create_checkered_backgrounds(app);
980            self.set_state(app, |_| {});
981        }
982    }
983
984    /// `OnAlphaSliderBackgroundRectangleSizeChanged`.
985    fn alpha_background_size_changed(self: Handle<Self>, app: &mut App, size: Size) {
986        if app.contains(self) && self.mounted(app) && app.get(self).alpha_background_size != size {
987            app.get_mut(self).alpha_background_size = size;
988            self.create_checkered_backgrounds(app);
989            self.set_state(app, |_| {});
990        }
991    }
992
993    /// `CreateColorPreviewCheckeredBackground` and `CreateAlphaSliderCheckeredBackground`: the
994    /// checkerboards of `CheckerColorBrush` at the size of what they lie behind.
995    fn create_checkered_backgrounds(self: Handle<Self>, app: &mut App) {
996        let Some(checker) = app.get(self).checker_color else {
997            return;
998        };
999        let checkers = |app: &App, size: Size| {
1000            let (width, height) = (size.width().round() as u32, size.height().round() as u32);
1001            image_from_pixel_data(
1002                app,
1003                width,
1004                height,
1005                checkered_background_pixels(width, height, checker),
1006            )
1007        };
1008        let preview = checkers(app, app.get(self).preview_size);
1009        let alpha = checkers(app, app.get(self).alpha_background_size);
1010        let state = app.get_mut(self);
1011        state.preview_checkers = preview;
1012        state.alpha_checkers = alpha;
1013    }
1014
1015    /// `UpdateVisualState`.
1016    fn visual_states(self: Handle<Self>, app: &App) -> VisualStates {
1017        let widget = self.widget(app);
1018        let state = app.get(self);
1019        let vertical = widget.orientation == Axis::Vertical;
1020        let previous = widget.previous_color.is_some();
1021        let previous_color = match (widget.is_color_spectrum_visible, previous) {
1022            (true, true) => PreviousColorVisibility::PreviousColorVisibleVertical,
1023            (true, false) => PreviousColorVisibility::PreviousColorCollapsedVertical,
1024            (false, true) => PreviousColorVisibility::PreviousColorVisibleHorizontal,
1025            (false, false) => PreviousColorVisibility::PreviousColorCollapsedHorizontal,
1026        };
1027        VisualStates {
1028            color_spectrum_visible: widget.is_color_spectrum_visible,
1029            color_preview_visible: widget.is_color_preview_visible,
1030            previous_color,
1031            third_dimension_slider_visible: widget.is_color_slider_visible,
1032            alpha_slider_visible: widget.is_alpha_enabled && widget.is_alpha_slider_visible,
1033            // The More button is for the vertical orientation only.
1034            more_button_visible: widget.is_more_button_visible && vertical,
1035            text_entry_grid_visible: !widget.is_more_button_visible
1036                || state.text_entry_grid_opened
1037                || !vertical,
1038            color_channel_text_input_visible: widget.is_color_channel_text_input_visible,
1039            alpha_text_input_visible: widget.is_alpha_enabled && widget.is_alpha_text_input_visible,
1040            color_representation: if state.color_representation == 0 {
1041                ColorRepresentation::RgbSelected
1042            } else {
1043                ColorRepresentation::HsvSelected
1044            },
1045            hex_input_visible: widget.is_hex_input_visible,
1046            alpha_enabled: widget.is_alpha_enabled,
1047            orientation: widget.orientation,
1048        }
1049    }
1050
1051    /// The property changes of `OnPropertyChanged`, from `old` to the widget: a colour the
1052    /// application passed that is not the picker's (`OnColorChanged`), `IsAlphaEnabled`, which
1053    /// rewrites the hex, a narrowed range, which brings the colour into it, and the components,
1054    /// which give the third slider another channel. `ColorChanged` of a change made here waits
1055    /// for the end of the frame.
1056    fn apply_widget(self: Handle<Self>, app: &mut App, old: &ColorPicker) {
1057        let widget = self.widget(app).clone();
1058        app.get_mut(self).updating_widget = true;
1059        if !same_color(widget.color, app.get(self).color) {
1060            app.get_mut(self).color = widget.color;
1061            self.read_color(app, widget.color);
1062            self.update_color_controls(app, ColorUpdateReason::ColorPropertyChanged);
1063        }
1064        if old.is_alpha_enabled != widget.is_alpha_enabled {
1065            let hex = self.current_hex_value(app);
1066            app.get_mut(self).current_hex = hex.clone();
1067            self.set_text(app, ChannelTextBox::Hex, &hex);
1068        }
1069        if (old.min_hue, old.max_hue) != (widget.min_hue, widget.max_hue) {
1070            let mut hsv = app.get(self).current_hsv;
1071            hsv.h = hsv
1072                .h
1073                .min(f64::from(widget.max_hue))
1074                .max(f64::from(widget.min_hue));
1075            self.update_color_hsv(app, hsv, ColorUpdateReason::ColorPropertyChanged);
1076        }
1077        if (old.min_saturation, old.max_saturation)
1078            != (widget.min_saturation, widget.max_saturation)
1079        {
1080            let mut hsv = app.get(self).current_hsv;
1081            hsv.s = hsv
1082                .s
1083                .min(f64::from(widget.max_saturation) / 100.0)
1084                .max(f64::from(widget.min_saturation) / 100.0);
1085            self.update_color_hsv(app, hsv, ColorUpdateReason::ColorPropertyChanged);
1086        }
1087        if (old.min_value, old.max_value) != (widget.min_value, widget.max_value) {
1088            let mut hsv = app.get(self).current_hsv;
1089            hsv.v = hsv
1090                .v
1091                .min(f64::from(widget.max_value) / 100.0)
1092                .max(f64::from(widget.min_value) / 100.0);
1093            self.update_color_hsv(app, hsv, ColorUpdateReason::ColorPropertyChanged);
1094        }
1095        if old.color_spectrum_components != widget.color_spectrum_components {
1096            self.update_third_dimension_slider(app);
1097        }
1098        app.get_mut(self).updating_widget = false;
1099    }
1100}
1101
1102impl State for ColorPickerState {
1103    type Widget = ColorPicker;
1104    waft_widgets::state_accessors!();
1105
1106    fn init_state(self: Handle<Self>, app: &mut App) {
1107        for text_box in ChannelTextBox::ALL {
1108            let controller = TextEditingController::new(app);
1109            controller.set_text(app, text_box.initial_text());
1110            let focus = FocusNode::new(app);
1111            let focus_listener =
1112                Listener::new(move |app| self.text_box_focus_changed(app, text_box));
1113            focus.add_listener(app, focus_listener.clone());
1114            app.get_mut(self).text_boxes.push(TextBoxPart {
1115                controller,
1116                focus,
1117                focus_listener,
1118            });
1119        }
1120        app.get_mut(self).traversal_policy = Some(OrderedTraversalPolicy::new(app));
1121        // `OnApplyTemplate`: `InitializeColor`, then the ranges as if set after `Color`.
1122        let widget = self.widget(app).clone();
1123        app.get_mut(self).updating_widget = true;
1124        self.read_color(app, widget.color);
1125        self.set_color_and_update_controls(app, ColorUpdateReason::InitializingColor);
1126        app.get_mut(self).updating_widget = false;
1127        self.apply_widget(app, &ColorPicker::new(widget.color, |_, _| {}));
1128    }
1129
1130    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
1131        // `OnCheckerColorChanged`: `CheckerColorBrush` is `SystemListLowColor` of the theme.
1132        let checker = ThemeResources::of(app, self.context(app)).system_list_low_color;
1133        if app.get(self).checker_color != Some(checker) {
1134            app.get_mut(self).checker_color = Some(checker);
1135            self.create_checkered_backgrounds(app);
1136        }
1137    }
1138
1139    fn did_update_widget(self: Handle<Self>, app: &mut App, old: &ColorPicker) {
1140        self.apply_widget(app, old);
1141    }
1142
1143    fn dispose(self: Handle<Self>, app: &mut App) {
1144        for part in std::mem::take(&mut app.get_mut(self).text_boxes) {
1145            part.focus.remove_listener(app, &part.focus_listener);
1146            part.focus.dispose(app);
1147            part.controller.dispose(app);
1148        }
1149    }
1150
1151    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1152        let resources = ThemeResources::of(app, context);
1153        let states = self.visual_states(app);
1154        let vertical = states.orientation == Axis::Vertical;
1155        let mut cells = Vec::new();
1156        // `ColorSpectrumGrid`.
1157        cells.push(
1158            GridCell::new(Margin::new(
1159                if vertical {
1160                    [0.0, 0.0, 0.0, 16.0]
1161                } else {
1162                    [0.0; 4]
1163                },
1164                self.color_spectrum_grid(app, &resources, states),
1165            ))
1166            .into_widget(),
1167        );
1168        if states.third_dimension_slider_visible {
1169            // `ThirdDimensionSliderGrid`.
1170            let (row, column) = if vertical { (1, 0) } else { (0, 1) };
1171            cells.push(
1172                GridCell::new(Margin::new(
1173                    if vertical {
1174                        [0.0, 0.0, 0.0, 6.0]
1175                    } else {
1176                        [0.0, 0.0, 6.0, 0.0]
1177                    },
1178                    self.third_dimension_slider_grid(app, &resources, states),
1179                ))
1180                .row(row)
1181                .column(column)
1182                .into_widget(),
1183            );
1184        }
1185        if states.alpha_slider_visible {
1186            // `AlphaSliderGrid`.
1187            let (row, column) = if vertical { (2, 0) } else { (0, 2) };
1188            cells.push(
1189                GridCell::new(Margin::new(
1190                    if vertical {
1191                        [0.0, 0.0, 0.0, 16.0]
1192                    } else {
1193                        [0.0, 0.0, 16.0, 0.0]
1194                    },
1195                    self.alpha_slider_grid(app, &resources, states),
1196                ))
1197                .row(row)
1198                .column(column)
1199                .into_widget(),
1200            );
1201        }
1202        // `MoreEntriesPanel`.
1203        let (row, column) = if vertical { (3, 0) } else { (0, 3) };
1204        cells.push(
1205            GridCell::new(Margin::new(
1206                if vertical {
1207                    [0.0, 0.0, 0.0, 12.0]
1208                } else {
1209                    [0.0; 4]
1210                },
1211                self.more_entries_panel(app, &resources, states),
1212            ))
1213            .row(row)
1214            .column(column)
1215            .into_widget(),
1216        );
1217        let grid = Grid::new()
1218            .row_definitions([RowDefinition::new(GridLength::AUTO); 4])
1219            .column_definitions([ColumnDefinition::new(GridLength::AUTO); 4])
1220            .children(cells);
1221        // `RootGrid`.
1222        let constraints = if vertical {
1223            BoxConstraints::new()
1224                .min_width(resources.color_picker_vertical_orientation_min_width)
1225                .max_width(resources.color_picker_vertical_orientation_max_width)
1226        } else {
1227            BoxConstraints::new()
1228                .min_height(resources.color_picker_vertical_orientation_min_height)
1229                .max_height(resources.color_picker_vertical_orientation_max_height)
1230                .max_width(10000.0)
1231        };
1232        let root = ConstrainedBox::new(constraints).child(Margin::new([0.0, 4.0, 0.0, 4.0], grid));
1233        let policy = app
1234            .get(self)
1235            .traversal_policy
1236            .clone()
1237            .expect("an initialized ColorPicker");
1238        FocusTraversalGroup::new(root)
1239            .policy(policy.erase())
1240            .into_widget()
1241    }
1242}
1243
1244/// XAML alignment of an element sized to its content: `alignment` within its slot.
1245#[cfg_attr(debug_assertions, track_caller)]
1246fn aligned<K>(alignment: AlignmentGeometry, child: impl IntoWidget<K>) -> WidgetRef {
1247    Align::new()
1248        .alignment(alignment)
1249        .width_factor(1.0)
1250        .height_factor(1.0)
1251        .child(child)
1252        .into_widget()
1253}
1254
1255/// The template's `TabIndex` of an element, `document_index` its place among the elements
1256/// without one, as a focus order: `TabIndex` first, then the order in the template.
1257#[cfg_attr(debug_assertions, track_caller)]
1258fn tab_order<K>(tab_index: i32, document_index: usize, child: impl IntoWidget<K>) -> WidgetRef {
1259    let order = f64::from(tab_index) * 64.0 + document_index as f64;
1260    FocusTraversalOrder::new(Rc::new(NumericFocusOrder::new(order)), child).into_widget()
1261}
1262
1263impl ColorPickerState {
1264    /// `ColorSpectrumGrid` (columns *, Auto): the spectrum and the preview.
1265    fn color_spectrum_grid(
1266        self: Handle<Self>,
1267        app: &App,
1268        resources: &ThemeResources,
1269        states: VisualStates,
1270    ) -> WidgetRef {
1271        let mut cells = Vec::new();
1272        if states.color_spectrum_visible {
1273            cells.push(GridCell::new(self.color_spectrum(resources, app)).into_widget());
1274        }
1275        if states.color_preview_visible {
1276            let vertical = states.orientation == Axis::Vertical;
1277            let preview = self.color_preview_rectangle_grid(app, resources, states);
1278            let cell = if states.color_spectrum_visible {
1279                // 44 wide, after the spectrum.
1280                let margin = if vertical {
1281                    [12.0, 0.0, 0.0, 0.0]
1282                } else {
1283                    [12.0, 0.0, 16.0, 0.0]
1284                };
1285                GridCell::new(Margin::new(
1286                    margin,
1287                    SizedBox::new().width(PREVIEW_SIZE).child(preview),
1288                ))
1289                .column(1)
1290            } else {
1291                // `ColorSpectrumCollapsed`: 44 tall, across both columns.
1292                GridCell::new(SizedBox::new().height(PREVIEW_SIZE).child(preview)).column_span(2)
1293            };
1294            cells.push(cell.into_widget());
1295        }
1296        Grid::new()
1297            .column_definitions([
1298                ColumnDefinition::new(GridLength::STAR),
1299                ColumnDefinition::new(GridLength::AUTO),
1300            ])
1301            .children(cells)
1302            .into_widget()
1303    }
1304
1305    /// `ColorSpectrum`: 256 to 336 square, its height following its width.
1306    fn color_spectrum(self: Handle<Self>, r: &ThemeResources, app: &App) -> WidgetRef {
1307        let widget = self.widget(app);
1308        let height = app
1309            .get(self)
1310            .spectrum_height
1311            .map(|height| height.clamp(SPECTRUM_MIN_SIZE, SPECTRUM_MAX_SIZE));
1312        let constraints = BoxConstraints::new()
1313            .min_width(SPECTRUM_MIN_SIZE)
1314            .max_width(SPECTRUM_MAX_SIZE)
1315            .min_height(height.unwrap_or(SPECTRUM_MIN_SIZE))
1316            .max_height(height.unwrap_or(SPECTRUM_MAX_SIZE));
1317        let spectrum = ColorSpectrum::new(app.get(self).spectrum_hsv, move |app, args| {
1318            self.spectrum_color_changed(app, args)
1319        })
1320        .min_hue(widget.min_hue)
1321        .max_hue(widget.max_hue)
1322        .min_saturation(widget.min_saturation)
1323        .max_saturation(widget.max_saturation)
1324        .min_value(widget.min_value)
1325        .max_value(widget.max_value)
1326        .shape(widget.color_spectrum_shape)
1327        .components(widget.color_spectrum_components)
1328        .corner_radius(widget.corner_radius.unwrap_or(r.control_corner_radius[0]))
1329        .is_enabled(widget.is_enabled);
1330        tab_order(
1331            0,
1332            0,
1333            SizeObserver::new(
1334                ConstrainedBox::new(constraints).child(spectrum),
1335                Rc::new(move |app, previous, size| self.spectrum_size_changed(app, previous, size)),
1336            ),
1337        )
1338    }
1339
1340    /// `ColorPreviewRectangleGrid` (two rows, two columns): the checkered background,
1341    /// `ColorPreviewRectangle`, `PreviousColorRectangle` and `BorderRectangle`.
1342    fn color_preview_rectangle_grid(
1343        self: Handle<Self>,
1344        app: &App,
1345        resources: &ThemeResources,
1346        states: VisualStates,
1347    ) -> WidgetRef {
1348        let state = app.get(self);
1349        let radius = self
1350            .widget(app)
1351            .corner_radius
1352            .unwrap_or(resources.control_corner_radius[0]);
1353        let rectangle = |fill: Option<ShapeFill>, stroke: Option<Color>| {
1354            CustomPaint::new()
1355                .painter(RectanglePainter::new(fill, stroke, radius))
1356                .into_widget()
1357        };
1358        let mut cells = vec![
1359            GridCell::new(rectangle(
1360                state.preview_checkers.clone().map(ShapeFill::Image),
1361                None,
1362            ))
1363            .row_span(2)
1364            .column_span(2)
1365            .into_widget(),
1366        ];
1367        // `ColorPreviewRectangle`, a half when the previous colour shows.
1368        let preview = GridCell::new(rectangle(Some(ShapeFill::Solid(state.color)), None));
1369        let preview = match states.previous_color {
1370            PreviousColorVisibility::PreviousColorVisibleVertical => {
1371                preview.row_span(1).column_span(2)
1372            }
1373            PreviousColorVisibility::PreviousColorVisibleHorizontal => {
1374                preview.row_span(2).column_span(1)
1375            }
1376            _ => preview.row_span(2).column_span(2),
1377        };
1378        cells.push(preview.into_widget());
1379        if let Some(previous) = self.widget(app).previous_color {
1380            let previous_cell = GridCell::new(rectangle(Some(ShapeFill::Solid(previous)), None));
1381            let previous_cell = match states.previous_color {
1382                PreviousColorVisibility::PreviousColorVisibleVertical => {
1383                    previous_cell.row(1).column_span(2)
1384                }
1385                _ => previous_cell.row(0).column(1).row_span(2),
1386            };
1387            cells.push(previous_cell.into_widget());
1388        }
1389        cells.push(
1390            GridCell::new(rectangle(None, Some(resources.color_picker_border_brush)))
1391                .row_span(2)
1392                .column_span(2)
1393                .into_widget(),
1394        );
1395        SizeObserver::new(
1396            Grid::new()
1397                .row_definitions([RowDefinition::new(GridLength::STAR); 2])
1398                .column_definitions([ColumnDefinition::new(GridLength::STAR); 2])
1399                .children(cells),
1400            Rc::new(move |app, _, size| self.preview_size_changed(app, size)),
1401        )
1402        .into_widget()
1403    }
1404
1405    /// `ThirdDimensionSliderGrid`: `ThirdDimensionBackgroundRectangle` under
1406    /// `ThirdDimensionSlider`.
1407    fn third_dimension_slider_grid(
1408        self: Handle<Self>,
1409        app: &App,
1410        _resources: &ThemeResources,
1411        states: VisualStates,
1412    ) -> WidgetRef {
1413        let widget = self.widget(app).clone();
1414        let vertical_slider = states.orientation == Axis::Horizontal;
1415        let (minimum, maximum) = widget.third_dimension_range();
1416        let background = CustomPaint::new()
1417            .painter(
1418                RectanglePainter::new(
1419                    Some(ShapeFill::Gradient {
1420                        stops: self.third_dimension_gradient(app),
1421                        rotated: vertical_slider,
1422                    }),
1423                    None,
1424                    _resources.color_picker_slider_corner_radius[0],
1425                )
1426                .slider_background(vertical_slider),
1427            )
1428            .size(slider_background_size(vertical_slider));
1429        let slider =
1430            ColorPickerSlider::new(app.get(self).third_dimension_value, move |app, value| {
1431                self.third_dimension_slider_changed(app, value)
1432            })
1433            .minimum(f64::from(minimum))
1434            .maximum(f64::from(maximum))
1435            .color_channel(widget.third_dimension_channel())
1436            .orientation(slider_orientation(vertical_slider))
1437            .is_thumb_tool_tip_enabled(false)
1438            .is_enabled(widget.is_enabled);
1439        Grid::new()
1440            .children([
1441                GridCell::new(background).into_widget(),
1442                GridCell::new(tab_order(1, 0, slider)).into_widget(),
1443            ])
1444            .into_widget()
1445    }
1446
1447    /// The stops of `ThirdDimensionSliderGradientBrush`: the colour from the range's minimum to
1448    /// its maximum of the third component, at full value for saturation; for hue, the hues of
1449    /// the range's ends and the primary hues between them.
1450    fn third_dimension_gradient(self: Handle<Self>, app: &App) -> Vec<(f64, Color)> {
1451        let widget = self.widget(app);
1452        let hsv = app.get(self).current_hsv;
1453        let stop = |offset: f64, hsv: Hsv| (offset, color_from_rgba(hsv_to_rgb(hsv), 1.0));
1454        match widget.third_dimension_channel() {
1455            ColorPickerHsvChannel::Saturation => {
1456                let min = widget.min_saturation;
1457                let max = widget.max_saturation.max(min);
1458                vec![
1459                    stop(0.0, Hsv::new(hsv.h, f64::from(min) / 100.0, 1.0)),
1460                    stop(1.0, Hsv::new(hsv.h, f64::from(max) / 100.0, 1.0)),
1461                ]
1462            }
1463            ColorPickerHsvChannel::Hue => {
1464                let min = widget.min_hue;
1465                let max = widget.max_hue.max(min);
1466                let (min_offset, max_offset) = (f64::from(min) / 359.0, f64::from(max) / 359.0);
1467                let mut stops = vec![stop(0.0, Hsv::new(f64::from(min), 1.0, 1.0))];
1468                for sextant in 1..=5 {
1469                    let offset = f64::from(sextant) / 6.0;
1470                    if min_offset < offset && max_offset > offset {
1471                        stops.push(stop(
1472                            (offset - min_offset) / (max_offset - min_offset),
1473                            Hsv::new(60.0 * f64::from(sextant), 1.0, 1.0),
1474                        ));
1475                    }
1476                }
1477                stops.push(stop(1.0, Hsv::new(f64::from(max), 1.0, 1.0)));
1478                stops
1479            }
1480            _ => {
1481                let min = widget.min_value;
1482                let max = widget.max_value.max(min);
1483                vec![
1484                    stop(0.0, Hsv::new(hsv.h, hsv.s, f64::from(min) / 100.0)),
1485                    stop(1.0, Hsv::new(hsv.h, hsv.s, f64::from(max) / 100.0)),
1486                ]
1487            }
1488        }
1489    }
1490
1491    /// `AlphaSliderGrid`: `AlphaSliderCheckeredBackgroundRectangle` and
1492    /// `AlphaSliderBackgroundRectangle`, the colour from transparent to opaque, under
1493    /// `AlphaSlider`.
1494    fn alpha_slider_grid(
1495        self: Handle<Self>,
1496        app: &App,
1497        _resources: &ThemeResources,
1498        states: VisualStates,
1499    ) -> WidgetRef {
1500        let widget = self.widget(app).clone();
1501        let state = app.get(self);
1502        let vertical_slider = states.orientation == Axis::Horizontal;
1503        let size = slider_background_size(vertical_slider);
1504        let checkers = CustomPaint::new()
1505            .painter(
1506                RectanglePainter::new(
1507                    state.alpha_checkers.clone().map(ShapeFill::Image),
1508                    None,
1509                    widget
1510                        .corner_radius
1511                        .unwrap_or(_resources.control_corner_radius[0]),
1512                )
1513                .slider_background(vertical_slider),
1514            )
1515            .size(size);
1516        let color = color_from_rgba(hsv_to_rgb(state.current_hsv), 1.0);
1517        let gradient = CustomPaint::new()
1518            .painter(
1519                RectanglePainter::new(
1520                    Some(ShapeFill::Gradient {
1521                        stops: vec![(0.0, color.with_alpha(0)), (1.0, color)],
1522                        rotated: vertical_slider,
1523                    }),
1524                    None,
1525                    _resources.color_picker_slider_corner_radius[0],
1526                )
1527                .slider_background(vertical_slider),
1528            )
1529            .size(size);
1530        let gradient = SizeObserver::new(
1531            gradient,
1532            Rc::new(move |app, _, size| self.alpha_background_size_changed(app, size)),
1533        );
1534        let slider = ColorPickerSlider::new(state.alpha_slider_value, move |app, value| {
1535            self.alpha_slider_changed(app, value)
1536        })
1537        .minimum(0.0)
1538        .maximum(100.0)
1539        .color_channel(ColorPickerHsvChannel::Alpha)
1540        .orientation(slider_orientation(vertical_slider))
1541        .is_thumb_tool_tip_enabled(false)
1542        .is_enabled(widget.is_enabled);
1543        Grid::new()
1544            .children([
1545                GridCell::new(checkers).into_widget(),
1546                GridCell::new(gradient).into_widget(),
1547                GridCell::new(tab_order(2, 0, slider)).into_widget(),
1548            ])
1549            .into_widget()
1550    }
1551
1552    /// `MoreEntriesPanel`, a vertical `StackPanel`: `MoreButton` at the right over
1553    /// `TextEntryGrid`.
1554    fn more_entries_panel(
1555        self: Handle<Self>,
1556        app: &App,
1557        resources: &ThemeResources,
1558        states: VisualStates,
1559    ) -> WidgetRef {
1560        let mut cells = Vec::new();
1561        if states.more_button_visible {
1562            cells.push(
1563                GridCell::new(aligned(
1564                    AlignmentGeometry::TOP_RIGHT,
1565                    tab_order(3, 0, self.more_button(app, states)),
1566                ))
1567                .into_widget(),
1568            );
1569        }
1570        if states.text_entry_grid_visible {
1571            cells.push(
1572                GridCell::new(self.text_entry_grid(app, resources, states))
1573                    .row(cells.len())
1574                    .into_widget(),
1575            );
1576        }
1577        stack_panel(cells)
1578    }
1579
1580    /// `MoreButton`: a toggle button without fill or border, its label and chevron at the
1581    /// right, the chevron up while the entries show.
1582    fn more_button(self: Handle<Self>, app: &App, states: VisualStates) -> WidgetRef {
1583        let opened = app.get(self).text_entry_grid_opened;
1584        let label = if opened { "Less" } else { "More" };
1585        let glyph = if states.text_entry_grid_visible {
1586            FluentSymbol::ChevronUp
1587        } else {
1588            FluentSymbol::ChevronDown
1589        };
1590        let content = Margin::new(
1591            [0.0, 5.0, 0.0, 7.0],
1592            Row::new()
1593                .main_axis_size(MainAxisSize::Min)
1594                .cross_axis_alignment(CrossAxisAlignment::Center)
1595                .children([
1596                    // `MoreButtonLabel`.
1597                    Text::new(label).into_widget(),
1598                    // `MoreGlyph`.
1599                    Margin::new(
1600                        [8.0, 0.0, 0.0, 0.0],
1601                        FontIcon::symbol(glyph).font_size(MORE_GLYPH_FONT_SIZE),
1602                    )
1603                    .into_widget(),
1604                ]),
1605        );
1606        let button = ToggleButton::new(Some(opened), move |app, checked| {
1607            self.more_button_checked(app, checked == Some(true))
1608        })
1609        .content(content)
1610        .is_enabled(self.widget(app).is_enabled)
1611        .template(|app, context, is_checked, content, states| {
1612            let resources = ThemeResources::of(app, context);
1613            toggle_button_presenter(
1614                &resources,
1615                more_button_brushes(&resources, is_checked == Some(true), states.common),
1616                ToggleButtonSetters {
1617                    padding: Some([0.0; 4]),
1618                    horizontal_content_alignment: AlignmentGeometry::CENTER_RIGHT,
1619                },
1620                content.unwrap_or_else(|| SizedBox::shrink().into_widget()),
1621                states,
1622            )
1623        });
1624        ConstrainedBox::new(
1625            BoxConstraints::new()
1626                .min_width(MORE_BUTTON_MIN_WIDTH)
1627                .min_height(MORE_BUTTON_MIN_HEIGHT),
1628        )
1629        .child(button)
1630        .into_widget()
1631    }
1632
1633    /// `TextEntryGrid` (columns *, 5, *; three Auto rows): `ColorRepresentationComboBox`,
1634    /// `HexTextBox`, and `ColorTextInputPanels` below them.
1635    fn text_entry_grid(
1636        self: Handle<Self>,
1637        app: &App,
1638        resources: &ThemeResources,
1639        states: VisualStates,
1640    ) -> WidgetRef {
1641        let vertical = states.orientation == Axis::Vertical;
1642        let mut cells = Vec::new();
1643        if states.color_channel_text_input_visible {
1644            // `ColorRepresentationComboBox`: `ComboBox` is left-aligned by its style.
1645            let index = app.get(self).color_representation;
1646            let combo_box = ComboBox::new(
1647                vec![
1648                    ComboBoxItem::text("rgb", "RGB"),
1649                    ComboBoxItem::text("hsv", "HSV"),
1650                ],
1651                Some(index),
1652                move |app, args| self.color_representation_changed(app, args.selected_index()),
1653            )
1654            .is_enabled(self.widget(app).is_enabled);
1655            cells.push(
1656                GridCell::new(aligned(
1657                    AlignmentGeometry::TOP_LEFT,
1658                    tab_order(4, 0, SizedBox::new().width(TEXT_BOX_WIDTH).child(combo_box)),
1659                ))
1660                .row(if vertical { 0 } else { 1 })
1661                .into_widget(),
1662            );
1663        }
1664        // `ColorTextInputPanels`.
1665        cells.push(
1666            GridCell::new(self.color_text_input_panels(app, resources, states))
1667                .row(if vertical { 1 } else { 2 })
1668                .column_span(3)
1669                .into_widget(),
1670        );
1671        if states.hex_input_visible {
1672            // `HexTextBox`: at the right of column 2; at the left of column 0 without the
1673            // channel entries (`ColorChannelTextInputCollapsed`); and in the `Horizontal`
1674            // orientation 120 wide, at the left above the entries, across the columns.
1675            let cell = if !vertical {
1676                GridCell::new(Margin::new(
1677                    [0.0, 0.0, 0.0, 12.0],
1678                    self.hex_text_box(app, states, TEXT_BOX_WIDTH, AlignmentGeometry::TOP_LEFT),
1679                ))
1680                .column_span(3)
1681            } else if states.color_channel_text_input_visible {
1682                GridCell::new(self.hex_text_box(
1683                    app,
1684                    states,
1685                    HEX_TEXT_BOX_WIDTH,
1686                    AlignmentGeometry::TOP_RIGHT,
1687                ))
1688                .column(2)
1689            } else {
1690                GridCell::new(self.hex_text_box(
1691                    app,
1692                    states,
1693                    HEX_TEXT_BOX_WIDTH,
1694                    AlignmentGeometry::TOP_LEFT,
1695                ))
1696            };
1697            cells.push(cell.into_widget());
1698        }
1699        Grid::new()
1700            .column_definitions([
1701                ColumnDefinition::new(GridLength::STAR),
1702                ColumnDefinition::new(GridLength::pixel(5.0)),
1703                ColumnDefinition::new(GridLength::STAR),
1704            ])
1705            .row_definitions([RowDefinition::new(GridLength::AUTO); 3])
1706            .children(cells)
1707            .into_widget()
1708    }
1709
1710    /// `HexTextBox`, `width` wide at `alignment`; 9 characters long with alpha enabled.
1711    fn hex_text_box(
1712        self: Handle<Self>,
1713        app: &App,
1714        states: VisualStates,
1715        width: f64,
1716        alignment: AlignmentGeometry,
1717    ) -> WidgetRef {
1718        let max_length = HEX_MAX_LENGTH[usize::from(states.alpha_enabled)];
1719        let tab_index = if states.orientation == Axis::Vertical {
1720            DEFAULT_TAB_INDEX
1721        } else {
1722            3
1723        };
1724        aligned(
1725            alignment,
1726            tab_order(
1727                tab_index,
1728                ChannelTextBox::Hex.index(),
1729                SizedBox::new().width(width).child(self.text_box(
1730                    app,
1731                    ChannelTextBox::Hex,
1732                    max_length,
1733                )),
1734            ),
1735        )
1736    }
1737
1738    /// The template's `TextBox` for `text_box`.
1739    fn text_box(
1740        self: Handle<Self>,
1741        app: &App,
1742        text_box: ChannelTextBox,
1743        max_length: i32,
1744    ) -> TextBox {
1745        let part = self.part(app, text_box);
1746        TextBox::new(part.controller.erase())
1747            .focus_node(part.focus.erase())
1748            .max_length(max_length)
1749            .is_enabled(self.widget(app).is_enabled)
1750            .text_changed(move |app, _| self.text_changed(app, text_box))
1751    }
1752
1753    /// `ColorTextInputPanels`, a vertical `StackPanel`: `ColorChannelTextInputPanel`, with
1754    /// `RgbPanel` or `HsvPanel`, and `AlphaPanel`.
1755    fn color_text_input_panels(
1756        self: Handle<Self>,
1757        app: &App,
1758        resources: &ThemeResources,
1759        states: VisualStates,
1760    ) -> WidgetRef {
1761        let mut cells = Vec::new();
1762        if states.color_channel_text_input_visible {
1763            let channels = match states.color_representation {
1764                ColorRepresentation::RgbSelected => [
1765                    ChannelTextBox::Red,
1766                    ChannelTextBox::Green,
1767                    ChannelTextBox::Blue,
1768                ],
1769                ColorRepresentation::HsvSelected => [
1770                    ChannelTextBox::Hue,
1771                    ChannelTextBox::Saturation,
1772                    ChannelTextBox::Value,
1773                ],
1774            };
1775            let rows = channels
1776                .iter()
1777                .enumerate()
1778                .flat_map(|(row, &text_box)| {
1779                    self.channel_row(app, resources, states, text_box, CHANNEL_MAX_LENGTH, row)
1780                })
1781                .collect::<Vec<_>>();
1782            cells.push(
1783                GridCell::new(channel_panel(
1784                    resources,
1785                    states,
1786                    [RowDefinition::new(GridLength::STAR); 3],
1787                    rows,
1788                ))
1789                .into_widget(),
1790            );
1791        }
1792        if states.alpha_text_input_visible {
1793            // `AlphaPanel`.
1794            let row = self.channel_row(
1795                app,
1796                resources,
1797                states,
1798                ChannelTextBox::Alpha,
1799                ALPHA_MAX_LENGTH,
1800                0,
1801            );
1802            cells.push(
1803                GridCell::new(Margin::new(
1804                    [0.0, 12.0, 0.0, 0.0],
1805                    channel_panel(
1806                        resources,
1807                        states,
1808                        [RowDefinition::new(GridLength::STAR)],
1809                        row,
1810                    ),
1811                ))
1812                .row(cells.len())
1813                .into_widget(),
1814            );
1815        }
1816        stack_panel(cells)
1817    }
1818
1819    /// One row of a channel panel: the text box, 120 wide, and its label, each 12 below the row
1820    /// above but for opacity, whose panel has that margin.
1821    fn channel_row(
1822        self: Handle<Self>,
1823        app: &App,
1824        resources: &ThemeResources,
1825        _states: VisualStates,
1826        text_box: ChannelTextBox,
1827        max_length: i32,
1828        row: usize,
1829    ) -> Vec<WidgetRef> {
1830        let margin = if text_box == ChannelTextBox::Alpha {
1831            [0.0; 4]
1832        } else {
1833            [0.0, 12.0, 0.0, 0.0]
1834        };
1835        let text = control_text_style(
1836            resources,
1837            resources.control_content_theme_font_size,
1838            FontWeight::NORMAL,
1839            resources.text_fill_color_primary,
1840        );
1841        vec![
1842            GridCell::new(Margin::new(
1843                margin,
1844                tab_order(
1845                    DEFAULT_TAB_INDEX,
1846                    text_box.index(),
1847                    SizedBox::new()
1848                        .width(TEXT_BOX_WIDTH)
1849                        .child(self.text_box(app, text_box, max_length)),
1850                ),
1851            ))
1852            .row(row)
1853            .into_widget(),
1854            GridCell::new(Margin::new(
1855                margin,
1856                aligned(
1857                    AlignmentGeometry::CENTER_LEFT,
1858                    DefaultTextStyle::new(text, Text::new(text_box.label())),
1859                ),
1860            ))
1861            .row(row)
1862            .column(2)
1863            .into_widget(),
1864        ]
1865    }
1866}
1867
1868/// `RgbPanel`, `HsvPanel` or `AlphaPanel`: columns Auto, 8 and the label column, which the
1869/// `Horizontal` orientation makes 122 wide.
1870fn channel_panel<const N: usize>(
1871    r: &ThemeResources,
1872    states: VisualStates,
1873    rows: [RowDefinition; N],
1874    children: Vec<WidgetRef>,
1875) -> WidgetRef {
1876    let label_column = if states.orientation == Axis::Vertical {
1877        GridLength::STAR
1878    } else {
1879        GridLength::pixel(r.color_picker_text_input_horizontal_orientation_margin)
1880    };
1881    Grid::new()
1882        .column_definitions([
1883            ColumnDefinition::new(GridLength::AUTO),
1884            ColumnDefinition::new(GridLength::pixel(8.0)),
1885            ColumnDefinition::new(label_column),
1886        ])
1887        .row_definitions(rows)
1888        .children(children)
1889        .into_widget()
1890}
1891
1892/// A vertical `StackPanel` of `cells`, one in each row: a grid of Auto rows in one star column,
1893/// which stretches each child across as the panel does.
1894fn stack_panel(cells: Vec<WidgetRef>) -> WidgetRef {
1895    let rows = cells.len();
1896    Grid::new()
1897        .row_definitions(vec![RowDefinition::new(GridLength::AUTO); rows])
1898        .children(cells)
1899        .into_widget()
1900}
1901
1902/// The orientation of the sliders: vertical in the picker's `Horizontal` orientation.
1903fn slider_orientation(vertical: bool) -> Axis {
1904    if vertical {
1905        Axis::Vertical
1906    } else {
1907        Axis::Horizontal
1908    }
1909}
1910
1911/// The size a slider background rectangle asks for: 12 across the slider.
1912fn slider_background_size(vertical: bool) -> Size {
1913    if vertical {
1914        Size::new(SLIDER_BACKGROUND_SIZE, 0.0)
1915    } else {
1916        Size::new(0.0, SLIDER_BACKGROUND_SIZE)
1917    }
1918}
1919
1920/// The `ToggleButton.Resources` of `MoreButton`: no fill or border in any state, and the
1921/// foreground `SystemBaseHighColor` at rest, `SystemBaseMediumColor` under the pointer and
1922/// `SystemBaseMediumLowColor` pressed or disabled, checked or not.
1923fn more_button_brushes(
1924    resources: &ThemeResources,
1925    is_checked: bool,
1926    state: CommonState,
1927) -> ToggleButtonBrushes {
1928    let r = &resources;
1929    let transparent = Color::from_argb(0, 0, 0, 0);
1930    let foreground = match state {
1931        CommonState::Normal => r.system_base_high_color,
1932        CommonState::PointerOver => r.system_base_medium_color,
1933        CommonState::Pressed | CommonState::Disabled => r.system_base_medium_low_color,
1934    };
1935    let base = crate::toggle_button_brushes(resources, Some(is_checked), state);
1936    ToggleButtonBrushes {
1937        background: transparent,
1938        border: Brush::Solid(transparent),
1939        foreground,
1940        background_sizing: base.background_sizing,
1941    }
1942}
1943
1944/// What a XAML `Rectangle` of the template is filled with.
1945#[derive(Clone, Debug, PartialEq)]
1946enum ShapeFill {
1947    /// `SolidColorBrush`.
1948    Solid(Color),
1949    /// `LinearGradientBrush` with its default `StartPoint` (0, 0) and `EndPoint` (1, 1) of the
1950    /// bounding box, `rotated` by 180 degrees (`RotateTransform Angle="180"`) for a vertical
1951    /// slider.
1952    Gradient {
1953        stops: Vec<(f64, Color)>,
1954        rotated: bool,
1955    },
1956    /// `ImageBrush`, stretched over the rectangle (`Stretch="Fill"`).
1957    Image(Image),
1958}
1959
1960/// A XAML `Rectangle` filling its cell, or 12 across a slider and centred: an optional `Fill`,
1961/// an optional `ColorPickerBorderStyle` stroke inside the bounds, and `RadiusX` and `RadiusY`.
1962#[derive(Clone, Debug, PartialEq)]
1963struct RectanglePainter {
1964    fill: Option<ShapeFill>,
1965    stroke: Option<Color>,
1966    radius: f64,
1967    /// `Some(vertical)` for a slider's background: 12 tall and centred (or 12 wide when
1968    /// vertical).
1969    slider_background: Option<bool>,
1970}
1971
1972impl RectanglePainter {
1973    fn new(fill: Option<ShapeFill>, stroke: Option<Color>, radius: f64) -> RectanglePainter {
1974        RectanglePainter {
1975            fill,
1976            stroke,
1977            radius,
1978            slider_background: None,
1979        }
1980    }
1981
1982    /// The rectangle is a slider's background, 12 across a slider that is `vertical` or not.
1983    fn slider_background(mut self, vertical: bool) -> RectanglePainter {
1984        self.slider_background = Some(vertical);
1985        self
1986    }
1987
1988    /// The rectangle's bounds in a cell of `size`.
1989    fn bounds(&self, size: Size) -> Rect {
1990        match self.slider_background {
1991            None => Rect::from_ltwh(0.0, 0.0, size.width(), size.height()),
1992            Some(false) => Rect::from_ltwh(
1993                0.0,
1994                (size.height() - SLIDER_BACKGROUND_SIZE) / 2.0,
1995                size.width(),
1996                SLIDER_BACKGROUND_SIZE,
1997            ),
1998            Some(true) => Rect::from_ltwh(
1999                (size.width() - SLIDER_BACKGROUND_SIZE) / 2.0,
2000                0.0,
2001                SLIDER_BACKGROUND_SIZE,
2002                size.height(),
2003            ),
2004        }
2005    }
2006
2007    /// The paint of `fill` over `bounds`.
2008    fn fill_paint(fill: &ShapeFill, bounds: Rect) -> Paint {
2009        match fill {
2010            ShapeFill::Solid(color) => Paint::from_color((*color).into()),
2011            ShapeFill::Gradient { stops, rotated } => {
2012                let (start, end) = if *rotated {
2013                    (bounds.bottom_right(), bounds.top_left())
2014                } else {
2015                    (bounds.top_left(), bounds.bottom_right())
2016                };
2017                Paint::from_shader(Shader::Linear {
2018                    start: Point::new(start.dx() as f32, start.dy() as f32),
2019                    end: Point::new(end.dx() as f32, end.dy() as f32),
2020                    stops: stops
2021                        .iter()
2022                        .map(|(offset, color)| GradientStop {
2023                            offset: *offset as f32,
2024                            color: (*color).into(),
2025                        })
2026                        .collect(),
2027                    spread: SpreadMode::Pad,
2028                    local: Matrix::IDENTITY,
2029                })
2030            }
2031            ShapeFill::Image(image) => {
2032                let [width, height] = image.size();
2033                let local = Matrix::from_affine(
2034                    (bounds.width() / f64::from(width)) as f32,
2035                    0.0,
2036                    0.0,
2037                    (bounds.height() / f64::from(height)) as f32,
2038                    bounds.left as f32,
2039                    bounds.top as f32,
2040                );
2041                Paint::from_shader(Shader::Image {
2042                    image: image.clone(),
2043                    sampling: Default::default(),
2044                    local,
2045                })
2046            }
2047        }
2048    }
2049}
2050
2051/// `CreateRoundedRect`'s limit: a radius is no more than half a side.
2052fn rectangle_radius(radius: f64, bounds: Rect) -> f32 {
2053    radius
2054        .abs()
2055        .min(bounds.width() / 2.0)
2056        .min(bounds.height() / 2.0) as f32
2057}
2058
2059impl CustomPainter for RectanglePainter {
2060    fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
2061        let bounds = self.bounds(size);
2062        if bounds.width() <= 0.0 || bounds.height() <= 0.0 {
2063            return;
2064        }
2065        // A stroked shape fills and strokes its outline inset by half the stroke.
2066        let outline = if self.stroke.is_some() {
2067            bounds.deflate(COLOR_PICKER_BORDER_THICKNESS / 2.0)
2068        } else {
2069            bounds
2070        };
2071        if let Some(fill) = &self.fill {
2072            let paint = RectanglePainter::fill_paint(fill, outline);
2073            canvas.draw_rrect(outline, rectangle_radius(self.radius, outline), &paint);
2074        }
2075        if let Some(stroke) = self.stroke {
2076            let mut paint = Paint::from_color(stroke.into());
2077            paint.style = PaintStyle::Stroke(Stroke::new(COLOR_PICKER_BORDER_THICKNESS as f32));
2078            canvas.draw_rrect(outline, rectangle_radius(self.radius, outline), &paint);
2079        }
2080    }
2081
2082    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
2083        old_delegate.as_any().downcast_ref::<Self>() != Some(self)
2084    }
2085
2086    fn as_any(&self) -> &dyn std::any::Any {
2087        self
2088    }
2089}