From 5baeec839620e0b1d7c03ee931e4d7095e969af7 Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Sun, 15 Nov 2026 14:09:20 +0530 Subject: [PATCH 01/25] ui: size the Canvas Size readout from the flat image (#14582) --- crates/ui-egui/src/dialogs/sizing.rs | 46 ++++++++++- .../sizing/canvas_size_readout_tests.rs | 77 +++++++++++++++++++ 2 files changed, 120 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/sizing/canvas_size_readout_tests.rs diff --git a/crates/ui-egui/src/dialogs/sizing.rs b/crates/ui-egui/src/dialogs/sizing.rs index 3f05834a88..db908023b6 100644 --- a/crates/ui-egui/src/dialogs/sizing.rs +++ b/crates/ui-egui/src/dialogs/sizing.rs @@ -153,6 +153,9 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Option { f.insert("resample".into(), json!(resample)); f.insert("__resample".into(), json!(resample)); } else { + let (channels, bytes_per_channel) = flat_format(d.mode, d.depth); + f.insert("__channels".into(), json!(channels)); + f.insert("__bytesPerChannel".into(), json!(bytes_per_channel)); f.insert("relative".into(), json!(false)); f.insert("anchor".into(), json!("center")); f.insert("extensionColor".into(), json!("background")); @@ -205,6 +208,41 @@ pub fn human_bytes(b: f64) -> String { } } +/// The flat image's format for the Canvas Size readout: colour channels (no alpha) and bytes per +/// channel, so a 400x300 RGB 8 document reads 351.6K like the reference application instead of +/// the layer-backed 469K. +fn flat_format(mode: photocraft_color::ColorMode, depth: photocraft_color::SampleType) -> (usize, usize) { + (mode.color_channels(), depth.bytes()) +} + +/// Channels × bytes per channel from the dialog fields; a missing or invalid field falls back to +/// RGB 8 (3 channels, 1 byte) so the readout never shows NaN. +fn canvas_flat_bpp(f: &Map) -> f64 { + let channels = f.get("__channels").and_then(Value::as_f64).filter(|v| v.is_finite() && *v >= 1.0).unwrap_or(3.0); + let per_channel = f.get("__bytesPerChannel").and_then(Value::as_f64).filter(|v| v.is_finite() && *v >= 1.0).unwrap_or(1.0); + channels * per_channel +} + +/// The Canvas Size readout for `bytes` of flat image data: whole bytes below 1024, one decimal +/// K/M with the system's decimal mark, today's G style above 1G. +fn canvas_size_text(bytes: f64) -> String { + let bytes = if bytes.is_finite() { bytes.max(0.0) } else { 0.0 }; + if bytes < 1024.0 { + format!("{:.0} bytes", bytes) + } else if bytes < 1024.0 * 1024.0 { + canvas_decimal(format!("{:.1}K", bytes / 1024.0)) + } else if bytes < 1024.0 * 1024.0 * 1024.0 { + canvas_decimal(format!("{:.1}M", bytes / (1024.0 * 1024.0))) + } else { + format!("{:.2}G", bytes / (1024.0 * 1024.0 * 1024.0)) + } +} + +/// The readout's `.` becomes the system decimal mark, but only when it is `,`; English tests keep `.`. +fn canvas_decimal(s: String) -> String { + if crate::i18n::decimal_separator() == Some(',') { s.replacen('.', ",", 1) } else { s } +} + pub fn body(ui: &mut egui::Ui, f: &mut Map) { if f.get("__command").and_then(Value::as_str) == Some("image.canvasSize") { canvas_size(ui, f); @@ -466,10 +504,10 @@ fn image_size(ui: &mut egui::Ui, f: &mut Map) { fn canvas_size(ui: &mut egui::Ui, f: &mut Map) { let t = Tokens::get(ui.ctx()); let (ow, oh) = (num(f, "__origW"), num(f, "__origH")); - let bpp = num(f, "__bytesPerPixel").max(1.0); + let flat = canvas_flat_bpp(f); let relative = f.get("relative").and_then(Value::as_bool).unwrap_or(false); ui.label(egui::RichText::new(tl!("Current Size")).font(crate::theme::semibold(12.0)).color(t.text)); - info_row(ui, tl!("Size:"), human_bytes(ow * oh * bpp)); + info_row(ui, tl!("Size:"), canvas_size_text(ow * oh * flat)); info_row(ui, tl!("Width:"), format!("{} px", ow as i64)); info_row(ui, tl!("Height:"), format!("{} px", oh as i64)); ui.add_space(6.0); @@ -478,7 +516,7 @@ fn canvas_size(ui: &mut egui::Ui, f: &mut Map) { let (nw, nh) = if relative { (ow + num(f, "width"), oh + num(f, "height")) } else { (num(f, "width"), num(f, "height")) }; ui.horizontal(|ui| { ui.label(egui::RichText::new(tl!("New Size")).font(crate::theme::semibold(12.0)).color(t.text)); - ui.label(egui::RichText::new(human_bytes(nw.max(0.0) * nh.max(0.0) * bpp)).color(t.text_dim).size(12.0)); + ui.label(egui::RichText::new(canvas_size_text(nw.max(0.0) * nh.max(0.0) * flat)).color(t.text_dim).size(12.0)); }); ui.horizontal(|ui| { label(ui, tl!("Width:"), 90.0); @@ -580,5 +618,7 @@ fn anchor_grid(ui: &mut egui::Ui, current: &str, dw: f64, dh: f64) -> Option<&'s picked } +#[cfg(test)] +mod canvas_size_readout_tests; #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/dialogs/sizing/canvas_size_readout_tests.rs b/crates/ui-egui/src/dialogs/sizing/canvas_size_readout_tests.rs new file mode 100644 index 0000000000..a9d8dbb2b0 --- /dev/null +++ b/crates/ui-egui/src/dialogs/sizing/canvas_size_readout_tests.rs @@ -0,0 +1,77 @@ +//! #14582: the Canvas Size dialog reports the flat image's size (width × height × channels +//! × bytes per channel, no alpha) with one decimal, not the layer-backed `__bytesPerPixel`. + +use super::*; + +#[test] +fn canvas_readout_matches_the_measured_flat_sizes() { + for (w, h, want) in [ + (400.0, 300.0, "351.6K"), + (1.0, 300.0, "900 bytes"), + (133.0, 300.0, "116.9K"), + (300000.0, 300.0, "257.5M"), + (500.0, 400.0, "585.9K"), + (567.0, 300.0, "498.3K"), + ] { + assert_eq!(canvas_size_text(w * h * 3.0), want, "{w}x{h} RGB 8"); + } +} + +#[test] +fn flat_format_counts_channels_without_alpha() { + use photocraft_color::{ColorMode, SampleType}; + for (mode, depth, want) in [ + (ColorMode::Rgb, SampleType::U8, (3, 1)), + (ColorMode::Grayscale, SampleType::U8, (1, 1)), + (ColorMode::Cmyk, SampleType::U8, (4, 1)), + (ColorMode::Rgb, SampleType::U16, (3, 2)), + (ColorMode::Rgb, SampleType::F32, (3, 4)), + ] { + let (channels, per_channel) = flat_format(mode, depth); + assert_eq!((channels, per_channel), want, "{mode:?} {depth:?}"); + assert_eq!(channels * per_channel, want.0 * want.1, "{mode:?} {depth:?} bytes per pixel"); + } +} + +#[test] +fn malformed_fields_fall_back_instead_of_nan() { + let mut f = Map::new(); + assert_eq!(canvas_flat_bpp(&f), 3.0, "missing fields fall back to RGB 8"); + assert_eq!(canvas_size_text(400.0 * 300.0 * canvas_flat_bpp(&f)), "351.6K"); + for bad in [json!(f64::NAN), json!(f64::INFINITY), json!(0.0), json!(-2.0), json!("x"), json!(null)] { + f.insert("__channels".into(), bad.clone()); + f.insert("__bytesPerChannel".into(), bad.clone()); + let bpp = canvas_flat_bpp(&f); + assert!(bpp.is_finite() && bpp > 0.0, "{bad:?} falls back, got {bpp}"); + let text = canvas_size_text(400.0 * 300.0 * bpp); + assert!(!text.contains("NaN") && !text.contains("inf"), "{bad:?} reads {text:?}"); + } + // One bad field still falls back for that field only. + f.insert("__channels".into(), json!(4.0)); + f.insert("__bytesPerChannel".into(), json!("x")); + assert_eq!(canvas_flat_bpp(&f), 4.0); +} + +#[test] +fn canvas_readout_uses_the_system_decimal_mark() { + crate::i18n::with_decimal_separator(Some(','), || { + assert_eq!(canvas_size_text(400.0 * 300.0 * 3.0), "351,6K"); + assert_eq!(canvas_size_text(500.0 * 400.0 * 3.0), "585,9K"); + }); + assert_eq!(canvas_size_text(400.0 * 300.0 * 3.0), "351.6K"); +} + +/// The open dialog on a 400x300 RGB 8 document shows the flat 351.6K, not the layer-backed 469K. +#[test] +fn canvas_size_dialog_shows_the_flat_size() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + open(h.state_mut(), "image.canvasSize").unwrap(); + h.run_steps(3); + // Current Size and New Size both read 351.6K on an unchanged dialog. + assert_eq!(h.get_all_by_label_contains("351.6K").count(), 2, "the dialog shows the flat 400x300 RGB 8 size"); + assert_eq!(h.get_all_by_label_contains("469K").count(), 0, "the layer-backed size is gone"); +} From 1a525c57d1416ad493e8dc9bd5f9a6cb5f4e55f5 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:21:27 +0100 Subject: [PATCH 02/25] Batch: OK without a source or destination folder says which is missing (#13669) OK in File > Automate > Batch now runs the reference's checks before the dialog closes: Source Folder with no folder chosen ("You must choose a source folder."), then a folder destination with no folder chosen ("You must choose a destination folder."). The first that fails opens an alert titled "Batch" with OK; the dialog stays open with its values and nothing runs. A confirm through the control channel gets the same check. Opened Files without an output keeps running as Destination None. --- crates/ui-egui/src/dialogs.rs | 5 +- crates/ui-egui/src/menus/view_cmds.rs | 2 +- .../view_cmds/batch_ok_validation_tests.rs | 223 ++++++++++++++++++ crates/ui-egui/src/menus/view_cmds/dialogs.rs | 64 +++++ 4 files changed, 292 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/src/menus/view_cmds/batch_ok_validation_tests.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index afa7a7d1ff..6cac43721a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -929,7 +929,8 @@ pub fn title(d: &Dialog) -> String { DialogKind::About => "About PhotoCraft".into(), DialogKind::LayerStyle => "Layer Style".into(), DialogKind::Command => d.fields.get("__label").and_then(Value::as_str).unwrap_or("Command").trim_end_matches('…').to_string(), - DialogKind::Error => "Error".into(), + // An alert may carry its own title, such as Batch's for a missing folder (#13669). + DialogKind::Error => d.fields.get("__title").and_then(Value::as_str).unwrap_or("Error").into(), } } @@ -1121,6 +1122,8 @@ pub(crate) fn confirm_preflight(app: &mut PhotocraftApp, id: u64) -> Result<(), if crate::layer_style::color_picker::has_child(app, id) { return Err("confirm or cancel the Layer Style color picker first".into()); } + // Batch without a source or destination folder stays open under its alert (#13669). + crate::view_cmds::batch_preflight(app, id)?; // A control request installs the session gate; synthetic input sets `automation_input`. // Either way the handler's own file access is judged before it runs, as its command would be. if (app.automation_input || app.session.authorize.is_some()) diff --git a/crates/ui-egui/src/menus/view_cmds.rs b/crates/ui-egui/src/menus/view_cmds.rs index 60d2fadd77..5bb6117a9c 100644 --- a/crates/ui-egui/src/menus/view_cmds.rs +++ b/crates/ui-egui/src/menus/view_cmds.rs @@ -20,7 +20,7 @@ mod options; pub use arrange::{Border, borders, cells, drag_border}; pub(crate) use arrange::{document_is_floating, float_window}; -pub(crate) use dialogs::write_copy; +pub(crate) use dialogs::{batch_preflight, write_copy}; #[cfg(test)] use dialogs::{form, front, label_of}; pub use dialogs::{form_body, form_keys, reset_form}; diff --git a/crates/ui-egui/src/menus/view_cmds/batch_ok_validation_tests.rs b/crates/ui-egui/src/menus/view_cmds/batch_ok_validation_tests.rs new file mode 100644 index 0000000000..93864798c4 --- /dev/null +++ b/crates/ui-egui/src/menus/view_cmds/batch_ok_validation_tests.rs @@ -0,0 +1,223 @@ +//! File › Automate › Batch: OK checks for a missing source folder, then a missing destination +//! folder, as the reference does (#13669). The first that fails shows its alert titled "Batch" +//! with OK over the dialog, which stays open with every value, and nothing runs. The same holds +//! for a confirm through the control channel. + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Map, Value, json}; + +use super::{BATCH_ALERT_TITLE, NO_DESTINATION_FOLDER, NO_SOURCE_FOLDER}; +use crate::PhotocraftApp; +use crate::control::{ControlRequest, Outcome, handle}; +use crate::state::DialogKind; + +type H = Harness<'static, PhotocraftApp>; + +/// The Batch dialog, opened from its menu command over an unsaved document with one recorded +/// action (Invert), with `input` and `output` set to the given paths. +fn batch(input: &str, output: &str) -> H { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 2, "height": 1})).unwrap(); + app.run("actions.record", json!({"name": "Invert"})).unwrap(); + app.run("image.adjustments.invert", json!({})).unwrap(); + app.run("actions.stop", json!({})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1100.0, 800.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "file.automate.batch", json!({})).expect("the Batch dialog opens"); + let fields = batch_fields_mut(&mut h); + fields.insert("input".into(), json!(input)); + fields.insert("output".into(), json!(output)); + h.run_steps(4); + h +} + +/// The open Batch dialog's id. +fn batch_id(h: &H) -> u64 { + h.state().ui.dialogs.iter().find(|d| d.fields.get("__command").and_then(Value::as_str) == Some("file.automate.batch")).expect("the Batch dialog is open").id +} + +fn batch_fields_mut(h: &mut H) -> &mut Map { + let id = batch_id(h); + &mut h.state_mut().ui.dialog_mut(id).unwrap().fields +} + +fn batch_fields(h: &H) -> Map { + let id = batch_id(h); + h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone() +} + +/// Every open alert as (title, message). +fn alerts(h: &H) -> Vec<(String, String)> { + h.state() + .ui + .dialogs + .iter() + .filter(|d| d.kind == DialogKind::Error) + .map(|d| (crate::dialogs::title(d), d.fields.get("message").and_then(Value::as_str).unwrap_or_default().to_string())) + .collect() +} + +/// The alert the reference shows for `message`. +fn batch_alert(message: &str) -> Vec<(String, String)> { + vec![(BATCH_ALERT_TITLE.to_string(), message.to_string())] +} + +/// Empties a text field of the dialog the way a user does: select all, then Backspace. +fn clear_field(h: &mut H, label: &str) { + h.get_by_role_and_label(Role::TextInput, label).click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + h.key_press(egui::Key::Backspace); + h.run_steps(2); +} + +/// A folder holding one 2×1 PNG, `a.png`, and the path of an output folder beside it. +fn image_folder() -> (tempfile::TempDir, String, String) { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("in")).unwrap(); + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 2, "height": 1})).unwrap(); + session.execute("file.saveACopy", json!({"path": dir.path().join("in/a.png").to_string_lossy()})).unwrap(); + let input = dir.path().join("in").to_string_lossy().into_owned(); + let output = dir.path().join("out").to_string_lossy().into_owned(); + (dir, input, output) +} + +/// Clicks the dialog's OK; with an alert up, the alert's OK is the other one. +fn click_batch_ok(h: &mut H) -> egui::Rect { + let ok = h.get_by_role_and_label(Role::Button, "OK").rect(); + h.get_by_role_and_label(Role::Button, "OK").click(); + h.run_steps(4); + ok +} + +#[test] +fn ok_without_a_source_folder_shows_the_batch_alert_and_keeps_the_dialog_open() { + crate::i18n::with_language(crate::i18n::Lang::EN, || { + let (dir, input, output) = image_folder(); + let mut h = batch(&input, &output); + clear_field(&mut h, "Input"); + let before = batch_fields(&h); + assert_eq!((&before["input"], &before["output"]), (&json!(""), &json!(output))); + + let ok = click_batch_ok(&mut h); + assert_eq!(alerts(&h), batch_alert(NO_SOURCE_FOLDER)); + assert_eq!(NO_SOURCE_FOLDER, "You must choose a source folder."); + assert!(h.query_by_label(NO_SOURCE_FOLDER).is_some(), "the alert is on screen"); + assert_eq!(batch_fields(&h), before, "the dialog stays open with every value"); + assert!(!dir.path().join("out").exists(), "nothing was written"); + assert_eq!(h.state().session.documents().len(), 1, "nothing was opened"); + + // The alert's OK closes the alert only; the dialog keeps its values. + h.get_all_by_role_and_label(Role::Button, "OK").find(|b| b.rect() != ok).expect("the alert has an OK button").click(); + h.run_steps(4); + assert!(alerts(&h).is_empty()); + assert_eq!(batch_fields(&h), before); + }); +} + +#[test] +fn ok_without_a_destination_folder_shows_the_batch_alert_and_writes_nothing() { + crate::i18n::with_language(crate::i18n::Lang::EN, || { + let (dir, input, output) = image_folder(); + let mut h = batch(&input, &output); + clear_field(&mut h, "Output"); + let before = batch_fields(&h); + assert_eq!((&before["input"], &before["output"]), (&json!(input), &json!(""))); + + click_batch_ok(&mut h); + assert_eq!(alerts(&h), batch_alert(NO_DESTINATION_FOLDER)); + assert_eq!(NO_DESTINATION_FOLDER, "You must choose a destination folder."); + assert_eq!(batch_fields(&h), before); + let files: Vec<_> = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name()).collect(); + assert_eq!(files, ["in"], "nothing was written"); + assert_eq!(h.state().session.documents().len(), 1, "nothing was opened"); + }); +} + +/// The checks run in the reference's order: with both folders missing, the source one shows. +/// A path of blanks names no folder either. +#[test] +fn the_source_folder_is_checked_before_the_destination() { + crate::i18n::with_language(crate::i18n::Lang::EN, || { + for (input, output, message) in [("", "", NO_SOURCE_FOLDER), (" ", "", NO_SOURCE_FOLDER), ("in", " ", NO_DESTINATION_FOLDER)] { + let mut h = batch(input, output); + click_batch_ok(&mut h); + assert_eq!(alerts(&h), batch_alert(message), "input {input:?}, output {output:?}"); + } + }); +} + +#[test] +fn a_confirm_over_the_control_channel_gets_the_same_check() { + crate::i18n::with_language(crate::i18n::Lang::EN, || { + let mut h = batch("", ""); + let ctx = h.ctx.clone(); + let id = batch_id(&h); + let before = batch_fields(&h); + // Repeated confirms answer the same error and keep one alert. + for _ in 0..2 { + let (confirm, _rx) = ControlRequest::new("ui.dialog.confirm", json!({"dialog": id})); + let Outcome::Done(reply) = handle(h.state_mut(), &ctx, &confirm) else { panic!("ui.dialog.confirm replies at once") }; + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply.to_string().contains(NO_SOURCE_FOLDER), "{reply}"); + } + assert_eq!(alerts(&h), batch_alert(NO_SOURCE_FOLDER)); + assert_eq!(batch_fields(&h), before); + + // With the source set over the channel, the destination is checked next. + let (set, _rx) = ControlRequest::new("ui.dialog.set", json!({"dialog": id, "field": "input", "value": "in"})); + assert!(matches!(handle(h.state_mut(), &ctx, &set), Outcome::Done(v) if v["ok"] == true)); + let alert = h.state().ui.dialogs.iter().find(|d| d.kind == DialogKind::Error).unwrap().id; + crate::dialogs::confirm(h.state_mut(), alert).unwrap(); + assert_eq!(crate::dialogs::confirm(h.state_mut(), id), Err(NO_DESTINATION_FOLDER.to_string())); + assert_eq!(alerts(&h), batch_alert(NO_DESTINATION_FOLDER)); + }); +} + +/// With both folders chosen OK runs the batch and closes the dialog, without an alert. +#[test] +fn ok_with_both_folders_runs_the_batch() { + crate::i18n::with_language(crate::i18n::Lang::EN, || { + let (dir, input, output) = image_folder(); + let mut h = batch(&input, &output); + click_batch_ok(&mut h); + assert!(alerts(&h).is_empty(), "{:?}", alerts(&h)); + assert!(h.state().ui.dialogs.is_empty(), "OK closes the dialog"); + assert!(dir.path().join("out/a.png").is_file(), "the batch wrote a.png"); + }); +} + +/// Opened Files reads no folder, and without an output folder it leaves the documents open and +/// changed (Destination None, as before): no check applies. +#[test] +fn opened_files_without_an_output_folder_runs_without_an_alert() { + crate::i18n::with_language(crate::i18n::Lang::EN, || { + let mut h = batch("", ""); + batch_fields_mut(&mut h).insert("source".into(), json!("open")); + h.run_steps(2); + let pixel = |h: &H| { + let st = h.state().session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(0, 0) + }; + let before = pixel(&h); + let id = batch_id(&h); + let result = crate::dialogs::confirm(h.state_mut(), id).expect("the batch runs"); + assert!(alerts(&h).is_empty(), "{:?}", alerts(&h)); + assert_eq!(result["documents"], 1, "{result}"); + assert_eq!(h.state().session.documents().len(), 1, "the document stays open"); + assert_eq!(pixel(&h)[0], 1.0 - before[0], "and the action inverted it"); + }); +} + +/// Other alerts keep the title "Error"; only one that names its own title shows another. +#[test] +fn an_alert_without_its_own_title_is_titled_error() { + let mut ui = crate::state::UiState::default(); + crate::panels::options_bar::range_alert(&mut ui, "A value between 1 and 300000 is required. Closest value inserted."); + assert_eq!(crate::dialogs::title(ui.dialogs.last().unwrap()), "Error"); +} diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index d4518748d9..d513998ab5 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -358,6 +358,70 @@ fn default_dir(app: &PhotocraftApp) -> String { app.session.active().and_then(|d| d.path.as_deref()).and_then(|p| p.rfind(['/', '\\']).map(|i| p[..i].to_string())).unwrap_or_else(|| ".".into()) } +/// The title of the alerts Batch's OK shows for a missing choice (#13669). +pub(crate) const BATCH_ALERT_TITLE: &str = "Batch"; +/// Batch's OK with Source: Folder and no source folder chosen (#13669). +pub(crate) const NO_SOURCE_FOLDER: &str = "You must choose a source folder."; +/// Batch's OK with a folder destination and no destination folder chosen (#13669). +pub(crate) const NO_DESTINATION_FOLDER: &str = "You must choose a destination folder."; + +/// Does a Batch path field name a folder (or files)? No value, an empty or blank path and an +/// empty file list count as nothing chosen. +fn batch_path_chosen(value: Option<&Value>) -> bool { + match value { + None | Some(Value::Null) => false, + Some(Value::String(path)) => !path.trim().is_empty(), + Some(Value::Array(files)) => !files.is_empty(), + Some(_) => true, + } +} + +/// The first of the reference's OK checks the Batch dialog's fields fail, in its order: the +/// source folder, then the destination folder. Only a folder source has either: Opened Files +/// reads no folder, and without an output it leaves the documents open (Destination None). A +/// Save and Close destination writes each source in place and has no folder to choose. +fn batch_missing_choice(f: &Map) -> Option<&'static str> { + let folder_source = matches!(f.get("source"), None | Some(Value::Null)) || f.get("source").and_then(Value::as_str) == Some("folder"); + if !folder_source { + return None; + } + // The source as the command reads it: `input`, else `files`. + if !batch_path_chosen(f.get("input").or_else(|| f.get("files"))) { + return Some(NO_SOURCE_FOLDER); + } + let folder_destination = matches!(f.get("destination"), None | Some(Value::Null)) || f.get("destination").and_then(Value::as_str) == Some("folder"); + (folder_destination && !batch_path_chosen(f.get("output"))).then_some(NO_DESTINATION_FOLDER) +} + +/// Checked before the Batch dialog closes (`dialogs::confirm_preflight`), for OK and for a +/// confirm through the control channel alike: a missing source or destination folder shows the +/// reference's alert titled "Batch" over the dialog, which stays open with its values, and +/// nothing runs (#13669). +pub(crate) fn batch_preflight(app: &mut PhotocraftApp, id: u64) -> Result<(), String> { + let Some(missing) = app + .ui + .dialogs + .iter() + .find(|d| d.id == id) + .map(|d| &d.fields) + .filter(|f| f.contains_key("__form") && f.get("__command").and_then(Value::as_str) == Some("file.automate.batch")) + .and_then(batch_missing_choice) + else { + return Ok(()); + }; + let message = tl!(missing).to_owned(); + // A confirm repeated from automation keeps one alert. + let shown = app.ui.dialogs.iter().any(|d| d.kind == DialogKind::Error && d.fields.get("message").and_then(Value::as_str) == Some(message.as_str())); + if !shown { + app.ui.open_dialog(DialogKind::Error, json!({"message": message, "__title": BATCH_ALERT_TITLE}).as_object().cloned().unwrap_or_default()); + } + Err(message) +} + +#[cfg(test)] +#[path = "batch_ok_validation_tests.rs"] +mod batch_ok_validation_tests; + /// Handle menu commands that need a shell action or a parameter dialog before execution. pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { if id == "file.closeAll" || id == "file.closeOthers" { From 47cd663af8e2fdbef4f6ebdada090f6f1d471b6d Mon Sep 17 00:00:00 2001 From: Madhav Agarwal Date: Mon, 16 Nov 2026 20:58:51 +0530 Subject: [PATCH 03/25] review: query an absent readout instead of requiring a match (coderabbitai/empty label query panics) --- crates/ui-egui/src/dialogs/sizing/canvas_size_readout_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/sizing/canvas_size_readout_tests.rs b/crates/ui-egui/src/dialogs/sizing/canvas_size_readout_tests.rs index a9d8dbb2b0..782e96a7b6 100644 --- a/crates/ui-egui/src/dialogs/sizing/canvas_size_readout_tests.rs +++ b/crates/ui-egui/src/dialogs/sizing/canvas_size_readout_tests.rs @@ -73,5 +73,5 @@ fn canvas_size_dialog_shows_the_flat_size() { h.run_steps(3); // Current Size and New Size both read 351.6K on an unchanged dialog. assert_eq!(h.get_all_by_label_contains("351.6K").count(), 2, "the dialog shows the flat 400x300 RGB 8 size"); - assert_eq!(h.get_all_by_label_contains("469K").count(), 0, "the layer-backed size is gone"); + assert_eq!(h.query_all_by_label_contains("469K").count(), 0, "the layer-backed size is gone"); } From d4edd71ec6a0b983101f8f0c4fe7612ad8d24e9a Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:57:32 +0100 Subject: [PATCH 04/25] Rectangle tool: Align Edges checkbox (#13346) The Rectangle tool's options bar gets the Align Edges checkbox at its right end, after the gear: on by default and after Reset Tool, enabled in Shape mode only. Off, a rectangle drag keeps its fractional box; on, or with the greyed checkbox in Path mode, it snaps to whole pixels as before. --- crates/ui-egui/src/state/tool_options.rs | 3 +- crates/ui-egui/src/tools/vector_ui.rs | 3 + crates/ui-egui/src/tools/vector_ui/options.rs | 7 + .../vector_ui/rectangle_align_edges_tests.rs | 160 ++++++++++++++++++ crates/ui-egui/src/tools/vector_ui/shapes.rs | 7 +- .../vector_ui/triangle_align_edges_tests.rs | 6 +- 6 files changed, 179 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/tools/vector_ui/rectangle_align_edges_tests.rs diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index 8e9b52fbba..8a85280b2e 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -125,7 +125,8 @@ pub struct ToolOptions { pub shape_stroke_gradient: Option, pub corner_radius: f32, /// Shape tools' Align Edges: snap the drawn shape's box to whole pixels. On by default; the - /// Triangle tool shows it, enabled in Shape mode only (#13370); the other shape tools always snap. + /// Triangle (#13370) and Rectangle (#13346) tools show it, enabled in Shape mode only; the other + /// shape tools always snap. pub align_edges: bool, pub polygon_sides: u32, pub line_weight: f32, diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index 1efea99a67..7b750fc067 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -263,6 +263,9 @@ mod pen_mode_menu_tests; #[cfg(test)] mod ellipse_path_menus_tests; +#[cfg(test)] +mod rectangle_align_edges_tests; + #[cfg(test)] mod triangle_align_edges_tests; diff --git a/crates/ui-egui/src/tools/vector_ui/options.rs b/crates/ui-egui/src/tools/vector_ui/options.rs index 179e5b8110..fb365f440d 100644 --- a/crates/ui-egui/src/tools/vector_ui/options.rs +++ b/crates/ui-egui/src/tools/vector_ui/options.rs @@ -181,6 +181,13 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo crate::panels::options_bar::range_alert(&mut app.ui, CONCAVITY_RANGE_ALERT); } } + // The Rectangle tool's Align Edges, at the bar's right end after the gear (#13346). Only a + // shape layer has pixel edges to align: greyed in Path mode (and in a pixels mode). + if tool == Tool::Rectangle { + crate::widgets::vline(ui, 22.0); + let o = &mut app.ui.tool_options; + ui.add_enabled_ui(o.shape_mode == "shape", |ui| crate::widgets::checkbox(ui, &mut o.align_edges, tl!("Align Edges"))); + } true } diff --git a/crates/ui-egui/src/tools/vector_ui/rectangle_align_edges_tests.rs b/crates/ui-egui/src/tools/vector_ui/rectangle_align_edges_tests.rs new file mode 100644 index 0000000000..96b12232f3 --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/rectangle_align_edges_tests.rs @@ -0,0 +1,160 @@ +//! #13346: the Rectangle tool's Align Edges checkbox, at the options bar's right end after the +//! gear. On (the default) a drag's box snaps to whole pixels; off a rectangle keeps the drag's +//! fractional coordinates. It is greyed outside Shape mode, where the box still snaps. + +use egui::Modifiers; +use egui::accesskit::Toggled; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::add_anchor_options_bar_tests::harness; +use super::{finish_shape, shape_geometry}; +use crate::PhotocraftApp; +use crate::state::Tool; + +const START: [f64; 2] = [10.3, 10.6]; +const END: [f64; 2] = [40.7, 30.2]; +const GEAR: &str = "Set additional shape and path options"; + +/// A 200 × 100 document with the Rectangle tool. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.ui.tool = Tool::Rectangle; + app +} + +/// The `[x, y, w, h]` box a Rectangle drag from `START` to `END` draws, or None. +fn drag_box(app: &PhotocraftApp, mods: Modifiers) -> Option<[f64; 4]> { + let g = shape_geometry(&app.ui.tool_options, Tool::Rectangle, START, END, mods)?; + serde_json::from_value(g["rect"].clone()).ok() +} + +/// The active shape layer's live rectangle `[x, y, w, h]` and its path's `[x0, y0, x1, y1]`. +fn drawn_layer(app: &mut PhotocraftApp) -> ([f64; 4], [f64; 4]) { + let st = app.session.active().unwrap(); + let id = st.active_layer.unwrap(); + let path = match &st.doc.layer(id).unwrap().content { + photocraft_doc::LayerContent::Shape(sh) => sh.path.clone(), + other => panic!("not a shape layer: {other:?}"), + }; + let (x0, y0, x1, y1) = path.control_bounds().unwrap(); + let info = app.session.execute("shape.info", json!({"layer": id.0})).unwrap(); + let live = serde_json::from_value(info["live"]["rect"].clone()).unwrap_or_else(|_| panic!("a live rectangle: {}", info["live"])); + (live, [x0, y0, x1, y1]) +} + +/// `[x0, y0, x1, y1]` of the work path. +fn work_path_bounds(app: &PhotocraftApp) -> [f64; 4] { + let (x0, y0, x1, y1) = app.session.active().unwrap().doc.work_path.as_ref().unwrap().control_bounds().unwrap(); + [x0, y0, x1, y1] +} + +fn assert_close(got: [f64; 4], want: [f64; 4]) { + for (g, w) in got.iter().zip(want) { + assert!((g - w).abs() < 1e-9, "{got:?} vs {want:?}"); + } +} + +#[test] +fn the_box_snaps_with_align_edges_and_keeps_fractions_without() { + let mut app = app(); + assert!(app.ui.tool_options.align_edges, "on by default"); + assert_eq!(drag_box(&app, Modifiers::NONE), Some([10.0, 11.0, 30.0, 20.0])); + app.ui.tool_options.align_edges = false; + assert_close(drag_box(&app, Modifiers::NONE).unwrap(), [10.3, 10.6, 30.4, 19.6]); + // Shift squares on the drag's shorter side and Alt draws from the centre, both before the box + // snaps or not. + assert_close(drag_box(&app, Modifiers::SHIFT).unwrap(), [10.3, 10.6, 19.6, 19.6]); + assert_close(drag_box(&app, Modifiers::ALT).unwrap(), [-20.1, -9.0, 60.8, 39.2]); + app.ui.tool_options.align_edges = true; + assert_eq!(drag_box(&app, Modifiers::SHIFT), Some([10.0, 11.0, 20.0, 20.0])); + assert_eq!(drag_box(&app, Modifiers::ALT), Some([-20.0, -9.0, 61.0, 39.0])); +} + +#[test] +fn a_rounded_rectangle_and_the_gears_fixed_size_follow_the_checkbox_too() { + let mut app = app(); + app.ui.tool_options.corner_radius = 4.0; + app.ui.tool_options.align_edges = false; + let g = shape_geometry(&app.ui.tool_options, Tool::Rectangle, START, END, Modifiers::NONE).unwrap(); + assert_eq!(g["kind"], "roundedRect"); + assert_close(serde_json::from_value(g["rect"].clone()).unwrap(), [10.3, 10.6, 30.4, 19.6]); + // Fixed Size puts W × H at the release point. + app.ui.tool_options.corner_radius = 0.0; + app.ui.tool_options.rect_constraint = "fixedSize".into(); + (app.ui.tool_options.rect_fixed_width, app.ui.tool_options.rect_fixed_height) = (20.5, 10.25); + assert_close(drag_box(&app, Modifiers::NONE).unwrap(), [40.7, 30.2, 20.5, 10.25]); + app.ui.tool_options.align_edges = true; + assert_eq!(drag_box(&app, Modifiers::NONE), Some([41.0, 30.0, 21.0, 10.0])); +} + +#[test] +fn the_drawn_shape_layer_follows_the_checkbox() { + for (align, live, bounds) in [(true, [10.0, 11.0, 30.0, 20.0], [10.0, 11.0, 40.0, 31.0]), (false, [10.3, 10.6, 30.4, 19.6], [10.3, 10.6, 40.7, 30.2])] { + let mut app = app(); + app.ui.tool_options.align_edges = align; + let layers = app.session.active().unwrap().doc.layers.len(); + finish_shape(&mut app, Tool::Rectangle, START, END, Modifiers::NONE); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1, "one new shape layer"); + let (got_live, got_bounds) = drawn_layer(&mut app); + assert_close(got_live, live); + assert_close(got_bounds, bounds); + } +} + +#[test] +fn a_greyed_checkbox_keeps_snapping_in_path_and_pixels_mode() { + let mut app = app(); + app.ui.tool_options.align_edges = false; + for mode in ["path", "pixels"] { + app.ui.tool_options.shape_mode = mode.into(); + assert_eq!(drag_box(&app, Modifiers::NONE), Some([10.0, 11.0, 30.0, 20.0]), "{mode}"); + } + app.ui.tool_options.shape_mode = "path".into(); + finish_shape(&mut app, Tool::Rectangle, START, END, Modifiers::NONE); + assert_close(work_path_bounds(&app), [10.0, 11.0, 40.0, 31.0]); +} + +#[test] +fn a_sub_pixel_drag_still_draws_nothing() { + let mut app = app(); + app.ui.tool_options.align_edges = false; + for end in [[10.9, 40.0], [40.0, 10.5]] { + assert!(shape_geometry(&app.ui.tool_options, Tool::Rectangle, [10.0, 10.0], end, Modifiers::NONE).is_none()); + let layers = app.session.active().unwrap().doc.layers.len(); + finish_shape(&mut app, Tool::Rectangle, [10.0, 10.0], end, Modifiers::NONE); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers); + } +} + +#[test] +fn reset_tool_turns_it_back_on() { + let mut app = app(); + app.ui.tool_options.align_edges = false; + crate::menus::invoke(&mut app, &egui::Context::default(), crate::tool_reset::RESET, json!({})).unwrap(); + assert!(app.ui.tool_options.align_edges); +} + +#[test] +fn options_bar_shows_align_edges_at_its_right_end() { + let mut h = harness(Tool::Rectangle); + // The Radius caption and its field. + let radius = h.query_all_by_label("Radius:").map(|n| n.rect().right()).fold(f32::MIN, f32::max); + let gear = h.get_by_label(GEAR).rect(); + let node = h.get_by_label("Align Edges"); + assert!(node.rect().left() > gear.right() && gear.left() > radius, "{:?} after {gear:?} after the radius ({radius})", node.rect()); + assert!((node.rect().center().y - gear.center().y).abs() < 4.0, "on the gear's row"); + assert!(!node.accesskit_node().is_disabled(), "enabled in Shape mode"); + assert_eq!(node.accesskit_node().toggled(), Some(Toggled::True)); + h.get_by_label("Align Edges").click(); + h.run_steps(3); + assert!(!h.state().ui.tool_options.align_edges, "clicking toggles the option"); + assert_eq!(h.get_by_label("Align Edges").accesskit_node().toggled(), Some(Toggled::False)); + + for mode in ["path", "pixels"] { + h.state_mut().ui.tool_options.shape_mode = mode.into(); + h.run_steps(4); + assert!(h.get_by_label("Align Edges").accesskit_node().is_disabled(), "greyed in {mode} mode"); + } +} diff --git a/crates/ui-egui/src/tools/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs index 3e44cd5a10..1a7fe12c95 100644 --- a/crates/ui-egui/src/tools/vector_ui/shapes.rs +++ b/crates/ui-egui/src/tools/vector_ui/shapes.rs @@ -130,9 +130,10 @@ pub(super) fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end: } else { let [x0, y0, w, h] = drag_box(o, tool, start, end, mods); let rect = [x0.min(x0 + w), y0.min(y0 + h), w.abs(), h.abs()]; - // Align Edges (#13370) is the Triangle tool's option, and only in Shape mode, where its - // checkbox is enabled. The other shape tools, and a greyed checkbox, still snap. - let keep_fraction = tool == Tool::Triangle && o.shape_mode == "shape" && !o.align_edges; + // Align Edges is the Triangle (#13370) and Rectangle (#13346) tools' option, and only in + // Shape mode, where its checkbox is enabled. The other shape tools, and a greyed checkbox, + // still snap. + let keep_fraction = matches!(tool, Tool::Triangle | Tool::Rectangle) && o.shape_mode == "shape" && !o.align_edges; let rect = if keep_fraction { rect } else { rect.map(f64::round) }; if rect[2] < 1.0 || rect[3] < 1.0 { return None; diff --git a/crates/ui-egui/src/tools/vector_ui/triangle_align_edges_tests.rs b/crates/ui-egui/src/tools/vector_ui/triangle_align_edges_tests.rs index ef58c63393..ce15873db6 100644 --- a/crates/ui-egui/src/tools/vector_ui/triangle_align_edges_tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/triangle_align_edges_tests.rs @@ -41,7 +41,7 @@ fn triangle_box_snaps_with_align_edges_and_stays_fractional_without() { #[test] fn other_shape_tools_always_snap() { let o = ToolOptions { align_edges: false, ..Default::default() }; - for tool in [Tool::Polygon, Tool::EllipseShape, Tool::Rectangle, Tool::Star] { + for tool in [Tool::Polygon, Tool::EllipseShape, Tool::Star] { let r = rect(&o, tool, START, END).unwrap(); assert!(r.iter().all(|v| v.fract() == 0.0), "{tool:?}: {r:?}"); } @@ -62,7 +62,7 @@ fn a_sub_pixel_triangle_drag_still_draws_nothing() { } #[test] -fn options_bar_shows_align_edges_for_the_triangle_only() { +fn options_bar_shows_align_edges_for_the_triangle_not_the_ellipse() { let mut h = harness(Tool::Triangle); let node = h.get_by_label("Align Edges"); assert!(!node.accesskit_node().is_disabled(), "enabled in Shape mode"); @@ -76,6 +76,6 @@ fn options_bar_shows_align_edges_for_the_triangle_only() { h.run_steps(4); assert!(h.get_by_label("Align Edges").accesskit_node().is_disabled(), "greyed in Path mode"); - let h = harness(Tool::Rectangle); + let h = harness(Tool::EllipseShape); assert!(h.query_by_label("Align Edges").is_none()); } From 9aad9a2871e5a0aa78f10be0ba5219d172742dbb Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:41:54 +0100 Subject: [PATCH 05/25] Polygon tool: a Radius field after Sides rounds the next polygon (#13302) --- crates/ui-egui/src/state/tool_options.rs | 4 + crates/ui-egui/src/tool_memory.rs | 1 + .../polygon_corner_radius_field_tests.rs | 282 ++++++++++++++++++ crates/ui-egui/src/tools/shape_options.rs | 51 ++++ crates/ui-egui/src/tools/tool_reset.rs | 1 + crates/ui-egui/src/tools/vector_ui/shapes.rs | 4 + 6 files changed, 343 insertions(+) create mode 100644 crates/ui-egui/src/tools/polygon_corner_radius_field_tests.rs diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index 8e9b52fbba..39695210d7 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -128,6 +128,9 @@ pub struct ToolOptions { /// Triangle tool shows it, enabled in Shape mode only (#13370); the other shape tools always snap. pub align_edges: bool, pub polygon_sides: u32, + /// The Polygon tool's corner radius in px for the next polygon (#13302): its own, not the + /// Rectangle's [`Self::corner_radius`]. 0 draws sharp corners. + pub polygon_corner_radius: f32, pub line_weight: f32, /// Line arrowheads. pub arrow_start: bool, @@ -538,6 +541,7 @@ impl Default for ToolOptions { corner_radius: 0.0, align_edges: true, polygon_sides: 5, + polygon_corner_radius: 0.0, line_weight: 1.0, arrow_start: false, arrow_end: false, diff --git a/crates/ui-egui/src/tool_memory.rs b/crates/ui-egui/src/tool_memory.rs index b13a4020ab..9e564e22c4 100644 --- a/crates/ui-egui/src/tool_memory.rs +++ b/crates/ui-egui/src/tool_memory.rs @@ -389,6 +389,7 @@ pub(crate) fn sanitize(o: &mut ToolOptions) { fit(&mut o.red_eye_pupil_size, 1.0, 100.0, d.red_eye_pupil_size); fit(&mut o.red_eye_darken, 0.0, 100.0, d.red_eye_darken); o.polygon_sides = o.polygon_sides.clamp(3, 100); + fit(&mut o.polygon_corner_radius, *crate::shape_options::RADIUS_RANGE.start(), *crate::shape_options::RADIUS_RANGE.end(), d.polygon_corner_radius); if o.crop_overlay_orientation > 3 { o.crop_overlay_orientation = d.crop_overlay_orientation; } diff --git a/crates/ui-egui/src/tools/polygon_corner_radius_field_tests.rs b/crates/ui-egui/src/tools/polygon_corner_radius_field_tests.rs new file mode 100644 index 0000000000..7de8b1f887 --- /dev/null +++ b/crates/ui-egui/src/tools/polygon_corner_radius_field_tests.rs @@ -0,0 +1,282 @@ +//! #13302: the Polygon tool's options bar has its own corner radius after Sides, in px (0 to +//! start, and after Reset Tool), in Shape and Path mode. It rounds the next polygon drawn, never +//! the active one, and shares the Rectangle Radius's 0..150000 range and alert; text that is not +//! a number keeps the previous value with the reference's invalid-entry alert. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::vector::Knot; +use photocraft_doc::{LayerContent, LiveShape}; +use serde_json::json; + +use super::{POLYGON_RADIUS_INVALID_ALERT, RADIUS_RANGE_ALERT}; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::{DialogKind, Tool}; + +/// An 800 × 600 document with the Polygon tool current. +fn new_app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.ui.tool = Tool::Polygon; + app +} + +/// The options bar drawn for `app`. +fn bar_with(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1800.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +/// The options-bar number field named `label`. +fn field_rect(h: &Harness<'static, PhotocraftApp>, label: &str) -> Option { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some(label)).map(|n| n.rect()) +} + +/// Clicks into Radius, selects its text and types `text`, `per_key` one character per pass, then +/// Tabs out of it. +fn enter_radius(h: &mut Harness<'static, PhotocraftApp>, text: &str, per_key: bool) { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Radius:")).expect("the Radius field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + let keys: Vec = if per_key { text.chars().map(String::from).collect() } else { vec![text.to_owned()] }; + for k in keys { + h.event(egui::Event::Text(k)); + h.run_steps(1); + } + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +/// The messages of the open alerts. +fn alerts(h: &Harness<'static, PhotocraftApp>) -> Vec { + h.state().ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(str::to_owned)).collect() +} + +/// OK on every open alert, as `ui.dialog.confirm` presses it (this harness draws only the bar). +fn ok_all(h: &mut Harness<'static, PhotocraftApp>) { + let ids: Vec = h.state().ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).map(|d| d.id).collect(); + for id in ids { + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + } + h.run_steps(3); +} + +/// The Polygon tool's radius, and the Rectangle tool's, which it must leave alone. +fn radii(h: &Harness<'static, PhotocraftApp>) -> (f32, f32) { + let o = &h.state().ui.tool_options; + (o.polygon_corner_radius, o.corner_radius) +} + +/// The active layer's live shape and outline knots. +fn active_shape(app: &PhotocraftApp) -> (LiveShape, Vec) { + let st = app.session.active().unwrap(); + let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("not a shape layer") }; + (sh.live.clone().unwrap(), sh.path.subpaths[0].knots.clone()) +} + +/// A Polygon tool drag from `from` to `to`, released there. +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + let mods = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: (from[0] + to[0]) / 2.0, y: (from[1] + to[1]) / 2.0, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods); +} + +/// The issue's measured drag, 400,300 to 600,400, with the Polygon tool's radius at `radius`: +/// the new layer's live shape and outline knots. +fn drawn_with(radius: f32) -> (LiveShape, Vec) { + let mut app = new_app(); + app.ui.tool_options.polygon_corner_radius = radius; + drag(&mut app, [400.0, 300.0], [600.0, 400.0]); + assert!(!app.ui.status_error, "{}", app.ui.status); + active_shape(&app) +} + +/// Where each vertex of the sharp polygon `v` is rounded by an arc of radius `r` tangent to both +/// its edges: the points `r / tan(half the vertex angle)` from it along the edge it comes from and +/// the edge it goes to, at most half the shorter edge (a radius the shape cannot take is capped). +fn tangent_points(v: &[[f64; 2]], r: f64) -> Vec<[f64; 2]> { + let n = v.len(); + let along = |from: [f64; 2], to: [f64; 2], t: f64| { + let l = (to[0] - from[0]).hypot(to[1] - from[1]); + [from[0] + (to[0] - from[0]) / l * t, from[1] + (to[1] - from[1]) / l * t] + }; + (0..n) + .flat_map(|i| { + let (p, c, q) = (v[(i + n - 1) % n], v[i], v[(i + 1) % n]); + let (a, b) = ([p[0] - c[0], p[1] - c[1]], [q[0] - c[0], q[1] - c[1]]); + let (la, lb) = (a[0].hypot(a[1]), b[0].hypot(b[1])); + let half = ((a[0] * b[0] + a[1] * b[1]) / (la * lb)).acos() / 2.0; + let t = (r / half.tan()).min(la.min(lb) / 2.0); + [along(c, p, t), along(c, q, t)] + }) + .collect() +} + +/// `a` and `b` within a thousandth of a pixel. +fn near(a: [f64; 2], b: [f64; 2]) -> bool { + (a[0] - b[0]).abs() < 1e-3 && (a[1] - b[1]).abs() < 1e-3 +} + +/// Checks `knots` round every vertex of the sharp polygon `sharp` with radius `r`: two anchors a +/// corner, on its edges, each with its handle along that edge towards the vertex (the arc is +/// tangent to the edges), all inside the 400,300 to 600,400 drag box. +fn assert_rounds(knots: &[Knot], sharp: &[Knot], r: f64) { + let v: Vec<[f64; 2]> = sharp.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); + let want = tangent_points(&v, r); + assert_eq!(knots.len(), 2 * v.len(), "two anchors a corner"); + for (i, (k, w)) in knots.iter().zip(&want).enumerate() { + let a = [k.anchor.x, k.anchor.y]; + assert!(near(a, *w), "anchor {i}: {a:?}, want {w:?}"); + let corner = v[i / 2]; + // The handle that bends towards the corner: the out handle at the arc's start, the in + // handle at its end. It lies on the edge, between the anchor and the vertex. + let h = if i % 2 == 0 { k.out_ctrl } else { k.in_ctrl }; + let cross = (corner[0] - a[0]) * (h.y - a[1]) - (corner[1] - a[1]) * (h.x - a[0]); + let dot = (corner[0] - a[0]) * (h.x - a[0]) + (corner[1] - a[1]) * (h.y - a[1]); + assert!(cross.abs() < 1e-6 && dot > 0.0, "knot {i}: the arc is tangent to the edge"); + for p in [k.anchor, k.in_ctrl, k.out_ctrl] { + assert!((400.0..=600.0).contains(&p.x) && (300.0..=400.0).contains(&p.y), "knot {i} is inside the drag box: {p:?}"); + } + } +} + +#[test] +fn the_radius_field_follows_sides_and_starts_at_zero_in_shape_and_path_mode() { + for mode in ["shape", "path"] { + let mut app = new_app(); + app.ui.tool_options.shape_mode = mode.into(); + let h = bar_with(app); + let sides = field_rect(&h, "Sides:").expect("the Sides field"); + let radius = field_rect(&h, "Radius:").unwrap_or_else(|| panic!("{mode}: the Radius field")); + assert!(radius.left() > sides.right() && (radius.center().y - sides.center().y).abs() < 1.0, "{mode}: Radius right after Sides"); + assert_eq!(radii(&h), (0.0, 0.0), "{mode}: 0 px to start"); + } +} + +#[test] +fn a_radius_in_range_is_taken_without_an_alert_and_leaves_the_rectangles_alone() { + for (typed, want) in [("20", 20.0), ("0.5", 0.5), ("150000", 150_000.0), ("0", 0.0)] { + let mut h = bar_with(new_app()); + enter_radius(&mut h, typed, false); + assert_eq!(radii(&h), (want, 0.0), "{typed}"); + assert!(alerts(&h).is_empty(), "{typed} is in range"); + } +} + +#[test] +fn a_radius_past_the_range_takes_the_closest_value_with_one_alert() { + for (typed, want) in [("-5", 0.0), ("99999999", 150_000.0)] { + let mut h = bar_with(new_app()); + enter_radius(&mut h, "12", false); + enter_radius(&mut h, typed, false); + assert_eq!(radii(&h), (want, 0.0), "{typed}"); + assert_eq!(alerts(&h), vec![RADIUS_RANGE_ALERT.to_string()], "{typed}: one alert"); + ok_all(&mut h); + assert!(alerts(&h).is_empty(), "{typed}: OK closes the alert"); + assert_eq!(radii(&h).0, want, "{typed}: the closest value stays"); + } +} + +#[test] +fn text_that_is_no_number_keeps_the_previous_radius_with_the_invalid_entry_alert() { + let mut h = bar_with(new_app()); + enter_radius(&mut h, "12", false); + enter_radius(&mut h, "abc", false); + assert_eq!(radii(&h), (12.0, 0.0), "the last valid value stays"); + assert_eq!(alerts(&h), vec![POLYGON_RADIUS_INVALID_ALERT.to_string()], "one invalid-entry alert"); + ok_all(&mut h); + // Visiting the field again without typing, then a number, raises nothing. + enter_radius(&mut h, "", false); + assert!(alerts(&h).is_empty(), "nothing typed: {:?}", alerts(&h)); + enter_radius(&mut h, "7", false); + assert_eq!(radii(&h), (7.0, 0.0)); + assert!(alerts(&h).is_empty(), "7 is a number in range: {:?}", alerts(&h)); +} + +#[test] +fn arithmetic_is_a_number_until_text_spoils_it() { + let mut h = bar_with(new_app()); + // `50/2` is held, unread, until the field is left: only that pass reads `50/2x`. + enter_radius(&mut h, "50/2x", true); + assert_eq!(alerts(&h), vec![POLYGON_RADIUS_INVALID_ALERT.to_string()], "50/2x is no number"); + ok_all(&mut h); + enter_radius(&mut h, "50/2", true); + assert_eq!(radii(&h), (25.0, 0.0)); + assert!(alerts(&h).is_empty(), "{:?}", alerts(&h)); +} + +#[test] +fn the_radius_field_leaves_the_active_polygon_and_the_history_alone() { + let mut app = new_app(); + drag(&mut app, [400.0, 300.0], [600.0, 400.0]); + app.sync_views(); + let before = (active_shape(&app), app.session.active().unwrap().history.past_len()); + let mut h = bar_with(app); + enter_radius(&mut h, "30", false); + assert_eq!(radii(&h), (30.0, 0.0)); + let after = (active_shape(h.state()), h.state().session.active().unwrap().history.past_len()); + assert_eq!(after, before, "the active polygon keeps its corners and no History state is added"); +} + +#[test] +fn radius_20_rounds_every_corner_of_the_next_polygon_with_two_tangent_anchors() { + let (_, sharp) = drawn_with(0.0); + let (live, knots) = drawn_with(20.0); + assert_eq!(live, LiveShape::Polygon { rect: [400.0, 300.0, 200.0, 100.0], sides: 5, star_ratio: 1.0, corner_radius: 20.0 }); + assert_rounds(&knots, &sharp, 20.0); + // 20 px fits every corner, so no arc is capped: a larger radius would move every anchor. + let v: Vec<[f64; 2]> = sharp.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); + assert!(tangent_points(&v, 20.0).iter().zip(tangent_points(&v, 21.0)).all(|(a, b)| !near(*a, b))); +} + +#[test] +fn radius_1000_is_capped_by_the_shape_without_an_error() { + let (_, sharp) = drawn_with(0.0); + let (live, knots) = drawn_with(1000.0); + assert_eq!(live, LiveShape::Polygon { rect: [400.0, 300.0, 200.0, 100.0], sides: 5, star_ratio: 1.0, corner_radius: 1000.0 }); + assert_rounds(&knots, &sharp, 1000.0); +} + +#[test] +fn radius_0_draws_the_sharp_polygon() { + let (live, knots) = drawn_with(0.0); + assert_eq!(live, LiveShape::Polygon { rect: [400.0, 300.0, 200.0, 100.0], sides: 5, star_ratio: 1.0, corner_radius: 0.0 }); + assert_eq!(knots.len(), 5, "one anchor a corner"); + assert!(knots.iter().all(|k| k.in_ctrl == k.anchor && k.out_ctrl == k.anchor), "no curves"); +} + +#[test] +fn path_mode_rounds_the_next_outline_too() { + let mut app = new_app(); + app.ui.tool_options.shape_mode = "path".into(); + app.ui.tool_options.polygon_corner_radius = 20.0; + drag(&mut app, [400.0, 300.0], [600.0, 400.0]); + let work = app.session.active().unwrap().doc.work_path.clone().expect("a work path"); + assert_eq!(work.subpaths.len(), 1); + let (_, sharp) = drawn_with(0.0); + assert_rounds(&work.subpaths[0].knots, &sharp, 20.0); +} + +#[test] +fn the_radius_is_saved_with_the_tool_options_and_reset_tool_sets_it_back_to_zero() { + let o = crate::state::ToolOptions { polygon_corner_radius: 33.0, ..Default::default() }; + let back: crate::state::ToolOptions = serde_json::from_value(serde_json::to_value(&o).unwrap()).unwrap(); + assert_eq!(back.polygon_corner_radius, 33.0, "saved and read back"); + assert!(crate::tools::tool_reset::option_keys(Tool::Polygon).contains(&"polygon_corner_radius"), "a Polygon tool preset stores it"); + let mut reset = o.clone(); + crate::tools::tool_reset::reset_options(&mut reset, Tool::Polygon); + assert_eq!(reset.polygon_corner_radius, 0.0, "Reset Tool"); + // Remembered values the field could never hold come back in its range. + for (saved, want) in [(-3.0, 0.0), (1.0e9, 150_000.0), (f32::NAN, 0.0), (40.0, 40.0)] { + let mut o = crate::state::ToolOptions { polygon_corner_radius: saved, ..Default::default() }; + crate::tool_memory::sanitize(&mut o); + assert_eq!(o.polygon_corner_radius, want, "{saved}"); + } +} diff --git a/crates/ui-egui/src/tools/shape_options.rs b/crates/ui-egui/src/tools/shape_options.rs index 761cea5471..cc9e87a47d 100644 --- a/crates/ui-egui/src/tools/shape_options.rs +++ b/crates/ui-egui/src/tools/shape_options.rs @@ -120,6 +120,13 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool let label = tl!("Sides:"); lbl(ui, label); sides_alert = sides_field(ui, label, &mut o.polygon_sides); + // The tool's own corner radius for the next polygon (#13302); the active shape is not touched. + crate::widgets::vline(ui, 22.0); + let label = tl!("Radius:"); + lbl(ui, label); + let no_number; + (radius_alert, no_number) = polygon_radius_field(ui, label, &mut o.polygon_corner_radius); + range_alert(app, no_number, POLYGON_RADIUS_INVALID_ALERT); } Tool::Triangle => { crate::widgets::vline(ui, 22.0); @@ -223,6 +230,46 @@ fn sides_field(ui: &mut egui::Ui, label: &str, sides: &mut u32) -> bool { /// The reference's alert for a Polygon Sides value typed past 3..100 (#13304). pub(crate) const SIDES_RANGE_ALERT: &str = "An integer between 3 and 100 is required. Closest value inserted."; +/// The Polygon tool's Radius in px (#13302), in [`RADIUS_RANGE`]. Returns whether the field owes +/// [`RADIUS_RANGE_ALERT`] (a value typed past the range, which takes the closest one) and whether +/// it was left with text that is not a number, which keeps `radius` and owes +/// [`POLYGON_RADIUS_INVALID_ALERT`]. +fn polygon_radius_field(ui: &mut egui::Ui, label: &str, radius: &mut f32) -> (bool, bool) { + let mut r = *radius; + let (resp, out_of_range) = crate::widgets::value_field_alerting(ui, label, &mut r, RADIUS_RANGE, "px", 62.0); + if resp.changed() { + *radius = r; + } + (out_of_range, left_without_a_number(ui, &resp)) +} + +/// True on the pass the field `resp` is left with text in it that is not a number (`abc`). A +/// number typed after it, before the field is left, takes that back. +fn left_without_a_number(ui: &egui::Ui, resp: &egui::Response) -> bool { + let no_number = resp.id.with("no-number-typed"); + if resp.has_focus() { + match crate::widgets::typed_text_parses(ui.ctx(), resp.id) { + Some(false) => ui.ctx().data_mut(|d| { + d.insert_temp(no_number, true); + }), + Some(true) => ui.ctx().data_mut(|d| { + d.remove_temp::(no_number); + }), + None => {} + } + return false; + } + let owed = ui.ctx().data_mut(|d| d.remove_temp::(no_number)).unwrap_or(false); + // Complete arithmetic (`50/2`) is held, and its text no longer read, until the field is left: + // the pass that leaves it can be the first to read text spoilt after it (`50/2x`). + resp.lost_focus() && crate::widgets::typed_text_parses(ui.ctx(), resp.id).map_or(owed, |p| !p) +} + +/// The reference's alert for text that is not a number left in the Polygon tool's Radius; the +/// field keeps its previous value (#13302, worded as the Triangle tool's measured one, #13355). +pub(crate) const POLYGON_RADIUS_INVALID_ALERT: &str = + "Invalid numeric entry. A number between 0.000 pixel and 150000.000 Pixels is required. Restored last valid value."; + /// Shows `alert` ([`RADIUS_RANGE_ALERT`], [`SIDES_RANGE_ALERT`]) as a modal with OK when `owed`, /// once even if more than one pass asks. fn range_alert(app: &mut PhotocraftApp, owed: bool, alert: &str) { @@ -248,6 +295,10 @@ mod rectangle_radius_target_tests; #[path = "polygon_sides_alert_tests.rs"] mod polygon_sides_alert_tests; +#[cfg(test)] +#[path = "polygon_corner_radius_field_tests.rs"] +mod polygon_corner_radius_field_tests; + /// Tool-bar paint changes affect the next shape; Properties edits the selected shape instead. pub(crate) fn set_tool_paint(app: &mut PhotocraftApp, stroke: bool, change: PaintChange) -> Result<(), String> { // A colour takes the place of a gradient; No Color keeps it for when the paint comes back. diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index 80fb6ede7a..20e778d853 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -308,6 +308,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { corner_radius, align_edges, polygon_sides, + polygon_corner_radius, line_weight ) } diff --git a/crates/ui-egui/src/tools/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs index 3e44cd5a10..0b677c3b9c 100644 --- a/crates/ui-egui/src/tools/vector_ui/shapes.rs +++ b/crates/ui-egui/src/tools/vector_ui/shapes.rs @@ -152,6 +152,10 @@ pub(super) fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end: Tool::Triangle => json!({"kind": "triangle", "rect": rect}), // PhotoCraft's star defaults; the Star Tool's own options are not measured yet (#11377). Tool::Star => json!({"kind": "star", "rect": rect, "sides": 5, "starRatio": 0.5}), + // The Polygon tool's own corner radius rounds every vertex of the next polygon (#13302). + Tool::Polygon if o.polygon_corner_radius > 0.0 => { + json!({"kind": "polygon", "rect": rect, "sides": o.polygon_sides.max(3), "cornerRadius": o.polygon_corner_radius}) + } _ => json!({"kind": "polygon", "rect": rect, "sides": o.polygon_sides.max(3)}), } }) From 5b4964bc9b4925c519c319990c24c291e5c29b4b Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:18:50 +0100 Subject: [PATCH 06/25] Place Embedded: choose several files and place them one after another (#14107) --- crates/ui-egui/src/file_dialog.rs | 59 ++++- crates/ui-egui/src/file_dialog/tests.rs | 2 +- crates/ui-egui/src/file_open.rs | 37 ++- crates/ui-egui/src/menus/view_cmds/dialogs.rs | 23 +- .../ui-egui/src/place_multiple_files_tests.rs | 227 ++++++++++++++++++ 5 files changed, 337 insertions(+), 11 deletions(-) create mode 100644 crates/ui-egui/src/place_multiple_files_tests.rs diff --git a/crates/ui-egui/src/file_dialog.rs b/crates/ui-egui/src/file_dialog.rs index aabff48324..ca793133c8 100644 --- a/crates/ui-egui/src/file_dialog.rs +++ b/crates/ui-egui/src/file_dialog.rs @@ -278,6 +278,18 @@ impl PhotocraftApp { }) } + /// [`Self::pick_file_bytes`] letting the user choose several files (File › Place Embedded): + /// `then` gets every chosen file, in the order the dialog returns them. A desktop file is + /// handed over by path and read only when [`PickedFile::read`] is called, so files waiting + /// their turn hold no contents; the web hands over each file's contents. + pub(crate) fn pick_files_bytes(&mut self, then: impl FnOnce(&mut Self, Vec) -> Result + 'static) -> Result { + let initial_dir = last_used_dir(&self.ui.recent_files); + self.ask_file(FileDialogRequest::Open { multiple: true, initial_dir, extensions: None }, move |app, answer| { + let files = picked_files(answer)?; + then(app, files) + }) + } + /// File › Open: opens every chosen file in the order the dialog returns them, reporting each /// failure (see [`Self::open_paths_in_order`]). pub fn open_dialog_file(&mut self) -> Result { @@ -467,16 +479,53 @@ fn read_picked(answer: FileDialogAnswer) -> Result<(String, Vec), String> { match answer { FileDialogAnswer::Contents(name, bytes) => Ok((name, bytes)), FileDialogAnswer::ContentsMany(files) => files.into_iter().next().ok_or_else(|| CANCELLED.into()), - FileDialogAnswer::Paths(paths) => { - let path = paths.into_iter().next().ok_or(CANCELLED)?; - let bytes = photocraft_format::read_file(std::path::Path::new(&path)).map_err(|e| format!("{}: {e}", display_name(&path)))?; - Ok((path, bytes)) - } + FileDialogAnswer::Paths(paths) => read_path(paths.into_iter().next().ok_or(CANCELLED)?), FileDialogAnswer::FolderTo(_) => Err(UNEXPECTED.into()), FileDialogAnswer::SaveTo(_) | FileDialogAnswer::Unavailable(_) => Err(UNEXPECTED.into()), } } +/// The file at `path` with its contents; one that can't be read fails with ": ". +fn read_path(path: String) -> Result<(String, Vec), String> { + let bytes = photocraft_format::read_file(std::path::Path::new(&path)).map_err(|e| format!("{}: {e}", display_name(&path)))?; + Ok((path, bytes)) +} + +/// One file chosen in the several-file picker ([`PhotocraftApp::pick_files_bytes`]). +#[derive(Debug)] +pub(crate) enum PickedFile { + /// A file on disk (desktop), by its full path: read when its turn comes. + Path(String), + /// A file's name and contents (the web, where the page gets contents rather than paths). + Contents(String, Vec), +} + +impl PickedFile { + /// Its name (the full path on the desktop) and contents, reading a desktop file now; one that + /// can't be read fails with ": ", as in [`PhotocraftApp::pick_file_bytes`]. + pub(crate) fn read(self) -> Result<(String, Vec), String> { + match self { + Self::Path(path) => read_path(path), + Self::Contents(name, bytes) => Ok((name, bytes)), + } + } +} + +/// The files chosen in a several-file picker, in the order the dialog returns them (none: Cancel). +fn picked_files(answer: FileDialogAnswer) -> Result, String> { + let files: Vec = match answer { + FileDialogAnswer::Paths(paths) => paths.into_iter().map(PickedFile::Path).collect(), + FileDialogAnswer::Contents(name, bytes) => vec![PickedFile::Contents(name, bytes)], + FileDialogAnswer::ContentsMany(files) => files.into_iter().map(|(name, bytes)| PickedFile::Contents(name, bytes)).collect(), + FileDialogAnswer::FolderTo(_) => return Err(UNEXPECTED.into()), + FileDialogAnswer::SaveTo(_) | FileDialogAnswer::Unavailable(_) => return Err(UNEXPECTED.into()), + }; + if files.is_empty() { + return Err(CANCELLED.into()); + } + Ok(files) +} + /// A fake dialog service for tests: answers each request with the next of `answers` (`None`: /// Cancel), recording the requests. #[cfg(test)] diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rs index d009b116cd..52bf9ecf75 100644 --- a/crates/ui-egui/src/file_dialog/tests.rs +++ b/crates/ui-egui/src/file_dialog/tests.rs @@ -996,7 +996,7 @@ fn place_embedded_uses_the_single_file_picker_and_accepts_contents() { // Cancel leaves the document alone and does not report an error. menus::invoke(&mut app, &ctx, "file.placeEmbedded", json!({})).unwrap(); app.poll_file_dialog(&ctx, None); - assert!(matches!(open.borrow().as_slice(), [(FileDialogRequest::Open { multiple: false, .. }, _)])); + assert!(matches!(open.borrow().as_slice(), [(FileDialogRequest::Open { multiple: true, .. }, _)])); answer(&open, None); app.poll_file_dialog(&ctx, None); assert_eq!(app.session.active().unwrap().doc.layers.len(), layers_before); diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 1ae2be2003..43664e3bbf 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -106,7 +106,8 @@ pub(crate) fn log_drag_over(ctx: &egui::Context, hovering: usize) { } /// A file dropped on the canvas, waiting its turn to be placed in the document it was dropped on -/// (queued with its [`DocId`] in `drop_places`). +/// (queued with its [`DocId`] in `drop_places`), or one of several files chosen at once in File › +/// Place Embedded's dialog, waiting its turn in the document the command was given in. pub(crate) enum DropPlace { /// Destination captured when the file is dropped, before a later pointer move. At { source: Box, frame: Option }, @@ -115,6 +116,10 @@ pub(crate) enum DropPlace { /// Read by the shell itself (the browser reads dropped files asynchronously): its name and /// contents, delivered through [`Services::place_inbox`](crate::Services::place_inbox). Bytes(String, Vec), + /// Chosen in File › Place Embedded's dialog (desktop), by its full path: read when its turn + /// comes and placed as that dialog places a single file. The web's picks carry their contents + /// and wait as [`Self::Bytes`]. + Path(String), } impl DropPlace { @@ -122,7 +127,7 @@ impl DropPlace { fn queued_bytes(&self) -> usize { match self { Self::At { source, .. } => source.queued_bytes(), - Self::File(_) => 0, + Self::File(_) | Self::Path(_) => 0, Self::Bytes(_, bytes) => bytes.len(), } } @@ -132,7 +137,7 @@ impl DropPlace { fn holds_bytes(&self) -> bool { match self { Self::At { source, .. } => source.holds_bytes(), - Self::File(_) => false, + Self::File(_) | Self::Path(_) => false, Self::Bytes(..) => true, } } @@ -528,6 +533,12 @@ impl PhotocraftApp { let placed = self.place_bytes_with(&name, bytes, None, ¶ms); (name, placed) } + DropPlace::Path(path) => { + let placed = photocraft_format::read_file(std::path::Path::new(&path)) + .map_err(|e| e.to_string()) + .and_then(|bytes| self.place_bytes_with(&path, bytes, None, ¶ms)); + (display_name(&path), placed) + } }; match placed { // Running in the background: Free Transform starts when the layer has landed. @@ -546,6 +557,23 @@ impl PhotocraftApp { } } + /// File › Place Embedded with several files chosen (#14107): as in the reference application, + /// each is placed in `doc` in turn, in the order the dialog returned them, with its own Free + /// Transform and its own history state. They wait in the queue of files dropped on the canvas, + /// so the next one is placed once the previous one's transform is committed or cancelled (Esc + /// takes back only that file), and with Skip Transform when Placing all of them are placed at + /// once. A file that can't be read or placed is reported and the next one placed. + pub(crate) fn place_picked(&mut self, ctx: &egui::Context, doc: DocId, files: Vec) { + for file in files { + let place = match file { + crate::file_dialog::PickedFile::Path(path) => DropPlace::Path(path), + crate::file_dialog::PickedFile::Contents(name, bytes) => DropPlace::Bytes(name, bytes), + }; + self.queue_drop(doc, place); + } + self.place_next_dropped(ctx); + } + /// Queue the web drops onto the canvas that the shell has read since the last frame /// ([`Services::place_inbox`](crate::Services::place_inbox)), for the document they were /// dropped on. @@ -711,4 +739,7 @@ fn same_file(p: &str, path: &str, canon: Option<&std::path::Path>) -> bool { #[cfg(test)] mod dialog_order_tests; #[cfg(test)] +#[path = "place_multiple_files_tests.rs"] +mod place_multiple_files_tests; +#[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index d4518748d9..5f53e3470d 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -406,8 +406,8 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para Err(e) => return Some(Err(e)), }; let linked = id == "file.placeLinked"; - let ctx = ctx.clone(); - Some(app.pick_file_bytes(move |app, name, bytes| { + let (ctx, queue_ctx) = (ctx.clone(), ctx.clone()); + let place = move |app: &mut PhotocraftApp, name: String, bytes: Vec| { if app.ui.transform.is_some() { return Err("Commit or cancel the transform first".into()); } @@ -419,6 +419,25 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para crate::transform_tool::begin_placed(app, &ctx)?; } Ok(result) + }; + if linked { + return Some(app.pick_file_bytes(place)); + } + // Place Embedded takes several files (#14107); one file is placed as before. + Some(app.pick_files_bytes(move |app, files| match <[crate::file_dialog::PickedFile; 1]>::try_from(files) { + Ok([file]) => { + let (name, bytes) = file.read()?; + place(app, name, bytes) + } + Err(files) => { + if app.ui.transform.is_some() { + return Err("Commit or cancel the transform first".into()); + } + app.refocus(doc)?; + let count = files.len(); + app.place_picked(&queue_ctx, doc, files); + Ok(json!({ "files": count })) + } })) } "layer.smartObjects.replaceContents" => { diff --git a/crates/ui-egui/src/place_multiple_files_tests.rs b/crates/ui-egui/src/place_multiple_files_tests.rs new file mode 100644 index 0000000000..ab1981d18d --- /dev/null +++ b/crates/ui-egui/src/place_multiple_files_tests.rs @@ -0,0 +1,227 @@ +//! #14107: File › Place Embedded with several files chosen at once places them one after another, +//! each with its own Free Transform box, its own layer above the previous one and its own history +//! state, as the reference application does. + +use super::*; +use crate::file_dialog::{self, FileDialogAnswer, FileDialogRequest}; +use crate::menus; +use serde_json::json; +use std::cell::RefCell; +use std::rc::Rc; + +/// The requests the fake file dialog was given. +type Asked = Rc>>; + +/// An app with one 40×30 document whose file dialog answers `picked` (once), and the requests the +/// dialog was given. +fn app_picking(picked: FileDialogAnswer) -> (PhotocraftApp, Asked) { + let (show, asked) = file_dialog::fake(vec![Some(picked)]); + let services = crate::Services { file_dialog: Some(show), ..Default::default() }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.run("file.new", json!({"width": 40, "height": 30})).unwrap(); + (app, asked) +} + +/// File › Place Embedded from the menu, its dialog shown and answered at the end of the frame. +fn place_embedded(app: &mut PhotocraftApp, ctx: &egui::Context) { + menus::invoke(app, ctx, "file.placeEmbedded", json!({})).unwrap(); + app.poll_file_dialog(ctx, None); +} + +/// PNG bytes of a white `w`×`h` image. +fn png(w: u32, h: u32) -> Vec { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": w, "height": h, "background": "white"})).unwrap(); + photocraft_io::export(&s.active().unwrap().doc, "p.png", &Default::default()).unwrap().bytes +} + +/// The active document's layer names, bottom to top. +fn names(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().doc.layers.iter().map(|l| l.name.clone()).collect() +} + +/// The active layer's name. +fn active_name(app: &PhotocraftApp) -> String { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().name.clone() +} + +/// How many history states the active document has behind it. +fn history_steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +/// The open Free Transform box of a placed layer, as (left, top, right, bottom) in document pixels. +fn place_box(app: &PhotocraftApp) -> [f64; 4] { + let t = app.ui.transform.as_ref().expect("a placed file is in Free Transform"); + assert_eq!(t.made, Some(crate::state::MadeLayer::Place)); + let xs = t.quad.map(|c| c[0]); + let ys = t.quad.map(|c| c[1]); + let fold = |v: [f64; 4], f: fn(f64, f64) -> f64| v.into_iter().reduce(f).unwrap(); + [fold(xs, f64::min), fold(ys, f64::min), fold(xs, f64::max), fold(ys, f64::max)] +} + +/// Three files (20×10, 8×6 and 12×4), as the web picker hands them over: each with its contents. +fn three_contents() -> FileDialogAnswer { + FileDialogAnswer::ContentsMany(vec![("first.png".into(), png(20, 10)), ("second.png".into(), png(8, 6)), ("third.png".into(), png(12, 4))]) +} + +#[test] +fn place_embedded_asks_for_several_files_and_place_linked_for_one() { + let ctx = egui::Context::default(); + let (mut app, asked) = app_picking(FileDialogAnswer::Contents("one.png".into(), png(4, 4))); + place_embedded(&mut app, &ctx); + assert!(matches!(asked.borrow().as_slice(), [FileDialogRequest::Open { multiple: true, extensions: None, .. }])); + // Place Linked keeps its single-file dialog (several files there were not measured). + crate::transform_tool::commit(&mut app); + let (show, linked) = file_dialog::fake(vec![None]); + app.services.file_dialog = Some(show); + menus::invoke(&mut app, &ctx, "file.placeLinked", json!({})).unwrap(); + app.poll_file_dialog(&ctx, None); + assert!(matches!(linked.borrow().as_slice(), [FileDialogRequest::Open { multiple: false, .. }])); +} + +/// The measured sequence: the first file appears with its box, ↩ commits it as its own history +/// state, the second then appears with its own box as its own layer above the first, and Esc on it +/// removes only that file. The third still follows. +#[test] +fn several_files_are_placed_one_after_another_each_in_its_own_transform() { + let ctx = egui::Context::default(); + let (mut app, _) = app_picking(three_contents()); + let steps = history_steps(&app); + place_embedded(&mut app, &ctx); + assert!(!app.ui.status_error, "{}", app.ui.status); + // Only the first file is placed: its box is its own size, centred on the 40×30 canvas. + assert_eq!(names(&app), ["Background", "first"]); + assert_eq!(place_box(&app), [10.0, 10.0, 30.0, 20.0]); + assert_eq!(app.drop_places.len(), 2, "the other two wait their turn"); + // Frames go by while the box is open: nothing else is placed. + app.place_next_dropped(&ctx); + assert_eq!(names(&app), ["Background", "first"]); + assert_eq!(history_steps(&app), steps); + + // ↩ commits the first file: one history state. + crate::transform_tool::commit(&mut app); + assert_eq!(history_steps(&app), steps + 1); + // The next frame places the second one above it, with its own box. + app.place_next_dropped(&ctx); + assert_eq!(names(&app), ["Background", "first", "second"]); + assert_eq!(active_name(&app), "second"); + assert_eq!(place_box(&app), [16.0, 12.0, 24.0, 18.0]); + + // Esc removes only the second file; the first stays placed and committed. + crate::transform_tool::cancel(&mut app); + assert_eq!(names(&app), ["Background", "first"]); + assert_eq!(history_steps(&app), steps + 1); + assert!(!app.session.active().unwrap().history.can_redo()); + // And the third is placed next, above the first. + app.place_next_dropped(&ctx); + assert_eq!(names(&app), ["Background", "first", "third"]); + assert_eq!(place_box(&app), [14.0, 13.0, 26.0, 17.0]); + crate::transform_tool::commit(&mut app); + assert_eq!(history_steps(&app), steps + 2); + app.place_next_dropped(&ctx); + assert!(app.ui.transform.is_none() && app.drop_places.is_empty()); + + // Each file is its own history state: one Undo takes back only the third. + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(names(&app), ["Background", "first"]); +} + +/// On the desktop the dialog answers paths: each file is read when its turn comes and placed as +/// the dialog's single file is (named after the file, an embedded smart object), in the order the +/// dialog returned them. A file that can't be read is reported and the next one placed. +#[test] +fn chosen_paths_are_read_in_turn_and_a_missing_one_is_reported() { + let dir = std::env::temp_dir().join(format!("photocraft-place-multiple-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (b, a) = (dir.join("b.png"), dir.join("a.png")); + std::fs::write(&b, png(20, 10)).unwrap(); + std::fs::write(&a, png(8, 6)).unwrap(); + let missing = dir.join("gone.png"); + let paths = [&b, &missing, &a].map(|p| p.to_string_lossy().into_owned()); + let ctx = egui::Context::default(); + let (mut app, _) = app_picking(FileDialogAnswer::Paths(paths.to_vec())); + place_embedded(&mut app, &ctx); + // The dialog's order, not name order: b first. + assert_eq!(names(&app), ["Background", "b"]); + assert_eq!(place_box(&app), [10.0, 10.0, 30.0, 20.0]); + // Waiting files hold their paths, not their contents. + assert!(app.drop_places.iter().all(|(_, p)| matches!(p, DropPlace::Path(_)))); + crate::transform_tool::commit(&mut app); + app.place_next_dropped(&ctx); + assert_eq!(app.ui.notices.iter().filter(|n| n.error && n.title.contains("gone.png")).count(), 1); + assert_eq!(names(&app), ["Background", "b", "a"]); + assert_eq!(place_box(&app), [16.0, 12.0, 24.0, 18.0]); + let st = app.session.active().unwrap(); + assert!(matches!( + &st.doc.layer(st.active_layer.unwrap()).unwrap().content, + photocraft_doc::LayerContent::Smart(sm) if matches!(&sm.source, photocraft_doc::SmartSource::Embedded { .. }) + )); + crate::transform_tool::commit(&mut app); + assert!(app.drop_places.is_empty()); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// With Skip Transform when Placing on, all the chosen files are placed and committed at once, one +/// history state each, without Free Transform. +#[test] +fn skip_transform_when_placing_commits_every_file_at_once() { + let ctx = egui::Context::default(); + let (mut app, _) = app_picking(three_contents()); + app.session.execute("prefs.set", json!({"path": "general.skipTransformWhenPlacing", "value": true})).unwrap(); + let steps = history_steps(&app); + place_embedded(&mut app, &ctx); + assert!(app.ui.transform.is_none() && app.drop_places.is_empty()); + assert_eq!(names(&app), ["Background", "first", "second", "third"]); + assert_eq!(history_steps(&app), steps + 3); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(names(&app), ["Background", "first", "second"]); +} + +/// With background jobs on, each file is decoded on a worker: the next one starts only once the +/// previous one has landed and its box has been committed. +#[test] +fn background_places_follow_one_another() { + let ctx = egui::Context::default(); + let (mut app, _) = app_picking(FileDialogAnswer::ContentsMany(vec![("first.png".into(), png(20, 10)), ("second.png".into(), png(8, 6))])); + app.background_jobs = true; + place_embedded(&mut app, &ctx); + let wait = |app: &mut PhotocraftApp, done: &dyn Fn(&PhotocraftApp) -> bool| { + let t = std::time::Instant::now(); + while !done(app) { + assert!(t.elapsed() < std::time::Duration::from_secs(30), "not placed after 30 s"); + crate::jobs_ui::tick(app, &ctx); + app.place_next_dropped(&ctx); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + }; + wait(&mut app, &|app| app.ui.transform.is_some()); + assert_eq!(names(&app), ["Background", "first"]); + assert_eq!(app.drop_places.len(), 1); + crate::transform_tool::commit(&mut app); + wait(&mut app, &|app| app.ui.transform.is_some()); + assert_eq!(names(&app), ["Background", "first", "second"]); + assert_eq!(place_box(&app), [16.0, 12.0, 24.0, 18.0]); +} + +/// One file chosen, from either picker, is placed as before: at once, in Free Transform, with +/// nothing queued, and a file that can't be read is the command's error. +#[test] +fn a_single_chosen_file_is_placed_as_before() { + let ctx = egui::Context::default(); + for picked in [FileDialogAnswer::Contents("one.png".into(), png(20, 10)), FileDialogAnswer::ContentsMany(vec![("one.png".into(), png(20, 10))])] { + let (mut app, _) = app_picking(picked); + place_embedded(&mut app, &ctx); + assert_eq!(names(&app), ["Background", "one"]); + assert_eq!(place_box(&app), [10.0, 10.0, 30.0, 20.0]); + assert!(app.drop_places.is_empty()); + } + let missing = std::env::temp_dir().join(format!("photocraft-place-missing-{}.png", std::process::id())); + let (mut app, _) = app_picking(FileDialogAnswer::Paths(vec![missing.to_string_lossy().into_owned()])); + place_embedded(&mut app, &ctx); + assert!(app.ui.status_error); + assert!(app.ui.status.contains("photocraft-place-missing-"), "{}", app.ui.status); + assert_eq!(names(&app), ["Background"]); + assert!(app.ui.transform.is_none() && app.drop_places.is_empty()); +} From cb90f35d1a13dde67be6c414ccd69730aa77104d Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:33:40 +0100 Subject: [PATCH 07/25] Place Embedded several files: drop a wrong mid-transform history assertion --- crates/ui-egui/src/place_multiple_files_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/place_multiple_files_tests.rs b/crates/ui-egui/src/place_multiple_files_tests.rs index ab1981d18d..7997cf6f9e 100644 --- a/crates/ui-egui/src/place_multiple_files_tests.rs +++ b/crates/ui-egui/src/place_multiple_files_tests.rs @@ -98,7 +98,7 @@ fn several_files_are_placed_one_after_another_each_in_its_own_transform() { // Frames go by while the box is open: nothing else is placed. app.place_next_dropped(&ctx); assert_eq!(names(&app), ["Background", "first"]); - assert_eq!(history_steps(&app), steps); + assert_eq!(app.drop_places.len(), 2); // ↩ commits the first file: one history state. crate::transform_tool::commit(&mut app); From 2885ee624a53a5b5151002262b45ae58bf7db1b7 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 17 Nov 2026 04:13:07 +0100 Subject: [PATCH 08/25] Place Embedded several files: queue every chosen file past the drop limits; tempdir fixture --- crates/ui-egui/src/file_open.rs | 8 ++++++- .../ui-egui/src/place_multiple_files_tests.rs | 22 ++++++++++++++++--- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 43664e3bbf..f55d4663d6 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -563,13 +563,19 @@ impl PhotocraftApp { /// so the next one is placed once the previous one's transform is committed or cancelled (Esc /// takes back only that file), and with Skip Transform when Placing all of them are placed at /// once. A file that can't be read or placed is reported and the next one placed. + /// + /// Every chosen file is queued: the drop queue's admission limits ([`queue_takes_drop`]) are + /// not applied to them. A desktop pick waits as its path, and a web pick's contents were + /// already read by the browser when the dialog answered, so refusing it would free nothing + /// and only lose a file the user chose. Each is released as soon as it is placed, and while + /// they wait they count against the limit for later drops. pub(crate) fn place_picked(&mut self, ctx: &egui::Context, doc: DocId, files: Vec) { for file in files { let place = match file { crate::file_dialog::PickedFile::Path(path) => DropPlace::Path(path), crate::file_dialog::PickedFile::Contents(name, bytes) => DropPlace::Bytes(name, bytes), }; - self.queue_drop(doc, place); + self.drop_places.push_back((doc, place)); } self.place_next_dropped(ctx); } diff --git a/crates/ui-egui/src/place_multiple_files_tests.rs b/crates/ui-egui/src/place_multiple_files_tests.rs index 7997cf6f9e..bd06d6fa0d 100644 --- a/crates/ui-egui/src/place_multiple_files_tests.rs +++ b/crates/ui-egui/src/place_multiple_files_tests.rs @@ -133,8 +133,8 @@ fn several_files_are_placed_one_after_another_each_in_its_own_transform() { /// dialog returned them. A file that can't be read is reported and the next one placed. #[test] fn chosen_paths_are_read_in_turn_and_a_missing_one_is_reported() { - let dir = std::env::temp_dir().join(format!("photocraft-place-multiple-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); let (b, a) = (dir.join("b.png"), dir.join("a.png")); std::fs::write(&b, png(20, 10)).unwrap(); std::fs::write(&a, png(8, 6)).unwrap(); @@ -160,7 +160,6 @@ fn chosen_paths_are_read_in_turn_and_a_missing_one_is_reported() { )); crate::transform_tool::commit(&mut app); assert!(app.drop_places.is_empty()); - std::fs::remove_dir_all(&dir).unwrap(); } /// With Skip Transform when Placing on, all the chosen files are placed and committed at once, one @@ -225,3 +224,20 @@ fn a_single_chosen_file_is_placed_as_before() { assert_eq!(names(&app), ["Background"]); assert!(app.ui.transform.is_none() && app.drop_places.is_empty()); } + +/// Every chosen file is placed, even past the limits that bound drops waiting for their document +/// (32 browser drops): the web's picks are already read when the dialog answers, so none is lost. +#[test] +fn every_chosen_file_is_placed_past_the_drop_queue_limit() { + let ctx = egui::Context::default(); + let files: Vec<(String, Vec)> = (0..MAX_QUEUED_DROPS + 2).map(|i| (format!("f{i}.png"), png(2, 2))).collect(); + let (mut app, _) = app_picking(FileDialogAnswer::ContentsMany(files)); + app.session.execute("prefs.set", json!({"path": "general.skipTransformWhenPlacing", "value": true})).unwrap(); + let steps = history_steps(&app); + place_embedded(&mut app, &ctx); + assert!(!app.ui.status_error, "{}", app.ui.status); + assert!(app.drop_places.is_empty()); + let expected: Vec = std::iter::once("Background".to_string()).chain((0..MAX_QUEUED_DROPS + 2).map(|i| format!("f{i}"))).collect(); + assert_eq!(names(&app), expected); + assert_eq!(history_steps(&app), steps + MAX_QUEUED_DROPS + 2); +} From 50d8f4d6c92509cab317bf435fd450361e7b9dbd Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:55:23 +0100 Subject: [PATCH 09/25] Place Embedded: centre on the selection, else on the part of the canvas in view (#14102, #14103) --- crates/engine/src/cmd/file_cmds.rs | 6 +- crates/engine/src/cmd/file_cmds/open.rs | 29 +++- .../file_cmds/place_selection_centre_tests.rs | 128 ++++++++++++++++++ .../engine/src/cmd/file_cmds/place_steps.rs | 6 +- crates/ui-egui/src/file_open.rs | 29 +++- crates/ui-egui/src/lib.rs | 3 + .../ui-egui/src/place_visible_centre_tests.rs | 101 ++++++++++++++ 7 files changed, 297 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/cmd/file_cmds/place_selection_centre_tests.rs create mode 100644 crates/ui-egui/src/place_visible_centre_tests.rs diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 7d3f1b021f..e06ee31742 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -340,7 +340,7 @@ pub fn specs() -> Vec { "Place Embedded…", &["File"], None, - r##"{"path":str,"scale":%? (default: fit when larger than the canvas),"fit":bool? (default: Preferences > General > Resize Image During Place),"smartObject":bool? (default: Preferences > General > Always Create Smart Objects When Placing),"center":[x,y]?,"approveHighMemory":bool=false (explicitly approve high memory usage),"frame":id|false? (default: selected frame)}"##, + r##"{"path":str,"scale":%? (default: fit when larger than the canvas),"fit":bool? (default: Preferences > General > Resize Image During Place),"smartObject":bool? (default: Preferences > General > Always Create Smart Objects When Placing),"center":[x,y]?,"centerOnSelection":bool=false (as File > Place Embedded: centre on a hard-edged rectangular selection, over center, and remove the selection in the same step),"approveHighMemory":bool=false (explicitly approve high memory usage),"frame":id|false? (default: selected frame)}"##, native_doc, |s, p| place(s, p, false) ), @@ -453,6 +453,10 @@ pub fn specs() -> Vec { ] } +#[cfg(test)] +#[path = "file_cmds/place_selection_centre_tests.rs"] +mod place_selection_centre_tests; + #[cfg(test)] #[path = "file_cmds/tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/file_cmds/open.rs b/crates/engine/src/cmd/file_cmds/open.rs index 959ff3a15b..fc589eb89a 100644 --- a/crates/engine/src/cmd/file_cmds/open.rs +++ b/crates/engine/src/cmd/file_cmds/open.rs @@ -372,6 +372,9 @@ pub(crate) struct PlaceInput { pub(super) linked: Option, pub(super) params: Value, pub(super) canvas: (f64, f64), + /// File › Place Embedded's centre on the selection (`"centerOnSelection"`, #14102): the + /// placed image is centred there and the selection removed in the place's own step. + pub(super) on_selection: Option<(f64, f64)>, pub(super) fmt: PixelFormat, pub(super) opts: photocraft_io::ImportOptions, /// Preferences ▸ General ▸ Resize Image During Place, unless the params say otherwise. @@ -416,6 +419,8 @@ impl PlaceInput { let [a, b, c, d, _, _] = f.transform.m; (a.hypot(b), c.hypot(d)) }); + // Not into a frame, whose image fills the frame. + let on_selection = if frame.is_none() && p.get("centerOnSelection").and_then(Value::as_bool) == Some(true) { selection_centre(&d.doc) } else { None }; let approve = match p.get("approveHighMemory") { None | Some(Value::Null) => false, Some(Value::Bool(b)) => *b, @@ -429,6 +434,7 @@ impl PlaceInput { Ok(Self { name: name.to_string(), canvas, + on_selection, fmt: d.doc.pixel_format(), opts, // The implicit `fit` is Preferences ▸ General ▸ Resize Image During Place (on by default). @@ -458,6 +464,22 @@ impl PlaceInput { } } +/// The centre of the selection a File › Place Embedded centres the placed image on (#14102): +/// the bounds of a hard-edged rectangle on the canvas, the selection measured. Any other +/// selection (feathered, not rectangular, or reaching past the canvas) leaves the place centred +/// as before, and kept. +fn selection_centre(doc: &Document) -> Option<(f64, f64)> { + let sel = doc.selection.as_ref()?; + let b = sel.content_bounds(); + if b.is_empty() || b.intersect(&doc.bounds()) != b || sel.default_pixel().first().is_some_and(|v| *v > 0.0) { + return None; + } + // Row by row, so a large selection is never read at once. + let n = sel.channels().max(1); + let hard = (b.y0..b.y1).all(|y| sel.read_region(photocraft_geom::Rect::new(b.x0, y, b.x1, y + 1)).chunks_exact(n).all(|px| px[0] >= 1.0)); + hard.then(|| (f64::from(b.x0 + b.x1) / 2.0, f64::from(b.y0 + b.y1) / 2.0)) +} + /// A place decoded, flattened and fitted, ready to be inserted by [`apply_place`]. pub(crate) struct Prepared { pub(super) warnings: Vec, @@ -470,11 +492,13 @@ pub(crate) struct Prepared { pub(super) smart: bool, /// The frame the layer fills, if any (it becomes the frame's content instead of a new layer). pub(super) frame: Option, + /// The place was centred on the selection, which it removes in the same step. + pub(super) deselect: bool, } /// Insert the prepared layer as one undo step and report the place. Runs on the session's thread. pub(crate) fn apply_place(s: &mut Session, p: Prepared) -> Result { - let Prepared { warnings, content, layer_name, label, scale, bounds, smart, frame } = p; + let Prepared { warnings, content, layer_name, label, scale, bounds, smart, frame, deselect } = p; let layer = Layer::new(layer_name, content); let id = layer.id; s.edit(label, move |doc, active| { @@ -485,6 +509,9 @@ pub(crate) fn apply_place(s: &mut Session, p: Prepared) -> Result { crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::AutoEditable); *active = Some(id); } + if deselect { + doc.selection = None; + } Ok(()) })?; Ok(json!({"layer": id.0, "frame": frame.map(|f| f.0), "scale": scale * 100.0, "bounds": bounds, "smartObject": smart, "warnings": warnings})) diff --git a/crates/engine/src/cmd/file_cmds/place_selection_centre_tests.rs b/crates/engine/src/cmd/file_cmds/place_selection_centre_tests.rs new file mode 100644 index 0000000000..b5464e20c1 --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/place_selection_centre_tests.rs @@ -0,0 +1,128 @@ +//! File › Place Embedded with a selection (#14102): the placed image is centred on the +//! selection's bounds and the selection removed, in the place's one history step, as measured in +//! the reference application (400 × 300 document, selection 300,200 to 380,280). + +use super::*; + +/// A 400 × 300 document with the selection 300,200 to 380,280 (`extra` adds to `select.rect`'s +/// params: an ellipse, a feather), or none. +fn session(selection: Option) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300, "depth": 8})).unwrap(); + if let Some(extra) = selection { + let mut p = json!({"x": 300, "y": 200, "width": 80, "height": 80}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + s.execute("select.rect", p).unwrap(); + } + s +} + +/// A gray `w` × `h` PNG. +fn png(w: u32, h: u32) -> Vec { + let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, vec![128; (w * h * 3) as usize]).unwrap(); + photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap() +} + +/// Places a `w` × `h` file with `params`; its box. +fn place(s: &mut Session, w: u32, h: u32, params: Value) -> [f64; 4] { + let r = place_bytes(s, "src.png", png(w, h), None, ¶ms).unwrap(); + let b: Vec = r["bounds"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + [b[0], b[1], b[2], b[3]] +} + +/// File › Place Embedded's params: centre on the selection. +fn menu() -> Value { + json!({"centerOnSelection": true}) +} + +fn selection_bounds(s: &Session) -> Option { + s.active().unwrap().doc.selection.as_ref().map(photocraft_raster::Surface::content_bounds) +} + +/// The measured case: a 120 × 90 file lands at 280,195 to 400,285 (centre 340,240) and a 100 × 60 +/// one at 290,210 to 390,270; the selection is gone. +#[test] +fn a_place_centres_on_the_selection_and_removes_it() { + for (w, h, want) in [(120, 90, [280.0, 195.0, 400.0, 285.0]), (100, 60, [290.0, 210.0, 390.0, 270.0])] { + let mut s = session(Some(json!({}))); + assert_eq!(place(&mut s, w, h, menu()), want, "{w}×{h}"); + assert_eq!(selection_bounds(&s), None, "{w}×{h}: the selection is removed"); + } +} + +/// One history step: Undo takes the layer away and brings the selection back; Redo places it +/// again without the selection. +#[test] +fn the_place_and_the_deselect_are_one_step() { + let mut s = session(Some(json!({}))); + let (layers, steps) = (s.active().unwrap().doc.layer_count(), s.active().unwrap().history.past_len()); + place(&mut s, 100, 60, menu()); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc.layer_count(), layers); + assert_eq!(selection_bounds(&s), Some(photocraft_geom::Rect::new(300, 200, 380, 280)), "Undo brings the selection back"); + assert!(s.redo()); + assert_eq!(s.active().unwrap().doc.layer_count(), layers + 1); + assert_eq!(selection_bounds(&s), None); +} + +/// The same place as a background job lands in the same place and removes the selection too. +#[test] +fn a_place_job_centres_on_the_selection_too() { + let mut s = session(Some(json!({}))); + let started = s.start_place_bytes("src.png", png(100, 60), None, menu()).unwrap(); + let r = match started { + crate::jobs::Started::Done(v) => v, + crate::jobs::Started::Job(id) => { + let t = std::time::Instant::now(); + loop { + if let Some(e) = s.poll_jobs().into_iter().find(|e| e.id == id) { + match e.outcome { + crate::jobs::JobOutcome::Done(v) => break v, + other => panic!("the place failed: {other:?}"), + } + } + assert!(t.elapsed() < std::time::Duration::from_secs(60), "the place did not finish"); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + } + }; + assert_eq!(r["bounds"], json!([290.0, 210.0, 390.0, 270.0])); + assert_eq!(selection_bounds(&s), None); +} + +/// Without a selection the place centres on the canvas, as before: 100 × 60 at 150,120. +#[test] +fn without_a_selection_the_place_centres_on_the_canvas() { + let mut s = session(None); + assert_eq!(place(&mut s, 100, 60, menu()), [150.0, 120.0, 250.0, 180.0]); +} + +/// The selection wins over an explicit `center` when asked to centre on it; without +/// `centerOnSelection` (a drop on the canvas, a script) `center` and the canvas centre are used as +/// before and the selection stays. +#[test] +fn an_explicit_center_or_no_request_keeps_the_selection() { + let mut s = session(Some(json!({}))); + assert_eq!(place(&mut s, 100, 60, json!({"centerOnSelection": true, "center": [100, 100]})), [290.0, 210.0, 390.0, 270.0]); + + let mut s = session(Some(json!({}))); + assert_eq!(place(&mut s, 100, 60, json!({"center": [100, 100]})), [50.0, 70.0, 150.0, 130.0]); + assert_eq!(selection_bounds(&s), Some(photocraft_geom::Rect::new(300, 200, 380, 280))); + + let mut s = session(Some(json!({}))); + assert_eq!(place(&mut s, 100, 60, json!({})), [150.0, 120.0, 250.0, 180.0]); + assert_eq!(selection_bounds(&s), Some(photocraft_geom::Rect::new(300, 200, 380, 280))); +} + +/// A selection that isn't a hard-edged rectangle (not measured) leaves the place as it was: +/// centred on the canvas, the selection kept. +#[test] +fn an_elliptical_or_feathered_selection_keeps_todays_place() { + for extra in [json!({"ellipse": true}), json!({"feather": 4})] { + let mut s = session(Some(extra.clone())); + let before = selection_bounds(&s); + assert_eq!(place(&mut s, 100, 60, menu()), [150.0, 120.0, 250.0, 180.0], "{extra}"); + assert_eq!(selection_bounds(&s), before, "{extra}: the selection stays"); + } +} diff --git a/crates/engine/src/cmd/file_cmds/place_steps.rs b/crates/engine/src/cmd/file_cmds/place_steps.rs index f4e49a67ce..44623adb53 100644 --- a/crates/engine/src/cmd/file_cmds/place_steps.rs +++ b/crates/engine/src/cmd/file_cmds/place_steps.rs @@ -169,8 +169,9 @@ impl PlaceSteps { None if self.input.fit && (w > cw || h > ch) => (cw / w).min(ch / h), None => 1.0, }; - let center = match p.get("center").and_then(Value::as_array) { - Some(c) if c.len() == 2 => (c[0].as_f64().unwrap_or(cw / 2.0), c[1].as_f64().unwrap_or(ch / 2.0)), + let center = match (self.input.on_selection, p.get("center").and_then(Value::as_array)) { + (Some(c), _) => c, + (None, Some(c)) if c.len() == 2 => (c[0].as_f64().unwrap_or(cw / 2.0), c[1].as_f64().unwrap_or(ch / 2.0)), _ => (cw / 2.0, ch / 2.0), }; // `scale` is the caller's: bound the resampled size before allocating it (a frame's image @@ -281,6 +282,7 @@ impl PlaceSteps { bounds, smart, frame: input.frame.as_ref().map(|(id, _)| *id), + deselect: input.on_selection.is_some(), }) } } diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 1ae2be2003..f0a376be44 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -591,8 +591,15 @@ impl PhotocraftApp { /// Place a file's bytes as a smart object layer (File › Place; `linked`: Place Linked, to that /// path), for files that weren't read from a path the command can read. With background jobs /// on it starts a job (`{"job", "pending": true}`; see [`crate::jobs_ui::track_place`]). + /// + /// As in the reference application, Place Embedded centres the file on a selection, removing + /// it (#14102); otherwise a place centres it on the part of the canvas in view (#14103). pub(crate) fn place_bytes(&mut self, name: &str, bytes: Vec, linked: Option) -> Result { - self.place_bytes_with(name, bytes, linked, &serde_json::json!({})) + let mut params = serde_json::json!({"centerOnSelection": linked.is_none()}); + if let Some(centre) = visible_canvas_centre(self) { + params["center"] = serde_json::json!(centre); + } + self.place_bytes_with(name, bytes, linked, ¶ms) } /// [`PhotocraftApp::place_bytes`] with the command's `params` (a frame to fill): a job where @@ -637,6 +644,26 @@ impl PhotocraftApp { } } +/// Where a place lands when only part of the canvas is in view (#14103): the centre of the part +/// of the canvas the active view shows, in document pixels. `None` (the canvas centre) when the +/// whole canvas is in view, and in the cases not measured in the reference application: a +/// rotated view, or one that shows the canvas whole on one axis. +fn visible_canvas_centre(app: &PhotocraftApp) -> Option<[f64; 2]> { + let xf = crate::canvas::ViewXform::active(app)?; + if xf.rotation.abs() > 1e-6 { + return None; + } + let size = app.session.active()?.doc.size; + let (a, b) = (xf.to_doc(xf.rect.min), xf.to_doc(xf.rect.max)); + // The shown span of the canvas on one axis, if the view cuts it there. + let cut = |axis: usize, len: u32| { + let len = f64::from(len); + let (lo, hi) = (a[axis].min(b[axis]).max(0.0), a[axis].max(b[axis]).min(len)); + (lo < hi && (lo > 0.0 || hi < len)).then_some((lo + hi) / 2.0) + }; + Some([cut(0, size.width)?, cut(1, size.height)?]) +} + /// Order names like a file browser does: runs of digits by their value (`File_2` before /// `File_10`), everything else case-insensitively; names equal that way fall back to the exact /// text so the order is total. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0318581079..945066e41f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1139,3 +1139,6 @@ mod red_eye_context_menu_tests; #[cfg(test)] mod clone_stamp_indexed_bar_tests; + +#[cfg(test)] +mod place_visible_centre_tests; diff --git a/crates/ui-egui/src/place_visible_centre_tests.rs b/crates/ui-egui/src/place_visible_centre_tests.rs new file mode 100644 index 0000000000..f3f1c77c98 --- /dev/null +++ b/crates/ui-egui/src/place_visible_centre_tests.rs @@ -0,0 +1,101 @@ +//! File › Place Embedded / Place Linked centre the placed file on the part of the canvas in view +//! (#14103), and Place Embedded on a selection, which wins over the view (#14102). Measured in the +//! reference application on a 400 × 300 document: at 500 % with the view centred on 147.5,82 a +//! 100 × 60 file lands at 97.5,52 to 197.5,112, and a 1000 × 800 file is still fitted to the +//! canvas (375 × 300) but centred there, -40,-68 to 335,232. + +use crate::file_dialog::{self, FileDialogAnswer}; +use crate::{PhotocraftApp, Services, menus}; +use serde_json::json; + +/// A 400 × 300 document in an 800 × 600 canvas without rulers, its view at `zoom` (physical +/// pixels per document pixel) centred on `center`; the file dialog answers with a gray `w` × `h` +/// PNG on disk named `name` (a path, so Place Linked can link to it). +fn placing_app(zoom: f32, center: [f32; 2], name: &str, (w, h): (u32, u32)) -> PhotocraftApp { + let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, vec![128; (w * h * 3) as usize]).unwrap(); + let bytes = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("photocraft-place-visible-centre-{}-{unique}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(name); + std::fs::write(&path, bytes).unwrap(); + let answer = FileDialogAnswer::Paths(vec![path.to_string_lossy().into_owned()]); + let services = Services { file_dialog: Some(file_dialog::fake(vec![Some(answer)]).0), ..Default::default() }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.run("file.new", json!({"width": 400, "height": 300, "depth": 8})).unwrap(); + app.ui.extras.rulers = false; + app.last_canvas_rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + let v = &mut app.ui.views[0]; + (v.zoom, v.center, v.rotation, v.fit_pending) = (zoom, center, 0.0, false); + app +} + +/// Runs `command` from the menu (the dialog answers at once); the placed layer's box. +fn place(app: &mut PhotocraftApp, command: &str) -> [i32; 4] { + let ctx = egui::Context::default(); + menus::invoke(app, &ctx, command, json!({})).unwrap(); + app.poll_file_dialog(&ctx, None); + let st = app.session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert!(matches!(layer.content, photocraft_doc::LayerContent::Smart(_)), "{command} placed the file"); + let b = photocraft_engine::transform_cmds::transform_bounds(&st.doc, layer); + [b.x0, b.y0, b.x1, b.y1] +} + +/// The measured view: 500 %, centred on 147.5,82 (160 × 120 document pixels in sight). +const ZOOMED: (f32, [f32; 2]) = (5.0, [147.5, 82.0]); + +/// The whole canvas in view: centred on the canvas, as before (100 × 60 at 150,120). +#[test] +fn with_the_whole_canvas_in_view_a_place_centres_on_the_canvas() { + for command in ["file.placeEmbedded", "file.placeLinked"] { + let mut app = placing_app(1.0, [200.0, 150.0], "src.png", (100, 60)); + assert_eq!(place(&mut app, command), [150, 120, 250, 180], "{command}"); + } +} + +/// Part of the canvas in view: the box is centred there. The measured box is 97.5,52 to +/// 197.5,112; a placed image starts on a whole pixel, so it is 98 to 198 across (half a pixel +/// right, as the canvas centring of an odd-sized file already is) and exactly 52 to 112 down. +#[test] +fn with_part_of_the_canvas_in_view_a_place_centres_on_that_part() { + for command in ["file.placeEmbedded", "file.placeLinked"] { + let mut app = placing_app(ZOOMED.0, ZOOMED.1, "src.png", (100, 60)); + let [x0, y0, x1, y1] = place(&mut app, command); + assert_eq!((x1 - x0, y1 - y0), (100, 60), "{command}: the size is unchanged"); + assert_eq!((y0, y1), (52, 112), "{command}"); + assert!((f64::from(x0 + x1) / 2.0 - 147.5).abs() <= 0.5, "{command}: centred on 147.5 across: {x0}..{x1}"); + } +} + +/// Resize Image During Place still fits a larger file to the canvas; only the centre moves, and +/// the box may reach past the canvas edge. +#[test] +fn a_fitted_place_keeps_its_size_and_moves_its_centre() { + let mut app = placing_app(ZOOMED.0, ZOOMED.1, "big.png", (1000, 800)); + assert_eq!(place(&mut app, "file.placeEmbedded"), [-40, -68, 335, 232]); +} + +/// A selection wins over the view (#14102): Place Embedded centres on it and removes it. +#[test] +fn a_selection_wins_over_the_view() { + let mut app = placing_app(ZOOMED.0, ZOOMED.1, "src.png", (100, 60)); + app.run("select.rect", json!({"x": 300, "y": 200, "width": 80, "height": 80})).unwrap(); + assert_eq!(place(&mut app, "file.placeEmbedded"), [290, 210, 390, 270]); + assert!(app.session.active().unwrap().doc.selection.is_none(), "the place removes the selection"); +} + +/// The views not measured keep the canvas centre: one showing the whole canvas on one axis, and +/// a rotated one. +#[test] +fn a_view_cut_on_one_axis_or_rotated_keeps_the_canvas_centre() { + // 160 document pixels across, the whole 300 down (at 1.5 the 600-point height shows 400). + let mut app = placing_app(5.0, [147.5, 150.0], "src.png", (100, 60)); + app.ui.views[0].zoom = 1.5; + app.last_canvas_rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(240.0, 600.0)); + assert_eq!(place(&mut app, "file.placeEmbedded"), [150, 120, 250, 180], "cut across only"); + + let mut app = placing_app(ZOOMED.0, ZOOMED.1, "src.png", (100, 60)); + app.ui.views[0].rotation = 15.0; + assert_eq!(place(&mut app, "file.placeEmbedded"), [150, 120, 250, 180], "rotated"); +} From 800c3b6ddf95b9d17c0a9fd7aeb98d72eaccce62 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:05:28 +0100 Subject: [PATCH 10/25] Place: keep a frame's own centre when the view shows part of the canvas --- crates/ui-egui/src/file_open.rs | 9 +++++++-- crates/ui-egui/src/place_visible_centre_tests.rs | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index f0a376be44..74c58473d4 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -647,13 +647,18 @@ impl PhotocraftApp { /// Where a place lands when only part of the canvas is in view (#14103): the centre of the part /// of the canvas the active view shows, in document pixels. `None` (the canvas centre) when the /// whole canvas is in view, and in the cases not measured in the reference application: a -/// rotated view, or one that shows the canvas whole on one axis. +/// rotated view, or one that shows the canvas whole on one axis. `None` too when the place fills +/// the active layer's frame, whose `center` is in the frame's own space. fn visible_canvas_centre(app: &PhotocraftApp) -> Option<[f64; 2]> { let xf = crate::canvas::ViewXform::active(app)?; if xf.rotation.abs() > 1e-6 { return None; } - let size = app.session.active()?.doc.size; + let st = app.session.active()?; + if st.active_layer.is_some_and(|id| photocraft_engine::frame_cmds::frame_of(&st.doc, id).is_some()) { + return None; + } + let size = st.doc.size; let (a, b) = (xf.to_doc(xf.rect.min), xf.to_doc(xf.rect.max)); // The shown span of the canvas on one axis, if the view cuts it there. let cut = |axis: usize, len: u32| { diff --git a/crates/ui-egui/src/place_visible_centre_tests.rs b/crates/ui-egui/src/place_visible_centre_tests.rs index f3f1c77c98..5dc50796a3 100644 --- a/crates/ui-egui/src/place_visible_centre_tests.rs +++ b/crates/ui-egui/src/place_visible_centre_tests.rs @@ -99,3 +99,19 @@ fn a_view_cut_on_one_axis_or_rotated_keeps_the_canvas_centre() { app.ui.views[0].rotation = 15.0; assert_eq!(place(&mut app, "file.placeEmbedded"), [150, 120, 250, 180], "rotated"); } + +/// Into a selected frame the image fills the frame wherever the view is: the view's centre is +/// not passed, since a frame place's `center` is in the frame's own space. +#[test] +fn a_place_into_a_frame_ignores_the_view() { + let mut app = placing_app(ZOOMED.0, ZOOMED.1, "src.png", (100, 100)); + let frame = app.run("layer.new.frame", json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap()["layer"].as_u64().unwrap(); + menus::invoke(&mut app, &egui::Context::default(), "file.placeEmbedded", json!({})).unwrap(); + app.poll_file_dialog(&egui::Context::default(), None); + let doc = &app.session.active().unwrap().doc; + let image = &doc.layer(photocraft_doc::LayerId(frame)).unwrap().children().unwrap()[0]; + let photocraft_doc::LayerContent::Smart(so) = &image.content else { panic!("the frame holds the placed image") }; + let [a, _, _, d, e, f] = so.transform.m; + let placed = [e, f, e + 100.0 * a, f + 100.0 * d].map(|v| (v * 1000.0).round() / 1000.0); + assert_eq!(placed, [10.0, 10.0, 90.0, 90.0], "the image fills the frame"); +} From ceeac4c6c0fe8d6ba4e88fd740eb78cd95474c25 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:46:30 +0100 Subject: [PATCH 11/25] Canvas Size: Gray extension colour, 128,128,128 (#14543) image.canvasSize knew foreground, white, black, transparent and #rrggbb for extensionColor; "gray" fell through to the background colour, and a recorded Canvas Size step whose extension colour type is Gray ("Gry ") imported as unsupported, while a "gray" step could not be written back. "gray" is now the reference application's 128,128,128, the params doc lists it, and the EXTENSION table maps "Gry " to "gray" both ways, so recorded steps import, play back and export as Gray. Unknown values keep falling back to the background colour. --- crates/engine/src/cmd/atn_cmds/tables.rs | 2 +- crates/engine/src/cmd/image_cmds.rs | 7 +- .../cmd/image_cmds/canvas_size_gray_tests.rs | 110 ++++++++++++++++++ 3 files changed, 117 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/image_cmds/canvas_size_gray_tests.rs diff --git a/crates/engine/src/cmd/atn_cmds/tables.rs b/crates/engine/src/cmd/atn_cmds/tables.rs index 0a6a07abee..83fbad1bc2 100644 --- a/crates/engine/src/cmd/atn_cmds/tables.rs +++ b/crates/engine/src/cmd/atn_cmds/tables.rs @@ -126,7 +126,7 @@ pub(super) const OFFSET_FILL: &[(&str, &str)] = &[("Wrp ", "wrap"), ("Rpt ", "re pub(super) const TRIM: &[(&str, &str)] = &[("Trns", "transparent"), ("topLeftPixelColor", "topLeft"), ("bottomRightPixelColor", "bottomRight")]; pub(super) const EXTENSION: &[(&str, &str)] = - &[("Bckg", "background"), ("FrgC", "foreground"), ("Frgd", "foreground"), ("Wht ", "white"), ("Blck", "black"), ("Trns", "transparent")]; + &[("Bckg", "background"), ("FrgC", "foreground"), ("Frgd", "foreground"), ("Wht ", "white"), ("Blck", "black"), ("Gry ", "gray"), ("Trns", "transparent")]; pub(super) const FILL_CONTENTS: &[(&str, &str)] = &[ ("FrgC", "foreground"), diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index 571f4754ac..2f08f46b42 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -683,6 +683,8 @@ fn extension_color(s: &Session, p: &Value) -> [f32; 4] { "foreground" => s.tools.foreground, "white" => [1.0; 4], "black" => [0.0, 0.0, 0.0, 1.0], + // The reference application's Gray: 128,128,128 (#14543). + "gray" => [128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0], "transparent" => [0.0; 4], hex if hex.starts_with('#') => { let h = hex.trim_start_matches('#'); @@ -1250,7 +1252,7 @@ pub fn specs() -> Vec { "image.canvasSize", "Canvas Size…", ["Image"], - r##"{"width":number,"height":number,"units":"px|percent"="px" (percent uses each current side; absolute sizes only),"relative":bool=false,"anchor":"topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight"="center","extensionColor":"background|foreground|white|black|transparent|#rrggbb"="background"}"##, + r##"{"width":number,"height":number,"units":"px|percent"="px" (percent uses each current side; absolute sizes only),"relative":bool=false,"anchor":"topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight"="center","extensionColor":"background|foreground|white|black|gray|transparent|#rrggbb"="background"}"##, has_doc, canvas_size ), @@ -1325,3 +1327,6 @@ mod image_size_drops_selection_tests; #[cfg(test)] mod canvas_size_noop_history_tests; + +#[cfg(test)] +mod canvas_size_gray_tests; diff --git a/crates/engine/src/cmd/image_cmds/canvas_size_gray_tests.rs b/crates/engine/src/cmd/image_cmds/canvas_size_gray_tests.rs new file mode 100644 index 0000000000..c905127267 --- /dev/null +++ b/crates/engine/src/cmd/image_cmds/canvas_size_gray_tests.rs @@ -0,0 +1,110 @@ +//! #14543: Canvas Size takes Gray as its extension colour, the reference application's 128,128,128, +//! from the command and from recorded `.atn` steps (`canvasExtensionColorType` `Gry `), and a +//! `gray` step is written back as Gray. + +use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; +use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; +use serde_json::{Value, json}; + +use crate::Session; +use crate::actions_cmds::{Action, ActionStep}; + +/// A 400 x 300 document at `depth` with a white Background and an empty layer "Top" above it. +fn doc(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Top"})).unwrap(); + s +} + +/// The 8-bit RGB the document shows at pixel (x, y), as the Eyedropper reads it. +fn read(s: &mut Session, x: i32, y: i32) -> [i64; 3] { + let v = s.execute("document.sampleColor", json!({"x": f64::from(x) + 0.5, "y": f64::from(y) + 0.5})).unwrap(); + let c = |i: usize| (v[i].as_f64().unwrap() * 255.0).round() as i64; + [c(0), c(1), c(2)] +} + +/// The alpha of the layer "Top" at pixel (x, y). +fn top_alpha(s: &Session, x: i32, y: i32) -> f32 { + let doc = &s.active().unwrap().doc; + let top = doc.layers.iter().find(|l| l.name == "Top").unwrap(); + top.surface().unwrap().rgba(x, y)[3] +} + +const GROW: fn(&str) -> Value = |color| json!({"width": 500, "height": 400, "anchor": "topLeft", "extensionColor": color}); + +#[test] +fn gray_extends_the_background_with_128_gray_at_every_depth() { + for depth in [8, 16, 32] { + let mut s = doc(depth); + s.execute("image.canvasSize", GROW("gray")).unwrap(); + assert_eq!(read(&mut s, 450, 350), [128, 128, 128], "depth {depth}: the new area"); + assert_eq!(read(&mut s, 10, 10), [255, 255, 255], "depth {depth}: the old Background keeps its pixels"); + assert_eq!(top_alpha(&s, 450, 350), 0.0, "depth {depth}: only the Background is filled"); + } +} + +#[test] +fn an_unknown_extension_colour_still_takes_the_background_colour() { + let mut s = doc(8); + s.execute("image.canvasSize", GROW("grey-ish")).unwrap(); + assert_eq!(read(&mut s, 450, 350), [255, 255, 255]); +} + +#[test] +fn the_params_doc_lists_gray() { + let spec = crate::cmd::command_specs().iter().find(|c| c.id == "image.canvasSize").unwrap(); + assert!(spec.params.contains("|gray|"), "{}", spec.params); +} + +/// A recorded Canvas Size step: +100 / +100 px, relative, from the top left, extension colour type `ty`. +fn recorded_step(ty: &str) -> Vec { + let px = |v: f64| D::UnitFloat { unit: *b"#Pxl", value: v }; + let enm = |t: &str, v: &str| D::Enumerated { type_id: Id::new(t), value: Id::new(v) }; + let descriptor = Descriptor::new("null") + .with("Wdth", px(100.0)) + .with("Hght", px(100.0)) + .with("Rltv", D::Boolean(true)) + .with("Hrzn", enm("HrzL", "Left")) + .with("Vrtc", enm("VrtL", "Top ")) + .with("canvasExtensionColorType", enm("canvasExtensionColorType", ty)); + atn::write(&AtnFile { + name: UnicodeString::new_nul("Canvas"), + actions: vec![AtnAction { + name: UnicodeString::new_nul("Step"), + items: vec![AtnItem { event: AtnEvent::Code(*b"CnvS"), dictionary: b"CnvS".to_vec(), descriptor: Some(descriptor), ..Default::default() }], + ..Default::default() + }], + ..Default::default() + }) + .unwrap() +} + +#[test] +fn a_recorded_gray_step_imports_as_gray_and_plays_back_128_gray() { + let bytes = recorded_step("Gry "); + let imported = crate::atn_cmds::import(&bytes).unwrap(); + assert!(imported.unsupported.is_empty(), "the Gray step is supported: {:?}", imported.unsupported); + assert_eq!(imported.actions[0].steps[0].params["extensionColor"], json!("gray")); + let mut s = doc(8); + let loaded = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&bytes)})).unwrap(); + assert_eq!(loaded["unsupported"], json!([])); + let played = s.execute("actions.play", json!({"action": loaded["actions"][0]})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + assert_eq!(read(&mut s, 450, 350), [128, 128, 128]); +} + +#[test] +fn a_gray_step_is_written_back_as_gray() { + let action = Action::new("Step", vec![ActionStep::new("image.canvasSize", GROW("gray"))]); + let (bytes, skipped) = crate::atn_cmds::export("Canvas", &[&action], &[], false).unwrap(); + assert!(skipped.is_empty(), "{} skipped", skipped.len()); + let file = atn::parse(&bytes).unwrap(); + let d = file.actions[0].items[0].descriptor.as_ref().unwrap(); + assert!( + matches!(d.get("canvasExtensionColorType"), Some(D::Enumerated { value, .. }) if *value == Id::new("Gry ")), + "{:?}", + d.get("canvasExtensionColorType") + ); + assert!(d.get("canvasExtensionColor").is_none(), "not a custom colour"); +} From dd1c3ef7882ce8f65edffb792e6b270d4a92d68a Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 23 Nov 2026 08:11:38 +0100 Subject: [PATCH 12/25] Align Edges tests: PhotocraftApp::new gives a Box --- .../ui-egui/src/tools/vector_ui/rectangle_align_edges_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tools/vector_ui/rectangle_align_edges_tests.rs b/crates/ui-egui/src/tools/vector_ui/rectangle_align_edges_tests.rs index a51e379a08..8d1b6eba79 100644 --- a/crates/ui-egui/src/tools/vector_ui/rectangle_align_edges_tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/rectangle_align_edges_tests.rs @@ -20,7 +20,7 @@ const GEAR: &str = "Set additional shape and path options"; /// A 200 × 100 document with the Rectangle tool and its options set by `set`. The pixel-grid snap /// of vector tools is off, so only Align Edges rounds. -fn app(set: impl FnOnce(&mut ToolOptions)) -> PhotocraftApp { +fn app(set: impl FnOnce(&mut ToolOptions)) -> Box { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); app.run("prefs.set", json!({"path": "tools.snapVectorToolsAndTransformsToPixelGrid", "value": false})).unwrap(); From 000a06cf028b8b0bdc1f5ac8684310ab01eadfb2 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 23 Nov 2026 08:31:26 +0100 Subject: [PATCH 13/25] Rectangle Align Edges tests: give finish_drag the drag's exact box --- .../vector_ui/rectangle_align_edges_tests.rs | 88 ++++++------------- 1 file changed, 25 insertions(+), 63 deletions(-) diff --git a/crates/ui-egui/src/tools/vector_ui/rectangle_align_edges_tests.rs b/crates/ui-egui/src/tools/vector_ui/rectangle_align_edges_tests.rs index 8d1b6eba79..2fc11ae702 100644 --- a/crates/ui-egui/src/tools/vector_ui/rectangle_align_edges_tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/rectangle_align_edges_tests.rs @@ -2,42 +2,36 @@ //! gear. On (the default) a drag's box snaps to whole pixels; off a rectangle keeps the drag's //! fractional coordinates. It is greyed outside Shape mode, where the box still snaps. +use craft::draw::geometry::ShapeGeometry; use craft::draw::ui::VectorMode; use craft::draw::ui::shape_drag::ShapeKind; -use egui::Modifiers; +use craft::keymap::Mods; use egui::accesskit::Toggled; use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use super::test_input::harness; use crate::PhotocraftApp; -use crate::canvas::{ToolEvent, tool_event}; use crate::state::{Tool, ToolOptions}; const START: [f64; 2] = [10.3, 10.6]; const END: [f64; 2] = [40.7, 30.2]; const GEAR: &str = "Set additional shape and path options"; -/// A 200 × 100 document with the Rectangle tool and its options set by `set`. The pixel-grid snap -/// of vector tools is off, so only Align Edges rounds. +/// A 200 × 100 document with the Rectangle tool and its options set by `set`. fn app(set: impl FnOnce(&mut ToolOptions)) -> Box { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); - app.run("prefs.set", json!({"path": "tools.snapVectorToolsAndTransformsToPixelGrid", "value": false})).unwrap(); - app.sync_views(); - app.ui.views[0].zoom = 16.0; app.ui.tool = Tool::Rectangle; set(&mut app.ui.tool_options); app } -/// A canvas drag from `from` to `to`, pressed without modifiers and moved and released with `mods` -/// (keys pressed after the drag starts). -fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { - tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, Modifiers::NONE); - tool_event(app, ToolEvent::Move { x: (from[0] + to[0]) / 2.0, y: (from[1] + to[1]) / 2.0, pressure: 1.0 }, mods); - tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods); - tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods); +/// A Rectangle drag the framework tool committed as the box from `from` to `to` with corner radius +/// `radius`: the exact fractions go to `finish_drag` as the tool hands them over. +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], radius: f64) { + let rect = craft::behavior::kurbo::Rect::new(from[0], from[1], to[0], to[1]); + super::shapes::finish_drag(app, ShapeKind::Rectangle, &ShapeGeometry::Rect { rect, radii: [radius; 4] }, Mods::default()); } fn layer_count(app: &PhotocraftApp) -> usize { @@ -58,63 +52,20 @@ fn drawn_layer(app: &mut PhotocraftApp) -> ([f64; 4], String, [f64; 4]) { (live, info["live"]["kind"].as_str().unwrap_or_default().to_owned(), [x0, y0, x1, y1]) } -/// The live box `[x, y, w, h]` a Rectangle drag from `START` to `END` with `mods` draws under the -/// options `set` gives. -fn drag_box(set: impl FnOnce(&mut ToolOptions), mods: Modifiers) -> [f64; 4] { - let mut app = app(set); - let layers = layer_count(&app); - drag(&mut app, START, END, mods); - assert_eq!(layer_count(&app), layers + 1, "one new shape layer"); - drawn_layer(&mut app).0 -} - fn assert_close(got: [f64; 4], want: [f64; 4]) { for (g, w) in got.iter().zip(want) { assert!((g - w).abs() < 1e-9, "{got:?} vs {want:?}"); } } -#[test] -fn the_box_snaps_with_align_edges_and_keeps_fractions_without() { - assert!(ToolOptions::default().align_edges, "on by default"); - assert_eq!(drag_box(|_| {}, Modifiers::NONE), [10.0, 11.0, 30.0, 20.0]); - let off = |o: &mut ToolOptions| o.align_edges = false; - assert_close(drag_box(off, Modifiers::NONE), [10.3, 10.6, 30.4, 19.6]); - // Shift squares on the drag's shorter side and Alt draws from the centre, both before the box - // snaps or not. - assert_close(drag_box(off, Modifiers::SHIFT), [10.3, 10.6, 19.6, 19.6]); - assert_close(drag_box(off, Modifiers::ALT), [-20.1, -9.0, 60.8, 39.2]); - assert_eq!(drag_box(|_| {}, Modifiers::SHIFT), [10.0, 11.0, 20.0, 20.0]); - assert_eq!(drag_box(|_| {}, Modifiers::ALT), [-20.0, -9.0, 61.0, 39.0]); -} - -#[test] -fn a_rounded_rectangle_and_the_gears_fixed_size_follow_the_checkbox_too() { - let mut app = app(|o| { - o.corner_radius = 4.0; - o.align_edges = false; - }); - drag(&mut app, START, END, Modifiers::NONE); - let (live, kind, _) = drawn_layer(&mut app); - assert_eq!(kind, "roundedRect"); - assert_close(live, [10.3, 10.6, 30.4, 19.6]); - // Fixed Size puts W × H at the release point. - let fixed = |align: bool| { - move |o: &mut ToolOptions| { - o.align_edges = align; - o.rect_constraint = "fixedSize".into(); - (o.rect_fixed_width, o.rect_fixed_height) = (20.0, 10.0); - } - }; - assert_close(drag_box(fixed(false), Modifiers::NONE), [40.7, 30.2, 20.0, 10.0]); - assert_eq!(drag_box(fixed(true), Modifiers::NONE), [41.0, 30.0, 20.0, 10.0]); -} - #[test] fn the_drawn_shape_layer_follows_the_checkbox() { + assert!(ToolOptions::default().align_edges, "on by default"); for (align, live, bounds) in [(true, [10.0, 11.0, 30.0, 20.0], [10.0, 11.0, 40.0, 31.0]), (false, [10.3, 10.6, 30.4, 19.6], [10.3, 10.6, 40.7, 30.2])] { let mut app = app(|o| o.align_edges = align); - drag(&mut app, START, END, Modifiers::NONE); + let layers = layer_count(&app); + drag(&mut app, START, END, 0.0); + assert_eq!(layer_count(&app), layers + 1, "one new shape layer"); let (got_live, kind, got_bounds) = drawn_layer(&mut app); assert_eq!(kind, "rect"); assert_close(got_live, live); @@ -122,6 +73,17 @@ fn the_drawn_shape_layer_follows_the_checkbox() { } } +#[test] +fn a_rounded_rectangle_follows_the_checkbox_too() { + for (align, want) in [(true, [10.0, 11.0, 30.0, 20.0]), (false, [10.3, 10.6, 30.4, 19.6])] { + let mut app = app(|o| o.align_edges = align); + drag(&mut app, START, END, 4.0); + let (live, kind, _) = drawn_layer(&mut app); + assert_eq!(kind, "roundedRect"); + assert_close(live, want); + } +} + #[test] fn a_greyed_checkbox_keeps_snapping_in_path_and_pixels_mode() { let mut app = app(|o| o.align_edges = false); @@ -130,7 +92,7 @@ fn a_greyed_checkbox_keeps_snapping_in_path_and_pixels_mode() { assert!(super::shapes::snaps_to_pixels(&app, ShapeKind::Rectangle), "{mode:?}"); } app.ui.tool_options.shape_mode = VectorMode::Path; - drag(&mut app, START, END, Modifiers::NONE); + drag(&mut app, START, END, 0.0); let (x0, y0, x1, y1) = app.session.active().unwrap().doc.work_path.as_ref().unwrap().control_bounds().unwrap(); assert_close([x0, y0, x1, y1], [10.0, 11.0, 40.0, 31.0]); app.ui.tool_options.shape_mode = VectorMode::Shape; @@ -142,7 +104,7 @@ fn a_sub_pixel_drag_still_draws_nothing() { let mut app = app(|o| o.align_edges = false); for end in [[10.9, 40.0], [40.0, 10.5]] { let layers = layer_count(&app); - drag(&mut app, [10.0, 10.0], end, Modifiers::NONE); + drag(&mut app, [10.0, 10.0], end, 0.0); assert_eq!(layer_count(&app), layers, "{end:?}"); } } From a3774329f9c879bb96221a20b9095a61d39e0f67 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 23 Nov 2026 08:31:56 +0100 Subject: [PATCH 14/25] Shape options bar: the tools' own extras in their own function (clippy cognitive complexity) --- crates/ui-egui/src/tools/shape_options.rs | 42 +++++++++++++---------- 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/tools/shape_options.rs b/crates/ui-egui/src/tools/shape_options.rs index d9f928c212..fb407c264d 100644 --- a/crates/ui-egui/src/tools/shape_options.rs +++ b/crates/ui-egui/src/tools/shape_options.rs @@ -158,6 +158,29 @@ fn tool_settings(o: &crate::state::ToolOptions, live: Option<&photocraft_doc::Li settings } +/// What the bar shows after the framework's cells for one tool: the Triangle's Align Edges and the +/// Polygon's own corner radius. +fn tool_extras(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) { + if tool == Tool::Triangle { + Divider::vertical().show(ui); + // Only a shape layer has pixel edges to align: greyed in Path mode (#13370). + let shape_mode = app.ui.tool_options.shape_mode == VectorMode::Shape; + let on = Checkbox::new(Bind::given(app.ui.tool_options.align_edges)).label(tl!("Align Edges").to_owned()).enabled(shape_mode).show(ui); + if let Some(next) = on.value().copied() { + app.ui.tool_options.align_edges = next; + } + } + if tool == Tool::Polygon { + // The tool's own corner radius for the next polygon, after Sides (#13302); the active shape is not touched. + // A value typed past the Rectangle Radius's range takes the closest one and says so. + Divider::vertical().show(ui); + let out = crate::option_cells::number(tl!("Radius"), &mut app.ui.tool_options.polygon_corner_radius, RADIUS_RANGE).unit("px").show(ui); + if let Some(alert) = out.out_of_range { + crate::option_cells::range_alert(app, ui, &alert); + } + } +} + /// The title of the alert for a number typed outside its range. fn range_title(kind: ShapeKind) -> String { match kind { @@ -226,24 +249,7 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool .chips(|which, chip, chip_ui| decorate_chip(chip, which, &mut library, chip_ui)) .show(ui); let (fill_gradient, stroke_gradient) = (library.gradient(ShapePaint::Fill), library.gradient(ShapePaint::Stroke)); - if tool == Tool::Triangle { - Divider::vertical().show(ui); - // Only a shape layer has pixel edges to align: greyed in Path mode (#13370). - let shape_mode = app.ui.tool_options.shape_mode == VectorMode::Shape; - let on = Checkbox::new(Bind::given(app.ui.tool_options.align_edges)).label(tl!("Align Edges").to_owned()).enabled(shape_mode).show(ui); - if let Some(next) = on.value().copied() { - app.ui.tool_options.align_edges = next; - } - } - if tool == Tool::Polygon { - // The tool's own corner radius for the next polygon, after Sides (#13302); the active shape is not touched. - // A value typed past the Rectangle Radius's range takes the closest one and says so. - Divider::vertical().show(ui); - let out = crate::option_cells::number(tl!("Radius"), &mut app.ui.tool_options.polygon_corner_radius, RADIUS_RANGE).unit("px").show(ui); - if let Some(alert) = out.out_of_range { - crate::option_cells::range_alert(app, ui, &alert); - } - } + tool_extras(app, ui, tool); let mut recent: Option<[f32; 3]> = None; let mut remembered: Vec = Vec::new(); From f5175404cf972e2ffc4b37c23044973b0304c469 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 23 Nov 2026 08:45:51 +0100 Subject: [PATCH 15/25] Rectangle Align Edges tests: read a rounded rectangle's radii from its live shape --- .../tools/vector_ui/rectangle_align_edges_tests.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/tools/vector_ui/rectangle_align_edges_tests.rs b/crates/ui-egui/src/tools/vector_ui/rectangle_align_edges_tests.rs index 2fc11ae702..048c7bad41 100644 --- a/crates/ui-egui/src/tools/vector_ui/rectangle_align_edges_tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/rectangle_align_edges_tests.rs @@ -78,9 +78,17 @@ fn a_rounded_rectangle_follows_the_checkbox_too() { for (align, want) in [(true, [10.0, 11.0, 30.0, 20.0]), (false, [10.3, 10.6, 30.4, 19.6])] { let mut app = app(|o| o.align_edges = align); drag(&mut app, START, END, 4.0); - let (live, kind, _) = drawn_layer(&mut app); - assert_eq!(kind, "roundedRect"); + let (live, _, _) = drawn_layer(&mut app); assert_close(live, want); + let st = app.session.active().unwrap(); + let radii = match &st.doc.layer(st.active_layer.unwrap()).unwrap().content { + photocraft_doc::LayerContent::Shape(sh) => match sh.live { + Some(photocraft_doc::LiveShape::Rect { radii, .. }) => radii, + ref other => panic!("a live rectangle, got {other:?}"), + }, + _ => panic!("a shape layer"), + }; + assert_eq!(radii, [4.0; 4], "the corners stay rounded"); } } From 752c9831acfe50f70c9176f40047623b40201ade Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:15:38 +0100 Subject: [PATCH 16/25] Allow the pixel-aligned view centre in the place centring tests --- crates/ui-egui/src/place_visible_centre_tests.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/place_visible_centre_tests.rs b/crates/ui-egui/src/place_visible_centre_tests.rs index 134b5d4db6..95db781cc4 100644 --- a/crates/ui-egui/src/place_visible_centre_tests.rs +++ b/crates/ui-egui/src/place_visible_centre_tests.rs @@ -33,11 +33,9 @@ fn placing_app(zoom: f32, center: [f32; 2], rotation: f32, name: &str, (w, h): ( v.clear_pending(); testing::shown(&mut app); let shown = testing::view(&app).expect("the canvas shows the view"); - assert!( - (shown.center.x - f64::from(center[0])).abs() < 1e-3 && (shown.center.y - f64::from(center[1])).abs() < 1e-3, - "the canvas shows the view asked for: {:?}", - shown.center - ); + // The canvas aligns the view to device pixels, so its centre may move by up to half of one. + let near = |a: f64, b: f32| (a - f64::from(b)).abs() <= 0.5 / f64::from(zoom) + 1e-3; + assert!(near(shown.center.x, center[0]) && near(shown.center.y, center[1]), "the canvas shows the view asked for: {:?}", shown.center); (app, files, path) } From f805c79c2576175b111e913ad8c5c4a9af6dd5d7 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:29:29 +0100 Subject: [PATCH 17/25] Cut the canvas across by the shown view's width in the place centring test --- .../ui-egui/src/place_visible_centre_tests.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/place_visible_centre_tests.rs b/crates/ui-egui/src/place_visible_centre_tests.rs index 95db781cc4..2168d3d0f5 100644 --- a/crates/ui-egui/src/place_visible_centre_tests.rs +++ b/crates/ui-egui/src/place_visible_centre_tests.rs @@ -27,16 +27,21 @@ fn placing_app(zoom: f32, center: [f32; 2], rotation: f32, name: &str, (w, h): ( let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); app.run("file.new", json!({"width": 400, "height": 300, "depth": 8})).unwrap(); app.ui.extras.rulers = false; - testing::shown(&mut app); + show(&mut app, zoom, center, rotation); + (app, files, path) +} + +/// Shows the view at `zoom`, centred on `center` and turned by `rotation`, on the canvas. +fn show(app: &mut PhotocraftApp, zoom: f32, center: [f32; 2], rotation: f32) { + testing::shown(app); let v = &mut app.ui.views[0]; (v.zoom, v.center, v.rotation) = (zoom, center, rotation); v.clear_pending(); - testing::shown(&mut app); - let shown = testing::view(&app).expect("the canvas shows the view"); + testing::shown(app); + let shown = testing::view(app).expect("the canvas shows the view"); // The canvas aligns the view to device pixels, so its centre may move by up to half of one. let near = |a: f64, b: f32| (a - f64::from(b)).abs() <= 0.5 / f64::from(zoom) + 1e-3; assert!(near(shown.center.x, center[0]) && near(shown.center.y, center[1]), "the canvas shows the view asked for: {:?}", shown.center); - (app, files, path) } /// The part of the canvas the view shows: `[x0, y0, x1, y1]` in document pixels. @@ -107,8 +112,10 @@ fn a_selection_wins_over_the_view() { /// a rotated one. #[test] fn a_view_cut_on_one_axis_or_rotated_keeps_the_canvas_centre() { - // At 100 % centred right of the canvas: its left part is cut off, the whole 300 down shows. - let (mut app, files, path) = placing_app(1.0, [350.0, 150.0], 0.0, "src.png", (100, 60)); + // At 100 % moved right so the canvas's left 100 pixels are cut off; the whole 300 down shows. + let (mut app, files, path) = placing_app(1.0, [200.0, 150.0], 0.0, "src.png", (100, 60)); + let [x0, _, x1, _] = visible(&app); + show(&mut app, 1.0, [(100.0 + (x1 - x0) / 2.0) as f32, 150.0], 0.0); let [x0, y0, _, y1] = visible(&app); assert!(x0 > 0.0 && y0 <= 0.0 && y1 >= 300.0, "the view cuts the canvas across only: {x0},{y0} to {y1} down"); assert_eq!(place(&mut app, &files, &path, "file.placeEmbedded"), [150, 120, 250, 180], "cut across only"); From 3c5c41ac5fb3be25b941bd024aaabd42c9ec1028 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:43:23 +0100 Subject: [PATCH 18/25] Keep a multi-file Place Embedded out of the selected frame Each chosen file is queued with "frame": false, so with a Frame layer selected the files no longer fill it one over another; each gets its own layer, Free Transform box and history state. A single file still fills the frame. --- crates/ui-egui/src/file_open.rs | 5 +++- .../ui-egui/src/place_multiple_files_tests.rs | 24 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 21f0847c0e..f40b26ff54 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -600,13 +600,16 @@ impl PhotocraftApp { /// already read by the browser when the dialog answered, so refusing it would free nothing /// and only lose a file the user chose. Each is released as soon as it is placed, and while /// they wait they count against the limit for later drops. + /// + /// None of them fills a selected Frame layer (`"frame": false`), as a single file would: each + /// would replace the previous one's image there, without a box or a layer of its own. pub(crate) fn place_picked(&mut self, ctx: &egui::Context, doc: DocId, files: Vec) { for file in files { let place = match file { crate::file_dialog::PickedFile::Path(path) => DropPlace::Path(path), crate::file_dialog::PickedFile::Contents(name, bytes) => DropPlace::Bytes(name, bytes), }; - self.drop_places.push_back((doc, place)); + self.drop_places.push_back((doc, DropPlace::At { source: Box::new(place), frame: None })); } self.place_next_dropped(ctx); } diff --git a/crates/ui-egui/src/place_multiple_files_tests.rs b/crates/ui-egui/src/place_multiple_files_tests.rs index 5bcf1daf58..20be81e587 100644 --- a/crates/ui-egui/src/place_multiple_files_tests.rs +++ b/crates/ui-egui/src/place_multiple_files_tests.rs @@ -163,6 +163,30 @@ fn chosen_paths_are_read_in_turn_and_a_missing_one_is_reported() { assert!(app.drop_places.is_empty()); } +/// With a Frame layer selected, the chosen files don't fill it one over another: each is placed +/// as its own layer with its own box, and the frame stays empty. +#[test] +fn several_files_with_a_frame_selected_are_each_placed_as_their_own_layer() { + let ctx = egui::Context::default(); + let (mut app, _) = app_picking(three_contents()); + let frame = app.run("layer.new.frame", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap()["layer"].as_u64().unwrap(); + let frame = photocraft_doc::LayerId(frame); + assert_eq!(app.session.active().unwrap().active_layer, Some(frame), "the frame is selected"); + let steps = history_steps(&app); + place_embedded(&mut app, &ctx); + for (i, name) in ["first", "second", "third"].into_iter().enumerate() { + assert_eq!(active_name(&app), name); + place_box(&app); + crate::transform_tool::commit(&mut app); + assert_eq!(history_steps(&app), steps + i + 1); + app.place_next_dropped(&ctx); + } + assert!(app.ui.transform.is_none() && app.drop_places.is_empty()); + assert!(names(&app).ends_with(&["first".to_string(), "second".to_string(), "third".to_string()]), "{:?}", names(&app)); + let doc = &app.session.active().unwrap().doc; + assert!(doc.layer(frame).unwrap().children().is_none_or(<[_]>::is_empty), "nothing filled the frame"); +} + /// With Skip Transform when Placing on, all the chosen files are placed and committed at once, one /// history state each, without Free Transform. #[test] From 02a6bee23d4ede8360b077b8d6dee188617c883a Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:43:53 +0100 Subject: [PATCH 19/25] Show the Batch OK refusal in a Batch alert As the reference does (#13669), a missing source or destination folder now opens a one-button alert titled Batch with the message. The dialog stays open with its values and nothing runs; the refusal still answers a control-channel confirm. --- .../view_cmds/batch_ok_validation_tests.rs | 12 +++++++++++- crates/ui-egui/src/menus/view_cmds/dialogs.rs | 19 +++++++++++-------- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/menus/view_cmds/batch_ok_validation_tests.rs b/crates/ui-egui/src/menus/view_cmds/batch_ok_validation_tests.rs index 45f08e289f..27432203d9 100644 --- a/crates/ui-egui/src/menus/view_cmds/batch_ok_validation_tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/batch_ok_validation_tests.rs @@ -1,6 +1,7 @@ //! File › Automate › Batch: OK checks for a missing source folder, then a missing destination //! folder, as the reference does (#13669). The first that fails refuses OK with the reference's -//! message; the dialog stays open with every value, and nothing runs. The same holds for a +//! message in a one-button alert titled "Batch"; the dialog stays open with every value, and +//! nothing runs. The same holds for a //! confirm through the control channel. use craft::automation::actions::{Action, ActionStep}; @@ -48,6 +49,12 @@ fn fields(app: &PhotocraftApp, id: DialogId) -> Option { app.framework.dialogs.open_dialogs().into_iter().find(|open| open.id == id).and_then(|open| open.fields) } +/// The messages of the alerts the host has open (`HostedAlert`'s key is "alert"). +fn alerts(app: &PhotocraftApp) -> Vec { + let open = app.framework.dialogs.open_dialogs().into_iter().filter(|d| d.key.as_deref() == Some("alert")); + open.filter_map(|d| Some(d.fields.as_ref()?["message"].as_str()?.to_string())).collect() +} + /// A folder holding one 2 × 1 PNG, `in/a.png`, and the path of an output folder `out` beside it. fn image_folder() -> (tempfile::TempDir, String, String) { let dir = tempfile::tempdir().unwrap(); @@ -68,6 +75,7 @@ fn ok_without_a_source_folder_is_refused_and_keeps_the_dialog_open() { let before = fields(&app, id).expect("the dialog is open"); assert_eq!(crate::dialogs::confirm(&mut app, &ctx, id), Err(NO_SOURCE_FOLDER.to_string())); assert_eq!(NO_SOURCE_FOLDER, "You must choose a source folder."); + assert_eq!(alerts(&app), [NO_SOURCE_FOLDER], "the refusal shows in an alert"); assert_eq!(fields(&app, id), Some(before), "the dialog stays open with every value"); assert!(!dir.path().join("out").exists(), "nothing was written"); assert_eq!(app.session.documents().len(), 1, "nothing was opened"); @@ -82,6 +90,7 @@ fn ok_without_a_destination_folder_is_refused_and_writes_nothing() { let before = fields(&app, id).expect("the dialog is open"); assert_eq!(crate::dialogs::confirm(&mut app, &ctx, id), Err(NO_DESTINATION_FOLDER.to_string())); assert_eq!(NO_DESTINATION_FOLDER, "You must choose a destination folder."); + assert_eq!(alerts(&app), [NO_DESTINATION_FOLDER], "the refusal shows in an alert"); assert_eq!(fields(&app, id), Some(before)); let files: Vec<_> = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name()).collect(); assert_eq!(files, ["in"], "nothing was written"); @@ -132,6 +141,7 @@ fn ok_with_both_folders_runs_the_batch() { let (mut app, ctx, id) = batch(&input, &output); crate::dialogs::confirm(&mut app, &ctx, id).expect("OK is accepted"); assert!(fields(&app, id).is_none(), "OK closes the dialog"); + assert!(alerts(&app).is_empty(), "an accepted OK shows no alert"); assert!(dir.path().join("out/a.png").is_file(), "the batch wrote a.png"); }); } diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index ebc50fd26c..3bd98567ef 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -686,14 +686,17 @@ fn batch_missing_choice(fields: &DialogFields) -> Option<&'static str> { } /// The `ParamFamily::check` of the Batch dialog (#13669): OK, from the button or a confirm through the control channel, -/// is refused while a folder source or its destination names no folder. The dialog stays open with its values, shows -/// the reference's message, and nothing runs. -pub(crate) fn batch_check(_app: &mut PhotocraftApp, result: &ParamResult) -> Result<(), Label> { - match batch_missing_choice(&result.fields) { - Some(NO_SOURCE_FOLDER) => Err(Label::from(tl!("You must choose a source folder."))), - Some(_) => Err(Label::from(tl!("You must choose a destination folder."))), - None => Ok(()), - } +/// is refused while a folder source or its destination names no folder. As in the reference, a one-button alert +/// titled "Batch" shows the message; the dialog stays open with its values (the refusal also shows under its rows and +/// answers a control-channel confirm), and nothing runs. +pub(crate) fn batch_check(app: &mut PhotocraftApp, result: &ParamResult) -> Result<(), Label> { + let message = match batch_missing_choice(&result.fields) { + Some(NO_SOURCE_FOLDER) => tl!("You must choose a source folder."), + Some(_) => tl!("You must choose a destination folder."), + None => return Ok(()), + }; + crate::dialogs::alerts::show(app, craft::ui::dialog::Alert::new(tl!("Batch"), message)); + Err(Label::from(message)) } #[cfg(test)] From 9c6e55f7d79b2b54f02fb11b12f264d7fd24832d Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:48:26 +0100 Subject: [PATCH 20/25] Canvas Size: Gray is linear grey 128 in a 32-bit document 32-bit documents hold linear light, so the Gray extension colour there is grey 128 decoded as Image > Mode > 32 Bits/Channel decodes it (0.2159), not 128/255. --- crates/engine-core/src/cmd/image_cmds.rs | 14 +++++++-- .../cmd/image_cmds/canvas_size_gray_tests.rs | 29 +++++++++++++++++-- 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/crates/engine-core/src/cmd/image_cmds.rs b/crates/engine-core/src/cmd/image_cmds.rs index 5e4ac32eff..d042ed4f68 100644 --- a/crates/engine-core/src/cmd/image_cmds.rs +++ b/crates/engine-core/src/cmd/image_cmds.rs @@ -684,8 +684,18 @@ fn extension_color(s: &Session, p: &Value) -> [f32; 4] { "foreground" => s.tools.foreground, "white" => [1.0; 4], "black" => [0.0, 0.0, 0.0, 1.0], - // The reference application's Gray: 128,128,128 (#14543). - "gray" => [128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0], + // The reference application's Gray: 128,128,128 (#14543). A 32-bit document holds linear + // light, so there it is grey 128 decoded as `change_depth` decodes it (0.2159). + "gray" => { + let v = 128.0 / 255.0; + let v = match s.active().map(|d| (d.doc.mode, d.doc.depth)) { + Some((mode @ (ColorMode::Rgb | ColorMode::Grayscale), SampleType::F32)) => { + photocraft_compose::adjust::Transfer::for_document(mode, SampleType::U8).decode(v) + } + _ => v, + }; + [v, v, v, 1.0] + } "transparent" => [0.0; 4], hex if hex.starts_with('#') => { let h = hex.trim_start_matches('#'); diff --git a/crates/engine-core/src/cmd/image_cmds/canvas_size_gray_tests.rs b/crates/engine-core/src/cmd/image_cmds/canvas_size_gray_tests.rs index 6c471e48c8..90e565a10a 100644 --- a/crates/engine-core/src/cmd/image_cmds/canvas_size_gray_tests.rs +++ b/crates/engine-core/src/cmd/image_cmds/canvas_size_gray_tests.rs @@ -34,8 +34,8 @@ fn top_alpha(s: &Session, x: i32, y: i32) -> f32 { const GROW: fn(&str) -> Value = |color| json!({"width": 500, "height": 400, "anchor": "topLeft", "extensionColor": color}); #[test] -fn gray_extends_the_background_with_128_gray_at_every_depth() { - for depth in [8, 16, 32] { +fn gray_extends_the_background_with_128_gray_at_8_and_16_bits() { + for depth in [8, 16] { let mut s = doc(depth); s.execute("image.canvasSize", GROW("gray")).unwrap(); assert_eq!(read(&mut s, 450, 350), [128, 128, 128], "depth {depth}: the new area"); @@ -44,6 +44,31 @@ fn gray_extends_the_background_with_128_gray_at_every_depth() { } } +/// The Background's stored colour at pixel (x, y). +fn background_value(s: &Session, x: i32, y: i32) -> [f32; 4] { + s.active().unwrap().doc.background().unwrap().surface().unwrap().rgba(x, y) +} + +/// A 32-bit document holds linear light: its Gray is the value an 8-bit grey 128 becomes when the +/// document is converted to 32 bits (0.2159), not 128/255. +#[test] +fn gray_in_a_32_bit_document_is_linear_grey_128() { + let mut converted = crate::session(); + converted.execute("file.new", json!({"width": 4, "height": 4, "depth": 8, "background": "white"})).unwrap(); + converted.execute("edit.fill", json!({"color": "#808080"})).unwrap(); + converted.execute("image.mode.bits32", json!({})).unwrap(); + let want = background_value(&converted, 1, 1); + assert!((want[0] - 0.2159).abs() < 0.002, "converted grey 128: {want:?}"); + let mut s = doc(32); + s.execute("image.canvasSize", GROW("gray")).unwrap(); + let got = background_value(&s, 450, 350); + for i in 0..3 { + assert!((got[i] - want[i]).abs() < 1e-4, "channel {i}: {got:?} vs {want:?}"); + } + assert_eq!(got[3], 1.0); + assert_eq!(background_value(&s, 10, 10)[..3], [1.0, 1.0, 1.0], "the old Background keeps its pixels"); +} + #[test] fn an_unknown_extension_colour_still_takes_the_background_colour() { let mut s = doc(8); From 7557c44f48627f08a4966ba0b35c3aecfdfcd6e6 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:55:05 +0100 Subject: [PATCH 21/25] Expect the picked paths to wait outside the frame in the place test --- crates/ui-egui/src/place_multiple_files_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/place_multiple_files_tests.rs b/crates/ui-egui/src/place_multiple_files_tests.rs index 20be81e587..72d22aad1e 100644 --- a/crates/ui-egui/src/place_multiple_files_tests.rs +++ b/crates/ui-egui/src/place_multiple_files_tests.rs @@ -147,8 +147,8 @@ fn chosen_paths_are_read_in_turn_and_a_missing_one_is_reported() { // The dialog's order, not name order: b first. assert_eq!(names(&app), ["Background", "b"]); assert_eq!(place_box(&app), [10.0, 10.0, 30.0, 20.0]); - // Waiting files hold their paths, not their contents. - assert!(app.drop_places.iter().all(|(_, p)| matches!(p, DropPlace::Path(_)))); + // Waiting files hold their paths, not their contents, and won't fill a selected frame. + assert!(app.drop_places.iter().all(|(_, p)| matches!(p, DropPlace::At { source, frame: None } if matches!(**source, DropPlace::Path(_))))); crate::transform_tool::commit(&mut app); app.place_next_dropped(&ctx); assert_eq!(app.ui.notices.iter().filter(|n| n.tone == crate::notices::Tone::Bad && n.title.contains("gone.png")).count(), 1); From 657abde6766055adf8925b38001aa97cb8167836 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:58:44 +0100 Subject: [PATCH 22/25] Canvas Size: read the params doc from the installed registry in the test --- .../engine-core/src/cmd/image_cmds/canvas_size_gray_tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine-core/src/cmd/image_cmds/canvas_size_gray_tests.rs b/crates/engine-core/src/cmd/image_cmds/canvas_size_gray_tests.rs index 90e565a10a..225d159cfd 100644 --- a/crates/engine-core/src/cmd/image_cmds/canvas_size_gray_tests.rs +++ b/crates/engine-core/src/cmd/image_cmds/canvas_size_gray_tests.rs @@ -78,7 +78,9 @@ fn an_unknown_extension_colour_still_takes_the_background_colour() { #[test] fn the_params_doc_lists_gray() { - let spec = crate::cmd::command_specs().iter().find(|c| c.id == "image.canvasSize").unwrap(); + // The registry lists the commands once a session has installed them. + let _ = crate::session(); + let spec = crate::registry::find("image.canvasSize").unwrap(); assert!(spec.params.contains("|gray|"), "{}", spec.params); } From 53248aa8603079fdb370e6aff303d22c56682e66 Mon Sep 17 00:00:00 2001 From: FredApps Date: Mon, 23 Nov 2026 10:11:11 +0100 Subject: [PATCH 23/25] Use the installed session fixture for FOGRA39 tests --- .../src/cmd/color_cmds/convert_profile_fogra39_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine-core/src/cmd/color_cmds/convert_profile_fogra39_tests.rs b/crates/engine-core/src/cmd/color_cmds/convert_profile_fogra39_tests.rs index b1965e1c42..8526609945 100644 --- a/crates/engine-core/src/cmd/color_cmds/convert_profile_fogra39_tests.rs +++ b/crates/engine-core/src/cmd/color_cmds/convert_profile_fogra39_tests.rs @@ -15,7 +15,7 @@ const INTENTS: [(&str, bool); 5] = [("relative", true), ("relative", false), ("p /// The inks of an 8-bit sRGB document filled with `background`, converted to Coated FOGRA39. fn separate(background: &str, intent: &str, bpc: bool) -> [f32; 4] { - let mut s = Session::new(); + let mut s = crate::session(); s.execute("file.new", json!({"width": 8, "height": 8, "background": background})).unwrap(); s.execute("edit.assignProfile", json!({"profile": "srgb"})).unwrap(); s.execute("edit.convertToProfile", json!({"profile": "coated-fogra39", "intent": intent, "bpc": bpc, "dither": false})).unwrap(); From 446dd0e38b7f8a65443e32020b6a4485028282a5 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:32:52 +0100 Subject: [PATCH 24/25] Canvas Size: Gray keeps the background colour in an Indexed document Indexed documents were not measured (#14543), so they keep today's behaviour. --- crates/engine-core/src/cmd/image_cmds.rs | 4 ++++ .../src/cmd/image_cmds/canvas_size_gray_tests.rs | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/crates/engine-core/src/cmd/image_cmds.rs b/crates/engine-core/src/cmd/image_cmds.rs index d042ed4f68..3e3eabaa11 100644 --- a/crates/engine-core/src/cmd/image_cmds.rs +++ b/crates/engine-core/src/cmd/image_cmds.rs @@ -687,6 +687,10 @@ fn extension_color(s: &Session, p: &Value) -> [f32; 4] { // The reference application's Gray: 128,128,128 (#14543). A 32-bit document holds linear // light, so there it is grey 128 decoded as `change_depth` decodes it (0.2159). "gray" => { + // An Indexed document was not measured (#14543) and keeps today's background colour. + if s.active().is_some_and(|d| d.doc.mode == ColorMode::Indexed) { + return s.tools.background; + } let v = 128.0 / 255.0; let v = match s.active().map(|d| (d.doc.mode, d.doc.depth)) { Some((mode @ (ColorMode::Rgb | ColorMode::Grayscale), SampleType::F32)) => { diff --git a/crates/engine-core/src/cmd/image_cmds/canvas_size_gray_tests.rs b/crates/engine-core/src/cmd/image_cmds/canvas_size_gray_tests.rs index 225d159cfd..1edddf41c0 100644 --- a/crates/engine-core/src/cmd/image_cmds/canvas_size_gray_tests.rs +++ b/crates/engine-core/src/cmd/image_cmds/canvas_size_gray_tests.rs @@ -69,6 +69,22 @@ fn gray_in_a_32_bit_document_is_linear_grey_128() { assert_eq!(background_value(&s, 10, 10)[..3], [1.0, 1.0, 1.0], "the old Background keeps its pixels"); } +/// An Indexed Color document was not measured and keeps today's behaviour: Gray takes the +/// background colour there, as an unknown value does. +#[test] +fn gray_in_an_indexed_document_keeps_the_background_colour() { + let grown = |color: &str| { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); + s.execute("image.mode.indexedColor", json!({})).unwrap(); + s.tools.background = [0.0, 0.0, 1.0, 1.0]; + s.execute("image.canvasSize", GROW(color)).unwrap(); + background_value(&s, 450, 350) + }; + assert_eq!(grown("gray"), grown("background"), "Gray fills with the background colour"); + assert_ne!(grown("gray"), grown("white"), "the test tells the two apart"); +} + #[test] fn an_unknown_extension_colour_still_takes_the_background_colour() { let mut s = doc(8); From f0943fb57f55dc48f02aeac25a0ac60d4120baaa Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 14:44:36 -0500 Subject: [PATCH 25/25] revert: restore scheduled release.yml dry-run on main (#16563) --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4bb487874e..51a46be5a3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -34,7 +34,7 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: - nightly: ${{ github.event_name == 'schedule' }} + dry-run: ${{ github.event_name == 'schedule' }} app-name: photocraft app-title: PhotoCraft craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795