diff --git a/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs b/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs new file mode 100644 index 0000000000..acbab6f0ee --- /dev/null +++ b/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs @@ -0,0 +1,421 @@ +use super::basic::{sliders, track_stops}; +use super::curves::gradient_bar; +use super::levels::nearest; +use super::{ + Color32, Edit, EditorCx, HUE_RANGES, HueRange, Rect, RichText, Sense, Stroke, StrokeKind, Tokens, Value, color32, flag, hue_color, json, num, nums, pos2, + vec2, widgets, +}; + +// --------------------------------------------------------------------------------------------- +// Hue/Saturation + +pub(super) const RANGE_LABELS: [&str; 6] = ["Reds", "Yellows", "Greens", "Cyans", "Blues", "Magentas"]; + +/// The range picker's swatches in order (#14753): Master, then the six colour ranges. +pub(super) const SWATCH_LABELS: [&str; 7] = ["Master", "Red", "Yellow", "Green", "Cyan", "Blue", "Magenta"]; + +/// A range swatch's diameter, in points. +const SWATCH: f32 = 18.0; + +/// The Saturation slider's track: grey to the hue at full saturation (UI-217-16). +pub(super) fn saturation_track(hue_deg: f32) -> [Color32; 2] { + [Color32::from_gray(128), hue_color(hue_deg)] +} + +/// The Lightness slider's track: black, mid grey, white, whatever the hue, as in Photoshop +/// (UI-217-16, #6539). +pub(super) fn lightness_track() -> [Color32; 3] { + [Color32::BLACK, Color32::from_gray(128), Color32::WHITE] +} + +pub(super) fn move_hue_range_handle(bounds: [f32; 4], k: usize, deg: f32) -> [f32; 4] { + let mut b = HueRange::canonical_bounds(bounds); + if k >= b.len() { + return b; + } + if k == 0 { + let delta = (deg - b[0] + 180.0).rem_euclid(360.0) - 180.0; + b[0] = (b[0] + delta).min(b[1]).max(b[1] - 180.0); + } else { + let rel = (deg - b[0]).rem_euclid(360.0); + let hi = if k == 3 { b[0] + 359.0 } else { b[k + 1] }; + b[k] = (b[0] + rel).clamp(b[k - 1], hi); + } + b +} + +/// The range handle a press at `x` grabs, given the four handles' x positions on a bar `w` wide: +/// the nearest within 10 points, or within a third of the gap to the next handle on that side, so +/// the middle third of a narrow zone still drags the zone (at least 3 points, for handles that +/// coincide). The bar is a hue circle: the next handle past an edge is the first from the other. +pub(super) fn hue_range_handle_at(xs: [f32; 4], x: f32, w: f32) -> Option { + let k = nearest(&xs, x)?; + let (xk, d) = (xs[k as usize], x - xs[k as usize]); + let gap = xs + .iter() + .enumerate() + .filter(|&(j, _)| j != k as usize) + .map(|(_, &o)| if d >= 0.0 { (o - xk).rem_euclid(w) } else { (xk - o).rem_euclid(w) }) + .fold(f32::INFINITY, f32::min); + (d.abs() < (gap / 3.0).clamp(3.0, 10.0)).then_some(k) +} + +/// Which zone of a colour range a hue `deg` falls in, between its handles: 0 = the left fade +/// (between the first two), 1 = the fully-on span, 2 = the right fade; `None` outside the range. +pub(super) fn hue_range_zone(bounds: [f32; 4], deg: f32) -> Option { + let b = HueRange::canonical_bounds(bounds); + let rel = (deg - b[0]).rem_euclid(360.0); + let (one, two, three) = (b[1] - b[0], b[2] - b[0], b[3] - b[0]); + if rel <= one { + Some(0) + } else if rel <= two { + Some(1) + } else if rel <= three { + Some(2) + } else { + None + } +} + +/// A drag of `delta` degrees on a zone of a colour range (#9252), as in Photoshop: the left fade +/// moves the two left handles, the fully-on span all four, the right fade the two right handles; +/// a side never crosses the other or grows the range past a turn. +pub(super) fn move_hue_range_zone(start: [f32; 4], zone: u8, delta: f32) -> [f32; 4] { + let b = HueRange::canonical_bounds(start); + if !delta.is_finite() { + return b; + } + let moved = match zone { + 0 => { + let d = delta.min(b[2] - b[1]).max(b[3] - 359.0 - b[0]); + [b[0] + d, b[1] + d, b[2], b[3]] + } + 1 => b.map(|v| v + delta), + 2 => { + let d = delta.max(b[1] - b[2]).min(b[0] + 359.0 - b[3]); + [b[0], b[1], b[2] + d, b[3] + d] + } + _ => b, + }; + HueRange::canonical_bounds(moved) +} + +/// The spectrum bar after the adjustment (what each hue becomes), sampled at `n` hues. +fn adjusted_spectrum(v: &Value, n: usize) -> Vec { + let hues: Vec<[f32; 3]> = (0..n).map(|i| photocraft_color::convert::hsb_to_rgb([i as f32 / (n - 1).max(1) as f32 * 360.0, 1.0, 1.0])).collect(); + adjusted_colors(v, &hues) +} + +/// What the adjustment `v` makes of each colour in `rgb`. +fn adjusted_colors(v: &Value, rgb: &[[f32; 3]]) -> Vec { + let adj = photocraft_engine::commands::adjustment_from_params("hueSaturation", v); + let rect = photocraft_geom::Rect::new(0, 0, rgb.len() as i32, 1); + let px = rgb.iter().map(|c| [c[0], c[1], c[2], 1.0]).collect(); + let mut buf = photocraft_compose::Buffer { rect, px }; + photocraft_compose::adjust::apply(&adj, &mut buf); + buf.px.iter().map(|p| color32([p[0], p[1], p[2]])).collect() +} + +/// The centre of a colour range: the middle of its fully-on span, in 0..360. +fn range_centre(bounds: [f32; 4]) -> f32 { + let b = HueRange::canonical_bounds(bounds); + ((b[1] + b[2]) / 2.0).rem_euclid(360.0) +} + +/// The label above the Hue field (#14753): the centre of colour range `range` (1 = Reds … +/// 6 = Magentas) and, once its Hue moves it, where it goes ("0° / 30°"); none for Master (0). +pub(super) fn range_centre_label(v: &Value, range: usize) -> Option { + let i = range.checked_sub(1)?; + let o = &v[*HUE_RANGES.get(i)?]; + let c = range_centre(nums(o, "range", HueRange::neutral(i).bounds)).round(); + let h = num(o, "hue", 0.0).round(); + // `+ 0.0` turns a -0 into 0, so no "-0°". + let deg = |d: f32| format!("{:.0}°", d.rem_euclid(360.0) + 0.0); + Some(if h == 0.0 { deg(c) } else { format!("{} / {}", deg(c), deg(c + h)) }) +} + +/// What colour range `i` (0 = Reds … 5 = Magentas) shows on its swatch (#14753): the colour at its +/// centre and, once its own Hue, Saturation or Lightness is not zero, what they make of it. +pub(super) fn range_swatch(v: &Value, i: usize) -> (Color32, Option) { + let Some(key) = HUE_RANGES.get(i) else { return (Color32::TRANSPARENT, None) }; + let o = &v[*key]; + let c = range_centre(nums(o, "range", HueRange::neutral(i).bounds)); + let before = photocraft_color::convert::hsb_to_rgb([c, 1.0, 1.0]); + let edited = ["hue", "saturation", "lightness"].iter().any(|k| num(o, k, 0.0) != 0.0); + let after = edited.then(|| { + // This range alone: Master and the other ranges don't change its swatch. + let mut only = json!({}); + only[*key] = o.clone(); + adjusted_colors(&only, &[before]).first().copied().unwrap_or(Color32::TRANSPARENT) + }); + (color32(before), after) +} + +/// The colorize colour, as Colorize makes a mid grey (#14753). +pub(super) fn colorize_color(v: &Value) -> Color32 { + adjusted_colors(v, &[[0.5; 3]]).first().copied().unwrap_or(Color32::TRANSPARENT) +} + +/// Half a disc of radius `r` at `c`: the left half or the right one. +fn half_disc(p: &egui::Painter, c: egui::Pos2, r: f32, left: bool, fill: Color32) { + let start = if left { std::f32::consts::FRAC_PI_2 } else { -std::f32::consts::FRAC_PI_2 }; + let pts = (0..=16).map(|k| start + std::f32::consts::PI * k as f32 / 16.0).map(|a| c + vec2(a.cos(), a.sin()) * r).collect(); + p.add(egui::Shape::convex_polygon(pts, fill, Stroke::NONE)); +} + +/// A hue wheel of radius `r` at `c`, red at the top: the Master swatch. +fn hue_wheel(p: &egui::Painter, c: egui::Pos2, r: f32) { + let at = |deg: f32| { + let a = (deg - 90.0).to_radians(); + c + vec2(a.cos(), a.sin()) * r + }; + for k in 0..36 { + let (a, z) = (k as f32 * 10.0, (k + 1) as f32 * 10.0); + // Each wedge overlaps the next by a little, so no background shows through the seams. + p.add(egui::Shape::convex_polygon(vec![c, at(a - 0.5), at(z + 0.5)], hue_color(a + 5.0), Stroke::NONE)); + } +} + +/// The range picker (#14753): seven round swatches, Master (a hue wheel) then the six colour +/// ranges, the selected one ringed; a click selects that range. An edited range shows its colour +/// before and after, split down the middle, with a dot under it. Colorize collapses the row into +/// one disc in the colorize colour. +fn range_swatches(ui: &mut egui::Ui, v: &Value, range: &mut usize, colorize: bool) { + let t = Tokens::get(ui.ctx()); + let size = vec2(SWATCH, SWATCH + 6.0); + let r = SWATCH / 2.0 - 2.0; + let centre = |rect: Rect| pos2(rect.center().x, rect.top() + SWATCH / 2.0); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + if colorize { + let (rect, resp) = ui.allocate_exact_size(size, Sense::hover()); + ui.painter().circle(centre(rect), r, colorize_color(v), Stroke::new(1.0, t.field_border)); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Colorize"))); + return; + } + let swatches: Vec<(Rect, egui::Response)> = SWATCH_LABELS.iter().map(|_| ui.allocate_exact_size(size, Sense::click())).collect(); + if let Some(i) = swatches.iter().position(|(_, resp)| resp.clicked()) { + *range = i; + } + let p = ui.painter(); + for (i, ((rect, resp), label)) in swatches.into_iter().zip(SWATCH_LABELS).enumerate() { + let c = centre(rect); + if i == 0 { + hue_wheel(p, c, r); + } else { + match range_swatch(v, i - 1) { + (before, Some(after)) => { + half_disc(p, c, r, true, before); + half_disc(p, c, r, false, after); + p.circle_filled(pos2(c.x, rect.bottom() - 1.5), 1.5, t.text_dim); + } + (before, None) => { + p.circle_filled(c, r, before); + } + } + } + let selected = i == *range; + if selected { + p.circle_stroke(c, r + 1.0, Stroke::new(2.0, t.text)); + } else { + p.circle_stroke(c, r, Stroke::new(1.0, t.field_border)); + } + // Keyboard focus gets its own accent ring, clear of the selection ring, so tabbing to + // a swatch shows where Space or Enter will act without moving the selection. + if resp.has_focus() { + p.circle_stroke(c, r + 3.0, Stroke::new(1.0, t.accent)); + } + let label = tl!(label); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, selected, label)); + resp.on_hover_text(label); + } + }); +} + +pub(super) fn spectrum_bar(p: &egui::Painter, r: Rect, colors: &[Color32]) { + let n = colors.len().saturating_sub(1).max(1); + for (i, w) in colors.windows(2).enumerate() { + let x0 = r.left() + r.width() * i as f32 / n as f32; + let x1 = r.left() + r.width() * (i + 1) as f32 / n as f32; + gradient_bar(p, Rect::from_min_max(pos2(x0, r.top()), pos2(x1, r.bottom())), w[0], w[1], false); + } +} + +pub(super) fn hue_saturation(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { + let t = Tokens::get(ui.ctx()); + let range_id = cx.mem.with("hs-range"); + let mut range: usize = ui.data(|d| d.get_temp(range_id)).unwrap_or(0); + let colorize = flag(v, "colorize", false); + if colorize { + range = 0; + } + range_swatches(ui, v, &mut range, colorize); + ui.data_mut(|d| d.insert_temp(range_id, range)); + let mut e = Edit::default(); + let hue_grad = widgets::hue_stops(); + if range == 0 { + let (hlo, hhi, slo) = if colorize { (0.0, 360.0, 0.0) } else { (-180.0, 180.0, -100.0) }; + let mut h = num(v, "hue", 0.0).clamp(hlo, hhi); + let r = widgets::slider_row(ui, tl!("Hue"), &mut h, hlo..=hhi, "°", track_stops(cx, &hue_grad)); + if r.changed() { + v["hue"] = json!(h.round()); + } + e.add(Edit::of(&r)); + // The Saturation track follows the current hue; the Lightness track is a fixed + // black-grey-white ramp, as in Photoshop (UI-217-16). + let sat_track = saturation_track(h); + let mut s = num(v, "saturation", 0.0).clamp(slo, 100.0); + let r = widgets::slider_row(ui, tl!("Saturation"), &mut s, slo..=100.0, "%", track_stops(cx, &sat_track)); + if r.changed() { + v["saturation"] = json!(s.round()); + } + e.add(Edit::of(&r)); + let light_track = lightness_track(); + let mut l = num(v, "lightness", 0.0).clamp(-100.0, 100.0); + let r = widgets::slider_row(ui, tl!("Lightness"), &mut l, -100.0..=100.0, "%", track_stops(cx, &light_track)); + if r.changed() { + v["lightness"] = json!(l.round()); + } + e.add(Edit::of(&r)); + } else { + let key = HUE_RANGES[range - 1]; + if !v.get(key).is_some_and(Value::is_object) { + v[key] = json!({}); + } + if let Some(centre) = range_centre_label(v, range) { + // One row, right-aligned: a bare right-to-left layout would centre it in all the height left. + ui.horizontal(|ui| ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(RichText::new(centre).color(t.text_dim)))); + } + let mut o = v[key].clone(); + let mut sub = Edit::default(); + let mut h = num(&o, "hue", 0.0); + let r = widgets::slider_row(ui, tl!("Hue"), &mut h, -180.0..=180.0, "°", track_stops(cx, &hue_grad)); + if r.changed() { + o["hue"] = json!(h.round()); + } + sub.add(Edit::of(&r)); + sub.add(sliders( + ui, + &mut o, + &[("saturation", tl!("Saturation"), -100.0, 100.0, 0.0, "%", None), ("lightness", tl!("Lightness"), -100.0, 100.0, 0.0, "%", None)], + )); + if sub.changed { + v[key] = o; + } + e.add(sub); + } + let mut c = colorize; + if widgets::checkbox(ui, &mut c, tl!("Colorize")).changed() { + v["colorize"] = json!(c); + let h = num(v, "hue", 0.0); + v["hue"] = json!(if c { + h.rem_euclid(360.0) + } else if h > 180.0 { + h - 360.0 + } else { + h + }); + if c { + v["saturation"] = json!(num(v, "saturation", 25.0).max(0.0).max(25.0)); + } + e.add(Edit::discrete(true)); + } + // Spectrum bars: input hues above, adjusted below; the selected range's sliders between. + ui.add_space(6.0); + // As wide as the sliders above, whatever the panel's width (#9242). + let w = ui.available_width(); + let (bars, bresp) = ui.allocate_exact_size(vec2(w, 40.0), Sense::click_and_drag()); + ui.data_mut(|d| d.insert_temp(cx.mem.with("hs-bars"), bars)); + let top = Rect::from_min_size(bars.min, vec2(w, 10.0)); + let bottom = Rect::from_min_size(pos2(bars.left(), bars.bottom() - 10.0), vec2(w, 10.0)); + let p = ui.painter_at(bars.expand(4.0)); + let input: Vec = (0..=36).map(|i| hue_color(i as f32 * 10.0)).collect(); + spectrum_bar(&p, top, &input); + spectrum_bar(&p, bottom, &adjusted_spectrum(v, 37)); + if range > 0 { + let key = HUE_RANGES[range - 1]; + let neutral = photocraft_doc::adjust::HueRange::neutral(range - 1).bounds; + let mut b = HueRange::canonical_bounds(nums(&v[key], "range", neutral)); + let xof = |deg: f32| bars.left() + deg.rem_euclid(360.0) / 360.0 * w; + let deg_of = |x: f32| ((x - bars.left()) / w * 360.0).clamp(0.0, 360.0); + let mid = bars.center().y; + // Range band (fully affected) and fall-off. + let band = |a: f32, z: f32, color: Color32| { + let (xa, xz) = (xof(a), xof(z)); + if xa <= xz { + p.rect_filled(Rect::from_min_max(pos2(xa, mid - 3.0), pos2(xz, mid + 3.0)), 0.0, color); + } else { + p.rect_filled(Rect::from_min_max(pos2(xa, mid - 3.0), pos2(bars.right(), mid + 3.0)), 0.0, color); + p.rect_filled(Rect::from_min_max(pos2(bars.left(), mid - 3.0), pos2(xz, mid + 3.0)), 0.0, color); + } + }; + band(b[0], b[3], t.text_faint); + band(b[1], b[2], t.text_dim); + for (k, d) in b.iter().enumerate() { + let x = xof(*d); + let fill = if k == 1 || k == 2 { t.text } else { t.field }; + p.rect_filled(Rect::from_center_size(pos2(x, mid), vec2(5.0, 12.0)), 1.0, fill); + p.rect_stroke(Rect::from_center_size(pos2(x, mid), vec2(5.0, 12.0)), 1.0, Stroke::new(1.0, t.text_dim), StrokeKind::Inside); + } + ui.data_mut(|d| d.insert_temp(cx.mem.with("hs-range-bars"), bars)); + let drag_id = cx.mem.with("hs-range-drag"); + let zone_id = cx.mem.with("hs-range-zone"); + let mut which: Option = ui.data(|d| d.get_temp(drag_id)).flatten(); + // A press between the handles drags a zone (#9252): its zone, the bounds and x it began at. + let mut zone: Option<(u8, [f32; 4], f32)> = ui.data(|d| d.get_temp(zone_id)).flatten(); + if bresp.is_pointer_button_down_on() + && ui.input(|i| i.pointer.primary_pressed()) + && let Some(pos) = ui.input(|i| i.pointer.press_origin()) + { + which = hue_range_handle_at(b.map(xof), pos.x, w); + zone = if which.is_none() { hue_range_zone(b, deg_of(pos.x)).map(|z| (z, b, pos.x)) } else { None }; + } + // The release frame applies its position too: a move and a release that land in one frame + // would otherwise commit the bounds from before the move. It ends where the button let go, + // not where the pointer went after that in the same frame. + let released_at = ui.input(|i| { + i.events.iter().find_map(|e| match e { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, .. } => Some(*pos), + _ => None, + }) + }); + let live = bresp.is_pointer_button_down_on() || released_at.is_some(); + let drag_pos = released_at.or_else(|| ui.input(|i| i.pointer.interact_pos())); + if live && let (Some((z, start, x0)), Some(pos)) = (zone, drag_pos) { + let before = b; + b = move_hue_range_zone(start, z, (pos.x - x0) / w * 360.0); + if b != before { + v[key]["range"] = json!(b.map(|x| x.round())); + e.changed = true; + } + } + if zone.is_some() && !bresp.is_pointer_button_down_on() { + zone = None; + e.commit = true; + } + ui.data_mut(|d| d.insert_temp(zone_id, zone)); + if live && let (Some(k), Some(pos)) = (which, drag_pos) { + let k = k as usize; + let deg = deg_of(pos.x); + let before = b; + b = move_hue_range_handle(b, k, deg); + if b != before { + v[key]["range"] = json!(b.map(|x| x.round())); + e.changed = true; + } + } + if which.is_some() && !bresp.is_pointer_button_down_on() { + which = None; + e.commit = true; + } + ui.data_mut(|d| d.insert_temp(drag_id, which)); + let lab = + format!("{:.0}° / {:.0}° · {:.0}° \\ {:.0}°", b[0].rem_euclid(360.0), b[1].rem_euclid(360.0), b[2].rem_euclid(360.0), b[3].rem_euclid(360.0)); + ui.label(RichText::new(lab).font(crate::theme::mono(11.0)).color(t.text_faint)); + } + e +} + +#[cfg(test)] +#[path = "hue_saturation_swatches_tests.rs"] +mod swatches_tests; diff --git a/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation_swatches_tests.rs b/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation_swatches_tests.rs new file mode 100644 index 0000000000..123fb09e06 --- /dev/null +++ b/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation_swatches_tests.rs @@ -0,0 +1,197 @@ +//! #14753: Hue/Saturation picks its range with seven round swatches (Master, then Red, Yellow, +//! Green, Cyan, Blue, Magenta) instead of a dropdown; an edited range shows its colour before and +//! after with a dot under it, a label above the Hue field gives the range's centre, and Colorize +//! collapses the row into one disc in the colorize colour. + +use egui::accesskit::{Role, Toggled}; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::{Value, json}; + +use super::super::EditorCx; +use super::{SWATCH_LABELS, colorize_color, hue_saturation, range_centre_label, range_swatch}; + +fn cx(mem: egui::Id) -> EditorCx { + EditorCx { + mem, + hist: None, + gray: false, + swatches: [[0.0; 3], [1.0; 3]], + gradients: Vec::new(), + dialog: false, + dynamic_color_sliders: true, + isolated_curve: None, + } +} + +fn mem() -> egui::Id { + egui::Id::unique("hue-saturation-swatches-test") +} + +/// The Hue/Saturation editor over `v`, as the Properties panel hosts it. +fn harness(v: Value) -> Harness<'static, Value> { + let mut h = Harness::builder().with_size(vec2(320.0, 400.0)).build_ui_state( + |ui, v: &mut Value| { + // The app's fonts load over a few frames; draw once they're in. + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + hue_saturation(ui, v, &cx(mem())); + } + }, + v, + ); + crate::PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +fn swatches(h: &Harness<'_, Value>) -> Vec<(String, bool)> { + h.query_all_by_role(Role::RadioButton) + .map(|n| { + let a = n.accesskit_node(); + (a.label().unwrap_or_default(), a.toggled() == Some(Toggled::True)) + }) + .collect() +} + +fn text_rect(h: &Harness<'_, Value>, text: &str) -> Option { + h.query_all_by_role(Role::Label) + .find(|n| { + let a = n.accesskit_node(); + a.value().as_deref() == Some(text) || a.label().as_deref() == Some(text) + }) + .map(|n| n.rect()) +} + +fn has_text(h: &Harness<'_, Value>, text: &str) -> bool { + text_rect(h, text).is_some() +} + +fn range(h: &Harness<'_, Value>) -> Option { + h.ctx.data(|d| d.get_temp(mem().with("hs-range"))) +} + +#[test] +fn seven_swatches_replace_the_dropdown_with_master_selected() { + let h = harness(json!({})); + let want: Vec<(String, bool)> = SWATCH_LABELS.iter().enumerate().map(|(i, l)| (l.to_string(), i == 0)).collect(); + assert_eq!(swatches(&h), want, "Master, Red, Yellow, Green, Cyan, Blue, Magenta; Master selected"); + assert!(h.query_all_by_role(Role::ComboBox).next().is_none(), "no range dropdown"); +} + +#[test] +fn a_click_selects_that_range_and_shows_its_centre() { + let mut h = harness(json!({})); + assert!(!has_text(&h, "0°") && !has_text(&h, "240°"), "no centre label for Master"); + h.query_all_by_role_and_label(Role::RadioButton, "Blue").next().expect("the Blue swatch").click(); + h.run_steps(3); + assert_eq!(range(&h), Some(5), "Blues selected"); + assert!(swatches(&h).iter().all(|(l, on)| *on == (l == "Blue")), "only Blue is selected: {:?}", swatches(&h)); + // Right-aligned just above the Hue row (title, field and slider), which now edits Blues. + let label = text_rect(&h, "240°").expect("the Blues centre"); + let hue = h.query_all_by_role(Role::Slider).find(|n| n.accesskit_node().label().as_deref() == Some("Hue")).expect("the Hue slider").rect(); + assert!(label.bottom() <= hue.top() + 1.0 && hue.top() - label.bottom() < 48.0, "label {label:?} right above Hue {hue:?}"); + assert!(label.center().x > 160.0, "right-aligned: {label:?}"); + + h.query_all_by_role_and_label(Role::RadioButton, "Red").next().expect("the Red swatch").click(); + h.run_steps(3); + assert_eq!(range(&h), Some(1)); + assert!(has_text(&h, "0°"), "the Reds centre"); + + h.query_all_by_role_and_label(Role::RadioButton, "Master").next().expect("the Master swatch").click(); + h.run_steps(3); + assert_eq!(range(&h), Some(0)); + assert!(!has_text(&h, "0°"), "no centre label for Master"); +} + +#[test] +fn reds_after_a_hue_shift_label_both_centres() { + let mut h = harness(json!({"reds": {"hue": 30}})); + h.query_all_by_role_and_label(Role::RadioButton, "Red").next().expect("the Red swatch").click(); + h.run_steps(3); + assert!(has_text(&h, "0° / 30°")); +} + +/// Circles stroked in `color` whose centre lies inside `rect`. +fn rings_in(h: &Harness<'_, Value>, rect: egui::Rect, color: egui::Color32) -> usize { + h.output() + .shapes + .iter() + .filter(|s| matches!(&s.shape, egui::Shape::Circle(c) if c.stroke.color == color && c.stroke.width > 0.0 && rect.contains(c.center))) + .count() +} + +#[test] +fn a_focused_swatch_shows_focus_apart_from_the_selection() { + let mut h = harness(json!({})); + let accent = crate::theme::Tokens::get(&h.ctx).accent; + let blue = h.query_all_by_role_and_label(Role::RadioButton, "Blue").next().expect("the Blue swatch").rect(); + let master = h.query_all_by_role_and_label(Role::RadioButton, "Master").next().expect("the Master swatch").rect(); + assert_eq!(rings_in(&h, blue, accent), 0, "no focus ring before focus"); + + h.query_all_by_role_and_label(Role::RadioButton, "Blue").next().expect("the Blue swatch").focus(); + h.run_steps(3); + assert_eq!(range(&h), Some(0), "focus alone keeps Master selected"); + assert_eq!(rings_in(&h, blue, accent), 1, "the focused Blue swatch has a focus ring"); + assert_eq!(rings_in(&h, master, accent), 0, "the selected Master swatch has none"); + assert!(swatches(&h).iter().all(|(l, on)| *on == (l == "Master")), "selection unchanged: {:?}", swatches(&h)); + + h.key_press(egui::Key::Space); + h.run_steps(3); + assert_eq!(range(&h), Some(5), "Space selects the focused swatch"); +} + +#[test] +fn colorize_collapses_the_row_into_one_disc() { + let h = harness(json!({"colorize": true, "hue": 120, "saturation": 25})); + assert!(swatches(&h).is_empty(), "no range swatches with Colorize on"); + assert_eq!(h.query_all_by_role_and_label(Role::Image, "Colorize").count(), 1, "one colorize disc"); +} + +#[test] +fn centre_labels() { + let v = json!({}); + assert_eq!(range_centre_label(&v, 0), None, "Master"); + assert_eq!(range_centre_label(&v, 1).as_deref(), Some("0°"), "Reds"); + assert_eq!(range_centre_label(&v, 2).as_deref(), Some("60°"), "Yellows"); + assert_eq!(range_centre_label(&v, 5).as_deref(), Some("240°"), "Blues"); + assert_eq!(range_centre_label(&v, 6).as_deref(), Some("300°"), "Magentas"); + assert_eq!(range_centre_label(&v, 7), None, "past the ranges: no label, no panic"); + assert_eq!(range_centre_label(&json!({"reds": {"hue": 30}}), 1).as_deref(), Some("0° / 30°")); + assert_eq!(range_centre_label(&json!({"reds": {"hue": -30}}), 1).as_deref(), Some("0° / 330°")); + // A moved range: its centre is the middle of its fully-on span. + assert_eq!(range_centre_label(&json!({"blues": {"range": [190, 220, 240, 270]}}), 5).as_deref(), Some("230°")); + // Saturation or Lightness alone moves no hue. + assert_eq!(range_centre_label(&json!({"blues": {"saturation": 50}}), 5).as_deref(), Some("240°")); +} + +#[test] +fn an_edited_range_shows_before_and_after() { + let close = |a: egui::Color32, b: [u8; 3]| [a.r(), a.g(), a.b()].iter().zip(b).all(|(x, y)| x.abs_diff(y) <= 2); + let (before, after) = range_swatch(&json!({}), 0); + assert!(close(before, [255, 0, 0]), "Reds: red, {before:?}"); + assert_eq!(after, None, "an untouched range has no after half"); + + let (before, after) = range_swatch(&json!({"reds": {"hue": 30}}), 0); + assert!(close(before, [255, 0, 0])); + let after = after.expect("Hue +30 edits Reds"); + assert!(close(after, [255, 128, 0]), "red turned 30° towards yellow: {after:?}"); + + let (_, after) = range_swatch(&json!({"blues": {"lightness": -100}}), 4); + assert!(close(after.expect("Lightness edits Blues"), [0, 0, 0]), "Blues at Lightness -100 is black"); + + // Master and the other ranges leave a range's swatch alone. + assert_eq!(range_swatch(&json!({"hue": 90, "greens": {"saturation": -50}}), 0).1, None); + // Reset puts every range back to zero: the after halves go. + let reset = json!({"reds": {"hue": 0, "saturation": 0, "lightness": 0}}); + assert_eq!(range_swatch(&reset, 0).1, None); + assert_eq!(range_swatch(&json!({}), 6), (egui::Color32::TRANSPARENT, None), "past the ranges: no panic"); +} + +#[test] +fn the_colorize_disc_takes_the_colorize_colour() { + let c = colorize_color(&json!({"colorize": true, "hue": 120, "saturation": 100})); + assert!(c.g() > c.r() + 64 && c.g() > c.b() + 64, "green: {c:?}"); + let c = colorize_color(&json!({"colorize": true, "hue": 240, "saturation": 100})); + assert!(c.b() > c.r() + 64 && c.b() > c.g() + 64, "blue: {c:?}"); +}