Skip to main content

waft_winui/controls/
color_helpers.rs

1//! `Common.idl` of ColorPicker (the enumerations and event arguments ColorSpectrum,
2//! ColorPickerSlider and ColorPicker share) and `ColorHelpers.cpp`: stepping a colour channel
3//! from the keyboard, to the next named colour with Ctrl, and the pixels of the checkered
4//! backgrounds behind translucent colours.
5
6use crate::{Hsv, argb, color_display_name, color_from_rgba, hsv_to_rgb};
7use waft_embedder::valo::{AlphaType, PixelBuffer, PixelFormat, PixelLayout};
8use waft_embedder::{Color, Image};
9use waft_foundation::App;
10
11/// XAML `ColorSpectrumShape`.
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
13pub enum ColorSpectrumShape {
14    /// A square: one component across, the other down.
15    #[default]
16    Box,
17    /// A circle: one component around, the other from the centre out.
18    Ring,
19}
20
21/// XAML `ColorSpectrumComponents`: the two HSV components a spectrum lays out, the first across
22/// a box or around a ring, the second down a box or out from a ring's centre. The third is the
23/// one the spectrum blends its images by.
24#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
25pub enum ColorSpectrumComponents {
26    HueValue,
27    ValueHue,
28    #[default]
29    HueSaturation,
30    SaturationHue,
31    SaturationValue,
32    ValueSaturation,
33}
34
35/// XAML `ColorPickerHsvChannel`: the channel a `ColorPickerSlider` sets.
36#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
37pub enum ColorPickerHsvChannel {
38    Hue,
39    Saturation,
40    #[default]
41    Value,
42    Alpha,
43}
44
45/// XAML `ColorChangedEventArgs`.
46#[derive(Clone, Copy, Debug, PartialEq)]
47pub struct ColorChangedEventArgs {
48    /// `OldColor`.
49    pub old_color: Color,
50    /// `NewColor`.
51    pub new_color: Color,
52}
53
54/// `IncrementDirection`.
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub(crate) enum IncrementDirection {
57    Lower,
58    Higher,
59}
60
61impl IncrementDirection {
62    /// The other direction.
63    pub(crate) fn reversed(self) -> IncrementDirection {
64        match self {
65            IncrementDirection::Lower => IncrementDirection::Higher,
66            IncrementDirection::Higher => IncrementDirection::Lower,
67        }
68    }
69
70    /// -1 lower, 1 higher.
71    fn sign(self) -> f64 {
72        match self {
73            IncrementDirection::Lower => -1.0,
74            IncrementDirection::Higher => 1.0,
75        }
76    }
77}
78
79/// `IncrementAmount`: an arrow key alone, or with Ctrl.
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub(crate) enum IncrementAmount {
82    Small,
83    Large,
84}
85
86/// The component of `hsv` that `channel` names.
87fn component(hsv: &mut Hsv, channel: ColorPickerHsvChannel) -> &mut f64 {
88    match channel {
89        ColorPickerHsvChannel::Hue => &mut hsv.h,
90        ColorPickerHsvChannel::Saturation => &mut hsv.s,
91        ColorPickerHsvChannel::Value => &mut hsv.v,
92        ColorPickerHsvChannel::Alpha => unreachable!("alpha is stepped by increment_alpha_channel"),
93    }
94}
95
96/// `IncrementColorChannel`: a small step moves `channel` by 1 (a degree of hue, a percent of
97/// saturation or value) and stops at the bounds, or with `should_wrap` goes to the other bound
98/// when it was already at one; a large step goes to the next named colour. The bounds are in
99/// degrees for hue and in percent for saturation and value.
100pub(crate) fn increment_color_channel(
101    original: Hsv,
102    channel: ColorPickerHsvChannel,
103    direction: IncrementDirection,
104    amount: IncrementAmount,
105    should_wrap: bool,
106    min_bound: f64,
107    max_bound: f64,
108) -> Hsv {
109    if amount == IncrementAmount::Large {
110        // The named colours are found in HSV units, so saturation and value bounds go to 0-1.
111        let (min_bound, max_bound) = match channel {
112            ColorPickerHsvChannel::Hue => (min_bound, max_bound),
113            _ => (min_bound / 100.0, max_bound / 100.0),
114        };
115        return find_next_named_color(
116            original,
117            channel,
118            direction,
119            should_wrap,
120            min_bound,
121            max_bound,
122        );
123    }
124    // Saturation and value go to 0-100 to keep away from rounding issues.
125    let mut hsv = Hsv::new(original.h, original.s * 100.0, original.v * 100.0);
126    let value = component(&mut hsv, channel);
127    let previous = *value;
128    *value += direction.sign();
129    if *value < min_bound {
130        *value = if should_wrap && previous == min_bound {
131            max_bound
132        } else {
133            min_bound
134        };
135    }
136    if *value > max_bound {
137        *value = if should_wrap && previous == max_bound {
138            min_bound
139        } else {
140            max_bound
141        };
142    }
143    Hsv::new(hsv.h, hsv.s / 100.0, hsv.v / 100.0)
144}
145
146/// The sign of `value`: -1, 0 or 1.
147fn sgn(value: f64) -> i32 {
148    i32::from(value > 0.0) - i32::from(value < 0.0)
149}
150
151/// The name of the colour `hsv` shows.
152fn hsv_name(hsv: Hsv) -> &'static str {
153    color_display_name(color_from_rgba(hsv_to_rgb(hsv), 1.0))
154}
155
156/// `FindNextNamedColor`: steps `channel` in `direction` until the colour has another name, then
157/// across that name's range to its far end, and returns the middle of the range. Without
158/// `should_wrap` it stops at the bound it reaches; with it, a search that comes back to the
159/// start finds no other name and stays where it is.
160fn find_next_named_color(
161    original: Hsv,
162    channel: ColorPickerHsvChannel,
163    direction: IncrementDirection,
164    should_wrap: bool,
165    min_bound: f64,
166    max_bound: f64,
167) -> Hsv {
168    let mut new_hsv = original;
169    let original_name = hsv_name(original);
170    let mut new_name = original_name;
171    let mut original_copy = original;
172    let original_value = *component(&mut original_copy, channel);
173    let increment = match channel {
174        ColorPickerHsvChannel::Hue => 1.0,
175        _ => 0.01,
176    };
177    let mut should_find_mid_point = true;
178    while new_name == original_name {
179        let value = component(&mut new_hsv, channel);
180        let previous = *value;
181        *value += direction.sign() * increment;
182        let mut just_wrapped = false;
183        if *value > max_bound {
184            if should_wrap {
185                *value = min_bound;
186                just_wrapped = true;
187            } else {
188                *value = max_bound;
189                should_find_mid_point = false;
190                break;
191            }
192        } else if *value < min_bound {
193            if should_wrap {
194                *value = max_bound;
195                just_wrapped = true;
196            } else {
197                *value = min_bound;
198                should_find_mid_point = false;
199                break;
200            }
201        }
202        // Wrapped all the way back past the start without finding another name.
203        if !just_wrapped
204            && previous != original_value
205            && sgn(*value - original_value) != sgn(previous - original_value)
206        {
207            should_find_mid_point = false;
208            break;
209        }
210        new_name = hsv_name(new_hsv);
211    }
212    if should_find_mid_point {
213        new_hsv = middle_of_named_range(
214            new_hsv,
215            new_name,
216            channel,
217            direction,
218            should_wrap,
219            min_bound,
220            max_bound,
221            increment,
222        );
223    }
224    new_hsv
225}
226
227/// The second half of `FindNextNamedColor`: from `start`, the first colour named `name`, steps
228/// on to where the name changes again and returns the middle of the two, on a whole step and
229/// within the bounds.
230#[allow(clippy::too_many_arguments)]
231fn middle_of_named_range(
232    start: Hsv,
233    name: &str,
234    channel: ColorPickerHsvChannel,
235    direction: IncrementDirection,
236    should_wrap: bool,
237    min_bound: f64,
238    max_bound: f64,
239    increment: f64,
240) -> Hsv {
241    let mut start_hsv = start;
242    let mut current = start;
243    let mut start_end_offset = 0.0;
244    let wrap_increment = match channel {
245        ColorPickerHsvChannel::Hue => 360.0,
246        _ => 1.0,
247    };
248    let mut current_name = name;
249    while current_name == name {
250        let value = component(&mut current, channel);
251        *value += direction.sign() * increment;
252        if *value > max_bound {
253            if should_wrap {
254                *value = min_bound;
255                start_end_offset = max_bound - min_bound;
256            } else {
257                *value = max_bound;
258                break;
259            }
260        } else if *value < min_bound {
261            if should_wrap {
262                *value = max_bound;
263                start_end_offset = min_bound - max_bound;
264            } else {
265                *value = min_bound;
266                break;
267            }
268        }
269        current_name = hsv_name(current);
270    }
271    let start_value = *component(&mut start_hsv, channel);
272    let current_value = *component(&mut current, channel);
273    let mut new_hsv = start;
274    let value = component(&mut new_hsv, channel);
275    *value = (start_value + current_value + start_end_offset) / 2.0;
276    // Halving may have landed halfway through a step; that leftover goes.
277    let mut leftover = value.abs();
278    while leftover > increment {
279        leftover -= increment;
280    }
281    *value -= leftover;
282    while *value < min_bound {
283        *value += wrap_increment;
284    }
285    while *value > max_bound {
286        *value -= wrap_increment;
287    }
288    new_hsv
289}
290
291/// `IncrementAlphaChannel`: a small step moves alpha by 1 percent; a large one goes to the next
292/// multiple of 10 percent in `direction`. Past a bound it stops there, or with `should_wrap` goes
293/// to the other one. The bounds are in percent; alpha is from 0 to 1.
294pub(crate) fn increment_alpha_channel(
295    original: f64,
296    direction: IncrementDirection,
297    amount: IncrementAmount,
298    should_wrap: bool,
299    min_bound: f64,
300    max_bound: f64,
301) -> f64 {
302    const SMALL: f64 = 1.0;
303    const LARGE: f64 = 10.0;
304    let mut alpha = original * 100.0;
305    alpha = match (amount, direction) {
306        (IncrementAmount::Small, _) => alpha + direction.sign() * SMALL,
307        (IncrementAmount::Large, IncrementDirection::Lower) => {
308            ((alpha - LARGE) / LARGE).ceil() * LARGE
309        }
310        (IncrementAmount::Large, IncrementDirection::Higher) => {
311            ((alpha + LARGE) / LARGE).floor() * LARGE
312        }
313    };
314    if alpha < min_bound {
315        alpha = if should_wrap { max_bound } else { min_bound };
316    }
317    if alpha > max_bound {
318        alpha = if should_wrap { min_bound } else { max_bound };
319    }
320    alpha / 100.0
321}
322
323/// `CheckerSize`: the side of one square of the checkered background, in pixels.
324const CHECKER_SIZE: u32 = 4;
325
326/// The pixels of `CreateCheckeredBackgroundAsync`: `width` by `height` premultiplied BGRA,
327/// transparent and `checker_color` squares alternating across and down.
328pub(crate) fn checkered_background_pixels(
329    width: u32,
330    height: u32,
331    checker_color: Color,
332) -> Vec<u8> {
333    let color = argb(checker_color);
334    let premultiplied = |channel: u8| (u32::from(channel) * u32::from(color.a) / 255) as u8;
335    let checker = [
336        premultiplied(color.b),
337        premultiplied(color.g),
338        premultiplied(color.r),
339        color.a,
340    ];
341    let mut pixels = Vec::with_capacity((width * height * 4) as usize);
342    for y in 0..height {
343        for x in 0..width {
344            let blank = (x / CHECKER_SIZE + y / CHECKER_SIZE).is_multiple_of(2);
345            pixels.extend(if blank { [0; 4] } else { checker });
346        }
347    }
348    pixels
349}
350
351/// `CreateBitmapFromPixelData` and `CreateSurfaceFromPixelData`: an image of `width` by `height`
352/// premultiplied BGRA pixels, from the platform; `None` while it has no renderer.
353pub(crate) fn image_from_pixel_data(
354    app: &App,
355    width: u32,
356    height: u32,
357    bgra: Vec<u8>,
358) -> Option<Image> {
359    if width == 0 || height == 0 {
360        return None;
361    }
362    let layout = PixelLayout::packed(
363        [width, height],
364        PixelFormat::Bgra8,
365        AlphaType::Premultiplied,
366    );
367    let pixels = PixelBuffer::new(layout, bgra).ok()?;
368    app.platform().import_pixels(pixels)
369}
370
371#[cfg(test)]
372mod tests {
373    use super::*;
374    use crate::{Rgb, rgb_to_hsv};
375
376    fn bytes(hsv: Hsv) -> (u8, u8, u8) {
377        let color = color_from_rgba(hsv_to_rgb(hsv), 1.0);
378        let bytes = argb(color);
379        (bytes.r, bytes.g, bytes.b)
380    }
381
382    /// `CanUseKeyboardToInteractWithColorSpectrum`: from red, the arrows and Ctrl+arrows step
383    /// hue and saturation with wrapping to these colours.
384    #[test]
385    fn spectrum_keys_reach_the_interaction_test_colours() {
386        use ColorPickerHsvChannel::{Hue, Saturation};
387        use IncrementAmount::{Large, Small};
388        use IncrementDirection::{Higher, Lower};
389        let steps = [
390            (Hue, Higher, Small, (255, 4, 0)),
391            (Hue, Lower, Small, (255, 0, 0)),
392            (Hue, Lower, Small, (255, 0, 4)),
393            (Hue, Higher, Small, (255, 0, 0)),
394            (Hue, Higher, Large, (255, 119, 0)),
395            (Hue, Lower, Large, (255, 0, 13)),
396            (Hue, Lower, Large, (255, 0, 170)),
397            (Hue, Higher, Large, (255, 0, 13)),
398            (Saturation, Lower, Small, (255, 3, 15)),
399            (Saturation, Higher, Small, (255, 0, 13)),
400            (Saturation, Higher, Small, (255, 255, 255)),
401            (Saturation, Lower, Small, (255, 0, 13)),
402            (Saturation, Lower, Large, (255, 153, 158)),
403            (Saturation, Higher, Large, (255, 38, 49)),
404            (Saturation, Higher, Large, (255, 242, 243)),
405            (Saturation, Lower, Large, (255, 41, 52)),
406            (Saturation, Lower, Large, (255, 153, 158)),
407            (Saturation, Higher, Large, (255, 38, 49)),
408        ];
409        let mut hsv = Hsv::new(0.0, 1.0, 1.0);
410        for (channel, direction, amount, expected) in steps {
411            let max = if channel == Hue { 359.0 } else { 100.0 };
412            hsv = increment_color_channel(hsv, channel, direction, amount, true, 0.0, max);
413            assert_eq!(bytes(hsv), expected, "{channel:?} {direction:?} {amount:?}");
414        }
415    }
416
417    /// `CanUseKeyboardToInteractWithSliders`: the value slider steps without wrapping.
418    #[test]
419    fn value_slider_keys_reach_the_interaction_test_colours() {
420        use IncrementAmount::{Large, Small};
421        use IncrementDirection::{Higher, Lower};
422        let steps = [
423            (Lower, Small, (252, 38, 49)),
424            (Higher, Small, (255, 38, 49)),
425            (Higher, Small, (255, 38, 49)),
426            (Lower, Large, (102, 15, 20)),
427            (Lower, Large, (15, 2, 3)),
428            (Lower, Large, (0, 0, 0)),
429            (Higher, Large, (105, 16, 20)),
430            (Higher, Large, (214, 32, 41)),
431            (Higher, Large, (255, 38, 49)),
432        ];
433        let mut hsv = rgb_to_hsv(Rgb::new(1.0, 38.0 / 255.0, 49.0 / 255.0));
434        for (direction, amount, expected) in steps {
435            hsv = increment_color_channel(
436                hsv,
437                ColorPickerHsvChannel::Value,
438                direction,
439                amount,
440                false,
441                0.0,
442                100.0,
443            );
444            assert_eq!(bytes(hsv), expected, "{direction:?} {amount:?}");
445        }
446    }
447
448    /// The alpha slider: 1 percent a step, and with Ctrl to multiples of 10.
449    #[test]
450    fn alpha_steps_snap_to_tens_with_ctrl() {
451        use IncrementAmount::{Large, Small};
452        use IncrementDirection::{Higher, Lower};
453        let byte = |alpha: f64| (alpha * 255.0).round() as i32;
454        let mut alpha = 1.0;
455        for (direction, amount, expected) in [
456            (Lower, Small, 252),
457            (Higher, Small, 255),
458            (Higher, Small, 255),
459            (Lower, Large, 230),
460            (Higher, Small, 232),
461            (Lower, Large, 230),
462            (Higher, Large, 255),
463        ] {
464            alpha = increment_alpha_channel(alpha, direction, amount, false, 0.0, 100.0);
465            assert_eq!(byte(alpha), expected);
466        }
467    }
468
469    #[test]
470    fn the_checkerboard_alternates_every_four_pixels() {
471        let pixels = checkered_background_pixels(8, 8, Color::from_argb(25, 0, 0, 0));
472        let at = |x: usize, y: usize| &pixels[(y * 8 + x) * 4..(y * 8 + x) * 4 + 4];
473        assert_eq!(at(0, 0), [0, 0, 0, 0]);
474        assert_eq!(at(4, 0), [0, 0, 0, 25]);
475        assert_eq!(at(4, 4), [0, 0, 0, 0]);
476        let light = checkered_background_pixels(8, 8, Color::from_argb(25, 255, 255, 255));
477        assert_eq!(&light[16..20], [25, 25, 25, 25]);
478    }
479}