Merge #17138 into the merge queue batch

History Brush: the default source is the open snapshot (#12845)
This commit is contained in:
David Mann committed 2026-11-30 10:38:21 +01:00
commit 76c03b7dd9
18 files changed
+452 -25

No files matched your search

@@ -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"));
+2
View File
@@ -66,6 +66,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;
@@ -40,6 +40,9 @@ pub(super) fn purge(s: &mut Session, what: &str) -> Result<Value> {
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;
@@ -0,0 +1,121 @@
//! #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() {
// 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();
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");
}
/// `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);
}
@@ -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,38 @@ 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<HistorySource> {
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). 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 {
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).
// 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<Arc<Document>> {
match src {
HistorySource::State(i) => st.history.row_doc(i, &st.doc),
@@ -90,11 +116,15 @@ fn set_source(s: &mut Session, p: &Value) -> Result<Value> {
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);
}
}
+14 -1
View File
@@ -1382,6 +1382,19 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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 }
@@ -1458,7 +1471,7 @@ pub fn specs() -> Vec<CommandSpec> {
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),
]
}
@@ -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]
+17 -2
View File
@@ -68,8 +68,18 @@ pub struct DocState {
/// When Saving), so saving an unchanged document again doesn't add a duplicate row.
pub(crate) save_snapshot: Option<u64>,
/// 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<u64>,
/// 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<u64>,
/// 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<u64>,
/// 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.
@@ -134,7 +144,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() },
@@ -164,6 +175,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,
}
+3 -1
View File
@@ -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));
@@ -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());
+5 -3
View File
@@ -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<CommandSpec> {
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.
@@ -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() {
+1
View File
@@ -129,6 +129,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;
@@ -0,0 +1,163 @@
//! #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<Value> {
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, 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!(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
/// 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();
// 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);
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);
}
/// 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: 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));
}
@@ -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();
}
+2 -2
View File
@@ -58,8 +58,8 @@ fn current_key(app: &PhotocraftApp) -> Option<HistoryKey> {
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<HistoryKey> {
/// 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<HistoryKey> {
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)),
@@ -417,6 +417,43 @@ 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");
}
/// #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]
@@ -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) }?;