From 6ab74d70ab4ec9fae98a514547b6fae8278516a6 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:20:04 +0100 Subject: [PATCH 1/3] feat(ui): live preview in Color Pickers for dialog fields and the Crop shield (#9886) While a Color Picker opened for another dialog's colour field is open (Edit > Fill's Color..., Stroke, a filter's or adjustment's colour, Replace Color's Result, New Document, guide and channel colours, Preferences), its colour now shows in that field before OK, as in Photoshop. The dialog's swatch and its own preview follow the picker. The Crop shield's custom colour previews the same way. The new color_picker_ui::live_preview module saves the target when the picker opens. The parent dialog's fields are kept on PhotocraftApp, not in the picker's fields, which automation can rewrite. On each colour change it resets the target to that saved state and applies the new colour, so a dialog that derives settings from the colour never builds on a colour it was only shown. Cancel, or a picker closed any other way, restores the target exactly. OK restores it and then sets the field as before. The document is never touched, so the parent dialog's OK still makes the single history step, and the parent's own Cmd+Z history records nothing while a colour is only previewed. Confirming a dialog while its colour picker is still open is now refused for every dialog, not only for the guide layout. ui.dialog.set on a picker shows the colour at once. Command targets (text colour, gradient stops, artboard, count groups) and the pasteboard colour are unchanged: open PR #9757 previews text and gradient stops, the rest are follow-ups. The foreground/background pickers keep changing the swatches only on OK, as in Photoshop. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/control/dispatch.rs | 2 + crates/ui-egui/src/dialogs.rs | 20 +- crates/ui-egui/src/dialogs/color_picker_ui.rs | 22 +- .../dialogs/color_picker_ui/live_preview.rs | 135 +++++++++ .../color_picker_ui/live_preview/tests.rs | 261 ++++++++++++++++++ crates/ui-egui/src/dialogs/edit_history.rs | 4 +- crates/ui-egui/src/lib.rs | 3 + docs/ui-parity.md | 4 +- 9 files changed, 441 insertions(+), 11 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/color_picker_ui/live_preview.rs create mode 100644 crates/ui-egui/src/dialogs/color_picker_ui/live_preview/tests.rs diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index e5f987c71d..04f8e885e4 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -157,6 +157,7 @@ impl PhotocraftApp { raw_redevelop: Vec::new(), wide_angle: None, dialog_edits: Default::default(), + color_picker_live: Vec::new(), pending_after_prompt: None, tone_hist: None, doc_hist: None, diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index f3e2756071..186a354db8 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -969,6 +969,8 @@ fn dialog_set(app: &mut PhotocraftApp, p: &Value) -> Outcome { Some(d) if !d.fields.contains_key(field) && crate::dialogs::is_route_marker(field) => err(format!("`{field}` is set only by the dialog it belongs to")), Some(d) => { d.fields.insert(field.to_string(), value); + // A Color Picker's colour shows in its target dialog at once, as a drag would. + crate::color_picker_ui::live_preview::sync(app); ok(Value::Null) } None => err(format!("no dialog {id}")), diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a14b42c37f..6b8a3da2a2 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -738,6 +738,10 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { } } ctx.data_mut(|m| m.insert_temp(egui::Id::unique(RECTS), shown)); + // A colour picked this frame shows in its target dialog on the next one. + if crate::color_picker_ui::live_preview::sync(app) { + ctx.request_repaint(); + } } /// The About window's tabs, as stored in its `tab` field. @@ -940,10 +944,12 @@ fn confirm_preflight(app: &mut PhotocraftApp, id: u64) -> Result<(), String> { { authorize(command, &Value::Object(d.fields.clone()))?; } + // A colour field shows the open picker's colour before its OK (`live_preview`): the dialog + // would otherwise commit a colour the picker may still cancel. + if app.ui.dialogs.iter().any(|child| crate::color_picker_ui::owns(&child.fields) && child.fields.get("__dialog").and_then(Value::as_u64) == Some(id)) { + return Err("confirm or cancel the color picker first".into()); + } if let Some(d) = app.ui.dialogs.iter().find(|d| d.id == id).filter(|d| crate::guide_layout_ui::owns(&d.fields)) { - if app.ui.dialogs.iter().any(|child| crate::color_picker_ui::owns(&child.fields) && child.fields.get("__dialog").and_then(Value::as_u64) == Some(id)) { - return Err("confirm or cancel the guide color picker first".into()); - } crate::guide_layout_ui::validate(app, &d.fields)?; } Ok(()) @@ -986,7 +992,11 @@ fn confirm_command_more(app: &mut PhotocraftApp, d: Dialog) -> Result crate::file_ui::confirm(app, &d.fields), _ if crate::new_guide_ui::owns(&d.fields) => crate::new_guide_ui::confirm(app, &d.fields), - _ if crate::color_picker_ui::owns(&d.fields) => crate::color_picker_ui::confirm(app, &d.fields), + _ if crate::color_picker_ui::owns(&d.fields) => { + // OK sets the target as it was before the live preview showed the colour in it. + crate::color_picker_ui::live_preview::end(app, d.id); + crate::color_picker_ui::confirm(app, &d.fields) + } _ if crate::color_range_ui::owns(&d.fields) => crate::color_range_ui::confirm(app, &d.fields), _ if crate::prefs_ui::owns(&d.fields) => crate::prefs_ui::confirm(app, &d.fields), _ if d.fields.contains_key("__export") => crate::export_dialog::confirm(app, &d.fields), @@ -1019,6 +1029,8 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { /// Cancel a dialog and its dependent Layer Style picker, without applying edits. pub fn cancel(app: &mut PhotocraftApp, id: u64) -> Result { let closed = app.ui.close_dialog(id).ok_or_else(|| format!("no dialog {id}"))?; + // A Color Picker puts back what its live preview showed in its target. + crate::color_picker_ui::live_preview::end(app, id); crate::actions::stopped(app, &closed.fields); if crate::guide_layout_ui::owns(&closed.fields) { app.ui.dialogs.retain(|child| child.fields.get("__dialog").and_then(Value::as_u64) != Some(id)); diff --git a/crates/ui-egui/src/dialogs/color_picker_ui.rs b/crates/ui-egui/src/dialogs/color_picker_ui.rs index 46ecbce0e8..0a8777a619 100644 --- a/crates/ui-egui/src/dialogs/color_picker_ui.rs +++ b/crates/ui-egui/src/dialogs/color_picker_ui.rs @@ -4,6 +4,8 @@ //! floats so hue survives greys), so `ui.dialog.set` drives it; OK runs `tools.setColors`. //! While it is the top dialog the image is its eyedropper, as in Photoshop: the pointer over the //! canvas is a pipette, and a click or drag there samples into the new colour ([`sample_at`]). +//! A picker for another dialog's colour field or the Crop shield shows its colour there before +//! OK, and Cancel puts it back ([`live_preview`]). use egui::{Color32, Mesh, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; use photocraft_color::convert::{hsb_to_rgb, rgb_to_hsb}; @@ -185,19 +187,27 @@ pub fn open_for_command(app: &mut PhotocraftApp, label: &str, rgb: [f32; 3], com app.ui.open_dialog(DialogKind::Command, f) } -/// Open the picker on `rgb` for a colour field of another dialog (e.g. Edit › Fill's Color…): OK -/// writes `"#rrggbb"` into `field` of dialog `dialog`, which stays open; Cancel leaves it alone. +/// Open the picker on `rgb` for a colour field of another dialog (e.g. Edit › Fill's Color…): the +/// field shows the picked colour while the picker is open ([`live_preview`]); OK writes +/// `"#rrggbb"` into `field` of dialog `dialog`, which stays open; Cancel puts it back as it was. pub fn open_for_field(app: &mut PhotocraftApp, label: &str, rgb: [f32; 3], dialog: u64, field: &str) -> u64 { let mut f = fields_with_web(app, "field", label, rgb); f.insert("__dialog".into(), json!(dialog)); f.insert("__field".into(), json!(field)); - app.ui.open_dialog(DialogKind::Command, f) + let id = app.ui.open_dialog(DialogKind::Command, f); + live_preview::begin_field(app, id, dialog, field); + id } /// Open the picker on `rgb` for a colour the shell keeps itself (e.g. the Crop shield's custom -/// colour): OK hands `"#rrggbb"` to `target`'s setter in [`confirm`]; Cancel leaves it alone. +/// colour): OK hands `"#rrggbb"` to `target`'s setter in [`confirm`]; Cancel leaves it alone. The +/// Crop shield shows the picked colour while the picker is open ([`live_preview`]). pub fn open_for_target(app: &mut PhotocraftApp, target: &str, label: &str, rgb: [f32; 3]) -> u64 { - app.ui.open_dialog(DialogKind::Command, fields_with_web(app, target, label, rgb)) + let id = app.ui.open_dialog(DialogKind::Command, fields_with_web(app, target, label, rgb)); + if target == "cropShield" { + live_preview::begin_crop_shield(app, id); + } + id } /// Set by a dialog body (to the picker's title) to open the Color Picker on its `color` field. @@ -808,6 +818,8 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result }, + /// The Crop shield's colour choice and custom colour. + CropShield { color: ShieldColor, custom: [u8; 3] }, +} + +/// One open picker's live target. +pub(crate) struct Live { + picker: u64, + before: Before, + /// The colour shown in the target; `None` while it shows what it was. + shown: Option, +} + +/// Preview picker `picker` in `field` of dialog `parent` (a key or a JSON pointer). +pub(super) fn begin_field(app: &mut PhotocraftApp, picker: u64, parent: u64, field: &str) { + let Some(d) = app.ui.dialogs.iter().find(|d| d.id == parent) else { return }; + let before = Before::Field { parent, field: field.into(), fields: d.fields.clone() }; + app.color_picker_live.push(Live { picker, before, shown: None }); +} + +/// Preview picker `picker` in the Crop shield's custom colour. +pub(super) fn begin_crop_shield(app: &mut PhotocraftApp, picker: u64) { + let s = &app.ui.tool_options.crop_shield; + let before = Before::CropShield { color: s.color, custom: s.custom_color }; + app.color_picker_live.push(Live { picker, before, shown: None }); +} + +/// The dialogs whose fields an open picker is previewing in: they record no ⌘Z step meanwhile +/// (`edit_history`), so a Cancel leaves no trace and an OK is one step. +pub(crate) fn previewed_dialogs(app: &PhotocraftApp) -> Vec { + app.color_picker_live + .iter() + .filter_map(|l| match l.before { + Before::Field { parent, .. } => Some(parent), + Before::CropShield { .. } => None, + }) + .collect() +} + +/// The colour to show for picker `picker`: `Some(None)` while it is the one it opened on (or not +/// a colour), `None` once the picker is closed. +fn picked(app: &PhotocraftApp, picker: u64) -> Option> { + let d = app.ui.dialogs.iter().find(|d| d.id == picker)?; + let colour = |key: &str| d.fields.get(key).and_then(Value::as_str).and_then(parse_hex).map(hex); + let (color, orig) = (colour("color"), colour("__orig")); + Some(color.filter(|c| orig.as_ref() != Some(c))) +} + +/// Show `color` in the target, or what it was (`None`). `Err` when the target is gone. +fn show(app: &mut PhotocraftApp, before: &Before, color: Option<&str>) -> Result<(), String> { + match before { + Before::Field { parent, field, fields } => { + let mut shown = fields.clone(); + if let Some(c) = color { + set_field(&mut shown, field, json!(c))?; + } + app.ui.dialog_mut(*parent).ok_or("the dialog this colour was for is closed")?.fields = shown; + } + Before::CropShield { color: was, custom } => match color { + Some(c) => crate::crop_shield::set_custom_color(app, c)?, + None => { + let s = &mut app.ui.tool_options.crop_shield; + (s.color, s.custom_color) = (*was, *custom); + } + }, + } + Ok(()) +} + +/// Show each open picker's colour in its target, and put back the target of a picker that closed +/// without [`end`]. True when a target changed (the caller repaints, so the parent redraws). +pub(crate) fn sync(app: &mut PhotocraftApp) -> bool { + if app.color_picker_live.is_empty() { + return false; + } + let mut live = std::mem::take(&mut app.color_picker_live); + let mut changed = false; + live.retain_mut(|l| { + let Some(color) = picked(app, l.picker) else { + if l.shown.is_some() { + changed |= show(app, &l.before, None).is_ok(); + } + return false; + }; + if color == l.shown { + return true; + } + // A target that is gone (its dialog closed) stops the preview. + if show(app, &l.before, color.as_deref()).is_err() { + return false; + } + l.shown = color; + changed = true; + true + }); + live.append(&mut app.color_picker_live); + app.color_picker_live = live; + changed +} + +/// Picker `picker` is closing (OK or Cancel): put its target back as it was when it opened and +/// stop previewing. OK then sets the target as it always has. +pub(crate) fn end(app: &mut PhotocraftApp, picker: u64) { + let Some(i) = app.color_picker_live.iter().position(|l| l.picker == picker) else { return }; + let l = app.color_picker_live.remove(i); + if l.shown.is_some() { + let _ = show(app, &l.before, None); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/color_picker_ui/live_preview/tests.rs b/crates/ui-egui/src/dialogs/color_picker_ui/live_preview/tests.rs new file mode 100644 index 0000000000..7710b0ea52 --- /dev/null +++ b/crates/ui-egui/src/dialogs/color_picker_ui/live_preview/tests.rs @@ -0,0 +1,261 @@ +use egui::vec2; +use egui_kittest::Harness; +use serde_json::{Map, Value, json}; + +use super::*; +use crate::color_picker_ui::{open_for_field, open_requested, request}; +use crate::crop_shield::ShieldColor; +use crate::state::DialogKind; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 16, "height": 12})).unwrap(); + app +} + +fn fields(app: &PhotocraftApp, id: u64) -> &Map { + &app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields +} + +fn past(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +/// The Picker's colour changes, as a drag in it or `ui.dialog.set` changes it, and a frame passes. +fn pick(app: &mut PhotocraftApp, picker: u64, color: &str) { + app.ui.dialog_mut(picker).unwrap().fields.insert("color".into(), json!(color)); + sync(app); +} + +/// Edit › Fill on Color…, with its Color Picker open over it as its Color… choice opens it. +fn fill_with_picker(app: &mut PhotocraftApp) -> (u64, u64) { + let fill = crate::fill_ui::open(app); + let f = &mut app.ui.dialog_mut(fill).unwrap().fields; + f.insert("contents".into(), json!("color")); + f.insert("color".into(), json!("#20a040")); + request(f, "Color Picker (Fill Color)"); + open_requested(app, fill); + let picker = crate::color_picker_ui::top(app).expect("the picker opens over the Fill dialog"); + (fill, picker) +} + +/// #9886: the Fill dialog's colour follows the picker before OK, Cancel puts back exactly what +/// the dialog held, and nothing reaches the document's History. +#[test] +fn a_dialog_colour_follows_the_picker_and_cancel_restores_it() { + let mut app = app(); + let (fill, picker) = fill_with_picker(&mut app); + let before = fields(&app, fill).clone(); + for color in ["#336699", "#ff0000", "#00ff00"] { + pick(&mut app, picker, color); + assert_eq!(fields(&app, fill)["color"], json!(color), "shown before OK"); + } + assert_eq!(past(&app), 0, "previewing makes no history step"); + crate::dialogs::cancel(&mut app, picker).unwrap(); + assert_eq!(fields(&app, fill), &before, "Cancel puts the dialog back as it was"); + assert!(app.color_picker_live.is_empty()); + assert_eq!(past(&app), 0); +} + +/// OK keeps the colour in the dialog, still without a history step; the dialog's own OK then +/// makes exactly one, with the picked colour. +#[test] +fn ok_keeps_the_colour_and_the_dialog_makes_one_history_step() { + let mut app = app(); + let (fill, picker) = fill_with_picker(&mut app); + pick(&mut app, picker, "#ff0000"); + pick(&mut app, picker, "#336699"); + crate::dialogs::confirm(&mut app, picker).unwrap(); + assert_eq!(fields(&app, fill)["color"], json!("#336699")); + assert!(app.color_picker_live.is_empty()); + assert_eq!(past(&app), 0, "the picker's OK only sets the dialog's colour"); + crate::dialogs::confirm(&mut app, fill).unwrap(); + assert_eq!(past(&app), 1, "one step for the Fill"); + let st = app.session.active().unwrap(); + let c = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(3, 3); + let want = [0x33 as f32 / 255.0, 0x66 as f32 / 255.0, 0x99 as f32 / 255.0]; + assert!((0..3).all(|i| (c[i] - want[i]).abs() < 1.5 / 255.0), "{c:?}"); +} + +/// Back on the colour it opened on, the target shows what it held, even a value that is not a +/// hex colour; a picker that never changes leaves it alone. +#[test] +fn the_opening_colour_shows_the_original_value() { + let mut app = app(); + let mut f = Map::new(); + f.insert("background".into(), json!("white")); + f.insert("other".into(), json!(3)); + let parent = app.ui.open_dialog(DialogKind::Command, f); + let before = fields(&app, parent).clone(); + let picker = open_for_field(&mut app, "Color Picker (Background Contents)", [1.0; 3], parent, "background"); + assert!(!sync(&mut app), "nothing to show yet"); + assert_eq!(fields(&app, parent), &before); + pick(&mut app, picker, "#808080"); + assert_eq!(fields(&app, parent)["background"], json!("#808080")); + pick(&mut app, picker, "#ffffff"); + assert_eq!(fields(&app, parent), &before, "the opening colour shows the original value"); + // Not a colour (a half-typed value from automation): the original value too. + pick(&mut app, picker, "#12"); + assert_eq!(fields(&app, parent), &before); +} + +/// A dialog that derives other settings from the shown colour (Replace Color's Result sets the +/// sliders and drops the colour) builds each preview on the settings it had, and Cancel undoes +/// what it derived. +#[test] +fn derived_settings_are_rebuilt_from_the_opening_ones() { + let mut app = app(); + let mut f = Map::new(); + f.insert("picked".into(), json!("#000000")); + f.insert("hue".into(), json!(0)); + let parent = app.ui.open_dialog(DialogKind::Command, f); + let before = fields(&app, parent).clone(); + let picker = open_for_field(&mut app, "Color Picker (Result)", [0.0; 3], parent, "picked"); + // The dialog's body consumes the colour each frame, as Replace Color's does. + let consume = |app: &mut PhotocraftApp| { + let f = &mut app.ui.dialog_mut(parent).unwrap().fields; + let picked = f.remove("picked").unwrap(); + let hue = f["hue"].as_i64().unwrap(); + f.insert("hue".into(), json!(hue + i64::from(picked != json!("#000000")))); + }; + pick(&mut app, picker, "#ff0000"); + consume(&mut app); + pick(&mut app, picker, "#00ff00"); + assert_eq!(fields(&app, parent)["hue"], json!(0), "rebuilt from the opening settings, not the last preview"); + assert_eq!(fields(&app, parent)["picked"], json!("#00ff00")); + consume(&mut app); + crate::dialogs::cancel(&mut app, picker).unwrap(); + assert_eq!(fields(&app, parent), &before); +} + +/// A picker closed without Cancel (a document closed, a parent cancelled) never leaves its +/// colour behind, and a closed parent ends the preview without an error or a panic. +#[test] +fn a_picker_or_parent_closed_any_other_way_ends_the_preview() { + let mut app = app(); + let (fill, picker) = fill_with_picker(&mut app); + let before = fields(&app, fill).clone(); + pick(&mut app, picker, "#336699"); + app.ui.close_dialog(picker); + assert!(sync(&mut app)); + assert_eq!(fields(&app, fill), &before); + assert!(app.color_picker_live.is_empty()); + + let (fill, picker) = fill_with_picker(&mut app); + pick(&mut app, picker, "#336699"); + crate::dialogs::cancel(&mut app, fill).unwrap(); + pick(&mut app, picker, "#ff0000"); + assert!(app.color_picker_live.is_empty(), "the preview ends with its dialog"); + assert!(crate::dialogs::confirm(&mut app, picker).is_err(), "OK reports the closed dialog"); + assert_eq!(past(&app), 0); +} + +/// The dialog under a picker can't be confirmed (by automation) with a colour the picker still +/// only shows. +#[test] +fn the_dialog_waits_for_its_picker() { + let mut app = app(); + let (fill, picker) = fill_with_picker(&mut app); + pick(&mut app, picker, "#336699"); + assert!(crate::dialogs::confirm(&mut app, fill).is_err()); + assert_eq!(past(&app), 0); + assert!(app.ui.dialogs.iter().any(|d| d.id == fill), "the dialog stays open"); +} + +/// The dialog's own ⌘Z history records no step for a previewed colour: none after Cancel, one +/// after OK. +#[test] +fn a_previewed_colour_is_no_dialog_undo_step() { + let ctx = egui::Context::default(); + let mut app = app(); + let (fill, picker) = fill_with_picker(&mut app); + crate::edit_history::track_dialogs(&mut app, &ctx); + let undo = |app: &mut PhotocraftApp| { + let mut now: Map = fields(app, fill).iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); + app.dialog_edits.get_mut(&fill).unwrap().step(&mut now, crate::edit_history::Step::Undo).then_some(now) + }; + for color in ["#336699", "#ff0000"] { + pick(&mut app, picker, color); + crate::edit_history::track_dialogs(&mut app, &ctx); + } + crate::dialogs::cancel(&mut app, picker).unwrap(); + crate::edit_history::track_dialogs(&mut app, &ctx); + assert_eq!(undo(&mut app), None, "Cancel leaves nothing to undo"); + + request(&mut app.ui.dialog_mut(fill).unwrap().fields, "Color Picker (Fill Color)"); + open_requested(&mut app, fill); + let picker = crate::color_picker_ui::top(&app).unwrap(); + for color in ["#336699", "#ff0000"] { + pick(&mut app, picker, color); + crate::edit_history::track_dialogs(&mut app, &ctx); + } + crate::dialogs::confirm(&mut app, picker).unwrap(); + crate::edit_history::track_dialogs(&mut app, &ctx); + let back = undo(&mut app).expect("OK is one step"); + assert_eq!(back["color"], json!("#20a040"), "straight back to the colour before the picker"); +} + +/// The Crop shield's custom colour follows its picker; Cancel restores the colour and the +/// Match Canvas choice, OK keeps the custom one. +#[test] +fn the_crop_shield_colour_follows_its_picker() { + let mut app = app(); + app.ui.tool_options.crop_shield.custom_color = [10, 20, 30]; + let before = app.ui.tool_options.crop_shield.clone(); + assert_eq!(before.color, ShieldColor::MatchCanvas); + let picker = crate::crop_shield::pick_custom_color(&mut app); + pick(&mut app, picker, "#336699"); + let s = &app.ui.tool_options.crop_shield; + assert_eq!((s.color, s.custom_color), (ShieldColor::Custom, [0x33, 0x66, 0x99]), "shown before OK"); + crate::dialogs::cancel(&mut app, picker).unwrap(); + assert_eq!(app.ui.tool_options.crop_shield, before); + + let picker = crate::crop_shield::pick_custom_color(&mut app); + pick(&mut app, picker, "#ff0000"); + pick(&mut app, picker, "#336699"); + crate::dialogs::confirm(&mut app, picker).unwrap(); + let s = &app.ui.tool_options.crop_shield; + assert_eq!((s.color, s.custom_color), (ShieldColor::Custom, [0x33, 0x66, 0x99])); + assert!(app.color_picker_live.is_empty()); + assert_eq!(past(&app), 0); +} + +/// Agents: `ui.dialog.set` on the picker shows the colour in the dialog at once, and +/// `ui.dialog.cancel` puts it back. +#[test] +fn control_edits_preview_at_once() { + let ctx = egui::Context::default(); + let mut app = app(); + let (fill, picker) = fill_with_picker(&mut app); + let call = |app: &mut PhotocraftApp, method: &str, params: Value| { + let (req, _rx) = crate::control::ControlRequest::new(method, params); + match crate::control::handle(app, &ctx, &req) { + crate::control::Outcome::Done(v) => v, + _ => panic!("{method}: expected an immediate reply"), + } + }; + let r = call(&mut app, "ui.dialog.set", json!({"dialog": picker, "field": "color", "value": "#336699"})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(fields(&app, fill)["color"], json!("#336699")); + assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": fill}))["ok"], false, "the picker answers first"); + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": picker}))["ok"], true); + assert_eq!(fields(&app, fill)["color"], json!("#20a040")); +} + +/// In the running dialogs: a colour typed into the picker shows in the Fill dialog's swatch field +/// before OK, and Esc (the picker's Cancel) puts it back. +#[test] +fn the_dialog_shows_the_colour_while_the_picker_is_open() { + let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).with_max_steps(64).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app()); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let (fill, picker) = fill_with_picker(h.state_mut()); + h.run_steps(3); + h.state_mut().ui.dialog_mut(picker).unwrap().fields.insert("color".into(), json!("#336699")); + h.run_steps(3); + assert_eq!(fields(h.state(), fill)["color"], json!("#336699")); + assert_eq!(past(h.state()), 0); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert_eq!(crate::color_picker_ui::top(h.state()), None); + assert_eq!(fields(h.state(), fill)["color"], json!("#20a040")); +} diff --git a/crates/ui-egui/src/dialogs/edit_history.rs b/crates/ui-egui/src/dialogs/edit_history.rs index 2012f912c7..dfc161e202 100644 --- a/crates/ui-egui/src/dialogs/edit_history.rs +++ b/crates/ui-egui/src/dialogs/edit_history.rs @@ -86,11 +86,13 @@ pub type DialogEdits = HashMap>>; /// Once a frame: records each open parameter dialog's settings and forgets closed dialogs. pub fn track_dialogs(app: &mut PhotocraftApp, ctx: &egui::Context) { let busy = ctx.input(|i| i.pointer.any_down()); + // A colour an open Color Picker only shows in a dialog is no step of it until the picker's OK. + let previewed = crate::color_picker_ui::live_preview::previewed_dialogs(app); let dialogs = &app.ui.dialogs; app.dialog_edits.retain(|id, _| dialogs.iter().any(|d| d.id == *id)); for d in dialogs.iter().filter(|d| d.kind == DialogKind::Command) { let now = settings(&d.fields); - app.dialog_edits.entry(d.id).or_insert_with(|| EditHistory::new(&now)).settle(&now, busy); + app.dialog_edits.entry(d.id).or_insert_with(|| EditHistory::new(&now)).settle(&now, busy || previewed.contains(&d.id)); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 67b54ef73e..7cfd20eaf5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -548,6 +548,9 @@ pub struct PhotocraftApp { pub(crate) wide_angle: Option, /// ⌘Z history of each open parameter dialog (edit_history). pub(crate) dialog_edits: edit_history::DialogEdits, + /// What each open Color Picker's live target was when it opened, to put back on Cancel + /// (`color_picker_ui::live_preview`). + pub(crate) color_picker_live: Vec, /// The filter a "Rasterize?" prompt answered for, run after the dialog closes, where the /// egui context is available again (rasterize_prompt). pub(crate) pending_after_prompt: Option<(String, serde_json::Value)>, diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4490d693c2..3b8181fe1c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; 12 of 181 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (a Color Picker for another dialog's colour or the Crop shield shows the picked colour there before OK, #9886; New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; 12 of 181 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -226,6 +226,7 @@ Paragraph; the rest open as in-app floating windows. | Docked resize pushes the neighbour | partial | #2573 | | Color panel modes from its panel menu (Hue Cube, Brightness Cube, Color Wheel, Grayscale/RGB/HSB/CMYK/Lab/Web Color sliders), colour ramp (RGB/CMYK Spectrum, Grayscale Ramp, Current Colors, Make Ramp Web Safe; Shift-click cycles, Alt-click picks the other colour), Copy Color as HTML / Hex Code; the out-of-gamut ⚠ with the nearest printable colour under the chips (sliders always; the cubes when the field is at least 53 pt tall); the same in every theme | done | `color_panel_ui.rs`, `color_panel_tests.rs`; UI-217-17, #2569, #6000, #8672 | | A colour picked in the Color or Swatches panel or the Color Picker recolours the selection: selected characters while editing; every selected type layer with a Type tool; every selected shape's fill with a shape, Pen or path selection tool; only the foreground with other tools, the Move tool too; a swatch click recolours the selected type layers and shape fills whatever the tool (#9238); one history step (a Color panel drag too) | done: `apply_color.rs`, `apply_color_tests.rs` | | +| A Color Picker opened for another dialog's colour (Edit › Fill's Color…, Edit › Stroke, a filter's or adjustment's colour, Replace Color's Result, New Document, New Guide and guide layout colours, channel and spot colours, Preferences) or for the Crop shield's custom colour shows the colour under the cursor there before OK, as in Photoshop, so the dialog's swatch and its own preview follow it; Cancel puts back exactly what was there, OK keeps it without a history step of its own (the dialog's OK makes the one step), and the dialog's ⌘Z history records only the picker's OK (#9886) | partial | `dialogs/color_picker_ui/live_preview.rs`, `dialogs/color_picker_ui/live_preview/tests.rs`; differs: the pickers whose OK runs a command without a preview of its own (text colour and gradient stops, open in #9757; gradient preset stops, artboard background, count group colour) and the pasteboard's custom colour show the colour only after OK | | Window size and dock width remembered | done | UI-217-2 | | Histogram panel: Compact (the default, of the entire image), Expanded and All Channels views (the channel kept across them); RGB/CMYK/Lab/Gray channels, Luminosity and Colors (overlaid, mixed where they overlap); Show Channels in Color and Show Statistics; Source (Entire Image, Selected Layer, Adjustment Composite) for multilayer documents; Mean, Std Dev, Median, Pixels, Level, Count, Percentile and Cache Level for the pointer level or a dragged range; the cached-data warning, Uncached Refresh (menu, button, warning click, double-click); the adjusted histogram over the original while an adjustment previews; Cache Levels 1–8 in Preferences › Performance; Color Sampler levels marked on the graph | partial | `histogram_panel.rs`, `histogram_panel_tests.rs`, `tone.rs`; differs: filter dialogs that preview on the CPU proxy aren't counted live, a selection doesn't limit the histogram yet, with Source Selected Layer an adjustment dialog's preview isn't counted, and new strings are English-only so far | | Command palette with recents | done | UI-217-7 | @@ -323,3 +324,4 @@ Paragraph; the rest open as in-app floating windows. | 2026-10-14 | minor | ⇧⌥ + letter blend mode keys for the painting tool or every selected layer; ⇧+ / ⇧− now step every selected layer and include Clear for Brush and Pencil | | 2026-10-15 | minor | ⇧⌥ blend mode letters work while a Free Transform box is open, without picking a tool | | 2026-10-14 | minor | Mode dropdowns for Clone Stamp, Pattern Stamp, History Brush, Healing and Paint Bucket; the blend mode keys reach them, and tools without a blend mode (not Dodge, Burn or Sponge) pass the keys to the layers | +| 2026-10-28 | minor | A Color Picker for another dialog's colour field (Fill, Stroke, filters, guides, channels, Preferences…) or the Crop shield's custom colour shows the colour there before OK; Cancel restores it (#9886); no percentage changed | From ead06c032da4738c1edf4ea3663892f83878a09f Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 2 Nov 2026 08:28:48 +0100 Subject: [PATCH 2/3] fix(ui): close field Color Pickers with their dialog, guard previewed dialogs (#9979 review) Follow-up to the CodeRabbit review of the live Color Picker preview: - Cancelling a dialog now also closes its field Color Pickers (found by `__dialog` or by the live preview's record of the parent). Before, the picker stayed open and its OK failed with "the dialog this colour was for is closed". - confirm_preflight also refuses a dialog that a live preview records as its parent, so rewriting a picker's `__dialog` through automation no longer lets the parent commit a colour the picker can still cancel. - ui.dialog.set on a dialog under a previewing picker is refused until the picker's OK or Cancel, since closing the picker puts the whole dialog back as it was when the picker opened. - The Crop shield preview adopts a shield colour set elsewhere (ui.set) while its picker is open, so Cancel no longer reverts it. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/control/dispatch.rs | 4 ++ crates/ui-egui/src/dialogs.rs | 14 ++++- .../dialogs/color_picker_ui/live_preview.rs | 55 +++++++++++++------ .../color_picker_ui/live_preview/tests.rs | 46 +++++++++++++++- 4 files changed, 99 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index c2391e06bd..89ac0d0825 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -1019,10 +1019,14 @@ fn discard_dialog_confirm(app: &mut PhotocraftApp, ctx: &egui::Context, choice: fn dialog_set(app: &mut PhotocraftApp, p: &Value) -> Outcome { let (Some(id), Some(field)) = (u64_param(p, "dialog"), str_param(p, "field")) else { return err("need `dialog` and `field`") }; let value = p.get("value").cloned().unwrap_or(Value::Null); + // A Color Picker previewing in this dialog owns its fields until its OK or Cancel: an edit now + // would be undone by the picker putting the dialog back as it was. + let previewed = crate::color_picker_ui::live_preview::previewed_dialogs(app).contains(&id); match app.ui.dialog_mut(id) { // A continuation belongs to the dialog that paused it, even when another // action has a valid token. Replacing it would resume or cancel that action. Some(_) if field == crate::actions::RESUME => err("the paused action token is read-only"), + Some(_) if previewed => err("confirm or cancel the color picker first"), // A marker picks the handler OK runs: a dialog keeps the ones it was opened with. Some(d) if !d.fields.contains_key(field) && crate::dialogs::is_route_marker(field) => err(format!("`{field}` is set only by the dialog it belongs to")), Some(d) => { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1ad577011c..c85ab8dd61 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -981,7 +981,10 @@ fn confirm_preflight(app: &mut PhotocraftApp, id: u64) -> Result<(), String> { } // A colour field shows the open picker's colour before its OK (`live_preview`): the dialog // would otherwise commit a colour the picker may still cancel. - if app.ui.dialogs.iter().any(|child| crate::color_picker_ui::owns(&child.fields) && child.fields.get("__dialog").and_then(Value::as_u64) == Some(id)) { + // The live preview's own record of the parent counts too: automation may rewrite `__dialog`. + if app.ui.dialogs.iter().any(|child| crate::color_picker_ui::owns(&child.fields) && child.fields.get("__dialog").and_then(Value::as_u64) == Some(id)) + || crate::color_picker_ui::live_preview::previewed_dialogs(app).contains(&id) + { return Err("confirm or cancel the color picker first".into()); } if let Some(d) = app.ui.dialogs.iter().find(|d| d.id == id).filter(|d| crate::guide_layout_ui::owns(&d.fields)) { @@ -1068,6 +1071,15 @@ pub fn cancel(app: &mut PhotocraftApp, id: u64) -> Result { let closed = app.ui.close_dialog(id).ok_or_else(|| format!("no dialog {id}"))?; // A Color Picker puts back what its live preview showed in its target. crate::color_picker_ui::live_preview::end(app, id); + // A field Color Picker of this dialog has no target left: it closes with the dialog. + let mut pickers = crate::color_picker_ui::live_preview::pickers_of(app, id); + pickers.extend( + app.ui.dialogs.iter().filter(|d| crate::color_picker_ui::owns(&d.fields) && d.fields.get("__dialog").and_then(Value::as_u64) == Some(id)).map(|d| d.id), + ); + for picker in &pickers { + crate::color_picker_ui::live_preview::end(app, *picker); + } + app.ui.dialogs.retain(|d| !pickers.contains(&d.id)); crate::actions::stopped(app, &closed.fields); if crate::guide_layout_ui::owns(&closed.fields) { app.ui.dialogs.retain(|child| child.fields.get("__dialog").and_then(Value::as_u64) != Some(id)); diff --git a/crates/ui-egui/src/dialogs/color_picker_ui/live_preview.rs b/crates/ui-egui/src/dialogs/color_picker_ui/live_preview.rs index 361506142c..ae2035ed0f 100644 --- a/crates/ui-egui/src/dialogs/color_picker_ui/live_preview.rs +++ b/crates/ui-egui/src/dialogs/color_picker_ui/live_preview.rs @@ -60,7 +60,12 @@ pub(crate) fn previewed_dialogs(app: &PhotocraftApp) -> Vec { .collect() } -/// The colour to show for picker `picker`: `Some(None)` while it is the one it opened on (or not +/// The field pickers previewing in dialog `parent`: they close with it. +pub(crate) fn pickers_of(app: &PhotocraftApp, parent: u64) -> Vec { + app.color_picker_live.iter().filter(|l| matches!(l.before, Before::Field { parent: p, .. } if p == parent)).map(|l| l.picker).collect() +} + +/// The colour picker `picker` shows: `Some(None)` while it is the one it opened on (or not /// a colour), `None` once the picker is closed. fn picked(app: &PhotocraftApp, picker: u64) -> Option> { let d = app.ui.dialogs.iter().find(|d| d.id == picker)?; @@ -69,23 +74,41 @@ fn picked(app: &PhotocraftApp, picker: u64) -> Option> { Some(color.filter(|c| orig.as_ref() != Some(c))) } -/// Show `color` in the target, or what it was (`None`). `Err` when the target is gone. -fn show(app: &mut PhotocraftApp, before: &Before, color: Option<&str>) -> Result<(), String> { +/// `"#rrggbb"` as the Crop shield stores it. +fn shield_rgb(color: &str) -> Option<[u8; 3]> { + parse_hex(color).map(|c| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)) +} + +/// Show `color` in the target, or what it was (`None`), where it shows `shown` now. `Err` when +/// the target is gone. +fn show(app: &mut PhotocraftApp, before: &mut Before, shown: Option<&str>, color: Option<&str>) -> Result<(), String> { match before { Before::Field { parent, field, fields } => { - let mut shown = fields.clone(); + let mut next = fields.clone(); if let Some(c) = color { - set_field(&mut shown, field, json!(c))?; + set_field(&mut next, field, json!(c))?; } - app.ui.dialog_mut(*parent).ok_or("the dialog this colour was for is closed")?.fields = shown; + app.ui.dialog_mut(*parent).ok_or("the dialog this colour was for is closed")?.fields = next; } - Before::CropShield { color: was, custom } => match color { - Some(c) => crate::crop_shield::set_custom_color(app, c)?, - None => { - let s = &mut app.ui.tool_options.crop_shield; - (s.color, s.custom_color) = (*was, *custom); + Before::CropShield { color: was, custom } => { + // A shield colour set elsewhere while the picker is open (`ui.set`) is what Cancel + // puts back, not the one the picker opened on. + let s = &app.ui.tool_options.crop_shield; + let expected = match shown { + Some(c) => (ShieldColor::Custom, shield_rgb(c)), + None => (*was, Some(*custom)), + }; + if (s.color, Some(s.custom_color)) != expected { + (*was, *custom) = (s.color, s.custom_color); } - }, + match color { + Some(c) => crate::crop_shield::set_custom_color(app, c)?, + None => { + let s = &mut app.ui.tool_options.crop_shield; + (s.color, s.custom_color) = (*was, *custom); + } + } + } } Ok(()) } @@ -101,7 +124,7 @@ pub(crate) fn sync(app: &mut PhotocraftApp) -> bool { live.retain_mut(|l| { let Some(color) = picked(app, l.picker) else { if l.shown.is_some() { - changed |= show(app, &l.before, None).is_ok(); + changed |= show(app, &mut l.before, l.shown.as_deref(), None).is_ok(); } return false; }; @@ -109,7 +132,7 @@ pub(crate) fn sync(app: &mut PhotocraftApp) -> bool { return true; } // A target that is gone (its dialog closed) stops the preview. - if show(app, &l.before, color.as_deref()).is_err() { + if show(app, &mut l.before, l.shown.as_deref(), color.as_deref()).is_err() { return false; } l.shown = color; @@ -125,9 +148,9 @@ pub(crate) fn sync(app: &mut PhotocraftApp) -> bool { /// stop previewing. OK then sets the target as it always has. pub(crate) fn end(app: &mut PhotocraftApp, picker: u64) { let Some(i) = app.color_picker_live.iter().position(|l| l.picker == picker) else { return }; - let l = app.color_picker_live.remove(i); + let mut l = app.color_picker_live.remove(i); if l.shown.is_some() { - let _ = show(app, &l.before, None); + let _ = show(app, &mut l.before, l.shown.as_deref(), None); } } diff --git a/crates/ui-egui/src/dialogs/color_picker_ui/live_preview/tests.rs b/crates/ui-egui/src/dialogs/color_picker_ui/live_preview/tests.rs index 7710b0ea52..f1d277fb8e 100644 --- a/crates/ui-egui/src/dialogs/color_picker_ui/live_preview/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker_ui/live_preview/tests.rs @@ -141,27 +141,67 @@ fn a_picker_or_parent_closed_any_other_way_ends_the_preview() { assert_eq!(fields(&app, fill), &before); assert!(app.color_picker_live.is_empty()); + // A cancelled dialog takes its field picker with it, leaving no picker whose OK has no target. let (fill, picker) = fill_with_picker(&mut app); + let other = open_for_field(&mut app, "Color Picker (Other)", [0.0; 3], 999_999, "color"); pick(&mut app, picker, "#336699"); crate::dialogs::cancel(&mut app, fill).unwrap(); - pick(&mut app, picker, "#ff0000"); + assert!(app.ui.dialogs.iter().all(|d| d.id != picker), "the picker closes with its dialog"); + assert!(app.ui.dialogs.iter().any(|d| d.id == other), "another dialog's picker stays"); assert!(app.color_picker_live.is_empty(), "the preview ends with its dialog"); - assert!(crate::dialogs::confirm(&mut app, picker).is_err(), "OK reports the closed dialog"); assert_eq!(past(&app), 0); } /// The dialog under a picker can't be confirmed (by automation) with a colour the picker still -/// only shows. +/// only shows, even when the picker's `__dialog` was rewritten to point elsewhere. #[test] fn the_dialog_waits_for_its_picker() { let mut app = app(); let (fill, picker) = fill_with_picker(&mut app); pick(&mut app, picker, "#336699"); assert!(crate::dialogs::confirm(&mut app, fill).is_err()); + app.ui.dialog_mut(picker).unwrap().fields.insert("__dialog".into(), json!(999_999)); + assert!(crate::dialogs::confirm(&mut app, fill).is_err(), "the live preview's record of the dialog counts"); assert_eq!(past(&app), 0); assert!(app.ui.dialogs.iter().any(|d| d.id == fill), "the dialog stays open"); } +/// Automation can't edit a dialog under a previewing picker: Cancel would put the edit back. +#[test] +fn the_dialog_under_a_picker_refuses_control_edits() { + let ctx = egui::Context::default(); + let mut app = app(); + let (fill, picker) = fill_with_picker(&mut app); + let (req, _rx) = crate::control::ControlRequest::new("ui.dialog.set", json!({"dialog": fill, "field": "opacity", "value": 50})); + let crate::control::Outcome::Done(r) = crate::control::handle(&mut app, &ctx, &req) else { panic!("an immediate reply") }; + assert_eq!(r["ok"], false, "{r}"); + assert_eq!(fields(&app, fill)["opacity"], json!(100.0)); + crate::dialogs::cancel(&mut app, picker).unwrap(); + let (req, _rx) = crate::control::ControlRequest::new("ui.dialog.set", json!({"dialog": fill, "field": "opacity", "value": 50})); + let crate::control::Outcome::Done(r) = crate::control::handle(&mut app, &ctx, &req) else { panic!("an immediate reply") }; + assert_eq!(r["ok"], true, "{r}"); +} + +/// A shield colour set elsewhere (`ui.set cropShield`) while its picker is open survives the +/// picker's Cancel. +#[test] +fn the_crop_shield_keeps_a_colour_set_while_its_picker_is_open() { + let mut app = app(); + let picker = crate::crop_shield::pick_custom_color(&mut app); + pick(&mut app, picker, "#336699"); + app.ui.tool_options.crop_shield.custom_color = [1, 2, 3]; + crate::dialogs::cancel(&mut app, picker).unwrap(); + let s = &app.ui.tool_options.crop_shield; + assert_eq!((s.color, s.custom_color), (ShieldColor::Custom, [1, 2, 3])); + + let picker = crate::crop_shield::pick_custom_color(&mut app); + app.ui.tool_options.crop_shield.color = ShieldColor::MatchCanvas; + pick(&mut app, picker, "#ff0000"); + crate::dialogs::cancel(&mut app, picker).unwrap(); + let s = &app.ui.tool_options.crop_shield; + assert_eq!((s.color, s.custom_color), (ShieldColor::MatchCanvas, [1, 2, 3]), "Cancel puts back the choice made while it was open"); +} + /// The dialog's own ⌘Z history records no step for a previewed colour: none after Cancel, one /// after OK. #[test] From c02842e8f57a0101cfbf6ac86cee8bf741455c13 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 2 Nov 2026 09:19:45 +0100 Subject: [PATCH 3/3] fix(ui): keep a Color Picker's target fixed while it is open (#9979 review) - ui.dialog.set refuses `__dialog` and `__field` on an open Color Picker. Otherwise automation could point the picker's OK at another dialog than the one its live preview showed the colour in. - Cancelling a dialog closes only the field pickers the live preview records for it. A `__dialog` match counts only for a picker without a live record, so a rewritten `__dialog` can no longer close another dialog's picker and put that dialog back as it was. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/control/dispatch.rs | 2 ++ crates/ui-egui/src/dialogs.rs | 9 ++++++- .../dialogs/color_picker_ui/live_preview.rs | 6 +++++ .../color_picker_ui/live_preview/tests.rs | 25 +++++++++++++++++++ 4 files changed, 41 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index 89ac0d0825..cd81f10586 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -1027,6 +1027,8 @@ fn dialog_set(app: &mut PhotocraftApp, p: &Value) -> Outcome { // action has a valid token. Replacing it would resume or cancel that action. Some(_) if field == crate::actions::RESUME => err("the paused action token is read-only"), Some(_) if previewed => err("confirm or cancel the color picker first"), + // A Color Picker's target is fixed when it opens: OK must set the field it previewed in. + Some(d) if matches!(field, "__dialog" | "__field") && crate::color_picker_ui::owns(&d.fields) => err("a Color Picker's target is fixed when it opens"), // A marker picks the handler OK runs: a dialog keeps the ones it was opened with. Some(d) if !d.fields.contains_key(field) && crate::dialogs::is_route_marker(field) => err(format!("`{field}` is set only by the dialog it belongs to")), Some(d) => { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index c85ab8dd61..7716a408ed 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1072,9 +1072,16 @@ pub fn cancel(app: &mut PhotocraftApp, id: u64) -> Result { // A Color Picker puts back what its live preview showed in its target. crate::color_picker_ui::live_preview::end(app, id); // A field Color Picker of this dialog has no target left: it closes with the dialog. + // A picker with a live target goes by the parent recorded when it opened; `__dialog` only + // names the parent of one without (e.g. its parent was closed before it could preview). let mut pickers = crate::color_picker_ui::live_preview::pickers_of(app, id); pickers.extend( - app.ui.dialogs.iter().filter(|d| crate::color_picker_ui::owns(&d.fields) && d.fields.get("__dialog").and_then(Value::as_u64) == Some(id)).map(|d| d.id), + app.ui + .dialogs + .iter() + .filter(|d| crate::color_picker_ui::owns(&d.fields) && d.fields.get("__dialog").and_then(Value::as_u64) == Some(id)) + .filter(|d| !crate::color_picker_ui::live_preview::previews(app, d.id)) + .map(|d| d.id), ); for picker in &pickers { crate::color_picker_ui::live_preview::end(app, *picker); diff --git a/crates/ui-egui/src/dialogs/color_picker_ui/live_preview.rs b/crates/ui-egui/src/dialogs/color_picker_ui/live_preview.rs index ae2035ed0f..dbf4455fc1 100644 --- a/crates/ui-egui/src/dialogs/color_picker_ui/live_preview.rs +++ b/crates/ui-egui/src/dialogs/color_picker_ui/live_preview.rs @@ -65,6 +65,12 @@ pub(crate) fn pickers_of(app: &PhotocraftApp, parent: u64) -> Vec { app.color_picker_live.iter().filter(|l| matches!(l.before, Before::Field { parent: p, .. } if p == parent)).map(|l| l.picker).collect() } +/// Whether picker `picker` has a live target: then its parent is the one recorded here, not its +/// `__dialog` field, which automation could have rewritten. +pub(crate) fn previews(app: &PhotocraftApp, picker: u64) -> bool { + app.color_picker_live.iter().any(|l| l.picker == picker) +} + /// The colour picker `picker` shows: `Some(None)` while it is the one it opened on (or not /// a colour), `None` once the picker is closed. fn picked(app: &PhotocraftApp, picker: u64) -> Option> { diff --git a/crates/ui-egui/src/dialogs/color_picker_ui/live_preview/tests.rs b/crates/ui-egui/src/dialogs/color_picker_ui/live_preview/tests.rs index f1d277fb8e..1a3b852f9f 100644 --- a/crates/ui-egui/src/dialogs/color_picker_ui/live_preview/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker_ui/live_preview/tests.rs @@ -299,3 +299,28 @@ fn the_dialog_shows_the_colour_while_the_picker_is_open() { assert_eq!(crate::color_picker_ui::top(h.state()), None); assert_eq!(fields(h.state(), fill)["color"], json!("#20a040")); } + +/// A picker's target is fixed when it opens: automation can't point its OK at another dialog, and +/// cancelling a dialog its `__dialog` was rewritten to never closes it. +#[test] +fn a_pickers_target_stays_the_dialog_it_opened_on() { + let ctx = egui::Context::default(); + let mut app = app(); + let (fill, picker) = fill_with_picker(&mut app); + let other = app.ui.open_dialog(DialogKind::Command, Map::new()); + let set = |app: &mut PhotocraftApp, field: &str, value: Value| { + let (req, _rx) = crate::control::ControlRequest::new("ui.dialog.set", json!({"dialog": picker, "field": field, "value": value})); + let crate::control::Outcome::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("an immediate reply") }; + r["ok"].as_bool() + }; + assert_eq!(set(&mut app, "__dialog", json!(other)), Some(false)); + assert_eq!(set(&mut app, "__field", json!("opacity")), Some(false)); + assert_eq!(set(&mut app, "color", json!("#336699")), Some(true), "the colour itself stays drivable"); + assert_eq!(fields(&app, fill)["color"], json!("#336699")); + + // Rewritten another way, `__dialog` still doesn't make it another dialog's picker. + app.ui.dialog_mut(picker).unwrap().fields.insert("__dialog".into(), json!(other)); + crate::dialogs::cancel(&mut app, other).unwrap(); + assert!(app.ui.dialogs.iter().any(|d| d.id == picker), "the picker stays with its own dialog"); + assert_eq!(fields(&app, fill)["color"], json!("#336699"), "and keeps previewing there"); +}