diff --git a/crates/imaging/src/ui/adjust/hue_saturation.rs b/crates/imaging/src/ui/adjust/hue_saturation.rs index ebaec581b..2be45f3e0 100644 --- a/crates/imaging/src/ui/adjust/hue_saturation.rs +++ b/crates/imaging/src/ui/adjust/hue_saturation.rs @@ -1,20 +1,24 @@ -//! [`HueSaturationEditor`]: Master and six colour ranges, Colorize, the two spectrum bars and the four range thumbs -//! that wrap at 360°. +//! [`HueSaturationEditor`]: Master and six colour ranges picked by their swatches, Colorize, the two spectrum bars and +//! the four range thumbs that wrap at 360°. #[cfg(feature = "suite")] pub(crate) mod stories; -use craft_behavior::Mixed; +use craft_behavior::{Metrics, Mixed, Sense}; use craft_theme::{Hsb, Srgba}; -use craft_ui::choice::Checkbox; -use craft_ui::contract::{Bind, EditResponse, Entry, Outcome, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _}; +use craft_ui::choice::{Checkbox, RadioGroup, Swatch, SwatchFill, SwatchMetrics, SwatchShape}; +use craft_ui::contract::{ + Bind, Common, Component, Cx, DisabledLook, EditResponse, Gap, MeasureCx, Outcome, PaintUi, Pattern, Props as _, Remember as _, Role, Show as _, + ShowContainer as _, +}; use craft_ui::display::{Shade, Text}; -use craft_ui::form::Field; -use craft_ui::pickers::Select; +use craft_ui::layout::RowAlign; +use craft_ui::layout_components::{Row as LayoutRow, Stack}; +use craft_ui::primitives::PaintShape; use craft_ui::runtime::env::{Env, Label, UnitKind}; -use craft_ui::style::{DataColor, TypeRole}; +use craft_ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx, TypeRole}; use craft_ui::value_drag::{Anchor, OffThumbs, SpanInk, Thumb, ThumbRow, ThumbSpan, TrackFace}; -use egui::{Color32, Ui}; +use egui::{Color32, Response, Ui, Vec2}; use super::sliders::{Run, editor_group, lifted, read, words}; use super::style::tones; @@ -37,6 +41,10 @@ const TURN: f64 = 360.0; const MAX_SPAN: f64 = 359.0; /// The bands under a range's thumbs: the whole range faint, its full-strength part muted. const RANGE_SPANS: [ThumbSpan; 2] = [ThumbSpan::new(0, 3, SpanInk::Faint), ThumbSpan::new(1, 2, SpanInk::Muted)]; +/// The grey Colorize's swatch shows the adjustment of: what Colorize makes of it is the colorize colour. +const MID_GREY: Srgba = Srgba::rgb(0.5, 0.5, 0.5); +/// The edited mark's dot as a share of its slot's height. +const EDITED_DOT: f32 = 1.0; /// One of Hue/Saturation's six colour ranges (Reds, Yellows, Greens, Cyans, Blues, Magentas). #[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] @@ -84,6 +92,18 @@ impl HueRangeValue { out.map(|b| b + shift) } + /// The middle of the range's fully-on span (its inner two bounds, canonical), in 0..360: 0° for the Reds, 240° + /// for the Blues. + pub fn centre(&self) -> f64 { + let bounds = Self::canonical_bounds(self.bounds); + ((bounds[1] + bounds[2]) / 2.0).rem_euclid(TURN) + } + + /// Whether the range's own hue, saturation or lightness changes anything. + fn edited(&self) -> bool { + self.hue != 0.0 || self.saturation != 0.0 || self.lightness != 0.0 + } + /// `bounds` with thumb `index` (0 range start … 3 range end) dragged to `degrees` (0..=360 on /// the bar), PhotoCraft's rule: canonicalise first; the start moves by the shortest turn to /// `degrees`, at most to the second thumb and at least 180° before it; any other thumb moves @@ -172,6 +192,14 @@ impl HueSaturation { self } + /// A value holding only range `r` of `self`: the master unchanged, Colorize off and the other ranges neutral, so + /// an adjustment of it shows what that range alone does. + fn only_range(&self, r: usize) -> HueSaturation { + let mut only = HueSaturation::default(); + only.ranges[r] = self.ranges[r]; + only + } + /// The four thumbs of range `r` as the thumb row shows them: each bound within one turn. fn thumbs(&self, r: usize) -> [f64; 4] { HueRangeValue::canonical_bounds(self.ranges[r].bounds).map(|degrees| degrees.rem_euclid(TURN)) @@ -192,9 +220,14 @@ impl HueSaturation { } } +/// A fully saturated, full-brightness hue. +fn hue_srgba(degrees: f64) -> Srgba { + Srgba::from_hsb(Hsb { h: degrees.rem_euclid(TURN) as f32, s: 1.0, b: 1.0 }) +} + /// A fully saturated, full-brightness hue as image data. fn hue_color(degrees: f64) -> DataColor { - DataColor::new(Color32::from(Srgba::from_hsb(Hsb { h: degrees as f32, s: 1.0, b: 1.0 }))) + DataColor::new(Color32::from(hue_srgba(degrees))) } /// The hue spectrum for a colour track: red, yellow, green, cyan, blue, magenta, red. @@ -243,17 +276,21 @@ impl std::ops::Deref for HueSaturationOutput { /// Hue/Saturation. /// -/// - **Range select** (Master, Reds … Magentas): view state of the editor, Master at first. Disabled and forced to -/// Master while Colorize is on. The range shown comes back in [`HueSaturationOutput::shown_range`]. +/// - **Range swatches** (Master, Reds … Magentas): a radio group of round swatches, view state of the editor, Master +/// (the hue wheel) at first. A range swatch shows the colour at the range's centre; once the range's own Hue, +/// Saturation or Lightness is not zero it shows that colour before and after the range alone (start and end halves, +/// through [`adjusted`](Self::adjusted)) with a dot under it. With a range shown, its centre stands above the Hue row, +/// at the end edge: "240°", or "0° / 30°" once its Hue moves it. While Colorize is on the row is one read-only +/// swatch of what the value makes of a mid grey, and the editor shows Master. The range shown comes back in +/// [`HueSaturationOutput::shown_range`]. /// - **Master**: Hue (−180..180°; 0..360° with Colorize) over the hue spectrum track, Saturation (−100..100 %; /// 0..100 % with Colorize) over a track from grey to the current hue, Lightness (−100..100 %) over a fixed black, /// grey, white track. Tracks only while dynamic tracks are on. /// - **A range**: its Hue, Saturation and Lightness rows, then the range thumbs (below). /// - **Colorize** (a `Set`): on, Hue wraps into 0..360 and Saturation becomes at least 25; off, a Hue above 180 wraps /// back by −360. -/// - **Spectrum bars**: the input hues above (37 samples, every 10°), the host's -/// [`adjusted_spectrum`](Self::adjusted_spectrum) below (the same 37 hues after the adjustment; the input bar again -/// without it). Not mirrored in right-to-left layouts: they are scales of the image. +/// - **Spectrum bars**: the input hues above (37 samples, every 10°), the host's [`adjusted`](Self::adjusted) below +/// (the same 37 hues after the adjustment; the input bar again without it). Not mirrored in right-to-left layouts: they are scales of the image. /// - **Range thumbs** (a range shown): four thumbs under the lower bar as one thumb row that wraps through 0° and keeps /// its order going round from the first thumb, over a faint band from the first thumb to the last and a muted one /// between the middle two. A drag on a thumb moves it with [`HueRangeValue::move_bound`], whole degrees; a press @@ -263,7 +300,7 @@ impl std::ops::Deref for HueSaturationOutput { pub struct HueSaturationEditor<'a> { label: Label, value: Bind<'a, HueSaturation>, - adjusted: Option<&'a dyn Fn(f64) -> Srgba>, + adjusted: Option<&'a dyn Fn(&HueSaturation, Srgba) -> Srgba>, range: Option>, context: AdjustContext, } @@ -274,9 +311,10 @@ impl<'a> HueSaturationEditor<'a> { Self { label: label.into(), value, adjusted: None, range: None, context: AdjustContext::dialog(true) } } - /// What a fully saturated, full-brightness hue (degrees 0..=360) becomes under the shown value: the host runs its - /// engine. Called 37 times a pass. - pub fn adjusted_spectrum(mut self, adjusted: &'a dyn Fn(f64) -> Srgba) -> Self { + /// What a colour of the image becomes under a value: the host runs its engine. The lower spectrum bar asks for 37 + /// full hues under the shown value, each edited range's swatch for its centre colour under a value holding only + /// that range, and Colorize's swatch for a mid grey under the shown value. Without it every colour stays as it is. + pub fn adjusted(mut self, adjusted: &'a dyn Fn(&HueSaturation, Srgba) -> Srgba) -> Self { self.adjusted = Some(adjusted); self } @@ -308,12 +346,51 @@ impl<'a> HueSaturationEditor<'a> { let at = if now.colorize { 0 } else { kept.min(6) }; let range = at.checked_sub(1); let names = [&words.reds, &words.yellows, &words.greens, &words.cyans, &words.blues, &words.magentas]; - let mut entries = vec![Entry::new(0usize, words.master.clone())]; - entries.extend(names.iter().enumerate().map(|(i, name)| Entry::new(i + 1, (*name).clone()))); + let after = |value: &HueSaturation, color: Srgba| adjusted.map_or(color, |adjusted| adjusted(value, color)); let mut picked = None; - Field::new(words.range.clone()).id_salt("range").show(ui, |ui, _| { - picked = Select::new(words.range.clone(), Bind::given(at), &entries).enabled(!now.colorize).show(ui).value().copied(); - }); + if now.colorize { + Swatch::new(words.colorize_color.clone(), after(&now, MID_GREY)).shape(SwatchShape::Round).read_only(true).show(ui); + } else { + picked = RadioGroup::new(words.range.clone(), Bind::given(at)) + .show(ui, |ui, _| { + LayoutRow::new().show(ui, |ui, _| { + for shown in 0..=names.len() { + let (label, fill, edited) = match shown.checked_sub(1) { + None => (words.master.clone(), SwatchFill::Spectrum, false), + Some(r) => { + let range = now.ranges[r]; + let before = hue_srgba(range.centre()); + let fill = if range.edited() { + SwatchFill::Split(before, after(&now.only_range(r), before)) + } else { + SwatchFill::Color(Mixed::Same(before)) + }; + (names[r].clone(), fill, range.edited()) + } + }; + Stack::new().gap(Gap::Tight).show(ui, |ui, _| { + Swatch::with_fill(label.clone(), fill.clone()).shape(SwatchShape::Round).member(shown).show(ui); + EditedMark::new(edited).show(ui); + }); + } + }); + }) + .value() + .copied(); + } + if let Some(r) = at.checked_sub(1) { + let range = now.ranges[r]; + let degrees = |at: f64| units.text(UnitKind::Degrees, at.round().rem_euclid(TURN) + 0.0, 0..=0); + let centre = range.centre(); + let text = if range.hue.round() == 0.0 { + degrees(centre) + } else { + words.range_centre_moved.fill(&[("from", °rees(centre)), ("to", °rees(centre + range.hue))]) + }; + LayoutRow::new().fill_width().align(RowAlign::End).show(ui, |ui, _| { + Text::new(text.clone()).shade(Shade::Faint).show(ui); + }); + } let mut run = Run::start(&mut value, context, now, memory.began); let hue_track = AdjustTrack::Colors(hue_stops()); let degrees = @@ -362,7 +439,7 @@ impl<'a> HueSaturationEditor<'a> { let input: Vec = (0..SAMPLES).map(|i| hue_color(i as f64 * SAMPLE_STEP)).collect(); let after: Vec = match adjusted { - Some(adjusted) => (0..SAMPLES).map(|i| DataColor::new(Color32::from(adjusted(i as f64 * SAMPLE_STEP)))).collect(), + Some(adjusted) => (0..SAMPLES).map(|i| DataColor::new(Color32::from(adjusted(&now, hue_srgba(i as f64 * SAMPLE_STEP))))).collect(), None => input.clone(), }; ToneRamp::new(&input).label(words.spectrum_before.clone()).show(ui); @@ -404,3 +481,69 @@ impl<'a> HueSaturationEditor<'a> { HueSaturationOutput { edit: lifted(edit, shown.output), shown_range } } } + +/// The style of the edited mark: its slot and the dot's colour. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +#[non_exhaustive] +pub struct EditedMarkStyle { + #[style(metrics)] + metrics: Metrics, + /// The slot: a swatch wide, `space.gap.tight` tall. + slot: Vec2, + /// The dot. + dot: StyleColor, +} + +/// The mark under a range swatch: a dot while the range is edited. Its slot is always there, so the row keeps its +/// height when a range is first edited. +#[derive(craft_ui::contract::Component, craft_ui::contract::Props)] +#[component(sample = EditedMark::sample)] +struct EditedMark { + #[common] + common: Common, + edited: bool, +} + +impl EditedMark { + fn new(edited: bool) -> Self { + EditedMark { common: Common::new(), edited } + } + + fn sample() -> Self { + EditedMark::new(true) + } +} + +impl Component for EditedMark { + const DISABLED: DisabledLook = DisabledLook::Faded; + const ROLE: Role = Role::None; + const OVERLAYS: bool = false; + const PARTS: bool = false; + const STOPS: bool = false; + type Style = EditedMarkStyle; + type Output = Response; + + fn style(cx: &StyleCx<'_>, _: EditedMarkStyleKey) -> EditedMarkStyle { + let slot = Vec2::new(SwatchMetrics::of(cx).side, cx.tokens.space.gap.tight); + EditedMarkStyle { metrics: Metrics::new(), slot, dot: cx.color(cx.tokens.color.text.muted) } + } + + fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { + cx.style.slot + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + if self.edited { + let radius = cx.rect.height() * EDITED_DOT / 2.0; + ui.draw().fill(&PaintShape::Circle(cx.rect.center(), radius), cx.style.dot); + } + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} diff --git a/crates/imaging/src/ui/adjust/hue_saturation/stories.rs b/crates/imaging/src/ui/adjust/hue_saturation/stories.rs index ac45deb2c..a61b42cbe 100644 --- a/crates/imaging/src/ui/adjust/hue_saturation/stories.rs +++ b/crates/imaging/src/ui/adjust/hue_saturation/stories.rs @@ -1,42 +1,61 @@ -//! Stories of Hue/Saturation: Master, a colour range with its thumbs, and Colorize. +//! Stories of Hue/Saturation: Master, a colour range with its thumbs, Colorize, and edited ranges on their swatches. use super::{HueRangeValue, HueSaturation, HueSaturationEditor}; -use craft_theme::Srgba; +use craft_theme::{Hsb, Srgba}; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; -/// What a hue becomes when the image is shifted 40° towards yellow: a stand-in for the host's engine. -fn shifted(degrees: f64) -> Srgba { - let turn = (degrees + 40.0).rem_euclid(360.0) / 60.0; - let (r, g, b) = match turn as u8 { - 0 => (1.0, turn.fract(), 0.0), - 1 => (1.0 - turn.fract(), 1.0, 0.0), - 2 => (0.0, 1.0, turn.fract()), - 3 => (0.0, 1.0 - turn.fract(), 1.0), - 4 => (turn.fract(), 0.0, 1.0), - _ => (1.0, 0.0, 1.0 - turn.fract()), - }; - Srgba::rgb(r as f32, g as f32, b as f32) +/// What `color` becomes under `value`: a stand-in for the host's engine. Colorize tints the colour with the master hue +/// and saturation; otherwise the master and the ranges whose full span holds the colour's hue shift that hue, scale +/// its saturation and move its brightness. +fn adjusted(value: &HueSaturation, color: Srgba) -> Srgba { + let Hsb { h, s, b } = color.to_hsb(); + if value.colorize { + let b = (f64::from(b) * (1.0 + value.lightness / 100.0)).clamp(0.0, 1.0); + return Srgba::from_hsb(Hsb { h: value.hue.rem_euclid(360.0) as f32, s: (value.saturation / 100.0) as f32, b: b as f32 }); + } + let (mut hue, mut saturation, mut lightness) = (value.hue, value.saturation, value.lightness); + for range in &value.ranges { + let bounds = HueRangeValue::canonical_bounds(range.bounds); + let inside = (f64::from(h) - bounds[1]).rem_euclid(360.0) <= bounds[2] - bounds[1]; + if inside { + (hue, saturation, lightness) = (hue + range.hue, saturation + range.saturation, lightness + range.lightness); + } + } + let s = (f64::from(s) * (1.0 + saturation / 100.0)).clamp(0.0, 1.0); + let b = (f64::from(b) * (1.0 + lightness / 100.0)).clamp(0.0, 1.0); + Srgba::from_hsb(Hsb { h: (f64::from(h) + hue).rem_euclid(360.0) as f32, s: s as f32, b: b as f32 }) } #[story(HueSaturationEditor<'static>, covers = [Default], drive = Drive::Never)] fn hue_saturation_master(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let (value, value_at) = data.value_at("master", HueSaturation { hue: 40.0, saturation: 20.0, ..HueSaturation::default() }); - HueSaturationEditor::new("Hue/Saturation", value_at.bind(value)).adjusted_spectrum(&shifted).show(ui).into() + HueSaturationEditor::new("Hue/Saturation", value_at.bind(value)).adjusted(&adjusted).show(ui).into() } -/// The Reds range with its four thumbs and the readout. +/// The Reds range with its four thumbs and the readout, its Hue moved: the split swatch, its dot and "0° / 15°". #[story(HueSaturationEditor<'static>, covers = [], drive = Drive::Never)] fn hue_saturation_range(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut start = HueSaturation::default(); start.ranges[0] = HueRangeValue { hue: 15.0, ..HueRangeValue::neutral(0) }; let (value, value_at) = data.value_at("range", start); - HueSaturationEditor::new("Hue/Saturation", value_at.bind(value)).range(Some(0)).adjusted_spectrum(&shifted).show(ui).into() + HueSaturationEditor::new("Hue/Saturation", value_at.bind(value)).range(Some(0)).adjusted(&adjusted).show(ui).into() } -/// Colorize on: the range select is off and the Hue runs 0 to 360. +/// Colorize on: one read-only swatch of the colorize colour, and the Hue runs 0 to 360. #[story(HueSaturationEditor<'static>, covers = [], drive = Drive::Never)] fn hue_saturation_colorize(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let (value, value_at) = data.value_at("colorize", HueSaturation { hue: 210.0, saturation: 40.0, colorize: true, ..HueSaturation::default() }); - HueSaturationEditor::new("Hue/Saturation", value_at.bind(value)).show(ui).into() + HueSaturationEditor::new("Hue/Saturation", value_at.bind(value)).adjusted(&adjusted).show(ui).into() +} + +/// Master shown with the Reds' Hue at +30 and the Blues' Saturation at −80: their swatches split before and after, +/// each with its dot. +#[story(HueSaturationEditor<'static>, covers = [], drive = Drive::Never)] +fn hue_saturation_edited_ranges(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let mut start = HueSaturation::default(); + start.ranges[0] = HueRangeValue { hue: 30.0, ..HueRangeValue::neutral(0) }; + start.ranges[4] = HueRangeValue { saturation: -80.0, ..HueRangeValue::neutral(4) }; + let (value, value_at) = data.value_at("edited", start); + HueSaturationEditor::new("Hue/Saturation", value_at.bind(value)).adjusted(&adjusted).show(ui).into() } diff --git a/crates/imaging/src/ui/adjust/labels.rs b/crates/imaging/src/ui/adjust/labels.rs index 2afd65bd3..0b8250341 100644 --- a/crates/imaging/src/ui/adjust/labels.rs +++ b/crates/imaging/src/ui/adjust/labels.rs @@ -96,6 +96,10 @@ craft_ui::words! { /// The degrees readout under the spectrum bars: the range's outer start, inner start, inner /// end and outer end, "{a} / {b} · {c} \\ {d}". range_readout: template "adjust.rangeReadout" = "{a} / {b} · {c} \\ {d}"; + /// The centre of the range shown, where its Hue moves it: "0° / 30°". + range_centre_moved: template "adjust.rangeCentreMoved" = "{from} / {to}"; + /// The one swatch Colorize shows: what it makes of a mid grey. + colorize_color: "adjust.colorizeColor" = "Colorize Color"; // Black & White. /// The Black & White editor's group name (AccessKit). diff --git a/crates/imaging/tests/it/adjust_editors.rs b/crates/imaging/tests/it/adjust_editors.rs index d366701bc..cb9fefc0b 100644 --- a/crates/imaging/tests/it/adjust_editors.rs +++ b/crates/imaging/tests/it/adjust_editors.rs @@ -2,8 +2,15 @@ //! editor, one gesture per slider drag, the Set of a check box, a preset or a button, and the requests the colour wells //! file. -use craft_imaging::ui::adjust::{AdjustSession, HueRangeValue}; -use craft_ui::testing::trial; +use std::cell::RefCell; +use std::rc::Rc; + +use craft_behavior::Mixed; +use craft_imaging::ui::adjust::{AdjustSession, HueRangeValue, HueSaturation, HueSaturationEditor}; +use craft_theme::Srgba; +use craft_ui::contract::{Bind, Role}; +use craft_ui::testing::{Fixture, trial}; +use egui::vec2; // --------------------------------------------------------------------------------------------- // Hue/Saturation @@ -20,6 +27,130 @@ fn range_thumbs_wrap_through_zero() { assert!(moved.windows(2).all(|pair| pair[0] <= pair[1])); } +/// What the Hue/Saturation editor's host sees: the value, the range shown and what the editor asked the engine last pass. +struct HueHost { + value: HueSaturation, + shown: Option, + asked: Vec<(HueSaturation, Srgba)>, +} + +/// The Hue/Saturation editor over `start`, with an engine that changes nothing and notes what it was asked. +fn hue_saturation(start: HueSaturation) -> (Fixture, Rc>) { + let host = Rc::new(RefCell::new(HueHost { value: start, shown: None, asked: Vec::new() })); + let held = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| { + let mut host = held.borrow_mut(); + let HueHost { value, shown, asked } = &mut *host; + let noted = RefCell::new(Vec::new()); + let engine = |value: &HueSaturation, color: Srgba| { + noted.borrow_mut().push((*value, color)); + color + }; + *shown = HueSaturationEditor::new("Hue/Saturation", Bind::bound(value)).adjusted(&engine).show(ui).shown_range; + *asked = noted.into_inner(); + }); + fixture.room(vec2(400.0, 640.0)); + fixture.settle(); + (fixture, host) +} + +/// The range swatches in order, each with whether it is checked. +fn range_swatches(fixture: &Fixture) -> Vec<(String, bool)> { + let tree = fixture.tree(); + fixture + .by_role(Role::RADIO_BUTTON) + .iter() + .map(|swatch| (tree.name_of(swatch.node).unwrap_or_default().to_owned(), tree.toggled_of(swatch.node) == Some(Mixed::Same(true)))) + .collect() +} + +/// The painted degree texts above the Hue row's title: the centre label, if one shows. +fn centre_labels(fixture: &Fixture) -> Vec { + let texts = fixture.texts(); + let hue = texts.iter().find(|text| text.text == "Hue").expect("the Hue row's title").rect; + texts.iter().filter(|text| text.text.contains('°') && text.rect.bottom() <= hue.top() + 0.5).map(|text| text.text.clone()).collect() +} + +fn click(fixture: &mut Fixture, label: &str) { + let swatch = fixture.by_label(label).unwrap_or_else(|| panic!("the {label} swatch")); + fixture.click(&swatch).settle(); +} + +const RANGES: [&str; 7] = ["Master", "Reds", "Yellows", "Greens", "Cyans", "Blues", "Magentas"]; + +/// Seven round swatches pick the range, Master selected at first; there is no range dropdown. +#[trial] +fn seven_swatches_replace_the_dropdown_with_master_selected() { + let (fixture, _) = hue_saturation(HueSaturation::default()); + let want: Vec<(String, bool)> = RANGES.iter().enumerate().map(|(i, name)| ((*name).to_owned(), i == 0)).collect(); + assert_eq!(range_swatches(&fixture), want); + assert!(fixture.by_role(Role::COMBO_BOX).is_empty(), "no range dropdown"); +} + +/// A click on a swatch shows that range, checks only its swatch and puts the range's centre above the Hue row; Master +/// has no centre. +#[trial] +fn a_click_selects_that_range_and_shows_its_centre() { + let (mut fixture, host) = hue_saturation(HueSaturation::default()); + assert!(centre_labels(&fixture).is_empty(), "no centre for Master"); + click(&mut fixture, "Blues"); + assert_eq!(host.borrow().shown, Some(4)); + assert!(range_swatches(&fixture).iter().all(|(name, on)| *on == (name == "Blues")), "{:?}", range_swatches(&fixture)); + assert_eq!(centre_labels(&fixture), ["240°"]); + click(&mut fixture, "Reds"); + assert_eq!(centre_labels(&fixture), ["0°"]); + click(&mut fixture, "Master"); + assert_eq!(host.borrow().shown, None); + assert!(centre_labels(&fixture).is_empty(), "no centre for Master"); +} + +/// A range's centre is the middle of its fully-on span, within one turn; a Hue shift shows where it moves the centre. +#[trial] +fn centre_labels_name_the_range_centre_and_where_its_hue_moves_it() { + let centres: Vec = [0, 1, 4, 5].map(|r| HueRangeValue::neutral(r).centre()).to_vec(); + assert_eq!(centres, [0.0, 60.0, 240.0, 300.0]); + assert_eq!(HueRangeValue::new(0.0, 0.0, 0.0, [190.0, 220.0, 240.0, 270.0]).centre(), 230.0); + for (shift, shown) in [(30.0, "0° / 30°"), (-30.0, "0° / 330°")] { + let mut start = HueSaturation::default(); + start.ranges[0].hue = shift; + let (mut fixture, _) = hue_saturation(start); + click(&mut fixture, "Reds"); + assert_eq!(centre_labels(&fixture), [shown]); + } +} + +/// Colorize shows one read-only swatch of the colorize colour and no range swatches. +#[trial] +fn colorize_collapses_the_row_into_one_swatch() { + let (fixture, _) = hue_saturation(HueSaturation { hue: 120.0, saturation: 25.0, colorize: true, ..HueSaturation::default() }); + assert!(range_swatches(&fixture).is_empty(), "no range swatches"); + let tree = fixture.tree(); + let wells = fixture.by_role(Role::COLOR_WELL).iter().filter(|well| tree.name_of(well.node) == Some("Colorize Color")).count(); + assert_eq!(wells, 1); +} + +/// An edited range's swatch shows its centre before and after that range alone: the engine is asked about the centre +/// under a value holding only that range. Back at neutral (what Reset writes) the swatch shows one colour again. +#[trial] +fn an_edited_range_shows_before_and_after() { + let mut start = HueSaturation { hue: 90.0, ..HueSaturation::default() }; + start.ranges[0].hue = 30.0; + let (mut fixture, host) = hue_saturation(start); + let mut only_reds = HueSaturation::default(); + only_reds.ranges[0].hue = 30.0; + let red = |color: &Srgba| color.r > 0.99 && color.g < 0.01 && color.b < 0.01; + assert!(host.borrow().asked.iter().any(|(value, color)| *value == only_reds && red(color)), "the Reds' centre under the Reds alone"); + let reds = fixture.by_label("Reds").expect("the Reds swatch"); + assert!(fixture.tree().value_of(reds.node).is_some_and(|value| value.contains(" / ")), "before and after"); + + host.borrow_mut().value = HueSaturation::default(); + fixture.settle(); + let shown = host.borrow().value; + assert!(host.borrow().asked.iter().all(|(value, _)| *value == shown), "no range is asked about alone"); + let reds = fixture.by_label("Reds").expect("the Reds swatch"); + assert!(fixture.tree().value_of(reds.node).is_some_and(|value| !value.contains(" / ")), "one colour"); +} + // --------------------------------------------------------------------------------------------- // The slider table and the session