Skip to main content

waft_winui/controls/
color_spectrum.rs

1//! ColorSpectrum.xaml, ColorSpectrum.cpp and SpectrumBrush.cpp: a square or circle of colours
2//! spanning two HSV components, with a selection ellipse on the selected colour.
3//!
4//! Template, back to front: `LayoutRoot` (a `Grid` filling the control) centres `SizingGrid`, a
5//! square as wide as the smaller side of `LayoutRoot`, clipped to that square. It holds
6//! `SpectrumRectangle` or `SpectrumEllipse` (by `ShapeSelected`), filled with the spectrum
7//! images, and their `SpectrumOverlayRectangle` and `SpectrumOverlayEllipse`, which the source
8//! never fills; `InputTarget`, a transparent canvas that takes the pointer and holds
9//! `SelectionEllipsePanel` (16 square, 48 in `PressedLarge`) centred on the selected colour, with
10//! `FocusEllipse` (2 larger on every side, shown in `Focused`) and `SelectionEllipse`, which owns
11//! `ColorNameToolTip`; and `RectangleBorder` or `EllipseBorder`, stroked with
12//! `ColorPickerBorderBrush`.
13//!
14//! The images (`CreateBitmapsAndColorMap`) are made when the control's size, `Shape`,
15//! `Components` or the range of a component it lays out changes: two images, at the minimum and
16//! maximum of the third component, or six, at the six primary hues when hue is the third. The
17//! spectrum shows the two the third component lies between, the second over the first at the
18//! opacity of how far between (`SpectrumBrush`'s cross-fade).
19//!
20//! The application owns the colour: `hsv_color` is what it passes, and `color_changed` asks for
21//! another. The colour the spectrum asks for is what it reads as its own until the application
22//! next builds it; if the application passed another by then, the spectrum shows that one.
23
24use crate::{
25    ColorPickerHsvChannel, ColorSpectrumComponents, ColorSpectrumShape, FocusState, Hsv,
26    IncrementAmount, IncrementDirection, InputDevice, SizeObserver, ThemeResources, ToolTip,
27    ToolTipService, argb, color_display_name, color_from_rgba, hsv_to_rgb, image_from_pixel_data,
28    increment_color_channel, rgb_from_color, rgb_to_hsv, same_color,
29};
30use std::{any::TypeId, f64::consts::PI, fmt, rc::Rc};
31use waft_embedder::valo::{Matrix, Paint, PaintStyle, Shader, Stroke};
32use waft_embedder::{Canvas, Color, Image, Offset, PointerDeviceKind, Rect, Size};
33use waft_foundation::{App, Handle, Listenable, Listener, OptionRetained, Ref};
34use waft_gestures::{EagerGestureRecognizer, PointerDownEvent};
35use waft_painting::draw_oval;
36use waft_rendering::{CustomPainter, HitTestBehavior};
37use waft_services::{HardwareKeyboard, KeyEvent, LogicalKeyboardKey};
38use waft_widgets::Listener as PointerListener;
39use waft_widgets::*;
40
41/// XAML `Vector4` of `ColorSpectrum.HsvColor`: hue from 0 to 360, and saturation, value and
42/// alpha from 0 to 1, as `x`, `y`, `z` and `w`.
43#[derive(Clone, Copy, Debug, PartialEq)]
44pub struct HsvColor {
45    /// `x`: the hue in degrees.
46    pub hue: f32,
47    /// `y`.
48    pub saturation: f32,
49    /// `z`.
50    pub value: f32,
51    /// `w`.
52    pub alpha: f32,
53}
54
55impl HsvColor {
56    /// `HsvColor`'s default, `{ 0, 0, 1, 1 }`: white.
57    pub const WHITE: HsvColor = HsvColor {
58        hue: 0.0,
59        saturation: 0.0,
60        value: 1.0,
61        alpha: 1.0,
62    };
63
64    /// The `HsvColor` of `color`, as `OnColorChanged` sets it when `Color` is set.
65    pub fn from_color(color: Color) -> HsvColor {
66        let hsv = rgb_to_hsv(rgb_from_color(color));
67        HsvColor {
68            hue: hsv.h as f32,
69            saturation: hsv.s as f32,
70            value: hsv.v as f32,
71            alpha: (f64::from(argb(color).a) / 255.0) as f32,
72        }
73    }
74
75    /// The `Color` of this colour, as `SetColor` sets it when `HsvColor` is set.
76    pub fn to_color(self) -> Color {
77        color_from_rgba(hsv_to_rgb(self.hsv()), f64::from(self.alpha))
78    }
79
80    /// Hue, saturation and value as `Hsv`.
81    pub(crate) fn hsv(self) -> Hsv {
82        Hsv::new(
83            f64::from(self.hue),
84            f64::from(self.saturation),
85            f64::from(self.value),
86        )
87    }
88
89    /// `hsv` with `alpha`.
90    pub(crate) fn from_hsv(hsv: Hsv, alpha: f32) -> HsvColor {
91        HsvColor {
92            hue: hsv.h as f32,
93            saturation: hsv.s as f32,
94            value: hsv.v as f32,
95            alpha,
96        }
97    }
98}
99
100impl Default for HsvColor {
101    fn default() -> Self {
102        HsvColor::WHITE
103    }
104}
105
106/// XAML `ColorChangedEventArgs` of `ColorSpectrum.ColorChanged`, with the `HsvColor` the
107/// spectrum asks for.
108#[derive(Clone, Copy, Debug, PartialEq)]
109pub struct ColorSpectrumColorChangedEventArgs {
110    /// `OldColor`.
111    pub old_color: Color,
112    /// `NewColor`.
113    pub new_color: Color,
114    /// `HsvColor` after the change, which the application stores and passes back.
115    pub hsv_color: HsvColor,
116}
117
118/// Receives XAML `ColorSpectrum.ColorChanged`.
119pub type ColorSpectrumColorChangedHandler =
120    Rc<dyn Fn(&mut App, ColorSpectrumColorChangedEventArgs)>;
121
122/// The `CommonStates` default `Width` and `Height` of `SelectionEllipsePanel`.
123pub const SELECTION_ELLIPSE_SIZE: f64 = 16.0;
124/// `SelectionEllipsePanel`'s `Width` and `Height` in `PressedLarge`.
125pub const SELECTION_ELLIPSE_LARGE_SIZE: f64 = 48.0;
126/// `FocusEllipse`'s `Margin="-2"` outside the panel.
127const FOCUS_ELLIPSE_OUTSET: f64 = 2.0;
128/// `StrokeThickness` of `FocusEllipse` and `SelectionEllipse`.
129const ELLIPSE_STROKE_THICKNESS: f64 = 2.0;
130/// `ColorPickerBorderStyle`'s `StrokeThickness`, of `RectangleBorder` and `EllipseBorder`.
131pub const COLOR_PICKER_BORDER_THICKNESS: f64 = 2.0;
132/// `SelectionEllipse`'s `Opacity` in `PointerOver`.
133const POINTER_OVER_SELECTION_OPACITY: f64 = 0.8;
134/// `ColorNameToolTip`'s `VerticalOffset`.
135const COLOR_NAME_TOOL_TIP_OFFSET: f64 = 20.0;
136
137/// XAML `ColorSpectrum` with the template of `ColorSpectrum.xaml`.
138#[derive(Clone)]
139pub struct ColorSpectrum {
140    /// `HsvColor`: the selected colour; `Color` is `HsvColor::to_color` of it.
141    pub hsv_color: HsvColor,
142
143    /// `ColorChanged`: asks the application for another `HsvColor`; the application owns
144    /// `hsv_color`.
145    pub color_changed: ColorSpectrumColorChangedHandler,
146
147    /// `MinHue`, from 0 to 359; 0 by default.
148    pub min_hue: i32,
149    /// `MaxHue`, from 0 to 359; 359 by default.
150    pub max_hue: i32,
151    /// `MinSaturation`, from 0 to 100; 0 by default.
152    pub min_saturation: i32,
153    /// `MaxSaturation`, from 0 to 100; 100 by default.
154    pub max_saturation: i32,
155    /// `MinValue`, from 0 to 100; 0 by default.
156    pub min_value: i32,
157    /// `MaxValue`, from 0 to 100; 100 by default.
158    pub max_value: i32,
159
160    /// `Shape`.
161    pub shape: ColorSpectrumShape,
162
163    /// `Components`.
164    pub components: ColorSpectrumComponents,
165
166    /// `CornerRadius` of the box: its top left is the rectangles' `RadiusX`, its bottom right
167    /// their `RadiusY`, the same here; 0 by default, as the style sets none.
168    pub corner_radius: f64,
169
170    /// `IsEnabled`.
171    pub is_enabled: bool,
172
173    /// Identity retained across parent rebuilds.
174    pub key: Option<KeyRef>,
175}
176
177/// Panics unless `value` is within `0..=max`, as the source throws for the property `name`.
178fn assert_range(name: &str, value: i32, max: i32) {
179    assert!(
180        (0..=max).contains(&value),
181        "{name} must be between 0 and {max}."
182    );
183}
184
185impl ColorSpectrum {
186    /// Creates a spectrum selecting `hsv_color`, which asks for others through `color_changed`.
187    pub fn new(
188        hsv_color: HsvColor,
189        color_changed: impl Fn(&mut App, ColorSpectrumColorChangedEventArgs) + 'static,
190    ) -> ColorSpectrum {
191        ColorSpectrum {
192            hsv_color,
193            color_changed: Rc::new(color_changed),
194            min_hue: 0,
195            max_hue: 359,
196            min_saturation: 0,
197            max_saturation: 100,
198            min_value: 0,
199            max_value: 100,
200            shape: ColorSpectrumShape::Box,
201            components: ColorSpectrumComponents::HueSaturation,
202            corner_radius: 0.0,
203            is_enabled: true,
204            key: None,
205        }
206    }
207
208    /// Sets MinHue.
209    pub fn min_hue(mut self, value: i32) -> Self {
210        assert_range("MinHue", value, 359);
211        self.min_hue = value;
212        self
213    }
214
215    /// Sets MaxHue.
216    pub fn max_hue(mut self, value: i32) -> Self {
217        assert_range("MaxHue", value, 359);
218        self.max_hue = value;
219        self
220    }
221
222    /// Sets MinSaturation.
223    pub fn min_saturation(mut self, value: i32) -> Self {
224        assert_range("MinSaturation", value, 100);
225        self.min_saturation = value;
226        self
227    }
228
229    /// Sets MaxSaturation.
230    pub fn max_saturation(mut self, value: i32) -> Self {
231        assert_range("MaxSaturation", value, 100);
232        self.max_saturation = value;
233        self
234    }
235
236    /// Sets MinValue.
237    pub fn min_value(mut self, value: i32) -> Self {
238        assert_range("MinValue", value, 100);
239        self.min_value = value;
240        self
241    }
242
243    /// Sets MaxValue.
244    pub fn max_value(mut self, value: i32) -> Self {
245        assert_range("MaxValue", value, 100);
246        self.max_value = value;
247        self
248    }
249
250    /// Sets Shape.
251    pub fn shape(mut self, value: ColorSpectrumShape) -> Self {
252        self.shape = value;
253        self
254    }
255
256    /// Sets Components.
257    pub fn components(mut self, value: ColorSpectrumComponents) -> Self {
258        self.components = value;
259        self
260    }
261
262    /// Sets CornerRadius.
263    pub fn corner_radius(mut self, value: f64) -> Self {
264        self.corner_radius = value;
265        self
266    }
267
268    /// Sets IsEnabled.
269    pub fn is_enabled(mut self, value: bool) -> Self {
270        self.is_enabled = value;
271        self
272    }
273
274    /// Sets widget identity.
275    pub fn key(mut self, key: KeyRef) -> Self {
276        self.key = Some(key);
277        self
278    }
279
280    /// The component ranges, as `CreateBitmapsAndColorMap` reads them.
281    fn ranges(&self) -> Ranges {
282        Ranges {
283            min_hue: self.min_hue,
284            max_hue: self.max_hue,
285            min_saturation: self.min_saturation,
286            max_saturation: self.max_saturation,
287            min_value: self.min_value,
288            max_value: self.max_value,
289        }
290    }
291}
292
293impl fmt::Debug for ColorSpectrum {
294    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295        f.debug_struct("ColorSpectrum")
296            .field("hsv_color", &self.hsv_color)
297            .field("shape", &self.shape)
298            .field("components", &self.components)
299            .field("is_enabled", &self.is_enabled)
300            .finish_non_exhaustive()
301    }
302}
303
304/// `MinHue` to `MaxValue`.
305#[derive(Clone, Copy, Debug, PartialEq, Eq)]
306struct Ranges {
307    min_hue: i32,
308    max_hue: i32,
309    min_saturation: i32,
310    max_saturation: i32,
311    min_value: i32,
312    max_value: i32,
313}
314
315/// The images `CreateBitmapsAndColorMap` made, by the component they are for.
316#[derive(Clone, Debug, PartialEq)]
317enum SpectrumSurfaces {
318    /// `m_saturationMinimumSurface` and `m_saturationMaximumSurface`, for `HueValue` and
319    /// `ValueHue`.
320    Saturation {
321        minimum: Option<Image>,
322        maximum: Option<Image>,
323    },
324    /// `m_valueSurface`, for `HueSaturation` and `SaturationHue`: the maximum value only.
325    Value(Option<Image>),
326    /// `m_hueRedSurface` to `m_huePurpleSurface`, for `ValueSaturation` and `SaturationValue`.
327    Hue([Option<Image>; 6]),
328}
329
330/// What the last `CreateBitmapsAndColorMap` made, and the `*FromLastBitmapCreation` fields it
331/// made them for, which place the selection ellipse and map the pointer.
332struct BitmapCreation {
333    shape: ColorSpectrumShape,
334    components: ColorSpectrumComponents,
335    /// `m_imageWidthFromLastBitmapCreation` and `m_imageHeightFromLastBitmapCreation`, which are
336    /// equal.
337    size: f64,
338    ranges: Ranges,
339    /// `m_hsvValues`: the colour at each pixel, row by row.
340    hsv_values: Vec<Hsv>,
341    surfaces: SpectrumSurfaces,
342}
343
344/// `CommonStates` of the template.
345#[derive(Clone, Copy, Debug, PartialEq, Eq)]
346enum SpectrumCommonState {
347    Normal,
348    /// `SelectionEllipse` at 0.8 opacity.
349    PointerOver,
350    Pressed,
351    /// `SelectionEllipsePanel` 48 square, for a pen or touch.
352    PressedLarge,
353}
354
355/// `SelectionEllipseColor`: a white selection ellipse with a black focus ellipse over dark
356/// colours, and the reverse over light ones.
357#[derive(Clone, Copy, Debug, PartialEq, Eq)]
358#[allow(clippy::enum_variant_names, reason = "the template's state names")]
359enum SelectionEllipseColor {
360    SelectionEllipseLight,
361    SelectionEllipseDark,
362}
363
364/// `FocusStates`: `FocusEllipse` shows in `Focused`.
365#[derive(Clone, Copy, Debug, PartialEq, Eq)]
366enum SpectrumFocusState {
367    Unfocused,
368    Focused,
369    PointerFocused,
370}
371
372impl StatefulWidget for ColorSpectrum {
373    type State = ColorSpectrumState;
374
375    fn key(&self) -> Option<&KeyRef> {
376        self.key.as_ref()
377    }
378
379    fn create_state(&self) -> ColorSpectrumState {
380        let color = self.hsv_color.to_color();
381        ColorSpectrumState {
382            state: StateData::new(),
383            focus: None,
384            hsv_color: self.hsv_color,
385            old_color: Color::from_argb(255, 255, 255, 255),
386            color_name: color_display_name(color),
387            is_pointer_over: false,
388            is_pointer_pressed: false,
389            should_show_large_selection: false,
390            focused: false,
391            layout_root_size: Size::ZERO,
392            creation: None,
393        }
394    }
395}
396
397/// The spectrum's own state (`ColorSpectrum.h` members).
398pub struct ColorSpectrumState {
399    state: StateData<ColorSpectrum>,
400
401    /// The control's focus.
402    focus: Option<Ref<FocusNode>>,
403
404    /// `HsvColor` as the spectrum reads it: the colour it last asked for until the application
405    /// next builds it, else the application's.
406    hsv_color: HsvColor,
407
408    /// `m_oldColor`: `Color` before it last changed.
409    old_color: Color,
410
411    /// `ColorNameToolTip.Content`.
412    color_name: &'static str,
413
414    /// `m_isPointerOver`.
415    is_pointer_over: bool,
416
417    /// `m_isPointerPressed`.
418    is_pointer_pressed: bool,
419
420    /// `m_shouldShowLargeSelection`: the press is a pen's or a touch.
421    should_show_large_selection: bool,
422
423    /// Whether the control has the focus.
424    focused: bool,
425
426    /// `LayoutRoot`'s size after the last layout.
427    layout_root_size: Size,
428
429    /// The last `CreateBitmapsAndColorMap`.
430    creation: Option<BitmapCreation>,
431}
432
433impl ColorSpectrumState {
434    fn focus(self: Handle<Self>, app: &App) -> Handle<FocusNode> {
435        app.get(self)
436            .focus
437            .handle()
438            .expect("an initialized ColorSpectrum")
439    }
440
441    /// `Color`.
442    fn color(self: Handle<Self>, app: &App) -> Color {
443        app.get(self).hsv_color.to_color()
444    }
445
446    /// `HsvColor` and `Color` become `hsv_color`; `m_oldColor` keeps the colour before when it
447    /// changes. Then `RaiseColorChanged`'s test: when the colour changed, or a channel is 0
448    /// before and after, the name tooltip shows the new colour's name, and the arguments of
449    /// `ColorChanged` come back.
450    fn set_hsv_color(
451        self: Handle<Self>,
452        app: &mut App,
453        hsv_color: HsvColor,
454    ) -> Option<ColorSpectrumColorChangedEventArgs> {
455        let old = self.color(app);
456        let new = hsv_color.to_color();
457        let state = app.get_mut(self);
458        if !same_color(old, new) {
459            state.old_color = old;
460        }
461        state.hsv_color = hsv_color;
462        let old_color = state.old_color;
463        let changed = !same_color(old_color, new);
464        let (before, after) = (argb(old_color), argb(new));
465        let channel_zero_in_both = (before.r == after.r && after.r == 0)
466            || (before.g == after.g && after.g == 0)
467            || (before.b == after.b && after.b == 0);
468        if !(changed || channel_zero_in_both) {
469            return None;
470        }
471        state.color_name = color_display_name(new);
472        Some(ColorSpectrumColorChangedEventArgs {
473            old_color,
474            new_color: new,
475            hsv_color,
476        })
477    }
478
479    /// `UpdateColor`: the user chose `hsv`, with the current alpha, and `ColorChanged` asks the
480    /// application for it.
481    fn update_color(self: Handle<Self>, app: &mut App, hsv: Hsv) {
482        let alpha = app.get(self).hsv_color.alpha;
483        let args = self.set_hsv_color(app, HsvColor::from_hsv(hsv, alpha));
484        self.set_state(app, |_| {});
485        if let Some(args) = args {
486            let handler = self.widget(app).color_changed.clone();
487            handler(app, args);
488        }
489    }
490
491    /// `UpdateColorFromPoint`: the colour of the pixel under `point` of `InputTarget`, pulled into
492    /// the circle for a ring, with the current third component. Nothing happens before the images
493    /// are made.
494    fn update_color_from_point(self: Handle<Self>, app: &mut App, point: Offset) {
495        let shape = self.widget(app).shape;
496        let current = app.get(self).hsv_color;
497        let Some(creation) = &app.get(self).creation else {
498            return;
499        };
500        if creation.hsv_values.is_empty() {
501            return;
502        }
503        let size = creation.size;
504        let mut x_position = point.dx();
505        let mut y_position = point.dy();
506        let radius = size / 2.0;
507        let distance = ((x_position - radius).powi(2) + (y_position - radius).powi(2)).sqrt();
508        if distance > radius && shape == ColorSpectrumShape::Ring {
509            x_position = (radius / distance) * (x_position - radius) + radius;
510            y_position = (radius / distance) * (y_position - radius) + radius;
511        }
512        let width = size.round() as i64;
513        let clamp_index = |position: f64| {
514            let index = position.round() as i64;
515            if index < 0 {
516                0
517            } else if position.round() >= size {
518                width - 1
519            } else {
520                index
521            }
522        };
523        let (x, y) = (clamp_index(x_position), clamp_index(y_position));
524        let mut hsv = creation.hsv_values[(y * width + x) as usize];
525        // The images hold two components; the third stays where it is.
526        match self.widget(app).components {
527            ColorSpectrumComponents::HueValue | ColorSpectrumComponents::ValueHue => {
528                hsv.s = f64::from(current.saturation)
529            }
530            ColorSpectrumComponents::HueSaturation | ColorSpectrumComponents::SaturationHue => {
531                hsv.v = f64::from(current.value)
532            }
533            ColorSpectrumComponents::ValueSaturation | ColorSpectrumComponents::SaturationValue => {
534                hsv.h = f64::from(current.hue)
535            }
536        }
537        self.update_color(app, hsv);
538    }
539
540    /// `OnKeyDown`: the arrows step the component across (Left, Right) or down (Up, Down) the
541    /// spectrum by one, or with Ctrl to the next named colour, wrapping at the bounds. Each arrow
542    /// moves the selection its way: left and up lower hue but raise saturation and value, whose
543    /// axes run the other way, except across a `SaturationValue` spectrum.
544    fn key_down(self: Handle<Self>, app: &mut App, key: LogicalKeyboardKey) -> KeyEventResult {
545        let horizontal = match key {
546            LogicalKeyboardKey::ARROW_LEFT | LogicalKeyboardKey::ARROW_RIGHT => true,
547            LogicalKeyboardKey::ARROW_UP | LogicalKeyboardKey::ARROW_DOWN => false,
548            _ => return KeyEventResult::Ignored,
549        };
550        let widget = self.widget(app).clone();
551        let control_down = HardwareKeyboard::instance(app).is_control_pressed(app);
552        let channel = arrow_channel(widget.components, horizontal);
553        let is_saturation_value = widget.components == ColorSpectrumComponents::SaturationValue;
554        let (min_bound, max_bound) = match channel {
555            ColorPickerHsvChannel::Hue => (widget.min_hue, widget.max_hue),
556            ColorPickerHsvChannel::Saturation => (widget.min_saturation, widget.max_saturation),
557            _ => (widget.min_value, widget.max_value),
558        };
559        let lowers = if channel == ColorPickerHsvChannel::Hue {
560            matches!(
561                key,
562                LogicalKeyboardKey::ARROW_LEFT | LogicalKeyboardKey::ARROW_UP
563            )
564        } else {
565            matches!(
566                key,
567                LogicalKeyboardKey::ARROW_RIGHT | LogicalKeyboardKey::ARROW_DOWN
568            )
569        };
570        let mut direction = if lowers {
571            IncrementDirection::Lower
572        } else {
573            IncrementDirection::Higher
574        };
575        // A `SaturationValue` spectrum runs the other way across.
576        if is_saturation_value && horizontal {
577            direction = direction.reversed();
578        }
579        let amount = if control_down {
580            IncrementAmount::Large
581        } else {
582            IncrementAmount::Small
583        };
584        let hsv = app.get(self).hsv_color.hsv();
585        let new_hsv = increment_color_channel(
586            hsv,
587            channel,
588            direction,
589            amount,
590            true,
591            f64::from(min_bound),
592            f64::from(max_bound),
593        );
594        self.update_color(app, new_hsv);
595        KeyEventResult::Handled
596    }
597
598    /// `OnInputTargetPointerPressed`: the control takes the focus, the pointer is pressed (large
599    /// for a pen or touch) and the colour under it is chosen.
600    fn pointer_pressed(self: Handle<Self>, app: &mut App, event: &PointerDownEvent) {
601        let focus = self.focus(app);
602        FocusState::name(app, focus.as_node(), FocusState::Pointer);
603        focus.request_focus(app, None);
604        let large = matches!(
605            event.kind,
606            PointerDeviceKind::Touch
607                | PointerDeviceKind::Stylus
608                | PointerDeviceKind::InvertedStylus
609        );
610        self.set_state(app, |state| {
611            state.is_pointer_pressed = true;
612            state.should_show_large_selection = large;
613        });
614        self.update_color_from_point(app, event.local_position());
615    }
616
617    /// `OnInputTargetPointerMoved`: while pressed, the colour under the pointer is chosen.
618    fn pointer_moved(self: Handle<Self>, app: &mut App, point: Offset) {
619        if app.get(self).is_pointer_pressed {
620            self.update_color_from_point(app, point);
621        }
622    }
623
624    /// `OnInputTargetPointerReleased`.
625    fn pointer_released(self: Handle<Self>, app: &mut App) {
626        self.set_state(app, |state| {
627            state.is_pointer_pressed = false;
628            state.should_show_large_selection = false;
629        });
630    }
631
632    /// `OnInputTargetPointerEntered` and `OnInputTargetPointerExited`.
633    fn pointer_over(self: Handle<Self>, app: &mut App, over: bool) {
634        self.set_state(app, |state| state.is_pointer_over = over);
635    }
636
637    /// `OnGotFocus` and `OnLostFocus`: arriving focus opens the name tooltip; leaving closes it.
638    fn focus_changed(self: Handle<Self>, app: &mut App) {
639        let focused = self.focus(app).has_primary_focus(app);
640        if focused != app.get(self).focused {
641            self.set_state(app, |state| state.focused = focused);
642        }
643    }
644
645    /// `OnLayoutRootSizeChanged`.
646    fn layout_root_size_changed(self: Handle<Self>, app: &mut App, size: Size) {
647        if !app.contains(self) || !self.mounted(app) || app.get(self).layout_root_size == size {
648            return;
649        }
650        app.get_mut(self).layout_root_size = size;
651        self.create_bitmaps_and_color_map(app);
652        self.set_state(app, |_| {});
653    }
654
655    /// `CreateBitmapsAndColorMap`: the images and the colour of each pixel for the current size,
656    /// shape, components and ranges. Nothing is made while `LayoutRoot` has no size.
657    fn create_bitmaps_and_color_map(self: Handle<Self>, app: &mut App) {
658        let size = app.get(self).layout_root_size;
659        let min_dimension = size.width().min(size.height());
660        if min_dimension == 0.0 {
661            return;
662        }
663        let widget = self.widget(app).clone();
664        let ranges = widget.ranges();
665        let pixels = spectrum_pixels(
666            min_dimension.round() as usize,
667            widget.shape,
668            widget.components,
669            ranges,
670        );
671        let side = min_dimension.round() as u32;
672        let image = |data: Vec<u8>| image_from_pixel_data(app, side, side, data);
673        let surfaces = match pixels.images {
674            SpectrumImages::Two { minimum, maximum } => match widget.components {
675                ColorSpectrumComponents::HueValue | ColorSpectrumComponents::ValueHue => {
676                    SpectrumSurfaces::Saturation {
677                        minimum: image(minimum),
678                        maximum: image(maximum),
679                    }
680                }
681                _ => SpectrumSurfaces::Value(image(maximum)),
682            },
683            SpectrumImages::Six(hues) => SpectrumSurfaces::Hue(hues.map(image)),
684        };
685        app.get_mut(self).creation = Some(BitmapCreation {
686            shape: widget.shape,
687            components: widget.components,
688            size: min_dimension,
689            ranges,
690            hsv_values: pixels.hsv_values,
691            surfaces,
692        });
693    }
694
695    /// `UpdateBitmapSources`: the images to fill with and the second's opacity. For saturation
696    /// or value as the third component, the images at its minimum and maximum (one image for
697    /// value, at its maximum) at the opacity of the colour's saturation (or 1); for hue, the
698    /// primary hues on either side of the colour's hue, at how far past the first it is.
699    fn spectrum_fill(self: Handle<Self>, app: &App) -> Option<SpectrumFill> {
700        let hsv = app.get(self).hsv_color;
701        let creation = app.get(self).creation.as_ref()?;
702        match &creation.surfaces {
703            SpectrumSurfaces::Saturation { minimum, maximum } => Some(SpectrumFill {
704                minimum: minimum.clone()?,
705                maximum: maximum.clone()?,
706                weight: f64::from(hsv.saturation),
707            }),
708            SpectrumSurfaces::Value(value) => Some(SpectrumFill {
709                minimum: value.clone()?,
710                maximum: value.clone()?,
711                weight: 1.0,
712            }),
713            SpectrumSurfaces::Hue(hues) => {
714                let sextant = f64::from(hsv.hue) / 60.0;
715                let first = if sextant < 1.0 {
716                    0
717                } else if sextant < 2.0 {
718                    1
719                } else if sextant < 3.0 {
720                    2
721                } else if sextant < 4.0 {
722                    3
723                } else if sextant < 5.0 {
724                    4
725                } else {
726                    5
727                };
728                Some(SpectrumFill {
729                    minimum: hues[first].clone()?,
730                    maximum: hues[(first + 1) % 6].clone()?,
731                    weight: sextant - f64::from(sextant as i32),
732                })
733            }
734        }
735    }
736
737    /// `UpdateEllipse`: the centre of the selection ellipse in `InputTarget`, from the images
738    /// last made; `None`, collapsing it, before there are any.
739    fn ellipse_center(self: Handle<Self>, app: &App) -> Option<Offset> {
740        let hsv = app.get(self).hsv_color;
741        let creation = app.get(self).creation.as_ref()?;
742        Some(ellipse_center(hsv, creation))
743    }
744
745    /// `SelectionEllipseShouldBeLight`: a light selection ellipse when the colour under it
746    /// contrasts more with black than with white, by relative luminance. With value as the third
747    /// component the spectrum shows full value, so that colour is the one judged.
748    fn selection_ellipse_color(self: Handle<Self>, app: &App) -> SelectionEllipseColor {
749        let hsv = app.get(self).hsv_color;
750        let displayed = match self.widget(app).components {
751            ColorSpectrumComponents::HueSaturation | ColorSpectrumComponents::SaturationHue => {
752                let full_value = Hsv::new(f64::from(hsv.hue), f64::from(hsv.saturation), 1.0);
753                color_from_rgba(hsv_to_rgb(full_value), f64::from(hsv.alpha))
754            }
755            _ => hsv.to_color(),
756        };
757        let linear = |channel: u8| {
758            let channel = f64::from(channel);
759            if channel <= 10.0 {
760                channel / 3294.0
761            } else {
762                (channel / 269.0 + 0.0513).powf(2.4)
763            }
764        };
765        let displayed = argb(displayed);
766        let luminance = 0.2126 * linear(displayed.r)
767            + 0.7152 * linear(displayed.g)
768            + 0.0722 * linear(displayed.b);
769        if luminance <= 0.5 {
770            SelectionEllipseColor::SelectionEllipseLight
771        } else {
772            SelectionEllipseColor::SelectionEllipseDark
773        }
774    }
775
776    /// `UpdateVisualState`'s `CommonStates`.
777    fn common_state(self: Handle<Self>, app: &App) -> SpectrumCommonState {
778        let state = app.get(self);
779        if state.is_pointer_pressed {
780            if state.should_show_large_selection {
781                SpectrumCommonState::PressedLarge
782            } else {
783                SpectrumCommonState::Pressed
784            }
785        } else if state.is_pointer_over {
786            SpectrumCommonState::PointerOver
787        } else {
788            SpectrumCommonState::Normal
789        }
790    }
791
792    /// `UpdateVisualState`'s `FocusStates`, by how the focus arrived.
793    fn focus_visual_state(self: Handle<Self>, app: &mut App) -> SpectrumFocusState {
794        if !app.get(self).focused || !self.widget(app).is_enabled {
795            return SpectrumFocusState::Unfocused;
796        }
797        match FocusState::current(app) {
798            FocusState::Pointer => SpectrumFocusState::PointerFocused,
799            FocusState::Keyboard => SpectrumFocusState::Focused,
800        }
801    }
802
803    /// `OnPropertyChanged` for the properties the images depend on: `Shape` and `Components`
804    /// always remake them, and a component's range when that component is an axis.
805    fn images_outdated(old: &ColorSpectrum, new: &ColorSpectrum) -> bool {
806        use ColorSpectrumComponents::*;
807        let hue_range = (old.min_hue, old.max_hue) != (new.min_hue, new.max_hue);
808        let saturation_range =
809            (old.min_saturation, old.max_saturation) != (new.min_saturation, new.max_saturation);
810        let value_range = (old.min_value, old.max_value) != (new.min_value, new.max_value);
811        old.shape != new.shape
812            || old.components != new.components
813            || (hue_range && !matches!(new.components, SaturationValue | ValueSaturation))
814            || (saturation_range && !matches!(new.components, HueValue | ValueHue))
815            || (value_range && !matches!(new.components, HueSaturation | SaturationHue))
816    }
817}
818
819/// The component an arrow steps: across (Left and Right) the first of `components`, down (Up
820/// and Down) the second.
821fn arrow_channel(components: ColorSpectrumComponents, horizontal: bool) -> ColorPickerHsvChannel {
822    use ColorPickerHsvChannel::{Hue, Saturation, Value};
823    use ColorSpectrumComponents::*;
824    match (components, horizontal) {
825        (HueSaturation | HueValue, true) | (SaturationHue | ValueHue, false) => Hue,
826        (SaturationValue | SaturationHue, true) | (HueSaturation | ValueSaturation, false) => {
827            Saturation
828        }
829        (ValueHue | ValueSaturation, true) | (SaturationValue | HueValue, false) => Value,
830    }
831}
832
833/// `UpdateEllipse`'s position: the colour, clamped to the ranges, as a share of each axis of a
834/// box, or as an angle and a distance from the centre of a ring. Saturation with hue, and value
835/// in any spectrum, run from their maximum at the top or the outside.
836fn ellipse_center(hsv: HsvColor, creation: &BitmapCreation) -> Offset {
837    let ranges = creation.ranges;
838    let (min_hue, max_hue) = (f64::from(ranges.min_hue), f64::from(ranges.max_hue));
839    let (min_saturation, max_saturation) = (
840        f64::from(ranges.min_saturation),
841        f64::from(ranges.max_saturation),
842    );
843    let (min_value, max_value) = (f64::from(ranges.min_value), f64::from(ranges.max_value));
844    let hue = f64::from(clamp_f32(hsv.hue, min_hue as f32, max_hue as f32));
845    let saturation = f64::from(clamp_f32(
846        hsv.saturation,
847        (min_saturation / 100.0) as f32,
848        (max_saturation / 100.0) as f32,
849    ));
850    let value = f64::from(clamp_f32(
851        hsv.value,
852        (min_value / 100.0) as f32,
853        (max_value / 100.0) as f32,
854    ));
855    let saturation_with_hue = matches!(
856        creation.components,
857        ColorSpectrumComponents::HueSaturation | ColorSpectrumComponents::SaturationHue
858    );
859    let size = creation.size;
860    let (x, y) = if creation.shape == ColorSpectrumShape::Box {
861        let h = (hue - min_hue) / (max_hue - min_hue);
862        let mut s = (saturation * 100.0 - min_saturation) / (max_saturation - min_saturation);
863        let mut v = (value * 100.0 - min_value) / (max_value - min_value);
864        if saturation_with_hue {
865            s = 1.0 - s;
866        } else {
867            v = 1.0 - v;
868        }
869        let (x_percent, y_percent) = match creation.components {
870            ColorSpectrumComponents::HueValue => (h, v),
871            ColorSpectrumComponents::HueSaturation => (h, s),
872            ColorSpectrumComponents::ValueHue => (v, h),
873            ColorSpectrumComponents::ValueSaturation => (v, s),
874            ColorSpectrumComponents::SaturationHue => (s, h),
875            ColorSpectrumComponents::SaturationValue => (s, v),
876        };
877        (size * x_percent, size * y_percent)
878    } else {
879        let share = |value: f64, min: f64, max: f64| {
880            if max != min {
881                (value - min) / (max - min)
882            } else {
883                0.0
884            }
885        };
886        let theta_of = |value: f64, min: f64, max: f64| {
887            if max != min {
888                360.0 * share(value, min, max)
889            } else {
890                0.0
891            }
892        };
893        let r_of = |value: f64, min: f64, max: f64| {
894            if max != min {
895                share(value, min, max) - 1.0
896            } else {
897                0.0
898            }
899        };
900        let h_theta = theta_of(hue, min_hue, max_hue);
901        let mut s_theta = theta_of(saturation * 100.0, min_saturation, max_saturation);
902        let mut v_theta = theta_of(value * 100.0, min_value, max_value);
903        let h_r = r_of(hue, min_hue, max_hue);
904        let mut s_r = r_of(saturation * 100.0, min_saturation, max_saturation);
905        let mut v_r = r_of(value * 100.0, min_value, max_value);
906        if saturation_with_hue {
907            s_theta = 360.0 - s_theta;
908            s_r = -s_r - 1.0;
909        } else {
910            v_theta = 360.0 - v_theta;
911            v_r = -v_r - 1.0;
912        }
913        let (theta, r) = match creation.components {
914            ColorSpectrumComponents::HueValue => (h_theta, v_r),
915            ColorSpectrumComponents::HueSaturation => (h_theta, s_r),
916            ColorSpectrumComponents::ValueHue => (v_theta, h_r),
917            ColorSpectrumComponents::ValueSaturation => (v_theta, s_r),
918            ColorSpectrumComponents::SaturationHue => (s_theta, h_r),
919            ColorSpectrumComponents::SaturationValue => (s_theta, v_r),
920        };
921        let radius = size / 2.0;
922        let angle = theta * PI / 180.0 + PI;
923        (
924            angle.cos() * radius * r + radius,
925            angle.sin() * radius * r + radius,
926        )
927    };
928    // A range of one value divides by zero; `Canvas.Left` and `Canvas.Top` of NaN place at 0.
929    let finite = |position: f64| if position.is_finite() { position } else { 0.0 };
930    Offset::new(finite(x), finite(y))
931}
932
933/// `clamp` of floats, as `UpdateEllipse` clamps the colour; `min` wins over `max`.
934fn clamp_f32(value: f32, min: f32, max: f32) -> f32 {
935    if value < min {
936        min
937    } else if max < value {
938        max
939    } else {
940        value
941    }
942}
943
944/// The pixel data `CreateBitmapsAndColorMap` computes for one size, shape, components and
945/// ranges.
946struct SpectrumPixels {
947    /// The colour of each pixel, row by row; the third component is the minimum's.
948    hsv_values: Vec<Hsv>,
949    images: SpectrumImages,
950}
951
952/// The BGRA pixels of the images: the third component at its minimum and maximum, or at the six
953/// primary hues.
954enum SpectrumImages {
955    Two { minimum: Vec<u8>, maximum: Vec<u8> },
956    Six([Vec<u8>; 6]),
957}
958
959/// Whether hue is the third component of `components`, so that six images are made.
960fn hue_is_third(components: ColorSpectrumComponents) -> bool {
961    matches!(
962        components,
963        ColorSpectrumComponents::ValueSaturation | ColorSpectrumComponents::SaturationValue
964    )
965}
966
967/// The pixel loops of `CreateBitmapsAndColorMap`: a box is filled column by column from its
968/// bottom right, which with the axes `FillPixelForBox` gives puts the first component across
969/// and the second down; a ring row by row. When a range's minimum is not below its maximum, the
970/// minimum is the only value.
971fn spectrum_pixels(
972    side: usize,
973    shape: ColorSpectrumShape,
974    components: ColorSpectrumComponents,
975    ranges: Ranges,
976) -> SpectrumPixels {
977    let ranges = Ranges {
978        max_hue: ranges.max_hue.max(ranges.min_hue),
979        max_saturation: ranges.max_saturation.max(ranges.min_saturation),
980        max_value: ranges.max_value.max(ranges.min_value),
981        ..ranges
982    };
983    let count = side * side;
984    let images = if hue_is_third(components) { 6 } else { 2 };
985    let mut data: Vec<Vec<u8>> = (0..images).map(|_| Vec::with_capacity(count * 4)).collect();
986    let mut hsv_values = Vec::with_capacity(count);
987    let mut fill = |hsvs: [Hsv; 6]| {
988        hsv_values.push(hsvs[0]);
989        let used: &[Hsv] = if images == 6 {
990            &hsvs
991        } else {
992            &[hsvs[0], hsvs[5]]
993        };
994        for (pixels, hsv) in data.iter_mut().zip(used) {
995            let rgb = hsv_to_rgb(*hsv);
996            let byte = |channel: f64| (channel * 255.0).round() as u8;
997            // The alpha byte is ignored.
998            pixels.extend([byte(rgb.b), byte(rgb.g), byte(rgb.r), 255]);
999        }
1000    };
1001    let n = side as f64;
1002    match shape {
1003        ColorSpectrumShape::Box => {
1004            for x in (0..side).rev() {
1005                for y in (0..side).rev() {
1006                    fill(pixel_for_box(x as f64, y as f64, n, components, ranges));
1007                }
1008            }
1009        }
1010        ColorSpectrumShape::Ring => {
1011            for y in 0..side {
1012                for x in 0..side {
1013                    fill(pixel_for_ring(
1014                        x as f64,
1015                        y as f64,
1016                        n / 2.0,
1017                        components,
1018                        ranges,
1019                    ));
1020                }
1021            }
1022        }
1023    }
1024    let images = if images == 6 {
1025        let mut six = data.into_iter();
1026        SpectrumImages::Six(std::array::from_fn(|_| six.next().expect("six images")))
1027    } else {
1028        let maximum = data.pop().expect("a maximum image");
1029        let minimum = data.pop().expect("a minimum image");
1030        SpectrumImages::Two { minimum, maximum }
1031    };
1032    SpectrumPixels { hsv_values, images }
1033}
1034
1035/// The ranges in HSV units.
1036fn hsv_ranges(ranges: Ranges) -> [f64; 6] {
1037    [
1038        f64::from(ranges.min_hue),
1039        f64::from(ranges.max_hue),
1040        f64::from(ranges.min_saturation) / 100.0,
1041        f64::from(ranges.max_saturation) / 100.0,
1042        f64::from(ranges.min_value) / 100.0,
1043        f64::from(ranges.max_value) / 100.0,
1044    ]
1045}
1046
1047/// `FillPixelForBox`: the colours of pixel `(x, y)` of the six images, from the shares `x` and
1048/// `y` are of the way back from the far corner.
1049fn pixel_for_box(
1050    x: f64,
1051    y: f64,
1052    side: f64,
1053    components: ColorSpectrumComponents,
1054    ranges: Ranges,
1055) -> [Hsv; 6] {
1056    let x_percent = (side - 1.0 - x) / (side - 1.0);
1057    let y_percent = (side - 1.0 - y) / (side - 1.0);
1058    pixel_colors(x_percent, y_percent, components, ranges)
1059}
1060
1061/// `FillPixelForRing`: the colours of pixel `(x, y)` from its angle around the centre and its
1062/// distance from the edge. A pixel outside the circle takes the colour at the edge, so that
1063/// hit-testing the edge always finds one.
1064fn pixel_for_ring(
1065    x: f64,
1066    y: f64,
1067    radius: f64,
1068    components: ColorSpectrumComponents,
1069    ranges: Ranges,
1070) -> [Hsv; 6] {
1071    let mut distance = ((x - radius).powi(2) + (y - radius).powi(2)).sqrt();
1072    let (mut x_to_use, mut y_to_use) = (x, y);
1073    if distance > radius {
1074        x_to_use = (radius / distance) * (x - radius) + radius;
1075        y_to_use = (radius / distance) * (y - radius) + radius;
1076        distance = radius;
1077    }
1078    let r = 1.0 - distance / radius;
1079    let mut theta = ((radius - y_to_use).atan2(radius - x_to_use) * 180.0 / PI + 180.0).floor();
1080    while theta > 360.0 {
1081        theta -= 360.0;
1082    }
1083    pixel_colors(r, theta / 360.0, components, ranges)
1084}
1085
1086/// The shared tail of `FillPixelForBox` and `FillPixelForRing`, for `first`, a box's `xPercent`
1087/// or a ring's `r`, and `second`, a box's `yPercent` or a ring's `thetaPercent`: the components
1088/// at those shares of their ranges and the third at its minimum and maximum (or the six primary
1089/// hues), with saturation beside hue, and value anywhere, inverted so that they run from their
1090/// maximum at the top or the outside.
1091fn pixel_colors(
1092    first: f64,
1093    second: f64,
1094    components: ColorSpectrumComponents,
1095    ranges: Ranges,
1096) -> [Hsv; 6] {
1097    let [h_min, h_max, s_min, s_max, v_min, v_max] = hsv_ranges(ranges);
1098    let hue = |share: f64| h_min + share * (h_max - h_min);
1099    let saturation = |share: f64| s_min + share * (s_max - s_min);
1100    let value = |share: f64| v_min + share * (v_max - v_min);
1101    let with_third = |h: Option<f64>, s: Option<f64>, v: Option<f64>| -> [Hsv; 6] {
1102        std::array::from_fn(|i| {
1103            let third = match (h, s, v) {
1104                (None, _, _) => 60.0 * i as f64,
1105                _ if i == 5 => 1.0,
1106                _ => 0.0,
1107            };
1108            Hsv::new(h.unwrap_or(third), s.unwrap_or(third), v.unwrap_or(third))
1109        })
1110    };
1111    let mut colors = match components {
1112        ColorSpectrumComponents::HueValue => {
1113            with_third(Some(hue(second)), None, Some(value(first)))
1114        }
1115        ColorSpectrumComponents::HueSaturation => {
1116            with_third(Some(hue(second)), Some(saturation(first)), None)
1117        }
1118        ColorSpectrumComponents::ValueHue => {
1119            with_third(Some(hue(first)), None, Some(value(second)))
1120        }
1121        ColorSpectrumComponents::ValueSaturation => {
1122            with_third(None, Some(saturation(first)), Some(value(second)))
1123        }
1124        ColorSpectrumComponents::SaturationHue => {
1125            with_third(Some(hue(first)), Some(saturation(second)), None)
1126        }
1127        ColorSpectrumComponents::SaturationValue => {
1128            with_third(None, Some(saturation(second)), Some(value(first)))
1129        }
1130    };
1131    let saturation_with_hue = matches!(
1132        components,
1133        ColorSpectrumComponents::HueSaturation | ColorSpectrumComponents::SaturationHue
1134    );
1135    for hsv in &mut colors {
1136        if saturation_with_hue {
1137            hsv.s = s_max - hsv.s + s_min;
1138        } else {
1139            hsv.v = v_max - hsv.v + v_min;
1140        }
1141    }
1142    colors
1143}
1144
1145impl State for ColorSpectrumState {
1146    type Widget = ColorSpectrum;
1147    waft_widgets::state_accessors!();
1148
1149    fn init_state(self: Handle<Self>, app: &mut App) {
1150        InputDevice::initialize(app);
1151        let focus = FocusNode::new(app);
1152        focus.as_node().set_on_key_event(
1153            app,
1154            Some(Rc::new(move |app, _, event: &KeyEvent| match event {
1155                KeyEvent::Down(down) => self.key_down(app, down.logical_key),
1156                KeyEvent::Repeat(repeat) => self.key_down(app, repeat.logical_key),
1157                KeyEvent::Up(_) => KeyEventResult::Ignored,
1158            })),
1159        );
1160        focus.add_listener(app, Listener::handle_method(self, Self::focus_changed));
1161        app.get_mut(self).focus = Some(focus);
1162    }
1163
1164    fn did_update_widget(self: Handle<Self>, app: &mut App, old: &ColorSpectrum) {
1165        let widget = self.widget(app).clone();
1166        if ColorSpectrumState::images_outdated(old, &widget) {
1167            self.create_bitmaps_and_color_map(app);
1168        }
1169        // `OnHsvColorChanged`: the application's colour, unless it is the one the spectrum has.
1170        if widget.hsv_color != app.get(self).hsv_color {
1171            self.set_hsv_color(app, widget.hsv_color);
1172        }
1173        if !widget.is_enabled {
1174            let state = app.get_mut(self);
1175            state.is_pointer_over = false;
1176            state.is_pointer_pressed = false;
1177            state.should_show_large_selection = false;
1178        }
1179    }
1180
1181    fn dispose(self: Handle<Self>, app: &mut App) {
1182        let focus = app
1183            .get_mut(self)
1184            .focus
1185            .take()
1186            .expect("an initialized ColorSpectrum");
1187        focus.remove_listener(app, &Listener::handle_method(self, Self::focus_changed));
1188        focus.dispose(app);
1189    }
1190
1191    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1192        let widget = self.widget(app).clone();
1193        let r = ThemeResources::of(app, context);
1194        let shape = app
1195            .get(self)
1196            .creation
1197            .as_ref()
1198            .map_or(widget.shape, |c| c.shape);
1199        let common = self.common_state(app);
1200        let ellipse_color = self.selection_ellipse_color(app);
1201        let focus_state = self.focus_visual_state(app);
1202        let (selection_stroke, focus_stroke) = match ellipse_color {
1203            SelectionEllipseColor::SelectionEllipseLight => (
1204                r.system_control_background_chrome_white_brush,
1205                r.system_control_background_chrome_black_high_brush,
1206            ),
1207            SelectionEllipseColor::SelectionEllipseDark => (
1208                r.system_control_background_chrome_black_high_brush,
1209                r.system_control_background_chrome_white_brush,
1210            ),
1211        };
1212        let panel_size = if common == SpectrumCommonState::PressedLarge {
1213            SELECTION_ELLIPSE_LARGE_SIZE
1214        } else {
1215            SELECTION_ELLIPSE_SIZE
1216        };
1217        // `SelectionEllipse`, owning `ColorNameToolTip`, which shows while the control has the
1218        // focus.
1219        let selection_ellipse = ToolTipService::new(
1220            Opacity::new(if common == SpectrumCommonState::PointerOver {
1221                POINTER_OVER_SELECTION_OPACITY
1222            } else {
1223                1.0
1224            })
1225            .child(CustomPaint::new().painter(EllipseStrokePainter {
1226                stroke: selection_stroke,
1227                thickness: ELLIPSE_STROKE_THICKNESS,
1228            })),
1229            ToolTip::text(app.get(self).color_name).vertical_offset(COLOR_NAME_TOOL_TIP_OFFSET),
1230        )
1231        .is_open(app.get(self).focused && widget.is_enabled);
1232        // `SelectionEllipsePanel`, with `FocusEllipse` 2 larger on every side.
1233        let mut panel_children = Vec::new();
1234        if focus_state == SpectrumFocusState::Focused {
1235            panel_children.push(
1236                Positioned::from_rect(
1237                    Rect::from_ltwh(
1238                        -FOCUS_ELLIPSE_OUTSET,
1239                        -FOCUS_ELLIPSE_OUTSET,
1240                        panel_size + 2.0 * FOCUS_ELLIPSE_OUTSET,
1241                        panel_size + 2.0 * FOCUS_ELLIPSE_OUTSET,
1242                    ),
1243                    CustomPaint::new().painter(EllipseStrokePainter {
1244                        stroke: focus_stroke,
1245                        thickness: ELLIPSE_STROKE_THICKNESS,
1246                    }),
1247                )
1248                .into_widget(),
1249            );
1250        }
1251        panel_children.push(Positioned::fill(selection_ellipse).into_widget());
1252        let mut input_children = Vec::new();
1253        if let Some(center) = self.ellipse_center(app) {
1254            input_children.push(
1255                Positioned::from_rect(
1256                    Rect::from_ltwh(
1257                        center.dx() - panel_size / 2.0,
1258                        center.dy() - panel_size / 2.0,
1259                        panel_size,
1260                        panel_size,
1261                    ),
1262                    IgnorePointer::new().child(
1263                        Stack::new()
1264                            .clip_behavior(Clip::None)
1265                            .children(panel_children),
1266                    ),
1267                )
1268                .into_widget(),
1269            );
1270        }
1271        let input_target = self.input_target(
1272            app,
1273            widget.is_enabled,
1274            Stack::new()
1275                .fit(StackFit::Expand)
1276                .clip_behavior(Clip::None)
1277                .children(input_children)
1278                .into_widget(),
1279        );
1280        let fill = self.spectrum_fill(app);
1281        // `SizingGrid`: its children in order, clipped to the square.
1282        let sizing_grid_children = vec![
1283            IgnorePointer::new()
1284                .child(CustomPaint::new().painter(SpectrumPainter {
1285                    shape,
1286                    corner_radius: widget.corner_radius,
1287                    fill,
1288                }))
1289                .into_widget(),
1290            input_target,
1291            IgnorePointer::new()
1292                .child(CustomPaint::new().painter(SpectrumBorderPainter {
1293                    shape,
1294                    corner_radius: widget.corner_radius,
1295                    stroke: r.color_picker_border_brush,
1296                }))
1297                .into_widget(),
1298        ];
1299        let side = app.get(self).layout_root_size;
1300        let side = side.width().min(side.height());
1301        let sizing_grid = if side > 0.0 {
1302            SizedBox::new()
1303                .width(side)
1304                .height(side)
1305                .child(
1306                    ClipRect::new().child(
1307                        Stack::new()
1308                            .fit(StackFit::Expand)
1309                            .children(sizing_grid_children),
1310                    ),
1311                )
1312                .into_widget()
1313        } else {
1314            SizedBox::shrink().into_widget()
1315        };
1316        // `LayoutRoot`: centres `SizingGrid` and reports its own size.
1317        let layout_root = SizeObserver::new(
1318            Center::new()
1319                .width_factor(1.0)
1320                .height_factor(1.0)
1321                .child(sizing_grid),
1322            Rc::new(move |app, _, size| self.layout_root_size_changed(app, size)),
1323        );
1324        Focus::new(layout_root)
1325            .focus_node(
1326                app.get(self)
1327                    .focus
1328                    .as_ref()
1329                    .expect("an initialized ColorSpectrum")
1330                    .erase(),
1331            )
1332            .can_request_focus(widget.is_enabled)
1333            .skip_traversal(!widget.is_enabled)
1334            .into_widget()
1335    }
1336}
1337
1338impl ColorSpectrumState {
1339    /// `InputTarget`: takes the pointer over the whole square while enabled
1340    /// (`ManipulationMode="None"`, so that no scrolling takes a touch from it), and reports its
1341    /// pointer entering and leaving.
1342    fn input_target(self: Handle<Self>, _app: &App, enabled: bool, child: WidgetRef) -> WidgetRef {
1343        if !enabled {
1344            return child;
1345        }
1346        let listener = PointerListener::new()
1347            .behavior(HitTestBehavior::Opaque)
1348            .on_pointer_down(Rc::new(move |app: &mut App, event| {
1349                self.pointer_pressed(app, &event);
1350            }))
1351            .on_pointer_move(Rc::new(move |app: &mut App, event| {
1352                self.pointer_moved(app, event.local_position());
1353            }))
1354            .on_pointer_up(Rc::new(move |app: &mut App, _event| {
1355                self.pointer_released(app);
1356            }))
1357            .child(child);
1358        let region = MouseRegion::new()
1359            .on_enter(Rc::new(move |app, _| self.pointer_over(app, true)))
1360            .on_exit(Rc::new(move |app, _| self.pointer_over(app, false)))
1361            .child(listener);
1362        RawGestureDetector::new()
1363            .gestures(vec![(
1364                TypeId::of::<EagerGestureRecognizer>(),
1365                GestureRecognizerFactoryWithHandlers::new(EagerGestureRecognizer::new, |_, _| {})
1366                    .into_factory(),
1367            )])
1368            .child(region)
1369            .into_widget()
1370    }
1371}
1372
1373/// The `SpectrumBrush` of the fill: `maximum` over `minimum` at `weight`'s opacity.
1374#[derive(Clone, Debug, PartialEq)]
1375struct SpectrumFill {
1376    minimum: Image,
1377    maximum: Image,
1378    weight: f64,
1379}
1380
1381/// `SpectrumRectangle` (the control's `CornerRadius` as `RadiusX` and `RadiusY`) or
1382/// `SpectrumEllipse`, filled with the spectrum images stretched over it.
1383#[derive(Clone, Debug, PartialEq)]
1384struct SpectrumPainter {
1385    shape: ColorSpectrumShape,
1386    corner_radius: f64,
1387    fill: Option<SpectrumFill>,
1388}
1389
1390impl SpectrumPainter {
1391    /// Fills the shape with `image` stretched over `size`, at `opacity`.
1392    fn fill_shape(&self, canvas: &mut Canvas, size: Size, image: &Image, opacity: f64) {
1393        let [width, height] = image.size();
1394        let local = Matrix::scale(
1395            (size.width() / f64::from(width)) as f32,
1396            (size.height() / f64::from(height)) as f32,
1397        );
1398        let mut paint = Paint::from_shader(Shader::Image {
1399            image: image.clone(),
1400            sampling: Default::default(),
1401            local,
1402        });
1403        paint.color = paint.color.with_alpha(opacity as f32);
1404        paint_shape(canvas, self.shape, size, self.corner_radius, &paint);
1405    }
1406}
1407
1408impl CustomPainter for SpectrumPainter {
1409    fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
1410        let Some(fill) = &self.fill else {
1411            return;
1412        };
1413        self.fill_shape(canvas, size, &fill.minimum, 1.0);
1414        if fill.weight > 0.0 && fill.maximum != fill.minimum {
1415            self.fill_shape(canvas, size, &fill.maximum, fill.weight);
1416        }
1417    }
1418
1419    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
1420        old_delegate.as_any().downcast_ref::<Self>() != Some(self)
1421    }
1422
1423    fn as_any(&self) -> &dyn std::any::Any {
1424        self
1425    }
1426}
1427
1428/// Fills `shape` over `size`: a rounded rectangle or the ellipse in it.
1429fn paint_shape(
1430    canvas: &mut Canvas,
1431    shape: ColorSpectrumShape,
1432    size: Size,
1433    corner_radius: f64,
1434    paint: &Paint,
1435) {
1436    let bounds = Rect::from_ltwh(0.0, 0.0, size.width(), size.height());
1437    match shape {
1438        ColorSpectrumShape::Box => {
1439            canvas.draw_rrect(bounds, shape_radius(corner_radius, bounds) as f32, paint)
1440        }
1441        ColorSpectrumShape::Ring => draw_oval(canvas, bounds, paint),
1442    }
1443}
1444
1445/// `RadiusX` and `RadiusY` as `CreateRoundedRect` limits them: no more than half the side.
1446fn shape_radius(radius: f64, bounds: Rect) -> f64 {
1447    radius
1448        .abs()
1449        .min(bounds.width() / 2.0)
1450        .min(bounds.height() / 2.0)
1451}
1452
1453/// `RectangleBorder` or `EllipseBorder` in `ColorPickerBorderStyle`: a 2-pixel stroke of `stroke`
1454/// inside the bounds, as a shape strokes the outline inset by half its thickness.
1455#[derive(Clone, Debug, PartialEq)]
1456struct SpectrumBorderPainter {
1457    shape: ColorSpectrumShape,
1458    corner_radius: f64,
1459    stroke: Color,
1460}
1461
1462impl CustomPainter for SpectrumBorderPainter {
1463    fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
1464        let outline = Rect::from_ltwh(0.0, 0.0, size.width(), size.height())
1465            .deflate(COLOR_PICKER_BORDER_THICKNESS / 2.0);
1466        let mut paint = Paint::from_color(self.stroke.into());
1467        paint.style = PaintStyle::Stroke(Stroke::new(COLOR_PICKER_BORDER_THICKNESS as f32));
1468        match self.shape {
1469            ColorSpectrumShape::Box => canvas.draw_rrect(
1470                outline,
1471                shape_radius(self.corner_radius, outline) as f32,
1472                &paint,
1473            ),
1474            ColorSpectrumShape::Ring => draw_oval(canvas, outline, &paint),
1475        }
1476    }
1477
1478    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
1479        old_delegate.as_any().downcast_ref::<Self>() != Some(self)
1480    }
1481
1482    fn as_any(&self) -> &dyn std::any::Any {
1483        self
1484    }
1485}
1486
1487/// An `Ellipse` with a `Stroke` of `thickness` and no fill, inside its box.
1488#[derive(Clone, Debug, PartialEq)]
1489struct EllipseStrokePainter {
1490    stroke: Color,
1491    thickness: f64,
1492}
1493
1494impl CustomPainter for EllipseStrokePainter {
1495    fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
1496        let outline =
1497            Rect::from_ltwh(0.0, 0.0, size.width(), size.height()).deflate(self.thickness / 2.0);
1498        let mut paint = Paint::from_color(self.stroke.into());
1499        paint.style = PaintStyle::Stroke(Stroke::new(self.thickness as f32));
1500        draw_oval(canvas, outline, &paint);
1501    }
1502
1503    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
1504        old_delegate.as_any().downcast_ref::<Self>() != Some(self)
1505    }
1506
1507    fn as_any(&self) -> &dyn std::any::Any {
1508        self
1509    }
1510}
1511
1512#[cfg(test)]
1513mod tests {
1514    use super::*;
1515
1516    fn creation(
1517        shape: ColorSpectrumShape,
1518        components: ColorSpectrumComponents,
1519        size: f64,
1520    ) -> BitmapCreation {
1521        let ranges = Ranges {
1522            min_hue: 0,
1523            max_hue: 359,
1524            min_saturation: 0,
1525            max_saturation: 100,
1526            min_value: 0,
1527            max_value: 100,
1528        };
1529        let pixels = spectrum_pixels(size as usize, shape, components, ranges);
1530        BitmapCreation {
1531            shape,
1532            components,
1533            size,
1534            ranges,
1535            hsv_values: pixels.hsv_values,
1536            surfaces: SpectrumSurfaces::Value(None),
1537        }
1538    }
1539
1540    fn red_at(creation: &BitmapCreation, x: usize, y: usize) -> Hsv {
1541        creation.hsv_values[y * creation.size as usize + x]
1542    }
1543
1544    #[test]
1545    fn a_hue_saturation_box_runs_hue_across_and_saturation_down() {
1546        let c = creation(
1547            ColorSpectrumShape::Box,
1548            ColorSpectrumComponents::HueSaturation,
1549            256.0,
1550        );
1551        assert_eq!(red_at(&c, 0, 0), Hsv::new(0.0, 1.0, 0.0));
1552        let right = red_at(&c, 255, 0);
1553        assert_eq!((right.h, right.s), (359.0, 1.0));
1554        let bottom = red_at(&c, 0, 255);
1555        assert_eq!((bottom.h, bottom.s), (0.0, 0.0));
1556        // The ellipse of a pixel's colour is on that pixel.
1557        let hsv = HsvColor::from_hsv(Hsv::new(right.h, right.s, 1.0), 1.0);
1558        assert_eq!(ellipse_center(hsv, &c), Offset::new(256.0, 0.0));
1559    }
1560
1561    #[test]
1562    fn a_ring_puts_hue_around_and_saturation_outwards() {
1563        let c = creation(
1564            ColorSpectrumShape::Ring,
1565            ColorSpectrumComponents::HueSaturation,
1566            256.0,
1567        );
1568        // Right of the centre is hue 0 (360) at full saturation; below it, a quarter turn.
1569        let right = red_at(&c, 255, 128);
1570        assert!(
1571            right.s > 0.99 && (right.h == 359.0 || right.h == 0.0),
1572            "{right:?}"
1573        );
1574        let below = red_at(&c, 128, 255);
1575        assert!((below.h - 89.75).abs() < 1.0, "{below:?}");
1576        // Hue 89.75 is a quarter of 359: straight below, halfway out.
1577        let centre = ellipse_center(HsvColor::from_hsv(Hsv::new(89.75, 0.5, 1.0), 1.0), &c);
1578        assert!((centre.dx() - 128.0).abs() < 1e-4, "{centre:?}");
1579        assert!((centre.dy() - 192.0).abs() < 1e-4, "{centre:?}");
1580    }
1581
1582    #[test]
1583    fn arrows_step_the_component_their_axis_shows() {
1584        use ColorPickerHsvChannel::*;
1585        use ColorSpectrumComponents::*;
1586        assert_eq!(arrow_channel(HueSaturation, true), Hue);
1587        assert_eq!(arrow_channel(HueSaturation, false), Saturation);
1588        assert_eq!(arrow_channel(SaturationValue, true), Saturation);
1589        assert_eq!(arrow_channel(SaturationValue, false), Value);
1590        assert_eq!(arrow_channel(ValueHue, true), Value);
1591        assert_eq!(arrow_channel(ValueHue, false), Hue);
1592    }
1593}