From 93bc39bcca128cad2beba3116241539670e8afc9 Mon Sep 17 00:00:00 2001 From: SBaksa <18648812+SBaksa@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:55:42 +1100 Subject: [PATCH 01/34] Layer Style: separator lines in effect Blend Mode lists (#14941) The effect pages drew their Blend Mode list with the plain dropdown, so the 27 modes had no family lines. New widgets::dropdown_grouped draws the same lines as the Layers panel (starts_blend_group) without wheel stepping. Tests in effect_blend_separators_tests.rs. Fixes #14941 --- crates/ui-egui/src/dialogs/layer_style.rs | 7 +- .../effect_blend_separators_tests.rs | 111 ++++++++++++++++++ crates/ui-egui/src/widgets.rs | 4 +- crates/ui-egui/src/widgets/dropdown.rs | 15 +++ 4 files changed, 134 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/layer_style/effect_blend_separators_tests.rs diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index 65772e1573..7b5e0f0eaf 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -25,6 +25,8 @@ use crate::{PhotocraftApp, widgets}; mod bevel_modes_tests; pub(crate) mod color_picker; mod contour; +#[cfg(test)] +mod effect_blend_separators_tests; mod gradient_field; #[cfg(test)] mod gradient_method_tests; @@ -1676,7 +1678,10 @@ fn page(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, widgets::row_label(ui, label, LABEL_W); let mut cur = disp.get(key).and_then(Value::as_str).unwrap_or("Normal").to_string(); let opts: Vec<(String, &str)> = photocraft_color::BlendMode::LAYER_MODES.iter().map(|m| (m.label().to_string(), m.label())).collect(); - if widgets::dropdown(ui, &format!("fx-blend-{selected}-{key}"), tl!(&label), &mut cur, &opts, 150.0) { + // The mode families are parted by lines, as on the Layers panel (#14941). + let starts_group = + |l: &String| photocraft_color::BlendMode::LAYER_MODES.iter().any(|m| m.label() == l && crate::panels::starts_blend_group(*m)); + if widgets::dropdown_grouped(ui, &format!("fx-blend-{selected}-{key}"), tl!(&label), &mut cur, &opts, 150.0, starts_group) { let value = json!(cur); disp[key] = value.clone(); set_param(f, selected, key, value); diff --git a/crates/ui-egui/src/dialogs/layer_style/effect_blend_separators_tests.rs b/crates/ui-egui/src/dialogs/layer_style/effect_blend_separators_tests.rs new file mode 100644 index 0000000000..14fd5d64dd --- /dev/null +++ b/crates/ui-egui/src/dialogs/layer_style/effect_blend_separators_tests.rs @@ -0,0 +1,111 @@ +//! #14941: the Blend Mode lists of the Layer Style effect pages part the 27 modes into the +//! reference's six families with five lines, as the Layers panel does; a pick stores the mode's +//! name as before. +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; + +use super::*; + +type State = (PhotocraftApp, Map); + +/// The reference's list, a family per row. +const GROUPS: [&[&str]; 6] = [ + &["Normal", "Dissolve"], + &["Darken", "Multiply", "Color Burn", "Linear Burn", "Darker Color"], + &["Lighten", "Screen", "Color Dodge", "Linear Dodge (Add)", "Lighter Color"], + &["Overlay", "Soft Light", "Hard Light", "Vivid Light", "Linear Light", "Pin Light", "Hard Mix"], + &["Difference", "Exclusion", "Subtract", "Divide"], + &["Hue", "Saturation", "Color", "Luminosity"], +]; + +/// The Layer Style dialog on `kind`'s page, for a layer that has that effect. +fn page(kind: &str) -> Harness<'static, State> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run(&format!("layer.layerStyle.{kind}"), json!({})).unwrap(); + let fields = { + let state = app.session.active().unwrap(); + initial_fields(state.doc.layer(state.active_layer.unwrap()).unwrap(), Some(kind), 120.0) + }; + let mut h = Harness::builder().with_size(vec2(1000.0, 2000.0)).build_ui_state( + |ui, state: &mut State| { + if ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("semibold".into()))) { + body(&mut state.0, ui, &mut state.1); + } + }, + (app, fields), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(3); + h +} + +/// Opens the dropdown named `name` and returns its rows' rects, in the reference's order. +fn open_list(h: &mut Harness<'static, State>, name: &str) -> Vec { + h.get_by_role_and_label(Role::ComboBox, name).click(); + h.run_steps(4); + let list = h.ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id))); + let Some(list) = list else { panic!("the {name} list is open") }; + // Other widgets share some labels (the effect list's "Color Overlay" row, the field's own + // text), so each row is the nearest match below the previous one in the same column. + let mut rows: Vec = Vec::new(); + for l in GROUPS.concat() { + let mut found = h.get_all_by_label(l).map(|n| n.rect()).filter(|r| list.contains_rect(*r)); + let row = match rows.last() { + None => found.next_back(), + Some(prev) => found.filter(|r| (r.left() - prev.left()).abs() < 2.0 && r.top() >= prev.bottom() - 0.5).min_by(|a, b| a.top().total_cmp(&b.top())), + }; + rows.push(row.unwrap_or_else(|| panic!("{l} is in the {name} list"))); + } + rows +} + +/// Asserts the rows are parted exactly where the reference's families start. +fn assert_grouped(rows: &[egui::Rect], what: &str) { + let gaps: Vec = rows.windows(2).map(|w| w[1].top() - w[0].bottom()).collect(); + let plain = gaps.iter().copied().fold(f32::INFINITY, f32::min); + let starts: Vec = GROUPS.iter().scan(0, |at, g| Some(std::mem::replace(at, *at + g.len()))).skip(1).collect(); + for (i, gap) in gaps.iter().enumerate() { + // gaps[i] lies above row i + 1. + let parted = *gap > plain + 0.5; + assert_eq!(parted, starts.contains(&(i + 1)), "{what}: line above {}: {gaps:?}", GROUPS.concat()[i + 1]); + } + assert_eq!(gaps.iter().filter(|g| **g > plain + 0.5).count(), 5, "{what}: five lines"); +} + +#[test] +fn the_inner_shadow_blend_mode_list_shows_the_five_lines() { + let mut h = page("innerShadow"); + let rows = open_list(&mut h, "Blend Mode"); + assert_grouped(&rows, "Inner Shadow"); +} + +#[test] +fn every_effect_page_with_a_blend_mode_shows_the_same_lines() { + for kind in ["dropShadow", "innerGlow", "outerGlow", "satin", "colorOverlay", "gradientOverlay", "patternOverlay", "stroke"] { + let mut h = page(kind); + let rows = open_list(&mut h, "Blend Mode"); + assert_grouped(&rows, kind); + } + for name in ["Highlight Mode", "Shadow Mode"] { + let mut h = page("bevelEmboss"); + let rows = open_list(&mut h, name); + assert_grouped(&rows, name); + } +} + +#[test] +fn a_pick_stores_the_mode_name_as_before() { + let mut h = page("innerShadow"); + open_list(&mut h, "Blend Mode"); + h.get_all_by_label("Linear Dodge (Add)").last().unwrap().click(); + h.run_steps(3); + assert_eq!(h.state().1["effects"][0]["params"]["blend"], "Linear Dodge (Add)"); + open_list(&mut h, "Blend Mode"); + h.get_all_by_label("Hue").last().unwrap().click(); + h.run_steps(3); + assert_eq!(h.state().1["effects"][0]["params"]["blend"], "Hue"); +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 5e22305dce..1bfbb46787 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -46,8 +46,8 @@ pub use color::{ #[cfg(test)] use color::{checker_tile_id, checker_uv}; pub use dropdown::{ - combo_list, dropdown, dropdown_enabled, dropdown_hovered, dropdown_literal, dropdown_wheel_grouped, dropdown_wheel_grouped_enabled, dropdown_wheel_hovered, - dropdown_with_tooltips, menu_scroll, swatch_popup, + combo_list, dropdown, dropdown_enabled, dropdown_grouped, dropdown_hovered, dropdown_literal, dropdown_wheel_grouped, dropdown_wheel_grouped_enabled, + dropdown_wheel_hovered, dropdown_with_tooltips, menu_scroll, swatch_popup, }; pub(crate) use fields::compact_wrapping_value_field; #[cfg(test)] diff --git a/crates/ui-egui/src/widgets/dropdown.rs b/crates/ui-egui/src/widgets/dropdown.rs index 8f8a6c5ba4..361194c767 100644 --- a/crates/ui-egui/src/widgets/dropdown.rs +++ b/crates/ui-egui/src/widgets/dropdown.rs @@ -42,6 +42,21 @@ pub fn dropdown_hovered(ui: &mut Ui, id: &str, name: &str, (!chosen.is_empty(), hovered) } +/// [`dropdown`] whose open list draws a line above each option (but the first) that `starts_group`, +/// as [`dropdown_wheel_grouped`] does, without the wheel stepping its value: the Layer Style effect +/// pages' Blend Mode lists (#14941). +pub fn dropdown_grouped( + ui: &mut Ui, + id: &str, + name: &str, + current: &mut T, + options: &[(T, &str)], + width: f32, + starts_group: impl Fn(&T) -> bool, +) -> bool { + !dropdown_with(ui, id, name, current, options, width, false, true, &starts_group, &|_| true).0.is_empty() +} + /// [`dropdown_hovered`] whose value also steps with the wheel over its button or open list: down /// picks the next option, up the previous one, one per notch (Shift too), stopping at the ends /// (Photoshop's Layers panel blend modes, #1747), for a wheel gesture that starts over either From bdd5ae31c86b745ea38b85c4e2cc8278e8d99082 Mon Sep 17 00:00:00 2001 From: ancientastronauttheorist Date: Wed, 25 Nov 2026 22:28:37 -0600 Subject: [PATCH 02/34] Home screen: the rail's Home row and the Window menu's documents lead back to the document With a document open and the Home screen up, the rail's Home row fires `window.home`, which no menu item makes available, so the shortcut path refused it ("not available in the current state"). A `home` command source now runs it, as the options bar's Home button does. Choosing an open document in the Window menu now also leaves Home. With no document open both still do nothing. Fixes #16802. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Gr84Vw42Y1h9tPLDK7SFRm --- crates/ui-egui/src/app/framework.rs | 12 +++ .../ui-egui/src/home_screen_way_back_tests.rs | 76 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus/invoke.rs | 2 + 4 files changed, 92 insertions(+) create mode 100644 crates/ui-egui/src/home_screen_way_back_tests.rs diff --git a/crates/ui-egui/src/app/framework.rs b/crates/ui-egui/src/app/framework.rs index bfa6c349ae..92edb0349c 100644 --- a/crates/ui-egui/src/app/framework.rs +++ b/crates/ui-egui/src/app/framework.rs @@ -623,6 +623,8 @@ pub(crate) const COMMAND_SOURCES: &[CommandSource] = &[ CommandSource { name: "artboard", states: crate::artboard_tool::source_states, run: crate::artboard_tool::run_fired }, // Space+F: the pasteboard colour keys of the held Hand. CommandSource { name: "canvasColor", states: no_states, run: crate::canvas_tool_menu::run_canvas_color }, + // The Home screen rail's Home row fires `window.home` (#16802), which no menu item makes available. + CommandSource { name: "home", states: no_states, run: run_home }, // The options bar's engine-command buttons: their commands run through `shortcuts::handle`. CommandSource { name: "selection", states: crate::panels::options_bar::selection::source_states, run: |_, _, _| false }, ]; @@ -687,6 +689,16 @@ fn command_states(app: &PhotocraftApp, held: &mut HeldStates) { #[cfg(test)] mod catalog_tests; +/// `window.home`, fired by the Home screen rail's Home row: leaves Home for the open documents, as the options bar's +/// Home button does, and does nothing with no document open ([`crate::canvas::start_screen::toggle_home`]). +fn run_home(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { + if command.id != "window.home" { + return false; + } + crate::canvas::start_screen::toggle_home(app); + true +} + /// Selects the tool a tool command names. fn run_tool(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { let Some(command) = crate::panels::tool_commands::ToolCommand::from_ref(command) else { diff --git a/crates/ui-egui/src/home_screen_way_back_tests.rs b/crates/ui-egui/src/home_screen_way_back_tests.rs new file mode 100644 index 0000000000..d388522634 --- /dev/null +++ b/crates/ui-egui/src/home_screen_way_back_tests.rs @@ -0,0 +1,76 @@ +//! #16802: with a document open, the Home screen has a way back to it: the rail's Home row, and the document's entry +//! at the bottom of the Window menu. With no document open, Home has nothing behind it and both leave it up. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::app::framework::BuildApp as _; + +type H = Harness<'static, Box>; + +/// The app showing its document area (the Home screen while Home is up), with `documents` documents open. The app's +/// own frame runs around it, so a command the Home screen fires is run as in the app. +fn harness(documents: usize) -> H { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for _ in 0..documents { + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + } + let mut h = Harness::builder() + .with_size(egui::vec2(1100.0, 700.0)) + .with_max_steps(64) + .build_app(|ui, app: &mut PhotocraftApp| crate::canvas::document_area(app, ui), app); + h.run_steps(4); + h +} + +/// Whether the Home screen is up. +fn home(h: &mut H) -> bool { + h.state_mut().home_screen_up() +} + +/// The options bar's Home button: shows Home over the open documents. +fn show_home(h: &mut H) { + crate::canvas::start_screen::toggle_home(h.state_mut()); + h.run_steps(4); +} + +/// A click on the Home row of the Home screen's rail. +fn click_home_row(h: &mut H) { + h.get_by_label("Home").click(); + h.run_steps(4); +} + +#[test] +fn the_rails_home_row_returns_to_the_open_document() { + let mut h = harness(1); + show_home(&mut h); + assert!(home(&mut h), "Home is up over the document"); + let doc = h.state().session.active().map(|d| d.doc.id); + click_home_row(&mut h); + assert!(!home(&mut h), "the Home row leaves Home: {}", h.state().ui.status); + assert_eq!(h.state().session.active().map(|d| d.doc.id), doc, "back on the same document, unchanged"); + assert_eq!(h.state().session.documents().len(), 1); +} + +#[test] +fn choosing_an_open_document_in_the_window_menu_leaves_home() { + let mut h = harness(2); + let first = h.state().session.documents()[0].doc.id; + show_home(&mut h); + assert!(home(&mut h)); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "window.document.0", json!({})).unwrap(); + h.run_steps(4); + assert!(!home(&mut h), "choosing the document leaves Home"); + assert_eq!(h.state().session.active().map(|d| d.doc.id), Some(first), "and shows that document"); +} + +#[test] +fn with_no_document_open_home_stays_up() { + let mut h = harness(0); + assert!(home(&mut h), "Home is all there is with no document"); + click_home_row(&mut h); + assert!(home(&mut h), "the Home row has nothing to return to"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 20d0f0d1ca..dbb16fff02 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1096,6 +1096,8 @@ mod selection_move_step_tests; #[cfg(test)] mod view_guides_submenu_tests; +#[cfg(test)] +mod home_screen_way_back_tests; #[cfg(test)] mod lasso_click_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 2d01f0df91..2516e4cc80 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -862,6 +862,8 @@ fn invoke_window_command(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, id.strip_prefix(DOCUMENT_ITEM).ok_or("no such document")?.parse::().ok().filter(|index| *index < count).ok_or("no such document")?; app.session.set_active(next); app.jobs.focus = None; + // Choosing a document shows it, so it leaves the Home screen opened over the documents (#16802). + app.ui.chrome.home = None; Ok(json!({"document": next})) })()), _ => None, From eabb2e2781d22f7c06c657ec7e09075d682b6aea Mon Sep 17 00:00:00 2001 From: ancientastronauttheorist Date: Wed, 25 Nov 2026 22:44:16 -0600 Subject: [PATCH 03/34] Home screen: window.home is available with a document open; Next and Previous Document leave Home MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Self-review fixes (#16802): - `window.home` is enabled whenever a document is open (`menus::state::is_enabled`), instead of a command source routing the rail's click around the menu gate. Availability and the click now agree, and with no document open the click is still reported as unavailable, as before. - Window › Next Document and Previous Document (Ctrl+Tab) leave Home as choosing a document does. - The Window menu tests fire their rows through the gate a menu click passes, and the Home row test checks that nothing opened or closed rather than a count. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Gr84Vw42Y1h9tPLDK7SFRm --- crates/ui-egui/src/app/framework.rs | 12 ------- .../ui-egui/src/home_screen_way_back_tests.rs | 31 ++++++++++++++----- crates/ui-egui/src/menus/invoke.rs | 2 ++ crates/ui-egui/src/menus/state.rs | 3 ++ 4 files changed, 29 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/app/framework.rs b/crates/ui-egui/src/app/framework.rs index 92edb0349c..bfa6c349ae 100644 --- a/crates/ui-egui/src/app/framework.rs +++ b/crates/ui-egui/src/app/framework.rs @@ -623,8 +623,6 @@ pub(crate) const COMMAND_SOURCES: &[CommandSource] = &[ CommandSource { name: "artboard", states: crate::artboard_tool::source_states, run: crate::artboard_tool::run_fired }, // Space+F: the pasteboard colour keys of the held Hand. CommandSource { name: "canvasColor", states: no_states, run: crate::canvas_tool_menu::run_canvas_color }, - // The Home screen rail's Home row fires `window.home` (#16802), which no menu item makes available. - CommandSource { name: "home", states: no_states, run: run_home }, // The options bar's engine-command buttons: their commands run through `shortcuts::handle`. CommandSource { name: "selection", states: crate::panels::options_bar::selection::source_states, run: |_, _, _| false }, ]; @@ -689,16 +687,6 @@ fn command_states(app: &PhotocraftApp, held: &mut HeldStates) { #[cfg(test)] mod catalog_tests; -/// `window.home`, fired by the Home screen rail's Home row: leaves Home for the open documents, as the options bar's -/// Home button does, and does nothing with no document open ([`crate::canvas::start_screen::toggle_home`]). -fn run_home(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { - if command.id != "window.home" { - return false; - } - crate::canvas::start_screen::toggle_home(app); - true -} - /// Selects the tool a tool command names. fn run_tool(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool { let Some(command) = crate::panels::tool_commands::ToolCommand::from_ref(command) else { diff --git a/crates/ui-egui/src/home_screen_way_back_tests.rs b/crates/ui-egui/src/home_screen_way_back_tests.rs index d388522634..14c295b2b4 100644 --- a/crates/ui-egui/src/home_screen_way_back_tests.rs +++ b/crates/ui-egui/src/home_screen_way_back_tests.rs @@ -47,11 +47,18 @@ fn the_rails_home_row_returns_to_the_open_document() { let mut h = harness(1); show_home(&mut h); assert!(home(&mut h), "Home is up over the document"); - let doc = h.state().session.active().map(|d| d.doc.id); + let (doc, open) = (h.state().session.active().map(|d| d.doc.id), h.state().session.documents().len()); click_home_row(&mut h); assert!(!home(&mut h), "the Home row leaves Home: {}", h.state().ui.status); - assert_eq!(h.state().session.active().map(|d| d.doc.id), doc, "back on the same document, unchanged"); - assert_eq!(h.state().session.documents().len(), 1); + assert_eq!(h.state().session.active().map(|d| d.doc.id), doc, "back on the same document"); + assert_eq!(h.state().session.documents().len(), open, "nothing opened or closed"); +} + +/// Chooses Window menu item `id`, through the gate a menu click passes (its enabled state included). +fn choose(h: &mut H, id: &str) { + let ctx = h.ctx.clone(); + crate::shortcut_dispatch::dispatch(h.state_mut(), &ctx, id); + h.run_steps(4); } #[test] @@ -60,13 +67,23 @@ fn choosing_an_open_document_in_the_window_menu_leaves_home() { let first = h.state().session.documents()[0].doc.id; show_home(&mut h); assert!(home(&mut h)); - let ctx = h.ctx.clone(); - crate::menus::invoke(h.state_mut(), &ctx, "window.document.0", json!({})).unwrap(); - h.run_steps(4); - assert!(!home(&mut h), "choosing the document leaves Home"); + choose(&mut h, "window.document.0"); + assert!(!home(&mut h), "choosing the document leaves Home: {}", h.state().ui.status); assert_eq!(h.state().session.active().map(|d| d.doc.id), Some(first), "and shows that document"); } +#[test] +fn next_and_previous_document_leave_home() { + for id in ["window.nextDocument", "window.previousDocument"] { + let mut h = harness(2); + let before = h.state().session.active().map(|d| d.doc.id); + show_home(&mut h); + choose(&mut h, id); + assert!(!home(&mut h), "{id} leaves Home: {}", h.state().ui.status); + assert_ne!(h.state().session.active().map(|d| d.doc.id), before, "{id} shows the other document"); + } +} + #[test] fn with_no_document_open_home_stays_up() { let mut h = harness(0); diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 2516e4cc80..5433e179fd 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -854,6 +854,8 @@ fn invoke_window_command(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, app.run("document.activate", json!({"document": next}))?; } app.jobs.focus = None; + // Next and Previous Document show the document they choose, so they leave Home too (#16802). + app.ui.chrome.home = None; Ok(json!({"document": next})) })()), _ if id.starts_with(DOCUMENT_ITEM) => Some((|| { diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index bf3cd0c253..9bc271b779 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -84,6 +84,9 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool { "window.togglePanels" => true, // With one document open the key stays quiet, as in Photoshop, rather than reporting why. "window.nextDocument" | "window.previousDocument" => app.session.active().is_some(), + // Home over the open documents, or back to them (the Home rail's Home row fires it, #16802). With no document + // open there is nothing behind Home. + "window.home" => !app.session.documents().is_empty(), i if panel_alias(i).is_some() || workspace_id(i).is_some() => true, i if proof_preset(i).is_some() => app.session.active().is_some(), // "Custom…" is the full Proof Setup dialog. From 80fa3a977c2c22ed979f12b3677a97027f720a56 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 13:20:30 -0800 Subject: [PATCH 04/34] Disable Transform Again until a transform exists --- crates/engine-core/src/cmd/edit_cmds.rs | 23 +++++++++++++--- .../cmd/transform_again_needs_prior_tests.rs | 27 +++++++++++++++++++ 2 files changed, 47 insertions(+), 3 deletions(-) create mode 100644 crates/engine-core/src/cmd/transform_again_needs_prior_tests.rs diff --git a/crates/engine-core/src/cmd/edit_cmds.rs b/crates/engine-core/src/cmd/edit_cmds.rs index 5849b59bfd..16f088d2fc 100644 --- a/crates/engine-core/src/cmd/edit_cmds.rs +++ b/crates/engine-core/src/cmd/edit_cmds.rs @@ -920,11 +920,24 @@ fn transform_again_copy(s: &mut Session) -> Result { } } +fn last_transform(s: &Session) -> Result<&Value> { + s.journal + .iter() + .rev() + .find(|(id, _)| id == "edit.transform") + .map(|(_, params)| params) + .ok_or_else(|| EngineError::Other("there is no transform to repeat".into())) +} + +fn can_transform_again(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + last_transform(s).map(|_| ()).map_err(|error| error.to_string()) +} + /// The `edit.transform` params that repeat the last transform on the layers `ids` (their frame /// together is the box it starts from). fn transform_again_params(s: &Session, ids: &[LayerId]) -> Result { - let (_, last) = - s.journal.iter().rev().find(|(id, _)| id == "edit.transform").cloned().ok_or(EngineError::Other("there is no transform to repeat".into()))?; + let last = last_transform(s)?; let (rect, quad) = (last.get("rect").cloned(), last.get("quad").cloned()); let mut p = json!({"interpolation": last.get("interpolation").cloned().unwrap_or(json!("bicubic"))}); match (rect, quad, last.get("matrix").cloned()) { @@ -1258,7 +1271,7 @@ pub fn specs() -> Vec { spec!("image.autoContrast", "Auto Contrast", &["Image"], Some("Cmd+Alt+Shift+L"), "{}", has_pixels, |s, _| auto_adjust(s, "contrast")), spec!("image.autoColor", "Auto Color", &["Image"], Some("Cmd+Shift+B"), "{}", has_pixels, |s, _| auto_adjust(s, "color")), spec!("edit.toggleLastState", "Toggle Last State", &["Edit"], Some("Cmd+Alt+Z"), "{}", has_doc, |s, _| toggle_last_state(s)), - spec!("edit.transform.again", "Again", &["Edit", "Transform"], Some("Cmd+Shift+T"), "{}", has_doc, |s, _| transform_again(s)), + spec!("edit.transform.again", "Again", &["Edit", "Transform"], Some("Cmd+Shift+T"), "{}", can_transform_again, |s, _| transform_again(s)), spec!( "edit.transform.againCopy", "Transform Again on a Copy", @@ -1314,3 +1327,7 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "transform_again_needs_prior_tests.rs"] +mod transform_again_needs_prior_tests; diff --git a/crates/engine-core/src/cmd/transform_again_needs_prior_tests.rs b/crates/engine-core/src/cmd/transform_again_needs_prior_tests.rs new file mode 100644 index 0000000000..52a9b164ab --- /dev/null +++ b/crates/engine-core/src/cmd/transform_again_needs_prior_tests.rs @@ -0,0 +1,27 @@ +use serde_json::json; + +#[test] +fn transform_again_is_enabled_only_after_a_transform_in_the_session() { + let command = "edit.transform.again"; + let mut session = crate::session(); + assert!(!session.is_enabled(command)); + + session.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + session.execute("layer.new.layer", json!({"name": "Pixels"})).unwrap(); + session.execute("select.rect", json!({"x": 10, "y": 10, "width": 25, "height": 20})).unwrap(); + session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + session.execute("select.deselect", json!({})).unwrap(); + assert!(!session.is_enabled(command), "ordinary document edits do not enable Again"); + let history = session.active().unwrap().history.past_len(); + let error = session.execute(command, json!({})).unwrap_err().to_string(); + assert!(error.contains("there is no transform to repeat"), "{error}"); + assert_eq!(session.active().unwrap().history.past_len(), history); + + session.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 10, 0]})).unwrap(); + assert!(session.is_enabled(command)); + session.execute(command, json!({})).unwrap(); + assert_eq!(session.active().unwrap().history.past_len(), history + 2); + + session.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + assert!(session.is_enabled(command), "the previous transform remains session-wide when opening another document"); +} From 1bc36fcd9091d698a2c7f82bd8a45e2815e0367a Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 13:34:19 -0800 Subject: [PATCH 05/34] Replace the selected text when pasting Lorem Ipsum --- crates/engine-core/src/cmd/type_extra_cmds.rs | 18 ++++++-- .../cmd/type_paste_lorem_selection_tests.rs | 44 +++++++++++++++++++ crates/ui-egui/src/menus/view_cmds/dialogs.rs | 5 ++- 3 files changed, 61 insertions(+), 6 deletions(-) create mode 100644 crates/engine-core/src/cmd/type_paste_lorem_selection_tests.rs diff --git a/crates/engine-core/src/cmd/type_extra_cmds.rs b/crates/engine-core/src/cmd/type_extra_cmds.rs index c3ce98effe..7a8696953e 100644 --- a/crates/engine-core/src/cmd/type_extra_cmds.rs +++ b/crates/engine-core/src/cmd/type_extra_cmds.rs @@ -800,10 +800,16 @@ fn paste_lorem(s: &mut Session, p: &Value) -> Result { // else the active layer when it is a type layer. let new = p.get("new").and_then(Value::as_bool) == Some(true); if !new && (explicit_layer(s, p)?.is_some() || has_text(s).is_ok()) { - let caret = with_text(s, p, "Paste Lorem Ipsum", |t, _| { + let range_end = p.get("end").and_then(Value::as_u64); + // The editor sends a range and its typing session's coalesce key. A new layer keeps its + // existing creation step; the first edit of an existing layer gets the type-edit label. + let label = if range_end.is_some() && p.get("coalesce").and_then(Value::as_str).is_some() { "Edit Type Layer" } else { "Paste Lorem Ipsum" }; + let caret = with_text(s, p, label, |t, _| { let at = p.get("at").and_then(Value::as_u64).map_or(t.text.len(), |c| byte_index(&t.text, c as usize)); - replace_text(t, at, at, LOREM_IPSUM); - Ok(char_index(&t.text, at + LOREM_IPSUM.len())) + let end = range_end.map_or(at, |c| byte_index(&t.text, usize::try_from(c).unwrap_or(usize::MAX))); + let start = at.min(end); + replace_text(t, start, at.max(end), LOREM_IPSUM); + Ok(char_index(&t.text, start + LOREM_IPSUM.len())) })?; return Ok(json!({"caret": caret})); } @@ -1116,7 +1122,7 @@ pub fn specs() -> Vec { "type.pasteLoremIpsum", "Paste Lorem Ipsum", &["Type"], - r##"{"layer":id?,"at":char? (default end),"new":bool=false (new paragraph text layer)}"##, + r##"{"layer":id?,"at":char? (default end),"end":char? (replace the range between at and end; omit to insert),"new":bool=false (new paragraph text layer)}"##, has_doc, paste_lorem ), @@ -1141,3 +1147,7 @@ mod tests; #[cfg(test)] #[path = "type_anti_alias_history_tests.rs"] mod anti_alias_history_tests; + +#[cfg(test)] +#[path = "type_paste_lorem_selection_tests.rs"] +mod type_paste_lorem_selection_tests; diff --git a/crates/engine-core/src/cmd/type_paste_lorem_selection_tests.rs b/crates/engine-core/src/cmd/type_paste_lorem_selection_tests.rs new file mode 100644 index 0000000000..ded602629d --- /dev/null +++ b/crates/engine-core/src/cmd/type_paste_lorem_selection_tests.rs @@ -0,0 +1,44 @@ +use serde_json::json; + +use super::LOREM_IPSUM; + +#[test] +fn paste_lorem_replaces_a_character_range_and_undo_restores_text() { + let mut session = crate::session(); + session.execute("file.new", json!({"width": 300, "height": 120})).unwrap(); + let layer = session.execute("type.create", json!({"x": 20, "y": 70, "text": "é猫Ω"})).unwrap()["layer"].clone(); + let before = session.active().unwrap().history.past_len(); + + // A reversed selection of one multi-byte character, as seen by the browser or desktop editor. + let result = session.execute("type.pasteLoremIpsum", json!({"layer": layer, "at": 2, "end": 1, "coalesce": "existing-type-edit"})).unwrap(); + assert_eq!(result["caret"], 1 + LOREM_IPSUM.chars().count()); + assert_eq!(session.execute("type.info", json!({"layer": layer})).unwrap()["text"], format!("é{LOREM_IPSUM}Ω")); + let history = &session.active().unwrap().history; + assert_eq!(history.past_len(), before + 1); + assert_eq!(history.undo_label(), Some("Edit Type Layer")); + assert!(session.undo()); + assert_eq!(session.execute("type.info", json!({"layer": layer})).unwrap()["text"], "é猫Ω"); + + session.execute("type.pasteLoremIpsum", json!({"layer": layer, "at": 1, "end": 1})).unwrap(); + assert_eq!(session.execute("type.info", json!({"layer": layer})).unwrap()["text"], format!("é{LOREM_IPSUM}猫Ω")); +} + +#[test] +fn paste_lorem_replaces_a_new_layers_placeholder_in_its_creation_step() { + let mut session = crate::session(); + session.execute("file.new", json!({"width": 300, "height": 120})).unwrap(); + let before = session.active().unwrap().history.past_len(); + let layer = + session.execute("type.create", json!({"x": 20, "y": 70, "text": "Lorem Ipsum", "coalesce": "new-type-layer"})).unwrap()["layer"].as_u64().unwrap(); + let result = session.execute("type.pasteLoremIpsum", json!({"layer": layer, "at": 0, "end": 11, "coalesce": "new-type-layer"})).unwrap(); + assert_eq!(result["caret"], LOREM_IPSUM.chars().count()); + assert_eq!(session.execute("type.info", json!({"layer": layer})).unwrap()["text"], LOREM_IPSUM); + + let state = session.active().unwrap(); + let id = photocraft_doc::LayerId(layer); + assert_eq!(state.doc.layer(id).unwrap().name, crate::type_cmds::layer_name(LOREM_IPSUM)); + assert_eq!(state.history.past_len(), before + 1); + assert_eq!(state.history.undo_label(), Some("New Type Layer")); + assert!(session.undo()); + assert!(session.active().unwrap().doc.layer(id).is_none()); +} diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 84d7cf6527..9f92b02ede 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -1055,9 +1055,10 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para return Some(r); } if id == "type.pasteLoremIpsum" && no_params(params) { - // While typing, paste at the caret. + // While typing, replace the selected characters, or insert at the caret. if let Some(te) = app.ui.text_edit.clone() { - let r = app.run(id, json!({"layer": te.layer, "at": te.caret, "coalesce": te.session})); + let [start, end] = crate::type_tool::selected_range(app).unwrap_or([te.caret; 2]); + let r = app.run(id, json!({"layer": te.layer, "at": start, "end": end, "coalesce": te.session})); if let (Ok(v), Some(te)) = (&r, app.ui.text_edit.as_mut()) && let Some(c) = v.get("caret").and_then(Value::as_u64) { From 677098198bf87550dd0f1de5f276bcabcdbf327c Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 13:39:00 -0800 Subject: [PATCH 06/34] Grey Paste Lorem Ipsum outside an active type edit --- crates/ui-egui/src/menus/state.rs | 5 ++ .../menus/type_paste_lorem_greyed_tests.rs | 56 +++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 crates/ui-egui/src/menus/type_paste_lorem_greyed_tests.rs diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 7053f2158c..9c8fac79a5 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -5,6 +5,10 @@ use photocraft_engine::color_cmds::ColorExt; use super::invoke::{panel_alias, proof_preset, workspace_id}; use super::{DOCUMENT_ITEM, PhotocraftApp, Value}; +#[cfg(test)] +#[path = "type_paste_lorem_greyed_tests.rs"] +mod type_paste_lorem_greyed_tests; + /// Whether View › Zoom Out has stopped at a document-specific minimum. pub(crate) fn zoom_out_at_minimum(app: &PhotocraftApp) -> bool { let Some(document) = app.session.active() else { return false }; @@ -114,6 +118,7 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool { "edit.paste" | "file.newFromClipboard" => app.session.is_enabled(id) || app.services.clipboard_get_image.is_some(), "edit.pasteSpecial.pasteInPlace" => app.session.is_enabled(id) || (app.services.clipboard_get_image.is_some() && app.session.active().is_some()), "select.selectAndMask" => app.session.is_enabled("select.refineEdge"), + "type.pasteLoremIpsum" => app.ui.text_edit.is_some(), "type.editText" => app .session .active() diff --git a/crates/ui-egui/src/menus/type_paste_lorem_greyed_tests.rs b/crates/ui-egui/src/menus/type_paste_lorem_greyed_tests.rs new file mode 100644 index 0000000000..92cfb400ac --- /dev/null +++ b/crates/ui-egui/src/menus/type_paste_lorem_greyed_tests.rs @@ -0,0 +1,56 @@ +use serde_json::json; + +use crate::PhotocraftApp; + +const PASTE: &str = "type.pasteLoremIpsum"; + +fn enabled(app: &PhotocraftApp) -> bool { + let rows = crate::menus::menu_rows(app); + let row = crate::menus::row(&rows, PASTE).expect("Paste Lorem Ipsum is in the menu"); + assert_eq!(row.path, ["Type"]); + row.enabled +} + +#[test] +fn paste_lorem_menu_requires_an_active_text_edit() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = app.ctx().clone(); + assert!(!enabled(&app), "no document"); + + app.run("file.new", json!({"width": 120, "height": 80, "background": "white"})).unwrap(); + app.sync_views(); + app.run("layer.new.layer", json!({"name": "Paint"})).unwrap(); + assert!(!enabled(&app), "pixel layer selected"); + app.run("select.deselectLayers", json!({})).unwrap(); + assert!(!enabled(&app), "no layer selected"); + + for params in [json!({"x": 4, "y": 24, "text": "Sample"}), json!({"box": [4, 8, 112, 64], "text": "Sample"})] { + let layer = app.run("type.create", params).unwrap()["layer"].as_u64().unwrap(); + assert!(!enabled(&app), "selecting a type layer does not start editing"); + crate::menus::invoke(&mut app, &ctx, "type.editText", json!({})).unwrap(); + let edit = app.ui.text_edit.as_mut().unwrap(); + edit.anchor = edit.caret; + assert!(enabled(&app), "enabled while editing"); + let result = crate::menus::invoke(&mut app, &ctx, PASTE, json!({})).unwrap(); + let info = app.run("type.info", json!({"layer": layer})).unwrap(); + let text = info["text"].as_str().unwrap(); + assert!(text.starts_with("Sample") && text.len() > "Sample".len()); + assert_eq!(result["caret"].as_u64().unwrap(), text.chars().count() as u64); + crate::type_tool::commit(&mut app); + assert!(!enabled(&app), "disabled after committing the edit"); + } +} + +#[test] +fn paste_lorem_engine_command_still_works_outside_the_editor() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 120, "height": 80, "background": "white"})).unwrap(); + let created = app.run(PASTE, json!({"new": true})).unwrap()["layer"].as_u64().unwrap(); + let info = app.run("type.info", json!({"layer": created})).unwrap(); + let original = info["text"].as_str().unwrap(); + let inserted = app.run(PASTE, json!({"layer": created, "at": 0})).unwrap(); + let updated = app.run("type.info", json!({"layer": created})).unwrap(); + assert_eq!(inserted["caret"].as_u64().unwrap(), original.chars().count() as u64); + assert_eq!(updated["text"].as_str().unwrap(), original.repeat(2)); + assert!(!enabled(&app)); +} From f8b049399940ccc0d0ebb1bda052c56802d71b12 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 13:47:16 -0800 Subject: [PATCH 07/34] Keep disabled Lorem Ipsum menu invocations inert --- crates/ui-egui/src/menus/invoke.rs | 1 + .../menus/type_paste_lorem_greyed_tests.rs | 19 +++++++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 7db099df4f..fe5ee120da 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -657,6 +657,7 @@ fn invoke_export_command(app: &mut PhotocraftApp, id: &str, params: &Value) -> R fn invoke_type_command(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { match id { + "type.pasteLoremIpsum" if app.ui.text_edit.is_none() && params.as_object().is_none_or(|object| object.is_empty()) => Some(Ok(Value::Null)), "type.increaseSize" | "type.decreaseSize" | "type.increaseSizeMore" | "type.decreaseSizeMore" if params.as_object().is_none_or(|object| object.is_empty()) => { diff --git a/crates/ui-egui/src/menus/type_paste_lorem_greyed_tests.rs b/crates/ui-egui/src/menus/type_paste_lorem_greyed_tests.rs index 92cfb400ac..17c0163fa2 100644 --- a/crates/ui-egui/src/menus/type_paste_lorem_greyed_tests.rs +++ b/crates/ui-egui/src/menus/type_paste_lorem_greyed_tests.rs @@ -1,4 +1,4 @@ -use serde_json::json; +use serde_json::{Value, json}; use crate::PhotocraftApp; @@ -11,22 +11,34 @@ fn enabled(app: &PhotocraftApp) -> bool { row.enabled } +fn assert_no_menu_paste(app: &mut PhotocraftApp, ctx: &egui::Context) { + let state = |app: &PhotocraftApp| app.session.active().map(|d| (d.revision, d.history.past_len())); + let before = state(app); + assert_eq!(crate::menus::invoke(app, ctx, PASTE, json!({})).unwrap(), Value::Null); + assert_eq!(state(app), before, "the disabled menu action leaves the document and history alone"); +} + #[test] fn paste_lorem_menu_requires_an_active_text_edit() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); let ctx = app.ctx().clone(); assert!(!enabled(&app), "no document"); + assert_no_menu_paste(&mut app, &ctx); app.run("file.new", json!({"width": 120, "height": 80, "background": "white"})).unwrap(); app.sync_views(); app.run("layer.new.layer", json!({"name": "Paint"})).unwrap(); assert!(!enabled(&app), "pixel layer selected"); + assert_no_menu_paste(&mut app, &ctx); app.run("select.deselectLayers", json!({})).unwrap(); assert!(!enabled(&app), "no layer selected"); + assert_no_menu_paste(&mut app, &ctx); for params in [json!({"x": 4, "y": 24, "text": "Sample"}), json!({"box": [4, 8, 112, 64], "text": "Sample"})] { let layer = app.run("type.create", params).unwrap()["layer"].as_u64().unwrap(); assert!(!enabled(&app), "selecting a type layer does not start editing"); + assert_no_menu_paste(&mut app, &ctx); + assert_eq!(app.run("type.info", json!({"layer": layer})).unwrap()["text"], "Sample"); crate::menus::invoke(&mut app, &ctx, "type.editText", json!({})).unwrap(); let edit = app.ui.text_edit.as_mut().unwrap(); edit.anchor = edit.caret; @@ -44,13 +56,16 @@ fn paste_lorem_menu_requires_an_active_text_edit() { #[test] fn paste_lorem_engine_command_still_works_outside_the_editor() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = app.ctx().clone(); app.run("file.new", json!({"width": 120, "height": 80, "background": "white"})).unwrap(); let created = app.run(PASTE, json!({"new": true})).unwrap()["layer"].as_u64().unwrap(); let info = app.run("type.info", json!({"layer": created})).unwrap(); let original = info["text"].as_str().unwrap(); - let inserted = app.run(PASTE, json!({"layer": created, "at": 0})).unwrap(); + let inserted = crate::menus::invoke(&mut app, &ctx, PASTE, json!({"layer": created, "at": 0})).unwrap(); let updated = app.run("type.info", json!({"layer": created})).unwrap(); assert_eq!(inserted["caret"].as_u64().unwrap(), original.chars().count() as u64); assert_eq!(updated["text"].as_str().unwrap(), original.repeat(2)); + app.run(PASTE, json!({})).unwrap(); + assert_eq!(app.run("type.info", json!({"layer": created})).unwrap()["text"].as_str().unwrap(), original.repeat(3)); assert!(!enabled(&app)); } From 11aa5831293fd5b36c9716f3af0103a6c8403d6b Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 13:51:55 -0800 Subject: [PATCH 08/34] Avoid empty Update All Text Layers history steps --- crates/engine-core/src/cmd/type_extra_cmds.rs | 57 ++++++++++--- .../src/cmd/type_update_all_layers_tests.rs | 80 +++++++++++++++++++ 2 files changed, 124 insertions(+), 13 deletions(-) create mode 100644 crates/engine-core/src/cmd/type_update_all_layers_tests.rs diff --git a/crates/engine-core/src/cmd/type_extra_cmds.rs b/crates/engine-core/src/cmd/type_extra_cmds.rs index c3ce98effe..950f44233e 100644 --- a/crates/engine-core/src/cmd/type_extra_cmds.rs +++ b/crates/engine-core/src/cmd/type_extra_cmds.rs @@ -816,19 +816,46 @@ fn paste_lorem(s: &mut Session, p: &Value) -> Result { } fn update_all(s: &mut Session) -> Result { - let mut n = 0; - s.edit("Update All Text Layers", |doc, _| { - let (dpi, format) = (doc.resolution_dpi, doc.pixel_format()); - let ids: Vec = doc.walk().into_iter().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).map(|(_, _, l)| l.id).collect(); - for id in ids { - if let Some(Layer { content: LayerContent::Text(t), .. }) = doc.layer_mut(id) { - refresh_at(dpi, format, t); - n += 1; - } + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let mut texts = doc + .walk() + .into_iter() + .filter_map(|(_, _, l)| match &l.content { + LayerContent::Text(text) => Some((l.id, text)), + _ => None, + }) + .peekable(); + if texts.peek().is_none() { + return Ok(json!({"updated": 0})); + } + let generation = photocraft_raster::spill::read_error_generation(); + doc.scratch_health().map_err(EngineError::Other)?; + let (dpi, format) = (doc.resolution_dpi, doc.pixel_format()); + let mut count = 0; + let mut changes = Vec::new(); + for (id, text) in texts { + let mut refreshed = text.clone(); + refresh_at(dpi, format, &mut refreshed); + // An identical render keeps its existing PSD block, including imported metadata. + // A missing block can still be restored even if its pixels were already current. + if text.cache != refreshed.cache || (text.psd_raw.is_none() && refreshed.psd_raw.is_some()) { + changes.push((id, refreshed.cache, refreshed.psd_raw)); } - Ok(()) - })?; - Ok(json!({"updated": n})) + count += 1; + } + photocraft_raster::spill::check_since(generation).and_then(|()| doc.scratch_health()).map_err(EngineError::Other)?; + if !changes.is_empty() { + s.edit("Update All Text Layers", |doc, _| { + for (id, cache, psd_raw) in changes { + if let Some(Layer { content: LayerContent::Text(text), .. }) = doc.layer_mut(id) { + text.cache = cache; + text.psd_raw = psd_raw; + } + } + Ok(()) + })?; + } + Ok(json!({"updated": count})) } fn style_font_missing(fonts: &mut photocraft_text::FontDb, style: &photocraft_doc::text::CharStyle) -> bool { @@ -1098,7 +1125,7 @@ pub fn specs() -> Vec { set_path_placement ), spec!("type.detachFromPath", "Release Type from Path", &[], LP, is_path_text, detach_from_path), - spec!("type.updateAllTextLayers", "Update All Text Layers", &["Type"], "{}", any_text, |s, _| update_all(s)), + spec!("type.updateAllTextLayers", "Update All Text Layers", &["Type"], "{}", has_doc, |s, _| update_all(s)), spec!("type.replaceAllMissingFonts", "Replace All Missing Fonts", &["Type"], "{} (with the default family)", any_text, |s, _| replace_fonts( s, &serde_json::Map::new(), @@ -1141,3 +1168,7 @@ mod tests; #[cfg(test)] #[path = "type_anti_alias_history_tests.rs"] mod anti_alias_history_tests; + +#[cfg(test)] +#[path = "type_update_all_layers_tests.rs"] +mod update_all_layers_tests; diff --git a/crates/engine-core/src/cmd/type_update_all_layers_tests.rs b/crates/engine-core/src/cmd/type_update_all_layers_tests.rs new file mode 100644 index 0000000000..843fdc8260 --- /dev/null +++ b/crates/engine-core/src/cmd/type_update_all_layers_tests.rs @@ -0,0 +1,80 @@ +use serde_json::json; + +use super::*; + +const UPDATE: &str = "type.updateAllTextLayers"; + +fn create_text(session: &mut Session, text: &str, y: i32) -> LayerId { + LayerId(session.execute("type.create", json!({"text": text, "x": 6, "y": y})).unwrap()["layer"].as_u64().unwrap()) +} + +fn text(session: &Session, id: LayerId) -> &TextLayer { + let LayerContent::Text(text) = &session.active().unwrap().doc.layer(id).unwrap().content else { panic!("expected text") }; + text +} + +fn assert_clean_refresh(session: &mut Session, visited: usize) { + session.saved_to("type-update.psd".into()); + let before = session.active().unwrap(); + let doc = before.doc.clone(); + let revision = before.revision; + let steps = before.history.past_len(); + assert_eq!(session.execute(UPDATE, json!({})).unwrap()["updated"], json!(visited)); + let after = session.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&doc, &after.doc)); + assert_eq!(after.history.past_len(), steps); + assert_eq!(after.revision, revision); + assert!(!after.is_dirty()); +} + +#[test] +fn update_all_is_available_without_text_and_keeps_healthy_layers_clean() { + let mut session = Session::new(); + assert!(!session.is_enabled(UPDATE)); + session.execute("file.new", json!({"width": 256, "height": 128, "background": "white"})).unwrap(); + assert!(session.is_enabled(UPDATE)); + assert_clean_refresh(&mut session, 0); + + create_text(&mut session, "First text", 24); + create_text(&mut session, "Second text", 54); + assert!(session.is_enabled(UPDATE)); + assert_clean_refresh(&mut session, 2); + session.execute("select.deselectLayers", json!({})).unwrap(); + assert!(session.is_enabled(UPDATE)); + assert_clean_refresh(&mut session, 2); +} + +#[test] +fn update_all_repairs_stale_text_in_one_undo_step() { + let mut session = Session::new(); + session.execute("file.new", json!({"width": 256, "height": 128, "background": "white"})).unwrap(); + let a = create_text(&mut session, "Existing text", 24); + let b = create_text(&mut session, "Text needing layout", 54); + let current = text(&session, b).cache.clone().unwrap(); + let missing = text(&session, b).psd_raw.clone().unwrap(); + let healthy = text(&session, a).psd_raw.clone().unwrap(); + session + .edit("Stale text fixture", |doc, _| { + let LayerContent::Text(text) = &mut doc.layer_mut(b).unwrap().content else { panic!("expected text") }; + text.cache = None; + text.psd_raw = None; + Ok(()) + }) + .unwrap(); + session.saved_to("type-update.psd".into()); + let prior_steps = session.active().unwrap().history.past_len(); + + assert_eq!(session.execute(UPDATE, json!({})).unwrap()["updated"], 2); + let updated = session.active().unwrap(); + assert!(updated.is_dirty()); + assert_eq!(updated.history.past_len(), prior_steps + 1); + assert_eq!(updated.history.undo_label(), Some("Update All Text Layers")); + assert_eq!(text(&session, b).cache.as_ref(), Some(¤t)); + assert_eq!(text(&session, b).psd_raw.as_ref(), Some(&missing)); + assert!(std::sync::Arc::ptr_eq(&healthy, text(&session, a).psd_raw.as_ref().unwrap())); + + session.execute("edit.undo", json!({})).unwrap(); + assert!(text(&session, b).cache.is_none()); + assert!(text(&session, b).psd_raw.is_none()); + assert_eq!(session.active().unwrap().history.past_len(), prior_steps); +} From 2a6fb517384f968f7a759d54a2eafe91ab61d654 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 14:07:03 -0800 Subject: [PATCH 09/34] Use an engine-core fixture for Transform Again --- .../src/cmd/transform_again_needs_prior_tests.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/engine-core/src/cmd/transform_again_needs_prior_tests.rs b/crates/engine-core/src/cmd/transform_again_needs_prior_tests.rs index 52a9b164ab..dd34796639 100644 --- a/crates/engine-core/src/cmd/transform_again_needs_prior_tests.rs +++ b/crates/engine-core/src/cmd/transform_again_needs_prior_tests.rs @@ -1,3 +1,4 @@ +use photocraft_geom::Rect; use serde_json::json; #[test] @@ -8,9 +9,12 @@ fn transform_again_is_enabled_only_after_a_transform_in_the_session() { session.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); session.execute("layer.new.layer", json!({"name": "Pixels"})).unwrap(); - session.execute("select.rect", json!({"x": 10, "y": 10, "width": 25, "height": 20})).unwrap(); - session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - session.execute("select.deselect", json!({})).unwrap(); + session + .edit("Paint fixture", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 35, 30), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); assert!(!session.is_enabled(command), "ordinary document edits do not enable Again"); let history = session.active().unwrap().history.past_len(); let error = session.execute(command, json!({})).unwrap_err().to_string(); From 45ef0d4042e848bece99568618881b3ea6eb00d8 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 14:15:10 -0800 Subject: [PATCH 10/34] Check the Lorem Ipsum editor before generic availability --- crates/ui-egui/src/menus/state.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 9c8fac79a5..2733836864 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -65,6 +65,10 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool { if crate::analysis::handles(id) { return true; } + // The view command wrapper otherwise uses the engine's document-level availability. + if id == "type.pasteLoremIpsum" { + return app.ui.text_edit.is_some() && app.session.is_enabled(id); + } if let Some(e) = crate::view_cmds::is_enabled(app, id) { return e; } @@ -118,7 +122,6 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool { "edit.paste" | "file.newFromClipboard" => app.session.is_enabled(id) || app.services.clipboard_get_image.is_some(), "edit.pasteSpecial.pasteInPlace" => app.session.is_enabled(id) || (app.services.clipboard_get_image.is_some() && app.session.active().is_some()), "select.selectAndMask" => app.session.is_enabled("select.refineEdge"), - "type.pasteLoremIpsum" => app.ui.text_edit.is_some(), "type.editText" => app .session .active() From e5f33cadcf9ce0a8cdc4f07c788c173ccc1e18b7 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 14:20:12 -0800 Subject: [PATCH 11/34] Expand Paste Lorem Ipsum to a full sample paragraph --- crates/engine-core/src/cmd/type_extra_cmds.rs | 19 +++++++++++++-- .../src/cmd/type_paste_lorem_length_tests.rs | 24 +++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 crates/engine-core/src/cmd/type_paste_lorem_length_tests.rs diff --git a/crates/engine-core/src/cmd/type_extra_cmds.rs b/crates/engine-core/src/cmd/type_extra_cmds.rs index c3ce98effe..e22b67bdf2 100644 --- a/crates/engine-core/src/cmd/type_extra_cmds.rs +++ b/crates/engine-core/src/cmd/type_extra_cmds.rs @@ -21,8 +21,23 @@ use crate::type_cmds::{ }; use crate::{EngineError, Result, Session}; -/// Photoshop's Paste Lorem Ipsum filler. -pub const LOREM_IPSUM: &str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; +/// One paragraph of Paste Lorem Ipsum filler. +pub const LOREM_IPSUM: &str = concat!( + "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ", + "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ", + "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. ", + "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ", + "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. ", + "Dum verba in pagina disponuntur, lector ordinem litterarum et spatium inter lineas considerat. ", + "Scriptor idem initium retinet et diversas sententias addit, ut forma paginae sine imagine clarius appareat. ", + "Alia verba brevia sunt, alia longiora, et finis cuiusque lineae pro latitudine spatii mutatur. ", + "Interdum pagina amplior plures litteras recipit, interdum angusta paucis verbis impletur. ", + "Utraque forma exemplum praebet, dum verba suo ordine manent.", +); + +#[cfg(test)] +#[path = "type_paste_lorem_length_tests.rs"] +mod paste_lorem_length_tests; // ---------- predicates ---------- diff --git a/crates/engine-core/src/cmd/type_paste_lorem_length_tests.rs b/crates/engine-core/src/cmd/type_paste_lorem_length_tests.rs new file mode 100644 index 0000000000..4921db325e --- /dev/null +++ b/crates/engine-core/src/cmd/type_paste_lorem_length_tests.rs @@ -0,0 +1,24 @@ +use serde_json::json; + +use crate::Session; + +#[test] +fn paste_lorem_adds_one_full_paragraph_without_growing_the_type_box() { + let mut session = Session::new(); + session.execute("file.new", json!({"width": 240, "height": 120})).unwrap(); + + for params in [json!({"x": 10, "y": 20, "text": "Existing"}), json!({"box": [10, 10, 20, 18], "text": "Existing"})] { + let layer = session.execute("type.create", params).unwrap()["layer"].as_u64().unwrap(); + let before = session.execute("type.info", json!({"layer": layer})).unwrap(); + let reply = session.execute("type.pasteLoremIpsum", json!({"layer": layer, "at": 0})).unwrap(); + let after = session.execute("type.info", json!({"layer": layer})).unwrap(); + let filler = after["text"].as_str().unwrap().strip_suffix("Existing").unwrap(); + let len = filler.chars().count(); + assert!((950..=1100).contains(&len), "expected about one thousand characters, got {len}"); + assert!(filler.starts_with("Lorem ipsum dolor sit amet")); + assert!(!filler.contains(['\r', '\n'])); + assert_eq!(reply["caret"], json!(len)); + assert!(!before["shape"].is_null()); + assert_eq!(after["shape"], before["shape"], "the full text is kept in the original point or paragraph geometry"); + } +} From 99f58639708cf54a36e2eb3c012c15920604e413 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 14:31:13 -0800 Subject: [PATCH 12/34] Initialize command registry in text refresh tests --- crates/engine-core/src/cmd/type_update_all_layers_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine-core/src/cmd/type_update_all_layers_tests.rs b/crates/engine-core/src/cmd/type_update_all_layers_tests.rs index 843fdc8260..fdf55e1d4f 100644 --- a/crates/engine-core/src/cmd/type_update_all_layers_tests.rs +++ b/crates/engine-core/src/cmd/type_update_all_layers_tests.rs @@ -29,7 +29,7 @@ fn assert_clean_refresh(session: &mut Session, visited: usize) { #[test] fn update_all_is_available_without_text_and_keeps_healthy_layers_clean() { - let mut session = Session::new(); + let mut session = crate::session(); assert!(!session.is_enabled(UPDATE)); session.execute("file.new", json!({"width": 256, "height": 128, "background": "white"})).unwrap(); assert!(session.is_enabled(UPDATE)); @@ -46,7 +46,7 @@ fn update_all_is_available_without_text_and_keeps_healthy_layers_clean() { #[test] fn update_all_repairs_stale_text_in_one_undo_step() { - let mut session = Session::new(); + let mut session = crate::session(); session.execute("file.new", json!({"width": 256, "height": 128, "background": "white"})).unwrap(); let a = create_text(&mut session, "Existing text", 24); let b = create_text(&mut session, "Text needing layout", 54); From d30f2ccb2693f398ed1c627811a830d4130ecb82 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 15:02:26 -0800 Subject: [PATCH 13/34] Initialize commands in the Lorem Ipsum length test --- crates/engine-core/src/cmd/type_paste_lorem_length_tests.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/engine-core/src/cmd/type_paste_lorem_length_tests.rs b/crates/engine-core/src/cmd/type_paste_lorem_length_tests.rs index 4921db325e..fedb3dbf2c 100644 --- a/crates/engine-core/src/cmd/type_paste_lorem_length_tests.rs +++ b/crates/engine-core/src/cmd/type_paste_lorem_length_tests.rs @@ -1,10 +1,8 @@ use serde_json::json; -use crate::Session; - #[test] fn paste_lorem_adds_one_full_paragraph_without_growing_the_type_box() { - let mut session = Session::new(); + let mut session = crate::session(); session.execute("file.new", json!({"width": 240, "height": 120})).unwrap(); for params in [json!({"x": 10, "y": 20, "text": "Existing"}), json!({"box": [10, 10, 20, 18], "text": "Existing"})] { From 0df43a4e7f0c5fffec725b0fce82fccc5de5b811 Mon Sep 17 00:00:00 2001 From: dholzric Date: Mon, 30 Nov 2026 18:01:48 -0600 Subject: [PATCH 14/34] Copy CSS: grey it for the states the reference greys (#18301) Layer > Copy CSS stayed enabled for a smart object, a hidden shape layer, two or more selected layers and in CMYK, Grayscale, Lab and Indexed documents. Its enabled check now refuses each of these with a reason. has_css is unchanged, so what a group writes is unchanged. Hidden layers of other kinds and the document modes that were not measured stay enabled. Co-Authored-By: Claude Fable 5.2 --- .../engine-vector/src/cmd/layer_css_cmds.rs | 36 +++++- .../src/cmd/layer_css_enabled_states_tests.rs | 120 ++++++++++++++++++ 2 files changed, 155 insertions(+), 1 deletion(-) create mode 100644 crates/engine-vector/src/cmd/layer_css_enabled_states_tests.rs diff --git a/crates/engine-vector/src/cmd/layer_css_cmds.rs b/crates/engine-vector/src/cmd/layer_css_cmds.rs index cf6e12a66c..5d0e2a8f35 100644 --- a/crates/engine-vector/src/cmd/layer_css_cmds.rs +++ b/crates/engine-vector/src/cmd/layer_css_cmds.rs @@ -50,9 +50,39 @@ fn enabled(s: &Session) -> std::result::Result<(), String> { if ids.is_empty() { return Err("no layer selected".into()); } + // Greyed in these document modes, for more than one selected layer, for a smart object and for a + // hidden shape, as measured in the reference application (#18301). Other modes and other hidden + // layers were not measured. + use photocraft_color::ColorMode; + let mode = match st.doc.mode { + ColorMode::Cmyk => Some("CMYK"), + ColorMode::Grayscale => Some("Grayscale"), + ColorMode::Lab => Some("Lab"), + ColorMode::Indexed => Some("Indexed Color"), + _ => None, + }; + if let Some(mode) = mode { + return Err(format!("not available in {mode} mode")); + } + if ids.len() > 1 { + return Err("more than one layer is selected".into()); + } + let selected = st.doc.walk().into_iter().map(|(_, _, l)| l).find(|l| ids.contains(&l.id)).ok_or("no layer selected")?; + // A fill layer with a vector mask is a shape here too. + let shape = match &selected.content { + LayerContent::Shape(_) => true, + LayerContent::Fill(_) => selected.vector_mask.is_some(), + _ => false, + }; + if matches!(selected.content, LayerContent::Smart(_)) { + return Err("the layer is a smart object".into()); + } + if shape && !selected.visible { + return Err("the shape layer is hidden".into()); + } // Photoshop greys Copy CSS out for a fill layer without a shape (measured), and for an // adjustment layer, which has nothing to place either. - if st.doc.walk().iter().any(|(_, _, l)| ids.contains(&l.id) && has_css(l)) { Ok(()) } else { Err("no selected layer has CSS".into()) } + if has_css(selected) { Ok(()) } else { Err("no selected layer has CSS".into()) } } /// Whether a layer can have a rule (one with nothing to place still gets none). @@ -374,3 +404,7 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "layer_css_enabled_states_tests.rs"] +mod enabled_states_tests; diff --git a/crates/engine-vector/src/cmd/layer_css_enabled_states_tests.rs b/crates/engine-vector/src/cmd/layer_css_enabled_states_tests.rs new file mode 100644 index 0000000000..5b8d86b2d1 --- /dev/null +++ b/crates/engine-vector/src/cmd/layer_css_enabled_states_tests.rs @@ -0,0 +1,120 @@ +//! #18301: Layer › Copy CSS is greyed, with a reason, for a smart object, a hidden shape layer, two or more selected +//! layers and CMYK, Grayscale, Lab and Indexed documents, as in the reference application. One visible shape, type, +//! pixel, Background or group layer in an RGB document keeps it enabled. Hidden layers of other kinds and Bitmap +//! documents were not measured and keep it enabled too. + +use photocraft_doc::LayerId; +use photocraft_geom::Rect; +use serde_json::json; + +use super::ID; +use crate::Session; + +fn document(mode: &str, depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 64, "height": 48, "mode": mode, "depth": depth})).unwrap(); + s +} + +fn shape(s: &mut Session) -> u64 { + s.execute("shape.create", json!({"rect": [8, 8, 20, 16], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap() +} + +fn pixels(s: &mut Session) -> u64 { + let id = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.edit("setup", |doc, _| { + doc.layer_mut(LayerId(id)).unwrap().surface_mut().unwrap().fill_rect(Rect::new(4, 4, 20, 20), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + id +} + +fn smart_object(s: &mut Session) -> u64 { + pixels(s); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap() +} + +fn point_type(s: &mut Session) -> u64 { + s.execute("type.create", json!({"x": 10, "y": 30, "text": "Hi", "size": 14})).unwrap()["layer"].as_u64().unwrap() +} + +fn group(s: &mut Session) -> u64 { + s.execute("layer.new.group", json!({})).unwrap()["layer"].as_u64().unwrap() +} + +fn hide(s: &mut Session, id: u64) { + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + s.execute("layer.select", json!({"layer": id})).unwrap(); +} + +/// Greyed with a reason, and running it is refused. +fn assert_greyed(s: &mut Session, case: &str) { + assert!(!s.is_enabled(ID), "{case}: greyed"); + assert!(s.disabled_reason(ID).is_some_and(|reason| !reason.is_empty()), "{case}: with a reason"); + assert!(s.execute(ID, json!({})).is_err(), "{case}: refused"); +} + +#[test] +fn a_smart_object_a_hidden_shape_and_several_layers_grey_copy_css() { + let mut s = document("rgb", 8); + smart_object(&mut s); + assert_greyed(&mut s, "a smart object"); + + let mut s = document("rgb", 8); + let id = shape(&mut s); + assert!(s.is_enabled(ID), "the shape while it is visible"); + hide(&mut s, id); + assert_greyed(&mut s, "a hidden shape layer"); + + for with_smart_object in [false, true] { + let mut s = document("rgb", 8); + let a = shape(&mut s); + let b = if with_smart_object { smart_object(&mut s) } else { shape(&mut s) }; + s.execute("layer.select", json!({"layer": a})).unwrap(); + s.execute("layer.select", json!({"layer": b, "mode": "add"})).unwrap(); + assert_greyed(&mut s, if with_smart_object { "a shape and a smart object" } else { "two shapes" }); + } +} + +#[test] +fn cmyk_grayscale_lab_and_indexed_documents_grey_copy_css() { + for mode in ["cmyk", "grayscale", "lab"] { + let mut s = document(mode, 8); + shape(&mut s); + assert_greyed(&mut s, mode); + } + let mut s = document("rgb", 8); + assert!(s.is_enabled(ID), "the Background before the mode change"); + s.execute("image.mode.indexedColor", json!({})).unwrap(); + assert_greyed(&mut s, "indexed"); +} + +#[test] +fn one_visible_layer_in_an_rgb_document_keeps_copy_css_enabled() { + for depth in [8, 16, 32] { + let mut s = document("rgb", depth); + assert!(s.is_enabled(ID), "{depth}-bit: the Background"); + for (kind, make) in [("a shape", shape as fn(&mut Session) -> u64), ("point type", point_type), ("a pixel layer", pixels), ("a group", group)] { + make(&mut s); + assert!(s.is_enabled(ID), "{depth}-bit: {kind}"); + } + shape(&mut s); + s.execute("layer.lockLayers", json!({"all": true})).unwrap(); + assert!(s.is_enabled(ID), "{depth}-bit: a shape with Lock All"); + } +} + +/// Not measured, so these stay enabled as they were. +#[test] +fn the_unmeasured_cases_keep_copy_css_enabled() { + for (kind, make) in [("type", point_type as fn(&mut Session) -> u64), ("pixel", pixels), ("group", group)] { + let mut s = document("rgb", 8); + let id = make(&mut s); + hide(&mut s, id); + assert!(s.is_enabled(ID), "a hidden {kind} layer"); + } + let mut s = crate::session(); + s.execute("file.new", json!({"width": 16, "height": 16, "mode": "bitmap", "depth": 1})).unwrap(); + assert!(s.is_enabled(ID), "a Bitmap document"); +} From 5118ce591be10e21c526ebc4f8da5f62c113ba49 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 16:43:19 -0800 Subject: [PATCH 15/34] Default RAW opening to Display P3 --- crates/engine-core/src/prefs.rs | 8 +++- .../prefs/raw_defaults_space_default_tests.rs | 45 +++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 crates/engine-core/src/prefs/raw_defaults_space_default_tests.rs diff --git a/crates/engine-core/src/prefs.rs b/crates/engine-core/src/prefs.rs index b2490fcadd..76d893ed93 100644 --- a/crates/engine-core/src/prefs.rs +++ b/crates/engine-core/src/prefs.rs @@ -114,7 +114,7 @@ choice!(CheckerColors { Light = "light", Medium = "medium", Dark = "dark", Red = choice!(LineStyle { Lines = "lines", Dashed = "dashedLines", Dots = "dots" } default Lines); choice!(TextEngine { Modern = "modern", EastAsian = "eastAsian", WorldReady = "worldReady" } default WorldReady); choice!(FontPreview { Off = "off", Small = "small", Medium = "medium", Large = "large", ExtraLarge = "extraLarge", Huge = "huge" } default Medium); -choice!(RawColorSpace { Srgb = "srgb", AdobeRgb = "adobeRgb", ProPhoto = "proPhoto", DisplayP3 = "displayP3" } default AdobeRgb); +choice!(RawColorSpace { Srgb = "srgb", AdobeRgb = "adobeRgb", ProPhoto = "proPhoto", DisplayP3 = "displayP3" } default DisplayP3); choice!(RawDepth { Eight = "8", Sixteen = "16" } default Sixteen); choice!(RawSharpen { None = "none", Screen = "screen", Glossy = "glossy", Matte = "matte" } default None); choice!( @@ -1247,7 +1247,7 @@ impl RawDemosaic { impl Default for RawDefaults { fn default() -> Self { Self { - color_space: RawColorSpace::AdobeRgb, + color_space: RawColorSpace::default(), bit_depth: RawDepth::Sixteen, resolution: 300, sharpen_for: RawSharpen::None, @@ -1950,6 +1950,10 @@ impl Session { #[path = "prefs/raw_defaults_resolution_tests.rs"] mod raw_defaults_resolution_tests; +#[cfg(test)] +#[path = "prefs/raw_defaults_space_default_tests.rs"] +mod raw_defaults_space_default_tests; + #[cfg(test)] #[path = "prefs/reset_keeps_workspaces_tests.rs"] mod reset_keeps_workspaces_tests; diff --git a/crates/engine-core/src/prefs/raw_defaults_space_default_tests.rs b/crates/engine-core/src/prefs/raw_defaults_space_default_tests.rs new file mode 100644 index 0000000000..074bc5958a --- /dev/null +++ b/crates/engine-core/src/prefs/raw_defaults_space_default_tests.rs @@ -0,0 +1,45 @@ +use craft_cms::{Builtin, Profile}; +use photocraft_raw::testgen::{DngSpec, mosaic, scene}; +use serde_json::json; + +use super::SavedPrefsExt; + +const SPACE: &str = "rawDefaults.colorSpace"; + +#[test] +fn raw_defaults_uses_display_p3_on_fresh_settings_and_after_reset() { + let mut s = crate::session(); + let get = json!({"path": SPACE}); + assert_eq!(s.execute("prefs.get", get.clone()).unwrap(), "displayP3"); + + for reset in ["rawDefaults", SPACE] { + s.execute("prefs.set", json!({"path": SPACE, "value": "adobeRgb"})).unwrap(); + assert_eq!(s.execute("prefs.get", get.clone()).unwrap(), "adobeRgb"); + s.execute("prefs.reset", json!({"path": reset})).unwrap(); + assert_eq!(s.execute("prefs.get", get.clone()).unwrap(), "displayP3"); + } +} + +#[test] +fn saved_raw_color_spaces_load_unchanged() { + for choice in super::RawColorSpace::NAMES { + let mut s = crate::session(); + let saved = json!({"rawDefaults": {"colorSpace": choice}}).to_string(); + assert!(s.load_prefs_json(&saved).unwrap().is_empty(), "{choice}"); + assert_eq!(s.execute("prefs.get", json!({"path": SPACE})).unwrap(), *choice); + } +} + +#[test] +fn a_raw_opens_with_the_factory_display_p3_profile() { + let (width, height) = (24, 16); + let raw = DngSpec::cfa(width, height, mosaic(&scene(width, height), width, [0, 1, 1, 2], 0, 65535)).build(); + let mut s = crate::session(); + crate::file_cmds::open_bytes_as(&mut s, "IMG_0001.dng", &raw, None, None).unwrap(); + + let doc = &s.active().unwrap().doc; + let profile = Profile::parse(doc.icc_profile.as_ref().unwrap()).unwrap(); + assert!(profile.same_colors(Builtin::DisplayP3.profile())); + assert_eq!(doc.resolution_dpi, 300.0); + assert_eq!(doc.depth, photocraft_color::SampleType::U16); +} From 2d1d8f17cb83899b21f91d9e67b7c72aedf772bf Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 16:52:20 -0800 Subject: [PATCH 16/34] Fit converted paragraphs to their laid-out text height --- .../cmd/type_convert_paragraph_box_tests.rs | 57 +++++++++++++++++++ crates/engine-core/src/cmd/type_extra_cmds.rs | 30 +++++++++- 2 files changed, 84 insertions(+), 3 deletions(-) create mode 100644 crates/engine-core/src/cmd/type_convert_paragraph_box_tests.rs diff --git a/crates/engine-core/src/cmd/type_convert_paragraph_box_tests.rs b/crates/engine-core/src/cmd/type_convert_paragraph_box_tests.rs new file mode 100644 index 0000000000..d543b0e41f --- /dev/null +++ b/crates/engine-core/src/cmd/type_convert_paragraph_box_tests.rs @@ -0,0 +1,57 @@ +use photocraft_doc::{LayerContent, LayerId, TextLayer, text::TextShape}; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::Session; + +fn text_and_ink(s: &Session, id: LayerId) -> (&TextLayer, Rect) { + let layer = s.active().unwrap().doc.layer(id).unwrap(); + let LayerContent::Text(text) = &layer.content else { panic!("expected text") }; + (text, layer.surface().unwrap().content_bounds()) +} + +fn convert(text: &str, size: u32) -> (f32, f64) { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 640, "height": 480, "resolution": 72})).unwrap(); + let result = s.execute("type.create", json!({"x": 100, "y": 200, "text": text, "font": "Arial", "size": size})).unwrap(); + let id = LayerId(result["layer"].as_u64().unwrap()); + let (point, before_ink) = text_and_ink(&s, id); + let before = super::layout_at(72.0, point); + let before_baseline = point.transform.m[5] + f64::from(before.lines[0].baseline); + let [x0, _, x1, _] = before.bounds().unwrap(); + let expected_width = (x1 - x0).max(1.0) + (size as f32 * 0.5).max(4.0); + + s.execute("type.convertToParagraphText", json!({})).unwrap(); + let (paragraph, after_ink) = text_and_ink(&s, id); + let TextShape::Box { width, height, .. } = paragraph.shape else { panic!("expected paragraph text") }; + let after = super::layout_at(72.0, paragraph); + assert_eq!(paragraph.text, text); + assert_eq!(after.lines.len(), before.lines.len()); + assert!(!after.overflows(text), "the new box must keep every line"); + assert!((width - expected_width).abs() < 1e-4); + let after_baseline = paragraph.transform.m[5] + f64::from(after.lines[0].baseline); + assert!((after_baseline - before_baseline).abs() < 1e-4); + assert_eq!(after_ink, before_ink); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Convert to Paragraph Text")); + (height, paragraph.transform.m[5]) +} + +#[test] +fn converting_48_point_arial_uses_its_line_height() { + let (height, y) = convert("Hello World", 48); + let arial_available = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()).has_family("Arial"); + if arial_available { + assert!((height - 58.0).abs() <= 1.0, "height {height}"); + assert!((y - 165.63).abs() <= 1.0, "top {y}"); + } else { + assert!(height >= 57.0, "the leading fits even with the fallback font: {height}"); + } +} + +#[test] +fn smaller_text_gets_a_shorter_box_and_multiline_text_still_fits() { + let (single, _) = convert("Hello World", 48); + let (small, _) = convert("Hello World", 24); + let (multiline, _) = convert("Hello World\nThird?\nA final line", 48); + assert!(small < single && single < multiline, "{small}, {single}, {multiline}"); +} diff --git a/crates/engine-core/src/cmd/type_extra_cmds.rs b/crates/engine-core/src/cmd/type_extra_cmds.rs index c3ce98effe..60d2f49648 100644 --- a/crates/engine-core/src/cmd/type_extra_cmds.rs +++ b/crates/engine-core/src/cmd/type_extra_cmds.rs @@ -189,17 +189,37 @@ fn to_paragraph(s: &mut Session, p: &Value) -> Result { let [x0, y0, x1, y1] = l.bounds().unwrap_or([0.0, -t.size_pt, t.size_pt, 0.0]); // A little slack so no line re-wraps; the box keeps the text where it was. let width = (x1 - x0).max(1.0) + indents + (size_px * 0.5).max(4.0); - let height = (y1 - y0).max(1.0) + size_px * 0.5; + let text_height = (y1 - y0).max(1.0); + let probe_height = text_height + size_px * 0.5; let x = match ps.align { TextAlign::Center | TextAlign::JustifyCenter => -width / 2.0, TextAlign::Right | TextAlign::JustifyRight => -width, _ => 0.0, }; let mut probe = t.clone(); - probe.shape = TextShape::Box { x, y: y0, width, height }; + probe.shape = TextShape::Box { x, y: y0, width, height: probe_height }; // Box text puts the first baseline at the box top plus the ascender height: measure it and // shift the box so that baseline stays at the point-text anchor (y = 0). - let b0 = layout_at(dpi, &probe).lines.first().map_or(0.0, |ln| ln.baseline); + let boxed = layout_at(dpi, &probe); + let b0 = boxed.lines.first().map_or(0.0, |ln| ln.baseline); + let mut height = text_height; + if t.text.is_empty() || l.lines.is_empty() { + height = probe_height; + } else if l.lines.len() == 1 { + // A single line still gets its leading. Across multiple lines the bounds already + // account for the laid-out baseline spacing. + let leading = l + .glyphs + .iter() + .map(|glyph| { + let style = &l.styles[glyph.style as usize]; + style.leading_pt.map_or(ps.auto_leading * l.faces[glyph.face as usize].size_px, |points| points * l.px_per_pt) + }) + .fold(0.0, f32::max); + height = height.max(leading); + } + // The box uses ascender placement; keep every baseline that fit the original probe. + height = height.max(boxed.lines.last().map_or(0.0, |ln| ln.baseline - y0)); let y = y0 - b0; t.shape = TextShape::Box { x: 0.0, y: 0.0, width, height }; t.transform = then_translate(&t.transform, f64::from(x), f64::from(y)); @@ -1141,3 +1161,7 @@ mod tests; #[cfg(test)] #[path = "type_anti_alias_history_tests.rs"] mod anti_alias_history_tests; + +#[cfg(test)] +#[path = "type_convert_paragraph_box_tests.rs"] +mod type_convert_paragraph_box_tests; From 841878714e1de2e0eadb161ee8c68d27391655c8 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 16:53:41 -0800 Subject: [PATCH 17/34] Keep paragraph and text-refresh tests independently mergeable --- .../src/cmd/type_convert_paragraph_box_tests.rs | 6 +++++- crates/engine-core/src/cmd/type_extra_cmds.rs | 8 ++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/crates/engine-core/src/cmd/type_convert_paragraph_box_tests.rs b/crates/engine-core/src/cmd/type_convert_paragraph_box_tests.rs index d543b0e41f..199b5c884c 100644 --- a/crates/engine-core/src/cmd/type_convert_paragraph_box_tests.rs +++ b/crates/engine-core/src/cmd/type_convert_paragraph_box_tests.rs @@ -18,7 +18,7 @@ fn convert(text: &str, size: u32) -> (f32, f64) { let (point, before_ink) = text_and_ink(&s, id); let before = super::layout_at(72.0, point); let before_baseline = point.transform.m[5] + f64::from(before.lines[0].baseline); - let [x0, _, x1, _] = before.bounds().unwrap(); + let [x0, top, x1, bottom] = before.bounds().unwrap(); let expected_width = (x1 - x0).max(1.0) + (size as f32 * 0.5).max(4.0); s.execute("type.convertToParagraphText", json!({})).unwrap(); @@ -29,6 +29,10 @@ fn convert(text: &str, size: u32) -> (f32, f64) { assert_eq!(after.lines.len(), before.lines.len()); assert!(!after.overflows(text), "the new box must keep every line"); assert!((width - expected_width).abs() < 1e-4); + if before.lines.len() == 1 { + let expected_height = (bottom - top).max(size as f32 * 1.2).max(after.lines[0].baseline); + assert!((height - expected_height).abs() < 1e-4, "expected {expected_height}, got {height}"); + } let after_baseline = paragraph.transform.m[5] + f64::from(after.lines[0].baseline); assert!((after_baseline - before_baseline).abs() < 1e-4); assert_eq!(after_ink, before_ink); diff --git a/crates/engine-core/src/cmd/type_extra_cmds.rs b/crates/engine-core/src/cmd/type_extra_cmds.rs index 60d2f49648..fcae511ce5 100644 --- a/crates/engine-core/src/cmd/type_extra_cmds.rs +++ b/crates/engine-core/src/cmd/type_extra_cmds.rs @@ -1154,6 +1154,10 @@ pub fn specs() -> Vec { all } +#[cfg(test)] +#[path = "type_convert_paragraph_box_tests.rs"] +mod type_convert_paragraph_box_tests; + #[cfg(test)] #[path = "type_extra_cmds/tests.rs"] mod tests; @@ -1161,7 +1165,3 @@ mod tests; #[cfg(test)] #[path = "type_anti_alias_history_tests.rs"] mod anti_alias_history_tests; - -#[cfg(test)] -#[path = "type_convert_paragraph_box_tests.rs"] -mod type_convert_paragraph_box_tests; From 8a040ae36d0cf79c59c3fcb185159fb09b9809e5 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 16:55:41 -0800 Subject: [PATCH 18/34] Test the RAW workflow through the Batch opener --- .../engine-core/src/prefs/raw_defaults_space_default_tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine-core/src/prefs/raw_defaults_space_default_tests.rs b/crates/engine-core/src/prefs/raw_defaults_space_default_tests.rs index 074bc5958a..35fcbb9c57 100644 --- a/crates/engine-core/src/prefs/raw_defaults_space_default_tests.rs +++ b/crates/engine-core/src/prefs/raw_defaults_space_default_tests.rs @@ -31,10 +31,12 @@ fn saved_raw_color_spaces_load_unchanged() { } #[test] -fn a_raw_opens_with_the_factory_display_p3_profile() { +fn batch_raw_opens_with_the_factory_display_p3_profile() { let (width, height) = (24, 16); let raw = DngSpec::cfa(width, height, mosaic(&scene(width, height), width, [0, 1, 1, 2], 0, 65535)).build(); let mut s = crate::session(); + // Batch passes the RAW workflow defaults to the scratch session before opening each input. + s.batch_raw_open = Some(s.prefs().raw_defaults.clone()); crate::file_cmds::open_bytes_as(&mut s, "IMG_0001.dng", &raw, None, None).unwrap(); let doc = &s.active().unwrap().doc; From ecea2de0571849dde21deb2dcb3a90055921beb0 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 17:28:00 -0800 Subject: [PATCH 19/34] Exercise the quiet Batch command in the RAW preference regression --- .../prefs/raw_defaults_space_default_tests.rs | 23 ++++++++++++++----- 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/crates/engine-core/src/prefs/raw_defaults_space_default_tests.rs b/crates/engine-core/src/prefs/raw_defaults_space_default_tests.rs index 35fcbb9c57..d139b64b4d 100644 --- a/crates/engine-core/src/prefs/raw_defaults_space_default_tests.rs +++ b/crates/engine-core/src/prefs/raw_defaults_space_default_tests.rs @@ -1,5 +1,3 @@ -use craft_cms::{Builtin, Profile}; -use photocraft_raw::testgen::{DngSpec, mosaic, scene}; use serde_json::json; use super::SavedPrefsExt; @@ -31,15 +29,28 @@ fn saved_raw_color_spaces_load_unchanged() { } #[test] +#[cfg(not(target_arch = "wasm32"))] fn batch_raw_opens_with_the_factory_display_p3_profile() { + use craft_cms::{Builtin, Profile}; + use photocraft_raw::testgen::{DngSpec, mosaic, scene}; + + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("IMG_0001.dng"); + let output = dir.path().join("out"); let (width, height) = (24, 16); let raw = DngSpec::cfa(width, height, mosaic(&scene(width, height), width, [0, 1, 1, 2], 0, 65535)).build(); + std::fs::write(&source, raw).unwrap(); let mut s = crate::session(); - // Batch passes the RAW workflow defaults to the scratch session before opening each input. - s.batch_raw_open = Some(s.prefs().raw_defaults.clone()); - crate::file_cmds::open_bytes_as(&mut s, "IMG_0001.dng", &raw, None, None).unwrap(); + let result = s + .execute( + "file.automate.batch", + json!({"input":[source], "output":output, "format":"psd", "suppressOpenOptions":true, "suppressWarnings":true, "steps":[]}), + ) + .unwrap(); + assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); - let doc = &s.active().unwrap().doc; + let saved = std::fs::read(output.join("IMG_0001.psd")).unwrap(); + let doc = photocraft_io::import("IMG_0001.psd", &saved).unwrap().document; let profile = Profile::parse(doc.icc_profile.as_ref().unwrap()).unwrap(); assert!(profile.same_colors(Builtin::DisplayP3.profile())); assert_eq!(doc.resolution_dpi, 300.0); From ff36a7b1c4484a20590d2b787c0ab0a1c3fc0fb7 Mon Sep 17 00:00:00 2001 From: kubuntugamer Date: Mon, 30 Nov 2026 20:52:14 -0600 Subject: [PATCH 20/34] Background Eraser: not-allowed cursor over a layer mask and a 32-bit document The reference shows the no-entry sign over a targeted layer mask and over the composite of a 32-bit document; the tool painted with its tip cursor there. The targets the item left unmeasured keep the tip cursor. Fixes #18097 --- .../background_eraser_target_cursor_tests.rs | 116 ++++++++++++++++++ crates/ui-egui/src/canvas/cursor_policy.rs | 14 +++ 2 files changed, 130 insertions(+) create mode 100644 crates/ui-egui/src/canvas/background_eraser_target_cursor_tests.rs diff --git a/crates/ui-egui/src/canvas/background_eraser_target_cursor_tests.rs b/crates/ui-egui/src/canvas/background_eraser_target_cursor_tests.rs new file mode 100644 index 0000000000..e66d2ceb5b --- /dev/null +++ b/crates/ui-egui/src/canvas/background_eraser_target_cursor_tests.rs @@ -0,0 +1,116 @@ +//! #18097: with the Background Eraser active the canvas cursor is the not-allowed one over a layer +//! mask and over the composite of a 32-bit document, as the reference application shows, and the +//! tip cursor everywhere the issue left unmeasured. + +use craft::behavior::{Cursor, CursorIcon}; +use egui::{Modifiers, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::guide_cursor_tests::hover; +use crate::state::Tool; + +const IN_IMAGE: f32 = 100.0; +const ON_LAYER: f32 = 150.0; +const BLOCKED: Option = Some(Cursor::System(CursorIcon::NotAllowed)); + +/// The canvas at 100 % on a 400 × 300 `depth`-bit document with the Background Eraser active. +fn harness(depth: u32) -> Harness<'static, Box> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300, "depth": depth})).unwrap(); + app.sync_views(); + app.ui.extras.rulers = false; + app.ui.tool = Tool::BackgroundEraser; + let ctx = app.ctx().clone(); + let mut h = Harness::builder().with_context(ctx).with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(move |_cc| app); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + v.zoom = 1.0; + v.center = [200.0, 150.0]; + v.clear_pending(); + h.run_steps(2); + h +} + +/// A pixel layer filled red, so the tool has pixels to erase. +fn pixel_layer(h: &mut Harness<'static, Box>) { + h.state_mut().run("layer.new.layer", json!({})).unwrap(); + h.state_mut().run("edit.fill", json!({"color": "#ff0000"})).unwrap(); +} + +/// A layer mask revealing everything, on the active layer. +fn layer_mask(h: &mut Harness<'static, Box>) { + h.state_mut().run("select.all", json!({})).unwrap(); + // The selection becomes the mask. + h.state_mut().run("layer.layerMask.revealSelection", json!({})).unwrap(); +} + +fn cursor(h: &mut Harness<'static, Box>) -> Option { + hover(h, IN_IMAGE, ON_LAYER, Modifiers::NONE); + h.state().canvas_tools.last_response.as_ref().and_then(|response| response.cursor.clone()) +} + +/// Done when 1 and 2: a layer mask (enabled or disabled, of a pixel layer or a group) blocks the +/// cursor, the layer's own pixels do not. +#[test] +fn a_layer_mask_blocks_the_background_eraser_cursor() { + let mut h = harness(8); + pixel_layer(&mut h); + let normal = cursor(&mut h); + assert!(normal.is_some() && normal != BLOCKED, "the pixel layer has the tip cursor"); + + layer_mask(&mut h); + h.state_mut().ui.mask_target = true; + assert_eq!(cursor(&mut h), BLOCKED, "the targeted mask"); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::NotAllowed); + + h.state_mut().run("layer.layerMask.enabled", json!({"enabled": false})).unwrap(); + assert_eq!(cursor(&mut h), BLOCKED, "a disabled mask is targeted too"); + + h.state_mut().run("layer.layerMask.enabled", json!({"enabled": true})).unwrap(); + h.state_mut().ui.mask_target = false; + assert_eq!(cursor(&mut h), normal, "the layer's own pixels keep the tip cursor"); + + // A group's mask, targeted from the Layers panel. + h.state_mut().run("layer.new.group", json!({})).unwrap(); + layer_mask(&mut h); + h.state_mut().ui.mask_target = true; + assert_eq!(cursor(&mut h), BLOCKED, "a group mask"); +} + +/// Done when 1 and 2: the composite of a 32-bit document blocks the cursor, an 8- or 16-bit one +/// does not. +#[test] +fn a_thirty_two_bit_composite_blocks_the_background_eraser_cursor() { + for (depth, blocked) in [(8, false), (16, false), (32, true)] { + let mut h = harness(depth); + pixel_layer(&mut h); + let got = cursor(&mut h); + assert_eq!(got == BLOCKED, blocked, "{depth}-bit: {got:?}"); + } +} + +/// Done when 3: the targets the issue left unmeasured keep today's cursor: the Quick Mask, an +/// adjustment layer's mask, and a vector mask. +#[test] +fn the_unmeasured_targets_keep_the_tip_cursor() { + let mut h = harness(8); + pixel_layer(&mut h); + let normal = cursor(&mut h); + + h.state_mut().run("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + assert_eq!(cursor(&mut h), normal, "Quick Mask"); + h.state_mut().run("select.editInQuickMaskMode", json!({"on": false})).unwrap(); + + h.state_mut().run("layer.newAdjustmentLayer.curves", json!({})).unwrap(); + layer_mask(&mut h); + h.state_mut().ui.mask_target = true; + assert_eq!(cursor(&mut h), normal, "an adjustment layer's mask"); + + let mut h = harness(8); + pixel_layer(&mut h); + let normal = cursor(&mut h); + h.state_mut().run("layer.vectorMask.add", json!({})).unwrap(); + assert_eq!(cursor(&mut h), normal, "a vector mask"); +} diff --git a/crates/ui-egui/src/canvas/cursor_policy.rs b/crates/ui-egui/src/canvas/cursor_policy.rs index 2157726e52..68ad2d975b 100644 --- a/crates/ui-egui/src/canvas/cursor_policy.rs +++ b/crates/ui-egui/src/canvas/cursor_policy.rs @@ -167,6 +167,16 @@ pub(super) fn paint_cursor_blocked(app: &PhotocraftApp) -> bool { if tool == Tool::ArtHistoryBrush { return app.session.active().is_some_and(|state| matches!(state.doc.mode, photocraft_color::ColorMode::Indexed | photocraft_color::ColorMode::Bitmap)); } + // The Background Eraser refuses a layer mask and the composite of a 32-bit document, and shows + // the not-allowed cursor over both (#18097). The targets the issue left unmeasured (an alpha + // channel, Quick Mask, an adjustment layer, colour channels) keep the tip cursor. + if tool == Tool::BackgroundEraser { + let Some(state) = app.session.active() else { return false }; + let target = super::paint_target(app); + let mask = target.as_str() == Some("mask") && !crate::adjustment_layer_active(state); + let wide = target.as_str() == Some("pixels") && state.doc.depth == photocraft_color::SampleType::F32; + return mask || wide; + } if !matches!(tool, Tool::Brush | Tool::Eraser | Tool::PaintBucket | Tool::MixerBrush) { return false; } @@ -264,3 +274,7 @@ mod locked_layer_cursor_tests; #[cfg(test)] #[path = "art_history_mode_cursor_tests.rs"] mod art_history_mode_cursor_tests; + +#[cfg(test)] +#[path = "background_eraser_target_cursor_tests.rs"] +mod background_eraser_target_cursor_tests; From 464343783947d6ba423c470e3eb1421de2a7b869 Mon Sep 17 00:00:00 2001 From: dholzric Date: Mon, 30 Nov 2026 20:56:20 -0600 Subject: [PATCH 21/34] Layer Align: grey it for a selected layer with Lock Position (#18443) can_align had no lock check, so the six entries stayed enabled and a click failed with "position-locked", or moved the other layers when the locked one happened to be in place. position_locked gives the refusal for the first selected layer whose position is locked. can_align uses it to grey the entries; align asks it before the edit, with Lock All counted, so the refusal also comes when the locked layer would not move and no History state is added. Kept as before: the menu state with Lock All and a locked layer together with a pixel selection (not measured), and the Background in the selection. Co-Authored-By: Claude Fable 5.2 --- .../engine-core/src/cmd/layer_multi_cmds.rs | 7 +- .../src/cmd/layer_multi_cmds/align.rs | 21 ++ .../align_position_lock_enabled_tests.rs | 180 ++++++++++++++++++ 3 files changed, 205 insertions(+), 3 deletions(-) create mode 100644 crates/engine-core/src/cmd/layer_multi_cmds/align_position_lock_enabled_tests.rs diff --git a/crates/engine-core/src/cmd/layer_multi_cmds.rs b/crates/engine-core/src/cmd/layer_multi_cmds.rs index e06fb798d0..4ce80a67f4 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds.rs @@ -19,7 +19,7 @@ mod selection; mod structure; pub use crate::damage::{layer_bounds, same_pixels, selection_only_change, step_damage}; -use align::{align, distribute}; +use align::{align, distribute, position_locked}; use moves::link_groups; pub use moves::shift_surface; #[cfg(test)] @@ -52,8 +52,9 @@ fn can_align(s: &Session) -> std::result::Result<(), String> { match d.selected_layers().len() { 0 => Err("no layer selected".into()), // Photoshop aligns to an active selection however many layers are selected; without one, - // a single layer aligns to the canvas and 2+ align to each other. - _ => Ok(()), + // a single layer aligns to the canvas and 2+ align to each other. A selected layer with + // Lock Position greys the entries (#18443). + _ => position_locked(&d.doc, d.selected_layers(), false).map_or(Ok(()), Err), } } fn can_distribute(s: &Session) -> std::result::Result<(), String> { diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/align.rs b/crates/engine-core/src/cmd/layer_multi_cmds/align.rs index 7c19de2481..86ae8e870e 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/align.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/align.rs @@ -47,12 +47,29 @@ fn bounded_selection(doc: &Document, sel: &[LayerId]) -> Vec<(LayerId, Rect)> { top_level(doc, sel).into_iter().filter_map(|id| Some((id, align_bounds(doc.layer(id)?, doc.bounds(), doc.pixel_format().sample)?))).collect() } +/// The refusal for a selected layer whose position is locked, naming it (#18443). `lock_all` counts Lock All as well: +/// the command refuses it, while its menu state was not measured. The Background is locked in place by construction +/// and still takes part. A locked layer together with a pixel selection was not measured either: there only +/// `move_layers` refuses, when the layer would have to move. +pub(super) fn position_locked(doc: &Document, sel: &[LayerId], lock_all: bool) -> Option { + let held = sel.iter().filter_map(|id| doc.layer(*id)).find(|l| { + let locks = doc.effective_locks(l.id); + (locks.position || (lock_all && locks.all)) && !doc.is_background(l.id) + })?; + let pixel_selection = doc.selection.as_ref().is_some_and(|m| !m.content_bounds().is_empty()); + (!pixel_selection).then(|| format!("layer \"{}\" is position-locked", held.name)) +} + pub(super) fn align(s: &mut Session, p: &Value, kind: &str) -> Result { let cmd = format!("layer.align.{kind}"); let edge = Edge::parse(kind).ok_or_else(|| bad(&cmd, "unknown edge"))?; let sel = selected(s); let to = p.get("to").and_then(Value::as_str).unwrap_or("auto").to_string(); let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); + // Refused before anything moves, also when the locked layer would stay where it is. + if let Some(refusal) = position_locked(&before, &sel, true) { + return Err(EngineError::Other(refusal)); + } // The History state is named after the entry (#18283). let name = match edge { Edge::Top => "Align Top Edges", @@ -198,3 +215,7 @@ mod align_history_names_tests; #[cfg(test)] #[path = "align_half_pixel_tests.rs"] mod align_half_pixel_tests; + +#[cfg(test)] +#[path = "align_position_lock_enabled_tests.rs"] +mod align_position_lock_enabled_tests; diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/align_position_lock_enabled_tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/align_position_lock_enabled_tests.rs new file mode 100644 index 0000000000..7e4521ce99 --- /dev/null +++ b/crates/engine-core/src/cmd/layer_multi_cmds/align_position_lock_enabled_tests.rs @@ -0,0 +1,180 @@ +//! #18443: Layer › Align is greyed when a selected layer has Lock Position, and the command refuses a selected layer +//! with Lock Position or Lock All by name, also when that layer would not move. Lock Transparent Pixels, Lock Image +//! Pixels and the Background in the selection do not block it. Not measured, so held as they were: the menu state +//! with Lock All, and a locked layer together with a pixel selection. + +use photocraft_doc::{Document, LayerId, Locks}; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::Session; + +const ENTRIES: [&str; 6] = [ + "layer.align.topEdges", + "layer.align.verticalCenters", + "layer.align.bottomEdges", + "layer.align.leftEdges", + "layer.align.horizontalCenters", + "layer.align.rightEdges", +]; + +const POSITION: Locks = Locks { transparency: false, pixels: false, position: true, artboard: false, all: false }; +const ALL: Locks = Locks { transparency: false, pixels: false, position: false, artboard: false, all: true }; +const PIXELS: Locks = Locks { transparency: false, pixels: true, position: false, artboard: false, all: false }; +const TRANSPARENCY: Locks = Locks { transparency: true, pixels: false, position: false, artboard: false, all: false }; + +/// The name of the layer the tests lock, which a refusal has to mention. +const HELD: &str = "Held in place"; + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +fn bounds(s: &Session, id: LayerId) -> Rect { + crate::damage::layer_bounds(doc(s).layer(id).unwrap()).unwrap() +} + +fn states(s: &Session) -> usize { + s.active().unwrap().history.past_len() +} + +fn pixel_layer(s: &mut Session, name: &str, r: Rect) -> LayerId { + let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.edit("paint", |doc, _| { + let layer = doc.layer_mut(id).unwrap(); + layer.name = name.into(); + layer.surface_mut().unwrap().fill_rect(r, &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + id +} + +/// A 100 x 80 document with a Background and two pixel layers: the one the tests lock, and a larger one down and to +/// the right of it. Left Edges and Top Edges leave the first where it is; the other four entries have to move it. +fn two_layers() -> (Session, LayerId, LayerId) { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 100, "height": 80})).unwrap(); + let held = pixel_layer(&mut s, HELD, Rect::new(10, 10, 20, 20)); + let free = pixel_layer(&mut s, "Free", Rect::new(40, 30, 70, 60)); + (s, held, free) +} + +/// Selects `ids`; the last one is the active layer. +fn select(s: &mut Session, ids: &[LayerId]) { + s.execute("layer.select", json!({"layer": ids[0].0})).unwrap(); + for id in &ids[1..] { + s.execute("layer.select", json!({"layer": id.0, "mode": "add"})).unwrap(); + } +} + +fn lock(s: &mut Session, id: LayerId, locks: Locks) { + s.edit("lock", |doc, _| { + doc.layer_mut(id).unwrap().locks = locks; + Ok(()) + }) + .unwrap(); +} + +#[test] +fn lock_position_on_a_selected_layer_greys_the_six_entries() { + for held_is_active in [false, true] { + let (mut s, held, free) = two_layers(); + select(&mut s, &if held_is_active { [free, held] } else { [held, free] }); + for entry in ENTRIES { + assert!(s.is_enabled(entry), "{entry}: enabled without a lock"); + } + lock(&mut s, held, POSITION); + for entry in ENTRIES { + let reason = s.disabled_reason(entry).unwrap_or_else(|| panic!("{entry} stays enabled, locked layer active: {held_is_active}")); + assert!(reason.contains(HELD), "{entry}: {reason}"); + } + } +} + +#[test] +fn a_selected_layer_with_lock_position_or_lock_all_refuses_the_align_by_name() { + for (locks, case) in [(POSITION, "Lock Position"), (ALL, "Lock All")] { + // Left Edges and Top Edges would leave the locked layer where it is. + for entry in ENTRIES { + let (mut s, held, free) = two_layers(); + select(&mut s, &[held, free]); + lock(&mut s, held, locks); + let (before, states_before) = (doc(&s).clone(), states(&s)); + let error = s.execute(entry, json!({})).expect_err(&format!("{entry}, {case}: refused")); + assert!(error.to_string().contains(HELD), "{entry}, {case}: {error}"); + assert!(*doc(&s) == before, "{entry}, {case}: nothing moved"); + assert_eq!(states(&s), states_before, "{entry}, {case}: no History state"); + } + } +} + +#[test] +fn lock_transparent_pixels_and_lock_image_pixels_do_not_block() { + for (locks, case) in [(TRANSPARENCY, "Lock Transparent Pixels"), (PIXELS, "Lock Image Pixels")] { + let (mut s, lower, upper) = two_layers(); + select(&mut s, &[lower, upper]); + lock(&mut s, lower, locks); + lock(&mut s, upper, locks); + for entry in ENTRIES { + assert!(s.is_enabled(entry), "{entry}, {case}"); + } + let was = bounds(&s, lower); + s.execute("layer.align.rightEdges", json!({})).unwrap(); + assert!(bounds(&s, lower).x0 > was.x0, "{case}: the locked layer moved"); + assert_eq!(bounds(&s, lower).x1, bounds(&s, upper).x1, "{case}: the right edges agree"); + } +} + +#[test] +fn the_background_in_the_selection_keeps_the_entries_enabled() { + let (mut s, _, free) = two_layers(); + let background = doc(&s).background().unwrap().id; + assert!(doc(&s).effective_locks(background).position, "the Background is locked in place"); + select(&mut s, &[background, free]); + for entry in ENTRIES { + assert!(s.is_enabled(entry), "{entry}"); + } + s.execute("layer.align.rightEdges", json!({})).unwrap(); + assert_eq!(bounds(&s, free).x1, doc(&s).bounds().x1, "the layer aligns to the Background's edge"); +} + +/// Not measured, so as before: Lock All leaves the menu entries enabled, and with a pixel selection a locked layer is +/// refused only when it would have to move. +#[test] +fn the_unmeasured_cases_keep_todays_behaviour() { + let (mut s, held, free) = two_layers(); + select(&mut s, &[held, free]); + lock(&mut s, held, ALL); + for entry in ENTRIES { + assert!(s.is_enabled(entry), "{entry}: Lock All"); + } + + for (locks, case) in [(POSITION, "Lock Position"), (ALL, "Lock All")] { + let (mut s, held, free) = two_layers(); + select(&mut s, &[held, free]); + lock(&mut s, held, locks); + // A selection whose left edge is the locked layer's. + s.execute("select.rect", json!({"x": 10, "y": 40, "width": 50, "height": 20})).unwrap(); + for entry in ENTRIES { + assert!(s.is_enabled(entry), "{entry}: {case} with a pixel selection"); + } + s.execute("layer.align.leftEdges", json!({})).unwrap(); + assert_eq!(bounds(&s, free).x0, bounds(&s, held).x0, "{case}: the other layer aligns to the selection"); + assert!(s.execute("layer.align.rightEdges", json!({})).is_err(), "{case}: the locked layer would have to move"); + } +} + +/// Not in the item: a lock inherited from a group counts as the layer's, as it does when a move is refused. +#[test] +fn lock_position_inherited_from_a_group_greys_the_entries_too() { + let (mut s, held, free) = two_layers(); + select(&mut s, &[held]); + let group = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + lock(&mut s, group, POSITION); + select(&mut s, &[held, free]); + assert!(!doc(&s).layer(held).unwrap().locks.position && doc(&s).effective_locks(held).position, "only the group holds the lock"); + for entry in ENTRIES { + assert!(!s.is_enabled(entry), "{entry}"); + } +} From aeba1971ce8facaeac05a8072a855caba0824008 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 19:50:05 -0800 Subject: [PATCH 22/34] Separate the Type menu preview and language groups --- crates/ui-egui/src/menu_catalog.rs | 6 +++++ .../src/menus/type_menu_groups_tests.rs | 22 +++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 crates/ui-egui/src/menus/type_menu_groups_tests.rs diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs index 10d1b57d61..b84e5adeef 100644 --- a/crates/ui-egui/src/menu_catalog.rs +++ b/crates/ui-egui/src/menu_catalog.rs @@ -468,6 +468,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["Type", "Anti-Alias"], "---", None, "---"), (&["Type", "Anti-Alias"], "Windows LCD", None, "type.antiAlias.windowsLcd"), (&["Type", "Anti-Alias"], "Windows", None, "type.antiAlias.windows"), + (&["Type"], "---", None, "---"), (&["Type", "Orientation"], "Horizontal", None, "type.orientation.horizontal"), (&["Type", "Orientation"], "Vertical", None, "type.orientation.vertical"), (&["Type", "OpenType"], "Standard Ligatures", None, "type.openType.standardLigatures"), @@ -524,6 +525,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["Type", "Font Preview Size"], "Large", None, "type.fontPreviewSize.large"), (&["Type", "Font Preview Size"], "Extra Large", None, "type.fontPreviewSize.extraLarge"), (&["Type", "Font Preview Size"], "Huge", None, "type.fontPreviewSize.huge"), + (&["Type"], "---", None, "---"), (&["Type", "Language Options"], "Default Features", None, "type.languageOptions.defaultFeatures"), (&["Type", "Language Options"], "East Asian Features", None, "type.languageOptions.eastAsianFeatures"), (&["Type", "Language Options"], "Middle Eastern Features", None, "type.languageOptions.middleEasternFeatures"), @@ -828,3 +830,7 @@ pub const ARRANGE_ICONS: &[(&str, &str)] = &[ ("window.arrange.sixUp", "arrange-six-up"), ("window.arrange.consolidateAllToTabs", "arrange-consolidate-all-to-tabs"), ]; + +#[cfg(test)] +#[path = "menus/type_menu_groups_tests.rs"] +mod type_menu_groups_tests; diff --git a/crates/ui-egui/src/menus/type_menu_groups_tests.rs b/crates/ui-egui/src/menus/type_menu_groups_tests.rs new file mode 100644 index 0000000000..bfe72ca8d3 --- /dev/null +++ b/crates/ui-egui/src/menus/type_menu_groups_tests.rs @@ -0,0 +1,22 @@ +use crate::PhotocraftApp; +use craft::menu::{Node, from_items}; + +#[test] +fn type_submenus_keep_their_reference_groups() { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let bar = from_items(&["Type"], &crate::menus::menu_rows(&app)); + let entries: Vec<_> = bar.menus[0] + .children + .iter() + .map(|node| match node { + Node::Separator => "---", + Node::Submenu { label, .. } | Node::Heading(label) => label.as_str(), + Node::Item(row) => row.command.id.as_str(), + }) + .collect(); + assert!(entries.windows(6).any(|rows| rows == ["---", "Anti-Alias", "---", "Orientation", "OpenType", "---"]), "{entries:?}"); + assert!(entries.windows(6).any(|rows| rows == ["---", "Font Preview Size", "---", "Language Options", "---", "type.updateAllTextLayers"]), "{entries:?}"); + let warp = entries.iter().position(|entry| *entry == "type.warpText").unwrap(); + let preview = entries.iter().position(|entry| *entry == "Font Preview Size").unwrap(); + assert!(warp < preview, "{entries:?}"); +} From fa78938ff6603d9ac56dc6b2d02e48db7d122525 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 20:03:09 -0800 Subject: [PATCH 23/34] Handle non-exhaustive menu nodes in Type test --- crates/ui-egui/src/menus/type_menu_groups_tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/menus/type_menu_groups_tests.rs b/crates/ui-egui/src/menus/type_menu_groups_tests.rs index bfe72ca8d3..477186a8be 100644 --- a/crates/ui-egui/src/menus/type_menu_groups_tests.rs +++ b/crates/ui-egui/src/menus/type_menu_groups_tests.rs @@ -12,6 +12,7 @@ fn type_submenus_keep_their_reference_groups() { Node::Separator => "---", Node::Submenu { label, .. } | Node::Heading(label) => label.as_str(), Node::Item(row) => row.command.id.as_str(), + _ => "", }) .collect(); assert!(entries.windows(6).any(|rows| rows == ["---", "Anti-Alias", "---", "Orientation", "OpenType", "---"]), "{entries:?}"); From adb0fb24d596f84fa92cc132eff8908a2b9eb4f2 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 20:08:05 -0800 Subject: [PATCH 24/34] Clamp both Lorem Ipsum selection offsets --- crates/engine-core/src/cmd/type_extra_cmds.rs | 5 +++-- .../src/cmd/type_paste_lorem_selection_tests.rs | 13 +++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/engine-core/src/cmd/type_extra_cmds.rs b/crates/engine-core/src/cmd/type_extra_cmds.rs index 7dea7d2d72..ad11a954a5 100644 --- a/crates/engine-core/src/cmd/type_extra_cmds.rs +++ b/crates/engine-core/src/cmd/type_extra_cmds.rs @@ -805,8 +805,9 @@ fn paste_lorem(s: &mut Session, p: &Value) -> Result { // existing creation step; the first edit of an existing layer gets the type-edit label. let label = if range_end.is_some() && p.get("coalesce").and_then(Value::as_str).is_some() { "Edit Type Layer" } else { "Paste Lorem Ipsum" }; let caret = with_text(s, p, label, |t, _| { - let at = p.get("at").and_then(Value::as_u64).map_or(t.text.len(), |c| byte_index(&t.text, c as usize)); - let end = range_end.map_or(at, |c| byte_index(&t.text, usize::try_from(c).unwrap_or(usize::MAX))); + let to_byte = |c| byte_index(&t.text, usize::try_from(c).unwrap_or(usize::MAX)); + let at = p.get("at").and_then(Value::as_u64).map_or(t.text.len(), to_byte); + let end = range_end.map_or(at, to_byte); let start = at.min(end); replace_text(t, start, at.max(end), LOREM_IPSUM); Ok(char_index(&t.text, start + LOREM_IPSUM.len())) diff --git a/crates/engine-core/src/cmd/type_paste_lorem_selection_tests.rs b/crates/engine-core/src/cmd/type_paste_lorem_selection_tests.rs index ded602629d..339b2a3a60 100644 --- a/crates/engine-core/src/cmd/type_paste_lorem_selection_tests.rs +++ b/crates/engine-core/src/cmd/type_paste_lorem_selection_tests.rs @@ -42,3 +42,16 @@ fn paste_lorem_replaces_a_new_layers_placeholder_in_its_creation_step() { assert!(session.undo()); assert!(session.active().unwrap().doc.layer(id).is_none()); } + +#[test] +fn paste_lorem_clamps_both_oversized_character_offsets() { + let mut session = crate::session(); + session.execute("file.new", json!({"width": 300, "height": 120})).unwrap(); + let layer = session.execute("type.create", json!({"x": 20, "y": 70, "text": "é猫Ω"})).unwrap()["layer"].as_u64().unwrap(); + let beyond_wasm32 = u64::from(u32::MAX) + 1; + + let result = session.execute("type.pasteLoremIpsum", json!({"layer": layer, "at": beyond_wasm32, "end": beyond_wasm32})).unwrap(); + + assert_eq!(result["caret"], 3 + LOREM_IPSUM.chars().count()); + assert_eq!(session.execute("type.info", json!({"layer": layer})).unwrap()["text"], format!("é猫Ω{LOREM_IPSUM}")); +} From 2b6a395181c6d9e8973aa6f3cc758dd6fa1a4954 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 20:08:05 -0800 Subject: [PATCH 25/34] Require the complete Lorem Ipsum sample --- crates/engine-core/src/cmd/type_paste_lorem_length_tests.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/engine-core/src/cmd/type_paste_lorem_length_tests.rs b/crates/engine-core/src/cmd/type_paste_lorem_length_tests.rs index fedb3dbf2c..9e3d0f8244 100644 --- a/crates/engine-core/src/cmd/type_paste_lorem_length_tests.rs +++ b/crates/engine-core/src/cmd/type_paste_lorem_length_tests.rs @@ -1,5 +1,7 @@ use serde_json::json; +use super::LOREM_IPSUM; + #[test] fn paste_lorem_adds_one_full_paragraph_without_growing_the_type_box() { let mut session = crate::session(); @@ -12,6 +14,7 @@ fn paste_lorem_adds_one_full_paragraph_without_growing_the_type_box() { let after = session.execute("type.info", json!({"layer": layer})).unwrap(); let filler = after["text"].as_str().unwrap().strip_suffix("Existing").unwrap(); let len = filler.chars().count(); + assert_eq!(filler, LOREM_IPSUM); assert!((950..=1100).contains(&len), "expected about one thousand characters, got {len}"); assert!(filler.starts_with("Lorem ipsum dolor sit amet")); assert!(!filler.contains(['\r', '\n'])); From 6028419c67887a35386806ae0715434661fb2eea Mon Sep 17 00:00:00 2001 From: kubuntugamer Date: Mon, 30 Nov 2026 22:11:38 -0600 Subject: [PATCH 26/34] Background Eraser: the lightest pen pressure erases nothing At pressure 0.01 a 41 px tip is 0.41 px wide, and the dab radius floor lifted it to a half-pixel radius, so the stroke erased a 1 px line while the reference leaves the layer untouched. A Background Eraser stroke whose every point is narrower than half a pixel now paints nothing; pressure 0.05 and up and mouse strokes are unchanged. Fixes #18060 --- crates/paint/src/bg_erase.rs | 17 ++++++ .../src/bg_erase_lowest_pressure_tests.rs | 59 +++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 crates/paint/src/bg_erase_lowest_pressure_tests.rs diff --git a/crates/paint/src/bg_erase.rs b/crates/paint/src/bg_erase.rs index a7597822c3..f0a0ed892b 100644 --- a/crates/paint/src/bg_erase.rs +++ b/crates/paint/src/bg_erase.rs @@ -121,9 +121,22 @@ pub fn background_eraser_stroke(stroke: &Stroke) -> Stroke { let mut stroke = stroke.clone(); stroke.brush.opacity = 1.0; stroke.brush.erase = false; + // The reference leaves the layer untouched at the lightest pen pressure (#18060): when every + // point's tip is narrower than half a pixel the stroke paints nothing. The floor that keeps a + // painted dab half a pixel wide would otherwise erase a 1 px line. A stroke whose pressure + // rises above the threshold keeps today's behaviour throughout, as the item leaves it. + if stroke.points.iter().all(|p| tip_narrower_than_half_a_pixel(&stroke.brush, p)) { + stroke.points.clear(); + } stroke } +/// Whether `p`'s tip diameter is below the half pixel a dab's radius is floored at. +fn tip_narrower_than_half_a_pixel(brush: &crate::BrushSettings, p: &crate::StrokePoint) -> bool { + let step = crate::dynamics::StepInput { point: *p, direction: 0.0, initial_direction: 0.0, step: 0 }; + crate::dynamics::base_diameter(brush, &step) < 0.5 +} + /// One Background Eraser dab's edit of a working copy of `pre` (the target before the stroke): /// shared by [`apply_background_eraser`] and live previews that run the dabs as they come, so both /// erase the same pixels. `None` when `pre` has no alpha channel (nothing can be erased). @@ -306,6 +319,10 @@ mod find_edges_tests; #[path = "bg_erase_decontamination_tests.rs"] mod decontamination_tests; +#[cfg(test)] +#[path = "bg_erase_lowest_pressure_tests.rs"] +mod lowest_pressure_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/paint/src/bg_erase_lowest_pressure_tests.rs b/crates/paint/src/bg_erase_lowest_pressure_tests.rs new file mode 100644 index 0000000000..584d2f4142 --- /dev/null +++ b/crates/paint/src/bg_erase_lowest_pressure_tests.rs @@ -0,0 +1,59 @@ +//! #18060: a Background Eraser stroke at the very lightest pen pressure erases nothing. With Size: +//! Pen Pressure and a 41 px hard tip, the reference application leaves the layer untouched at +//! pressure 0.01, while 0.02 and up paint a thin line; the lightest measurement below is 0.05, +//! which keeps the widths the item records. + +use photocraft_color::PixelFormat; +use photocraft_geom::Rect; +use photocraft_raster::{Surface, from_rgba}; + +use crate::bg_erase::{BgEraseSettings, apply_background_eraser}; +use crate::replace::{Limits, Sampling}; +use crate::{BrushSettings, Stroke, StrokePoint}; + +const GREEN: [f32; 4] = [0.2, 0.6, 0.2, 1.0]; +const Y: f64 = 20.0; + +/// A 60 × 40 flat green field: any erased pixel shows. +fn field() -> Surface { + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(Rect::new(0, 0, 60, 40), &from_rgba(&PixelFormat::RGBA8, GREEN)); + s +} + +/// A constant-pressure horizontal stroke with the measured 41 px hard tip and Size: Pen Pressure. +fn stroke(pressure: f32) -> Stroke { + Stroke { + brush: BrushSettings { size: 41.0, hardness: 1.0, spacing: 0.25, pressure_size: true, ..Default::default() }, + points: (5..=35).map(|x| StrokePoint::new(f64::from(x), Y, pressure)).collect(), + } +} + +fn settings() -> BgEraseSettings { + BgEraseSettings { sampling: Sampling::BackgroundSwatch, limits: Limits::Contiguous, tolerance: 0.5, background: GREEN, ..Default::default() } +} + +/// Done when 1: at pressure 0.01 every pixel's alpha is unchanged. +#[test] +fn the_lightest_pressure_leaves_the_layer_untouched() { + let pre = field(); + let mut s = pre.clone(); + let d = apply_background_eraser(&mut s, &stroke(0.01), &settings(), None).unwrap(); + assert!(d.is_empty(), "nothing was erased: {d:?}"); + assert_eq!(s, pre, "pressure 0.01 leaves the layer untouched"); +} + +/// Done when 2 and 3: 0.05 and above still erase, and a mouse stroke (pressure 1.0) is unchanged. +#[test] +fn pressure_005_and_above_still_erase() { + for (pressure, erased) in [(0.05, false), (0.25, false), (0.5, false), (1.0, true)] { + let mut s = field(); + let d = apply_background_eraser(&mut s, &stroke(pressure), &settings(), None).unwrap(); + assert!(!d.is_empty(), "pressure {pressure} erases"); + let centre = s.rgba(20, Y as i32)[3]; + match erased { + true => assert_eq!(centre, 0.0, "the mouse (pressure 1.0) erases fully: {centre}"), + false => assert!(centre < 1.0, "pressure {pressure} paints a thin line: {centre}"), + } + } +} From a94ee2dad8b75a4b78e24156457cfdb857666f5c Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 20:26:20 -0800 Subject: [PATCH 27/34] Refuse Smart Object conversion in Bitmap and Indexed Color --- crates/engine-core/src/cmd/smart_cmds.rs | 30 +++++---- .../cmd/smart_cmds/indexed_bitmap_tests.rs | 67 +++++++++++++++++++ 2 files changed, 85 insertions(+), 12 deletions(-) create mode 100644 crates/engine-core/src/cmd/smart_cmds/indexed_bitmap_tests.rs diff --git a/crates/engine-core/src/cmd/smart_cmds.rs b/crates/engine-core/src/cmd/smart_cmds.rs index 84e50aa8aa..9959e75cb2 100644 --- a/crates/engine-core/src/cmd/smart_cmds.rs +++ b/crates/engine-core/src/cmd/smart_cmds.rs @@ -161,6 +161,13 @@ fn embed_all_linked(s: &mut Session, _p: &Value) -> Result { fn has_doc(s: &Session) -> std::result::Result<(), String> { s.active().map(|_| ()).ok_or_else(|| "no document open".into()) } +fn can_update_all_contents(s: &Session) -> std::result::Result<(), String> { + let doc = &s.active().ok_or("no document open")?.doc; + if matches!(doc.mode, ColorMode::Bitmap | ColorMode::Indexed) && !doc.walk().iter().any(|(_, _, layer)| matches!(&layer.content, LayerContent::Smart(_))) { + return Err("the document has no smart object".into()); + } + Ok(()) +} fn has_smart_filters(s: &Session) -> std::result::Result<(), String> { if active_smart(s)?.smart_filters.is_empty() { Err("the smart object has no smart filters".into()) } else { Ok(()) } } @@ -172,12 +179,16 @@ fn has_filter_mask(s: &Session) -> std::result::Result<(), String> { active_smart(s)?.filter_mask.as_ref().map(|_| ()).ok_or_else(|| "the smart object has no filter mask".into()) } fn convertible(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or("no document open")?; - let id = d.active_layer.ok_or("no active layer")?; - d.doc.layer(id).map(|_| ()).ok_or_else(|| "no active layer".into()) + let mode = s.active().ok_or("no document open")?.doc.mode; + match mode { + ColorMode::Bitmap => return Err("Convert to Smart Object is unavailable in Bitmap mode".into()), + ColorMode::Indexed => return Err("Convert to Smart Object is unavailable in Indexed Color mode".into()), + _ => {} + } + super::enabled::has_layer(s) } fn not_smart(s: &Session) -> std::result::Result<(), String> { - convertible(s)?; + super::enabled::has_layer(s)?; if active_smart(s).is_ok() { Err("the layer is already a smart object".into()) } else { Ok(()) } } @@ -294,14 +305,7 @@ pub fn specs() -> Vec { |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()), crate::link_watch::update_changed ), - spec!( - "layer.smartObjects.updateAllModifiedContent", - "Update All Modified Content", - SO, - "{}", - |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()), - |s, _| update_all(s) - ), + spec!("layer.smartObjects.updateAllModifiedContent", "Update All Modified Content", SO, "{}", can_update_all_contents, |s, _| update_all(s)), spec!( "layer.smartObjects.convertToLayers", "Convert to Layers", @@ -434,6 +438,8 @@ pub fn specs() -> Vec { mod stack_cache; mod unpack; +#[cfg(test)] +mod indexed_bitmap_tests; #[cfg(test)] mod reset_transform_enabled_tests; #[cfg(test)] diff --git a/crates/engine-core/src/cmd/smart_cmds/indexed_bitmap_tests.rs b/crates/engine-core/src/cmd/smart_cmds/indexed_bitmap_tests.rs new file mode 100644 index 0000000000..4f328b1d82 --- /dev/null +++ b/crates/engine-core/src/cmd/smart_cmds/indexed_bitmap_tests.rs @@ -0,0 +1,67 @@ +use super::{ColorMode, Document, Layer, LayerContent, SO, SampleType, Session, SmartObject, SmartSource, specs}; +use photocraft_color::Color; +use photocraft_geom::{Affine, Size}; +use serde_json::{Value, json}; +use std::sync::Arc; + +const CONVERT: &str = "layer.smartObjects.convertToSmartObject"; +const UPDATE_ALL: &str = "layer.smartObjects.updateAllModifiedContent"; + +fn document(mode: ColorMode, depth: SampleType) -> Document { + Document::with_background("Mode", Size::new(8, 8), mode, depth, Color::rgb(0.5, 0.5, 0.5)) +} + +fn session(doc: Document) -> Session { + let mut s = crate::session(); + s.add_document(doc, None); + s +} + +#[test] +fn bitmap_and_indexed_disable_new_smart_objects_even_with_an_explicit_target() { + for (mode, label) in [(ColorMode::Bitmap, "Bitmap"), (ColorMode::Indexed, "Indexed Color")] { + let mut s = session(document(mode, SampleType::U8)); + for spec in specs().into_iter().filter(|spec| spec.menu == SO) { + assert!(!s.is_enabled(spec.id), "{mode:?} enabled {}", spec.id); + } + + let state = s.active().unwrap(); + let doc = state.doc.clone(); + let active = state.active_layer.unwrap(); + let history = state.history.past_len(); + for params in [Value::Null, json!({"layer": active.0})] { + let refusal = s.execute(CONVERT, params).unwrap_err().to_string(); + assert!(refusal.contains(label), "{refusal}"); + let state = s.active().unwrap(); + assert!(Arc::ptr_eq(&state.doc, &doc)); + assert_eq!(state.active_layer, Some(active)); + assert_eq!(state.history.past_len(), history); + } + } +} + +#[test] +fn supported_document_modes_keep_their_smart_object_commands_at_each_depth() { + for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab, ColorMode::Grayscale] { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let s = session(document(mode, depth)); + assert!(s.is_enabled(CONVERT), "{mode:?}/{depth:?}"); + assert!(s.is_enabled(UPDATE_ALL), "{mode:?}/{depth:?}"); + } + } +} + +#[test] +fn an_existing_smart_object_retains_its_content_commands() { + for mode in [ColorMode::Bitmap, ColorMode::Indexed] { + let mut doc = document(mode, SampleType::U8); + let source = SmartSource::Embedded { file_name: "Existing.pcraft".into(), bytes: Arc::new(Vec::new()) }; + let layer = Layer::new("Existing", LayerContent::Smart(SmartObject::new(source, Affine::translate(0.0, 0.0), None))); + let id = doc.insert_above(None, layer); + let mut s = session(doc); + s.execute("layer.select", json!({"layer": id.0})).unwrap(); + + assert!(s.is_enabled("layer.smartObjects.editContents"), "{mode:?}"); + assert!(s.is_enabled(UPDATE_ALL), "{mode:?}"); + } +} From 1b6f273527b1162a6452a7aad0928d382140d32e Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 20:48:27 -0800 Subject: [PATCH 28/34] Encode untagged 32-bit RGB pixels for Quick Export PNG --- crates/engine-core/src/cmd/web_cmds/quick.rs | 20 +++++- .../cmd/web_cmds/quick_export_32bit_tests.rs | 67 +++++++++++++++++++ 2 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 crates/engine-core/src/cmd/web_cmds/quick_export_32bit_tests.rs diff --git a/crates/engine-core/src/cmd/web_cmds/quick.rs b/crates/engine-core/src/cmd/web_cmds/quick.rs index befb25a554..151b069a17 100644 --- a/crates/engine-core/src/cmd/web_cmds/quick.rs +++ b/crates/engine-core/src/cmd/web_cmds/quick.rs @@ -139,7 +139,21 @@ pub(super) fn quick_export(s: &mut Session, p: &Value) -> Result { let q = Value::Object(o); let st = WebSettings::from_params(&q, cmd)?; let (wdoc, _, _) = web_document(&doc, &json!({}), &st)?; - let buf = photocraft_compose::flatten(&wdoc); + let mut buf = photocraft_compose::flatten(&wdoc); + // A new 32-bit RGB document can be untagged. Encode its linear composite + // when exporting sRGB PNG. Tagged documents use web_document's ICC conversion. + if fmt == "png" + && st.convert_to_srgb + && doc.mode == photocraft_color::ColorMode::Rgb + && doc.depth == photocraft_color::SampleType::F32 + && doc.icc_profile.is_none() + { + for [r, g, b, _] in &mut buf.px { + *r = photocraft_color::convert::linear_to_srgb(*r); + *g = photocraft_color::convert::linear_to_srgb(*g); + *b = photocraft_color::convert::linear_to_srgb(*b); + } + } let xmp = web_xmp(&doc, st.metadata); let exif = web_exif(&doc, st.metadata); let opt = optimize( @@ -157,3 +171,7 @@ pub(super) fn quick_export(s: &mut Session, p: &Value) -> Result { crate::automate_cmds::fire_event(s, "export"); Ok(json!({"path": path, "format": fmt, "bytes": opt.bytes.len(), "warnings": web_warnings(&st, exif, wdoc.resolution_dpi)})) } + +#[cfg(test)] +#[path = "quick_export_32bit_tests.rs"] +mod quick_export_32bit_tests; diff --git a/crates/engine-core/src/cmd/web_cmds/quick_export_32bit_tests.rs b/crates/engine-core/src/cmd/web_cmds/quick_export_32bit_tests.rs new file mode 100644 index 0000000000..49b7eee672 --- /dev/null +++ b/crates/engine-core/src/cmd/web_cmds/quick_export_32bit_tests.rs @@ -0,0 +1,67 @@ +use photocraft_codecs::{ChannelLayout, Image, SampleType}; +use photocraft_doc::Layer; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::Session; + +fn document(depth: u32, background: &str, alpha: f32) -> Session { + let mut session = crate::session(); + session.execute("file.new", json!({"width": 4, "height": 1, "depth": depth, "background": background})).unwrap(); + session + .edit("Paint samples", |doc, _| { + let fmt = doc.pixel_format(); + let mut layer = Layer::raster("Samples", fmt); + let surface = layer.surface_mut().unwrap(); + for (x, rgb) in [(0, [200_u8, 30, 30]), (1, [30, 30, 200]), (2, [0, 0, 0])] { + let [r, g, b] = rgb.map(|v| f32::from(v) / 255.0); + surface.fill_rect(Rect::new(x, 0, x + 1, 1), &photocraft_raster::from_rgba(&fmt, [r, g, b, alpha])); + } + doc.insert_above(None, layer); + Ok(()) + }) + .unwrap(); + assert!(session.active().unwrap().doc.icc_profile.is_none()); + session +} + +fn export_png(session: &mut Session, convert_to_srgb: bool) -> Image { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("quick.png"); + session.execute("file.export.exportPreferences", json!({"convertToSrgb": convert_to_srgb})).unwrap(); + let active = session.active().unwrap(); + let (document, history, dirty) = (active.doc.clone(), active.history.past_len(), active.is_dirty()); + session.execute("file.export.quickExport", json!({"path": path.to_str().unwrap()})).unwrap(); + let active = session.active().unwrap(); + assert_eq!(active.doc, document); + assert_eq!(active.history.past_len(), history); + assert_eq!(active.is_dirty(), dirty); + let encoded = photocraft_codecs::decode(&std::fs::read(path).unwrap()).unwrap(); + assert_eq!(encoded.sample_type(), SampleType::U8); + encoded +} + +#[test] +fn rgb_png_encodes_linear_samples_only_at_32_bits() { + for (depth, high, low) in [(8, 200, 30), (16, 200, 30), (32, 229, 96)] { + let image = export_png(&mut document(depth, "white", 1.0), true); + assert_eq!(image.layout(), ChannelLayout::Rgb, "{depth} bits"); + assert_eq!(image.data(), &[high, low, low, low, low, high, 0, 0, 0, 255, 255, 255], "{depth} bits"); + } +} + +#[test] +fn png_keeps_alpha_and_respects_profile_and_conversion_preferences() { + let image = export_png(&mut document(32, "transparent", 0.5), true); + assert_eq!(image.layout(), ChannelLayout::Rgba); + assert_eq!(&image.data()[..8], &[229, 96, 96, 128, 96, 96, 229, 128]); + + let image = export_png(&mut document(32, "white", 1.0), false); + assert_eq!(&image.data()[..6], &[200, 30, 30, 30, 30, 200]); + + let mut tagged = document(32, "white", 1.0); + tagged.execute("edit.assignProfile", json!({"profile": "srgb"})).unwrap(); + assert!(tagged.active().unwrap().doc.icc_profile.is_some()); + let image = export_png(&mut tagged, true); + assert_eq!(&image.data()[..6], &[200, 30, 30, 30, 30, 200]); +} From 5f9e0593069f41f4e6a86a85df87038acd71ebb9 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 20:58:47 -0800 Subject: [PATCH 29/34] Reject alignment of a group with its own descendants --- .../src/cmd/layer_multi_cmds/align.rs | 18 +++-- .../align_group_own_child_tests.rs | 68 +++++++++++++++++++ 2 files changed, 81 insertions(+), 5 deletions(-) create mode 100644 crates/engine-core/src/cmd/layer_multi_cmds/align_group_own_child_tests.rs diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/align.rs b/crates/engine-core/src/cmd/layer_multi_cmds/align.rs index 7c19de2481..6b8a90d038 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/align.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/align.rs @@ -42,9 +42,9 @@ impl Edge { } } -/// Selected top-level layers that have content bounds, bottom-to-top. -fn bounded_selection(doc: &Document, sel: &[LayerId]) -> Vec<(LayerId, Rect)> { - top_level(doc, sel).into_iter().filter_map(|id| Some((id, align_bounds(doc.layer(id)?, doc.bounds(), doc.pixel_format().sample)?))).collect() +/// Keep layers that have content bounds, in the given order. +fn bounded_layers(doc: &Document, layers: Vec) -> Vec<(LayerId, Rect)> { + layers.into_iter().filter_map(|id| Some((id, align_bounds(doc.layer(id)?, doc.bounds(), doc.pixel_format().sample)?))).collect() } pub(super) fn align(s: &mut Session, p: &Value, kind: &str) -> Result { @@ -63,7 +63,11 @@ pub(super) fn align(s: &mut Session, p: &Value, kind: &str) -> Result { Edge::Right => "Align Right Edges", }; let moved = s.edit(name, |doc, _| { - let items = bounded_selection(doc, &sel); + let roots = top_level(doc, &sel); + if roots.len() != sel.len() { + return Err(EngineError::Other("a group cannot be aligned together with one of its own descendants".into())); + } + let items = bounded_layers(doc, roots); if items.is_empty() { return Err(EngineError::Other("the selected layers have no content to align".into())); } @@ -147,7 +151,7 @@ pub(super) fn distribute(s: &mut Session, kind: &str) -> Result { let kind = kind.to_string(); let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); let moved = s.edit("Distribute", |doc, _| { - let mut items = bounded_selection(doc, &sel); + let mut items = bounded_layers(doc, top_level(doc, &sel)); if items.len() < 3 { return Err(EngineError::Other("distributing needs three or more layers with content".into())); } @@ -191,6 +195,10 @@ pub(super) fn distribute(s: &mut Session, kind: &str) -> Result { Ok(json!({"moved": moved})) } +#[cfg(test)] +#[path = "align_group_own_child_tests.rs"] +mod align_group_own_child_tests; + #[cfg(test)] #[path = "align_history_names_tests.rs"] mod align_history_names_tests; diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/align_group_own_child_tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/align_group_own_child_tests.rs new file mode 100644 index 0000000000..1819c1433e --- /dev/null +++ b/crates/engine-core/src/cmd/layer_multi_cmds/align_group_own_child_tests.rs @@ -0,0 +1,68 @@ +use photocraft_doc::{ColorMode, Document, Layer, LayerId, PixelFormat, SampleType, Size}; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::Session; + +fn paint(name: &str, bounds: Rect) -> Layer { + let mut layer = Layer::raster(name, PixelFormat::RGBA8); + layer.surface_mut().unwrap().fill_rect(bounds, &[1.0, 0.0, 0.0, 1.0]); + layer +} + +fn fixture() -> (Session, LayerId, LayerId, LayerId, LayerId) { + let outside = paint("Outside", Rect::new(4, 4, 10, 12)); + let child = paint("Child", Rect::new(20, 16, 27, 23)); + let (outside_id, child_id) = (outside.id, child.id); + let inner = Layer::group("Inner", vec![child]); + let inner_id = inner.id; + let outer = Layer::group("Outer", vec![inner]); + let outer_id = outer.id; + let mut doc = Document::new("Alignment", Size::new(48, 32), ColorMode::Rgb, SampleType::U8); + doc.layers.push(outside); + doc.layers.push(outer); + let mut session = crate::session(); + session.add_document(doc, None); + (session, outside_id, child_id, inner_id, outer_id) +} + +fn select(session: &mut Session, first: LayerId, second: LayerId) { + session.execute("layer.select", json!({"layer": first.0})).unwrap(); + session.execute("layer.select", json!({"layer": second.0, "mode": "toggle"})).unwrap(); + let selected = session.active().unwrap().selected_layers(); + assert_eq!(selected.len(), 2); + assert!(selected.contains(&first) && selected.contains(&second)); +} + +#[test] +fn alignment_refuses_direct_and_nested_descendants_without_an_edit() { + let (mut session, _, child, inner, outer) = fixture(); + for group in [inner, outer] { + select(&mut session, group, child); + let st = session.active().unwrap(); + let (before, history) = (st.doc.clone(), st.history.past_len()); + for edge in ["topEdges", "verticalCenters", "bottomEdges", "leftEdges", "horizontalCenters", "rightEdges"] { + let command = format!("layer.align.{edge}"); + assert!(session.is_enabled(&command), "{command} menu eligibility stays the same"); + let error = session.execute(&command, json!({})).unwrap_err(); + assert!(error.to_string().contains("a group cannot be aligned together with one of its own descendants"), "{error}"); + let st = session.active().unwrap(); + assert_eq!(st.doc, before); + assert_eq!(st.history.past_len(), history); + } + } +} + +#[test] +fn alignment_moves_a_child_with_an_outside_layer_without_reparenting() { + let (mut session, outside, child, inner, _) = fixture(); + select(&mut session, outside, child); + let history = session.active().unwrap().history.past_len(); + let result = session.execute("layer.align.leftEdges", json!({})).unwrap(); + assert_eq!(result["moved"], 1); + let st = session.active().unwrap(); + assert_eq!(st.doc.layers.index().parent(child), Some(inner)); + assert_eq!(st.doc.layer(child).unwrap().surface().unwrap().content_bounds(), Rect::new(4, 16, 11, 23)); + assert_eq!(st.doc.layer(outside).unwrap().surface().unwrap().content_bounds(), Rect::new(4, 4, 10, 12)); + assert_eq!(st.history.past_len(), history + 1); +} From f5f399c0d64be16dda1d2c60697c858843f28e28 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 21:08:46 -0800 Subject: [PATCH 30/34] Show Move rollover with Auto-Select off and transform controls on --- .../src/move_hover_auto_select_off_tests.rs | 59 +++++++++++++++++++ crates/ui-egui/src/tools/move_hover.rs | 23 +++++--- 2 files changed, 73 insertions(+), 9 deletions(-) create mode 100644 crates/ui-egui/src/move_hover_auto_select_off_tests.rs diff --git a/crates/ui-egui/src/move_hover_auto_select_off_tests.rs b/crates/ui-egui/src/move_hover_auto_select_off_tests.rs new file mode 100644 index 0000000000..a1d6483849 --- /dev/null +++ b/crates/ui-egui/src/move_hover_auto_select_off_tests.rs @@ -0,0 +1,59 @@ +use egui::{Event, Modifiers, PointerButton}; +use photocraft_doc::LayerId; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::guide_cursor_tests::{harness, hover, screen}; +use crate::state::Tool; + +fn paint(app: &mut PhotocraftApp, bounds: Rect) -> LayerId { + let layer = LayerId(app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + app.session + .edit("Paint fixture", |doc, _| { + doc.layer_mut(layer).unwrap().surface_mut().unwrap().fill_rect(bounds, &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + layer +} + +#[test] +fn hover_with_transform_controls_and_auto_select_off_does_not_select_on_click() { + let mut h = harness(Tool::Move); + let app = h.state_mut(); + let bounds = Rect::new(90, 110, 130, 145); + let painted = paint(app, bounds); + paint(app, Rect::new(290, 90, 335, 140)); + app.ui.tool_options.move_auto_select = false; + app.ui.tool_options.move_show_transform = true; + h.run_steps(2); + + hover(&mut h, 110.0, 125.0, Modifiers::NONE); + assert_eq!(h.state().canvas_hover_layer, Some(painted)); + assert_eq!(super::target(h.state_mut(), Some([110.0, 125.0]), false, false), Some(bounds)); + let st = h.state().session.active().unwrap(); + let (before, active, history) = (st.doc.clone(), st.active_layer, st.history.past_len()); + assert_ne!(active, Some(painted)); + let pos = screen(&h, 110.0, 125.0); + for pressed in [true, false] { + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(2); + } + let st = h.state().session.active().unwrap(); + assert_eq!(st.doc, before); + assert_eq!(st.active_layer, active); + assert_eq!(st.history.past_len(), history); + + h.state_mut().ui.tool_options.move_show_transform = false; + hover(&mut h, 110.0, 125.0, Modifiers::NONE); + assert_eq!(h.state().canvas_hover_layer, None); + hover(&mut h, 110.0, 125.0, Modifiers::COMMAND); + assert_eq!(h.state().canvas_hover_layer, Some(painted)); + + h.state_mut().ui.tool_options.move_auto_select = true; + hover(&mut h, 110.0, 125.0, Modifiers::NONE); + assert_eq!(h.state().canvas_hover_layer, Some(painted)); + hover(&mut h, 110.0, 125.0, Modifiers::COMMAND); + assert_eq!(h.state().canvas_hover_layer, None); +} diff --git a/crates/ui-egui/src/tools/move_hover.rs b/crates/ui-egui/src/tools/move_hover.rs index af59be78e4..03d699c6bb 100644 --- a/crates/ui-egui/src/tools/move_hover.rs +++ b/crates/ui-egui/src/tools/move_hover.rs @@ -1,6 +1,6 @@ -//! Move tool › Show Highlight on Rollover (Preferences › Tools, on by default): with Auto-Select -//! on, or ⌘ held while it is off, hovering the canvas outlines the layer (or group, per the -//! Auto-Select target) that a click there would pick. The hit test is the click's own +//! Move tool › Show Highlight on Rollover (Preferences › Tools, on by default): hovering the canvas +//! outlines the layer or group the Auto-Select hit test finds. Show Transform Controls also allows +//! the outline while Auto-Select is off and no modifier is held. The hit test is the click's own //! (`pick_cmds::move_auto_select_target`), so a type layer is outlined anywhere inside its text, as it //! is picked there (#2591). The answer is cached per document revision and pointer pixel: a //! pointer resting on the canvas costs nothing per frame. @@ -14,7 +14,7 @@ use photocraft_geom::Rect; use crate::PhotocraftApp; use crate::state::Tool; -/// The last answer: what a click at `at` on that revision of the document would outline. +/// The cached rollover target at `at` on this document revision. pub(crate) struct Hover { doc: DocId, revision: u64, @@ -25,16 +25,17 @@ pub(crate) struct Hover { } /// The document-space bounds to outline with the pointer at `at` (document px), or `None` when -/// nothing is highlighted: the preference is off, another tool is current, a click wouldn't -/// Auto-Select (it's off without ⌘, or the selected pixels move instead), a button is down (which -/// covers every drag), or a transform is under way. +/// nothing is highlighted: the preference is off, another tool is current, the hover mode is +/// inactive, the selected pixels move instead, a button is down, or a transform is under way. pub(crate) fn target(app: &mut PhotocraftApp, at: Option<[f64; 2]>, command: bool, pressed: bool) -> Option { + let options = &app.ui.tool_options; + let hover_enabled = if options.move_auto_select { !command } else { command || options.move_show_transform }; if !app.session.prefs().tools.show_highlight_on_rollover || app.ui.tool != Tool::Move - || !app.ui.tool_options.move_show_hover_bounds + || !options.move_show_hover_bounds || pressed || app.ui.transform.is_some() - || app.ui.tool_options.move_auto_select == command + || !hover_enabled || crate::move_ui::moves_selected_pixels_with(app, Tool::Move) { app.canvas_hover_layer = None; @@ -122,6 +123,10 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, canvas: egui::Rec HoverOutline::new(tl!("Layer rollover"), shape).show_at(ui, canvas); } +#[cfg(test)] +#[path = "../move_hover_auto_select_off_tests.rs"] +mod move_hover_auto_select_off_tests; + #[cfg(test)] mod tests { use serde_json::json; From ca28a2ab5107a7e7a56c9a9c2c8479d461ba9ccb Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 21:12:01 -0800 Subject: [PATCH 31/34] Keep groups with locked children in place when aligning left or right --- .../src/cmd/layer_multi_cmds/align.rs | 14 +++++ .../align_group_locked_child_tests.rs | 62 +++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 crates/engine-core/src/cmd/layer_multi_cmds/align_group_locked_child_tests.rs diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/align.rs b/crates/engine-core/src/cmd/layer_multi_cmds/align.rs index 7c19de2481..f88ea79110 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/align.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/align.rs @@ -1,3 +1,5 @@ +use photocraft_doc::Layer; + use super::moves::{move_layers, with_links}; use super::selection::{selected, top_level}; use super::{Document, EngineError, LayerId, Rect, Result, Session, Value, bad, json}; @@ -92,6 +94,10 @@ pub(super) fn align(s: &mut Session, p: &Value, kind: &str) -> Result { if target.is_empty() { return Err(EngineError::Other("nothing to align to".into())); } + if matches!(edge, Edge::Left | Edge::Right) && sel.iter().filter_map(|id| doc.layer(*id)).any(has_position_locked_descendant) { + // Left and Right Edges still record their History step when a group cannot move. + return Ok(0); + } let t2 = edge.value2(&target); // A centre can fall on a half pixel, which rounds towards +x / +y (#18282). A selection that is not a plain // rectangle was not measured as the reference and keeps rounding the other way. @@ -113,6 +119,10 @@ pub(super) fn align(s: &mut Session, p: &Value, kind: &str) -> Result { Ok(json!({"moved": moved})) } +fn has_position_locked_descendant(layer: &Layer) -> bool { + layer.children().is_some_and(|children| children.iter().any(|child| child.locks.position || child.locks.all || has_position_locked_descendant(child))) +} + /// Whether a selection selects every pixel of its bounds fully: a rectangle with hard edges. fn plain_rectangle(mask: &photocraft_raster::Surface, bounds: Rect) -> bool { let mut row = vec![0.0; bounds.width() as usize]; @@ -195,6 +205,10 @@ pub(super) fn distribute(s: &mut Session, kind: &str) -> Result { #[path = "align_history_names_tests.rs"] mod align_history_names_tests; +#[cfg(test)] +#[path = "align_group_locked_child_tests.rs"] +mod align_group_locked_child_tests; + #[cfg(test)] #[path = "align_half_pixel_tests.rs"] mod align_half_pixel_tests; diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/align_group_locked_child_tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/align_group_locked_child_tests.rs new file mode 100644 index 0000000000..1ff13c5a21 --- /dev/null +++ b/crates/engine-core/src/cmd/layer_multi_cmds/align_group_locked_child_tests.rs @@ -0,0 +1,62 @@ +use photocraft_doc::{ColorMode, Document, Layer, LayerId, Locks, PixelFormat, SampleType, Size}; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::Session; + +fn paint(name: &str, bounds: Rect) -> Layer { + let mut layer = Layer::raster(name, PixelFormat::RGBA8); + layer.surface_mut().unwrap().fill_rect(bounds, &[1.0, 0.0, 0.0, 1.0]); + layer +} + +fn fixture(locks: Locks, nested: bool) -> (Session, LayerId) { + let outside = paint("Outside", Rect::new(20, 30, 60, 70)); + let outside_id = outside.id; + let mut child = paint("Child", Rect::new(40, 200, 60, 220)); + let child_id = child.id; + child.locks = locks; + let child = if nested { Layer::group("Nested", vec![child]) } else { child }; + let group = Layer::group("Group", vec![child, paint("Sibling", Rect::new(100, 240, 130, 270))]); + let group_id = group.id; + let mut doc = Document::new("Alignment", Size::new(400, 300), ColorMode::Rgb, SampleType::U8); + doc.layers.push(outside); + doc.layers.push(group); + let mut session = crate::session(); + session.add_document(doc, None); + session.execute("layer.select", json!({"layers": [outside_id.0, group_id.0]})).unwrap(); + assert_eq!(session.active().unwrap().selected_layers(), &[outside_id, group_id]); + (session, child_id) +} + +#[test] +fn horizontal_edges_leave_every_layer_in_place_with_a_locked_group_child() { + for (locks, nested) in [(Locks { position: true, ..Locks::default() }, false), (Locks { all: true, ..Locks::default() }, true)] { + let (mut session, _) = fixture(locks, nested); + for (edge, label) in [("leftEdges", "Align Left Edges"), ("rightEdges", "Align Right Edges")] { + let st = session.active().unwrap(); + let (before, history) = (st.doc.clone(), st.history.past_len()); + let result = session.execute(&format!("layer.align.{edge}"), json!({})).unwrap(); + assert_eq!(result["moved"], 0); + let st = session.active().unwrap(); + assert_eq!(st.doc, before); + assert_eq!(st.history.past_len(), history + 1); + assert_eq!(st.history.undo_label(), Some(label)); + } + } +} + +#[test] +fn unlocked_groups_align_and_vertical_alignment_keeps_its_behavior() { + let (mut session, child) = fixture(Locks::default(), false); + let result = session.execute("layer.align.leftEdges", json!({})).unwrap(); + assert_eq!(result["moved"], 1); + let st = session.active().unwrap(); + assert_eq!(st.doc.layer(child).unwrap().surface().unwrap().content_bounds(), Rect::new(20, 200, 40, 220)); + + let (mut session, child) = fixture(Locks { position: true, ..Locks::default() }, false); + let result = session.execute("layer.align.topEdges", json!({})).unwrap(); + assert_eq!(result["moved"], 1); + let st = session.active().unwrap(); + assert_eq!(st.doc.layer(child).unwrap().surface().unwrap().content_bounds(), Rect::new(40, 30, 60, 50)); +} From 38622c0083d7332f895e9d94bee9770b8e9f285a Mon Sep 17 00:00:00 2001 From: dholzric Date: Tue, 1 Dec 2026 01:30:23 -0600 Subject: [PATCH 32/34] Group from Layers: grey it while an artboard is selected (#18190) `can_group_from_layers` in `crates/engine-core/src/cmd/layer_multi_cmds/structure.rs` only refused the Background layer, leaving `layer.new.groupFromLayers` enabled when an artboard was among the selected layers so the dialog opened and then failed on OK with "artboards can't go into a group". Refuse in `can_group_from_layers` with "artboards can't go into a group" whenever any selected layer is an artboard, leaving `group_layers_with` and `layer.groupLayers` unchanged. Co-authored-by: Cursor --- .../group_from_layers_artboard_tests.rs | 143 ++++++++++++++++++ .../src/cmd/layer_multi_cmds/structure.rs | 11 +- 2 files changed, 152 insertions(+), 2 deletions(-) create mode 100644 crates/engine-core/src/cmd/layer_multi_cmds/group_from_layers_artboard_tests.rs diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/group_from_layers_artboard_tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/group_from_layers_artboard_tests.rs new file mode 100644 index 0000000000..e65a23abc4 --- /dev/null +++ b/crates/engine-core/src/cmd/layer_multi_cmds/group_from_layers_artboard_tests.rs @@ -0,0 +1,143 @@ +//! #18190: Layer › New › Group from Layers… (`layer.new.groupFromLayers`) is disabled whenever an +//! artboard is among the selected layers, instead of opening the dialog and failing on OK. + +use photocraft_doc::LayerId; +use serde_json::{Value, json}; + +use crate::{EngineError, Session}; + +const GROUP_FROM_LAYERS: &str = "layer.new.groupFromLayers"; + +fn layer_id(v: Value) -> LayerId { + LayerId(v["layer"].as_u64().unwrap()) +} + +/// Selects `ids` in order, leaving the last one active. +fn select(s: &mut Session, ids: &[LayerId]) { + for (i, id) in ids.iter().enumerate() { + let mode = if i == 0 { "replace" } else { "add" }; + s.execute("layer.select", json!({"layer": id.0, "mode": mode})).unwrap(); + } + assert_eq!(s.active().unwrap().active_layer, ids.last().copied()); +} + +fn snapshot(s: &Session) -> (photocraft_doc::layer_tree::LayerTree, Vec, Option, Vec) { + let d = s.active().unwrap(); + (d.doc.layers.clone(), d.selected_layers().to_vec(), d.active_layer, d.history.entries()) +} + +fn children(s: &Session, group: LayerId) -> Vec { + s.active().unwrap().doc.layer(group).unwrap().children().unwrap().iter().map(|l| l.id).collect() +} + +/// Builds a document with `board_a` (holding `in_a`), empty `board_b`, and a top-level `loose` layer. +fn fixture() -> (Session, LayerId, LayerId, LayerId, LayerId) { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 200, "height": 120, "background": "transparent"})).unwrap(); + let in_a = s.active().unwrap().doc.layers[0].id; + select(&mut s, &[in_a]); + let board_a = layer_id(s.execute("layer.new.artboardFromLayers", json!({"name": "Board A"})).unwrap()); + assert_eq!(s.active().unwrap().doc.artboard_of(in_a), Some(board_a)); + + s.execute("select.deselectLayers", json!({})).unwrap(); + let board_b = layer_id(s.execute("layer.new.artboard", json!({"name": "Board B", "rect": [110, 0, 80, 80]})).unwrap()); + + s.execute("select.deselectLayers", json!({})).unwrap(); + let loose = layer_id(s.execute("layer.new.layer", json!({"name": "Loose"})).unwrap()); + assert_eq!(s.active().unwrap().doc.artboard_of(loose), None); + + (s, board_a, in_a, board_b, loose) +} + +#[test] +fn disabled_and_refused_whenever_an_artboard_is_selected() { + let (mut s, board_a, in_a, board_b, loose) = fixture(); + let selections: &[(&str, &[LayerId])] = &[ + ("artboard alone", &[board_a]), + ("artboard then child", &[board_a, in_a]), + ("child then artboard", &[in_a, board_a]), + ("two artboards (A then B)", &[board_a, board_b]), + ("two artboards (B then A)", &[board_b, board_a]), + ("artboard then loose layer", &[board_a, loose]), + ("loose layer then artboard", &[loose, board_a]), + ]; + + for &(case, ids) in selections { + select(&mut s, ids); + let why = s.disabled_reason(GROUP_FROM_LAYERS); + assert!(why.as_deref().is_some_and(|w| w.contains("artboard")), "{case}: expected disabled reason naming artboards, got {why:?}"); + assert!(!s.is_enabled(GROUP_FROM_LAYERS), "{case}: stays enabled"); + assert!(s.precheck(GROUP_FROM_LAYERS, &json!({})).is_err(), "{case}: precheck must refuse"); + + for params in [json!({}), json!({"name": "Set", "color": "red"})] { + let before = snapshot(&s); + let err = s.execute(GROUP_FROM_LAYERS, params.clone()).unwrap_err(); + assert!(matches!(err, EngineError::Disabled(..)), "{case} {params}: got {err:?}"); + assert!(snapshot(&s) == before, "{case} {params}: changed state"); + } + } + + // Explicit `layer` calls: naming an artboard, or naming a layer in a selection that holds an + // artboard, is refused; naming an ordinary layer outside the selection still groups it alone. + select(&mut s, &[loose]); + let before = snapshot(&s); + assert!(matches!(s.execute(GROUP_FROM_LAYERS, json!({"layer": board_a.0})), Err(EngineError::Disabled(..)))); + assert!(snapshot(&s) == before); + + select(&mut s, &[board_a, in_a]); + let before = snapshot(&s); + assert!(matches!(s.execute(GROUP_FROM_LAYERS, json!({"layer": in_a.0})), Err(EngineError::Disabled(..)))); + assert!(snapshot(&s) == before); + + let g = layer_id(s.execute(GROUP_FROM_LAYERS, json!({"layer": loose.0})).unwrap()); + assert_eq!(children(&s, g), vec![loose]); +} + +#[test] +fn layers_inside_one_or_two_artboards_without_a_selected_artboard_still_group() { + // Inside one artboard. + let mut s = crate::session(); + s.execute("file.new", json!({"width": 200, "height": 120, "background": "transparent"})).unwrap(); + let a1 = s.active().unwrap().doc.layers[0].id; + let a2 = layer_id(s.execute("layer.new.layer", json!({"name": "A2"})).unwrap()); + select(&mut s, &[a1, a2]); + let board = layer_id(s.execute("layer.new.artboardFromLayers", json!({"name": "Board"})).unwrap()); + + select(&mut s, &[a1, a2]); + assert!(s.is_enabled(GROUP_FROM_LAYERS)); + let g = layer_id(s.execute(GROUP_FROM_LAYERS, json!({"name": "InBoard"})).unwrap()); + assert_eq!(s.active().unwrap().doc.artboard_of(g), Some(board)); + assert_eq!(children(&s, g), vec![a1, a2]); + + // Across two artboards, with neither artboard itself selected. + let mut s = crate::session(); + s.execute("file.new", json!({"width": 240, "height": 120, "background": "transparent"})).unwrap(); + let in_a = s.active().unwrap().doc.layers[0].id; + select(&mut s, &[in_a]); + let board_a = layer_id(s.execute("layer.new.artboardFromLayers", json!({"name": "Board A"})).unwrap()); + + s.execute("select.deselectLayers", json!({})).unwrap(); + let in_b = layer_id(s.execute("layer.new.layer", json!({"name": "In B"})).unwrap()); + select(&mut s, &[in_b]); + let board_b = layer_id(s.execute("layer.new.artboardFromLayers", json!({"name": "Board B"})).unwrap()); + + select(&mut s, &[in_a, in_b]); + assert!(s.is_enabled(GROUP_FROM_LAYERS)); + let g = layer_id(s.execute(GROUP_FROM_LAYERS, json!({"name": "Across"})).unwrap()); + assert_eq!(s.active().unwrap().doc.artboard_of(g), Some(board_b)); + assert_eq!(children(&s, g), vec![in_a, in_b]); + assert!(children(&s, board_a).is_empty()); +} + +#[test] +fn group_layers_keeps_todays_behaviour_with_an_artboard_selected() { + let (mut s, board_a, in_a, _, _) = fixture(); + for ids in [&[board_a][..], &[board_a, in_a][..]] { + select(&mut s, ids); + assert!(s.is_enabled("layer.groupLayers"), "not measured: enabled state stays as today"); + let before = snapshot(&s); + let err = s.execute("layer.groupLayers", json!({})).unwrap_err(); + assert!(err.to_string().contains("artboards"), "{err}"); + assert!(snapshot(&s) == before); + } +} diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs b/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs index 2a1f8213e0..e899a90437 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs @@ -111,14 +111,17 @@ pub(crate) fn check_group_depth(doc: &Document, what: &str) -> Result<()> { Ok(()) } -/// Group from Layers is greyed while the Background is among the selected layers, as in the -/// menus (#14709). +/// Group from Layers is greyed while the Background or an artboard is among the selected layers, +/// as in the menus (#14709, #18190). pub(super) fn can_group_from_layers(s: &Session) -> std::result::Result<(), String> { super::has_layer(s)?; let d = s.active().ok_or("no document open")?; if d.selected_layers().iter().any(|id| d.doc.is_background(*id)) { return Err("the Background layer can't go into a group".into()); } + if d.selected_layers().iter().any(|id| d.doc.layer(*id).is_some_and(|l| l.artboard().is_some())) { + return Err("artboards can't go into a group".into()); + } Ok(()) } @@ -426,3 +429,7 @@ pub fn set_visible_selected(s: &mut Session, visible: bool) -> Result { #[cfg(test)] #[path = "group_from_layers_keeps_layer_tags_tests.rs"] mod group_from_layers_keeps_layer_tags_tests; + +#[cfg(test)] +#[path = "group_from_layers_artboard_tests.rs"] +mod group_from_layers_artboard_tests; From 939a21c85ec559bd3e30d8a76af781c8bde15b2d Mon Sep 17 00:00:00 2001 From: dholzric Date: Tue, 1 Dec 2026 01:40:03 -0600 Subject: [PATCH 33/34] Magic Eraser: a contiguous fill stays in the selection's bounding rectangle (#18068) With a selection, magic_eraser found the region on the whole canvas and only clipped the erase to the selection. A fill could then reach another selected part by a path outside the selection, and a click outside it erased inside it. With a selection and Contiguous on, the region is now found inside the selection's bounding rectangle, over selected and unselected pixels alike. A seed outside the rectangle finds nothing and adds no History state. Kept as before (not measured): a selection with partly selected pixels, and Sample All Layers. One existing test clicked outside the bounding rectangle of its selection and expected an erase; its click moved inside the selection. Co-Authored-By: Claude Fable 5.2 --- crates/engine-paint/src/cmd/eraser_cmds.rs | 22 ++- ...raser_contiguous_selection_bounds_tests.rs | 142 ++++++++++++++++++ .../magic_eraser_mode_refusal_tests.rs | 3 +- 3 files changed, 165 insertions(+), 2 deletions(-) create mode 100644 crates/engine-paint/src/cmd/eraser_cmds/magic_eraser_contiguous_selection_bounds_tests.rs diff --git a/crates/engine-paint/src/cmd/eraser_cmds.rs b/crates/engine-paint/src/cmd/eraser_cmds.rs index 5afcaa92c0..c70235018b 100644 --- a/crates/engine-paint/src/cmd/eraser_cmds.rs +++ b/crates/engine-paint/src/cmd/eraser_cmds.rs @@ -133,12 +133,30 @@ fn magic_eraser(s: &mut Session, p: &Value) -> Result { return Ok(damage(s, Rect::EMPTY, false)); } } + /// The bounding rectangle of a selection whose pixels are all fully selected or not selected, on the canvas. + /// `None` for one with partly selected pixels (feathered, anti-aliased), and for an empty one. + fn hard_bounds(selection: &photocraft_raster::Surface, canvas: Rect) -> Option { + let bounds = selection.content_bounds(); + if bounds.is_empty() || selection.default_pixel().first().is_some_and(|v| *v > 0.0) { + return None; + } + let channels = selection.channels().max(1); + let hard = (bounds.y0..bounds.y1).step_by(64).all(|y| { + let rows = Rect::new(bounds.x0, y, bounds.x1, y.saturating_add(64).min(bounds.y1)); + selection.read_region(rows).chunks_exact(channels).all(|px| px[0] <= 0.0 || px[0] >= 1.0) + }); + hard.then(|| bounds.intersect(&canvas)) + } let (area, img) = if sample_all { crate::selection_cmds::sample_rgba8(s, true)? } else { let d = s.active().ok_or(EngineError::NoDocument)?; let surf = d.doc.layer(id).and_then(Layer::surface).ok_or(EngineError::NoLayer(id))?; - (d.doc.bounds(), sel::rgba8_image(surf, d.doc.bounds())) + // #18068: with a selection, a contiguous fill runs inside the selection's bounding rectangle, over selected + // and unselected pixels alike, and a seed outside that rectangle finds nothing. A selection with partly + // selected pixels and Sample All Layers were not measured and keep the whole canvas. + let area = d.doc.selection.as_ref().filter(|_| contiguous).and_then(|m| hard_bounds(m, d.doc.bounds())).unwrap_or_else(|| d.doc.bounds()); + (area, sel::rgba8_image(surf, area)) }; // The reference's colour distance is measured for 8-bit RGB only (#11995). let rgb8 = s.active().is_some_and(|d| d.doc.mode == ColorMode::Rgb && d.doc.depth == SampleType::U8); @@ -337,6 +355,8 @@ pub fn specs() -> Vec { ] } +#[cfg(test)] +mod magic_eraser_contiguous_selection_bounds_tests; #[cfg(test)] mod magic_eraser_mode_refusal_tests; #[cfg(test)] diff --git a/crates/engine-paint/src/cmd/eraser_cmds/magic_eraser_contiguous_selection_bounds_tests.rs b/crates/engine-paint/src/cmd/eraser_cmds/magic_eraser_contiguous_selection_bounds_tests.rs new file mode 100644 index 0000000000..525759a457 --- /dev/null +++ b/crates/engine-paint/src/cmd/eraser_cmds/magic_eraser_contiguous_selection_bounds_tests.rs @@ -0,0 +1,142 @@ +//! #18068: with a selection and Contiguous on, the Magic Eraser's fill stays inside the selection's bounding +//! rectangle, over selected and unselected pixels alike, so it cannot reach another selected part by a path outside +//! it, and a click outside that rectangle erases nothing. The documents are the issue's, at a tenth of the size. +//! Not measured, so as before: a selection with partly selected pixels, and Sample All Layers. + +use serde_json::{Value, json}; + +use crate::Session; + +/// Red inside selection A and inside selection B, on the bar. +const IN_A: (i32, i32) = (10, 30); +const IN_B: (i32, i32) = (70, 30); +/// On the bar between A and B's side of the cut: inside the bounding rectangle, not selected. +const BESIDE_A: (i32, i32) = (25, 30); +/// The middle of the bar, between A and B: red when the bar is not cut. +const BETWEEN: (i32, i32) = (40, 30); +/// The top of the arch, above the bounding rectangle. +const ON_THE_ARCH: (i32, i32) = (40, 6); +/// White above the bounding rectangle, joined to the white of A and B above the bar. +const WHITE_ABOVE: (i32, i32) = (40, 12); +/// White inside A, above the bar. +const WHITE_IN_A: (i32, i32) = (10, 22); + +fn fill(s: &mut Session, [x, y, w, h]: [i32; 4], color: &str) { + s.execute("select.rect", json!({"x": x, "y": y, "width": w, "height": h, "antiAlias": false})).unwrap(); + s.execute("edit.fill", json!({"color": color})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); +} + +/// An 80 x 45 white document with a red bar across rows 25 to 35. +fn uncut_bar() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 80, "height": 45, "mode": "rgb", "depth": 8, "background": "#ffffff"})).unwrap(); + fill(&mut s, [0, 25, 80, 10], "#ff0000"); + s +} + +/// The bar cut between x 35 and 45, its two halves joined only by a red arch that rises to row 5, above the bounding +/// rectangle of the selections. +fn cut_bar() -> Session { + let mut s = uncut_bar(); + fill(&mut s, [35, 25, 10, 10], "#ffffff"); + for arch in [[30, 5, 3, 20], [47, 5, 3, 20], [30, 5, 20, 3]] { + fill(&mut s, arch, "#ff0000"); + } + s +} + +/// Selections A (x 0 to 20) and B (x 60 to 80), rows 20 to 40: their bounding rectangle is the full width of those +/// rows. +fn select_a_and_b(s: &mut Session) { + s.execute("select.rect", json!({"x": 0, "y": 20, "width": 20, "height": 20})).unwrap(); + s.execute("select.rect", json!({"x": 60, "y": 20, "width": 20, "height": 20, "mode": "add"})).unwrap(); +} + +fn erase(s: &mut Session, (x, y): (i32, i32), options: Value) -> Value { + let mut p = json!({"x": x, "y": y}); + p.as_object_mut().unwrap().extend(options.as_object().unwrap().clone()); + s.execute("paint.magicEraser", p).unwrap() +} + +fn alpha(s: &Session, (x, y): (i32, i32)) -> f32 { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)[3] +} + +/// How many History states there are, and the name of the newest. +fn history(s: &Session) -> (usize, Option) { + let history = &s.active().unwrap().history; + (history.past_len(), history.undo_label().map(String::from)) +} + +#[test] +fn a_contiguous_fill_cannot_reach_another_selected_part_round_the_outside() { + for anti_alias in [true, false] { + let mut s = cut_bar(); + select_a_and_b(&mut s); + let states = history(&s).0; + let reply = erase(&mut s, IN_A, json!({"antiAlias": anti_alias})); + assert_eq!(reply["erased"], true, "anti-alias {anti_alias}"); + assert_eq!(alpha(&s, IN_A), 0.0, "anti-alias {anti_alias}: the red of A is erased"); + assert_eq!(alpha(&s, IN_B), 1.0, "anti-alias {anti_alias}: B is only joined to A by the arch, outside the rectangle"); + assert_eq!(alpha(&s, BESIDE_A), 1.0, "anti-alias {anti_alias}: the erase stays clipped to the selection"); + assert_eq!(history(&s), (states + 1, Some("Magic Eraser".into())), "anti-alias {anti_alias}"); + } +} + +#[test] +fn a_seed_outside_the_bounding_rectangle_erases_nothing() { + for (mut s, seed, case) in [(cut_bar(), ON_THE_ARCH, "the arch"), (uncut_bar(), WHITE_ABOVE, "white above the rectangle")] { + select_a_and_b(&mut s); + let (before, states) = (s.active().unwrap().doc.clone(), history(&s)); + let reply = erase(&mut s, seed, json!({})); + assert_eq!(reply, json!({"erased": false, "damage": [0, 0, 0, 0]}), "{case}"); + assert!(s.active().unwrap().doc == before, "{case}: nothing changed"); + assert_eq!(history(&s), states, "{case}: no History state"); + } +} + +#[test] +fn a_seed_in_the_rectangle_erases_the_selected_part_of_its_region() { + // The uncut bar joins A and B inside the rectangle, through pixels that are not selected. + for (seed, case) in [(BETWEEN, "between A and B"), (IN_A, "inside A")] { + let mut s = uncut_bar(); + select_a_and_b(&mut s); + let states = history(&s).0; + erase(&mut s, seed, json!({})); + assert_eq!((alpha(&s, IN_A), alpha(&s, IN_B)), (0.0, 0.0), "{case}: the red of A and B is erased"); + assert_eq!(alpha(&s, BETWEEN), 1.0, "{case}: the unselected red stays"); + assert_eq!(alpha(&s, WHITE_IN_A), 1.0, "{case}: the white of A stays"); + assert_eq!(history(&s), (states + 1, Some("Magic Eraser".into())), "{case}"); + } +} + +#[test] +fn contiguous_off_and_no_selection_keep_the_whole_canvas() { + // Contiguous off: every matching pixel, so the rectangle plays no part. + let mut s = cut_bar(); + select_a_and_b(&mut s); + erase(&mut s, ON_THE_ARCH, json!({"contiguous": false})); + assert_eq!((alpha(&s, IN_A), alpha(&s, IN_B)), (0.0, 0.0), "Contiguous off erases the matching red of A and B"); + + // No selection: the fill follows the arch. + let mut s = cut_bar(); + erase(&mut s, IN_A, json!({})); + assert_eq!((alpha(&s, ON_THE_ARCH), alpha(&s, IN_B)), (0.0, 0.0), "without a selection the whole joined red is erased"); +} + +/// Not measured, so as before: the region is found on the whole canvas and reaches B round the arch. +#[test] +fn a_soft_selection_and_sample_all_layers_keep_the_whole_canvas() { + let mut s = cut_bar(); + select_a_and_b(&mut s); + s.execute("select.modify.feather", json!({"radius": 1})).unwrap(); + erase(&mut s, IN_A, json!({})); + assert_eq!((alpha(&s, IN_A), alpha(&s, IN_B)), (0.0, 0.0), "a feathered selection"); + + let mut s = cut_bar(); + select_a_and_b(&mut s); + erase(&mut s, IN_A, json!({"sampleAllLayers": true})); + assert_eq!((alpha(&s, IN_A), alpha(&s, IN_B)), (0.0, 0.0), "Sample All Layers"); +} diff --git a/crates/engine-paint/src/cmd/eraser_cmds/magic_eraser_mode_refusal_tests.rs b/crates/engine-paint/src/cmd/eraser_cmds/magic_eraser_mode_refusal_tests.rs index 338463626a..3eff9f4292 100644 --- a/crates/engine-paint/src/cmd/eraser_cmds/magic_eraser_mode_refusal_tests.rs +++ b/crates/engine-paint/src/cmd/eraser_cmds/magic_eraser_mode_refusal_tests.rs @@ -96,7 +96,8 @@ fn duotone_and_multichannel_keep_todays_behaviour() { for (case, mode) in [("Duotone", photocraft_color::ColorMode::Duotone), ("Multichannel", photocraft_color::ColorMode::Multichannel)] { let mut s = session(mode, SampleType::U8); let id = s.active().unwrap().active_layer.unwrap(); - let r = s.execute("paint.magicEraser", json!({"x": 2, "y": 2, "antiAlias": false})); + // Inside the selection: a click outside its bounding rectangle erases nothing (#18068). + let r = s.execute("paint.magicEraser", json!({"x": 12, "y": 12, "antiAlias": false})); assert!(r.is_ok(), "{case}: keeps today's behaviour, answers {r:?}"); assert_eq!(r.unwrap()["erased"], true, "{case}"); assert_eq!(s.active().unwrap().doc.layer(id).unwrap().name, "Layer 0", "{case}"); From a67b3344ecc3320cbed0be72062ee8adc8038b8d Mon Sep 17 00:00:00 2001 From: dholzric Date: Tue, 1 Dec 2026 01:43:18 -0600 Subject: [PATCH 34/34] Move: allow multi-layer moves when the active layer is hidden (#18136) `hidden_target::refusal` in `crates/engine-core/src/hidden_target.rs` checked only the active layer for `layer.translate`, refusing Move drags, Alt+drags, and arrow nudges with "Could not complete your request because the target layer is hidden." whenever a hidden layer happened to be active in a multi-layer selection. Allow `layer.translate` when no explicit `layer` parameter is given and two or more layers are selected, keeping the refusal for a single hidden layer selected alone and for calls that explicitly name a hidden layer. Co-authored-by: Cursor --- .../move_hidden_in_selection_tests.rs | 130 ++++++++++++++++++ crates/engine-core/src/hidden_target.rs | 7 + 2 files changed, 137 insertions(+) create mode 100644 crates/engine-core/src/cmd/layer_multi_cmds/move_hidden_in_selection_tests.rs diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/move_hidden_in_selection_tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/move_hidden_in_selection_tests.rs new file mode 100644 index 0000000000..f8608ca536 --- /dev/null +++ b/crates/engine-core/src/cmd/layer_multi_cmds/move_hidden_in_selection_tests.rs @@ -0,0 +1,130 @@ +//! #18136: Moving a multi-layer selection moves every selected layer, hidden ones included, even +//! when the active layer is hidden. Moving a single hidden layer alone, or an explicitly named +//! hidden layer, keeps the hidden-target refusal. + +use photocraft_doc::LayerId; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::Session; +use crate::hidden_target::{HIDDEN, refusal}; + +fn painted_layer(s: &mut Session, name: &str, rect: Rect) -> LayerId { + let id = LayerId(s.execute("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap()); + s.edit("paint", |doc, _| { + doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(rect, &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + id +} + +fn select(s: &mut Session, ids: &[LayerId]) { + for (i, id) in ids.iter().enumerate() { + let mode = if i == 0 { "replace" } else { "add" }; + s.execute("layer.select", json!({"layer": id.0, "mode": mode})).unwrap(); + } + assert_eq!(s.active().unwrap().active_layer, ids.last().copied()); +} + +fn bounds(s: &Session, id: LayerId) -> Option { + crate::damage::layer_bounds(s.active().unwrap().doc.layer(id).unwrap()) +} + +fn three_layer_doc() -> (Session, LayerId, LayerId, LayerId) { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 1000, "height": 700, "background": "white"})).unwrap(); + let a = painted_layer(&mut s, "A", Rect::new(10, 20, 50, 60)); + let b = painted_layer(&mut s, "B", Rect::new(80, 90, 130, 140)); + let h = painted_layer(&mut s, "Hidden", Rect::new(100, 450, 200, 500)); + s.execute("layer.setProps", json!({"layer": h.0, "visible": false})).unwrap(); + (s, a, b, h) +} + +#[test] +fn multi_layer_selection_moves_every_layer_when_the_active_layer_is_hidden() { + for hidden_active in [true, false] { + let (mut s, a, b, h) = three_layer_doc(); + let order = if hidden_active { [a, b, h] } else { [h, a, b] }; + select(&mut s, &order); + + assert_eq!(refusal(&s, "layer.translate", &json!({})), None, "hidden_active={hidden_active}"); + let (ra, rb, rh) = (bounds(&s, a).unwrap(), bounds(&s, b).unwrap(), bounds(&s, h).unwrap()); + let steps = s.active().unwrap().history.past_len(); + + s.execute("layer.translate", json!({"dx": 100, "dy": 50})).unwrap(); + + assert_eq!(bounds(&s, a), Some(ra.translate(100, 50))); + assert_eq!(bounds(&s, b), Some(rb.translate(100, 50))); + assert_eq!(bounds(&s, h), Some(rh.translate(100, 50))); + let doc = &s.active().unwrap().doc; + assert!(!doc.layer(h).unwrap().visible, "the hidden layer stays hidden"); + assert!(doc.layer(a).unwrap().visible && doc.layer(b).unwrap().visible); + let hist = &s.active().unwrap().history; + assert_eq!((hist.past_len(), hist.undo_label()), (steps + 1, Some("Move"))); + } + + // A layer hidden through a hidden parent group also moves when selected with another layer, + // and two hidden layers selected together follow the same multi-layer rule. + let mut s = crate::session(); + s.execute("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); + let vis = painted_layer(&mut s, "Visible", Rect::new(10, 10, 30, 30)); + let nested = painted_layer(&mut s, "Nested", Rect::new(40, 40, 60, 60)); + select(&mut s, &[nested]); + let group = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.setProps", json!({"layer": group.0, "visible": false})).unwrap(); + + select(&mut s, &[vis, nested]); + let (rv, rn) = (bounds(&s, vis).unwrap(), bounds(&s, nested).unwrap()); + s.execute("layer.translate", json!({"dx": 15, "dy": 25})).unwrap(); + assert_eq!((bounds(&s, vis), bounds(&s, nested)), (Some(rv.translate(15, 25)), Some(rn.translate(15, 25)))); + + s.execute("layer.setProps", json!({"layer": vis.0, "visible": false})).unwrap(); + select(&mut s, &[vis, nested]); + let (rv, rn) = (bounds(&s, vis).unwrap(), bounds(&s, nested).unwrap()); + s.execute("layer.translate", json!({"dx": 5, "dy": 10})).unwrap(); + assert_eq!((bounds(&s, vis), bounds(&s, nested)), (Some(rv.translate(5, 10)), Some(rn.translate(5, 10)))); +} + +#[test] +fn a_single_hidden_layer_alone_is_still_refused() { + let (mut s, _, _, h) = three_layer_doc(); + select(&mut s, &[h]); + let rh = bounds(&s, h); + let steps = s.active().unwrap().history.past_len(); + + assert_eq!(refusal(&s, "layer.translate", &json!({})), Some(HIDDEN)); + let err = s.execute("layer.translate", json!({"dx": 100, "dy": 50})).unwrap_err().to_string(); + assert!(err.contains(HIDDEN), "{err}"); + assert_eq!(bounds(&s, h), rh); + assert_eq!(s.active().unwrap().history.past_len(), steps); + + // A single layer hidden through its parent group is still refused too. + let child = painted_layer(&mut s, "InGroup", Rect::new(20, 20, 40, 40)); + select(&mut s, &[child]); + let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.setProps", json!({"layer": g.0, "visible": false})).unwrap(); + select(&mut s, &[child]); + let rc = bounds(&s, child); + let steps = s.active().unwrap().history.past_len(); + assert_eq!(refusal(&s, "layer.translate", &json!({})), Some(HIDDEN)); + assert!(s.execute("layer.translate", json!({"dx": 10, "dy": 10})).unwrap_err().to_string().contains(HIDDEN)); + assert_eq!(bounds(&s, child), rc); + assert_eq!(s.active().unwrap().history.past_len(), steps); +} + +#[test] +fn an_explicit_hidden_layer_param_is_still_refused() { + let (mut s, a, b, h) = three_layer_doc(); + for order in [[a, b, h], [h, a, b]] { + select(&mut s, &order); + let before = s.active().unwrap().doc.clone(); + let steps = s.active().unwrap().history.past_len(); + for layer in [json!(h.0), json!("Hidden")] { + let err = s.execute("layer.translate", json!({"layer": layer, "dx": 100, "dy": 50})).unwrap_err().to_string(); + assert!(err.contains(HIDDEN), "{err}"); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.past_len(), steps); + } + } +} diff --git a/crates/engine-core/src/hidden_target.rs b/crates/engine-core/src/hidden_target.rs index 8eaaed25e1..3f98d93481 100644 --- a/crates/engine-core/src/hidden_target.rs +++ b/crates/engine-core/src/hidden_target.rs @@ -55,9 +55,16 @@ pub fn refusal(s: &Session, id: &str, params: &Value) -> Option<&'static str> { return None; } let st = s.active()?; + if id == "layer.translate" && matches!(crate::commands::explicit_layer(s, ¶ms), Ok(None)) && st.selected_layers().len() > 1 { + return None; + } let layer = crate::commands::layer_param(s, ¶ms).ok()?; // The Art History Brush's text was measured on a layer's pixels only. let pixels = crate::channel_cmds::target_of(¶ms) == crate::channel_cmds::Target::Pixels; let why = if id == "paint.artHistoryBrush" && pixels { ART_HISTORY_HIDDEN } else { HIDDEN }; (st.doc.layer(layer).is_some() && !shown(&st.doc, layer)).then_some(why) } + +#[cfg(test)] +#[path = "cmd/layer_multi_cmds/move_hidden_in_selection_tests.rs"] +mod move_hidden_in_selection_tests;