Skip to content

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

History panel menu: review fixes (floating steps, cleared-state memory, clean undo, New Snapshot)

David Manne23840f51615
diff --git a/crates/engine/src/float_cmds.rs b/crates/engine/src/float_cmds.rs
index e5450b233..f17a163be 100644
--- a/crates/engine/src/float_cmds.rs
+++ b/crates/engine/src/float_cmds.rs
@@ -218,14 +218,17 @@ pub(crate) fn before_command(s: &mut Session, id: &str) -> Result<Option<Value>>
return Ok(None);
}
match id {
- "edit.undo" | "edit.stepBackward" => {
+ // Edit › Undo and the History panel's Step Backward step back over the move itself.
+ "edit.undo" | "edit.stepBackward" | "history.stepBackward" => {
st.floating = None;
Ok(Some(json!({"floating": "returned"})))
}
- // Returning to a History state puts the piece back too (it never reached the document),
- // and then moves the history: dropping it first would add a step and discard the redo
- // states the jump may be heading for.
- "history.selectState" => {
+ // Redo / Step Forward with nothing to step to leave the piece floating (and are refused).
+ "edit.redo" | "history.stepForward" if !st.history.can_redo() => Ok(None),
+ // Returning to a History state, or stepping forward to one, puts the piece back too (it
+ // never reached the document), and then moves the history: dropping it first would add
+ // a step and discard the redo states the step is heading for.
+ "history.selectState" | "edit.redo" | "history.stepForward" => {
st.floating = None;
Ok(None)
}
diff --git a/crates/engine/src/float_cmds/tests.rs b/crates/engine/src/float_cmds/tests.rs
index bb2ba5b91..d0766553f 100644
--- a/crates/engine/src/float_cmds/tests.rs
+++ b/crates/engine/src/float_cmds/tests.rs
@@ -65,6 +65,43 @@ fn any_other_command_drops_it_and_undo_puts_it_back() {
assert!(alpha(&st.doc, id, 12, 12) == 0.0 && alpha(&st.doc, id, 35, 20) == 1.0);
}
+/// The History panel's Step Backward / Step Forward treat a floating piece like Edit › Undo /
+/// Redo: no Move step is recorded and the redo states survive.
+#[test]
+fn history_panel_steps_put_the_piece_back_and_keep_the_redo_states() {
+ for back in ["edit.undo", "history.stepBackward"] {
+ let (mut s, id) = session();
+ let steps = s.active().unwrap().history.past_len();
+ s.execute("select.float", json!({"dx": 20, "dy": 0})).unwrap();
+ assert_eq!(s.execute(back, json!({})).unwrap()["floating"], json!("returned"), "{back}");
+ let st = s.active().unwrap();
+ assert!(floating(st).is_none() && alpha(&st.doc, id, 12, 12) == 1.0, "{back}: piece back");
+ assert_eq!((st.history.past_len(), st.history.can_redo()), (steps, false), "{back}: no Move step");
+ }
+ for forward in ["edit.redo", "history.stepForward"] {
+ let (mut s, id) = session();
+ // A redo state (the deselection), then a moved piece over the selection undo restored.
+ s.execute("select.deselect", json!({})).unwrap();
+ s.undo();
+ let steps = s.active().unwrap().history.past_len();
+ s.execute("select.float", json!({"dx": 20, "dy": 0})).unwrap();
+ s.execute(forward, json!({})).unwrap();
+ let st = s.active().unwrap();
+ assert!(floating(st).is_none(), "{forward}: piece back");
+ assert_eq!(alpha(&st.doc, id, 12, 12), 1.0, "{forward}: the move never reached the document");
+ assert!(st.doc.selection.is_none(), "{forward}: stepped forward to the deselection");
+ assert_eq!((st.history.past_len(), st.history.can_redo()), (steps + 1, false), "{forward}: no Move step");
+ // Nothing to step forward to: refused, and the piece keeps floating.
+ let (mut s, _) = session();
+ s.execute("select.float", json!({"dx": 20, "dy": 0})).unwrap();
+ let steps = s.active().unwrap().history.past_len();
+ assert!(s.execute(forward, json!({})).is_err(), "{forward}: nothing to redo");
+ let st = s.active().unwrap();
+ assert_eq!(floating(st).map(|f| f.offset), Some((20, 0)), "{forward}: still floating");
+ assert_eq!(st.history.past_len(), steps);
+ }
+}
+
#[test]
fn needs_a_selection_and_an_unlocked_pixel_layer() {
let mut s = Session::new();
diff --git a/crates/engine/src/history_menu_cmds.rs b/crates/engine/src/history_menu_cmds.rs
index 7154addbf..5d079f7cf 100644
--- a/crates/engine/src/history_menu_cmds.rs
+++ b/crates/engine/src/history_menu_cmds.rs
@@ -191,6 +191,43 @@ mod tests {
assert!(!s.is_enabled("edit.undo"), "the cleared states are gone");
}
+ #[test]
+ fn clear_history_and_its_undo_keep_a_saved_document_clean() {
+ let mut s = session();
+ let st = s.active_mut().unwrap();
+ st.saved_revision = st.revision;
+ s.execute("history.clear", json!({})).unwrap();
+ assert!(!s.active().unwrap().is_dirty(), "Clear History is no edit");
+ let revision = s.active().unwrap().revision;
+ assert!(s.execute("edit.undo", json!({})).unwrap().as_bool().unwrap());
+ let st = s.active().unwrap();
+ assert!(!st.is_dirty(), "nor is undoing it");
+ assert!(st.revision > revision, "the panels still see the list change");
+ // A modified document stays modified.
+ s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();
+ s.execute("history.clear", json!({})).unwrap();
+ s.execute("edit.undo", json!({})).unwrap();
+ assert!(s.active().unwrap().is_dirty());
+ }
+
+ #[test]
+ fn clear_history_leaves_other_documents_alone() {
+ let mut s = session();
+ let first = entries(&s);
+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ assert_eq!(s.active_index(), Some(1));
+ s.execute("history.clear", json!({})).unwrap();
+ assert_eq!(entries(&s).len(), 1);
+ let other = &s.documents()[0];
+ assert_eq!(other.history.entries(), first, "the other document keeps its states");
+ assert!(!other.history.is_cleared() && other.history.can_undo());
+ assert!(s.set_active(0));
+ assert!(s.is_enabled("history.clear") && s.is_enabled("history.stepBackward"));
+ s.execute("history.stepBackward", json!({})).unwrap();
+ assert_eq!(entries(&s).len(), first.len() - 1);
+ }
+
#[test]
fn history_menu_commands_refuse_without_a_document_and_ignore_odd_params() {
let mut s = Session::new();
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 36d52d0fb..cad74af31 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -844,6 +844,18 @@ impl Session {
let Some(st) = self.active_mut() else { return false };
st.coalesce = None;
match st.history.undo(st.doc.clone()) {
+ // Undo Clear History: the list comes back, the document is the same one. Not an
+ // edit: keep a clean document clean (the revision still moves for the panels).
+ Some((d, layers)) if Arc::ptr_eq(&d, &st.doc) => {
+ restore_target(st, layers);
+ let clean = !st.is_dirty();
+ st.revision += 1;
+ if clean {
+ st.saved_revision = st.revision;
+ }
+ st.last_damage = Some(photocraft_geom::Rect::EMPTY);
+ true
+ }
Some((mut d, layers)) => {
// Save As changes file identity outside history, just like the saved path.
if d.name != st.doc.name {
diff --git a/crates/ops/src/lib.rs b/crates/ops/src/lib.rs
index 5e8610ac1..b3898429c 100644
--- a/crates/ops/src/lib.rs
+++ b/crates/ops/src/lib.rs
@@ -91,10 +91,13 @@ impl History {
if self.max_bytes == 0 {
self.tiles = None;
}
+ // The tile counter also counted the cleared states this step forgets: rebuild it lazily.
+ if self.cleared.take().is_some() {
+ self.tiles = None;
+ }
if let Some(tiles) = &mut self.tiles {
tiles.add(&before);
}
- self.cleared = None;
let prev_label = std::mem::replace(&mut self.current_label, label.into());
let prev_layers = std::mem::replace(&mut self.current_layers, layers);
self.undo.push_back(HistoryState { label: prev_label, doc: before, layers: prev_layers });
@@ -195,6 +198,7 @@ impl History {
pub fn purge_last(&mut self) -> bool {
self.clear_redo();
if self.cleared.take().is_some() {
+ self.tiles = None;
return true;
}
let Some(state) = self.undo.pop_back() else { return false };
@@ -241,11 +245,26 @@ impl History {
self.cleared.is_some()
}
+ /// The undo and redo states history holds: the cleared ones while Clear History can still be
+ /// undone (the list is then empty), so memory figures and the byte budget count them.
+ fn held(&self) -> (&VecDeque<HistoryState>, &Vec<HistoryState>) {
+ match &self.cleared {
+ Some(c) => (&c.undo, &c.redo),
+ None => (&self.undo, &self.redo),
+ }
+ }
+
+ /// Every state history holds, cleared ones included (see [`Self::held`]).
+ fn held_states(&self) -> impl Iterator<Item = &HistoryState> {
+ let (undo, redo) = self.held();
+ undo.iter().chain(redo.iter())
+ }
+
/// Approximate unique pixel bytes held by history (tiles not shared with `current`).
pub fn unique_bytes(&self, current: &Document) -> usize {
let mut seen = HashSet::new();
tile_bytes(current, &mut seen);
- self.undo.iter().chain(self.redo.iter()).map(|s| tile_bytes(&s.doc, &mut seen)).sum()
+ self.held_states().map(|s| tile_bytes(&s.doc, &mut seen)).sum()
}
/// Pixel bytes of `current` plus the tiles only history holds (what [`History::trim`]
@@ -256,7 +275,7 @@ impl History {
}
let mut seen = HashSet::new();
let own = tile_bytes(current, &mut seen);
- self.undo.iter().chain(self.redo.iter()).fold(own, |n, s| n.saturating_add(tile_bytes(&s.doc, &mut seen)))
+ self.held_states().fold(own, |n, s| n.saturating_add(tile_bytes(&s.doc, &mut seen)))
}
/// Bytes of the tiles only `extra` documents hold (History panel snapshots, #4530): not
@@ -267,7 +286,7 @@ impl History {
}
let mut seen = HashSet::new();
tile_bytes(current, &mut seen);
- for s in self.undo.iter().chain(self.redo.iter()) {
+ for s in self.held_states() {
tile_bytes(&s.doc, &mut seen);
}
extra.iter().fold(0, |n, d| n.saturating_add(tile_bytes(d, &mut seen)))
@@ -281,7 +300,7 @@ impl History {
for d in keep {
tile_bytes(d, &mut seen);
}
- self.undo.iter().chain(self.redo.iter()).fold(0, |n, s| n.saturating_add(tile_bytes(&s.doc, &mut seen)))
+ self.held_states().fold(0, |n, s| n.saturating_add(tile_bytes(&s.doc, &mut seen)))
}
/// Keep pixel memory within [`History::max_bytes`]: the current document's tiles plus the
@@ -296,7 +315,13 @@ impl History {
/// snapshots, which outlive the states) against the budget too, so they can't take memory
/// beyond it unseen (#4530). The most recent state is still always kept.
pub fn trim_with(&mut self, current: &Document, pinned: &[&Document]) -> usize {
- if self.max_bytes == 0 || self.undo.len() <= 1 {
+ // While Clear History can be undone, the cleared states are what history holds: the
+ // oldest of them go first, as the list's would.
+ let (undo, redo) = match &mut self.cleared {
+ Some(c) => (&mut c.undo, &c.redo),
+ None => (&mut self.undo, &self.redo),
+ };
+ if self.max_bytes == 0 || undo.len() <= 1 {
return 0;
}
// An upper bound of what only `pinned` holds (some of it may be in states too): if the
@@ -310,7 +335,7 @@ impl History {
};
let tiles = self.tiles.get_or_insert_with(|| {
let mut tiles = tiles::Tiles::default();
- for state in self.undo.iter().chain(&self.redo) {
+ for state in undo.iter().chain(redo) {
tiles.add(&state.doc);
}
tiles
@@ -323,19 +348,19 @@ impl History {
for d in pinned {
total = total.saturating_add(tile_bytes(d, &mut seen));
}
- for s in self.redo.iter().rev() {
+ for s in redo.iter().rev() {
total = total.saturating_add(tile_bytes(&s.doc, &mut seen));
}
let mut keep = 0;
- for s in self.undo.iter().rev() {
+ for s in undo.iter().rev() {
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;
- for state in self.undo.drain(..drop) {
+ let drop = undo.len() - keep;
+ for state in undo.drain(..drop) {
tiles.remove(&state.doc);
}
drop
@@ -659,7 +684,7 @@ mod tests {
assert_eq!(counter.bytes_with(current), total as u128);
assert_eq!(h.pixel_bytes(current), total);
let mut seen = HashSet::new();
- let retained: usize = h.undo.iter().chain(&h.redo).map(|s| tile_bytes(&s.doc, &mut seen)).sum();
+ let retained: usize = h.held_states().map(|s| tile_bytes(&s.doc, &mut seen)).sum();
let empty = Document::new("empty", Size::new(1, 1), ColorMode::Rgb, SampleType::U8);
assert_eq!(counter.bytes_with(&empty), retained as u128);
}
@@ -924,6 +949,45 @@ mod tests {
assert!(!h.is_cleared());
}
+ #[test]
+ fn cleared_states_still_count_in_the_memory_figures_and_the_budget() {
+ let mut h = History::new(50);
+ let mut cur = Arc::new(base());
+ let tile = 256 * 256 * 4;
+ 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]);
+ });
+ }
+ cur = h.undo(cur).unwrap().0;
+ let (unique, pixels) = (h.unique_bytes(&cur), h.pixel_bytes(&cur));
+ assert_eq!(unique, 5 * tile, "four undo states and one redo state");
+ assert!(h.clear_states());
+ assert_eq!(h.unique_bytes(&cur), unique, "Clear History frees nothing while it can be undone");
+ assert_eq!(h.pixel_bytes(&cur), pixels);
+ assert_eq!(h.extra_bytes(&cur, &[&base()]), tile, "a snapshot's own tile, not the cleared states'");
+ assert_eq!(h.unique_bytes_besides(&cur, &[]), unique);
+ // The budget counts them too: the oldest cleared states go first.
+ h.max_bytes = 4 * tile;
+ assert_eq!(h.trim(&cur), 2);
+ assert_counter(&h, &cur);
+ assert_eq!(h.pixel_bytes(&cur), 4 * tile);
+ assert!(h.is_cleared() && h.past_len() == 0, "the list stays cleared");
+ h.undo(cur.clone()).unwrap();
+ assert_eq!(h.entries(), ["paint 1", "paint 2", "paint 3"], "undo brings back what the budget kept");
+ assert_eq!(h.redo_labels().collect::<Vec<_>>(), ["paint 4"]);
+ // A new step after Clear History forgets the cleared states, and the counter with them.
+ assert!(h.clear_states());
+ h.trim(&cur);
+ 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.unique_bytes(&cur), tile, "only the state before the new step");
+ assert_eq!(h.pixel_bytes(&cur), 2 * tile);
+ }
+
#[test]
fn a_new_step_or_purge_forgets_the_cleared_states() {
let mut h = History::new(10);
diff --git a/crates/ui-egui/src/history_menu_ui.rs b/crates/ui-egui/src/history_menu_ui.rs
index e0768f5ba..cf95f18a0 100644
--- a/crates/ui-egui/src/history_menu_ui.rs
+++ b/crates/ui-egui/src/history_menu_ui.rs
@@ -12,8 +12,9 @@ pub const ITEMS: &[(&str, Option<&str>)] = &[
("Step Forward", Some("history.stepForward")),
("Step Backward", Some("history.stepBackward")),
("---", None),
- // Snapshots are not implemented yet.
- ("New Snapshot…", None),
+ // Takes a Full Document snapshot at once; switches to the New Snapshot dialog when that
+ // lands (#3567).
+ ("New Snapshot…", Some("history.newSnapshot")),
("Delete", Some("history.deleteState")),
("Clear History", Some("history.clear")),
("New Document", Some("history.newDocument")),
@@ -108,7 +109,8 @@ mod tests {
let mut h = harness(app());
assert_eq!(states(&h), (4, 0));
assert!(is_disabled(&h, "Step Forward") && !is_disabled(&h, "Step Backward"));
- assert!(is_disabled(&h, "New Snapshot…") && is_disabled(&h, "History Options…"), "not built yet: greyed");
+ assert!(is_disabled(&h, "History Options…"), "not built yet: greyed");
+ assert!(!is_disabled(&h, "New Snapshot…"));
click(&mut h, "Step Backward");
assert_eq!(states(&h), (3, 1));
assert!(!is_disabled(&h, "Step Forward"));
@@ -146,11 +148,22 @@ mod tests {
let ctx = h.ctx.clone();
crate::transform_tool::begin(h.state_mut(), &ctx).unwrap();
h.run_steps(2);
- for label in ["Step Backward", "Delete", "Clear History", "New Document"] {
+ for label in ["Step Backward", "New Snapshot…", "Delete", "Clear History", "New Document"] {
assert!(is_disabled(&h, label), "{label}");
}
}
+ #[test]
+ fn new_snapshot_adds_a_snapshot_and_leaves_the_states() {
+ let mut h = harness(app());
+ let snaps = |h: &Harness<'static, PhotocraftApp>| h.state().session.active().unwrap().snapshots.len();
+ let (before, steps) = (snaps(&h), states(&h));
+ click(&mut h, "New Snapshot…");
+ assert!(!h.state().ui.status_error, "{}", h.state().ui.status);
+ assert_eq!(snaps(&h), before + 1);
+ assert_eq!(states(&h), steps, "a snapshot is no history step");
+ }
+
/// With a snapshot selected in the panel, Delete removes the snapshot and leaves the states,
/// as the panel's trash does (#5324); without one it removes the current state.
#[test]