diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 126f5abfec..95847e2c51 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -307,9 +307,9 @@ fn strip_number(ch: Channel, hsb: [f32; 3]) -> (f64, &'static str, f64) { } /// The box in a `size` × `size` area: the field of channel `ch` and its strip, on HSB `hsb`, with -/// markers when `marked`. Returns the HSB a click, a drag, a key or a screen reader's action picks, +/// markers when `marked`. Returns what a click, a drag, a key or a screen reader's action picks, /// and its phase. -fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> Option<([f32; 3], Live)> { +fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> Option<(Picked, Live)> { let (z, x, y) = box_pos(ch, hsb); let mut pick = None; ui.horizontal_top(|ui| { @@ -317,21 +317,50 @@ fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> let field = vec2((size - STRIP_GAP - STRIP).max(1.0), size); let at = |x: f32, y: f32| widgets::hsb32(box_pick(ch, z, x, y, hsb)); if let (Some((x, y)), phase) = widgets::color_field(ui, "color-wheel-box", (tl!("Color box"), ch.field_axes()), field, (x, y), marked, &at) { - pick = Some((box_pick(ch, z, x, y, hsb), phase)); + pick = Some((Picked::Field(ch, x, y), phase)); } // The hue strip shows the whole spectrum; the others change only their own component. let track = |z: f32| widgets::hsb32(if ch == Channel::Hue { [z * 360.0, 1.0, 1.0] } else { box_pick(ch, z, x, y, hsb) }); let (v, suffix, max) = strip_number(ch, hsb); let shown = SliderValue::field(v, 0.0..=max, suffix, 0); match widgets::channel_slider_stepped(ui, "color-wheel-strip", ch.name(), Some(shown), z, marked, vec2(STRIP, size), &track) { - (Some(z), phase, _) => pick = Some((box_pick(ch, z, x, y, hsb), phase)), - (None, _, Some(v)) => pick = Some((box_pick(ch, (v / max) as f32, x, y, hsb), Live::Released)), + (Some(z), phase, _) => pick = Some((Picked::Strip(ch, z), phase)), + (None, _, Some(v)) => pick = Some((Picked::Strip(ch, (v / max) as f32), Live::Released)), _ => {} } }); pick } +/// What a press, a drag, a key or a screen reader's action sets on the wheel or the box: the +/// components it gives, the others coming from the HSB it is applied to ([`Picked::hsb`]). +#[derive(Clone, Copy)] +enum Picked { + /// The hue ring's hue. + Hue(f32), + /// The square's saturation and brightness. + Square(f32, f32), + /// The box's field point (x across, y down) in channel `ch`. + Field(Channel, f32, f32), + /// The box's strip value in channel `ch`. + Strip(Channel, f32), +} + +impl Picked { + /// The HSB this pick gives on a color showing HSB `was`. + fn hsb(self, was: [f32; 3]) -> [f32; 3] { + match self { + Picked::Hue(h) => [h, was[1], was[2]], + Picked::Square(s, b) => [was[0], s, b], + Picked::Field(ch, x, y) => box_pick(ch, box_pos(ch, was).0, x, y, was), + Picked::Strip(ch, z) => { + let (_, x, y) = box_pos(ch, was); + box_pick(ch, z, x, y, was) + } + } + } +} + /// The opacity (0 to 1) the row shows for `tgt` and whether the row can set it: the selected /// gradient stop's or freeform point's (the first when none is selected, as [`wheel_target`] /// picks it), else that of the fill or stroke item @@ -461,24 +490,28 @@ fn hex_shown(app: &VectorcraftApp, tgt: &Target, color: Option<&Color>) -> Strin } /// The hex field's id for `tgt`: it names the document, the selected objects or text characters, -/// the appearance item, the proxy and the gradient stop or freeform point, but not the color, so a -/// text typed for one of them is dropped when another one is targeted, even one showing the same hex. +/// the object selected in a symbol instance, the appearance item, the proxy and the gradient stop or +/// freeform point, but not the color, so a text typed for one of them is dropped when another one is +/// targeted, even one showing the same hex. fn hex_field_id(app: &VectorcraftApp, tgt: &Target) -> impl std::hash::Hash + use<> { let o = Owner::of(app, tgt, Color::rgb8(0, 0, 0)); - ("color-wheel-hex", o.doc, o.selection, o.text_selection, o.appearance_item, o.fill, o.slot) + let part = app.session.active().and_then(|d| d.selection.symbol_part.as_ref().map(|p| (p.instance, p.path.clone()))); + ("color-wheel-hex", o.doc, o.selection, part, o.text_selection, o.appearance_item, o.fill, o.slot) } /// The Show Hex Field row for `tgt`: a `#` and a field as wide as the row, showing `shown`. A -/// committed text goes through `color.parse`; a text it refuses shows its error in the status bar -/// and changes nothing. True when a text was committed. -fn hex_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, shown: &str) -> bool { +/// committed text goes through `color.parse` as typed; a text it refuses shows its error in the +/// status bar and changes nothing. The text's alpha is not applied when `opacity_set` (the opacity +/// row set the opacity in this frame), so a press on that row that commits the text keeps the +/// opacity it set. True when a text was committed. +fn hex_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, shown: &str, opacity_set: bool) -> bool { let mut typed = None; let id = hex_field_id(app, tgt); ui.horizontal(|ui| { let t = Tokens::get(ui.ctx()); ui.label(egui::RichText::new("#").size(15.0).color(t.text)); let width = ui.available_width(); - typed = widgets::text_field_named(ui, id, Some(tl!("Hex or CSS color")), Some(shown), width, 1); + typed = widgets::exact_text_field_named(ui, id, Some(tl!("Hex or CSS color")), shown, width); }); let Some(text) = typed else { return false }; match app.run("color.parse", json!({ "text": text })) { @@ -490,7 +523,7 @@ fn hex_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, shown: &str) -> // The document's RGB numbers, in the model a pick would store them in. let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); let c = stored_rgb(&cms::active(), rgb, replaced(app, tgt, false).as_ref(), cmyk_doc); - let alpha = r["opacity"].as_f64().map(|o| (o / 100.0) as f32); + let alpha = r["opacity"].as_f64().map(|o| (o / 100.0) as f32).filter(|_| !opacity_set); apply_typed(app, tgt, c, alpha); } Err(e) => app.status(e), @@ -701,8 +734,9 @@ pub(crate) fn chroma_tick(max_chroma: f64) -> f32 { /// Each track shows the colors its slider reaches and dims the part outside sRGB, and a tick on the /// C track marks the largest chroma sRGB holds at the row's L and H. The rows are gray with no /// color to edit and while the working RGB space is not sRGB. Returns the OKLCH a drag, an arrow -/// key, a screen reader or a field asks for, and its phase. -pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f64; 3], Live)> { +/// key, a screen reader or a field asks for, the index of the row that set it (0 for L, 1 for C, 2 +/// for H) and its phase. +pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f64; 3], usize, Live)> { let t = Tokens::get(ui.ctx()); let enabled = color.is_some() && cms.rgb_is_srgb(); let lch = match (color, pstate::>(ui.ctx(), OKLCH_MEMORY)) { @@ -749,13 +783,13 @@ pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: .on_hover_text(tl!("The largest chroma sRGB holds at this lightness and hue")); } if let Some(x) = dragged { - out = Some((at(x), phase)); + out = Some((at(x), i, phase)); } if let Some(k) = keyed { - out = Some((with(i, k), Live::Released)); + out = Some((with(i, k), i, Live::Released)); } if let Some(f) = widgets::plain_field_named(ui, ("color-wheel-oklch-field", i), Some(name), v, suffix, 0, field_w) { - out = Some((with(i, f), Live::Released)); + out = Some((with(i, f), i, Live::Released)); } }); } @@ -774,7 +808,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { (c, _) => display_hsb(&cms, &c.unwrap_or(app.session.last_solid)), }; let marked = color.is_some(); - let mut pick: Option<([f32; 3], Live)> = None; + let mut pick: Option<(Picked, Live)> = None; ui.horizontal_top(|ui| { ui.vertical(|ui| { ui.set_width(44.0); @@ -794,7 +828,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let name = tl!("Saturation and brightness"); let (field, field_phase) = widgets::color_field(&mut field_ui, "field", (name, axes), square.size(), (hsb[1], 1.0 - hsb[2]), marked, &at); if let Some((h, phase)) = ring.hue { - pick = Some(([h, hsb[1], hsb[2]], phase)); + pick = Some((Picked::Hue(h), phase)); } // A press between the square and the ring picks the closest point of the square, which // takes the keyboard focus. @@ -802,10 +836,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let field_id = widgets::id_with(field_ui.scope_id(), "field"); field_ui.memory_mut(|m| m.request_focus(field_id)); let f = |v: f32, lo: f32, len: f32| ((v - lo) / len).clamp(0.0, 1.0); - pick = Some(([hsb[0], f(p.x, square.left(), square.width()), 1.0 - f(p.y, square.top(), square.height())], phase)); + pick = Some((Picked::Square(f(p.x, square.left(), square.width()), 1.0 - f(p.y, square.top(), square.height())), phase)); } if let Some((x, y)) = field { - pick = Some(([hsb[0], x, 1.0 - y], field_phase)); + pick = Some((Picked::Square(x, 1.0 - y), field_phase)); } }); if app.ui.color_wheel.vision { @@ -843,20 +877,28 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } } + let mut committed = false; if let Some(hex) = hex { ui.add_space(4.0); - // A pick or an OKLCH edit read in the frame that commits a text was made on the color - // before the text, so it is not applied. - if hex_row(app, ui, &tgt, &hex) { - return; - } + committed = hex_row(app, ui, &tgt, &hex, opacity_set); } - // A pick or an OKLCH edit read in the frame of an opacity edit goes to the stops as that edit - // left them, so the stop keeps both. - let tgt = if opacity_set { wheel_target(app, ui) } else { tgt }; + // A pick or an OKLCH edit read in the frame of an opacity edit or of a text commit goes to the + // target as that edit or text left it, so a stop keeps both. After a text commit that changed + // the color, the components the pick or the row does not set come from the color the text + // applied; a text that left the color as it was keeps the remembered hue. + let tgt = if opacity_set || committed { wheel_target(app, ui) } else { tgt }; + let now = tgt.color().filter(|c| committed && Some(*c) != color); let behind = super::alt_held(ui); let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); - if let Some((lch, phase)) = picked_lch { + if let Some((asked, row, phase)) = picked_lch { + let lch = match now { + Some(c) => { + let mut lch = oklab::to_oklch(cms.display_rgb(&c)); + lch[row] = asked[row]; + lch + } + None => asked, + }; let (srgb, _) = oklab::from_oklch(lch[0], lch[1], lch[2]); let c = stored_srgb(&cms, srgb, replaced(app, &tgt, behind).as_ref(), cmyk_doc); apply(app, &tgt, c, phase, behind); @@ -865,7 +907,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } return; } - let Some((hsb, phase)) = pick else { return }; + let Some((picked, phase)) = pick else { return }; + let hsb = picked.hsb(now.map_or(hsb, |c| display_hsb(&cms, &c))); let c = stored(&cms, hsb, replaced(app, &tgt, behind).as_ref(), cmyk_doc); apply(app, &tgt, c, phase, behind); if !behind { diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index bae909218f..d820aab5e9 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -803,20 +803,23 @@ fn oklch_sliders_need_srgb_as_the_working_space() { assert_eq!(settings.sliders, Sliders::Oklch); set(&mut settings, &json!({"sliders": "none"}), &p3).unwrap(); assert_eq!(settings.sliders, Sliders::None, "the rows can be hidden in any working space"); + let asked = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let seen = asked.clone(); let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state( move |ui, app: &mut VectorcraftApp| { let tgt = super::color::wheel_target(app, ui); let color = tgt.color(); - let _ = oklch_rows(app, ui, &tgt, color, &p3); + if oklch_rows(app, ui, &tgt, color, &p3).is_some() { + seen.store(true, std::sync::atomic::Ordering::Relaxed); + } }, app(json!("#ff0000")), ); h.run_steps(2); assert!(oklch_slider(&h, "Lightness").accesskit_node().is_disabled()); - let undo = undo_len(h.state()); let rail = oklch_slider(&h, "Lightness").rect(); click(&mut h, on_rail(rail, 0.2), Modifiers::NONE); - assert_eq!(undo_len(h.state()), undo, "a gray row picks nothing"); + assert!(!asked.load(std::sync::atomic::Ordering::Relaxed), "a gray row asks for no OKLCH"); } /// The rows show what they asked for while the color displays as it did, and the color's own @@ -861,3 +864,18 @@ fn ui_color_wheel_sets_and_reads_the_sliders() { assert_eq!(e, "`sliders` must be none or oklch"); assert_eq!(app.ui.color_wheel.view, crate::panels::color_wheel::View::Box, "an error changes nothing"); } + +/// An explicit null for any `ui.colorWheel` key keeps that key's value, as leaving the key out does, +/// and the other keys of the same call still apply. +#[test] +fn ui_color_wheel_keeps_a_key_given_as_null() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let set = json!({"view": "box", "channel": "red", "opacity": true, "hexField": true, "sliders": "oklch", "vision": true}); + let all = app.run("ui.colorWheel", set.clone()).unwrap(); + assert_eq!(all, set); + for key in ["view", "channel", "opacity", "hexField", "sliders", "vision"] { + assert_eq!(app.run("ui.colorWheel", json!({ key: null })).unwrap(), all, "{key}: null"); + } + let got = app.run("ui.colorWheel", json!({"view": null, "channel": "blue", "opacity": null, "hexField": false})).unwrap(); + assert_eq!(got, json!({"view": "box", "channel": "blue", "opacity": true, "hexField": false, "sliders": "oklch", "vision": true})); +} diff --git a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs index e53a7d203e..cef02c5e23 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs @@ -314,6 +314,117 @@ fn a_text_typed_for_one_object_does_not_go_to_another_with_the_same_hex() { assert_eq!(undo_count(h.state()), before, "nothing was applied"); } +/// Selects the field's text and types `text` over it, without committing it. +fn type_pending(h: &mut Harness<'static, VectorcraftApp>, text: &str) { + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").type_text(text); + h.run_steps(1); +} + +/// A click at `pos` whose press and release come in one frame. +fn quick_click(h: &mut Harness<'static, VectorcraftApp>, pos: egui::Pos2) { + h.event(egui::Event::PointerMoved(pos)); + h.run_steps(1); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + h.input_mut().events.extend([button(true), button(false)]); + h.run_steps(2); +} + +/// A click on the square in one frame that takes the focus from an edited field applies the text, +/// then the click's saturation and brightness at the hue the text gave: a gradient stop keeps the +/// typed alpha. +#[test] +fn a_wheel_click_in_one_frame_after_typing_applies_both() { + let mut app = app(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + let before = undo_count(&app); + let mut h = harness(app); + type_pending(&mut h, "#33669980"); + let square = h.get_by_label("Saturation and brightness").rect(); + quick_click(&mut h, square.right_top() + vec2(-1.0, 1.0)); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let stop = &g.gradient.stops[0]; + assert!((stop.opacity - 0.502).abs() < 1e-4, "the typed alpha stays: {}", stop.opacity); + let hex = stop.color.to_hex(); + assert_ne!(hex, "#336699", "the click picked a color"); + let ch = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).unwrap(); + assert!(ch(5) > 0xf0 && ch(1) < 0x10 && ch(3) > 0x60 && ch(3) < 0xa0, "the pick keeps the typed hue: {hex}"); + assert_eq!(undo_count(h.state()), before + 2); +} + +/// A text that leaves a white as it was, committed by a click on the square in one frame, keeps the +/// hue the white was picked from: the click's saturation brings that hue back. +#[test] +fn a_click_that_commits_the_same_white_keeps_the_remembered_hue() { + let mut app = app(); + let rect = selected(&app)[0]; + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + let mut h = harness(app); + let square = h.get_by_label("Saturation and brightness").rect(); + quick_click(&mut h, square.left_top()); + assert_eq!(rgb8(&fill_color(h.state(), rect)), [255, 255, 255], "the square picks white"); + type_pending(&mut h, "#ffffff"); + quick_click(&mut h, square.right_top() + vec2(-1.0, 1.0)); + let [r, g, b] = rgb8(&fill_color(h.state(), rect)); + assert!(g > 0xf0 && r < 0x10 && b < 0x10, "the green comes back: {r:02x}{g:02x}{b:02x}"); +} + +/// A press on the opacity slider in one frame that takes the focus from a field holding hex with an +/// alpha applies the typed color and keeps the opacity the press set, not the typed alpha. +#[test] +fn an_opacity_click_in_one_frame_keeps_its_opacity_over_a_typed_alpha() { + let mut app = app(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + app.run("ui.colorWheel", json!({"opacity": true})).unwrap(); + let mut h = harness(app); + type_pending(&mut h, "#33669900"); + let rail = h.get_by_role_and_label(Role::Slider, "Opacity").rect(); + quick_click(&mut h, rail.center()); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let stop = &g.gradient.stops[0]; + assert_eq!(stop.color.to_hex(), "#336699", "the text applies"); + assert!(stop.opacity > 0.2 && stop.opacity < 0.8, "the press sets the opacity: {}", stop.opacity); +} + +/// A text typed for one object of a dynamic symbol instance is dropped when another object of the +/// same instance showing the same hex is selected: Enter then changes neither of them. +#[test] +fn a_text_typed_for_one_object_of_a_symbol_instance_does_not_go_to_another() { + let mut app = app(); + let a = selected(&app)[0]; + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + let b = selected(&app)[0]; + let inst = app.run("symbol.new", json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap(); + app.run("symbol.instance.selectPart", json!({"id": inst, "path": [0]})).unwrap(); + let before = undo_count(&app); + let mut h = harness(app); + type_pending(&mut h, "#336699"); + h.state_mut().run("symbol.instance.selectPart", json!({"id": inst, "path": [1]})).unwrap(); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(2); + let Paint::Solid { color, .. } = crate::panels::current_paints(h.state()).0 else { panic!("a solid fill") }; + assert_eq!(rgb8(&color), [255, 0, 0], "the second object keeps its color"); + assert_eq!(undo_count(h.state()), before, "nothing was applied"); +} + +/// A text with a character `color.parse` does not read as whitespace (a no-break space) is refused, +/// as `color.parse` refuses it, and changes nothing. +#[test] +fn a_no_break_space_in_the_text_is_refused() { + let app = app(); + let doc = app.session.doc().unwrap().doc.clone(); + let mut h = harness(app); + type_in(&mut h, "\u{a0}#336699"); + assert_eq!(*h.state().session.doc().unwrap().doc, *doc); + assert!(!h.state().ui.status.is_empty(), "the status bar says why"); + assert!(h.state_mut().run("color.parse", json!({"text": "\u{a0}#336699"})).is_err()); +} + /// A press on the opacity slider that takes the focus from an edited field applies the text and /// keeps the opacity the press set: a gradient stop takes both. #[test]