From a6b4d29801be1f16de39931ddded26ffc8be6023 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Thu, 26 Nov 2026 20:26:58 +0100 Subject: [PATCH 1/6] fix(history): default History Brush source is the open snapshot (#12845) The History Brush, Fill > History and the Art History Brush restore from one per-document source. With none set in the History panel the engine asked the history for it, and the history answers row 0: the oldest state still held. Once the history is full row 0 is a recent step, so a click painted that step instead of the image the document opened with. The default now resolves to the open snapshot, the first History panel snapshot (the document as opened, named after it), which the states' trimming never removes. The engine records its id per document, together with the id of a state chosen with history.setSource - the history reports row 0 both for a chosen row 0 and for nothing chosen, and it must not be edited here. Deleting that snapshot leaves the default empty, as for any deleted source; with History Options > Automatically Create First Snapshot off the default keeps today's behaviour, the oldest state held. --- crates/engine-core/src/cmd.rs | 2 + .../src/cmd/edit_menu_cmds/purge.rs | 3 + .../cmd/history_brush_default_source_tests.rs | 101 +++++++++++++++++ .../src/cmd/history_source_cmds.rs | 41 ++++++- .../cmd/new_document_history_name_tests.rs | 8 +- crates/engine-core/src/doc_state.rs | 18 +++- crates/engine-core/src/session/documents.rs | 4 +- crates/engine/tests/it/main.rs | 1 + .../paint_in_history_brush_default_source.rs | 102 ++++++++++++++++++ .../tests/it/paint_in_history_source_cmds.rs | 14 ++- crates/ui-egui/src/panels/history.rs | 4 +- .../src/panels/history_panel_select_tests.rs | 21 ++++ .../src/tools/retouch_ui/bar/history.rs | 12 ++- 13 files changed, 311 insertions(+), 20 deletions(-) create mode 100644 crates/engine-core/src/cmd/history_brush_default_source_tests.rs create mode 100644 crates/engine/tests/it/paint_in_history_brush_default_source.rs diff --git a/crates/engine-core/src/cmd.rs b/crates/engine-core/src/cmd.rs index 764d48d423..9a2f9b7cab 100644 --- a/crates/engine-core/src/cmd.rs +++ b/crates/engine-core/src/cmd.rs @@ -64,6 +64,8 @@ pub mod fx_visibility_cmds; pub mod gallery_cmds; pub mod gradient_fill_cmds; pub mod group_view_cmds; +#[cfg(test)] +mod history_brush_default_source_tests; pub mod history_cmds; pub mod history_menu_cmds; pub mod history_options_cmds; diff --git a/crates/engine-core/src/cmd/edit_menu_cmds/purge.rs b/crates/engine-core/src/cmd/edit_menu_cmds/purge.rs index 8f84de4fe7..768d0a2dce 100644 --- a/crates/engine-core/src/cmd/edit_menu_cmds/purge.rs +++ b/crates/engine-core/src/cmd/edit_menu_cmds/purge.rs @@ -40,6 +40,9 @@ pub(super) fn purge(s: &mut Session, what: &str) -> Result { if s.documents().iter().any(|d| d.history.can_undo() || d.history.can_redo()) { for st in &mut s.docs { st.history.clear(); + // The state source went back to the default with the states (#2966), so the + // engine's record of that choice goes with it (#12845). + st.source_state_id = None; st.coalesce = None; } freed += b; diff --git a/crates/engine-core/src/cmd/history_brush_default_source_tests.rs b/crates/engine-core/src/cmd/history_brush_default_source_tests.rs new file mode 100644 index 0000000000..034fbc680a --- /dev/null +++ b/crates/engine-core/src/cmd/history_brush_default_source_tests.rs @@ -0,0 +1,101 @@ +//! #12845 (EPIC-HISTORY-BRUSH #12618): the History Brush's default source is the open snapshot, +//! the document as opened, not the oldest state held. `historySource` therefore reports +//! `{snapshot, name}` with the document's name on a new or opened document, the default survives +//! the history filling up, deleting the open snapshot leaves no source, and with History Options › +//! Automatically Create First Snapshot off the default stays the oldest state. + +use serde_json::{Value, json}; + +use crate::Session; + +/// The active document's History Brush source, as `historySource` in `doc_inspect` reports it. +fn source(s: &Session) -> Value { + crate::inspect::document(s.active().unwrap())["historySource"].clone() +} + +/// The name of the active document's first snapshot row. +fn opened_name(s: &Session) -> String { + s.active().unwrap().snapshots()[0].name.clone() +} + +#[test] +fn the_default_source_is_the_open_snapshot_named_after_the_document() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + assert_eq!(source(&s), json!({"snapshot": 0, "name": opened_name(&s)})); + assert_eq!(s.active().unwrap().doc.name, opened_name(&s), "the open snapshot is named after the document"); + // Edits move the oldest state's label but not the default. + s.execute("layer.new.layer", json!({})).unwrap(); + assert_eq!(source(&s), json!({"snapshot": 0, "name": opened_name(&s)})); +} + +#[test] +fn the_default_open_snapshot_survives_a_full_history() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let expected = source(&s); + s.active_mut().unwrap().history.max_states = 2; + for _ in 0..6 { + s.execute("layer.new.layer", json!({})).unwrap(); + } + let st = s.active().unwrap(); + assert_eq!(st.history.past_len(), 2, "the history filled up and older states fell off"); + assert!(st.history.entries().first().is_some_and(|label| label != "New"), "the opening state is gone from row 0: {:?}", st.history.entries()); + assert_eq!(source(&s), expected, "the default still names the document as opened"); + assert_eq!(st.snapshots().len(), 1, "the open snapshot is not a state and is never trimmed"); +} + +#[test] +fn deleting_the_open_snapshot_leaves_no_source() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("history.deleteSnapshot", json!({"snapshot": 0})).unwrap(); + assert!(source(&s).is_null(), "no source until one is set"); + // An explicit state source still works after that. + s.execute("history.setSource", json!({"state": 0})).unwrap(); + assert_eq!(source(&s)["state"], 0); +} + +#[test] +fn the_default_follows_automatically_create_first_snapshot() { + // Preferences are process-wide, so the loop ends on the default (on) for the other tests. + for first in [false, true] { + let mut s = crate::session(); + s.execute("history.options", json!({"automaticallyCreateFirstSnapshot": first})).unwrap(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + if first { + assert_eq!(source(&s), json!({"snapshot": 0, "name": opened_name(&s)}), "the open snapshot"); + } else { + // Not measured: no open snapshot exists, so today's default (the oldest state) stays. + assert_eq!(source(&s), json!({"state": 0, "label": "New"}), "the oldest state held"); + } + } +} + +/// A state set in the panel is still the source once the open snapshot is gone: the default does +/// not overwrite an explicit choice. +#[test] +fn an_explicit_state_source_survives_deleting_the_open_snapshot() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("history.setSource", json!({"state": 1})).unwrap(); + assert_eq!(source(&s), json!({"state": 1, "label": "New Layer"})); + s.execute("history.deleteSnapshot", json!({"snapshot": 0})).unwrap(); + assert_eq!(source(&s), json!({"state": 1, "label": "New Layer"}), "explicit sources are untouched"); +} + +/// With Automatically Create First Snapshot off, deleting states down to one and setting a state +/// source keep working exactly as today (the oldest-state default). +#[test] +fn without_an_open_snapshot_the_oldest_state_default_remains() { + let mut s = crate::session(); + s.execute("history.options", json!({"automaticallyCreateFirstSnapshot": false})).unwrap(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + // The current state is a redo row now; the default is still row 0. + assert_eq!(source(&s), json!({"state": 0, "label": "New"})); + s.execute("history.setSource", json!({"state": 1})).unwrap(); + assert_eq!(source(&s)["label"], "New Layer"); +} diff --git a/crates/engine-core/src/cmd/history_source_cmds.rs b/crates/engine-core/src/cmd/history_source_cmds.rs index 192b5ad045..80e5347f82 100644 --- a/crates/engine-core/src/cmd/history_source_cmds.rs +++ b/crates/engine-core/src/cmd/history_source_cmds.rs @@ -1,7 +1,9 @@ //! The History Brush's source (#2966): the History panel's source column, at the left of every //! state and snapshot, sets what the History Brush (and Fill › History) restores from. Exactly one -//! source per document; by default the oldest state held (Photoshop's default is the first -//! snapshot, the document as opened, which that state is until it falls off the history). +//! source per document; by default the open snapshot, the first History panel snapshot (the +//! document as opened, named after it; #12845), which outlives the states (#12618). With History +//! Options › Automatically Create First Snapshot off there is no open snapshot, and the default +//! stays the oldest state held; deleting the open snapshot also leaves no source until one is set. //! //! A state source is kept by state, not by index ([`photocraft_ops::History::set_brush_source`]), //! so it stays on its state while older states fall off, and that state is kept when it would fall @@ -41,14 +43,39 @@ pub enum HistorySource { Snapshot(u64), } -/// The document's History Brush source, `None` once the source state or snapshot is gone. +/// The document's History Brush source, `None` once the source state or snapshot is gone. With no +/// source set it is the open snapshot (the document as opened, #12845); when no open snapshot was +/// taken (History Options › Automatically Create First Snapshot off) it is the oldest state held, +/// as before. pub fn source(st: &DocState) -> Option { - match st.source_snapshot.or_else(|| st.history.brush_source_snapshot()) { - Some(id) => st.snapshots().iter().any(|s| s.id == id).then_some(HistorySource::Snapshot(id)), + if let Some(id) = st.source_snapshot.or_else(|| st.history.brush_source_snapshot()) { + return st.snapshots().iter().any(|s| s.id == id).then_some(HistorySource::Snapshot(id)); + } + // A state set in the panel is kept by its state id: it stays the source while older states fall + // off and is gone once it is deleted or discarded (#2966). ops' + // [`photocraft_ops::History::brush_source`] reads row 0 both for such a set state and for "none + // set", so the choice is recorded here in `source_state_id` (#12845). + if let Some(id) = st.source_state_id { + // Clear History holds a set source back with the states it took off: until its undo, the + // current state is the source, as before (#3536). + let row = if st.history.is_cleared() { st.history.brush_source() } else { st.history.row_of(id) }; + return row.map(HistorySource::State); + } + match st.open_snapshot { + // The document as opened outlives the states, so a click still restores it (#12618). + // Deleting this snapshot leaves no source, as for any deleted source. + Some(id) => st.snapshots().iter().find(|s| s.id == id).map(|s| HistorySource::Snapshot(s.id)), + // Not measured (Automatically Create First Snapshot off): today's default. None => st.history.brush_source().map(HistorySource::State), } } +/// Whether `src` is the document's open snapshot, the History panel's first row (the document as +/// opened): the History Brush's default source (#12845). +pub fn is_open_snapshot(st: &DocState, src: HistorySource) -> bool { + matches!(src, HistorySource::Snapshot(id) if st.open_snapshot == Some(id)) +} + pub fn source_of(st: &DocState, src: HistorySource) -> Option> { match src { HistorySource::State(i) => st.history.row_doc(i, &st.doc), @@ -90,11 +117,15 @@ fn set_source(s: &mut Session, p: &Value) -> Result { if !st.history.set_brush_source(i) { return Err(bad(format!("no history state {i}"))); } + // Kept by state id as well, so the open-snapshot default can tell this choice from + // ops' never-set default (#12845). + st.source_state_id = st.history.row_id(i); st.source_snapshot = None; } Some(HistorySource::Snapshot(id)) => { // No state is the source now, so none is kept past its time. st.history.reset_brush_source(); + st.source_state_id = None; st.source_snapshot = Some(id); } } diff --git a/crates/engine-core/src/cmd/new_document_history_name_tests.rs b/crates/engine-core/src/cmd/new_document_history_name_tests.rs index 7cd855830c..7824f1bbb3 100644 --- a/crates/engine-core/src/cmd/new_document_history_name_tests.rs +++ b/crates/engine-core/src/cmd/new_document_history_name_tests.rs @@ -50,18 +50,20 @@ fn every_background_and_mode_of_file_new_gives_new() { } #[test] -fn the_first_state_stays_new_through_undo_and_redo_and_is_the_default_brush_source() { +fn the_first_state_stays_new_through_undo_and_redo_while_the_default_source_is_the_open_snapshot() { let mut s = crate::session(); s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); let source = |s: &Session| crate::inspect::document(s.active().unwrap())["historySource"].clone(); - assert_eq!(source(&s), json!({"state": 0, "label": "New"})); + // The default source is the open snapshot (#12845); the "New" state stays the opening state. + let opened = |s: &Session| crate::inspect::document(s.active().unwrap())["snapshots"][0]["name"].as_str().unwrap().to_string(); + assert_eq!(source(&s), json!({"snapshot": 0, "name": opened(&s)})); s.execute("layer.new.layer", json!({})).unwrap(); assert_eq!(history(&s).0, json!(["New", "New Layer"])); s.execute("edit.undo", json!({})).unwrap(); assert_eq!(history(&s).0, json!(["New"])); s.execute("edit.redo", json!({})).unwrap(); assert_eq!(history(&s).0, json!(["New", "New Layer"])); - assert_eq!(source(&s), json!({"state": 0, "label": "New"})); + assert_eq!(source(&s), json!({"snapshot": 0, "name": opened(&s)})); } #[test] diff --git a/crates/engine-core/src/doc_state.rs b/crates/engine-core/src/doc_state.rs index 5dcd43213f..ea3fa3a0c1 100644 --- a/crates/engine-core/src/doc_state.rs +++ b/crates/engine-core/src/doc_state.rs @@ -61,8 +61,17 @@ pub struct DocState { /// 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`]). + /// the source is a state ([`DocState::source_state_id`]) or the default + /// ([`crate::history_source_cmds::source`]). pub(crate) source_snapshot: Option, + /// The state id chosen as the History Brush's source (`history.setSource {state}`); `None`: no + /// state was set, so the default applies (#12845). The history keeps the state it names past its + /// own time; Edit › Purge › Histories clears it along with the states it removed. + pub(crate) source_state_id: Option, + /// The snapshot holding the document as opened (`DocState::new`), `None` when History Options › + /// Automatically Create First Snapshot was off when the document was admitted. It is the + /// History Brush's default source (#12845); deleting that snapshot leaves the default empty. + pub(crate) open_snapshot: Option, /// Names the user gave layers (Rename Layer, Duplicate Layer's Name, `type.edit`'s name): a /// type layer keeps such a name although it looks like a copy's ("Title copy 2"), while a /// name Duplicate Layer made still follows the text (#9023). Kept for the session only. @@ -127,7 +136,8 @@ impl DocState { }; let doc = Arc::new(doc); // Photoshop's first snapshot: the document as opened, named after it, so the History - // panel's top row can always bring it back (#2966). + // panel's top row can always bring it back (#2966). It is also the History Brush's default + // source (#12845). let first = history_cmds::Snapshot { id: 0, name: doc.name.clone(), doc: doc.clone(), layers: target }; Self { inputs: DocStateInputs { doc, active_layer, selected_layers: active_layer.into_iter().collect() }, @@ -155,6 +165,10 @@ impl DocState { next_snapshot: 1, save_snapshot: None, source_snapshot: None, + source_state_id: None, + // The id `DocState::new` gives the document-as-opened snapshot above; session's + // `add_document` clears it when Automatically Create First Snapshot is off. + open_snapshot: Some(0), typed_names: Default::default(), pixel_revision: 0, } diff --git a/crates/engine-core/src/session/documents.rs b/crates/engine-core/src/session/documents.rs index 8c358493a9..c3739cbe54 100644 --- a/crates/engine-core/src/session/documents.rs +++ b/crates/engine-core/src/session/documents.rs @@ -225,9 +225,11 @@ impl Session { 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). + // as opened, so the History panel starts at the opening state (#2966) and the History + // Brush's default stays the oldest state held (#12845). if !self.prefs.get().history_options.automatically_create_first_snapshot { st.snapshots_mut().clear(); + st.open_snapshot = None; } self.pcraft_caches.insert(st.doc.id, Default::default()); self.docs.push(craft_tracked::Tracked::new(st)); diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 69b4cb0840..a34857c601 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -124,6 +124,7 @@ mod paint_in_fx_view_cmds; mod paint_in_fx_visibility_cmds; mod paint_in_gradient_fill_cmds; mod paint_in_hidden_target; +mod paint_in_history_brush_default_source; mod paint_in_history_cmds; mod paint_in_history_menu_cmds; mod paint_in_history_options_cmds; diff --git a/crates/engine/tests/it/paint_in_history_brush_default_source.rs b/crates/engine/tests/it/paint_in_history_brush_default_source.rs new file mode 100644 index 0000000000..8f6b7220e4 --- /dev/null +++ b/crates/engine/tests/it/paint_in_history_brush_default_source.rs @@ -0,0 +1,102 @@ +//! #12845 (EPIC-HISTORY-BRUSH #12618): the History Brush's default source is the open snapshot, so +//! a click paints the pixels the document had when it opened, even after the history filled up and +//! the opening state fell off. The opened pixels are read from the open snapshot itself, so the +//! comparison is against the state captured at open, not a hand-written colour. + +use photocraft_engine::Session; +use serde_json::{Value, json}; + +/// A white 8×8 document. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": 16, "background": "white"})).unwrap(); + s +} + +fn rgba(s: &Session, x: i32, y: i32) -> [f32; 4] { + let st = s.active().unwrap(); + st.doc.layers[0].surface().unwrap().rgba(x, y) +} + +/// The pixel (3, 3) of the document as opened, as the History panel holds it (snapshot 0). +fn opened_pixel(s: &Session) -> [f32; 4] { + s.active().unwrap().snapshots()[0].doc.layers[0].surface().unwrap().rgba(3, 3) +} + +fn close(a: [f32; 4], b: [f32; 4]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01) +} + +fn paint(s: &mut Session, extra: Value) -> photocraft_engine::Result { + let mut p = json!({"points": [[3, 3]], "size": 40, "hardness": 100}); + if let (Some(p), Some(e)) = (p.as_object_mut(), extra.as_object()) { + p.extend(e.clone()); + } + s.execute("paint.historyBrush", p) +} + +#[test] +fn default_source_reports_the_open_snapshot() { + let s = session(); + let name = s.active().unwrap().doc.name.clone(); + assert_eq!(photocraft_engine::inspect::document(s.active().unwrap())["historySource"], json!({"snapshot": 0, "name": name})); +} + +#[test] +fn the_default_brush_paints_the_pixels_the_document_opened_with() { + let mut s = session(); + let at_open = opened_pixel(&s); + s.execute("paint.stroke", json!({"points": [[0, 3], [7, 3]], "size": 8, "hardness": 100, "color": "#ff0000"})).unwrap(); + assert!(rgba(&s, 3, 3)[0] > 0.9 && rgba(&s, 3, 3)[1] < 0.1, "the stroke painted red"); + paint(&mut s, json!({})).unwrap(); + assert!(close(rgba(&s, 3, 3), at_open), "the default source restores the opened pixel: {:?} vs {at_open:?}", rgba(&s, 3, 3)); +} + +#[test] +fn a_default_brush_click_still_paints_the_opened_image_after_the_history_fills_up() { + let mut s = session(); + let at_open = opened_pixel(&s); + s.active_mut().unwrap().history.max_states = 2; + for colour in ["#ff0000", "#00ff00", "#0000ff", "#ff00ff"] { + s.execute("paint.stroke", json!({"points": [[0, 3], [7, 3]], "size": 8, "hardness": 100, "color": colour})).unwrap(); + } + let st = s.active().unwrap(); + assert!(st.history.entries()[0] != "New", "the opening state fell off row 0: {:?}", st.history.entries()); + paint(&mut s, json!({})).unwrap(); + assert!(close(rgba(&s, 3, 3), at_open), "a click still restores the opened image: {:?} vs {at_open:?}", rgba(&s, 3, 3)); +} + +#[test] +fn deleting_the_open_snapshot_leaves_the_default_without_a_source() { + let mut s = session(); + s.execute("history.deleteSnapshot", json!({"snapshot": 0})).unwrap(); + assert!(photocraft_engine::inspect::document(s.active().unwrap())["historySource"].is_null()); + let before = rgba(&s, 3, 3); + let e = paint(&mut s, json!({})).unwrap_err().to_string(); + assert!(e.contains("source was deleted"), "{e}"); + assert_eq!(rgba(&s, 3, 3), before, "nothing painted"); + // Setting a source makes it paint again: a snapshot of the red document. + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let snap = s.execute("history.newSnapshot", json!({"name": "Red"})).unwrap()["snapshot"].clone(); + s.execute("history.setSource", json!({"snapshot": snap})).unwrap(); + paint(&mut s, json!({})).unwrap(); + assert!(rgba(&s, 3, 3)[0] > 0.9, "{:?}", rgba(&s, 3, 3)); +} + +/// With Automatically Create First Snapshot off there is no open snapshot: the default keeps +/// today's behaviour and paints the oldest state held. +#[test] +fn without_the_open_snapshot_the_default_still_paints_the_oldest_state() { + let mut s = Session::new(); + s.execute("history.options", json!({"automaticallyCreateFirstSnapshot": false})).unwrap(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": 16, "background": "white"})).unwrap(); + // Preferences are process-wide: put the default back before this test's documents are gone. + let restore = |s: &mut Session| s.execute("history.options", json!({"automaticallyCreateFirstSnapshot": true})).unwrap(); + assert!(s.active().unwrap().snapshots().is_empty()); + let opened = rgba(&s, 3, 3); + s.execute("paint.stroke", json!({"points": [[0, 3], [7, 3]], "size": 8, "hardness": 100, "color": "#ff0000"})).unwrap(); + paint(&mut s, json!({})).unwrap(); + assert!(close(rgba(&s, 3, 3), opened), "the oldest state (the opening state) is the source"); + assert_eq!(photocraft_engine::inspect::document(s.active().unwrap())["historySource"], json!({"state": 0, "label": "New"})); + restore(&mut s); +} diff --git a/crates/engine/tests/it/paint_in_history_source_cmds.rs b/crates/engine/tests/it/paint_in_history_source_cmds.rs index 900e00eb6e..62bc48a16f 100644 --- a/crates/engine/tests/it/paint_in_history_source_cmds.rs +++ b/crates/engine/tests/it/paint_in_history_source_cmds.rs @@ -31,9 +31,11 @@ fn close(a: [f32; 3], b: [f32; 3]) -> bool { } #[test] -fn default_source_is_the_oldest_state() { +fn default_source_is_the_open_snapshot() { let mut s = session(); - assert_eq!(photocraft_engine::inspect::document(s.active().unwrap())["historySource"], json!({"state": 0, "label": "New"})); + // #12845: the default is the document as opened, not the oldest state held. + let name = s.active().unwrap().doc.name.clone(); + assert_eq!(photocraft_engine::inspect::document(s.active().unwrap())["historySource"], json!({"snapshot": 0, "name": name})); brush(&mut s, json!({})); assert!(close(rgb(&s), [1.0, 1.0, 1.0]), "{:?}", rgb(&s)); } @@ -105,15 +107,17 @@ fn deleting_the_source_state_leaves_no_source() { } /// Edit › Purge › Histories clears the states: the source goes back to the default instead of -/// leaving every document without one (#3536 review). +/// leaving every document without one (#3536 review). Since #12845 that default is the open +/// snapshot, which Purge keeps, so the brush paints the document as opened. #[test] fn purging_histories_resets_a_state_source() { let mut s = session(); s.execute("history.setSource", json!({"state": 1})).unwrap(); s.execute("edit.purge.histories", json!({})).unwrap(); - assert_eq!(photocraft_engine::inspect::document(s.active().unwrap())["historySource"], json!({"state": 0, "label": "Fill"})); + let name = s.active().unwrap().doc.name.clone(); + assert_eq!(photocraft_engine::inspect::document(s.active().unwrap())["historySource"], json!({"snapshot": 0, "name": name})); brush(&mut s, json!({})); - assert!(close(rgb(&s), [0.0, 1.0, 0.0]), "the only state left: {:?}", rgb(&s)); + assert!(close(rgb(&s), [1.0, 1.0, 1.0]), "the open snapshot Purge kept: {:?}", rgb(&s)); s.execute("edit.fill", json!({"contents": "history"})).unwrap(); } diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs index 420ae5de8b..38f47e0f23 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -58,8 +58,8 @@ fn current_key(app: &PhotocraftApp) -> Option { st.history.row_id(st.history.past_len()).map(HistoryKey::State) } -/// The row that is the History Brush's source. -fn source_key(st: &photocraft_engine::DocState) -> Option { +/// The row that is the History Brush's source: the open snapshot by default (#12845). +pub(crate) fn source_key(st: &photocraft_engine::DocState) -> Option { match photocraft_engine::history_source_cmds::source(st)? { HistorySource::State(row) => st.history.row_id(row).map(HistoryKey::State), HistorySource::Snapshot(id) => Some(HistoryKey::Snapshot(id)), diff --git a/crates/ui-egui/src/panels/history_panel_select_tests.rs b/crates/ui-egui/src/panels/history_panel_select_tests.rs index 443a3d1f86..3f6e0fbe78 100644 --- a/crates/ui-egui/src/panels/history_panel_select_tests.rs +++ b/crates/ui-egui/src/panels/history_panel_select_tests.rs @@ -417,6 +417,27 @@ fn the_first_snapshot_row_follows_the_option() { } } +/// #12845: the source column marks the open snapshot row by default, still when the states have +/// filled up and fallen off, and nothing once that row is deleted. +#[test] +fn the_source_icon_starts_on_the_open_snapshot_row() { + let mut app = app(); + assert!(matches!(history::source_key(app.session.active().unwrap()), Some(HistoryKey::Snapshot(0))), "the open snapshot row"); + app.session.active_mut().unwrap().history.max_states = 2; + for _ in 0..4 { + app.run("edit.fill", json!({"color": "#00ff00"})).unwrap(); + } + let st = app.session.active().unwrap(); + assert!(st.history.entries().first().is_some_and(|label| label != "New"), "older states fell off: {:?}", st.history.entries()); + assert!(matches!(history::source_key(st), Some(HistoryKey::Snapshot(0))), "still the open snapshot row"); + assert!(rows(st).iter().any(|r| matches!(r.key, HistoryKey::Snapshot(0))), "the row is listed"); + // Deleting that row leaves the panel with no source icon at all. + app.run("history.deleteSnapshot", json!({"snapshot": 0})).unwrap(); + assert_eq!(history::source_key(app.session.active().unwrap()), None, "no source until one is set"); + app.run("history.setSource", json!({"state": 0})).unwrap(); + assert!(matches!(history::source_key(app.session.active().unwrap()), Some(HistoryKey::State(_))), "a state row again"); +} + /// Snapshot thumbnails belong to the snapshot's document (#6087): 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. #[test] diff --git a/crates/ui-egui/src/tools/retouch_ui/bar/history.rs b/crates/ui-egui/src/tools/retouch_ui/bar/history.rs index f1e18875ed..aff6be4c6c 100644 --- a/crates/ui-egui/src/tools/retouch_ui/bar/history.rs +++ b/crates/ui-egui/src/tools/retouch_ui/bar/history.rs @@ -28,10 +28,18 @@ pub(crate) enum SourceCaption { /// The History Brush's source as the bar names it. pub(crate) fn source_caption(app: &PhotocraftApp) -> SourceCaption { - use photocraft_engine::history_source_cmds::{HistorySource, source}; + use photocraft_engine::history_source_cmds::{HistorySource, is_open_snapshot, source}; let Some(st) = app.session.active() else { return SourceCaption::Deleted }; let named = || match source(st)? { - HistorySource::Snapshot(id) => st.snapshots().iter().find(|s| s.id == id).map(|s| SourceCaption::Named(s.name.clone())), + // The default source, the open snapshot (#12845), keeps the bar's opening-state wording; + // any other snapshot is named. + src @ HistorySource::Snapshot(id) => { + if is_open_snapshot(st, src) { + Some(SourceCaption::Opening) + } else { + st.snapshots().iter().find(|s| s.id == id).map(|s| SourceCaption::Named(s.name.clone())) + } + } HistorySource::State(idx) => { let entries = st.history.entries(); let name = if idx < entries.len() { entries.get(idx).cloned() } else { st.history.redo_labels().nth(idx - entries.len()).map(str::to_string) }?; From cc51cd4de1da0d2f615b985bc9dbdf119df07da6 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Thu, 26 Nov 2026 20:41:12 +0100 Subject: [PATCH 2/6] fix(history): follow the history when it moves the source record While a state source is set the history keeps the answer: a source state deleted or discarded leaves no source (#2966), Clear History holds it back until its undo, and an action folding its steps renames the row (#3536). Reading the recorded id first and the history's own row second follows all three, instead of only the two the panel does directly. --- crates/engine-core/src/cmd/history_source_cmds.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/crates/engine-core/src/cmd/history_source_cmds.rs b/crates/engine-core/src/cmd/history_source_cmds.rs index 80e5347f82..2b5ee6c5c2 100644 --- a/crates/engine-core/src/cmd/history_source_cmds.rs +++ b/crates/engine-core/src/cmd/history_source_cmds.rs @@ -54,12 +54,11 @@ pub fn source(st: &DocState) -> Option { // A state set in the panel is kept by its state id: it stays the source while older states fall // off and is gone once it is deleted or discarded (#2966). ops' // [`photocraft_ops::History::brush_source`] reads row 0 both for such a set state and for "none - // set", so the choice is recorded here in `source_state_id` (#12845). + // set", so the choice is recorded here in `source_state_id` (#12845). While a state source is + // set, ops keeps the answer: Clear History holds it back until its undo, and an action folding + // its steps can rename the row (#3536). if let Some(id) = st.source_state_id { - // Clear History holds a set source back with the states it took off: until its undo, the - // current state is the source, as before (#3536). - let row = if st.history.is_cleared() { st.history.brush_source() } else { st.history.row_of(id) }; - return row.map(HistorySource::State); + return st.history.row_of(id).or_else(|| st.history.brush_source()).map(HistorySource::State); } match st.open_snapshot { // The document as opened outlives the states, so a click still restores it (#12618). From 474d3ee06764eafe6d9d7a0933f0a2af4ca3a7b0 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Thu, 26 Nov 2026 22:23:26 +0100 Subject: [PATCH 3/6] test(history): cover the CLI report and the tools that share the source (#12845) The round-one review found that the new default reaches one more report than the local gates covered: apps/photocraft-cli/tests/it/orientation.rs compares the whole info JSON of a .pcraft with the same file re-saved, ignoring the path and the names it knows vary. historySource now names the open snapshot, which carries the document's own name, so the two documents differed. The test's own ignore-list grows by that name; the command's report is unchanged, and it still has to match shape for shape. Same review: the Art History Brush and Fill > History share the document's one source, so the new default is pinned for them too where the open snapshot and row 0 hold different pixels; a snapshot taken with replaceExisting under the document's own name drops the open snapshot (ids are never reused), which takes the default source with it; the panel's source column gets its first click test; and a source set on the row that is current when a play folds its steps is pinned through the play. The fill-keys help line and module header still promised the oldest state held, and two test comments said the same; they name the open snapshot now. --- apps/photocraft-cli/tests/it/orientation.rs | 5 ++ .../cmd/history_brush_default_source_tests.rs | 22 +++++++- .../engine-paint/src/cmd/fill_cmds/tests.rs | 2 +- crates/engine-paint/src/cmd/fill_key_cmds.rs | 8 ++- .../engine/tests/it/actions_single_history.rs | 19 +++++++ .../paint_in_history_brush_default_source.rs | 56 ++++++++++++++++++- .../src/panels/history_panel_select_tests.rs | 16 ++++++ 7 files changed, 122 insertions(+), 6 deletions(-) diff --git a/apps/photocraft-cli/tests/it/orientation.rs b/apps/photocraft-cli/tests/it/orientation.rs index e29549e3a7..628b8e7730 100644 --- a/apps/photocraft-cli/tests/it/orientation.rs +++ b/apps/photocraft-cli/tests/it/orientation.rs @@ -142,6 +142,11 @@ fn orientation_6_jpeg_converts_upright_and_rotates_back() { for v in [&mut ia, &mut ib] { v.as_object_mut().unwrap().remove("name"); v["snapshots"][0].as_object_mut().unwrap().remove("name"); + // The History Brush's default source names the open snapshot, which carries the document's + // own name as well (#12845); its shape still has to match. + if let Some(source) = v["historySource"].as_object_mut() { + source.remove("name"); + } } assert_eq!(ia, ib); let (pa, pb) = (d.join("a.png"), d.join("b.png")); diff --git a/crates/engine-core/src/cmd/history_brush_default_source_tests.rs b/crates/engine-core/src/cmd/history_brush_default_source_tests.rs index 034fbc680a..8b1b5a28b2 100644 --- a/crates/engine-core/src/cmd/history_brush_default_source_tests.rs +++ b/crates/engine-core/src/cmd/history_brush_default_source_tests.rs @@ -58,7 +58,8 @@ fn deleting_the_open_snapshot_leaves_no_source() { #[test] fn the_default_follows_automatically_create_first_snapshot() { - // Preferences are process-wide, so the loop ends on the default (on) for the other tests. + // Each session starts from the default and carries its own preferences: the option is set on + // the session that then opens the document. for first in [false, true] { let mut s = crate::session(); s.execute("history.options", json!({"automaticallyCreateFirstSnapshot": first})).unwrap(); @@ -99,3 +100,22 @@ fn without_an_open_snapshot_the_oldest_state_default_remains() { s.execute("history.setSource", json!({"state": 1})).unwrap(); assert_eq!(source(&s)["label"], "New Layer"); } + +/// `history.newSnapshot` with `replaceExisting` drops a snapshot of that name, so taking the +/// document's own name removes the open snapshot. Snapshot ids are never reused, so the new row is +/// not the open snapshot, and the default source is gone with it (#12845). +#[test] +fn a_replacement_named_after_the_document_takes_the_default_source_away() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let name = s.active().unwrap().doc.name.clone(); + s.execute("layer.new.layer", json!({})).unwrap(); + let fresh = s.execute("history.newSnapshot", json!({"name": name, "replaceExisting": true})).unwrap()["snapshot"].as_u64().unwrap(); + assert_ne!(fresh, 0, "the new row takes a fresh id"); + assert!(source(&s).is_null(), "no open snapshot, so no default source"); + // A snapshot or a state picked by hand still works. + s.execute("history.setSource", json!({"snapshot": fresh})).unwrap(); + assert_eq!(source(&s)["snapshot"], json!(fresh)); + s.execute("history.setSource", json!({"state": 0})).unwrap(); + assert_eq!(source(&s)["state"], 0); +} diff --git a/crates/engine-paint/src/cmd/fill_cmds/tests.rs b/crates/engine-paint/src/cmd/fill_cmds/tests.rs index 4d5169f707..9923e1ed19 100644 --- a/crates/engine-paint/src/cmd/fill_cmds/tests.rs +++ b/crates/engine-paint/src/cmd/fill_cmds/tests.rs @@ -167,7 +167,7 @@ fn history_pattern_and_content_aware() { // History: back to state 1 (after the white fill). s.execute(CMD, json!({"contents": "history", "state": 1})).unwrap(); assert_eq!(px(&s, 5, 5), [1.0; 4]); - // The default source is the oldest state: the empty layer. + // The default source is the open snapshot, the document as opened (the empty layer; #12845). s.execute(CMD, json!({"contents": "history"})).unwrap(); assert_eq!(px(&s, 5, 5)[3], 0.0); assert!(s.execute(CMD, json!({"contents": "history", "state": 999})).is_err()); diff --git a/crates/engine-paint/src/cmd/fill_key_cmds.rs b/crates/engine-paint/src/cmd/fill_key_cmds.rs index 4fcd5c64dc..9ca5e9fab2 100644 --- a/crates/engine-paint/src/cmd/fill_key_cmds.rs +++ b/crates/engine-paint/src/cmd/fill_key_cmds.rs @@ -1,6 +1,7 @@ //! Photoshop's fill keys (#249): ⌥⌫ fills the selection (or the whole layer) with the foreground //! colour, ⌘⌫ with the background colour, and with ⇧ added they preserve transparency. ⌘⌥⌫ fills -//! from history: the History Brush's source state (the oldest state still held). Photoshop +//! from history: the History Brush's source (by default its open snapshot, the document as +//! opened; #12845). Photoshop //! has no menu item for them; here they are ordinary commands with default shortcuts, so they //! appear in Edit › Keyboard Shortcuts (Tools) and can be rebound, recorded and driven by agents. //! @@ -156,7 +157,7 @@ pub fn specs() -> Vec { label: "Fill from History", menu: &[], shortcut: Some("Cmd+Alt+Backspace"), - params: r##"{"state":n? (default: the History Brush's source, the oldest state still held),"layer":id?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}?,"preserveTransparency":bool?}"##, + params: r##"{"state":n? (default: the History Brush's source, by default its open snapshot - the document as opened),"layer":id?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}?,"preserveTransparency":bool?}"##, enabled: fill_enabled, run: fill_history, journal: true, @@ -262,7 +263,8 @@ mod tests { s.execute("edit.fillForeground", json!({})).unwrap(); s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 6})).unwrap(); s.execute("edit.fillHistory", json!({})).unwrap(); - // The oldest state (the new, transparent layer) comes back inside the selection only. + // The open snapshot (the new, transparent document; #12845) comes back inside the + // selection only. assert_eq!(px(&s, 1, 1)[3], 0.0); assert_eq!(px(&s, 6, 1), [1.0, 0.0, 0.0, 1.0]); // A named state, and refused ones change nothing. diff --git a/crates/engine/tests/it/actions_single_history.rs b/crates/engine/tests/it/actions_single_history.rs index 0b66eb00ac..50282a6c80 100644 --- a/crates/engine/tests/it/actions_single_history.rs +++ b/crates/engine/tests/it/actions_single_history.rs @@ -238,6 +238,25 @@ fn in_action_undo_clear_restores_history_and_keeps_grouped_image_undo() { } } +/// A source set on the row that is current when a play folds its steps into one state: the play +/// moves that row, and Fill › History must still paint its exact pixels (#12845, review round two). +#[test] +fn source_on_the_current_row_survives_the_play_folding_its_steps() { + for single_state in [false, true] { + let mut s = history_control_session(single_state); + // `history_control_session` set the source on the row current then: the green document. + let green = s.active().unwrap().doc.layers[0].surface().unwrap().rgba(0, 0); + assert_eq!(green, [0.0, 1.0, 0.0, 1.0], "the source row is the green fill"); + s.actions_mut().list = only("Fill blue", vec![("edit.fill".into(), json!({"color": "#0000ff"}))]); + let result = s.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "singleState={single_state}: {result}"); + let after_the_play = s.active().unwrap().doc.layers[0].surface().unwrap().rgba(0, 0); + assert_eq!(after_the_play, [0.0, 0.0, 1.0, 1.0], "singleState={single_state}: the play filled blue"); + s.execute("edit.fill", json!({"contents": "history"})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers[0].surface().unwrap().rgba(0, 0), green, "singleState={single_state}: the source row still paints"); + } +} + /// A source held by Clear History becomes active on Undo Clear, with no additional image Undo row. #[test] fn cleared_intermediate_source_restores_exact_pixels_after_undo_redo() { diff --git a/crates/engine/tests/it/paint_in_history_brush_default_source.rs b/crates/engine/tests/it/paint_in_history_brush_default_source.rs index 8f6b7220e4..6a97c78e1d 100644 --- a/crates/engine/tests/it/paint_in_history_brush_default_source.rs +++ b/crates/engine/tests/it/paint_in_history_brush_default_source.rs @@ -90,7 +90,8 @@ fn without_the_open_snapshot_the_default_still_paints_the_oldest_state() { let mut s = Session::new(); s.execute("history.options", json!({"automaticallyCreateFirstSnapshot": false})).unwrap(); s.execute("file.new", json!({"width": 8, "height": 8, "depth": 16, "background": "white"})).unwrap(); - // Preferences are process-wide: put the default back before this test's documents are gone. + // Tidy-up only: preferences belong to the session, so this does not reach other tests; it + // leaves the option as the default it started from. let restore = |s: &mut Session| s.execute("history.options", json!({"automaticallyCreateFirstSnapshot": true})).unwrap(); assert!(s.active().unwrap().snapshots().is_empty()); let opened = rgba(&s, 3, 3); @@ -100,3 +101,56 @@ fn without_the_open_snapshot_the_default_still_paints_the_oldest_state() { assert_eq!(photocraft_engine::inspect::document(s.active().unwrap())["historySource"], json!({"state": 0, "label": "New"})); restore(&mut s); } + +/// The Art History Brush shares the document's one source, so its default is the open snapshot too. +/// The history has filled up here, so the oldest state held would paint a colour instead. (The +/// brush itself is 8-bit only, so this document is 8-bit.) +#[test] +fn the_art_history_brush_default_source_is_the_open_snapshot() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": 8, "background": "white"})).unwrap(); + let at_open = opened_pixel(&s); + s.active_mut().unwrap().history.max_states = 2; + for colour in ["#ff0000", "#00ff00", "#0000ff"] { + s.execute("paint.stroke", json!({"points": [[0, 3], [7, 3]], "size": 8, "hardness": 100, "color": colour})).unwrap(); + } + assert!(!close(rgba(&s, 3, 3), at_open), "the canvas holds the last stroke"); + s.execute("paint.artHistoryBrush", json!({"points": [[3, 3]], "size": 40, "hardness": 100})).unwrap(); + assert!(close(rgba(&s, 3, 3), at_open), "the open snapshot, not the trimmed row 0: {:?}", rgba(&s, 3, 3)); +} + +/// Fill > History reads the same source: with the history full its default fills the opened image +/// back, where the oldest state held would fill a colour. +#[test] +fn fill_from_history_uses_the_open_snapshot_after_the_history_fills_up() { + let mut s = session(); + let at_open = opened_pixel(&s); + s.active_mut().unwrap().history.max_states = 2; + for colour in ["#ff0000", "#00ff00", "#0000ff"] { + s.execute("edit.fill", json!({"color": colour})).unwrap(); + } + let st = s.active().unwrap(); + assert!(st.history.entries().first().is_some_and(|label| label == "Fill"), "row 0 is a fill state: {:?}", st.history.entries()); + s.execute("edit.fill", json!({"contents": "history"})).unwrap(); + assert!(close(rgba(&s, 3, 3), at_open), "the opened image comes back: {:?}", rgba(&s, 3, 3)); +} + +/// `history.newSnapshot` with `replaceExisting` drops the open snapshot by name, and snapshot ids +/// are never reused: the default is left empty and the brush refuses, as after a delete (#12845). +#[test] +fn a_replacement_snapshot_named_after_the_document_leaves_the_brush_without_a_source() { + let mut s = session(); + let name = s.active().unwrap().doc.name.clone(); + s.execute("paint.stroke", json!({"points": [[0, 3], [7, 3]], "size": 8, "hardness": 100, "color": "#ff0000"})).unwrap(); + let fresh = s.execute("history.newSnapshot", json!({"name": name, "replaceExisting": true})).unwrap()["snapshot"].as_u64().unwrap(); + assert_ne!(fresh, 0, "a fresh id, so the new row is not the open snapshot"); + assert!(photocraft_engine::inspect::document(s.active().unwrap())["historySource"].is_null()); + let before = rgba(&s, 3, 3); + let e = paint(&mut s, json!({})).unwrap_err().to_string(); + assert!(e.contains("source was deleted"), "{e}"); + assert_eq!(rgba(&s, 3, 3), before, "nothing painted"); + // Picking that snapshot as the source paints again. + s.execute("history.setSource", json!({"snapshot": fresh})).unwrap(); + paint(&mut s, json!({})).unwrap(); + assert!(close(rgba(&s, 3, 3), before), "the picked snapshot holds the red stroke: {:?}", rgba(&s, 3, 3)); +} diff --git a/crates/ui-egui/src/panels/history_panel_select_tests.rs b/crates/ui-egui/src/panels/history_panel_select_tests.rs index 3f6e0fbe78..dcdbd9bb37 100644 --- a/crates/ui-egui/src/panels/history_panel_select_tests.rs +++ b/crates/ui-egui/src/panels/history_panel_select_tests.rs @@ -438,6 +438,22 @@ fn the_source_icon_starts_on_the_open_snapshot_row() { assert!(matches!(history::source_key(app.session.active().unwrap()), Some(HistoryKey::State(_))), "a state row again"); } +/// #12845: the source column answers a click. Clicking a snapshot row's source box sends +/// `history.setSource {snapshot}` and the panel marks that row; a state row wins again when it is +/// clicked. +#[test] +fn a_click_on_a_snapshot_source_box_makes_it_the_source() { + let mut app = app(); + let state_row = state_key(&app, 1); + apply(&mut app, HistoryEvent::SetSource(state_row)); + assert!(matches!(history::source_key(app.session.active().unwrap()), Some(HistoryKey::State(_))), "a state row first"); + apply(&mut app, HistoryEvent::SetSource(HistoryKey::Snapshot(0))); + assert!(matches!(history::source_key(app.session.active().unwrap()), Some(HistoryKey::Snapshot(0))), "the open snapshot row"); + let current_row = current_key(&app); + apply(&mut app, HistoryEvent::SetSource(current_row)); + assert!(matches!(history::source_key(app.session.active().unwrap()), Some(HistoryKey::State(_))), "the current state row"); +} + /// Snapshot thumbnails belong to the snapshot's document (#6087): 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. #[test] From 6f5293e3c1356a376208bfeed2e0dd6ed4f0816c Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sat, 28 Nov 2026 13:58:05 +0100 Subject: [PATCH 4/6] test(history-brush): make the re-set source recovery checks prove the paint Both recovery checks compared the canvas after the History Brush click against a pixel the canvas already held: a paint command that returned Ok without touching pixels passed them, and the deleted-snapshot check looked only at the red channel. Turn the canvas blue after capturing the snapshot, assert the canvas changed, and compare all four channels with the captured pixel, so the assertions fail when the brush paints nothing. --- .../it/paint_in_history_brush_default_source.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/engine/tests/it/paint_in_history_brush_default_source.rs b/crates/engine/tests/it/paint_in_history_brush_default_source.rs index 6a97c78e1d..10a1467793 100644 --- a/crates/engine/tests/it/paint_in_history_brush_default_source.rs +++ b/crates/engine/tests/it/paint_in_history_brush_default_source.rs @@ -75,12 +75,16 @@ fn deleting_the_open_snapshot_leaves_the_default_without_a_source() { let e = paint(&mut s, json!({})).unwrap_err().to_string(); assert!(e.contains("source was deleted"), "{e}"); assert_eq!(rgba(&s, 3, 3), before, "nothing painted"); - // Setting a source makes it paint again: a snapshot of the red document. + // Setting a source makes it paint again: a snapshot of the red document, taken before the + // canvas turns blue so a paint that did nothing cannot pass by leaving the red in place. s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let red = rgba(&s, 3, 3); let snap = s.execute("history.newSnapshot", json!({"name": "Red"})).unwrap()["snapshot"].clone(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + assert!(!close(rgba(&s, 3, 3), red), "the canvas holds the blue fill before the click"); s.execute("history.setSource", json!({"snapshot": snap})).unwrap(); paint(&mut s, json!({})).unwrap(); - assert!(rgba(&s, 3, 3)[0] > 0.9, "{:?}", rgba(&s, 3, 3)); + assert!(close(rgba(&s, 3, 3), red), "the click restored the snapshot's red: {:?}", rgba(&s, 3, 3)); } /// With Automatically Create First Snapshot off there is no open snapshot: the default keeps @@ -149,7 +153,10 @@ fn a_replacement_snapshot_named_after_the_document_leaves_the_brush_without_a_so let e = paint(&mut s, json!({})).unwrap_err().to_string(); assert!(e.contains("source was deleted"), "{e}"); assert_eq!(rgba(&s, 3, 3), before, "nothing painted"); - // Picking that snapshot as the source paints again. + // Picking that snapshot as the source paints again: turn the canvas blue first, so a paint + // that did nothing cannot pass by leaving the red stroke in place. + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + assert!(!close(rgba(&s, 3, 3), before), "the canvas holds the blue fill before the click"); s.execute("history.setSource", json!({"snapshot": fresh})).unwrap(); paint(&mut s, json!({})).unwrap(); assert!(close(rgba(&s, 3, 3), before), "the picked snapshot holds the red stroke: {:?}", rgba(&s, 3, 3)); From 07b1589f00437e6b2310322614ca29e556ef7d6d Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sat, 28 Nov 2026 15:30:54 +0100 Subject: [PATCH 5/6] fix(history): a duplicated copy cites the state it starts on (#12845) CI was red on main's duplicate_history suite at this head: the suite came in with #14680 (8303d38c60), passes on main, and fails only together with this branch's open-snapshot default. #12845 makes the open snapshot the History Brush's default source, so Image > Duplicate reported its copy's source as the snapshot the copy was made from ({"snapshot":0,"label":"oracle copy"}) although the copy's History panel holds one "Duplicate Image" state: the suite wants {"state":0,"label":"Duplicate Image"}. The duplicate command now names that state as the copy's source instead of falling through to the ambient default, so documents that were created or opened keep the open-snapshot default (#12845's measured rows: history_brush_default_source 7/7, engine paint_in_history_brush_default_source 8/8, engine-core lib 3369 passed / 0 failed). To show the interaction red without merging main, main's image_cmds/duplicate_history_tests.rs is copied in byte for byte (blob ebd56be16e) and registered with the same #[path] mod line at the same place, so a later merge of main cannot conflict on it. Main's #14680 block around the pin is also taken verbatim from main, so the early-copied suite runs green here (red: 4 failed / 2 passed with the copied suite alone; green: 6 passed after the pin). --- crates/engine-core/src/cmd/image_cmds.rs | 12 ++ .../cmd/image_cmds/duplicate_history_tests.rs | 152 ++++++++++++++++++ crates/engine-core/src/doc_state.rs | 5 +- 3 files changed, 167 insertions(+), 2 deletions(-) create mode 100644 crates/engine-core/src/cmd/image_cmds/duplicate_history_tests.rs diff --git a/crates/engine-core/src/cmd/image_cmds.rs b/crates/engine-core/src/cmd/image_cmds.rs index ad5178fbae..943fbb5daf 100644 --- a/crates/engine-core/src/cmd/image_cmds.rs +++ b/crates/engine-core/src/cmd/image_cmds.rs @@ -1254,6 +1254,14 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { reidentify_copied_layers(&mut doc); let name = doc.name.clone(); let index = s.add_document(doc, None); + if let Some(st) = s.active_mut() { + st.history.set_current_label("Duplicate Image"); + // The copy has never been saved; closing it must ask before discarding its content. + st.saved_revision = 0; + // #12845: the copy starts on its own "Duplicate Image" state, so that state is its History + // Brush source: the snapshot the copy was made from is not the document as opened. + st.source_state_id = st.history.row_id(0); + } Ok(json!({ "document": index, "name": name })) } @@ -1350,6 +1358,10 @@ mod canvas_size_relative_percent_tests; #[cfg(test)] mod canvas_size_selection_tests; +#[cfg(test)] +#[path = "image_cmds/duplicate_history_tests.rs"] +mod duplicate_history_tests; + #[cfg(test)] #[path = "image_size_drops_selection_tests.rs"] mod image_size_drops_selection_tests; diff --git a/crates/engine-core/src/cmd/image_cmds/duplicate_history_tests.rs b/crates/engine-core/src/cmd/image_cmds/duplicate_history_tests.rs new file mode 100644 index 0000000000..ebd56be16e --- /dev/null +++ b/crates/engine-core/src/cmd/image_cmds/duplicate_history_tests.rs @@ -0,0 +1,152 @@ +//! #14597: a duplicate starts with its own history baseline and must be saved before closing. + +use serde_json::{Value, json}; +use std::sync::Arc; + +use crate::Session; + +fn layered_source(depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 8, "name": "oracle", "background": "white", "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap(); + s.edit("fill", |doc, _| { + let bounds = doc.bounds(); + let surface = doc.layers.last_mut().unwrap().surface_mut().unwrap(); + surface.fill_rect(bounds, &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +fn open_png(s: &mut Session) { + let img = photocraft_codecs::Image::from_u8(8, 8, photocraft_codecs::ChannelLayout::Rgb, vec![128; 8 * 8 * 3]).unwrap(); + let bytes = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + crate::file_cmds::open_bytes_as(s, "oracle.png", &bytes, None, Some("oracle.png".into())).unwrap(); +} + +fn history(s: &Session) -> Value { + crate::inspect::document(s.active().unwrap()) +} + +#[test] +fn layered_and_merged_copies_have_one_duplicate_state_under_their_named_snapshot() { + for depth in [8, 16, 32] { + for merged in [false, true] { + for name in [None, Some("My Dup")] { + let mut s = layered_source(depth); + let mut params = json!({"mergedOnly": merged}); + if let Some(name) = name { + params["name"] = json!(name); + } + s.execute("image.duplicate", params).unwrap(); + let copy = history(&s); + assert_eq!(copy["history"], json!(["Duplicate Image"]), "depth={depth}, merged={merged}, name={name:?}"); + assert_eq!(copy["snapshots"], json!([{"id": 0, "name": name.unwrap_or("oracle copy")}])); + assert_eq!(copy["canUndo"], false); + assert_eq!(copy["canRedo"], false); + assert_eq!(copy["historySource"], json!({"state": 0, "label": "Duplicate Image"})); + assert_eq!(s.active().unwrap().doc.layers.len(), if merged { 1 } else { 2 }); + } + } + } +} + +#[test] +fn unsaved_copies_refuse_ask_but_allow_explicit_discard() { + for depth in [8, 16, 32] { + for merged in [false, true] { + let mut s = layered_source(depth); + let source = s.active().unwrap().doc.clone(); + s.execute("image.duplicate", json!({"mergedOnly": merged})).unwrap(); + let copy = s.active().unwrap(); + let id = copy.doc.id; + assert!(copy.is_dirty(), "depth={depth}, merged={merged}"); + assert!(copy.path.is_none()); + assert_eq!(crate::inspect::session(&s)["documents"][1]["dirty"], true); + let err = s.execute("file.close", json!({"save": "ask"})).unwrap_err(); + assert!(matches!(err, crate::EngineError::BadParams { .. }), "{err}"); + assert!(err.to_string().contains("unsaved changes"), "{err}"); + assert_eq!(s.documents().len(), 2); + assert_eq!(s.active().unwrap().doc.id, id); + assert!(s.active().unwrap().is_dirty()); + s.execute("file.close", json!({"save": "discard"})).unwrap(); + assert_eq!(s.documents().len(), 1); + assert!(Arc::ptr_eq(&s.active().unwrap().doc, &source)); + } + } +} + +#[test] +fn duplicating_leaves_clean_and_dirty_sources_and_their_history_unchanged() { + for dirty in [false, true] { + for merged in [false, true] { + let mut s = crate::session(); + open_png(&mut s); + if dirty { + s.execute("layer.new.layer", json!({})).unwrap(); + } + let source = s.active().unwrap(); + assert_eq!(source.is_dirty(), dirty); + let before = crate::inspect::document(source); + let doc = source.doc.clone(); + let revisions = (source.revision, source.saved_revision); + s.execute("image.duplicate", json!({"mergedOnly": merged})).unwrap(); + let source = &s.documents()[0]; + assert_eq!(crate::inspect::document(source), before); + assert!(Arc::ptr_eq(&source.doc, &doc)); + assert_eq!((source.revision, source.saved_revision), revisions); + assert_eq!(source.is_dirty(), dirty); + } + } +} + +#[test] +fn new_and_opened_documents_keep_their_clean_initial_states_next_to_a_duplicate() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + open_png(&mut s); + s.execute("image.duplicate", json!({})).unwrap(); + for (source, label) in s.documents()[..2].iter().zip(["New", "Open"]) { + assert_eq!(source.history.entries(), [label]); + assert!(!source.is_dirty()); + } + assert_eq!(s.documents()[1].path.as_deref(), Some("oracle.png")); +} + +#[test] +fn editing_undoing_and_redoing_a_copy_preserves_its_unsaved_duplicate_baseline() { + for merged in [false, true] { + let mut s = layered_source(8); + s.execute("image.duplicate", json!({"mergedOnly": merged})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + assert_eq!(history(&s)["history"], json!(["Duplicate Image", "New Layer"])); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(history(&s)["history"], json!(["Duplicate Image"])); + assert!(s.active().unwrap().is_dirty()); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(history(&s)["history"], json!(["Duplicate Image", "New Layer"])); + assert!(s.active().unwrap().is_dirty()); + } +} + +#[test] +fn saving_a_duplicate_clears_its_dirty_mark_and_allows_ask_to_close() { + let dir = tempfile::tempdir().unwrap(); + for merged in [false, true] { + let path = dir.path().join(format!("copy-{merged}.pcraft")); + let mut s = layered_source(8); + s.execute("image.duplicate", json!({"mergedOnly": merged})).unwrap(); + assert!(s.active().unwrap().is_dirty()); + let saved_path = path.to_str().unwrap(); + crate::file_cmds::save_doc(&s.active().unwrap().doc, saved_path, None).unwrap(); + // Save As is shell-owned; finish the successful write through its engine API. + s.active_mut().unwrap().saved_to(saved_path.into()); + assert!(path.is_file()); + assert!(!s.active().unwrap().is_dirty()); + assert_eq!(s.active().unwrap().path.as_deref(), path.to_str()); + assert_eq!(history(&s)["history"], json!(["Duplicate Image"])); + s.execute("file.close", json!({"save": "ask"})).unwrap(); + assert_eq!(s.documents().len(), 1); + } +} diff --git a/crates/engine-core/src/doc_state.rs b/crates/engine-core/src/doc_state.rs index ea3fa3a0c1..5dd5edfdc1 100644 --- a/crates/engine-core/src/doc_state.rs +++ b/crates/engine-core/src/doc_state.rs @@ -64,8 +64,9 @@ pub struct DocState { /// the source is a state ([`DocState::source_state_id`]) or the default /// ([`crate::history_source_cmds::source`]). pub(crate) source_snapshot: Option, - /// The state id chosen as the History Brush's source (`history.setSource {state}`); `None`: no - /// state was set, so the default applies (#12845). The history keeps the state it names past its + /// The state id chosen as the History Brush's source (`history.setSource {state}`, or the state + /// `image.duplicate` starts its copy on, which is not the document as opened); `None`: no state + /// was set, so the default applies (#12845). The history keeps the state it names past its /// own time; Edit › Purge › Histories clears it along with the states it removed. pub(crate) source_state_id: Option, /// The snapshot holding the document as opened (`DocState::new`), `None` when History Options › From 0ba490828c6c5cdf875b37c4d63a50603c54be46 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sat, 28 Nov 2026 15:34:26 +0100 Subject: [PATCH 6/6] fix(history): keep the duplicate source pin clear of main's #14680 hunk The pin went inside duplicate(), which is where main's #14680 fix also ends the function: two different insertions at one base position conflict, so the PR would not have been mergeable and CI would have had no merge commit to test. image.duplicate now runs a wrapper that pins the copy's source, so the branch text inside that hunk is main's byte for byte and a later merge of main stays clean (throwaway merge against upstream/main: no conflicts). --- crates/engine-core/src/cmd/image_cmds.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/engine-core/src/cmd/image_cmds.rs b/crates/engine-core/src/cmd/image_cmds.rs index 943fbb5daf..c1f05357f5 100644 --- a/crates/engine-core/src/cmd/image_cmds.rs +++ b/crates/engine-core/src/cmd/image_cmds.rs @@ -1258,13 +1258,23 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { st.history.set_current_label("Duplicate Image"); // The copy has never been saved; closing it must ask before discarding its content. st.saved_revision = 0; - // #12845: the copy starts on its own "Duplicate Image" state, so that state is its History - // Brush source: the snapshot the copy was made from is not the document as opened. - st.source_state_id = st.history.row_id(0); } Ok(json!({ "document": index, "name": name })) } +/// `image.duplicate` with the History Brush source its copy starts on (#12845). `add_document` took +/// an open snapshot holding the document the copy was made from, so the open-snapshot default names +/// that row; the copy's own baseline is the "Duplicate Image" state, so that state is its source. +/// A wrapper, so the pin stays out of `duplicate`: main's #14680 fix ends that function, and a line +/// inside it would conflict when main is merged in. +fn duplicate_with_source(s: &mut Session, p: &Value) -> Result { + let out = duplicate(s, p)?; + if let Some(st) = s.active_mut() { + st.source_state_id = st.history.row_id(0); + } + Ok(out) +} + macro_rules! spec { ($id:literal, $label:literal, [$($m:literal),*], $params:literal, $en:expr, $run:expr) => { CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: true } @@ -1341,7 +1351,7 @@ pub fn specs() -> Vec { spec!("image.mode.bits8", "8 Bits/Channel", ["Image", "Mode"], "{}", has_doc, |s, _| convert_depth(s, SampleType::U8)), spec!("image.mode.bits16", "16 Bits/Channel", ["Image", "Mode"], "{}", has_doc, |s, _| convert_depth(s, SampleType::U16)), spec!("image.mode.bits32", "32 Bits/Channel", ["Image", "Mode"], "{}", has_doc, |s, _| convert_depth(s, SampleType::F32)), - spec!("image.duplicate", "Duplicate…", ["Image"], r##"{"name":str,"mergedOnly":bool=false}"##, has_doc, duplicate), + spec!("image.duplicate", "Duplicate…", ["Image"], r##"{"name":str,"mergedOnly":bool=false}"##, has_doc, duplicate_with_source), ] }