From bdc76f44d91345a6b0fddedfae883d4f89ff7a57 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:21:44 +0100 Subject: [PATCH 01/38] fix(paint): wrap procedural pattern seed hashing Use explicit wrapping seed arithmetic in checked builds and cover boundary/high u32 seeds across all four texture styles. --- crates/paint/src/procedural.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/paint/src/procedural.rs b/crates/paint/src/procedural.rs index 5469dacebc..57662dbe0d 100644 --- a/crates/paint/src/procedural.rs +++ b/crates/paint/src/procedural.rs @@ -37,7 +37,8 @@ fn fbm(x: f32, y: f32, size: f32, cells: i32, octaves: u32, salt: u64) -> f32 { pub fn pattern(style: PatternStyle, size: u32, seed: u32) -> PatternImage { let n = size.clamp(8, 1024) as usize; let s = n as f32; - let salt = u64::from(seed) * 0x0100_0000_01B3 + 17; + // Seed hashing wraps so every u32 seed also works in checked builds. + let salt = u64::from(seed).wrapping_mul(0x0100_0000_01B3).wrapping_add(17); let mut data = vec![0.0f32; n * n]; for y in 0..n { for x in 0..n { @@ -281,6 +282,18 @@ mod tests { assert!(seam < 0.08, "{seam}"); } + #[test] + fn patterns_accept_full_seed_range() { + for seed in [0, 1, (1 << 24) - 1, 1 << 24, u32::MAX] { + for style in [PatternStyle::Noise, PatternStyle::Paper, PatternStyle::Canvas, PatternStyle::Dots] { + let p = pattern(style, 8, seed); + assert_eq!((p.width, p.height, p.data.len()), (8, 8, 64)); + assert!(p.data.iter().all(|v| (0.0..=1.0).contains(v)), "{style:?} seed {seed}"); + assert_eq!(p.data, pattern(style, 8, seed).data); + } + } + } + #[test] fn tips_have_paint() { for t in [ From 20ff6bc6052a3e7285ca103e5b1285a2e7bad5de Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:25:38 +0100 Subject: [PATCH 02/38] Validate palette size for exact transparency handling Reject Exact conversion if the opaque palette uses every slot and the image needs a transparent entry. Leave the edit transaction uncommitted in that case. --- crates/engine/src/cmd/mode_cmds.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index 4d75962e96..6e24019b2e 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -360,6 +360,10 @@ fn indexed_color(s: &mut Session, p: &Value) -> Result { } let has_clear = transparency && px.iter().any(|q| q[3] < 0.5); let mut pal = quantize::build_palette(&px, kind, if has_clear { colors.saturating_sub(1).max(2) } else { colors }, forced).map_err(|e| bad(CMD, e))?; + // Exact must reserve one palette slot for clear pixels. + if kind == PaletteKind::Exact && has_clear && pal.len() >= 256 { + return Err(bad(CMD, "Exact with transparency needs 255 or fewer opaque palette colours plus one transparent entry")); + } let transparent = if has_clear && pal.len() < 256 { pal.push([255, 255, 255]); Some(pal.len() - 1) From 65b3b20b24b833eb05a2270cfeaeba9f8fd8e88a Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:26:31 +0100 Subject: [PATCH 03/38] test(engine): cover Exact indexed transparency capacity Cover unchanged document state after refusal and successful conversion on both valid palette boundaries. --- crates/engine/src/cmd/mode_cmds/tests.rs | 41 ++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/crates/engine/src/cmd/mode_cmds/tests.rs b/crates/engine/src/cmd/mode_cmds/tests.rs index 7e49ee5f8f..f32584a5a5 100644 --- a/crates/engine/src/cmd/mode_cmds/tests.rs +++ b/crates/engine/src/cmd/mode_cmds/tests.rs @@ -439,6 +439,47 @@ fn indexed_matte_without_transparency_fills_clear_pixels_and_rejects_bad_input_a assert_eq!(doc(&s).color_table.as_ref().unwrap().transparent, None); } +#[test] +fn indexed_exact_rejects_full_opaque_palette_with_clear_pixels_atomically() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 257, "height": 1, "background": "transparent"})).unwrap(); + paint(&mut s, |x, _| if x < 256 { [x as f32 / 255.0, x as f32 / 255.0, x as f32 / 255.0, 1.0] } else { [0.0; 4] }); + let before = doc(&s).layers[0].surface().unwrap().to_interleaved(doc(&s).bounds()); + let history = s.active().unwrap().history.past_len(); + let revision = s.active().unwrap().revision; + let error = s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": true})).unwrap_err(); + let message = error.to_string(); + assert!(message.contains("255") && message.contains("transparent entry"), "{message}"); + assert_eq!(doc(&s).mode, ColorMode::Rgb); + assert!(doc(&s).color_table.is_none()); + assert_eq!(doc(&s).layers[0].surface().unwrap().to_interleaved(doc(&s).bounds()), before); + assert_eq!(s.active().unwrap().history.past_len(), history); + assert_eq!(s.active().unwrap().revision, revision); +} + +#[test] +fn indexed_exact_reserves_transparency_only_when_needed_and_available() { + for (opaque, clear) in [(255u32, true), (256, false)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": opaque + u32::from(clear), "height": 1, "background": "transparent"})).unwrap(); + paint(&mut s, |x, _| if x < opaque as i32 { [x as f32 / 255.0, x as f32 / 255.0, x as f32 / 255.0, 1.0] } else { [0.0; 4] }); + let result = s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": true})).unwrap(); + assert_eq!(doc(&s).mode, ColorMode::Indexed); + let table = doc(&s).color_table.as_ref().unwrap(); + assert_eq!(table.colors.len(), 256); + assert_eq!(table.transparent, if clear { Some(255) } else { None }); + assert_eq!(result["transparentIndex"], if clear { json!(255) } else { Value::Null }); + let surface = doc(&s).layers[0].surface().unwrap(); + for x in 0..opaque as i32 { + let gray = x as f32 / 255.0; + assert_eq!(surface.rgba(x, 0), [gray, gray, gray, 1.0]); + } + if clear { + assert_eq!(surface.rgba(opaque as i32, 0)[3], 0.0); + } + } +} + #[test] fn indexed_exact_transparency_and_sources() { // Two colours + transparency: exact palette with a transparent entry. From d57b7b2ff13231642211904f6e8480f187a56b20 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:47:11 +0100 Subject: [PATCH 04/38] Implement checkpoint for Exact conversion failures Restore the active document state and action history on a rejected Exact conversion that auto-drops a floating selection. Keep the normal command, drop, and history sequence on success. --- crates/engine/src/jobs.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index d4870e52f6..86fb590a5c 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -1721,6 +1721,29 @@ impl Session { // authorization, validation, floating-selection and admission failures. let live_commit = self.live_commit.take(); self.sync_scratch_state(); + // A refused Exact conversion must also undo its automatic floating-selection drop. + let checkpoint = if id == "image.mode.indexedColor" && params.get("palette").and_then(Value::as_str) == Some("exact") { + self.active.and_then(|index| { + self.docs + .get(index) + .filter(|state| crate::float_cmds::floating(state).is_some()) + .map(|state| (index, state.clone(), self.action_history.clone())) + }) + } else { + None + }; + let result = self.dispatch_with_commit(id, params, background, live_commit); + if result.is_err() + && let Some((index, state, action_history)) = checkpoint + && self.docs.get(index).is_some_and(|current| current.doc.id == state.doc.id) + { + self.docs[index] = state; + self.action_history = action_history; + } + result + } + + fn dispatch_with_commit(&mut self, id: &str, params: Value, background: bool, live_commit: Option) -> Result { let spec = crate::commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; // Params are named fields: anything but an object (or null, meaning none) is a caller // mistake, not "use every default". From 923dbadade2a7c8cbb679ab694c0101d689484d6 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:47:20 +0100 Subject: [PATCH 05/38] test(engine): cover Exact conversion with a floating selection Reproduce failure after a partial clear-pixel fill, preserving the floating copy and redo. Exercise successful conversion after filling the last clear pixel. --- crates/engine/src/cmd/mode_cmds/tests.rs | 58 ++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/crates/engine/src/cmd/mode_cmds/tests.rs b/crates/engine/src/cmd/mode_cmds/tests.rs index f32584a5a5..4bb0ddc91c 100644 --- a/crates/engine/src/cmd/mode_cmds/tests.rs +++ b/crates/engine/src/cmd/mode_cmds/tests.rs @@ -480,6 +480,64 @@ fn indexed_exact_reserves_transparency_only_when_needed_and_available() { } } +#[test] +fn indexed_exact_failure_restores_a_floating_copy_and_redo() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 258, "height": 1, "background": "transparent"})).unwrap(); + paint(&mut s, |x, _| if x < 256 { [x as f32 / 255.0, x as f32 / 255.0, x as f32 / 255.0, 1.0] } else { [0.0; 4] }); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap(); + s.edit("redo marker", |doc, _| { + doc.name.push_str(" changed"); + Ok(()) + }) + .unwrap(); + assert!(s.undo()); + s.execute("select.float", json!({"dx": 256, "copy": true})).unwrap(); + let before = s.active().unwrap().clone(); + assert!(before.history.can_redo()); + let piece = crate::float_cmds::floating(&before).unwrap(); + let pixels = before.doc.layers[0].surface().unwrap().to_interleaved(before.doc.bounds()); + + let error = s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": true})).unwrap_err(); + assert!(error.to_string().contains("255"), "{error}"); + let after = s.active().unwrap(); + let restored = crate::float_cmds::floating(after).unwrap(); + assert_eq!(after.doc.id, before.doc.id); + assert_eq!(after.doc.mode, ColorMode::Rgb); + assert!(std::sync::Arc::ptr_eq(&after.doc, &before.doc)); + assert_eq!(after.doc.layers[0].surface().unwrap().to_interleaved(after.doc.bounds()), pixels); + assert_eq!((restored.layer, restored.offset, restored.revision, restored.moved), (piece.layer, piece.offset, piece.revision, piece.moved)); + assert!(std::sync::Arc::ptr_eq(&restored.parts, &piece.parts)); + assert_eq!(after.revision, before.revision); + assert_eq!(after.history.past_len(), before.history.past_len()); + assert!(after.history.can_redo()); + assert_eq!(after.active_layer, before.active_layer); + assert_eq!(after.selected_layers, before.selected_layers); +} + +#[test] +fn indexed_exact_success_drops_the_floating_copy_before_counting_colours() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 257, "height": 1, "background": "transparent"})).unwrap(); + paint(&mut s, |x, _| if x < 256 { [x as f32 / 255.0, x as f32 / 255.0, x as f32 / 255.0, 1.0] } else { [0.0; 4] }); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap(); + s.execute("select.float", json!({"dx": 256, "copy": true})).unwrap(); + let history = s.active().unwrap().history.past_len(); + let result = s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": true})).unwrap(); + assert_eq!(doc(&s).mode, ColorMode::Indexed); + assert_eq!(doc(&s).color_table.as_ref().unwrap().colors.len(), 256); + assert_eq!(result["transparentIndex"], Value::Null); + assert!(crate::float_cmds::floating(s.active().unwrap()).is_none()); + assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(256, 0), [0.0, 0.0, 0.0, 1.0]); + assert_eq!(s.active().unwrap().history.past_len(), history + 2, "drop and conversion remain separate history steps"); + assert!(s.undo()); + assert_eq!(doc(&s).mode, ColorMode::Rgb); + assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(256, 0)[3], 1.0); + assert!(s.undo()); + assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(256, 0)[3], 0.0); + assert_eq!(s.active().unwrap().history.past_len(), history); +} + #[test] fn indexed_exact_transparency_and_sources() { // Two colours + transparency: exact palette with a transparent entry. From 1fba8d090f1a2fc6cafc30b4a4296580656c9e2f Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:06:47 +0100 Subject: [PATCH 06/38] fix(xtask): run corpus tests for changes to the current ATN module Point the changed-path trigger at the current engine command module and share the predicate with regression tests. --- xtask/src/corpus.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/xtask/src/corpus.rs b/xtask/src/corpus.rs index 0be1f83625..871a9e1c2c 100644 --- a/xtask/src/corpus.rs +++ b/xtask/src/corpus.rs @@ -24,7 +24,12 @@ const HEIF_CRATES: &[&str] = &["photocraft-io"]; /// Paths whose changes make `test-corpus --changed` run (the file-format and rendering crates, /// and the engine's `.atn` import and export). -const CRITICAL: &[&str] = &["crates/io/", "crates/compose/", "crates/gpu/", "crates/text/", "crates/format/", "crates/raw/", "crates/engine/src/atn_cmds"]; +const CRITICAL: &[&str] = &["crates/io/", "crates/compose/", "crates/gpu/", "crates/text/", "crates/format/", "crates/raw/", "crates/engine/src/cmd/atn_cmds"]; + +fn is_critical(path: &str) -> bool { + CRITICAL.iter().any(|prefix| path.starts_with(prefix)) +} + /// `cargo xtask corpus [--all | --pngsuite | --download | --psd | --psd-tools | --heif | --exr | --pixls | --affinity | --atn | --photoshop [--local] | --gimp [--local]] [--update-manifest]` pub fn cmd(args: &[&str]) -> Result<(), String> { let update = args.contains(&"--update-manifest"); @@ -417,7 +422,7 @@ pub fn test_cmd(args: &[&str]) -> Result<(), String> { let mut raw_changed = false; if ours.contains(&"--changed") { let changed = changed_files()?; - let hits: Vec<&String> = changed.iter().filter(|f| CRITICAL.iter().any(|c| f.starts_with(c))).collect(); + let hits: Vec<&String> = changed.iter().filter(|f| is_critical(f)).collect(); if hits.is_empty() { println!("test-corpus --changed: nothing under {} changed since origin/main; skipping", CRITICAL.join(", ")); return Ok(()); From 3c1043a87b1a56e5571e596431ca80247a194a93 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:07:29 +0100 Subject: [PATCH 07/38] test(xtask): cover ATN corpus trigger paths Exercise the ATN root and nested modules, all existing corpus prefixes, and unrelated engine paths. --- xtask/src/corpus/tests.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/xtask/src/corpus/tests.rs b/xtask/src/corpus/tests.rs index b1c7b515a9..0b187445e2 100644 --- a/xtask/src/corpus/tests.rs +++ b/xtask/src/corpus/tests.rs @@ -1,5 +1,38 @@ use super::*; +#[test] +fn changed_atn_root_triggers_corpus_tests() { + assert!(is_critical("crates/engine/src/cmd/atn_cmds.rs")); +} + +#[test] +fn changed_atn_modules_trigger_corpus_tests() { + for path in ["crates/engine/src/cmd/atn_cmds/steps_render.rs", "crates/engine/src/cmd/atn_cmds/tests.rs"] { + assert!(is_critical(path), "{path}"); + } +} + +#[test] +fn existing_critical_sources_still_trigger_corpus_tests() { + for path in [ + "crates/io/src/ora.rs", + "crates/compose/src/lib.rs", + "crates/gpu/src/lib.rs", + "crates/text/src/lib.rs", + "crates/format/src/lib.rs", + "crates/raw/src/lib.rs", + ] { + assert!(is_critical(path), "{path}"); + } +} + +#[test] +fn unrelated_sources_do_not_trigger_corpus_tests() { + for path in ["crates/engine/src/jobs.rs", "crates/engine/src/cmd/layer_cmds.rs", "docs/actions.md", "apps/photocraft-web/src/main.rs"] { + assert!(!is_critical(path), "{path}"); + } +} + /// The flags each pinned corpus is fetched with by `fetch_all(local, update)`. fn calls(local: bool, update: bool) -> Vec<(&'static str, bool)> { let mut seen = Vec::new(); From 2a3fae44ef62bd7c7b833a1acf0d3ea940781b39 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:45:42 +0100 Subject: [PATCH 08/38] fix(xtask): limit ATN corpus trigger to real module paths Updated the CRITICAL paths to include a trailing slash for consistency and modified the is_critical function to check for a specific path. --- xtask/src/corpus.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xtask/src/corpus.rs b/xtask/src/corpus.rs index 871a9e1c2c..3d217c9f78 100644 --- a/xtask/src/corpus.rs +++ b/xtask/src/corpus.rs @@ -24,10 +24,10 @@ const HEIF_CRATES: &[&str] = &["photocraft-io"]; /// Paths whose changes make `test-corpus --changed` run (the file-format and rendering crates, /// and the engine's `.atn` import and export). -const CRITICAL: &[&str] = &["crates/io/", "crates/compose/", "crates/gpu/", "crates/text/", "crates/format/", "crates/raw/", "crates/engine/src/cmd/atn_cmds"]; +const CRITICAL: &[&str] = &["crates/io/", "crates/compose/", "crates/gpu/", "crates/text/", "crates/format/", "crates/raw/", "crates/engine/src/cmd/atn_cmds/"]; fn is_critical(path: &str) -> bool { - CRITICAL.iter().any(|prefix| path.starts_with(prefix)) + path == "crates/engine/src/cmd/atn_cmds.rs" || CRITICAL.iter().any(|prefix| path.starts_with(prefix)) } /// `cargo xtask corpus [--all | --pngsuite | --download | --psd | --psd-tools | --heif | --exr | --pixls | --affinity | --atn | --photoshop [--local] | --gimp [--local]] [--update-manifest]` From 9de261912872a901ab0005ecd185156accc0ac8f Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:46:09 +0100 Subject: [PATCH 09/38] test(xtask): exclude similarly named ATN sibling paths --- xtask/src/corpus/tests.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/xtask/src/corpus/tests.rs b/xtask/src/corpus/tests.rs index 0b187445e2..921bdc24e9 100644 --- a/xtask/src/corpus/tests.rs +++ b/xtask/src/corpus/tests.rs @@ -12,6 +12,18 @@ fn changed_atn_modules_trigger_corpus_tests() { } } +#[test] +fn similarly_named_atn_siblings_do_not_trigger_corpus_tests() { + for path in [ + "crates/engine/src/cmd/atn_cmds_extra.rs", + "crates/engine/src/cmd/atn_cmds_old/tests.rs", + "crates/engine/src/cmd/atn_cmds.rs.bak", + "crates/engine/src/cmd/atn_cmds", + ] { + assert!(!is_critical(path), "{path}"); + } +} + #[test] fn existing_critical_sources_still_trigger_corpus_tests() { for path in [ From e39dfb94552f2d697333a538dc42508cd4bb3083 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 07:24:26 +0000 Subject: [PATCH 10/38] Appearance and Language menu picks change the theme and the language A theme or language row is a fired command (app.theme, app.language) with the choice in its parameters. The drain's dispatch refused both ids (no enable rule, so the engine's rule answered: not available) and passed invoke empty parameters. Both rows are enabled with or without a document, and dispatch passes the fired command's parameters to invoke. Trials run the whole app with and without a document: a theme fired as the macOS menu fires it, a theme clicked in Window > Appearance, and a language row. --- crates/ui-egui/src/input/shortcut_dispatch.rs | 16 ++- crates/ui-egui/src/menus.rs | 3 + .../src/menus/appearance_menu_trials.rs | 118 ++++++++++++++++++ crates/ui-egui/src/menus/state.rs | 4 + 4 files changed, 135 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/menus/appearance_menu_trials.rs diff --git a/crates/ui-egui/src/input/shortcut_dispatch.rs b/crates/ui-egui/src/input/shortcut_dispatch.rs index f0af34bbdf..1d0c5189b7 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch.rs @@ -709,17 +709,20 @@ fn run_pressed(app: &mut PhotocraftApp, ctx: &egui::Context, f: &Fired) { // The Delete key is Edit › Clear, or deletes the layers when nothing is selected (`delete_key_command`). let id = if id == EditCommands::Delete.id() { "edit.clear" } else { id }; let id = clip_key_command(app, delete_key_command(app, id.to_string())); - dispatch_as(app, ctx, &id, f.alt_variant); + // A key that runs another command (Delete, the clip keys) runs it without the fired command's parameters. + let command = if id == f.command.id { f.command.clone() } else { CommandRef::new(id) }; + dispatch_as(app, ctx, &command, f.alt_variant); } /// Run a shortcut's command like its menu item (dialogs included), or say why it can't run. pub fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str) { - dispatch_as(app, ctx, id, false); + dispatch_as(app, ctx, &CommandRef::new(id), false); } -/// [`dispatch`]; with `last`, an adjustment dialog opens at its last confirmed settings and New Layer makes the -/// layer without its dialog. -fn dispatch_as(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, last: bool) { +/// [`dispatch`] of a fired command, its parameters included (an Appearance or Language row's choice); with `last`, an +/// adjustment dialog opens at its last confirmed settings and New Layer makes the layer without its dialog. +fn dispatch_as(app: &mut PhotocraftApp, ctx: &egui::Context, command: &CommandRef, last: bool) { + let id = command.id.as_str(); let action = id.strip_prefix(crate::actions::SHORTCUT_PREFIX); let command_id = if action.is_some() { "actions.play" } else { id }; // A key saved for an action that was since deleted or renamed names no action. @@ -748,7 +751,8 @@ fn dispatch_as(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, last: boo let opened = if last { crate::adjust_dialog::open_last(app, id) } else { crate::adjust_dialog::open(app, id) }; opened.map(|_| serde_json::Value::Null) } else { - crate::menus::invoke(app, ctx, id, json!({})) + let params = if command.params.is_null() { json!({}) } else { command.params.clone() }; + crate::menus::invoke(app, ctx, id, params) }; match r { Ok(_) => Outcome::Ran, diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 4df91e6dc1..2b3ccdd3f1 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -104,6 +104,9 @@ pub(crate) const DOCUMENT_ITEM: &str = "window.document."; #[cfg(test)] mod tests; +#[cfg(test)] +mod appearance_menu_trials; + #[cfg(test)] mod open_recent_position_tests; diff --git a/crates/ui-egui/src/menus/appearance_menu_trials.rs b/crates/ui-egui/src/menus/appearance_menu_trials.rs new file mode 100644 index 0000000000..bdff4c3900 --- /dev/null +++ b/crates/ui-egui/src/menus/appearance_menu_trials.rs @@ -0,0 +1,118 @@ +//! The Appearance and Language menus in the whole app: a pick changes the theme the framework draws with and the +//! language, whether it comes from a click on the in-window bar or from the macOS menu, which fires the row's command. +//! Both menus work with or without a document open. + +use craft::keymap::CommandRef; +use craft::menu::{LANGUAGE_COMMAND, ThemeChoice}; +use craft::ui::runtime::commands::{FireSource, fire}; +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{AccessKitNode, Queryable}; + +use crate::PhotocraftApp; +use crate::theme::AppTheme; + +/// The whole app, empty or with one document open. +fn harness(document: bool) -> Harness<'static, Box> { + let mut session = photocraft_engine::Session::new(); + if document { + session.execute("file.new", serde_json::json!({"width": 64, "height": 48})).unwrap(); + } + crate::shortcut_dispatch::tests::app_harness(PhotocraftApp::new(session, crate::Services::default())) +} + +/// The theme the framework's root takes each frame (`frame_input`) and the panel fill the theme installs. +fn shown(h: &Harness<'_, Box>) -> (String, bool, egui::Color32) { + let theme = &h.state().ui.theme; + (theme.id().as_str().to_string(), theme.is_dark(), h.ctx.global_style().visuals.panel_fill) +} + +/// Classic in light mode: a light theme of its own row, unlike the dark theme the app starts with. +fn classic() -> (AppTheme, ThemeChoice) { + let theme = AppTheme::classic(); + let choice = ThemeChoice::theme(theme.id().clone(), false); + (theme, choice) +} + +/// Runs the frames that take a fired command and show its result. +fn settle(h: &mut Harness<'_, Box>) { + h.run_steps(6); +} + +/// The centre of the top-most menu title or row labelled `label`. +fn top(h: &Harness<'_, Box>, label: &str) -> egui::Pos2 { + let named = |node: &AccessKitNode<'_>| { + node.label().as_deref() == Some(label) && matches!(node.role(), Role::MenuItem | Role::MenuItemRadio | Role::MenuItemCheckBox) + }; + let node = h.get_all_by(named).min_by(|a, b| a.rect().min.y.total_cmp(&b.rect().min.y)).unwrap_or_else(|| panic!("no menu row {label}")); + node.rect().center() +} + +/// Moves the pointer over the top-most node labelled `label`. +fn hover_top(h: &mut Harness<'_, Box>, label: &str) { + let at = top(h, label); + h.event(egui::Event::PointerMoved(at)); + settle(h); +} + +/// Clicks the top-most node labelled `label` with the pointer, a frame for the press and one for the release. +fn click_top(h: &mut Harness<'_, Box>, label: &str) { + let at = top(h, label); + h.event(egui::Event::PointerMoved(at)); + h.step(); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + h.step(); + } + settle(h); +} + +/// Asserts the app shows Classic light after a pick, with the panel fill it installs. +fn assert_classic(h: &Harness<'_, Box>, before: &(String, bool, egui::Color32), document: bool) { + let (theme, _) = classic(); + let after = shown(h); + assert_eq!((after.0.as_str(), after.1), (theme.id().as_str(), false), "document {document}; status: {}", h.state().ui.status); + assert_ne!(after.2, before.2, "document {document}: the panels take the theme's fill"); + assert_eq!(after.2, theme.tokens().chrome, "document {document}"); +} + +#[test] +fn a_theme_fired_from_the_menu_shows_it() { + for document in [true, false] { + let mut h = harness(document); + let (theme, choice) = classic(); + let before = shown(&h); + assert_ne!(before.0, theme.id().as_str(), "the app starts on another theme"); + assert!(fire(&h.ctx.clone(), choice.command(), FireSource::Menu), "the runtime takes the menu's theme row"); + settle(&mut h); + assert_classic(&h, &before, document); + } +} + +#[test] +fn a_theme_clicked_in_the_window_menu_shows_it() { + for document in [true, false] { + let mut h = harness(document); + let (theme, _) = classic(); + let before = shown(&h); + click_top(&mut h, "Window"); + hover_top(&mut h, "Appearance"); + let name = h.state().framework.theme_name(theme.id(), false); + click_top(&mut h, &name); + assert_classic(&h, &before, document); + } +} + +#[test] +fn a_language_fired_from_the_menu_is_saved() { + // A language other than English where the build has the catalogs; English (from Automatic) where it has only that. + let code = crate::i18n::Lang::all().map(crate::i18n::Lang::code).find(|code| *code != "en").unwrap_or("en"); + for document in [true, false] { + let mut h = harness(document); + assert_eq!(h.state().session.prefs().interface.language, "auto"); + let row = CommandRef::with_params(LANGUAGE_COMMAND, serde_json::json!({"lang": code})); + assert!(fire(&h.ctx.clone(), row, FireSource::Menu), "the runtime takes the menu's language row"); + settle(&mut h); + assert_eq!(h.state().session.prefs().interface.language, code, "document {document}; status: {}", h.state().ui.status); + } +} diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index b391038165..7831ae9382 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -1,3 +1,5 @@ +use craft::menu::{LANGUAGE_COMMAND, THEME_COMMAND}; + use super::invoke::{panel_alias, proof_preset, workspace_id}; use super::{DOCUMENT_ITEM, PhotocraftApp, Value}; @@ -72,6 +74,8 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool { i if crate::links::url_for(i).is_some() => true, // Interface brightness works with or without a document, as in Photoshop. "view.darkenInterface" | "view.lightenInterface" => true, + // Appearance and Language rows: the theme and the language change with or without a document. + THEME_COMMAND | LANGUAGE_COMMAND => true, "file.save" | "file.saveAs" | "file.export.exportAs" | "file.export.quickExportAsPng" => { app.session.active().is_some() && app.services.export.is_some() } From f0a1b7c9c38c255bbdd17a6942da7728c9f758c7 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:39:20 +0100 Subject: [PATCH 11/38] Tests: cut duplicate bevel thread cases (#15935) --- crates/compose/src/effects/tests.rs | 67 +++++++++++++++-------------- 1 file changed, 35 insertions(+), 32 deletions(-) diff --git a/crates/compose/src/effects/tests.rs b/crates/compose/src/effects/tests.rs index e546ece5bf..3654dd78fc 100644 --- a/crates/compose/src/effects/tests.rs +++ b/crates/compose/src/effects/tests.rs @@ -700,49 +700,52 @@ fn chisel_fields_do_not_depend_on_the_threads() { #[test] fn bevel_maps_do_not_depend_on_the_threads() { - // Every style and technique, softened or not, and a texture; one thread (in order) is the reference. - let mut patchy = aa_disc(101, 101, 40.0); + // Compact anti-aliased fixtures keep curved, rounded, clipped oblique and patchy edges. + // Dimensions above 16 and below 64 exercise multi-row groups with 2 threads and + // one row per group with 8. Odd extents also leave a short final group. + let mut patchy = aa_disc(51, 51, 18.0); + let patchy_width = patchy.w; for (i, v) in patchy.v.iter_mut().enumerate() { - if (i % 101 / 13 + i / 101 / 17) % 5 == 0 { + if (i % patchy_width / 7 + i / patchy_width / 9) % 5 == 0 { *v *= 0.6; } } - let shapes = [aa_disc(97, 83, 30.0), aa_round_rect(131, 77, 9.0, 11.0, 120.0, 66.0, 14.0), aa_bar(90, 130, 60.0, 150.0, 25.0), patchy]; + let shapes = [aa_disc(49, 47, 13.0), aa_round_rect(61, 47, 10.0, 9.0, 51.0, 38.0, 8.0), aa_bar(47, 63, 60.0, 74.0, 15.0), patchy]; let mut sf = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); sf.fill_rect(Rect::new(0, 0, 4, 2), &[0.0, 0.0, 0.0, 1.0]); sf.fill_rect(Rect::new(0, 2, 4, 4), &[1.0, 1.0, 1.0, 1.0]); let pats = [Pattern::new("stripes", sf, 4, 4)]; let light = GlobalLight::default(); let styles = [BevelStyle::InnerBevel, BevelStyle::OuterBevel, BevelStyle::Emboss, BevelStyle::PillowEmboss, BevelStyle::StrokeEmboss]; - for (k, shape) in shapes.iter().enumerate() { + let techniques = [BevelTechnique::Smooth, BevelTechnique::ChiselHard, BevelTechnique::ChiselSoft]; + let settings = [(5.0, 0.0, false), (12.0, 2.0, false), (8.0, 0.0, true)]; + for (shape_index, shape) in shapes.iter().enumerate() { let tex = TextureCtx { rect: Rect::new(3, 5, 3 + shape.w as i32, 5 + shape.h as i32), patterns: &pats, anchor: (0.0, 0.0) }; - for style in styles { - for technique in [BevelTechnique::Smooth, BevelTechnique::ChiselHard, BevelTechnique::ChiselSoft] { - for (size, soften, textured) in [(5.0, 0.0, false), (12.0, 2.0, false), (8.0, 0.0, true)] { - let mut b = bevel_of(style, technique); - (b.size, b.soften) = (size, soften); - if textured { - b.texture = Some(photocraft_doc::BevelTexture { - name: "stripes".into(), - id: String::new(), - scale: 1.0, - depth: 1.0, - invert: false, - link: true, - phase: (0.0, 0.0), - }); - } - let run = || bevel_maps(shape, &b, &light, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)).0; - let one = with_threads(1, run); - // 2 threads give groups of several units with a short last one, 16 one unit a group: the two ways `par_units` splits work (#15652). - for threads in [2, 16] { - let many = with_threads(threads, run); - assert_eq!(one.len(), many.len()); - for (j, (a, m)) in one.iter().zip(&many).enumerate() { - assert_eq!(bits(&a.v), bits(&m.v), "shape {k}, {style:?} {technique:?} size {size} map {j} on {threads} threads"); - } - } - } + for (style_index, style) in styles.into_iter().enumerate() { + // Rotate each set through shapes. Stepping the settings twice as fast as + // the techniques across styles also gives every technique each setting. + let technique = techniques[(shape_index + style_index) % techniques.len()]; + let (size, soften, textured) = settings[(shape_index + 2 * style_index) % settings.len()]; + let threads = [2, 8][(shape_index + style_index) % 2]; + let mut b = bevel_of(style, technique); + (b.size, b.soften) = (size, soften); + if textured { + b.texture = Some(photocraft_doc::BevelTexture { + name: "stripes".into(), + id: String::new(), + scale: 1.0, + depth: 1.0, + invert: false, + link: true, + phase: (0.0, 0.0), + }); + } + let run = || bevel_maps(shape, &b, &light, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)).0; + let one = with_threads(1, run); + let many = with_threads(threads, run); + assert_eq!(one.len(), many.len()); + for (j, (a, m)) in one.iter().zip(&many).enumerate() { + assert_eq!(bits(&a.v), bits(&m.v), "shape {shape_index}, {style:?} {technique:?} size {size} map {j} on {threads} threads"); } } } From 56050cf13b1ad5d2e0aa188d6bc59c81217225c1 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:49:32 +0100 Subject: [PATCH 12/38] Credit MMexicann as mexicann --- contributors/people.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 9b7ed5a52e..e86ee8a01a 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -355,3 +355,6 @@ real_name = "Sven Lafebre" [people.kirubhakaran12] sync_github_name = true + +[people.MMexicann] +display_name = "mexicann" From ba53b470489edd457d61abf9ab6e1425a34abf44 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:54:15 +0100 Subject: [PATCH 13/38] Use the standard divisibility check in the bevel fixture --- crates/compose/src/effects/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/compose/src/effects/tests.rs b/crates/compose/src/effects/tests.rs index 3654dd78fc..6291cb393b 100644 --- a/crates/compose/src/effects/tests.rs +++ b/crates/compose/src/effects/tests.rs @@ -706,7 +706,7 @@ fn bevel_maps_do_not_depend_on_the_threads() { let mut patchy = aa_disc(51, 51, 18.0); let patchy_width = patchy.w; for (i, v) in patchy.v.iter_mut().enumerate() { - if (i % patchy_width / 7 + i / patchy_width / 9) % 5 == 0 { + if (i % patchy_width / 7 + i / patchy_width / 9).is_multiple_of(5) { *v *= 0.6; } } From e19e864a843e58f1d9bafe0bcce7aeee9f2af0be Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:06:47 +0100 Subject: [PATCH 14/38] Audit coverage removed by the shared UI framework port Added documentation for tests affected by the shared UI port, including an inventory of removed tests and their successors. The document tracks changes related to the UI rework and provides details on test coverage and assertions. --- .../framework-port-test-map.md | 305 ++++++++++++++++++ 1 file changed, 305 insertions(+) create mode 100644 docs/integration-testing/framework-port-test-map.md diff --git a/docs/integration-testing/framework-port-test-map.md b/docs/integration-testing/framework-port-test-map.md new file mode 100644 index 0000000000..72a59060b7 --- /dev/null +++ b/docs/integration-testing/framework-port-test-map.md @@ -0,0 +1,305 @@ +# Tests affected by the shared UI port + +Tracking issue [#15466](https://github.com/storytold/photocraft/issues/15466), part of the [UI rework](https://github.com/storytold/photocraft/issues/15476). + +This inventory compares the PhotoCraft parent [`01b79958a7`](https://github.com/storytold/photocraft/commit/01b79958a7b73c3d840b76492069e9635f9f7394) with the framework port [`ed14e1c413`](https://github.com/storytold/photocraft/commit/ed14e1c413ebea61dcb54abda3d388b33a29a4af). Successors were checked in PhotoCraft [`42c853396d`](https://github.com/storytold/photocraft/commit/42c853396d147a554f540c9723b90e1179080a79) and its pinned craft-libs [`683fe06031`](https://github.com/storytold/craft-libs/commit/683fe06031224725b913c8ad3697d8e8bfec6c90). + +The scan found **226 whole-file removals** with **1,659 recognized test declarations**. 215 paths belonged to `ui-egui`. The scan includes inline tests in implementation files and counts whole paths, so its file total uses a different scope from the original issue’s test-file count. Declarations removed from files that stayed in place are outside this inventory. + +The source scan recognized Rust functions marked `#[test]`, namespaced `#[…::test]` and `#[trial]`. 121 declarations have at least one same-name candidate. The inventory also records bodies with identical Rust tokens after dropping comments and whitespace. Names and body matches identify places to inspect. The behavior notes below come from reading assertions. No tests were run for this audit. + +## Reviewed successors + +| Removed PhotoCraft source | Current test | Assertions retained and scope | +| --- | --- | --- | +| [`crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs#L41) | [PhotoCraft rectangle input](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/tools/vector_ui/rectangle_click_in_shape_tests.rs#L41) | Inside-click and one-pixel motion leave the live shape alone. Rounded corners use the outline, and path and pixel modes retain their distinct behavior. | +| [`crates/ui-egui/src/canvas/canvas_autoscroll.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/canvas/canvas_autoscroll.rs#L140) | [Autoscroll edges](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-canvas/tests/it/canvas/navigate.rs#L734) | Checks edge clamping, fitting and overscrolled images, a rotated view with pixel aspect, and an oblique screen axis. The old HiDPI, flip and negative quarter-turn cases need separate review. | +| [`crates/ui-egui/src/canvas/rotate_view/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/canvas/rotate_view/tests.rs#L163) | [Rotate View drag](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-canvas/tests/it/canvas/tools.rs#L312) | Checks pointer movement in both flip states and 15-degree Shift steps. PhotoCraft history and key routing are outside this fixture. | +| [`crates/ui-egui/src/canvas/zoom_hold.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/canvas/zoom_hold.rs#L139) | [Zoom hold and scrub](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-canvas/tests/it/canvas/tools.rs#L381) | Checks the anchor, 30 and 120 Hz holds, an animation-off step, quick clicks and drag scrubbing. Nonfinite input, limits and history still need review. | +| [`crates/ui-egui/src/canvas/pixel_grid.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/canvas/pixel_grid.rs#L194) | [Grid line colour](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-canvas/tests/it/canvas_controls/grid.rs#L76), [Canvas grid](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/tests/it/gpu_tests/checker_canvas.rs#L169) | Checks transparency, adaptive contrast and the 500% threshold in the app. Exact 501% behavior and panning-cache bounds remain open. | +| [`crates/ui-egui/tests/it/crop_shift_corner.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/tests/it/crop_shift_corner.rs#L100) | [Crop corner diagonal](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-canvas/tests/it/canvas/crop.rs#L756) | Checks the ratio, reachable guide snap and distant-guide rejection in pending geometry. PhotoCraft’s committed result is a separate assertion. | +| [`crates/ui-egui/tests/it/crop_turn_keeps_frame_inside.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/tests/it/crop_turn_keeps_frame_inside.rs#L152) | [Turned crop fit](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-canvas/tests/it/canvas/crop.rs#L667) | Checks fit, shrink, restore, corner movement and the Command override. Committed pixels and a modifier changed during a turn remain open. | +| [`crates/ui-egui/src/tools/crop_mode/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/tools/crop_mode/tests.rs#L519) | [Dropped crop on document switch](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/tools/crop_mode_tests.rs#L92) | Switching away drops the pending crop and returns the original view upright. The old test repeated the scenario in both document orders. | +| [`crates/ui-egui/src/input/control_click.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/input/control_click.rs#L45) | [macOS Control-click](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-contract/tests/it/runtime/control_click.rs#L39), [PhotoCraft menus](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/canvas_menu_tests.rs#L88) | Checks secondary click through release, other modifiers and platforms, re-entry and the next primary click. PhotoCraft also checks that the right menus open. | +| [`crates/ui-egui/src/menus/menu_keys/harness_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/menus/menu_keys/harness_tests.rs#L397) | [Command shortcut focus](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-widgets/tests/it/menu/pick_focus.rs#L131) | A command dispatches once, closes the menu and restores its prior focus. | +| [`crates/ui-egui/src/menus/menu_nav/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/menus/menu_nav/tests.rs#L453) | [Popup clearance](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-widgets/tests/it/menu/overflow.rs#L169) | The menu and submenu clear the bar and stay in the window. The original ran across more display and menu configurations. | +| [`crates/ui-egui/src/menus/menu_nav/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/menus/menu_nav/tests.rs#L832) | [Submenu pointer path](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-widgets/tests/it/menu/submenus.rs#L42) | Moving toward the open submenu over a competing row keeps it open, then a rested pointer switches it. The legacy path matrix was broader. | +| [`crates/ui-egui/src/widgets/type_ahead.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/widgets/type_ahead.rs#L129) | [Localized type-ahead](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-widgets/tests/it/pickers/select_list.rs#L118) | Checks Azerbaijani dotted and dotless I, combining dot and Greek. The old split composing sequence needs separate review. | +| [`crates/ui-egui/src/widgets/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/widgets/tests.rs#L629) | [Text event limits](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-contract/tests/it/text/input_cap.rs#L110) | Checks Unicode character limits for text, paste and IME and removes an out-of-bounds preedit range. | +| [`crates/ui-egui/src/widgets/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/widgets/tests.rs#L916) | [Numeric expression stepping](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-widgets/tests/it/text/number.rs#L614) | Arrow keys evaluate `5+5`, reach 11 then 10, and keep focus in the field. | +| [`crates/ui-egui/src/widgets/task_bar.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/widgets/task_bar.rs#L203) | [Task bar placement](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs#L185) | Checks anchoring, manual placement, pin/reset, clamping and nonfinite input. Exact spacing and a fixed left edge during content growth need separate review. | +| [`crates/ui-egui/src/panels/layer_row_ui/edit_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/panels/layer_row_ui/edit_tests.rs#L161) | [Invalid type edits](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/layers_thumbnail_tests.rs#L146) | A rejected type edit keeps the active tool and leaves text editing inactive. | +| [`crates/ui-egui/src/panels/layer_row_ui/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/panels/layer_row_ui/tests.rs#L804) | [Masked artboard retargeting](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/layers_thumbnail_tests.rs#L164) | Clicking an artboard thumbnail exits mask view and retargets the artboard. | +| [`crates/ui-egui/src/panels/props_layout/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/panels/props_layout/tests.rs#L338) | [Background plus another layer](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/panels/properties.rs#L165) | A single Background hides alignment actions. A multiple selection keeps them and horizontal alignment moves only x. | +| [`crates/ui-egui/src/panels/titlebar/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/panels/titlebar/tests.rs#L278) | [Dirty window close](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/panels/title_bar/tests.rs#L50) | Checks the unsaved-work prompt for a drawable window and direct closing after device loss. The former no-document case needs separate review. | +| [`crates/ui-egui/src/panels/layer_reveal/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/panels/layer_reveal/tests.rs#L69) | [Layer reveal and group behavior](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/layers/tests/it/panel_reveal.rs#L136), [Per-document scroll](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/layers/tests/it/panel_reveal.rs#L188) | Checks group expansion, row visibility, stable visible rows, optional group preservation and retained scroll. PhotoCraft’s undo-triggered reveal still needs a fixture. | +| [`crates/ui-egui/src/dialogs/export_dialog/enter_key_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/export_dialog/enter_key_tests.rs#L51) | [Explicit export button](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-patterns/tests/it/form_dialogs/hosted.rs#L265), [Scale field Enter](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-patterns/tests/it/form_dialogs/hosted.rs#L348), [Escape cancellation](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-patterns/tests/it/form_dialogs/hosted.rs#L104) | Bare Enter keeps Export As open. Enter in Scale commits the field, only the button requests a path, and Escape reaches the host as Cancel. | +| [`crates/ui-egui/src/dialogs/image_size_readout_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/image_size_readout_tests.rs#L43) | [Flat image size](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/dialogs/sizing/tests.rs#L159), [Bitmap row padding and previous size](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-patterns/tests/it/form_dialogs/hosted.rs#L385) | Checks channel and depth calculations, whole-byte bitmap rows and when the previous size appears. Localized formatting and same-byte changes remain open. | +| [`crates/ui-egui/src/dialogs/image_size_resample_shortcuts_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/image_size_resample_shortcuts_tests.rs#L74) | [Alt-digit resampling](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-patterns/tests/it/form_dialogs/hosted.rs#L404) | Checks two picks, ignored chords, typing in the field and unavailable choices. Full key position coverage, same-frame ordering and applying the choice remain open. | + +The Magnetic Lasso cursor-preference matrix returned in [PhotoCraft #15805](https://github.com/storytold/photocraft/pull/15805). The removed Alt+Tab case has a draft in [craft-libs #2805](https://github.com/storytold/craft-libs/pull/2805). Customized-workspace Properties coverage is tracked in [#15791](https://github.com/storytold/photocraft/issues/15791). + +## Coverage still to review + +These assertions have no equivalent identified in the reviewed successors. The gaps concern test coverage based on these snapshots. + +- Selection outline paint order above guides across zoom and DPI and drawing in a secondary view. [Original assertion](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/canvas/guide_ants_tests.rs#L49) +- Escape and Enter routing while the crop ratio list owns the keyboard, with the crop remaining pending. [Original assertion](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/tests/it/crop_popup_keys.rs#L72) +- The pointer-driven third and fourth corner and hover grid. The current app tests cover committed quad input. [Original assertion](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/tools/perspective_crop_click_preview_tests.rs#L31) +- Perspective Crop hover hit zones and keeping the drag cursor while moving. [Original assertion](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/canvas/perspective_crop_cursor_tests.rs#L45) +- Native pinch and Ctrl-wheel in the same frame coalesce into one zoom. [Original assertion](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/canvas/wheel_nav/tests.rs#L770) +- Non-US physical bracket fallback, the Dvorak exception and leaving the German plus key alone. [Original assertion](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/input/layout_keys.rs#L142) +- Off-field diagonal selection follows x on single-line fields and preserves multiline movement. [Original assertion](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/input/single_line_drag.rs#L157) +- Field-local rejection before parsing, including Unicode, IME, undo and same-frame Tab. [Original assertion](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/widgets/numeric_input_tests.rs#L52) +- Fit Image validation and undo across field editing and programmatic input. [Original assertion](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/fit_image_range_tests.rs#L59) +- Camera Raw anchored zoom, clamped panning, snap limits and fitting after tiny or nonfinite resize. [Original assertion](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/camera_raw_preview_ui.rs#L299) +- Dialog-specific undo isolation for Filter Gallery and Vanishing Point. [Original assertion](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/edit_history.rs#L197) + +## Identical body matches + +Each row links the first matched declaration at a destination and counts matching bodies at that path. The inventory counts unique legacy declarations, so a test at more than one destination is counted once there. + +| Removed source | Candidate location | Matched bodies | +| --- | --- | ---: | +| [`apps/photocraft/src/icon_theme.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/apps/photocraft/src/icon_theme.rs#L280) | [`crates/window/src/desktop/icon_theme.rs`](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/window/src/desktop/icon_theme.rs#L253) | 4 | +| [`apps/photocraft/src/portal_save/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/apps/photocraft/src/portal_save/tests.rs#L5) | [`crates/dialogs/src/portal/tests.rs`](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/dialogs/src/portal/tests.rs#L23) | 1 | +| [`crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs#L54) | [`crates/ui-egui/src/tools/vector_ui/rectangle_click_in_shape_tests.rs`](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/tools/vector_ui/rectangle_click_in_shape_tests.rs#L54) | 2 | +| [`crates/ui-egui/src/dialogs/adjust_editors/curves.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/adjust_editors/curves.rs#L545) | [`crates/ui-egui/src/dialogs/adjust_editors/curves.rs`](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/dialogs/adjust_editors/curves.rs#L546) | 13 | +| [`crates/ui-egui/src/shape_bounds_box_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/shape_bounds_box_tests.rs#L86) | [`crates/ui-egui/src/tools/shape_controls/box_tests.rs`](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/tools/shape_controls/box_tests.rs#L71) | 2 | +| [`crates/ui-egui/src/tools/analysis_ui/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/tools/analysis_ui/tests.rs#L147) | [`crates/ui-egui/src/tools/analysis/tests.rs`](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/tools/analysis/tests.rs#L134) | 2 | +| [`crates/ui-egui/src/widgets/point_curve.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/widgets/point_curve.rs#L229) | [`crates/ui-egui/src/widgets/point_curve.rs`](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/widgets/point_curve.rs#L262) | 6 | +| [`crates/ui-egui/src/widgets/tone.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/widgets/tone.rs#L582) | [`crates/ui-egui/src/tone.rs`](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/tone.rs#L533) | 13 | +| [`crates/ui-egui/tests/it/custom_print_paper.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/tests/it/custom_print_paper.rs#L234) | [`crates/ui-egui/src/dialogs/file_ui/custom_paper_tests.rs`](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/dialogs/file_ui/custom_paper_tests.rs#L200) | 1 | + +## Whole-file inventory + +A dash means no same-name candidate or identical body surfaced in the scanned snapshots. Current tests can cover a behavior under a different name. The assertion comparisons above record reviewed examples, including renamed tests. + +| Removed path | Cases | Same-name leads | Identical bodies | +| --- | ---: | ---: | ---: | +| `apps/photocraft/src/agent_link.rs` | 6 | 1 | — | +| `apps/photocraft/src/appearance.rs` | 3 | — | — | +| `apps/photocraft/src/caption_style.rs` | 7 | — | — | +| `apps/photocraft/src/control_server.rs` | 8 | 1 | — | +| `apps/photocraft/src/file_dialog_probe.rs` | 7 | 2 | — | +| `apps/photocraft/src/icon_theme.rs` | 9 | 8 | 4 | +| `apps/photocraft/src/mac_menu.rs` | 2 | — | — | +| `apps/photocraft/src/portal_save/tests.rs` | 11 | 1 | 1 | +| `apps/photocraft/src/screen_color.rs` | 6 | — | — | +| `crates/engine/src/cmd/updates_cmds.rs` | 4 | — | — | +| `crates/engine/src/kys.rs` | 10 | 1 | — | +| `crates/ui-egui/examples/cursor_bench/args.rs` | 1 | — | — | +| `crates/ui-egui/src/background_eraser_alt_click_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/background_eraser_bar_angle_tests.rs` | 13 | 1 | — | +| `crates/ui-egui/src/background_eraser_brush_popup_tests.rs` | 5 | — | — | +| `crates/ui-egui/src/background_eraser_digit_keys_tests.rs` | 7 | — | — | +| `crates/ui-egui/src/blend_dropdown_groups_tests.rs` | 2 | — | — | +| `crates/ui-egui/src/blend_dropdown_keys_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/blend_dropdown_wheel_tests.rs` | 9 | — | — | +| `crates/ui-egui/src/blur_strength_alert_tests.rs` | 5 | — | — | +| `crates/ui-egui/src/brush_alt_digit_smoothing_tests.rs` | 7 | — | — | +| `crates/ui-egui/src/brush_hud_rate_tests.rs` | 4 | — | — | +| `crates/ui-egui/src/brush_opacity_minimum_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/brush_options_tooltips_tests.rs` | 5 | — | — | +| `crates/ui-egui/src/brush_picker_angle_widget_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/bucket_bitmap_alert_tests.rs` | 4 | — | — | +| `crates/ui-egui/src/burn_bar_tooltips_tests.rs` | 10 | — | — | +| `crates/ui-egui/src/burn_default_tip_tests.rs` | 3 | 2 | — | +| `crates/ui-egui/src/burn_exposure_field_tests.rs` | 10 | — | — | +| `crates/ui-egui/src/cam_options_bar_tests.rs` | 5 | — | — | +| `crates/ui-egui/src/cam_reset_tool_mode_tests.rs` | 3 | — | — | +| `crates/ui-egui/src/canvas/ants.rs` | 7 | — | — | +| `crates/ui-egui/src/canvas/canvas_autoscroll.rs` | 10 | — | — | +| `crates/ui-egui/src/canvas/canvas_popup.rs` | 2 | — | — | +| `crates/ui-egui/src/canvas/canvas_tool_menu/hand_menu_entries_tests.rs` | 3 | — | — | +| `crates/ui-egui/src/canvas/canvas_tool_menu/zoom_menu_anchor_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/canvas/guide_ants_tests.rs` | 2 | — | — | +| `crates/ui-egui/src/canvas/paint.rs` | 5 | — | — | +| `crates/ui-egui/src/canvas/pattern_preview.rs` | 6 | — | — | +| `crates/ui-egui/src/canvas/perspective_crop_cursor_tests.rs` | 5 | — | — | +| `crates/ui-egui/src/canvas/pixel_grid.rs` | 16 | — | — | +| `crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs` | 6 | 6 | 2 | +| `crates/ui-egui/src/canvas/remove_cursor_tests.rs` | 3 | — | — | +| `crates/ui-egui/src/canvas/rotate_view/tests.rs` | 21 | — | — | +| `crates/ui-egui/src/canvas/sampler_cursor_tests.rs` | 5 | — | — | +| `crates/ui-egui/src/canvas/scrollbars.rs` | 11 | — | — | +| `crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs` | 8 | — | — | +| `crates/ui-egui/src/canvas/tool_cursor/count_tests.rs` | 5 | 1 | — | +| `crates/ui-egui/src/canvas/tool_cursor/ruler_tests.rs` | 9 | — | — | +| `crates/ui-egui/src/canvas/tool_cursor/tests.rs` | 50 | — | — | +| `crates/ui-egui/src/canvas/wheel_nav/scroll_step_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/canvas/wheel_nav/tests.rs` | 52 | — | — | +| `crates/ui-egui/src/canvas/zoom_field.rs` | 6 | — | — | +| `crates/ui-egui/src/canvas/zoom_hold.rs` | 9 | — | — | +| `crates/ui-egui/src/canvas/zoom_levels.rs` | 6 | — | — | +| `crates/ui-egui/src/canvas/zoom_window_fit.rs` | 14 | — | — | +| `crates/ui-egui/src/clone_stamp_reset_tip_tests.rs` | 4 | 2 | — | +| `crates/ui-egui/src/color_replacement_alt_click_tests.rs` | 3 | — | — | +| `crates/ui-egui/src/color_replacement_blend_keys_tests.rs` | 5 | — | — | +| `crates/ui-egui/src/color_replacement_tolerance_field_tests.rs` | 8 | — | — | +| `crates/ui-egui/src/dialogs/adjust_editors/curves.rs` | 13 | 13 | 13 | +| `crates/ui-egui/src/dialogs/camera_raw_preview_ui.rs` | 6 | — | — | +| `crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs` | 2 | — | — | +| `crates/ui-egui/src/dialogs/credits/ui_tests.rs` | 12 | — | — | +| `crates/ui-egui/src/dialogs/dialog_alt_reset.rs` | 3 | — | — | +| `crates/ui-egui/src/dialogs/edit_history.rs` | 4 | — | — | +| `crates/ui-egui/src/dialogs/export_dialog/enter_key_tests.rs` | 4 | — | — | +| `crates/ui-egui/src/dialogs/fit_image_range_tests.rs` | 7 | — | — | +| `crates/ui-egui/src/dialogs/image_size_readout_tests.rs` | 13 | — | — | +| `crates/ui-egui/src/dialogs/image_size_resample_shortcuts_tests.rs` | 9 | — | — | +| `crates/ui-egui/src/dialogs/label_column_tests.rs` | 1 | — | — | +| `crates/ui-egui/src/dialogs/layer_style/bevel_modes_tests.rs` | 1 | — | — | +| `crates/ui-egui/src/dialogs/rgb_histogram.rs` | 7 | — | — | +| `crates/ui-egui/src/dialogs/select_mask_ui/cycle_tool_mode_tests.rs` | 9 | — | — | +| `crates/ui-egui/src/dialogs/shape_dialog/create_triangle_range_alert_tests.rs` | 7 | — | — | +| `crates/ui-egui/src/dodge_default_tip_tests.rs` | 3 | 2 | — | +| `crates/ui-egui/src/dropdown_press_tests.rs` | 3 | — | — | +| `crates/ui-egui/src/empty_workspace_tests.rs` | 2 | — | — | +| `crates/ui-egui/src/eraser_range_alert_tests.rs` | 8 | — | — | +| `crates/ui-egui/src/i18n/casing.rs` | 1 | — | — | +| `crates/ui-egui/src/input/control_click.rs` | 4 | — | — | +| `crates/ui-egui/src/input/layout_keys.rs` | 3 | — | — | +| `crates/ui-egui/src/input/page_keys.rs` | 2 | — | — | +| `crates/ui-egui/src/input/scrub_wrap.rs` | 2 | — | — | +| `crates/ui-egui/src/input/single_line_drag.rs` | 4 | — | — | +| `crates/ui-egui/src/layer_shortcut_tests.rs` | 10 | — | — | +| `crates/ui-egui/src/layer_via_label_tests.rs` | 5 | — | — | +| `crates/ui-egui/src/layers_empty_area_menu_tests.rs` | 10 | — | — | +| `crates/ui-egui/src/marquee_press_mods_tests.rs` | 3 | — | — | +| `crates/ui-egui/src/menu_item_labels_tests.rs` | 4 | — | — | +| `crates/ui-egui/src/menus/menu_keys.rs` | 4 | — | — | +| `crates/ui-egui/src/menus/menu_keys/harness_tests.rs` | 23 | 1 | — | +| `crates/ui-egui/src/menus/menu_nav/tests.rs` | 24 | — | — | +| `crates/ui-egui/src/mixer_cursor_tests.rs` | 5 | — | — | +| `crates/ui-egui/src/new_doc_pixel_aspect_tests.rs` | 7 | — | — | +| `crates/ui-egui/src/new_doc_save_preset_icon_tests.rs` | 7 | — | — | +| `crates/ui-egui/src/new_doc_web_artboards_tests.rs` | 8 | — | — | +| `crates/ui-egui/src/new_group_button_tests.rs` | 8 | — | — | +| `crates/ui-egui/src/options_hit_area_tests.rs` | 11 | — | — | +| `crates/ui-egui/src/panels/brushes_tab/tests.rs` | 12 | — | — | +| `crates/ui-egui/src/panels/compact_visual_regressions.rs` | 12 | — | — | +| `crates/ui-egui/src/panels/layer_filter_ui/effect_tests.rs` | 5 | — | — | +| `crates/ui-egui/src/panels/layer_filter_ui/group_tests.rs` | 7 | — | — | +| `crates/ui-egui/src/panels/layer_menu_ui/color_tests.rs` | 4 | — | — | +| `crates/ui-egui/src/panels/layer_pct_slider_tests.rs` | 7 | — | — | +| `crates/ui-egui/src/panels/layer_reveal/tests.rs` | 3 | — | — | +| `crates/ui-egui/src/panels/layer_row_ui/edit_tests.rs` | 7 | 1 | — | +| `crates/ui-egui/src/panels/layer_row_ui/rename_tests.rs` | 8 | — | — | +| `crates/ui-egui/src/panels/layer_row_ui/tests.rs` | 25 | 1 | — | +| `crates/ui-egui/src/panels/layer_tree_ui/tests.rs` | 7 | — | — | +| `crates/ui-egui/src/panels/options_bar/hand_tooltips_tests.rs` | 3 | — | — | +| `crates/ui-egui/src/panels/options_bar/zoom_buttons_tests.rs` | 4 | — | — | +| `crates/ui-egui/src/panels/panel_state.rs` | 1 | — | — | +| `crates/ui-egui/src/panels/props_layout/tests.rs` | 13 | 1 | — | +| `crates/ui-egui/src/panels/titlebar/tests.rs` | 25 | — | — | +| `crates/ui-egui/src/pen_path_visual_tests.rs` | 1 | — | — | +| `crates/ui-egui/src/pencil_auto_erase_tooltip_tests.rs` | 1 | — | — | +| `crates/ui-egui/src/pencil_shift_digit_opacity_tests.rs` | 4 | — | — | +| `crates/ui-egui/src/polygon_lasso_step_snap_tests.rs` | 7 | — | — | +| `crates/ui-egui/src/prefs/flick_pan.rs` | 4 | — | — | +| `crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs` | 10 | — | — | +| `crates/ui-egui/src/profile_prompt_tests.rs` | 2 | — | — | +| `crates/ui-egui/src/shape_bounds_box_tests.rs` | 18 | 6 | 2 | +| `crates/ui-egui/src/sharpen_refusal_alert_tests.rs` | 7 | 4 | — | +| `crates/ui-egui/src/sharpen_strength_alert_tests.rs` | 5 | — | — | +| `crates/ui-egui/src/smoothing_options_greyed_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/smudge_default_tip_tests.rs` | 4 | 2 | — | +| `crates/ui-egui/src/smudge_mode_bar_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/smudge_strength_alert_tests.rs` | 5 | — | — | +| `crates/ui-egui/src/sponge_default_tip_tests.rs` | 4 | 2 | — | +| `crates/ui-egui/src/sponge_flow_field_tests.rs` | 9 | — | — | +| `crates/ui-egui/src/sponge_refusal_alert_tests.rs` | 6 | 5 | — | +| `crates/ui-egui/src/state/type_default_size_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/status_bar_tests.rs` | 8 | — | — | +| `crates/ui-egui/src/text/bidi_text.rs` | 1 | — | — | +| `crates/ui-egui/src/text/egui_fonts.rs` | 3 | — | — | +| `crates/ui-egui/src/text/font_filters.rs` | 3 | — | — | +| `crates/ui-egui/src/text/font_preview.rs` | 5 | — | — | +| `crates/ui-egui/src/tool_options_theme_tests.rs` | 4 | — | — | +| `crates/ui-egui/src/toolbar_more_slot_flyout_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/tools/analysis_ruler_click_tests.rs` | 4 | — | — | +| `crates/ui-egui/src/tools/analysis_ruler_escape_tests.rs` | 2 | — | — | +| `crates/ui-egui/src/tools/analysis_ruler_move_tests.rs` | 5 | — | — | +| `crates/ui-egui/src/tools/analysis_ruler_shift_tests.rs` | 4 | — | — | +| `crates/ui-egui/src/tools/analysis_ruler_visibility_tests.rs` | 3 | — | — | +| `crates/ui-egui/src/tools/analysis_ui/sampler_drag_tests.rs` | 11 | — | — | +| `crates/ui-egui/src/tools/analysis_ui/sampler_extras_tests.rs` | 2 | — | — | +| `crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs` | 8 | 2 | — | +| `crates/ui-egui/src/tools/analysis_ui/tests.rs` | 14 | 9 | 2 | +| `crates/ui-egui/src/tools/anchor_tools/delete_anchor_shown_anchors_tests.rs` | 5 | — | — | +| `crates/ui-egui/src/tools/corner_radius/tests.rs` | 13 | 5 | — | +| `crates/ui-egui/src/tools/crop_mode/tests.rs` | 26 | — | — | +| `crates/ui-egui/src/tools/crop_options_labels_tests.rs` | 10 | — | — | +| `crates/ui-egui/src/tools/crop_overlay.rs` | 13 | — | — | +| `crates/ui-egui/src/tools/crop_shield.rs` | 14 | 1 | — | +| `crates/ui-egui/src/tools/crop_size.rs` | 18 | — | — | +| `crates/ui-egui/src/tools/crop_straighten.rs` | 9 | — | — | +| `crates/ui-egui/src/tools/direct_select/alt_drag_duplicate_tests.rs` | 7 | — | — | +| `crates/ui-egui/src/tools/direct_select/convert_point_tolerance_tests.rs` | 9 | — | — | +| `crates/ui-egui/src/tools/direct_select/shift_angle_tests.rs` | 5 | — | — | +| `crates/ui-egui/src/tools/ellipse_center_mark_tests.rs` | 4 | — | — | +| `crates/ui-egui/src/tools/gradient_refusal_messages_tests.rs` | 4 | 2 | — | +| `crates/ui-egui/src/tools/lasso_ui/tests.rs` | 21 | 6 | — | +| `crates/ui-egui/src/tools/line_live_handles_tests.rs` | 8 | — | — | +| `crates/ui-egui/src/tools/magnetic_lasso_ui/caps_lock_cursor_tests.rs` | 3 | — | — | +| `crates/ui-egui/src/tools/perspective_crop_click_preview_tests.rs` | 9 | — | — | +| `crates/ui-egui/src/tools/perspective_crop_modifiers_tests.rs` | 11 | — | — | +| `crates/ui-egui/src/tools/perspective_crop_shield_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/tools/remove_default_size_tests.rs` | 4 | — | — | +| `crates/ui-egui/src/tools/remove_locked_alert_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/tools/shape_stroke_ui/shortcut_tests.rs` | 4 | — | — | +| `crates/ui-egui/src/tools/transform_tex.rs` | 5 | 1 | — | +| `crates/ui-egui/src/tools/transform_tool/warp_handles_visible_tests.rs` | 4 | — | — | +| `crates/ui-egui/src/tools/transform_tool/warp_options_bar_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/tools/transform_tool/warp_split_one_shot_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/tools/type_tool/fonts_loading_tests.rs` | 1 | — | — | +| `crates/ui-egui/src/tools/type_tool/options_tooltips_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/tools/type_tool/size_presets_tests.rs` | 13 | — | — | +| `crates/ui-egui/src/tools/vector_ui/add_anchor_options_bar_tests.rs` | 1 | — | — | +| `crates/ui-egui/src/tools/vector_ui/delete_anchor_options_bar_tests.rs` | 2 | — | — | +| `crates/ui-egui/src/tools/vector_ui/pen_alt_drag_segment_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/tools/vector_ui/pen_mode_menu_tests.rs` | 5 | — | — | +| `crates/ui-egui/src/tools/vector_ui/rectangle_path_make_tests.rs` | 1 | — | — | +| `crates/ui-egui/src/tools/warp_preview.rs` | 4 | — | — | +| `crates/ui-egui/src/tools/zoom_tool/tests.rs` | 12 | 1 | — | +| `crates/ui-egui/src/tools/zoom_tool/zoom_out_mode_tests.rs` | 8 | — | — | +| `crates/ui-egui/src/transform_corner_projection_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/transform_reference_point_tests.rs` | 4 | — | — | +| `crates/ui-egui/src/transform_relative_position_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/transform_rotate_snap_tests.rs` | 3 | — | — | +| `crates/ui-egui/src/widgets/angle_dial.rs` | 4 | — | — | +| `crates/ui-egui/src/widgets/color_button_tests.rs` | 4 | — | — | +| `crates/ui-egui/src/widgets/color_count.rs` | 3 | — | — | +| `crates/ui-egui/src/widgets/field_tab.rs` | 4 | — | — | +| `crates/ui-egui/src/widgets/field_wheel.rs` | 20 | — | — | +| `crates/ui-egui/src/widgets/numeric_expression.rs` | 5 | — | — | +| `crates/ui-egui/src/widgets/numeric_input_tests.rs` | 6 | — | — | +| `crates/ui-egui/src/widgets/point_curve.rs` | 6 | 6 | 6 | +| `crates/ui-egui/src/widgets/press_menu.rs` | 9 | — | — | +| `crates/ui-egui/src/widgets/swap_arrow.rs` | 3 | — | — | +| `crates/ui-egui/src/widgets/tab_strip.rs` | 5 | — | — | +| `crates/ui-egui/src/widgets/task_bar.rs` | 4 | — | — | +| `crates/ui-egui/src/widgets/tests.rs` | 82 | — | — | +| `crates/ui-egui/src/widgets/text_field_menu.rs` | 2 | — | — | +| `crates/ui-egui/src/widgets/tone.rs` | 15 | 13 | 13 | +| `crates/ui-egui/src/widgets/type_ahead.rs` | 8 | — | — | +| `crates/ui-egui/tests/it/actions_record_again.rs` | 4 | 4 | — | +| `crates/ui-egui/tests/it/background_eraser_reset_tip.rs` | 4 | 2 | — | +| `crates/ui-egui/tests/it/camera_raw_localization.rs` | 1 | — | — | +| `crates/ui-egui/tests/it/camera_raw_zoom.rs` | 6 | — | — | +| `crates/ui-egui/tests/it/crop_beyond_canvas.rs` | 1 | — | — | +| `crates/ui-egui/tests/it/crop_default_mode.rs` | 6 | — | — | +| `crates/ui-egui/tests/it/crop_frame_look.rs` | 10 | — | — | +| `crates/ui-egui/tests/it/crop_overlay_icons.rs` | 5 | — | — | +| `crates/ui-egui/tests/it/crop_popup_keys.rs` | 2 | — | — | +| `crates/ui-egui/tests/it/crop_shift_corner.rs` | 9 | — | — | +| `crates/ui-egui/tests/it/crop_turn_grid.rs` | 10 | — | — | +| `crates/ui-egui/tests/it/crop_turn_keeps_frame_inside.rs` | 8 | — | — | +| `crates/ui-egui/tests/it/custom_print_paper.rs` | 6 | 5 | 1 | +| `crates/ui-egui/tests/it/export_as_scaling.rs` | 2 | — | — | +| `crates/ui-egui/tests/it/eyedropper_ring.rs` | 2 | — | — | +| `crates/ui-egui/tests/it/marching_ants_pixels.rs` | 2 | — | — | +| `crates/ui-egui/tests/it/marquee_autoscroll.rs` | 3 | — | — | +| `crates/ui-egui/tests/it/transform_readout_units.rs` | 1 | — | — | +| `crates/ui-egui/tests/magnetic_lasso_spacing.rs` | 11 | — | — | +| `crates/ui-egui/tests/magnetic_lasso_width_keys.rs` | 5 | — | — | From 2134254ad59d5d7455eecb1c67624199a5b8ba46 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:09:03 +0100 Subject: [PATCH 15/38] Restore crop ratio popup keyboard regression coverage --- crates/ui-egui/tests/it/crop_task_bar.rs | 35 ++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/crates/ui-egui/tests/it/crop_task_bar.rs b/crates/ui-egui/tests/it/crop_task_bar.rs index 14a391c1db..30bbe4d907 100644 --- a/crates/ui-egui/tests/it/crop_task_bar.rs +++ b/crates/ui-egui/tests/it/crop_task_bar.rs @@ -176,6 +176,41 @@ fn the_bars_preset_dropdown_is_the_options_bars() { assert_eq!(h.get_all_by_value("1 : 1 (Square)").count(), 2, "the options bar shows the same preset"); } +#[test] +fn the_options_bar_ratio_list_takes_escape_and_enter_before_the_crop() { + let mut h = harness(); + control(&mut h, "ui.set", json!({"panels": {"context_task_bar": false}})); + draw_frame(&mut h, [100.0, 50.0], [300.0, 250.0]); + assert!(pending(h.state()), "the drawn square crop is pending"); + let before = frame_rect(&h).expect("the pending frame"); + let size = |h: &Harness| h.state().session.active().map(|s| (s.doc.size.width, s.doc.size.height)); + let square = "1 : 1 (Square)"; + + // Escape dismisses the list. Enter accepts its first row, the selected free Ratio. + // Neither key should reach the pending crop while the list is open (#7386). + for key in [egui::Key::Escape, egui::Key::Enter] { + assert!(!has(&h, square), "the square row is only in the open list"); + let at = h.get_by_value("Ratio").rect().center(); + click_at(&mut h, at); + assert!(has(&h, square), "the options bar ratio list opened"); + h.key_press(key); + h.run_steps(12); + assert!(!has(&h, square), "{key:?} closed the ratio list"); + assert!(pending(h.state()), "{key:?} left the crop pending"); + assert_eq!(frame_rect(&h), Some(before), "{key:?} left the frame alone"); + assert_eq!(size(&h), Some((400, 300)), "{key:?} did not crop the document"); + } + + // A closed dropdown still has focus. Click inside the frame to return focus to the canvas. + let at = h.state().last_canvas_rect.center(); + click_at(&mut h, at); + assert_eq!(frame_rect(&h), Some(before), "the click only moved focus"); + h.key_press(egui::Key::Enter); + h.run_steps(6); + assert_eq!(size(&h), Some((200, 200)), "Enter on the canvas commits the pending crop"); + assert!(!pending(h.state())); +} + #[test] fn inspect_reports_a_bar_hidden_before_the_next_draw_as_hidden() { let mut h = harness(); From b94787a48d45bd41d431d127b48957f96004884a Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:11:40 +0100 Subject: [PATCH 16/38] Record additional reviewed framework successors --- docs/integration-testing/framework-port-test-map.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/integration-testing/framework-port-test-map.md b/docs/integration-testing/framework-port-test-map.md index 72a59060b7..9f913b5045 100644 --- a/docs/integration-testing/framework-port-test-map.md +++ b/docs/integration-testing/framework-port-test-map.md @@ -21,6 +21,8 @@ The source scan recognized Rust functions marked `#[test]`, namespaced `#[…::t | [`crates/ui-egui/tests/it/crop_turn_keeps_frame_inside.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/tests/it/crop_turn_keeps_frame_inside.rs#L152) | [Turned crop fit](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-canvas/tests/it/canvas/crop.rs#L667) | Checks fit, shrink, restore, corner movement and the Command override. Committed pixels and a modifier changed during a turn remain open. | | [`crates/ui-egui/src/tools/crop_mode/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/tools/crop_mode/tests.rs#L519) | [Dropped crop on document switch](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/tools/crop_mode_tests.rs#L92) | Switching away drops the pending crop and returns the original view upright. The old test repeated the scenario in both document orders. | | [`crates/ui-egui/src/input/control_click.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/input/control_click.rs#L45) | [macOS Control-click](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-contract/tests/it/runtime/control_click.rs#L39), [PhotoCraft menus](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/canvas_menu_tests.rs#L88) | Checks secondary click through release, other modifiers and platforms, re-entry and the next primary click. PhotoCraft also checks that the right menus open. | +| [`crates/ui-egui/src/input/scrub_wrap.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/input/scrub_wrap.rs#L75) | [Scrub wrap](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-widgets/tests/it/label/mod.rs#L44) | Checks that a warp landing and the next move preserve a continuous value. Movement coalesced with the landing event and both logical edges remain open. | +| [`crates/ui-egui/src/input/page_keys.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/input/page_keys.rs#L116) | [Canvas page navigation](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-canvas/tests/it/canvas/navigate.rs#L62) | Checks vertical Page Down and horizontal Cmd or Ctrl Page Down. The legacy zoom-scaled amount, Shift step and Home or End corner assertions still need review. | | [`crates/ui-egui/src/menus/menu_keys/harness_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/menus/menu_keys/harness_tests.rs#L397) | [Command shortcut focus](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-widgets/tests/it/menu/pick_focus.rs#L131) | A command dispatches once, closes the menu and restores its prior focus. | | [`crates/ui-egui/src/menus/menu_nav/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/menus/menu_nav/tests.rs#L453) | [Popup clearance](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-widgets/tests/it/menu/overflow.rs#L169) | The menu and submenu clear the bar and stay in the window. The original ran across more display and menu configurations. | | [`crates/ui-egui/src/menus/menu_nav/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/menus/menu_nav/tests.rs#L832) | [Submenu pointer path](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-widgets/tests/it/menu/submenus.rs#L42) | Moving toward the open submenu over a competing row keeps it open, then a rested pointer switches it. The legacy path matrix was broader. | @@ -36,6 +38,7 @@ The source scan recognized Rust functions marked `#[test]`, namespaced `#[…::t | [`crates/ui-egui/src/dialogs/export_dialog/enter_key_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/export_dialog/enter_key_tests.rs#L51) | [Explicit export button](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-patterns/tests/it/form_dialogs/hosted.rs#L265), [Scale field Enter](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-patterns/tests/it/form_dialogs/hosted.rs#L348), [Escape cancellation](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-patterns/tests/it/form_dialogs/hosted.rs#L104) | Bare Enter keeps Export As open. Enter in Scale commits the field, only the button requests a path, and Escape reaches the host as Cancel. | | [`crates/ui-egui/src/dialogs/image_size_readout_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/image_size_readout_tests.rs#L43) | [Flat image size](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/dialogs/sizing/tests.rs#L159), [Bitmap row padding and previous size](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-patterns/tests/it/form_dialogs/hosted.rs#L385) | Checks channel and depth calculations, whole-byte bitmap rows and when the previous size appears. Localized formatting and same-byte changes remain open. | | [`crates/ui-egui/src/dialogs/image_size_resample_shortcuts_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/image_size_resample_shortcuts_tests.rs#L74) | [Alt-digit resampling](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-patterns/tests/it/form_dialogs/hosted.rs#L404) | Checks two picks, ignored chords, typing in the field and unavailable choices. Full key position coverage, same-frame ordering and applying the choice remain open. | +| [`crates/ui-egui/src/dialogs/camera_raw_preview_ui.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/camera_raw_preview_ui.rs#L299) | [Leaving Fit](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-canvas/tests/it/full_window_parts.rs#L27), [Pointer anchor](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-canvas/tests/it/full_window_parts.rs#L107), [Shift+Alt zoom ladder](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-canvas/tests/it/canvas/navigate.rs#L555) | Shared canvas tests cover the core navigation. The Camera Raw input wiring and its pan and snap limits still need app-level coverage. | The Magnetic Lasso cursor-preference matrix returned in [PhotoCraft #15805](https://github.com/storytold/photocraft/pull/15805). The removed Alt+Tab case has a draft in [craft-libs #2805](https://github.com/storytold/craft-libs/pull/2805). Customized-workspace Properties coverage is tracked in [#15791](https://github.com/storytold/photocraft/issues/15791). @@ -52,7 +55,7 @@ These assertions have no equivalent identified in the reviewed successors. The g - Off-field diagonal selection follows x on single-line fields and preserves multiline movement. [Original assertion](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/input/single_line_drag.rs#L157) - Field-local rejection before parsing, including Unicode, IME, undo and same-frame Tab. [Original assertion](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/widgets/numeric_input_tests.rs#L52) - Fit Image validation and undo across field editing and programmatic input. [Original assertion](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/fit_image_range_tests.rs#L59) -- Camera Raw anchored zoom, clamped panning, snap limits and fitting after tiny or nonfinite resize. [Original assertion](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/camera_raw_preview_ui.rs#L299) +- Camera Raw-specific clamped panning, snap limits and fitting after tiny or nonfinite resize. [Original assertion](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/camera_raw_preview_ui.rs#L299) - Dialog-specific undo isolation for Filter Gallery and Vanishing Point. [Original assertion](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/edit_history.rs#L197) ## Identical body matches From d23c5957b1353e7b2e66725d1be0e6d5f94e86f6 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:48:32 +0000 Subject: [PATCH 17/38] Map additional framework regression tests --- .../framework-port-test-map.md | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/docs/integration-testing/framework-port-test-map.md b/docs/integration-testing/framework-port-test-map.md index 9f913b5045..9c2d1ee6b0 100644 --- a/docs/integration-testing/framework-port-test-map.md +++ b/docs/integration-testing/framework-port-test-map.md @@ -39,6 +39,34 @@ The source scan recognized Rust functions marked `#[test]`, namespaced `#[…::t | [`crates/ui-egui/src/dialogs/image_size_readout_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/image_size_readout_tests.rs#L43) | [Flat image size](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/dialogs/sizing/tests.rs#L159), [Bitmap row padding and previous size](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-patterns/tests/it/form_dialogs/hosted.rs#L385) | Checks channel and depth calculations, whole-byte bitmap rows and when the previous size appears. Localized formatting and same-byte changes remain open. | | [`crates/ui-egui/src/dialogs/image_size_resample_shortcuts_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/image_size_resample_shortcuts_tests.rs#L74) | [Alt-digit resampling](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-patterns/tests/it/form_dialogs/hosted.rs#L404) | Checks two picks, ignored chords, typing in the field and unavailable choices. Full key position coverage, same-frame ordering and applying the choice remain open. | | [`crates/ui-egui/src/dialogs/camera_raw_preview_ui.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/camera_raw_preview_ui.rs#L299) | [Leaving Fit](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-canvas/tests/it/full_window_parts.rs#L27), [Pointer anchor](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-canvas/tests/it/full_window_parts.rs#L107), [Shift+Alt zoom ladder](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-canvas/tests/it/canvas/navigate.rs#L555) | Shared canvas tests cover the core navigation. The Camera Raw input wiring and its pan and snap limits still need app-level coverage. | +| [`apps/photocraft/src/icon_theme.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/apps/photocraft/src/icon_theme.rs#L250) | [Desktop icon themes](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/window/src/desktop/icon_theme.rs#L220), [Caption masks](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-shell/tests/it/shell/caption_button.rs#L51) | Theme lookup follows the child, parent and hicolor order, honors icon size and XDG paths, and handles cyclic indexes. Caption tests cover mask dimensions and pixels, refused renders and images producing no coverage. | +| [`apps/photocraft/src/file_dialog_probe.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/apps/photocraft/src/file_dialog_probe.rs#L140) | [File chooser backend probe](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/dialogs/src/probe/tests.rs#L11) | Retains no-backend diagnostics, exact FileChooser interface matching, and the distinction between missing-interface errors and inconclusive access errors. The former executable PATH lookup has no assertion in this group. | +| [`apps/photocraft/src/portal_save/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/apps/photocraft/src/portal_save/tests.rs#L134) | [Portal URI and file type tests](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/dialogs/src/portal/tests.rs#L23) | Checks local URI decoding and when the chosen type supplies or replaces an extension. The successor uses a pure filename helper. The former mocked portal handle, overwrite and cancel sequences need separate coverage. | +| [`crates/ui-egui/tests/it/actions_record_again.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/tests/it/actions_record_again.rs#L47) | [Record Again tests](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/panels/actions/record_again_tests.rs#L89) | Retains seeded dimensions, cancellation, a single-step update with its flags, preservation on stale or denied edits, cross-dialog isolation and preview authorization. The hosted dialog test reads fields through the current control route. | +| [`crates/ui-egui/tests/it/custom_print_paper.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/tests/it/custom_print_paper.rs#L177) | [Custom paper tests](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/dialogs/file_ui/custom_paper_tests.rs#L144) | Retains custom dimensions across units, presets and reopening, preview and PDF orientation, postcard aliases and rejection without document or output changes. The old standard- and Retina-scale drag fixture is outside these five cases. | +| [`crates/ui-egui/src/background_eraser_alt_click_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/background_eraser_alt_click_tests.rs#L127) | [Brush resize and Alt sampling](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/tools/brush_resize/tests.rs#L155) | Retains foreground sampling without a paint or history step, plain erase dispatch, and the Ctrl+Alt and Alt+right resize routes. The former per-pixel and in-flight assertions still need mapping. | +| [`crates/ui-egui/src/background_eraser_bar_angle_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/background_eraser_bar_angle_tests.rs#L134) | [Background Eraser angle and pressure](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs#L91) | Brush and Background Eraser retain separate angle and pressure settings after tool switches. Visible angle text is a separate legacy assertion. | +| [`crates/ui-egui/src/background_eraser_bar_angle_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/background_eraser_bar_angle_tests.rs#L66) | [Options bar range alerts](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs#L53) | The hosted field clamps angles to −180° or 180° and retains the accepted value after dismissing one alert. Fractional angles still need a successor. | +| [`crates/ui-egui/src/brush_picker_angle_widget_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/brush_picker_angle_widget_tests.rs#L88) | [Brush-picker angle drag](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/brush_picker_escape_tests.rs#L75) | A drag in the real popup reaches 135° with one brush command. The old panel helper and simultaneous roundness check still need a mapping. | +| [`crates/ui-egui/src/background_eraser_digit_keys_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/background_eraser_digit_keys_tests.rs#L63) | [Tool-specific digit values](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/input/opacity_keys.rs#L195), [Double-zero dispatch](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/input/opacity_keys.rs#L252) | Preserves unrelated brush, layer and tool values, leaves Background Eraser tolerance alone on Shift digits, and sets it to 100% on double-zero. The new plain-digit case starts at the expected value, so it establishes isolation rather than a nondefault change. | +| [`crates/ui-egui/src/brush_alt_digit_smoothing_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/brush_alt_digit_smoothing_tests.rs#L44) | [Tool smoothing dispatch](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/input/opacity_keys.rs#L293) | Preserves other smoothing preferences, interrupts a pending opacity pair and ignores smoothing on Move. Actual Alt-key routing still needs an end-to-end case. | +| [`crates/ui-egui/src/brush_opacity_minimum_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/brush_opacity_minimum_tests.rs#L77) | [Brush and Pencil double-zero](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/input/opacity_keys.rs#L252), [Digit-pair timing](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/input/opacity_keys.rs#L275) | Checks Brush and Pencil opacity at 100%, Brush flow at 1% and the digit pairing window. The legacy leading-zero and build-up-specific cases still need mapping. | +| [`crates/ui-egui/src/sponge_flow_field_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/sponge_flow_field_tests.rs#L88) | [Sponge range alert](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs#L53), [Retouch dab parameters](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/tools/retouch_ui/tests.rs#L249) | Covers upper-bound clamping with one alert and checks that dabs send the bar value, including rounding a restored 33.7 to 34. Lower-bound typing and the painted-pixel check need separate cases. | +| [`crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs#L603) | [Restoring the active Camera Raw modal](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-contract/tests/it/runtime/windows.rs#L177), [Modal activation across window systems](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-contract/tests/it/runtime/windows.rs#L129) | Checks that regaining main-window focus restores and raises a Camera Raw modal, with platform-specific attention requests. The already-focused dimmed click is a separate legacy path. | +| [`crates/ui-egui/src/dialogs/rgb_histogram.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/rgb_histogram.rs#L189) | [Typical histogram scale](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/imaging/tests/it/histogram.rs#L34), [Overlapping color channels](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/imaging/tests/it/histogram.rs#L48) | Checks that spikes can clip while typical detail remains visible, and that crossing channels retain their overlap color. The old mask, theme and geometry matrices still need mapping. | +| [`crates/ui-egui/src/dialogs/edit_history.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/edit_history.rs#L175) | [Dialog-local undo and drag](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-patterns/tests/it/form_dialogs/dialog.rs#L31), [Redo truncation](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/behavior/src/edit_history.rs#L155), [Undo routing to the dialog](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-shell/tests/it/commands/board.rs#L112) | Covers a drag as one undo step, dropping redo after a new edit and routing undo to the modal instead of the application. Lens Correction and Vanishing Point still need case-specific mapping. | +| [`crates/ui-egui/src/dialogs/edit_history.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/edit_history.rs#L225) | [Filter Gallery undo and selection](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/imaging/tests/it/filter_gallery.rs#L181) | The shared workspace reduces two effects to one on Command-Z, clamps the selection and reports it once. PhotoCraft document-history isolation was a separate legacy assertion. | +| [`crates/ui-egui/src/dialogs/credits/ui_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/credits/ui_tests.rs#L101) | [Contributor sorting](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-patterns/tests/it/form_dialogs/about.rs#L235), [Generic table alignment and scroll](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-widgets/tests/it/table.rs#L323) | Checks actual About header sorting and undated rows staying last. Shared table tests cover numeric alignment and header scrolling. About-specific column widths and resize persistence remain open. | +| [`crates/ui-egui/src/dialogs/shape_dialog/create_triangle_range_alert_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/shape_dialog/create_triangle_range_alert_tests.rs#L59) | [Triangle and Rectangle range alerts](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/draw/tests/it/shape_drag.rs#L344), [Creating a Triangle in PhotoCraft](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/dialogs/shape_dialog/tests.rs#L79) | Checks out-of-range Triangle and Rectangle dimensions clamping with one alert on Tab, in-range input without an alert, and valid Triangle confirmation creating a layer. Rectangle now alerts too. Confirm while alerting, Cancel and comma-locale cases still need mapping. | +| [`crates/ui-egui/src/dialogs/fit_image_range_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/fit_image_range_tests.rs#L59) | [Hosted integer field validation](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-patterns/tests/it/form_dialogs/dialog.rs#L765), [Escape during a dialog draft](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-patterns/tests/it/form_dialogs/dialog.rs#L563), [Fit Image staging and confirmation](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/menus/view_cmds/tests.rs#L156) | The shared field exercises the same integer bounds and verifies clamping with one alert on Tab. Nonnumeric text now retains the value without an alert. The app test checks staging and valid confirmation. Invalid Fit Image submission and its undo behavior still need app-level cases. | +| [`crates/ui-egui/src/dialogs/dialog_alt_reset.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/dialogs/dialog_alt_reset.rs#L81) | [Alt changes Cancel to Reset](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/ui-patterns/tests/it/form_dialogs/dialog.rs#L586) | The hosted footer retains a deliberate in-place reset to opening or explicit values. The old JSON marker has been replaced by typed opt-in, whose opt-out path still needs a matching assertion. | +| [`crates/ui-egui/src/tools/analysis_ui/sampler_drag_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/tools/analysis_ui/sampler_drag_tests.rs#L63) | [Color Sampler press and release](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/color-ui/tests/it/sampling.rs#L78) | Retains adding and moving on release, cancelling placement with Escape, refusing an off-canvas addition, removing by dragging out or using Alt, and refusal at the point limit. Live PhotoCraft marker painting and numbering still need coverage. | +| [`crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs#L120) | [Stale sampler menu](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs#L31) | A stale point index or document cannot delete another sample. The successor checks the menu helper directly and closes the stale menu. The former control-channel refusal and menu painting are separate paths. | +| [`crates/ui-egui/src/tools/analysis_ui/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/tools/analysis_ui/tests.rs#L106) | [Count Tool transactions](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/tools/analysis/tests.rs#L52), [Note defaults and panel state](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/tools/analysis/tests.rs#L115) | Retains Count Tool placement, movement and Alt-removal, including one history entry for a real move. Note tests verify selection, the panel opening, drag movement, sampled author and color, and reuse for a new note. | +| [`crates/ui-egui/src/tools/corner_radius/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/tools/corner_radius/tests.rs#L45) | [Corner radius handle](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/tools/shape_controls/corner_tests.rs#L87), [Corner radius across selected shapes](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/tools/shape_controls/corner_tests.rs#L100) | Retains all-corner and multi-target drags as one history step, skips an unselected shape and honors per-shape limits. Alt for a single corner and live cursor and readout still need mapping. | +| [`crates/ui-egui/src/tools/lasso_ui/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/tools/lasso_ui/tests.rs#L29) | [Straight lasso segments](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/imaging/tests/it/select.rs#L551), [Latched lasso operation](https://github.com/storytold/craft-libs/blob/683fe06031224725b913c8ad3697d8e8bfec6c90/crates/imaging/tests/it/select.rs#L640) | Checks straight vertices while Alt is held, closing on release and initial Subtract surviving later modifier changes. The old final mask, undo and initial Shift/Add and Alt+Shift/Intersect cases still need mapping. | +| [`crates/ui-egui/src/tools/lasso_ui/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/tools/lasso_ui/tests.rs#L174) | [Pasteboard click and drag](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/lasso_click_tests.rs#L21) | Retains the click modifier matrix, one undo step and the actual mask sample from a drag that starts on the pasteboard. | +| [`crates/ui-egui/src/tools/lasso_ui/tests.rs`](https://github.com/storytold/photocraft/blob/01b79958a7b73c3d840b76492069e9635f9f7394/crates/ui-egui/src/tools/lasso_ui/tests.rs#L231) | [Freeform Pen owned paths](https://github.com/storytold/photocraft/blob/42c853396d147a554f540c9723b90e1179080a79/crates/ui-egui/src/tools/vector_ui/freeform_pen_tests.rs#L60) | Retains the old subpath, straight controls, one history step and undo, and rejects a changed target, source, revision or document. The old same-press Alt release case still needs mapping. | The Magnetic Lasso cursor-preference matrix returned in [PhotoCraft #15805](https://github.com/storytold/photocraft/pull/15805). The removed Alt+Tab case has a draft in [craft-libs #2805](https://github.com/storytold/craft-libs/pull/2805). Customized-workspace Properties coverage is tracked in [#15791](https://github.com/storytold/photocraft/issues/15791). From a7948b7a3ad5ddc22665f15a8ad1783e1aaeef2a Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:56:46 +0100 Subject: [PATCH 18/38] Restore Fit Image dialog validation coverage --- crates/ui-egui/src/menus/view_cmds/tests.rs | 34 +++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/ui-egui/src/menus/view_cmds/tests.rs b/crates/ui-egui/src/menus/view_cmds/tests.rs index 89b022749f..cf88596d58 100644 --- a/crates/ui-egui/src/menus/view_cmds/tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/tests.rs @@ -211,6 +211,40 @@ fn command_dialogs_open_and_refuse() { assert!(app.ui.views.is_empty() && app.session.documents().is_empty()); } +/// Fit Image's dialog bounds apply before the command, where a zero side would mean unconstrained. +#[test] +fn fit_image_validates_dialog_bounds_before_one_undoable_resize() { + let (mut app, ctx) = app_with(1); + let id = open_form(&mut app, &ctx, "file.automate.fitImage"); + let opening = fields(&app, id); + let original = app.session.active().unwrap(); + let (size, steps, revision) = (original.doc.size, original.history.past_len(), original.revision); + + for key in ["width", "height"] { + for value in [json!(0), json!(300_001), json!("abc")] { + assert!(app.framework.dialogs.set_json_field(&ctx, id, key, value.clone()).is_err(), "{key} accepted {value}"); + assert_eq!(fields(&app, id), opening); + } + } + + set(&mut app, &ctx, id, "width", json!(1)); + set(&mut app, &ctx, id, "height", json!(300_000)); + let accepted = fields(&app, id); + assert_eq!(accepted["width"].as_f64(), Some(1.0)); + assert_eq!(accepted["height"].as_f64(), Some(300_000.0)); + let staged = app.session.active().unwrap(); + assert_eq!((staged.doc.size, staged.history.past_len(), staged.revision), (size, steps, revision)); + + confirm(&mut app, &ctx, id).unwrap(); + let resized = app.session.active().unwrap(); + assert_eq!((resized.doc.size.width, resized.doc.size.height), (1, 1)); + assert_eq!(resized.history.past_len(), steps + 1); + assert_eq!(resized.history.undo_label(), Some("Image Size")); + + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.size, size); +} + #[test] fn data_sets_as_files_enablement_respects_target_platform() { let (app, _) = app_with(1); From c05add970c466917febc01cabcf8187523ce0027 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:04:14 +0000 Subject: [PATCH 19/38] Cover Color Sampler menu routing and point deletion --- .../src/tools/analysis/sampler_menu_tests.rs | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs b/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs index 2389fd03e4..ad1c6ee0ad 100644 --- a/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs +++ b/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs @@ -25,6 +25,59 @@ fn samplers(app: &PhotocraftApp) -> Vec<[f64; 2]> { app.session.active().unwrap().color_samplers.clone() } +/// The mouse opens the same ordered menu the control channel sees, and only a hit can be deleted. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_sampler_menu_only_deletes_the_point_under_the_pointer() { + use crate::canvas::testing::{control, key}; + + let (mut app, _) = app(); + app.run("view.colorSamplers.add", json!({"x": 180, "y": 90})).unwrap(); + let before = samplers(&app); + let expected_rows = [ + SAMPLER_DELETE, + "colorSampler.readout.actual", + "colorSampler.readout.proof", + "colorSampler.readout.gray", + "colorSampler.readout.rgb", + "colorSampler.readout.web", + "colorSampler.readout.hsb", + "colorSampler.readout.hsl", + "colorSampler.readout.cmyk", + "colorSampler.readout.lab", + "colorSampler.readout.gray16", + "colorSampler.readout.rgb16", + "colorSampler.readout.cmyk16", + "colorSampler.readout.lab16", + "colorSampler.readout.totalInk", + ]; + + for ((x, y), can_delete) in [((70.0, 40.0), false), ((120.0, 60.0), true)] { + right_click(&mut app, x, y); + assert_eq!(samplers(&app), before, "a right-click never places a sampler"); + let inspected = control(&mut app, "ui.inspect", json!({})); + let rows = inspected.pointer("/result/canvasToolMenu/entries").and_then(serde_json::Value::as_array).expect("the open sampler menu"); + let ids: Vec<_> = rows.iter().filter_map(|row| row["id"].as_str()).collect(); + assert_eq!(ids, expected_rows); + assert_eq!(rows.iter().filter(|row| row["separator"] == true).count(), 4); + let enabled: Vec<_> = rows.iter().filter(|row| row["enabled"] == true).map(|row| row["id"].as_str().unwrap()).collect(); + let expected_enabled: &[&str] = if can_delete { &[SAMPLER_DELETE] } else { &[] }; + assert_eq!(enabled, expected_enabled, "right-click at ({x}, {y})"); + + let reply = control(&mut app, "ui.context.choose", json!({"id": SAMPLER_DELETE})); + assert_eq!(reply["ok"], can_delete, "right-click at ({x}, {y}): {reply}"); + if !can_delete { + assert_eq!(samplers(&app), before, "an unavailable Delete changes nothing"); + key(&mut app, egui::Key::Escape, egui::Modifiers::NONE); + } + assert!(app.ui.canvas_tool_menu.is_none(), "the menu closes"); + } + + assert_eq!(samplers(&app), [[20.5, 20.5], [180.5, 90.5]], "only the middle sampler is removed"); + let listed = app.run("view.colorSamplers.list", json!({})).unwrap(); + assert_eq!(listed["samplers"][1]["number"], 2, "the last sampler becomes number 2"); +} + /// Delete never removes a different sampler when the list changes while the menu is open: one /// deleted meanwhile, or another document with a sampler at the same index and spot. #[test] From ffa5efd1a7989f659bedc458dc4e0948bb7224fc Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:07:30 +0000 Subject: [PATCH 20/38] Use an asymmetric resize to verify dialog arguments --- crates/ui-egui/src/menus/view_cmds/tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menus/view_cmds/tests.rs b/crates/ui-egui/src/menus/view_cmds/tests.rs index cf88596d58..ef4261412a 100644 --- a/crates/ui-egui/src/menus/view_cmds/tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/tests.rs @@ -232,12 +232,14 @@ fn fit_image_validates_dialog_bounds_before_one_undoable_resize() { let accepted = fields(&app, id); assert_eq!(accepted["width"].as_f64(), Some(1.0)); assert_eq!(accepted["height"].as_f64(), Some(300_000.0)); + set(&mut app, &ctx, id, "width", json!(80)); + set(&mut app, &ctx, id, "height", json!(40)); let staged = app.session.active().unwrap(); assert_eq!((staged.doc.size, staged.history.past_len(), staged.revision), (size, steps, revision)); confirm(&mut app, &ctx, id).unwrap(); let resized = app.session.active().unwrap(); - assert_eq!((resized.doc.size.width, resized.doc.size.height), (1, 1)); + assert_eq!((resized.doc.size.width, resized.doc.size.height), (50, 40)); assert_eq!(resized.history.past_len(), steps + 1); assert_eq!(resized.history.undo_label(), Some("Image Size")); From b762ac1ea7e66a889537e25b3db84d7a93260d44 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:10:10 +0000 Subject: [PATCH 21/38] Verify the full ordering of Color Sampler menu rows --- .../src/tools/analysis/sampler_menu_tests.rs | 40 ++++++++++--------- 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs b/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs index ad1c6ee0ad..677e1d8db0 100644 --- a/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs +++ b/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs @@ -35,21 +35,25 @@ fn the_sampler_menu_only_deletes_the_point_under_the_pointer() { app.run("view.colorSamplers.add", json!({"x": 180, "y": 90})).unwrap(); let before = samplers(&app); let expected_rows = [ - SAMPLER_DELETE, - "colorSampler.readout.actual", - "colorSampler.readout.proof", - "colorSampler.readout.gray", - "colorSampler.readout.rgb", - "colorSampler.readout.web", - "colorSampler.readout.hsb", - "colorSampler.readout.hsl", - "colorSampler.readout.cmyk", - "colorSampler.readout.lab", - "colorSampler.readout.gray16", - "colorSampler.readout.rgb16", - "colorSampler.readout.cmyk16", - "colorSampler.readout.lab16", - "colorSampler.readout.totalInk", + Some(SAMPLER_DELETE), + None, + Some("colorSampler.readout.actual"), + Some("colorSampler.readout.proof"), + None, + Some("colorSampler.readout.gray"), + Some("colorSampler.readout.rgb"), + Some("colorSampler.readout.web"), + Some("colorSampler.readout.hsb"), + Some("colorSampler.readout.hsl"), + Some("colorSampler.readout.cmyk"), + Some("colorSampler.readout.lab"), + None, + Some("colorSampler.readout.gray16"), + Some("colorSampler.readout.rgb16"), + Some("colorSampler.readout.cmyk16"), + Some("colorSampler.readout.lab16"), + None, + Some("colorSampler.readout.totalInk"), ]; for ((x, y), can_delete) in [((70.0, 40.0), false), ((120.0, 60.0), true)] { @@ -57,9 +61,9 @@ fn the_sampler_menu_only_deletes_the_point_under_the_pointer() { assert_eq!(samplers(&app), before, "a right-click never places a sampler"); let inspected = control(&mut app, "ui.inspect", json!({})); let rows = inspected.pointer("/result/canvasToolMenu/entries").and_then(serde_json::Value::as_array).expect("the open sampler menu"); - let ids: Vec<_> = rows.iter().filter_map(|row| row["id"].as_str()).collect(); - assert_eq!(ids, expected_rows); - assert_eq!(rows.iter().filter(|row| row["separator"] == true).count(), 4); + let order: Vec<_> = + rows.iter().map(|row| if row["separator"] == true { None } else { Some(row["id"].as_str().expect("expected a menu item id")) }).collect(); + assert_eq!(order, expected_rows); let enabled: Vec<_> = rows.iter().filter(|row| row["enabled"] == true).map(|row| row["id"].as_str().unwrap()).collect(); let expected_enabled: &[&str] = if can_delete { &[SAMPLER_DELETE] } else { &[] }; assert_eq!(enabled, expected_enabled, "right-click at ({x}, {y})"); From 3e9bd35d48be126efec006b0286dadf5371e44e3 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:11:03 +0100 Subject: [PATCH 22/38] Restore Alt-drag corner radius coverage --- .../src/tools/shape_controls/corner_tests.rs | 31 ++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/tools/shape_controls/corner_tests.rs b/crates/ui-egui/src/tools/shape_controls/corner_tests.rs index 3ebd32d644..c1d32ca157 100644 --- a/crates/ui-egui/src/tools/shape_controls/corner_tests.rs +++ b/crates/ui-egui/src/tools/shape_controls/corner_tests.rs @@ -57,10 +57,14 @@ fn active(app: &PhotocraftApp) -> photocraft_doc::LayerId { /// A press at `from`, two moves and a release at `to`, as a mouse does it. fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { - testing::press(app, from, NONE); - testing::move_to(app, [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0], NONE); - testing::move_to(app, to, NONE); - testing::release(app, to, NONE); + drag_with_modifiers(app, from, to, NONE); +} + +fn drag_with_modifiers(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + testing::press(app, from, mods); + testing::move_to(app, [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0], mods); + testing::move_to(app, to, mods); + testing::release(app, to, mods); } /// Live rectangles, bottom first: (20, 20) 60 × 40 radii 15, (110, 20) 70 × 50 radii 15, and (20, 120) 80 × 60 @@ -96,6 +100,25 @@ fn dragging_a_widget_rounds_every_corner_in_one_step() { assert_eq!(radii_of(&app, id), [20.0; 4]); } +#[test] +fn alt_drag_changes_only_the_grabbed_corner_within_its_radius_limits() { + let mut app = app(Tool::PathSelection); + let id = active(&app); + let n = steps(&app); + let alt = Modifiers { alt: true, ..Modifiers::NONE }; + + // Drag the bottom-right widget far enough in to reach half the 80 px short side. + drag_with_modifiers(&mut app, [140.0, 100.0], [80.0, 40.0], alt); + assert_eq!(radii_of(&app, id), [20.0, 20.0, 40.0, 20.0]); + assert_eq!(steps(&app), n + 1); + + // Drag the top-right widget out past its corner to take its radius down to zero. + drag_with_modifiers(&mut app, [140.0, 60.0], [180.0, 20.0], alt); + assert_eq!(radii_of(&app, id), [20.0, 0.0, 40.0, 20.0]); + assert_eq!(steps(&app), n + 2); + assert_eq!(active(&app), id); +} + #[test] fn one_widget_rounds_every_selected_rectangle_alike_in_one_step() { let (mut app, ids) = three(Tool::PathSelection); From c31a1dbbc9f5bc6e9555bd134fd83a58997baa17 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:18:57 +0100 Subject: [PATCH 23/38] Check that canvas Enter records exactly one Crop edit --- crates/ui-egui/tests/it/crop_task_bar.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/it/crop_task_bar.rs b/crates/ui-egui/tests/it/crop_task_bar.rs index 30bbe4d907..87b35c7773 100644 --- a/crates/ui-egui/tests/it/crop_task_bar.rs +++ b/crates/ui-egui/tests/it/crop_task_bar.rs @@ -184,6 +184,8 @@ fn the_options_bar_ratio_list_takes_escape_and_enter_before_the_crop() { assert!(pending(h.state()), "the drawn square crop is pending"); let before = frame_rect(&h).expect("the pending frame"); let size = |h: &Harness| h.state().session.active().map(|s| (s.doc.size.width, s.doc.size.height)); + let history = |h: &Harness| h.state().session.active().expect("the crop document").history.past_len(); + let steps = history(&h); let square = "1 : 1 (Square)"; // Escape dismisses the list. Enter accepts its first row, the selected free Ratio. @@ -208,7 +210,7 @@ fn the_options_bar_ratio_list_takes_escape_and_enter_before_the_crop() { h.key_press(egui::Key::Enter); h.run_steps(6); assert_eq!(size(&h), Some((200, 200)), "Enter on the canvas commits the pending crop"); - assert!(!pending(h.state())); + assert_eq!(history(&h), steps + 1, "Enter adds one document history step"); } #[test] From 59b1751e2106ff9a2277af6de95041113e8655a2 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:23:42 +0000 Subject: [PATCH 24/38] Pass the live Crop tool through the canvas adapter --- crates/ui-egui/src/canvas/tools/crop.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas/tools/crop.rs b/crates/ui-egui/src/canvas/tools/crop.rs index d172d522bb..0d9bc1296e 100644 --- a/crates/ui-egui/src/canvas/tools/crop.rs +++ b/crates/ui-egui/src/canvas/tools/crop.rs @@ -21,7 +21,7 @@ pub(crate) fn show_frame(app: &mut PhotocraftApp, ui: &mut egui::Ui, rect: egui: Some(app.canvas_tools.crop.tool.show_frame(ui, rect, &run.input(&ctx))) } -/// Applies what the pass reported to the document and the crop options. -pub(crate) fn finish(app: &mut PhotocraftApp, output: CropOutput) { - crate::crop_ui::finish(app, output); +/// Applies what the pass reported while the live Crop tool is still held by the canvas rig. +pub(crate) fn finish(app: &mut PhotocraftApp, tool: &mut CropTool, output: CropOutput) { + crate::crop_ui::finish(app, tool, output); } From caa4fe860acc25e7c1ec09848592a5b8b8bc2abe Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:23:49 +0100 Subject: [PATCH 25/38] Return crop acceptance to the active tool --- crates/ui-egui/src/tools/crop_ui.rs | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/tools/crop_ui.rs b/crates/ui-egui/src/tools/crop_ui.rs index 23828a19c6..89e3336a32 100644 --- a/crates/ui-egui/src/tools/crop_ui.rs +++ b/crates/ui-egui/src/tools/crop_ui.rs @@ -65,10 +65,14 @@ pub(crate) fn document(app: &PhotocraftApp) -> Option { Some(CropDocument::new(CropDocKey::new(st.doc.id.0), size, f64::from(st.doc.resolution_dpi)).selection(bounds)) } -/// Maps what a pass of the tool reported to the app. -pub(crate) fn finish(app: &mut PhotocraftApp, output: CropOutput) { +/// Maps what a canvas pass reported and acknowledges the crop on the tool that emitted it. +pub(crate) fn finish(app: &mut PhotocraftApp, tool: &mut CropTool, output: CropOutput) { for event in output.events { - handle_event(app, event); + if let CropEvent::Apply(commit) = event { + tool.applied(apply_commit(app, &commit)); + } else { + handle_event(app, event); + } } } @@ -122,7 +126,11 @@ pub(crate) fn toggle_straighten(app: &mut PhotocraftApp) { /// Runs one event of the tool. True for an `Apply` that cropped the document. pub(super) fn handle_event(app: &mut PhotocraftApp, event: impl Into>) -> bool { match event.into() { - Some(CropEvent::Apply(commit)) => apply_commit(app, &commit), + Some(CropEvent::Apply(commit)) => { + let accepted = apply_commit(app, &commit); + app.canvas_tools.crop.tool.applied(accepted); + accepted + } Some(CropEvent::Discard(key)) => { upright_view(app, key); false @@ -137,7 +145,7 @@ pub(super) fn handle_event(app: &mut PhotocraftApp, event: impl Into bool { let rect = commit.frame.rect; let px = |v: f64| v.round().max(1.0) as u64; @@ -164,13 +172,11 @@ fn apply_commit(app: &mut PhotocraftApp, commit: &CropCommit) -> bool { if let Some(view) = app.session.active_index().and_then(|i| app.ui.views.get_mut(i)) { view.place(craft::ui::canvas::ViewCommands::FitOnScreen); } - app.canvas_tools.crop.tool.applied(true); true } Err(error) => { app.ui.status = error; app.ui.status_error = true; - app.canvas_tools.crop.tool.applied(false); false } } From 6e777b496337a27e4d3a548c64767da93f02a663 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:23:58 +0100 Subject: [PATCH 26/38] Acknowledge the result on the Crop tool that emitted it --- crates/ui-egui/src/canvas/tools/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/tools/mod.rs b/crates/ui-egui/src/canvas/tools/mod.rs index 8e39edf481..94095c3897 100644 --- a/crates/ui-egui/src/canvas/tools/mod.rs +++ b/crates/ui-egui/src/canvas/tools/mod.rs @@ -670,7 +670,7 @@ fn with_rig( if let Some(tool) = crop_tool { tools.crop.tool = tool; } - crop::finish(app, output); + crop::finish(app, &mut tools.crop.tool, output); } result } From eeb92cef243734833e87700d13073570807a0fd1 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:24:03 +0100 Subject: [PATCH 27/38] Verify Enter and Done clear pending Crop state --- crates/ui-egui/tests/it/crop_task_bar.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/tests/it/crop_task_bar.rs b/crates/ui-egui/tests/it/crop_task_bar.rs index 87b35c7773..100fb88ee3 100644 --- a/crates/ui-egui/tests/it/crop_task_bar.rs +++ b/crates/ui-egui/tests/it/crop_task_bar.rs @@ -211,6 +211,7 @@ fn the_options_bar_ratio_list_takes_escape_and_enter_before_the_crop() { h.run_steps(6); assert_eq!(size(&h), Some((200, 200)), "Enter on the canvas commits the pending crop"); assert_eq!(history(&h), steps + 1, "Enter adds one document history step"); + assert!(!pending(h.state()), "Enter clears the pending Crop session once the document accepts the crop"); } #[test] @@ -281,6 +282,7 @@ fn cancel_and_done_only_while_a_crop_is_pending() { let at = widget(&h, "Done"); click_at(&mut h, at); assert_eq!(h.state().session.active().map(|s| (s.doc.size.width, s.doc.size.height)), Some((220, 170)), "Done crops"); + assert!(!pending(h.state()), "Done also clears the pending Crop session"); } /// The active document's stored zoom. From 18897c8d0ea8df4e8d90c11fafae0f5981c0952b Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:32:21 +0100 Subject: [PATCH 28/38] Restore guide and selection outline paint-order coverage --- crates/ui-egui/src/canvas/tests.rs | 94 ++++++++++++++++++++++++++---- 1 file changed, 84 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index daf454eb5f..33e44212b5 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -659,6 +659,21 @@ fn a_secondary_canvas_hand_pans_while_a_transform_is_open() { assert_eq!(box_key(&app), box_before, "the drag didn't touch the box"); } +/// The canvas can paint a batch as a nested list, which keeps its place in egui's final paint order. +fn flattened_paint_shapes(output: &egui::FullOutput) -> Vec<&egui::Shape> { + fn open<'a>(shape: &'a egui::Shape, into: &mut Vec<&'a egui::Shape>) { + match shape { + egui::Shape::Vec(list) => list.iter().for_each(|shape| open(shape, into)), + shape => into.push(shape), + } + } + let mut shapes = Vec::new(); + for clipped in &output.shapes { + open(&clipped.shape, &mut shapes); + } + shapes +} + #[test] fn guides_draw_over_the_transform_preview_and_under_its_box() { // #5086: a guide crossing a layer under Free Transform was hidden behind the preview of @@ -692,16 +707,7 @@ fn guides_draw_over_the_transform_preview_and_under_its_box() { // At 100 % centred on the document, screen and document coordinates coincide. let layer = Rect::from_min_max(pos2(100.0, 100.0), pos2(200.0, 160.0)); let near = |r: Rect| (r.min - layer.min).length() < 1.0 && (r.max - layer.max).length() < 1.0; - fn open<'a>(shape: &'a egui::Shape, into: &mut Vec<&'a egui::Shape>) { - match shape { - egui::Shape::Vec(list) => list.iter().for_each(|shape| open(shape, into)), - shape => into.push(shape), - } - } - let mut shapes = Vec::new(); - for clipped in &out.shapes { - open(&clipped.shape, &mut shapes); - } + let shapes = flattened_paint_shapes(&out); let position = |pred: &dyn Fn(&egui::Shape) -> bool| shapes.iter().position(|s| pred(s)); // The moving pixels: the mesh that spans the layer's box. let preview = position(&|s| matches!(s, egui::Shape::Mesh(m) if near(m.calc_bounds()))); @@ -716,6 +722,74 @@ fn guides_draw_over_the_transform_preview_and_under_its_box() { assert!(guide < frame, "the box ({frame}) draws over the guide ({guide})"); } +#[test] +fn marching_ants_draw_over_a_guide_on_the_selection_edge() { + use craft::behavior::kurbo::Point; + + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = app.ctx().clone(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap(); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 100})).unwrap(); + app.ui.tool = Tool::RectMarquee; + app.ui.extras.rulers = false; + app.ui.extras.grid = false; + app.ui.extras.guides = true; + app.ui.view.extras = true; + app.ui.view.show.canvas_guides = true; + app.ui.view.show.selection_edges = true; + app.sync_views(); + + let mut view = app.ui.views[0].clone(); + view.zoom = 1.0; + view.center = [200.0, 150.0]; + view.clear_pending(); + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let draw = |app: &mut PhotocraftApp| { + let input = egui::RawInput { screen_rect: Some(rect), ..Default::default() }; + let mut output = ctx.run_ui(input, |ui| { + canvas_view(app, ui, CanvasHost::main(0), rect, view.clone(), true); + }); + output.textures_delta.clear(); + output + }; + + let output = draw(&mut app); + let shown = active_view(&app).expect("the canvas view"); + let edge = Rect::from_two_pos(shown.to_screen(Point::new(100.0, 100.0)), shown.to_screen(Point::new(100.0, 160.0))); + let pixel = output.pixels_per_point.recip(); + let is_guide = |shape: &egui::Shape| { + let egui::Shape::LineSegment { points, .. } = shape else { return false }; + points.iter().all(|p| (p.x - edge.left()).abs() <= pixel) + && points[0].y.min(points[1].y) < edge.top() - pixel + && points[0].y.max(points[1].y) > edge.bottom() + pixel + }; + let is_ants = |shape: &egui::Shape| { + let bounds = match shape { + egui::Shape::Mesh(mesh) => mesh.calc_bounds(), + egui::Shape::Rect(rect) => rect.rect, + egui::Shape::LineSegment { points, .. } => Rect::from_two_pos(points[0], points[1]), + _ => return false, + }; + // A strip or dash on the selection edge, allowing for the framework's device-pixel snap. + bounds.height() > 0.0 + && bounds.width() <= 2.0 * pixel + && (bounds.center().x - edge.left()).abs() <= pixel + && bounds.top() >= edge.top() - pixel + && bounds.bottom() <= edge.bottom() + 2.0 * pixel + }; + let shapes = flattened_paint_shapes(&output); + let guide = shapes.iter().position(|shape| is_guide(shape)).expect("the guide spanning the selection"); + let ants = shapes.iter().position(|shape| is_ants(shape)).expect("the ants along the left edge"); + assert!(guide < ants, "the guide ({guide}) paints before the ants ({ants})"); + + app.ui.view.show.selection_edges = false; + let output = draw(&mut app); + let shapes = flattened_paint_shapes(&output); + assert!(shapes.iter().any(|shape| is_guide(shape)), "hiding selection edges leaves the guide"); + assert!(!shapes.iter().any(|shape| is_ants(shape)), "the edge paint belongs to the ants"); +} + #[test] fn layer_style_dialog_previews_live_and_cancel_restores() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); From c3a6cbf4a37b0e0a5ab977281ff5a7e5f8b99ff5 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:32:31 +0100 Subject: [PATCH 29/38] Verify app shortcuts recover when a recorder closes --- .../prefs/prefs_ui/shortcut_capture_tests.rs | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcut_capture_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_capture_tests.rs index 7d46727407..8ede607906 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcut_capture_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcut_capture_tests.rs @@ -6,6 +6,7 @@ use craft::keymap::{Binding, CommandRef, Policy}; use egui::{Event, Key, Modifiers}; use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; use photocraft_engine::prefs::{bindable_items, normalize_shortcut}; use serde_json::json; @@ -73,6 +74,37 @@ fn toolbar_shortcut_can_be_captured_and_restored_on_restart() { assert_eq!(restarted.state().ui.tool, crate::state::Tool::Pencil); } +#[test] +fn closing_keyboard_shortcuts_while_recording_restores_app_hotkeys() { + use crate::state::Tool; + + let mut session = photocraft_engine::Session::new(); + session.prefs.edit(|p| p.interface.language = "en".into()); + let mut h = harness_with(session); + edit_and_ok(&mut h, "tools.select.pencil", "F6"); + h.state_mut().ui.tool = Tool::Move; + crate::prefs_ui::open_shortcuts(h.state_mut(), 0); + h.run_steps(2); + + h.get_by_label("Search by key").click(); + h.run_steps(2); + assert!(crate::prefs_ui::recording(h.state()), "the recorder is waiting for a key"); + tap(&mut h, Key::F6, Modifiers::NONE); + assert!(h.query_all_by_label("Search:").any(|node| node.accesskit_node().value().as_deref() == Some("F6")), "the recorder took F6"); + assert_eq!(h.state().ui.tool, Tool::Move, "F6 leaves the tool alone during recording"); + assert!(!crate::prefs_ui::recording(h.state()), "the chord ended the search recording"); + + h.get_by_label("Search by key").click(); + h.run_steps(2); + assert!(crate::prefs_ui::recording(h.state()), "recording again before the dialog closes"); + assert!(super::shortcuts::cancel(h.state_mut()), "Cancel closes the active dialog"); + h.run_steps(2); + assert!(!crate::prefs_ui::shortcuts_open(h.state()), "the modal is gone"); + + tap(&mut h, Key::F6, Modifiers::NONE); + assert_eq!(h.state().ui.tool, Tool::Pencil, "F6 selects Pencil again after the dialog closes"); +} + #[test] fn toolbar_shortcut_overrides_remove_old_keys_and_skip_removed_group_members() { use crate::state::Tool; From d16b7c4b8511ad02d71414a0108a05240c03e493 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:47:45 +0100 Subject: [PATCH 30/38] Cover canceling a staged Vanishing Point paste --- crates/ui-egui/src/dialogs/vp_ui/tests.rs | 24 +++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/crates/ui-egui/src/dialogs/vp_ui/tests.rs b/crates/ui-egui/src/dialogs/vp_ui/tests.rs index 4da523c58a..7026cb57a2 100644 --- a/crates/ui-egui/src/dialogs/vp_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/vp_ui/tests.rs @@ -109,6 +109,30 @@ fn a_plane_and_ok_paste_in_one_step() { assert!(l.rgba(230, 20)[0] < 0.5, "outside the plane"); } +#[test] +fn vanishing_point_cancel_leaves_pending_paste_unapplied() { + let mut app = app_with_layer(); + copy_red_square(&mut app); + let st = app.session.active().unwrap(); + let (original, steps, revision) = (st.doc.clone(), st.history.past_len(), st.revision); + + let mut h = open(app); + set(&mut h, json!({"planes": [floor()]})); + let pending = describe(h.state()).expect("Vanishing Point is open"); + assert_eq!(pending["paste"].as_array().map(Vec::len), Some(1), "OK would paste onto the plane"); + + let dialog = h.state().vanishing.as_ref().unwrap().dialog; + let ctx = h.ctx.clone(); + crate::control::dialogs::workspace_ui(h.state_mut(), &ctx, VP, &json!({"cancel": true})).unwrap(); + h.run_steps(4); + let app = h.state(); + assert!(app.framework.dialogs.get_dyn(dialog).is_none(), "Cancel closes the dialog"); + assert!(app.vanishing.is_none(), "Cancel drops the workspace"); + let st = app.session.active().unwrap(); + assert_eq!(st.doc, original, "Cancel leaves the document unchanged"); + assert_eq!((st.history.past_len(), st.revision), (steps, revision), "Cancel does not edit the document or its history"); +} + #[test] fn a_torn_wall_and_clone_strokes_are_one_step_and_preview_on_the_source() { let mut app = app_with_layer(); From 779b20eeb0d713af4f87148df5a5f5c2a14ea5a3 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 11:21:29 +0100 Subject: [PATCH 31/38] Open Recent lists an automation open where the file is on disk (#16098) app.open is requested by a path relative to the automation read root. It went into Open Recent as is, where it names nothing: Home drew a blank card and clicking it failed. The workspace now reports the file's location below the root that holds it, and app.open (also the directory .pcraft path) lists that. The document's save-back path stays root-relative; without a location the open is not listed. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft/src/services.rs | 6 +++- crates/automation/src/workspace.rs | 12 ++++++++ crates/automation/src/workspace/tests.rs | 19 ++++++++++++ crates/ui-egui/src/control/dispatch.rs | 14 +++++++-- crates/ui-egui/src/control/tests.rs | 38 ++++++++++++++++++++++-- crates/ui-egui/src/file_open.rs | 11 ++++++- crates/ui-egui/src/lib.rs | 10 +++---- crates/ui-egui/src/services.rs | 10 +++++++ 8 files changed, 108 insertions(+), 12 deletions(-) diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index c89876e52d..72e070e7e7 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -429,6 +429,9 @@ pub fn automation(workspace: Option) Ok(opened.map(|doc| (name, doc))) }) as photocraft_ui_egui::AutomationOpenPcraftFn }); + let locate = workspace.clone().map(|workspace| { + Box::new(move |path: &str| workspace.location(path).map(|location| location.to_string_lossy().into_owned())) as photocraft_ui_egui::AutomationLocateFn + }); let save = workspace.clone().map(|workspace| { std::sync::Arc::new(move |doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings, ctl: &photocraft_ui_egui::jobs_ui::SaveCtl| { save_through(doc, path, settings, ctl, |p, encoded, _| workspace.write_stream(p, &mut |w| encoded.write_to(w)).map_err(|e| e.to_string())) @@ -441,7 +444,7 @@ pub fn automation(workspace: Option) photocraft_automation::workspace::authorize_desktop_engine_command(id, params).map_err(|error| error.to_string()) }) as photocraft_ui_egui::AutomationCommandFn }); - photocraft_ui_egui::AutomationServices { read, write, open_pcraft, save, command, authorize } + photocraft_ui_egui::AutomationServices { read, write, open_pcraft, locate, save, command, authorize } } /// What agent requests may read, write and run with the agent settings' folders @@ -486,6 +489,7 @@ pub fn native(automation: Option, wa automation_read: automation.read, automation_write: automation.write, automation_open_pcraft: automation.open_pcraft, + automation_locate: automation.locate, automation_save: automation.save, automation_command: automation.command, automation_authorize: automation.authorize, diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 979cae498e..9b86d87b39 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -103,6 +103,18 @@ impl AuthorizedWorkspace { Ok((bytes, save_path)) } + /// Where the file or `.pcraft` folder that `path` names is on disk: below the first read + /// root that holds it (the root `read` and `open_pcraft` pick), as that root was configured + /// at launch. Open Recent lists this, since the person reopens the file outside automation, + /// where a root-relative request path names nothing. It grants no access. + pub fn location(&self, path: &str) -> Option { + self.read.iter().find_map(|root| { + let relative = scoped_path(path, root).ok()??; + root.dir.metadata(&relative).ok()?; + Some(root.configured_path.join(relative)) + }) + } + fn open_read(&self, path: &str) -> Result<(cap_std::fs::File, &RootCapability), AutomationError> { if self.read.is_empty() { return Err(AutomationError::BadRequest(format!("{DENIED}: read authority is absent"))); diff --git a/crates/automation/src/workspace/tests.rs b/crates/automation/src/workspace/tests.rs index 03622c9c59..9207831449 100644 --- a/crates/automation/src/workspace/tests.rs +++ b/crates/automation/src/workspace/tests.rs @@ -64,6 +64,25 @@ fn read_growth_is_rejected_at_the_observed_length() { assert!(read_to_observed_length(&mut empty, 0).is_err()); } +#[test] +fn location_names_the_file_below_the_root_that_holds_it() { + let (library, work, _) = roots("location"); + std::fs::create_dir_all(work.join("shots")).unwrap(); + std::fs::write(work.join("shots/a.png"), b"a").unwrap(); + std::fs::write(library.join("same.png"), b"first").unwrap(); + std::fs::write(work.join("same.png"), b"second").unwrap(); + let workspace = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path()], Some(&work)).unwrap(); + // A root-relative request names the file below the root that holds it, as an absolute path. + assert_eq!(workspace.location("shots/a.png"), Some(work.join("shots").join("a.png"))); + // The first root that holds the name wins, as for `read`. + assert_eq!(workspace.location("same.png"), Some(library.join("same.png"))); + // An absolute request below a root keeps naming that file. + assert_eq!(workspace.location(&work.join("same.png").to_string_lossy()), Some(work.join("same.png"))); + assert_eq!(workspace.location("missing.png"), None); + assert_eq!(workspace.location("../outside.png"), None, "a path escaping the roots has no location"); + assert_eq!(AuthorizedWorkspace::default().location("shots/a.png"), None, "no read root, no location"); +} + #[test] fn open_pcraft_loads_a_directory_below_the_read_root() { let (inside, _, workspace) = roots("pcraft-dir"); diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index 7eb85f9422..273d9dc942 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -1362,7 +1362,8 @@ fn app_open(app: &mut PhotocraftApp, path: &str, approved: bool) -> Reply { let warnings = app.open_automation_bytes_with_approval(&name, &bytes, approved)?; // Brushes/gradients go to the preset libraries: no document, no Open Recent entry. if !crate::preset_files_ui::is_preset_file(&name) { - app.opened_from(path); + let recent = automation_location(app, path); + app.opened_from_listed(path, recent.as_deref()); if let Some(state) = app.session.active_mut() && state.path.is_some() { @@ -1373,6 +1374,13 @@ fn app_open(app: &mut PhotocraftApp, path: &str, approved: bool) -> Reply { })) } +/// Where the file an automation open read is on disk, for Open Recent. The request path is +/// relative to an automation root, so it names nothing when the person reopens it from Open +/// Recent or Home; without a location the open is not listed there. +fn automation_location(app: &PhotocraftApp, path: &str) -> Option { + app.services.automation_locate.as_ref().and_then(|locate| locate(path)) +} + /// Directory .pcraft (the native on-disk form) loads through a capability-scoped /// source; the single-file (zip) form falls back to the bytes path, as do all /// other formats. `None` means "not a directory .pcraft". @@ -1386,7 +1394,9 @@ fn open_pcraft_directory(app: &mut PhotocraftApp, path: &str) -> Option { app.session.add_document(doc, None); // Recent files, but no save-back target: the capability writer // replaces files, never directories. - app.push_recent(path); + if let Some(recent) = automation_location(app, path) { + app.push_recent(&recent); + } app.sync_views(); app.ui.status = crate::i18n::fmt(tl!("Opened {name}"), &[("name", &name)]); app.ui.status_error = false; diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index dc88c6efed..46e782afbd 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -1198,6 +1198,34 @@ fn automation_save_passes_dds_options_without_asking() { assert_eq!(asked.borrow().len(), 2, "a bad ddsCompression writes nothing"); } +#[test] +fn an_automation_open_without_a_location_is_not_listed_in_open_recent() { + use photocraft_color::{ColorMode, SampleType}; + use photocraft_doc::Document; + use photocraft_geom::Size; + + let services = crate::Services { + import: Some(Box::new(|name: &str, _b: &[u8], _opts: &photocraft_io::ImportOptions| { + Ok((Document::new(name, Size::new(4, 4), ColorMode::Rgb, SampleType::U8), Vec::new())) + })), + automation_read: Some(Box::new(|path: &str| { + Ok(crate::AutomationReadResult { + name: path.rsplit('/').next().unwrap_or(path).to_string(), + bytes: b"x".to_vec(), + save_path: Some(path.to_string()), + }) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let ctx = app.ctx().clone(); + let r = call(&mut app, &ctx, "app.open", json!({"path": "shots/gk_25.png"})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(app.session.active().unwrap().path.as_deref(), Some("shots/gk_25.png"), "the save-back target stays the root-relative path"); + // A root-relative path names no file for Open Recent or Home, so nothing is listed. + assert!(app.ui.recent_files.is_empty(), "{:?}", app.ui.recent_files); +} + #[test] fn automation_open_and_save_use_the_roots_and_reply_with_warnings() { use photocraft_color::{ColorMode, SampleType}; @@ -1234,6 +1262,7 @@ fn automation_open_and_save_use_the_roots_and_reply_with_warnings() { save_path: Some(path.to_string()), }) })), + automation_locate: Some(Box::new(|path: &str| Some(format!("/work/{path}")))), automation_write: Some(Box::new(move |path: &str, _b: &[u8]| { w.borrow_mut().push(path.to_string()); Ok(()) @@ -1245,7 +1274,8 @@ fn automation_open_and_save_use_the_roots_and_reply_with_warnings() { assert_eq!(r["result"]["warnings"], json!(["Adjustment layer flattened"]), "{r}"); assert_eq!(r["result"]["name"], "warn.psd"); assert_eq!(app.session.active().unwrap().path.as_deref(), Some("in/warn.psd")); - assert_eq!(app.ui.recent_files, vec!["in/warn.psd".to_string()]); + // Open Recent lists where the file is, not the root-relative request path, which names nothing outside automation. + assert_eq!(app.ui.recent_files, vec!["/work/in/warn.psd".to_string()]); let r = call(&mut app, &ctx, "app.save", json!({"path": "out.png"})); assert_eq!(r["result"], json!({"path": "out.png", "warnings": ["Layers were flattened"]}), "{r}"); assert_eq!(*written.borrow(), vec!["out.png".to_string()]); @@ -1457,6 +1487,7 @@ fn app_open_opens_a_directory_pcraft_and_falls_back_for_the_zip_form() { Err(format!("no such path: {path}")) } })), + automation_locate: Some(Box::new(|path: &str| Some(format!("/work/{path}")))), ..Default::default() }; let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); @@ -1465,7 +1496,7 @@ fn app_open_opens_a_directory_pcraft_and_falls_back_for_the_zip_form() { let r = call(&mut app, &ctx, "app.open", json!({"path": "native.pcraft"})); assert_eq!(r["result"], json!({"path": "native.pcraft", "name": "native.pcraft", "warnings": []}), "{r}"); assert_eq!(app.session.active().unwrap().doc.name, "Native"); - assert_eq!(app.ui.recent_files, vec!["native.pcraft".to_string()], "the open is recorded in recent files"); + assert_eq!(app.ui.recent_files, vec!["/work/native.pcraft".to_string()], "the open is recorded in recent files, where it is on disk"); assert_eq!(app.session.active().unwrap().path, None, "no save-back target: the automation writer replaces files, never directories"); let r = call(&mut app, &ctx, "app.save", json!({})); assert!(r["error"].as_str().unwrap().contains("pass `path`"), "an in-place save is refused up front: {r}"); @@ -2120,6 +2151,7 @@ fn automation_library_open_requires_explicit_save_as_before_implicit_save() { save_path: path.starts_with("work/").then(|| path.to_owned()), }) })), + automation_locate: Some(Box::new(|path: &str| Some(format!("/roots/{path}")))), automation_write: Some(Box::new(move |path: &str, _: &[u8]| { if path == "failed.psd" { return Err("test write failure".into()); @@ -2135,7 +2167,7 @@ fn automation_library_open_requires_explicit_save_as_before_implicit_save() { let opened = call(&mut app, &ctx, "app.open", json!({"path": "library/same.psd"})); assert_eq!(opened["ok"], true, "{opened}"); assert_eq!(app.session.active().unwrap().path, None); - assert_eq!(app.ui.recent_files, vec!["library/same.psd"]); + assert_eq!(app.ui.recent_files, vec!["/roots/library/same.psd"]); app.run("layer.new.layer", json!({"name": "edit"})).unwrap(); assert!(app.session.active().unwrap().is_dirty()); let refused = call(&mut app, &ctx, "app.save", json!({})); diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 8d4d58dbbc..6f41518347 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -230,6 +230,13 @@ impl PhotocraftApp { /// Record that the active document was just opened from `path`: File › Save writes back to it /// (unless it's a template or derivative preview) and it goes to the top of Open Recent. pub(crate) fn opened_from(&mut self, path: &str) { + self.opened_from_listed(path, Some(path)); + } + + /// [`Self::opened_from`], with `recent` the path Open Recent lists for it (`None`: not listed). + /// An automation open is requested by a root-relative path, which names nothing outside + /// automation, so it lists where the file is on disk instead. + pub(crate) fn opened_from_listed(&mut self, path: &str, recent: Option<&str>) { if !is_template(path) && let Some(st) = self.session.active_mut() && !st.source_read_only @@ -238,7 +245,9 @@ impl PhotocraftApp { let doc = st.doc.id; self.remember_stamp(doc, path); } - self.push_recent(path); + if let Some(recent) = recent { + self.push_recent(recent); + } } /// The name a file called `name` opens under: its own, or the first free "Untitled-N" for a diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a89837fb4c..7db1cdeaa1 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -236,11 +236,11 @@ pub(crate) use services::SAVE_OPTIONS_OPEN; #[cfg(test)] pub(crate) use services::saved_revision_after_write; pub use services::{ - AdoptAutosaveFn, AppendTextFn, AutomationAuthorizeFn, AutomationCommandFn, AutomationOpenPcraftFn, AutomationReadFn, AutomationServices, AutomationWriteFn, - AutosaveFn, AutosaveResultsFn, CapsLockFn, ClipboardGetFn, ClipboardGetSvgFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn, - ExportFn, ExportSettings, ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp, FileStampFn, FormatChoices, ImportFn, - Inbox, LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PhotoshopShortcutsFn, PlaceInbox, RecoverFn, Recoverable, RightButtonDownFn, - SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn, + AdoptAutosaveFn, AppendTextFn, AutomationAuthorizeFn, AutomationCommandFn, AutomationLocateFn, AutomationOpenPcraftFn, AutomationReadFn, + AutomationServices, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn, ClipboardGetFn, ClipboardGetSvgFn, ClipboardSetFn, ClipboardUnreadableFn, + CursorPosFn, DiscardAutosaveFn, ExportFn, ExportSettings, ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp, + FileStampFn, FormatChoices, ImportFn, Inbox, LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PhotoshopShortcutsFn, PlaceInbox, RecoverFn, + Recoverable, RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn, }; pub(crate) use services::{opaque_layer, saves_flat_in_place}; pub use text::cjk_fonts; diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 1249b00557..e84c92bd47 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -338,6 +338,11 @@ pub type AutomationWriteFn = Box Result<(), String>>; /// caller falls back to the bytes path for the zip form. pub type AutomationOpenPcraftFn = Box Result, String>>; +/// Where a path an automation read opened is on disk (absolute), for Open Recent: the person +/// reopens it outside automation, where a root-relative request path names nothing. `None` +/// when no read root holds it. +pub type AutomationLocateFn = Box Option>; + /// Reject engine commands which still perform ambient filesystem I/O. pub type AutomationCommandFn = Box Result<(), String>>; /// Same policy as [`AutomationCommandFn`] for each step a command runs (`actions.play`). @@ -351,6 +356,7 @@ pub struct AutomationServices { pub read: Option, pub write: Option, pub open_pcraft: Option, + pub locate: Option, pub save: Option, pub command: Option, pub authorize: Option, @@ -546,6 +552,9 @@ pub struct Services { pub automation_read: Option, pub automation_write: Option, pub automation_open_pcraft: Option, + /// Where an automation open's file is on disk, for Open Recent. Without it an automation + /// open is not listed there. + pub automation_locate: Option, pub automation_command: Option, /// Same policy as [`Self::automation_command`], as a function pointer the engine calls for /// each step of `actions.play`. Installed on the session only while a control request or @@ -657,6 +666,7 @@ impl Services { self.automation_read = a.read; self.automation_write = a.write; self.automation_open_pcraft = a.open_pcraft; + self.automation_locate = a.locate; self.automation_save = a.save; self.automation_command = a.command; self.automation_authorize = a.authorize; From 60ce64e2bfa022fd3104b9f4f7c37585720af645 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:33:25 +0100 Subject: [PATCH 32/38] Cover Escape ownership in Targa Options --- .../dialogs/discard_ui/tests/targa_tests.rs | 57 ++++++++++++++++--- 1 file changed, 50 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/discard_ui/tests/targa_tests.rs b/crates/ui-egui/src/dialogs/discard_ui/tests/targa_tests.rs index 078d03624c..38786b3901 100644 --- a/crates/ui-egui/src/dialogs/discard_ui/tests/targa_tests.rs +++ b/crates/ui-egui/src/dialogs/discard_ui/tests/targa_tests.rs @@ -16,6 +16,18 @@ fn asked(bits: Option) -> Vec { serde_json::to_vec(&bits).unwrap() } +/// Records the Targa options on each write without encoding or touching the filesystem. +fn targa_writes(app: &mut PhotocraftApp) -> Writes { + let writes: Writes = Rc::default(); + let written = writes.clone(); + app.services.export = Some(Box::new(|_, _, settings| Ok((asked(settings.tga_bits.map(TgaBits::bits)), Vec::new())))); + app.services.write = Some(Box::new(move |path, bytes| { + written.borrow_mut().push((path.to_string(), bytes.to_vec())); + Ok(()) + })); + writes +} + /// One 8×8 RGB document (with an "Alpha 1" channel when `alpha_channel`) whose exports record /// their Targa bits, in a harness running the dialogs and answering a save dialog with `to`. fn targa_app(alpha_channel: bool, to: &str) -> (Prompted, Writes) { @@ -24,13 +36,7 @@ fn targa_app(alpha_channel: bool, to: &str) -> (Prompted, Writes) { app.run("select.all", json!({})).unwrap(); app.run("select.saveSelection", json!({})).unwrap(); } - let writes: Writes = Rc::default(); - let written = writes.clone(); - app.services.export = Some(Box::new(|_, _, settings| Ok((asked(settings.tga_bits.map(TgaBits::bits)), Vec::new())))); - app.services.write = Some(Box::new(move |path, bytes| { - written.borrow_mut().push((path.to_string(), bytes.to_vec())); - Ok(()) - })); + let writes = targa_writes(&mut app); let h = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 600.0)).with_context(app.ctx().clone()).build_ui_state( |ui, app| { crate::dialogs::run(app, ui); @@ -76,6 +82,43 @@ fn targa_options_writes_the_choice_or_cancels() { assert_eq!(writes.borrow().as_slice(), &[("t.tga".to_string(), asked(Some(24)))]); } +/// With the real window key handling running, Targa Options owns the first Escape. +#[test] +fn escape_cancels_targa_options_before_deselecting() { + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 760.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::AppTheme::pro()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app + }); + let writes = targa_writes(h.state_mut()); + h.run_steps(4); + h.state_mut().run("select.all", json!({})).unwrap(); + let st = h.state().session.active().unwrap(); + let (selection, history) = (st.doc.selection.clone().expect("Select All created a selection"), st.history.past_len()); + + h.state_mut().save_as(Some("t.tga".into())).unwrap(); + h.run_steps(2); + assert_eq!(parked(&h), Some(("t.tga".to_string(), false))); + let dialog = h.state().framework.dialogs.open_dialogs().last().expect("Targa Options is open").id; + + h.key_press(Key::Escape); + h.run_steps(4); + assert!(h.state().framework.dialogs.get_dyn(dialog).is_none(), "Escape closes Targa Options"); + assert!(parked(&h).is_none(), "Escape cancels the parked save"); + assert!(writes.borrow().is_empty(), "the cancelled save writes nothing"); + let st = h.state().session.active().unwrap(); + assert_eq!(st.path, None, "the cancelled save leaves the document unsaved"); + assert_eq!(st.doc.selection.as_ref(), Some(&selection), "the dialog's Escape leaves the selection intact"); + assert_eq!(st.history.past_len(), history, "the dialog's Escape leaves document history intact"); + + h.key_press(Key::Escape); + h.run_steps(4); + let st = h.state().session.active().unwrap(); + assert!(st.doc.selection.is_none(), "once the dialog is gone, Escape reaches the window and deselects"); + assert_eq!(st.history.past_len(), history + 1, "only the second Escape edits the document"); +} + /// Scripts choose with `tgaBits` and are never asked; a grayscale Targa (8-bit, nothing to choose) /// and other formats aren't asked either. #[test] From e1d950d6b2c91b146b87d3ee4eeb3d74fedf6db3 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 14:04:27 +0100 Subject: [PATCH 33/38] Smart Filter Lens Blur: setParams refuses an alpha channel depth Applying Lens Blur to a Smart Object already refuses an alpha channel as the depth map: a smart filter re-renders from its params alone, without the document's channels (#7400). layer.smartFilter.setParams did not, so since the Lens Blur dialog sends a chosen channel as `depthMap: "channel"` (#15883), OK in a Smart Filter's Lens Blur dialog could record a source the re-render cannot read. setParams now refuses it with the same message, merged or replaced, and the filter and history stay as they were. Follow-up to the review of integration batch #16092. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/smart_cmds/filters.rs | 4 +++ crates/engine/src/cmd/smart_cmds/tests.rs | 28 +++++++++++++++++++++ crates/engine/src/filters.rs | 7 +++++- 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/smart_cmds/filters.rs b/crates/engine/src/cmd/smart_cmds/filters.rs index 46a5ccba39..70486a8451 100644 --- a/crates/engine/src/cmd/smart_cmds/filters.rs +++ b/crates/engine/src/cmd/smart_cmds/filters.rs @@ -229,6 +229,10 @@ pub(super) fn set_filter_params(s: &mut Session, p: &Value) -> Result { f.params = photocraft_io::smart_map::displace_without_map(&f.params); } } + // As applying it does: the re-render can't read the document's alpha channels. + if f.command == "filter.blur.lensBlur" && f.params.get("depthMap").and_then(Value::as_str) == Some("channel") { + return Err(EngineError::Other(crate::filters::LENS_BLUR_CHANNEL_ON_SMART.into())); + } // Authorize the underlying command with the complete merged params, including paths // already stored in the document, before committing the edit or starting a worker. if let Some(gate) = authorize { diff --git a/crates/engine/src/cmd/smart_cmds/tests.rs b/crates/engine/src/cmd/smart_cmds/tests.rs index 34cb323dae..8465f33719 100644 --- a/crates/engine/src/cmd/smart_cmds/tests.rs +++ b/crates/engine/src/cmd/smart_cmds/tests.rs @@ -1667,3 +1667,31 @@ fn set_params_replace_drops_a_shape_blur_radius_it_leaves_out() { s.execute("layer.smartFilter.setParams", json!({"params": {"shape": "circle"}, "replace": true})).unwrap(); assert!(params(&s).get("radius").is_none(), "replaced: {}", params(&s)); } + +/// A smart filter re-renders from its params alone, without the document's alpha channels (#7400): Lens Blur refuses an +/// alpha channel as its depth on a Smart Object, both when it is applied and when a recorded filter's params are edited +/// (merged or replaced), and the refused edit changes neither the filter nor the history. +#[test] +fn lens_blur_smart_filter_refuses_an_alpha_channel_depth_on_edit() { + let mut s = session(8); + paint(&mut s); + s.execute("select.all", json!({})).unwrap(); + s.execute("select.saveSelection", json!({"name": "Depth"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("filter.convertForSmartFilters", json!({})).unwrap(); + let channel = json!({"radius": 4, "depthMap": "channel", "depthChannel": 0}); + let applied = s.execute("filter.blur.lensBlur", channel.clone()).unwrap_err().to_string(); + assert!(applied.contains("rasterize the layer first"), "{applied}"); + s.execute("filter.blur.lensBlur", json!({"radius": 4, "depthMap": "transparency"})).unwrap(); + let recorded = active_smart(&s).smart_filters[0].params.clone(); + let steps = s.active().unwrap().history.past_len(); + for replace in [false, true] { + let e = s.execute("layer.smartFilter.setParams", json!({"index": 0, "params": channel, "replace": replace})).unwrap_err().to_string(); + assert!(e.contains("rasterize the layer first"), "replace={replace}: {e}"); + assert_eq!(active_smart(&s).smart_filters[0].params, recorded, "replace={replace}"); + assert_eq!(s.active().unwrap().history.past_len(), steps, "replace={replace}"); + } + // Sources that need no channel stay editable. + s.execute("layer.smartFilter.setParams", json!({"index": 0, "params": {"depthMap": "none"}})).unwrap(); + assert_eq!(active_smart(&s).smart_filters[0].params["depthMap"], json!("none")); +} diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs index dd263e335a..9a48debb9b 100644 --- a/crates/engine/src/filters.rs +++ b/crates/engine/src/filters.rs @@ -76,6 +76,11 @@ fn preset(id: &str) -> Option<(&'static str, FilterParams)> { }) } +/// Why Lens Blur refuses an alpha channel as its depth on a Smart Object: a smart filter re-renders from its params +/// alone, without the document's channels, so the depth would be lost (#7400). Applying it and editing a recorded +/// filter's params both refuse it. +pub(crate) const LENS_BLUR_CHANNEL_ON_SMART: &str = "Lens Blur can't read an alpha channel as depth on a Smart Object: rasterize the layer first"; + /// Builds the algorithm parameters for a filter command id from JSON params /// (Photoshop dialog units). Stored smart filters and previews retain their tolerant decoding; /// new command invocations pass through `validate_params` before any document changes. @@ -339,7 +344,7 @@ pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result // A smart filter re-renders from its params alone, without the document's // channels, so Lens Blur's alpha-channel depth would be lost (#7400). if matches!(fp, FilterParams::LensBlur { depth: algo::DepthSource::Channel, .. }) { - return Err(EngineError::Other("Lens Blur can't read an alpha channel as depth on a Smart Object: rasterize the layer first".into())); + return Err(EngineError::Other(LENS_BLUR_CHANNEL_ON_SMART.into())); } // A smart filter re-renders from its params alone: a Displace map read from an // open document, which the re-render can't read again, is kept in them, as From 3dbb289460105c265031a3ebf2c0b8b5c28919ec Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 16:59:54 +0100 Subject: [PATCH 34/38] Status bar: keep the bar the slot's direct child, memoize its body and trailing group One memoized view around the whole status bar made the bar a child of the status slot's row: since craft-libs 02be56cfbb a memoized view in a row moves down onto the row's line, so the bar was shifted about 5 px and its readout was clipped at the window's bottom edge. The bar now stays the slot's direct child, as on main, and its body (readout, message) and trailing group (render path, redraw, job) are a memoized view each, as the options bar's lead is. --- crates/ui-egui/src/menu_floor_trials.rs | 29 +++++ crates/ui-egui/src/panels/status_bar.rs | 159 +++++++++++++----------- 2 files changed, 113 insertions(+), 75 deletions(-) diff --git a/crates/ui-egui/src/menu_floor_trials.rs b/crates/ui-egui/src/menu_floor_trials.rs index 333f8b484c..9fdb3eb08a 100644 --- a/crates/ui-egui/src/menu_floor_trials.rs +++ b/crates/ui-egui/src/menu_floor_trials.rs @@ -6,6 +6,7 @@ use craft::ui::runtime::measure::{MemoRun, last_frame_derived_builds, last_frame_memo_runs, last_pass_memo_key_bytes}; use egui::{Event, Pos2, vec2}; use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT as _, Queryable as _}; use serde_json::json; use crate::PhotocraftApp; @@ -156,3 +157,31 @@ fn the_held_menu_model_equals_a_fresh_build_after_each_step() { h.state_mut().session.saved_to("/tmp/Renamed.psd".into()); held_is_fresh(&mut h, "a save that renames the document"); } + +#[test] +fn the_status_bar_sits_inside_the_window_when_its_views_run_and_replay() { + let mut h = harness(1, 0, 0); + let screen = h.ctx.content_rect(); + // The status bar's zoom field: the lowest node named Zoom that shows the percentage as its value. + let field = |h: &H| { + h.query_all_by_label("Zoom") + .filter(|n| { + let a = n.accesskit_node(); + a.role() != egui::accesskit::Role::Slider && a.value().is_some() && a.bounding_box().is_some() + }) + .map(|n| n.rect()) + .max_by(|a, b| a.bottom().total_cmp(&b.bottom())) + }; + // A settled frame replays the bar's views; a status message runs its body again. + for step in ["settled", "a status message"] { + if step == "a status message" { + h.state_mut().ui.status = "Saved".into(); + } + h.run_steps(2); + let Some(field) = field(&h) else { panic!("{step}: the status bar shows its zoom field") }; + assert!( + field.bottom() <= screen.bottom() && field.top() >= screen.bottom() - 40.0, + "{step}: the zoom field {field:?} sits in the status bar inside the window {screen:?}, not moved down past its edge" + ); + } +} diff --git a/crates/ui-egui/src/panels/status_bar.rs b/crates/ui-egui/src/panels/status_bar.rs index e7a87005f8..9ca8bd15da 100644 --- a/crates/ui-egui/src/panels/status_bar.rs +++ b/crates/ui-egui/src/panels/status_bar.rs @@ -33,7 +33,7 @@ impl Progress { } } -/// Every input of the status bar. +/// Every input of the status bar's body: the readout and the status message. #[derive(MemoProps)] struct StatusProps<'a> { values: StatusValues, @@ -42,6 +42,12 @@ struct StatusProps<'a> { /// The active document's main canvas as its last pass showed it; a document not yet shown has no readout. view: Option, message: Option, + out: Outbox<'a, StatusEvent>, +} + +/// Every input of the status bar's trailing group: the render-path note, the background redraw and the job. +#[derive(MemoProps)] +struct TrailingProps<'a> { render_path: Option, redraw: Option, job: Option, @@ -62,91 +68,94 @@ enum StatusEvent { /// The status bar, in the shell's status slot: the zoom readout of the active document and the latest status /// message, and at the far end the render-path note, the background redraw and the background jobs' progress with -/// Cancel (#210). One view holds the whole bar, so a frame where none of it changed replays it. +/// Cancel (#210). The body and the trailing group are a memoized view each, so a frame where neither changed replays +/// them. The bar itself stays the slot's direct child: it fills the slot's height and centres its content there, where +/// a memoized view around it would be moved down onto the slot row's line and clipped at the window's bottom edge. pub fn status_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let job = crate::jobs_ui::status_job(app); - let mut sent = Vec::new(); - let props = StatusProps { - values: chrome_ui::status_values(app), - item: chrome_ui::status_item(&app.ui.chrome), - document: app.session.active().map(|st| Size::new(st.doc.size.width as f64, st.doc.size.height as f64)), - view: crate::canvas::active_view(app), - message: (!app.ui.status.is_empty()) - .then(|| StatusMessage::new(app.ui.status.clone()).tone(if app.ui.status_error { Tone::Warn } else { Tone::Neutral })), - render_path: chrome_ui::render_path_label(app) - .map(|(label, tip, command)| StatusMessage::new(label).tone(Tone::Warn).command(CommandRef::new(command)).tooltip(tip)), - redraw: crate::background_redraw::progress(app), - job: job.as_ref().map(|(_, progress)| progress.clone()), - out: Outbox::new(&mut sent), - }; - let _ = MemoView::new("status-bar", props, status_view).show(ui); - let mut invalid_zoom = None; - for event in sent { + let values = chrome_ui::status_values(app); + let item = chrome_ui::status_item(&app.ui.chrome); + let document = app.session.active().map(|st| Size::new(st.doc.size.width as f64, st.doc.size.height as f64)); + let view = crate::canvas::active_view(app); + let message = + (!app.ui.status.is_empty()).then(|| StatusMessage::new(app.ui.status.clone()).tone(if app.ui.status_error { Tone::Warn } else { Tone::Neutral })); + let render_path = chrome_ui::render_path_label(app) + .map(|(label, tip, command)| StatusMessage::new(label).tone(Tone::Warn).command(CommandRef::new(command)).tooltip(tip)); + let redraw = crate::background_redraw::progress(app); + let progress = job.as_ref().map(|(_, progress)| progress.clone()); + // The bar may run each group more than once in a pass (it measures the trailing group first); each run sends into + // its group's outbox, and the last of each kind of event applies below. + let (mut body_sent, mut trailing_sent) = (Vec::new(), Vec::new()); + Bar::new("", BarKind::Status) + .trailing(|ui, _| { + let props = TrailingProps { render_path: render_path.clone(), redraw: redraw.clone(), job: progress.clone(), out: Outbox::new(&mut trailing_sent) }; + let _ = MemoView::new("status-bar-trailing", props, trailing_view).show(ui); + }) + .show(ui, |ui, _| { + let props = StatusProps { values: values.clone(), item, document, view, message: message.clone(), out: Outbox::new(&mut body_sent) }; + let _ = MemoView::new("status-bar", props, body_view).show(ui); + }); + let (mut picked, mut edited, mut invalid_zoom, mut cancelled) = (None, None, None, false); + for event in body_sent.into_iter().chain(trailing_sent) { match event { - StatusEvent::Item(picked) => chrome_ui::set_status_item(&mut app.ui.chrome, picked), - StatusEvent::View(new) => { - if let Some(i) = app.session.active_index() { - let ppp = app.canvas_ppp(); - app.ui.views[i].set_from(&new, ppp); - } - } + StatusEvent::Item(item) => picked = Some(item), + StatusEvent::View(new) => edited = Some(new), StatusEvent::InvalidZoom(invalid) => invalid_zoom = Some(invalid), - StatusEvent::CancelJob => { - if let Some((id, _)) = &job { - crate::jobs_ui::cancel(app, *id); - } - } + StatusEvent::CancelJob => cancelled = true, } } + if let Some(picked) = picked { + chrome_ui::set_status_item(&mut app.ui.chrome, picked); + } + if let Some(new) = edited + && let Some(i) = app.session.active_index() + { + let ppp = app.canvas_ppp(); + app.ui.views[i].set_from(&new, ppp); + } + if cancelled && let Some((id, _)) = &job { + crate::jobs_ui::cancel(app, *id); + } chrome_ui::zoom_alert(app, invalid_zoom); } -/// The status bar's view. -fn status_view(props: &mut StatusProps<'_>, ui: &mut egui::Ui) { - let mut cancelled = false; - let mut picked = None; - let mut invalid_zoom = None; - let mut edited = None; - Bar::new("", BarKind::Status) - .trailing(|ui, _| { - if let Some(shown) = &props.render_path { - shown.show(ui); - } - if let Some(progress) = &props.redraw { - progress.widget().show(ui); - } - if let Some(progress) = &props.job { - cancelled |= progress.widget().show(ui).cancelled; - } - }) - .show(ui, |ui, _| { - match (props.document, props.view) { - (Some(size), Some(view)) => { - let out = StatusReadout::new(Bind::given(view), size, props.item, &props.values).show(ui); - picked = out.item.or(picked); - invalid_zoom = out.invalid_zoom.or(invalid_zoom.take()); - edited = out.view.value().copied().or(edited); - } - (Some(_), None) => {} - (None, _) => { - StatusMessage::new(tl!("No document")).show(ui); - } - } - // A command run with no document open still reports here (#1567: File › Automate › Batch). - if let Some(shown) = &props.message { - shown.show(ui); - } - }); - if let Some(picked) = picked { - props.out.send(StatusEvent::Item(picked)); +/// The status bar's trailing group. +fn trailing_view(props: &mut TrailingProps<'_>, ui: &mut egui::Ui) { + if let Some(shown) = &props.render_path { + shown.show(ui); } - if let Some(view) = edited { - props.out.send(StatusEvent::View(view)); + if let Some(progress) = &props.redraw { + progress.widget().show(ui); } - if let Some(invalid) = invalid_zoom { - props.out.send(StatusEvent::InvalidZoom(invalid)); - } - if cancelled { + if let Some(progress) = &props.job + && progress.widget().show(ui).cancelled + { props.out.send(StatusEvent::CancelJob); } } + +/// The status bar's body. +fn body_view(props: &mut StatusProps<'_>, ui: &mut egui::Ui) { + match (props.document, props.view) { + (Some(size), Some(view)) => { + let out = StatusReadout::new(Bind::given(view), size, props.item, &props.values).show(ui); + if let Some(picked) = out.item { + props.out.send(StatusEvent::Item(picked)); + } + if let Some(view) = out.view.value().copied() { + props.out.send(StatusEvent::View(view)); + } + if let Some(invalid) = out.invalid_zoom { + props.out.send(StatusEvent::InvalidZoom(invalid)); + } + } + (Some(_), None) => {} + (None, _) => { + StatusMessage::new(tl!("No document")).show(ui); + } + } + // A command run with no document open still reports here (#1567: File › Automate › Batch). + if let Some(shown) = &props.message { + shown.show(ui); + } +} From 72f7f9377718b3a329de3aa75a9e28c61fc2edf9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 14:27:04 +0000 Subject: [PATCH 35/38] Document state is Tracked (#15709) --- Cargo.lock | 8 ++ crates/color/Cargo.toml | 3 + crates/color/src/blend.rs | 2 +- crates/color/src/lib.rs | 8 +- crates/doc/Cargo.toml | 2 +- crates/doc/src/adjust.rs | 16 +-- crates/doc/src/advanced.rs | 4 +- crates/doc/src/analysis.rs | 10 +- crates/doc/src/blend_if.rs | 4 +- crates/doc/src/comps.rs | 10 +- crates/doc/src/effects.rs | 40 +++--- crates/doc/src/frame.rs | 2 +- crates/doc/src/import_conversion.rs | 18 +-- crates/doc/src/layer_tree.rs | 6 + crates/doc/src/lib.rs | 45 +++--- crates/doc/src/mode.rs | 10 +- crates/doc/src/pattern.rs | 4 +- crates/doc/src/slices.rs | 10 +- crates/doc/src/text.rs | 30 ++-- crates/doc/src/text_styles.rs | 10 +- crates/doc/src/variables.rs | 16 +-- crates/doc/src/vector.rs | 28 ++-- crates/doc/src/video.rs | 6 +- crates/engine/src/cmd/channel_cmds/view.rs | 4 +- crates/engine/src/cmd/edit_cmds.rs | 4 - crates/engine/src/cmd/edit_menu_cmds/purge.rs | 2 +- crates/engine/src/cmd/file_cmds/processing.rs | 4 +- crates/engine/src/cmd/float_cmds.rs | 15 +- crates/engine/src/cmd/fx_view_cmds.rs | 7 +- crates/engine/src/cmd/group_view_cmds.rs | 7 +- crates/engine/src/cmd/history_cmds.rs | 2 +- crates/engine/src/cmd/mask_view_cmds.rs | 11 +- crates/engine/src/cmd/slice_cmds.rs | 6 +- crates/engine/src/cmd/symmetry_cmds.rs | 4 +- crates/engine/src/doc_state.rs | 51 +++---- crates/engine/src/jobs.rs | 23 ++- crates/engine/src/lib.rs | 9 +- crates/engine/src/link_watch.rs | 27 ++-- crates/engine/src/prefs.rs | 12 +- crates/engine/src/presets.rs | 1 - crates/engine/src/presets/clone_source.rs | 2 +- crates/engine/src/presets/shapes.rs | 1 - crates/engine/src/presets/styles.rs | 2 - crates/engine/src/session/documents.rs | 33 ++++- crates/geom/Cargo.toml | 3 + crates/geom/src/lib.rs | 10 +- crates/geom/src/warp.rs | 8 +- crates/ops/Cargo.toml | 3 + crates/ops/src/lib.rs | 12 +- crates/ops/src/tiles.rs | 2 +- crates/paint/src/symmetry.rs | 4 +- crates/raster/Cargo.toml | 3 + crates/raster/src/interrupt.rs | 2 +- crates/raster/src/lib.rs | 15 +- crates/ui-egui/src/app.rs | 1 - crates/ui-egui/src/app/files.rs | 2 +- crates/ui-egui/src/app/targets.rs | 20 ++- crates/ui-egui/src/doc_revision_trials.rs | 24 ++-- crates/ui-egui/src/doc_tracked_trials.rs | 133 ++++++++++++++++++ crates/ui-egui/src/home_recent_ui.rs | 4 +- crates/ui-egui/src/lib.rs | 4 +- crates/ui-egui/src/menus/facts.rs | 10 +- crates/ui-egui/src/panels/layers.rs | 15 +- crates/ui-egui/src/panels/layers_tree.rs | 123 +++++++++++----- .../src/panels/preset_panels/clone_source.rs | 2 +- crates/ui-egui/src/save_identity_tests.rs | 2 +- .../ui-egui/src/tools/type_tool/defaults.rs | 2 +- 67 files changed, 597 insertions(+), 326 deletions(-) create mode 100644 crates/ui-egui/src/doc_tracked_trials.rs diff --git a/Cargo.lock b/Cargo.lock index cc668196ee..ac35cf8938 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6460,6 +6460,8 @@ name = "photocraft-color" version = "0.23.1" dependencies = [ "craft-cms", + "craft-tracked", + "craft-ui-macros", "serde", ] @@ -6571,6 +6573,8 @@ dependencies = [ name = "photocraft-geom" version = "0.23.1" dependencies = [ + "craft-tracked", + "craft-ui-macros", "serde", ] @@ -6661,6 +6665,8 @@ dependencies = [ name = "photocraft-ops" version = "0.23.1" dependencies = [ + "craft-tracked", + "craft-ui-macros", "photocraft-doc", ] @@ -6701,6 +6707,8 @@ dependencies = [ name = "photocraft-raster" version = "0.23.1" dependencies = [ + "craft-tracked", + "craft-ui-macros", "crc32fast", "lz4_flex", "photocraft-color", diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml index df5d12cb34..a424eb6b2d 100644 --- a/crates/color/Cargo.toml +++ b/crates/color/Cargo.toml @@ -10,3 +10,6 @@ workspace = true [dependencies] craft-cms = { workspace = true } serde = { workspace = true } +# Plain data (the engine holds documents in a `Tracked`): the marker and its derive, without the UI. +craft-tracked = { workspace = true } +craft-ui-macros = { workspace = true } diff --git a/crates/color/src/blend.rs b/crates/color/src/blend.rs index 7b26f06a4f..43861a5c21 100644 --- a/crates/color/src/blend.rs +++ b/crates/color/src/blend.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize}; -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum BlendMode { /// Groups only: children blend directly into the group's backdrop. PassThrough, diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 281c3e01b9..bb95599702 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -24,7 +24,7 @@ pub fn dither_noise(x: i32, y: i32) -> f32 { use serde::{Deserialize, Serialize}; /// Storage type of one channel sample. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum SampleType { U8, U16, @@ -47,7 +47,7 @@ impl SampleType { } /// Document colour model (Photoshop "Image → Mode"). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum ColorMode { Bitmap, Grayscale, @@ -74,7 +74,7 @@ impl ColorMode { } /// Layout of a pixel: colour model, sample type, and whether an alpha channel follows the colour channels. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct PixelFormat { pub mode: ColorMode, pub sample: SampleType, @@ -161,7 +161,7 @@ pub fn write_sample(bytes: &mut [u8], sample: SampleType, index: usize, v: f32) } /// A colour value in the document's model with alpha, as normalised floats. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Color { pub mode: ColorMode, /// Up to 4 colour components (unused ones are 0) followed by nothing; alpha kept separately. diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index 296cbe090d..f6a95a38c9 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -13,6 +13,6 @@ photocraft-color = { workspace = true } photocraft-raster = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } -# LayerId is plain data (the Layers panel keys its rows by it): the marker and its derive, without the UI. +# Plain data (the engine holds documents in a `Tracked`): the marker and its derive, without the UI. craft-tracked = { workspace = true } craft-ui-macros = { workspace = true } diff --git a/crates/doc/src/adjust.rs b/crates/doc/src/adjust.rs index 78603f6ae1..fc8d78a611 100644 --- a/crates/doc/src/adjust.rs +++ b/crates/doc/src/adjust.rs @@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize}; use std::sync::Arc; -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct CurvePoint { pub input: f32, pub output: f32, @@ -18,7 +18,7 @@ pub fn is_identity_curve(points: &[CurvePoint]) -> bool { } /// A 3D LUT file format (Photoshop's `LUTFormat`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum LutFormat { #[serde(rename = "cube")] Cube, @@ -29,7 +29,7 @@ pub enum LutFormat { } /// A Color Lookup's LUT file as loaded: its format and bytes. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct LutSource { pub format: LutFormat, pub bytes: Arc>, @@ -92,7 +92,7 @@ pub fn lut3d_len(size: u32) -> Option { usize::try_from(size).ok()?.checked_pow(3)?.checked_mul(3) } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct LevelsChannel { pub in_black: f32, pub in_white: f32, @@ -111,7 +111,7 @@ impl Default for LevelsChannel { /// happens in display RGB; `Cmyk` and `Lab` records are applied to the pixel converted into that /// space (the same conversions the document's surfaces use), so ink and Lab channel edits behave /// like Photoshop's in CMYK and Lab documents. Grayscale documents use `Rgb` with the master record. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum ToneSpace { /// `per_channel` = red, green, blue. #[default] @@ -125,7 +125,7 @@ pub enum ToneSpace { } /// One of Hue/Saturation's six colour ranges (reds, yellows, greens, cyans, blues, magentas). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct HueRange { /// Hue shift in degrees (-180..=180). pub hue: f32, @@ -197,7 +197,7 @@ fn default_hue_ranges() -> [HueRange; 6] { /// A gradient as Photoshop's Gradient Editor holds it (#8351): a few colour stops, a midpoint /// on each segment, Smoothness and the interpolation method, which renderers bake into dense /// linear stops. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct GradientSource { /// Colour stops (location 0..1, sRGB), in location order. pub stops: Vec<(f32, [f32; 3])>, @@ -211,7 +211,7 @@ pub struct GradientSource { } /// Photoshop adjustment layers (Layer → New Adjustment Layer). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum Adjustment { BrightnessContrast { brightness: f32, diff --git a/crates/doc/src/advanced.rs b/crates/doc/src/advanced.rs index 073b6f8b85..5e70185404 100644 --- a/crates/doc/src/advanced.rs +++ b/crates/doc/src/advanced.rs @@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize}; /// Blending Options › Advanced Blending › Knockout: which layers beneath this one its shape /// punches through. Fill opacity controls the strength (0 % fill shows the knocked-out area bare). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum Knockout { /// The layer blends with everything beneath it (the default). @@ -68,7 +68,7 @@ impl Knockout { } /// The Advanced Blending switches of a layer (see the module docs). `Default` is Photoshop's. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default, rename_all = "camelCase")] pub struct AdvancedBlending { /// Knockout: None / Shallow / Deep. PSD `knko`. diff --git a/crates/doc/src/analysis.rs b/crates/doc/src/analysis.rs index 9b1d8efdb0..2975210d57 100644 --- a/crates/doc/src/analysis.rs +++ b/crates/doc/src/analysis.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; /// Image › Analysis › Set Measurement Scale: `pixel_length` pixels equal `logical_length` /// `units`. The default is 1 pixel = 1 pixel. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct MeasurementScale { pub pixel_length: f64, @@ -37,7 +37,7 @@ impl MeasurementScale { } /// One Count tool group: its numbered markers (document pixel coordinates, in click order). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct CountGroup { pub name: String, @@ -57,7 +57,7 @@ impl Default for CountGroup { /// The Ruler tool line, optionally with a protractor second arm (⌥-drag from an end point). /// `start` is the vertex the angle is measured at when there is a protractor. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Ruler { pub start: [f64; 2], pub end: [f64; 2], @@ -66,7 +66,7 @@ pub struct Ruler { } /// Measurement settings and marks of a document. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct Measurement { pub scale: MeasurementScale, @@ -87,7 +87,7 @@ impl Measurement { } /// A Note tool annotation (PSD `Anno` text annotation). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct Note { pub author: String, diff --git a/crates/doc/src/blend_if.rs b/crates/doc/src/blend_if.rs index ce7c279e9f..117d08adce 100644 --- a/crates/doc/src/blend_if.rs +++ b/crates/doc/src/blend_if.rs @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize}; /// One Blend If slider pair: `black` = (low, high), `white` = (low, high), all on 0..=255. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct BlendRange { pub black: [u8; 2], pub white: [u8; 2], @@ -75,7 +75,7 @@ impl BlendRange { /// A layer's Blend If settings. `ranges[0]` is the "Gray" entry (composite of the colour /// channels), then one entry per colour channel of the document's mode (R, G, B / C, M, Y, K / /// L, a, b / Gray), each as `[this layer, underlying layer]`. Empty = every pixel blends. -#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct BlendIf { pub ranges: Vec<[BlendRange; 2]>, } diff --git a/crates/doc/src/comps.rs b/crates/doc/src/comps.rs index 796baa7d43..98dcbe17d4 100644 --- a/crates/doc/src/comps.rs +++ b/crates/doc/src/comps.rs @@ -15,7 +15,7 @@ use crate::{Document, Effects, Layer, LayerContent, LayerId}; /// One layer's state as captured by a comp. `None` = not recorded (PSD comps record only what /// their capture flags asked for). -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct CompLayerState { pub layer: LayerId, pub visible: Option, @@ -26,7 +26,7 @@ pub struct CompLayerState { } /// Layer › Layer Style state captured by "Appearance". -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct CompAppearance { pub blend: BlendMode, pub opacity: f32, @@ -34,7 +34,7 @@ pub struct CompAppearance { pub effects: Effects, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct LayerComp { /// Stable id (the PSD `compID`). Never 0: Photoshop uses 0 for the Last Document State. pub id: u32, @@ -107,7 +107,7 @@ pub fn next_comp_id(doc: &Document) -> u32 { } /// What an artboard paints behind its contents. -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum ArtboardBackground { #[default] @@ -151,7 +151,7 @@ impl ArtboardBackground { /// An artboard: a top-level group that clips its children to `rect` and paints `background` /// behind them (Layer › New › Artboard). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Artboard { /// The board in document pixels. pub rect: Rect, diff --git a/crates/doc/src/effects.rs b/crates/doc/src/effects.rs index a71aa883dd..a6836523a3 100644 --- a/crates/doc/src/effects.rs +++ b/crates/doc/src/effects.rs @@ -15,7 +15,7 @@ use crate::adjust::CurvePoint; pub const PATTERN_SCALE_RANGE: (f32, f32) = (0.01, 10.0); /// Gradient geometry (fill layers, gradient overlays, gradient strokes). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum GradientStyle { #[default] Linear, @@ -26,7 +26,7 @@ pub enum GradientStyle { } /// A gradient: colour stops plus transparency stops (both at `0..=1`). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Gradient { pub stops: Vec<(f32, Color)>, /// Opacity stops; empty means fully opaque. @@ -44,7 +44,7 @@ pub struct Gradient { /// Editable colour stops behind a Gradient Overlay's baked render stops. /// Older documents have no interpolation record and keep their existing appearance. /// Writers must rebake `gradient.stops` from this record, or clear it when replacing the curve. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct GradientInterpolation { pub method: String, pub smoothness: f32, @@ -67,7 +67,7 @@ impl Default for Gradient { } /// Effect contour (transfer curve applied to the effect's coverage). -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum Contour { #[default] Linear, @@ -93,7 +93,7 @@ impl Contour { } /// Paint used by strokes and glows. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum FxPaint { Color(Color), Gradient(Gradient), @@ -106,7 +106,7 @@ pub enum FxPaint { } /// Blend mode + opacity + enabled, shared by every effect. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct FxCommon { pub enabled: bool, pub blend: BlendMode, @@ -119,7 +119,7 @@ impl FxCommon { } } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Shadow { pub common: FxCommon, pub color: Color, @@ -136,21 +136,21 @@ pub struct Shadow { pub knocks_out: bool, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum GlowTechnique { #[default] Softer, Precise, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum GlowSource { Center, #[default] Edge, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Glow { pub common: FxCommon, pub paint: FxPaint, @@ -167,14 +167,14 @@ pub struct Glow { pub source: GlowSource, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum StrokePosition { Outside, Inside, Center, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct StrokeFx { pub common: FxCommon, pub size: f32, @@ -185,7 +185,7 @@ pub struct StrokeFx { pub overprint: bool, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Satin { pub common: FxCommon, pub color: Color, @@ -197,7 +197,7 @@ pub struct Satin { pub invert: bool, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum BevelStyle { OuterBevel, #[default] @@ -207,7 +207,7 @@ pub enum BevelStyle { StrokeEmboss, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum BevelTechnique { #[default] Smooth, @@ -215,7 +215,7 @@ pub enum BevelTechnique { ChiselSoft, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Bevel { pub enabled: bool, pub style: BevelStyle, @@ -246,7 +246,7 @@ pub struct Bevel { } /// The Contour element of Bevel & Emboss. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct BevelContour { pub contour: Contour, /// Range `0..=1` (Photoshop's default 50 %): the part of the bevel the contour spans. @@ -261,7 +261,7 @@ impl Default for BevelContour { } /// The Texture element of Bevel & Emboss. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct BevelTexture { pub name: String, pub id: String, @@ -277,7 +277,7 @@ pub struct BevelTexture { /// One layer effect. Several instances of the same kind are allowed /// (Photoshop's multiple strokes/shadows/overlays). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum Effect { DropShadow(Shadow), InnerShadow(Shadow), @@ -409,7 +409,7 @@ pub fn yes() -> bool { } /// Document-wide light used by effects with `use_global_light`. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct GlobalLight { pub angle: f32, pub altitude: f32, diff --git a/crates/doc/src/frame.rs b/crates/doc/src/frame.rs index 251671111b..97e507270b 100644 --- a/crates/doc/src/frame.rs +++ b/crates/doc/src/frame.rs @@ -4,7 +4,7 @@ use crate::{Path, ShapeLayer, ShapeStroke}; use photocraft_geom::{Affine, Point, Rect}; use serde::{Deserialize, Serialize}; -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Frame { pub path: Path, pub transform: Affine, diff --git a/crates/doc/src/import_conversion.rs b/crates/doc/src/import_conversion.rs index 8383564794..2846f3f52f 100644 --- a/crates/doc/src/import_conversion.rs +++ b/crates/doc/src/import_conversion.rs @@ -22,13 +22,13 @@ const TARGET_BYTES: usize = 128; const ATTACHMENT_BYTES: usize = 160; /// An optional future report is retained without interpreting its record or binary payloads. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub enum ImportConversion { Report(ConversionReport), Opaque { schema_version: u32, record: Arc>, attachments: Vec>> }, } -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub struct ConversionReport { pub source_format: String, @@ -40,7 +40,7 @@ pub struct ConversionReport { pub attachments: Vec, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub struct ConversionEntry { pub feature_code: String, @@ -55,7 +55,7 @@ pub struct ConversionEntry { pub attachments: Vec, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "snake_case")] pub enum ConversionDisposition { NativeEquivalent, @@ -64,7 +64,7 @@ pub enum ConversionDisposition { SkippedNonessential, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "snake_case")] pub enum ConversionReason { NativePolicy, @@ -77,7 +77,7 @@ pub enum ConversionReason { } /// Ordinals/paths identify the source snapshot, including duplicate display names. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub struct SourceItemRef { pub kind: String, @@ -90,7 +90,7 @@ pub struct SourceItemRef { } /// Import-time references may become stale; they are never remapped into live instructions. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub struct NativeTargetRef { pub layer_id: Option, @@ -102,7 +102,7 @@ pub struct NativeTargetRef { pub label: String, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub struct RetainedImportData { pub owner: SourceItemRef, @@ -113,7 +113,7 @@ pub struct RetainedImportData { pub bytes: Arc>, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui_macros::PlainData)] pub enum ConversionValidationError { Limit(&'static str), Invalid(&'static str), diff --git a/crates/doc/src/layer_tree.rs b/crates/doc/src/layer_tree.rs index b6b8614002..3ea7c6aa30 100644 --- a/crates/doc/src/layer_tree.rs +++ b/crates/doc/src/layer_tree.rs @@ -135,6 +135,12 @@ impl DerefMut for LayerTree { } } +// The index is a pure function of `layers`: every write goes through `DerefMut`, which drops it, `Clone` starts +// without it, and every lookup answers the same whether it is built or not. Its one observable trace is +// `LayerIndex::serial`, a rebuild probe for tests that no view reads. So a shared reference can't change what readers +// see, and a `Tracked` document's revision covers the tree. +impl craft_tracked::PlainData for LayerTree {} + impl Clone for LayerTree { fn clone(&self) -> Self { Self { layers: self.layers.clone(), index: OnceLock::new() } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 79df00ab90..20b279ba14 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -69,7 +69,7 @@ impl LayerId { } /// Identity of the source contents shared by smart-object instances, independent of their bytes. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct SmartContentsId(pub u64); impl SmartContentsId { @@ -93,7 +93,7 @@ impl DocId { } } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Locks { pub transparency: bool, pub pixels: bool, @@ -141,7 +141,7 @@ impl Locks { } /// Photoshop layer colour labels. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum LabelColor { #[default] None, @@ -245,7 +245,7 @@ mod label_color_tests { } } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct LayerMask { /// Grayscale surface; untouched pixels read as `default` (0 = hide, 1 = reveal). pub surface: Surface, @@ -295,7 +295,7 @@ impl LayerMask { } /// Layer styles. Parsed PSD effect data is kept raw until the effects engine lands (M9). -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq, craft_ui_macros::PlainData)] pub struct Effects { pub enabled: bool, pub items: Vec, @@ -327,7 +327,7 @@ pub fn walks() -> u64 { WALKS.with(std::cell::Cell::get) } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct Group { pub children: Vec, pub expanded: bool, @@ -339,7 +339,7 @@ pub struct Group { pub frame_stroke: Option, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum Fill { Solid(Color), /// Gradient between stops at `angle` degrees (`style` geometry, optionally reversed), laid @@ -444,7 +444,7 @@ impl std::hash::Hash for Fill { } } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct TextLayer { pub text: String, pub font_family: String, @@ -559,13 +559,13 @@ fn normalize_runs(text: &str, runs: Vec<(usize, S)>, base: S) -> Vec<( /// A bounded display preview for an embedded native vector, bound to its exact source bytes. /// The SVG is display data only; saving the object retains the native source format. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct VectorPreview { pub source_hash: [u8; 32], pub svg: Arc>, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct SmartObject { /// Ordinary layer duplicates share this identity; independent contents receive a fresh one. pub contents_id: SmartContentsId, @@ -624,16 +624,17 @@ impl SmartObject { } } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub enum SmartSource { Embedded { file_name: String, bytes: Arc> }, Linked { path: String }, } /// A filter applied non-destructively: a command id plus its parameters (data, not code). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct SmartFilter { pub command: String, + #[plain_data(assume = "JSON value: plain data")] pub params: serde_json::Value, pub blend: BlendMode, pub opacity: f32, @@ -645,7 +646,7 @@ pub struct SmartFilter { /// Used by the compositor instead of rendering [`Fill`] itself, but only while /// `fill` still equals the layer's current fill (editing the fill invalidates /// the cache automatically). -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct FillCache { /// The fill these pixels were rendered for. pub fill: Fill, @@ -653,7 +654,7 @@ pub struct FillCache { pub surface: Surface, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub enum LayerContent { Raster(Surface), Group(Group), @@ -686,7 +687,7 @@ impl LayerContent { } } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct Layer { pub id: LayerId, pub name: String, @@ -836,7 +837,7 @@ impl Layer { /// Ruler guides in document pixels. f64 like the rest of the view geometry: a guide placed in /// ruler units (1 cm at 300 ppi is 118.110236… px) or read from a PSD's 1/32 px positions keeps /// its exact place. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Guides { pub horizontal: Vec, pub vertical: Vec, @@ -849,7 +850,7 @@ pub struct Guides { /// One guide's own colour. It is keyed by orientation and position, not by index, so code that /// drops or reorders guide positions (crop, artboards, guide layouts) can never move a colour onto /// another guide: a guide whose entry no longer matches simply uses the preference colour. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct GuideColor { pub vertical: bool, pub position: f64, @@ -879,7 +880,7 @@ impl Guides { } /// Which areas an alpha channel's overlay colour marks (Channel Options › Color Indicates). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum ColorIndicates { /// Colour shows over black (unselected) pixels: Photoshop's default. @@ -892,7 +893,7 @@ pub enum ColorIndicates { /// An extra (alpha or spot) channel, also used for the temporary Quick Mask channel. /// /// The surface is grayscale at the document depth; white = selected (1.0), black = masked. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct AlphaChannel { pub name: String, pub surface: Surface, @@ -923,7 +924,7 @@ impl AlphaChannel { /// A raw PSD global tagged block: (signature, key, data). pub type PsdGlobalBlock = ([u8; 4], [u8; 4], Arc>); -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq, craft_ui_macros::PlainData)] pub struct Metadata { /// Historical conversion information; never consulted by native rendering or editing. /// Shared so document/history clones do not duplicate report entries, strings or retained payloads. @@ -942,7 +943,7 @@ pub struct Metadata { pub psd_global_blocks: Vec, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct Document { pub id: DocId, pub name: String, @@ -1014,7 +1015,7 @@ pub struct Document { /// The encoder settings a document's file was opened or saved with: what File › Save and the /// Save As defaults reuse for that format. Empty for a new document or a file without lossy /// options. Qualities are on the codecs' 1–100 scale. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default, rename_all = "camelCase")] pub struct FileEncoding { /// JPEG quality (estimated from the file's quantisation tables on open). diff --git a/crates/doc/src/mode.rs b/crates/doc/src/mode.rs index 3fecadd2b7..9980c49ed5 100644 --- a/crates/doc/src/mode.rs +++ b/crates/doc/src/mode.rs @@ -14,7 +14,7 @@ use crate::LayerId; use crate::adjust::CurvePoint; /// Image › Mode › Color Table: the palette of an Indexed Color document (at most 256 entries). -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct ColorTable { /// sRGB 8-bit entries. pub colors: Vec<[u8; 3]>, @@ -53,7 +53,7 @@ impl ColorTable { /// pixel copy while the layer is unchanged. A save keeps the indices only while they hold, and an /// open pairs them with the layer it loads: identical tiles load as one, so loaded pixels can't /// prove they are unchanged. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct ColorIndices { /// The layer the indices are for. pub layer: LayerId, @@ -91,7 +91,7 @@ impl ColorIndices { } /// One Duotone ink: its display colour and the curve mapping gray density to ink density. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct DuotoneInk { pub name: String, /// Display colour of the solid ink (sRGB 0..=1). @@ -107,7 +107,7 @@ impl DuotoneInk { } /// Image › Mode › Duotone: 1–4 inks (Monotone, Duotone, Tritone, Quadtone) printed over paper. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Duotone { pub inks: Vec, /// The PSD colour-mode data this came from, written back unchanged while the inks are unedited. @@ -172,7 +172,7 @@ fn curve_eval(pts: &[CurvePoint], x: f32) -> f32 { } /// Layer › Smart Objects › Stack Mode: a per-pixel statistic over the smart object's layers. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum StackMode { Entropy, Kurtosis, diff --git a/crates/doc/src/pattern.rs b/crates/doc/src/pattern.rs index 185ddb9ccb..d07fb34ab9 100644 --- a/crates/doc/src/pattern.rs +++ b/crates/doc/src/pattern.rs @@ -14,7 +14,7 @@ pub const MAX_EDGE: u32 = 30_000; pub const MAX_PAINT_PIXELS: u64 = 1 << 26; /// A bounded, cancellable pattern hash could not be completed. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, craft_ui_macros::PlainData)] pub enum PatternBuildError { InvalidDimensions, ScratchLimit { required: usize, available: usize }, @@ -58,7 +58,7 @@ pub const BAND_ROWS: u32 = 256; /// One pattern tile. Pixels cover `0..width × 0..height` of `surface`, in any pixel format /// (depth and colour model are the pattern's own, as in Photoshop). -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct Pattern { /// Unique id (a UUID string, as Photoshop's `Idnt`). pub id: String, diff --git a/crates/doc/src/slices.rs b/crates/doc/src/slices.rs index 6bfb9b1577..b1a7509d85 100644 --- a/crates/doc/src/slices.rs +++ b/crates/doc/src/slices.rs @@ -12,7 +12,7 @@ use serde::{Deserialize, Serialize}; use crate::{Document, LayerId}; /// Where a slice comes from (PSD `ESliceOrigin`). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum SliceOrigin { /// Fills the canvas around user and layer slices; regenerated, never edited. @@ -50,7 +50,7 @@ impl SliceOrigin { } /// Slice Options › Slice Type. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum SliceKind { /// Exported as an image file. @@ -96,7 +96,7 @@ impl SliceKind { } /// One slice and its Slice Options. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default, rename_all = "camelCase")] pub struct Slice { /// Stable id (PSD `sliceID`), unique within the document. @@ -126,7 +126,7 @@ pub struct Slice { } /// The document's slices (PSD resource 1050). -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default, rename_all = "camelCase")] pub struct Slices { /// Group name (PSD: the base name, usually the document name). @@ -154,7 +154,7 @@ impl Slices { /// A slice as shown and exported: user/layer slices plus generated auto slices, numbered the way /// Photoshop numbers them (top-to-bottom, left-to-right, from 1). -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct ResolvedSlice { /// 1-based display number. pub number: usize, diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index f6c8619f5a..e24f267d6d 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -13,7 +13,7 @@ use photocraft_color::Color; use serde::{Deserialize, Serialize}; /// Kerning mode (Photoshop: Metrics, Optical, 0). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum Kerning { /// Font kerning (`kern` feature). #[default] @@ -24,7 +24,7 @@ pub enum Kerning { Off, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum Caps { #[default] Normal, @@ -34,7 +34,7 @@ pub enum Caps { /// Superscript / subscript (Photoshop's `FontBaseline`). The run is drawn smaller and raised or /// lowered; `size_pt` and `baseline_shift_pt` keep their own values. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum FontBaseline { #[default] Normal, @@ -43,21 +43,21 @@ pub enum FontBaseline { } /// An OpenType feature setting, e.g. `{ tag: "ss01", value: 1 }`. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct FontFeature { pub tag: String, pub value: u16, } /// A variable-font axis setting, e.g. `{ axis: "wght", value: 650.0 }`. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct FontVariation { pub axis: String, pub value: f32, } /// Character style (Photoshop's Character panel). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct CharStyle { /// Family name ("Inter"). Empty = the default family. @@ -147,13 +147,13 @@ impl Default for CharStyle { } /// A character style applied to `len` UTF-8 bytes. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct TextRun { pub len: usize, pub style: CharStyle, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum TextAlign { #[default] Left, @@ -175,7 +175,7 @@ impl TextAlign { } } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum TextDirection { /// From the first strong character (Unicode bidi rules). #[default] @@ -185,7 +185,7 @@ pub enum TextDirection { } /// Paragraph style (Photoshop's Paragraph panel). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct ParagraphStyle { pub align: TextAlign, @@ -221,7 +221,7 @@ impl Default for ParagraphStyle { } /// A paragraph style applied to `len` UTF-8 bytes (whole paragraphs, including the break). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct ParagraphRun { pub len: usize, pub style: ParagraphStyle, @@ -230,7 +230,7 @@ pub struct ParagraphRun { /// Point text grows from its anchor (text-space origin = first baseline at the anchor); /// paragraph (box) text wraps inside a rectangle; path text runs along a curve; area text /// wraps inside a closed path. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum TextShape { #[default] Point, @@ -258,7 +258,7 @@ pub enum TextShape { Area { path: super::vector::Path }, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum Orientation { #[default] Horizontal, @@ -266,7 +266,7 @@ pub enum Orientation { Vertical, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum AntiAlias { None, Sharp, @@ -283,7 +283,7 @@ pub enum AntiAlias { /// Warp text settings (Photoshop `warp` descriptor), applied to the glyph outlines by /// `photocraft-text` (see its `warp` module) and round-tripped through PSD. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct TextWarp { /// `warpNone`, `warpArc`, `warpFlag`, … pub style: String, diff --git a/crates/doc/src/text_styles.rs b/crates/doc/src/text_styles.rs index bb85ef2f27..8a5f386351 100644 --- a/crates/doc/src/text_styles.rs +++ b/crates/doc/src/text_styles.rs @@ -28,31 +28,34 @@ pub type StyleAttrs = Map; const REF_KEY: &str = "style_sheet"; /// A named character style. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct CharacterStyleDef { /// Stable id (≥ 1), referenced by [`CharStyle::style_sheet`]. pub id: u32, pub name: String, /// Character attributes this style sets (others come from the paragraph style). + #[plain_data(assume = "JSON values: plain data")] pub attrs: StyleAttrs, } /// A named paragraph style (or Basic Paragraph). -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct ParagraphStyleDef { /// Stable id (≥ 1; Basic Paragraph is 0), referenced by [`ParagraphStyle::style_sheet`]. pub id: u32, pub name: String, /// Paragraph attributes this style sets. + #[plain_data(assume = "JSON values: plain data")] pub para_attrs: StyleAttrs, /// Character attributes this style sets (the basis of every run in its paragraphs). + #[plain_data(assume = "JSON values: plain data")] pub char_attrs: StyleAttrs, } /// The document's named type styles. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct TextStyles { /// Character styles in panel order ("None" is implicit and first). @@ -63,6 +66,7 @@ pub struct TextStyles { pub basic: ParagraphStyleDef, /// Style sheets of the PSD text engine this document was read from (`ResourceDict` /// `StyleSheetSet` / `ParagraphSheetSet`), kept so unmapped data survives a round trip. + #[plain_data(assume = "JSON value: plain data")] pub psd_raw: Option, } diff --git a/crates/doc/src/variables.rs b/crates/doc/src/variables.rs index 83f0e5f5a9..88385ee62b 100644 --- a/crates/doc/src/variables.rs +++ b/crates/doc/src/variables.rs @@ -13,7 +13,7 @@ use serde::{Deserialize, Serialize}; use crate::LayerId; /// All variable definitions and data sets for a document. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Variables { /// Variable definitions, each bound to a layer. #[serde(default)] @@ -27,7 +27,7 @@ pub struct Variables { } /// One named variable bound to a layer. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct VariableDef { /// Unique variable name (matched by data-set values and CSV headers). pub name: String, @@ -38,7 +38,7 @@ pub struct VariableDef { } /// The aspect of a layer a variable controls (Photoshop's three variable types). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(tag = "type", rename_all = "camelCase")] pub enum VarKind { /// Show or hide the layer. @@ -58,7 +58,7 @@ pub enum VarKind { } /// How a replacement image is scaled into the layer bounds (Photoshop's "Method"). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum PixelMethod { /// Scale to fit inside the bounds, keeping aspect (default). @@ -73,7 +73,7 @@ pub enum PixelMethod { } /// Where a replacement image sits within the layer bounds. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum PixelAlign { TopLeft, @@ -89,7 +89,7 @@ pub enum PixelAlign { } /// A named row of values, one per variable (keyed by variable name). -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct DataSet { pub name: String, /// Variable name → value. A variable with no entry keeps the document's current value. @@ -98,7 +98,7 @@ pub struct DataSet { } /// One variable's value within a data set. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct DataValue { /// Which variable (by name). pub variable: String, @@ -107,7 +107,7 @@ pub struct DataValue { } /// The payload of a [`DataValue`], matched to the variable's [`VarKind`]. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(tag = "kind", content = "value", rename_all = "camelCase")] pub enum Value { /// For a Visibility variable. diff --git a/crates/doc/src/vector.rs b/crates/doc/src/vector.rs index 0f6b4af7e2..3220eccb16 100644 --- a/crates/doc/src/vector.rs +++ b/crates/doc/src/vector.rs @@ -22,7 +22,7 @@ use serde::{Deserialize, Serialize}; use crate::{Fill, Surface}; /// A Bézier knot (anchor + two control points). -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Knot { pub anchor: Point, /// Control point of the segment arriving at this knot. @@ -50,7 +50,7 @@ impl Knot { } /// How a subpath combines with the subpaths before it (Photoshop's path operations). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum PathOp { /// Combine shapes (union). #[default] @@ -68,14 +68,14 @@ pub enum PathOp { } /// Winding rule used to fill each subpath. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum FillRule { #[default] NonZero, EvenOdd, } -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Subpath { pub closed: bool, pub knots: Vec, @@ -114,7 +114,7 @@ impl Subpath { } /// A vector path: subpaths plus how they are filled and combined. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Path { pub subpaths: Vec, #[serde(default)] @@ -167,7 +167,7 @@ impl Path { } /// A document-level path (Paths panel entry). -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq, craft_ui_macros::PlainData)] pub struct NamedPath { pub name: String, pub path: Path, @@ -176,7 +176,7 @@ pub struct NamedPath { } /// The document's clipping path (PSD resource 2999): which saved path clips on export. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct ClippingPath { pub name: String, /// Output flatness in device pixels (0 = printer default). @@ -184,7 +184,7 @@ pub struct ClippingPath { } /// A layer's vector mask (Layer › Vector Mask). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct VectorMask { pub path: Path, pub enabled: bool, @@ -204,7 +204,7 @@ impl VectorMask { } /// Where a stroke sits relative to the path. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum StrokeAlign { Inside, #[default] @@ -212,7 +212,7 @@ pub enum StrokeAlign { Outside, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum LineCap { #[default] Butt, @@ -220,7 +220,7 @@ pub enum LineCap { Square, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum LineJoin { #[default] Miter, @@ -229,7 +229,7 @@ pub enum LineJoin { } /// Shape stroke (Photoshop's shape "Stroke" options, not the layer-style stroke). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(default)] pub struct ShapeStroke { /// Width in px. @@ -291,7 +291,7 @@ impl ShapeStroke { } /// Parametric ("live") shape the path was generated from, kept for re-editing (Properties panel). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(tag = "kind", rename_all = "camelCase")] pub enum LiveShape { /// Rectangle `[x, y, w, h]` with corner radii `[tl, tr, br, bl]` (all zero = sharp). @@ -341,7 +341,7 @@ pub enum LiveShape { } /// A shape layer: a filled and/or stroked path. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct ShapeLayer { pub path: Path, /// `None` = no fill (Photoshop's fill "none"). diff --git a/crates/doc/src/video.rs b/crates/doc/src/video.rs index f93a32173e..b0d29d79b2 100644 --- a/crates/doc/src/video.rs +++ b/crates/doc/src/video.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize}; use photocraft_raster::Surface; /// Where a video layer's footage came from. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub enum VideoSource { /// Created blank (Layer › Video Layers › New Blank Video Layer). Blank, @@ -20,7 +20,7 @@ pub enum VideoSource { /// /// Frames are full raster surfaces held in memory and saved in native documents. The /// optional original footage is kept separately from painted frames for comparison/restore. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct VideoData { pub frames: Vec, /// Immutable original footage of a file-backed sequence. COW surfaces share unchanged @@ -57,7 +57,7 @@ impl PartialEq for VideoData { } /// The document timeline. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Timeline { /// Frames per second. pub fps: f32, diff --git a/crates/engine/src/cmd/channel_cmds/view.rs b/crates/engine/src/cmd/channel_cmds/view.rs index 067d05e08e..d37a93e357 100644 --- a/crates/engine/src/cmd/channel_cmds/view.rs +++ b/crates/engine/src/cmd/channel_cmds/view.rs @@ -5,7 +5,7 @@ use super::{AlphaChannel, Color, ColorIndicates, ColorMode, DocState, Document, // View state /// What pixel commands edit (Channels panel click / ⌘2…⌘9). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase", tag = "kind", content = "index")] pub enum ChannelTarget { /// The layers (all colour channels). In Quick Mask mode this edits the Quick Mask. @@ -22,7 +22,7 @@ pub enum ChannelTarget { } /// Per-document Channels panel state: the target and the eye toggles. Not part of history. -#[derive(Clone, Debug, Default, PartialEq, Serialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub struct ChannelView { pub target: ChannelTarget, diff --git a/crates/engine/src/cmd/edit_cmds.rs b/crates/engine/src/cmd/edit_cmds.rs index a70ae99f7e..2fdfad4eec 100644 --- a/crates/engine/src/cmd/edit_cmds.rs +++ b/crates/engine/src/cmd/edit_cmds.rs @@ -26,14 +26,11 @@ pub struct Clip { pub svg: Option>>, /// Native colour indices for a multi-component clip, in channel order. Singletons are grayscale. pub components: Option>, - #[plain_data(assume = "raster tiles: shared copy-on-write pixels, paged to disk unseen; a shared reference can't change them")] pub surface: Surface, - #[plain_data(assume = "geometry: plain numbers")] pub bounds: Rect, /// The copied layer itself, when Copy took a whole layer that Paste should recreate rather /// than rasterize (see [`whole_layer`]): a scratch document in the source's colour holding it. /// `surface` still holds its pixels, for Paste Into, masks, channels and other apps. - #[plain_data(assume = "the scratch document is replaced, never changed in place")] pub layers: Option>, /// The source document's resolution (ppi): File › New from the clipboard takes it, as /// Photoshop's Clipboard preset does. None for an image from another app. @@ -44,7 +41,6 @@ pub struct Clip { /// The artboard the pixels were copied from (its id and rect at the time), when they came /// from one: Paste into another board of the same document keeps their place on the board /// ([`board_shift`], #8788). None outside boards, across several, or for a copied board. - #[plain_data(assume = "a layer id and its rect: plain numbers")] pub board: Option<(LayerId, Rect)>, } diff --git a/crates/engine/src/cmd/edit_menu_cmds/purge.rs b/crates/engine/src/cmd/edit_menu_cmds/purge.rs index 3cc6aee5b3..8f84de4fe7 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/purge.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/purge.rs @@ -3,7 +3,7 @@ use super::{Result, Session, Value, json}; // ------------------------------------------------------------------ Purge fn history_bytes(s: &Session, all: bool) -> usize { - let docs: Vec<&crate::DocState> = if all { s.documents().iter().collect() } else { s.active().into_iter().collect() }; + let docs: Vec<&crate::DocState> = if all { s.documents().iter().map(|st| &**st).collect() } else { s.active().into_iter().collect() }; // Purge keeps the snapshots, so the tiles they share with the states aren't freed. docs.iter() .map(|d| { diff --git a/crates/engine/src/cmd/file_cmds/processing.rs b/crates/engine/src/cmd/file_cmds/processing.rs index 6700353339..68d55fe0e9 100644 --- a/crates/engine/src/cmd/file_cmds/processing.rs +++ b/crates/engine/src/cmd/file_cmds/processing.rs @@ -137,7 +137,7 @@ pub(super) fn image_processor(s: &mut Session, p: &Value) -> Result { let inputs = batch_inputs_tree(p, cmd, &output)?; process_tree(s, &inputs, &output, format, save, TreeNaming::Unique, &process) } else { - let documents = if source == "current" { vec![s.active().ok_or(EngineError::NoDocument)?] } else { s.documents().iter().collect() }; + let documents = if source == "current" { vec![s.active().ok_or(EngineError::NoDocument)?] } else { s.documents().iter().map(|st| &**st).collect() }; if documents.is_empty() { return Err(EngineError::NoDocument); } @@ -227,7 +227,7 @@ fn image_processor_formats(s: &Session, p: &Value, source: &str, output: &str) - "folder" => ProcessorInputs::Folder(batch_inputs_tree(p, IMAGE_PROCESSOR, output)?), "current" => ProcessorInputs::Documents(vec![s.active().ok_or(EngineError::NoDocument)?]), _ if s.documents().is_empty() => return Err(EngineError::NoDocument), - _ => ProcessorInputs::Documents(s.documents().iter().collect()), + _ => ProcessorInputs::Documents(s.documents().iter().map(|st| &**st).collect()), }; let mut files = Vec::new(); let mut errors = Vec::new(); diff --git a/crates/engine/src/cmd/float_cmds.rs b/crates/engine/src/cmd/float_cmds.rs index 2853788b02..9a06516353 100644 --- a/crates/engine/src/cmd/float_cmds.rs +++ b/crates/engine/src/cmd/float_cmds.rs @@ -28,7 +28,7 @@ use crate::{DocState, EngineError, Result, Session}; /// A layer split by its selection: the layer with the selected pixels cut out, and the cut pixels /// (cropped to the selection). Splitting touches only the selection's area, and placing the piece /// ([`CutParts::moved`]) only the piece's: the cut-out layer's other tiles are shared. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct CutParts { pub layer: LayerId, rest: Surface, @@ -258,7 +258,7 @@ fn cut_piece(base: &Surface, sel: &Surface, b: photocraft_geom::Rect, with_alpha } /// A piece floating `offset` whole pixels from where it was cut, over document `revision`. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct Floating { pub layer: LayerId, pub offset: (i32, i32), @@ -392,11 +392,18 @@ pub(crate) fn drops_for(s: &Session, id: &str) -> bool { /// Before any command (`Session::dispatch`): Undo puts a floating piece back (and is used up: /// returns its result); every other command but the floating ones drops it first. pub(crate) fn before_command(s: &mut Session, id: &str) -> Result> { - let Some(st) = s.active_mut() else { return Ok(None) }; + // Runs before every command: read through `active`, and borrow the document to change only to drop a stale + // float, since the borrow moves its `Tracked` revision. + let Some(st) = s.active() else { return Ok(None) }; if floating(st).is_none() { - st.floating = None; + if st.floating.is_some() + && let Some(st) = s.active_mut() + { + st.floating = None; + } return Ok(None); } + let Some(st) = s.active_mut() else { return Ok(None) }; match id { // Edit › Undo and the History panel's Step Backward step back over the move itself. "edit.undo" | "history.stepBackward" => { diff --git a/crates/engine/src/cmd/fx_view_cmds.rs b/crates/engine/src/cmd/fx_view_cmds.rs index 58bac49b32..7031d4c7b6 100644 --- a/crates/engine/src/cmd/fx_view_cmds.rs +++ b/crates/engine/src/cmd/fx_view_cmds.rs @@ -64,7 +64,6 @@ fn set_expanded(s: &mut Session, p: &Value) -> Result { if !expanded { st.fx_collapsed.extend(targets.iter().copied()); } - st.note_disclosure_change(); Ok(json!({"expanded": expanded, "layers": targets.len()})) } @@ -104,7 +103,7 @@ mod tests { } /// Smart Filters hide and show with the layer's effects, as view state: no document edit, revision or history step; - /// the Layers view revision, which the Layers panel's rows follow, moves. + /// the document's `Tracked` revision, which the Layers panel's rows follow, moves. #[test] fn smart_filters_share_the_effects_disclosure_without_an_edit() { let (mut s, a, b) = session(); @@ -113,7 +112,7 @@ mod tests { s.execute("image.adjustments.invert", json!({})).unwrap(); let smart = s.active().unwrap().active_layer.unwrap(); let doc = s.active().unwrap().doc.clone(); - let revisions = |s: &Session| s.active().map(|st| (st.revision, st.layers_view_revision())).unwrap(); + let revisions = |s: &Session| s.active_tracked().map(|st| (st.revision, st.revision().count)).unwrap(); let before = revisions(&s); let steps = s.active().unwrap().history.past_len(); s.execute(ID, json!({"layer": smart.0, "expanded": false})).unwrap(); @@ -121,7 +120,7 @@ mod tests { assert!(open(&s, b)); assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); let after = revisions(&s); - assert!(after.0 == before.0 && after.1 > before.1, "the Layers view revision only: {before:?} -> {after:?}"); + assert!(after.0 == before.0 && after.1 > before.1, "the tracked revision only: {before:?} -> {after:?}"); assert_eq!(s.active().unwrap().history.past_len(), steps); s.execute(ID, json!({"expanded": false, "all": true})).unwrap(); assert!(!open(&s, smart.0) && !open(&s, b)); diff --git a/crates/engine/src/cmd/group_view_cmds.rs b/crates/engine/src/cmd/group_view_cmds.rs index df742dbae0..6e004dbedc 100644 --- a/crates/engine/src/cmd/group_view_cmds.rs +++ b/crates/engine/src/cmd/group_view_cmds.rs @@ -77,7 +77,6 @@ fn set_expanded(s: &mut Session, p: &Value) -> Result { _ => return Err(EngineError::NoLayer(id)), } }; - st.note_disclosure_change(); Ok(json!({"expanded": expanded, "groups": changed})) } @@ -121,10 +120,10 @@ mod tests { st.saved_revision = st.revision; let undo_steps = s.active().unwrap().history.entries().len(); assert!(expanded(&s, inner) && expanded(&s, outer)); - let (revision, view) = s.active().map(|st| (st.revision, st.layers_view_revision())).unwrap(); + let (revision, view) = s.active_tracked().map(|st| (st.revision, st.revision())).unwrap(); assert_eq!(s.execute(ID, json!({"layer": inner})).unwrap()["expanded"], false); - let st = s.active().unwrap(); - assert!(st.revision == revision && st.layers_view_revision() > view, "the Layers view revision only: the Layers panel's rows follow it"); + let st = s.active_tracked().unwrap(); + assert!(st.revision == revision && st.revision() != view, "the tracked revision only: the Layers panel's rows follow it"); assert!(!expanded(&s, inner) && expanded(&s, outer)); assert_eq!(s.active().unwrap().history.entries().len(), undo_steps, "no history step"); assert_eq!(s.active().unwrap().saved_revision, s.active().unwrap().revision, "still clean"); diff --git a/crates/engine/src/cmd/history_cmds.rs b/crates/engine/src/cmd/history_cmds.rs index 30cacb8a5d..0a5c2f186a 100644 --- a/crates/engine/src/cmd/history_cmds.rs +++ b/crates/engine/src/cmd/history_cmds.rs @@ -24,7 +24,7 @@ use crate::image_cmds::reidentify_copied_layers; use crate::{EngineError, Result, Session}; /// A History panel snapshot: the document as it was when taken, and the layers it targeted. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct Snapshot { pub id: u64, pub name: String, diff --git a/crates/engine/src/cmd/mask_view_cmds.rs b/crates/engine/src/cmd/mask_view_cmds.rs index 14778a98bf..4c23aa71b9 100644 --- a/crates/engine/src/cmd/mask_view_cmds.rs +++ b/crates/engine/src/cmd/mask_view_cmds.rs @@ -24,7 +24,7 @@ pub const ID: &str = "view.layerMask"; pub const OVERLAY_ID: &str = "layer.toggleMaskOverlay"; /// How a shown layer mask is drawn. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum MaskViewMode { /// The mask alone, as a grayscale image (⌥-click). @@ -34,7 +34,7 @@ pub enum MaskViewMode { } /// Which layer's mask is shown, and how. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, craft_ui_macros::PlainData)] pub struct LayerMaskView { pub layer: LayerId, pub mode: MaskViewMode, @@ -71,11 +71,16 @@ pub fn current(st: &DocState) -> Option { /// Drop a mask view that no longer applies (another layer became active, the layer or its mask /// was deleted, undo). pub(crate) fn fix(st: &mut DocState) { - if st.channel_view.layer_mask.is_some() && current(st).is_none() { + if stale(st) { st.channel_view.layer_mask = None; } } +/// Whether `st` keeps a layer-mask view that no longer applies ([`fix`] ends it). +pub(crate) fn stale(st: &DocState) -> bool { + st.channel_view.layer_mask.is_some() && current(st).is_none() +} + fn mode_name(v: Option) -> &'static str { match v.map(|v| v.mode) { None => "off", diff --git a/crates/engine/src/cmd/slice_cmds.rs b/crates/engine/src/cmd/slice_cmds.rs index 9826c2322a..33360ce68e 100644 --- a/crates/engine/src/cmd/slice_cmds.rs +++ b/crates/engine/src/cmd/slice_cmds.rs @@ -92,9 +92,10 @@ fn layer_slice_rect(doc: &Document, s: &Slice) -> Option { } /// Re-fits layer-based slices of the active document to their layers; drops slices whose layer -/// was deleted (as Photoshop does). Not a history step. +/// was deleted (as Photoshop does). Not a history step. Runs after every command, so it reads through `active` and +/// borrows the document to change only when a slice moves: the borrow moves its `Tracked` revision. pub(crate) fn refresh(s: &mut Session) { - let Some(st) = s.active_mut() else { return }; + let Some(st) = s.active() else { return }; if !st.doc.slices.list.iter().any(|sl| sl.origin == SliceOrigin::Layer) { return; } @@ -109,6 +110,7 @@ pub(crate) fn refresh(s: &mut Session) { if changes.is_empty() { return; } + let Some(st) = s.active_mut() else { return }; let doc = Arc::make_mut(st.doc_mut()); for (id, r) in changes { match r { diff --git a/crates/engine/src/cmd/symmetry_cmds.rs b/crates/engine/src/cmd/symmetry_cmds.rs index 4b93d797de..97781c3ff3 100644 --- a/crates/engine/src/cmd/symmetry_cmds.rs +++ b/crates/engine/src/cmd/symmetry_cmds.rs @@ -14,14 +14,14 @@ use crate::{EngineError, Result, Session, commands::CommandSpec}; const MAX_SEGMENTS: usize = 1024; const SAMPLES_PER_CURVE: usize = 12; -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub struct SymmetryAxis { pub source: String, pub segments: Vec<[[f64; 2]; 2]>, } /// Per-document painting tool state, never stored in the document's paths or pixels. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui_macros::PlainData)] pub enum PaintingSymmetry { Path(SymmetryAxis), Preset(PresetSymmetry), diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index c8b9a2eea1..8ed80a30df 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -1,21 +1,21 @@ use super::{Arc, Document, History, LayerId, LayerTarget, channel_cmds, float_cmds, history_cmds, layer_multi_cmds, symmetry_cmds}; -/// Per-document editing state. -#[derive(Clone, Debug)] +/// Per-document editing state. Plain data: the session holds each in a `Tracked`, whose revision moves with every +/// write, view state included. +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct DocState { inputs: DocStateInputs, - selected_cache: std::sync::OnceLock>, + selected_cache: SelectedOrder, pub history: History, /// Anchor of range selection (the last plainly or command-clicked layer). pub layer_anchor: Option, pub path: Option, /// An Affinity document (or its preview) must not acquire the native source as its Save path. pub source_read_only: bool, - /// Increments on every change; UIs re-render when it moves. + /// Counts the edit steps: save state ([`Self::is_dirty`]) and damage measure from it. Views key on the `Tracked` + /// revision the session holds the state in, which also moves with view state. pub revision: u64, pub saved_revision: u64, - /// Native save cache shared with this document's workers, released with the editing state. - pub pcraft_cache: photocraft_io::PcraftExportCache, /// How much of `revision` came from view-only changes (channel eyes, targeting): pixel caches can ignore those. pub view_revision: u64, /// Area changed since revision [`DocState::damage_from`] (None = assume everything changed): @@ -38,8 +38,6 @@ pub struct DocState { /// Layers panel: layers whose effects list is collapsed under their row (the fx triangle; /// view state, not history). Effects lists start open. pub fx_collapsed: Vec, - /// See [`DocState::layers_view_revision`]. - layers_view_revision: u64, /// ⌥-click on a layer's eye (`layer.showOnly`): the layer shown alone and every layer's /// visibility before, so the next ⌥-click restores it (view state, not history). pub show_only: Option<(LayerId, Vec<(LayerId, bool)>)>, @@ -76,7 +74,7 @@ pub struct DocState { } /// Read-only document and layer selection inputs. Mutations go through `DocState` methods. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct DocStateInputs { /// The current document. pub doc: Arc, @@ -86,6 +84,15 @@ pub struct DocStateInputs { pub selected_layers: Vec, } +/// The selected layers in document order ([`DocState::selected_layers`]), built on the first read after a write. +#[derive(Clone, Debug, Default)] +struct SelectedOrder(std::sync::OnceLock>); + +// The order is a pure function of the document and the raw selection: every write to either goes through a +// `DocState` method that drops it (`doc_mut`, `set_active_layer`, `selection_mut`), and readers get the same answer +// whether it is built or not. So a shared reference can't change what readers see. +impl craft_tracked::PlainData for SelectedOrder {} + impl std::ops::Deref for DocState { type Target = DocStateInputs; fn deref(&self) -> &Self::Target { @@ -124,14 +131,13 @@ impl DocState { let first = history_cmds::Snapshot { id: 0, name: doc.name.clone(), doc: doc.clone(), layers: target }; Self { inputs: DocStateInputs { doc, active_layer, selected_layers: active_layer.into_iter().collect() }, - selected_cache: std::sync::OnceLock::new(), + selected_cache: SelectedOrder::default(), history, layer_anchor: active_layer, path, source_read_only: false, revision: 1, saved_revision: 1, - pcraft_cache: Default::default(), view_revision: 0, last_damage: None, damage_span: None, @@ -141,7 +147,6 @@ impl DocState { isolated_layers: Vec::new(), symmetry: None, fx_collapsed: Vec::new(), - layers_view_revision: 0, show_only: None, floating: None, color_samplers: Vec::new(), @@ -179,7 +184,7 @@ impl DocState { } /// Mutable access invalidates the ordered selection, including on document replacement. pub fn doc_mut(&mut self) -> &mut Arc { - self.selected_cache.take(); + self.selected_cache.0.take(); &mut self.inputs.doc } /// The active layer, if any. @@ -189,7 +194,7 @@ impl DocState { /// Set the active layer and invalidate the held ordered selection. pub fn set_active_layer(&mut self, active: Option) { if self.inputs.active_layer != active { - self.selected_cache.take(); + self.selected_cache.0.take(); self.inputs.active_layer = active; } } @@ -199,14 +204,14 @@ impl DocState { } /// Mutate the raw selection, invalidating the held ordered selection before access. pub fn selection_mut(&mut self) -> &mut Vec { - self.selected_cache.take(); + self.selected_cache.0.take(); &mut self.inputs.selected_layers } /// Selected layers in bottom-to-top document order, including the active layer. /// Missing IDs are skipped; if the active layer is not in the raw selection, only it is used. /// The first read after a mutation builds the held slice; later reads reuse it. pub fn selected_layers(&self) -> &[LayerId] { - self.selected_cache.get_or_init(|| selected_in(&self.inputs.doc, self.inputs.active_layer, &self.inputs.selected_layers)) + self.selected_cache.0.get_or_init(|| selected_in(&self.inputs.doc, self.inputs.active_layer, &self.inputs.selected_layers)) } pub fn is_layer_selected(&self, id: LayerId) -> bool { self.active_layer == Some(id) || (self.active_layer.is_some_and(|a| self.selected_layers.contains(&a)) && self.selected_layers.contains(&id)) @@ -314,15 +319,6 @@ impl DocState { self.last_damage = Some(photocraft_geom::Rect::EMPTY); self.record_damage(); } - /// Moves when an effects list or a group in the Layers panel opens or closes. That is view - /// state, not an edit, so [`DocState::revision`] stays; the Layers panel's rows key on this. - pub fn layers_view_revision(&self) -> u64 { - self.layers_view_revision - } - /// Count an effects list or group opened or closed (see [`Self::layers_view_revision`]). - pub(crate) fn note_disclosure_change(&mut self) { - self.layers_view_revision += 1; - } /// Move to the next revision for a view-only change (channel eyes, a history state deleted, /// Layers panel isolation): readers keyed on the revision follow it, pixel caches ignore it /// through `view_revision`, and no pixels need drawing again. `keep_clean` as for @@ -471,19 +467,14 @@ impl Default for ToolState { /// copies them (Paste Layer Style puts them all on each target). #[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct CopiedStyle { - #[plain_data(assume = "document effects: plain values")] pub effects: photocraft_doc::Effects, - #[plain_data(assume = "an enum")] pub blend: photocraft_color::BlendMode, pub fill: f32, - #[plain_data(assume = "document blending options: plain values")] pub advanced: photocraft_doc::AdvancedBlending, - #[plain_data(assume = "document blend ranges: plain values")] pub blend_if: photocraft_doc::BlendIf, pub excluded_channels: u32, /// The colour mode it was copied in: Blend If's channel ranges and the channel restrictions /// only carry over to a document in the same mode. - #[plain_data(assume = "an enum")] pub mode: photocraft_color::ColorMode, } diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index 6d94aae181..42d0a402df 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -1874,7 +1874,6 @@ impl Session { } else if !st.fx_collapsed.contains(&layer_id) { st.fx_collapsed.push(layer_id); } - st.note_disclosure_change(); } self.after_command(id, params, spec.journal, automation, Some(nested_from), pre_selected.as_deref(), &record_before); Ok(Started::Done(v)) @@ -1898,7 +1897,11 @@ impl Session { /// keeps the damage it reported. Debug and test builds also count a whole-document redraw of /// a small change ([`Session::whole_redraws`]). pub(crate) fn note_command_damage(&mut self, id: &str, before: &Arc, from: u64) { - let Some(st) = self.active_mut().filter(|st| st.doc.id == before.id && st.revision > from) else { return }; + // Read first: the borrow moves the document's `Tracked` revision, and this runs after every command. + if !self.active().is_some_and(|st| st.doc.id == before.id && st.revision > from) { + return; + } + let Some(st) = self.active_mut() else { return }; if st.revision - from > 1 { st.last_damage = crate::layer_multi_cmds::step_damage(before, &st.doc); st.damage_span = Some((from, st.revision)); @@ -1931,10 +1934,13 @@ impl Session { /// stroke on a layer with a Gradient Overlay reports the stroke, but the gradient is laid out /// again over the whole grown layer (#4053). `before` is the active document before. fn add_relayout_damage(&mut self, before: &Arc) { - let Some(st) = self.active_mut().filter(|st| st.doc.id == before.id && !Arc::ptr_eq(&st.doc, before)) else { return }; + // Read first: the borrow moves the document's `Tracked` revision, and this runs after every command. + let Some(st) = self.active().filter(|st| st.doc.id == before.id && !Arc::ptr_eq(&st.doc, before)) else { return }; let Some(d) = st.last_damage.filter(|d| !d.is_empty()) else { return }; let extra = photocraft_compose::relayout_damage(before, &st.doc); - if !extra.is_empty() { + if !extra.is_empty() + && let Some(st) = self.active_mut() + { st.last_damage = Some(d.union(&extra)); st.record_damage(); } @@ -1971,9 +1977,12 @@ impl Session { pre_selected: Option<&[LayerId]>, before: &crate::actions_record::Before, ) { - // A layer-mask view ends when another layer becomes active (#196). - if let Some(st) = self.active_mut() { - crate::mask_view_cmds::fix(st); + // A layer-mask view ends when another layer becomes active (#196). Borrowed to change only when it does: the + // borrow moves the document's `Tracked` revision, and this runs after every command. + if self.active().is_some_and(crate::mask_view_cmds::stale) + && let Some(st) = self.active_mut() + { + st.channel_view.layer_mask = None; } crate::edit_menu_cmds::after_command(self, id, ¶ms); crate::automate_cmds::after_command(self, id); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 29d4327180..71ceb89ee6 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -202,7 +202,10 @@ pub(crate) fn active_layer_of(s: &Session) -> std::result::Result<&photocraft_do #[derive(Default)] pub struct Session { - docs: Vec, + /// The open documents, each in a `Tracked`: views key on its revision, which every write moves. + docs: Vec>, + /// Each open document's native save cache, shared with its save workers; dropped when the document closes. + pcraft_caches: std::collections::HashMap, documents_generation: u64, /// Override Open belongs only to one Batch scratch session, never to caller preferences. pub(crate) batch_open: Option, @@ -313,8 +316,8 @@ pub struct Session { /// The stamps being taken on a worker thread ([`Session::start_link_scan`]). pub link_scan: Option, /// Each open document's linked smart objects' files that were not there when last looked at - /// ([`Session::missing_links`]). - link_missing: std::collections::HashSet<(u64, String)>, + /// ([`Session::missing_links`]). Written only when the set changes, so its revision says when the list did. + link_missing: craft_tracked::Tracked>, /// Select Subject's last result, reused while the pixels are unchanged (#2865). subject_cache: smartselect_cmds::SubjectCache, /// Object Selection's Object Finder results (#4087), shared by the hover preview and the diff --git a/crates/engine/src/link_watch.rs b/crates/engine/src/link_watch.rs index 893933fd80..7cbb1cff09 100644 --- a/crates/engine/src/link_watch.rs +++ b/crates/engine/src/link_watch.rs @@ -99,7 +99,9 @@ impl Session { // Nothing to look at: no links, or none that is followed. None of them is listed as // missing either, so a link added back isn't shown missing before its first look. if files.iter().all(|(_, file, _)| file.is_none()) { - self.link_missing.retain(|(d, _)| *d != doc); + if self.link_missing.iter().any(|(d, _)| *d == doc) { + self.link_missing.retain(|(d, _)| *d != doc); + } return; } let slot: LinkScan = Arc::default(); @@ -121,20 +123,27 @@ impl Session { self.link_missing.iter().filter(|(d, _)| *d == doc).map(|(_, p)| p.clone()).collect() } + /// Moves whenever the missing linked files ([`Self::missing_links`]) of any open document change. + pub fn missing_links_revision(&self) -> craft_tracked::Revision { + self.link_missing.revision() + } + /// Remember which of document `doc`'s files in `now` were not there, and forget the files of /// closed documents. The web app has no files to look at, so it lists none. fn note_missing_links(&mut self, doc: u64, now: &[(String, Vec, Option)]) { let open: HashSet = self.documents().iter().map(|d| d.doc.id.0).collect(); - self.link_missing.retain(|(d, _)| *d != doc && open.contains(d)); - if cfg!(target_arch = "wasm32") { - return; - } - let document = self.active().and_then(|st| st.path.clone()); - for (path, _, stamp) in now { - if stamp.is_none() && crate::doc_path::resolve_in(path, document.as_deref().map(std::path::Path::new)).is_ok() { - self.link_missing.insert((doc, path.clone())); + let mut missing: HashSet<(u64, String)> = self.link_missing.iter().filter(|(d, _)| *d != doc && open.contains(d)).cloned().collect(); + if !cfg!(target_arch = "wasm32") { + let document = self.active().and_then(|st| st.path.clone()); + for (path, _, stamp) in now { + if stamp.is_none() && crate::doc_path::resolve_in(path, document.as_deref().map(std::path::Path::new)).is_ok() { + missing.insert((doc, path.clone())); + } } } + if *self.link_missing != missing { + *self.link_missing = missing; + } } /// Apply a finished look (`None` while there is none, or it is still running). diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 23a0a97042..bd1e3e41ed 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -1970,11 +1970,15 @@ impl Session { let bytes = self.prefs().performance.history_cap_bytes(); let budget = self.prefs().performance.effect_cache_budget_bytes(); let non_linear = self.prefs().history_options.allow_non_linear_history; + // A document is written only when its limits change: every write moves its `Tracked` revision. for st in &mut self.docs { - st.history.max_states = n; - st.history.max_bytes = bytes; - st.history.non_linear = non_linear; - st.trim_history(); + let history = &st.history; + if (history.max_states, history.max_bytes, history.non_linear) != (n, bytes, non_linear) { + st.history.max_states = n; + st.history.max_bytes = bytes; + st.history.non_linear = non_linear; + st.trim_history(); + } } photocraft_compose::set_effect_cache_budget(budget); crate::transform_cmds::set_budget(u64::from(self.prefs().performance.effective_memory_usage_mb()) << 20); diff --git a/crates/engine/src/presets.rs b/crates/engine/src/presets.rs index 4e2bb9e926..ad40728e5b 100644 --- a/crates/engine/src/presets.rs +++ b/crates/engine/src/presets.rs @@ -94,7 +94,6 @@ pub struct PresetState { #[plain_data(assume = "craft-color-ui swatch groups: plain values and strings")] pub swatches: Vec, /// The user contour library of the Layer Style dialog (`layer.layerStyle.contours.*`). - #[plain_data(assume = "document contours: plain numbers")] pub contours: Vec, } diff --git a/crates/engine/src/presets/clone_source.rs b/crates/engine/src/presets/clone_source.rs index d7193364bc..2ba36df475 100644 --- a/crates/engine/src/presets/clone_source.rs +++ b/crates/engine/src/presets/clone_source.rs @@ -432,7 +432,7 @@ fn set(s: &mut Session, p: &Value) -> Result { return Err(bad(CMD, "document requires a source point")); } let index = value.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(CMD, "document must be an open document index"))?; - Some(s.documents().get(index).ok_or_else(|| bad(CMD, "the source document is not open"))?) + Some(&**s.documents().get(index).ok_or_else(|| bad(CMD, "the source document is not open"))?) } }; let (document, active_layer) = (doc.map(|st| st.doc.id), doc.and_then(|st| st.active_layer).map(|id| id.0)); diff --git a/crates/engine/src/presets/shapes.rs b/crates/engine/src/presets/shapes.rs index 42237eb3e0..7b4c99edb3 100644 --- a/crates/engine/src/presets/shapes.rs +++ b/crates/engine/src/presets/shapes.rs @@ -28,7 +28,6 @@ pub const CUSTOM_GROUP: &str = "Custom Shapes"; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct ShapePreset { pub name: String, - #[plain_data(assume = "a document path: plain geometry")] pub path: Path, /// An imported library's opaque identity; old and locally drawn presets need none. #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/crates/engine/src/presets/styles.rs b/crates/engine/src/presets/styles.rs index 2523faa11e..e2ae82e52d 100644 --- a/crates/engine/src/presets/styles.rs +++ b/crates/engine/src/presets/styles.rs @@ -19,11 +19,9 @@ use crate::{EngineError, Result, Session}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct StylePreset { pub name: String, - #[plain_data(assume = "document effects: plain values")] pub effects: Vec, /// Blending options saved with the style ("Include Layer Blending Options"). #[serde(default)] - #[plain_data(assume = "an enum")] pub blend: Option, #[serde(default)] pub fill_opacity: Option, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 2c173d63b9..fb78e9c494 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -23,7 +23,7 @@ impl Session { Self::default() } - pub fn documents(&self) -> &[DocState] { + pub fn documents(&self) -> &[craft_tracked::Tracked] { &self.docs } @@ -37,11 +37,28 @@ impl Session { } pub fn active(&self) -> Option<&DocState> { + self.active_tracked().map(|st| &**st) + } + + /// The active document as the session tracks it, for views that key on its revision. + pub fn active_tracked(&self) -> Option<&craft_tracked::Tracked> { self.active.and_then(|i| self.docs.get(i)) } + /// The active document to change: the borrow moves its `Tracked` revision, so a caller that may write nothing + /// reads through [`Self::active`] first. pub fn active_mut(&mut self) -> Option<&mut DocState> { - self.active.and_then(|i| self.docs.get_mut(i)) + self.active.and_then(|i| self.docs.get_mut(i)).map(|st| &mut **st) + } + + /// The open document with this id as the session tracks it, active or not. + pub fn tracked(&self, id: photocraft_doc::DocId) -> Option<&craft_tracked::Tracked> { + self.docs.iter().find(|d| d.doc.id == id) + } + + /// The native save cache of the open document `id`, which its save workers share. + pub fn pcraft_cache(&self, id: photocraft_doc::DocId) -> Option<&photocraft_io::PcraftExportCache> { + self.pcraft_caches.get(&id) } /// Completes a successful save of the active document: the file becomes its path and names it, and its revision is @@ -56,7 +73,7 @@ impl Session { /// The open document with this id, active or not. pub fn document_mut(&mut self, id: photocraft_doc::DocId) -> Option<&mut DocState> { - self.docs.iter_mut().find(|d| d.doc.id == id) + self.docs.iter_mut().find(|d| d.doc.id == id).map(|st| &mut **st) } /// Monotonic active-document generation. It changes when a different document becomes @@ -208,7 +225,8 @@ impl Session { if !self.prefs.get().history_options.automatically_create_first_snapshot { st.snapshots_mut().clear(); } - self.docs.push(st); + self.pcraft_caches.insert(st.doc.id, Default::default()); + self.docs.push(craft_tracked::Tracked::new(st)); self.documents_generation = self.documents_generation.wrapping_add(1); let i = self.docs.len() - 1; self.active = Some(i); @@ -246,10 +264,13 @@ impl Session { self.subject_cache.forget_doc(id); self.object_finder.forget_doc(id); self.presets.clone.forget_doc(id); - self.link_missing.retain(|(d, _)| *d != id.0); + if self.link_missing.iter().any(|(d, _)| *d == id.0) { + self.link_missing.retain(|(d, _)| *d != id.0); + } self.link_scan = None; } - let d = self.docs.remove(index); + let d = self.docs.remove(index).into_inner(); + self.pcraft_caches.remove(&d.doc.id); self.documents_generation = self.documents_generation.wrapping_add(1); self.open_document_order.retain(|&id| id != d.doc.id); self.active = if self.docs.is_empty() { diff --git a/crates/geom/Cargo.toml b/crates/geom/Cargo.toml index 2c3541d35d..faae7413d0 100644 --- a/crates/geom/Cargo.toml +++ b/crates/geom/Cargo.toml @@ -9,3 +9,6 @@ workspace = true [dependencies] serde = { workspace = true } +# Plain data (the engine holds documents in a `Tracked`): the marker and its derive, without the UI. +craft-tracked = { workspace = true } +craft-ui-macros = { workspace = true } diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 44a078dd36..50919c0eb5 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -12,7 +12,7 @@ pub mod warp; /// Edge length of a raster tile in pixels. pub const TILE_SIZE: i32 = 256; -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Size { pub width: u32, pub height: u32, @@ -31,7 +31,7 @@ impl Size { } /// Integer rectangle, half-open: `[x0, x1) × [y0, y1)`. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Rect { pub x0: i32, pub y0: i32, @@ -116,7 +116,7 @@ impl Rect { } /// Index of a tile in the infinite tile grid. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct TileCoord { pub tx: i32, pub ty: i32, @@ -136,7 +136,7 @@ impl TileCoord { } } -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Point { pub x: f64, pub y: f64, @@ -149,7 +149,7 @@ impl Point { } /// 2D affine transform `[a c e; b d f; 0 0 1]` (column vectors). -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct Affine { pub m: [f64; 6], } diff --git a/crates/geom/src/warp.rs b/crates/geom/src/warp.rs index e6bf592606..8a9b9a82e0 100644 --- a/crates/geom/src/warp.rs +++ b/crates/geom/src/warp.rs @@ -20,7 +20,7 @@ use std::f64::consts::PI; use serde::{Deserialize, Serialize}; /// Warp style: none, a custom mesh, or one of Photoshop's presets (menu order). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub enum WarpStyle { #[default] @@ -161,7 +161,7 @@ impl WarpStyle { } /// A preset style prepared for one box: its control grid and the box it bends. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, craft_ui_macros::PlainData)] pub struct StyleWarp { /// The 4 × 4 Bezier control grid in box units (0..1, y down), row-major. grid: Grid, @@ -529,7 +529,7 @@ const BERN_INV: [[f64; 4]; 4] = [[1.0, 0.0, 0.0, 0.0], [-5.0 / 6.0, 3.0, -1.5, 1 /// `us`/`vs` are the patch boundaries in the box's normalised coordinates (`0..=1`, increasing, /// first 0 and last 1). Control points are a `(3·(us.len()-1)+1) × (3·(vs.len()-1)+1)` grid in /// row-major order, in output (document) coordinates; neighbouring patches share their edge row. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] pub struct BezierMesh { pub us: Vec, pub vs: Vec, @@ -1029,7 +1029,7 @@ fn move_control_points(points: &mut [[f64; 2]], nx: usize, ny: usize, cols: usiz } /// A complete warp: what Photoshop's `warp` descriptor stores, plus the custom mesh. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "camelCase")] pub struct Warp { pub style: WarpStyle, diff --git a/crates/ops/Cargo.toml b/crates/ops/Cargo.toml index 7a15a111aa..6f19afa707 100644 --- a/crates/ops/Cargo.toml +++ b/crates/ops/Cargo.toml @@ -9,3 +9,6 @@ workspace = true [dependencies] photocraft-doc = { workspace = true } +# Plain data (the engine holds documents in a `Tracked`): the marker and its derive, without the UI. +craft-tracked = { workspace = true } +craft-ui-macros = { workspace = true } diff --git a/crates/ops/src/lib.rs b/crates/ops/src/lib.rs index 0e647b1490..f9a10d53e5 100644 --- a/crates/ops/src/lib.rs +++ b/crates/ops/src/lib.rs @@ -22,13 +22,13 @@ mod tiles; /// bring them back with the state's document, as the reference app does. Selecting layers is not /// a step of its own, so the session updates the current state's target with /// [`History::set_current_layers`] just before recording the next step (#1356). -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, craft_ui_macros::PlainData)] pub struct LayerTarget { pub active: Option, pub selected: Vec, } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct HistoryState { pub label: String, pub doc: Arc, @@ -42,13 +42,13 @@ pub struct HistoryState { } /// The context in which a selected action row must remain available after it is folded away. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub enum ActionBrushSource { Current(HistoryState), Cleared(HistoryState), } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] pub struct History { /// Past states; the last one is the state *before* the current document. undo: VecDeque, @@ -96,7 +96,7 @@ pub struct History { static NEXT_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); /// What [`History::rollback`] needs to take the most recent [`History::record`] back. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] struct LastRecord { visibility_capture_before: Option>>, /// The document it replaced (the state a rollback makes current again). @@ -113,7 +113,7 @@ struct LastRecord { /// The undo and redo states [`History::clear_states`] removed, and the History Brush source set /// before it. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui_macros::PlainData)] struct Cleared { undo: VecDeque, redo: Vec, diff --git a/crates/ops/src/tiles.rs b/crates/ops/src/tiles.rs index 64da14929e..8eab8dce95 100644 --- a/crates/ops/src/tiles.rs +++ b/crates/ops/src/tiles.rs @@ -5,7 +5,7 @@ use photocraft_doc::{Document, LayerContent, SmartSource, Surface}; use std::collections::{HashMap, HashSet}; use std::sync::Arc; -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, Default, craft_ui_macros::PlainData)] pub(crate) struct Tiles { refs: HashMap, bytes: u128, diff --git a/crates/paint/src/symmetry.rs b/crates/paint/src/symmetry.rs index 6adf8a382f..54c9c5f3b9 100644 --- a/crates/paint/src/symmetry.rs +++ b/crates/paint/src/symmetry.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; pub const MAX_COORDINATE: f64 = 1_000_000.0; -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)] #[serde(rename_all = "lowercase")] pub enum SymmetryMode { Vertical, @@ -29,7 +29,7 @@ impl SymmetryMode { } } -#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, craft_ui_macros::PlainData)] pub struct PresetSymmetry { pub mode: SymmetryMode, pub center: [f64; 2], diff --git a/crates/raster/Cargo.toml b/crates/raster/Cargo.toml index f319dcee81..7a8bf6ea11 100644 --- a/crates/raster/Cargo.toml +++ b/crates/raster/Cargo.toml @@ -11,6 +11,9 @@ workspace = true photocraft-geom = { workspace = true } photocraft-color = { workspace = true } serde = { workspace = true } +# Plain data (the engine holds documents in a `Tracked`): the marker and its derive, without the UI. +craft-tracked = { workspace = true } +craft-ui-macros = { workspace = true } crc32fast = "1" lz4_flex = { version = "0.11", default-features = false, features = ["std", "safe-encode", "safe-decode"] } diff --git a/crates/raster/src/interrupt.rs b/crates/raster/src/interrupt.rs index 2a5521331b..745fc6607b 100644 --- a/crates/raster/src/interrupt.rs +++ b/crates/raster/src/interrupt.rs @@ -65,7 +65,7 @@ impl<'a> Interrupt<'a> { } /// Returned by an operation that stopped because its [`Interrupt`] was cancelled. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui_macros::PlainData)] pub struct Cancelled; impl std::fmt::Display for Cancelled { diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 59474e6ab5..68940781de 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -35,7 +35,7 @@ pub fn stored_tiles_bytes(tiles: u64, fmt: &PixelFormat) -> u64 { } /// A checked surface allocation could not be represented or reserved. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, craft_ui_macros::PlainData)] pub enum AllocationError { ScratchRead(String), SizeOverflow, @@ -63,7 +63,7 @@ impl fmt::Display for AllocationError { impl std::error::Error for AllocationError {} /// Failure to prepare an interruptible row write. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, craft_ui_macros::PlainData)] pub enum RowWriteError { Allocation(AllocationError), Cancelled(Cancelled), @@ -226,6 +226,13 @@ impl Tile { } } +// The cell moves the bytes between memory and the scratch disk behind `&self`, and the pixels stay the same: an +// eviction compresses and drops them under the write lock, a reload restores the same bytes, and only `&mut` writes +// (`bytes_mut`) change them. The exception is a scratch read error: `bytes` then returns a zero placeholder, and a +// later successful reload returns the real pixels, both through `&self`. Both transitions move +// `spill::read_error_generation`, so views that show document pixels also key on it. +impl craft_tracked::PlainData for Tile {} + impl Clone for Tile { fn clone(&self) -> Self { match self.try_bytes() { @@ -317,6 +324,10 @@ pub struct Surface { tiles: BTreeMap>, } +// `generation` names the current pixels: a read assigns the number once, and every write goes through `&mut` +// (`note_mutation`), which clears it. A shared reference can't change the pixels or which number names them. +impl craft_tracked::PlainData for Surface {} + impl Clone for Surface { fn clone(&self) -> Self { // Read first so the clone and the original share one number: they hold the same pixels. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index a7ae862e55..4e61d8a721 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -71,7 +71,6 @@ impl PhotocraftApp { texture_serials: Default::default(), menu_model: None, toolbar_slots: Default::default(), - layers_tree: None, dock_model: Default::default(), move_preview: None, move_hover: None, diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 651c6023d8..4716314e04 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -542,7 +542,7 @@ impl PhotocraftApp { settings.webp_lossless = e.webp_lossless.unwrap_or(settings.webp_lossless); settings.webp_quality = e.webp_quality.map(|q| q.min(100)); settings.document_path = st.path.as_deref().map(std::path::PathBuf::from); - settings.pcraft_cache = Some(st.pcraft_cache.clone()); + settings.pcraft_cache = self.session.pcraft_cache(st.doc.id).cloned(); } settings } diff --git a/crates/ui-egui/src/app/targets.rs b/crates/ui-egui/src/app/targets.rs index e642ddb7dd..51fac77346 100644 --- a/crates/ui-egui/src/app/targets.rs +++ b/crates/ui-egui/src/app/targets.rs @@ -129,10 +129,14 @@ impl PhotocraftApp { /// menu commands and the engine all edit the mask. A view change only: no command, no step. pub(crate) fn target_mask_over_colour_rows(&mut self) { use photocraft_engine::channel_cmds::ChannelTarget; - let Some(st) = self.session.active_mut() else { return }; + let Some(st) = self.session.active() else { return }; let raster_with_mask = st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.mask.is_some() && matches!(l.content, photocraft_doc::LayerContent::Raster(_))); - if matches!(st.channel_view.target, ChannelTarget::Color(_)) && photocraft_engine::mask_view_cmds::current(st).is_none() && raster_with_mask { + if matches!(st.channel_view.target, ChannelTarget::Color(_)) + && photocraft_engine::mask_view_cmds::current(st).is_none() + && raster_with_mask + && let Some(st) = self.session.active_mut() + { let v = &mut st.channel_view; v.target = ChannelTarget::LayerMask; v.selected_colors.clear(); @@ -144,7 +148,10 @@ impl PhotocraftApp { /// active layer (a shape layer's path is its content, not a mask). Targeting a mask or the /// pixels brings back that target's foreground/background pair, as in Photoshop (#2166). pub(crate) fn sync_mask_targets(&mut self) { - if let Some(st) = self.session.active_mut() { + // Read through `active`, and borrow the document to change only for the one write below: the borrow moves its + // `Tracked` revision, and this runs after every command and control request. + let mut untarget_mask = false; + if let Some(st) = self.session.active() { use photocraft_engine::channel_cmds::ChannelTarget; let channel = st.channel_view.target; match photocraft_engine::mask_view_cmds::current(st) { @@ -177,13 +184,14 @@ impl PhotocraftApp { if self.ui.mask_target && st.active_layer.and_then(|id| st.doc.layer(id)).is_none_or(|l| l.mask.is_none()) { self.ui.mask_target = false; } - if !self.ui.mask_target && st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::LayerMask { - st.channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Composite; - } + untarget_mask = !self.ui.mask_target && st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::LayerMask; if !self.ui.mask_target || self.ui.properties_layer != st.active_layer.map(|l| l.0) { self.ui.properties_layer = None; } } + if untarget_mask && let Some(st) = self.session.active_mut() { + st.channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Composite; + } if self.ui.filter_mask_target.is_some() && !self.filter_mask_targeted() { self.ui.filter_mask_target = None; } diff --git a/crates/ui-egui/src/doc_revision_trials.rs b/crates/ui-egui/src/doc_revision_trials.rs index 8dd27fd436..2ffdbaf5d5 100644 --- a/crates/ui-egui/src/doc_revision_trials.rs +++ b/crates/ui-egui/src/doc_revision_trials.rs @@ -4,6 +4,7 @@ use craft::layers::ui::thumbs::{LayerThumb, ThumbContents}; use craft::ui::primitives::textures::{ThumbRequest, ThumbSource}; +use craft::ui::runtime::measure::last_frame_derived_builds; use egui_kittest::Harness; use photocraft_doc::{Fill, Layer, LayerContent, LayerId, PixelFormat}; use photocraft_engine::Session; @@ -96,8 +97,8 @@ fn thumbnail_revisions_follow_only_their_own_layer() { ); } -/// The Layers panel walks its rows again only when their revision moves: a rename and both disclosure toggles (a -/// layer's effects list, a group) move it, idle frames don't. +/// The Layers panel's model is built again only when what its rows show changed: a rename and both disclosure toggles +/// (a layer's effects list, a group) build it once, idle frames don't. #[test] fn layers_rows_follow_renames_and_both_toggles() { let mut s = Session::new(); @@ -112,19 +113,20 @@ fn layers_rows_follow_renames_and_both_toggles() { }) .unwrap(); let mut h = harness(s); - // The panel's model, which the app holds across passes and replaces only when what the rows show changed. - let revision = |h: &H| h.state().layers_tree.as_ref().map(|model| model.revision()); + let builds = |h: &H| { + let id = crate::panels::layers_tree::model_id(); + last_frame_derived_builds(&h.ctx).iter().filter(|(built, _)| *built == id).map(|(_, n)| n).sum::() + }; h.run_steps(2); - let start = revision(&h); - assert!(start.is_some()); - h.run_steps(10); - assert_eq!(revision(&h), start, "idle frames keep the rows"); + for frame in 0..10 { + h.run_steps(1); + assert_eq!(builds(&h), 0, "idle frame {frame} keeps the rows"); + } let moves = |h: &mut H, command: &str, params: serde_json::Value| { - let before = revision(h); h.state_mut().run(command, params).unwrap(); - h.run_steps(2); - assert_ne!(revision(h), before, "{command} moves the rows' revision"); + h.run_steps(1); + assert_eq!(builds(h), 1, "{command} builds the rows once"); }; moves(&mut h, "layer.renameLayer", json!({"layer": a.0, "name": "Renamed"})); moves(&mut h, "layer.setEffectsExpanded", json!({"layer": a.0, "expanded": false})); diff --git a/crates/ui-egui/src/doc_tracked_trials.rs b/crates/ui-egui/src/doc_tracked_trials.rs new file mode 100644 index 0000000000..6ac5519f59 --- /dev/null +++ b/crates/ui-egui/src/doc_tracked_trials.rs @@ -0,0 +1,133 @@ +//! Count trials for the documents the session holds in a `Tracked` (#15709): a job that applies to a document in the +//! background moves only that document's revision and builds nothing keyed on the active one, an idle frame and a +//! preference write that keeps the history limits move no document's revision, and a view-only write that leaves the +//! edit revision alone still moves the tracked one. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use craft::ui::runtime::measure::last_frame_derived_builds; +use egui_kittest::Harness; +use photocraft_engine::channel_cmds::ChannelTarget; +use photocraft_engine::jobs::Started; +use serde_json::json; + +use crate::PhotocraftApp; + +type H = Harness<'static, Box>; + +/// The app with two new documents, A (index 0) and B (index 1), each with a pixel layer, B active, settled. +fn harness() -> H { + let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut s = photocraft_engine::Session::new(); + for _ in 0..2 { + s.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + } + PhotocraftApp::with_context(cc.egui_ctx.clone(), s, crate::Services::default()) + }); + h.run_steps(8); + h +} + +/// How many times the last frame built the value derived under `id`. +fn builds(h: &H, id: egui::Id) -> u32 { + last_frame_derived_builds(&h.ctx).iter().filter(|(built, _)| *built == id).map(|(_, n)| n).sum() +} + +/// Every open document's `Tracked` revision. +fn revisions(h: &H) -> Vec { + h.state().session.documents().iter().map(|st| st.revision()).collect() +} + +#[test] +fn a_job_on_another_document_builds_nothing_keyed_on_the_active_one() { + let mut h = harness(); + // A filter job on A, held until B is the active document. + h.state_mut().session.set_active(0); + let gate = Arc::new(AtomicBool::new(false)); + let open = Arc::clone(&gate); + let started = h + .state_mut() + .session + .start_job( + "filter.blur.gaussianBlur", + json!({"radius": 2}), + "Deferred Blur", + true, + move |job| { + while !open.load(Ordering::Relaxed) { + job.check()?; + std::thread::sleep(std::time::Duration::from_millis(1)); + } + Ok(()) + }, + |s, ()| { + s.edit("Deferred Blur", |doc, active| { + let layer = active.ok_or_else(|| photocraft_engine::EngineError::Other("no active layer".into()))?; + let surface = doc.layer_mut(layer).and_then(|l| l.surface_mut()).ok_or(photocraft_engine::EngineError::NoLayer(layer))?; + surface.fill_rect(photocraft_geom::Rect::new(0, 0, 1, 1), &[0.4, 0.3, 0.2, 1.0]); + Ok(()) + })?; + Ok(json!({})) + }, + ) + .unwrap(); + let Started::Job(job) = started else { panic!("the job ran inline") }; + h.state_mut().session.set_active(1); + h.run_steps(4); + + let before = revisions(&h); + gate.store(true, Ordering::Relaxed); + h.state_mut().session.wait_job(job).unwrap(); + h.run_steps(1); + let after = revisions(&h); + assert_ne!(after[0], before[0], "the job's apply moves A's revision"); + assert_eq!(after[1], before[1], "and leaves B's"); + assert_eq!(builds(&h, crate::panels::layers_tree::model_id()), 0, "B's Layers model builds nothing"); + + h.state_mut().session.set_active(0); + h.run_steps(1); + assert_eq!(builds(&h, crate::panels::layers_tree::model_id()), 1, "switching to A builds its Layers model once"); +} + +#[test] +fn an_idle_frame_moves_no_documents_revision() { + let mut h = harness(); + h.state_mut().run("window.toggle.history", json!({"show": true})).unwrap(); + h.state_mut().run("window.toggle.navigator", json!({"show": true})).unwrap(); + h.run_steps(8); + let settled = revisions(&h); + for frame in 0..10 { + h.run_steps(1); + assert_eq!(revisions(&h), settled, "idle frame {frame} moves no document's revision"); + } +} + +#[test] +fn a_preference_write_that_keeps_the_history_limits_moves_no_documents_revision() { + let mut h = harness(); + let settled = revisions(&h); + let on = h.state().session.prefs().script_events.enabled; + h.state_mut().session.edit_prefs(|prefs| prefs.script_events.enabled = !on); + assert_eq!(revisions(&h), settled, "a preference write that keeps the history limits moves no document's revision"); + let states = h.state().session.prefs().performance.history_states; + h.state_mut().session.edit_prefs(|prefs| prefs.performance.history_states = states + 1); + assert!(revisions(&h).iter().zip(&settled).all(|(now, was)| now != was), "a new history limit moves every document's revision"); +} + +#[test] +fn targeting_a_mask_over_colour_rows_moves_only_the_tracked_revision() { + let mut h = harness(); + h.state_mut().run("layer.layerMask.revealAll", json!({})).unwrap(); + h.state_mut().session.active_mut().unwrap().channel_view.target = ChannelTarget::Color(0); + h.run_steps(4); + let st = h.state().session.active_tracked().unwrap(); + let (edits, tracked) = (st.revision, st.revision()); + h.state_mut().target_mask_over_colour_rows(); + let st = h.state().session.active_tracked().unwrap(); + assert_eq!(st.channel_view.target, ChannelTarget::LayerMask, "the mask is the target"); + assert_eq!(st.revision, edits, "a view change is no edit step"); + assert_ne!(st.revision(), tracked, "but it moves the tracked revision views key on"); +} diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index 9518515318..dc64309867 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -132,7 +132,7 @@ fn lock(cache: &Mutex) -> MutexGuard<'_, ThumbnailCache> { /// The recent files' thumbnail source for one pass: the open documents (their live pictures), the shared version /// cache and whether the window gained focus this pass. pub(crate) struct RecentThumbs<'a> { - docs: &'a [photocraft_engine::DocState], + docs: &'a [craft::ui::contract::Tracked], cache: &'a Mutex, ctx: egui::Context, focus_gained: bool, @@ -154,7 +154,7 @@ pub(crate) fn thumbnails(ctx: &egui::Context) -> Thumbnails { impl RecentThumbs<'_> { /// The open document whose path is `path`. fn open_doc(&self, path: &str) -> Option<&photocraft_engine::DocState> { - self.docs.iter().find(|d| d.path.as_deref().is_some_and(|p| paths_match(p, path))) + self.docs.iter().find(|d| d.path.as_deref().is_some_and(|p| paths_match(p, path))).map(|st| &**st) } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 75691ac40b..9fe533aa0f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -358,8 +358,6 @@ pub struct PhotocraftApp { pub(crate) menu_model: Option, /// The toolbar's slots for the stored layout (`tool_commands::ToolbarSlots`). pub(crate) toolbar_slots: panels::tool_commands::ToolbarSlots, - /// The Layers panel's model, held across passes (`layers_tree::PhotoLayers::held`). - pub(crate) layers_tree: Option>, /// The dock's spec model and kept panels (`panel_docking::DockModel`). pub(crate) dock_model: panels::panel_docking::DockModel, /// Move tool drag shown live (`move_ui`). @@ -952,6 +950,8 @@ mod chrome_settle_trials; #[cfg(test)] mod doc_revision_trials; #[cfg(test)] +mod doc_tracked_trials; +#[cfg(test)] mod drag_settle_trials; #[cfg(test)] mod layer_thumb_bounds_tests; diff --git a/crates/ui-egui/src/menus/facts.rs b/crates/ui-egui/src/menus/facts.rs index 87dde76f10..5798c602c3 100644 --- a/crates/ui-egui/src/menus/facts.rs +++ b/crates/ui-egui/src/menus/facts.rs @@ -8,6 +8,7 @@ use std::sync::Arc; use craft::ui::contract::{MemoProps, Revision, Tracked}; use photocraft_doc::DocId; +use photocraft_engine::DocState; use crate::PhotocraftApp; @@ -31,10 +32,9 @@ struct Documents<'a> { generation: u64, active_generation: u64, active_index: Option, - /// The active document and its revision, which moves with every change to it: its content, layers, selection, - /// history, mode and mask state, which most rules read. - #[memo_props(hash = "a plain model id")] - active: Option<(DocId, u64)>, + /// The active document, by its `Tracked` revision, which moves with every change to it: its content, layers, + /// selection, history, mode, mask and view state, which most rules read. + active: Option<&'a Tracked>, /// A running job greys the commands that would change its document. jobs: (bool, Option), /// Smart Objects › Edit Contents' parent: whether the active document is a smart object's contents. @@ -131,7 +131,7 @@ impl<'a> MenuFacts<'a> { generation: s.documents_generation(), active_generation: s.active_generation(), active_index: s.active_index(), - active: active.map(|d| (d.doc.id, d.revision)), + active: s.active_tracked(), jobs: (s.has_jobs(), s.active_job().map(|job| job.id.0)), smart_child: active.is_some_and(|d| s.smart_links.iter().any(|link| link.child == d.doc.id)), fade: s.edit_state.fade.as_ref().map(|fade| (fade.doc, fade.revision)), diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index b75b5acc25..0cb7ef055c 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -19,16 +19,15 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { use craft::ui::contract::Bind; use craft::ui::primitives::textures::{ThumbnailOptions, Thumbnails}; - use super::layers_tree::{self, PhotoLayers, PhotoThumbs}; + use super::layers_tree::{self, PhotoThumbs}; // A Move-way pick of a layer opens its groups only when the Move option says so (#11381). let reveal = crate::layer_reveal::take(app); let ctx = ui.ctx().clone(); // Thumbnail Contents is the clip preference alone, so the panel reads it each pass. app.ui.layers_settings.options.thumbnail_contents = crate::layers_panel_ui::thumbnail_contents(app); - // Taken out of the app for the pass; a move keeps its revision. - let held = app.layers_tree.take(); - let Some(st) = app.session.active() else { + let Some(st) = app.session.active_tracked() else { + layers_tree::no_model(app); let _ = Notice::new(Tone::Neutral, tl!("No document")).layout(NoticeLayout::Centred).show(ui); return; }; @@ -39,14 +38,15 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let mut filter = app.ui.layer_filter.clone(); let before = filter.clone(); let picked = crate::smart_ui::selected(&app.smart_filter_picks, &st.doc, st.active_layer); - let tree = PhotoLayers::new(app, st, &filter, foreign, picked).held(held); + let model = layers_tree::model(app, st, &filter, foreign, picked); + let Some(tree) = &*model else { return }; let thumbs = Thumbnails::>::in_context(&ctx, "photocraft-layer-thumbs", ThumbnailOptions::new()); let source = PhotoThumbs::new(app, &st.doc); - let mut panel = LayersPanel::new(&tree) + let mut panel = LayersPanel::new(tree) .settings(settings) .thumbnails(&thumbs, &source) .filter(Bind::bound(&mut filter)) - .row_menu(|target| layers_tree::row_menu(app, &tree, target)) + .row_menu(|target| layers_tree::row_menu(app, tree, target)) .document(st.doc.id); if let Some((id, groups)) = reveal { panel = panel.reveal(id, groups); @@ -61,7 +61,6 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { panel = panel.start_rename(id); } let out = panel.show(ui); - app.layers_tree = Some(tree); app.find_layers_focus = false; app.layers_rename = None; if filter != before { diff --git a/crates/ui-egui/src/panels/layers_tree.rs b/crates/ui-egui/src/panels/layers_tree.rs index 7753d129a1..2524a2a54a 100644 --- a/crates/ui-egui/src/panels/layers_tree.rs +++ b/crates/ui-egui/src/panels/layers_tree.rs @@ -13,7 +13,7 @@ use craft::layers::ui::tree::{ SubRows, ThumbBadge, }; use craft::theme::LabelColor as UiLabel; -use craft::ui::contract::{Entry, PlainData, ReorderMove, Tracked}; +use craft::ui::contract::{Entry, MemoProps, PlainData, ReorderMove, Tracked}; use craft::ui::list::ThumbSize; use craft::ui::patterns::blend_keys::{BlendKeyEntry, blend_entries}; use craft::ui::primitives::textures::{Revision, ThumbRender, ThumbRequest, ThumbSource, thumb_image}; @@ -79,12 +79,92 @@ pub(crate) fn listed_filter(app: &PhotocraftApp) -> Option { + doc: &'a Tracked, + filter: &'a LayerFilter, + #[memo_props(hash = "craft-layers part: a fieldless enum")] + target: LayerPart, + mask_target: bool, + vector_mask_target: bool, + link_enabled: bool, + #[memo_props(hash = "a plain model id")] + hovered: Option, + working_text: Option, + /// The missing linked files of the open documents (the Smart Object filter). + missing: craft::ui::contract::Revision, + foreign_drag: bool, + picked: Option, +} + +/// The id the Layers panel's model is derived under. +pub(crate) fn model_id() -> egui::Id { + egui::Id::unique("photocraft-layers-model") +} + +/// The value the Layers panel's model is derived as: `None` while no document is open. +pub(crate) type Model = Option>; + +/// The Layers panel's model of the active document `st`, derived from what it is built from: built again only when +/// one of [`LayersFacts`] changed. A new build is a new `Tracked`, so the panel's key moves exactly then. It is always +/// `Some`. +pub(crate) fn model( + app: &PhotocraftApp, + st: &Tracked, + filter: &LayerFilter, + foreign_drag: bool, + picked: Option, +) -> Arc { + let facts = LayersFacts { + doc: st, + filter, + target: edit_target(app, st), + mask_target: app.ui.mask_target, + vector_mask_target: app.ui.vector_mask_target, + link_enabled: app.session.is_enabled("layer.linkLayers"), + hovered: app.canvas_hover_layer, + working_text: working_text(app), + missing: app.session.missing_links_revision(), + foreign_drag, + picked, + }; + craft::ui::runtime::derived::derived(app.ctx(), model_id(), &facts, || Some(Tracked::new(PhotoLayers::new(app, st, filter, foreign_drag, picked)))) +} + +/// Derives the model as `None` while no document is open: the kept model, which holds the document it showed, is +/// replaced in the pass that finds the document gone. +pub(crate) fn no_model(app: &PhotocraftApp) { + let _ = craft::ui::runtime::derived::derived(app.ctx(), model_id(), &(), || Model::None); +} + +/// A Type Mask session's working text, which the panel never lists. +fn working_text(app: &PhotocraftApp) -> Option { + app.ui.text_edit.as_ref().filter(|ed| ed.mask).map(|ed| ed.layer) +} + +/// The part of the active layer edits go to ([`LayerTree::selection`]). +fn edit_target(app: &PhotocraftApp, st: &DocState) -> LayerPart { + let ui = &app.ui; + match st.active_layer.and_then(|id| st.doc.layer(id)) { + Some(l) if l.frame.is_some() => match crate::frame_tool::target(app, l) { + crate::frame_tool::Target::Frame => LayerPart::FrameShape, + crate::frame_tool::Target::Content => LayerPart::FrameContent, + crate::frame_tool::Target::Both => LayerPart::Pixels, + }, + Some(l) if ui.filter_mask_target == Some(l.id.0) && app.filter_mask_targeted() => LayerPart::FilterMask, + Some(l) if ui.vector_mask_target && l.vector_mask.is_some() => LayerPart::VectorMask, + Some(l) if ui.mask_target && l.mask.is_some() => LayerPart::LayerMask, + _ => LayerPart::Pixels, + } +} + /// The Layers panel's model of the active document: the document, the parts of its state the rows show and what the /// app decides for them (the edit target, the hovered layer, the filter's answers). Plain data: the panel holds it in a -/// `Tracked`, and the host writes a new one only when what it holds changed ([`PhotoLayers::held`]). +/// `Tracked`, derived from [`LayersFacts`] ([`model`]). #[derive(Clone, PlainData)] pub(crate) struct PhotoLayers { - #[plain_data(assume = "the document is replaced, never changed in place, while an Arc to it is shared")] doc: Arc, active_layer: Option, selected: Vec, @@ -110,39 +190,15 @@ pub(crate) struct PhotoLayers { picked: Option, } -/// Equal when they show the same: the same document value (one `Arc`) and the same state. -impl PartialEq for PhotoLayers { - fn eq(&self, other: &Self) -> bool { - Arc::ptr_eq(&self.doc, &other.doc) - && (&self.active_layer, &self.selected, &self.isolated_layers, &self.fx_collapsed, &self.filter, self.target) - == (&other.active_layer, &other.selected, &other.isolated_layers, &other.fx_collapsed, &other.filter, other.target) - && (self.mask_target, self.vector_mask_target, self.link_enabled, self.hovered, self.working_text, self.foreign_drag, self.picked) - == (other.mask_target, other.vector_mask_target, other.link_enabled, other.hovered, other.working_text, other.foreign_drag, other.picked) - && self.empty == other.empty - && self.missing == other.missing - } -} - impl PhotoLayers { pub(crate) fn new(app: &PhotocraftApp, st: &DocState, filter: &LayerFilter, foreign_drag: bool, picked: Option) -> Self { - let working_text = app.ui.text_edit.as_ref().filter(|ed| ed.mask).map(|ed| ed.layer); let empty = match (filter.by, filter.attribute) { (FilterBy::Attribute, LayerAttribute::Empty | LayerAttribute::NotEmpty) => crate::layer_filter_ui::attribute::empty_layers(app), _ => None, }; let missing = if filter.by == FilterBy::SmartObject { app.session.missing_links() } else { HashSet::new() }; let ui = &app.ui; - let target = match st.active_layer.and_then(|id| st.doc.layer(id)) { - Some(l) if l.frame.is_some() => match crate::frame_tool::target(app, l) { - crate::frame_tool::Target::Frame => LayerPart::FrameShape, - crate::frame_tool::Target::Content => LayerPart::FrameContent, - crate::frame_tool::Target::Both => LayerPart::Pixels, - }, - Some(l) if ui.filter_mask_target == Some(l.id.0) && app.filter_mask_targeted() => LayerPart::FilterMask, - Some(l) if ui.vector_mask_target && l.vector_mask.is_some() => LayerPart::VectorMask, - Some(l) if ui.mask_target && l.mask.is_some() => LayerPart::LayerMask, - _ => LayerPart::Pixels, - }; + let target = edit_target(app, st); Self { doc: Arc::clone(&st.doc), active_layer: st.active_layer, @@ -155,7 +211,7 @@ impl PhotoLayers { vector_mask_target: ui.vector_mask_target, link_enabled: app.session.is_enabled("layer.linkLayers"), hovered: app.canvas_hover_layer, - working_text, + working_text: working_text(app), empty, missing, foreign_drag, @@ -163,15 +219,6 @@ impl PhotoLayers { } } - /// `self` in `held`: the held value while it is equal, else a new `Tracked`, so the panel's key moves only when - /// what it shows changed. - pub(crate) fn held(self, held: Option>) -> Tracked { - match held { - Some(held) if *held == self => held, - _ => Tracked::new(self), - } - } - fn doc(&self) -> &Document { &self.doc } diff --git a/crates/ui-egui/src/panels/preset_panels/clone_source.rs b/crates/ui-egui/src/panels/preset_panels/clone_source.rs index 5fb26441eb..20a7732aef 100644 --- a/crates/ui-egui/src/panels/preset_panels/clone_source.rs +++ b/crates/ui-egui/src/panels/preset_panels/clone_source.rs @@ -73,7 +73,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } // The document the source was set in (the active one for slots set before slots remembered it). let source_doc = match slot.document { - Some(id) => slot.open_document().and_then(|_| app.session.documents().iter().find(|d| d.doc.id == id)), + Some(id) => slot.open_document().and_then(|_| app.session.documents().iter().find(|d| d.doc.id == id).map(|st| &**st)), None => app.session.active(), }; let source_line = match (slot.source, source_doc) { diff --git a/crates/ui-egui/src/save_identity_tests.rs b/crates/ui-egui/src/save_identity_tests.rs index 4551cbe061..3ae0b08a8e 100644 --- a/crates/ui-egui/src/save_identity_tests.rs +++ b/crates/ui-egui/src/save_identity_tests.rs @@ -40,7 +40,7 @@ fn identity(app: &PhotocraftApp) -> (String, Option, u64, u64) { fn save_settings_share_only_the_open_documents_native_cache() { let mut app = app(); let first = app.save_settings().io_options().pcraft_cache.unwrap(); - assert_eq!(first, app.session.active().unwrap().pcraft_cache); + assert_eq!(Some(&first), app.session.pcraft_cache(app.session.active().unwrap().doc.id)); assert_eq!(first, app.save_settings().io_options().pcraft_cache.unwrap()); app.run("file.new", json!({"width": 2, "height": 2})).unwrap(); assert_ne!(first, app.save_settings().io_options().pcraft_cache.unwrap()); diff --git a/crates/ui-egui/src/tools/type_tool/defaults.rs b/crates/ui-egui/src/tools/type_tool/defaults.rs index 12b004d2c2..3f8717dc3b 100644 --- a/crates/ui-egui/src/tools/type_tool/defaults.rs +++ b/crates/ui-egui/src/tools/type_tool/defaults.rs @@ -26,7 +26,7 @@ pub(crate) fn target_text(app: &PhotocraftApp) -> Option<&TextLayer> { /// document where the same layer id may name another layer, else the active one. pub(super) fn target_doc(app: &PhotocraftApp) -> Option<&photocraft_engine::DocState> { match &app.ui.text_edit { - Some(ed) => app.session.documents().get(edit_home(app, ed)?), + Some(ed) => app.session.documents().get(edit_home(app, ed)?).map(|st| &**st), None => app.session.active(), } } From 12a5837e88cb1e63ec8309ef5a46b9eae8f42d18 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 14:35:00 +0000 Subject: [PATCH 36/38] Command-state sources are derived values (#15709) --- crates/ui-egui/src/app/framework.rs | 129 ++++++++------- .../src/app/framework/catalog_tests.rs | 74 +-------- crates/ui-egui/src/command_state_trials.rs | 147 ++++++++++++++++++ crates/ui-egui/src/doc_tracked_trials.rs | 47 +++++- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus/facts.rs | 100 ++++++++---- crates/ui-egui/src/menus/workspace_ui.rs | 5 + crates/ui-egui/src/panels/actions/menu.rs | 25 +++ crates/ui-egui/src/panels/brush_panel.rs | 5 + crates/ui-egui/src/panels/channels_panel.rs | 13 ++ crates/ui-egui/src/panels/histogram_panel.rs | 7 + crates/ui-egui/src/panels/history_menu_ui.rs | 15 ++ crates/ui-egui/src/panels/layers_panel_ui.rs | 21 +++ .../src/panels/options_bar/selection.rs | 5 + crates/ui-egui/src/panels/preset_browser.rs | 8 + crates/ui-egui/src/panels/registry.rs | 49 +++--- crates/ui-egui/src/panels/swatches_ui.rs | 5 + crates/ui-egui/src/tools/align_bar.rs | 5 + crates/ui-egui/src/tools/artboard_tool.rs | 7 +- crates/ui-egui/src/tools/slice_ui.rs | 19 ++- 20 files changed, 487 insertions(+), 201 deletions(-) create mode 100644 crates/ui-egui/src/command_state_trials.rs diff --git a/crates/ui-egui/src/app/framework.rs b/crates/ui-egui/src/app/framework.rs index 020f2b5575..2dcba65340 100644 --- a/crates/ui-egui/src/app/framework.rs +++ b/crates/ui-egui/src/app/framework.rs @@ -19,7 +19,7 @@ use craft::i18n::Direction; use craft::keymap::Overrides; use craft::theme::{AppDefaults, AppSizes, ComponentSet, ModeChoice, Size, SuiteChoice, ThemeId, ThemePair, resolve_sized}; use craft::theme_store::{SelectionChange, SuiteClient}; -use craft::ui::contract::Tracked; +use craft::ui::contract::{MemoProps, Tracked}; use craft::ui::dialog::DialogHost; use craft::ui::fonts::UiFonts; use craft::ui::runtime::commands::{AppCatalog, CommandInput, CommandRef, CommandSet as _, CommandState, CommandStates, Fired, NavCommand}; @@ -546,97 +546,106 @@ impl Framework { } } +/// One source's command states. +pub(crate) type SourceStates = Vec<(CommandRef, CommandState)>; + +/// The id a command source's states are derived under. +pub(crate) fn states_id(source: &'static str) -> egui::Id { + egui::Id::unique(("photocraft-states", source)) +} + +/// `build`'s states for `source`, derived from `facts`: the kept `Arc` while the facts are unchanged, else a new build. +/// The facts can hold only checked inputs, but nothing checks that they hold everything `build` reads: a read they +/// leave out keeps stale states, which the held-equals-fresh trial catches. +pub(crate) fn derived_states(app: &PhotocraftApp, source: &'static str, facts: &K, build: impl FnOnce() -> SourceStates) -> Arc { + craft::ui::runtime::derived::derived(app.ctx(), states_id(source), facts, build) +} + +/// The states of a source that has no command states: one shared empty list, whatever the source's name. +pub(crate) fn no_states(app: &PhotocraftApp, _name: &'static str) -> Arc { + derived_states(app, "none", &(), Vec::new) +} + +/// A source's states for the coming frame, derived under the source's name ([`states_id`]) from what they read. +pub(crate) type StatesOf = fn(&PhotocraftApp, &'static str) -> Arc; + /// One user of the framework's command sets: the states its commands show and the runner of the /// ones it fires. pub(crate) struct CommandSource { - /// The states of the source's commands for the coming frame. - states: fn(&PhotocraftApp) -> Vec<(CommandRef, CommandState)>, - /// What `states` reads, for a source whose every input is a plain value or a revision that moves exactly when - /// the data changes: the states are computed again only when the key changes. `None`: computed every frame, - /// because what the source reads has no such revision yet. - key: Option StatesKey>, + /// The name the source's states are derived under. + pub(crate) name: &'static str, + /// The states of the source's commands. + pub(crate) states: StatesOf, /// Runs `command` when it is this source's; whether it was. run: fn(&mut PhotocraftApp, &egui::Context, &CommandRef) -> bool, } -/// Every command source, in the order [`run_command`] tries them. The theme has no entry: it has -/// no command state, and its picks run through `menus::invoke`. +/// Every command source besides the panels' ([`crate::panels::registry::PANELS`], one source each), in the order +/// [`run_command`] tries them after the panels. The theme has no entry: it has no command state, and its picks run +/// through `menus::invoke`. pub(crate) const COMMAND_SOURCES: &[CommandSource] = &[ - CommandSource { states: crate::panels::registry::states, key: None, run: crate::panels::registry::run_fired }, - CommandSource { states: tool_states, key: Some(tool_states_key), run: run_tool }, - CommandSource { states: crate::workspace_ui::states, key: None, run: crate::workspace_ui::run_fired }, - CommandSource { states: crate::slice_ui::command_states, key: Some(crate::slice_ui::command_states_key), run: crate::slice_ui::run_fired }, - CommandSource { states: crate::align_bar::command_states, key: None, run: crate::align_bar::run_fired }, - CommandSource { states: crate::artboard_tool::command_states, key: Some(crate::artboard_tool::command_states_key), run: crate::artboard_tool::run_fired }, + CommandSource { name: "tool", states: tool_states, run: run_tool }, + CommandSource { name: "workspace", states: crate::workspace_ui::source_states, run: crate::workspace_ui::run_fired }, + CommandSource { name: "slice", states: crate::slice_ui::source_states, run: crate::slice_ui::run_fired }, + CommandSource { name: "align", states: crate::align_bar::source_states, run: crate::align_bar::run_fired }, + CommandSource { name: "artboard", states: crate::artboard_tool::source_states, run: crate::artboard_tool::run_fired }, // Space+F: the pasteboard colour keys of the held Hand. - CommandSource { states: |_| Vec::new(), key: Some(|_| StatesKey::default()), run: crate::canvas_tool_menu::run_canvas_color }, + CommandSource { name: "canvasColor", states: no_states, run: crate::canvas_tool_menu::run_canvas_color }, // The options bar's engine-command buttons: their commands run through `shortcuts::handle`. - CommandSource { states: crate::panels::options_bar::selection::command_states, key: None, run: |_, _, _| false }, + CommandSource { name: "selection", states: crate::panels::options_bar::selection::source_states, run: |_, _, _| false }, ]; -/// The key of a [`CommandSource`]'s states: the plain values and exact revisions they are computed from, so equal -/// keys mean equal states. -pub(crate) type StatesKey = [u64; 4]; +/// Every source by its name, with its states: the command sources, then the panels, each under its panel id. A later +/// source's state wins for a command two sources name. +pub(crate) fn sources() -> impl Iterator { + let panels = crate::panels::registry::PANELS.iter().map(|panel| (panel.id, panel.states)); + COMMAND_SOURCES.iter().map(|source| (source.name, source.states)).chain(panels) +} -/// The states each [`CommandSource`] last computed, by its place in [`COMMAND_SOURCES`], with their key, and the one -/// list of all of them the runtime reads. +/// Every source's states, in [`sources`]' order. +fn source_states(app: &PhotocraftApp) -> impl Iterator> + '_ { + sources().map(move |(name, states)| states(app, name)) +} + +/// The states each source last gave, in [`source_states`]' order, and the one list of all of them the runtime reads. #[derive(Default)] pub(crate) struct HeldStates { - kept: Vec>, + kept: Vec>, /// Every source's states, written only when one source's list changes: the runtime reads them again only when /// the revision moves. pub(crate) states: Tracked, - /// How many times each source computed its states, for the count trials. - #[cfg(test)] - pub(crate) runs: Vec, -} - -/// One source's states and the key they were computed at (`None` for a source without a key). -#[derive(Clone)] -struct KeptStates { - key: Option, - states: Vec<(CommandRef, CommandState)>, } /// The tool commands: the current tool's row is checked. -fn tool_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { +fn build_tool_states(app: &PhotocraftApp) -> SourceStates { Tool::ALL.iter().map(|&tool| (CommandRef::from(crate::panels::tool_commands::command_of(tool)), CommandState::new().checked(app.ui.tool == tool))).collect() } -/// What [`tool_states`] reads: the tool. -fn tool_states_key(app: &PhotocraftApp) -> StatesKey { - [app.ui.tool as u64, 0, 0, 0] +/// [`build_tool_states`], derived from the tool. +fn tool_states(app: &PhotocraftApp, name: &'static str) -> Arc { + derived_states(app, name, &(app.ui.tool as u64), || build_tool_states(app)) } -/// Brings the held states up to date for the coming frame. A keyed source runs only when its key changed since it last -/// ran; a source without a key runs every frame. The held list is written only when a source's states differ from the -/// ones it last gave. +/// Brings the held states up to date for the coming frame. A source whose states are the `Arc` it last gave costs a +/// pointer compare; the held list is written only when a source's states differ by value from the ones it last gave. fn command_states(app: &PhotocraftApp, held: &mut HeldStates) { - held.kept.resize(COMMAND_SOURCES.len(), None); - #[cfg(test)] - held.runs.resize(COMMAND_SOURCES.len(), 0); let mut changed = false; - for (at, source) in COMMAND_SOURCES.iter().enumerate() { - let key = source.key.map(|key| key(app)); - if key.is_some() && held.kept[at].as_ref().is_some_and(|kept| kept.key == key) { - continue; - } - #[cfg(test)] - { - held.runs[at] += 1; - } - let states = (source.states)(app); - match &mut held.kept[at] { - Some(kept) if kept.states == states => kept.key = key, - slot => { - *slot = Some(KeptStates { key, states }); + for (at, states) in source_states(app).enumerate() { + match held.kept.get_mut(at) { + Some(kept) if Arc::ptr_eq(kept, &states) => {} + Some(kept) => { + changed |= **kept != *states; + *kept = states; + } + None => { + held.kept.push(states); changed = true; } } } if changed { let mut states = CommandStates::new(); - for (command, state) in held.kept.iter().flatten().flat_map(|kept| &kept.states) { + for (command, state) in held.kept.iter().flat_map(|kept| kept.iter()) { states.set(command.clone(), state.clone()); } *held.states = states; @@ -655,9 +664,9 @@ fn run_tool(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) true } -/// Runs `command` through the first source that owns it; whether one did. +/// Runs `command` through the first source that owns it, the panels first; whether one did. pub(crate) fn run_command(app: &mut PhotocraftApp, ctx: &egui::Context, command: &CommandRef) -> bool { - COMMAND_SOURCES.iter().any(|source| (source.run)(app, ctx, command)) + crate::panels::registry::run_fired(app, ctx, command) || COMMAND_SOURCES.iter().any(|source| (source.run)(app, ctx, command)) } impl PhotocraftApp { diff --git a/crates/ui-egui/src/app/framework/catalog_tests.rs b/crates/ui-egui/src/app/framework/catalog_tests.rs index 7c5ed7e939..7599ab9c1d 100644 --- a/crates/ui-egui/src/app/framework/catalog_tests.rs +++ b/crates/ui-egui/src/app/framework/catalog_tests.rs @@ -1,18 +1,12 @@ -//! Count trials: the command catalog, the keymap overrides and the keyed command states are built only when what -//! they read changes. +//! Count trials: the command catalog and the keymap overrides are built only when what they read changes. use craft::automation::actions::ActionStep; use serde_json::json; -use super::{COMMAND_SOURCES, PhotocraftApp}; +use super::PhotocraftApp; use crate::canvas::testing; use crate::state::Tool; -/// The places of the keyed sources in [`COMMAND_SOURCES`]. -const TOOL_SOURCE: usize = 1; -const SLICE_SOURCE: usize = 3; -const ARTBOARD_SOURCE: usize = 5; - fn app() -> Box { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); testing::frame(&mut app); @@ -24,22 +18,6 @@ fn builds(app: &PhotocraftApp) -> (usize, usize) { (app.framework.catalog_builds, app.framework.overrides_builds) } -/// How many times each keyed command source computed its states, by its place in [`COMMAND_SOURCES`]; `None` for a -/// source that computes them every frame. -fn keyed_runs(app: &PhotocraftApp) -> Vec> { - COMMAND_SOURCES.iter().zip(&app.framework.held_states.runs).map(|(source, &runs)| source.key.map(|_| runs)).collect() -} - -/// The revision of the states the runtime reads. -fn held_revision(app: &PhotocraftApp) -> craft::ui::contract::Revision { - app.framework.held_states.states.revision() -} - -/// The keyed sources that computed their states between `before` and `after`. -fn ran(before: &[Option], after: &[Option]) -> Vec { - before.iter().zip(after).enumerate().filter(|(_, (was, now))| was.is_some() && was != now).map(|(at, _)| at).collect() -} - fn frames(app: &mut PhotocraftApp, n: usize) { for _ in 0..n { testing::frame(app); @@ -91,51 +69,3 @@ fn the_catalog_is_built_only_when_its_inputs_change() { assert_eq!(builds(&app), (2, 3), "a step edit builds nothing"); assert_eq!(app.framework.keymap_inputs().1, generation + 1, "the catalog keeps its generation"); } - -#[test] -fn keyed_command_states_run_only_when_their_key_changes() { - let mut app = app(); - assert_eq!((COMMAND_SOURCES[TOOL_SOURCE].states)(&app).len(), Tool::ALL.len(), "TOOL_SOURCE names the tool commands"); - let before = keyed_runs(&app); - assert!(before.iter().flatten().all(|&runs| runs == 1), "the first frame computes every keyed source once"); - - let revision = held_revision(&app); - frames(&mut app, 100); - assert_eq!(keyed_runs(&app), before, "idle frames compute no keyed source"); - assert_eq!(held_revision(&app), revision, "idle frames write no states"); - - let other = if app.ui.tool == Tool::Brush { Tool::Move } else { Tool::Brush }; - crate::tool_memory::select(&mut app, other); - frames(&mut app, 2); - assert_ne!(held_revision(&app), revision, "a tool change writes the states"); - let revision = held_revision(&app); - frames(&mut app, 10); - assert_eq!(held_revision(&app), revision, "the frames after the tool change write no states"); - let after = keyed_runs(&app); - for (at, (was, now)) in before.iter().zip(&after).enumerate() { - let moved = usize::from(at == TOOL_SOURCE); - assert_eq!(now.map(|n| n - was.unwrap_or_default()), was.map(|_| moved), "source {at} after a tool change"); - } - - let before = keyed_runs(&app); - app.ui.artboard_tool.adding = true; - frames(&mut app, 2); - assert_eq!(ran(&before, &keyed_runs(&app)), [ARTBOARD_SOURCE], "the placing mode"); - - let before = keyed_runs(&app); - app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); - frames(&mut app, 2); - let after = keyed_runs(&app); - assert!(ran(&before, &after).contains(&SLICE_SOURCE) && ran(&before, &after).contains(&ARTBOARD_SOURCE), "a document opens"); - let has_doc = |app: &PhotocraftApp| (COMMAND_SOURCES[ARTBOARD_SOURCE].states)(app)[0].1.is_enabled(); - assert!(has_doc(&app)); - - let before = keyed_runs(&app); - app.ui.slices.selected = Some(1); - frames(&mut app, 2); - let selected = keyed_runs(&app); - assert_eq!(ran(&before, &selected), [SLICE_SOURCE], "the selected slice"); - app.session.file_menu.slices_locked = true; - frames(&mut app, 2); - assert_eq!(ran(&selected, &keyed_runs(&app)), [SLICE_SOURCE], "the slice lock"); -} diff --git a/crates/ui-egui/src/command_state_trials.rs b/crates/ui-egui/src/command_state_trials.rs new file mode 100644 index 0000000000..1d0c0d81f0 --- /dev/null +++ b/crates/ui-egui/src/command_state_trials.rs @@ -0,0 +1,147 @@ +//! Count trials for the command states the runtime reads (#15709): every source's states are a value derived from +//! what they read, so an idle frame builds none, an edit builds only the sources that read what it changed, and the +//! held states always equal a fresh build of every source. + +use craft::behavior::geometry::CropBox; +use craft::behavior::kurbo::Rect as DocRect; +use craft::ui::runtime::commands::{CommandRef, CommandStates}; +use craft::ui::runtime::measure::last_frame_derived_builds; +use egui_kittest::Harness; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::app::framework::{sources, states_id}; +use crate::state::Tool; + +type H = Harness<'static, Box>; + +/// The sources whose states follow the enable rules, which read the document, the session and the tool. +pub(crate) const RULES: [&str; 5] = ["align", "selection", "history", "layers", "channels"]; + +/// The app with one new document holding a pixel layer, settled. +fn harness() -> H { + harness_of(|s| { + s.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + }) +} + +/// The app with the session `open` makes, the Brush tool picked, settled. +fn harness_of(open: impl FnOnce(&mut photocraft_engine::Session) + 'static) -> H { + let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut s = photocraft_engine::Session::new(); + open(&mut s); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), s, crate::Services::default()); + app.ui.tool = Tool::Brush; + app + }); + h.run_steps(8); + h +} + +/// The sources the last frame built states for, in the framework's order. +fn built(h: &H) -> Vec<&'static str> { + let builds = last_frame_derived_builds(&h.ctx); + sources().map(|(name, _)| name).filter(|name| builds.iter().any(|(id, _)| *id == states_id(name))).collect() +} + +/// Runs one frame after `change` and checks which sources it built. +fn builds_only(h: &mut H, what: &str, change: impl FnOnce(&mut PhotocraftApp), expected: &[&str]) { + h.run_steps(2); + change(h.state_mut()); + h.run_steps(1); + let mut expected = expected.to_vec(); + expected.sort_by_key(|source| sources().position(|(name, _)| name == *source)); + assert_eq!(built(h), expected, "{what} builds only the sources that read it"); +} + +#[test] +fn an_idle_frame_builds_no_command_states() { + let mut h = harness(); + for frame in 0..10 { + h.run_steps(1); + assert_eq!(built(&h), Vec::<&str>::new(), "idle frame {frame} builds no source"); + } +} + +#[test] +fn an_edit_builds_only_the_sources_that_read_it() { + let mut h = harness(); + builds_only( + &mut h, + "the brush texture", + |app| { + let on = app.session.tools.brush.texture.enabled; + app.session.tools.brush.texture.enabled = !on; + }, + &["brushSettings"], + ); + builds_only(&mut h, "a tool", |app| crate::tool_memory::select(app, Tool::Hand), &[&["tool"][..], &RULES].concat()); + builds_only(&mut h, "the artboard placing mode", |app| app.ui.artboard_tool.adding = true, &["artboard"]); + builds_only(&mut h, "the selected slice", |app| app.ui.slices.selected = Some(1), &["slice"]); + // View › Lock Slices reads the lock, so the rule-holding sources build with the slice states. + builds_only(&mut h, "the slice lock", |app| app.session.file_menu.slices_locked = true, &[&["slice"][..], &RULES].concat()); + builds_only( + &mut h, + "a new layer", + |app| { + app.run("layer.new.layer", json!({})).unwrap(); + }, + &[&["slice"][..], &RULES].concat(), + ); +} + +#[test] +fn a_document_opening_builds_the_slice_and_artboard_states() { + let mut h = harness_of(|_| {}); + h.run_steps(2); + h.state_mut().run("file.new", json!({"width": 64, "height": 64})).unwrap(); + h.run_steps(1); + let built = built(&h); + assert!(built.contains(&"slice") && built.contains(&"artboard"), "a document opens: {built:?}"); + let add_new = CommandRef::from(craft::draw::ui::artboard::ArtboardCommand::AddNew); + let artboard = h.state().framework.held_states.states.get(&add_new).cloned(); + assert!(artboard.is_some_and(|state| state.is_enabled()), "Add New Artboard is on with a document"); +} + +/// Checks that every held state is the one its source builds afresh: the sources are asked again through a new context, +/// whose derived store is empty, so each builds from the app's state as it is now. +fn held_is_fresh(h: &mut H, step: &str) { + h.run_steps(2); + let app = h.state_mut(); + let fresh = egui::Context::default(); + PhotocraftApp::setup_context(&fresh, Default::default()); + let own = std::mem::replace(&mut app.ctx, fresh); + let built: Vec<_> = sources().map(|(name, states)| (name, states(app, name))).collect(); + app.ctx = own; + let mut held = (*app.framework.held_states.states).clone(); + for (name, states) in built { + for (command, state) in states.iter() { + assert!(held.remove(command).as_ref() == Some(state), "after {step}, the {name} state of {command:?} is a fresh build"); + } + } + assert!(held == CommandStates::new(), "after {step}, every held state has a source"); +} + +#[test] +fn the_held_command_states_equal_a_fresh_build_after_each_step() { + let mut h = harness(); + held_is_fresh(&mut h, "settling"); + crate::tool_memory::select(h.state_mut(), Tool::Move); + held_is_fresh(&mut h, "a tool"); + h.state_mut().session.tools.brush.texture.enabled = true; + held_is_fresh(&mut h, "the brush texture"); + h.state_mut().run("layer.new.layer", json!({})).unwrap(); + held_is_fresh(&mut h, "a new layer"); + h.state_mut().run("layer.layerMask.revealAll", json!({})).unwrap(); + h.state_mut().ui.mask_target = true; + held_is_fresh(&mut h, "a mask target"); + crate::workspace_ui::save(h.state_mut(), "Trial").unwrap(); + held_is_fresh(&mut h, "a new workspace"); + crate::tool_memory::select(h.state_mut(), Tool::Crop); + h.run_steps(2); + h.state_mut().canvas_tools.crop.tool.crop_to(CropBox::new(DocRect::new(10.0, 10.0, 100.0, 60.0), 0.0)); + held_is_fresh(&mut h, "a pending crop"); + assert!(crate::crop_ui::pending(h.state()), "the crop is pending"); +} diff --git a/crates/ui-egui/src/doc_tracked_trials.rs b/crates/ui-egui/src/doc_tracked_trials.rs index 6ac5519f59..9e18d08c79 100644 --- a/crates/ui-egui/src/doc_tracked_trials.rs +++ b/crates/ui-egui/src/doc_tracked_trials.rs @@ -1,7 +1,7 @@ //! Count trials for the documents the session holds in a `Tracked` (#15709): a job that applies to a document in the //! background moves only that document's revision and builds nothing keyed on the active one, an idle frame and a //! preference write that keeps the history limits move no document's revision, and a view-only write that leaves the -//! edit revision alone still moves the tracked one. +//! edit revision alone still moves the tracked one and rebuilds what shows it. use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; @@ -13,6 +13,7 @@ use photocraft_engine::jobs::Started; use serde_json::json; use crate::PhotocraftApp; +use crate::app::framework::states_id; type H = Harness<'static, Box>; @@ -31,11 +32,29 @@ fn harness() -> H { h } +/// How many times `builds` built the value derived under `id`. +fn count(builds: &[(egui::Id, u32)], id: egui::Id) -> u32 { + builds.iter().filter(|(built, _)| *built == id).map(|(_, n)| n).sum() +} + /// How many times the last frame built the value derived under `id`. fn builds(h: &H, id: egui::Id) -> u32 { - last_frame_derived_builds(&h.ctx).iter().filter(|(built, _)| *built == id).map(|(_, n)| n).sum() + count(&last_frame_derived_builds(&h.ctx), id) } +/// Runs `frames` frames and gives every build they made, frame after frame. +fn builds_over(h: &mut H, frames: usize) -> Vec<(egui::Id, u32)> { + let mut all = Vec::new(); + for _ in 0..frames { + h.run_steps(1); + all.extend(last_frame_derived_builds(&h.ctx)); + } + all +} + +/// The command sources that hold the active document. +const DOCUMENT_SOURCES: [&str; 6] = ["slice", "align", "selection", "history", "layers", "channels"]; + /// Every open document's `Tracked` revision. fn revisions(h: &H) -> Vec { h.state().session.documents().iter().map(|st| st.revision()).collect() @@ -81,15 +100,31 @@ fn a_job_on_another_document_builds_nothing_keyed_on_the_active_one() { let before = revisions(&h); gate.store(true, Ordering::Relaxed); h.state_mut().session.wait_job(job).unwrap(); - h.run_steps(1); + // Builds are summed over a few frames, so one a frame late counts too. + let job_frames = builds_over(&mut h, 4); let after = revisions(&h); assert_ne!(after[0], before[0], "the job's apply moves A's revision"); assert_eq!(after[1], before[1], "and leaves B's"); - assert_eq!(builds(&h, crate::panels::layers_tree::model_id()), 0, "B's Layers model builds nothing"); + assert_eq!(count(&job_frames, crate::panels::layers_tree::model_id()), 0, "B's Layers model builds nothing"); + assert_eq!(count(&job_frames, states_id("slice")), 0, "B's slice states build nothing"); + // The job's end and Edit › Fade's document are rule inputs: the menu model and each rule-holding source build once. + assert_eq!(count(&job_frames, crate::menus::model_id()), 1, "the job's apply and end build the menu model once"); + for source in crate::command_state_trials::RULES { + assert_eq!(count(&job_frames, states_id(source)), 1, "the job's apply and end build the {source} states once"); + } + let idle = builds_over(&mut h, 4); + assert_eq!(count(&idle, crate::menus::model_id()), 0, "the frames after the job build no menu model"); + assert_eq!(count(&idle, crate::panels::layers_tree::model_id()), 0, "the frames after the job build no Layers model"); + for (name, _) in crate::app::framework::sources() { + assert_eq!(count(&idle, states_id(name)), 0, "the frames after the job build no {name} states"); + } h.state_mut().session.set_active(0); h.run_steps(1); assert_eq!(builds(&h, crate::panels::layers_tree::model_id()), 1, "switching to A builds its Layers model once"); + for source in DOCUMENT_SOURCES { + assert_eq!(builds(&h, states_id(source)), 1, "switching to A builds the {source} states once"); + } } #[test] @@ -118,7 +153,7 @@ fn a_preference_write_that_keeps_the_history_limits_moves_no_documents_revision( } #[test] -fn targeting_a_mask_over_colour_rows_moves_only_the_tracked_revision() { +fn targeting_a_mask_over_colour_rows_rebuilds_the_channels_states() { let mut h = harness(); h.state_mut().run("layer.layerMask.revealAll", json!({})).unwrap(); h.state_mut().session.active_mut().unwrap().channel_view.target = ChannelTarget::Color(0); @@ -130,4 +165,6 @@ fn targeting_a_mask_over_colour_rows_moves_only_the_tracked_revision() { assert_eq!(st.channel_view.target, ChannelTarget::LayerMask, "the mask is the target"); assert_eq!(st.revision, edits, "a view change is no edit step"); assert_ne!(st.revision(), tracked, "but it moves the tracked revision views key on"); + h.run_steps(1); + assert_eq!(builds(&h, states_id("channels")), 1, "the Channels states follow it"); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9fe533aa0f..421199b27f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -948,6 +948,8 @@ mod brush_settle_trials; #[cfg(test)] mod chrome_settle_trials; #[cfg(test)] +mod command_state_trials; +#[cfg(test)] mod doc_revision_trials; #[cfg(test)] mod doc_tracked_trials; diff --git a/crates/ui-egui/src/menus/facts.rs b/crates/ui-egui/src/menus/facts.rs index 5798c602c3..936d742d50 100644 --- a/crates/ui-egui/src/menus/facts.rs +++ b/crates/ui-egui/src/menus/facts.rs @@ -19,10 +19,19 @@ pub(crate) struct MenuFacts<'a> { language: &'static str, /// The keymap's overrides and catalog generations: the rows show its chords. keymap: (u64, u64), + rules: RuleFacts<'a>, + prefs: PrefFacts<'a>, + shown: ShownFacts<'a>, +} + +/// What the enable rules read ([`super::is_enabled`], `Session::is_enabled`): the documents, the session and the shell +/// state they ask about. A command source whose states follow the rules holds these; the menu model holds them with +/// what its rows show. +#[derive(MemoProps)] +pub(crate) struct RuleFacts<'a> { documents: Documents<'a>, session: SessionFacts, - prefs: PrefFacts<'a>, - ui: UiFacts<'a>, + ui: UiRuleFacts<'a>, } /// The open documents and the active one. @@ -65,6 +74,8 @@ struct SessionFacts { actions: (u64, Option<(usize, usize)>, u8), /// Edit › Undo's label when it undoes an Actions library change. undo_label: Option<&'static str>, + /// The installed plug-ins' revision: a plug-in's menu item needs it installed. + plugins: u64, } /// The preferences the rows show. @@ -81,9 +92,9 @@ struct PrefFacts<'a> { favorite_themes: &'a Vec, } -/// The shell's state the rows show. +/// The shell's state the rules read. #[derive(MemoProps)] -struct UiFacts<'a> { +struct UiRuleFacts<'a> { tool: u64, /// The open Free Transform: its undo steps' and phase's revision, Content-Aware Scale, its layer count and a /// running commit. @@ -101,6 +112,19 @@ struct UiFacts<'a> { /// a brush resize. modal: (usize, bool, Option<&'static str>, bool, bool), selected_guide: bool, + /// Save, Paste and Place Embedded ask which services this platform has: export, the clipboard image and files. + services: (bool, bool, bool), + /// The locked workspace greys the panel commands that move, float or close panels. + workspaces_locked: bool, + /// Window › Arrange: the docked and floating document windows. + document_windows: (usize, usize), + /// File › Automate › Batch: an action is selected in the Actions panel. + batch_action: bool, +} + +/// The shell's state the rows show beside the rules: ticks, labels and the lists they name. +#[derive(MemoProps)] +struct ShownFacts<'a> { extras: crate::state::Extras, view: &'a crate::view_cmds::ViewOptions, /// The options, status, menu and contextual task bars. @@ -113,20 +137,50 @@ struct UiFacts<'a> { ticks: Arc>, recent_files: &'a Tracked>, workspaces: &'a Tracked, - /// Save and Paste rules ask which services this platform has. - services: (bool, bool), } impl<'a> MenuFacts<'a> { /// The facts of `app`'s current state. pub(crate) fn of(app: &'a PhotocraftApp) -> MenuFacts<'a> { - let s = &app.session; - let active = s.active(); - let prefs = s.prefs(); + let prefs = app.session.prefs(); let ui = &app.ui; MenuFacts { language: crate::i18n::current().code(), keymap: app.framework.keymap_inputs(), + rules: RuleFacts::of(app), + prefs: PrefFacts { + language: &prefs.interface.language, + hidden: &prefs.menus.hidden, + colors: &prefs.menus.colors, + show_menu_colors: prefs.interface.show_menu_colors, + quick_export: prefs.export.quick_export_format.name(), + font_preview: prefs.type_.font_preview.name(), + generator: prefs.plug_ins.generator_enabled, + appearance: prefs.interface.appearance_mode.name(), + favorite_themes: &prefs.interface.favorite_themes, + }, + shown: ShownFacts { + extras: ui.extras, + view: &ui.view, + bars: (ui.panels.options_bar, ui.panels.status_bar, ui.panels.menu_bar, ui.panels.context_task_bar), + palette: ui.palette.open, + theme: (ui.theme.id().as_str(), ui.theme.is_dark()), + arrangement: ui.document_windows.arrangement, + ticks: window_ticks(app), + recent_files: &ui.recent_files, + workspaces: &app.workspaces, + }, + } + } +} + +impl<'a> RuleFacts<'a> { + /// What the rules read in `app`'s current state. + pub(crate) fn of(app: &'a PhotocraftApp) -> RuleFacts<'a> { + let s = &app.session; + let active = s.active(); + let ui = &app.ui; + RuleFacts { documents: Documents { generation: s.documents_generation(), active_generation: s.active_generation(), @@ -150,19 +204,9 @@ impl<'a> MenuFacts<'a> { mask_targeted: s.tools.mask_targeted, actions: (s.actions.list.revision(), s.actions.recording, s.actions.playing), undo_label: crate::actions::library::edit_undo_label(app), + plugins: photocraft_plugins::registry::revision(), }, - prefs: PrefFacts { - language: &prefs.interface.language, - hidden: &prefs.menus.hidden, - colors: &prefs.menus.colors, - show_menu_colors: prefs.interface.show_menu_colors, - quick_export: prefs.export.quick_export_format.name(), - font_preview: prefs.type_.font_preview.name(), - generator: prefs.plug_ins.generator_enabled, - appearance: prefs.interface.appearance_mode.name(), - favorite_themes: &prefs.interface.favorite_themes, - }, - ui: UiFacts { + ui: UiRuleFacts { tool: ui.tool as u64, transform: ui .transform @@ -181,16 +225,10 @@ impl<'a> MenuFacts<'a> { app.brush_resize.active(), ), selected_guide: crate::guide_select::selected(app).is_some(), - extras: ui.extras, - view: &ui.view, - bars: (ui.panels.options_bar, ui.panels.status_bar, ui.panels.menu_bar, ui.panels.context_task_bar), - palette: ui.palette.open, - theme: (ui.theme.id().as_str(), ui.theme.is_dark()), - arrangement: ui.document_windows.arrangement, - ticks: window_ticks(app), - recent_files: &ui.recent_files, - workspaces: &app.workspaces, - services: (app.services.export.is_some(), app.services.clipboard_get_image.is_some()), + services: (app.services.export.is_some(), app.services.clipboard_get_image.is_some(), app.services.files.is_some()), + workspaces_locked: app.workspaces.set.locked, + document_windows: (ui.document_windows.docked.len(), ui.document_windows.floating.len()), + batch_action: crate::actions::selected_action(app).is_some(), }, } } diff --git a/crates/ui-egui/src/menus/workspace_ui.rs b/crates/ui-egui/src/menus/workspace_ui.rs index 56b31618b6..80ae255718 100644 --- a/crates/ui-egui/src/menus/workspace_ui.rs +++ b/crates/ui-egui/src/menus/workspace_ui.rs @@ -321,6 +321,11 @@ pub fn states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { workspace_states(&app.workspaces.set).into_iter().map(|(command, state)| (CommandRef::from(command), state)).collect() } +/// [`states`], derived from the workspaces. +pub fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + crate::app::framework::derived_states(app, name, &app.workspaces, || states(app)) +} + // --------------------------------------------------------------------------------------------------------------- // Menu commands. // --------------------------------------------------------------------------------------------------------------- diff --git a/crates/ui-egui/src/panels/actions/menu.rs b/crates/ui-egui/src/panels/actions/menu.rs index 64d33fcb4c..6961d913f7 100644 --- a/crates/ui-egui/src/panels/actions/menu.rs +++ b/crates/ui-egui/src/panels/actions/menu.rs @@ -52,6 +52,31 @@ pub(crate) fn states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { .collect() } +/// What [`states`] reads: the list, the menu's facts and the panel's state. +#[derive(craft::ui::contract::MemoProps)] +struct StatesFacts<'a> { + list: u64, + recording: bool, + path_selected: bool, + waiting: bool, + tool_recording: bool, + panel: &'a craft::automation::ui::actions::ActionsPanelState, +} + +/// [`states`], derived from [`StatesFacts`]. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + let menu = facts(app); + let facts = StatesFacts { + list: app.session.actions.list.revision(), + recording: menu.recording, + path_selected: menu.path_selected, + waiting: menu.waiting, + tool_recording: menu.tool_recording, + panel: &app.ui.actions.panel, + }; + crate::app::framework::derived_states(app, name, &facts, || states(app)) +} + /// Runs a fired command of the Actions panel; `false` for a command of another set. Its event goes through the one /// mapping that every Actions event takes. pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { diff --git a/crates/ui-egui/src/panels/brush_panel.rs b/crates/ui-egui/src/panels/brush_panel.rs index f90d1e1531..d5213c150e 100644 --- a/crates/ui-egui/src/panels/brush_panel.rs +++ b/crates/ui-egui/src/panels/brush_panel.rs @@ -224,6 +224,11 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta ] } +/// [`command_states`], derived from the brush. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + crate::app::framework::derived_states(app, name, &app.session.tools.brush, || command_states(app)) +} + /// Runs a fired menu command; false for a command this panel does not own. pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { let Some(command) = BrushSettingsCommand::from_ref(command) else { return false }; diff --git a/crates/ui-egui/src/panels/channels_panel.rs b/crates/ui-egui/src/panels/channels_panel.rs index 284940c03c..2d4dc86584 100644 --- a/crates/ui-egui/src/panels/channels_panel.rs +++ b/crates/ui-egui/src/panels/channels_panel.rs @@ -460,6 +460,19 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta .collect() } +/// What [`command_states`] reads: the rules (the active document and its channel view among them) and the mask target. +#[derive(craft::ui::contract::MemoProps)] +struct StatesFacts<'a> { + rules: crate::menus::facts::RuleFacts<'a>, + mask_target: bool, +} + +/// [`command_states`], derived from [`StatesFacts`]. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + let facts = StatesFacts { rules: crate::menus::facts::RuleFacts::of(app), mask_target: app.ui.mask_target }; + crate::app::framework::derived_states(app, name, &facts, || command_states(app)) +} + /// Runs a fired command of the Channels set; false for another set's command. pub(crate) fn run_fired(app: &mut PhotocraftApp, ctx: &egui::Context, command: &CommandRef) -> bool { let Some(command) = ChannelsCommands::from_ref(command) else { return false }; diff --git a/crates/ui-egui/src/panels/histogram_panel.rs b/crates/ui-egui/src/panels/histogram_panel.rs index 8996cd1991..65cb782240 100644 --- a/crates/ui-egui/src/panels/histogram_panel.rs +++ b/crates/ui-egui/src/panels/histogram_panel.rs @@ -642,6 +642,13 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta .collect() } +/// [`command_states`], derived from the panel's settings and whether a document with a selection is open. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + let active = app.session.active(); + let facts = (&app.ui.histogram, active.is_some(), active.is_some_and(|st| st.doc.selection.is_some())); + crate::app::framework::derived_states(app, name, &facts, || command_states(app)) +} + /// Runs a scope command the menu or a key fired: the settings change, then they persist; Uncached Refresh recounts. /// Returns whether the command belongs to this panel. pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { diff --git a/crates/ui-egui/src/panels/history_menu_ui.rs b/crates/ui-egui/src/panels/history_menu_ui.rs index b3f859a00a..305e438b6a 100644 --- a/crates/ui-egui/src/panels/history_menu_ui.rs +++ b/crates/ui-egui/src/panels/history_menu_ui.rs @@ -56,6 +56,21 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta ITEMS.iter().flatten().map(|&id| (CommandRef::new(id), CommandState::new().enabled(command_state(app, resolve(id, snapshot).0)))).collect() } +/// What [`command_states`] reads: the rules (the Pen and Crop histories and an open Free Transform among them) and the +/// snapshot selected in the panel. +#[derive(craft::ui::contract::MemoProps)] +struct StatesFacts<'a> { + rules: crate::menus::facts::RuleFacts<'a>, + #[memo_props(hash = "a plain model id, a snapshot id and the history spot: plain values")] + snapshot: &'a Option<(photocraft_doc::DocId, u64, crate::panels::history::HistorySpot)>, +} + +/// [`command_states`], derived from [`StatesFacts`]. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + let facts = StatesFacts { rules: crate::menus::facts::RuleFacts::of(app), snapshot: &app.ui.history_snapshot }; + crate::app::framework::derived_states(app, name, &facts, || command_states(app)) +} + /// Runs the item `command` and reports whether it is one of this menu's. History Options… opens its /// dialog, as the menu bar's command does. Step Backward/Forward over a Pen path step it as Edit › /// Undo/Redo do (`vector_ui::pen_history_step`). diff --git a/crates/ui-egui/src/panels/layers_panel_ui.rs b/crates/ui-egui/src/panels/layers_panel_ui.rs index 4e62eb18a2..17988d94e9 100644 --- a/crates/ui-egui/src/panels/layers_panel_ui.rs +++ b/crates/ui-egui/src/panels/layers_panel_ui.rs @@ -165,6 +165,27 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta states } +/// What [`command_states`] reads: the rules (the document's selection among them), the filter bar, the clip +/// preference's value and the UI language, which Duplicate Layers…' title is translated into. +#[derive(craft::ui::contract::MemoProps)] +struct StatesFacts<'a> { + rules: crate::menus::facts::RuleFacts<'a>, + language: &'static str, + show_filters: bool, + clip: bool, +} + +/// [`command_states`], derived from [`StatesFacts`]. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + let facts = StatesFacts { + rules: crate::menus::facts::RuleFacts::of(app), + language: crate::i18n::current().code(), + show_filters: app.ui.layers_settings.show_filters, + clip: app.session.prefs().interface.clip_thumbnails_to_layer_bounds, + }; + crate::app::framework::derived_states(app, name, &facts, || command_states(app)) +} + /// Runs a fired settings command of the panel menu. `false` for every other command: PhotoCraft's `layer.arrange.*` /// bindings stay the one path of the stacking keys, and the catalogue commands run through the menus. pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { diff --git a/crates/ui-egui/src/panels/options_bar/selection.rs b/crates/ui-egui/src/panels/options_bar/selection.rs index f9b8462b84..dab5347b65 100644 --- a/crates/ui-egui/src/panels/options_bar/selection.rs +++ b/crates/ui-egui/src/panels/options_bar/selection.rs @@ -117,6 +117,11 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta vec![(CommandRef::new(SELECT_AND_MASK), CommandState::new().enabled(crate::menus::is_enabled(app, SELECT_AND_MASK)))] } +/// [`command_states`], derived from what the rules read. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + crate::app::framework::derived_states(app, name, &crate::menus::facts::RuleFacts::of(app), || command_states(app)) +} + /// The Select and Mask… button; its enabled state is [`command_states`]'. fn select_and_mask(ui: &mut egui::Ui) { Button::command(SELECT_AND_MASK).show(ui); diff --git a/crates/ui-egui/src/panels/preset_browser.rs b/crates/ui-egui/src/panels/preset_browser.rs index 480dbfaedc..78975d8024 100644 --- a/crates/ui-egui/src/panels/preset_browser.rs +++ b/crates/ui-egui/src/panels/preset_browser.rs @@ -445,6 +445,14 @@ pub(crate) fn styles_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandStat .collect() } +/// [`styles_states`], derived from what it reads: the presets the styles live in, the selected style and the browser's +/// view. +pub(crate) fn styles_source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + let view = app.ui.presets_ui.browsers.get(STYLES.id).map_or(PresetView::Grid, |state| state.view); + let facts = (app.session.presets.revision(), app.ui.presets_ui.selected.get(STYLES.id), view); + crate::app::framework::derived_states(app, name, &facts, || styles_states(app)) +} + /// Runs a Styles panel menu command; `false` when `cmd` is not one of its commands. pub(crate) fn styles_run(app: &mut PhotocraftApp, ctx: &egui::Context, cmd: &CommandRef) -> bool { let Some(command) = PresetCommands::from_ref(cmd) else { return false }; diff --git a/crates/ui-egui/src/panels/registry.rs b/crates/ui-egui/src/panels/registry.rs index fff40da505..00b1eed5d1 100644 --- a/crates/ui-egui/src/panels/registry.rs +++ b/crates/ui-egui/src/panels/registry.rs @@ -1,8 +1,9 @@ //! The panel registry: every panel PhotoCraft shows in its workspace, with its name, icon, size policy, body and //! panel menu, and the built-in workspaces those panels are arranged in. //! -//! The dock (`panel_docking`) reads a panel's spec and body from here; the command sources read each panel's menu -//! states and run its fired commands through [`states`] and [`run_fired`]. One arrangement serves every theme. +//! The dock (`panel_docking`) reads a panel's spec and body from here; the framework reads each panel's menu states as +//! a command source of its own ([`PanelEntry::states`]) and runs its fired commands through [`run_fired`]. One +//! arrangement serves every theme. use craft::behavior::Axis; use craft::behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, SplitSize, Workspace}; @@ -11,10 +12,13 @@ use craft::ui::contract::{Scroll, ShowContainer as _}; use craft::ui::docking::DockHeights; use craft::ui::layout_components::Stack; use craft::ui::menu::PanelRow; -use craft::ui::runtime::commands::{CommandRef, CommandSet as _, CommandState}; +use craft::ui::runtime::commands::{CommandRef, CommandSet as _}; use egui::{Rect, pos2, vec2}; +use std::sync::Arc; + use super::PhotocraftApp; +use crate::app::framework::{SourceStates, StatesOf, derived_states, no_states}; /// One registered panel. pub(crate) struct PanelEntry { @@ -34,8 +38,9 @@ pub(crate) struct PanelEntry { pub body: fn(&mut PhotocraftApp, &mut egui::Ui), /// The rows of the panel's menu, before the dock's own rows. pub rows: fn(&PhotocraftApp) -> Vec, - /// The state of each command the rows name, for a panel whose rows are a framework command set. - pub states: fn(&PhotocraftApp) -> Vec<(CommandRef, CommandState)>, + /// The state of each command the rows name, for a panel whose rows are a framework command set: a value derived + /// under the panel's id from what the states read, so one panel's change builds only its own. + pub states: StatesOf, /// Runs a fired command of the panel's command set; `false` when the command is not the panel's. pub run: fn(&mut PhotocraftApp, &egui::Context, &CommandRef) -> bool, } @@ -57,10 +62,6 @@ fn no_rows(_: &PhotocraftApp) -> Vec { Vec::new() } -fn no_states(_: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { - Vec::new() -} - /// The body of a panel whose group view draws it. fn drawn_by_group_view(_: &mut PhotocraftApp, _: &mut egui::Ui) {} @@ -105,13 +106,13 @@ pub(crate) static PANELS: &[PanelEntry] = &[ PanelEntry { heights: Some(COLOR_HEIGHTS), rows: |_| ColorPanelMenu::rows(), - states: color_states, + states: color_source_states, run: color_run, ..panel("color", || tl!("Color").to_string(), "palette", LEAST, super::color::panel) }, PanelEntry { rows: super::swatches_ui::panel_rows, - states: super::swatches_ui::command_states, + states: super::swatches_ui::source_states, run: super::swatches_ui::run_fired, ..panel("swatches", || tl!("Swatches").to_string(), "swatch_book", LEAST, super::swatches_ui::panel) }, @@ -140,7 +141,7 @@ pub(crate) static PANELS: &[PanelEntry] = &[ PanelEntry { heights: Some(NAVIGATOR_HEIGHTS), ..panel("navigator", || tl!("Navigator").to_string(), "navigation", LEAST, super::navigator::navigator) }, PanelEntry { rows: super::histogram_panel::panel_rows, - states: super::histogram_panel::command_states, + states: super::histogram_panel::source_states, run: super::histogram_panel::run_fired, ..panel("histogram", || tl!("Histogram").to_string(), "chart_line", LEAST, |app, ui| scrolled(app, ui, super::histogram_panel::show)) }, @@ -148,13 +149,13 @@ pub(crate) static PANELS: &[PanelEntry] = &[ PanelEntry { heights: Some(HISTORY_HEIGHTS), rows: super::history_menu_ui::panel_rows, - states: super::history_menu_ui::command_states, + states: super::history_menu_ui::source_states, run: super::history_menu_ui::run_fired, ..panel("history", || tl!("History").to_string(), "clock", LEAST, super::history::history) }, PanelEntry { rows: super::actions::menu::panel_rows, - states: super::actions::menu::states, + states: super::actions::menu::source_states, run: super::actions::menu::run_fired, ..panel("actions", || tl!("Actions").to_string(), "play", LEAST, super::actions::panel) }, @@ -166,13 +167,13 @@ pub(crate) static PANELS: &[PanelEntry] = &[ PanelEntry { heights: Some(LAYERS_HEIGHTS), rows: super::layers_panel_ui::panel_rows, - states: super::layers_panel_ui::command_states, + states: super::layers_panel_ui::source_states, run: super::layers_panel_ui::run_fired, ..panel("layers", || tl!("Layers").to_string(), "layers", 110.0, super::layers::layers) }, PanelEntry { rows: super::channels_panel::panel_rows, - states: super::channels_panel::command_states, + states: super::channels_panel::source_states, run: super::channels_panel::run_fired, ..panel("channels", || tl!("Channels").to_string(), "squares_subtract", 110.0, super::channels_panel::show) }, @@ -180,7 +181,7 @@ pub(crate) static PANELS: &[PanelEntry] = &[ PanelEntry { heights: Some(BRUSHES_HEIGHTS), ..panel("brushes", || tl!("Brushes").to_string(), "brush", 70.0, super::brush_panel::brushes::panel) }, PanelEntry { rows: super::preset_browser::styles_rows, - states: super::preset_browser::styles_states, + states: super::preset_browser::styles_source_states, run: super::preset_browser::styles_run, ..floating("styles", || tl!("Styles").to_string(), "sparkles", [300.0, 420.0], |app, ui| scrolled(app, ui, super::preset_panels::styles_panel)) }, @@ -215,7 +216,7 @@ pub(crate) static PANELS: &[PanelEntry] = &[ panel("timeline", || tl!("Timeline").to_string(), "split_horizontal", LEAST, super::timeline_ui::body), PanelEntry { rows: super::brush_panel::panel_rows, - states: super::brush_panel::command_states, + states: super::brush_panel::source_states, run: super::brush_panel::run_fired, ..floating("brushSettings", || tl!("Brush Settings").to_string(), "brush_cleaning", [520.0, 460.0], super::brush_settings::brush_settings) }, @@ -226,10 +227,15 @@ pub(crate) static PANELS: &[PanelEntry] = &[ ]; /// The Color panel menu's states, from the panel's own state. -fn color_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { +fn color_states(app: &PhotocraftApp) -> SourceStates { ColorPanelMenu::states(&app.ui.color_panel.panel).into_iter().map(|(command, state)| (command.into(), state)).collect() } +/// [`color_states`], derived from the panel's state. +fn color_source_states(app: &PhotocraftApp, name: &'static str) -> Arc { + derived_states(app, name, &app.ui.color_panel.panel, || color_states(app)) +} + /// Runs a fired Color panel menu command; Copy Color as HTML and Copy Color's Hex Code put their text on the /// clipboard. fn color_run(app: &mut PhotocraftApp, ctx: &egui::Context, command: &CommandRef) -> bool { @@ -280,11 +286,6 @@ pub(crate) fn permissions(panel: &str) -> Permissions { } } -/// The state of every panel's menu commands. -pub(crate) fn states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { - PANELS.iter().flat_map(|panel| (panel.states)(app)).collect() -} - /// Runs a fired panel menu command through the panel whose command set it belongs to; `false` when none takes it. pub(crate) fn run_fired(app: &mut PhotocraftApp, ctx: &egui::Context, command: &CommandRef) -> bool { PANELS.iter().any(|panel| (panel.run)(app, ctx, command)) diff --git a/crates/ui-egui/src/panels/swatches_ui.rs b/crates/ui-egui/src/panels/swatches_ui.rs index bf9c1842aa..81fd58c88a 100644 --- a/crates/ui-egui/src/panels/swatches_ui.rs +++ b/crates/ui-egui/src/panels/swatches_ui.rs @@ -243,6 +243,11 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta SwatchesMenu::states(&app.session.presets.swatches).into_iter().map(|(command, state)| (CommandRef::from(command), state)).collect() } +/// [`command_states`], derived from the presets the swatches live in. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + crate::app::framework::derived_states(app, name, &app.session.presets.revision(), || command_states(app)) +} + /// Runs a fired command of the Swatches menu; false for another set's command. pub(crate) fn run_fired(app: &mut PhotocraftApp, ctx: &egui::Context, command: &CommandRef) -> bool { let Some(command) = SwatchesCommand::from_ref(command) else { return false }; diff --git a/crates/ui-egui/src/tools/align_bar.rs b/crates/ui-egui/src/tools/align_bar.rs index b6a0dcf594..9eab1e26d8 100644 --- a/crates/ui-egui/src/tools/align_bar.rs +++ b/crates/ui-egui/src/tools/align_bar.rs @@ -47,6 +47,11 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta all().map(|action| (CommandRef::new(action.id()), CommandState::new().enabled(command_id(action).is_some_and(|id| app.session.is_enabled(id))))).collect() } +/// [`command_states`], derived from what the rules read. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + crate::app::framework::derived_states(app, name, &crate::menus::facts::RuleFacts::of(app), || command_states(app)) +} + /// Runs a fired `AlignAction`. False when `command` is not one of them. The context is the /// command-source shape's; these commands need none. pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { diff --git a/crates/ui-egui/src/tools/artboard_tool.rs b/crates/ui-egui/src/tools/artboard_tool.rs index 982ed64deb..925b9327d4 100644 --- a/crates/ui-egui/src/tools/artboard_tool.rs +++ b/crates/ui-egui/src/tools/artboard_tool.rs @@ -287,9 +287,10 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta vec![(ArtboardCommand::AddNew.into(), state)] } -/// What [`command_states`] reads: whether a document is open, and the placing mode. -pub(crate) fn command_states_key(app: &PhotocraftApp) -> crate::app::framework::StatesKey { - [u64::from(app.session.active().is_some()), u64::from(app.ui.artboard_tool.adding), 0, 0] +/// [`command_states`], derived from what it reads: whether a document is open, and the placing mode. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + let facts = (app.session.active().is_some(), app.ui.artboard_tool.adding); + crate::app::framework::derived_states(app, name, &facts, || command_states(app)) } /// Runs a fired Artboard command: Add New Artboard flips the placing mode and adds no board. `ctx` is the shape every diff --git a/crates/ui-egui/src/tools/slice_ui.rs b/crates/ui-egui/src/tools/slice_ui.rs index dd2d513fcd..4790f07919 100644 --- a/crates/ui-egui/src/tools/slice_ui.rs +++ b/crates/ui-egui/src/tools/slice_ui.rs @@ -317,12 +317,19 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta .collect() } -/// What [`command_states`] reads: the active document and its revision (the selected slice resolves from its -/// slices), the selected slice's number and the lock. -pub(crate) fn command_states_key(app: &PhotocraftApp) -> crate::app::framework::StatesKey { - let revision = app.session.active().map_or(u64::MAX, |st| st.revision); - let selected = app.ui.slices.selected.map_or(u64::MAX, |n| n as u64); - [app.session.active_generation(), revision, selected, u64::from(app.session.file_menu.slices_locked)] +/// What [`command_states`] reads: the active document (the selected slice resolves from its slices), the selected +/// slice's number and the lock. +#[derive(craft::ui::contract::MemoProps)] +struct StatesFacts<'a> { + doc: Option<&'a craft::ui::contract::Tracked>, + selected: Option, + locked: bool, +} + +/// [`command_states`], derived from [`StatesFacts`]. +pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { + let facts = StatesFacts { doc: app.session.active_tracked(), selected: app.ui.slices.selected, locked: app.session.file_menu.slices_locked }; + crate::app::framework::derived_states(app, name, &facts, || command_states(app)) } /// Runs a fired slice command; whether it was one. From 1f86f4bacf1ec4b5aaa779277fa67334ac564ea5 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:17:28 +0700 Subject: [PATCH 37/38] io: cover Camera Raw settings through PSD save and reopen (#16218) Co-authored-by: FredApps --- crates/io/src/camera_raw_map/tests.rs | 48 +++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/crates/io/src/camera_raw_map/tests.rs b/crates/io/src/camera_raw_map/tests.rs index 0d1e1a603a..6e2373657a 100644 --- a/crates/io/src/camera_raw_map/tests.rs +++ b/crates/io/src/camera_raw_map/tests.rs @@ -165,6 +165,54 @@ fn active_unimplemented_controls_and_malformed_curves_stay_opaque() { } } +#[test] +fn psd_reopen_keeps_editable_camera_raw_and_preserves_active_unsupported_optics() { + use std::sync::Arc; + + use photocraft_color::{ColorMode, SampleType}; + use photocraft_doc::{Document, Layer, LayerContent, SmartObject, SmartSource}; + use photocraft_geom::{Affine, Size}; + use photocraft_raster::Surface; + + let size = Size::new(2, 2); + let mut source = Document::new("contents", size, ColorMode::Rgb, SampleType::U8); + let mut pixels = Surface::new(source.pixel_format()); + pixels.fill_rect(source.bounds(), &[0.25, 0.50, 0.75, 1.0]); + source.layers.push(Layer::new("synthetic pixels", LayerContent::Raster(pixels.clone()))); + let bytes = Arc::new(photocraft_format::save_to_bytes(&source, &Default::default()).unwrap()); + + // Use the existing generated descriptor, not the optional external PSD. Nonzero MDis cannot + // be rendered by the editable Camera Raw filter and must survive even when the layer is saved. + for optics in [false, true] { + let mut item = source_item(); + if optics { + let mut settings = get_desc(&item, "Fltr").unwrap().clone(); + set(&mut settings, "MDis", Value::Integer(17)); + set(&mut item, "Fltr", Value::Descriptor(settings)); + } + let mut smart = + SmartObject::new(SmartSource::Embedded { file_name: "contents.pcraft".into(), bytes: bytes.clone() }, Affine::IDENTITY, Some(pixels.clone())); + smart.smart_filters.push(filter_from_item(&item)); + let mut doc = Document::new("camera raw compatibility", size, ColorMode::Rgb, SampleType::U8); + doc.layers.push(Layer::new("edited", LayerContent::Smart(smart))); + + let saved = crate::export(&doc, "psd", &Default::default()).unwrap(); + let reopened = crate::import("saved.psd", &saved.bytes).unwrap().document; + let layer = reopened.layers.iter().find(|layer| layer.name == "edited").unwrap(); + let LayerContent::Smart(smart) = &layer.content else { panic!("the Camera Raw layer must reopen as a smart object") }; + let [filter] = smart.smart_filters.as_slice() else { panic!("expected the saved Camera Raw filter") }; + if optics { + assert_eq!(filter.command, UNSUPPORTED_FILTER); + } else { + assert_eq!(filter.command, COMMAND); + let settings: CameraRaw = serde_json::from_value(filter.params.clone()).unwrap(); + assert!((settings.exposure - 1.15).abs() < 1e-6); + } + let roundtripped = item_for_filter(filter).unwrap(); + assert_eq!(get_desc(&roundtripped, "Fltr"), get_desc(&item, "Fltr")); + } +} + #[test] #[ignore = "requires a user-supplied Camera Raw PSD"] fn all_sliders_fixture() { From 8aee04760986486b9d91734b6d91f254ca83b1b8 Mon Sep 17 00:00:00 2001 From: "Stefan S." Date: Sat, 21 Nov 2026 19:00:37 +0100 Subject: [PATCH 38/38] Open luminance and data-channel EXRs as RGB 32-bit (#16149) * Open luminance and data-channel EXRs as RGB 32-bit A Y-only, Z-only or Y + A EXR opened as a Grayscale document tagged linear gray through File > Open (the band decoder) and File > Open EXR Parts. Every EXR now opens as RGB 32-bit tagged linear sRGB, as in the reference application: the gray band is expanded to R = G = B with its alpha kept, and exr_parts converts every part or group to RGBA. RGB files are unchanged. The whole-file decoder in flat.rs (the bytes import and File > Open's fallback for a Z-only file) still opens gray as Grayscale and is left for a follow-up; an ignored test records it. Fixes #14069. * Cover a Z-only EXR through File > Open The band decoder reads a Z-only scanline EXR, so File > Open of one is covered by the passing test; only the bytes import through flat.rs stays an open point for #14069. --------- Co-authored-by: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> --- crates/io/src/exr_native.rs | 25 +++- crates/io/src/exr_parts.rs | 39 ++--- .../tests/it/exr_open_luminance_rgb_tests.rs | 135 ++++++++++++++++++ crates/io/tests/it/exr_part_profile.rs | 51 ++++--- crates/io/tests/it/main.rs | 1 + crates/io/tests/it/streaming_exr.rs | 16 ++- 6 files changed, 218 insertions(+), 49 deletions(-) create mode 100644 crates/io/tests/it/exr_open_luminance_rgb_tests.rs diff --git a/crates/io/src/exr_native.rs b/crates/io/src/exr_native.rs index 83fbe6097b..36b8ef7699 100644 --- a/crates/io/src/exr_native.rs +++ b/crates/io/src/exr_native.rs @@ -26,6 +26,18 @@ fn require_scratch(expected: bool) -> Result<(), IoError> { Ok(()) } +/// Interleaved F32 gray + alpha samples as F32 RGBA, the gray value in R, G and B. +fn gray_alpha_to_rgba(data: &[u8]) -> Vec { + let mut out = Vec::with_capacity(data.len().saturating_mul(2)); + for [gray, alpha] in data.as_chunks::<4>().0.as_chunks::<2>().0 { + out.extend_from_slice(gray); + out.extend_from_slice(gray); + out.extend_from_slice(gray); + out.extend_from_slice(alpha); + } + out +} + /// Decode a single-part flat scanline EXR from `source` one compression block at a time. /// `Ok(None)`: the header is not one the band decoder takes (multi-part, deep, tiled, custom /// chromaticities, over its block limits or malformed by its stricter checks); the caller @@ -41,7 +53,9 @@ pub(crate) fn import(source: R, ctl: &Interrupt<'_>) -> Result return Ok(None), }; let info = decoder.info(); - let mode = if info.gray { ColorMode::Grayscale } else { ColorMode::Rgb }; + // Every EXR opens as RGB 32-bit, as in the reference application: a luminance or single + // data channel (decoded as gray) fills R, G and B alike (#14069). + let mode = ColorMode::Rgb; let fmt = PixelFormat::new(mode, SampleType::F32, true); let scratch_expected = photocraft_raster::spill::enabled(); if !scratch_expected { @@ -76,7 +90,11 @@ pub(crate) fn import(source: R, ctl: &Interrupt<'_>) -> Result(source: R, ctl: &Interrupt<'_>) -> Result Result<(Surface, ColorMode), IoError> { - let (layout, mode) = if matches!(img.layout(), ChannelLayout::Gray | ChannelLayout::GrayA) { - (ChannelLayout::GrayA, ColorMode::Grayscale) - } else { - (ChannelLayout::Rgba, ColorMode::Rgb) - }; +/// An image as an importable layer: F16 becomes F32 (lossless, warned once by the caller), the +/// layout is RGBA (a gray part or group fills R, G and B alike, as every EXR opens as RGB, +/// #14069), the surface is built a band of rows at a time. +fn layer_surface(img: &Image, max: &mut (u32, u32)) -> Result { max.0 = max.0.max(img.width()); max.1 = max.1.max(img.height()); - let converted = img.convert(layout, SampleType::F32); - image_surface(&converted, layout, SampleType::F32).map(|s| (s, mode)) + let converted = img.convert(ChannelLayout::Rgba, SampleType::F32); + image_surface(&converted, ChannelLayout::Rgba, SampleType::F32) } /// Imports the chosen entries as the layers of one document: parts whole, groups from their -/// own channels, F16 kept losslessly as F32, the linear-light EXR values tagged linear sRGB -/// or linear gray. +/// own channels, F16 kept losslessly as F32, the document RGB and the linear-light EXR values +/// tagged linear sRGB. /// `precomp` adds the additive sum of the file's AOV groups as a top layer and fails, /// naming the missing AOVs, when the light-path set is incomplete. pub fn import(name: &str, bytes: &[u8], sel: &Selection) -> Result { @@ -230,7 +225,6 @@ pub fn import(name: &str, bytes: &[u8], sel: &Selection) -> Result = Vec::new(); let mut warnings: Vec = Vec::new(); - let mut gray_only = true; let mut max = (1u32, 1u32); let mut f16_seen = false; @@ -239,8 +233,7 @@ pub fn import(name: &str, bytes: &[u8], sel: &Selection) -> Result Result Result Vec { + let mut chans: Vec<&(&str, f32, f32)> = channels.iter().collect(); + chans.sort_by_key(|c| c.0); + let mut out = vec![0x76, 0x2f, 0x31, 0x01, 2, 0, 0, 0]; + let mut attr = |name: &str, kind: &str, value: &[u8]| { + out.extend(name.bytes().chain([0]).chain(kind.bytes()).chain([0])); + out.extend((value.len() as i32).to_le_bytes()); + out.extend(value); + }; + let mut chlist = Vec::new(); + for (name, _, _) in &chans { + chlist.extend(name.bytes().chain([0])); + chlist.extend(2i32.to_le_bytes()); // FLOAT + chlist.extend([0, 0, 0, 0]); // pLinear + reserved + chlist.extend(1i32.to_le_bytes()); + chlist.extend(1i32.to_le_bytes()); + } + chlist.push(0); + let window: Vec = [0i32, 0, W as i32 - 1, H as i32 - 1].iter().flat_map(|v| v.to_le_bytes()).collect(); + attr("channels", "chlist", &chlist); + attr("compression", "compression", &[0]); + attr("dataWindow", "box2i", &window); + attr("displayWindow", "box2i", &window); + attr("lineOrder", "lineOrder", &[0]); + attr("pixelAspectRatio", "float", &1f32.to_le_bytes()); + attr("screenWindowCenter", "v2f", &[0; 8]); + attr("screenWindowWidth", "float", &1f32.to_le_bytes()); + out.push(0); + let line_bytes = 4 * W as usize * chans.len(); + let table_end = out.len() + 8 * H as usize; + for y in 0..H as usize { + out.extend(((table_end + y * (8 + line_bytes)) as u64).to_le_bytes()); + } + for y in 0..H as i32 { + out.extend(y.to_le_bytes()); + out.extend((line_bytes as i32).to_le_bytes()); + for (_, left, right) in &chans { + for x in 0..W { + out.extend(if x < 16 { left } else { right }.to_le_bytes()); + } + } + } + out +} + +fn y_only() -> Vec { + exr(&[("Y", 0.7, 0.2)]) +} +fn z_only() -> Vec { + exr(&[("Z", 5.0, 0.25)]) +} +fn y_a() -> Vec { + exr(&[("Y", 0.7, 0.2), ("A", 1.0, 0.5)]) +} +fn rgba() -> Vec { + exr(&[("R", 0.8, 0.1), ("G", 0.4, 0.1), ("B", 0.2, 0.1), ("A", 1.0, 0.5)]) +} + +/// File > Open: the file from disk. +fn open_file(tag: &str, bytes: &[u8]) -> ImportResult { + let path = std::env::temp_dir().join(format!("photocraft-14069-{tag}-{}.exr", std::process::id())); + std::fs::write(&path, bytes).unwrap(); + let result = import_file("f.exr", &path, &ImportOptions::default(), &Interrupt::NONE); + let _ = std::fs::remove_file(&path); + result.unwrap() +} + +/// File > Open EXR Parts... with every listed entry chosen. +fn open_parts(bytes: &[u8]) -> ImportResult { + let entries = exr_parts::entries(bytes).unwrap(); + let selection = exr_parts::Selection { parts: entries.iter().map(|e| e.name.clone()).collect(), groups: vec![], view: "both".into(), precomp: false }; + exr_parts::import("p", bytes, &selection).unwrap() +} + +fn px(doc: &Document, x: i32, y: i32) -> Vec { + doc.layers[0].surface().unwrap().read_region(Rect::from_xywh(x, y, 1, 1)) +} + +/// RGB 32-bit, linear sRGB, (4,4) = `left`, (24,4) = `right` as RGBA. +fn assert_rgb(route: &str, r: &ImportResult, left: [f32; 4], right: [f32; 4]) { + let d = &r.document; + assert_eq!((d.mode, d.depth), (ColorMode::Rgb, SampleType::F32), "{route}: mode and depth"); + assert_eq!(d.icc_profile, Some(craft_cms::Builtin::LinearSrgb.profile().to_bytes()), "{route}: linear sRGB, not linear gray"); + assert_eq!(px(d, 4, 4), left, "{route}: left half"); + assert_eq!(px(d, 24, 4), right, "{route}: right half"); +} + +#[test] +fn luminance_exr_opens_as_rgb_through_file_open() { + assert_rgb("Y File > Open", &open_file("y", &y_only()), [0.7, 0.7, 0.7, 1.0], [0.2, 0.2, 0.2, 1.0]); + assert_rgb("Z File > Open", &open_file("z", &z_only()), [5.0, 5.0, 5.0, 1.0], [0.25, 0.25, 0.25, 1.0]); + assert_rgb("Y+A File > Open", &open_file("ya", &y_a()), [0.7, 0.7, 0.7, 1.0], [0.2, 0.2, 0.2, 0.5]); +} + +#[test] +fn luminance_and_data_exr_open_as_rgb_through_open_exr_parts() { + assert_rgb("Y parts", &open_parts(&y_only()), [0.7, 0.7, 0.7, 1.0], [0.2, 0.2, 0.2, 1.0]); + assert_rgb("Z parts", &open_parts(&z_only()), [5.0, 5.0, 5.0, 1.0], [0.25, 0.25, 0.25, 1.0]); + assert_rgb("Y+A parts", &open_parts(&y_a()), [0.7, 0.7, 0.7, 1.0], [0.2, 0.2, 0.2, 0.5]); +} + +#[test] +fn rgba_exr_opens_as_before() { + let left = [0.8, 0.4, 0.2, 1.0]; + let right = [0.1, 0.1, 0.1, 0.5]; + assert_rgb("RGBA File > Open", &open_file("rgba", &rgba()), left, right); + assert_rgb("RGBA parts", &open_parts(&rgba()), left, right); + assert_rgb("RGBA bytes", &import("f.exr", &rgba()).unwrap(), left, right); +} + +/// Open point: the whole-file decoder in `flat.rs` (the bytes import, and File > Open's +/// fallback for headers the band decoder refuses) still maps a gray EXR to Grayscale. That file +/// is outside this item's scope until the epic owner agrees. +#[test] +#[ignore = "flat.rs still opens gray EXRs as Grayscale (#14069 open point)"] +fn luminance_exr_opens_as_rgb_through_whole_file_decoder() { + assert_rgb("Y bytes", &import("f.exr", &y_only()).unwrap(), [0.7, 0.7, 0.7, 1.0], [0.2, 0.2, 0.2, 1.0]); + assert_rgb("Z bytes", &import("f.exr", &z_only()).unwrap(), [5.0, 5.0, 5.0, 1.0], [0.25, 0.25, 0.25, 1.0]); + assert_rgb("Y+A bytes", &import("f.exr", &y_a()).unwrap(), [0.7, 0.7, 0.7, 1.0], [0.2, 0.2, 0.2, 0.5]); +} diff --git a/crates/io/tests/it/exr_part_profile.rs b/crates/io/tests/it/exr_part_profile.rs index 1f7d4fbb70..35d4561a2b 100644 --- a/crates/io/tests/it/exr_part_profile.rs +++ b/crates/io/tests/it/exr_part_profile.rs @@ -4,7 +4,8 @@ use craft_cms::{Builtin, ColorSpace, Intent, Profile, Transform}; use photocraft_codecs::{self as codecs, ChannelLayout, Format, Image, SampleType as CodecSample}; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::Document; -use photocraft_io::{ExportOptions, ImportResult, export, exr_parts, import}; +use photocraft_io::{ExportOptions, ImportOptions, ImportResult, export, exr_parts, import, import_file}; +use photocraft_raster::Interrupt; fn exr(layout: ChannelLayout, depth: CodecSample) -> Vec { // Exactly representable in half precision, including negative and HDR luminance. @@ -36,34 +37,48 @@ fn samples(doc: &Document) -> Vec { doc.layers[0].surface().unwrap().read_region(doc.bounds()) } +/// File > Open of the file from disk (the band decoder). +fn opened(bytes: &[u8]) -> ImportResult { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let path = std::env::temp_dir().join(format!("photocraft-exr-part-profile-{}-{n}.exr", std::process::id())); + std::fs::write(&path, bytes).unwrap(); + let result = import_file("ordinary.exr", &path, &ImportOptions::default(), &Interrupt::NONE); + let _ = std::fs::remove_file(&path); + result.unwrap() +} + +/// A gray part opens as RGB 32-bit linear sRGB like File > Open (#14069). #[test] fn selected_gray_exr_part_keeps_linear_profile_and_float_samples() { for depth in [CodecSample::F16, CodecSample::F32] { for layout in [ChannelLayout::Gray, ChannelLayout::GrayA] { let bytes = exr(layout, depth); let selected = selected_part(&bytes); - let ordinary = import("ordinary.exr", &bytes).unwrap(); + let ordinary = opened(&bytes); let doc = &selected.document; - assert_eq!((doc.mode, doc.depth), (ColorMode::Grayscale, SampleType::F32)); + assert_eq!((doc.mode, doc.depth), (ColorMode::Rgb, SampleType::F32)); assert_eq!(doc.size, ordinary.document.size); assert_eq!(selected.warnings, ordinary.warnings); assert_eq!(selected.warnings.len(), usize::from(depth == CodecSample::F16)); - let expected = codecs::decode(&bytes).unwrap().convert(ChannelLayout::GrayA, CodecSample::F32).to_f32_samples().unwrap(); - assert_eq!(samples(doc), expected, "{layout:?} {depth:?}: samples and alpha stay unchanged"); + let expected = codecs::decode(&bytes).unwrap().convert(ChannelLayout::Rgba, CodecSample::F32).to_f32_samples().unwrap(); + assert_eq!(samples(doc), expected, "{layout:?} {depth:?}: gray in R, G and B; alpha unchanged"); assert_eq!(samples(doc), samples(&ordinary.document)); - assert_eq!(doc.icc_profile, Some(craft_cms::builtin::linear_gray().to_bytes()), "{layout:?} {depth:?}: linear luminance"); + assert_eq!(doc.icc_profile, Some(Builtin::LinearSrgb.profile().to_bytes()), "{layout:?} {depth:?}: linear light"); assert_eq!(doc.icc_profile, ordinary.document.icc_profile); - // The tagged samples convert to display gray, rather than being interpreted as sGray. + // The tagged samples convert to display sRGB, rather than being interpreted as sRGB. let profile = Profile::parse(doc.icc_profile.as_deref().unwrap()).unwrap(); - assert_eq!(profile.color_space, ColorSpace::Gray); - let transform = Transform::new(&profile, Builtin::SGray.profile(), Intent::RelativeColorimetric, false).unwrap(); + assert_eq!(profile.color_space, ColorSpace::Rgb); + let transform = Transform::new(&profile, Builtin::Srgb.profile(), Intent::RelativeColorimetric, false).unwrap(); let mut display = samples(doc); - transform.apply(&mut display, 2).unwrap(); + transform.apply(&mut display, 4).unwrap(); for i in [1, 2] { - let expected_gray = photocraft_color::convert::linear_to_srgb(expected[i * 2]); - assert!((display[i * 2] - expected_gray).abs() < 1e-4, "{layout:?} {depth:?}: display gray"); - assert_eq!(display[i * 2 + 1], expected[i * 2 + 1], "alpha is not gamma encoded"); + let expected_gray = photocraft_color::convert::linear_to_srgb(expected[i * 4]); + for c in 0..3 { + assert!((display[i * 4 + c] - expected_gray).abs() < 1e-4, "{layout:?} {depth:?}: display gray"); + } + assert_eq!(display[i * 4 + 3], expected[i * 4 + 3], "alpha is not gamma encoded"); } } } @@ -75,7 +90,7 @@ fn selected_gray_exr_part_exports_like_ordinary_import() { for layout in [ChannelLayout::Gray, ChannelLayout::GrayA] { let bytes = exr(layout, depth); let selected = selected_part(&bytes).document; - let ordinary = import("ordinary.exr", &bytes).unwrap().document; + let ordinary = opened(&bytes).document; for ext in ["exr", "tga"] { let output = export(&selected, ext, &ExportOptions::default()).unwrap(); let control = export(&ordinary, ext, &ExportOptions::default()).unwrap(); @@ -83,15 +98,15 @@ fn selected_gray_exr_part_exports_like_ordinary_import() { let control = codecs::decode(&control.bytes).unwrap(); assert_eq!(output.layout(), control.layout()); assert_eq!(output.to_normalized(), control.to_normalized(), "{layout:?} {depth:?} {ext}: same colours as File > Open"); - let output = output.convert(ChannelLayout::GrayA, CodecSample::F32).to_f32_samples().unwrap(); + let output = output.convert(ChannelLayout::Rgba, CodecSample::F32).to_f32_samples().unwrap(); let original = samples(&selected); if ext == "exr" { assert_eq!(output, original, "linear EXR samples, including negative/HDR and alpha, survive re-export"); } else { for i in [1, 2] { - let expected = photocraft_color::convert::linear_to_srgb(original[i * 2]); - assert!((output[i * 2] - expected).abs() <= 1.0 / 255.0, "TGA uses display-encoded gray"); - assert!((output[i * 2 + 1] - original[i * 2 + 1]).abs() <= 1.0 / 255.0, "TGA preserves alpha"); + let expected = photocraft_color::convert::linear_to_srgb(original[i * 4]); + assert!((output[i * 4] - expected).abs() <= 1.0 / 255.0, "TGA uses display-encoded values"); + assert!((output[i * 4 + 3] - original[i * 4 + 3]).abs() <= 1.0 / 255.0, "TGA preserves alpha"); } } } diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 6c4dc3481b..9b6239fa37 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -24,6 +24,7 @@ mod deflate_compatibility; mod effects_multi; mod exif_resolution; mod export_progress; +mod exr_open_luminance_rgb_tests; mod exr_part_profile; mod flat; mod flat_export_renderer; diff --git a/crates/io/tests/it/streaming_exr.rs b/crates/io/tests/it/streaming_exr.rs index 3c395bec3f..5535c447d8 100644 --- a/crates/io/tests/it/streaming_exr.rs +++ b/crates/io/tests/it/streaming_exr.rs @@ -4,8 +4,13 @@ use photocraft_raster::Interrupt; use std::sync::atomic::{AtomicBool, Ordering}; fn fixture(layout: ChannelLayout, sample: SampleType, compression: ExrCompression) -> Vec { + fixture_as(layout, layout, sample, compression) +} + +/// The `layout` fixture's samples written with the channels of `stored`. +fn fixture_as(layout: ChannelLayout, stored: ChannelLayout, sample: SampleType, compression: ExrCompression) -> Vec { let values: Vec = (0..31 * 35 * layout.channels()).map(|i| [-0.25, 4.0, 0.0, 0.0001, 0.5][i % 5]).collect(); - let image = Image::from_f32(31, 35, layout, &values).unwrap().convert(layout, sample); + let image = Image::from_f32(31, 35, layout, &values).unwrap().convert(stored, sample); photocraft_codecs::encode(&image, Format::OpenExr, &EncodeOptions { exr_compression: compression, ..Default::default() }).unwrap() } @@ -22,7 +27,14 @@ fn native_scanline_import_preserves_hdr_document_and_cancels_without_publication for compression in [ExrCompression::None, ExrCompression::Rle, ExrCompression::Zip1, ExrCompression::Zip16, ExrCompression::Piz] { let bytes = fixture(layout, sample, compression); std::fs::write(&path, &bytes).unwrap(); - let reference = photocraft_io::import("HDR", &bytes).unwrap(); + // Every EXR opens as RGB (#14069); the whole-file decoder still opens gray + // as Grayscale, so a gray file is compared with its RGB twin. + let rgb = match layout { + ChannelLayout::Gray => ChannelLayout::Rgb, + ChannelLayout::GrayA => ChannelLayout::Rgba, + other => other, + }; + let reference = photocraft_io::import("HDR", &fixture_as(layout, rgb, sample, compression)).unwrap(); let actual = open(&path, &Interrupt::NONE).unwrap(); { let a = &actual.document;