From ed23b65e6d8ef4a487e40f204a78f126302835fe Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 15 Nov 2026 01:42:41 -0600 Subject: [PATCH 01/15] =?UTF-8?q?Edit=20=E2=80=BA=20Fade=20names=20the=20s?= =?UTF-8?q?tep=20it=20fades,=20in=20its=20own=20menu=20group,=20with=20the?= =?UTF-8?q?=20same=20label=20in=20the=20right-click=20menu=20(#13803)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/engine/src/cmd/edit_menu_cmds.rs | 10 ++++ crates/ui-egui/src/canvas/canvas_tool_menu.rs | 6 ++- crates/ui-egui/src/menu_catalog.rs | 2 + crates/ui-egui/src/menus.rs | 3 ++ crates/ui-egui/src/menus/fade_label_tests.rs | 50 +++++++++++++++++++ crates/ui-egui/src/menus/items.rs | 4 ++ crates/ui-egui/src/menus/render.rs | 9 ++++ crates/ui-egui/src/menus/state.rs | 6 +++ 8 files changed, 88 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/src/menus/fade_label_tests.rs diff --git a/crates/engine/src/cmd/edit_menu_cmds.rs b/crates/engine/src/cmd/edit_menu_cmds.rs index b021ce0cc5..c4c8dd4c46 100644 --- a/crates/engine/src/cmd/edit_menu_cmds.rs +++ b/crates/engine/src/cmd/edit_menu_cmds.rs @@ -63,6 +63,16 @@ pub struct EditState { pub find_cursor: Option<(LayerId, usize, usize)>, } +/// Edit › Fade's menu label, as the reference application shows it (#13803): `Fade …` (`Fade Invert…`, `Fade Gaussian Blur…`) while Fade can run, plain +/// `Fade…` when it can't. +pub fn fade_menu_label(s: &Session) -> String { + match s.edit_state.fade.as_ref().filter(|_| can_fade(s).is_ok()) { + Some(f) => format!("Fade {}…", f.label), + None => "Fade…".into(), + } +} + /// Commands whose result Edit › Fade can blend back against the previous state. fn fadeable(id: &str) -> bool { id.starts_with("filter.") diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index b7a9a99cdb..55249653ff 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -1783,8 +1783,10 @@ pub fn show(app: &mut PhotocraftApp, ctx: &Context) { }; let text = match row_label(app, &menu, label, command) { // Spelled out so `cargo xtask i18n-coverage` lists the new label. - "Free Transform Points" => tl!("Free Transform Points"), - key => tl!(key), + "Free Transform Points" => tl!("Free Transform Points").to_string(), + // The same label as Edit › Fade (#13803). + "Fade…" => crate::menus::fade_label(app), + key => tl!(key).to_string(), }; let item = egui::Button::selectable(mode_checked(app, &menu, command), text).min_size(egui::vec2(200.0, 20.0)); if ui.add_enabled(entry_enabled(app, &menu, command), item).clicked() { diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs index b4bf26a64e..e3821da0f7 100644 --- a/crates/ui-egui/src/menu_catalog.rs +++ b/crates/ui-egui/src/menu_catalog.rs @@ -79,6 +79,8 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["Edit"], "Undo", None, "edit.undo"), (&["Edit"], "Redo", None, "edit.redo"), (&["Edit"], "Toggle Last State", Some("Cmd+Alt+Z"), "edit.toggleLastState"), + // Fade sits in its own group, between separators (#13803). + (&["Edit"], "---", None, "---"), (&["Edit"], "Fade…", Some("Cmd+Shift+F"), "edit.fade"), (&["Edit"], "---", None, "---"), (&["Edit"], "Cut", None, "edit.cut"), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index ef489dd14d..a82948dbe2 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -7,6 +7,8 @@ use crate::state::DialogKind; mod bar; pub mod enable_rules; +#[cfg(test)] +mod fade_label_tests; mod invoke; mod items; pub mod menu_keys; @@ -28,6 +30,7 @@ pub(crate) use invoke::{invoke_unguarded, panel_alias}; pub(crate) use items::ItemCache; pub use items::{MenuItem, is_live, menu_items}; pub use render::alt_click; +pub use render::fade_label; #[cfg(test)] use render::submenu_enabled; #[cfg(test)] diff --git a/crates/ui-egui/src/menus/fade_label_tests.rs b/crates/ui-egui/src/menus/fade_label_tests.rs new file mode 100644 index 0000000000..ebc72cf173 --- /dev/null +++ b/crates/ui-egui/src/menus/fade_label_tests.rs @@ -0,0 +1,50 @@ +//! #13803: Edit › Fade names the step it fades (`Fade Invert…`), reads plain `Fade…` and is +//! greyed when nothing can be faded, sits in its own group between separators, and the selection +//! right-click menu and `ui.menu.list` show the same label. + +use super::*; +use serde_json::json; + +fn app() -> crate::PhotocraftApp { + let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app +} + +/// Edit › Fade's (label, enabled) as the menus and `ui.menu.list` report it. +fn fade(app: &crate::PhotocraftApp) -> (String, bool) { + let item = menu_items(app).into_iter().find(|i| i.id == "edit.fade").expect("Edit › Fade"); + (item.label, item.enabled) +} + +#[test] +fn the_label_names_the_step_it_fades() { + let mut app = app(); + app.run("image.adjustments.invert", json!({})).unwrap(); + assert_eq!(fade(&app), ("Fade Invert…".into(), true)); + app.run("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap(); + assert_eq!(fade(&app).0, "Fade Gaussian Blur…"); + app.run("paint.stroke", json!({"points": [[8, 20], [56, 20]], "size": 6})).unwrap(); + assert_eq!(fade(&app).0, "Fade Brush Tool…"); + assert_eq!(fade_label(&app), "Fade Brush Tool…", "the right-click menu's row shows the same"); +} + +#[test] +fn nothing_to_fade_reads_plain_fade_and_is_greyed() { + let mut app = app(); + assert_eq!(fade(&app), ("Fade…".into(), false), "a fresh document"); + app.run("image.adjustments.invert", json!({})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + assert_eq!(fade(&app), ("Fade…".into(), false), "after Deselect"); + assert_eq!(fade_label(&app), "Fade…"); + let empty = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + assert_eq!(fade(&empty), ("Fade…".into(), false), "no document"); +} + +#[test] +fn fade_sits_in_its_own_group() { + let items = menu_items(&app()); + let edit: Vec<&str> = items.iter().filter(|i| i.path.len() == 1 && i.path[0] == "Edit").map(|i| i.label.as_str()).take(7).collect(); + assert_eq!(edit, ["Undo", "Redo", "Toggle Last State", "---", "Fade…", "---", "Cut"], "{edit:?}"); +} diff --git a/crates/ui-egui/src/menus/items.rs b/crates/ui-egui/src/menus/items.rs index 7b441da8d2..695e3715a2 100644 --- a/crates/ui-egui/src/menus/items.rs +++ b/crates/ui-egui/src/menus/items.rs @@ -116,6 +116,10 @@ pub fn menu_items(app: &PhotocraftApp) -> Vec { { item.label = "Merge Group".into(); } + // Edit › Fade names the step it fades (#13803). + if let Some(item) = items.iter_mut().find(|i| i.id == "edit.fade") { + item.label = photocraft_engine::edit_menu_cmds::fade_menu_label(&app.session); + } // The File quick-export command uses the format selected in Export Preferences. // On the web it intentionally downloads PNG until the quick-export service supports // the other formats; the Layer quick-export command also always produces PNG. diff --git a/crates/ui-egui/src/menus/render.rs b/crates/ui-egui/src/menus/render.rs index 82a824cf48..096089742e 100644 --- a/crates/ui-egui/src/menus/render.rs +++ b/crates/ui-egui/src/menus/render.rs @@ -150,3 +150,12 @@ pub fn alt_click(id: String, alt: bool) -> String { _ => id, } } + +/// Edit › Fade's label as the menus show it, translated (#13803): `Fade Invert…` while Fade can +/// run, `Fade…` when it can't. The selection right-click menu shows the same. +pub fn fade_label(app: &crate::PhotocraftApp) -> String { + match crate::menus::menu_items(app).into_iter().find(|i| i.id == "edit.fade") { + Some(item) => translated_menu_label(crate::i18n::current(), &item), + None => tl!("Fade…").to_string(), + } +} diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index e4bdc7a66c..ac9d7d8d59 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -238,5 +238,11 @@ pub(super) fn translated_menu_label(lang: crate::i18n::Lang, item: &MenuItem) -> { return crate::i18n::tr_id(lang, &item.id, "Quick Export as PNG").replace("PNG", fmt); } + // "Fade Invert…": the translated "Fade…" around the step's own history name (#13803). + if item.id == "edit.fade" + && let Some(step) = item.label.strip_prefix("Fade ").and_then(|l| l.strip_suffix('…')) + { + return crate::i18n::tr_id(lang, &item.id, "Fade…").replace('…', &format!(" {step}…")); + } crate::i18n::tr_id(lang, &item.id, &item.label).to_string() } From 51ae4f3849c5f0696651a5ece50aff7fea4b4bab Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 15 Nov 2026 08:28:52 -0600 Subject: [PATCH 02/15] Fade menu label: read from the engine, so a hidden Edit row does not change the right-click menu --- crates/ui-egui/src/menus/fade_label_tests.rs | 11 +++++++++++ crates/ui-egui/src/menus/render.rs | 8 +++----- crates/ui-egui/src/menus/state.rs | 16 +++++++++++----- 3 files changed, 25 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/menus/fade_label_tests.rs b/crates/ui-egui/src/menus/fade_label_tests.rs index ebc72cf173..5f3f4eed7a 100644 --- a/crates/ui-egui/src/menus/fade_label_tests.rs +++ b/crates/ui-egui/src/menus/fade_label_tests.rs @@ -48,3 +48,14 @@ fn fade_sits_in_its_own_group() { let edit: Vec<&str> = items.iter().filter(|i| i.path.len() == 1 && i.path[0] == "Edit").map(|i| i.label.as_str()).take(7).collect(); assert_eq!(edit, ["Undo", "Redo", "Toggle Last State", "---", "Fade…", "---", "Cut"], "{edit:?}"); } + +/// CodeRabbit on #15091: the label comes from the engine, so hiding Fade in Edit › Menus (which drops its row +/// from the menu list) does not turn the right-click menu's Fade back into plain `Fade…`. +#[test] +fn a_hidden_menu_row_does_not_change_the_right_click_label() { + let mut app = app(); + app.run("image.adjustments.invert", json!({})).unwrap(); + app.session.prefs.edit(|p| p.menus.hidden.push("edit.fade".into())); + assert!(menu_items(&app).iter().all(|i| i.id != "edit.fade"), "the row is hidden from the menu list"); + assert_eq!(fade_label(&app), "Fade Invert…"); +} diff --git a/crates/ui-egui/src/menus/render.rs b/crates/ui-egui/src/menus/render.rs index 096089742e..5e09e30d24 100644 --- a/crates/ui-egui/src/menus/render.rs +++ b/crates/ui-egui/src/menus/render.rs @@ -152,10 +152,8 @@ pub fn alt_click(id: String, alt: bool) -> String { } /// Edit › Fade's label as the menus show it, translated (#13803): `Fade Invert…` while Fade can -/// run, `Fade…` when it can't. The selection right-click menu shows the same. +/// run, `Fade…` when it can't. The selection right-click menu shows the same. Read from the engine, +/// not from the menu list, so hiding Fade in Edit › Menus does not change the right-click menu. pub fn fade_label(app: &crate::PhotocraftApp) -> String { - match crate::menus::menu_items(app).into_iter().find(|i| i.id == "edit.fade") { - Some(item) => translated_menu_label(crate::i18n::current(), &item), - None => tl!("Fade…").to_string(), - } + super::state::translated_fade_label(crate::i18n::current(), &photocraft_engine::edit_menu_cmds::fade_menu_label(&app.session)) } diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index ac9d7d8d59..6966c325e2 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -238,11 +238,17 @@ pub(super) fn translated_menu_label(lang: crate::i18n::Lang, item: &MenuItem) -> { return crate::i18n::tr_id(lang, &item.id, "Quick Export as PNG").replace("PNG", fmt); } - // "Fade Invert…": the translated "Fade…" around the step's own history name (#13803). - if item.id == "edit.fade" - && let Some(step) = item.label.strip_prefix("Fade ").and_then(|l| l.strip_suffix('…')) - { - return crate::i18n::tr_id(lang, &item.id, "Fade…").replace('…', &format!(" {step}…")); + if item.id == "edit.fade" { + return translated_fade_label(lang, &item.label); } crate::i18n::tr_id(lang, &item.id, &item.label).to_string() } + +/// Edit › Fade's `label` translated: `Fade Invert…` is the translated "Fade…" around the step's own +/// history name (#13803), plain `Fade…` just the translation. +pub(super) fn translated_fade_label(lang: crate::i18n::Lang, label: &str) -> String { + match label.strip_prefix("Fade ").and_then(|l| l.strip_suffix('…')) { + Some(step) => crate::i18n::tr_id(lang, "edit.fade", "Fade…").replace('…', &format!(" {step}…")), + None => crate::i18n::tr_id(lang, "edit.fade", label).to_string(), + } +} From e309f401b79cfed241739ae32b1ff6a133447d31 Mon Sep 17 00:00:00 2001 From: NaufalDzz Date: Tue, 24 Nov 2026 16:53:36 +0000 Subject: [PATCH 03/15] Info panel: update hover_doc from the canvas pass (#16654) Co-authored-by: OpenBot <335604065+openbotgit[bot]@users.noreply.github.com> --- crates/ui-egui/src/canvas/document_display.rs | 15 +++++ crates/ui-egui/src/panels/info.rs | 57 +++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/crates/ui-egui/src/canvas/document_display.rs b/crates/ui-egui/src/canvas/document_display.rs index fe02adcd58..63df49f930 100644 --- a/crates/ui-egui/src/canvas/document_display.rs +++ b/crates/ui-egui/src/canvas/document_display.rs @@ -316,6 +316,21 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, let mut overlay_context = None; let shown = canvas.show_at(ui, rect, |ui, body| { let Some(space) = canvas_space(&body.env) else { return }; + if !measuring && app.session.active_index() == Some(idx) { + let hovered = ui + .input(|i| i.pointer.hover_pos()) + .filter(|pos| space.view.rect.contains(*pos) && ui.ctx().layer_id_at(*pos).is_none_or(|layer| layer == ui.layer_id())) + .map(|pos| { + let at = space.view.to_doc(pos); + [at.x, at.y] + }); + let next = if primary { hovered } else { hovered.or(app.hover_doc) }; + if app.hover_doc != next { + app.hover_doc = next; + // The Info panel may have already drawn earlier in this frame. + ctx.request_repaint(); + } + } pasteboards(app, ui, body.rect, idx, border, label.clone()); guides = super::rulers::show(app, ui, host, ruler_guide(&body.env)); selection_controls(app, ui, body.rect, idx, &label); diff --git a/crates/ui-egui/src/panels/info.rs b/crates/ui-egui/src/panels/info.rs index 4bd9e0b9af..17b35899a8 100644 --- a/crates/ui-egui/src/panels/info.rs +++ b/crates/ui-egui/src/panels/info.rs @@ -229,6 +229,63 @@ mod tests { app.run("view.colorSamplers.add", json!({"x": 8, "y": 8})).unwrap(); assert_eq!(sampler_readouts(&mut app).len(), 2, "so does a new sampler"); } + + /// Hovering the canvas or dragging the Eyedropper updates `hover_doc` and the Info panel's + /// colour and position readouts; leaving the canvas clears them (#16654). + #[test] + fn canvas_hover_and_eyedropper_drag_update_info_readings() { + use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + use crate::canvas::document_display::CanvasHost; + use crate::state::{Tool, View}; + + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = app.ctx().clone(); + app.run("file.new", json!({"width": 100, "height": 100, "background": "white"})).unwrap(); + app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "pixels"})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session + .edit("blue half", |doc, active| { + let id = active.unwrap(); + let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + surf.fill_rect(photocraft_geom::Rect::new(50, 0, 100, 100), &[0.0, 0.0, 1.0, 1.0]); + Ok(()) + }) + .unwrap(); + let mut view = View { zoom: 1.0, center: [50.0, 50.0], doc_size: [100, 100], ..Default::default() }; + view.clear_pending(); + let rect = Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)); + let step = |app: &mut PhotocraftApp, events: Vec| { + let input = RawInput { screen_rect: Some(rect), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + crate::canvas::canvas_view(app, ui, CanvasHost::main(0), rect, view.clone(), true); + }); + out.textures_delta.clear(); + }; + + // Hover over the red half: Info reports red and (20, 30). + step(&mut app, vec![Event::PointerMoved(pos2(20.5, 30.5))]); + let r = readings(&mut app, &[]); + assert_eq!(r.color.map(|c| c.rgb), Some([255, 0, 0]), "hovered red pixel"); + let pos = r.position.expect("hovered position"); + assert!(pos[0].as_str().starts_with("20") && pos[1].as_str().starts_with("30"), "got {pos:?}"); + + // Dragging the Eyedropper into the blue half keeps updating the Info readout. + app.ui.tool = Tool::Eyedropper; + step(&mut app, vec![Event::PointerButton { pos: pos2(20.5, 30.5), button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]); + step(&mut app, vec![Event::PointerMoved(pos2(75.5, 40.5))]); + let r = readings(&mut app, &[]); + assert_eq!(r.color.map(|c| c.rgb), Some([0, 0, 255]), "dragged blue pixel"); + let pos = r.position.expect("dragged position"); + assert!(pos[0].as_str().starts_with("75") && pos[1].as_str().starts_with("40"), "got {pos:?}"); + + // Releasing and leaving the canvas clears the readings. + step(&mut app, vec![Event::PointerButton { pos: pos2(75.5, 40.5), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }]); + step(&mut app, vec![Event::PointerGone]); + let r = readings(&mut app, &[]); + assert_eq!(r.color, None, "cleared after leaving canvas"); + assert_eq!(r.position, None, "position cleared after leaving canvas"); + } } #[cfg(test)] From 7b86f6c295b9fa5ed8b3576e0bfbca53dad061a3 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:23:47 +0100 Subject: [PATCH 04/15] Background from Layer: greyed with several layers selected (#17306) With two or more layers selected the command is disabled and a call without a layer is refused with the reason; a call that names its layer converts that layer as before. --- crates/engine-core/src/cmd/background_cmds.rs | 25 +++- crates/engine-core/src/session/execute.rs | 5 + .../it/background_from_layer_multi_select.rs | 133 ++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + 4 files changed, 162 insertions(+), 2 deletions(-) create mode 100644 crates/engine/tests/it/background_from_layer_multi_select.rs diff --git a/crates/engine-core/src/cmd/background_cmds.rs b/crates/engine-core/src/cmd/background_cmds.rs index b1fe7ce2cc..67685db92e 100644 --- a/crates/engine-core/src/cmd/background_cmds.rs +++ b/crates/engine-core/src/cmd/background_cmds.rs @@ -12,7 +12,10 @@ use serde_json::{Value, json}; use crate::commands::CommandSpec; use crate::{EngineError, Result, Session}; -const CMD: &str = "layer.new.backgroundFromLayer"; +pub(crate) const CMD: &str = "layer.new.backgroundFromLayer"; + +/// Why Background from Layer is greyed with two or more layers selected (#17306). +const SEVERAL_SELECTED: &str = "several layers selected; select one layer to make it the Background"; /// The document's Background layer, if it has one (always the bottom layer). pub(crate) fn background_id(doc: &Document) -> Option { @@ -41,7 +44,19 @@ fn convertible(l: &Layer) -> std::result::Result<(), String> { } } +/// The menu's precondition: greyed, as in the reference, with two or more layers selected +/// (#17306); otherwise [`can_convert_active`]. fn can_convert(s: &Session) -> std::result::Result<(), String> { + let d = s.active().ok_or("no document open")?; + if d.selected_layers().len() > 1 { + return Err(SEVERAL_SELECTED.into()); + } + can_convert_active(s) +} + +/// Can the active layer become the Background? A call that names its `"layer"` (scripts, +/// actions) is checked with this alone: it converts that layer whatever else is selected. +pub(crate) fn can_convert_active(s: &Session) -> std::result::Result<(), String> { let d = s.active().ok_or("no document open")?; if background_id(&d.doc).is_some() { return Err("the document already has a Background layer".into()); @@ -52,7 +67,13 @@ fn can_convert(s: &Session) -> std::result::Result<(), String> { fn background_from_layer(s: &mut Session, p: &Value) -> Result { let id = match p.get("layer") { - None | Some(Value::Null) => crate::commands::layer_param(s, p)?, + None | Some(Value::Null) => { + // Without a named layer the selection is the target, and it must be one layer. + if s.active().is_some_and(|d| d.selected_layers().len() > 1) { + return Err(EngineError::Disabled(CMD.into(), SEVERAL_SELECTED.into())); + } + crate::commands::layer_param(s, p)? + } Some(v) => LayerId(v.as_u64().ok_or_else(|| EngineError::BadParams { cmd: CMD.into(), msg: "`layer` must be a layer id".into() })?), }; let bg = s.tools.background; diff --git a/crates/engine-core/src/session/execute.rs b/crates/engine-core/src/session/execute.rs index 6bbecf98ff..33dd3e5d80 100644 --- a/crates/engine-core/src/session/execute.rs +++ b/crates/engine-core/src/session/execute.rs @@ -159,6 +159,11 @@ impl Session { if let Some(why) = bitmap_mode_refusal(self, spec.id, params) { return Err(why.into()); } + // A named layer is converted whatever else is selected; the menu (no params) is greyed + // with several layers selected (#17306). + if spec.id == crate::background_cmds::CMD && params.get("layer").is_some_and(|l| !l.is_null()) { + return crate::background_cmds::can_convert_active(self); + } channel_cmds::mask_target_enabled(self, spec.id, params).unwrap_or_else(|| (spec.enabled)(self)) } diff --git a/crates/engine/tests/it/background_from_layer_multi_select.rs b/crates/engine/tests/it/background_from_layer_multi_select.rs new file mode 100644 index 0000000000..1c1bca541f --- /dev/null +++ b/crates/engine/tests/it/background_from_layer_multi_select.rs @@ -0,0 +1,133 @@ +//! Layer › New › Background from Layer with several layers selected (#17306). +//! +//! Measured in the reference: with two layers selected the menu item is greyed. With one layer it +//! is live for pixel, type, smart object, fill and shape layers and greyed for groups and +//! adjustment layers. A script or action that names the layer (`"layer": id`) converts that +//! layer, whatever is selected. + +use photocraft_doc::LayerId; +use photocraft_engine::Session; +use serde_json::{Value, json}; + +const CMD: &str = "layer.new.backgroundFromLayer"; + +/// A document without a Background: a transparent "Layer 1" plus A and B on top. +fn no_background() -> (Session, [LayerId; 3]) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 12, "background": "transparent"})).unwrap(); + let base = s.active().unwrap().active_layer.unwrap(); + let a = new_layer(&mut s, "A"); + let b = new_layer(&mut s, "B"); + (s, [base, a, b]) +} + +fn new_layer(s: &mut Session, name: &str) -> LayerId { + LayerId(s.execute("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap()) +} + +fn ids(r: &Value) -> LayerId { + LayerId(r["layer"].as_u64().unwrap()) +} + +fn order(s: &Session) -> Vec { + s.active().unwrap().doc.layers.iter().map(|l| l.id).collect() +} + +fn background(s: &Session) -> Option { + s.active().unwrap().doc.background().map(|l| l.id) +} + +#[test] +fn two_selected_layers_grey_the_command_and_a_call_without_layer_is_refused() { + let (mut s, [_, a, b]) = no_background(); + s.execute("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + assert_eq!(s.active().unwrap().selected_layers().len(), 2); + assert!(!s.is_enabled(CMD), "greyed with two layers selected"); + let why = s.disabled_reason(CMD).unwrap(); + assert!(why.contains("layers selected"), "the reason names the multi-selection: {why}"); + + let before = order(&s); + let revision = s.active().unwrap().revision; + let err = s.execute(CMD, json!({})).unwrap_err().to_string(); + assert!(err.contains("layers selected"), "the error names the reason: {err}"); + assert_eq!(order(&s), before, "no layer moved"); + assert_eq!(background(&s), None, "no Background made"); + assert_eq!(s.active().unwrap().revision, revision, "the document did not change"); + + // Three layers selected: greyed too. + let (mut s, [base, a, b]) = no_background(); + s.execute("layer.select", json!({"layers": [base.0, a.0, b.0]})).unwrap(); + assert!(!s.is_enabled(CMD)); + assert!(s.execute(CMD, json!({"layer": null})).is_err(), "a null layer is the selection too"); +} + +#[test] +fn an_explicit_layer_converts_that_layer_with_several_selected() { + // The named layer is one of the selected ones. + let (mut s, [_, a, b]) = no_background(); + s.execute("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + let r = s.execute(CMD, json!({"layer": a.0})).unwrap(); + assert_eq!(ids(&r), a); + assert_eq!(background(&s), Some(a), "A is the Background"); + assert_eq!(order(&s)[0], a, "at the bottom"); + + // The named layer is outside the selection. + let (mut s, [base, a, b]) = no_background(); + s.execute("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + s.execute(CMD, json!({"layer": base.0})).unwrap(); + assert_eq!(background(&s), Some(base)); +} + +#[test] +fn one_selected_layer_keeps_todays_rules() { + let live = |make: &dyn Fn(&mut Session)| { + let (mut s, _) = no_background(); + make(&mut s); + assert_eq!(s.active().unwrap().selected_layers().len(), 1); + s.is_enabled(CMD) + }; + assert!(live(&|_| {}), "pixel layer"); + assert!( + live(&|s| { + s.execute("type.create", json!({"x": 2, "y": 10, "text": "I", "size": 8})).unwrap(); + }), + "type layer" + ); + assert!( + live(&|s| { + s.execute("edit.fill", json!({"contents": "black"})).unwrap(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + }), + "smart object" + ); + assert!( + live(&|s| { + s.execute("layer.newFillLayer.solidColor", json!({"color": "#4080c0"})).unwrap(); + }), + "solid colour fill layer" + ); + assert!( + live(&|s| { + s.execute("shape.create", json!({"kind": "rect", "rect": [2, 2, 6, 6]})).unwrap(); + }), + "shape layer" + ); + assert!( + !live(&|s| { + s.execute("layer.new.group", json!({})).unwrap(); + }), + "group" + ); + assert!( + !live(&|s| { + s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + }), + "adjustment layer" + ); + + // And one selected pixel layer converts as before. + let (mut s, [_, a, _]) = no_background(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute(CMD, json!({})).unwrap(); + assert_eq!(background(&s), Some(a)); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 44bad7c952..f5205efc17 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -37,6 +37,7 @@ mod atn_video_frames; mod auto_blend_layer_kinds; mod average_smart; mod background_and_mask_depth; +mod background_from_layer_multi_select; mod background_job_target; mod background_layer_consistency; mod brush_smoothing; From 82304e178e3408ffd8678068b180576d98ab2dce Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:41:16 +0100 Subject: [PATCH 05/15] Frames: Convert to Frame resizes around the layer's centre (#17325) A new width or height moves the frame's origin by half the change, so the frame keeps the layer's centre as in the reference. --- crates/engine-core/src/cmd/frame_cmds.rs | 7 ++- .../cmd/frame_cmds/convert_resize_tests.rs | 55 +++++++++++++++++++ .../engine-core/src/cmd/frame_cmds/tests.rs | 3 +- 3 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 crates/engine-core/src/cmd/frame_cmds/convert_resize_tests.rs diff --git a/crates/engine-core/src/cmd/frame_cmds.rs b/crates/engine-core/src/cmd/frame_cmds.rs index 335358c3a2..db89fba03d 100644 --- a/crates/engine-core/src/cmd/frame_cmds.rs +++ b/crates/engine-core/src/cmd/frame_cmds.rs @@ -235,7 +235,10 @@ fn convert(s: &mut Session, p: &Value) -> Result { Some(v) => v.as_f64().filter(|v| v.is_finite() && (1.0..=300_000.0).contains(v)).ok_or_else(|| bad(format!("{k} must be 1..=300000"))), } }; - f.transform.m = [n("width", a)?, b, c, n("height", d)?, x, y]; + // The frame keeps the layer's centre, as in the reference (#17325): a new width or height moves the + // origin by half the change. `normalized` gives an axis-aligned transform, so `b` and `c` are 0. + let (w, h) = (n("width", a)?, n("height", d)?); + f.transform.m = [w, b, c, h, x + (a - w) / 2.0, y + (d - h) / 2.0]; } if !f.valid() { return Err(bad("invalid converted frame")); @@ -396,4 +399,6 @@ pub fn specs() -> Vec { #[cfg(test)] mod content_name_tests; #[cfg(test)] +mod convert_resize_tests; +#[cfg(test)] mod tests; diff --git a/crates/engine-core/src/cmd/frame_cmds/convert_resize_tests.rs b/crates/engine-core/src/cmd/frame_cmds/convert_resize_tests.rs new file mode 100644 index 0000000000..ca863c5703 --- /dev/null +++ b/crates/engine-core/src/cmd/frame_cmds/convert_resize_tests.rs @@ -0,0 +1,55 @@ +//! #17325: Convert to Frame with a new width or height resizes the frame around the layer's centre, as the reference +//! application does; without either the frame keeps the layer's bounds. + +use super::*; + +/// A 400 × 200 document with a shape layer "Rect" covering 200..280 × 60..120. +fn rect_layer() -> (Session, u64) { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); + let r = s.execute("shape.create", json!({"kind": "rect", "rect": [200, 60, 80, 60], "fill": "#e07020"})).unwrap(); + let id = r["layer"].as_u64().unwrap(); + s.execute("layer.setProps", json!({"layer": id, "name": "Rect"})).unwrap(); + (s, id) +} + +/// The frame's rect as (x0, x1, y0, y1). +fn frame_rect(s: &Session, id: u64) -> (f64, f64, f64, f64) { + let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); + let [w, _, _, h, x, y] = l.frame.as_ref().expect("a frame").transform.m; + (x, x + w, y, y + h) +} + +#[test] +fn the_layer_has_the_measured_bounds() { + let (mut s, id) = rect_layer(); + s.execute("layer.frame.convert", json!({"layer": id})).unwrap(); + assert_eq!(frame_rect(&s, id), (200.0, 280.0, 60.0, 120.0), "without width or height the frame keeps the layer bounds"); +} + +#[test] +fn a_new_width_grows_around_the_centre() { + let (mut s, id) = rect_layer(); + let r = s.execute("layer.frame.convert", json!({"layer": id, "name": "MyFrame", "width": 160})).unwrap(); + assert_eq!(r["name"], "MyFrame"); + assert_eq!(frame_rect(&s, id), (160.0, 320.0, 60.0, 120.0)); +} + +#[test] +fn a_new_height_grows_around_the_centre() { + let (mut s, id) = rect_layer(); + s.execute("layer.frame.convert", json!({"layer": id, "height": 100})).unwrap(); + assert_eq!(frame_rect(&s, id), (200.0, 280.0, 40.0, 140.0)); +} + +#[test] +fn both_shrink_around_the_centre_and_the_mask_follows() { + let (mut s, id) = rect_layer(); + s.execute("layer.frame.convert", json!({"layer": id, "width": 40, "height": 20})).unwrap(); + assert_eq!(frame_rect(&s, id), (220.0, 260.0, 80.0, 100.0)); + let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); + let path = &l.vector_mask.as_ref().unwrap().path; + let coverage = |x: i32, y: i32| photocraft_vector::path_coverage(path, photocraft_geom::Rect::new(x, y, x + 1, y + 1))[0]; + assert_eq!(coverage(240, 90), 1.0, "the centre is inside"); + assert_eq!(coverage(210, 90), 0.0, "the old left edge is outside"); +} diff --git a/crates/engine-core/src/cmd/frame_cmds/tests.rs b/crates/engine-core/src/cmd/frame_cmds/tests.rs index d672a24ff9..a09ada1282 100644 --- a/crates/engine-core/src/cmd/frame_cmds/tests.rs +++ b/crates/engine-core/src/cmd/frame_cmds/tests.rs @@ -247,7 +247,8 @@ fn converting_a_shape_uses_its_outline_and_leaves_an_empty_frame() { let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); assert_eq!(l.name, "Portrait"); assert!(l.children().unwrap().is_empty()); - assert_eq!(l.frame.as_ref().unwrap().transform.m, [20., 0., 0., 25., 10., 15.]); + // The ellipse's 40 × 30 box at (10, 15) resized to 20 × 25 around its centre (30, 30) (#17325). + assert_eq!(l.frame.as_ref().unwrap().transform.m, [20., 0., 0., 25., 20., 17.5]); assert_eq!(TestMask(l.vector_mask.as_ref().unwrap().path.clone()).value(10, 15), 0.0); assert!(s.undo()); assert!(matches!(s.active().unwrap().doc.layer(LayerId(id)).unwrap().content, LayerContent::Shape(_))); From 2ad09cd72a0cf554a413799f795d9f7d80441d89 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:44:19 +0100 Subject: [PATCH 06/15] Record Measurements: warn and record nothing when no data point is enabled for the source (#17407) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Recording with no data point set for the measured source (Selection, Ruler Tool or Count Tool) wrote an empty "Measurement N" row. The command now returns the reference application's warning and records nothing; the menu shows it as an alert with OK and "Set Data Points…", which opens Select Data Points. --- crates/engine-core/src/cmd/analysis_cmds.rs | 28 +++++++ .../record_no_data_points_tests.rs | 72 ++++++++++++++++++ crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/tools/analysis/mod.rs | 51 ++++++++++++- .../record_no_data_points_alert_tests.rs | 76 +++++++++++++++++++ 5 files changed, 226 insertions(+), 2 deletions(-) create mode 100644 crates/engine-core/src/cmd/analysis_cmds/record_no_data_points_tests.rs create mode 100644 crates/ui-egui/src/tools/analysis/record_no_data_points_alert_tests.rs diff --git a/crates/engine-core/src/cmd/analysis_cmds.rs b/crates/engine-core/src/cmd/analysis_cmds.rs index 9eb24468ea..5a729e5a0b 100644 --- a/crates/engine-core/src/cmd/analysis_cmds.rs +++ b/crates/engine-core/src/cmd/analysis_cmds.rs @@ -1058,6 +1058,27 @@ fn feature_values(m: &mut Map, f: &Feature, count: usize, factor: m.insert("histogram".into(), json!(f.histogram)); } +/// The start of Record Measurements' error when no data point is enabled for the source it records; the source's +/// name and a full stop follow (#17407). +pub const NO_DATA_POINTS: &str = "There are no measurement data points currently enabled for the "; + +/// The second line of that alert. +pub const NO_DATA_POINTS_DETAIL: &str = "Data points must be set before measurements can be recorded."; + +/// The name the alert gives source `source` (`selection`, `ruler` or `count`). +pub fn data_points_source_name(source: &str) -> &'static str { + match source { + "ruler" => "Ruler Tool", + "count" => "Count Tool", + _ => "Selection", + } +} + +/// Record Measurements' error for `source` with no data point enabled: the alert's two lines. +fn no_data_points(source: &str) -> String { + format!("{NO_DATA_POINTS}{}.\n{NO_DATA_POINTS_DETAIL}", data_points_source_name(source)) +} + fn record(s: &mut Session, p: &Value) -> Result { const CMD: &str = "image.analysis.recordMeasurements"; let d = doc(s)?; @@ -1117,6 +1138,11 @@ fn record(s: &mut Session, p: &Value) -> Result { rows.push(m); } } + // No data point enabled for the source: the reference application's alert, and nothing is recorded (no + // empty row, no label number used up, #17407). + if s.analysis.data_points.of(source).is_empty() { + return Err(EngineError::Other(no_data_points(source))); + } s.analysis.next_measurement += 1; let keep = s.analysis.data_points.of(source).to_vec(); let mut ids = Vec::new(); @@ -1414,4 +1440,6 @@ mod analysis_straighten_selection_tests; #[cfg(test)] mod data_points_empty_set_tests; #[cfg(test)] +mod record_no_data_points_tests; +#[cfg(test)] mod tests; diff --git a/crates/engine-core/src/cmd/analysis_cmds/record_no_data_points_tests.rs b/crates/engine-core/src/cmd/analysis_cmds/record_no_data_points_tests.rs new file mode 100644 index 0000000000..73a0b401b2 --- /dev/null +++ b/crates/engine-core/src/cmd/analysis_cmds/record_no_data_points_tests.rs @@ -0,0 +1,72 @@ +//! #17407: Record Measurements with no data point enabled for the source it records refuses with the reference +//! application's alert text, records nothing and does not use up a label number. Ruler and Count get the same check, +//! naming their tool. + +use super::*; + +const RECORD: &str = "image.analysis.recordMeasurements"; +const POINTS: &str = "image.analysis.selectDataPoints"; + +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 200, "height": 120, "background": "white"})).unwrap(); + s +} + +fn log_len(s: &mut Session) -> usize { + s.execute("measurementLog.list", json!({})).unwrap()["rows"].as_array().map_or(0, Vec::len) +} + +fn message(e: &EngineError) -> String { + e.to_string() +} + +#[test] +fn a_selection_with_only_ruler_points_on_warns_and_records_nothing() { + let mut s = session(); + s.execute(POINTS, json!({"selection": [], "ruler": ["length", "angle"], "count": []})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + + let e = s.execute(RECORD, json!({})).unwrap_err(); + assert_eq!( + message(&e), + "There are no measurement data points currently enabled for the Selection.\nData points must be set before measurements can be recorded." + ); + assert!(message(&e).starts_with(NO_DATA_POINTS)); + assert_eq!(log_len(&mut s), 0, "no empty row"); + + // The label number was not used up: after setting a point, the first row is "Measurement 1". + s.execute(POINTS, json!({"selection": ["label", "area"]})).unwrap(); + let r = s.execute(RECORD, json!({})).unwrap(); + assert_eq!(r["rows"][0]["values"]["label"], json!("Measurement 1"), "{r}"); + assert_eq!(log_len(&mut s), 1); +} + +#[test] +fn ruler_and_count_get_the_same_check_with_their_tool_name() { + let mut s = session(); + s.execute(POINTS, json!({"selection": ["area"], "ruler": [], "count": []})).unwrap(); + s.execute("image.analysis.rulerTool", json!({"start": [10, 50], "end": [40, 10]})).unwrap(); + let e = s.execute(RECORD, json!({"source": "ruler"})).unwrap_err(); + assert_eq!(message(&e), format!("{NO_DATA_POINTS}Ruler Tool.\n{NO_DATA_POINTS_DETAIL}")); + + s.execute("count.add", json!({"x": 20, "y": 20})).unwrap(); + let e = s.execute(RECORD, json!({"source": "count"})).unwrap_err(); + assert_eq!(message(&e), format!("{NO_DATA_POINTS}Count Tool.\n{NO_DATA_POINTS_DETAIL}")); + assert_eq!(log_len(&mut s), 0); + + // With a point on, each source records as before. + s.execute(POINTS, json!({"ruler": ["length"], "count": ["count"]})).unwrap(); + assert!(s.execute(RECORD, json!({"source": "ruler"})).is_ok()); + assert!(s.execute(RECORD, json!({"source": "count"})).is_ok()); + assert_eq!(log_len(&mut s), 2); +} + +#[test] +fn a_source_that_has_points_records_whatever_the_other_sources_hold() { + let mut s = session(); + s.execute(POINTS, json!({"selection": ["area"], "ruler": [], "count": []})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + let r = s.execute(RECORD, json!({})).unwrap(); + assert_eq!(r["rows"][0]["values"]["area"], json!(5000.0), "{r}"); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 62884471a4..02590fa11b 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -440,6 +440,7 @@ pub(crate) type PromptRow = fn(&mut PhotocraftApp, &egui::Context, &mut PromptAn pub(crate) const PROMPTS: &[PromptRow] = &[ crate::tools::tool_reset::answer, crate::analysis::note_alerts::answer, + crate::analysis::no_data_points_answer, delete_layer_prompt::answer, mask_trash_prompt::answer, disk_change_prompt::answer, diff --git a/crates/ui-egui/src/tools/analysis/mod.rs b/crates/ui-egui/src/tools/analysis/mod.rs index 488d9499f8..fce2102caa 100644 --- a/crates/ui-egui/src/tools/analysis/mod.rs +++ b/crates/ui-egui/src/tools/analysis/mod.rs @@ -8,6 +8,8 @@ //! [`note_alerts`]. use craft::behavior::Selection; +use craft::ui::dialog::{PromptAnswer, PromptChoice, StandardPrompt}; +use photocraft_engine::analysis_cmds; use photocraft_engine::color_cmds::ColorExt; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -172,8 +174,12 @@ pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option "auto", }; let r = app.run(id, json!({"source": source})); - if r.is_ok() { - let _ = crate::panel_docking::show_panel(app, MEASUREMENT_LOG, Some(true)); + match &r { + Ok(_) => { + let _ = crate::panel_docking::show_panel(app, MEASUREMENT_LOG, Some(true)); + } + Err(e) if e.starts_with(analysis_cmds::NO_DATA_POINTS) => no_data_points_alert(app, e), + Err(_) => {} } r } @@ -199,6 +205,43 @@ pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option tl!("Ruler Tool"), + "Count Tool" => tl!("Count Tool"), + _ => tl!("Selection"), + }; + let message = crate::i18n::fmt(tl!("There are no measurement data points currently enabled for the {source}."), &[("source", name)]); + let prompt = StandardPrompt::custom(message) + .title(tl!("PhotoCraft")) + .paragraph(tl!("Data points must be set before measurements can be recorded.")) + .icon(craft::behavior::IconId::new("warning")) + .button(PromptChoice::Proceed, tl!("OK")) + .button(PromptChoice::Alternate, tl!("Set Data Points…")) + .escape(PromptChoice::Proceed) + .tag(NoDataPoints); + let _ = crate::dialogs::alerts::open_prompt(app, prompt); +} + +/// The `PROMPTS` entry of that alert: Set Data Points… opens Select Data Points, whose OK only stores the set. +pub(crate) fn no_data_points_answer(app: &mut PhotocraftApp, _ctx: &egui::Context, answer: &mut PromptAnswer) -> bool { + if answer.take_tag::().is_none() { + return false; + } + if answer.choice == PromptChoice::Alternate + && let Err(error) = dialogs::open(app, dialogs::Kind::DataPoints) + { + crate::dialogs::alerts::report_error(app, error); + } + true +} + /// Export the Measurement Log (or the given rows) as CSV through the save picker. pub(crate) fn export_log(app: &mut PhotocraftApp, rows: Option>) -> Result { let p = rows.map_or(json!({}), |r| json!({"rows": r})); @@ -251,3 +294,7 @@ pub(super) fn status_on_err(app: &mut PhotocraftApp, r: Result) { app.ui.status_error = false; } } + +#[cfg(test)] +#[path = "record_no_data_points_alert_tests.rs"] +mod record_no_data_points_alert_tests; diff --git a/crates/ui-egui/src/tools/analysis/record_no_data_points_alert_tests.rs b/crates/ui-egui/src/tools/analysis/record_no_data_points_alert_tests.rs new file mode 100644 index 0000000000..fffc0f5f7e --- /dev/null +++ b/crates/ui-egui/src/tools/analysis/record_no_data_points_alert_tests.rs @@ -0,0 +1,76 @@ +//! #17407: Image › Analysis › Record Measurements with no data point enabled for the source shows the warning with +//! OK and Set Data Points…; the latter opens Select Data Points with the current set, whose OK only stores the set. + +use craft::ui::dialog::{DialogId, StandardPrompt}; +use craft::ui::patterns::form_dialogs::HostedParamDialog; +use serde_json::json; + +use super::NoDataPoints; +use crate::PhotocraftApp; + +const RECORD: &str = "image.analysis.recordMeasurements"; + +fn app() -> (Box, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + app.run("image.analysis.selectDataPoints", json!({"selection": [], "ruler": ["length", "angle"], "count": []})).unwrap(); + app.run("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + let ctx = app.ctx().clone(); + (app, ctx) +} + +fn rows(app: &mut PhotocraftApp) -> usize { + app.run("measurementLog.list", json!({})).unwrap()["rows"].as_array().map_or(0, Vec::len) +} + +/// The open alert: its id, and its message, paragraphs and buttons as shown. +fn alert(app: &PhotocraftApp) -> Option<(DialogId, String, Vec, Vec)> { + let id = crate::dialogs::alerts::prompt_tagged::(app)?; + let prompt = app.framework.dialogs.get::()?; + let host = app.framework.host(); + let buttons = prompt.shown_buttons(host).into_iter().map(|(_, label)| label).collect(); + Some((id, prompt.shown_message(host), prompt.shown_paragraphs(host), buttons)) +} + +#[test] +fn record_measurements_shows_the_warning_with_ok_and_set_data_points() { + let (mut app, ctx) = app(); + assert!(crate::menus::invoke(&mut app, &ctx, RECORD, json!({})).is_err()); + let (id, message, paragraphs, buttons) = alert(&app).expect("the warning is open"); + assert_eq!(message, "There are no measurement data points currently enabled for the Selection."); + assert_eq!(paragraphs, ["Data points must be set before measurements can be recorded."]); + assert_eq!(buttons, ["OK", "Set Data Points…"]); + assert_eq!(rows(&mut app), 0, "nothing is recorded"); + + crate::dialogs::confirm(&mut app, &ctx, id).unwrap(); + assert!(alert(&app).is_none(), "OK closes it"); + assert!(app.framework.dialogs.get::().is_none(), "OK opens nothing"); +} + +#[test] +fn set_data_points_opens_select_data_points_whose_ok_only_stores_the_set() { + let (mut app, ctx) = app(); + let _ = crate::menus::invoke(&mut app, &ctx, RECORD, json!({})); + let (id, ..) = alert(&app).unwrap(); + app.framework.dialogs.set_json_field(&ctx, id, "choice", json!("alternate")).unwrap(); + crate::dialogs::confirm(&mut app, &ctx, id).unwrap(); + assert!(alert(&app).is_none()); + + let dialog = app.framework.dialogs.get::().map(craft::ui::dialog::StackDialog::id).expect("Select Data Points is open"); + // The current set: Ruler Length is ticked, Selection Area is not. + let fields = serde_json::to_value(app.framework.dialogs.get_by_id::(dialog).unwrap().fields()).unwrap(); + assert_eq!(fields["ruler:length"], json!(true), "{fields}"); + assert_ne!(fields["selection:area"], json!(true), "{fields}"); + + crate::dialogs::confirm(&mut app, &ctx, dialog).unwrap(); + assert_eq!(rows(&mut app), 0, "its OK records nothing"); + assert!(alert(&app).is_none(), "its OK does not record, so it does not warn again"); + let points = app.run("image.analysis.selectDataPoints", json!({})).unwrap(); + assert_eq!(points["dataPoints"]["ruler"], json!(["length", "angle"]), "its OK stores the set it shows: {points}"); + + app.run("image.analysis.selectDataPoints", json!({"selection": ["area"], "ruler": [], "count": []})).unwrap(); + // Now Record Measurements records, as "Measurement 1". + crate::menus::invoke(&mut app, &ctx, RECORD, json!({})).unwrap(); + assert_eq!(rows(&mut app), 1); + assert!(alert(&app).is_none()); +} From acb96f504b73b3741f6f292e3181ae285c17c461 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:43:07 +0100 Subject: [PATCH 07/15] Auto-Align Layers: Vignette Removal brightens the aligned layers' corners (#14197) edit.autoAlignLayers takes vignetteRemoval (bool, default false). It estimates one radial falloff from the layers' overlaps with Photomerge's estimator, read on a copy box-averaged to at most 1024 px across, with exposure gains solved beside it and dropped, then divides the falloff out of every aligned layer, the reference of a planar layout included unless its pixels are locked. Collage and Reposition ignore it, as the dialog clears it there. The result carries the falloff, and a warning when the overlaps show none (layers that nearly coincide) or a locked reference was left as it was. A wrong-typed value is an error. --- crates/engine-core/src/cmd/photo_cmds.rs | 115 ++++++++++- crates/engine-vector/src/cmd/align_cmds.rs | 70 ++++++- .../align_cmds/auto_align_vignette_tests.rs | 181 ++++++++++++++++++ 3 files changed, 350 insertions(+), 16 deletions(-) create mode 100644 crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs diff --git a/crates/engine-core/src/cmd/photo_cmds.rs b/crates/engine-core/src/cmd/photo_cmds.rs index 6a2ae71ece..b8745ba258 100644 --- a/crates/engine-core/src/cmd/photo_cmds.rs +++ b/crates/engine-core/src/cmd/photo_cmds.rs @@ -627,22 +627,14 @@ fn apply_photometric(rois: &mut [RoiImage], fmt: PixelFormat, geometry: Option f64 { + pl.inverse(u, v).map_or(0.0, |(sx, sy)| { + let (w, h) = (size.0 as f64, size.1 as f64); + let (dx, dy) = (sx - w / 2.0, sy - h / 2.0); + (dx * dx + dy * dy) / (w * w / 4.0 + h * h / 4.0) + }) +} + +/// A colour sample brightened by the factor `f` (CMYK scales the light, not the ink), within range unless float. +fn scale_sample(v: f32, f: f32, fmt: PixelFormat) -> f32 { + let v = if fmt.mode == ColorMode::Cmyk { 1.0 - (1.0 - v) * f } else { v * f }; + if fmt.sample == SampleType::F32 { v } else { v.clamp(0.0, 1.0) } +} + +/// Vignette estimates read the layers box-averaged to at most this many pixels across: the falloff is smooth, and +/// [`panorama::photometric`] samples about 40 000 points of the overlaps anyway. +const VIGNETTE_SIDE: usize = 1024; + +/// The colour channels and coverage of `surf`'s content, box-averaged over `k × k` pixels on a grid aligned to the origin. +fn roi_downsampled(surf: &Surface, k: usize) -> Result { + let fmt = surf.format(); + let (n, cc) = (fmt.channels(), fmt.mode.color_channels()); + let b = surf.content_bounds(); + if b.is_empty() { + return Ok(RoiImage { x0: 0, y0: 0, w: 0, h: 0, ch: cc, px: Vec::new(), alpha: Vec::new() }); + } + let ki = k as i32; + let (gx0, gy0) = (b.x0.div_euclid(ki), b.y0.div_euclid(ki)); + let (w, h) = (((b.x1 - gx0 * ki) as usize).div_ceil(k), ((b.y1 - gy0 * ki) as usize).div_ceil(k)); + let overflow = || crate::allocation::error("Auto-Align", "vignette estimate size overflowed"); + let cells = w.checked_mul(h).ok_or_else(overflow)?; + let samples = cells.checked_mul(cc).ok_or_else(overflow)?; + let mut px = crate::allocation::capacity(samples, "Auto-Align vignette estimate")?; + px.resize(samples, 0.0f32); + let mut alpha = crate::allocation::capacity(cells, "Auto-Align vignette estimate")?; + alpha.resize(cells, 0.0f32); + let mut row = vec![0.0f32; w * k * n]; + for y in gy0 * ki..(gy0 + h as i32) * ki { + surf.read_region_into(Rect::new(gx0 * ki, y, (gx0 + w as i32) * ki, y + 1), &mut row); + let line = ((y - gy0 * ki) as usize / k) * w; + for (x, q) in row.chunks_exact(n).enumerate() { + let cell = line + x / k; + let a = if fmt.alpha { q[n - 1] } else { 1.0 }; + alpha[cell] += a; + for c in 0..cc { + px[cell * cc + c] += q[c] * a; + } + } + } + let area = (k * k) as f32; + for (cell, a) in alpha.iter_mut().enumerate() { + for v in &mut px[cell * cc..(cell + 1) * cc] { + *v = if *a > 0.0 { *v / *a } else { 0.0 }; + } + *a /= area; + } + Ok(RoiImage { x0: gx0, y0: gy0, w, h, ch: cc, px, alpha }) +} + +/// The vignetting falloff shared by `layers`, each warped into canvas coordinates by its placement from a `size` frame +/// (Auto-Align's Vignette Removal, #14197): Photomerge's estimate from the layers' overlaps, read at most +/// [`VIGNETTE_SIDE`] pixels across. Exposure gains are estimated beside it, so a brighter layer isn't taken for +/// vignetting, and then dropped. `[0, 0]` when the overlaps show none: too few, or every scene point at about the same +/// radius in each layer (a bracket whose layers nearly coincide). +pub fn estimate_vignette(layers: &[(&Surface, &Placement)], size: (usize, usize)) -> Result<[f64; 2]> { + let area = layers.iter().fold(Rect::EMPTY, |a, (s, _)| a.union(&s.content_bounds())); + if area.is_empty() { + return Ok([0.0, 0.0]); + } + let k = (area.width().max(area.height()) as usize).div_ceil(VIGNETTE_SIDE).max(1); + let rois = layers.iter().map(|(s, _)| roi_downsampled(s, k)).collect::>>()?; + // The same source points, landing on the `k`× smaller grid: a cell's centre is the centre of its `k × k` pixels. + let shrink = Homography([1.0 / k as f64, 0.0, 0.0, 0.0, 1.0 / k as f64, 0.0, 0.0, 0.0, 1.0]); + let placements: Vec = layers.iter().map(|(_, pl)| Placement { h: shrink.mul(&pl.h), ..(*pl).clone() }).collect(); + let sizes = vec![size; layers.len()]; + Ok(panorama::photometric(&rois, Some((&placements, &sizes)), true, true).vignette) +} + +/// `surf`, warped into canvas coordinates by `pl` from a `size` frame, with the falloff `vignette` +/// ([`estimate_vignette`]) divided out of its colour channels. +pub fn remove_vignette(surf: &Surface, pl: &Placement, size: (usize, usize), vignette: [f64; 2]) -> Surface { + let fmt = surf.format(); + let (n, cc) = (fmt.channels(), fmt.mode.color_channels()); + let photo = panorama::Photometric { gains: vec![vec![1.0; cc]], vignette }; + let b = surf.content_bounds(); + let mut out = surf.clone(); + let mut row = vec![0.0f32; b.width() as usize * n]; + for y in b.y0..b.y1 { + let line = Rect::new(b.x0, y, b.x1, y + 1); + surf.read_region_into(line, &mut row); + for (x, q) in (b.x0..).zip(row.chunks_exact_mut(n)) { + let f = photo.factor(0, 0, source_r2(pl, size, x as f64 + 0.5, y as f64 + 0.5)); + for v in &mut q[..cc] { + *v = scale_sample(*v, f, fmt); + } + } + out.write_region(line, &row); + } + out +} + /// Per-image seam weights (1 inside an image's seam region, else 0) over each ROI. fn compute_seam_weights(rois: &[RoiImage], canvas: Rect, order: &[usize]) -> Vec> { let n = rois.len(); diff --git a/crates/engine-vector/src/cmd/align_cmds.rs b/crates/engine-vector/src/cmd/align_cmds.rs index f7066086e7..1c3ce12df3 100644 --- a/crates/engine-vector/src/cmd/align_cmds.rs +++ b/crates/engine-vector/src/cmd/align_cmds.rs @@ -8,7 +8,8 @@ //! ([`photocraft_algo::direct`], `registration`: auto falls back to it, or ask for it). Projections: Auto, Perspective //! (homography), Cylindrical and Spherical (rigid motion on the cylinder / sphere, focal length //! from the homographies or EXIF), Collage (similarity) and Reposition (translation). The -//! reference stays put in the planar projections. +//! reference stays put in the planar projections. Vignette Removal estimates one radial falloff +//! from the layers' overlaps, as Photomerge does, and divides it out of every aligned layer. //! //! Auto-Blend gives each selected layer a mask so the composite shows, per pixel, the sharpest //! layer (Stack Images, for focus stacking) or one layer per region with seams routed where the @@ -21,7 +22,7 @@ //! from focus ([`photocraft_algo::dff`]): black = the bottom layer, white = the top, so that once //! on a layer mask it drives Lens Blur's depth map. -use photocraft_algo::panorama::Layout; +use photocraft_algo::panorama::{Layout, Placement}; use photocraft_algo::pyramid; use photocraft_algo::transform::Interp; use photocraft_algo::warp::warp_mesh_gray; @@ -31,7 +32,9 @@ use photocraft_raster::{Surface, to_rgba}; use serde_json::{Value, json}; use crate::commands::CommandSpec; -use crate::photo_cmds::{BlendOptions, NO_DETAIL, plane_matrix, register, register_direct, seam_blend, seam_order, warp_placed}; +use crate::photo_cmds::{ + BlendOptions, NO_DETAIL, estimate_vignette, plane_matrix, register, register_direct, remove_vignette, seam_blend, seam_order, warp_placed, +}; use crate::{EngineError, Result, Session}; fn bad(cmd: &str, msg: impl Into) -> EngineError { @@ -84,6 +87,12 @@ fn auto_align(s: &mut Session, p: &Value) -> Result { let projection = p.get("projection").and_then(Value::as_str).unwrap_or("auto"); let layout = Layout::parse(projection) .ok_or_else(|| bad(cmd, format!("unknown projection `{projection}` (auto|perspective|cylindrical|spherical|collage|reposition)")))?; + let vignette = match p.get("vignetteRemoval") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "`vignetteRemoval` must be true or false"))?, + }; + // The dialog greys and clears Vignette Removal under Collage and Reposition; a script's request is ignored there too. + let vignette = vignette && !matches!(layout, Layout::Collage | Layout::Reposition); let st = s.active().ok_or(EngineError::NoDocument)?; let doc = st.doc.clone(); let reference = match p.get("reference").and_then(Value::as_u64) { @@ -130,7 +139,7 @@ fn auto_align(s: &mut Session, p: &Value) -> Result { if let Some(l) = moves.iter().find(|&&i| pinned(&doc, ids[i])).and_then(|&i| doc.layer(ids[i])) { return Err(EngineError::Other(format!("Auto-Align can't move the locked layer \"{}\"", l.name))); } - let warped: Vec<(LayerId, Surface, Option)> = moves + let mut warped: Vec<(LayerId, Surface, Option)> = moves .iter() .map(|&i| { let pl = al.placements[i].as_ref().ok_or_else(|| EngineError::Other("Auto-Align lost a layer's placement".into()))?; @@ -150,6 +159,37 @@ fn auto_align(s: &mut Session, p: &Value) -> Result { Ok((ids[i], px, mask)) }) .collect::>()?; + // Vignette Removal (#14197): one falloff for all the aligned layers, from their overlaps, divided out of each. The + // reference of a planar layout stays put but is brightened too, unless a lock keeps its pixels. + let size = (area.width() as usize, area.height() as usize); + let still = (!moves.contains(&ref_idx)).then_some(ref_idx).and_then(|i| Some((i, al.placements[i].as_ref()?))); + let mut falloff = None; + let mut reference_px = None; + let mut warnings: Vec = Vec::new(); + if vignette { + let mut layers: Vec<(&Surface, &Placement)> = warped.iter().zip(&moves).filter_map(|((_, px, _), &i)| Some((px, al.placements[i].as_ref()?))).collect(); + layers.extend(still.map(|(i, pl)| (surfs[i], pl))); + let v = estimate_vignette(&layers, size)?; + if negligible(v) { + warnings.push(NO_VIGNETTE.to_owned()); + } else { + for ((_, px, _), &i) in warped.iter_mut().zip(&moves) { + if let Some(pl) = al.placements[i].as_ref() { + *px = remove_vignette(px, pl, size, v); + } + } + if let Some((i, pl)) = still { + let locks = doc.effective_locks(ids[i]); + if locks.all || locks.pixels { + warnings + .push(format!("Vignette Removal left the locked reference layer \"{}\" as it was", doc.layer(ids[i]).map_or("", |l| l.name.as_str()))); + } else { + reference_px = Some((ids[i], remove_vignette(surfs[i], pl, size, v))); + } + } + } + falloff = Some(v); + } s.edit("Auto-Align Layers", |doc, _| { for (id, px, mask) in &warped { // Photoshop turns the Background into a normal layer before moving it. @@ -162,6 +202,12 @@ fn auto_align(s: &mut Session, p: &Value) -> Result { m.surface = ms.clone(); } } + // The reference doesn't move, so a Background stays the Background. + if let Some((id, px)) = &reference_px + && let Some(surf) = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.surface_mut() + { + *surf = px.clone(); + } Ok(()) })?; let model = match al.layout { @@ -179,10 +225,19 @@ fn auto_align(s: &mut Session, p: &Value) -> Result { }) .collect(); Ok( - json!({"reference": reference.0, "layout": al.layout.name(), "registration": used, "focal": al.focal, "rms": al.rms, "aligned": aligned, "failed": failed}), + json!({"reference": reference.0, "layout": al.layout.name(), "registration": used, "focal": al.focal, "rms": al.rms, "aligned": aligned, "failed": failed, "vignette": falloff, "warnings": warnings}), ) } +/// Auto-Align's warning when Vignette Removal was asked for but the layers' overlaps show no falloff to remove. +const NO_VIGNETTE: &str = "Vignette Removal found no vignetting to remove: the layers' overlaps don't show any (layers that nearly coincide, as in a focus or exposure bracket, can't show it)"; + +/// Whether the falloff `log V = a·r² + b·r⁴` changes no pixel by as much as 1% out to the corners (r² = 1): what the +/// overlaps of layers that nearly coincide leave, where the estimate stays at its prior. +fn negligible([a, b]: [f64; 2]) -> bool { + (0..=10).map(|i| f64::from(i) / 10.0).all(|r2| (a * r2 + b * r2 * r2).abs() < 0.01) +} + /// The most memory Auto-Blend's working buffers may take past the canvas: a bound independent /// of the layers' own bounding boxes, which a sparse layer (a dot at each far corner) can make /// arbitrarily large, and of how many layers are blended. @@ -456,7 +511,7 @@ pub fn specs() -> Vec { spec!( "edit.autoAlignLayers", "Auto-Align Layers…", - r##"{"projection":"auto|perspective|cylindrical|spherical|collage|reposition","reference":layer id?=the locked selected layer, else the bottom selected layer,"geometricCorrection":bool=false,"interpolation":"bicubic|bilinear|nearest","registration":"auto|features|intensity"}"##, + r##"{"projection":"auto|perspective|cylindrical|spherical|collage|reposition","reference":layer id?=the locked selected layer, else the bottom selected layer,"geometricCorrection":bool=false,"vignetteRemoval":bool=false (ignored with collage and reposition),"interpolation":"bicubic|bilinear|nearest","registration":"auto|features|intensity"}"##, two_layers, auto_align ), @@ -478,3 +533,6 @@ mod auto_blend_background_tests; #[cfg(test)] mod auto_blend_stack_bottom_mask_tests; + +#[cfg(test)] +mod auto_align_vignette_tests; diff --git a/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs b/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs new file mode 100644 index 0000000000..a3e845b6a7 --- /dev/null +++ b/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs @@ -0,0 +1,181 @@ +//! Auto-Align's Vignette Removal (#14197): one falloff estimated from the layers' overlaps, as Photomerge does, and +//! divided out of every aligned layer; off, and under Collage or Reposition, the layers come out as before. + +use super::*; + +const W: i32 = 400; +const H: i32 = 300; + +/// A scene larger than the canvas: soft mid-tone patches on a gentle gradient, every value well inside 0..1. +fn scene() -> Vec<[f32; 3]> { + let (sw, sh) = (W + 120, H + 100); + let mut px: Vec<[f32; 3]> = + (0..sw * sh).map(|i| 0.45 + 0.1 * (i % sw) as f32 / sw as f32 + 0.05 * (i / sw) as f32 / sh as f32).map(|v| [v, v, v]).collect(); + let mut seed = 7u64; + let mut rnd = || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as f32 / (1u64 << 31) as f32 + }; + for _ in 0..400 { + let (x, y) = ((rnd() * (sw - 20) as f32) as i32, (rnd() * (sh - 16) as f32) as i32); + let (rw, rh) = (4 + (rnd() * 16.0) as i32, 4 + (rnd() * 12.0) as i32); + let c = [0.3 + 0.5 * rnd(), 0.3 + 0.5 * rnd(), 0.3 + 0.5 * rnd()]; + for yy in y..y + rh { + for xx in x..x + rw { + px[(yy * sw + xx) as usize] = c; + } + } + } + px +} + +/// A canvas-sized layer: the scene seen from (`ox`, `oy`), darkened towards the corners by `exp(falloff · r²)` +/// (r = 1 at a corner), as a lens does. +fn photo_layer(s: &mut Session, name: &str, ox: i32, oy: i32, falloff: f32) -> LayerId { + let px = scene(); + s.execute("layer.new.layer", json!({"name": name})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + s.edit("photo", |doc, _| { + let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + let mut row = vec![0.0f32; W as usize * 4]; + for y in 0..H { + for x in 0..W { + let (dx, dy) = (x as f32 + 0.5 - W as f32 / 2.0, y as f32 + 0.5 - H as f32 / 2.0); + let v = (falloff * (dx * dx + dy * dy) / ((W * W + H * H) as f32 / 4.0)).exp(); + let c = px[((y + oy) * (W + 120) + x + ox) as usize]; + row[x as usize * 4..x as usize * 4 + 4].copy_from_slice(&[c[0] * v, c[1] * v, c[2] * v, 1.0]); + } + surf.write_region(Rect::new(0, y, W, y + 1), &row); + } + Ok(()) + }) + .unwrap(); + id +} + +/// Two vignetted photos of one scene, 60 x 40 px apart, both selected. +fn pair(falloff: f32, shift: (i32, i32)) -> (Session, [LayerId; 2]) { + let mut s = crate::session(); + s.execute("file.new", json!({"width": W, "height": H, "background": "transparent"})).unwrap(); + let a = photo_layer(&mut s, "A", 0, 0, falloff); + let b = photo_layer(&mut s, "B", shift.0, shift.1, falloff); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + (s, [a, b]) +} + +fn pixels(s: &Session, id: LayerId) -> Vec { + s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().read_region(Rect::new(-200, -200, W + 200, H + 200)) +} + +/// How far apart the two aligned layers are where both are opaque: the mean |log| of their luminance ratio. The scene is +/// the same in both, so what's left is each one's vignetting at a different place in the frame. +fn mismatch(s: &Session, [a, b]: [LayerId; 2]) -> f64 { + let (pa, pb) = (pixels(s, a), pixels(s, b)); + let (mut sum, mut n) = (0.0, 0usize); + for (qa, qb) in pa.as_chunks::<4>().0.iter().zip(pb.as_chunks::<4>().0) { + if qa[3] > 0.999 && qb[3] > 0.999 { + let (la, lb) = (qa[..3].iter().sum::(), qb[..3].iter().sum::()); + sum += f64::from((la / lb).ln().abs()); + n += 1; + } + } + assert!(n > 10_000, "the layers overlap"); + sum / n as f64 +} + +/// The mean luminance of layer `id` in the four corner squares of its own frame, a few pixels in from its warped edge. +fn corners(s: &Session, id: LayerId) -> f32 { + let surf = s.active().unwrap().doc.layer(id).unwrap().surface().unwrap(); + let b = surf.content_bounds(); + let mut sum = 0.0; + for (x, y) in [(b.x0 + 4, b.y0 + 4), (b.x1 - 34, b.y0 + 4), (b.x0 + 4, b.y1 - 34), (b.x1 - 34, b.y1 - 34)] { + sum += surf.read_region(Rect::new(x, y, x + 30, y + 30)).as_chunks::<4>().0.iter().map(|q| q[..3].iter().sum::()).sum::(); + } + sum / (4.0 * 900.0 * 3.0) +} + +fn align(s: &mut Session, params: Value) -> Value { + let r = s.execute("edit.autoAlignLayers", params).unwrap(); + assert_eq!(r["failed"], json!([]), "{r}"); + r +} + +#[test] +fn shifted_vignetted_layers_come_out_flatter_with_their_corners_brightened() { + let (mut s, ids) = pair(-0.5, (60, 40)); + let r = align(&mut s, json!({"projection": "auto"})); + assert_eq!(r["vignette"], Value::Null, "off by default: {r}"); + let (before, plain) = (mismatch(&s, ids), ids.map(|id| pixels(&s, id))); + let dark = ids.map(|id| corners(&s, id)); + s.undo(); + let r = align(&mut s, json!({"projection": "auto", "vignetteRemoval": false})); + assert!(ids.map(|id| pixels(&s, id)) == plain, "false is today's result: {r}"); + s.undo(); + let r = align(&mut s, json!({"projection": "auto", "vignetteRemoval": true})); + let v = r["vignette"].as_array().unwrap_or_else(|| panic!("{r}")); + assert!(v[0].as_f64().unwrap() + v[1].as_f64().unwrap() < -0.1, "a darkening falloff is found: {r}"); + assert_eq!(r["warnings"], json!([]), "{r}"); + let after = mismatch(&s, ids); + assert!(after < before * 0.6, "the overlap agrees better: {after} vs {before}"); + for (i, id) in ids.into_iter().enumerate() { + assert!(corners(&s, id) > dark[i] * 1.1, "layer {i}'s corners are brighter, the reference's too: {r}"); + } +} + +#[test] +fn collage_and_reposition_ignore_vignette_removal() { + for projection in ["collage", "reposition"] { + let (mut s, ids) = pair(-0.5, (60, 40)); + align(&mut s, json!({"projection": projection})); + let plain = ids.map(|id| pixels(&s, id)); + s.undo(); + let r = align(&mut s, json!({"projection": projection, "vignetteRemoval": true})); + assert!(ids.map(|id| pixels(&s, id)) == plain, "{projection}: {r}"); + assert_eq!(r["vignette"], Value::Null, "{projection}: {r}"); + } +} + +/// Layers that coincide see every scene point at the same radius, so the overlaps can't show a falloff: the layers are +/// left as they are and the result says so, rather than claiming a correction. +#[test] +fn coinciding_layers_report_that_no_vignetting_was_found() { + let (mut s, ids) = pair(-0.5, (0, 0)); + align(&mut s, json!({"projection": "auto", "registration": "intensity"})); + let plain = ids.map(|id| pixels(&s, id)); + s.undo(); + let r = align(&mut s, json!({"projection": "auto", "registration": "intensity", "vignetteRemoval": true})); + assert_eq!(r["warnings"], json!([NO_VIGNETTE]), "{r}"); + assert!(ids.map(|id| pixels(&s, id)) == plain, "{r}"); +} + +#[test] +fn a_wrong_typed_vignette_removal_is_an_error() { + let (mut s, ids) = pair(-0.5, (60, 40)); + for bad in [json!("yes"), json!(1), json!(1e308), json!([true]), json!({"on": true})] { + let e = s.execute("edit.autoAlignLayers", json!({"vignetteRemoval": bad})).unwrap_err(); + assert!(e.to_string().contains("vignetteRemoval"), "{bad}: {e}"); + } + assert_eq!(s.active().unwrap().doc.layer(ids[1]).unwrap().surface().unwrap().content_bounds(), Rect::new(0, 0, W, H), "nothing moved"); +} + +/// A reference whose pixels are locked stays as it was, and the result says so; the layers aligned onto it are still +/// brightened. +#[test] +fn a_pixel_locked_reference_keeps_its_pixels() { + let (mut s, [a, b]) = pair(-0.5, (60, 40)); + s.edit("lock", |doc, _| { + doc.layer_mut(a).unwrap().locks.set("pixels", true); + Ok(()) + }) + .unwrap(); + align(&mut s, json!({"projection": "auto"})); + let dark = corners(&s, b); + s.undo(); + let kept = pixels(&s, a); + let r = align(&mut s, json!({"projection": "auto", "vignetteRemoval": true})); + assert_eq!(r["reference"], a.0, "{r}"); + assert!(pixels(&s, a) == kept, "{r}"); + assert!(r["warnings"].as_array().is_some_and(|w| w.len() == 1 && w[0].as_str().is_some_and(|m| m.contains("\"A\""))), "{r}"); + assert!(corners(&s, b) > dark * 1.1, "{r}"); +} From 5fbc4dbc8bdf482c3f2c386cd1b16042ac6ec273 Mon Sep 17 00:00:00 2001 From: Dan Date: Sun, 29 Nov 2026 10:14:08 +0000 Subject: [PATCH 08/15] Restore captured settings when resetting a workspace (#17648) --- .../workspace_reset_captured_toolbar_tests.rs | 84 +++++++++++++++++++ crates/ui-egui/src/menus/workspace_ui.rs | 6 ++ 2 files changed, 90 insertions(+) create mode 100644 crates/ui-egui/src/menus/workspace_reset_captured_toolbar_tests.rs diff --git a/crates/ui-egui/src/menus/workspace_reset_captured_toolbar_tests.rs b/crates/ui-egui/src/menus/workspace_reset_captured_toolbar_tests.rs new file mode 100644 index 0000000000..9dcfcaf624 --- /dev/null +++ b/crates/ui-egui/src/menus/workspace_reset_captured_toolbar_tests.rs @@ -0,0 +1,84 @@ +use std::sync::Arc; + +use craft::settings::testing::MemoryFiles; +use craft::settings::{Location, OpenOptions, SettingsStore}; +use photocraft_engine::Session; +use photocraft_engine::prefs::SavedPrefs; +use serde_json::{Value, json}; + +use crate::{PhotocraftApp, Services, menus}; + +fn invoke(app: &mut PhotocraftApp, id: &str, params: Value) { + let ctx = app.ctx().clone(); + menus::invoke(app, &ctx, id, params).unwrap(); +} + +fn customizations(app: &mut PhotocraftApp) -> [Value; 3] { + ["toolbar", "shortcuts", "menus"].map(|path| app.run("prefs.get", json!({"path": path})).unwrap()) +} + +fn set_customizations(app: &mut PhotocraftApp, extra_tool: &str, brush_key: &str, fill_color: &str) { + app.run("edit.toolbar", json!({"reset": true, "extras": [[extra_tool]]})).unwrap(); + app.run("prefs.set", json!({"values": {"shortcuts.tools.select.brush": brush_key, "menus.colors.edit.fill": fill_color}})).unwrap(); +} + +#[test] +fn reset_restores_and_saves_all_captured_customizations() { + let files = Arc::new(MemoryFiles::new()); + let open_app = || { + let options = OpenOptions::new(Location::Dir("/memory/photocraft".into())).files(files.clone()); + let services = Services { settings: Some(SettingsStore::::open_with(options)), ..Default::default() }; + PhotocraftApp::new(Session::new(), services) + }; + let mut app = open_app(); + set_customizations(&mut app, "Frame", "F8", "red"); + let captured = customizations(&mut app); + invoke(&mut app, "workspace.new", json!({"name": "Retouch", "toolbar": true, "keyboardShortcuts": true, "menus": true})); + + set_customizations(&mut app, "Crop", "F9", "blue"); + let changed = customizations(&mut app); + for (before, after) in captured.iter().zip(&changed) { + assert_ne!(before, after); + } + invoke(&mut app, "workspace.reset", json!({})); + assert_eq!(customizations(&mut app), captured); + + crate::prefs_ui::save_preferences(&mut app).unwrap(); + drop(app); + let mut restarted = open_app(); + assert_eq!(customizations(&mut restarted), captured); +} + +#[test] +fn reset_applies_each_capture_independently() { + for toolbar in [true, false] { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + set_customizations(&mut app, "Frame", "F8", "red"); + let captured = customizations(&mut app); + invoke(&mut app, "workspace.new", json!({"name": "Retouch", "toolbar": toolbar, "keyboardShortcuts": !toolbar, "menus": !toolbar})); + + set_customizations(&mut app, "Crop", "F9", "blue"); + let changed = customizations(&mut app); + invoke(&mut app, "workspace.reset", json!({})); + let restored = customizations(&mut app); + for (index, captured_by_workspace) in [toolbar, !toolbar, !toolbar].into_iter().enumerate() { + let expected = if captured_by_workspace { &captured[index] } else { &changed[index] }; + assert_eq!(&restored[index], expected); + } + } +} + +#[test] +fn reset_keeps_live_customizations_without_captures() { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + set_customizations(&mut app, "Frame", "F8", "red"); + let live = customizations(&mut app); + invoke(&mut app, "workspace.reset", json!({})); + assert_eq!(customizations(&mut app), live, "built-in workspace"); + + invoke(&mut app, "workspace.new", json!({"name": "Panels Only"})); + set_customizations(&mut app, "Crop", "F9", "blue"); + let live = customizations(&mut app); + invoke(&mut app, "workspace.reset", json!({})); + assert_eq!(customizations(&mut app), live, "saved workspace without captures"); +} diff --git a/crates/ui-egui/src/menus/workspace_ui.rs b/crates/ui-egui/src/menus/workspace_ui.rs index fce826ac76..8877dbf5d6 100644 --- a/crates/ui-egui/src/menus/workspace_ui.rs +++ b/crates/ui-egui/src/menus/workspace_ui.rs @@ -270,6 +270,8 @@ pub fn run(app: &mut PhotocraftApp, _ctx: &egui::Context, command: WorkspaceComm Some(_) | None => {} } if command == WorkspaceCommands::Reset { + let current = app.workspaces.set.current.clone(); + restore_extras(app, ¤t); crate::dock::persist(app); } store(app); @@ -560,6 +562,10 @@ fn extras_options() -> [(&'static str, &'static str); 13] { ] } +#[cfg(test)] +#[path = "workspace_reset_captured_toolbar_tests.rs"] +mod workspace_reset_captured_toolbar_tests; + #[cfg(test)] mod tests { use super::*; From 1ebc72122f6d5658fc6228f377d6fdf4bb2ff604 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:09:33 +0100 Subject: [PATCH 09/15] Auto-Align Vignette Removal: fit CMYK light, keep the reference in one frame (#14197) - The estimate read CMYK samples as they are stored, as ink, which grows towards darkened corners, so it fitted ink growth and then brightened the light. It now reads the red, green and blue light the inks let through. The correction brightens the light of C, M and Y only: K's light multiplies theirs, so brightening it too would brighten twice. - With Geometric Distortion fitting a nonzero k1, the reference's placement carries that k1 but its pixels stay as they are. The estimate now reads the reference warped by its placement, as it reads the layers that moved, and its correction measures radii with k1 = 0, in its own pixels. New test: shifted_vignetted_cmyk_layers_come_out_flatter_with_their_corners_brightened. --- crates/engine-core/src/cmd/photo_cmds.rs | 14 +++-- crates/engine-vector/src/cmd/align_cmds.rs | 14 ++++- .../align_cmds/auto_align_vignette_tests.rs | 59 +++++++++++++++---- 3 files changed, 70 insertions(+), 17 deletions(-) diff --git a/crates/engine-core/src/cmd/photo_cmds.rs b/crates/engine-core/src/cmd/photo_cmds.rs index b8745ba258..d231d0dbca 100644 --- a/crates/engine-core/src/cmd/photo_cmds.rs +++ b/crates/engine-core/src/cmd/photo_cmds.rs @@ -662,10 +662,12 @@ fn scale_sample(v: f32, f: f32, fmt: PixelFormat) -> f32 { /// [`panorama::photometric`] samples about 40 000 points of the overlaps anyway. const VIGNETTE_SIDE: usize = 1024; -/// The colour channels and coverage of `surf`'s content, box-averaged over `k × k` pixels on a grid aligned to the origin. +/// The light in `surf`'s colour channels and its coverage, box-averaged over `k × k` pixels on a grid aligned to the +/// origin. CMYK reads as the red, green and blue light its inks let through, since the estimate fits light, not ink. fn roi_downsampled(surf: &Surface, k: usize) -> Result { let fmt = surf.format(); - let (n, cc) = (fmt.channels(), fmt.mode.color_channels()); + let cmyk = fmt.mode == ColorMode::Cmyk; + let (n, cc) = (fmt.channels(), if cmyk { 3 } else { fmt.mode.color_channels() }); let b = surf.content_bounds(); if b.is_empty() { return Ok(RoiImage { x0: 0, y0: 0, w: 0, h: 0, ch: cc, px: Vec::new(), alpha: Vec::new() }); @@ -689,7 +691,8 @@ fn roi_downsampled(surf: &Surface, k: usize) -> Result { let a = if fmt.alpha { q[n - 1] } else { 1.0 }; alpha[cell] += a; for c in 0..cc { - px[cell * cc + c] += q[c] * a; + let light = if cmyk { (1.0 - q[c]) * (1.0 - q[3]) } else { q[c] }; + px[cell * cc + c] += light * a; } } } @@ -723,7 +726,8 @@ pub fn estimate_vignette(layers: &[(&Surface, &Placement)], size: (usize, usize) } /// `surf`, warped into canvas coordinates by `pl` from a `size` frame, with the falloff `vignette` -/// ([`estimate_vignette`]) divided out of its colour channels. +/// ([`estimate_vignette`]) divided out of its colour channels. CMYK brightens the light of C, M and Y; K's light +/// multiplies theirs, so brightening it as well would brighten twice. pub fn remove_vignette(surf: &Surface, pl: &Placement, size: (usize, usize), vignette: [f64; 2]) -> Surface { let fmt = surf.format(); let (n, cc) = (fmt.channels(), fmt.mode.color_channels()); @@ -736,7 +740,7 @@ pub fn remove_vignette(surf: &Surface, pl: &Placement, size: (usize, usize), vig surf.read_region_into(line, &mut row); for (x, q) in (b.x0..).zip(row.chunks_exact_mut(n)) { let f = photo.factor(0, 0, source_r2(pl, size, x as f64 + 0.5, y as f64 + 0.5)); - for v in &mut q[..cc] { + for v in &mut q[..if fmt.mode == ColorMode::Cmyk { 3 } else { cc }] { *v = scale_sample(*v, f, fmt); } } diff --git a/crates/engine-vector/src/cmd/align_cmds.rs b/crates/engine-vector/src/cmd/align_cmds.rs index 1c3ce12df3..3e1b39879d 100644 --- a/crates/engine-vector/src/cmd/align_cmds.rs +++ b/crates/engine-vector/src/cmd/align_cmds.rs @@ -167,8 +167,18 @@ fn auto_align(s: &mut Session, p: &Value) -> Result { let mut reference_px = None; let mut warnings: Vec = Vec::new(); if vignette { + // The reference keeps its own pixels, but its placement carries the lens distortion `k1` that Geometric + // Distortion may fit: the estimate reads it warped by that placement, as it reads the layers that moved, and its + // correction measures radii in its own pixels, with no distortion. + let still_warped = match still { + Some((i, pl)) if pl.k1 != 0.0 => { + let b = surfs[i].content_bounds(); + Some(if b.is_empty() { surfs[i].clone() } else { warp_placed(surfs[i], b, (0.0, 0.0), pl, (0.0, 0.0), interp)? }) + } + _ => None, + }; let mut layers: Vec<(&Surface, &Placement)> = warped.iter().zip(&moves).filter_map(|((_, px, _), &i)| Some((px, al.placements[i].as_ref()?))).collect(); - layers.extend(still.map(|(i, pl)| (surfs[i], pl))); + layers.extend(still.map(|(i, pl)| (still_warped.as_ref().unwrap_or(surfs[i]), pl))); let v = estimate_vignette(&layers, size)?; if negligible(v) { warnings.push(NO_VIGNETTE.to_owned()); @@ -184,7 +194,7 @@ fn auto_align(s: &mut Session, p: &Value) -> Result { warnings .push(format!("Vignette Removal left the locked reference layer \"{}\" as it was", doc.layer(ids[i]).map_or("", |l| l.name.as_str()))); } else { - reference_px = Some((ids[i], remove_vignette(surfs[i], pl, size, v))); + reference_px = Some((ids[i], remove_vignette(surfs[i], &Placement { k1: 0.0, ..pl.clone() }, size, v))); } } } diff --git a/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs b/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs index a3e845b6a7..5fed7bd397 100644 --- a/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs +++ b/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs @@ -1,6 +1,8 @@ //! Auto-Align's Vignette Removal (#14197): one falloff estimated from the layers' overlaps, as Photomerge does, and //! divided out of every aligned layer; off, and under Collage or Reposition, the layers come out as before. +use photocraft_color::{ColorMode, PixelFormat}; + use super::*; const W: i32 = 400; @@ -29,21 +31,31 @@ fn scene() -> Vec<[f32; 3]> { px } +/// The CMYK test layers' black ink, everywhere. +const BLACK_INK: f32 = 0.1; + /// A canvas-sized layer: the scene seen from (`ox`, `oy`), darkened towards the corners by `exp(falloff · r²)` -/// (r = 1 at a corner), as a lens does. +/// (r = 1 at a corner), as a lens does. In CMYK the scene's light is printed in C, M and Y over [`BLACK_INK`]. fn photo_layer(s: &mut Session, name: &str, ox: i32, oy: i32, falloff: f32) -> LayerId { let px = scene(); s.execute("layer.new.layer", json!({"name": name})).unwrap(); let id = s.active().unwrap().active_layer.unwrap(); s.edit("photo", |doc, _| { let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); - let mut row = vec![0.0f32; W as usize * 4]; + let fmt = surf.format(); + let n = fmt.channels(); + let mut row = vec![0.0f32; W as usize * n]; for y in 0..H { for x in 0..W { let (dx, dy) = (x as f32 + 0.5 - W as f32 / 2.0, y as f32 + 0.5 - H as f32 / 2.0); let v = (falloff * (dx * dx + dy * dy) / ((W * W + H * H) as f32 / 4.0)).exp(); let c = px[((y + oy) * (W + 120) + x + ox) as usize]; - row[x as usize * 4..x as usize * 4 + 4].copy_from_slice(&[c[0] * v, c[1] * v, c[2] * v, 1.0]); + let q = &mut row[x as usize * n..(x as usize + 1) * n]; + if fmt.mode == ColorMode::Cmyk { + q.copy_from_slice(&[1.0 - c[0] * v, 1.0 - c[1] * v, 1.0 - c[2] * v, BLACK_INK, 1.0]); + } else { + q.copy_from_slice(&[c[0] * v, c[1] * v, c[2] * v, 1.0]); + } } surf.write_region(Rect::new(0, y, W, y + 1), &row); } @@ -53,10 +65,15 @@ fn photo_layer(s: &mut Session, name: &str, ox: i32, oy: i32, falloff: f32) -> L id } -/// Two vignetted photos of one scene, 60 x 40 px apart, both selected. +/// Two vignetted photos of one scene, `shift` apart, both selected. fn pair(falloff: f32, shift: (i32, i32)) -> (Session, [LayerId; 2]) { + pair_in("rgb", falloff, shift) +} + +/// [`pair`] in a document of colour mode `mode`. +fn pair_in(mode: &str, falloff: f32, shift: (i32, i32)) -> (Session, [LayerId; 2]) { let mut s = crate::session(); - s.execute("file.new", json!({"width": W, "height": H, "background": "transparent"})).unwrap(); + s.execute("file.new", json!({"width": W, "height": H, "mode": mode, "background": "transparent"})).unwrap(); let a = photo_layer(&mut s, "A", 0, 0, falloff); let b = photo_layer(&mut s, "B", shift.0, shift.1, falloff); s.execute("layer.select", json!({"layer": a.0})).unwrap(); @@ -68,14 +85,24 @@ fn pixels(s: &Session, id: LayerId) -> Vec { s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().read_region(Rect::new(-200, -200, W + 200, H + 200)) } +/// The red, green and blue light of pixel `q` summed: what CMYK's inks let through. +fn light(mode: ColorMode, q: &[f32]) -> f32 { + if mode == ColorMode::Cmyk { q[..3].iter().map(|c| (1.0 - c) * (1.0 - q[3])).sum() } else { q[..3].iter().sum() } +} + +fn format(s: &Session) -> PixelFormat { + s.active().unwrap().doc.pixel_format() +} + /// How far apart the two aligned layers are where both are opaque: the mean |log| of their luminance ratio. The scene is /// the same in both, so what's left is each one's vignetting at a different place in the frame. fn mismatch(s: &Session, [a, b]: [LayerId; 2]) -> f64 { let (pa, pb) = (pixels(s, a), pixels(s, b)); + let (mode, ch) = (format(s).mode, format(s).channels()); let (mut sum, mut n) = (0.0, 0usize); - for (qa, qb) in pa.as_chunks::<4>().0.iter().zip(pb.as_chunks::<4>().0) { - if qa[3] > 0.999 && qb[3] > 0.999 { - let (la, lb) = (qa[..3].iter().sum::(), qb[..3].iter().sum::()); + for (qa, qb) in pa.chunks_exact(ch).zip(pb.chunks_exact(ch)) { + if qa[ch - 1] > 0.999 && qb[ch - 1] > 0.999 { + let (la, lb) = (light(mode, qa), light(mode, qb)); sum += f64::from((la / lb).ln().abs()); n += 1; } @@ -88,9 +115,10 @@ fn mismatch(s: &Session, [a, b]: [LayerId; 2]) -> f64 { fn corners(s: &Session, id: LayerId) -> f32 { let surf = s.active().unwrap().doc.layer(id).unwrap().surface().unwrap(); let b = surf.content_bounds(); + let (mode, ch) = (format(s).mode, format(s).channels()); let mut sum = 0.0; for (x, y) in [(b.x0 + 4, b.y0 + 4), (b.x1 - 34, b.y0 + 4), (b.x0 + 4, b.y1 - 34), (b.x1 - 34, b.y1 - 34)] { - sum += surf.read_region(Rect::new(x, y, x + 30, y + 30)).as_chunks::<4>().0.iter().map(|q| q[..3].iter().sum::()).sum::(); + sum += surf.read_region(Rect::new(x, y, x + 30, y + 30)).chunks_exact(ch).map(|q| light(mode, q)).sum::(); } sum / (4.0 * 900.0 * 3.0) } @@ -103,7 +131,18 @@ fn align(s: &mut Session, params: Value) -> Value { #[test] fn shifted_vignetted_layers_come_out_flatter_with_their_corners_brightened() { - let (mut s, ids) = pair(-0.5, (60, 40)); + shifted_layers_come_out_flatter("rgb"); +} + +/// CMYK samples are ink, which grows towards darkened corners: the falloff is fitted to their light, and the light of +/// C, M and Y is brightened once, not again through K's. +#[test] +fn shifted_vignetted_cmyk_layers_come_out_flatter_with_their_corners_brightened() { + shifted_layers_come_out_flatter("cmyk"); +} + +fn shifted_layers_come_out_flatter(mode: &str) { + let (mut s, ids) = pair_in(mode, -0.5, (60, 40)); let r = align(&mut s, json!({"projection": "auto"})); assert_eq!(r["vignette"], Value::Null, "off by default: {r}"); let (before, plain) = (mismatch(&s, ids), ids.map(|id| pixels(&s, id))); From 1a63bb9068a63852226d37e935dbf1f441d38263 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:22:51 +0100 Subject: [PATCH 10/15] Auto-Align Vignette Removal: thin K when C, M and Y can't carry it; Lab without a cast (#14197) - CMYK: the light the inks let through is brightened once and re-encoded. C, M and Y thin out while they can carry it, and K thins out as far as the brightest light needs, so a grey printed in K alone brightens too. Where C, M and Y can carry it, the result is as before. - Lab: the estimate reads one channel, L as sRGB-encoded luminance, and the correction brightens that light and turns it back into L. a and b grow with (L* + 16), as they do when the light itself is brighter, so a neutral pixel stays neutral instead of taking a cast. New tests: shifted_vignetted_cmyk_layers_in_black_ink_alone_come_out_flatter_with_their_corners_brightened, shifted_vignetted_lab_layers_come_out_flatter_without_a_colour_cast. Both fail without the change. --- crates/engine-core/src/cmd/photo_cmds.rs | 81 +++++++++++++++++-- .../align_cmds/auto_align_vignette_tests.rs | 69 ++++++++++++---- 2 files changed, 129 insertions(+), 21 deletions(-) diff --git a/crates/engine-core/src/cmd/photo_cmds.rs b/crates/engine-core/src/cmd/photo_cmds.rs index d231d0dbca..0525c6627d 100644 --- a/crates/engine-core/src/cmd/photo_cmds.rs +++ b/crates/engine-core/src/cmd/photo_cmds.rs @@ -663,11 +663,13 @@ fn scale_sample(v: f32, f: f32, fmt: PixelFormat) -> f32 { const VIGNETTE_SIDE: usize = 1024; /// The light in `surf`'s colour channels and its coverage, box-averaged over `k × k` pixels on a grid aligned to the -/// origin. CMYK reads as the red, green and blue light its inks let through, since the estimate fits light, not ink. +/// origin. The estimate fits light: CMYK reads as the red, green and blue light its inks let through, Lab as one +/// channel, its lightness as encoded luminance ([`lab_light`]). fn roi_downsampled(surf: &Surface, k: usize) -> Result { let fmt = surf.format(); let cmyk = fmt.mode == ColorMode::Cmyk; - let (n, cc) = (fmt.channels(), if cmyk { 3 } else { fmt.mode.color_channels() }); + let lab = fmt.mode == ColorMode::Lab; + let (n, cc) = (fmt.channels(), if cmyk { 3 } else if lab { 1 } else { fmt.mode.color_channels() }); let b = surf.content_bounds(); if b.is_empty() { return Ok(RoiImage { x0: 0, y0: 0, w: 0, h: 0, ch: cc, px: Vec::new(), alpha: Vec::new() }); @@ -691,7 +693,13 @@ fn roi_downsampled(surf: &Surface, k: usize) -> Result { let a = if fmt.alpha { q[n - 1] } else { 1.0 }; alpha[cell] += a; for c in 0..cc { - let light = if cmyk { (1.0 - q[c]) * (1.0 - q[3]) } else { q[c] }; + let light = if cmyk { + (1.0 - q[c]) * (1.0 - q[3]) + } else if lab { + lab_light(q[0]) + } else { + q[c] + }; px[cell * cc + c] += light * a; } } @@ -726,8 +734,8 @@ pub fn estimate_vignette(layers: &[(&Surface, &Placement)], size: (usize, usize) } /// `surf`, warped into canvas coordinates by `pl` from a `size` frame, with the falloff `vignette` -/// ([`estimate_vignette`]) divided out of its colour channels. CMYK brightens the light of C, M and Y; K's light -/// multiplies theirs, so brightening it as well would brighten twice. +/// ([`estimate_vignette`]) divided out of its colour channels: of the light that CMYK's inks let through +/// ([`brighten_cmyk`]) and of Lab's lightness ([`brighten_lab`]). pub fn remove_vignette(surf: &Surface, pl: &Placement, size: (usize, usize), vignette: [f64; 2]) -> Surface { let fmt = surf.format(); let (n, cc) = (fmt.channels(), fmt.mode.color_channels()); @@ -740,8 +748,14 @@ pub fn remove_vignette(surf: &Surface, pl: &Placement, size: (usize, usize), vig surf.read_region_into(line, &mut row); for (x, q) in (b.x0..).zip(row.chunks_exact_mut(n)) { let f = photo.factor(0, 0, source_r2(pl, size, x as f64 + 0.5, y as f64 + 0.5)); - for v in &mut q[..if fmt.mode == ColorMode::Cmyk { 3 } else { cc }] { - *v = scale_sample(*v, f, fmt); + match fmt.mode { + ColorMode::Cmyk => brighten_cmyk(q, f, fmt), + ColorMode::Lab => brighten_lab(q, f, fmt), + _ => { + for v in &mut q[..cc] { + *v = scale_sample(*v, f, fmt); + } + } } } out.write_region(line, &row); @@ -749,6 +763,59 @@ pub fn remove_vignette(surf: &Surface, pl: &Placement, size: (usize, usize), vig out } +/// CMYK pixel `q` with the red, green and blue light its inks let through brightened by the factor `f`, within range +/// unless float. Only C, M and Y thin out while they can carry it; K thins out as far as the brightest light needs, so a +/// grey printed in K alone still brightens. +fn brighten_cmyk(q: &mut [f32], f: f32, fmt: PixelFormat) { + let float = fmt.sample == SampleType::F32; + let light: [f32; 3] = std::array::from_fn(|c| { + let l = (1.0 - q[c]) * (1.0 - q[3]) * f; + if float { l } else { l.clamp(0.0, 1.0) } + }); + let k = q[3].min(1.0 - light.iter().fold(0.0f32, |a, l| a.max(*l))).max(0.0); + if k >= 1.0 { + return; + } + for c in 0..3 { + let v = 1.0 - light[c] / (1.0 - k); + q[c] = if float { v } else { v.clamp(0.0, 1.0) }; + } + q[3] = k; +} + +/// Lab's encoded L (0..1 for L* 0..100) as relative luminance Y. +fn lab_luminance(l: f32) -> f32 { + let t = (l * 100.0 + 16.0) / 116.0; + if t > 6.0 / 29.0 { t * t * t } else { 3.0 * (6.0f32 / 29.0).powi(2) * (t - 4.0 / 29.0) } +} + +/// Relative luminance `y` as Lab's encoded L. +fn lab_lightness(y: f32) -> f32 { + let t = if y > (6.0f32 / 29.0).powi(3) { y.cbrt() } else { y / (3.0 * (6.0f32 / 29.0).powi(2)) + 4.0 / 29.0 }; + (116.0 * t - 16.0) / 100.0 +} + +/// Lab's encoded L as the sRGB-encoded luminance the vignette is fitted to and divided out of, as RGB's encoded values +/// are. +fn lab_light(l: f32) -> f32 { + photocraft_color::convert::linear_to_srgb(lab_luminance(l).max(0.0)) +} + +/// Lab pixel `q` with its light ([`lab_light`]) brightened by the factor `f`. a and b grow with `(L* + 16)`, as they do +/// when the light itself is brighter, so a neutral pixel stays neutral. +fn brighten_lab(q: &mut [f32], f: f32, fmt: PixelFormat) { + let float = fmt.sample == SampleType::F32; + let light = scale_sample(lab_light(q[0]), f, fmt); + let l = lab_lightness(photocraft_color::convert::srgb_to_linear(light)); + let l = if float { l } else { l.clamp(0.0, 1.0) }; + let grow = (l * 100.0 + 16.0) / (q[0] * 100.0 + 16.0).max(1e-6); + q[0] = l; + for v in &mut q[1..3] { + let ab = ((*v * 255.0 - 128.0) * grow + 128.0) / 255.0; + *v = if float { ab } else { ab.clamp(0.0, 1.0) }; + } +} + /// Per-image seam weights (1 inside an image's seam region, else 0) over each ROI. fn compute_seam_weights(rois: &[RoiImage], canvas: Rect, order: &[usize]) -> Vec> { let n = rois.len(); diff --git a/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs b/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs index 5fed7bd397..bef3ceb0af 100644 --- a/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs +++ b/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs @@ -1,6 +1,7 @@ //! Auto-Align's Vignette Removal (#14197): one falloff estimated from the layers' overlaps, as Photomerge does, and //! divided out of every aligned layer; off, and under Collage or Reposition, the layers come out as before. +use photocraft_color::convert::{lab_to_srgb, srgb_to_lab}; use photocraft_color::{ColorMode, PixelFormat}; use super::*; @@ -35,8 +36,9 @@ fn scene() -> Vec<[f32; 3]> { const BLACK_INK: f32 = 0.1; /// A canvas-sized layer: the scene seen from (`ox`, `oy`), darkened towards the corners by `exp(falloff · r²)` -/// (r = 1 at a corner), as a lens does. In CMYK the scene's light is printed in C, M and Y over [`BLACK_INK`]. -fn photo_layer(s: &mut Session, name: &str, ox: i32, oy: i32, falloff: f32) -> LayerId { +/// (r = 1 at a corner), as a lens does. `look` is the document's mode, or `cmyk-k` for the scene in grey in K alone; in +/// `cmyk` the scene's light is printed in C, M and Y over [`BLACK_INK`]. +fn photo_layer(s: &mut Session, look: &str, name: &str, ox: i32, oy: i32, falloff: f32) -> LayerId { let px = scene(); s.execute("layer.new.layer", json!({"name": name})).unwrap(); let id = s.active().unwrap().active_layer.unwrap(); @@ -51,10 +53,15 @@ fn photo_layer(s: &mut Session, name: &str, ox: i32, oy: i32, falloff: f32) -> L let v = (falloff * (dx * dx + dy * dy) / ((W * W + H * H) as f32 / 4.0)).exp(); let c = px[((y + oy) * (W + 120) + x + ox) as usize]; let q = &mut row[x as usize * n..(x as usize + 1) * n]; - if fmt.mode == ColorMode::Cmyk { - q.copy_from_slice(&[1.0 - c[0] * v, 1.0 - c[1] * v, 1.0 - c[2] * v, BLACK_INK, 1.0]); - } else { - q.copy_from_slice(&[c[0] * v, c[1] * v, c[2] * v, 1.0]); + let c = c.map(|c| c * v); + match look { + "cmyk" => q.copy_from_slice(&[1.0 - c[0], 1.0 - c[1], 1.0 - c[2], BLACK_INK, 1.0]), + "cmyk-k" => q.copy_from_slice(&[0.0, 0.0, 0.0, 1.0 - (c[0] + c[1] + c[2]) / 3.0, 1.0]), + "lab" => { + let [l, a, b] = srgb_to_lab(c); + q.copy_from_slice(&[l / 100.0, (a + 128.0) / 255.0, (b + 128.0) / 255.0, 1.0]); + } + _ => q.copy_from_slice(&[c[0], c[1], c[2], 1.0]), } } surf.write_region(Rect::new(0, y, W, y + 1), &row); @@ -70,12 +77,13 @@ fn pair(falloff: f32, shift: (i32, i32)) -> (Session, [LayerId; 2]) { pair_in("rgb", falloff, shift) } -/// [`pair`] in a document of colour mode `mode`. -fn pair_in(mode: &str, falloff: f32, shift: (i32, i32)) -> (Session, [LayerId; 2]) { +/// [`pair`] drawn as [`photo_layer`]'s `look`. +fn pair_in(look: &str, falloff: f32, shift: (i32, i32)) -> (Session, [LayerId; 2]) { let mut s = crate::session(); + let mode = look.split('-').next().unwrap_or(look); s.execute("file.new", json!({"width": W, "height": H, "mode": mode, "background": "transparent"})).unwrap(); - let a = photo_layer(&mut s, "A", 0, 0, falloff); - let b = photo_layer(&mut s, "B", shift.0, shift.1, falloff); + let a = photo_layer(&mut s, look, "A", 0, 0, falloff); + let b = photo_layer(&mut s, look, "B", shift.0, shift.1, falloff); s.execute("layer.select", json!({"layer": a.0})).unwrap(); s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); (s, [a, b]) @@ -85,9 +93,13 @@ fn pixels(s: &Session, id: LayerId) -> Vec { s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().read_region(Rect::new(-200, -200, W + 200, H + 200)) } -/// The red, green and blue light of pixel `q` summed: what CMYK's inks let through. +/// The red, green and blue light of pixel `q` summed: what CMYK's inks let through, and Lab's colour in sRGB. fn light(mode: ColorMode, q: &[f32]) -> f32 { - if mode == ColorMode::Cmyk { q[..3].iter().map(|c| (1.0 - c) * (1.0 - q[3])).sum() } else { q[..3].iter().sum() } + match mode { + ColorMode::Cmyk => q[..3].iter().map(|c| (1.0 - c) * (1.0 - q[3])).sum(), + ColorMode::Lab => lab_to_srgb([q[0] * 100.0, q[1] * 255.0 - 128.0, q[2] * 255.0 - 128.0]).iter().sum(), + _ => q[..3].iter().sum(), + } } fn format(s: &Session) -> PixelFormat { @@ -141,8 +153,36 @@ fn shifted_vignetted_cmyk_layers_come_out_flatter_with_their_corners_brightened( shifted_layers_come_out_flatter("cmyk"); } -fn shifted_layers_come_out_flatter(mode: &str) { - let (mut s, ids) = pair_in(mode, -0.5, (60, 40)); +/// A grey printed in K alone can only brighten if K thins out. +#[test] +fn shifted_vignetted_cmyk_layers_in_black_ink_alone_come_out_flatter_with_their_corners_brightened() { + shifted_layers_come_out_flatter("cmyk-k"); +} + +/// Lab's lightness is brightened, and its a and b only as far as a brighter light would take them: no colour cast. +#[test] +fn shifted_vignetted_lab_layers_come_out_flatter_without_a_colour_cast() { + let ab = |s: &Session, id: LayerId| { + let surf = s.active().unwrap().doc.layer(id).unwrap().surface().unwrap(); + let b = surf.content_bounds(); + let px = surf.read_region(Rect::new(b.x0 + 4, b.y0 + 4, b.x0 + 34, b.y0 + 34)); + let mean = |c: usize| px.as_chunks::<4>().0.iter().map(|q| q[c] * 255.0 - 128.0).sum::() / 900.0; + [mean(1), mean(2)] + }; + let (mut s, ids) = pair_in("lab", -0.5, (60, 40)); + align(&mut s, json!({"projection": "auto"})); + let before = ids.map(|id| ab(&s, id)); + let (s, ids) = shifted_layers_come_out_flatter("lab"); + for (i, id) in ids.into_iter().enumerate() { + let after = ab(&s, id); + assert!((0..2).all(|c| (after[c] - before[i][c]).abs() < 5.0), "layer {i}'s corner a and b stay put: {after:?} vs {:?}", before[i]); + } +} + +/// Aligns a shifted vignetted pair drawn as `look` without and with Vignette Removal, checks the second is flatter with +/// brighter corners, and returns it. +fn shifted_layers_come_out_flatter(look: &str) -> (Session, [LayerId; 2]) { + let (mut s, ids) = pair_in(look, -0.5, (60, 40)); let r = align(&mut s, json!({"projection": "auto"})); assert_eq!(r["vignette"], Value::Null, "off by default: {r}"); let (before, plain) = (mismatch(&s, ids), ids.map(|id| pixels(&s, id))); @@ -160,6 +200,7 @@ fn shifted_layers_come_out_flatter(mode: &str) { for (i, id) in ids.into_iter().enumerate() { assert!(corners(&s, id) > dark[i] * 1.1, "layer {i}'s corners are brighter, the reference's too: {r}"); } + (s, ids) } #[test] From c193177e5bdcad0954023d50efd6f1c62c6bbd67 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:33:56 +0100 Subject: [PATCH 11/15] Auto-Align Vignette Removal: brighten Lab through XYZ, in the toe of L* too (#14197) Lab's a and b grew with (L* + 16), which matches brighter light only where Lab's companding is a cube root; in the linear toe (L* below about 8) it changed the shadows' saturation. The correction now turns the pixel into X, Y and Z relative to white, scales all three by the luminance ratio, and encodes it back with the piecewise companding. New test: a_brightened_lab_shadow_keeps_its_colour (fails without the change). --- crates/engine-core/src/cmd/photo_cmds.rs | 44 ++++++++++--------- .../engine-core/src/cmd/photo_cmds/tests.rs | 18 ++++++++ 2 files changed, 41 insertions(+), 21 deletions(-) diff --git a/crates/engine-core/src/cmd/photo_cmds.rs b/crates/engine-core/src/cmd/photo_cmds.rs index 0525c6627d..998926275c 100644 --- a/crates/engine-core/src/cmd/photo_cmds.rs +++ b/crates/engine-core/src/cmd/photo_cmds.rs @@ -783,36 +783,38 @@ fn brighten_cmyk(q: &mut [f32], f: f32, fmt: PixelFormat) { q[3] = k; } -/// Lab's encoded L (0..1 for L* 0..100) as relative luminance Y. -fn lab_luminance(l: f32) -> f32 { - let t = (l * 100.0 + 16.0) / 116.0; - if t > 6.0 / 29.0 { t * t * t } else { 3.0 * (6.0f32 / 29.0).powi(2) * (t - 4.0 / 29.0) } +/// CIE L*a*b*'s companding: a tristimulus value relative to white → its `f`, a cube root above a linear toe. +fn lab_f(t: f32) -> f32 { + if t > (6.0f32 / 29.0).powi(3) { t.cbrt() } else { t / (3.0 * (6.0f32 / 29.0).powi(2)) + 4.0 / 29.0 } } -/// Relative luminance `y` as Lab's encoded L. -fn lab_lightness(y: f32) -> f32 { - let t = if y > (6.0f32 / 29.0).powi(3) { y.cbrt() } else { y / (3.0 * (6.0f32 / 29.0).powi(2)) + 4.0 / 29.0 }; - (116.0 * t - 16.0) / 100.0 +/// The inverse of [`lab_f`]. +fn lab_f_inv(f: f32) -> f32 { + if f > 6.0 / 29.0 { f * f * f } else { 3.0 * (6.0f32 / 29.0).powi(2) * (f - 4.0 / 29.0) } } -/// Lab's encoded L as the sRGB-encoded luminance the vignette is fitted to and divided out of, as RGB's encoded values -/// are. +/// Lab's encoded L (0..1 for L* 0..100) as the sRGB-encoded luminance the vignette is fitted to and divided out of, as +/// RGB's encoded values are. fn lab_light(l: f32) -> f32 { - photocraft_color::convert::linear_to_srgb(lab_luminance(l).max(0.0)) + photocraft_color::convert::linear_to_srgb(lab_f_inv((l * 100.0 + 16.0) / 116.0).max(0.0)) } -/// Lab pixel `q` with its light ([`lab_light`]) brightened by the factor `f`. a and b grow with `(L* + 16)`, as they do -/// when the light itself is brighter, so a neutral pixel stays neutral. +/// Lab pixel `q` with its light ([`lab_light`]) brightened by the factor `f`: X, Y and Z grow by the same ratio, as they +/// do when the light itself is brighter, so a neutral pixel stays neutral and a colour keeps its hue and saturation. fn brighten_lab(q: &mut [f32], f: f32, fmt: PixelFormat) { let float = fmt.sample == SampleType::F32; - let light = scale_sample(lab_light(q[0]), f, fmt); - let l = lab_lightness(photocraft_color::convert::srgb_to_linear(light)); - let l = if float { l } else { l.clamp(0.0, 1.0) }; - let grow = (l * 100.0 + 16.0) / (q[0] * 100.0 + 16.0).max(1e-6); - q[0] = l; - for v in &mut q[1..3] { - let ab = ((*v * 255.0 - 128.0) * grow + 128.0) / 255.0; - *v = if float { ab } else { ab.clamp(0.0, 1.0) }; + let fy = (q[0] * 100.0 + 16.0) / 116.0; + let (a, b) = (q[1] * 255.0 - 128.0, q[2] * 255.0 - 128.0); + let xyz = [lab_f_inv(fy + a / 500.0), lab_f_inv(fy), lab_f_inv(fy - b / 200.0)]; + if xyz[1] <= 0.0 { + return; + } + let light = scale_sample(photocraft_color::convert::linear_to_srgb(xyz[1]), f, fmt); + let grow = photocraft_color::convert::srgb_to_linear(light) / xyz[1]; + let [fx, fy, fz] = xyz.map(|t| lab_f(t * grow)); + let lab = [(116.0 * fy - 16.0) / 100.0, (500.0 * (fx - fy) + 128.0) / 255.0, (200.0 * (fy - fz) + 128.0) / 255.0]; + for (v, n) in q.iter_mut().zip(lab) { + *v = if float { n } else { n.clamp(0.0, 1.0) }; } } diff --git a/crates/engine-core/src/cmd/photo_cmds/tests.rs b/crates/engine-core/src/cmd/photo_cmds/tests.rs index 23baa9f901..0a2c17863f 100644 --- a/crates/engine-core/src/cmd/photo_cmds/tests.rs +++ b/crates/engine-core/src/cmd/photo_cmds/tests.rs @@ -654,3 +654,21 @@ fn photomerge_open_documents_ignores_the_folder() { let _ = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "reposition", "paths": paths})); } } + +/// Vignette Removal brightens a Lab colour as brighter light would, in the linear toe of L* too: its linear red, green +/// and blue grow by one ratio, so the colour keeps its hue and saturation (#14197). +#[test] +fn a_brightened_lab_shadow_keeps_its_colour() { + use photocraft_color::convert::{lab_to_srgb, srgb_to_linear}; + let linear = |q: &[f32]| lab_to_srgb([q[0] * 100.0, q[1] * 255.0 - 128.0, q[2] * 255.0 - 128.0]).map(srgb_to_linear); + let fmt = PixelFormat::new(ColorMode::Lab, SampleType::F32, true); + for lab in [[4.0f32, 3.0, -2.0], [40.0, 20.0, -15.0]] { + let mut q = [lab[0] / 100.0, (lab[1] + 128.0) / 255.0, (lab[2] + 128.0) / 255.0, 1.0]; + let before = linear(&q); + brighten_lab(&mut q, 1.3, fmt); + let after = linear(&q); + let grow = after.iter().zip(&before).map(|(a, b)| a / b).collect::>(); + assert!(grow[0] > 1.0, "{lab:?} brightens: {grow:?}"); + assert!(grow.iter().all(|g| (g / grow[0] - 1.0).abs() < 0.01), "{lab:?}: every channel grows alike: {before:?} → {after:?}"); + } +} From d4380ddf5919febbd13d43450db969eec31e7a7a Mon Sep 17 00:00:00 2001 From: Dan Date: Sun, 29 Nov 2026 11:36:15 +0000 Subject: [PATCH 12/15] Honor the rotation direction in recorded Crop actions (#17690) --- .../src/cmd/atn_cmds/crop_angle_sign_tests.rs | 106 ++++++++++++++++++ .../engine-core/src/cmd/atn_cmds/steps_doc.rs | 9 +- 2 files changed, 113 insertions(+), 2 deletions(-) create mode 100644 crates/engine-core/src/cmd/atn_cmds/crop_angle_sign_tests.rs diff --git a/crates/engine-core/src/cmd/atn_cmds/crop_angle_sign_tests.rs b/crates/engine-core/src/cmd/atn_cmds/crop_angle_sign_tests.rs new file mode 100644 index 0000000000..01fe9955e1 --- /dev/null +++ b/crates/engine-core/src/cmd/atn_cmds/crop_angle_sign_tests.rs @@ -0,0 +1,106 @@ +use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; +use craft_psd::descriptor::{UnicodeString, Value as D}; +use photocraft_doc::{LayerContent, LayerId, Size, SmartObject}; +use photocraft_geom::{Point, Rect}; +use photocraft_paint::tile::{b64_decode, b64_encode}; +use serde_json::json; + +use super::{ang, desc, get_num, px}; +use crate::Session; + +fn document() -> (Session, LayerId, LayerId) { + let mut s = crate::session(); + s.execute("prefs.set", json!({"path": "actions.createSingleHistoryState", "value": false})).unwrap(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Embedded square"})).unwrap(); + s.edit("Paint square", |doc, active| { + let surface = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surface.fill_rect(Rect::new(150, 100, 250, 200), &[0.2, 0.4, 0.8, 1.0]); + Ok(()) + }) + .unwrap(); + let converted = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let shape = s.execute("shape.create", json!({"kind": "rect", "rect": [250, 20, 140, 70], "fill": "#ff6600"})).unwrap(); + (s, LayerId(converted["layer"].as_u64().unwrap()), LayerId(shape["layer"].as_u64().unwrap())) +} + +fn smart_object(s: &Session, id: LayerId) -> &SmartObject { + let LayerContent::Smart(smart) = &s.active().unwrap().doc.layer(id).unwrap().content else { panic!("expected a Smart Object") }; + smart +} + +fn shape_corners(s: &Session, id: LayerId) -> Vec { + let LayerContent::Shape(shape) = &s.active().unwrap().doc.layer(id).unwrap().content else { panic!("expected a shape") }; + shape.path.subpaths[0].knots.iter().map(|knot| knot.anchor).collect() +} + +fn play_atn(s: &mut Session, data: &str) { + let loaded = s.execute("actions.load", json!({"data": data})).unwrap(); + assert_eq!(loaded["unsupported"], json!([]), "{loaded}"); + let before = s.active().unwrap().history.past_len(); + let played = s.execute("actions.play", json!({"action": loaded["actions"][0]})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + assert!(played.get("failed").is_none(), "{played}"); + let state = s.active().unwrap(); + assert_eq!(state.history.past_len(), before + 1); + assert_eq!(state.history.undo_label(), Some("Crop")); + assert_eq!(state.doc.size, Size::new(300, 200)); +} + +#[test] +fn imported_crop_turns_shape_and_smart_object_clockwise() { + let frame = desc("Rctn").with("Top ", px(50.0)).with("Left", px(50.0)).with("Btom", px(250.0)).with("Rght", px(350.0)); + let crop = desc("null").with("To ", D::Descriptor(frame)).with("Angl", ang(10.0)).with("Dlt ", D::Boolean(false)); + let file = AtnFile { + name: UnicodeString::new_nul("Crops"), + actions: vec![AtnAction { + name: UnicodeString::new_nul("Turn and crop"), + items: vec![AtnItem { event: AtnEvent::Code(*b"Crop"), dictionary: b"Crop".to_vec(), descriptor: Some(crop), ..Default::default() }], + ..Default::default() + }], + ..Default::default() + }; + let (mut s, smart, shape) = document(); + let origin = smart_object(&s, smart).source.clone(); + play_atn(&mut s, &b64_encode(&atn::write(&file).unwrap())); + + let placed = smart_object(&s, smart); + assert_eq!(placed.source, origin); + let corners = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| placed.transform.apply(Point::new(x, y))); + for (point, (x, y)) in corners.into_iter().zip([(109.4, 42.1), (207.9, 59.4), (190.6, 157.9), (92.1, 140.6)]) { + assert!((point.x - x).abs() <= 1.0 && (point.y - y).abs() <= 1.0, "{point:?} expected ({x}, {y})"); + } + + let corners = shape_corners(&s, shape); + let bounds = [ + corners.iter().map(|p| p.x).fold(f64::INFINITY, f64::min), + corners.iter().map(|p| p.y).fold(f64::INFINITY, f64::min), + corners.iter().map(|p| p.x).fold(f64::NEG_INFINITY, f64::max), + corners.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max), + ]; + for (edge, expected) in bounds.into_iter().zip([209.0, -20.0, 360.0, 74.0]) { + assert!((edge - expected).abs() <= 1.0, "{bounds:?}"); + } +} + +#[test] +fn recorded_crop_exports_a_canvas_angle_and_replays_the_same_geometry() { + for angle in [-10.0, 6.5] { + let (mut recorded, smart, shape) = document(); + recorded.execute("actions.record", json!({"name": "Turn and crop"})).unwrap(); + recorded.execute("image.crop", json!({"x": 50, "y": 50, "width": 300, "height": 200, "angle": angle, "deleteCroppedPixels": false})).unwrap(); + recorded.execute("actions.stop", json!({})).unwrap(); + let saved = recorded.execute("actions.save", json!({"action": "Turn and crop"})).unwrap(); + assert_eq!(saved["skipped"], json!([])); + let data = saved["data"].as_str().unwrap(); + let file = atn::parse(&b64_decode(data).unwrap()).unwrap(); + let [step] = file.actions[0].items.as_slice() else { panic!("expected a single Crop step") }; + assert_eq!(step.event.id(), "Crop"); + assert_eq!(get_num(step.descriptor.as_ref().unwrap(), "Angl"), Some(-angle)); + + let (mut replayed, replayed_smart, replayed_shape) = document(); + play_atn(&mut replayed, data); + assert_eq!(smart_object(&replayed, replayed_smart).transform, smart_object(&recorded, smart).transform); + assert_eq!(shape_corners(&replayed, replayed_shape), shape_corners(&recorded, shape)); + } +} diff --git a/crates/engine-core/src/cmd/atn_cmds/steps_doc.rs b/crates/engine-core/src/cmd/atn_cmds/steps_doc.rs index 9dcc36a101..98f28c0426 100644 --- a/crates/engine-core/src/cmd/atn_cmds/steps_doc.rs +++ b/crates/engine-core/src/cmd/atn_cmds/steps_doc.rs @@ -7,6 +7,10 @@ use super::fields::{Mapped, none, step, steps}; use super::tables::{ALIGN, EXTENSION, INTENT, INTERPOLATION, MODES, PROFILES, PURGE, SAVE_FORMATS, lookup, lookup_back}; use super::{D, Descriptor, Id, Map, ReferenceItem, STOP_MESSAGE, UnicodeString, Value, json}; +#[cfg(test)] +#[path = "crop_angle_sign_tests.rs"] +mod crop_angle_sign_tests; + /// `placeEvent`: File › Place Embedded / Linked, with the file and the recorded scale. pub(super) fn place_from(d: &Descriptor) -> Mapped { let Some(path) = d.get("null").and_then(path_text) else { return Mapped::Unsupported { harmless: false } }; @@ -631,7 +635,8 @@ pub(super) fn crop_from(d: &Descriptor) -> Mapped { p.insert("height".into(), (bottom - top).round().into()); } if let Some(a) = get_num(d, "Angl") { - p.insert("angle".into(), a.into()); + // ATN records the canvas turn. PhotoCraft's Crop angle describes the frame's turn. + p.insert("angle".into(), (-a).into()); } if let Some(del) = get_bool(d, "Dlt ") { p.insert("deleteCroppedPixels".into(), del.into()); @@ -650,7 +655,7 @@ pub(super) fn crop_to(_: &str, p: &Value) -> Option { d = d.with("To ", D::Descriptor(desc("Rctn").with("Top ", px(y)).with("Left", px(x)).with("Btom", px(y + h)).with("Rght", px(x + w)))); } if let Some(a) = jnum(p, "angle") { - d = d.with("Angl", ang(a)); + d = d.with("Angl", ang(-a)); } if let Some(del) = jbool(p, "deleteCroppedPixels") { d = d.with("Dlt ", D::Boolean(del)); From b3fbeda8dec52949713d902aab6fa6729f002b94 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 29 Nov 2026 12:59:16 +0100 Subject: [PATCH 13/15] Canvas menu Fade row: one label type for every arm; restore the label's characters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The merge's Fade arm returned a `String` while the other arms return `&str`, and the row's `Fade…` literal had been re-encoded, so it could not match. Sort the menus.rs re-export as rustfmt wants. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/canvas_tool_menu.rs | 43 +++++++++++-------- crates/ui-egui/src/menus.rs | 2 +- 2 files changed, 25 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index ec0dffb12e..cb06dcb1d8 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -1984,25 +1984,30 @@ pub fn entries(app: &PhotocraftApp, menu: &CanvasToolMenu) -> Vec> out.push(Entry::separator()); continue; }; - let text = match row_label(app, menu, label, command) { - // The same label as Edit › Fade (#13803). - "Fade…" => crate::menus::fade_label(app), - // Spelled out so `cargo xtask i18n-coverage` lists the new label. - "Free Transform Points" => tl!("Free Transform Points"), - "Fill Subpath…" => tl!("Fill Subpath…"), - "Fill Subpaths…" => tl!("Fill Subpaths…"), - "Stroke Subpath…" => tl!("Stroke Subpath…"), - "Stroke Subpaths…" => tl!("Stroke Subpaths…"), - "Rasterize Vector Mask" => tl!("Rasterize Vector Mask"), - // `layer_menu_ui::layer_count_label`'s labels, likewise (#12358). - "Duplicate Layer…" => tl!("Duplicate Layer…"), - "Delete Layer" => tl!("Delete Layer"), - "Duplicate Layers…" => tl!("Duplicate Layers…"), - "Delete Layers" => tl!("Delete Layers"), - "Rasterize Layers" => tl!("Rasterize Layers"), - "Hide Contextual Task Bar" => tl!("Hide Contextual Task Bar"), - "Show Contextual Task Bar" => tl!("Show Contextual Task Bar"), - key => tl!(key).to_string(), + let shown = row_label(app, menu, label, command); + // The same label as Edit › Fade (#13803). + let text = if shown == "Fade…" { + crate::menus::fade_label(app) + } else { + match shown { + // Spelled out so `cargo xtask i18n-coverage` lists the new label. + "Free Transform Points" => tl!("Free Transform Points"), + "Fill Subpath…" => tl!("Fill Subpath…"), + "Fill Subpaths…" => tl!("Fill Subpaths…"), + "Stroke Subpath…" => tl!("Stroke Subpath…"), + "Stroke Subpaths…" => tl!("Stroke Subpaths…"), + "Rasterize Vector Mask" => tl!("Rasterize Vector Mask"), + // `layer_menu_ui::layer_count_label`'s labels, likewise (#12358). + "Duplicate Layer…" => tl!("Duplicate Layer…"), + "Delete Layer" => tl!("Delete Layer"), + "Duplicate Layers…" => tl!("Duplicate Layers…"), + "Delete Layers" => tl!("Delete Layers"), + "Rasterize Layers" => tl!("Rasterize Layers"), + "Hide Contextual Task Bar" => tl!("Hide Contextual Task Bar"), + "Show Contextual Task Bar" => tl!("Show Contextual Task Bar"), + key => tl!(key), + } + .to_string() }; out.push(Entry::new(command.to_string(), text).enabled(entry_enabled(app, menu, command)).checked(mode_checked(app, menu, command))); } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a954dcd7ed..71be6f2e01 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -31,10 +31,10 @@ pub(crate) use invoke::{invoke_unguarded, panel_alias}; pub use items::{MenuModel, base_rows, is_live, menu_rows, model, row}; #[cfg(test)] pub(crate) use items::{fresh_bar, model_id}; -pub use state::{fade_label, is_enabled}; pub(crate) use state::reveal_label; #[cfg(test)] use state::translated_menu_label; +pub use state::{fade_label, is_enabled}; /// What may run from the menus now: the gate (a dialog, the shortcut recorder) and the per-command /// rules (a full-window workspace, a pending crop). Both bars, the runtime's command gate and From bf6229a7afa9ede395601dbc559d7741a5e965b2 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:12:58 +0100 Subject: [PATCH 14/15] Vignette estimate: the channel count as a match, which rustfmt keeps on one line each (#14197) --- crates/engine-core/src/cmd/photo_cmds.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine-core/src/cmd/photo_cmds.rs b/crates/engine-core/src/cmd/photo_cmds.rs index 998926275c..1b4ef684b0 100644 --- a/crates/engine-core/src/cmd/photo_cmds.rs +++ b/crates/engine-core/src/cmd/photo_cmds.rs @@ -669,7 +669,12 @@ fn roi_downsampled(surf: &Surface, k: usize) -> Result { let fmt = surf.format(); let cmyk = fmt.mode == ColorMode::Cmyk; let lab = fmt.mode == ColorMode::Lab; - let (n, cc) = (fmt.channels(), if cmyk { 3 } else if lab { 1 } else { fmt.mode.color_channels() }); + let n = fmt.channels(); + let cc = match fmt.mode { + ColorMode::Cmyk => 3, + ColorMode::Lab => 1, + mode => mode.color_channels(), + }; let b = surf.content_bounds(); if b.is_empty() { return Ok(RoiImage { x0: 0, y0: 0, w: 0, h: 0, ch: cc, px: Vec::new(), alpha: Vec::new() }); From 4ede13f851292a1e5fde7faa7eb8e6f32c4c977d Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 29 Nov 2026 13:20:19 +0100 Subject: [PATCH 15/15] Fade label tests: PhotocraftApp::new returns a Box on main Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/menus/fade_label_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menus/fade_label_tests.rs b/crates/ui-egui/src/menus/fade_label_tests.rs index fbf04a63c6..82d2895c02 100644 --- a/crates/ui-egui/src/menus/fade_label_tests.rs +++ b/crates/ui-egui/src/menus/fade_label_tests.rs @@ -5,7 +5,7 @@ use super::*; use serde_json::json; -fn app() -> crate::PhotocraftApp { +fn app() -> Box { let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); app