From c39de363431a0827d8cf21be4a4bdc697e28960f Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 12 Oct 2026 15:09:40 +0200 Subject: [PATCH 01/44] History Options: Automatically Create First Snapshot, New Snapshot When Saving, Show New Snapshot Dialog by Default (#2966) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The three snapshot options of History panel ☰ › History Options… that #3535 leaves out, as in Photoshop. Builds on #3567 (first snapshot, New Snapshot dialog) and #3535 (History Options dialog), which this branch merges. Co-Authored-By: Claude Opus 5.5 (1M context) --- Cargo.lock | 1 + crates/automation/src/headless.rs | 2 + crates/automation/tests/save_snapshot.rs | 47 +++++ crates/engine/Cargo.toml | 3 + crates/engine/src/history_options_cmds.rs | 198 +++++++++++++++++++--- crates/engine/src/lib.rs | 8 +- crates/engine/src/prefs.rs | 21 ++- crates/ui-egui/src/history_options_ui.rs | 41 +++-- crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/panels.rs | 73 +++++++- crates/ui-egui/src/view_cmds.rs | 7 +- docs/control-protocol.md | 2 +- docs/scorecard.md | 4 +- docs/ui-parity.md | 5 +- 21 files changed, 393 insertions(+), 42 deletions(-) create mode 100644 crates/automation/tests/save_snapshot.rs diff --git a/Cargo.lock b/Cargo.lock index 160403c482..412e6676f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4349,6 +4349,7 @@ name = "photocraft-engine" version = "0.8.0" dependencies = [ "blake3", + "chrono", "exr", "flate2", "photocraft-affinity", diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index cd92f584a2..e1745391a1 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -268,6 +268,8 @@ impl Headless { if let Some(st) = self.session.active_mut() { st.saved_to(target.to_string_lossy().into_owned()); } + // History Options › Automatically Create New Snapshot When Saving (#2966). + photocraft_engine::history_options_cmds::snapshot_on_save(&mut self.session); if let Some(active) = previously_active { self.session.set_active(active); } diff --git a/crates/automation/tests/save_snapshot.rs b/crates/automation/tests/save_snapshot.rs new file mode 100644 index 0000000000..95c922c4a3 --- /dev/null +++ b/crates/automation/tests/save_snapshot.rs @@ -0,0 +1,47 @@ +//! History Options › Automatically Create New Snapshot When Saving (#2966) through the headless +//! server: a save of the document to its own layered file adds a snapshot when the option is on; +//! a flat export is a copy and adds none, and with the option off no save does. + +use photocraft_automation::Headless; +use serde_json::json; + +fn tmp() -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!( + "pc-save-snapshot-{}-{}", + std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn snapshots(h: &Headless) -> usize { + h.session.active().unwrap().snapshots.len() +} + +#[test] +fn a_document_save_adds_a_snapshot_only_with_the_option() { + let dir = tmp(); + let psd = dir.join("a.psd"); + let png = dir.join("a.png"); + let mut h = Headless::trusted_local(); + h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + assert_eq!(snapshots(&h), 1, "the first snapshot"); + + // Off (the default): saving adds nothing. + h.handle("doc.save", json!({"path": psd.to_str().unwrap()})).unwrap(); + assert_eq!(snapshots(&h), 1); + + h.handle("engine.execute", json!({"command": "history.options", "params": {"automaticallyCreateNewSnapshotWhenSaving": true}})).unwrap(); + h.handle("engine.execute", json!({"command": "image.adjustments.invert", "params": {}})).unwrap(); + h.handle("doc.save", json!({})).unwrap(); + assert_eq!(snapshots(&h), 2, "the save added one"); + let st = h.session.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&st.snapshots[1].doc, &st.doc), "of the document as saved"); + assert!(!st.is_dirty(), "and the document stays saved"); + + // A flat export is a copy, not a save of the document. + h.handle("doc.save", json!({"path": png.to_str().unwrap()})).unwrap(); + assert_eq!(snapshots(&h), 2); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index d15e0f985a..21375c4131 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -40,6 +40,9 @@ roxmltree = "0.20" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] tempfile = "3" +# The local time that names History Options' snapshot on save (#2966); already in the tree +# through rmcp. The web build has no local clock here and names it "Snapshot N". +chrono = { version = "0.4", default-features = false, features = ["clock"] } [dev-dependencies] photocraft-affinity = { workspace = true, features = ["synth"] } diff --git a/crates/engine/src/history_options_cmds.rs b/crates/engine/src/history_options_cmds.rs index 88cec69f6e..c812b0d6d0 100644 --- a/crates/engine/src/history_options_cmds.rs +++ b/crates/engine/src/history_options_cmds.rs @@ -1,35 +1,96 @@ -//! History panel › History Options… (#2966): Allow Non-Linear History and Make Layer Visibility -//! Changes Undoable. The values are preferences (`historyOptions.*`, also `prefs.set`), applied -//! by [`Session::apply_prefs`] and [`Session::edit_visibility`]. Without params the command -//! reports them; the GUI opens its dialog instead and runs it with the dialog's values on OK. -//! -//! Photoshop's three snapshot options (Automatically Create First Snapshot, Automatically -//! Create New Snapshot When Saving, Show New Snapshot Dialog by Default) are not here: snapshots -//! are not implemented, and a checkbox that does nothing is worse than a missing one. +//! History panel › History Options… (#2966), Photoshop's five checkboxes: Automatically Create +//! First Snapshot, Automatically Create New Snapshot When Saving, Allow Non-Linear History, Show +//! New Snapshot Dialog by Default and Make Layer Visibility Changes Undoable. The values are +//! preferences (`historyOptions.*`, also `prefs.set`), applied by [`Session::add_document`], +//! [`snapshot_on_save`], [`Session::apply_prefs`], [`Session::edit_visibility`] and the GUI's +//! camera button. Without params the command reports them; the GUI opens its dialog instead and +//! runs it with the dialog's values on OK. use serde_json::{Map, Value}; use crate::commands::CommandSpec; +use crate::history_cmds::Snapshot; +use crate::prefs::HistoryOptions; use crate::{EngineError, Result, Session}; const CMD: &str = "history.options"; -/// The option keys, as in `prefs.get historyOptions` and the command's params. -pub const OPTIONS: [&str; 2] = ["allowNonLinearHistory", "makeLayerVisibilityChangesUndoable"]; +/// The option keys, as in `prefs.get historyOptions` and the command's params, in the order of +/// Photoshop's dialog. +pub const OPTIONS: [&str; 5] = [ + "automaticallyCreateFirstSnapshot", + "automaticallyCreateNewSnapshotWhenSaving", + "allowNonLinearHistory", + "showNewSnapshotDialogByDefault", + "makeLayerVisibilityChangesUndoable", +]; + +/// The option named `key` (one of [`OPTIONS`]). +fn option_mut<'a>(o: &'a mut HistoryOptions, key: &str) -> Option<&'a mut bool> { + Some(match key { + "automaticallyCreateFirstSnapshot" => &mut o.automatically_create_first_snapshot, + "automaticallyCreateNewSnapshotWhenSaving" => &mut o.automatically_create_new_snapshot_when_saving, + "allowNonLinearHistory" => &mut o.allow_non_linear_history, + "showNewSnapshotDialogByDefault" => &mut o.show_new_snapshot_dialog_by_default, + "makeLayerVisibilityChangesUndoable" => &mut o.make_layer_visibility_changes_undoable, + _ => return None, + }) +} fn bad(msg: impl Into) -> EngineError { EngineError::BadParams { cmd: CMD.into(), msg: msg.into() } } -/// The current History Options as `{allowNonLinearHistory, makeLayerVisibilityChangesUndoable}`. +/// The current History Options, keyed by [`OPTIONS`]. pub fn current(s: &Session) -> Value { let o = &s.prefs().history_options; serde_json::json!({ + "automaticallyCreateFirstSnapshot": o.automatically_create_first_snapshot, + "automaticallyCreateNewSnapshotWhenSaving": o.automatically_create_new_snapshot_when_saving, "allowNonLinearHistory": o.allow_non_linear_history, + "showNewSnapshotDialogByDefault": o.show_new_snapshot_dialog_by_default, "makeLayerVisibilityChangesUndoable": o.make_layer_visibility_changes_undoable, }) } +/// History Options › Show New Snapshot Dialog by Default: whether a plain click on the History +/// panel's camera button opens New Snapshot. +pub fn show_new_snapshot_dialog(s: &Session) -> bool { + s.prefs().history_options.show_new_snapshot_dialog_by_default +} + +/// History Options › Automatically Create New Snapshot When Saving: after the active document +/// was saved to its own file (not a copy or an export), add a snapshot of it named with the local +/// time of the save, as Photoshop does. Not a history state. Returns the new snapshot's id, or +/// `None` when the option is off or no document is active. Shells call it where they record a +/// document save. +pub fn snapshot_on_save(s: &mut Session) -> Option { + if !s.prefs().history_options.automatically_create_new_snapshot_when_saving { + return None; + } + let st = s.active_mut()?; + let name = save_snapshot_name().unwrap_or_else(|| crate::history_cmds::next_snapshot_name(st)); + let id = st.next_snapshot; + st.next_snapshot = id.saturating_add(1); + let (doc, layers) = (st.doc.clone(), st.layer_target()); + // Like the camera button: the document and its saved state are unchanged. + st.snapshots.push(Snapshot { id, name, doc, layers }); + Some(id) +} + +/// The local time as `HH:MM:SS`, the name of a snapshot made on save; `None` without a clock +/// (the web build), where the snapshot gets the camera button's "Snapshot N" instead. +fn save_snapshot_name() -> Option { + #[cfg(not(target_arch = "wasm32"))] + { + Some(chrono::Local::now().format("%H:%M:%S").to_string()) + } + #[cfg(target_arch = "wasm32")] + { + None + } +} + fn options(s: &mut Session, p: &Value) -> Result { let given: Map = match p { Value::Null => Map::new(), @@ -39,7 +100,7 @@ fn options(s: &mut Session, p: &Value) -> Result { // Validate everything before changing anything. let mut set = Vec::new(); for (k, v) in &given { - if !OPTIONS.contains(&k.as_str()) { + if option_mut(&mut HistoryOptions::default(), k).is_none() { return Err(bad(format!("unknown option `{k}` (expected {})", OPTIONS.join(", ")))); } let b = v.as_bool().ok_or_else(|| bad(format!("`{k}` must be true or false")))?; @@ -48,9 +109,8 @@ fn options(s: &mut Session, p: &Value) -> Result { if !set.is_empty() { s.edit_prefs(|prefs| { for (k, b) in &set { - match k.as_str() { - "allowNonLinearHistory" => prefs.history_options.allow_non_linear_history = *b, - _ => prefs.history_options.make_layer_visibility_changes_undoable = *b, + if let Some(o) = option_mut(&mut prefs.history_options, k) { + *o = *b; } } }); @@ -103,7 +163,7 @@ pub fn specs() -> Vec { label: "History Options…", menu: &[], shortcut: None, - params: r##"{"allowNonLinearHistory":bool?,"makeLayerVisibilityChangesUndoable":bool?} → both values (no params: report them). Allow Non-Linear History: an edit after stepping back keeps the later states and is appended at the end; deleting a state deletes only it (default off). Make Layer Visibility Changes Undoable: showing or hiding a layer is a history state (default on). Also `prefs.set historyOptions.*`"##, + params: r##"{"automaticallyCreateFirstSnapshot":bool?,"automaticallyCreateNewSnapshotWhenSaving":bool?,"allowNonLinearHistory":bool?,"showNewSnapshotDialogByDefault":bool?,"makeLayerVisibilityChangesUndoable":bool?} → all five values (no params: report them). Automatically Create First Snapshot: a new or opened document starts with a snapshot of itself, named after it (default on). Automatically Create New Snapshot When Saving: each save of the document (not a copy) adds a snapshot named with the time of the save (default off). Allow Non-Linear History: an edit after stepping back keeps the later states and is appended at the end; deleting a state deletes only it (default off). Show New Snapshot Dialog by Default: a click on the History panel's camera button opens New Snapshot, not only ⌥-click (default off). Make Layer Visibility Changes Undoable: showing or hiding a layer is a history state (default on). Also `prefs.set historyOptions.*`"##, enabled: always, run: options, journal: false, @@ -131,10 +191,21 @@ mod tests { #[test] fn defaults_match_photoshop_and_round_trip_through_prefs() { let mut s = Session::new(); - assert_eq!(s.execute(CMD, json!({})).unwrap(), json!({"allowNonLinearHistory": false, "makeLayerVisibilityChangesUndoable": true})); + let defaults = json!({ + "automaticallyCreateFirstSnapshot": true, + "automaticallyCreateNewSnapshotWhenSaving": false, + "allowNonLinearHistory": false, + "showNewSnapshotDialogByDefault": false, + "makeLayerVisibilityChangesUndoable": true, + }); + assert_eq!(s.execute(CMD, json!({})).unwrap(), defaults); assert_eq!(s.execute("prefs.get", json!({"path": "historyOptions"})).unwrap(), current(&s)); - let r = s.execute(CMD, json!({"allowNonLinearHistory": true, "makeLayerVisibilityChangesUndoable": false})).unwrap(); - assert_eq!(r, json!({"allowNonLinearHistory": true, "makeLayerVisibilityChangesUndoable": false})); + let flipped: Map = defaults.as_object().unwrap().iter().map(|(k, v)| (k.clone(), json!(!v.as_bool().unwrap()))).collect(); + let r = s.execute(CMD, Value::Object(flipped.clone())).unwrap(); + assert_eq!(r, Value::Object(flipped)); + for key in OPTIONS { + assert_eq!(s.execute("prefs.get", json!({"path": format!("historyOptions.{key}")})).unwrap(), r[key], "{key}"); + } assert_eq!(s.execute("prefs.get", json!({"path": "historyOptions.allowNonLinearHistory"})).unwrap(), json!(true)); // Saved and restored with the other preferences. let saved = s.prefs_to_json(); @@ -160,6 +231,11 @@ mod tests { json!({"allowNonLinearHistory": 1}), json!({"makeLayerVisibilityChangesUndoable": null}), json!({"allowNonLinearHistory": true, "snapshots": true}), + json!({"automaticallyCreateFirstSnapshot": "true"}), + json!({"automaticallyCreateNewSnapshotWhenSaving": 0}), + json!({"showNewSnapshotDialogByDefault": [true]}), + json!({"showNewSnapshotDialogByDefault": true, "showNewSnapshotDialog": true}), + json!({"AutomaticallyCreateFirstSnapshot": false}), json!([true]), json!("x"), json!(3), @@ -168,6 +244,8 @@ mod tests { assert_eq!(current(&s), before, "{p} changed nothing"); } assert!(s.execute("prefs.set", json!({"path": "historyOptions.allowNonLinearHistory", "value": "on"})).is_err()); + assert!(s.execute("prefs.set", json!({"path": "historyOptions.automaticallyCreateFirstSnapshot", "value": 1})).is_err()); + assert!(s.execute("prefs.set", json!({"path": "historyOptions.showNewSnapshotDialogByDefault", "value": null})).is_err()); assert_eq!(current(&s), before); } @@ -248,4 +326,86 @@ mod tests { s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); assert!(s.active().unwrap().history.non_linear); } + + fn snapshot_names(s: &Session) -> Vec { + s.active().unwrap().snapshots.iter().map(|snap| snap.name.clone()).collect() + } + + /// PNG bytes of a small image, to open. + fn png() -> Vec { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 6})).unwrap(); + crate::file_cmds::encode(&s.active().unwrap().doc, "a.png", None::).unwrap().0 + } + + /// Automatically Create First Snapshot (checked against Photoshop): on (the default), a new or + /// opened document starts with a snapshot named after it; off, it starts with none and the + /// camera's first snapshot is still "Snapshot 1". + #[test] + fn first_snapshot_follows_the_option_on_new_and_open() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let name = s.active().unwrap().doc.name.clone(); + assert_eq!(snapshot_names(&s), [name]); + crate::file_cmds::open_bytes_as(&mut s, "photo.png", &png(), None, None).unwrap(); + assert_eq!(snapshot_names(&s), ["photo.png"], "named after the file, as Photoshop does"); + + s.execute(CMD, json!({"automaticallyCreateFirstSnapshot": false})).unwrap(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + assert!(snapshot_names(&s).is_empty()); + assert_eq!(entries(&s).len(), 1, "the opening state is still there"); + crate::file_cmds::open_bytes_as(&mut s, "photo.png", &png(), None, None).unwrap(); + assert!(snapshot_names(&s).is_empty()); + assert_eq!(s.execute("history.newSnapshot", json!({})).unwrap(), json!({"snapshot": 1, "name": "Snapshot 1"})); + assert_eq!(crate::inspect::document(s.active().unwrap())["snapshots"], json!([{"id": 1, "name": "Snapshot 1"}])); + // Documents opened earlier keep theirs: the option applies when a document opens. + s.set_active(0); + assert_eq!(snapshot_names(&s).len(), 1); + } + + /// Automatically Create New Snapshot When Saving: off (the default), a save adds nothing; on, + /// each save adds a snapshot of the document as saved, named with the time, and not a + /// history state. + #[test] + fn a_save_adds_a_snapshot_only_with_the_option() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + assert_eq!(snapshot_on_save(&mut s), None); + assert_eq!(snapshot_names(&s).len(), 1, "only the first snapshot"); + + s.execute(CMD, json!({"automaticallyCreateNewSnapshotWhenSaving": true})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.active_mut().unwrap().saved_to("saved.psd".into()); + let states = entries(&s); + let id = snapshot_on_save(&mut s).unwrap(); + let st = s.active().unwrap(); + let snap = st.snapshots.last().unwrap(); + assert_eq!(snap.id, id); + assert!(std::sync::Arc::ptr_eq(&snap.doc, &st.doc), "the document as saved"); + // HH:MM:SS, the local time of the save. + let parts: Vec<&str> = snap.name.split(':').collect(); + assert!(parts.len() == 3 && parts.iter().all(|p| p.len() == 2 && p.bytes().all(|b| b.is_ascii_digit())), "{}", snap.name); + assert_eq!(entries(&s), states, "not a history state"); + assert!(!s.active().unwrap().is_dirty(), "the saved document stays clean"); + // Each save adds one; selecting it brings that save back. + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + let second = snapshot_on_save(&mut s).unwrap(); + assert_eq!(snapshot_names(&s).len(), 3); + s.execute("history.selectSnapshot", json!({"snapshot": id})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers[0].surface().unwrap().rgba(1, 1), [1.0, 0.0, 0.0, 1.0]); + assert!(second > id); + // No document: nothing to do, no panic. + let mut empty = Session::new(); + empty.execute(CMD, json!({"automaticallyCreateNewSnapshotWhenSaving": true})).unwrap(); + assert_eq!(snapshot_on_save(&mut empty), None); + } + + #[test] + fn show_new_snapshot_dialog_reads_the_option() { + let mut s = Session::new(); + assert!(!show_new_snapshot_dialog(&s)); + s.execute("prefs.set", json!({"path": "historyOptions.showNewSnapshotDialogByDefault", "value": true})).unwrap(); + assert!(show_new_snapshot_dialog(&s)); + assert_eq!(crate::inspect::session(&s)["historyOptions"]["showNewSnapshotDialogByDefault"], json!(true)); + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 626c80f76c..9b5dc9b3e3 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -219,7 +219,8 @@ pub struct DocState { /// to `.pcraft` or PSD, and not a history step. pub color_samplers: Vec<[f64; 2]>, /// History panel snapshots, oldest first (`history.newSnapshot`, #2966): the first (id 0) is - /// the document as opened. Kept for the session only, as in Photoshop: not history states, + /// the document as opened (unless History Options › Automatically Create First Snapshot is + /// off). Kept for the session only, as in Photoshop: not history states, /// and not saved with the document. pub snapshots: Vec, /// The id the next snapshot gets; ids are never reused, so deleting one keeps the others. @@ -497,6 +498,11 @@ impl Session { st.history.max_states = self.prefs.get().performance.history_states.max(1) as usize; st.history.max_bytes = self.prefs.get().performance.history_budget_bytes(); st.history.non_linear = self.prefs.get().history_options.allow_non_linear_history; + // History Options › Automatically Create First Snapshot off: no snapshot of the document + // as opened, so the History panel starts at the opening state (#2966). + if !self.prefs.get().history_options.automatically_create_first_snapshot { + st.snapshots.clear(); + } self.docs.push(st); let i = self.docs.len() - 1; self.active = Some(i); diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 365b57fa6b..9540e21268 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -946,21 +946,36 @@ impl Default for Integrations { } } -/// The History panel's History Options… (not part of Edit › Preferences in Photoshop either). -/// Photoshop's snapshot options are not here yet: snapshots are not implemented. +/// The History panel's History Options… (not part of Edit › Preferences in Photoshop either), +/// in the dialog's order. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct HistoryOptions { + /// Automatically Create First Snapshot: a new or opened document starts with a snapshot of + /// itself, named after it (the History panel's top row). + pub automatically_create_first_snapshot: bool, + /// Automatically Create New Snapshot When Saving: every save of the document (not a copy) + /// adds a snapshot named with the time of the save. + pub automatically_create_new_snapshot_when_saving: bool, /// Allow Non-Linear History: editing after selecting an earlier state keeps the later /// states (the new step is appended at the end), and deleting a state deletes only it. pub allow_non_linear_history: bool, + /// Show New Snapshot Dialog by Default: a plain click on the History panel's camera button + /// opens New Snapshot (otherwise only ⌥-click does). + pub show_new_snapshot_dialog_by_default: bool, /// Make Layer Visibility Changes Undoable: showing or hiding a layer is a history state. pub make_layer_visibility_changes_undoable: bool, } impl Default for HistoryOptions { fn default() -> Self { - Self { allow_non_linear_history: false, make_layer_visibility_changes_undoable: true } + Self { + automatically_create_first_snapshot: true, + automatically_create_new_snapshot_when_saving: false, + allow_non_linear_history: false, + show_new_snapshot_dialog_by_default: false, + make_layer_visibility_changes_undoable: true, + } } } diff --git a/crates/ui-egui/src/history_options_ui.rs b/crates/ui-egui/src/history_options_ui.rs index 2d4756543b..0ff35dbc0e 100644 --- a/crates/ui-egui/src/history_options_ui.rs +++ b/crates/ui-egui/src/history_options_ui.rs @@ -1,8 +1,8 @@ //! The History Options dialog (History panel menu › History Options…, #2966): a form over the -//! engine's `history.options` with its two checkboxes, filled with the current values. OK runs -//! the command with the dialog's values (the generic command-dialog confirm), Cancel changes -//! nothing. Agents can also run `history.options` with params directly, or `prefs.set -//! historyOptions.*`; a call with params skips the dialog. +//! engine's `history.options` with Photoshop's five checkboxes in its order, filled with the +//! current values. OK runs the command with the dialog's values (the generic command-dialog +//! confirm), Cancel changes nothing. Agents can also run `history.options` with params directly, +//! or `prefs.set historyOptions.*`; a call with params skips the dialog. use serde_json::{Map, Value, json}; @@ -27,11 +27,16 @@ pub fn open(app: &mut PhotocraftApp) -> u64 { f.insert("__label".into(), json!("History Options…")); f.insert("__form".into(), json!(true)); f.insert("__choices".into(), json!({})); - // Photoshop's capitalised labels, in the UI language (the form would sentence-case the keys). + // Photoshop's order and capitalised labels, in the UI language (the form would sort the keys + // and sentence-case them). + f.insert("__order".into(), json!(photocraft_engine::history_options_cmds::OPTIONS)); f.insert( "__labels".into(), json!({ + "automaticallyCreateFirstSnapshot": tl!("Automatically Create First Snapshot"), + "automaticallyCreateNewSnapshotWhenSaving": tl!("Automatically Create New Snapshot When Saving"), "allowNonLinearHistory": tl!("Allow Non-Linear History"), + "showNewSnapshotDialogByDefault": tl!("Show New Snapshot Dialog by Default"), "makeLayerVisibilityChangesUndoable": tl!("Make Layer Visibility Changes Undoable"), }), ); @@ -58,19 +63,25 @@ mod tests { let d = app.ui.dialogs.iter().find(|d| d.id == id).unwrap(); assert_eq!(d.fields["allowNonLinearHistory"], json!(false)); assert_eq!(d.fields["makeLayerVisibilityChangesUndoable"], json!(true)); + assert_eq!(d.fields["automaticallyCreateFirstSnapshot"], json!(true)); + assert_eq!(d.fields["automaticallyCreateNewSnapshotWhenSaving"], json!(false)); + assert_eq!(d.fields["showNewSnapshotDialogByDefault"], json!(false)); assert_eq!(crate::dialogs::title(d), "History Options"); // Cancel changes nothing. app.ui.dialog_mut(id).unwrap().fields.insert("allowNonLinearHistory".into(), json!(true)); crate::dialogs::cancel(&mut app, id).unwrap(); assert!(!app.session.prefs().history_options.allow_non_linear_history); - // OK applies both checkboxes. + // OK applies every checkbox. let id = open(&mut app); let fields = &mut app.ui.dialog_mut(id).unwrap().fields; - fields.insert("allowNonLinearHistory".into(), json!(true)); - fields.insert("makeLayerVisibilityChangesUndoable".into(), json!(false)); + for key in photocraft_engine::history_options_cmds::OPTIONS { + let on = fields[key].as_bool().unwrap(); + fields.insert(key.into(), json!(!on)); + } crate::dialogs::confirm(&mut app, id).unwrap(); let o = &app.session.prefs().history_options; assert!(o.allow_non_linear_history && !o.make_layer_visibility_changes_undoable); + assert!(!o.automatically_create_first_snapshot && o.automatically_create_new_snapshot_when_saving && o.show_new_snapshot_dialog_by_default); assert!(app.ui.dialogs.is_empty()); // Reopened, it shows what was chosen; with params the command runs without a dialog. let id = open(&mut app); @@ -82,16 +93,24 @@ mod tests { assert!(crate::menus::invoke(&mut app, &ctx, COMMAND, json!({"allowNonLinearHistory": "no"})).is_err()); } + /// The five checkboxes with Photoshop's labels, top to bottom in its dialog's order. #[test] - fn the_dialog_draws_both_checkboxes_with_photoshops_labels() { + fn the_dialog_draws_the_checkboxes_in_photoshops_order() { use egui_kittest::{Harness, kittest::Queryable}; let mut h = Harness::builder().with_size(egui::vec2(700.0, 400.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app()); PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); open(h.state_mut()); h.run_steps(3); h.get_by_label("History Options"); - h.get_by_label("Allow Non-Linear History"); - h.get_by_label("Make Layer Visibility Changes Undoable"); + let labels = [ + "Automatically Create First Snapshot", + "Automatically Create New Snapshot When Saving", + "Allow Non-Linear History", + "Show New Snapshot Dialog by Default", + "Make Layer Visibility Changes Undoable", + ]; + let tops: Vec = labels.iter().map(|l| h.get_by_label(l).rect().min.y).collect(); + assert!(tops.windows(2).all(|w| w[0] < w[1]), "top to bottom: {tops:?}"); h.get_by_label("OK"); h.get_by_label("Cancel"); } diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 8c482c864d..c963b60982 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3673,3 +3673,6 @@ navigator Zoom Zvětšení Remove after each stroke Odstranit po každém tahu Apply the removal ({key}) Použít odstranění ({key}) Strokes to remove: {n} (Enter applies, Esc cancels) Tahy k odstranění: {n} (Enter použije, Esc zruší) + Automatically Create First Snapshot Automaticky vytvořit první snímek + Automatically Create New Snapshot When Saving Automaticky vytvořit nový snímek při ukládání + Show New Snapshot Dialog by Default Ve výchozím nastavení zobrazit dialog Nový snímek diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 211262dbf2..1199c83d59 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2699,3 +2699,6 @@ curves Smooth Glätten Remove after each stroke Nach jedem Strich entfernen Apply the removal ({key}) Entfernen anwenden ({key}) Strokes to remove: {n} (Enter applies, Esc cancels) Striche zum Entfernen: {n} (Eingabe wendet an, Esc bricht ab) + Automatically Create First Snapshot Ersten Snapshot automatisch erstellen + Automatically Create New Snapshot When Saving Beim Speichern automatisch neuen Snapshot erstellen + Show New Snapshot Dialog by Default Dialogfeld „Neuer Snapshot“ standardmäßig anzeigen diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index e4a1cdb050..2d8e929569 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2740,3 +2740,6 @@ curves Smooth Suavizar Remove after each stroke Eliminar después de cada trazo Apply the removal ({key}) Aplicar la eliminación ({key}) Strokes to remove: {n} (Enter applies, Esc cancels) Trazos por eliminar: {n} (Intro aplica, Esc cancela) + Automatically Create First Snapshot Crear automáticamente la primera instantánea + Automatically Create New Snapshot When Saving Crear automáticamente una instantánea nueva al guardar + Show New Snapshot Dialog by Default Mostrar el cuadro de diálogo Instantánea nueva de forma predeterminada diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 256a21ab63..c91d161bd6 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3229,3 +3229,6 @@ curves Smooth 매끄럽게 Remove after each stroke 획마다 제거 Apply the removal ({key}) 제거 적용 ({key}) Strokes to remove: {n} (Enter applies, Esc cancels) 제거할 획: {n} (Enter 적용, Esc 취소) + Automatically Create First Snapshot 첫 번째 스냅샷 자동 만들기 + Automatically Create New Snapshot When Saving 저장할 때 새 스냅샷 자동 만들기 + Show New Snapshot Dialog by Default 기본적으로 새 스냅샷 대화 상자 표시 diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 710709a82e..f28a31bc6b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3543,3 +3543,6 @@ curves Smooth Làm mượt History Options… Tùy chọn lịch sử… Allow Non-Linear History Cho phép lịch sử không tuyến tính Make Layer Visibility Changes Undoable Cho phép hoàn tác thay đổi hiển thị lớp + Automatically Create First Snapshot Tự động tạo ảnh chụp trạng thái đầu tiên + Automatically Create New Snapshot When Saving Tự động tạo ảnh chụp trạng thái mới khi lưu + Show New Snapshot Dialog by Default Mặc định hiện hộp thoại Ảnh chụp trạng thái mới diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 4294d08cdd..f09fb57d33 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2664,3 +2664,6 @@ curves Smooth 平滑 Remove after each stroke 每次描边后移除 Apply the removal ({key}) 应用移除 ({key}) Strokes to remove: {n} (Enter applies, Esc cancels) 待移除的描边:{n}(Enter 应用,Esc 取消) + Automatically Create First Snapshot 自动创建第一幅快照 + Automatically Create New Snapshot When Saving 存储时自动创建新快照 + Show New Snapshot Dialog by Default 默认显示新建快照对话框 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 42bd150bca..aeecf651ce 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2649,3 +2649,6 @@ curves Smooth 平滑 Remove after each stroke 每次描邊後移除 Apply the removal ({key}) 套用移除 ({key}) Strokes to remove: {n} (Enter applies, Esc cancels) 待移除的描邊:{n}(Enter 套用,Esc 取消) + Automatically Create First Snapshot 自動建立第一個快照 + Automatically Create New Snapshot When Saving 儲存時自動建立新快照 + Show New Snapshot Dialog by Default 預設顯示新增快照對話框 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 73c02ac426..1e3f1ec157 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1395,6 +1395,8 @@ impl PhotocraftApp { st.saved_to(path.to_string()); // The job locked the document, but record the revision that was written. st.saved_revision = revision; + // History Options › Automatically Create New Snapshot When Saving (#2966). + photocraft_engine::history_options_cmds::snapshot_on_save(&mut app.session); } // "Save Document" script events and File › Generate › Image Assets. if hooks diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 7380d10cef..0c3e7724d8 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -2956,9 +2956,11 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { footer_cmd = Some("history.deleteState"); } let can_snap = app.session.is_enabled("history.newSnapshot"); - // ⌥-click opens New Snapshot (name, From) instead, as in Photoshop. + // ⌥-click opens New Snapshot (name, From) instead, as in Photoshop; with History + // Options › Show New Snapshot Dialog by Default a plain click does too. + let dialog_by_default = photocraft_engine::history_options_cmds::show_new_snapshot_dialog(&app.session); if ui.add_enabled_ui(can_snap, |ui| icons::button(ui, "scan", 26.0, false, tl!("Create new snapshot"))).inner.clicked() { - if ui.input(|i| i.modifiers.alt) { + if dialog_by_default || ui.input(|i| i.modifiers.alt) { snapshot_dialog = true; } else { footer_cmd = Some("history.newSnapshot"); @@ -4607,6 +4609,73 @@ mod snapshot_row_tests { assert!(h.state().ui.dialogs.is_empty()); } + /// History Options › Show New Snapshot Dialog by Default (#2966): a plain click on the camera + /// opens New Snapshot as ⌥-click does, and ⌥-click still opens it (Photoshop's button always + /// prompts with the option on). Off, a plain click takes the snapshot at once. + #[test] + fn show_new_snapshot_dialog_by_default_makes_a_click_open_the_dialog() { + for (dialog_by_default, modifiers) in [(true, egui::Modifiers::NONE), (true, egui::Modifiers::ALT), (false, egui::Modifiers::NONE)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + app.run("history.options", json!({"showNewSnapshotDialogByDefault": dialog_by_default})).unwrap(); + let mut h = Harness::builder().with_size(vec2(900.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + history(app, ui); + crate::dialogs::show(app, &ctx); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.state_mut().ui.theme = crate::theme::ThemeKind::ProMedium; + h.run_steps(4); + let mut buttons: Vec = h + .ctx + .viewport(|v| v.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).filter(|w| w.rect.size() == vec2(26.0, 26.0)).map(|w| w.rect).collect()); + buttons.sort_by(|a, b| b.center().x.total_cmp(&a.center().x)); + let camera = buttons[1].center(); + h.event(egui::Event::ModifiersChanged(modifiers)); + h.event(egui::Event::PointerMoved(camera)); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: camera, button: egui::PointerButton::Primary, pressed, modifiers }); + h.run_steps(1); + } + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.run_steps(3); + let snaps = h.state().session.active().unwrap().snapshots.len(); + let dialog = h.state().ui.dialogs.last().is_some_and(|d| crate::snapshot_dialog::owns(&d.fields)); + if dialog_by_default { + assert!(dialog, "{modifiers:?}: the dialog opens"); + assert_eq!(snaps, 1, "{modifiers:?}: no snapshot until OK"); + h.get_by_label("OK").click(); + h.run_steps(3); + assert_eq!(h.state().session.active().unwrap().snapshots.last().unwrap().name, "Snapshot 1"); + } else { + assert!(!dialog, "off: no dialog"); + assert_eq!(snaps, 2, "off: the click takes the snapshot"); + } + } + } + + /// History Options › Automatically Create First Snapshot: on, the panel's top row is a + /// snapshot named after the document; off, there is none above the opening state. + #[test] + fn the_first_snapshot_row_follows_the_option() { + for first in [true, false] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("history.options", json!({"automaticallyCreateFirstSnapshot": first})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + let name = app.session.active().unwrap().doc.name.clone(); + let mut h = Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state(|ui, app: &mut PhotocraftApp| history(app, ui), app); + h.run_steps(3); + assert_eq!(h.query_by_label(&name).is_some(), first, "a snapshot row named after the document: {first}"); + } + } + /// Renaming belongs to one document: snapshot ids restart in each, so switching tabs must not /// carry the edit over to the other document's snapshot with the same id. #[test] diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rs index cb75e28032..3f3b33cf16 100644 --- a/crates/ui-egui/src/view_cmds.rs +++ b/crates/ui-egui/src/view_cmds.rs @@ -978,7 +978,12 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { // come from `__labels` verbatim; everything else goes through the catalogue. let labels = f.get("__labels").cloned().unwrap_or(Value::Null); let label = |k: &str| labels.get(k).and_then(Value::as_str).map_or_else(|| label_of(k), str::to_string); - let keys: Vec = f.keys().filter(|k| !k.starts_with("__")).cloned().collect(); + // `__order` lists the fields in the dialog's order (the map itself is sorted by key); fields + // it leaves out follow in key order. + let order: Vec = + f.get("__order").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default(); + let mut keys: Vec = order.iter().filter(|k| !k.starts_with("__") && f.contains_key(k.as_str())).cloned().collect(); + keys.extend(f.keys().filter(|k| !k.starts_with("__") && !order.contains(k)).cloned()); egui::Grid::new("form-dialog").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| { for k in keys { let v = f.get(&k).cloned().unwrap_or(Value::Null); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3a8ddb38a8..4c913280a1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -106,7 +106,7 @@ store expose and persist the same setting; scripts keep using canonical command | `layer.newAdjustmentLayer.hueSaturation` | `{"hue":30,"saturation":10}` | | `paint.stroke` | `{"points":[[x,y,pressure],…],"size":20,"color":"#ff0000"}` | | `select.rect` | `{"x":0,"y":0,"width":100,"height":50,"mode":"add","ellipse":false}` | -| `document.inspect` | `{}`: layer tree, history, snapshots (`[{id, name}]`, for `history.selectSnapshot`; id 0 is the document as opened), selection bounds | +| `document.inspect` | `{}`: layer tree, history, snapshots (`[{id, name}]`, for `history.selectSnapshot`; id 0 is the document as opened, unless `history.options` `automaticallyCreateFirstSnapshot` is off), selection bounds | | `document.pixel` | `{"x":10,"y":10}`: composite RGBA | | `document.presets.list` | `{}` → `{presets:[{name,settings}]}`: saved New Document configurations | | `document.presets.save` | `{"name":"Product square","settings":{"width":1600,"height":1600,"background":"transparent"}}`: save a snapshot; names are trimmed, 1–255 characters, and ASCII case-insensitive duplicates are rejected | diff --git a/docs/scorecard.md b/docs/scorecard.md index ff0188d419..a7d0390de1 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 6 | 13 | 8 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 | | [Tools](#tools) | 28 | 14 | 1 | | -| [Workspace and UI](#workspace-and-ui) | 13 | 5 | 5 | settings that do nothing: 27 of 158 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 13 | 5 | 5 | settings that do nothing: 27 of 161 (target 0) | | [Type](#type) | 4 | 2 | 3 | | | [Automation](#automation) | 4 | 2 | 5 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present | @@ -176,7 +176,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 27 of 158** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 27 of 161** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `file_handling.maximize_psd_compatibility`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c798387e26..fd0a4b8087 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (History snapshots) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (History snapshots; History Options snapshot options) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -202,7 +202,7 @@ Paragraph; the rest open as in-app floating windows. | Command palette with recents | done | UI-217-7 | | Every preference takes effect | partial | 46 of 149 do nothing (scorecard) | | UI scale presets | missing | UI-217-9, #2492 | -| History snapshots: camera button, New Snapshot dialog (⌥-click: Name, From), the first snapshot (the document as opened), snapshot rows (click returns, rename, delete), `history.*Snapshot` commands | partial | `history_cmds.rs`, `snapshot_rows` in `panels.rs`, `snapshot_dialog.rs`; the snapshot History Options and History Brush sources to come (#2966) | +| History snapshots: camera button, New Snapshot dialog (⌥-click: Name, From), the first snapshot (the document as opened), snapshot rows (click returns, rename, delete), `history.*Snapshot` commands; History Options' snapshot options (Automatically Create First Snapshot, New Snapshot When Saving, Show New Snapshot Dialog by Default) | partial | `history_cmds.rs`, `history_options_cmds.rs`, `snapshot_rows` in `panels.rs`, `snapshot_dialog.rs`; History Brush sources to come (#2966) | | Themes: Photoshop's four greys | partial | five themes; #2661 | | Document tabs: overflow, context menu, reorder | done | UI-217-6; middle-click close #2570 | | Layers panel: wheel steps blend modes, drop on New/Trash | partial | UI-217-14 | @@ -218,3 +218,4 @@ Paragraph; the rest open as in-app floating windows. | 2026-10-11 | minor | ⇧-drag a guide out of a ruler lands on the nearest ruler tick (#3770) | | 2026-10-11 | minor | Layer and selection keys from Photoshop's shortcut set: ⌘, toggles, ⌘\, /, ⌘⌥2, ⌘⌥⌫, Tab rename-next, ⌥-click thumbnail to fit | | 2026-10-12 | minor | History snapshots: the New Snapshot dialog (⌥-click the camera), and the first snapshot of the document as opened as the panel's top row (#2966) | +| 2026-10-12 | minor | History Options: Automatically Create First Snapshot, Automatically Create New Snapshot When Saving, Show New Snapshot Dialog by Default (#2966) | From 9591d0446130e250c39b1aae15f41eaf30e04a7a Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 13 Oct 2026 00:43:44 +0200 Subject: [PATCH 02/44] Merge fixups: translate the History Options and New Snapshot strings into Hungarian and Turkish Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/i18n/hu.tsv | 6 ++++++ crates/ui-egui/src/i18n/tr.tsv | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e0eff7b8a7..f77695d5f7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3649,6 +3649,12 @@ cameraRaw Yellow Sárga Auto-leading % Automatikus sorköz % Automatically Create First Snapshot Első pillanatkép automatikus létrehozása Automatically Create New Snapshot When Saving Új pillanatkép automatikus létrehozása mentéskor + From: Forrás: + Full Document Teljes dokumentum + Merged Layers Egyesített rétegek + History Options… Előzménybeállítások… + Allow Non-Linear History Nemlineáris előzmények engedélyezése + Make Layer Visibility Changes Undoable A rétegláthatóság módosításai visszavonhatók legyenek Avoid Widows/Orphans Fattyúsorok elkerülése Blend RGB Colors Using Gamma 1.0 RGB-színek keverése 1,0 gammával Blending Mode Keverési mód diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 8401f8e5ac..1f735bea85 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2647,6 +2647,12 @@ cameraRaw Color Renk Set New Snapshot as Default Yeni Anlık Görüntüyü Varsayılan Olarak Ayarla Automatically Create First Snapshot İlk Anlık Görüntüyü Otomatik Olarak Oluştur Automatically Create New Snapshot When Saving Kaydederken Otomatik Olarak Yeni Anlık Görüntü Oluştur + From: Kaynak: + Full Document Tam Belge + Merged Layers Birleştirilmiş Katmanlar + History Options… Geçmiş Seçenekleri… + Allow Non-Linear History Doğrusal Olmayan Geçmişe İzin Ver + Make Layer Visibility Changes Undoable Katman Görünürlüğü Değişikliklerini Geri Alınabilir Yap Show New Snapshot Dialog by Default Yeni Anlık Görüntü İletişim Kutusunu Varsayılan Olarak Göster Clear History Geçmişi Temizle Panel Options… Panel Seçenekleri… From 5bdd9f773eadd8fd5eab9c178c01efe5c36762dc Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 13 Oct 2026 13:26:50 +0200 Subject: [PATCH 03/44] History snapshot options: Serbian labels Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/i18n/sr.tsv | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 7a85f8d58f..7e79139a1a 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -2268,6 +2268,12 @@ Automatically Create New Snapshot When Saving Automatski napravi novi snimak stanja pri čuvanju Show New Snapshot Dialog by Default Podrazumevano prikaži dijalog za novi snimak stanja Clear History Obriši istoriju + History Options… Opcije istorije… + Allow Non-Linear History Dozvoli nelinearnu istoriju + Make Layer Visibility Changes Undoable Omogući opozivanje promena vidljivosti slojeva + From: Od: + Full Document Ceo dokument + Merged Layers Spojeni slojevi Panel Options… Opcije panela… View menu Meni prikaza Keep view in sync Drži prikaz usklađenim From 0c425166d626f6727281dfd3c9a9aba77d733137 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 13 Oct 2026 19:32:21 +0200 Subject: [PATCH 04/44] docs: regenerate scorecard after merging main Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index af13a3f265..5cff3b2f13 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 7 | 13 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 145/256, round trip ≥ 258/256 | | [Tools](#tools) | 28 | 14 | 1 | | -| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 156 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 161 (target 0) | | [Type](#type) | 4 | 3 | 2 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present | @@ -176,7 +176,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 26 of 156** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 26 of 161** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. From 79b2bee666f5d9f56f57d232a8f4f214b140d5aa Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 13 Oct 2026 20:07:38 +0200 Subject: [PATCH 05/44] docs: regenerate scorecard after merging main Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 92f9315ebd..fc88746a66 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 7 | 13 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 145/256, round trip ≥ 258/256 | | [Tools](#tools) | 28 | 14 | 1 | | -| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 157 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 162 (target 0) | | [Type](#type) | 4 | 3 | 2 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present | @@ -176,7 +176,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 26 of 157** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 26 of 162** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. From 5d3557281ea87108970f397794c4f3c332fb0da9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 14 Oct 2026 13:02:10 +0200 Subject: [PATCH 06/44] Dropdowns: popups as tall as their items, up to the window (#5495) egui's ComboBox capped every list at the size its popup takes on the frame it opens (default_area_size, 400 pt), so the Layers panel's 27 blend modes scrolled even in tall windows. widgets::combo_list draws the button and its list itself (keeping egui's ids): the list is as tall as its options up to the visible window and scrolls only past that. It opens below the button at its left edge, or moves up over it to fit, never beside it, so it stays put while wheel steps change the value and the button's width (#1747). All five former .height(420) dropdowns use it. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/adjust_editors.rs | 55 ++-- .../ui-egui/src/blend_dropdown_wheel_tests.rs | 11 +- crates/ui-egui/src/crop_presets.rs | 2 +- crates/ui-egui/src/type_tool.rs | 20 +- crates/ui-egui/src/widgets.rs | 305 ++++++++++++++---- 5 files changed, 282 insertions(+), 111 deletions(-) diff --git a/crates/ui-egui/src/adjust_editors.rs b/crates/ui-egui/src/adjust_editors.rs index 2678cc65f2..605c4b8c58 100644 --- a/crates/ui-egui/src/adjust_editors.rs +++ b/crates/ui-egui/src/adjust_editors.rs @@ -1384,38 +1384,33 @@ fn gradient_map(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { label(ui, tl!("Preset:")); let mut picked = None; let (press, close) = crate::press_menu::PressCombo::before(ui, cx.mem.with("gm-preset")); - let combo = egui::ComboBox::from_id_salt(cx.mem.with("gm-preset")) - .selected_text(tl!("Custom")) - .width(ui.available_width().min(190.0)) - .height(420.0) - .icon(widgets::chevron_icon) - .close_behavior(close) - .show_ui(ui, |ui| { - let gear = crate::icons::button(ui, "settings", 24.0, false, tl!("Gradient Preset Options")); - egui::containers::menu::SubMenu::new().show(ui, &gear, |ui| { - if ui.button(tl!("Import .GRD")).clicked() { - e.import_gradients = true; - ui.close(); - } - }); - ui.separator(); - for g in &cx.gradients { - ui.label(RichText::new(&g.name).color(t.text_faint)); - for p in &g.items { - ui.horizontal(|ui| { - // A map has no transparency: colour stops only, shown opaque. - let rgba: Vec<(f32, [f32; 4])> = p.resolve(fg, bg).into_iter().map(|(at, c)| (at, [c[0], c[1], c[2], 1.0])).collect(); - let (r, swatch) = ui.allocate_exact_size(vec2(48.0, 16.0), Sense::click()); - crate::preset_panels::paint_gradient(ui, r, &rgba); - // Both, not short-circuited: the name is drawn either way. - let name = ui.selectable_label(false, &p.name); - if press.chosen(ui, &swatch) | press.chosen(ui, &name) { - picked = Some(rgba.iter().map(|(at, c)| (*at, [c[0], c[1], c[2]])).collect::>()); - } - }); - } + let width = ui.available_width().min(190.0); + let combo = widgets::combo_list(ui, cx.mem.with("gm-preset"), tl!("Custom"), width, close, |ui| { + let gear = crate::icons::button(ui, "settings", 24.0, false, tl!("Gradient Preset Options")); + egui::containers::menu::SubMenu::new().show(ui, &gear, |ui| { + if ui.button(tl!("Import .GRD")).clicked() { + e.import_gradients = true; + ui.close(); } }); + ui.separator(); + for g in &cx.gradients { + ui.label(RichText::new(&g.name).color(t.text_faint)); + for p in &g.items { + ui.horizontal(|ui| { + // A map has no transparency: colour stops only, shown opaque. + let rgba: Vec<(f32, [f32; 4])> = p.resolve(fg, bg).into_iter().map(|(at, c)| (at, [c[0], c[1], c[2], 1.0])).collect(); + let (r, swatch) = ui.allocate_exact_size(vec2(48.0, 16.0), Sense::click()); + crate::preset_panels::paint_gradient(ui, r, &rgba); + // Both, not short-circuited: the name is drawn either way. + let name = ui.selectable_label(false, &p.name); + if press.chosen(ui, &swatch) | press.chosen(ui, &name) { + picked = Some(rgba.iter().map(|(at, c)| (*at, [c[0], c[1], c[2]])).collect::>()); + } + }); + } + } + }); press.after(&combo.response); if let Some(p) = picked { stops = p; diff --git a/crates/ui-egui/src/blend_dropdown_wheel_tests.rs b/crates/ui-egui/src/blend_dropdown_wheel_tests.rs index c6b9186f86..31b28adbda 100644 --- a/crates/ui-egui/src/blend_dropdown_wheel_tests.rs +++ b/crates/ui-egui/src/blend_dropdown_wheel_tests.rs @@ -165,16 +165,17 @@ fn wheel_steps_in_the_open_list_keep_the_chosen_mode_in_view() { let mut h = harness(pixel_layer); let at = dropdown(&h).center(); click(&mut h, at); - // Unscrolled, the list shows its first entry at the top and is at most 420 pt tall. - let (top, darken) = (entry(&h, "Normal").top(), entry(&h, "Darken").center()); + // The open list, unscrolled, shows its first entry at the top. + let list = h.ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id))).unwrap(); + let darken = entry(&h, "Darken").center(); for _ in 0..22 { wheel(&mut h, darken, -1.0); } h.run_steps(30); assert_eq!(blend(&h), BlendMode::Divide); - let in_view = |r: Rect| r.top() >= top - 0.5 && r.bottom() <= top + 420.0 + 0.5; + let in_view = |r: Rect| list.contains_rect(r); let chosen = entry(&h, "Divide"); - assert!(in_view(chosen), "{chosen:?} in view below {top}"); + assert!(in_view(chosen), "{chosen:?} in view in {list:?}"); // The wheel over the button scrolls the open list along too. for _ in 0..21 { wheel(&mut h, at, 1.0); @@ -182,7 +183,7 @@ fn wheel_steps_in_the_open_list_keep_the_chosen_mode_in_view() { h.run_steps(30); assert_eq!(blend(&h), BlendMode::Dissolve); let chosen = entry(&h, "Dissolve"); - assert!(in_view(chosen), "{chosen:?} in view below {top}"); + assert!(in_view(chosen), "{chosen:?} in view in {list:?}"); } /// The mode the canvas previews on the active layer, if any (#970). diff --git a/crates/ui-egui/src/crop_presets.rs b/crates/ui-egui/src/crop_presets.rs index e049fdfa8c..33966178c0 100644 --- a/crates/ui-egui/src/crop_presets.rs +++ b/crates/ui-egui/src/crop_presets.rs @@ -142,7 +142,7 @@ pub fn dropdown(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let current_user = users.iter().rev().find(|(_, f)| matches(o, f)).map(|(n, _)| n.clone()); let can_new = savable(o).is_some(); let mut chosen: Option = None; - egui::ComboBox::from_id_salt("crop-ratio").selected_text(label).width(140.0).height(420.0).icon(crate::widgets::chevron_icon).show_ui(ui, |ui| { + crate::widgets::combo_list(ui, "crop-ratio", label, 140.0, egui::PopupCloseBehavior::CloseOnClick, |ui| { let (before, after): (Vec<_>, Vec<_>) = builtin.iter().partition(|(k, _)| k != crop_size::FRONT); for (k, l) in &before { if ui.selectable_label(current_user.is_none() && *k == o.crop_ratio, tl!(l)).clicked() { diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index f00fb57157..286b05e8c1 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -1884,20 +1884,14 @@ fn kerning_field(ui: &mut egui::Ui, shown: &str, width: f32) -> Option(ui: &mut Ui, id: &str, current: &mut T, o let mut reveal = wheel && ui.data_mut(|d| d.remove_temp::(reveal_id)).unwrap_or(false); // The list opens on the press: press, drag onto an option and release to choose it (#2735). let (press, close) = crate::press_menu::PressCombo::before(ui, id); - let response = - egui::ComboBox::from_id_salt(id).selected_text(label).width(width).height(420.0).icon(chevron_icon).close_behavior(close).show_ui(ui, |ui| { - fit_widest_option(ui, options.iter().map(|(_, l)| tl!(l))); - // A typed letter jumps to the next option starting with it, ↩ closes the list (#1481). - let labels: Vec<&str> = options.iter().map(|(_, l)| tl!(l)).collect(); - let shown = options.iter().position(|(v, _)| v == current); - if let Some((v, _)) = type_ahead::keys(ui, ui.make_persistent_id(id), shown, &labels).and_then(|i| options.get(i)) { + let response = combo_list(ui, id, label, width, close, |ui| { + fit_widest_option(ui, options.iter().map(|(_, l)| tl!(l))); + // A typed letter jumps to the next option starting with it, ↩ closes the list (#1481). + let labels: Vec<&str> = options.iter().map(|(_, l)| tl!(l)).collect(); + let shown = options.iter().position(|(v, _)| v == current); + if let Some((v, _)) = type_ahead::keys(ui, ui.make_persistent_id(id), shown, &labels).and_then(|i| options.get(i)) { + *current = v.clone(); + chosen.push(v.clone()); + reveal = true; + keyed = true; + } + // Over the open list the wheel steps the value too, instead of scrolling the list. + over_list = wheel && ui.rect_contains_pointer(ui.clip_rect()); + if over_list { + let stepped = wheel_steps(ui, wheel_id, true, current, options); + wheeled = !stepped.is_empty(); + reveal |= wheeled; + chosen.extend(stepped); + } + // The row nearest the pointer, by its distance to each row. + let pointer = ui.ctx().pointer_hover_pos().filter(|_| ui.rect_contains_pointer(ui.clip_rect())); + let mut nearest: Option<(f32, &T)> = None; + for (v, l) in options { + let item = ui.selectable_label(v == current, tl!(l)); + if reveal && v == current { + item.scroll_to_me(None); + } + if item.hovered() { + hovered = Some(v.clone()); + } + if let Some(p) = pointer { + let d = (item.rect.top() - p.y).max(p.y - item.rect.bottom()).max(0.0); + if nearest.is_none_or(|(n, _)| d < n) { + nearest = Some((d, v)); + } + } + if press.chosen(ui, &item) { *current = v.clone(); chosen.push(v.clone()); - reveal = true; - keyed = true; } - // Over the open list the wheel steps the value too, instead of scrolling the list. - over_list = wheel && ui.rect_contains_pointer(ui.clip_rect()); - if over_list { - let stepped = wheel_steps(ui, wheel_id, true, current, options); - wheeled = !stepped.is_empty(); - reveal |= wheeled; - chosen.extend(stepped); - } - // The row nearest the pointer, by its distance to each row. - let pointer = ui.ctx().pointer_hover_pos().filter(|_| ui.rect_contains_pointer(ui.clip_rect())); - let mut nearest: Option<(f32, &T)> = None; - for (v, l) in options { - let item = ui.selectable_label(v == current, tl!(l)); - if reveal && v == current { - item.scroll_to_me(None); - } - if item.hovered() { - hovered = Some(v.clone()); - } - if let Some(p) = pointer { - let d = (item.rect.top() - p.y).max(p.y - item.rect.bottom()).max(0.0); - if nearest.is_none_or(|(n, _)| d < n) { - nearest = Some((d, v)); - } - } - if press.chosen(ui, &item) { - *current = v.clone(); - chosen.push(v.clone()); - } - } - // Between two rows (item spacing) the pointer hovers neither; it is still over the list, - // so keep previewing the nearest row instead of flashing the current value back (#2553). - if hovered.is_none() { - hovered = nearest.map(|(_, v)| v.clone()); - } - }); + } + // Between two rows (item spacing) the pointer hovers neither; it is still over the list, + // so keep previewing the nearest row instead of flashing the current value back (#2553). + if hovered.is_none() { + hovered = nearest.map(|(_, v)| v.clone()); + } + }); press.after(&response.response); if combo_box_arrow_keys(ui, &response.response, current, options) { chosen.push(current.clone()); @@ -1473,14 +1472,117 @@ fn combo_box_arrow_keys(ui: &mut Ui, response: &Response, /// off the bottom. egui moves a popup up to keep it in the window, so a menu opened low on the /// screen first shifts up and only scrolls when it is taller than the window. pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R { - // The popup frame's margin and stroke, and a small gap to the window's edges. - let frame = ui.spacing().menu_margin.sum().y + 2.0 + 2.0 * MENU_EDGE; - let room = (crate::work_area::visible_rect(ui.ctx()).height() - frame).max(MENU_MIN_HEIGHT); + let room = popup_max_height(ui.ctx(), ui.spacing()); // A popup's Ui is only as tall as the popup was last frame (400 pt on the first), so ask for // the whole room: the area still shrinks to its rows when they need less. egui::ScrollArea::vertical().max_height(room).min_scrolled_height(room).show(ui, add_contents).inner } +/// The most a popup's rows may take: the part of the window that can be seen (clear of a taskbar a +/// too-tall window runs under, #315), less the popup frame's margin and stroke and a small gap to +/// the window's edges. egui moves a popup up to keep it in the window, so a popup this tall fits. +pub fn popup_max_height(ctx: &egui::Context, spacing: &egui::style::Spacing) -> f32 { + let frame = spacing.menu_margin.sum().y + 2.0 + 2.0 * MENU_EDGE; + (crate::work_area::visible_rect(ctx).height() - frame).max(MENU_MIN_HEIGHT) +} + +/// A dropdown: a button showing `selected_text` (at least `width` wide, wider for a longer text) +/// whose list (`add_contents`) opens below it on a click. The list is as tall as its options up to +/// the part of the window that can be seen, scrolling only past that (#5495): Photoshop's dropdowns +/// open at full height. egui's `ComboBox` capped every list at the size its popup takes on the +/// frame it opens (`default_area_size`, 400 pt), so the Layers panel's 27 blend modes scrolled. +/// +/// The list's left edge is the button's, and a list that doesn't fit below the button moves up +/// over it to stay in the window, never beside it: so it stays put while its value (and with it +/// the button's width) changes, as the wheel steps it over the open list (#1747). The ids are +/// egui's `ComboBox` ones, so `ComboBox::is_open` and [`crate::press_menu::PressCombo`] apply. +pub fn combo_list( + ui: &mut Ui, + id_salt: impl egui::AsIdSalt, + selected_text: impl Into, + width: f32, + close: egui::PopupCloseBehavior, + add_contents: impl FnOnce(&mut Ui) -> R, +) -> egui::InnerResponse> { + let button_id = ui.make_persistent_id(egui::IdSalt::new(id_salt)); + let popup_id = button_id.with("popup"); + let selected_text = selected_text.into(); + ui.horizontal(|ui| { + let ctx = ui.ctx().clone(); + let button = combo_button(ui, button_id, &selected_text, width, egui::Popup::is_id_open(&ctx, popup_id)); + let enabled = ui.is_enabled(); + button.widget_info(|| { + let mut info = egui::WidgetInfo::new(egui::WidgetType::ComboBox); + info.enabled = enabled; + info.current_text_value = Some(selected_text.text().to_owned()); + info + }); + let room = popup_max_height(&ctx, ui.spacing()); + // Below the button, or as far up as the list's height (from the last frame) needs. + let visible = crate::work_area::visible_rect(&ctx).shrink(MENU_EDGE); + let height = egui::AreaState::load(&ctx, popup_id).and_then(|s| s.size).map_or(0.0, |s| s.y); + let top = button.rect.bottom().min(visible.bottom() - height).max(visible.top()); + let left = button.rect.left(); + let inner = egui::Popup::menu(&button) + .id(popup_id) + .anchor(Rect::from_x_y_ranges(left..=left, top..=top)) + .align(egui::RectAlign::BOTTOM_START) + .align_alternatives(&[]) + .width(button.rect.width()) + .close_behavior(close) + .style(egui::style::StyleModifier::default()) + .show(|ui| { + ui.set_min_width(ui.available_width()); + // A popup's Ui is only as tall as the popup was last frame (400 pt on the first), + // so ask for the whole room: the area still shrinks to its rows when they need less. + egui::ScrollArea::vertical() + .max_height(room) + .min_scrolled_height(room) + .show(ui, |ui| { + // Options don't wrap in a list as narrow as its button: they widen it. + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); + add_contents(ui) + }) + .inner + }) + .map(|r| r.inner); + egui::InnerResponse::new(inner, button) + }) + .inner +} + +/// The button of a [`combo_list`], drawn as egui's `ComboBox` draws its own. +fn combo_button(ui: &mut Ui, id: egui::Id, text: &egui::WidgetText, width: f32, open: bool) -> Response { + let background = ui.painter().add(egui::Shape::Noop); + let margin = ui.spacing().button_padding; + let min_height = ui.spacing().interact_size.y; + let mut outer = ui.available_rect_before_wrap(); + outer.set_height(outer.height().max(min_height)); + let mut content = ui.new_child(egui::UiBuilder::new().max_rect(outer.shrink2(margin))); + let icon_spacing = content.spacing().icon_spacing; + let icon_size = Vec2::splat(content.spacing().icon_width); + let wrap_mode = content.wrap_mode(); + let wrap_width = if wrap_mode == egui::TextWrapMode::Extend { f32::INFINITY } else { content.available_width() - icon_spacing - icon_size.x }; + let galley = text.clone().into_galley(&content, Some(wrap_mode), wrap_width, egui::TextStyle::Button); + let size = vec2((galley.size().x + icon_spacing + icon_size.x).max(width - 2.0 * margin.x), galley.size().y.max(icon_size.y)); + let (_, rect) = content.allocate_space(size); + let mut outer = content.min_rect().expand2(margin); + outer.set_height(outer.height().max(min_height)); + let response = ui.interact(outer, id, Sense::click()); + if ui.is_rect_visible(outer) { + let visuals = if open { &ui.visuals().widgets.open } else { ui.style().interact(&response) }; + let shape = + egui::epaint::RectShape::new(outer.expand(visuals.expansion), visuals.corner_radius, visuals.weak_bg_fill, visuals.bg_stroke, StrokeKind::Inside); + ui.painter().set(background, shape); + let icon_rect = Align2::RIGHT_CENTER.align_size_within_rect(icon_size, rect); + chevron_icon(ui, icon_rect.expand(visuals.expansion), visuals, open); + let text_rect = Align2::LEFT_CENTER.align_size_within_rect(galley.size(), rect); + ui.painter().galley(text_rect.min, galley, visuals.text_color()); + } + ui.advance_cursor_after_rect(outer); + response +} + /// Gap kept between a context menu and the window's edges, and the shortest it gets. const MENU_EDGE: f32 = 4.0; const MENU_MIN_HEIGHT: f32 = 120.0; @@ -1519,23 +1621,22 @@ pub fn dropdown_with_tooltips(ui: &mut Ui, id: &str, curre let label = options.iter().find(|(v, _, _)| v == current).map(|(_, l, _)| tl!(l)).unwrap_or("—"); let mut changed = false; let (press, close) = crate::press_menu::PressCombo::before(ui, id); - let response = - egui::ComboBox::from_id_salt(id).selected_text(label).width(width).height(420.0).icon(chevron_icon).close_behavior(close).show_ui(ui, |ui| { - fit_widest_option(ui, options.iter().map(|(_, l, _)| tl!(l))); - let labels: Vec<&str> = options.iter().map(|(_, l, _)| tl!(l)).collect(); - let shown = options.iter().position(|(v, _, _)| v == current); - if let Some((v, _, _)) = type_ahead::keys(ui, ui.make_persistent_id(id), shown, &labels).and_then(|i| options.get(i)) { + let response = combo_list(ui, id, label, width, close, |ui| { + fit_widest_option(ui, options.iter().map(|(_, l, _)| tl!(l))); + let labels: Vec<&str> = options.iter().map(|(_, l, _)| tl!(l)).collect(); + let shown = options.iter().position(|(v, _, _)| v == current); + if let Some((v, _, _)) = type_ahead::keys(ui, ui.make_persistent_id(id), shown, &labels).and_then(|i| options.get(i)) { + *current = v.clone(); + changed = true; + } + for (v, l, tip) in options { + let item = ui.selectable_label(v == current, tl!(l)).on_hover_text(tl!(tip)); + if press.chosen(ui, &item) { *current = v.clone(); changed = true; } - for (v, l, tip) in options { - let item = ui.selectable_label(v == current, tl!(l)).on_hover_text(tl!(tip)); - if press.chosen(ui, &item) { - *current = v.clone(); - changed = true; - } - } - }); + } + }); press.after(&response.response); if let Some((_, _, tip)) = options.iter().find(|(v, _, _)| v == current) { let _ = response.response.on_hover_text(tl!(tip)); @@ -2237,6 +2338,86 @@ mod tests { } } + /// A window `height` tall with the Layers panel's blend mode dropdown (all 27 modes, wheel + /// steps them) `down` from its top, opened. + fn open_blend_modes(height: f32, down: f32) -> Harness<'static, photocraft_color::BlendMode> { + use photocraft_color::BlendMode; + let mut h = Harness::builder().with_size(egui::vec2(400.0, height)).build_ui_state( + move |ui, mode: &mut BlendMode| { + ui.add_space(down); + let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect(); + super::dropdown_wheel_hovered(ui, "blend-mode", mode, &opts, 120.0); + }, + BlendMode::Normal, + ); + crate::theme::apply(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run(); + h.get_by_role(egui::accesskit::Role::ComboBox).click(); + h.run_steps(4); + h + } + + /// The open list's rect. + fn open_list(h: &Harness<'_, T>) -> egui::Rect { + 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 list is open") }; + list + } + + /// Each mode's row in the open list: its label's last node, as the box shows the chosen one's. + fn mode_rows(h: &Harness<'_, T>) -> Vec { + use photocraft_color::BlendMode; + BlendMode::LAYER_MODES.iter().map(|m| h.get_all_by_label(m.label()).last().map(|n| n.rect()).unwrap_or(egui::Rect::NOTHING)).collect() + } + + /// Photoshop opens the Layers panel's blend modes at full height when the window has room, no + /// scroll bar (#5495): not capped at a fixed height. A short window still scrolls the list, + /// which stays inside the window. + #[test] + fn dropdown_list_is_as_tall_as_its_options_up_to_the_window() { + let h = open_blend_modes(1000.0, 0.0); + let (list, rows) = (open_list(&h), mode_rows(&h)); + for (i, row) in rows.iter().enumerate() { + assert!(list.contains_rect(*row), "row {i} {row:?} shows in the list {list:?}"); + } + let h = open_blend_modes(300.0, 0.0); + let (list, rows) = (open_list(&h), mode_rows(&h)); + assert!(list.top() >= 0.0 && list.bottom() <= 300.0, "the list {list:?} stays in the window"); + assert!(list.height() > 200.0, "the list {list:?} uses the window's height"); + assert!(rows.last().is_some_and(|r| !list.contains_rect(*r)), "the last rows scroll: {rows:?}"); + } + + /// The open list opens at the button's left edge, below it or moved up over it to fit, and + /// stays put while the wheel steps through every mode over it (#1747), although the button + /// widens for the longer names (#5495). + #[test] + fn dropdown_list_stays_put_while_the_wheel_steps_its_value() { + use photocraft_color::BlendMode; + // A tall window with room below the button, and a 900 pt one with the button half way down. + for (height, down) in [(1000.0, 0.0), (900.0, 420.0)] { + let mut h = open_blend_modes(height, down); + let button = h.get_by_role(egui::accesskit::Role::ComboBox).rect(); + let list = open_list(&h); + assert!(list.top() >= 0.0 && list.bottom() <= height, "{height}: the list {list:?} is in the window"); + assert!((list.left() - button.left()).abs() < 8.0, "{height}: the list {list:?} starts at the button {button:?}"); + let rows = mode_rows(&h); + assert!(rows.iter().all(|r| list.contains_rect(*r)), "{height}: all modes show in {list:?}"); + let over = list.center(); + for _ in 1..BlendMode::LAYER_MODES.len() { + h.hover_at(over); + h.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }); + h.run_steps(3); + assert_eq!(open_list(&h), list, "{height}: the list stays put at {:?}", h.state()); + } + assert_eq!(*h.state(), BlendMode::Luminosity, "{height}: the wheel stepped through every mode"); + } + } + const MODES: [(usize, &str); 4] = [(0, "Normal"), (1, "Dissolve"), (2, "Darken"), (3, "Multiply")]; /// A wheel dropdown (or a plain one) of [`MODES`], whose state is the chosen index. From 097027edb0186f0321b2fe5eb29c4dca3640efb6 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 14 Oct 2026 14:06:18 +0200 Subject: [PATCH 07/44] Layers: separators between the Blend Mode groups (#5532) Photoshop's blend mode lists draw a line between their six groups (Normal, Dissolve | darken | lighten | contrast | difference | colour). The Layers panel's Blend Mode list and the options bar's Mode lists (Brush/Pencil, Gradient) now do too. The lines are only drawn: options, order, wheel, arrow keys, type-ahead and hover preview are unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../src/blend_dropdown_groups_tests.rs | 64 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/panels.rs | 21 +++++- crates/ui-egui/src/widgets.rs | 53 +++++++++++++-- 4 files changed, 134 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/blend_dropdown_groups_tests.rs diff --git a/crates/ui-egui/src/blend_dropdown_groups_tests.rs b/crates/ui-egui/src/blend_dropdown_groups_tests.rs new file mode 100644 index 0000000000..de3d1d7d93 --- /dev/null +++ b/crates/ui-egui/src/blend_dropdown_groups_tests.rs @@ -0,0 +1,64 @@ +//! #5532: the Layers panel's Blend Mode list draws a line between Photoshop's six groups of modes: +//! Normal, Dissolve | Darken … Darker Color | Lighten … Lighter Color | Overlay … Hard Mix | +//! Difference … Divide | Hue … Luminosity. + +use egui::accesskit::Role; +use egui::{Pos2, Rect, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use photocraft_doc::BlendMode; +use serde_json::json; + +use crate::PhotocraftApp; + +/// The app with a new document and a pixel layer above the Background, active. +fn harness() -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app + }); + h.run_steps(8); + h +} + +fn click(h: &mut Harness<'_, PhotocraftApp>, at: Pos2) { + h.hover_at(at); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + h.run_steps(1); + } + h.run_steps(2); +} + +#[test] +fn the_layers_blend_mode_list_has_a_line_between_each_group() { + let mut h = harness(); + // The Layers panel's dropdown: the lowest one (the options bar and the title bar have some too). + let button = h.query_all_by_role(Role::ComboBox).map(|n| n.rect()).max_by(|a, b| a.top().total_cmp(&b.top())).unwrap(); + click(&mut h, button.center()); + let list = h.ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id))).unwrap(); + // Each mode's row in the open list. + let rows: Vec = BlendMode::LAYER_MODES + .iter() + .map(|m| h.get_all_by_label(m.label()).map(|n| n.rect()).rfind(|r| list.contains_rect(*r)).unwrap_or_else(|| panic!("{m:?} is in the list"))) + .collect(); + let gaps: Vec = rows.windows(2).map(|w| w[1].top() - w[0].bottom()).collect(); + let row_gap = gaps.iter().copied().fold(f32::INFINITY, f32::min); + let lines: Vec<(BlendMode, BlendMode)> = + gaps.iter().enumerate().filter(|(_, g)| **g > row_gap + 2.0).map(|(i, _)| (BlendMode::LAYER_MODES[i], BlendMode::LAYER_MODES[i + 1])).collect(); + assert_eq!( + lines, + [ + (BlendMode::Dissolve, BlendMode::Darken), + (BlendMode::DarkerColor, BlendMode::Lighten), + (BlendMode::LighterColor, BlendMode::Overlay), + (BlendMode::HardMix, BlendMode::Difference), + (BlendMode::Divide, BlendMode::Hue), + ], + "row gaps {gaps:?}" + ); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 38118955c3..56f7796f9f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2563,6 +2563,9 @@ mod warp_text_dialog_tests; #[cfg(test)] mod blend_dropdown_wheel_tests; +#[cfg(test)] +mod blend_dropdown_groups_tests; + #[cfg(test)] mod options_bar_mode_wheel_tests; diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 733f923c8a..0d84710549 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1263,7 +1263,14 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { opt_label(ui, tl!("Mode")); let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect(); // The wheel over it steps the mode, as over the Layers panel's (#2061). - widgets::dropdown_wheel_hovered(ui, "gradient-blend-mode", &mut app.ui.tool_options.gradient_blend_mode, &opts, 96.0); + widgets::dropdown_wheel_grouped( + ui, + "gradient-blend-mode", + &mut app.ui.tool_options.gradient_blend_mode, + &opts, + 96.0, + |m| starts_blend_group(*m), + ); opt_label(ui, tl!("Opacity")); let r = widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0); // Live while scrubbed, one undo step per scrub (#5012). @@ -2149,6 +2156,13 @@ fn blend_options(groups: bool, current: BlendMode) -> Vec<(BlendMode, &'static s std::iter::once(BlendMode::PassThrough).filter(|_| groups).chain(BlendMode::LAYER_MODES).chain(own).map(|m| (m, m.label())).collect() } +/// Whether blend mode `m` starts one of the groups Photoshop's blend mode lists draw a line above: +/// Normal, Dissolve (and Pass Through, Clear) | darken | lighten | contrast | difference | colour +/// (#5532). The first mode of a list never gets a line. +pub(crate) fn starts_blend_group(m: BlendMode) -> bool { + matches!(m, BlendMode::Darken | BlendMode::Lighten | BlendMode::Overlay | BlendMode::Difference | BlendMode::Hue) +} + /// Scroll the Layers panel while holding a layer drag over its top/bottom edge or past them. /// /// Returns the *content* displacement in points for this frame, so positive moves the @@ -2240,7 +2254,8 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let opacity_label = if t.pro { tl!("Opacity:") } else { tl!("Opacity") }; let (blend_width, show_opacity_label) = opacity_row_layout(ui.available_width(), body_text_width(ui, opacity_label), ui.spacing().item_spacing.x); - let (chosen, hovered) = widgets::dropdown_wheel_hovered(ui, "blend", &mut m, &blend_options(l.is_group(), l.blend), blend_width); + let (chosen, hovered) = + widgets::dropdown_wheel_grouped(ui, "blend", &mut m, &blend_options(l.is_group(), l.blend), blend_width, |m| starts_blend_group(*m)); // One step per choice: a click, an arrow key or each wheel notch (#1747). for m in &chosen { actions.push(("layer.setProps".into(), json!({"layer": l.id.0, "blend": m.label()}))); @@ -3748,7 +3763,7 @@ fn paint_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraft_engine::B let at = opts.iter().position(|o| o.0 == Some(BlendMode::Dissolve)).map_or(opts.len(), |i| i + 1); opts.insert(at, (None, "Clear")); let mut mode = if *clear || held { None } else { Some(b.mode) }; - if !widgets::dropdown_wheel_hovered(ui, id, &mut mode, &opts, 96.0).0.is_empty() { + if !widgets::dropdown_wheel_grouped(ui, id, &mut mode, &opts, 96.0, |m| m.is_some_and(starts_blend_group)).0.is_empty() { *clear = mode.is_none(); if let Some(m) = mode { b.mode = m; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index e642dfc3e6..bfaab548e7 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1295,7 +1295,7 @@ pub fn dropdown(ui: &mut Ui, id: &str, current: &mut T, op /// [`dropdown`], also returning the option under the pointer in its open list (live previews). pub fn dropdown_hovered(ui: &mut Ui, id: &str, current: &mut T, options: &[(T, &str)], width: f32) -> (bool, Option) { - let (chosen, hovered) = dropdown_with(ui, id, current, options, width, false); + let (chosen, hovered) = dropdown_with(ui, id, current, options, width, false, &|_| false); (!chosen.is_empty(), hovered) } @@ -1306,10 +1306,32 @@ pub fn dropdown_hovered(ui: &mut Ui, id: &str, current: &m /// in order (one per notch; the last is `current`) and the option under the pointer in the open /// list, none while the pointer rests where the wheel last stepped. pub fn dropdown_wheel_hovered(ui: &mut Ui, id: &str, current: &mut T, options: &[(T, &str)], width: f32) -> (Vec, Option) { - dropdown_with(ui, id, current, options, width, true) + dropdown_with(ui, id, current, options, width, true, &|_| false) } -fn dropdown_with(ui: &mut Ui, id: &str, current: &mut T, options: &[(T, &str)], width: f32, wheel: bool) -> (Vec, Option) { +/// [`dropdown_wheel_hovered`] whose open list draws a line above each option (but the first) that +/// `starts_group`: Photoshop's blend mode lists group their modes (#5532). The lines are only +/// drawn: the options, their order and how the wheel, the keys and the pointer pick them stay. +pub fn dropdown_wheel_grouped( + ui: &mut Ui, + id: &str, + current: &mut T, + options: &[(T, &str)], + width: f32, + starts_group: impl Fn(&T) -> bool, +) -> (Vec, Option) { + dropdown_with(ui, id, current, options, width, true, &starts_group) +} + +fn dropdown_with( + ui: &mut Ui, + id: &str, + current: &mut T, + options: &[(T, &str)], + width: f32, + wheel: bool, + starts_group: &dyn Fn(&T) -> bool, +) -> (Vec, Option) { let label = options.iter().find(|(v, _)| v == current).map(|(_, l)| tl!(l)).unwrap_or("—"); let (mut chosen, mut hovered) = (Vec::new(), None); // The wheel's notches add up over the button and the open list alike. @@ -1344,7 +1366,10 @@ fn dropdown_with(ui: &mut Ui, id: &str, current: &mut T, o // The row nearest the pointer, by its distance to each row. let pointer = ui.ctx().pointer_hover_pos().filter(|_| ui.rect_contains_pointer(ui.clip_rect())); let mut nearest: Option<(f32, &T)> = None; - for (v, l) in options { + for (i, (v, l)) in options.iter().enumerate() { + if i > 0 && starts_group(v) { + list_separator(ui); + } let item = ui.selectable_label(v == current, tl!(l)); if reveal && v == current { item.scroll_to_me(None); @@ -1388,6 +1413,15 @@ fn dropdown_with(ui: &mut Ui, id: &str, current: &mut T, o (chosen, hovered) } +/// A line between two groups of an open dropdown list's options, as wide as the list. Like egui's +/// separator it takes no width while egui sizes the list, so it never widens it. +fn list_separator(ui: &mut Ui) { + let t = Tokens::get(ui.ctx()); + let width = if ui.is_sizing_pass() { 0.0 } else { ui.available_width() }; + let (rect, _) = ui.allocate_exact_size(vec2(width, 1.0), Sense::hover()); + ui.painter().hline(rect.x_range(), rect.center().y, Stroke::new(1.0, t.separator)); +} + /// Makes an open dropdown list as wide as its widest option is when hovered, from the start. egui /// takes a plain row's frame stroke off its padding but draws a hovered row with the stroke, so a /// row grows by two stroke widths under the pointer, and the list never shrinks back: scrolling @@ -2387,6 +2421,17 @@ mod tests { assert!(rows.last().is_some_and(|r| !list.contains_rect(*r)), "the last rows scroll: {rows:?}"); } + /// A dropdown not given groups draws no lines between its options: the rows are evenly spaced + /// (#5532, only blend mode lists group theirs). + #[test] + fn dropdown_list_without_groups_has_no_separators() { + let h = open_blend_modes(1000.0, 0.0); + let rows = mode_rows(&h); + let gaps: Vec = rows.windows(2).map(|w| w[1].top() - w[0].bottom()).collect(); + let (lo, hi) = gaps.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), g| (lo.min(*g), hi.max(*g))); + assert!(hi - lo < 1.0, "even row gaps: {gaps:?}"); + } + /// The open list opens at the button's left edge, below it or moved up over it to fit, and /// stays put while the wheel steps through every mode over it (#1747), although the button /// widens for the longer names (#5495). From 42e831fa305003cb07b09d479c14b558e7e12d14 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 15 Oct 2026 14:00:07 +0200 Subject: [PATCH 08/44] History Options: no duplicate snapshot when saving an unchanged document (#2966) Automatically Create New Snapshot When Saving adds no row when the document is unchanged since the snapshot the previous save added (and that snapshot is still there), so Ctrl+S on a clean document doesn't stack duplicates. The new snapshot's tiles are trimmed against the history budget at once, and its memory cost is documented: snapshots count against History & Cache by dropping the oldest states, but are never dropped themselves. Tests: the engine dedupe, and the desktop save path (a save adds one, Save a Copy none, a background save finishing on another document snapshots the document it saved). The purge test from main deletes the first snapshot so it measures only the snapshot it takes. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/history_cmds.rs | 3 ++ crates/engine/src/history_options_cmds.rs | 45 +++++++++++++++++++- crates/engine/src/lib.rs | 4 ++ crates/ui-egui/src/save_identity_tests.rs | 50 +++++++++++++++++++++++ docs/control-protocol.md | 2 +- docs/scorecard.md | 4 +- 6 files changed, 103 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/history_cmds.rs b/crates/engine/src/history_cmds.rs index d5736d1b1b..0a943f62fb 100644 --- a/crates/engine/src/history_cmds.rs +++ b/crates/engine/src/history_cmds.rs @@ -503,6 +503,9 @@ mod tests { #[test] fn purging_histories_frees_only_what_no_snapshot_keeps() { let mut s = session(); + // Only the snapshot taken here: the first snapshot (the document as opened) would keep + // tiles of the oldest states too. + s.execute("history.deleteSnapshot", json!({"snapshot": 0})).unwrap(); s.execute("history.newSnapshot", json!({})).unwrap(); s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); let st = s.active().unwrap(); diff --git a/crates/engine/src/history_options_cmds.rs b/crates/engine/src/history_options_cmds.rs index c812b0d6d0..5ea1d4bcaa 100644 --- a/crates/engine/src/history_options_cmds.rs +++ b/crates/engine/src/history_options_cmds.rs @@ -62,19 +62,36 @@ pub fn show_new_snapshot_dialog(s: &Session) -> bool { /// History Options › Automatically Create New Snapshot When Saving: after the active document /// was saved to its own file (not a copy or an export), add a snapshot of it named with the local /// time of the save, as Photoshop does. Not a history state. Returns the new snapshot's id, or -/// `None` when the option is off or no document is active. Shells call it where they record a -/// document save. +/// `None` when the option is off, no document is active, or the document is unchanged since the +/// snapshot the previous save added (and that snapshot is still there), so saving a clean +/// document again doesn't add a duplicate row. Shells call it where they record a document save. +/// +/// Memory: like every History panel snapshot, each one pins a copy of the document for the +/// session (only the tiles that differ from the document and the other snapshots cost memory). +/// [`crate::DocState::trim_history`] counts those tiles against the History & Cache budget by +/// dropping the oldest history states, but never drops a snapshot itself: many saves of a +/// changing document can hold more than the budget until snapshots are deleted or the document +/// is closed. pub fn snapshot_on_save(s: &mut Session) -> Option { if !s.prefs().history_options.automatically_create_new_snapshot_when_saving { return None; } let st = s.active_mut()?; + // Saved again without a change: the previous save's snapshot already shows this document. + if let Some(prev) = st.save_snapshot + && st.snapshots.iter().any(|snap| snap.id == prev && std::sync::Arc::ptr_eq(&snap.doc, &st.doc)) + { + return None; + } let name = save_snapshot_name().unwrap_or_else(|| crate::history_cmds::next_snapshot_name(st)); let id = st.next_snapshot; st.next_snapshot = id.saturating_add(1); let (doc, layers) = (st.doc.clone(), st.layer_target()); // Like the camera button: the document and its saved state are unchanged. st.snapshots.push(Snapshot { id, name, doc, layers }); + st.save_snapshot = Some(id); + // The snapshot's tiles count against the history budget. + st.trim_history(); Some(id) } @@ -400,6 +417,30 @@ mod tests { assert_eq!(snapshot_on_save(&mut empty), None); } + /// Saving an unchanged document again (⌘S on a clean document) adds no duplicate row; a + /// change, or deleting the previous save's snapshot, makes the next save add one again. + #[test] + fn saving_an_unchanged_document_adds_no_duplicate_snapshot() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute(CMD, json!({"automaticallyCreateNewSnapshotWhenSaving": true})).unwrap(); + let first = snapshot_on_save(&mut s).unwrap(); + assert_eq!(snapshot_on_save(&mut s), None, "unchanged since the last save snapshot"); + assert_eq!(snapshot_names(&s).len(), 2, "the first snapshot and one save snapshot"); + // A view-only change (no document change) doesn't count either. + s.active_mut().unwrap().revision += 1; + assert_eq!(snapshot_on_save(&mut s), None); + // An edit does. + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let second = snapshot_on_save(&mut s).unwrap(); + assert!(second > first); + assert_eq!(snapshot_on_save(&mut s), None); + // The previous save's snapshot deleted: the next save shows the document again. + s.execute("history.deleteSnapshot", json!({"snapshot": second})).unwrap(); + assert!(snapshot_on_save(&mut s).is_some()); + assert_eq!(snapshot_names(&s).len(), 3); + } + #[test] fn show_new_snapshot_dialog_reads_the_option() { let mut s = Session::new(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a443454027..ca86984045 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -235,6 +235,9 @@ pub struct DocState { pub snapshots: Vec, /// The id the next snapshot gets; ids are never reused, so deleting one keeps the others. next_snapshot: u64, + /// The snapshot the latest save added (History Options › Automatically Create New Snapshot + /// When Saving), so saving an unchanged document again doesn't add a duplicate row. + save_snapshot: Option, } impl DocState { @@ -283,6 +286,7 @@ impl DocState { color_samplers: Vec::new(), snapshots: vec![first], next_snapshot: 1, + save_snapshot: None, } } /// The selected layers in bottom-to-top document order, always including the active layer. diff --git a/crates/ui-egui/src/save_identity_tests.rs b/crates/ui-egui/src/save_identity_tests.rs index c947afc9b6..aa535a9d46 100644 --- a/crates/ui-egui/src/save_identity_tests.rs +++ b/crates/ui-egui/src/save_identity_tests.rs @@ -254,3 +254,53 @@ fn save_settings_start_at_the_opened_files_encoding() { app.open_bytes("art.webp", &lossless).unwrap(); assert!(app.save_settings().webp_lossless); } + +/// The names of the active document's History panel snapshots. +fn snapshots(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().snapshots.iter().map(|s| s.name.clone()).collect() +} + +/// History Options › Automatically Create New Snapshot When Saving (#2966) through the desktop +/// save path: a save adds one snapshot, saving again unchanged adds none, Save a Copy adds none. +#[test] +fn a_save_adds_one_snapshot_and_a_copy_none() { + let mut app = app(); + app.run("history.options", json!({"automaticallyCreateNewSnapshotWhenSaving": true})).unwrap(); + let before = snapshots(&app).len(); + app.save_as(Some("saved.psd".into())).unwrap(); + assert_eq!(snapshots(&app).len(), before + 1, "the save adds a snapshot"); + let st = app.session.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&st.snapshots.last().unwrap().doc, &st.doc), "of the document as saved"); + app.save_as(Some("saved.psd".into())).unwrap(); + assert_eq!(snapshots(&app).len(), before + 1, "saving an unchanged document adds no duplicate"); + + app.run("layer.new.layer", json!({})).unwrap(); + app.write_document("copy.psd".into(), &ExportSettings::default(), true).unwrap(); + assert_eq!(snapshots(&app).len(), before + 1, "Save a Copy adds none"); + app.save_as(Some("saved.psd".into())).unwrap(); + assert_eq!(snapshots(&app).len(), before + 2); +} + +/// A background save that finishes while another document is active snapshots the document it +/// saved, not the active one. +#[test] +fn a_background_save_snapshots_its_own_document() { + let mut app = app(); + app.run("history.options", json!({"automaticallyCreateNewSnapshotWhenSaving": true})).unwrap(); + let (saved_doc, revision) = { + let st = app.session.active().unwrap(); + (st.doc.id, st.revision) + }; + let saved_snaps = snapshots(&app).len(); + app.run("file.new", json!({"width": 4, "height": 4, "name": "Untitled-2"})).unwrap(); + let active = app.active_doc_id().unwrap(); + assert_ne!(active, saved_doc); + let active_snaps = snapshots(&app).len(); + // What jobs_ui does when the save job of `saved_doc` ends. + app.saved(saved_doc, revision, "background.psd", &[], false); + assert_eq!(app.active_doc_id(), Ok(active), "the active document stays active"); + assert_eq!(snapshots(&app).len(), active_snaps, "the active document gets no snapshot"); + let st = app.session.documents().iter().find(|st| st.doc.id == saved_doc).unwrap(); + assert_eq!(st.snapshots.len(), saved_snaps + 1, "the saved document gets one"); + assert_eq!(st.path.as_deref(), Some("background.psd")); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index fb6870b3a2..47a59fd04d 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -112,7 +112,7 @@ store expose and persist the same setting; scripts keep using canonical command | `layer.newAdjustmentLayer.hueSaturation` | `{"hue":30,"saturation":10}` | | `paint.stroke` | `{"points":[[x,y,pressure],…],"size":20,"color":"#ff0000"}` | | `select.rect` | `{"x":0,"y":0,"width":100,"height":50,"mode":"add","ellipse":false}` | -| `document.inspect` | `{}`: layer tree, history, snapshots (`[{id, name}]`, for `history.selectSnapshot`; id 0 is the document as opened, unless `history.options` `automaticallyCreateFirstSnapshot` is off), selection bounds | +| `document.inspect` | `{}`: layer tree, history, snapshots (`[{id, name}]`, for `history.selectSnapshot`; id 0 is the document as opened, unless `history.options` `automaticallyCreateFirstSnapshot` is off; with `automaticallyCreateNewSnapshotWhenSaving` on, each save of a changed document adds one named `HH:MM:SS`, or `Snapshot N` in the browser; every snapshot keeps its copy of the document for the session: its tiles count against the History & Cache budget by dropping the oldest history states, but snapshots are never dropped themselves), selection bounds | | `layer.list` | `{"document":index?,"flat":bool?}`: just the layers, top-down: `id`, `name`, `kind`, `visible`, `bounds` (`[x,y,w,h]` or null), `selected`, `active`; groups list their `children`, or with `flat` every layer is one row with its `depth` and `parent` group id | | `document.pixel` | `{"x":10,"y":10}`: composite RGBA | | `document.presets.list` | `{}` → `{presets:[{name,settings}]}`: saved New Document configurations | diff --git a/docs/scorecard.md b/docs/scorecard.md index 1e0576ba02..beab3671e1 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 7 | 14 | 6 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 188/256, round trip ≥ 258/256 | | [Tools](#tools) | 33 | 11 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 166 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 171 (target 0) | | [Type](#type) | 4 | 3 | 2 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 29 of 29 crates; panic_hunt present | @@ -177,7 +177,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 26 of 166** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 26 of 171** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. From 9b227c2c5bfdde2000f784b11cfa50b6cc75540c Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 20 Oct 2026 19:49:23 +0200 Subject: [PATCH 09/44] Regenerate docs/scorecard.md Co-Authored-By: Claude Opus 5.5 --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index c4b53a20f8..d675bbec72 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 24 | 58 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 19 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 7 | 14 | 6 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 188/256, round trip ≥ 258/256 | | [Tools](#tools) | 33 | 11 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 25 of 169 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 25 of 174 (target 0) | | [Type](#type) | 4 | 3 | 2 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -179,7 +179,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 25 of 169** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 25 of 174** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. From 0427d52cbb5d445dfefb1d0d286bfb653c07d475 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 12:17:13 +0200 Subject: [PATCH 10/44] Fix up the merges of #3535, #3567 and #6088: one catalog line per string, purge test as in #3567 The merges left the History Options and New Snapshot strings twice in the hu, sr, tr and vi catalogs (this branch's old copies next to #3535's and #3567's), which the catalog consistency test refuses; the owners' lines stay. The purge-histories test had both #3567's and this branch's edits; it is #3567's again. A test checks the snapshots against #3535's current visibility rule: with visibility changes not undoable, undoing the selection of the first snapshot or a save snapshot hides a layer the eye hid again, and Redo shows it. Regenerated docs/scorecard.md. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/history_cmds.rs | 3 --- crates/engine/src/history_options_cmds.rs | 27 +++++++++++++++++++++++ crates/ui-egui/src/i18n/hu.tsv | 5 ----- crates/ui-egui/src/i18n/sr.tsv | 3 --- crates/ui-egui/src/i18n/tr.tsv | 5 ----- crates/ui-egui/src/i18n/vi.tsv | 3 --- docs/scorecard.md | 4 ++-- 7 files changed, 29 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/history_cmds.rs b/crates/engine/src/history_cmds.rs index 2242ce98d0..4c352ad4b9 100644 --- a/crates/engine/src/history_cmds.rs +++ b/crates/engine/src/history_cmds.rs @@ -516,9 +516,6 @@ mod tests { #[test] fn purging_histories_frees_only_what_no_snapshot_keeps() { let mut s = session(); - // Only the snapshot taken here: the first snapshot (the document as opened) would keep - // tiles of the oldest states too. - s.execute("history.deleteSnapshot", json!({"snapshot": 0})).unwrap(); s.execute("history.newSnapshot", json!({})).unwrap(); s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); let st = s.active().unwrap(); diff --git a/crates/engine/src/history_options_cmds.rs b/crates/engine/src/history_options_cmds.rs index 60f97098b4..5f04c55888 100644 --- a/crates/engine/src/history_options_cmds.rs +++ b/crates/engine/src/history_options_cmds.rs @@ -553,6 +553,33 @@ mod tests { assert_eq!(crate::inspect::session(&s)["historyOptions"]["showNewSnapshotDialogByDefault"], json!(true)); } + /// The first snapshot and a save snapshot are recorded steps like any other: with Make Layer + /// Visibility Changes Undoable off, selecting one that shows a layer the eye hid, then Undo, + /// hides the layer again, and Redo shows it (the step changed it, #3535's rule). + #[test] + fn selecting_a_snapshot_undoes_its_own_visibility_change() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap().0; + // Red, not the white document as opened (`red` only reads the red channel). + let red = |s: &Session| s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().surface().unwrap().pixel(1, 1)[1] < 0.5; + s.execute(CMD, json!({"makeLayerVisibilityChangesUndoable": false, "automaticallyCreateNewSnapshotWhenSaving": true})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.active_mut().unwrap().saved_to("saved.psd".into()); + let saved = snapshot_on_save(&mut s).unwrap(); + // The eye hides the layer: no state. + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + for (snap, is_red) in [(0, false), (saved, true)] { + s.execute("history.selectSnapshot", json!({"snapshot": snap})).unwrap(); + assert!(visible(&s, id) && red(&s) == is_red, "snapshot {snap} shows the layer as it was"); + s.execute("edit.undo", json!({})).unwrap(); + assert!(!visible(&s, id) && red(&s), "undoing snapshot {snap} hides the layer again"); + s.execute("edit.redo", json!({})).unwrap(); + assert!(visible(&s, id) && red(&s) == is_red, "redoing snapshot {snap} shows it"); + s.execute("edit.undo", json!({})).unwrap(); + } + } + /// With the oldest state current, non-linear Delete is still enabled for a later (dimmed) /// state (the History panel's trash and its drop target ask for it); linear history has /// nothing to delete there. diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0825e7c7c9..4f2b0c5eb4 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3702,12 +3702,7 @@ cameraRaw Yellow Sárga Auto-leading % Automatikus sorköz % Automatically Create First Snapshot Első pillanatkép automatikus létrehozása Automatically Create New Snapshot When Saving Új pillanatkép automatikus létrehozása mentéskor - From: Forrás: - Full Document Teljes dokumentum - Merged Layers Egyesített rétegek History Options… Előzménybeállítások… - Allow Non-Linear History Nemlineáris előzmények engedélyezése - Make Layer Visibility Changes Undoable A rétegláthatóság módosításai visszavonhatók legyenek Avoid Widows/Orphans Fattyúsorok elkerülése Blend RGB Colors Using Gamma 1.0 RGB-színek keverése 1,0 gammával Blending Mode Keverési mód diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 513dcd47bb..275d0a3ac0 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -2290,9 +2290,6 @@ History Options… Opcije istorije… Allow Non-Linear History Dozvoli nelinearnu istoriju Make Layer Visibility Changes Undoable Omogući opozivanje promena vidljivosti slojeva - From: Od: - Full Document Ceo dokument - Merged Layers Spojeni slojevi Panel Options… Opcije panela… View menu Meni prikaza Keep view in sync Drži prikaz usklađenim diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 84cd0aeec5..d045880b51 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2697,12 +2697,7 @@ cameraRaw Color Renk Set New Snapshot as Default Yeni Anlık Görüntüyü Varsayılan Olarak Ayarla Automatically Create First Snapshot İlk Anlık Görüntüyü Otomatik Olarak Oluştur Automatically Create New Snapshot When Saving Kaydederken Otomatik Olarak Yeni Anlık Görüntü Oluştur - From: Kaynak: - Full Document Tam Belge - Merged Layers Birleştirilmiş Katmanlar History Options… Geçmiş Seçenekleri… - Allow Non-Linear History Doğrusal Olmayan Geçmişe İzin Ver - Make Layer Visibility Changes Undoable Katman Görünürlüğü Değişikliklerini Geri Alınabilir Yap Show New Snapshot Dialog by Default Yeni Anlık Görüntü İletişim Kutusunu Varsayılan Olarak Göster Clear History Geçmişi Temizle Panel Options… Panel Seçenekleri… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 521ab4fdc3..4e919df810 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3670,9 +3670,6 @@ curves Smooth Làm mượt set in Print Settings… đặt trong thiết lập in… ICO is limited to 256 × 256 pixels ICO giới hạn ở 256 × 256 pixel # History panel › History Options… (#2966) - History Options… Tùy chọn lịch sử… - Allow Non-Linear History Cho phép lịch sử không tuyến tính - Make Layer Visibility Changes Undoable Cho phép hoàn tác thay đổi hiển thị lớp Automatically Create First Snapshot Tự động tạo ảnh chụp trạng thái đầu tiên Automatically Create New Snapshot When Saving Tự động tạo ảnh chụp trạng thái mới khi lưu Show New Snapshot Dialog by Default Mặc định hiện hộp thoại Ảnh chụp trạng thái mới diff --git a/docs/scorecard.md b/docs/scorecard.md index c26e0a8020..7707161883 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 25 | 59 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 20 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 7 | 14 | 6 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 188/256, round trip ≥ 258/256 | | [Tools](#tools) | 33 | 11 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 172 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 175 (target 0) | | [Type](#type) | 4 | 3 | 2 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -180,7 +180,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 26 of 172** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 26 of 175** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.gpu_adapter`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. From a218cf17b5d3542a534a6398132ffe64da25b64f Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 17:10:19 +0200 Subject: [PATCH 11/44] Dropdowns: open the list beside its button, never over it (#5495) A full-height list that didn't fit below its button moved up over it, so the release of the click that opened it chose the row under the pointer (the Layers panel's Blend Mode box picked Hard Light). As in Photoshop the list now opens below the button, or above it when the whole list doesn't fit below and there is more room above, capped to that side's room (the rest scrolls). A release back on the box that opened the list chooses nothing, also where a too-short window still makes a list cover it. Co-Authored-By: Claude Opus 5.5 --- .../ui-egui/src/blend_dropdown_wheel_tests.rs | 29 ++++ crates/ui-egui/src/press_menu.rs | 13 +- crates/ui-egui/src/widgets.rs | 149 +++++++++++++----- 3 files changed, 148 insertions(+), 43 deletions(-) diff --git a/crates/ui-egui/src/blend_dropdown_wheel_tests.rs b/crates/ui-egui/src/blend_dropdown_wheel_tests.rs index 31b28adbda..5e00133164 100644 --- a/crates/ui-egui/src/blend_dropdown_wheel_tests.rs +++ b/crates/ui-egui/src/blend_dropdown_wheel_tests.rs @@ -212,3 +212,32 @@ fn a_wheel_step_ends_the_hover_preview_until_the_pointer_moves() { h.run_steps(3); assert_eq!(previewed(&mut h), Some(BlendMode::Multiply), "a moved pointer previews again"); } + +/// The open list's rect (the one foreground area: no other popup is open). +fn open_list(h: &Harness<'_, PhotocraftApp>) -> Option { + h.ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id))) +} + +/// A plain click on the Layers panel's Blend Mode box, released where it was pressed (after one +/// frame, or after a few as a person's click takes), opens the list beside the box and chooses +/// nothing (#5495 review): the full-height list doesn't fit below the box low in the panel, and +/// it must not open over the box, where the release would pick the row under the pointer. +#[test] +fn a_click_on_the_blend_mode_box_opens_the_list_beside_it_and_changes_nothing() { + for held in [6, 1] { + let mut h = harness(pixel_layer); + let undo = steps(&h); + let button = dropdown(&h); + let at = button.center(); + h.hover_at(at); + h.run_steps(1); + for (pressed, frames) in [(true, held), (false, 4)] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + h.run_steps(frames); + } + assert_eq!((blend(&h), steps(&h)), (BlendMode::Normal, undo), "held {held}: the click chose nothing"); + let Some(list) = open_list(&h) else { panic!("held {held}: the list is open") }; + assert!(!list.intersects(button.shrink(1.0)), "held {held}: the list {list:?} leaves the box {button:?} free"); + assert!(list.top() >= 0.0 && list.bottom() <= 900.0, "held {held}: the list {list:?} is in the window"); + } +} diff --git a/crates/ui-egui/src/press_menu.rs b/crates/ui-egui/src/press_menu.rs index 7110e833b4..ec0be0439e 100644 --- a/crates/ui-egui/src/press_menu.rs +++ b/crates/ui-egui/src/press_menu.rs @@ -130,7 +130,13 @@ impl PressCombo { /// Was option `item` (in the open list `ui`) chosen this frame: clicked, or the press-drag /// gesture that opened the list released on it? The list closes when it was. pub fn chosen(&self, ui: &Ui, item: &Response) -> bool { - let released_on = item.enabled() && item.contains_pointer() && ui.input(|i| i.pointer.primary_released()) && self.owns_gesture(ui.ctx()); + // A release back on the box chooses nothing, also where a list covers the box. + let on_box = |ctx: &egui::Context| { + let at = ctx.input(|i| i.pointer.interact_pos()); + ctx.data(|d| d.get_temp::(gesture_id().with(self.popup))).zip(at).is_some_and(|(b, p)| b.contains(p)) + }; + let released_on = + item.enabled() && item.contains_pointer() && ui.input(|i| i.pointer.primary_released()) && self.owns_gesture(ui.ctx()) && !on_box(ui.ctx()); if released_on { ui.close(); } @@ -145,7 +151,10 @@ impl PressCombo { if pressed && !Popup::is_id_open(ctx, self.popup) { // Opened now, the list counts as open this frame and egui shows it from the next. Popup::open_id(ctx, self.popup); - ctx.data_mut(|d| d.insert_temp(gesture_id(), self.popup)); + ctx.data_mut(|d| { + d.insert_temp(gesture_id(), self.popup); + d.insert_temp(gesture_id().with(self.popup), button.rect); + }); ctx.request_repaint(); } else if self.owns_gesture(ctx) && ctx.input(|i| i.pointer.primary_released() || !i.pointer.primary_down()) { ctx.data_mut(|d| d.remove::(gesture_id())); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 57fd0db5fc..48bd5c7617 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1635,30 +1635,27 @@ fn combo_box_arrow_keys(ui: &mut Ui, response: &Response, /// off the bottom. egui moves a popup up to keep it in the window, so a menu opened low on the /// screen first shifts up and only scrolls when it is taller than the window. pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R { - let room = popup_max_height(ui.ctx(), ui.spacing()); + // The popup frame's margin and stroke, and a small gap to the window's edges. + let frame = ui.spacing().menu_margin.sum().y + 2.0 + 2.0 * MENU_EDGE; + let room = (crate::work_area::visible_rect(ui.ctx()).height() - frame).max(MENU_MIN_HEIGHT); // A popup's Ui is only as tall as the popup was last frame (400 pt on the first), so ask for // the whole room: the area still shrinks to its rows when they need less. egui::ScrollArea::vertical().max_height(room).min_scrolled_height(room).show(ui, add_contents).inner } -/// The most a popup's rows may take: the part of the window that can be seen (clear of a taskbar a -/// too-tall window runs under, #315), less the popup frame's margin and stroke and a small gap to -/// the window's edges. egui moves a popup up to keep it in the window, so a popup this tall fits. -pub fn popup_max_height(ctx: &egui::Context, spacing: &egui::style::Spacing) -> f32 { - let frame = spacing.menu_margin.sum().y + 2.0 + 2.0 * MENU_EDGE; - (crate::work_area::visible_rect(ctx).height() - frame).max(MENU_MIN_HEIGHT) -} - /// A dropdown: a button showing `selected_text` (at least `width` wide, wider for a longer text) /// whose list (`add_contents`) opens below it on a click. The list is as tall as its options up to -/// the part of the window that can be seen, scrolling only past that (#5495): Photoshop's dropdowns +/// the room the window has on that side, scrolling only past that (#5495): Photoshop's dropdowns /// open at full height. egui's `ComboBox` capped every list at the size its popup takes on the /// frame it opens (`default_area_size`, 400 pt), so the Layers panel's 27 blend modes scrolled. /// -/// The list's left edge is the button's, and a list that doesn't fit below the button moves up -/// over it to stay in the window, never beside it: so it stays put while its value (and with it -/// the button's width) changes, as the wheel steps it over the open list (#1747). The ids are -/// egui's `ComboBox` ones, so `ComboBox::is_open` and [`crate::press_menu::PressCombo`] apply. +/// The list never covers its button, as in Photoshop: it opens below the button, or above it when +/// the whole list doesn't fit below and there is more room above, and scrolls when it doesn't fit +/// on that side either. Over the button, the release of the click that opened it would choose the +/// row under the pointer. Its left edge is the button's and its side only depends on its rows' +/// height, so it stays put while its value (and with it the button's width) changes, as the wheel +/// steps it over the open list (#1747). The ids are egui's `ComboBox` ones, so +/// `ComboBox::is_open` and [`crate::press_menu::PressCombo`] apply. pub fn combo_list( ui: &mut Ui, id_salt: impl egui::AsIdSalt, @@ -1680,16 +1677,21 @@ pub fn combo_list( info.current_text_value = Some(selected_text.text().to_owned()); info }); - let room = popup_max_height(&ctx, ui.spacing()); - // Below the button, or as far up as the list's height (from the last frame) needs. + // The room below and above the button, less the popup frame's margin and stroke. The + // rows' full height is measured on the (invisible) pass that sizes the list as it opens. let visible = crate::work_area::visible_rect(&ctx).shrink(MENU_EDGE); - let height = egui::AreaState::load(&ctx, popup_id).and_then(|s| s.size).map_or(0.0, |s| s.y); - let top = button.rect.bottom().min(visible.bottom() - height).max(visible.top()); - let left = button.rect.left(); + let frame = ui.spacing().menu_margin.sum().y + 2.0; + let below = visible.bottom() - button.rect.bottom() - frame; + let above = button.rect.top() - visible.top() - frame; + let rows_id = popup_id.with("rows"); + let rows = ctx.data(|d| d.get_temp::(rows_id)); + let up = rows.is_some_and(|rows| rows > below) && above > below; + let (align, room) = if up { (egui::RectAlign::TOP_START, above) } else { (egui::RectAlign::BOTTOM_START, below) }; + let room = room.max(MENU_MIN_HEIGHT); let inner = egui::Popup::menu(&button) .id(popup_id) - .anchor(Rect::from_x_y_ranges(left..=left, top..=top)) - .align(egui::RectAlign::BOTTOM_START) + .anchor(button.rect) + .align(align) .align_alternatives(&[]) .width(button.rect.width()) .close_behavior(close) @@ -1698,15 +1700,14 @@ pub fn combo_list( ui.set_min_width(ui.available_width()); // A popup's Ui is only as tall as the popup was last frame (400 pt on the first), // so ask for the whole room: the area still shrinks to its rows when they need less. - egui::ScrollArea::vertical() - .max_height(room) - .min_scrolled_height(room) - .show(ui, |ui| { - // Options don't wrap in a list as narrow as its button: they widen it. - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); - add_contents(ui) - }) - .inner + let scroll = egui::ScrollArea::vertical().max_height(room).min_scrolled_height(room).show(ui, |ui| { + // Options don't wrap in a list as narrow as its button: they widen it. + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); + add_contents(ui) + }); + let rows = scroll.content_size.y; + ui.ctx().data_mut(|d| d.insert_temp(rows_id, rows)); + scroll.inner }) .map(|r| r.inner); egui::InnerResponse::new(inner, button) @@ -2655,21 +2656,32 @@ mod tests { assert!(rows.last().is_some_and(|r| !list.contains_rect(*r)), "the last rows scroll: {rows:?}"); } - /// The open list opens at the button's left edge, below it or moved up over it to fit, and - /// stays put while the wheel steps through every mode over it (#1747), although the button - /// widens for the longer names (#5495). + /// The open list opens at the button's left edge, below the button or above it, never over it + /// (#5495 review: a click released in place would choose the row under the pointer): below + /// when the whole list fits there, else on the side with more room, scrolling when it doesn't + /// fit there either. It stays put while the wheel steps through every mode over it (#1747), + /// although the button widens for the longer names. #[test] - fn dropdown_list_stays_put_while_the_wheel_steps_its_value() { + fn dropdown_list_opens_beside_its_button_and_stays_put_while_the_wheel_steps_its_value() { use photocraft_color::BlendMode; - // A tall window with room below the button, and a 900 pt one with the button half way down. - for (height, down) in [(1000.0, 0.0), (900.0, 420.0)] { + // (window height, button's distance from the top, list below it, all modes in sight) + let cases = [ + (1000.0, 0.0, true, true), // room below + (900.0, 420.0, true, false), // room on neither side, more below + (900.0, 520.0, false, false), // room on neither side, more above + (1000.0, 900.0, false, true), // room above only, near the bottom edge + (300.0, 150.0, false, false), // a window shorter than the list + ]; + for (height, down, below, all) in cases { let mut h = open_blend_modes(height, down); let button = h.get_by_role(egui::accesskit::Role::ComboBox).rect(); let list = open_list(&h); - assert!(list.top() >= 0.0 && list.bottom() <= height, "{height}: the list {list:?} is in the window"); - assert!((list.left() - button.left()).abs() < 8.0, "{height}: the list {list:?} starts at the button {button:?}"); + assert!(list.top() >= 0.0 && list.bottom() <= height, "{height}/{down}: the list {list:?} is in the window"); + assert!((list.left() - button.left()).abs() < 8.0, "{height}/{down}: the list {list:?} starts at the button {button:?}"); + assert!(!list.intersects(button.shrink(1.0)), "{height}/{down}: the list {list:?} leaves the button {button:?} free"); + assert_eq!(list.top() >= button.bottom() - 1.0, below, "{height}/{down}: the list {list:?} is below the button {button:?}"); let rows = mode_rows(&h); - assert!(rows.iter().all(|r| list.contains_rect(*r)), "{height}: all modes show in {list:?}"); + assert_eq!(rows.iter().all(|r| list.contains_rect(*r)), all, "{height}/{down}: all modes show in {list:?}"); let over = list.center(); for _ in 1..BlendMode::LAYER_MODES.len() { h.hover_at(over); @@ -2680,12 +2692,67 @@ mod tests { modifiers: Modifiers::NONE, }); h.run_steps(3); - assert_eq!(open_list(&h), list, "{height}: the list stays put at {:?}", h.state()); + assert_eq!(open_list(&h), list, "{height}/{down}: the list stays put at {:?}", h.state()); } - assert_eq!(*h.state(), BlendMode::Luminosity, "{height}: the wheel stepped through every mode"); + assert_eq!(*h.state(), BlendMode::Luminosity, "{height}/{down}: the wheel stepped through every mode"); } } + /// A short list opens below its button when it fits there, and above it near the window's + /// bottom edge, whole either way. + #[test] + fn a_short_dropdown_list_opens_below_or_above_its_button_whole() { + for (down, below) in [(100.0, true), (360.0, false)] { + let mut h = Harness::builder().with_size(egui::vec2(300.0, 400.0)).build_ui_state( + move |ui, selected: &mut usize| { + ui.add_space(down); + super::dropdown(ui, "blend-mode", selected, &MODES, 120.0); + }, + 0, + ); + h.run(); + h.get_by_role(egui::accesskit::Role::ComboBox).click(); + h.run_steps(4); + let button = h.get_by_role(egui::accesskit::Role::ComboBox).rect(); + let list = open_list(&h); + assert_eq!(list.top() >= button.bottom() - 1.0, below, "{down}: the list {list:?} is below the button {button:?}"); + assert!(!list.intersects(button.shrink(1.0)), "{down}: the list {list:?} leaves the button {button:?} free"); + for (_, label) in MODES { + let row = h.get_all_by_label(label).last().map(|n| n.rect()).unwrap_or(egui::Rect::NOTHING); + assert!(list.contains_rect(row), "{down}: {label} {row:?} shows in {list:?}"); + } + assert!(list.height() < 150.0, "{down}: the list {list:?} is only as tall as its rows"); + assert_eq!(*h.state(), 0, "{down}: the click chose nothing"); + } + } + + /// In a window too short for the list on either side the list still covers its button; the + /// release of the click that opened it, held a few frames, chooses nothing (#5495 review). + #[test] + fn the_release_of_the_opening_click_chooses_nothing_where_the_list_covers_the_button() { + use photocraft_color::BlendMode; + let mut h = Harness::builder().with_size(egui::vec2(400.0, 110.0)).build_ui_state( + |ui, mode: &mut BlendMode| { + ui.add_space(40.0); + let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect(); + super::dropdown_wheel_hovered(ui, "blend-mode", mode, &opts, 120.0); + }, + BlendMode::Normal, + ); + h.run(); + let button = h.get_by_role(egui::accesskit::Role::ComboBox).rect(); + let at = button.center(); + h.hover_at(at); + h.run(); + for (pressed, frames) in [(true, 6), (false, 4)] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(frames); + } + let list = open_list(&h); + assert!(list.contains(at), "the list {list:?} covers the button {button:?} here"); + assert_eq!(*h.state(), BlendMode::Normal, "the click chose nothing"); + } + const MODES: [(usize, &str); 4] = [(0, "Normal"), (1, "Dissolve"), (2, "Darken"), (3, "Multiply")]; /// A wheel dropdown (or a plain one) of [`MODES`], whose state is the chosen index. From a4812f6270034ac8291c93ae09bd59648ed390a2 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 17:26:44 +0200 Subject: [PATCH 12/44] Layers: the separator test opens the Blend Mode list in a window tall enough for all of it (#5532) Since #5501's review fix a list that fits on neither side of its box opens below it and scrolls, as at 1440x900, so the test now uses a 1600 pt window to see every group. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/blend_dropdown_groups_tests.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/blend_dropdown_groups_tests.rs b/crates/ui-egui/src/blend_dropdown_groups_tests.rs index de3d1d7d93..8d14adc1f8 100644 --- a/crates/ui-egui/src/blend_dropdown_groups_tests.rs +++ b/crates/ui-egui/src/blend_dropdown_groups_tests.rs @@ -11,9 +11,10 @@ use serde_json::json; use crate::PhotocraftApp; -/// The app with a new document and a pixel layer above the Background, active. +/// The app with a new document and a pixel layer above the Background, active. The window is tall +/// enough for the whole Blend Mode list below its box (at 900 pt it fits on neither side and scrolls). fn harness() -> Harness<'static, PhotocraftApp> { - let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + let mut h = Harness::builder().with_size(vec2(1440.0, 1600.0)).with_max_steps(64).build_eframe(|cc| { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); From bf67b1c43f2cf9756f38789c689dc534c589d3bb Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 20:26:26 +0200 Subject: [PATCH 13/44] Address CodeRabbit review: a dropdown list only takes the room its side has combo_list floored the list's scroll height at 120 pt, so where a side had less room the taller list was pushed back into the window, over its button (and past the window's top in a 110 pt window). It now takes just that side's room and scrolls. The 110 pt test now checks the list leaves the button free and stays in the window, and that the opening click still chooses nothing. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/widgets.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 48bd5c7617..2e3761840b 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1687,7 +1687,9 @@ pub fn combo_list( let rows = ctx.data(|d| d.get_temp::(rows_id)); let up = rows.is_some_and(|rows| rows > below) && above > below; let (align, room) = if up { (egui::RectAlign::TOP_START, above) } else { (egui::RectAlign::BOTTOM_START, below) }; - let room = room.max(MENU_MIN_HEIGHT); + // Only the room that side has, even when it is small: a taller list would be pushed back + // into the window, over its button (#5495 review). + let room = room.max(0.0); let inner = egui::Popup::menu(&button) .id(popup_id) .anchor(button.rect) @@ -2726,10 +2728,11 @@ mod tests { } } - /// In a window too short for the list on either side the list still covers its button; the - /// release of the click that opened it, held a few frames, chooses nothing (#5495 review). + /// In a window with less than 120 pt on either side of the button the list still leaves + /// its button free, scrolling in the room that side has, and stays in the window; the release + /// of the click that opened it, held a few frames, chooses nothing (#5495 review). #[test] - fn the_release_of_the_opening_click_chooses_nothing_where_the_list_covers_the_button() { + fn in_a_very_short_window_the_list_still_leaves_its_button_free_and_the_opening_click_chooses_nothing() { use photocraft_color::BlendMode; let mut h = Harness::builder().with_size(egui::vec2(400.0, 110.0)).build_ui_state( |ui, mode: &mut BlendMode| { @@ -2749,7 +2752,8 @@ mod tests { h.run_steps(frames); } let list = open_list(&h); - assert!(list.contains(at), "the list {list:?} covers the button {button:?} here"); + assert!(!list.intersects(button.shrink(1.0)), "the list {list:?} leaves the button {button:?} free"); + assert!(list.top() >= 0.0 && list.bottom() <= 110.0, "the list {list:?} is in the window"); assert_eq!(*h.state(), BlendMode::Normal, "the click chose nothing"); } From 841af396b7bf51eb87356f922daf434b21e90726 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 00:36:15 +0200 Subject: [PATCH 14/44] Crop: switching documents leaves the old document's view turned (#9202) In default mode a turned crop frame turns its document's view. When another document became active, cancel_stale's cancel turned only the newly active view upright, so the old document kept the crop's turn with no crop on it. Turn the crop document's own view upright first. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/crop_mode.rs | 27 +++++++++++++++++++++++++++ crates/ui-egui/src/crop_ui.rs | 10 ++++++++++ 2 files changed, 37 insertions(+) diff --git a/crates/ui-egui/src/crop_mode.rs b/crates/ui-egui/src/crop_mode.rs index 36bc4d659a..1edf39c9b5 100644 --- a/crates/ui-egui/src/crop_mode.rs +++ b/crates/ui-egui/src/crop_mode.rs @@ -745,6 +745,33 @@ mod tests { assert!(out[0].1 == out[1].1, "same pixels"); } + /// #9202: switching documents drops a turned pending crop and turns its own document's view + /// upright, as Esc would, not only the view of the document switched to. + #[test] + fn switching_documents_turns_the_dropped_crops_view_upright() { + // The crop on the first document, then on the second. + for (on, other) in [(0, 1), (1, 0)] { + let mut app = app(); + app.run("file.new", json!({"width": 300, "height": 150})).unwrap(); + app.sync_views(); + assert!(app.session.set_active(on)); + app.sync_views(); + let v = &mut app.ui.views[on]; + (v.zoom, v.center, v.fit_pending, v.rotation) = (1.0, [100.0, 50.0], false, 0.0); + with_frame(&mut app); + screen_drag(&mut app, &[pos2(450.0, 300.0), pos2(440.0, 320.0), pos2(370.0, 380.0)], NONE); + assert!((view_rotation(&app) - 90.0).abs() < 0.01, "crop on {on}: the view turned with the frame"); + assert!(app.session.set_active(other)); + app.sync_views(); + assert_eq!(app.ui.crop_rect, None, "crop on {on}: the turned crop is dropped"); + app.ui.tool = Tool::Brush; + crate::crop_ui::ensure_frame(&mut app); + assert!(app.session.set_active(on)); + app.sync_views(); + assert_eq!(view_rotation(&app), 0.0, "crop on {on}: its document isn't left turned"); + } + } + #[test] fn picking_the_crop_tool_turns_a_rotated_view_upright() { let mut app = app(); diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index 73e9ce5642..3bbccad1b3 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -592,6 +592,16 @@ pub fn cancel_stale(app: &mut PhotocraftApp) { let pending = app.ui.crop_rect.is_some() || app.crop.drag.is_some(); // A frame made before any document was claimed (control channel, tests) is the active one's. if pending && app.crop.doc.is_some() && app.crop.doc != active { + // Default mode turned the frame's own view, which `cancel` doesn't reach: it turns the + // active one upright, and `ui.views` is still in the order of `view_docs` here (#9202). + if !crate::crop_mode::classic(app) { + let doc = app.crop.doc; + let synced = app.view_docs.iter().position(|d| Some(*d) == doc); + let i = synced.or_else(|| app.session.documents().iter().position(|st| Some(st.doc.id) == doc)); + if let Some(v) = i.and_then(|i| app.ui.views.get_mut(i)) { + v.rotation = 0.0; + } + } cancel(app); } app.crop.doc = active; From b2b402939a8cfe3fd2969ab42918a04f8ac27d12 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 00:56:48 +0200 Subject: [PATCH 15/44] Crop W x H budgets the hidden pixels it resamples (#9212) image.crop's target size, Image Size and Bitmap's Output resolution budgeted only the new canvas, but resample_doc scales every surface's whole content, including the pixels a non-deleting crop kept outside the canvas. A 20 px frame of a 2000 px image resampled to 2000 px tried to allocate 160 GB. resample_doc now refuses, before touching the document, when the largest surface it scales would pass the budget (at that surface's own bytes per pixel). A failed compound (the turned crop) also rolls back the painting symmetry its rotation moved. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/analysis_cmds.rs | 3 + crates/engine/src/image_cmds.rs | 116 ++++++++++++++++++++++++--- crates/engine/src/mode_cmds.rs | 2 +- crates/engine/src/mode_cmds/tests.rs | 12 +++ 4 files changed, 121 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/analysis_cmds.rs b/crates/engine/src/analysis_cmds.rs index 8932295d52..55f1ce5b44 100644 --- a/crates/engine/src/analysis_cmds.rs +++ b/crates/engine/src/analysis_cmds.rs @@ -187,6 +187,8 @@ pub(crate) fn compound(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess // Color Sampler points are view state a step may move (crop, rotation): roll them back too, so // a failed second step can't leave them pinned to pixels the restored document no longer has. let samplers = st.color_samplers.clone(); + // So is the painting symmetry, which a rotation moves with the pixels. + let symmetry = st.symmetry.clone(); let r = f(s); if r.is_err() { s.journal.truncate(journal); @@ -210,6 +212,7 @@ pub(crate) fn compound(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess st.channel_view = channel_view; st.coalesce = coalesce; st.color_samplers = samplers; + st.symmetry = symmetry; st.revision += 1; // A failed compound does not make an otherwise untouched document dirty. if was_clean { diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs index 6353f1f2cc..6c30d204f0 100644 --- a/crates/engine/src/image_cmds.rs +++ b/crates/engine/src/image_cmds.rs @@ -254,8 +254,7 @@ fn image_size(s: &mut Session, p: &Value) -> Result { Method::Automatic if nw > ow || nh > oh => Resample::PreserveDetails, Method::Automatic => Resample::BicubicSharper, }; - resample_doc(doc, nw, nh, filter); - Ok(()) + resample_doc(doc, "image.imageSize", nw, nh, filter) })?; // The size the document has now: without resampling `width`/`height` are ignored (#1815). let size = s.active().ok_or(EngineError::NoDocument)?.doc.size; @@ -290,13 +289,15 @@ pub(crate) fn check_working_budget(cmd: &str, doc: &Document, nw: u32, nh: u32, /// Resamples the whole document (pixels, masks, channels, selection, effects, vectors, guides) to /// `nw` x `nh` px with `filter`: the body of Image Size, shared by the Crop tool's W x H x Resolution -/// mode. Callers check [`check_resample_budget`] first. -pub(crate) fn resample_doc(doc: &mut Document, nw: u32, nh: u32, filter: Resample) { +/// mode. Callers check [`check_resample_budget`] for the new canvas first; the pixels outside the +/// canvas are scaled too, so a surface they would grow past the budget is refused here (#9212). +pub(crate) fn resample_doc(doc: &mut Document, cmd: &str, nw: u32, nh: u32, filter: Resample) -> Result<()> { let (ow, oh) = (doc.size.width, doc.size.height); let (sx, sy) = (nw as f64 / ow.max(1) as f64, nh as f64 / oh.max(1) as f64); if (sx - 1.0).abs() < 1e-12 && (sy - 1.0).abs() < 1e-12 { - return; + return Ok(()); } + check_hidden_resample_budget(cmd, doc, sx, sy)?; // Content that reaches the canvas edge keeps it: a Background stays opaque to the border. let canvas = Rect::from_xywh(0, 0, ow, oh); let taken = crate::smart_cmds::take_caches(&mut doc.layers); @@ -325,6 +326,53 @@ pub(crate) fn resample_doc(doc: &mut Document, nw: u32, nh: u32, filter: Resampl doc.size = Size::new(nw, nh); crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::All); let Ok(()) = crate::smart_cmds::restore_unrendered(doc, taken, |c| Ok::<_, Infallible>(resize_surface_in_canvas(c, sx, sy, filter, canvas))); + Ok(()) +} + +/// [`check_resample_budget`] for the largest surface [`resample_doc`] scales by `sx` x `sy`: each +/// keeps its pixels outside the canvas (a crop that didn't delete them, a layer moved off the +/// canvas), and those grow with the scale like the rest. +fn check_hidden_resample_budget(cmd: &str, doc: &mut Document, sx: f64, sy: f64) -> Result<()> { + let canvas = doc.bounds(); + // The largest surface by bytes: its scaled width, height and bytes per pixel (a mask has one + // channel, the layers the document's). + let mut largest = (0u32, 0u32, 1u64); + let mut visit = |surf: &Surface| { + let r = surf.content_bounds(); + // What lies within the canvas scales to within the new canvas, already budgeted. + if r.is_empty() || canvas.union(&r) == canvas { + return; + } + // The output's extent, as `resize_surface_in_canvas` lays it out. + let side = |a: i32, b: i32, k: f64| ((f64::from(b) * k).ceil() - (f64::from(a) * k).floor()).clamp(0.0, f64::from(u32::MAX)) as u32; + let (w, h) = (side(r.x0, r.x1, sx), side(r.y0, r.y1, sy)); + let bpp = surf.format().bytes_per_pixel().max(1) as u64; + let bytes = |(w, h, bpp): (u32, u32, u64)| u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bpp); + if bytes((w, h, bpp)) > bytes(largest) { + largest = (w, h, bpp); + } + }; + // The surfaces `resample_doc` scales, smart object caches included. + for_each_surface(&mut doc.layers, true, &mut |surf, _| visit(surf)); + for ch in doc.channels.iter().chain(doc.quick_mask.as_ref()) { + visit(&ch.surface); + } + if let Some(sel) = &doc.selection { + visit(sel); + } + let (w, h, bpp) = largest; + let px = u64::from(w).saturating_mul(u64::from(h)); + if px.saturating_mul(bpp) <= MAX_RESAMPLE_BYTES { + return Ok(()); + } + let max_mp = MAX_RESAMPLE_BYTES / bpp / 1_000_000; + Err(bad( + cmd, + format!( + "{w} x {h} px is {} megapixels; resampling at this bit depth is limited to {max_mp} megapixels. The pixels outside the canvas are resampled too: choose a smaller size, or delete them first (Crop with Delete Cropped Pixels)", + px / 1_000_000 + ), + )) } fn bad(cmd: &str, msg: impl Into) -> EngineError { @@ -614,8 +662,7 @@ fn crop(s: &mut Session, p: &Value) -> Result { crate::crop_fill::fill_uncovered(doc, *active, &crate::crop_fill::Coverage::crop(r, original.width, original.height))?; } doc.selection = None; - target.apply(doc); - Ok(()) + target.apply(doc) })?; Ok(crop_result(s, json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() }))) } @@ -630,15 +677,16 @@ struct CropTarget { impl CropTarget { /// Applies the target to a document that has just been cropped (inside the crop's history step). - fn apply(&self, doc: &mut Document) { + fn apply(&self, doc: &mut Document) -> Result<()> { if let Some((w, h)) = self.size { // As for Image Size: an Indexed Color document holds only its colour table's colours (#6019). let filter = if doc.mode == ColorMode::Indexed { Resample::Nearest } else { self.filter }; - resample_doc(doc, w, h, filter); + resample_doc(doc, "image.crop", w, h, filter)?; } if let Some(r) = self.resolution { doc.resolution_dpi = r; } + Ok(()) } /// Where Color Sampler points go: shifted by the crop's origin, then scaled with the pixels @@ -803,8 +851,7 @@ fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool, content_awar crate::crop_fill::fill_uncovered(doc, *active, &coverage)?; } doc.selection = None; - crop_target.apply(doc); - Ok(()) + crop_target.apply(doc) }) })?; Ok(crop_result(s, json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "angle": angle }))) @@ -1850,6 +1897,53 @@ mod tests { assert_eq!(doc(&s).size, Size::new(40, 20)); } + /// #9212: a non-deleting crop keeps the pixels outside the frame, and W x H resamples them + /// too. A 20 px frame of a 2000 px Background resampled to 2000 px scales its hidden pixels + /// x100, to 200000 px a side (160 GB at 8 bits, past the 8 GiB budget): refused before + /// allocating, like a target size past the budget. + #[test] + fn crop_target_budgets_the_hidden_pixels_it_resamples() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 2000, "height": 2000})).unwrap(); + s.execute("paint.setSymmetry", json!({"mode": "vertical", "center": [500, 700]})).unwrap(); + let symmetry = s.active().unwrap().symmetry.clone(); + let past = s.active().unwrap().history.past_len(); + let mut p = json!({"x": 0, "y": 0, "width": 20, "height": 20, "deleteCroppedPixels": false, "targetWidth": 2000, "targetHeight": 2000}); + for angle in [None, Some(90)] { + let mut p = p.clone(); + if let Some(a) = angle { + p["angle"] = json!(a); + } + let err = s.execute("image.crop", p).unwrap_err().to_string(); + assert!(err.contains("200000 x 200000 px is 40000 megapixels"), "{angle:?}: {err}"); + assert_eq!(doc(&s).size, Size::new(2000, 2000), "{angle:?}: the document is unchanged"); + assert_eq!(s.active().unwrap().history.past_len(), past, "{angle:?}: no history step"); + // The turned crop rotates first: the painting symmetry turns back with the document. + assert_eq!(s.active().unwrap().symmetry, symmetry, "{angle:?}: the painting symmetry stays"); + } + // Deleting the cropped pixels leaves only the frame to resample. + p["deleteCroppedPixels"] = json!(true); + s.execute("image.crop", p).unwrap(); + assert_eq!(doc(&s).size, Size::new(2000, 2000)); + assert_eq!(s.active().unwrap().history.past_len(), past + 1); + } + + /// #9212: Image Size resamples the pixels outside the canvas as well. After a non-deleting + /// crop to 10 px, 20000 px (400 MP, within the budget) scales the hidden 100 px Background x2000. + #[test] + fn image_size_budgets_the_hidden_pixels_it_resamples() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + s.execute("image.crop", json!({"x": 0, "y": 0, "width": 10, "height": 10, "deleteCroppedPixels": false})).unwrap(); + let past = s.active().unwrap().history.past_len(); + let err = s.execute("image.imageSize", json!({"width": 20000, "height": 20000})).unwrap_err().to_string(); + assert!(err.contains("200000 x 200000 px is 40000 megapixels"), "{err}"); + assert_eq!((doc(&s).size, s.active().unwrap().history.past_len()), (Size::new(10, 10), past)); + // Without resampling only the resolution changes. + s.execute("image.imageSize", json!({"resolution": 300, "resample": "none"})).unwrap(); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(10, 10), 300.0)); + } + #[test] fn crop_target_rejects_bad_params_without_changing_the_document() { let rect = json!({"x": 0, "y": 0, "width": 10, "height": 10}); diff --git a/crates/engine/src/mode_cmds.rs b/crates/engine/src/mode_cmds.rs index 180f940e91..e809c03dae 100644 --- a/crates/engine/src/mode_cmds.rs +++ b/crates/engine/src/mode_cmds.rs @@ -481,7 +481,7 @@ fn bitmap(s: &mut Session, p: &Value) -> Result { } s.edit("Bitmap", |doc, active| { if (nw, nh) != (doc.size.width, doc.size.height) { - crate::image_cmds::resample_doc(doc, nw, nh, photocraft_algo::resample::Resample::Bicubic); + crate::image_cmds::resample_doc(doc, CMD, nw, nh, photocraft_algo::resample::Resample::Bicubic)?; } doc.resolution_dpi = dpi; let px = composite(doc, true); diff --git a/crates/engine/src/mode_cmds/tests.rs b/crates/engine/src/mode_cmds/tests.rs index 84d816a349..57493dcc32 100644 --- a/crates/engine/src/mode_cmds/tests.rs +++ b/crates/engine/src/mode_cmds/tests.rs @@ -399,6 +399,18 @@ fn bitmap_output_resolution_resamples_and_sets_the_resolution() { assert_eq!(first_white(doc(&s), 0, 1, 0), Some(128)); } +/// #9212: the Output resolution resamples the pixels outside the canvas too. A 10 px crop that +/// kept a 1000 px document's pixels, converted from 1 to 100 ppi, would grow them to 100000 px a +/// side (20 GB of gray and alpha at 8 bits, past the 8 GiB budget): refused before allocating. +#[test] +fn bitmap_output_resolution_budgets_the_hidden_pixels() { + let mut s = ramp(1000, 1000, 8, 1.0); + s.execute("image.crop", json!({"x": 0, "y": 0, "width": 10, "height": 10, "deleteCroppedPixels": false})).unwrap(); + let err = s.execute("image.mode.bitmap", json!({"method": "threshold", "resolution": 100})).unwrap_err().to_string(); + assert!(err.contains("100000 x 100000 px is 10000 megapixels"), "{err}"); + assert_eq!((doc(&s).size.width, doc(&s).mode), (10, ColorMode::Grayscale)); +} + #[test] fn bitmap_halftone_screen_is_laid_out_at_the_output_resolution() { // The same 10 lines/inch screen has twice the cell (in pixels) at twice the resolution: the From 1e75581a963a2633c73c066189f7c59d1898390a Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 01:24:01 +0200 Subject: [PATCH 16/44] Crop: a tool switch during a frame drag ends the drag (#9223) A tool key pressed while dragging the crop frame left crop.drag set when the new tool's handler takes every event before the Crop tool's (Perspective Crop, Ruler, Slice, Frame, Artboard), so the frame was neither committed on leave nor cancelled. tool_event now ends the gesture before any handler runs. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 5 +++++ crates/ui-egui/src/crop_ui.rs | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ab3e6939a7..00f6dacfdb 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -5906,6 +5906,11 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { crate::guide_select::clear(app); } + // A tool key pressed mid-drag ends the crop gesture here: a later handler can take every event + // of the new tool, and a drag left set keeps the frame from committing on leave (#9223). + if app.ui.tool != Tool::Crop { + app.crop.drag = None; + } if crate::symmetry_ui::pointer(app, ev, crate::workspace_ui::sticky_mods(app, mods)) { return; } diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index 73e9ce5642..e651507524 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -1855,6 +1855,27 @@ mod tests { assert_eq!(app.session.active().unwrap().doc.size, Size::new(200, 100)); } + /// A tool key pressed while a drag on the frame is held (⇧C to Perspective Crop): the next + /// tool's events end the gesture, even a tool that takes every event before the Crop tool's + /// handler, and leaving then commits the frame as it does for any other tool (#3368). + #[test] + fn a_tool_switch_during_a_drag_ends_it_and_commits_the_frame() { + for tool in [Tool::PerspectiveCrop, Tool::Ruler, Tool::Slice, Tool::Frame, Tool::Artboard, Tool::Brush] { + let mut app = app(SampleType::U8); + ensure_frame(&mut app); + drag(&mut app, &[[20.0, 20.0], [120.0, 80.0]], NONE); + tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 50.0, pressure: 1.0 }, NONE); + assert!(app.crop.drag.is_some()); + app.ui.tool = tool; + tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 50.0, pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Up { x: 70.0, y: 50.0 }, NONE); + assert!(app.crop.drag.is_none(), "{tool:?}"); + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, None, "{tool:?}"); + assert_eq!(app.session.active().unwrap().doc.size, Size::new(100, 60), "{tool:?}"); + } + } + /// Image › Crop with a pending crop commits the frame (the one Image item Photoshop keeps). #[test] fn image_crop_menu_commits_a_pending_crop() { From 60cd5002c455541cff4b5107b6c3091a6a31fe7e Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:40:19 +0200 Subject: [PATCH 17/44] Address CodeRabbit review: a tool switch mid-drag ends the crop gesture as a release would A box drawn over the untouched default frame, or that frame resized by a handle, kept `default_frame` set when another tool's key ended the drag, so leaving dropped the edit instead of committing it. The release logic is now one function both paths run. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/canvas.rs | 5 +- crates/ui-egui/src/crop_ui.rs | 93 ++++++++++++++++++++++++++--------- 2 files changed, 73 insertions(+), 25 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 00f6dacfdb..e1a818091b 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -5907,9 +5907,10 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) crate::guide_select::clear(app); } // A tool key pressed mid-drag ends the crop gesture here: a later handler can take every event - // of the new tool, and a drag left set keeps the frame from committing on leave (#9223). + // of the new tool, and a drag left set keeps the frame from committing on leave. It ends as a + // release would, so a box drawn over the untouched default frame is committed, not dropped (#9223). if app.ui.tool != Tool::Crop { - app.crop.drag = None; + crate::crop_ui::end_drag(app); } if crate::symmetry_ui::pointer(app, ev, crate::workspace_ui::sticky_mods(app, mods)) { return; diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index e651507524..a575cefa73 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -760,7 +760,7 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { /// Pointer input for the Crop tool. Returns true when the event was its. pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool { if app.ui.tool != Tool::Crop { - app.crop.drag = None; + end_drag(app); return false; } let p = match ev { @@ -828,34 +828,52 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool ToolEvent::Move { .. } => update(app, p, mods), ToolEvent::Up { .. } => { update(app, p, mods); - let Some(drag) = app.crop.drag.take() else { return true }; - let ok = app.ui.crop_rect.is_some_and(size_ok); - // A click outside the untouched default frame (no turn) leaves it the default. - let changed = !matches!(drag, CropDrag::Rotate { from, .. } | CropDrag::TurnImage { from, .. } if from == angle(app)) - && !matches!(drag, CropDrag::MoveImage { rect, .. } if app.ui.crop_rect == Some(rect)); - if ok && changed { - app.crop.default_frame = false; - } - match drag { - CropDrag::Draw { prev, .. } if !ok => app.ui.crop_rect = prev, - CropDrag::Move { rect, .. } | CropDrag::Resize { rect, view: None, .. } if !ok => app.ui.crop_rect = Some(rect), - // A live-centred resize collapsed: the frame and the view it moved go back. - CropDrag::Resize { rect, view: Some(view), .. } if !ok => crate::crop_mode::offset_image(app, rect, Some(view), [0.0, 0.0]), - // Auto Center Preview: a box drawn in default mode moves to the middle. (A resized - // one stays where its centre was: `crop_mode::live_resize`.) - CropDrag::Draw { .. } if ok => { - crate::crop_mode::sync_frame(app); - crate::crop_mode::auto_center(app); - } - _ => {} - } - push_press_step(app); + release(app); } } crate::crop_mode::sync_frame(app); true } +/// Another tool was picked while a drag on the frame is held (a tool key, #9223): the gesture ends +/// where the pointer last moved it, as a release there would, so a box drawn over the untouched +/// default frame counts as drawn and leaving the tool commits it. +pub fn end_drag(app: &mut PhotocraftApp) { + if app.crop.drag.is_none() { + return; + } + let tool = std::mem::replace(&mut app.ui.tool, Tool::Crop); + release(app); + crate::crop_mode::sync_frame(app); + app.ui.tool = tool; +} + +/// The release of a drag on the frame, the pointer's last move already applied. +fn release(app: &mut PhotocraftApp) { + let Some(drag) = app.crop.drag.take() else { return }; + let ok = app.ui.crop_rect.is_some_and(size_ok); + // A click outside the untouched default frame (no turn) leaves it the default. + let changed = !matches!(drag, CropDrag::Rotate { from, .. } | CropDrag::TurnImage { from, .. } if from == angle(app)) + && !matches!(drag, CropDrag::MoveImage { rect, .. } if app.ui.crop_rect == Some(rect)); + if ok && changed { + app.crop.default_frame = false; + } + match drag { + CropDrag::Draw { prev, .. } if !ok => app.ui.crop_rect = prev, + CropDrag::Move { rect, .. } | CropDrag::Resize { rect, view: None, .. } if !ok => app.ui.crop_rect = Some(rect), + // A live-centred resize collapsed: the frame and the view it moved go back. + CropDrag::Resize { rect, view: Some(view), .. } if !ok => crate::crop_mode::offset_image(app, rect, Some(view), [0.0, 0.0]), + // Auto Center Preview: a box drawn in default mode moves to the middle. (A resized + // one stays where its centre was: `crop_mode::live_resize`.) + CropDrag::Draw { .. } if ok => { + crate::crop_mode::sync_frame(app); + crate::crop_mode::auto_center(app); + } + _ => {} + } + push_press_step(app); +} + /// On release: the frame state at the press becomes a box Undo step when the gesture changed it. fn push_press_step(app: &mut PhotocraftApp) { if let Some(before) = app.crop.press_step.take() @@ -1876,6 +1894,35 @@ mod tests { } } + /// The same mid-drag tool switch on the untouched default frame: a box drawn over it, or the + /// frame resized by a handle, is an edit and commits on leave; a box too small to keep goes back + /// to the default frame, which leaving drops (#9223). + #[test] + fn a_tool_switch_during_a_drag_on_the_default_frame_keeps_the_edit() { + let cases: [(&[[f64; 2]], Size); 3] = [ + (&[[20.0, 20.0], [120.0, 80.0]], Size::new(100, 60)), + (&[[200.0, 100.0], [150.0, 80.0]], Size::new(150, 80)), + (&[[20.0, 20.0], [20.0, 20.0]], Size::new(200, 100)), + ]; + for (path, size) in cases { + for tool in [Tool::PerspectiveCrop, Tool::Brush] { + let mut app = app(SampleType::U8); + ensure_frame(&mut app); + assert!(app.crop.default_frame); + tool_event(&mut app, ToolEvent::Down { x: path[0][0], y: path[0][1], pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Move { x: path[1][0], y: path[1][1], pressure: 1.0 }, NONE); + assert!(app.crop.drag.is_some()); + app.ui.tool = tool; + tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 50.0, pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Up { x: 70.0, y: 50.0 }, NONE); + assert!(app.crop.drag.is_none(), "{tool:?} {path:?}"); + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, None, "{tool:?} {path:?}"); + assert_eq!(app.session.active().unwrap().doc.size, size, "{tool:?} {path:?}"); + } + } + } + /// Image › Crop with a pending crop commits the frame (the one Image item Photoshop keeps). #[test] fn image_crop_menu_commits_a_pending_crop() { From 9b84eebad8e656b8b61025db35e8b2bd06675fc9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:50:06 +0200 Subject: [PATCH 18/44] Image Size: refuse a resolution outside 1..30000 ppi instead of clamping it (#9260) `image.imageSize` read `resolution` as `as f32` and clamped it to 1..10000, so 1e39 (inf) silently became 10000 ppi, -5 and 0 became 1 ppi, a string was ignored, and a valid 20000 ppi (allowed by File > New, Bitmap and the dialog's own field) dropped to 10000. Parse it once like `image.crop`: non-finite, non-number or outside 1..=MAX_RESOLUTION is an error and the document is untouched; the keepPrintSize path uses the same value. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/image_cmds.rs | 38 +++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs index 6353f1f2cc..eb29f9a96d 100644 --- a/crates/engine/src/image_cmds.rs +++ b/crates/engine/src/image_cmds.rs @@ -11,6 +11,7 @@ use photocraft_raster::Surface; use serde_json::{Value, json}; use crate::commands::CommandSpec; +use crate::document_preset_cmds::MAX_RESOLUTION; use crate::{EngineError, Result, Session}; fn has_doc(s: &Session) -> std::result::Result<(), String> { @@ -212,14 +213,22 @@ fn image_size(s: &mut Session, p: &Value) -> Result { pw = pw.or(Some(ow as f64 * pc / 100.0)); ph = ph.or(Some(oh as f64 * pc / 100.0)); } + // The document range File › New and the dialog's field allow; outside it, refuse rather than + // clamp (#9260: 1e39 became inf as f32, then silently 10000 ppi). + let dpi = match p.get("resolution") { + None | Some(Value::Null) => None, + Some(v) => { + let r = v.as_f64().filter(|r| r.is_finite() && (1.0..=MAX_RESOLUTION).contains(r)); + Some(r.ok_or_else(|| bad("image.imageSize", format!("`resolution` = {v} must be a number of pixels per inch from 1 to {MAX_RESOLUTION}")))?) + } + }; // `keepPrintSize`: only the resolution given, the pixels follow it (Photoshop's Image Size // with Resample on, as an action records it). if p.get("keepPrintSize").and_then(Value::as_bool) == Some(true) && pw.is_none() && ph.is_none() - && let Some(r) = p.get("resolution").and_then(Value::as_f64) + && let Some(r) = dpi { - let r = r.clamp(1.0, 10_000.0); let old = f64::from(d.doc.resolution_dpi).max(1.0); pw = Some(ow as f64 * r / old); ph = Some(oh as f64 * r / old); @@ -237,7 +246,6 @@ fn image_size(s: &mut Session, p: &Value) -> Result { if !matches!(resample, Method::None) && (nw, nh) != (ow, oh) { check_resample_budget("image.imageSize", &d.doc, nw, nh, ", or turn Resample off to change only the resolution")?; } - let dpi = p.get("resolution").and_then(Value::as_f64).map(|v| v as f32); if !matches!(resample, Method::None) && (nw, nh) != (ow, oh) { // Color Sampler points scale with the pixels (same map `transform_geometry` applies). let (sx, sy) = (f64::from(nw) / f64::from(ow.max(1)), f64::from(nh) / f64::from(oh.max(1))); @@ -246,7 +254,7 @@ fn image_size(s: &mut Session, p: &Value) -> Result { s.edit("Image Size", |doc, _| { if let Some(r) = dpi { // Type keeps its pixel size; resampling below then scales it with the pixels. - crate::canvas_geom::set_resolution(doc, r.clamp(1.0, 10_000.0)); + crate::canvas_geom::set_resolution(doc, r as f32); } let filter = match resample { Method::None => return Ok(()), @@ -1270,6 +1278,28 @@ mod tests { assert_eq!(r, json!({"width": 40, "height": 20})); } + /// #9260: a resolution outside the document range (1..=30000 ppi, as File › New and the + /// dialog's field) is refused and leaves the document as it was, instead of being clamped; + /// one inside it, also above 10000, is set as given. + #[test] + fn image_size_refuses_a_resolution_out_of_range() { + for extra in [json!({"resample": "none"}), json!({"resample": "bicubic"}), json!({"resample": "bicubic", "keepPrintSize": true})] { + for r in [json!(1e39), json!(-5), json!(0), json!(0.5), json!(30_001), json!("300")] { + let mut s = session(); + let (size, dpi, past) = (doc(&s).size, doc(&s).resolution_dpi, s.active().unwrap().history.past_len()); + let mut p = extra.clone(); + p["resolution"] = r; + assert!(s.execute("image.imageSize", p.clone()).is_err(), "{p}"); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi, s.active().unwrap().history.past_len()), (size, dpi, past), "{p}: nothing changed"); + } + } + let mut s = session(); + s.execute("image.imageSize", json!({"resolution": 20_000, "resample": "none"})).unwrap(); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(40, 20), 20_000.0)); + s.execute("image.imageSize", json!({"resolution": null, "resample": "none"})).unwrap(); + assert_eq!(doc(&s).resolution_dpi, 20_000.0, "null leaves the resolution as it is"); + } + /// Type keeps its pixel size across a resolution change: resampled 2x at twice the ppi it is /// twice as tall (not 4x), with Resample off it stays, and a later re-render doesn't jump. #[test] From d1353e90a744f15b44cb1445d6ac5f66cf8b7fe7 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:05:42 +0100 Subject: [PATCH 19/44] Image Size: a document's own out-of-range resolution still passes (#9260) An imported file can carry a resolution outside 1..30000 ppi (PNG pHYs 1 px/m, PSD 0, TIFF in cm), and the Image Size dialog sends it back unchanged on OK; refusing it would block a plain resize that worked before. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/image_cmds.rs | 20 ++++++++++++++++++-- crates/ui-egui/src/sizing.rs | 24 ++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs index eb29f9a96d..2c8e2e53b3 100644 --- a/crates/engine/src/image_cmds.rs +++ b/crates/engine/src/image_cmds.rs @@ -214,11 +214,14 @@ fn image_size(s: &mut Session, p: &Value) -> Result { ph = ph.or(Some(oh as f64 * pc / 100.0)); } // The document range File › New and the dialog's field allow; outside it, refuse rather than - // clamp (#9260: 1e39 became inf as f32, then silently 10000 ppi). + // clamp (#9260: 1e39 became inf as f32, then silently 10000 ppi). The document's own + // resolution always passes: an imported file may have one outside the range, and the dialog + // sends it back unchanged. let dpi = match p.get("resolution") { None | Some(Value::Null) => None, Some(v) => { - let r = v.as_f64().filter(|r| r.is_finite() && (1.0..=MAX_RESOLUTION).contains(r)); + let own = |r: f64| r as f32 == d.doc.resolution_dpi; + let r = v.as_f64().filter(|&r| r.is_finite() && ((1.0..=MAX_RESOLUTION).contains(&r) || own(r))); Some(r.ok_or_else(|| bad("image.imageSize", format!("`resolution` = {v} must be a number of pixels per inch from 1 to {MAX_RESOLUTION}")))?) } }; @@ -1298,6 +1301,19 @@ mod tests { assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(40, 20), 20_000.0)); s.execute("image.imageSize", json!({"resolution": null, "resample": "none"})).unwrap(); assert_eq!(doc(&s).resolution_dpi, 20_000.0, "null leaves the resolution as it is"); + // An imported document's own resolution outside the range (a PNG pHYs of 1 px/m is + // 0.0254 ppi) still resizes: the Image Size dialog sends it back unchanged on OK. + for own in [0.0254_f32, 40_000.0] { + let mut s = session(); + s.edit("ppi", |doc, _| { + doc.resolution_dpi = own; + Ok(()) + }) + .unwrap(); + s.execute("image.imageSize", json!({"width": 80, "height": 40, "resolution": f64::from(own), "resample": "bicubic"})).unwrap(); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(80, 40), own), "{own}"); + assert!(s.execute("image.imageSize", json!({"resolution": 0.03, "resample": "none"})).is_err(), "{own}: another value is still checked"); + } } /// Type keeps its pixel size across a resolution change: resampled 2x at twice the ppi it is diff --git a/crates/ui-egui/src/sizing.rs b/crates/ui-egui/src/sizing.rs index bf8adf549f..f450e4fab0 100644 --- a/crates/ui-egui/src/sizing.rs +++ b/crates/ui-egui/src/sizing.rs @@ -518,6 +518,30 @@ mod tests { assert_eq!(app.session.active().unwrap().doc.size, photocraft_doc::Size::new(120, 50)); } + /// #9260: OK with a new Width resizes a document whose own resolution is outside the range + /// the command accepts (an imported PNG's pHYs of 1 px/m is 0.0254 ppi); the dialog sends that + /// resolution back unchanged. + #[test] + fn ok_resizes_a_document_with_an_imported_resolution_out_of_range() { + for own in [0.0254_f32, 40_000.0] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 100, "resolution": 72})).unwrap(); + app.session + .edit("ppi", |doc, _| { + doc.resolution_dpi = own; + Ok(()) + }) + .unwrap(); + let id = open(&mut app, "image.imageSize").unwrap(); + let d = app.ui.dialog_mut(id).unwrap(); + d.fields.insert("width".into(), json!(100)); + d.fields.insert("height".into(), json!(50)); + crate::dialogs::confirm(&mut app, id).unwrap(); + let doc = &app.session.active().unwrap().doc; + assert_eq!((doc.size, doc.resolution_dpi), (photocraft_doc::Size::new(100, 50), own), "{own}"); + } + } + #[test] fn alt_reset_restores_open_dimensions() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); From 1e695c5a28cffd940e799cd7c931989125711dde Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:09:27 +0100 Subject: [PATCH 20/44] Crop: Esc in full screen cancels a drag on the default frame (#9275) The untouched default frame lets Esc leave full screen (#7315), but the frame stays the default until the gesture's release, so Esc mid-drag left full screen and the drag went on. A gesture in progress now keeps Esc. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/shortcuts.rs | 8 ++++++-- crates/ui-egui/src/view_cmds/tests.rs | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 023bbb4d79..5df8d24f28 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -692,8 +692,12 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { return; } // In a full screen mode, the Crop tool's untouched default frame (Straighten off) has nothing to cancel: cancelling only - // makes the next one, so Esc goes on to leave full screen (#7315). - let untouched = app.ui.view.screen_mode != "standard" && app.ui.polygon.is_empty() && app.crop.default_frame && !crate::crop_straighten::mode(app); + // makes the next one, so Esc goes on to leave full screen (#7315). A gesture on it is still cancelled (#9275). + let untouched = app.ui.view.screen_mode != "standard" + && app.ui.polygon.is_empty() + && app.crop.default_frame + && app.crop.drag.is_none() + && !crate::crop_straighten::mode(app); if !untouched && pressed(Key::Escape) { app.ui.polygon.clear(); app.ui.polygon_mode.clear(); diff --git a/crates/ui-egui/src/view_cmds/tests.rs b/crates/ui-egui/src/view_cmds/tests.rs index 05c1f1bb60..82baf593ac 100644 --- a/crates/ui-egui/src/view_cmds/tests.rs +++ b/crates/ui-egui/src/view_cmds/tests.rs @@ -577,6 +577,29 @@ fn esc_leaves_full_screen_with_the_crop_tool_showing_its_default_frame() { assert_eq!(app.ui.view.screen_mode, "standard"); } +/// #9275: a gesture on the default frame is something to cancel, so Esc in full screen cancels it +/// (as in Standard Screen Mode) and full screen stays. +#[test] +fn esc_in_full_screen_cancels_a_crop_drag_on_the_default_frame() { + use crate::canvas::{ToolEvent, tool_event}; + let none = egui::Modifiers::NONE; + // Inside draws a new box, on the corner handle resizes, outside turns. + for (what, from) in [("draw", [20.0, 20.0]), ("resize", [100.0, 80.0]), ("turn", [130.0, 110.0])] { + let (mut app, ctx) = app_with(1); + app.ui.tool = crate::Tool::Crop; + crate::crop_ui::ensure_frame(&mut app); + menu(&mut app, &ctx, "view.screenMode.fullScreen", json!({})).unwrap(); + tool_event(&mut app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, none); + tool_event(&mut app, ToolEvent::Move { x: 60.0, y: 50.0, pressure: 1.0 }, none); + assert!(app.crop.drag.is_some() && app.crop.default_frame, "{what}: mid-gesture on the default frame"); + press_esc(&mut app, &ctx); + assert_eq!(app.ui.view.screen_mode, "fullScreen", "{what}: Esc cancels the gesture, full screen stays"); + assert!(app.crop.drag.is_none(), "{what}: the gesture is cancelled"); + tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 50.0 }, none); + assert!(!crate::crop_ui::pending(&app), "{what}: the release leaves no pending crop"); + } +} + #[test] fn esc_leaves_full_screen_modes_unless_something_else_owns_it() { let (mut app, ctx) = app_with(1); From 3d5c2ac62baf406feb6cd8ab6aad122eb223656d Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:15:19 +0100 Subject: [PATCH 21/44] Crop: a click on the frame or a handle never snaps it (#9283) A release at the press point went through the snapping like any drag's, so a click inside an edited frame (or a default-mode click moving the image) or on a handle pulled an edge within reach onto the document's and recorded a box Undo step; a double-click to commit cropped that rect. A click now leaves the frame alone, as a Move-tool click leaves the layer. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/crop_ui.rs | 21 +++++++++++++++++++++ crates/ui-egui/src/snap_ui.rs | 17 +++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index 73e9ce5642..4814ad5331 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -1388,6 +1388,27 @@ mod tests { assert_eq!(app.ui.crop_rect, Some([0.0, 10.0, 40.0, 40.0]), "left edge snaps to the document edge"); } + /// A click on the frame (released where it was pressed) changes nothing, as a Move-tool click + /// doesn't move the layer: snapping the release would pull an edge within reach onto the + /// document's, so a double-click to commit cropped another rect. + #[test] + fn a_click_on_the_frame_or_a_handle_never_snaps_it() { + let frame = [5.0, 10.0, 105.0, 60.0]; + for classic in [true, false] { + // Inside (Classic: moves the frame; default: moves the image), the left edge's handle, the top-left corner's. + for p in [[50.0, 30.0], [5.0, 35.0], [5.0, 10.0]] { + let mut app = app(SampleType::U8); + app.ui.tool_options.crop_shield.classic_mode = classic; + app.ui.extras.snap = true; + app.ui.crop_rect = Some(frame); + app.crop.default_frame = false; + drag(&mut app, &[p], NONE); + assert_eq!(app.ui.crop_rect, Some(frame), "classic {classic}, click at {p:?}"); + assert!(!crate::menus::is_enabled(&app, "edit.undo"), "classic {classic}, click at {p:?}: no box step"); + } + } + } + /// #3145: Edit › Undo while a crop is pending steps the *box*, not the document (Photoshop keeps /// Undo live during a crop), so a moved frame comes back. #[test] diff --git a/crates/ui-egui/src/snap_ui.rs b/crates/ui-egui/src/snap_ui.rs index e19c95a2e7..ce8f2347df 100644 --- a/crates/ui-egui/src/snap_ui.rs +++ b/crates/ui-egui/src/snap_ui.rs @@ -487,6 +487,18 @@ fn follow_reposition(app: &mut PhotocraftApp) { } } +/// A click on a crop frame or one of its handles (released where it was pressed, the frame not +/// moved) changes nothing, as a Move-tool click doesn't move the layer (`canvas::tool_event`): +/// snapping the release would pull an edge within reach onto a nearby one. +fn crop_click(app: &PhotocraftApp, p: [f64; 2]) -> bool { + use crate::crop_ui::CropDrag; + let Some(snap) = app.prefs_rt.snap.as_ref() else { return false }; + let Some(CropDrag::Move { rect, .. } | CropDrag::Resize { rect, .. } | CropDrag::MoveImage { rect, .. }) = app.crop.drag else { + return false; + }; + app.ui.tool == Tool::Crop && p == snap.start && app.ui.crop_rect == Some(rect) +} + /// Snap a tool event's coordinates (called by `canvas::tool_event` before the tools see it). pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> ToolEvent { match ev { @@ -527,6 +539,11 @@ pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifier if app.prefs_rt.snap.is_none() { return ev; } + if crop_click(app, [x, y]) { + app.prefs_rt.snap = None; + app.prefs_rt.snap_lines.clear(); + return ev; + } follow_reposition(app); let disabled = override_for_gesture(app, mods); if let Some(s) = app.prefs_rt.snap.as_mut() { From 617d40d2683fac3e5d6a2d1ba4e7b139e0f62d1e Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:30:33 +0100 Subject: [PATCH 22/44] Address CodeRabbit review: only the exact own resolution passes, and keepPrintSize with it keeps the pixels (#9260) An out-of-range value that merely rounded to the document's resolution as f32 was accepted, and keepPrintSize with an own resolution below 1 ppi resampled the canvas against old.max(1.0), shrinking it to 1 x 1. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/image_cmds.rs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs index 2c8e2e53b3..49b95c1c05 100644 --- a/crates/engine/src/image_cmds.rs +++ b/crates/engine/src/image_cmds.rs @@ -216,23 +216,24 @@ fn image_size(s: &mut Session, p: &Value) -> Result { // The document range File › New and the dialog's field allow; outside it, refuse rather than // clamp (#9260: 1e39 became inf as f32, then silently 10000 ppi). The document's own // resolution always passes: an imported file may have one outside the range, and the dialog - // sends it back unchanged. + // sends it back unchanged (exactly: a value that only rounds to it as f32 is refused). + let own_dpi = f64::from(d.doc.resolution_dpi); let dpi = match p.get("resolution") { None | Some(Value::Null) => None, Some(v) => { - let own = |r: f64| r as f32 == d.doc.resolution_dpi; - let r = v.as_f64().filter(|&r| r.is_finite() && ((1.0..=MAX_RESOLUTION).contains(&r) || own(r))); + let r = v.as_f64().filter(|&r| r.is_finite() && ((1.0..=MAX_RESOLUTION).contains(&r) || r == own_dpi)); Some(r.ok_or_else(|| bad("image.imageSize", format!("`resolution` = {v} must be a number of pixels per inch from 1 to {MAX_RESOLUTION}")))?) } }; // `keepPrintSize`: only the resolution given, the pixels follow it (Photoshop's Image Size - // with Resample on, as an action records it). + // with Resample on, as an action records it). An unchanged resolution keeps the pixels. if p.get("keepPrintSize").and_then(Value::as_bool) == Some(true) && pw.is_none() && ph.is_none() && let Some(r) = dpi + && r != own_dpi { - let old = f64::from(d.doc.resolution_dpi).max(1.0); + let old = own_dpi.max(1.0); pw = Some(ow as f64 * r / old); ph = Some(oh as f64 * r / old); } @@ -1313,6 +1314,13 @@ mod tests { s.execute("image.imageSize", json!({"width": 80, "height": 40, "resolution": f64::from(own), "resample": "bicubic"})).unwrap(); assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(80, 40), own), "{own}"); assert!(s.execute("image.imageSize", json!({"resolution": 0.03, "resample": "none"})).is_err(), "{own}: another value is still checked"); + // Only the exact value: one that merely rounds to it as f32 is refused. + let near = if own < 1.0 { f64::from(own) * (1.0 + 1e-9) } else { f64::from(own) + 0.001 }; + assert_eq!(near as f32, own); + assert!(s.execute("image.imageSize", json!({"resolution": near, "resample": "none"})).is_err(), "{own}: {near}"); + // keepPrintSize with the unchanged resolution keeps the pixels. + s.execute("image.imageSize", json!({"resolution": f64::from(own), "resample": "bicubic", "keepPrintSize": true})).unwrap(); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(80, 40), own), "{own}: keepPrintSize"); } } From 6f70783ba953363e55492d5d901457424eb1090e Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:35:30 +0100 Subject: [PATCH 23/44] Crop: a Straighten line inside the frame no longer snaps like a frame move (#9277) A press inside an edited, upright Classic Mode frame got the frame-move snap even when it drew a Straighten line (button armed, or Cmd/Ctrl), so every point of the line was shifted by the offset that would align the moved frame, and the frame turned to the wrong angle. The line's ends now snap as points, as they already do outside the frame. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/snap_ui.rs | 43 +++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/snap_ui.rs b/crates/ui-egui/src/snap_ui.rs index e19c95a2e7..4c6868d94d 100644 --- a/crates/ui-egui/src/snap_ui.rs +++ b/crates/ui-egui/src/snap_ui.rs @@ -240,8 +240,10 @@ fn begin(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) { { // Inside the untouched default frame draws a new crop (in both modes): snap its corner, not // the old canvas-sized frame's bounds. An edited Classic Mode frame still moves and snaps - // its edges. - let gesture = if app.crop.default_frame { Gesture::Point } else { Gesture::Move { rect } }; + // its edges. A straighten line (`crop_straighten::pointer` takes the press first) snaps its + // ends as points, as outside the frame, never by the offset of a frame it doesn't move. + let straightens = app.crop.drag.is_none() && (app.crop.straighten.armed || mods.command); + let gesture = if app.crop.default_frame || straightens { Gesture::Point } else { Gesture::Move { rect } }; Some((gesture, Vec::new())) } else if tool == Tool::Crop && crate::crop_mode::moves_image(app) @@ -699,6 +701,43 @@ mod tests { } } + /// A straighten line drawn inside an upright, edited frame levels the frame on the line as + /// drawn: it isn't shifted by the offset that would snap the frame if the press moved it. The + /// default mode moves the image there, which never shifted the line; it stays as it was. + #[test] + fn a_straighten_line_inside_the_frame_is_not_snapped_as_a_frame_move() { + let mac_cmd = egui::Modifiers { mac_cmd: true, command: true, ..Default::default() }; + for (classic, armed, m) in [(true, true, egui::Modifiers::NONE), (true, false, mac_cmd), (false, true, egui::Modifiers::NONE)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = 1.0; + app.ui.views[0].fit_pending = false; + app.ui.tool = Tool::Crop; + app.ui.tool_options.crop_shield.classic_mode = classic; + app.ui.extras.snap = true; + app.ui.view.show.smart_guides = true; + crate::crop_ui::ensure_frame(&mut app); + app.ui.crop_rect = Some([20.0, 20.0, 120.0, 70.0]); + app.crop.default_frame = false; + if classic { + // Without Straighten the press moves the frame and snaps its edges, as on main. + crate::snap_ui::begin(&mut app, [30.0, 30.0], egui::Modifiers::NONE); + let gesture = app.prefs_rt.snap.take().map(|s| s.gesture); + assert_eq!(gesture, Some(Gesture::Move { rect: [20.0, 20.0, 120.0, 70.0] })); + } + app.crop.straighten.armed = armed; + // Moving the frame by the line's (100, 8) would bring its centre 3 px from the + // document's: that offset must not reach the line. Both ends are clear of every target. + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 130.0, y: 38.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 130.0, y: 38.0 }, m); + let want = crate::crop_straighten::frame_angle([30.0, 30.0], [130.0, 38.0], 0.0).unwrap(); + let got = crate::crop_ui::angle(&app); + assert!((got - want).abs() < 1e-9, "Classic Mode {classic}, armed {armed}: {got} vs {want}"); + } + } + #[test] fn move_tool_snaps_to_other_layer_edges_with_smart_guides() { let mut app = app_with_box(); From 9891eaeb2efcae43002d7829438ba092c0c15711 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:35:15 +0100 Subject: [PATCH 24/44] Crop: History jumps wait for a pending crop (#9285) With a drawn crop frame, a History panel click (state, snapshot, Step Forward/Backward or Delete in its menu) or a control-channel history.selectState resized the document under the frame, which kept its coordinates, so Enter cropped the old ones. The Edit menu already greys these while a crop is pending; the panel and the control channel come through app.run, so crop_ui::intercept now refuses them there and the panel menu greys them, as for Free Transform. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/crop_ui.rs | 40 +++++++++++++++++++++++++++ crates/ui-egui/src/history_menu_ui.rs | 24 ++++++++++++++-- 2 files changed, 62 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index 73e9ce5642..ca37c16df6 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -495,6 +495,9 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option { /// Intercept Undo/Redo/Toggle Last State while the Crop tool owns box history, for every caller /// (menus, shortcuts, the control channel, MCP) — as `transform_tool::intercept` does. pub fn intercept(app: &mut PhotocraftApp, id: &str) -> Option> { + if holds_history(app, id) { + return Some(Err("Commit or cancel the crop first".into())); + } if app.ui.tool != Tool::Crop || (app.crop.undo.is_empty() && app.crop.redo.is_empty()) { return None; } @@ -506,6 +509,13 @@ pub fn intercept(app: &mut PhotocraftApp, id: &str) -> Option bool { + pending(app) && matches!(id, "history.selectState" | "history.selectSnapshot" | "history.stepBackward" | "history.stepForward" | "history.deleteState") +} + /// Undo (or redo) one box step. fn step(app: &mut PhotocraftApp, redo: bool) -> serde_json::Value { let s = if redo { app.crop.redo.pop() } else { app.crop.undo.pop() }; @@ -1424,6 +1434,36 @@ mod tests { assert!(crate::menus::is_enabled(&app, "edit.redo")); } + /// A History jump under a drawn frame would resize the document while the frame keeps its + /// coordinates, so Enter cropped the old ones (#9285): the panel's rows, snapshots and menu + /// wait for the crop, as they do for Free Transform. + #[test] + fn history_jumps_wait_for_a_pending_crop() { + let size = |app: &PhotocraftApp| app.session.active().map(|st| (st.doc.size.width, st.doc.size.height)); + let mut app = app(SampleType::U8); + app.run("history.newSnapshot", json!({})).unwrap(); + app.run("image.canvasSize", json!({"width": 300, "height": 200})).unwrap(); + let snapshot = app.session.active().unwrap().snapshots[0].id; + app.ui.crop_rect = Some([220.0, 120.0, 290.0, 190.0]); + app.crop.default_frame = false; + for (cmd, p) in [ + ("history.selectState", json!({"state": 0})), + ("history.selectSnapshot", json!({"snapshot": snapshot})), + ("history.stepBackward", json!({})), + ("history.deleteState", json!({})), + ] { + assert!(app.run(cmd, p).is_err(), "{cmd} waits for the crop"); + assert_eq!(size(&app), Some((300, 200)), "{cmd} left the document as it was"); + } + assert_eq!(app.ui.crop_rect, Some([220.0, 120.0, 290.0, 190.0]), "the frame stays"); + // Without a drawn frame (the tool's own frame around the canvas) History works as before. + app.crop.default_frame = true; + app.run("history.selectState", json!({"state": 0})).unwrap(); + assert_eq!(size(&app), Some((200, 100))); + app.run("history.stepForward", json!({})).unwrap(); + assert_eq!(size(&app), Some((300, 200))); + } + #[test] fn handles_resize_with_shift_and_alt() { let mut app = app(SampleType::U8); diff --git a/crates/ui-egui/src/history_menu_ui.rs b/crates/ui-egui/src/history_menu_ui.rs index da77f9d2fb..cadd12e5b2 100644 --- a/crates/ui-egui/src/history_menu_ui.rs +++ b/crates/ui-egui/src/history_menu_ui.rs @@ -42,8 +42,9 @@ fn enabled(app: &PhotocraftApp, cmd: &str) -> bool { if cmd == "window.panel.close" { return !app.session.prefs().workspace_locked; } - // An open Free Transform owns the history (see `panels::history`). - app.ui.transform.is_none() && app.session.is_enabled(cmd) + // An open Free Transform owns the history (see `panels::history`), and a drawn crop frame + // holds its jumps back (`crop_ui::holds_history`). + app.ui.transform.is_none() && !crate::crop_ui::holds_history(app, cmd) && app.session.is_enabled(cmd) } /// Draw the History items of the panel menu and run the one clicked. @@ -153,6 +154,25 @@ mod tests { } } + /// A drawn crop frame greys the items that move the document under it (#9285). + #[test] + fn jumps_wait_for_a_drawn_crop_frame() { + let mut app = app(); + app.ui.tool = crate::state::Tool::Crop; + app.ui.crop_rect = Some([4.0, 4.0, 40.0, 30.0]); + app.crop.default_frame = false; + let mut h = harness(app); + for label in ["Step Backward", "Delete"] { + assert!(is_disabled(&h, label), "{label}"); + } + assert!(!is_disabled(&h, "New Snapshot…"), "a snapshot leaves the document as it is"); + h.state_mut().crop.default_frame = true; + h.run_steps(2); + assert!(!is_disabled(&h, "Step Backward"), "the tool's own frame around the canvas holds nothing back"); + click(&mut h, "Step Backward"); + assert_eq!(states(&h), (3, 1)); + } + #[test] fn new_snapshot_adds_a_snapshot_and_leaves_the_states() { let mut h = harness(app()); From 81c716b85ae90c88b68298cd9651115ebea99376 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:45:10 +0100 Subject: [PATCH 25/44] Crop: test Step Forward under a drawn frame too (#9285) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/crop_ui.rs | 9 +++++++-- crates/ui-egui/src/history_menu_ui.rs | 5 +++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index ca37c16df6..9de681397c 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -510,8 +510,8 @@ pub fn intercept(app: &mut PhotocraftApp, id: &str) -> Option bool { pending(app) && matches!(id, "history.selectState" | "history.selectSnapshot" | "history.stepBackward" | "history.stepForward" | "history.deleteState") } @@ -1460,6 +1460,11 @@ mod tests { app.crop.default_frame = true; app.run("history.selectState", json!({"state": 0})).unwrap(); assert_eq!(size(&app), Some((200, 100))); + // Step Forward has a state to redo now; a drawn frame holds it back too. + app.crop.default_frame = false; + assert!(app.run("history.stepForward", json!({})).is_err(), "history.stepForward waits for the crop"); + assert_eq!(size(&app), Some((200, 100))); + app.crop.default_frame = true; app.run("history.stepForward", json!({})).unwrap(); assert_eq!(size(&app), Some((300, 200))); } diff --git a/crates/ui-egui/src/history_menu_ui.rs b/crates/ui-egui/src/history_menu_ui.rs index cadd12e5b2..b529293b93 100644 --- a/crates/ui-egui/src/history_menu_ui.rs +++ b/crates/ui-egui/src/history_menu_ui.rs @@ -161,8 +161,9 @@ mod tests { app.ui.tool = crate::state::Tool::Crop; app.ui.crop_rect = Some([4.0, 4.0, 40.0, 30.0]); app.crop.default_frame = false; + app.session.execute("history.stepBackward", json!({})).unwrap(); let mut h = harness(app); - for label in ["Step Backward", "Delete"] { + for label in ["Step Backward", "Step Forward", "Delete"] { assert!(is_disabled(&h, label), "{label}"); } assert!(!is_disabled(&h, "New Snapshot…"), "a snapshot leaves the document as it is"); @@ -170,7 +171,7 @@ mod tests { h.run_steps(2); assert!(!is_disabled(&h, "Step Backward"), "the tool's own frame around the canvas holds nothing back"); click(&mut h, "Step Backward"); - assert_eq!(states(&h), (3, 1)); + assert_eq!(states(&h), (2, 2)); } #[test] From 4aff057464cf2d8cb9c229b728d47dcc5c0c69cd Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:49:35 +0100 Subject: [PATCH 26/44] Address CodeRabbit review: a Windows Ctrl straighten line doesn't snap its start (#9277) Windows Ctrl both starts a straighten line and is held while drawing it, which turns snapping off on Move and Up; the press still snapped, so the frame turned by a different angle. The override now covers the press of a straighten line too, and every straighten press snaps as a point, wherever it starts. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/snap_ui.rs | 51 +++++++++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/snap_ui.rs b/crates/ui-egui/src/snap_ui.rs index 4c6868d94d..027ef23c81 100644 --- a/crates/ui-egui/src/snap_ui.rs +++ b/crates/ui-egui/src/snap_ui.rs @@ -214,6 +214,7 @@ fn begin(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) { let tool = crate::canvas::event_tool(app, mods); let moves_layer = crate::canvas::command_moves_layer(app, tool, p, mods); let crop_tol = crate::crop_ui::tolerance(app); + let straightens = tool == Tool::Crop && app.crop.drag.is_none() && (app.crop.straighten.armed || mods.command); let gesture = if let Some(t) = &app.ui.transform { let corner = match crate::transform_tool::hit(t, p, crate::transform_tool::handle_tolerance(app)) { crate::transform_tool::Hit::Corner(index) => t.quad.get(index).map(|&point| (Gesture::TransformCorner { index, point }, vec![LayerId(t.layer)])), @@ -233,6 +234,11 @@ fn begin(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) { } else if tool == Tool::Move || moves_layer { let exclude = app.session.active().map(|s| s.selected_layers()).unwrap_or_default(); moving_rect(app, tool).map(|rect| (Gesture::Move { rect }, exclude)) + } else if straightens { + // A straighten line (`crop_straighten::pointer` takes the press before the frame's drags) + // snaps its ends as points wherever it starts, never by the offset of a frame or image it + // doesn't move. + Some((Gesture::Point, Vec::new())) } else if tool == Tool::Crop && (crate::crop_mode::classic(app) || app.crop.default_frame) && let Some(rect) = @@ -240,10 +246,8 @@ fn begin(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) { { // Inside the untouched default frame draws a new crop (in both modes): snap its corner, not // the old canvas-sized frame's bounds. An edited Classic Mode frame still moves and snaps - // its edges. A straighten line (`crop_straighten::pointer` takes the press first) snaps its - // ends as points, as outside the frame, never by the offset of a frame it doesn't move. - let straightens = app.crop.drag.is_none() && (app.crop.straighten.armed || mods.command); - let gesture = if app.crop.default_frame || straightens { Gesture::Point } else { Gesture::Move { rect } }; + // its edges. + let gesture = if app.crop.default_frame { Gesture::Point } else { Gesture::Move { rect } }; Some((gesture, Vec::new())) } else if tool == Tool::Crop && crate::crop_mode::moves_image(app) @@ -297,7 +301,10 @@ fn begin(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) { } else { SnapTargets::default() }; - app.prefs_rt.snap = Some(ActiveSnap { gesture, start: p, targets, smart, disabled: false }); + // Windows Ctrl both starts a straighten line and is held while it is drawn: the override then + // covers the press too, or the line's start would snap and its end not. + let disabled = straightens && override_held(mods); + app.prefs_rt.snap = Some(ActiveSnap { gesture, start: p, targets, smart, disabled }); } /// Snap a guide drag that ⌘ with a selection tool starts at `p` (`canvas::command_guide_at`, @@ -738,6 +745,40 @@ mod tests { } } + /// Windows Ctrl both starts a straighten line and is held while drawing it, which turns + /// snapping off: the press stays where it was too, so the frame levels on the line as drawn, + /// inside an edited frame, outside it and in the untouched default frame. ⌘ on the Mac is not + /// the override: both ends snap. + #[test] + fn a_windows_ctrl_straighten_line_does_not_snap_its_start_either() { + let win_ctrl = egui::Modifiers { ctrl: true, command: true, ..Default::default() }; + let mac_cmd = egui::Modifiers { mac_cmd: true, command: true, ..Default::default() }; + for frame in [Some([20.0, 20.0, 120.0, 70.0]), Some([130.0, 20.0, 190.0, 70.0]), None] { + for (m, start) in [(win_ctrl, [97.0, 30.0]), (mac_cmd, [100.0, 30.0])] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = 1.0; + app.ui.views[0].fit_pending = false; + app.ui.tool = Tool::Crop; + app.ui.tool_options.crop_shield.classic_mode = true; + app.ui.extras.snap = true; + crate::crop_ui::ensure_frame(&mut app); + if let Some(r) = frame { + app.ui.crop_rect = Some(r); + app.crop.default_frame = false; + } + // The press is 3 px from the document's centre line; the end is clear of every target. + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 97.0, y: 30.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 180.0, y: 38.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 180.0, y: 38.0 }, m); + let want = crate::crop_straighten::frame_angle(start, [180.0, 38.0], 0.0).unwrap(); + let got = crate::crop_ui::angle(&app); + assert!((got - want).abs() < 1e-9, "frame {frame:?}, {m:?}: {got} vs {want}"); + } + } + } + #[test] fn move_tool_snaps_to_other_layer_edges_with_smart_guides() { let mut app = app_with_box(); From 3640b3162505d2484c0972fb54b66e702a93e06e Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 03:13:26 +0100 Subject: [PATCH 27/44] Crop / Perspective Crop: a drag held past the canvas edge scrolls the view (#9307) The edge auto-scroll (#4183) ran only while app.drag was set, but both crop tools keep their gestures in app.crop.drag / app.pcrop.drag. Frame draws, moves and classic resizes, and Perspective Crop box, corner and quad drags, now scroll too; turns and the default mode's camera-driven drags stay as they were. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 4 +- crates/ui-egui/src/crop_ui.rs | 61 ++++++++++++++++++++++ crates/ui-egui/src/perspective_crop_ui.rs | 62 +++++++++++++++++++++++ 3 files changed, 125 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ab3e6939a7..50900231fd 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -4895,9 +4895,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: painter.set(layer_edges, egui::Shape::rect_stroke(xf.doc_rect(b), 0, Stroke::new(1.0, LAYER_EDGES), egui::StrokeKind::Outside)); } // A tool drag held past the canvas edge scrolls the view toward the pointer (#4183); the - // drag's next move then extends into what scrolled in. + // drag's next move then extends into what scrolled in. The crop tools keep their own drags. if primary - && app.drag.is_some() + && (app.drag.is_some() || crate::crop_ui::autoscrolls(app) || crate::perspective_crop_ui::dragging(app)) && tool != Tool::Hand && !middle && let Some(p) = ui.input(|i| i.pointer.primary_down().then(|| i.pointer.latest_pos()).flatten()) diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index 73e9ce5642..25aacdb5b8 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -419,6 +419,13 @@ pub fn active(app: &PhotocraftApp) -> bool { app.ui.tool == Tool::Crop && app.crop.drag.is_some() } +/// A drag that sizes or moves the frame over the image, which scrolls the view when held past the +/// canvas edge (#4183). Not the turns, nor the default mode's image moves and live-centred resizes: +/// those drive the camera themselves. +pub fn autoscrolls(app: &PhotocraftApp) -> bool { + app.ui.tool == Tool::Crop && matches!(app.crop.drag, Some(CropDrag::Draw { .. } | CropDrag::Move { .. } | CropDrag::Resize { view: None, .. })) +} + /// Cancel the pending crop: the frame, any gesture on it and the default-frame state. With the /// Crop tool still picked, [`ensure_frame`] then makes the active document a new default frame. pub fn cancel(app: &mut PhotocraftApp) { @@ -1536,6 +1543,60 @@ mod tests { assert!(st.crop.drag.is_none()); } + /// Real egui input: a handle dragged past the canvas edge and held there scrolls the view, as a + /// marquee drag does (#4183), so the frame can reach the part of the image that was off screen. + #[test] + fn a_handle_held_past_the_canvas_edge_scrolls_the_view() { + use egui::{Event, PointerButton, pos2}; + let mut a = app(SampleType::U8); + // 200x100 at 400% in a 600x400 canvas: document x 25..175 shows. + a.ui.views = vec![crate::state::View { + zoom: 4.0, + center: [100.0, 50.0], + fit_pending: false, + fill_pending: false, + doc_size: [200, 100], + rotation: 0.0, + zoom_animating: false, + zoom_anchor: None, + display_camera: None, + zoom_transition: None, + }]; + a.ui.crop_rect = Some([40.0, 10.0, 100.0, 40.0]); + a.crop.default_frame = false; + a.ui.extras.rulers = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let v = app.ui.views[0].clone(); + crate::canvas::canvas_view(app, ui, 0, ui.max_rect(), v, true); + }, + a, + ); + h.run_steps(2); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + // The right edge's middle handle: document (100, 25). + let p0 = h.state().ui.views[0].center; + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + let xf = crate::canvas::ViewXform { rect, zoom: 4.0, center: p0, flip: false, rotation: 0.0, aspect: 1.0 }; + let grab = xf.to_screen(100.0, 25.0); + h.event(Event::PointerMoved(grab)); + h.event(button(grab, true)); + h.step(); + let out = pos2(650.0, grab.y); + for p in [pos2(grab.x + 40.0, grab.y), out] { + h.event(Event::PointerMoved(p)); + h.step(); + } + let before = h.state().ui.views[0].center; + h.run_steps(10); + let st = h.state(); + assert!(matches!(st.crop.drag, Some(CropDrag::Resize { .. })), "{:?}", st.crop.drag); + assert!(st.ui.views[0].center[0] > before[0], "the view scrolled right: {:?} -> {:?}", before, st.ui.views[0].center); + assert!(st.ui.crop_rect.is_some_and(|r| r[2] > 175.0), "the frame reached past what showed: {:?}", st.ui.crop_rect); + h.event(button(out, false)); + h.step(); + } + /// #1918: a pending crop belongs to the document it was drawn on. File › New, opening a file /// or switching tabs cancels it; it never shows on, or crops, another document. /// A turned pending frame is dropped with its angle when another document becomes active, and diff --git a/crates/ui-egui/src/perspective_crop_ui.rs b/crates/ui-egui/src/perspective_crop_ui.rs index 2a696bd5ed..1753eb3d7b 100644 --- a/crates/ui-egui/src/perspective_crop_ui.rs +++ b/crates/ui-egui/src/perspective_crop_ui.rs @@ -53,6 +53,11 @@ pub fn pending(app: &PhotocraftApp) -> bool { app.ui.perspective_crop.is_some() || !app.pcrop.clicks.is_empty() || app.pcrop.drag.is_some() } +/// A box, corner or quad drag in progress: held past the canvas edge, it scrolls the view (#4183). +pub fn dragging(app: &PhotocraftApp) -> bool { + app.ui.tool == Tool::PerspectiveCrop && app.pcrop.drag.is_some() +} + pub fn cancel(app: &mut PhotocraftApp) { app.ui.perspective_crop = None; app.pcrop.drag = None; @@ -327,6 +332,63 @@ mod tests { assert_eq!(app.ui.perspective_crop, None); } + /// Real egui input: a corner dragged past the canvas edge and held there scrolls the view, as a + /// marquee drag does (#4183), so the corner can reach the part of the image that was off screen. + #[test] + fn a_corner_held_past_the_canvas_edge_scrolls_the_view() { + use egui::{Event, Modifiers, PointerButton, pos2}; + let doc = Document::with_background("p", Size::new(200, 100), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut s = photocraft_engine::Session::new(); + s.add_document(doc, None); + let mut a = PhotocraftApp::new(s, crate::Services::default()); + a.ui.tool = Tool::PerspectiveCrop; + a.ui.extras.snap = false; + a.ui.extras.rulers = false; + // 200x100 at 400% in a 600x400 canvas: document x 25..175 shows. + a.ui.views = vec![crate::state::View { + zoom: 4.0, + center: [100.0, 50.0], + fit_pending: false, + fill_pending: false, + doc_size: [200, 100], + rotation: 0.0, + zoom_animating: false, + zoom_anchor: None, + display_camera: None, + zoom_transition: None, + }]; + a.ui.perspective_crop = Some([[40.0, 10.0], [100.0, 10.0], [100.0, 40.0], [40.0, 40.0]]); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let v = app.ui.views[0].clone(); + crate::canvas::canvas_view(app, ui, 0, ui.max_rect(), v, true); + }, + a, + ); + h.run_steps(2); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + let xf = crate::canvas::ViewXform { rect, zoom: 4.0, center: [100.0, 50.0], flip: false, rotation: 0.0, aspect: 1.0 }; + // The top-right corner: document (100, 10). + let grab = xf.to_screen(100.0, 10.0); + h.event(Event::PointerMoved(grab)); + h.event(button(grab, true)); + h.step(); + let out = pos2(650.0, grab.y); + for p in [pos2(grab.x + 40.0, grab.y), out] { + h.event(Event::PointerMoved(p)); + h.step(); + } + let before = h.state().ui.views[0].center; + h.run_steps(10); + let st = h.state(); + assert!(matches!(st.pcrop.drag, Some(Drag::Corner { index: 1, .. })), "{:?}", st.pcrop.drag); + assert!(st.ui.views[0].center[0] > before[0], "the view scrolled right: {:?} -> {:?}", before, st.ui.views[0].center); + assert!(st.ui.perspective_crop.is_some_and(|q| q[1][0] > 175.0), "the corner reached past what showed: {:?}", st.ui.perspective_crop); + h.event(button(out, false)); + h.step(); + } + /// A box drag makes the quad, corners drag alone, and ↵'s commit crops the document to the /// quad's size; four clicks in any order make a quad in TL, TR, BR, BL order. #[test] From 92dfbca72f024fc858fd7ff8f822a2398810f5c6 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 03:26:57 +0100 Subject: [PATCH 28/44] Crop auto-scroll: only for a press on the canvas (#9307) A crop drag left over by a tool switch (#9223) must not scroll the view while a panel slider beside the canvas is held. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 5 ++-- crates/ui-egui/src/crop_ui.rs | 45 +++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 50900231fd..d6e7b0e4a1 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -4895,9 +4895,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: painter.set(layer_edges, egui::Shape::rect_stroke(xf.doc_rect(b), 0, Stroke::new(1.0, LAYER_EDGES), egui::StrokeKind::Outside)); } // A tool drag held past the canvas edge scrolls the view toward the pointer (#4183); the - // drag's next move then extends into what scrolled in. The crop tools keep their own drags. + // drag's next move then extends into what scrolled in. The crop tools keep their own drags, + // pressed on this canvas (not a panel slider held while a stale crop drag lingers). if primary - && (app.drag.is_some() || crate::crop_ui::autoscrolls(app) || crate::perspective_crop_ui::dragging(app)) + && (app.drag.is_some() || (pointer_here && (crate::crop_ui::autoscrolls(app) || crate::perspective_crop_ui::dragging(app)))) && tool != Tool::Hand && !middle && let Some(p) = ui.input(|i| i.pointer.primary_down().then(|| i.pointer.latest_pos()).flatten()) diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index 25aacdb5b8..c589714106 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -1597,6 +1597,51 @@ mod tests { h.step(); } + /// A press that started off the canvas (a panel slider beside it) doesn't scroll the view, + /// even with a crop drag still recorded: only a drag on the canvas auto-scrolls. + #[test] + fn a_press_beside_the_canvas_does_not_scroll_it_for_a_crop_drag() { + use egui::{Event, PointerButton, pos2}; + let mut a = app(SampleType::U8); + a.ui.views = vec![crate::state::View { + zoom: 4.0, + center: [100.0, 50.0], + fit_pending: false, + fill_pending: false, + doc_size: [200, 100], + rotation: 0.0, + zoom_animating: false, + zoom_anchor: None, + display_camera: None, + zoom_transition: None, + }]; + a.ui.crop_rect = Some([40.0, 10.0, 100.0, 40.0]); + a.crop.default_frame = false; + a.ui.extras.rulers = false; + // Left over from a drag a tool switch didn't end. + a.crop.drag = Some(CropDrag::Resize { hx: 1, hy: 0, start: [100.0, 25.0], rect: [40.0, 10.0, 100.0, 40.0], view: None }); + // The canvas takes the left 400 points; the rest stands in for a panel. + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let v = app.ui.views[0].clone(); + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 400.0)); + crate::canvas::canvas_view(app, ui, 0, rect, v, true); + }, + a, + ); + h.run_steps(2); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let p = pos2(500.0, 100.0); + h.event(Event::PointerMoved(p)); + h.event(button(p, true)); + h.step(); + h.event(Event::PointerMoved(pos2(550.0, 100.0))); + h.run_steps(10); + assert_eq!(h.state().ui.views[0].center, [100.0, 50.0], "the view stayed put"); + h.event(button(pos2(550.0, 100.0), false)); + h.step(); + } + /// #1918: a pending crop belongs to the document it was drawn on. File › New, opening a file /// or switching tabs cancels it; it never shows on, or crops, another document. /// A turned pending frame is dropped with its angle when another document becomes active, and From a4bb2d90469071d7a9ab1f0909b245a11f32838c Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 10:43:32 +0100 Subject: [PATCH 29/44] Address CodeRabbit review: a click-sized Perspective Crop press doesn't auto-scroll A new-box press held past egui's click time and slipped a point or two past the canvas edge counted as a drag for auto-scroll, while the release still classifies it as a corner-placing click; the scroll then moved the pointer's document position and turned the click into a box. `dragging` now uses the same click test as the release (`is_click`). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/perspective_crop_ui.rs | 90 ++++++++++++++++++++++- 1 file changed, 87 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/perspective_crop_ui.rs b/crates/ui-egui/src/perspective_crop_ui.rs index 1753eb3d7b..d3c5488d04 100644 --- a/crates/ui-egui/src/perspective_crop_ui.rs +++ b/crates/ui-egui/src/perspective_crop_ui.rs @@ -54,8 +54,21 @@ pub fn pending(app: &PhotocraftApp) -> bool { } /// A box, corner or quad drag in progress: held past the canvas edge, it scrolls the view (#4183). +/// A press that hasn't moved further than a click doesn't: scrolling would turn a corner-placing +/// click near the edge into a box. pub fn dragging(app: &PhotocraftApp) -> bool { - app.ui.tool == Tool::PerspectiveCrop && app.pcrop.drag.is_some() + app.ui.tool == Tool::PerspectiveCrop + && match app.pcrop.drag { + Some(Drag::New { start, cur }) => !is_click(app, start, cur), + Some(_) => true, + None => false, + } +} + +/// A new-box press released within [`CLICK_PX`] screen points of where it began places a corner. +fn is_click(app: &PhotocraftApp, start: [f64; 2], cur: [f64; 2]) -> bool { + let click = crate::distort_ui::tolerance(app) * CLICK_PX / 8.0; + (cur[0] - start[0]).abs() <= click && (cur[1] - start[1]).abs() <= click } pub fn cancel(app: &mut PhotocraftApp) { @@ -126,8 +139,7 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent) -> bool { ToolEvent::Up { .. } => { drag_to(app, p); if let Some(Drag::New { start, cur }) = app.pcrop.drag { - let click = tol * CLICK_PX / 8.0; - if (cur[0] - start[0]).abs() <= click && (cur[1] - start[1]).abs() <= click { + if is_click(app, start, cur) { app.pcrop.clicks.push(start); if let [a, b, c, d] = app.pcrop.clicks[..] { app.ui.perspective_crop = Some(ordered([a, b, c, d])); @@ -389,6 +401,78 @@ mod tests { h.step(); } + /// A corner-placing click pressed just inside the canvas edge that slips a point past it doesn't + /// scroll the view (scrolling would turn it into a box); a new box dragged past the edge does. + #[test] + fn a_click_at_the_canvas_edge_places_a_corner_without_scrolling() { + use egui::{Event, Modifiers, PointerButton, pos2}; + let doc = Document::with_background("p", Size::new(200, 100), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut s = photocraft_engine::Session::new(); + s.add_document(doc, None); + let mut a = PhotocraftApp::new(s, crate::Services::default()); + a.ui.tool = Tool::PerspectiveCrop; + a.ui.extras.snap = false; + a.ui.extras.rulers = false; + // 200x100 at 400% in a 600x400 canvas 100 points from the window's left: document x 25..175 + // shows. + a.ui.views = vec![crate::state::View { + zoom: 4.0, + center: [100.0, 50.0], + fit_pending: false, + fill_pending: false, + doc_size: [200, 100], + rotation: 0.0, + zoom_animating: false, + zoom_anchor: None, + display_camera: None, + zoom_transition: None, + }]; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let v = app.ui.views[0].clone(); + let rect = egui::Rect::from_min_size(egui::pos2(100.0, 0.0), egui::vec2(600.0, 400.0)); + crate::canvas::canvas_view(app, ui, 0, rect, v, true); + }, + a, + ); + h.run_steps(2); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + // Pressed a point inside the left edge (the scrollbars sit right and bottom), slipping two + // points past it: still a click. + let press = pos2(101.0, 200.0); + let slip = pos2(99.0, 200.0); + h.event(Event::PointerMoved(press)); + h.event(button(press, true)); + h.step(); + // Held past egui's click time, the press becomes a drag that hasn't left the click size. + for p in [slip, pos2(98.5, 200.0), slip] { + h.event(Event::PointerMoved(p)); + h.run_steps(4); + } + assert_eq!(h.state().ui.views[0].center, [100.0, 50.0], "a click doesn't scroll the view"); + h.event(button(slip, false)); + h.step(); + let st = h.state(); + assert_eq!(st.pcrop.clicks.len(), 1, "the click placed a corner: {:?}", st.pcrop.clicks); + assert_eq!(st.ui.perspective_crop, None); + // A new box dragged from inside the canvas past its edge does scroll. + let start = pos2(200.0, 200.0); + h.event(Event::PointerMoved(start)); + h.event(button(start, true)); + h.step(); + for p in [pos2(140.0, 220.0), pos2(50.0, 220.0)] { + h.event(Event::PointerMoved(p)); + h.step(); + } + let before = h.state().ui.views[0].center; + h.run_steps(10); + let st = h.state(); + assert!(matches!(st.pcrop.drag, Some(Drag::New { .. })), "{:?}", st.pcrop.drag); + assert!(st.ui.views[0].center[0] < before[0], "the box drag scrolled left: {:?} -> {:?}", before, st.ui.views[0].center); + h.event(button(pos2(50.0, 220.0), false)); + h.step(); + } + /// A box drag makes the quad, corners drag alone, and ↵'s commit crops the document to the /// quad's size; four clicks in any order make a quad in TL, TR, BR, BL order. #[test] From 130b2b373fa1efaa9b2ec0f894dc2a52682e00f7 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 11:08:24 +0100 Subject: [PATCH 30/44] SVG: read the DOCTYPE's internal subset when checking the markup Co-Authored-By: Claude Opus 5.5 --- crates/io/src/svg.rs | 49 +++++++++++++++++++++++++++++++++++---- crates/io/tests/it/svg.rs | 41 ++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 5 deletions(-) diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 6363945d7e..bc4881cf27 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -263,7 +263,7 @@ fn parse(bytes: &[u8]) -> Result { /// [`parse`] with the font database `fonts` supplies (the tests hand in an empty one). fn parse_with(bytes: &[u8], fonts: fn() -> Arc) -> Result { let xml = inflate(bytes)?; - if nesting_depth(&xml, MAX_XML_DEPTH) > MAX_XML_DEPTH { + if nesting_depth(&xml, MAX_XML_DEPTH)? > MAX_XML_DEPTH { return Err(IoError::Svg(format!("elements are nested more than {MAX_XML_DEPTH} levels deep"))); } let has_text = xml.windows(4).any(|w| w == b"text"); @@ -297,8 +297,10 @@ fn inflate(bytes: &[u8]) -> Result, IoError> { /// The deepest element nesting in `xml`, stopping as soon as it passes `limit` (the result is /// then `limit + 1`). Comments, CDATA sections, processing instructions and the DOCTYPE add /// nothing; quoted attribute values may hold `>` or `/>`. Malformed markup is only counted -/// loosely: the parser rejects it afterwards. -fn nesting_depth(xml: &[u8], limit: usize) -> usize { +/// loosely: the parser rejects it afterwards. The parser expands the DTD's entities after this +/// count, so an entity holding markup (a `<`) is an error: it could nest deeper than anything +/// counted here. A `<` there stays text. +fn nesting_depth(xml: &[u8], limit: usize) -> Result { let after = |from: usize, pat: &[u8]| -> usize { xml.get(from..).and_then(|s| s.windows(pat.len()).position(|w| w == pat)).map_or(xml.len(), |p| from.saturating_add(p).saturating_add(pat.len())) }; @@ -320,6 +322,41 @@ fn nesting_depth(xml: &[u8], limit: usize) -> usize { } (xml.len(), false) }; + // The byte after the DOCTYPE starting at `from`: its internal subset `[...]` is walked + // declaration by declaration, so a quote in a comment there can't hide the markup after it. + let doctype_end = |from: usize| -> Result { + let (mut quote, mut j) = (None, from); + loop { + let Some(&b) = xml.get(j) else { return Ok(xml.len()) }; + j = j.saturating_add(1); + match quote { + Some(q) if b == q => quote = None, + Some(_) => {} + None if b == b'"' || b == b'\'' => quote = Some(b), + None if b == b'>' => return Ok(j), + None if b == b'[' => break, + None => {} + } + } + while let Some(rest) = xml.get(j..).filter(|r| !r.is_empty()) { + j = if rest.starts_with(b"") + } else if rest.starts_with(b"") + } else if rest.starts_with(b" usize { after(at.saturating_add(9), b"]]>") } else if rest.starts_with(b"") + } else if rest.starts_with(b" usize { depth = depth.saturating_add(1); deepest = deepest.max(depth); if deepest > limit { - return deepest; + return Ok(deepest); } } end }; } - deepest + Ok(deepest) } /// The document canvas for a drawing: its size in px, scaled down to [`MAX_SIDE`] when needed. diff --git a/crates/io/tests/it/svg.rs b/crates/io/tests/it/svg.rs index c71bb0ae4f..527067508b 100644 --- a/crates/io/tests/it/svg.rs +++ b/crates/io/tests/it/svg.rs @@ -351,6 +351,47 @@ fn deeply_nested_markup_is_an_error_not_a_stack_overflow() { assert_eq!(r.document.layers.len(), 1); } +/// The parser expands a DTD's internal entities after the depth check: an entity holding +/// markup, or a quote in a DTD comment that made the check skip ahead, hid 20 000 nested groups +/// from it and overflowed the stack again. Both are errors now; same small stack as above. +#[test] +fn a_dtd_cannot_hide_nesting_from_the_depth_check() { + let deep = |open: &str, close: &str| format!("{}{}", open.repeat(20_000), close.repeat(20_000)); + let with_dtd = |subset: &str, body: &str| format!("{body}"); + let cases = [ + ("entity", with_dtd(&format!("", deep("", "")), "&a;")), + ("single-quoted entity", with_dtd(&format!("", deep("", "")), "&a;")), + ("quote in a comment", with_dtd("", &format!("{}'", deep("", "")))), + ]; + std::thread::Builder::new() + .stack_size(512 * 1024) + .spawn(move || { + for (name, svg) in &cases { + let gz = gzip(svg.as_bytes()); + for bytes in [svg.as_bytes(), gz.as_slice()] { + let e = import("deep.svg", bytes).err().unwrap_or_else(|| panic!("{name} opened")); + assert!(matches!(&e, IoError::Svg(_)), "{name}: {e}"); + } + } + }) + .unwrap() + .join() + .unwrap(); +} + +/// Text-only entities, as Illustrator declares its namespaces, still open, `<` included: +/// the parser keeps a character reference in an entity as text. +#[test] +fn text_entities_in_a_dtd_still_open() { + let r = open( + " ?> ]>\ + &c;", + ); + assert_eq!(r.document.layers.len(), 1); + assert!(close(px(&r.document, 4, 4), [1.0, 0.0, 0.0, 1.0])); +} + /// The depth check reads the markup, not the parser's tree: it must not count `<` in comments, /// CDATA, processing instructions or the DOCTYPE, nor end a tag at a `>` inside quotes. #[test] From b05e02c9b319beccf58ddd8ad000b05dc91064e2 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 11:20:04 +0100 Subject: [PATCH 31/44] SVG: end the DTD's element, attribute and notation declarations as the parser does Co-Authored-By: Claude Opus 5.5 --- crates/io/src/svg.rs | 7 +++++-- crates/io/tests/it/svg.rs | 10 ++++++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index bc4881cf27..17eaef221d 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -343,12 +343,15 @@ fn nesting_depth(xml: &[u8], limit: usize) -> Result { after(j.saturating_add(4), b"-->") } else if rest.starts_with(b"") - } else if rest.starts_with(b"`, quotes or not. + after(j.saturating_add(2), b">") } else if rest.starts_with(b"]") { return Ok(tag_end(j.saturating_add(1)).0); } else { diff --git a/crates/io/tests/it/svg.rs b/crates/io/tests/it/svg.rs index 527067508b..f856616989 100644 --- a/crates/io/tests/it/svg.rs +++ b/crates/io/tests/it/svg.rs @@ -352,7 +352,7 @@ fn deeply_nested_markup_is_an_error_not_a_stack_overflow() { } /// The parser expands a DTD's internal entities after the depth check: an entity holding -/// markup, or a quote in a DTD comment that made the check skip ahead, hid 20 000 nested groups +/// markup, or a quote in a DTD comment or declaration that made the check skip ahead, hid 20 000 nested groups /// from it and overflowed the stack again. Both are errors now; same small stack as above. #[test] fn a_dtd_cannot_hide_nesting_from_the_depth_check() { @@ -362,6 +362,12 @@ fn a_dtd_cannot_hide_nesting_from_the_depth_check() { ("entity", with_dtd(&format!("", deep("", "")), "&a;")), ("single-quoted entity", with_dtd(&format!("", deep("", "")), "&a;")), ("quote in a comment", with_dtd("", &format!("{}'", deep("", "")))), + ("quote in an element declaration", with_dtd("", &format!("{}'", deep("", "")))), + ( + "entity between quoted attribute lists", + with_dtd(&format!("", deep("", "")), "&a;"), + ), + ("entity between quoted notations", with_dtd(&format!("", deep("", "")), "&a;")), ]; std::thread::Builder::new() .stack_size(512 * 1024) @@ -385,7 +391,7 @@ fn a_dtd_cannot_hide_nesting_from_the_depth_check() { fn text_entities_in_a_dtd_still_open() { let r = open( " ?> ]>\ + ?> ]>\ &c;", ); assert_eq!(r.document.layers.len(), 1); From 21d0ac3a1026c01d8d4b1906e91940956165d53b Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 26 Oct 2026 13:27:52 +0100 Subject: [PATCH 32/44] Tests: a .pcraft smart object with a hostile SVG source does not abort Image Size or a PSD save Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/tests/it/svg_smart_object.rs | 29 ++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/crates/engine/tests/it/svg_smart_object.rs b/crates/engine/tests/it/svg_smart_object.rs index 16d8f3d459..450d54c175 100644 --- a/crates/engine/tests/it/svg_smart_object.rs +++ b/crates/engine/tests/it/svg_smart_object.rs @@ -62,3 +62,32 @@ fn re_placing_at_another_scale_re_renders_the_vector_source() { assert!(alpha(&surf, 268, 60) > 0.99 && alpha(&surf, 271, 60) < 0.01); assert!(red(&surf, 150, 81) < 0.02 && red(&surf, 150, 75) > 0.98 && red(&surf, 150, 87) > 0.98); } + +/// A `.pcraft` opens from its cached pixels and parses an embedded SVG source only on a later +/// edit. A source whose DTD entity hides 20 000 nested groups from the depth check used to open +/// clean and then overflow the stack on Image Size or a PSD save; both are an error or a fallback +/// now. Run on a 2 MB stack, as the app's import and command threads are. +#[test] +fn a_pcraft_smart_object_with_a_hostile_svg_does_not_abort_a_later_edit() { + let deep = format!("{}{}", "".repeat(20_000), "".repeat(20_000)); + let hostile = format!("]>&a;"); + std::thread::Builder::new() + .stack_size(2 * 1024 * 1024) + .spawn(move || { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100, "background": "white"})).unwrap(); + photocraft_engine::file_cmds::place_bytes(&mut s, "logo.svg", SVG.as_bytes().to_vec(), None, &json!({"scale": 100})).unwrap(); + let mut doc = (*s.active().unwrap().doc).clone(); + let LayerContent::Smart(sm) = &mut doc.layers.last_mut().unwrap().content else { panic!("smart object") }; + sm.source = photocraft_doc::SmartSource::Embedded { file_name: "logo.svg".into(), bytes: std::sync::Arc::new(hostile.into_bytes()) }; + let carrier = photocraft_format::save_to_bytes(&doc, &photocraft_format::SaveOptions::default()).unwrap(); + + photocraft_engine::file_cmds::open_bytes_as(&mut s, "carrier.pcraft", &carrier, None, None).unwrap(); + let _ = s.execute("image.imageSize", json!({"width": 50, "height": 50})); + let dir = tempfile::tempdir().unwrap(); + let _ = s.execute("file.saveACopy", json!({"path": dir.path().join("copy.psd").to_string_lossy()})); + }) + .unwrap() + .join() + .unwrap(); +} From da87348f8612c701c008a75835ed7a0841154ae9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 26 Oct 2026 13:52:42 +0100 Subject: [PATCH 33/44] SVG: the fallback font search reads each font's character map once (#9671) A character the text's font lacks made usvg's fallback search ask every face in the database whether it has the character, and for a face loaded from a file (every system font) that reads the whole font file. Once per text element: 20 elements with U+10FF00 took 3 s with 273 installed faces. The fallback selector is now our own copy of usvg's loop (same order, used-face exclusion and style filter), and the per-face check answers from a per-process cache of each file face's cmap table, picked as ttf-parser's Face::parse picks it (last record of a linear walk, so an unsorted table directory gives the same table) and looked up the same way. Bounded at 64 MiB; a file that doesn't load isn't remembered. Co-Authored-By: Claude Opus 5.5 (1M context) --- Cargo.lock | 1 + crates/io/Cargo.toml | 2 + crates/io/src/svg.rs | 141 ++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 142 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 128d0f35bd..1930841ac3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5139,6 +5139,7 @@ dependencies = [ "serde_json", "thiserror 2.0.21", "tiff", + "ttf-parser", "zune-core 0.5.3", "zune-jpegxl", ] diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 83ccd3b784..5cf15cf62d 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -44,6 +44,8 @@ roxmltree = "0.21" # already in the tree through the UI's icon loader; text shaping needs the fonts feature set. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] resvg = { version = "0.45", default-features = false, features = ["text", "system-fonts", "raster-images"] } +# The SVG fallback font search keeps each font file's character map (already in the tree through usvg). +ttf-parser = { version = "0.25", default-features = false } [target.'cfg(target_arch = "wasm32")'.dependencies] resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] } diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 7ff563d466..4532c33697 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -268,15 +268,78 @@ fn in_memory(id: usvg::fontdb::ID, db: &mut Arc) -> usvg loaded.into_iter().find(|&n| db.face_source(n).is_some_and(|(_, i)| i == index)).unwrap_or(id) } +/// Most `cmap` table bytes [`has_char`] keeps; past it a face is asked on disk (slow, still right). +#[cfg(not(target_arch = "wasm32"))] +const MAX_CACHED_CMAP_BYTES: usize = 64 << 20; + +/// Whether face `face` maps `c` to a glyph, as usvg's own check decides it. usvg reads a font +/// file's whole font for every face it asks, so one character no font has re-read every +/// installed font once per text element (430 ms each with 273 faces). A file face's `cmap` table +/// is kept instead, read once per process; a file that doesn't load isn't remembered. +#[cfg(not(target_arch = "wasm32"))] +fn has_char(db: &usvg::fontdb::Database, face: &usvg::fontdb::FaceInfo, c: char) -> bool { + use std::collections::HashMap; + use std::path::PathBuf; + use std::sync::{Mutex, PoisonError}; + use ttf_parser::{Face, Tag, cmap}; + type Cmaps = (HashMap<(PathBuf, u32), Arc>>, usize); + static CMAPS: OnceLock> = OnceLock::new(); + let maps = || CMAPS.get_or_init(Mutex::default).lock().unwrap_or_else(PoisonError::into_inner); + let in_cmap = + |table: &[u8]| cmap::Table::parse(table).is_some_and(|t| t.subtables.into_iter().any(|s| s.is_unicode() && s.glyph_index(u32::from(c)).is_some())); + let usvg_check = |data: &[u8], index| Face::parse(data, index).is_ok_and(|f| f.glyph_index(c).is_some()); + let usvg::fontdb::Source::File(path) = &face.source else { + return db.with_face_data(face.id, usvg_check).unwrap_or(false); + }; + let key = (path.clone(), face.index); + if let Some(table) = maps().0.get(&key).cloned() { + return in_cmap(&table); + } + // usvg's check parses the whole face first: one that doesn't parse has no characters. Its + // `cmap` is the last such table record (a linear walk, unsorted directories included). + let cmap_of = |data: &[u8], index| { + let face = Face::parse(data, index).ok()?; + let raw = face.raw_face(); + let record = raw.table_records.into_iter().filter(|r| r.tag == Tag::from_bytes(b"cmap")).last(); + let table = record.and_then(|r| { + let start = usize::try_from(r.offset).ok()?; + raw.data.get(start..start.checked_add(usize::try_from(r.length).ok()?)?) + }); + Some(table.unwrap_or_default().to_vec()) + }; + let Some(table) = db.with_face_data(face.id, cmap_of).flatten() else { + return false; + }; + let found = in_cmap(&table); + let mut maps = maps(); + // An import that missed at the same time may have kept it already. + if !maps.0.contains_key(&key) && maps.1.saturating_add(table.len()) <= MAX_CACHED_CMAP_BYTES { + maps.1 = maps.1.saturating_add(table.len()); + maps.0.insert(key, Arc::new(table)); + } + found +} + +/// usvg's fallback choice (the first face, in database order, not used yet, sharing the base +/// face's style, weight or stretch and having `c`), asked through [`has_char`]. +#[cfg(not(target_arch = "wasm32"))] +fn fallback_face(c: char, used: &[usvg::fontdb::ID], db: &usvg::fontdb::Database) -> Option { + let base = db.face(*used.first()?)?; + db.faces() + .filter(|f| !used.contains(&f.id)) + .filter(|f| base.style == f.style || base.weight == f.weight || base.stretch == f.stretch) + .find(|f| has_char(db, f, c)) + .map(|f| f.id) +} + /// usvg's font choice, with the chosen faces read from memory ([`in_memory`]). fn font_resolver() -> usvg::FontResolver<'static> { #[cfg(not(target_arch = "wasm32"))] { let select = usvg::FontResolver::default_font_selector(); - let fallback = usvg::FontResolver::default_fallback_selector(); usvg::FontResolver { select_font: Box::new(move |font, db| select(font, db).map(|id| in_memory(id, db))), - select_fallback: Box::new(move |c, used, db| fallback(c, used, db).map(|id| in_memory(id, db))), + select_fallback: Box::new(|c, used, db| fallback_face(c, used, db).map(|id| in_memory(id, db))), } } #[cfg(target_arch = "wasm32")] @@ -1281,6 +1344,80 @@ mod tests { } } + /// #9671: the fallback search for a character the text's font lacks reads each font file's + /// character map once per process, not the whole file on every text element (430 ms an + /// element with 273 installed faces). A second import still finds the fallback face after + /// its file stopped being readable, so it didn't go back to the disk. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_fallback_search_reads_each_font_file_once() { + use std::sync::atomic::{AtomicBool, Ordering}; + static GONE: AtomicBool = AtomicBool::new(false); + fn path() -> std::path::PathBuf { + std::env::temp_dir().join(format!("photocraft-svg-test-fallback-{}.ttf", std::process::id())) + } + fn inter_and_mono_on_disk() -> Arc { + std::fs::write(path(), include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf")).unwrap(); + let mut db = usvg::fontdb::Database::new(); + db.load_font_data(include_bytes!("../../../assets/fonts/Inter-Regular.ttf").to_vec()); + db.load_font_file(path()).unwrap(); + if GONE.load(Ordering::SeqCst) { + std::fs::write(path(), b"not a font any more").unwrap(); + } + Arc::new(db) + } + // Inter has no box-drawing characters; JetBrains Mono has. + let svg = "I\u{2500}I"; + let outlines = |parsed: Parsed| { + let layers = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap().document.layers; + let groups = layers.into_iter().filter_map(|l| if let LayerContent::Group(g) = l.content { Some(g) } else { None }); + groups.flat_map(|g| g.children).filter_map(|l| if let LayerContent::Shape(s) = l.content { Some(s.path) } else { None }).collect::>() + }; + let first = parse_with(svg.as_bytes(), inter_and_mono_on_disk).unwrap(); + let mono = + first.tree.fontdb().faces().any(|f| f.families.iter().any(|(n, _)| n == "JetBrains Mono") && matches!(f.source, usvg::fontdb::Source::Binary(_))); + assert!(mono, "the box-drawing character falls back to JetBrains Mono"); + let first = outlines(first); + GONE.store(true, Ordering::SeqCst); + let second = outlines(parse_with(svg.as_bytes(), inter_and_mono_on_disk).unwrap()); + let _ = std::fs::remove_file(path()); + assert!(first.iter().any(|p| !p.subpaths.is_empty()), "the text has outlines"); + assert!(second == first, "the second import set the character in the same fallback face"); + } + + /// #9671: the kept `cmap` is the one usvg reads (the last such record of a linear walk), also + /// in a font whose table directory isn't sorted by tag, where a binary search misses it. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_fallback_search_reads_the_cmap_of_an_unsorted_font() { + fn inter_and_unsorted_mono_on_disk() -> Arc { + let mut font = include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf").to_vec(); + let count = usize::from(u16::from_be_bytes([font[4], font[5]])); + // The `cmap` record moves to the end of the directory. + let mut records: Vec> = font[12..12 + count * 16].chunks(16).map(<[u8]>::to_vec).collect(); + let at = records.iter().position(|r| r.starts_with(b"cmap")).unwrap(); + let cmap = records.remove(at); + records.push(cmap); + font.splice(12..12 + count * 16, records.concat()); + let raw = ttf_parser::RawFace::parse(&font, 0).unwrap(); + assert!(raw.table(ttf_parser::Tag::from_bytes(b"cmap")).is_none(), "a binary search misses the cmap"); + assert!(raw.table(ttf_parser::Tag::from_bytes(b"name")).is_some(), "fontdb still finds the name"); + let path = std::env::temp_dir().join(format!("photocraft-svg-test-unsorted-{}.ttf", std::process::id())); + std::fs::write(&path, font).unwrap(); + let mut db = usvg::fontdb::Database::new(); + db.load_font_data(include_bytes!("../../../assets/fonts/Inter-Regular.ttf").to_vec()); + db.load_font_file(&path).unwrap(); + Arc::new(db) + } + let svg = + b"I\xE2\x94\x80I"; + let parsed = parse_with(svg, inter_and_unsorted_mono_on_disk).unwrap(); + let _ = std::fs::remove_file(std::env::temp_dir().join(format!("photocraft-svg-test-unsorted-{}.ttf", std::process::id()))); + let mono = + parsed.tree.fontdb().faces().any(|f| f.families.iter().any(|(n, _)| n == "JetBrains Mono") && matches!(f.source, usvg::fontdb::Source::Binary(_))); + assert!(mono, "the box-drawing character falls back to JetBrains Mono"); + } + /// #9406: moving a font collection into memory keeps its faces in their order, so the /// fallback search for a later text still finds the face it found on disk first. #[cfg(not(target_arch = "wasm32"))] From bfa718f20b8f3af2ecdd50eb73acf24b7c750b49 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 26 Oct 2026 14:43:48 +0100 Subject: [PATCH 34/44] Dropdowns: a list opening above its box is in place from its first visible frame (#5495) egui placed an upward list's bottom by the size it had the frame before, so it moved up by ~46 pt as it settled and a click two frames after opening missed the row (main's intermediate_ui_scale_choices test). Its top is now placed from the rows' measured height plus the popup frame's margin. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/widgets.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index cf860b2b93..e5115bc12d 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1769,15 +1769,25 @@ pub fn combo_list( let rows_id = popup_id.with("rows"); let rows = ctx.data(|d| d.get_temp::(rows_id)); let up = rows.is_some_and(|rows| rows > below) && above > below; - let (align, room) = if up { (egui::RectAlign::TOP_START, above) } else { (egui::RectAlign::BOTTOM_START, below) }; // Only the room that side has, even when it is small: a taller list would be pushed back // into the window, over its button (#5495 review). - let room = room.max(0.0); + let room = (if up { above } else { below }).max(0.0); + // Above the button the list's top is placed from its known height: egui would place its + // bottom by the size the list had last frame, so it would move as it settles, under a + // click aimed at a row. `chrome` is the popup frame's margin and stroke. + let anchor = match rows.filter(|_| up) { + Some(rows) => { + let chrome = egui::Frame::popup(&ctx.global_style()).total_margin().sum().y; + let top = button.rect.top() - rows.min(room) - chrome; + egui::Rect::from_x_y_ranges(button.rect.x_range(), top - button.rect.height()..=top) + } + None => button.rect, + }; let parent_layer = ui.layer_id(); let inner = egui::Popup::menu(&button) .id(popup_id) - .anchor(button.rect) - .align(align) + .anchor(anchor) + .align(egui::RectAlign::BOTTOM_START) .align_alternatives(&[]) .width(button.rect.width()) .close_behavior(close) From d03b47f8a9e28590309d98a9be076b53a10b36bd Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 26 Oct 2026 15:25:54 +0100 Subject: [PATCH 35/44] Scorecard: regenerate after merging main (#3634) Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 8045086f6b..7bdd69549d 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 31 | 65 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 27 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 12 of 180 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 12 of 183 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -187,7 +187,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 12 of 180** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 12 of 183** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.gpu_adapter`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. From 0dfbbbf1a93d3aa80feda6fcef26c5eefe86c933 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 29 Oct 2026 17:01:52 +0100 Subject: [PATCH 36/44] Crop: the click guard skips the snap on release again An earlier merge (f35107a8ea, snap_ui.rs moved into canvas/) applied the guard's hunk to the Move branch, whose context lines match the Up branch's. A click has no Move, so its release still snapped the frame and the test a_click_on_the_frame_or_a_handle_never_snaps_it failed. The guard is back on Up, where a release at the press point leaves the frame alone. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/snap_ui.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/canvas/snap_ui.rs b/crates/ui-egui/src/canvas/snap_ui.rs index 92123bb38b..d52e6f28cb 100644 --- a/crates/ui-egui/src/canvas/snap_ui.rs +++ b/crates/ui-egui/src/canvas/snap_ui.rs @@ -526,11 +526,6 @@ pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifier if app.prefs_rt.snap.is_none() { return ev; } - if crop_click(app, [x, y]) { - app.prefs_rt.snap = None; - app.prefs_rt.snap_lines.clear(); - return ev; - } follow_reposition(app); let disabled = override_for_gesture(app, mods); if let Some(s) = app.prefs_rt.snap.as_mut() { @@ -544,6 +539,11 @@ pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifier if app.prefs_rt.snap.is_none() { return ev; } + if crop_click(app, [x, y]) { + app.prefs_rt.snap = None; + app.prefs_rt.snap_lines.clear(); + return ev; + } follow_reposition(app); let disabled = override_for_gesture(app, mods); if let Some(s) = app.prefs_rt.snap.as_mut() { From b69f56de4d5dc0f650ae1a30961d316391f59954 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 29 Oct 2026 17:09:17 +0100 Subject: [PATCH 37/44] Scorecard: regenerate after merging main (#3634) Co-Authored-By: Claude Opus 5.5 --- docs/scorecard.md | 4 ++-- docs/ui-parity.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 076537a3a2..965e949839 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 45 | 79 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 41 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 12 of 181 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 12 of 184 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -203,7 +203,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 12 of 181** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 12 of 184** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.gpu_adapter`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 01a4e74df3..65c77d4c42 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (History Options snapshot options, #3634; New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; 12 of 181 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (History Options snapshot options, #3634; New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; 12 of 184 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -230,7 +230,7 @@ Paragraph; the rest open as in-app floating windows. | Histogram panel: Compact (the default, of the entire image), Expanded and All Channels views (the channel kept across them); RGB/CMYK/Lab/Gray channels, Luminosity and Colors (overlaid, mixed where they overlap); Show Channels in Color and Show Statistics; Source (Entire Image, Selected Layer, Adjustment Composite) for multilayer documents; Mean, Std Dev, Median, Pixels, Level, Count, Percentile and Cache Level for the pointer level or a dragged range; the cached-data warning, Uncached Refresh (menu, button, warning click, double-click); the adjusted histogram over the original while an adjustment previews; Cache Levels 1–8 in Preferences › Performance; Color Sampler levels marked on the graph | partial | `histogram_panel.rs`, `histogram_panel_tests.rs`, `tone.rs`; differs: filter dialogs that preview on the CPU proxy aren't counted live, a selection doesn't limit the histogram yet, with Source Selected Layer an adjustment dialog's preview isn't counted, and new strings are English-only so far | | Command palette with recents | done | UI-217-7 | | Menu bar from the keyboard: Alt / F10 focus the bar, ← → ↓ ↩ drive it, Alt+letter opens a menu, underlined mnemonics run items | done | `menu_keys.rs`, #4988; macOS uses the native bar | -| Every preference takes effect | partial | 12 of 181 do nothing (scorecard, 2026-10-27) | +| Every preference takes effect | partial | 12 of 184 do nothing (scorecard, 2026-10-29) | | UI scale presets | done | UI-217-9; 75–125% in 5% steps (#2492, #3222) | | History snapshots: camera button, New Snapshot dialog (⌥-click: Name, From), the first snapshot (the document as opened), snapshot rows (click returns and selects, rename, delete; the trash deletes the selected snapshot, and a snapshot or state dragged onto it, #5324), `history.*Snapshot` commands; History Options' snapshot options (Automatically Create First Snapshot, New Snapshot When Saving, Show New Snapshot Dialog by Default) | partial | `history_cmds.rs`, `history_options_cmds.rs`, `snapshot_rows` in `panels.rs`, `snapshot_dialog.rs`; History Brush sources to come (#2966) | | Themes: Photoshop's four greys | partial | five themes; #2661 | From ec49d0b5820ea1e84decc549f772d035747bdf7c Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 29 Oct 2026 17:19:25 +0100 Subject: [PATCH 38/44] Address CodeRabbit review: end a crop drag before the frame sees a tool switch The canvas ends the gesture before `ensure_frame` (which dropped the untouched default frame under the box being drawn, and the Hand never reached `tool_event`), keeping the pen eraser exception. A press inside the default frame that never moves is no edit, so leaving still drops a selection-derived default frame. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 4 ++ crates/ui-egui/src/tools/crop_ui.rs | 12 +++- crates/ui-egui/src/tools/crop_ui/tests.rs | 70 +++++++++++++++++++++++ 3 files changed, 85 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 3896b84cf6..374c6a6e5a 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1876,6 +1876,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: crate::crop_straighten::set_held(app, !ctx.text_edit_focused() && ui.input(|i| i.modifiers.command)); // A tab switched this frame drops the other document's pending crop (#1918). crate::crop_ui::cancel_stale(app); + // A tool picked mid-drag ends the crop gesture before the frame sees the switch, which would + // otherwise drop the untouched default frame under the box being drawn (#9223). The Hand and + // Zoom never reach `tool_event`, so this is the one place that sees every tool. + crate::crop_ui::end_drag_on_leave(app); crate::crop_ui::ensure_frame(app); let mut drawing = crate::crop_ui::active(app); if let Some(d) = app.drag.as_mut().filter(|d| crate::hold_keys::repositions(d.tool)) { diff --git a/crates/ui-egui/src/tools/crop_ui.rs b/crates/ui-egui/src/tools/crop_ui.rs index 249ba88f5c..6a569aa68f 100644 --- a/crates/ui-egui/src/tools/crop_ui.rs +++ b/crates/ui-egui/src/tools/crop_ui.rs @@ -863,7 +863,9 @@ fn release(app: &mut PhotocraftApp, drag: CropDrag) { let ok = app.ui.crop_rect.is_some_and(size_ok); // A click outside the untouched default frame (no turn) leaves it the default. let changed = !matches!(drag, CropDrag::Rotate { from, .. } | CropDrag::TurnImage { from, .. } if from == angle(app)) - && !matches!(drag, CropDrag::MoveImage { rect, .. } if app.ui.crop_rect == Some(rect)); + && !matches!(drag, CropDrag::MoveImage { rect, .. } if app.ui.crop_rect == Some(rect)) + // A press that never moved draws nothing: the frame shown is still the previous one. + && !matches!(drag, CropDrag::Draw { anchor, cur, .. } if anchor == cur); if ok && changed { app.crop.default_frame = false; } @@ -886,6 +888,14 @@ pub fn end_drag(app: &mut PhotocraftApp) { app.ui.tool = tool; } +/// [`end_drag`] once another tool is current, except while the pen's eraser end stands in for the +/// Crop tool (`stylus`): the gesture goes on when the tip comes back. +pub fn end_drag_on_leave(app: &mut PhotocraftApp) { + if app.ui.tool != Tool::Crop && app.stylus.tool_before_eraser != Some(Tool::Crop) { + end_drag(app); + } +} + /// On release: the frame state at the press becomes a box Undo step when the gesture changed it. fn push_press_step(app: &mut PhotocraftApp) { if let Some(before) = app.crop.press_step.take() diff --git a/crates/ui-egui/src/tools/crop_ui/tests.rs b/crates/ui-egui/src/tools/crop_ui/tests.rs index 4c00297a02..8160a3c42f 100644 --- a/crates/ui-egui/src/tools/crop_ui/tests.rs +++ b/crates/ui-egui/src/tools/crop_ui/tests.rs @@ -858,6 +858,76 @@ fn a_tool_switch_during_a_drag_on_the_default_frame_keeps_the_edit() { } } +/// Real egui input: a tool picked while a box is being drawn over the untouched default frame +/// (a tool key mid-drag) commits that box on leaving, whichever tool it is; the canvas ends the +/// gesture before the frame sees the switch, also for the Hand, whose events never reach +/// `tool_event` (#9223). +#[test] +fn a_tool_switch_during_a_real_drag_commits_the_drawn_box() { + use egui::{Event, PointerButton, pos2}; + for tool in [Tool::Brush, Tool::PerspectiveCrop, Tool::Hand] { + let mut a = app(SampleType::U8); + a.sync_views(); + let v = &mut a.ui.views[0]; + (v.zoom, v.center, v.fit_pending, v.doc_size, v.rotation) = (2.0, [100.0, 50.0], false, [200, 100], 0.0); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let v = app.ui.views[0].clone(); + crate::canvas::canvas_view(app, ui, 0, ui.max_rect(), v, true); + }, + a, + ); + h.run_steps(2); + assert!(h.state().crop.default_frame, "{tool:?}"); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let p0 = pos2(200.0, 150.0); + h.event(Event::PointerMoved(p0)); + h.event(button(p0, true)); + h.step(); + for p in [pos2(220.0, 170.0), pos2(260.0, 190.0)] { + h.event(Event::PointerMoved(p)); + h.step(); + } + assert!(h.state().crop.drag.is_some(), "{tool:?}"); + h.state_mut().ui.tool = tool; + h.event(Event::PointerMoved(pos2(270.0, 195.0))); + h.step(); + h.event(button(pos2(270.0, 195.0), false)); + h.run_steps(2); + let st = h.state(); + assert!(st.crop.drag.is_none(), "{tool:?}"); + assert_eq!(st.ui.crop_rect, None, "{tool:?}"); + assert_eq!(st.session.active().unwrap().doc.size, Size::new(30, 20), "{tool:?}: the drawn 60x40 screen px at 200%"); + } +} + +/// A press inside the untouched default frame that never moves draws nothing, so the frame +/// stays the default one and leaving drops it: no crop to the selection's bounds, released or +/// cut short by a tool switch (#9223). +#[test] +fn a_press_that_never_moves_leaves_the_default_frame_untouched() { + for switch in [false, true] { + let mut app = app(SampleType::U8); + app.run("select.rect", json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap(); + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, Some([10.0, 20.0, 40.0, 60.0])); + let steps = app.session.active().unwrap().history.past_len(); + tool_event(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 }, NONE); + if switch { + app.ui.tool = Tool::Brush; + end_drag_on_leave(&mut app); + } else { + tool_event(&mut app, ToolEvent::Up { x: 25.0, y: 40.0 }, NONE); + assert!(app.crop.default_frame, "a click is no edit"); + app.ui.tool = Tool::Brush; + } + ensure_frame(&mut app); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.size, st.history.past_len()), (Size::new(200, 100), steps), "switch: {switch}"); + assert_eq!(app.ui.crop_rect, None, "switch: {switch}"); + } +} + /// Image › Crop with a pending crop commits the frame (the one Image item Photoshop keeps). #[test] fn image_crop_menu_commits_a_pending_crop() { From cf9a7254d597a8903c2326bc383684c1af55d389 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 29 Oct 2026 17:20:25 +0100 Subject: [PATCH 39/44] Address CodeRabbit review: budget the image between bicubic passes A bicubic shrink of both axes stores the image between its two passes with one axis still at its old size, larger than the result. The hidden pixel budget now checks the largest rectangle of each surface's pass plan (algo::resample::largest_resize_rect), masks, channels and the selection with their Bilinear filter. Co-Authored-By: Claude Opus 5.5 --- crates/algo/src/resample.rs | 18 +++++++++++- crates/algo/src/resample/tests.rs | 19 ++++++++++++ crates/engine/src/cmd/image_cmds.rs | 36 +++++++++++------------ crates/engine/src/cmd/image_cmds/tests.rs | 18 ++++++++++++ 4 files changed, 72 insertions(+), 19 deletions(-) diff --git a/crates/algo/src/resample.rs b/crates/algo/src/resample.rs index 4dcf0b6944..c8c0580bbf 100644 --- a/crates/algo/src/resample.rs +++ b/crates/algo/src/resample.rs @@ -288,6 +288,21 @@ pub fn scaled_rect(r: Rect, sx: f64, sy: f64) -> Rect { Rect::new((r.x0 as f64 * sx).floor() as i32, (r.y0 as f64 * sy).floor() as i32, (r.x1 as f64 * sx).ceil() as i32, (r.y1 as f64 * sy).ceil() as i32) } +/// The largest rectangle a resize of content at `r` by `(sx, sy)` with `filter` stores: the +/// result, or the image between the passes of a two-pass bicubic. That one keeps an axis at its +/// old size, so when both axes shrink it is larger than the result (#9212). +pub fn largest_resize_rect(r: Rect, sx: f64, sy: f64, filter: Resample) -> Rect { + let area = |r: Rect| u64::from(r.width()) * u64::from(r.height()); + let (mut cur, mut largest) = (r, Rect::EMPTY); + for p in plan(filter, sx, sy) { + cur = scaled_rect(cur, p.sx, p.sy); + if area(cur) > area(largest) { + largest = cur; + } + } + largest +} + /// Resizes a surface by `(sx, sy)` about the document origin. The surface's /// default pixel is kept (masks keep their "reveal all" background). pub fn resize_surface(s: &Surface, sx: f64, sy: f64, filter: Resample) -> Surface { @@ -346,7 +361,8 @@ fn resize(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Option) /// Runs `filter`'s passes. Between two passes the image is stored in its own format, which /// clips it (and rounds it at 8 and 16 bits) as Photoshop does; the smaller scale goes first, so -/// the intermediate image is never larger than the result. +/// the intermediate image is never larger than the result when an axis grows, but is when both +/// shrink ([`largest_resize_rect`]). fn resize_with_budget(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Option, budget: usize) -> Surface { let mut cur: Option = None; let mut canvas = canvas; diff --git a/crates/algo/src/resample/tests.rs b/crates/algo/src/resample/tests.rs index 0ee08847e1..3fb68936d3 100644 --- a/crates/algo/src/resample/tests.rs +++ b/crates/algo/src/resample/tests.rs @@ -400,3 +400,22 @@ fn nearest_neighbor_reduction_does_not_average() { } } } + +/// #9212: a bicubic shrink of both axes stores the image between its passes with one axis at the +/// old size, larger than the result; single-pass filters and growing axes store nothing larger. +#[test] +fn largest_resize_rect_counts_the_image_between_the_passes() { + let r = Rect::new(0, 0, 100, 80); + for f in [Resample::Bicubic, Resample::BicubicSharper, Resample::BicubicAutomatic, Resample::PreserveDetails] { + assert_eq!(largest_resize_rect(r, 0.5, 0.5, f), Rect::new(0, 0, 50, 80), "{f:?}"); + } + // The axis with the smaller scale goes first. + assert_eq!(largest_resize_rect(r, 0.5, 0.25, Resample::Bicubic), Rect::new(0, 0, 100, 20)); + for f in [Resample::Bilinear, Resample::Nearest, Resample::Lanczos] { + assert_eq!(largest_resize_rect(r, 0.5, 0.5, f), Rect::new(0, 0, 50, 40), "{f:?}"); + } + for f in [Resample::Bicubic, Resample::BicubicAutomatic] { + assert_eq!(largest_resize_rect(r, 2.0, 3.0, f), Rect::new(0, 0, 200, 240), "{f:?} grows"); + assert_eq!(largest_resize_rect(r, 0.5, 2.0, f), Rect::new(0, 0, 50, 160), "{f:?} shrinks x, grows y"); + } +} diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index 4494b5d13d..ad4203ece5 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -3,7 +3,7 @@ use std::convert::Infallible; -use photocraft_algo::resample::{Resample, crop_surface, resize_surface_in_canvas, translate_surface}; +use photocraft_algo::resample::{Resample, crop_surface, largest_resize_rect, resize_surface_in_canvas, scaled_rect, translate_surface}; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::{Document, Effect, Effects, FxPaint, Layer, LayerContent, LayerId, Size}; use photocraft_geom::Rect; @@ -297,7 +297,7 @@ pub(crate) fn resample_doc(doc: &mut Document, cmd: &str, nw: u32, nh: u32, filt if (sx - 1.0).abs() < 1e-12 && (sy - 1.0).abs() < 1e-12 { return Ok(()); } - check_hidden_resample_budget(cmd, doc, sx, sy)?; + check_hidden_resample_budget(cmd, doc, sx, sy, filter)?; // Content that reaches the canvas edge keeps it: a Background stays opaque to the border. let canvas = Rect::from_xywh(0, 0, ow, oh); let taken = crate::smart_cmds::take_caches(&mut doc.layers); @@ -329,23 +329,23 @@ pub(crate) fn resample_doc(doc: &mut Document, cmd: &str, nw: u32, nh: u32, filt Ok(()) } -/// [`check_resample_budget`] for the largest surface [`resample_doc`] scales by `sx` x `sy`: each -/// keeps its pixels outside the canvas (a crop that didn't delete them, a layer moved off the -/// canvas), and those grow with the scale like the rest. -fn check_hidden_resample_budget(cmd: &str, doc: &mut Document, sx: f64, sy: f64) -> Result<()> { - let canvas = doc.bounds(); - // The largest surface by bytes: its scaled width, height and bytes per pixel (a mask has one +/// [`check_resample_budget`] for the largest surface [`resample_doc`] stores while scaling by +/// `sx` x `sy` with `filter` (masks, channels and the selection with Bilinear): each keeps its +/// pixels outside the canvas (a crop that didn't delete them, a layer moved off the canvas), and +/// those grow with the scale like the rest. A bicubic shrink also stores the image between its +/// two passes, one axis still at its old size ([`largest_resize_rect`]). +fn check_hidden_resample_budget(cmd: &str, doc: &mut Document, sx: f64, sy: f64, filter: Resample) -> Result<()> { + let new_canvas = scaled_rect(doc.bounds(), sx, sy); + // The largest surface by bytes: its width, height and bytes per pixel (a mask has one // channel, the layers the document's). let mut largest = (0u32, 0u32, 1u64); - let mut visit = |surf: &Surface| { - let r = surf.content_bounds(); - // What lies within the canvas scales to within the new canvas, already budgeted. - if r.is_empty() || canvas.union(&r) == canvas { + let mut visit = |surf: &Surface, filter: Resample| { + let r = largest_resize_rect(surf.content_bounds(), sx, sy, filter); + // What stays within the new canvas is already budgeted. + if r.is_empty() || new_canvas.union(&r) == new_canvas { return; } - // The output's extent, as `resize_surface_in_canvas` lays it out. - let side = |a: i32, b: i32, k: f64| ((f64::from(b) * k).ceil() - (f64::from(a) * k).floor()).clamp(0.0, f64::from(u32::MAX)) as u32; - let (w, h) = (side(r.x0, r.x1, sx), side(r.y0, r.y1, sy)); + let (w, h) = (r.width(), r.height()); let bpp = surf.format().bytes_per_pixel().max(1) as u64; let bytes = |(w, h, bpp): (u32, u32, u64)| u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bpp); if bytes((w, h, bpp)) > bytes(largest) { @@ -353,12 +353,12 @@ fn check_hidden_resample_budget(cmd: &str, doc: &mut Document, sx: f64, sy: f64) } }; // The surfaces `resample_doc` scales, smart object caches included. - for_each_surface(&mut doc.layers, true, &mut |surf, _| visit(surf)); + for_each_surface(&mut doc.layers, true, &mut |surf, is_mask| visit(surf, if is_mask { Resample::Bilinear } else { filter })); for ch in doc.channels.iter().chain(doc.quick_mask.as_ref()) { - visit(&ch.surface); + visit(&ch.surface, Resample::Bilinear); } if let Some(sel) = &doc.selection { - visit(sel); + visit(sel, Resample::Bilinear); } let (w, h, bpp) = largest; let px = u64::from(w).saturating_mul(u64::from(h)); diff --git a/crates/engine/src/cmd/image_cmds/tests.rs b/crates/engine/src/cmd/image_cmds/tests.rs index fe9af44182..19b12a5200 100644 --- a/crates/engine/src/cmd/image_cmds/tests.rs +++ b/crates/engine/src/cmd/image_cmds/tests.rs @@ -1008,3 +1008,21 @@ fn duplicate_document() { assert_eq!(doc(&s).layers.len(), 1); assert!(doc(&s).name.ends_with("copy")); } + +/// #9212: a bicubic shrink stores the image between its two passes with one axis at its old +/// size. A Background whose kept pixels reach (69999, 69999), halved from 200 to 100 px, ends at +/// about 35000 x 35000 px (4.9 GB, within the 8 GiB budget) but passes through about +/// 35000 x 70000 px (9.8 GB): refused before allocating. Bilinear has one pass and fits. The +/// check alone runs, so nothing that large is allocated either way. +#[cfg(target_pointer_width = "64")] +#[test] +fn hidden_resample_budget_counts_the_image_between_bicubic_passes() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + let mut d = doc(&s).clone(); + let bg = d.background_mut().unwrap().surface_mut().unwrap(); + bg.fill_rect(Rect::new(69_999, 69_999, 70_000, 70_000), &[1.0, 0.0, 0.0, 1.0]); + let err = check_hidden_resample_budget("image.imageSize", &mut d, 0.5, 0.5, Resample::Bicubic).unwrap_err().to_string(); + assert!(err.contains(" x 70000 px is "), "{err}"); + check_hidden_resample_budget("image.imageSize", &mut d, 0.5, 0.5, Resample::Bilinear).unwrap(); +} From 25782b0ca94f9ad9a36c9317dc918379e20bfb09 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 29 Oct 2026 18:25:17 +0100 Subject: [PATCH 40/44] Address CodeRabbit review: crop auto-scroll only for real crop drags - Crop: a new-frame drag still within 3 screen points of its press (a long press near the edge that slipped past it) doesn't scroll, so it can't grow a frame under a still pointer; Move and Resize still scroll. - Both crop tools scroll only while the canvas widget itself holds the press (not a scrollbar or panel with a stale crop drag) and the crop tool has the pointer (not a temporary Zoom held mid-drag). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 14 +- crates/ui-egui/src/tools/crop_ui.rs | 20 ++- crates/ui-egui/src/tools/crop_ui/tests.rs | 121 ++++++++++++++++++ .../ui-egui/src/tools/perspective_crop_ui.rs | 67 ++++++++++ 4 files changed, 213 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 0669106626..ffdf5d11bb 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1608,8 +1608,6 @@ struct CanvasTailInput<'a> { bars_id: egui::Id, layer_edges: egui::layers::ShapeIdx, camera: Option<([f32; 2], f32)>, - /// The pointer was pressed on this canvas (not on a panel over it). - pointer_here: bool, } fn finish_canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, input: &CanvasTailInput<'_>) { @@ -1629,16 +1627,19 @@ fn finish_canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut Vie let bars_id = input.bars_id; let layer_edges = input.layer_edges; let camera = input.camera; - let pointer_here = input.pointer_here; app.tool_override = None; if let Some(b) = layer_edges_rect(app, idx) { painter.set(layer_edges, egui::Shape::rect_stroke(xf.doc_rect(b), 0, Stroke::new(1.0, LAYER_EDGES), egui::StrokeKind::Outside)); } // A tool drag held past the canvas edge scrolls the view toward the pointer (#4183); the - // drag's next move then extends into what scrolled in. The crop tools keep their own drags, - // pressed on this canvas (not a panel slider held while a stale crop drag lingers). + // drag's next move then extends into what scrolled in. The crop tools keep their own drags: + // they scroll only while the press is the canvas's own (not a panel slider or a scrollbar held + // while a stale crop drag lingers) and the crop tool has it (not a temporary Zoom, which + // freezes the drag). + let crop_drag = + response.is_pointer_button_down_on() && tool == app.ui.tool && (crate::crop_ui::autoscrolls(app) || crate::perspective_crop_ui::dragging(app)); if primary - && (app.drag.is_some() || (pointer_here && (crate::crop_ui::autoscrolls(app) || crate::perspective_crop_ui::dragging(app)))) + && (app.drag.is_some() || crop_drag) && tool != Tool::Hand && !middle && let Some(p) = ui.input(|i| i.pointer.primary_down().then(|| i.pointer.latest_pos()).flatten()) @@ -2032,7 +2033,6 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: bars_id, layer_edges, camera, - pointer_here, }; finish_canvas_view(app, ui, &mut view, &tail); view diff --git a/crates/ui-egui/src/tools/crop_ui.rs b/crates/ui-egui/src/tools/crop_ui.rs index f9eeee5f7c..92f65104cc 100644 --- a/crates/ui-egui/src/tools/crop_ui.rs +++ b/crates/ui-egui/src/tools/crop_ui.rs @@ -421,9 +421,25 @@ pub fn active(app: &PhotocraftApp) -> bool { /// A drag that sizes or moves the frame over the image, which scrolls the view when held past the /// canvas edge (#4183). Not the turns, nor the default mode's image moves and live-centred resizes: -/// those drive the camera themselves. +/// those drive the camera themselves. A new frame's drag that hasn't left the size of a click (a +/// long press that slipped past the edge) doesn't either: scrolling would draw a frame under the +/// still pointer. pub fn autoscrolls(app: &PhotocraftApp) -> bool { - app.ui.tool == Tool::Crop && matches!(app.crop.drag, Some(CropDrag::Draw { .. } | CropDrag::Move { .. } | CropDrag::Resize { view: None, .. })) + app.ui.tool == Tool::Crop + && match app.crop.drag { + Some(CropDrag::Draw { anchor, cur, .. }) => !is_click(app, anchor, cur), + Some(CropDrag::Move { .. } | CropDrag::Resize { view: None, .. }) => true, + _ => false, + } +} + +/// A new-frame drag shorter than this (screen points) on both axes is still a click. +const CLICK_PX: f64 = 3.0; + +/// Document points `a` and `b` lie within [`CLICK_PX`] screen points of each other on both axes. +fn is_click(app: &PhotocraftApp, a: [f64; 2], b: [f64; 2]) -> bool { + let click = CLICK_PX / (app.point_zoom() as f64).max(0.01); + (b[0] - a[0]).abs() <= click && (b[1] - a[1]).abs() <= click } /// Cancel the pending crop: the frame, any gesture on it and the default-frame state. With the diff --git a/crates/ui-egui/src/tools/crop_ui/tests.rs b/crates/ui-egui/src/tools/crop_ui/tests.rs index 1069c3bd47..cf5391606c 100644 --- a/crates/ui-egui/src/tools/crop_ui/tests.rs +++ b/crates/ui-egui/src/tools/crop_ui/tests.rs @@ -588,6 +588,127 @@ fn a_press_beside_the_canvas_does_not_scroll_it_for_a_crop_drag() { h.step(); } +/// The 200x100 test document at 400% (document x 25..175 shows in a 600-point canvas). +fn zoomed_view(height: u32) -> crate::state::View { + crate::state::View { + zoom: 4.0, + center: [100.0, height as f32 / 2.0], + fit_pending: false, + fill_pending: false, + doc_size: [200, height], + rotation: 0.0, + zoom_animating: false, + zoom_anchor: None, + display_camera: None, + zoom_transition: None, + } +} + +/// A press held just inside the canvas edge (past egui's click time, so egui starts a drag) that +/// slips a point past it is still a click: it draws no frame and doesn't scroll the view, which +/// would grow a frame under the still pointer. A new frame dragged past the edge does scroll. +#[test] +fn a_held_click_at_the_canvas_edge_draws_no_frame_and_does_not_scroll() { + use egui::{Event, PointerButton, pos2}; + let mut a = app(SampleType::U8); + a.ui.views = vec![zoomed_view(100)]; + a.ui.extras.rulers = false; + // The canvas starts 100 points from the window's left, so its left edge (no scrollbar there) + // has room past it. + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let v = app.ui.views[0].clone(); + let rect = egui::Rect::from_min_size(egui::pos2(100.0, 0.0), egui::vec2(600.0, 400.0)); + crate::canvas::canvas_view(app, ui, 0, rect, v, true); + }, + a, + ); + h.run_steps(2); + let frame = h.state().ui.crop_rect; + assert!(h.state().crop.default_frame, "{frame:?}"); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let press = pos2(101.0, 200.0); + let slip = pos2(99.0, 200.0); + h.event(Event::PointerMoved(press)); + h.event(button(press, true)); + h.step(); + for p in [slip, pos2(98.5, 200.0), slip] { + h.event(Event::PointerMoved(p)); + h.run_steps(4); + } + assert!(matches!(h.state().crop.drag, Some(CropDrag::Draw { .. })), "egui started a drag: {:?}", h.state().crop.drag); + assert_eq!(h.state().ui.views[0].center, [100.0, 50.0], "a click doesn't scroll the view"); + h.event(button(slip, false)); + h.step(); + let st = h.state(); + assert_eq!(st.ui.crop_rect, frame, "the click drew no frame"); + assert!(st.crop.default_frame); + // A new frame dragged from inside the canvas past its edge does scroll. + let start = pos2(300.0, 200.0); + h.event(Event::PointerMoved(start)); + h.event(button(start, true)); + h.step(); + for p in [pos2(240.0, 220.0), pos2(50.0, 220.0)] { + h.event(Event::PointerMoved(p)); + h.step(); + } + let before = h.state().ui.views[0].center; + h.run_steps(10); + let st = h.state(); + assert!(matches!(st.crop.drag, Some(CropDrag::Draw { .. })), "{:?}", st.crop.drag); + assert!(st.ui.views[0].center[0] < before[0], "the frame drag scrolled left: {:?} -> {:?}", before, st.ui.views[0].center); + assert!(st.ui.crop_rect.is_some_and(|r| r[0] < 25.0), "the frame reached past what showed: {:?}", st.ui.crop_rect); + h.event(button(pos2(50.0, 220.0), false)); + h.step(); +} + +/// A scrollbar drag is the scrollbar's, even with a crop drag still recorded (left over from a +/// drag a tool switch didn't end): dragged out past the canvas edge, it doesn't auto-scroll the +/// view as a crop drag would. +#[test] +fn a_scrollbar_drag_past_the_canvas_edge_does_not_scroll_for_a_crop_drag() { + use egui::{Event, PointerButton, pos2}; + let doc = Document::with_background("crop", Size::new(200, 200), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut s = photocraft_engine::Session::new(); + s.add_document(doc, None); + let mut a = PhotocraftApp::new(s, crate::Services::default()); + a.ui.tool = Tool::Crop; + a.ui.tool_options.crop_shield.classic_mode = true; + a.ui.extras.snap = false; + a.ui.extras.rulers = false; + // 200x200 at 400% in a 600x400 canvas: both scrollbars show. + a.ui.views = vec![zoomed_view(200)]; + a.ui.crop_rect = Some([40.0, 10.0, 100.0, 40.0]); + a.crop.default_frame = false; + a.crop.drag = Some(CropDrag::Resize { hx: 1, hy: 0, start: [100.0, 25.0], rect: [40.0, 10.0, 100.0, 40.0], view: None }); + // The window is taller than the canvas, so the pointer can leave it below the bottom bar. + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 500.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let v = app.ui.views[0].clone(); + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + crate::canvas::canvas_view(app, ui, 0, rect, v, true); + }, + a, + ); + h.run_steps(2); + assert!(h.state().ui.view.shows_scrollbars()); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + // The horizontal bar's thumb (the view is centred, so is the thumb), dragged straight down + // out of the canvas: the bar keeps x, and nothing else may move the view. + let thumb = pos2(294.0, 400.0 - crate::canvas::scrollbars::THICKNESS / 2.0); + h.event(Event::PointerMoved(thumb)); + h.event(button(thumb, true)); + h.step(); + for p in [pos2(294.0, 420.0), pos2(294.0, 480.0)] { + h.event(Event::PointerMoved(p)); + h.step(); + } + h.run_steps(10); + assert_eq!(h.state().ui.views[0].center, [100.0, 100.0], "the view stayed put"); + h.event(button(pos2(294.0, 480.0), false)); + h.step(); +} + /// #1918: a pending crop belongs to the document it was drawn on. File › New, opening a file /// or switching tabs cancels it; it never shows on, or crops, another document. /// A turned pending frame is dropped with its angle when another document becomes active, and diff --git a/crates/ui-egui/src/tools/perspective_crop_ui.rs b/crates/ui-egui/src/tools/perspective_crop_ui.rs index d3c5488d04..ed60c90d41 100644 --- a/crates/ui-egui/src/tools/perspective_crop_ui.rs +++ b/crates/ui-egui/src/tools/perspective_crop_ui.rs @@ -401,6 +401,73 @@ mod tests { h.step(); } + /// ⌘Space (Ctrl+Space off the Mac) pressed during a corner drag held past the canvas edge + /// selects the temporary Zoom, which takes the pointer from the drag: the view no longer + /// scrolls for the corner the Zoom froze. + #[test] + fn a_temporary_zoom_during_a_corner_drag_stops_the_scrolling() { + use egui::{Event, Key, Modifiers, PointerButton, pos2}; + let doc = Document::with_background("p", Size::new(800, 100), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut s = photocraft_engine::Session::new(); + s.add_document(doc, None); + let mut a = PhotocraftApp::new(s, crate::Services::default()); + a.ui.tool = Tool::PerspectiveCrop; + a.ui.extras.snap = false; + a.ui.extras.rulers = false; + // 800x100 at 400% in a 600x400 canvas: document x 25..175 shows, with room to scroll right. + a.ui.views = vec![crate::state::View { + zoom: 4.0, + center: [100.0, 50.0], + fit_pending: false, + fill_pending: false, + doc_size: [800, 100], + rotation: 0.0, + zoom_animating: false, + zoom_anchor: None, + display_camera: None, + zoom_transition: None, + }]; + a.ui.perspective_crop = Some([[40.0, 10.0], [100.0, 10.0], [100.0, 40.0], [40.0, 40.0]]); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let v = app.ui.views[0].clone(); + crate::canvas::canvas_view(app, ui, 0, ui.max_rect(), v, true); + }, + a, + ); + h.run_steps(2); + let button = |pos, pressed, modifiers| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers }; + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + let xf = crate::canvas::ViewXform { rect, zoom: 4.0, center: [100.0, 50.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let grab = xf.to_screen(100.0, 10.0); + h.event(Event::PointerMoved(grab)); + h.event(button(grab, true, Modifiers::NONE)); + h.step(); + let out = pos2(650.0, grab.y); + for p in [pos2(grab.x + 40.0, grab.y), out] { + h.event(Event::PointerMoved(p)); + h.step(); + } + // Scrolling while the crop tool has the pointer. + let before = h.state().ui.views[0].center; + h.run_steps(2); + assert!(h.state().ui.views[0].center[0] > before[0], "the corner drag scrolls: {:?} -> {:?}", before, h.state().ui.views[0].center); + let zoom = Modifiers::COMMAND; + let zoom = if cfg!(target_os = "macos") { Modifiers { mac_cmd: true, ..zoom } } else { Modifiers { ctrl: true, ..zoom } }; + h.event(Event::ModifiersChanged(zoom)); + h.event(Event::Key { key: Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: zoom }); + h.step(); + assert_eq!(crate::hold_keys::held_tool(h.state(), &h.ctx), Some(crate::hold_keys::Temporary::ZoomIn)); + assert!(h.state().pcrop.drag.is_some(), "the corner drag is still recorded"); + let before = h.state().ui.views[0].center; + h.run_steps(10); + assert_eq!(h.state().ui.views[0].center, before, "the temporary Zoom's press doesn't scroll for the corner"); + h.event(button(out, false, zoom)); + h.event(Event::Key { key: Key::Space, physical_key: None, pressed: false, repeat: false, modifiers: zoom }); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.step(); + } + /// A corner-placing click pressed just inside the canvas edge that slips a point past it doesn't /// scroll the view (scrolling would turn it into a box); a new box dragged past the edge does. #[test] From 79fee531168dce1c02161acdc0cefb2dd133ad06 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 2 Nov 2026 19:05:38 +0100 Subject: [PATCH 41/44] Address CodeRabbit review: the hidden-pixel resample refusal suggests Delete Cropped Pixels only when it would help Delete Cropped Pixels clips pixel layers, fill caches and video frames only. When a layer mask, channel, the quick mask, the selection, type, a shape or a smart object holds the hidden pixels over the budget, the refusal now says so instead of pointing to an option that can't clear it. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/image_cmds.rs | 54 ++++++++++++++++------- crates/engine/src/cmd/image_cmds/tests.rs | 23 ++++++++++ 2 files changed, 62 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index df27a24ae3..76880145cf 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -1,6 +1,7 @@ //! Image menu: Image Size, Canvas Size, Crop, Trim, Mode (colour model and //! bit depth) conversions, Duplicate. +use std::collections::HashSet; use std::convert::Infallible; use photocraft_algo::resample::{Resample, crop_surface, largest_resize_rect, resize_surface_in_canvas, scaled_rect, translate_surface}; @@ -333,23 +334,39 @@ pub(crate) fn resample_doc(doc: &mut Document, cmd: &str, nw: u32, nh: u32, filt /// `sx` x `sy` with `filter` (masks, channels and the selection with Bilinear): each keeps its /// pixels outside the canvas (a crop that didn't delete them, a layer moved off the canvas), and /// those grow with the scale like the rest. A bicubic shrink also stores the image between its -/// two passes, one axis still at its old size ([`largest_resize_rect`]). +/// two passes, one axis still at its old size ([`largest_resize_rect`]). The refusal suggests +/// Delete Cropped Pixels only when the surfaces over the budget are all ones it clips +/// ([`delete_cropped_pixels`]). fn check_hidden_resample_budget(cmd: &str, doc: &mut Document, sx: f64, sy: f64, filter: Resample) -> Result<()> { let new_canvas = scaled_rect(doc.bounds(), sx, sy); - // The largest surface by bytes: its width, height and bytes per pixel (a mask has one - // channel, the layers the document's). - let mut largest = (0u32, 0u32, 1u64); + // The surfaces Delete Cropped Pixels clips; masks, channels, the selection, type, shapes and + // smart objects keep their pixels outside the crop. + let mut clipped: HashSet<*const Surface> = HashSet::new(); + for_each_layer(&mut doc.layers, &mut |l| { + clipped.extend(l.fill_cache.as_ref().map(|fc| std::ptr::from_ref(&fc.surface))); + if let Some(v) = &l.video { + clipped.extend(v.frames.iter().chain(v.original_frames.iter().flatten()).map(std::ptr::from_ref)); + } + if let LayerContent::Raster(s) = &l.content { + clipped.insert(std::ptr::from_ref(s)); + } + }); + let bytes = |(w, h, bpp): (u32, u32, u64)| u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bpp); + // The largest surface by bytes, and the largest one Delete Cropped Pixels doesn't clip: its + // width, height and bytes per pixel (a mask has one channel, the layers the document's). + let (mut largest, mut largest_kept) = ((0u32, 0u32, 1u64), (0u32, 0u32, 1u64)); let mut visit = |surf: &Surface, filter: Resample| { let r = largest_resize_rect(surf.content_bounds(), sx, sy, filter); // What stays within the new canvas is already budgeted. if r.is_empty() || new_canvas.union(&r) == new_canvas { return; } - let (w, h) = (r.width(), r.height()); - let bpp = surf.format().bytes_per_pixel().max(1) as u64; - let bytes = |(w, h, bpp): (u32, u32, u64)| u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bpp); - if bytes((w, h, bpp)) > bytes(largest) { - largest = (w, h, bpp); + let this = (r.width(), r.height(), surf.format().bytes_per_pixel().max(1) as u64); + if bytes(this) > bytes(largest) { + largest = this; + } + if !clipped.contains(&std::ptr::from_ref(surf)) && bytes(this) > bytes(largest_kept) { + largest_kept = this; } }; // The surfaces `resample_doc` scales, smart object caches included. @@ -360,17 +377,24 @@ fn check_hidden_resample_budget(cmd: &str, doc: &mut Document, sx: f64, sy: f64, if let Some(sel) = &doc.selection { visit(sel, Resample::Bilinear); } - let (w, h, bpp) = largest; - let px = u64::from(w).saturating_mul(u64::from(h)); - if px.saturating_mul(bpp) <= MAX_RESAMPLE_BYTES { + let (kept, (w, h, bpp)) = if bytes(largest_kept) > MAX_RESAMPLE_BYTES { + (true, largest_kept) + } else if bytes(largest) > MAX_RESAMPLE_BYTES { + (false, largest) + } else { return Ok(()); - } + }; + let hint = if kept { + "choose a smaller size (layer masks, channels, the quick mask, the selection, type, shapes and smart objects keep theirs through Crop with Delete Cropped Pixels)" + } else { + "choose a smaller size, or delete them first (Crop with Delete Cropped Pixels)" + }; let max_mp = MAX_RESAMPLE_BYTES / bpp / 1_000_000; Err(bad( cmd, format!( - "{w} x {h} px is {} megapixels; resampling at this bit depth is limited to {max_mp} megapixels. The pixels outside the canvas are resampled too: choose a smaller size, or delete them first (Crop with Delete Cropped Pixels)", - px / 1_000_000 + "{w} x {h} px is {} megapixels; resampling at this bit depth is limited to {max_mp} megapixels. The pixels outside the canvas are resampled too: {hint}", + u64::from(w).saturating_mul(u64::from(h)) / 1_000_000 ), )) } diff --git a/crates/engine/src/cmd/image_cmds/tests.rs b/crates/engine/src/cmd/image_cmds/tests.rs index ef12a7bdf1..fc34b29244 100644 --- a/crates/engine/src/cmd/image_cmds/tests.rs +++ b/crates/engine/src/cmd/image_cmds/tests.rs @@ -855,12 +855,35 @@ fn image_size_budgets_the_hidden_pixels_it_resamples() { let past = s.active().unwrap().history.past_len(); let err = s.execute("image.imageSize", json!({"width": 20000, "height": 20000})).unwrap_err().to_string(); assert!(err.contains("200000 x 200000 px is 40000 megapixels"), "{err}"); + // The hidden pixels are a pixel layer's: Delete Cropped Pixels would clear them. + assert!(err.contains("or delete them first (Crop with Delete Cropped Pixels)"), "{err}"); assert_eq!((doc(&s).size, s.active().unwrap().history.past_len()), (Size::new(10, 10), past)); // Without resampling only the resolution changes. s.execute("image.imageSize", json!({"resolution": 300, "resample": "none"})).unwrap(); assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(10, 10), 300.0)); } +/// Delete Cropped Pixels clips pixel layers only: an alpha channel keeps its pixels outside the +/// crop, so the refusal doesn't send the user to an option that can't clear it. +#[test] +fn hidden_resample_budget_names_what_delete_cropped_pixels_keeps() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + s.edit("channel", |doc, _| { + let fmt = photocraft_color::PixelFormat::new(ColorMode::Grayscale, doc.pixel_format().sample, false); + let mut ch = Surface::new(fmt); + ch.write_region(Rect::new(0, 0, 100, 100), &[1.0; 100 * 100]); + doc.channels.push(photocraft_doc::AlphaChannel::new("Alpha 1", ch)); + Ok(()) + }) + .unwrap(); + s.execute("image.crop", json!({"x": 0, "y": 0, "width": 10, "height": 10, "deleteCroppedPixels": true})).unwrap(); + let err = s.execute("image.imageSize", json!({"width": 20000, "height": 20000})).unwrap_err().to_string(); + assert!(err.contains("200000 x 200000 px is 40000 megapixels"), "{err}"); + assert!(err.contains("channels") && !err.contains("delete them first"), "{err}"); + assert_eq!(doc(&s).size, Size::new(10, 10)); +} + #[test] fn crop_target_rejects_bad_params_without_changing_the_document() { let rect = json!({"x": 0, "y": 0, "width": 10, "height": 10}); From 7d903ba8fb4e8a92f8f65ff538b4c2eac9806dbc Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 5 Nov 2026 12:26:31 +0100 Subject: [PATCH 42/44] svg: pass the cache limits main added to import_parsed in the fallback test Co-Authored-By: Claude Opus 5.5 --- crates/io/src/svg/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index 3d84285c62..0a59cc661d 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -476,7 +476,7 @@ fn the_fallback_search_reads_each_font_file_once() { // Inter has no box-drawing characters; JetBrains Mono has. let svg = "I\u{2500}I"; let outlines = |parsed: Parsed| { - let layers = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap().document.layers; + let layers = import_parsed("t", parsed, MAX_GROUP_DEPTH, None, false).unwrap().document.layers; let groups = layers.into_iter().filter_map(|l| if let LayerContent::Group(g) = l.content { Some(g) } else { None }); groups.flat_map(|g| g.children).filter_map(|l| if let LayerContent::Shape(s) = l.content { Some(s.path) } else { None }).collect::>() }; From 5b1b6cf13d88edef9ee9b26fb9f3fd8f14c03a01 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 6 Nov 2026 01:49:40 +0100 Subject: [PATCH 43/44] Merge fix-up: check entity markup in main's bounded embedded-SVG parse too nesting_depth now returns a Result; main's parse_image_bounded_with gets the same entity-markup rejection as the other callers. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/svg.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 372e933e6e..1127971e11 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -627,7 +627,7 @@ fn parse_image_bounded_with( if left.is_none() { return Err(overrun(IoError::Svg("embedded SVG XML exceeds the decoded byte budget".into()))); } - let nesting = nesting_depth(&xml, xml_left); + let nesting = nesting_depth(&xml, xml_left)?; if nesting > xml_left { return Err(IoError::Svg(format!("elements are nested more than {xml_left} levels deep"))); } From 88704d23501f92492f8d19bb8503b31da8d32495 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 6 Nov 2026 02:06:41 +0100 Subject: [PATCH 44/44] Merge fix-up: the turned crop's hidden pixels after Layer 0 replaces the Background Since #10867 the non-deleting crop turns a 2000 px layer to 2001 px bounds, so the budget refusal names 200100 x 200100 px. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/image_cmds/tests.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/image_cmds/tests.rs b/crates/engine/src/cmd/image_cmds/tests.rs index 66878c6d46..c7e3189254 100644 --- a/crates/engine/src/cmd/image_cmds/tests.rs +++ b/crates/engine/src/cmd/image_cmds/tests.rs @@ -843,7 +843,10 @@ fn crop_target_budgets_the_hidden_pixels_it_resamples() { p["angle"] = json!(a); } let err = s.execute("image.crop", p).unwrap_err().to_string(); - assert!(err.contains("200000 x 200000 px is 40000 megapixels"), "{angle:?}: {err}"); + // Since the crop turns the Background into Layer 0 (#10867), the turned layer's + // bounds are 2001 px a side, resampled x100 to 200100. + let want = if angle.is_some() { "200100 x 200100 px is 40040 megapixels" } else { "200000 x 200000 px is 40000 megapixels" }; + assert!(err.contains(want) && err.contains("Delete Cropped Pixels"), "{angle:?}: {err}"); assert_eq!(doc(&s).size, Size::new(2000, 2000), "{angle:?}: the document is unchanged"); assert_eq!(s.active().unwrap().history.past_len(), past, "{angle:?}: no history step"); // The turned crop rotates first: the painting symmetry turns back with the document.