diff --git a/crates/algo/src/resample.rs b/crates/algo/src/resample.rs index 15a2eb72aa..a0c363732a 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 { resize_controlled(s, sx, sy, filter, canvas, budget, &photocraft_raster::Interrupt::NONE) } diff --git a/crates/algo/src/resample/tests.rs b/crates/algo/src/resample/tests.rs index 3c80881675..2407457a2d 100644 --- a/crates/algo/src/resample/tests.rs +++ b/crates/algo/src/resample/tests.rs @@ -401,6 +401,25 @@ 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"); + } +} + #[test] fn controlled_resize_matches_pixels_and_discards_cancelled_work() { for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 9c3e7f9fbc..f6e3fd4a12 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -424,6 +424,8 @@ impl Headless { if let Some(st) = this.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 this.session); Ok(()) })?; } 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 a21c38f06a..6d6700dc91 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -46,6 +46,9 @@ semver = "1" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] tempfile = "3" +# `clock`: 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 = { workspace = true, features = ["clock"] } # `file_cmds::same_file` on Windows: the volume serial number and file index, so a hard link to a # file is that file (std's `MetadataExt::file_index` is unstable). diff --git a/crates/engine/src/cmd/analysis_cmds.rs b/crates/engine/src/cmd/analysis_cmds.rs index 4608186f01..0bf2a335ad 100644 --- a/crates/engine/src/cmd/analysis_cmds.rs +++ b/crates/engine/src/cmd/analysis_cmds.rs @@ -188,6 +188,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); @@ -212,6 +214,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/cmd/history_options_cmds.rs b/crates/engine/src/cmd/history_options_cmds.rs index 17341b5ae1..c2f814d008 100644 --- a/crates/engine/src/cmd/history_options_cmds.rs +++ b/crates/engine/src/cmd/history_options_cmds.rs @@ -1,35 +1,113 @@ -//! 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) come with #3634, which -//! makes the snapshots act on them. +//! 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, 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) +} + +/// 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 +117,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 +126,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; } } }); @@ -120,7 +197,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, @@ -148,10 +225,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(); @@ -177,6 +265,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), @@ -185,6 +278,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); } @@ -358,6 +453,139 @@ mod tests { 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); + } + + /// 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(); + 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)); + } + + /// 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/engine/src/cmd/history_source_cmds.rs b/crates/engine/src/cmd/history_source_cmds.rs index c4c0f5e225..c42b69b3d8 100644 --- a/crates/engine/src/cmd/history_source_cmds.rs +++ b/crates/engine/src/cmd/history_source_cmds.rs @@ -366,6 +366,7 @@ mod tests { json!({"state": 1.5}), json!({"state": "1"}), json!({"state": [1]}), + json!({"snapshot": 99}), json!({"snapshot": 1}), json!({"snapshot": -1}), json!({"snapshot": "Open"}), @@ -375,7 +376,7 @@ mod tests { assert!(s.execute(CMD, p.clone()).is_err(), "{p}"); } assert_eq!(s.active().unwrap().history.brush_source(), Some(0), "nothing changed"); - // Snapshot 0 is the document as opened, so it is a valid source. + // Snapshot 0 is the document as opened (Automatically Create First Snapshot), so it is a valid source. assert_eq!(s.execute(CMD, json!({"snapshot": 0})).unwrap()["snapshot"], 0); } } diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index 6de4bf6f70..ffe55a995c 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -1,9 +1,10 @@ //! 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, 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; @@ -11,6 +12,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> { @@ -235,15 +237,27 @@ 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). The document's own + // resolution always passes: an imported file may have one outside the range, and the dialog + // 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 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) = p.get("resolution").and_then(Value::as_f64) + && let Some(r) = dpi + && r != own_dpi { - let r = r.clamp(1.0, 10_000.0); - 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); } @@ -260,7 +274,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); let scale_styles = p.get("scaleStyles").and_then(Value::as_bool).unwrap_or(true); if !matches!(resample, Method::None) && (nw, nh) != (ow, oh) { // Before the sampler map or the document change: a resize that doesn't fit would trap on the web (#10024). @@ -272,7 +285,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(()), @@ -280,8 +293,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_with_styles(doc, nw, nh, filter, scale_styles); - Ok(()) + resample_doc_with_styles(doc, "image.imageSize", nw, nh, filter, scale_styles) })?; // The size the document has now: without resampling `width`/`height` are ignored (#1815). let size = s.active().ok_or(EngineError::NoDocument)?.doc.size; @@ -316,18 +328,20 @@ 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) { - resample_doc_with_styles(doc, nw, nh, filter, true); +/// 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<()> { + resample_doc_with_styles(doc, cmd, nw, nh, filter, true) } /// Resize document content while optionally retaining layer-effect sizes in pixels. -fn resample_doc_with_styles(doc: &mut Document, nw: u32, nh: u32, filter: Resample, scale_styles: bool) { +fn resample_doc_with_styles(doc: &mut Document, cmd: &str, nw: u32, nh: u32, filter: Resample, scale_styles: bool) -> 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, 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); @@ -358,6 +372,76 @@ fn resample_doc_with_styles(doc: &mut Document, nw: u32, nh: u32, filter: Resamp 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`] 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`]). 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 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 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. + 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, Resample::Bilinear); + } + if let Some(sel) = &doc.selection { + visit(sel, Resample::Bilinear); + } + 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: {hint}", + u64::from(w).saturating_mul(u64::from(h)) / 1_000_000 + ), + )) } fn bad(cmd: &str, msg: impl Into) -> EngineError { @@ -728,8 +812,7 @@ fn crop_with(s: &mut Session, p: &Value, keep_background: bool) -> 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() }))) } @@ -744,15 +827,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 @@ -937,8 +1021,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 }))) diff --git a/crates/engine/src/cmd/image_cmds/tests.rs b/crates/engine/src/cmd/image_cmds/tests.rs index fc4ce0bcf9..96e0637994 100644 --- a/crates/engine/src/cmd/image_cmds/tests.rs +++ b/crates/engine/src/cmd/image_cmds/tests.rs @@ -234,6 +234,48 @@ fn resolution_only_change() { 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"); + // 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"); + // 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"); + } +} + /// 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] @@ -825,6 +867,79 @@ fn crop_target_accepts_whole_number_floats() { 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(); + // 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. + 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}"); + // 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}); @@ -973,6 +1088,24 @@ fn duplicate_document() { 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(); +} + #[test] fn trim_and_duplicate_merged_on_too_large_document_fail_gracefully_without_panic() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index 3043f080e6..ea6504f7a8 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -566,7 +566,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 w = doc.size.width as usize; diff --git a/crates/engine/src/cmd/mode_cmds/tests.rs b/crates/engine/src/cmd/mode_cmds/tests.rs index 4d3c97b02b..8f190f445c 100644 --- a/crates/engine/src/cmd/mode_cmds/tests.rs +++ b/crates/engine/src/cmd/mode_cmds/tests.rs @@ -452,6 +452,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 diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index e10f5be984..06123cbab1 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -48,11 +48,15 @@ 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. pub(crate) 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. + pub(crate) save_snapshot: Option, /// The snapshot set as the History Brush's source (`history.setSource {snapshot}`); `None`: /// the source is a state, kept by the history ([`photocraft_ops::History::brush_source`]). pub(crate) source_snapshot: Option, @@ -114,6 +118,7 @@ impl DocState { color_samplers: Vec::new(), snapshots: vec![first], next_snapshot: 1, + save_snapshot: None, source_snapshot: None, typed_names: Default::default(), } diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 096989606f..b18991b666 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -1125,21 +1125,36 @@ impl Actions { } } -/// The History panel's History Options… (not part of Edit › Preferences in Photoshop either). -/// Photoshop's snapshot options come with #3634. +/// 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/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 3e6bc4abc7..7cef2be12e 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -142,6 +142,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_cap_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/tests/it/svg_smart_object.rs b/crates/engine/tests/it/svg_smart_object.rs index c32041581f..1016aac628 100644 --- a/crates/engine/tests/it/svg_smart_object.rs +++ b/crates/engine/tests/it/svg_smart_object.rs @@ -63,6 +63,35 @@ fn re_placing_at_another_scale_re_renders_the_vector_source() { 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(); +} + /// Placed through a background job, an SVG is rendered at its placement scale on the worker and /// lands exactly as the inline place does: still sharp, not a resampled raster. #[test] diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index ba4c368c5d..dcd86482db 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -49,6 +49,8 @@ imagesize = "0.13" # 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 2d33f69fb1..ba8900fb87 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -281,15 +281,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")] @@ -329,7 +392,7 @@ fn options(fontdb: Arc, depth_left: usize) -> usvg::Opti Ok(std::borrow::Cow::Owned(xml)) if !xml.starts_with(&[0x1f, 0x8b]) => ("image/svg+xml", Arc::new(xml)), _ => return None, }; - if nesting_depth(&xml, depth_left) > depth_left { + if !nesting_depth(&xml, depth_left).is_ok_and(|depth| depth <= depth_left) { return None; } return default_resolver(mime, xml, opts); @@ -366,7 +429,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)?; - let depth = nesting_depth(&xml, MAX_XML_DEPTH); + let depth = nesting_depth(&xml, MAX_XML_DEPTH)?; if depth > MAX_XML_DEPTH { return Err(IoError::Svg(format!("elements are nested more than {MAX_XML_DEPTH} levels deep"))); } @@ -627,7 +690,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"))); } @@ -806,8 +869,10 @@ fn inflate_with_limit(bytes: &[u8], limit: u64) -> Result` or `/>`. Malformed markup is only counted -/// loosely: the parser rejects it afterwards. -pub(crate) 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. +pub(crate) 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())) }; @@ -829,6 +894,44 @@ pub(crate) 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"`, 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 { + j.saturating_add(1) + }; + } + Ok(xml.len()) + }; let (mut depth, mut deepest, mut i) = (0usize, 0usize, 0usize); while let Some(p) = xml.get(i..).and_then(|s| s.iter().position(|&b| b == b'<')) { let at = i.saturating_add(p); @@ -839,6 +942,8 @@ pub(crate) fn nesting_depth(xml: &[u8], limit: usize) -> 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/src/svg/tests.rs b/crates/io/src/svg/tests.rs index e1d2a1a890..15b6379359 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -487,6 +487,79 @@ fn imports_missing_the_same_font_at_once_share_one_read() { } } +/// #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, 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::>() + }; + 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"))] diff --git a/crates/io/src/xml.rs b/crates/io/src/xml.rs index 13e02004d1..423c8c8555 100644 --- a/crates/io/src/xml.rs +++ b/crates/io/src/xml.rs @@ -15,7 +15,7 @@ pub fn parse<'i>(text: &'i str, opts: ParsingOptions<'i>) -> Result if opts.allow_dtd && internal_subset(text.as_bytes()) { return Err("internal DTD subsets aren't supported".into()); } - if crate::svg::nesting_depth(text.as_bytes(), MAX_DEPTH) > MAX_DEPTH { + if crate::svg::nesting_depth(text.as_bytes(), MAX_DEPTH).map_err(|e| e.to_string())? > MAX_DEPTH { return Err(format!("elements are nested more than {MAX_DEPTH} levels deep")); } Document::parse_with_options(text, opts).map_err(|e| e.to_string()) diff --git a/crates/io/tests/it/svg.rs b/crates/io/tests/it/svg.rs index 0cd3c832b3..3f0ba53462 100644 --- a/crates/io/tests/it/svg.rs +++ b/crates/io/tests/it/svg.rs @@ -411,6 +411,53 @@ 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 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() { + 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("", "")))), + ("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) + .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] diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index e106a2ecfb..26ac96f722 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -637,6 +637,8 @@ impl PhotocraftApp { // The job locked the document, but record the revision that was written. st.saved_revision = revision; app.remember_stamp(doc, path); + // 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 && let Some(r) = photocraft_engine::automate_cmds::document_saved(&mut app.session, doc) { 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..4b5bb069a0 --- /dev/null +++ b/crates/ui-egui/src/blend_dropdown_groups_tests.rs @@ -0,0 +1,101 @@ +//! #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 at 1440×900 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 +} + +/// The Layers panel's dropdown: the lowest one (the options bar and the title bar have some too). +fn dropdown(h: &Harness<'_, PhotocraftApp>) -> Rect { + h.query_all_by_role(Role::ComboBox).map(|n| n.rect()).max_by(|a, b| a.top().total_cmp(&b.top())).unwrap() +} + +/// 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))) +} + +fn blend(h: &Harness<'_, PhotocraftApp>) -> BlendMode { + let st = h.state().session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().blend +} + +fn steps(h: &Harness<'_, PhotocraftApp>) -> usize { + h.state().session.active().unwrap().history.past_len() +} + +/// Presses at `at`, holds for `held` frames and releases there. +fn click(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, held: usize) { + 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); + } +} + +#[test] +fn the_layers_blend_mode_list_has_a_line_between_each_group() { + let mut h = harness(); + let at = dropdown(&h).center(); + click(&mut h, at, 1); + assert!(open_list(&h).is_some(), "the list is open"); + // Each mode's row in the open list: its label's last node (the box shows the chosen one's + // first). Rows scrolled out of the list keep their place in it, so the gaps hold for all. + let rows: Vec = BlendMode::LAYER_MODES + .iter() + .map(|m| h.get_all_by_label(m.label()).map(|n| n.rect()).next_back().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:?}" + ); +} + +/// A plain click on the Layers panel's Blend Mode box at 1440×900, 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: the list doesn't open over the box, where the release would pick a row +/// (#5495 review of a taller list). +#[test] +fn a_click_on_the_blend_mode_box_opens_the_list_and_changes_nothing() { + for held in [6, 1] { + let mut h = harness(); + let undo = steps(&h); + let button = dropdown(&h); + click(&mut h, button.center(), held); + 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/brush_mode_menu.rs b/crates/ui-egui/src/brush_mode_menu.rs index 3523267b10..431ad7aea2 100644 --- a/crates/ui-egui/src/brush_mode_menu.rs +++ b/crates/ui-egui/src/brush_mode_menu.rs @@ -72,7 +72,7 @@ pub(crate) fn choices() -> Vec<((Option, bool), &'static str)> { fn blend_items(behind: bool, clear: bool) -> Vec { let mut out = Vec::new(); for m in BlendMode::LAYER_MODES { - if matches!(m, BlendMode::Darken | BlendMode::Lighten | BlendMode::Overlay | BlendMode::Difference | BlendMode::Hue) { + if crate::panels::starts_blend_group(m) { out.push(Item::Separator); } out.push(Item::Blend(m)); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 3cdd87d26b..ae4f7a45e0 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1699,9 +1699,14 @@ fn finish_canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut Vie 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: + // 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() + && (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()) @@ -1962,6 +1967,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(pen) = app.ui.pen.as_mut().filter(|pen| pen.dragging && !pen.curvature) { diff --git a/crates/ui-egui/src/canvas/snap_ui.rs b/crates/ui-egui/src/canvas/snap_ui.rs index 9184abe989..84b4f785dc 100644 --- a/crates/ui-egui/src/canvas/snap_ui.rs +++ b/crates/ui-egui/src/canvas/snap_ui.rs @@ -202,6 +202,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 { use crate::transform_tool::Hit; let h = crate::transform_tool::box_hit(app, t, p, crate::transform_tool::handle_tolerance(app)); @@ -231,6 +232,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) = @@ -297,7 +303,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`, @@ -524,6 +533,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 { @@ -564,6 +585,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() { diff --git a/crates/ui-egui/src/canvas/snap_ui/tests.rs b/crates/ui-egui/src/canvas/snap_ui/tests.rs index 17ba7ca349..b42264a188 100644 --- a/crates/ui-egui/src/canvas/snap_ui/tests.rs +++ b/crates/ui-egui/src/canvas/snap_ui/tests.rs @@ -93,6 +93,77 @@ fn drawing_a_new_crop_snaps_its_corner_not_the_default_frame() { } } +/// 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}"); + } +} + +/// 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(); diff --git a/crates/ui-egui/src/canvas/tool_input.rs b/crates/ui-egui/src/canvas/tool_input.rs index 6db5aace3e..0b47c8447f 100644 --- a/crates/ui-egui/src/canvas/tool_input.rs +++ b/crates/ui-egui/src/canvas/tool_input.rs @@ -61,6 +61,12 @@ fn preflight_tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modi { 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. 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 { + crate::crop_ui::end_drag(app); + } if crate::symmetry_ui::pointer(app, ev, crate::workspace_ui::sticky_mods(app, mods)) { return None; } diff --git a/crates/ui-egui/src/dialogs/history_options_ui.rs b/crates/ui-egui/src/dialogs/history_options_ui.rs index 2d4756543b..0ff35dbc0e 100644 --- a/crates/ui-egui/src/dialogs/history_options_ui.rs +++ b/crates/ui-egui/src/dialogs/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/dialogs/sizing/tests.rs b/crates/ui-egui/src/dialogs/sizing/tests.rs index a7e7c1dd20..7c26de6c81 100644 --- a/crates/ui-egui/src/dialogs/sizing/tests.rs +++ b/crates/ui-egui/src/dialogs/sizing/tests.rs @@ -50,6 +50,30 @@ fn dialog_maps_to_engine_command() { 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()); diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 05a8e9fca1..6ae23fc2ef 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3910,6 +3910,9 @@ navigator Zoom Zvětšení Sent to {printer} Odesláno do {printer} set in Print Settings… nastavuje se v nastavení tisku… ICO is limited to 256 × 256 pixels ICO je omezen na 256 × 256 pixelů + 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 Memory usage percent Využití paměti (%) Show Favorite Fonts Zobrazit oblíbená písma No favorite fonts yet: click the star beside a font to add it. Zatím žádná oblíbená písma: přidejte písmo kliknutím na hvězdičku vedle něj. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4fc25594e5..259a20a503 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3309,6 +3309,9 @@ curves Smooth Glätten Sent to {printer} An {printer} gesendet set in Print Settings… in den Druckeinstellungen festlegen… ICO is limited to 256 × 256 pixels ICO ist auf 256 × 256 Pixel begrenzt + 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 Memory usage percent Speichernutzung (%) Show Favorite Fonts Favorisierte Schriften anzeigen No favorite fonts yet: click the star beside a font to add it. Noch keine favorisierten Schriften: Klicken Sie auf den Stern neben einer Schrift, um sie hinzuzufügen. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index c6ba89568d..d4979e6386 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3499,6 +3499,9 @@ curves Smooth 매끄럽게 Sent to {printer} {printer}(으)로 전송됨 set in Print Settings… 인쇄 설정에서 지정… ICO is limited to 256 × 256 pixels ICO는 256 × 256픽셀로 제한됩니다 + Automatically Create First Snapshot 첫 번째 스냅샷 자동 만들기 + Automatically Create New Snapshot When Saving 저장할 때 새 스냅샷 자동 만들기 + Show New Snapshot Dialog by Default 기본적으로 새 스냅샷 대화 상자 표시 Memory usage percent 메모리 사용 비율(%) Show Favorite Fonts 즐겨찾는 글꼴 표시 No favorite fonts yet: click the star beside a font to add it. 아직 즐겨찾는 글꼴이 없습니다. 글꼴 옆의 별을 클릭하여 추가하세요. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 965da7e9e9..53b9fc161d 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3761,6 +3761,10 @@ curves Smooth Làm mượt Sent to {printer} Đã gửi tới {printer} 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) + 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 Memory usage percent Tỷ lệ sử dụng bộ nhớ Show Favorite Fonts Hiển thị phông chữ yêu thích No favorite fonts yet: click the star beside a font to add it. Chưa có phông chữ yêu thích: nhấp vào ngôi sao bên cạnh phông chữ để thêm. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index eb5c42b602..f8a764bd76 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2950,6 +2950,9 @@ curves Smooth 平滑 Sent to {printer} 已发送到 {printer} set in Print Settings… 在打印设置中设置… ICO is limited to 256 × 256 pixels ICO 最大为 256 × 256 像素 + Automatically Create First Snapshot 自动创建第一幅快照 + Automatically Create New Snapshot When Saving 存储时自动创建新快照 + Show New Snapshot Dialog by Default 默认显示新建快照对话框 Memory usage percent 内存使用比例 (%) Show Favorite Fonts 显示收藏的字体 No favorite fonts yet: click the star beside a font to add it. 还没有收藏的字体:点击字体旁边的星标即可添加。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 981284b482..87061727c7 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2911,6 +2911,9 @@ curves Smooth 平滑 Sent to {printer} 已傳送至 {printer} set in Print Settings… 在列印設定中設定… ICO is limited to 256 × 256 pixels ICO 最大為 256 × 256 像素 + Automatically Create First Snapshot 自動建立第一個快照 + Automatically Create New Snapshot When Saving 儲存時自動建立新快照 + Show New Snapshot Dialog by Default 預設顯示新增快照對話框 Memory usage percent 記憶體使用比例 (%) Show Favorite Fonts 顯示我的最愛字體 No favorite fonts yet: click the star beside a font to add it. 尚無我的最愛字體:按一下字體旁的星號即可加入。 diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 26dfa5e96f..8cf978e36c 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -820,8 +820,12 @@ fn handle_registry_and_tool_keys(app: &mut PhotocraftApp, ctx: &egui::Context, f return true; } // 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/lib.rs b/crates/ui-egui/src/lib.rs index 783b952cd6..d042afba59 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -881,6 +881,9 @@ mod blend_dropdown_wheel_tests; #[cfg(test)] mod paths_scroll_tests; +#[cfg(test)] +mod blend_dropdown_groups_tests; + #[cfg(test)] mod options_bar_mode_wheel_tests; diff --git a/crates/ui-egui/src/menus/view_cmds/tests.rs b/crates/ui-egui/src/menus/view_cmds/tests.rs index 52df38d96c..8b80767e6f 100644 --- a/crates/ui-egui/src/menus/view_cmds/tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/tests.rs @@ -764,6 +764,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); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 222b1829f1..9011b4f97a 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -262,6 +262,13 @@ mod title_tests { } } +/// 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) +} + fn label(ui: &mut egui::Ui, s: &str) { let t = Tokens::get(ui.ctx()); ui.label(RichText::new(s).color(t.text_dim)); @@ -822,7 +829,7 @@ mod snapshot_row_tests { let p = trash(&h); click(&mut h, p); let st = h.state().session.active().unwrap(); - assert_eq!(st.snapshots.len(), 1, "the trash deleted the snapshot (the first snapshot stays)"); + assert_eq!(st.snapshots.len(), 1, "the trash deleted the snapshot, leaving the first one"); assert_eq!(st.history.entries().len(), steps, "and left the states alone"); // An edit after the click deselects the snapshot: the trash deletes the state. @@ -836,7 +843,7 @@ mod snapshot_row_tests { let p = trash(&h); click(&mut h, p); let st = h.state().session.active().unwrap(); - assert_eq!(st.snapshots.len(), 2, "the snapshot is kept"); + assert_eq!(st.snapshots.len(), 2, "the snapshot is kept, after the first one"); assert_eq!(st.history.entries().len(), steps - 1, "the current state is deleted"); } @@ -849,7 +856,7 @@ mod snapshot_row_tests { let to = trash(&h); drag(&mut h, egui::pos2(row.x, row.y), to); let st = h.state().session.active().unwrap(); - assert_eq!(st.snapshots.len(), 1, "the dragged snapshot is deleted (the first snapshot stays)"); + assert_eq!(st.snapshots.len(), 1, "the dragged snapshot is deleted, leaving the first one"); assert_eq!(st.history.entries().len(), steps, "no state is"); // The second-to-last state: it and the state after it go, as with Delete. @@ -862,7 +869,7 @@ mod snapshot_row_tests { drag(&mut h, egui::pos2(row.x, row.y), to); let st = h.state().session.active().unwrap(); assert_eq!(st.history.entries().len(), 1, "the dragged state and the ones after it are deleted"); - assert_eq!(st.snapshots.len(), 2, "the snapshot is kept"); + assert_eq!(st.snapshots.len(), 2, "the snapshot is kept, after the first one"); } /// With Allow Non-Linear History and only the oldest state current, a click on the trash has @@ -1001,6 +1008,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}"); + } + } + /// Snapshot thumbnails belong to the snapshot's document (#6087): closing a document drops /// them, and a document reopened with the same id (a `.pcraft` keeps it) gets fresh ones /// rather than the closed document's, even before the views are synced. diff --git a/crates/ui-egui/src/panels/brush_controls.rs b/crates/ui-egui/src/panels/brush_controls.rs index d618999d9f..ee83682dcd 100644 --- a/crates/ui-egui/src/panels/brush_controls.rs +++ b/crates/ui-egui/src/panels/brush_controls.rs @@ -1,11 +1,13 @@ -use super::{Align2, BlendMode, Color32, PhotocraftApp, Rect, Sense, Stroke, StrokeKind, Tokens, c32, icons, json, pos2, vec2, widgets}; +use super::{Align2, BlendMode, Color32, PhotocraftApp, Rect, Sense, Stroke, StrokeKind, Tokens, c32, icons, json, pos2, starts_blend_group, vec2, widgets}; /// A painting tool's Mode dropdown over `modes` (`None` is Clear); the wheel over it steps the -/// mode. Returns the mode picked this frame. +/// mode. Returns the mode picked this frame. A list of every blend mode draws the Layers panel's +/// group lines (#5532; Clear starts none); a short one (the Healing Brush's) draws none. pub(super) fn tool_mode_dropdown(ui: &mut egui::Ui, id: &str, modes: &[Option], current: Option) -> Option> { let opts: Vec<(Option, &str)> = modes.iter().map(|m| (*m, m.map_or("Clear", BlendMode::label))).collect(); + let grouped = BlendMode::LAYER_MODES.iter().all(|m| modes.contains(&Some(*m))); let mut mode = current; - let chosen = widgets::dropdown_wheel_hovered(ui, id, tl!("Mode"), &mut mode, &opts, 96.0).0; + let chosen = widgets::dropdown_wheel_grouped(ui, id, tl!("Mode"), &mut mode, &opts, 96.0, |m| grouped && m.is_some_and(starts_blend_group)).0; chosen.last().copied() } @@ -21,7 +23,7 @@ pub(super) fn paint_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraf } else { (Some(b.mode), false) }; - if !widgets::dropdown_wheel_hovered(ui, id, tl!("Mode"), &mut mode, &opts, 96.0).0.is_empty() { + if !widgets::dropdown_wheel_grouped(ui, id, tl!("Mode"), &mut mode, &opts, 96.0, |m| m.0.is_some_and(starts_blend_group)).0.is_empty() { *clear = mode == (None, false); b.behind = mode.1; if mode.1 { diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs index aad55b96d2..38d3797014 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -144,9 +144,11 @@ pub(super) fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { }); } 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", json!({}))); diff --git a/crates/ui-egui/src/panels/history_menu_ui.rs b/crates/ui-egui/src/panels/history_menu_ui.rs index 245fa986d8..fa865d42c4 100644 --- a/crates/ui-egui/src/panels/history_menu_ui.rs +++ b/crates/ui-egui/src/panels/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. @@ -158,6 +159,26 @@ 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; + app.session.execute("history.stepBackward", json!({})).unwrap(); + let mut h = harness(app); + 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"); + 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), (2, 2)); + } + #[test] fn new_snapshot_adds_a_snapshot_and_leaves_the_states() { let mut h = harness(app()); diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 835b370af2..7dfa2ad6cd 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -4,7 +4,9 @@ use super::layer_drag::{ }; use super::layer_row::{RowSel, layer_row}; use super::options_bar::{LAYER_PCT_W, body_text_width, pct_action, scrub_pct_label}; -use super::{BlendMode, Layer, LayerId, MaskKind, PhotocraftApp, Rect, Sense, Tokens, Value, empty, icons, json, label, pos2, theme, vec2, widgets}; +use super::{ + BlendMode, Layer, LayerId, MaskKind, PhotocraftApp, Rect, Sense, Tokens, Value, empty, icons, json, label, pos2, starts_blend_group, theme, vec2, widgets, +}; // ----------------------------------------------------------------------------- layers @@ -58,7 +60,7 @@ fn inactive_blend_rows(ui: &mut egui::Ui, pro: bool) { let (blend_width, show_opacity_label) = opacity_row_layout(ui.available_width(), body_text_width(ui, opacity_label), ui.spacing().item_spacing.x); let mut m = BlendMode::Normal; let options = blend_options(false, m); - widgets::dropdown_wheel_hovered(ui, "blend", tl!("Blend Mode"), &mut m, &options, blend_width); + widgets::dropdown_wheel_grouped(ui, "blend", tl!("Blend Mode"), &mut m, &options, blend_width, |m| starts_blend_group(*m)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let mut o = 100.0; widgets::popup_value_field(ui, opacity_label, &mut o, 0.0..=100.0, "%", LAYER_PCT_W); @@ -154,7 +156,9 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { 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", tl!("Blend Mode"), &mut m, &blend_options(all_groups, l.blend), blend_width); + widgets::dropdown_wheel_grouped(ui, "blend", tl!("Blend Mode"), &mut m, &blend_options(all_groups, 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 { let mut p = targets.clone(); diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index ba20b0bfba..15c602ae99 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -1,6 +1,6 @@ use super::brush_controls::{brush_preset_chip, mixer_load_swatch, paint_mode_dropdown, smoothing_field, smoothing_options, tool_mode_dropdown}; use super::properties::{select_and_mask_button, selection_mode_buttons}; -use super::{BlendMode, Color32, PhotocraftApp, RichText, Sense, Tokens, Tool, Value, icons, json, vec2, widgets}; +use super::{BlendMode, Color32, PhotocraftApp, RichText, Sense, Tokens, Tool, Value, icons, json, starts_blend_group, vec2, widgets}; use photocraft_paint::BrushSettings; // Custom controls also need to bring keyboard focus into a scroll viewport. @@ -449,7 +449,9 @@ fn selection_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: 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", tl!("Blend Mode"), &mut app.ui.tool_options.gradient_blend_mode, &opts, 96.0); + widgets::dropdown_wheel_grouped(ui, "gradient-blend-mode", tl!("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). diff --git a/crates/ui-egui/src/save_identity_tests.rs b/crates/ui-egui/src/save_identity_tests.rs index f23a440d4d..f59464d6d1 100644 --- a/crates/ui-egui/src/save_identity_tests.rs +++ b/crates/ui-egui/src/save_identity_tests.rs @@ -298,6 +298,56 @@ fn save_settings_start_at_the_opened_files_encoding() { 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")); +} + /// A browser download is only requested: the document takes the name but keeps its unsaved /// changes, so the leave-page guard stays armed (#4962). A confirmed write still saves it. #[test] diff --git a/crates/ui-egui/src/tools/crop_mode/tests.rs b/crates/ui-egui/src/tools/crop_mode/tests.rs index 4401e9b15d..c0afceb0d1 100644 --- a/crates/ui-egui/src/tools/crop_mode/tests.rs +++ b/crates/ui-egui/src/tools/crop_mode/tests.rs @@ -458,6 +458,33 @@ fn commit_is_the_same_in_both_modes_and_the_view_stays_upright() { 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/tools/crop_ui.rs b/crates/ui-egui/src/tools/crop_ui.rs index ef5416d8a6..490be07fa5 100644 --- a/crates/ui-egui/src/tools/crop_ui.rs +++ b/crates/ui-egui/src/tools/crop_ui.rs @@ -499,6 +499,29 @@ 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. 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 + && 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 /// Crop tool still picked, [`ensure_frame`] then makes the active document a new default frame. pub fn cancel(app: &mut PhotocraftApp) { @@ -653,6 +676,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; } @@ -664,6 +690,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() }; @@ -750,6 +783,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; @@ -952,7 +995,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 { @@ -1060,7 +1103,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; } @@ -1072,6 +1117,25 @@ fn release(app: &mut PhotocraftApp, drag: CropDrag) { push_press_step(app); } +/// 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) { + let Some(drag) = app.crop.drag.take() else { return }; + let tool = std::mem::replace(&mut app.ui.tool, Tool::Crop); + release(app, drag); + crate::crop_mode::sync_frame(app); + 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 0d5c356b40..93e2de2556 100644 --- a/crates/ui-egui/src/tools/crop_ui/tests.rs +++ b/crates/ui-egui/src/tools/crop_ui/tests.rs @@ -496,6 +496,27 @@ fn moving_the_frame_snaps_its_edges() { 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] @@ -532,6 +553,41 @@ fn box_undo_and_redo_grey_out_when_their_stack_is_empty() { 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))); + // 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))); +} + #[test] fn handles_resize_with_shift_and_alt() { let mut app = app(SampleType::U8); @@ -665,6 +721,226 @@ fn space_on_the_canvas_moves_the_frame_not_the_view() { 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(); +} + +/// 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(); +} + +/// 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 @@ -984,6 +1260,126 @@ fn the_stylus_eraser_and_a_gesture_in_progress_keep_the_frame_pending() { 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:?}"); + } +} + +/// 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:?}"); + } + } +} + +/// 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() { diff --git a/crates/ui-egui/src/tools/perspective_crop_ui.rs b/crates/ui-egui/src/tools/perspective_crop_ui.rs index 2a696bd5ed..ed60c90d41 100644 --- a/crates/ui-egui/src/tools/perspective_crop_ui.rs +++ b/crates/ui-egui/src/tools/perspective_crop_ui.rs @@ -53,6 +53,24 @@ 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). +/// 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 + && 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) { app.ui.perspective_crop = None; app.pcrop.drag = None; @@ -121,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])); @@ -327,6 +344,202 @@ 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(); + } + + /// ⌘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] + 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] diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index cb5354e550..cf5e648190 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -42,7 +42,9 @@ pub use color::{ }; #[cfg(test)] use color::{checker_tile_id, checker_uv}; -pub use dropdown::{dropdown, dropdown_hovered, dropdown_literal, dropdown_wheel_hovered, dropdown_with_tooltips, menu_scroll, swatch_popup}; +pub use dropdown::{ + dropdown, dropdown_hovered, dropdown_literal, dropdown_wheel_grouped, dropdown_wheel_hovered, dropdown_with_tooltips, menu_scroll, swatch_popup, +}; pub(crate) use fields::compact_wrapping_value_field; #[cfg(test)] use fields::{FieldOpts, NUMERIC_INPUT_LIMIT, value_field_in}; diff --git a/crates/ui-egui/src/widgets/dropdown.rs b/crates/ui-egui/src/widgets/dropdown.rs index 6f83b0edd2..ca0ea37d67 100644 --- a/crates/ui-egui/src/widgets/dropdown.rs +++ b/crates/ui-egui/src/widgets/dropdown.rs @@ -1,7 +1,7 @@ use super::panel::chevron_icon; use super::scrub::take_label_scrub_name; use super::slider::wheel_notches_of; -use super::{Pos2, Rect, Response, Ui, Vec2, type_ahead}; +use super::{Pos2, Rect, Response, Sense, Stroke, Tokens, Ui, Vec2, type_ahead, vec2}; /// A compact labelled dropdown in the studio style. pub fn dropdown(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> bool { @@ -11,13 +11,13 @@ pub fn dropdown(ui: &mut Ui, id: &str, name: &str, current /// [`dropdown`] whose option labels are shown exactly as given: names the user typed (a channel /// or layer name) must not be translated, unlike the built-in labels [`dropdown`] translates (#5335). pub fn dropdown_literal(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> bool { - let (chosen, _) = dropdown_with(ui, id, name, current, options, width, false, false); + let (chosen, _) = dropdown_with(ui, id, name, current, options, width, false, false, &|_| false); !chosen.is_empty() } /// [`dropdown`], also returning the option under the pointer in its open list (live previews). pub fn dropdown_hovered(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> (bool, Option) { - let (chosen, hovered) = dropdown_with(ui, id, name, current, options, width, false, true); + let (chosen, hovered) = dropdown_with(ui, id, name, current, options, width, false, true, &|_| false); (!chosen.is_empty(), hovered) } @@ -35,7 +35,22 @@ pub fn dropdown_wheel_hovered( options: &[(T, &str)], width: f32, ) -> (Vec, Option) { - dropdown_with(ui, id, name, current, options, width, true, true) + dropdown_with(ui, id, name, current, options, width, true, true, &|_| false) +} + +/// [`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, + name: &str, + current: &mut T, + options: &[(T, &str)], + width: f32, + starts_group: impl Fn(&T) -> bool, +) -> (Vec, Option) { + dropdown_with(ui, id, name, current, options, width, true, true, &starts_group) } #[allow(clippy::too_many_arguments)] @@ -48,6 +63,7 @@ fn dropdown_with( width: f32, wheel: bool, translate: bool, + starts_group: &dyn Fn(&T) -> bool, ) -> (Vec, Option) { let shown = |l: &str| if translate { tl!(l).to_string() } else { l.to_string() }; let label = options.iter().find(|(v, _)| v == current).map(|(_, l)| shown(l)).unwrap_or_else(|| "—".into()); @@ -86,7 +102,10 @@ fn dropdown_with( // 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, _), text) in options.iter().zip(texts.iter()) { + for (i, ((v, _), text)) in options.iter().zip(texts.iter()).enumerate() { + if i > 0 && starts_group(v) { + list_separator(ui); + } let item = ui.selectable_label(v == current, text.as_str()); if reveal && v == current { item.scroll_to_me(None); @@ -135,6 +154,15 @@ fn dropdown_with( (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 diff --git a/crates/ui-egui/src/widgets/tests.rs b/crates/ui-egui/src/widgets/tests.rs index d4c1bd81b3..9dd705f638 100644 --- a/crates/ui-egui/src/widgets/tests.rs +++ b/crates/ui-egui/src/widgets/tests.rs @@ -1442,3 +1442,44 @@ fn the_wheel_leaves_a_plain_dropdown_alone() { wheel(&mut h, egui::MouseWheelUnit::Line, egui::vec2(0.0, -1.0), Modifiers::NONE); assert_eq!(*h.state(), 0); } + +/// [`MODES`] in a wheel dropdown whose list draws a line above each option `starts_group` picks, +/// opened: the open list's rect and each option's row in it. +fn open_grouped_modes(starts_group: fn(&usize) -> bool) -> (egui::Rect, Vec) { + let mut h = Harness::builder().with_size(egui::vec2(300.0, 300.0)).build_ui_state( + move |ui, selected: &mut usize| { + super::dropdown_wheel_grouped(ui, "blend-mode", tl!("Blend Mode"), selected, &MODES, 120.0, starts_group); + }, + 0, + ); + crate::theme::apply(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run(); + h.get_by_role(egui::accesskit::Role::ComboBox).click(); + h.run_steps(4); + let list = h.ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id))); + let Some(list) = list else { panic!("the list is open") }; + let rows = MODES.iter().map(|(_, l)| h.get_all_by_label(l).map(|n| n.rect()).rfind(|r| list.contains_rect(*r)).unwrap_or(egui::Rect::NOTHING)).collect(); + (list, rows) +} + +/// The gaps between consecutive rows of an open list. +fn row_gaps(rows: &[egui::Rect]) -> Vec { + rows.windows(2).map(|w| w[1].top() - w[0].bottom()).collect() +} + +/// A grouped dropdown draws a line above each option starting a group, never above the first one, +/// and the lines take no width: the list is as wide as without them (#5532). +#[test] +fn a_grouped_dropdown_list_draws_a_line_above_each_group_and_keeps_its_width() { + let (plain_list, plain) = open_grouped_modes(|_| false); + let plain_gaps = row_gaps(&plain); + let (lo, hi) = plain_gaps.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), g| (lo.min(*g), hi.max(*g))); + assert!(hi - lo < 1.0, "no groups, even row gaps: {plain_gaps:?}"); + // Darken (index 2) starts a group; so does Normal, the first option, which never gets a line. + let (list, rows) = open_grouped_modes(|i| matches!(*i, 0 | 2)); + let gaps = row_gaps(&rows); + assert!((gaps[0] - lo).abs() < 0.5 && (gaps[2] - lo).abs() < 0.5, "only Dissolve/Darken is wider: {gaps:?}"); + assert!(gaps[1] > lo + 2.0, "a line between Dissolve and Darken: {gaps:?}"); + assert!((rows[0].top() - plain[0].top()).abs() < 0.5, "no line above the first row: {rows:?} vs {plain:?}"); + assert_eq!(list.width(), plain_list.width(), "the line doesn't widen the list"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b508c3a71c..99a5b248a6 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -167,7 +167,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; 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, four floats 0..1 (not 0..255) | | `document.presets.list` | `{}` → `{presets:[{name,settings}]}`: saved New Document configurations | diff --git a/docs/scorecard.md b/docs/scorecard.md index 20dcc91b3e..3b6bc68787 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 | 51 | 85 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 47 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: 10 of 191 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 194 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 3 | 3 | 660 of 660 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -209,7 +209,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 10 of 191** (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: 10 of 194** (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.legacy_compositing`, `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 7031163bfb..58a5a317be 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-11-06 · **Change:** minor (Channels panel menu: New Channel…, Duplicate Channel, Delete Channel, New Spot Channel…, Merge Spot Channel, Channel Options…, Split Channels, Merge Channels…, #11451; a Color Picker for another dialog's colour or the Crop shield shows the picked colour there before OK, #9886; Edit › Transform › Distort side handles move their edge, Perspective side handles skew, #10085; Ctrl + Alt + wheel zooms the canvas like ⌥ + wheel on Windows and Linux, where winit reports a held Ctrl as both ctrl and command, #10488; Layers panel filter by Color, #5898; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; Shape Fill/Stroke popover as Photoshop's, every colour swatch opens the full Color Picker with a live preview; the text and gradient stop Color Pickers show the picked colour on the canvas before OK, #5530; selected colour sets edit drawing, tone and supported filters; geometry remains open; a paragraph box that can't hold its text enlarges its lower-right handle and shows a black + in it, as the reference application; Free Transform of several selected layers, #6501; Path Operations fixes: the first component keeps combining, a hidden component selection is left alone, a dragged live shape stays live, a refused Pen draft ends once; Pen, Freeform Pen, Curvature Pen and Path Selection Path Operations menu, which changes selected components, `+` / `-` keys, #1397; the Pen carries on an open shape or vector mask path; selection-aware font controls, pending caret fonts and focused commit, plus direct font-name editing with a compact no-match message, #9338; 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; 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-11-06 · **Change:** minor (History Options snapshot options, #3634; Channels panel menu: New Channel…, Duplicate Channel, Delete Channel, New Spot Channel…, Merge Spot Channel, Channel Options…, Split Channels, Merge Channels…, #11451; a Color Picker for another dialog's colour or the Crop shield shows the picked colour there before OK, #9886; Edit › Transform › Distort side handles move their edge, Perspective side handles skew, #10085; Ctrl + Alt + wheel zooms the canvas like ⌥ + wheel on Windows and Linux, where winit reports a held Ctrl as both ctrl and command, #10488; Layers panel filter by Color, #5898; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; Shape Fill/Stroke popover as Photoshop's, every colour swatch opens the full Color Picker with a live preview; the text and gradient stop Color Pickers show the picked colour on the canvas before OK, #5530; selected colour sets edit drawing, tone and supported filters; geometry remains open; a paragraph box that can't hold its text enlarges its lower-right handle and shows a black + in it, as the reference application; Free Transform of several selected layers, #6501; Path Operations fixes: the first component keeps combining, a hidden component selection is left alone, a dragged live shape stays live, a refused Pen draft ends once; Pen, Freeform Pen, Curvature Pen and Path Selection Path Operations menu, which changes selected components, `+` / `-` keys, #1397; the Pen carries on an open shape or vector mask path; selection-aware font controls, pending caret fonts and focused commit, plus direct font-name editing with a compact no-match message, #9338; 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; 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, @@ -246,9 +246,9 @@ 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 | 11 of 183 do nothing (scorecard, 2026-11-01) | +| Every preference takes effect | partial | 10 of 192 do nothing (scorecard, 2026-11-06) | | 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 | 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 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 | | 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 | @@ -330,6 +330,7 @@ Paragraph; the rest open as in-app floating windows. | 2026-10-12 | minor | Toolbar tool shortcuts can be reassigned, removed and reset in Keyboard Shortcuts (#4086); capture, restart, group cycling, conflict and text-focus regressions | | 2026-10-12 | minor | Smart filter rows can be selected, and dragged (⌥: copied) onto another smart object or onto Delete (#4271) | | 2026-10-12 | minor | Free Transform options bar: H and V skew fields; a sheared box reads as skew instead of a taller H | +| 2026-10-12 | minor | History Options: Automatically Create First Snapshot, Automatically Create New Snapshot When Saving, Show New Snapshot Dialog by Default (#2966) | | 2026-10-12 | minor | Crop tool Fill › Content-Aware Fill done (#3823); Delete Cropped Pixels off split into its own row, still partial | | 2026-10-12 | minor | Layers panel: Clip Thumbnails to Layer Bounds frames each layer's pixels instead of the canvas (#4281) | | 2026-10-12 | minor | Guides: ⌥-click turns a guide through the click; double-click opens Preferences › Guides, Grid & Slices |