Skip to content

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

History: Delete current state and New Document from the panel footer work (#1117) (#2039)

David Mann6fba13cd1d37
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 178861396..aa363a34f 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -1152,6 +1152,7 @@ fn build() -> Vec<CommandSpec> {
v.extend(crate::distort_cmds::specs());
v.extend(crate::analysis_cmds::specs());
v.extend(crate::notes_cmds::specs());
+ v.extend(crate::history_cmds::specs());
v.extend(crate::proof_sim::specs());
v.extend(crate::presets::specs());
v.extend(crate::document_preset_cmds::specs());
diff --git a/crates/engine/src/history_cmds.rs b/crates/engine/src/history_cmds.rs
new file mode 100644
index 000000000..652e2326b
--- /dev/null
+++ b/crates/engine/src/history_cmds.rs
@@ -0,0 +1,206 @@
+//! History panel actions beyond stepping (#1117): Delete (the trash button) and New Document (the
+//! "Create new document from current state" button). Stepping to a state is Edit › Undo / Redo.
+//!
+//! States are indexed like [`photocraft_ops::History::entries`]: 0 is the oldest state still
+//! held, the last index is the current document. Snapshots are not implemented.
+
+use serde_json::{Value, json};
+
+use crate::commands::{CommandSpec, int};
+use crate::image_cmds::for_each_layer;
+use crate::{EngineError, Result, Session};
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+/// The `state` param as an index into the active document's history entries, defaulting to the
+/// current state.
+fn state_index(s: &Session, cmd: &str, p: &Value) -> Result<(usize, usize)> {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let current = st.history.past_len();
+ let i = match p.get("state") {
+ None | Some(Value::Null) => current,
+ Some(_) => {
+ let v = int(p, "state").ok_or_else(|| bad(cmd, "`state` must be a number"))?;
+ usize::try_from(v).ok().filter(|i| *i <= current).ok_or_else(|| bad(cmd, format!("`state` = {v} is not a state (0..={current})")))?
+ }
+ };
+ Ok((i, current))
+}
+
+/// History panel › Delete: drop the state and every state after it, as Photoshop does in linear
+/// history. The document returns to the state before it, and the deleted steps can't be redone.
+/// The oldest state (the document as opened) can't be deleted.
+fn delete_state(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "history.deleteState";
+ let (i, current) = state_index(s, CMD, p)?;
+ if i == 0 {
+ return Err(bad(CMD, "the oldest state can't be deleted"));
+ }
+ // Step back to the state before `i`; the steps from `i` on are then redo states.
+ for _ in i..=current {
+ if !s.undo() {
+ return Err(EngineError::Other("the history can't step back right now".into()));
+ }
+ }
+ let st = s.active_mut().ok_or(EngineError::NoDocument)?;
+ st.history.clear_redo();
+ let entries = st.history.entries();
+ Ok(json!({ "states": entries.len(), "current": entries.last() }))
+}
+
+/// History panel › New Document: a new untitled document holding the document as it was at a
+/// state (the current one by default), named after that state, with a history of its own.
+fn new_document(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "history.newDocument";
+ let (i, current) = state_index(s, CMD, p)?;
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let src = if i == current { Some(st.doc.clone()) } else { st.history.state(i) };
+ let src = src.ok_or_else(|| bad(CMD, format!("state {i} is not held")))?;
+ let label = st.history.entries().get(i).cloned().unwrap_or_default();
+ let mut doc = (*src).clone();
+ doc.id = photocraft_doc::DocId::fresh();
+ doc.name = match p.get("name").and_then(Value::as_str) {
+ Some(n) if !n.trim().is_empty() => n.to_string(),
+ _ if !label.trim().is_empty() => label,
+ _ => format!("{} copy", doc.name),
+ };
+ for_each_layer(&mut doc.layers, &mut |l| l.id = photocraft_doc::LayerId::fresh());
+ let name = doc.name.clone();
+ let index = s.add_document(doc, None);
+ Ok(json!({ "document": index, "name": name }))
+}
+
+fn can_delete(s: &Session) -> std::result::Result<(), String> {
+ s.active().filter(|d| d.history.can_undo()).map(|_| ()).ok_or_else(|| "the oldest state can't be deleted".into())
+}
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ CommandSpec {
+ id: "history.deleteState",
+ label: "Delete State",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"state":index?} (History entry, 0 = oldest; default the current state) → {states,current}: removes the state and every later one"##,
+ enabled: can_delete,
+ run: delete_state,
+ journal: true,
+ },
+ CommandSpec {
+ id: "history.newDocument",
+ label: "New Document from State",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"state":index?,"name":str?} (History entry, 0 = oldest; default the current state) → {document,name}"##,
+ enabled: has_doc,
+ run: new_document,
+ journal: true,
+ },
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A document with three steps after Open: entries Open, New Layer, Fill, Fill.
+ fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 20, "height": 10})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap();
+ s
+ }
+
+ fn entries(s: &Session) -> Vec<String> {
+ s.active().unwrap().history.entries()
+ }
+
+ #[test]
+ fn delete_current_state_steps_back_and_drops_it() {
+ let mut s = session();
+ let before = entries(&s);
+ let prev_doc = s.active().unwrap().history.state(before.len() - 2).unwrap();
+ let r = s.execute("history.deleteState", json!({})).unwrap();
+ assert_eq!(r["states"], json!(before.len() - 1));
+ assert_eq!(entries(&s), before[..before.len() - 1].to_vec());
+ assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &prev_doc), "the document is the state before");
+ assert!(!s.active().unwrap().history.can_redo(), "the deleted state can't be redone");
+ assert!(s.execute("edit.redo", json!({})).is_err());
+ }
+
+ #[test]
+ fn delete_an_earlier_state_drops_it_and_every_later_one() {
+ let mut s = session();
+ let first = s.active().unwrap().history.state(0).unwrap();
+ s.execute("history.deleteState", json!({"state": 1})).unwrap();
+ assert_eq!(entries(&s), vec!["Open".to_string()]);
+ assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &first));
+ assert!(!s.active().unwrap().history.can_redo());
+ // Redo states after an undo go too.
+ let mut s = session();
+ s.execute("edit.undo", json!({})).unwrap();
+ s.execute("history.deleteState", json!({})).unwrap();
+ assert_eq!(entries(&s).len(), 2);
+ assert!(!s.active().unwrap().history.can_redo());
+ }
+
+ #[test]
+ fn delete_state_refuses_the_oldest_state_and_bad_params() {
+ let mut s = Session::new();
+ assert!(s.execute("history.deleteState", json!({})).is_err(), "no document");
+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
+ assert!(!s.is_enabled("history.deleteState"), "only the opening state");
+ assert!(s.execute("history.deleteState", json!({})).is_err());
+ let mut s = session();
+ let before = entries(&s);
+ for p in [json!({"state": 0}), json!({"state": -1}), json!({"state": 99}), json!({"state": "x"}), json!({"state": f64::MAX}), json!({"state": [1]})] {
+ assert!(s.execute("history.deleteState", p.clone()).is_err(), "{p}");
+ assert_eq!(entries(&s), before, "{p} changed nothing");
+ }
+ }
+
+ #[test]
+ fn new_document_from_a_state_copies_it_into_a_fresh_document() {
+ let mut s = session();
+ let src = s.active().unwrap().doc.clone();
+ let label = entries(&s).last().cloned().unwrap();
+ let r = s.execute("history.newDocument", json!({})).unwrap();
+ assert_eq!(s.documents().len(), 2);
+ assert_eq!(r["document"], json!(1));
+ assert_eq!(r["name"], json!(label), "named after the state");
+ let new = s.active().unwrap();
+ assert_eq!(new.doc.size, src.size);
+ assert_eq!(new.doc.layers.len(), src.layers.len());
+ assert_ne!(new.doc.id, src.id);
+ assert_eq!(new.history.entries().len(), 1, "a fresh history");
+ // An earlier state, with a chosen name; the source document is untouched.
+ s.set_active(0);
+ let before = entries(&s);
+ let open = s.active().unwrap().history.state(0).unwrap();
+ s.execute("history.newDocument", json!({"state": 0, "name": "Start"})).unwrap();
+ let new = s.active().unwrap();
+ assert_eq!(new.doc.name, "Start");
+ assert_eq!(new.doc.layers.len(), open.layers.len());
+ s.set_active(0);
+ assert_eq!(entries(&s), before);
+ }
+
+ #[test]
+ fn new_document_refuses_bad_params() {
+ let mut s = Session::new();
+ assert!(s.execute("history.newDocument", json!({})).is_err(), "no document");
+ let mut s = session();
+ for p in [json!({"state": -1}), json!({"state": 99}), json!({"state": "x"}), json!({"state": f64::NAN.to_string()})] {
+ assert!(s.execute("history.newDocument", p.clone()).is_err(), "{p}");
+ }
+ assert_eq!(s.documents().len(), 1);
+ }
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index e14d3d136..ed1c84a89 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -45,6 +45,7 @@ pub mod gallery_cmds;
pub mod gradient_fill_cmds;
pub mod group_view_cmds;
pub mod hidden_target;
+pub mod history_cmds;
pub mod image_cmds;
pub mod inspect;
pub mod jobs;
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 593d1674b..53b1e78e5 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -2347,15 +2347,29 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
}
});
+ let mut footer_cmd: Option<&str> = None;
if t.pro {
+ let can_delete = app.session.is_enabled("history.deleteState");
+ let can_new = app.session.is_enabled("history.newDocument");
widgets::panel_footer(ui, |ui| {
- let _ = icons::button(ui, "trash", 26.0, false, tl!("Delete current state"));
- let _ = icons::button(ui, "scan", 26.0, false, tl!("Create new snapshot"));
- let _ = icons::button(ui, "file-plus", 26.0, false, tl!("Create new document from current state"));
+ if ui.add_enabled_ui(can_delete, |ui| icons::button(ui, "trash", 26.0, false, tl!("Delete current state"))).inner.clicked() {
+ footer_cmd = Some("history.deleteState");
+ }
+ // Snapshots are not implemented yet: shown greyed, as Photoshop's footer has the button.
+ ui.add_enabled_ui(false, |ui| icons::button(ui, "scan", 26.0, false, tl!("Create new snapshot")));
+ if ui.add_enabled_ui(can_new, |ui| icons::button(ui, "file-plus", 26.0, false, tl!("Create new document from current state"))).inner.clicked() {
+ footer_cmd = Some("history.newDocument");
+ }
});
}
// An open Free Transform owns Undo (transform_tool::intercept): stepping the document's history under
// its box would leave it transforming pixels that changed.
+ if let Some(cmd) = footer_cmd.filter(|_| app.ui.transform.is_none())
+ && let Err(e) = app.run(cmd, json!({}))
+ {
+ app.ui.status = e;
+ app.ui.status_error = true;
+ }
if let Some(delta) = target.filter(|_| app.ui.transform.is_none()) {
let (cmd, n) = if delta < 0 { ("edit.undo", -delta) } else { ("edit.redo", delta) };
for _ in 0..n {
@@ -3332,6 +3346,42 @@ mod history_transform_tests {
}
}
}
+
+ /// The Photoshop-theme footer (#1117): trash deletes the current state, file-plus makes a
+ /// new document from it, and the snapshot button is greyed (snapshots aren't implemented).
+ #[test]
+ fn history_footer_buttons_run_their_commands() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 200, "height": 150})).unwrap();
+ app.run("layer.new.layer", json!({})).unwrap();
+ app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ let mut h = Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state(|ui, app: &mut PhotocraftApp| history(app, ui), app);
+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium);
+ h.state_mut().ui.theme = crate::theme::ThemeKind::ProMedium;
+ h.run_steps(3);
+ // Footer buttons are the only 26 pt squares; the bar lays them out right to left.
+ let buttons = |h: &Harness<'static, PhotocraftApp>| {
+ let mut b: Vec<(Rect, bool)> = h.ctx.viewport(|v| {
+ v.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).filter(|w| w.rect.size() == vec2(26.0, 26.0)).map(|w| (w.rect, w.enabled)).collect()
+ });
+ b.sort_by(|a, b| b.0.center().x.total_cmp(&a.0.center().x));
+ b
+ };
+ let b = buttons(&h);
+ assert_eq!(b.len(), 3, "trash, snapshot, new document: {b:?}");
+ assert!(b[0].1 && !b[1].1 && b[2].1, "only the snapshot button is disabled: {b:?}");
+ let docs = h.state().session.documents().len();
+ click(&mut h, b[2].0.center());
+ assert_eq!(h.state().session.documents().len(), docs + 1, "file-plus makes a new document");
+ h.state_mut().session.set_active(0);
+ h.run_steps(2);
+ let steps = h.state().session.active().unwrap().history.entries().len();
+ let b = buttons(&h);
+ click(&mut h, b[0].0.center());
+ let st = h.state().session.active().unwrap();
+ assert_eq!(st.history.entries().len(), steps - 1, "trash deletes the current state");
+ assert!(!st.history.can_redo(), "and it can't be redone");
+ }
}
#[cfg(test)]