Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

History Brush source: snapshot sources, size check, purge and budget fixes

David Mann8435a4586f93
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index dd7e78475..6f04a8a65 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -503,7 +503,7 @@ fn build() -> Vec<CommandSpec> {
"Fill…",
["Edit"],
Some("Shift+F5"),
- r##"{"contents":"foreground|background|color|contentAware|pattern|history|black|gray|white"="color","color":"#rrggbb|[r,g,b,a]"=foreground (contents=color),"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"state":index? (contents=history; default the oldest state),"colorAdaptation":bool=true (contents=contentAware),"mode":"normal|multiply|…"="normal","opacity":0..100=100,"preserveTransparency":bool=false,"target":"pixels"|"mask"|"quickMask"|{"channel":i}?}"##,
+ r##"{"contents":"foreground|background|color|contentAware|pattern|history|black|gray|white"="color","color":"#rrggbb|[r,g,b,a]"=foreground (contents=color),"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"state":row?,"snapshot":id? (contents=history: a History panel row as history.setSource, redo rows last, or a snapshot; default the History Brush source),"colorAdaptation":bool=true (contents=contentAware),"mode":"normal|multiply|…"="normal","opacity":0..100=100,"preserveTransparency":bool=false,"target":"pixels"|"mask"|"quickMask"|{"channel":i}?}"##,
has_pixel_or_channel,
crate::fill_cmds::fill
),
diff --git a/crates/engine/src/fill_cmds.rs b/crates/engine/src/fill_cmds.rs
index ba3c92638..13bbe8e78 100644
--- a/crates/engine/src/fill_cmds.rs
+++ b/crates/engine/src/fill_cmds.rs
@@ -120,17 +120,8 @@ pub fn fill(s: &mut Session, p: &Value) -> Result<Value> {
Source::Pixels(area, photocraft_compose::pattern::render(&tile, &place, area))
}
"history" => {
- let explicit = match p.get("state") {
- None | Some(Value::Null) => None,
- Some(v) => Some(v.as_u64().ok_or_else(|| bad(format!("`state` must be a history state index, not {v}")))? as usize),
- };
- let past = st.history.past_len();
- let source_doc = match explicit {
- Some(i) if i == past => st.doc.clone(),
- Some(i) => st.history.state(i).ok_or_else(|| bad(format!("no history state {i} (0..={past})")))?,
- // The History Brush's source (History panel), by default the oldest state held.
- None => crate::history_source_cmds::source_doc(st)?,
- };
+ // A History panel row `state` or a `snapshot`, else the History Brush's source.
+ let source_doc = crate::history_source_cmds::paint_source(st, p, CMD)?;
let src = crate::channel_cmds::read_target_surface(source_doc.as_ref(), id, p)
.map_err(|_| EngineError::Other("the target did not exist (as pixels, a mask or a channel) in that history state".into()))?;
Source::Pixels(area, read_rgba(src, area, "reading Fill's history source")?)
diff --git a/crates/engine/src/history_source_cmds.rs b/crates/engine/src/history_source_cmds.rs
index 6457dd256..c84cbe840 100644
--- a/crates/engine/src/history_source_cmds.rs
+++ b/crates/engine/src/history_source_cmds.rs
@@ -1,14 +1,21 @@
//! The History Brush's source (#2966): the History panel's source column, at the left of every
-//! state, sets which state the History Brush (and Fill › History) restores from. Exactly one
+//! 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).
//!
-//! The 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
-//! off the history itself. Once it is deleted, or discarded by a new step after stepping back,
-//! there is no source until one is set, and the History Brush refuses to paint without an
-//! explicit `state`, as Photoshop does. (Photoshop keeps a source discarded by a new step in the
-//! list; that needs states outside the linear history, so here it is gone.)
+//! 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
+//! off the history itself. A snapshot source is kept by snapshot id ([`HistorySource::Snapshot`]),
+//! a separate namespace from the states. Once the source state or snapshot is deleted, or a redo
+//! state source is discarded by a new step, there is no source until one is set, and the History
+//! Brush refuses to paint without an explicit `state` or `snapshot`, as Photoshop does.
+//! (Photoshop keeps a source discarded by a new step in the list; that needs states outside the
+//! linear history, so here it is gone.) Edit › Purge › Histories keeps the snapshots (and a
+//! snapshot source) and resets a state source to the default.
+//!
+//! Rows: `state` is a History panel row everywhere here (this command, `paint.historyBrush`, Fill
+//! › History and `historySource` in `doc_inspect`): the states (0 = oldest), the current one, then
+//! the greyed redo states, the next redo first.
use std::sync::Arc;
@@ -24,41 +31,110 @@ fn bad(msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: CMD.into(), msg: msg.into() }
}
-/// The document the History Brush paints from when no `state` is passed: the source state set in
-/// the History panel, or the default (the oldest state held).
-pub(crate) fn source_doc(st: &DocState) -> Result<Arc<Document>> {
- st.history
- .brush_source()
- .and_then(|i| st.history.row_doc(i, &st.doc))
- .ok_or_else(|| EngineError::Other("the History Brush source state was deleted: set a new source in the History panel".into()))
+/// What the History Brush paints from: a History panel state row, or a snapshot by id. The two
+/// are separate, so snapshot 1 and state row 1 never stand for each other.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum HistorySource {
+ /// A History panel row ([`photocraft_ops::History::row_id`]).
+ State(usize),
+ /// A History panel snapshot ([`crate::history_cmds::Snapshot::id`]).
+ Snapshot(u64),
}
-/// `history.setSource {state}`: make a History panel row the History Brush's source. Rows are
-/// numbered as the panel lists them: the states (0 = oldest, then the current one), then the
-/// greyed states a step back left redoable.
-fn set_source(s: &mut Session, p: &Value) -> Result<Value> {
- if p.get("snapshot").is_some_and(|v| !v.is_null()) {
- return Err(EngineError::Other("History snapshots are not supported yet: set the source to a `state`".into()));
+/// The document's History Brush source, `None` once the source state or snapshot is gone.
+pub fn source(st: &DocState) -> Option<HistorySource> {
+ match st.source_snapshot {
+ Some(id) => st.snapshots.iter().any(|s| s.id == id).then_some(HistorySource::Snapshot(id)),
+ None => st.history.brush_source().map(HistorySource::State),
+ }
+}
+
+fn source_of(st: &DocState, src: HistorySource) -> Option<Arc<Document>> {
+ match src {
+ HistorySource::State(i) => st.history.row_doc(i, &st.doc),
+ HistorySource::Snapshot(id) => st.snapshots.iter().find(|s| s.id == id).map(|s| s.doc.clone()),
+ }
+}
+
+/// A `state` or `snapshot` param (`None` when neither is passed), checked against the document.
+fn parse(st: &DocState, p: &Value, cmd: &str) -> Result<Option<HistorySource>> {
+ let bad = |msg: String| EngineError::BadParams { cmd: cmd.into(), msg };
+ let get = |k: &str| p.get(k).filter(|v| !v.is_null());
+ let index = |k: &str, v: &Value| v.as_u64().ok_or_else(|| bad(format!("`{k}` must be a non-negative integer, not {v}")));
+ match (get("state"), get("snapshot")) {
+ (Some(_), Some(_)) => Err(bad("pass a `state` or a `snapshot`, not both".into())),
+ (Some(v), None) => {
+ let rows = st.history.entries().len().saturating_add(st.history.redo_labels().count());
+ let i = usize::try_from(index("state", v)?).ok().filter(|i| *i < rows);
+ let i = i.ok_or_else(|| bad(format!("no history state {v}: a History panel row (0..{rows}, the greyed redo rows last)")))?;
+ Ok(Some(HistorySource::State(i)))
+ }
+ (None, Some(v)) => {
+ let id = index("snapshot", v)?;
+ if !st.snapshots.iter().any(|s| s.id == id) {
+ return Err(bad(format!("no snapshot {id}")));
+ }
+ Ok(Some(HistorySource::Snapshot(id)))
+ }
+ (None, None) => Ok(None),
}
- let v = match p.get("state") {
- None | Some(Value::Null) => return Err(bad("pass the `state` to paint from (a History panel row, 0 = oldest)")),
- Some(v) => v,
+}
+
+/// The document the History Brush and Fill › History paint from: the `state` (History panel row)
+/// or `snapshot` passed, else the source set in the History panel. A source of another canvas
+/// size is refused rather than painting shifted pixels (after Crop, Canvas Size or Image Size):
+/// Photoshop refuses too, "the current canvas size does not match that of the history state"
+/// (its message as users report it; Adobe's help doesn't document the case).
+pub(crate) fn paint_source(st: &DocState, p: &Value, cmd: &str) -> Result<Arc<Document>> {
+ let doc = match parse(st, p, cmd)? {
+ Some(src) => source_of(st, src).ok_or_else(|| EngineError::Other("that history state or snapshot is gone".into()))?,
+ None => source(st)
+ .and_then(|src| source_of(st, src))
+ .ok_or_else(|| EngineError::Other("the History Brush source was deleted: set a new source in the History panel".into()))?,
};
+ if doc.size != st.doc.size {
+ return Err(EngineError::Other(format!(
+ "the current canvas size ({}×{}) does not match that of the History Brush source ({}×{}): set a source of this size in the History panel",
+ st.doc.size.width, st.doc.size.height, doc.size.width, doc.size.height
+ )));
+ }
+ Ok(doc)
+}
+
+/// `history.setSource {state}` or `{snapshot}`: make a History panel row or a snapshot the History
+/// Brush's source.
+fn set_source(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.active_mut().ok_or(EngineError::NoDocument)?;
- let rows = st.history.entries().len() + st.history.redo_labels().count();
- let i = v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(format!("`state` must be a History panel row (0..{rows}), not {v}")))?;
- if !st.history.set_brush_source(i) {
- return Err(bad(format!("no history state {i} (0..{rows})")));
+ match parse(st, p, CMD)? {
+ None => return Err(bad("pass the `state` (a History panel row, 0 = oldest) or the `snapshot` id to paint from")),
+ Some(HistorySource::State(i)) => {
+ if !st.history.set_brush_source(i) {
+ return Err(bad(format!("no history state {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_snapshot = Some(id);
+ }
}
Ok(source_json(st))
}
-/// The source as `doc_inspect` reports it: its History panel row and label (`null` when its state
-/// was deleted).
+/// The source as `doc_inspect` reports it: `{state,label}` (a History panel row) or
+/// `{snapshot,name}`; `null` once its state or snapshot is gone.
pub fn source_json(st: &DocState) -> Value {
- let Some(i) = st.history.brush_source() else { return Value::Null };
- let label = st.history.entries().into_iter().chain(st.history.redo_labels().map(str::to_string)).nth(i);
- json!({ "state": i, "label": label })
+ match source(st) {
+ None => Value::Null,
+ Some(HistorySource::State(i)) => {
+ let label = st.history.entries().into_iter().chain(st.history.redo_labels().map(str::to_string)).nth(i);
+ json!({ "state": i, "label": label })
+ }
+ Some(HistorySource::Snapshot(id)) => {
+ json!({ "snapshot": id, "name": st.snapshots.iter().find(|s| s.id == id).map(|s| s.name.clone()) })
+ }
+ }
}
fn has_doc(s: &Session) -> std::result::Result<(), String> {
@@ -71,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Set History Brush Source",
menu: &[],
shortcut: None,
- params: r##"{"state":index} (History panel row: 0 = oldest state, then the current one, then the greyed redo states; `snapshot` is not supported yet) → {state,label}: paint.historyBrush and Fill › History use this state when no `state` is passed"##,
+ params: r##"{"state":row} | {"snapshot":id} (state: a History panel row, 0 = oldest state, then the current one, then the greyed redo states; snapshot: a history.newSnapshot id) → {state,label} | {snapshot,name}: paint.historyBrush and Fill › History use this source when neither `state` nor `snapshot` is passed"##,
enabled: has_doc,
run: set_source,
journal: true,
@@ -183,6 +259,100 @@ mod tests {
assert!(close(rgb(&s), [1.0, 0.0, 0.0]), "{:?}", rgb(&s));
}
+ /// Edit › Purge › Histories clears the states: the source goes back to the default instead of
+ /// leaving every document without one (#3536 review).
+ #[test]
+ fn purging_histories_resets_a_state_source() {
+ let mut s = session();
+ s.execute(CMD, json!({"state": 1})).unwrap();
+ s.execute("edit.purge.histories", json!({})).unwrap();
+ assert_eq!(crate::inspect::document(s.active().unwrap())["historySource"], json!({"state": 0, "label": "Fill"}));
+ brush(&mut s, json!({}));
+ assert!(close(rgb(&s), [0.0, 1.0, 0.0]), "the only state left: {:?}", rgb(&s));
+ s.execute("edit.fill", json!({"contents": "history"})).unwrap();
+ }
+
+ /// After Canvas Size (or Crop, Image Size) the old states have another size: painting from one
+ /// would shift the pixels, so the History Brush and Fill › History refuse, as Photoshop does.
+ #[test]
+ fn a_source_of_another_canvas_size_is_refused() {
+ let mut s = session();
+ s.execute("image.canvasSize", json!({"width": 12, "height": 8, "anchor": "topLeft"})).unwrap();
+ for cmd in ["paint.historyBrush", "edit.fill"] {
+ for state in [json!(null), json!(0), json!(2)] {
+ let p =
+ if cmd == "edit.fill" { json!({"contents": "history", "state": state}) } else { json!({"points": [[4, 4]], "size": 40, "state": state}) };
+ let e = s.execute(cmd, p.clone()).unwrap_err().to_string();
+ assert!(e.contains("canvas size"), "{cmd} {p}: {e}");
+ }
+ }
+ assert_eq!(s.active().unwrap().history.entries().len(), 4, "nothing painted");
+ // The state after the resize is the same size: it paints.
+ s.execute(CMD, json!({"state": 3})).unwrap();
+ brush(&mut s, json!({}));
+ s.execute("edit.fill", json!({"contents": "history"})).unwrap();
+ // A snapshot of the old size is refused the same way.
+ let snap = s.execute("history.newSnapshot", json!({})).unwrap()["snapshot"].clone();
+ s.execute("image.canvasSize", json!({"width": 8, "height": 8, "anchor": "topLeft"})).unwrap();
+ s.execute(CMD, json!({"snapshot": snap})).unwrap();
+ assert!(s.execute("paint.historyBrush", json!({"points": [[4, 4]], "size": 40})).is_err());
+ }
+
+ /// `state` is a History panel row for the History Brush and Fill too: the greyed redo rows
+ /// count, as in `history.setSource` and `historySource`.
+ #[test]
+ fn the_brush_and_fill_take_redo_rows() {
+ let mut s = session();
+ assert!(s.undo());
+ brush(&mut s, json!({"state": 2}));
+ assert!(close(rgb(&s), [0.0, 1.0, 0.0]), "the greyed green state: {:?}", rgb(&s));
+ let mut s = session();
+ assert!(s.undo());
+ s.execute("edit.fill", json!({"contents": "history", "state": 2})).unwrap();
+ assert!(close(rgb(&s), [0.0, 1.0, 0.0]), "{:?}", rgb(&s));
+ assert!(s.execute("edit.fill", json!({"contents": "history", "state": 4})).is_err(), "no such row");
+ }
+
+ /// A snapshot as the source (the column on snapshot rows): kept by snapshot id, apart from the
+ /// state rows; deleting it leaves no source; Purge › Histories keeps it.
+ #[test]
+ fn a_snapshot_can_be_the_source() {
+ let mut s = session();
+ assert!(s.undo());
+ let snap = s.execute("history.newSnapshot", json!({"name": "Red"})).unwrap()["snapshot"].as_u64().unwrap();
+ assert_eq!(snap, 1, "snapshot 1, while state row 1 is the red fill too: they must not mix");
+ assert!(s.redo());
+ s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();
+ let r = s.execute(CMD, json!({"snapshot": snap})).unwrap();
+ assert_eq!(r, json!({"snapshot": 1, "name": "Red"}));
+ assert_eq!(crate::inspect::document(s.active().unwrap())["historySource"], r);
+ // No state is the source now: the default would be state 0 (white).
+ assert_eq!(s.active().unwrap().history.brush_source(), Some(0));
+ brush(&mut s, json!({}));
+ assert!(close(rgb(&s), [1.0, 0.0, 0.0]), "the snapshot paints: {:?}", rgb(&s));
+ s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();
+ s.execute("edit.fill", json!({"contents": "history"})).unwrap();
+ assert!(close(rgb(&s), [1.0, 0.0, 0.0]), "{:?}", rgb(&s));
+ // An explicit snapshot or state still wins.
+ brush(&mut s, json!({"state": 0}));
+ assert!(close(rgb(&s), [1.0, 1.0, 1.0]), "{:?}", rgb(&s));
+ brush(&mut s, json!({"snapshot": snap}));
+ assert!(close(rgb(&s), [1.0, 0.0, 0.0]), "{:?}", rgb(&s));
+ // Purging histories keeps the snapshots and so the source.
+ s.execute("edit.purge.histories", json!({})).unwrap();
+ assert_eq!(crate::inspect::document(s.active().unwrap())["historySource"], r);
+ // A state source replaces it.
+ s.execute(CMD, json!({"state": 0})).unwrap();
+ assert_eq!(crate::inspect::document(s.active().unwrap())["historySource"]["state"], 0);
+ s.execute(CMD, json!({"snapshot": snap})).unwrap();
+ // Deleting the snapshot leaves no source.
+ s.execute("history.deleteSnapshot", json!({"snapshot": snap})).unwrap();
+ assert!(crate::inspect::document(s.active().unwrap())["historySource"].is_null());
+ assert!(s.execute("paint.historyBrush", json!({"points": [[4, 4]], "size": 40})).is_err());
+ assert!(s.execute("edit.fill", json!({"contents": "history"})).is_err());
+ assert!(s.execute(CMD, json!({"snapshot": snap})).is_err(), "it is gone");
+ }
+
#[test]
fn bad_params_and_no_document_are_errors() {
assert!(matches!(Session::new().execute(CMD, json!({"state": 0})), Err(EngineError::NoDocument | EngineError::Disabled(..))));
@@ -197,7 +367,11 @@ mod tests {
json!({"state": "1"}),
json!({"state": [1]}),
json!({"snapshot": 0}),
+ json!({"snapshot": 1}),
+ json!({"snapshot": -1}),
+ json!({"snapshot": "Open"}),
json!({"snapshot": "Open", "state": 1}),
+ json!({"snapshot": 1, "state": 1}),
] {
assert!(s.execute(CMD, p.clone()).is_err(), "{p}");
}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index f8eea7ffe..85a8cf9a9 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -233,6 +233,9 @@ pub struct DocState {
pub snapshots: Vec<history_cmds::Snapshot>,
/// The id the next snapshot gets; ids are never reused, so deleting one keeps the others.
next_snapshot: 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`]).
+ pub(crate) source_snapshot: Option<u64>,
}
impl DocState {
@@ -276,6 +279,7 @@ impl DocState {
color_samplers: Vec::new(),
snapshots: Vec::new(),
next_snapshot: 1,
+ source_snapshot: None,
}
}
/// The selected layers in bottom-to-top document order, always including the active layer.
diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rs
index 6c06b1ea0..d8a19659a 100644
--- a/crates/engine/src/retouch_cmds.rs
+++ b/crates/engine/src/retouch_cmds.rs
@@ -612,17 +612,12 @@ fn healing_brush(s: &mut Session, p: &Value) -> Result<Value> {
Ok(clone_result(dmg, off, aligned, p, &stroke))
}
-/// The History Brush's source: the targeted surface (pixels, mask, channel) as it was in history
-/// state `state` (default: the source set in the History panel, `history.setSource`, else the
-/// oldest state still held, the "Open" snapshot unless trimmed).
+/// The History Brush's source: the targeted surface (pixels, mask, channel) as it was in History
+/// panel row `state` or snapshot `snapshot` (default: the source set in the History panel,
+/// `history.setSource`, else the oldest state still held, the "Open" state unless trimmed).
fn history_source(s: &Session, id: Option<LayerId>, p: &Value, cmd: &str) -> Result<Surface> {
let st = s.active().ok_or(EngineError::NoDocument)?;
- let explicit = p.get("state").and_then(Value::as_u64).map(|v| v as usize);
- let source_doc = match explicit {
- Some(i) if i == st.history.past_len() => st.doc.clone(),
- Some(i) => st.history.state(i).ok_or_else(|| bad(cmd, format!("no history state {i} (0..={})", st.history.past_len())))?,
- None => crate::history_source_cmds::source_doc(st)?,
- };
+ let source_doc = crate::history_source_cmds::paint_source(st, p, cmd)?;
crate::channel_cmds::read_target_surface(source_doc.as_ref(), id, p)
.cloned()
.map_err(|_| EngineError::Other("the target did not exist (as pixels, a mask or a channel) in that history state".into()))
@@ -1365,7 +1360,7 @@ pub fn specs() -> Vec<CommandSpec> {
menu: &[],
shortcut: None,
params: brush_params!(
- r#","state":index (into history.entries; default the History panel's source, history.setSource, else 0 = the oldest held state)"#
+ r#","state":row (a History panel row, as history.setSource: 0 = oldest state, then the current one, then the greyed redo states),"snapshot":id (a history.newSnapshot id; default: the History panel's source, else the oldest held state; a source of another canvas size is an error)"#
),
enabled: has_pixel_layer,
run: history_brush,
diff --git a/crates/ops/src/lib.rs b/crates/ops/src/lib.rs
index a4fd92031..2cffcce1c 100644
--- a/crates/ops/src/lib.rs
+++ b/crates/ops/src/lib.rs
@@ -255,10 +255,19 @@ impl History {
self.redo.clear();
}
+ /// Forget every past and redo state (Edit › Purge › Histories). The History Brush's source
+ /// goes back to the default, the oldest state held (now the current one): a source set on a
+ /// state the purge removed would otherwise leave no source.
pub fn clear(&mut self) {
self.undo.clear();
self.redo.clear();
self.tiles = None;
+ self.reset_brush_source();
+ }
+
+ /// Make the History Brush's source the default again (the oldest state held), pinning no state.
+ pub fn reset_brush_source(&mut self) {
+ self.brush_source = None;
}
/// Approximate unique pixel bytes held by history (tiles not shared with `current`).
@@ -306,8 +315,10 @@ impl History {
/// Keep pixel memory within [`History::max_bytes`]: the current document's tiles plus the
/// tiles only history holds (newest states first). The oldest undo states that don't fit are
- /// dropped; the most recent one is always kept so the last step can be undone. Returns how
- /// many states were dropped.
+ /// dropped; the most recent one is always kept so the last step can be undone. The History
+ /// Brush's source state ([`History::set_brush_source`]) is never dropped: its unique tiles are
+ /// counted first, and the newest states fill what remains. Returns how many states were
+ /// dropped.
pub fn trim(&mut self, current: &Document) -> usize {
self.trim_with(current, &[])
}
@@ -346,29 +357,35 @@ impl History {
for s in self.redo.iter().rev() {
total = total.saturating_add(tile_bytes(&s.doc, &mut seen));
}
+ // The History Brush's source is kept whatever its age, so its own tiles come first; the
+ // newest states then fill what remains of the budget (the most recent one always).
+ let source = self.brush_source.and_then(|id| self.undo.iter().position(|s| s.id == id));
+ if let Some(state) = source.and_then(|i| self.undo.get(i)) {
+ total = total.saturating_add(tile_bytes(&state.doc, &mut seen));
+ }
let mut keep = 0;
- for s in self.undo.iter().rev() {
+ for (i, s) in self.undo.iter().enumerate().rev() {
+ if Some(i) == source {
+ continue;
+ }
total = total.saturating_add(tile_bytes(&s.doc, &mut seen));
if total > self.max_bytes && keep >= 1 {
break;
}
keep += 1;
}
- let drop = self.undo.len() - keep;
- let mut pinned = None;
- for state in self.undo.drain(..drop) {
- // The History Brush's source is kept, as when states fall off the count limit.
- if Some(state.id) == self.brush_source {
- pinned = Some(state);
+ let mut kept = VecDeque::with_capacity(keep + 1);
+ let mut dropped = 0;
+ for (i, state) in std::mem::take(&mut self.undo).into_iter().enumerate().rev() {
+ if Some(i) == source || kept.len() < keep + usize::from(source.is_some_and(|j| j > i)) {
+ kept.push_front(state);
} else {
tiles.remove(&state.doc);
+ dropped += 1;
}
}
- let kept = usize::from(pinned.is_some());
- if let Some(state) = pinned {
- self.undo.push_front(state);
- }
- drop - kept
+ self.undo = kept;
+ dropped
}
}
@@ -524,6 +541,52 @@ mod tests {
assert_eq!(h.brush_source(), Some(0));
}
+ /// The pinned source counts against the byte budget: with room for three states, the
+ /// source and the two newest are kept, never more than the budget (#3536 review).
+ #[test]
+ fn byte_budget_counts_the_brush_source_first() {
+ let mut h = History::new(50);
+ let mut cur = Arc::new(base());
+ let tile = h.pixel_bytes(&cur);
+ assert!(tile > 0);
+ for i in 0..5 {
+ edit(&mut h, &mut cur, &format!("paint {i}"), |d| {
+ let id = d.layers[0].id;
+ d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]);
+ });
+ }
+ // Every state holds one tile of its own; the source is the oldest (Open).
+ assert!(h.set_brush_source(0));
+ h.max_bytes = tile * 4;
+ assert_eq!(h.trim(&cur), 2);
+ assert_eq!(h.entries(), ["Open", "paint 2", "paint 3", "paint 4"]);
+ assert!(h.pixel_bytes(&cur) <= h.max_bytes, "{} > {}", h.pixel_bytes(&cur), h.max_bytes);
+ assert_eq!(h.trim(&cur), 0, "it fits now");
+ // A new step trims to the budget again, still keeping the source.
+ edit(&mut h, &mut cur, "paint 5", |d| {
+ let id = d.layers[0].id;
+ d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[1.0, 0.0, 0.0, 1.0]);
+ });
+ assert_eq!(h.trim(&cur), 1);
+ assert_eq!(h.entries(), ["Open", "paint 3", "paint 4", "paint 5"]);
+ assert!(h.pixel_bytes(&cur) <= h.max_bytes);
+ assert_eq!(h.brush_source(), Some(0));
+ }
+
+ /// Edit › Purge › Histories clears every state: a source set on one of them goes back to the
+ /// default (the oldest state held) instead of leaving no source (#3536 review).
+ #[test]
+ fn clear_resets_the_brush_source() {
+ let mut h = History::new(50);
+ let mut cur = Arc::new(base());
+ edit(&mut h, &mut cur, "A", |d| d.name = "a".into());
+ edit(&mut h, &mut cur, "B", |d| d.name = "b".into());
+ assert!(h.set_brush_source(1));
+ h.clear();
+ assert_eq!(h.brush_source(), Some(0));
+ assert_eq!(h.row_doc(0, &cur).unwrap().name, "b");
+ }
+
#[test]
fn new_edit_clears_redo() {
let mut h = History::default();
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index a716c7e58..75eb730e4 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -3,6 +3,7 @@
use egui::{Align2, Color32, CornerRadius, Pos2, Rect, RichText, Sense, Stroke, StrokeKind, pos2, vec2};
use photocraft_color::BlendMode;
use photocraft_doc::{Layer, LayerContent, LayerId};
+use photocraft_engine::history_source_cmds::HistorySource;
use serde_json::{Value, json};
use crate::mask_thumbs_ui::MaskKind;
@@ -3091,7 +3092,7 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let entries = st.history.entries();
let current = entries.len() - 1;
let redo: Vec<String> = st.history.redo_labels().map(str::to_string).collect();
- let source = st.history.brush_source();
+ let source = photocraft_engine::history_source_cmds::source(st);
let selected_snap = selected_snapshot(ui.ctx(), st);
let ctx = ui.ctx().clone();
// A row dragged onto the trash (#5324); a drag that never saw its release must not outlive it.
@@ -3156,7 +3157,7 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
if is_redo { t.text_faint } else { t.icon },
);
ui.painter().text(pos2(rect.left() + 58.0, rect.center().y), Align2::LEFT_CENTER, &e, egui::FontId::proportional(12.0), color);
- if history_source_column(ui, rect, i, source == Some(i)) {
+ if history_source_column(ui, rect, egui::Id::new(("history-source", i)), source == Some(HistorySource::State(i))) {
set_source = Some(i);
}
if resp.clicked() && i != current {
@@ -3245,13 +3246,13 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
}
-/// The History panel's source column at the left of a state row: the History Brush icon on the
-/// source state; a click makes the row the source (`history.setSource`). It sits above the row, so
-/// the click doesn't also step to the state.
-fn history_source_column(ui: &mut egui::Ui, row: Rect, i: usize, is_source: bool) -> bool {
+/// The History panel's source column at the left of a state or snapshot row: the History Brush
+/// icon on the source; a click makes the row the source (`history.setSource`). It sits above the
+/// row, so the click doesn't also step to the state or snapshot.
+fn history_source_column(ui: &mut egui::Ui, row: Rect, salt: egui::Id, is_source: bool) -> bool {
let t = Tokens::get(ui.ctx());
let cell = Rect::from_min_size(row.min, vec2(24.0, row.height()));
- let resp = ui.interact(cell, ui.id().with(("history-source", i)), Sense::click()).on_hover_text(tl!("Sets the source for the history brush"));
+ let resp = ui.interact(cell, ui.id().with(salt), Sense::click()).on_hover_text(tl!("Sets the source for the history brush"));
if is_source {
icons::paint(ui, cell.shrink(4.0), icons::tool_icon(Tool::HistoryBrush), 12.0, t.icon);
} else if resp.hovered() {
@@ -3306,6 +3307,7 @@ fn snapshot_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, selected: Option<u6
let t = Tokens::get(ui.ctx());
let st = app.session.active()?;
let (doc_id, snaps) = (st.doc.id, st.snapshots.clone());
+ let source = photocraft_engine::history_source_cmds::source(st);
let live: Vec<u64> = snaps.iter().map(|s| s.id).collect();
// Per document: snapshot ids restart in each, and a tab switch must not carry the edit over.
let rename_id = egui::Id::new(("history-snapshot-rename", doc_id));
@@ -3353,7 +3355,9 @@ fn snapshot_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, selected: Option<u6
ui.painter().text(pos2(thumb.right() + 8.0, rect.center().y), Align2::LEFT_CENTER, &snap.name, egui::FontId::proportional(12.0), t.text);
}
}
- if resp.double_clicked() {
+ if history_source_column(ui, rect, egui::Id::new(("history-snapshot-source", snap.id)), source == Some(HistorySource::Snapshot(snap.id))) {
+ cmd = Some(("history.setSource", json!({"snapshot": snap.id})));
+ } else if resp.double_clicked() {
renaming = Some((snap.id, snap.name.clone()));
} else if resp.clicked() {
cmd = Some(("history.selectSnapshot", json!({"snapshot": snap.id})));
@@ -4801,6 +4805,27 @@ mod history_transform_tests {
assert_eq!(st.history.brush_source(), Some(1), "the clicked state is the source");
assert_eq!((st.history.entries().len(), st.history.can_redo()), (3, false), "and the document did not step back");
}
+
+ /// Snapshot rows have the source column too: a click makes the snapshot the source without
+ /// returning to it.
+ #[test]
+ fn history_source_column_on_a_snapshot_row() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 200, "height": 150})).unwrap();
+ app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ app.run("history.newSnapshot", json!({})).unwrap();
+ let mut h = Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state(|ui, app: &mut PhotocraftApp| history(app, ui), app);
+ h.run_steps(2);
+ // The snapshot row's cell is the only 24×38 one (the opening row has no column).
+ let cells: Vec<Rect> = h
+ .ctx
+ .viewport(|v| v.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).filter(|w| w.rect.size() == vec2(24.0, 38.0)).map(|w| w.rect).collect());
+ let cell = *cells.first().expect("a snapshot source cell");
+ click(&mut h, cell.center());
+ let st = h.state().session.active().unwrap();
+ assert_eq!(photocraft_engine::history_source_cmds::source(st), Some(HistorySource::Snapshot(1)));
+ assert_eq!(st.history.entries().len(), 2, "the document did not return to the snapshot");
+ }
}
#[cfg(test)]