PhotoCraft: An open-source, photo editor written by scratch in pure Rust
History panel: snapshots (camera button, snapshot rows) (#3545)
F4LCON973e7776ea4d
diff --git a/crates/engine/src/history_cmds.rs b/crates/engine/src/history_cmds.rsindex d9ca98f96..bb9cb3439 100644--- a/crates/engine/src/history_cmds.rs+++ b/crates/engine/src/history_cmds.rs@@ -2,14 +2,34 @@//! "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.+//! held, the last index is the current document.+//!+//! Snapshots (#2966, the camera button) are named copies of the document that outlive the+//! states: `history.newSnapshot` takes one, `history.selectSnapshot` brings it back as a new,+//! undoable state. They live on [`crate::DocState::snapshots`] for the session only, as in+//! Photoshop, and are addressed by an id that is never reused. Their tiles are shared+//! copy-on-write with the document and its history, and are not counted in the history's pixel+//! budget.++use std::sync::Arc;+use photocraft_doc::{Document, Layer, LayerContent};+use photocraft_ops::LayerTarget;use serde_json::{Value, json};use crate::commands::{CommandSpec, int};use crate::image_cmds::reidentify_copied_layers;use crate::{EngineError, Result, Session};+/// A History panel snapshot: the document as it was when taken, and the layers it targeted.+#[derive(Clone, Debug)]+pub struct Snapshot {+ pub id: u64,+ pub name: String,+ pub doc: Arc<Document>,+ pub layers: LayerTarget,+}+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }}@@ -72,6 +92,105 @@ fn new_document(s: &mut Session, p: &Value) -> Result<Value> {Ok(json!({ "document": index, "name": name }))}+/// The `snapshot` param: the index of the active document's snapshot with that id.+fn snapshot_index(s: &Session, cmd: &str, p: &Value) -> Result<usize> {+ let st = s.active().ok_or(EngineError::NoDocument)?;+ let id = p.get("snapshot").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "`snapshot` must be a snapshot id"))?;+ st.snapshots.iter().position(|snap| snap.id == id).ok_or_else(|| bad(cmd, format!("no snapshot {id}")))+}++/// A non-blank `name` param, trimmed; `None` when absent.+fn name_param(cmd: &str, p: &Value) -> Result<Option<String>> {+ match p.get("name") {+ None | Some(Value::Null) => Ok(None),+ Some(Value::String(n)) if !n.trim().is_empty() => Ok(Some(n.trim().to_string())),+ Some(_) => Err(bad(cmd, "`name` must be a non-empty string")),+ }+}++/// History panel › Create new snapshot (the camera button): a named copy of the document,+/// "Snapshot N" by default. `from` is the New Snapshot dialog's From: the full document (default),+/// its layers merged into one, or only the active layer. Not a history state.+fn new_snapshot(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "history.newSnapshot";+ let name = name_param(CMD, p)?;+ let from = match p.get("from") {+ None | Some(Value::Null) => "fullDocument",+ Some(Value::String(f)) if matches!(f.as_str(), "fullDocument" | "mergedLayers" | "currentLayer") => f.as_str(),+ Some(_) => return Err(bad(CMD, "`from` must be \"fullDocument\", \"mergedLayers\" or \"currentLayer\"")),+ };+ let st = s.active().ok_or(EngineError::NoDocument)?;+ let one_layer = |doc: &Document, layer: Layer| {+ let mut doc = doc.clone();+ let id = layer.id;+ doc.layers = vec![layer];+ (Arc::new(doc), LayerTarget { active: Some(id), selected: vec![id] })+ };+ let (doc, layers) = match from {+ "mergedLayers" => {+ let fmt = st.doc.pixel_format();+ one_layer(&st.doc, Layer::new("Merged Layers", LayerContent::Raster(crate::file_cmds::flattened(&st.doc, fmt))))+ }+ "currentLayer" => {+ let layer = st.active_layer.and_then(|id| st.doc.layer(id)).ok_or_else(|| bad(CMD, "no active layer"))?;+ one_layer(&st.doc, layer.clone())+ }+ _ => (st.doc.clone(), st.layer_target()),+ };+ let st = s.active_mut().ok_or(EngineError::NoDocument)?;+ let id = st.next_snapshot;+ st.next_snapshot = id.saturating_add(1);+ let name = name.unwrap_or_else(|| format!("Snapshot {id}"));+ st.snapshots.push(Snapshot { id, name: name.clone(), doc, layers });+ Ok(json!({ "snapshot": id, "name": name }))+}++/// Clicking a snapshot: the document returns to it as one new, undoable state named after it.+fn select_snapshot(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "history.selectSnapshot";+ let i = snapshot_index(s, CMD, p)?;+ // A background job is computing from the current state: it must not move under it.+ if s.active_job().is_some() {+ return Err(EngineError::Other("the document is busy with a background job".into()));+ }+ let snap = s.active().and_then(|st| st.snapshots.get(i).cloned()).ok_or(EngineError::NoDocument)?;+ s.edit(&snap.name, |doc, active| {+ // Keep the identity (colour state, views and caches are keyed by it) and the tab name.+ let (id, name) = (doc.id, doc.name.clone());+ *doc = (*snap.doc).clone();+ doc.id = id;+ doc.name = name;+ *active = snap.layers.active.filter(|l| doc.layer(*l).is_some()).or_else(|| doc.top_layer());+ Ok(())+ })?;+ let st = s.active_mut().ok_or(EngineError::NoDocument)?;+ if st.active_layer == snap.layers.active {+ st.selected_layers.clone_from(&snap.layers.selected);+ crate::fix_selection(st);+ }+ Ok(json!({ "snapshot": snap.id, "name": snap.name }))+}++/// Renaming a snapshot (double-click its name).+fn rename_snapshot(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "history.renameSnapshot";+ let i = snapshot_index(s, CMD, p)?;+ let name = name_param(CMD, p)?.ok_or_else(|| bad(CMD, "`name` is required"))?;+ let st = s.active_mut().ok_or(EngineError::NoDocument)?;+ let snap = st.snapshots.get_mut(i).ok_or_else(|| bad(CMD, "no such snapshot"))?;+ snap.name.clone_from(&name);+ Ok(json!({ "snapshot": snap.id, "name": name }))+}++/// Deleting a snapshot; the document and its history are unchanged.+fn delete_snapshot(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "history.deleteSnapshot";+ let i = snapshot_index(s, CMD, p)?;+ let st = s.active_mut().ok_or(EngineError::NoDocument)?;+ let snap = st.snapshots.remove(i);+ Ok(json!({ "snapshot": snap.id, "snapshots": st.snapshots.len() }))+}+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())}@@ -102,6 +221,46 @@ pub fn specs() -> Vec<CommandSpec> {run: new_document,journal: true,},+ CommandSpec {+ id: "history.newSnapshot",+ label: "New Snapshot",+ menu: &[],+ shortcut: None,+ params: r##"{"name":str?="Snapshot N","from":"fullDocument"|"mergedLayers"|"currentLayer"="fullDocument"} → {snapshot,name}: a named copy of the document for the session (not a history state)"##,+ enabled: has_doc,+ run: new_snapshot,+ journal: true,+ },+ CommandSpec {+ id: "history.selectSnapshot",+ label: "Select Snapshot",+ menu: &[],+ shortcut: None,+ params: r##"{"snapshot":id} → {snapshot,name}: the document returns to the snapshot as a new history state named after it"##,+ enabled: has_doc,+ run: select_snapshot,+ journal: true,+ },+ CommandSpec {+ id: "history.renameSnapshot",+ label: "Rename Snapshot",+ menu: &[],+ shortcut: None,+ params: r##"{"snapshot":id,"name":str} → {snapshot,name}"##,+ enabled: has_doc,+ run: rename_snapshot,+ journal: true,+ },+ CommandSpec {+ id: "history.deleteSnapshot",+ label: "Delete Snapshot",+ menu: &[],+ shortcut: None,+ params: r##"{"snapshot":id} → {snapshot,snapshots}: the document and its history are unchanged"##,+ enabled: has_doc,+ run: delete_snapshot,+ journal: true,+ },]}@@ -193,6 +352,114 @@ mod tests {assert_eq!(entries(&s), before);}+ /// The top layer's pixel at (1, 1).+ fn top_pixel(s: &Session) -> [f32; 4] {+ s.active().unwrap().doc.layers.last().unwrap().surface().unwrap().rgba(1, 1)+ }++ fn snapshots(s: &Session) -> Value {+ crate::inspect::document(s.active().unwrap())["snapshots"].clone()+ }++ #[test]+ fn new_snapshot_keeps_the_document_and_is_not_a_history_state() {+ let mut s = session();+ let before = entries(&s);+ let r = s.execute("history.newSnapshot", json!({})).unwrap();+ assert_eq!(r, json!({"snapshot": 1, "name": "Snapshot 1"}));+ assert_eq!(entries(&s), before, "taking a snapshot is not a step");+ let r = s.execute("history.newSnapshot", json!({"name": "Before green"})).unwrap();+ assert_eq!(r, json!({"snapshot": 2, "name": "Before green"}));+ assert_eq!(snapshots(&s), json!([{"id": 1, "name": "Snapshot 1"}, {"id": 2, "name": "Before green"}]));+ }++ #[test]+ fn select_snapshot_returns_to_it_as_one_undoable_state() {+ let mut s = session();+ s.execute("history.newSnapshot", json!({})).unwrap();+ let green = top_pixel(&s);+ let id = s.active().unwrap().doc.id;+ s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();+ let blue = top_pixel(&s);+ let before = entries(&s);+ s.execute("history.selectSnapshot", json!({"snapshot": 1})).unwrap();+ assert_eq!(top_pixel(&s), green);+ assert_eq!(entries(&s).len(), before.len() + 1, "one new state");+ assert_eq!(entries(&s).last().map(String::as_str), Some("Snapshot 1"));+ assert_eq!(s.active().unwrap().doc.id, id, "the same document");+ assert!(s.active().unwrap().active_layer.is_some());+ s.execute("edit.undo", json!({})).unwrap();+ assert_eq!(top_pixel(&s), blue, "undo leaves the snapshot");+ assert_eq!(snapshots(&s).as_array().unwrap().len(), 1, "snapshots are not history");+ }++ #[test]+ fn snapshots_from_merged_layers_or_the_current_layer() {+ let mut s = session();+ assert_eq!(s.active().unwrap().doc.layers.len(), 2);+ s.execute("history.newSnapshot", json!({"from": "mergedLayers"})).unwrap();+ s.execute("history.newSnapshot", json!({"from": "currentLayer"})).unwrap();+ s.execute("history.newSnapshot", json!({"from": "fullDocument"})).unwrap();+ s.execute("history.selectSnapshot", json!({"snapshot": 1})).unwrap();+ let doc = s.active().unwrap().doc.clone();+ assert_eq!(doc.layers.len(), 1, "merged into one layer");+ assert_eq!(doc.layers[0].surface().unwrap().rgba(1, 1), [0.0, 1.0, 0.0, 1.0], "the visible result");+ s.execute("history.selectSnapshot", json!({"snapshot": 2})).unwrap();+ assert_eq!(s.active().unwrap().doc.layers.len(), 1, "only the active layer");+ s.execute("history.selectSnapshot", json!({"snapshot": 3})).unwrap();+ assert_eq!(s.active().unwrap().doc.layers.len(), 2);+ }++ #[test]+ fn rename_and_delete_snapshots_keep_the_other_ids() {+ let mut s = session();+ for _ in 0..3 {+ s.execute("history.newSnapshot", json!({})).unwrap();+ }+ s.execute("history.renameSnapshot", json!({"snapshot": 2, "name": "Lesson start"})).unwrap();+ s.execute("history.deleteSnapshot", json!({"snapshot": 1})).unwrap();+ assert_eq!(snapshots(&s), json!([{"id": 2, "name": "Lesson start"}, {"id": 3, "name": "Snapshot 3"}]));+ let r = s.execute("history.newSnapshot", json!({})).unwrap();+ assert_eq!(r["snapshot"], json!(4), "ids are never reused");+ }++ #[test]+ fn snapshot_commands_refuse_bad_params() {+ let mut s = Session::new();+ for (cmd, p) in [+ ("history.newSnapshot", json!({})),+ ("history.selectSnapshot", json!({"snapshot": 1})),+ ("history.renameSnapshot", json!({"snapshot": 1, "name": "x"})),+ ("history.deleteSnapshot", json!({"snapshot": 1})),+ ] {+ assert!(s.execute(cmd, p).is_err(), "{cmd}: no document");+ }+ let mut s = session();+ s.execute("history.newSnapshot", json!({})).unwrap();+ let (before, snaps) = (entries(&s), snapshots(&s));+ for (cmd, p) in [+ ("history.newSnapshot", json!({"from": "everything"})),+ ("history.newSnapshot", json!({"from": 3})),+ ("history.newSnapshot", json!({"name": 7})),+ ("history.selectSnapshot", json!({})),+ ("history.selectSnapshot", json!({"snapshot": 99})),+ ("history.selectSnapshot", json!({"snapshot": -1})),+ ("history.selectSnapshot", json!({"snapshot": "1"})),+ ("history.selectSnapshot", json!({"snapshot": f64::MAX})),+ ("history.renameSnapshot", json!({"snapshot": 1})),+ ("history.renameSnapshot", json!({"snapshot": 1, "name": " "})),+ ("history.renameSnapshot", json!({"snapshot": 99, "name": "x"})),+ ("history.deleteSnapshot", json!({"snapshot": 99})),+ ("history.deleteSnapshot", json!({"snapshot": [1]})),+ ] {+ assert!(s.execute(cmd, p.clone()).is_err(), "{cmd} {p}");+ assert_eq!((entries(&s), snapshots(&s)), (before.clone(), snaps.clone()), "{cmd} {p} changed nothing");+ }+ // Current Layer needs an active layer.+ s.execute("select.deselectLayers", json!({})).unwrap();+ assert!(s.execute("history.newSnapshot", json!({"from": "currentLayer"})).is_err());+ }+#[test]fn new_document_refuses_bad_params() {let mut s = Session::new();diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rsindex 86aaf48d7..d0b2a72e9 100644--- a/crates/engine/src/inspect.rs+++ b/crates/engine/src/inspect.rs@@ -40,6 +40,7 @@ pub fn document(d: &DocState) -> Value {"selectionBounds": doc.selection.as_ref().map(|s| { let r = s.content_bounds(); [r.x0, r.y0, r.width() as i32, r.height() as i32] }),"layers": doc.layers.iter().rev().map(|l| layer_sel(l, &selected)).collect::<Vec<_>>(),"history": d.history.entries(),+ "snapshots": d.snapshots.iter().map(|snap| json!({"id": snap.id, "name": snap.name})).collect::<Vec<_>>(),"canUndo": d.history.can_undo(),"canRedo": d.history.can_redo(),"revision": d.revision,diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 035cfabef..21f3c8adb 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -217,6 +217,11 @@ pub struct DocState {/// pixel coordinates. Per-document view state: discarded when the document closes, never saved/// to `.pcraft` or PSD, and not a history step.pub color_samplers: Vec<[f64; 2]>,+ /// History panel snapshots, oldest first (`history.newSnapshot`, #2966). Kept for the+ /// session only, as in Photoshop: not history states, and not saved with the document.+ 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,}impl DocState {@@ -243,6 +248,8 @@ impl DocState {show_only: None,floating: None,color_samplers: Vec::new(),+ snapshots: Vec::new(),+ next_snapshot: 1,}}/// The selected layers in bottom-to-top document order, always including the active layer.diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex fe7c8678a..42e81d024 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -564,6 +564,9 @@ pub struct PhotocraftApp {pub fps: f32,last_frame_time: f64,thumbs: HashMap<(photocraft_doc::LayerId, u8), (u64, egui::TextureHandle)>,+ /// History snapshot thumbnails by (document, snapshot id): a snapshot never changes, so each+ /// is made once (`snapshot_thumb`, #2966).+ snapshot_thumbs: HashMap<(DocId, u64), egui::TextureHandle>,/// Snapshots whose live layer/mask keys were last used to prune thumbnail handles.thumb_documents: Vec<(DocId, std::sync::Weak<Document>)>,/// Content bounds cached per (key, revision): scanning a 36 MP layer every frame cost ~77 ms.@@ -741,6 +744,7 @@ impl PhotocraftApp {fps: 0.0,last_frame_time: 0.0,thumbs: HashMap::new(),+ snapshot_thumbs: HashMap::new(),thumb_documents: Vec::new(),bounds_cache: HashMap::new(),proxy: None,@@ -1872,6 +1876,29 @@ impl PhotocraftApp {self.store_thumb(ctx, key, rev, img)}+ /// The History panel thumbnail of snapshot `snap` of document `doc` (#2966): its composite,+ /// centred in a square. Thumbnails of `doc`'s snapshots not in `live` are dropped.+ pub fn snapshot_thumb(&mut self, ctx: &egui::Context, doc: DocId, snap: &photocraft_engine::history_cmds::Snapshot, live: &[u64]) -> egui::TextureId {+ self.snapshot_thumbs.retain(|(d, id), _| *d != doc || live.contains(id));+ if let Some(tex) = self.snapshot_thumbs.get(&(doc, snap.id)) {+ return tex.id();+ }+ let comp = photocraft_compose::thumbnail(&snap.doc, 56);+ let (w, h) = (comp.width as usize, comp.height as usize);+ let side = w.max(h);+ let (ox, oy) = ((side - w) / 2, (side - h) / 2);+ let mut px = vec![egui::Color32::TRANSPARENT; side * side];+ for (i, &[r, g, b, a]) in comp.pixels.as_chunks::<4>().0.iter().enumerate() {+ if let Some(out) = px.get_mut((i / w + oy) * side + i % w + ox) {+ *out = egui::Color32::from_rgba_unmultiplied(r, g, b, a);+ }+ }+ let tex = ctx.load_texture(format!("snapshot-{}", snap.id), egui::ColorImage::new([side, side], px), egui::TextureOptions::LINEAR);+ let id = tex.id();+ self.snapshot_thumbs.insert((doc, snap.id), tex);+ id+ }+pub fn mask_thumb(&mut self, ctx: &egui::Context, doc: &Document, id: photocraft_doc::LayerId, mask: &photocraft_doc::LayerMask) -> egui::TextureId {let rev = surface_fingerprint(&mask.surface) ^ (doc.size.width as u64) << 40;let key = (id, mask_thumbs_ui::THUMB_MASK);diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex 2667f74af..e30047aa6 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -2874,12 +2874,16 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {ui.painter().text(pos2(thumb.right() + 8.0, rect.center().y), Align2::LEFT_CENTER, &doc.name, egui::FontId::proportional(12.0), t.text);ui.painter().line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, t.separator));}+ let mut snap_cmd = None;let mut target: Option<isize> = None;let all = entries.iter().map(|e| (e.clone(), false)).chain(redo.iter().map(|e| (e.clone(), true)));// The dock gives History a fixed height: the rows scroll above the footer.let footer = if t.pro { widgets::footer_height(ui) + ui.spacing().item_spacing.y } else { 0.0 };let max_h = (ui.available_height() - footer).max(40.0);egui::ScrollArea::vertical().id_salt("history-rows").max_height(max_h).auto_shrink([false, false]).show(ui, |ui| {+ // Snapshots head the list and scroll with the states, so many of them never push the+ // footer out of a short dock.+ snap_cmd = snapshot_rows(app, ui);for (i, (e, is_redo)) in all.enumerate() {let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click());if i == current {@@ -2917,8 +2921,10 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {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")));+ let can_snap = app.session.is_enabled("history.newSnapshot");+ if ui.add_enabled_ui(can_snap, |ui| icons::button(ui, "scan", 26.0, false, tl!("Create new snapshot"))).inner.clicked() {+ footer_cmd = Some("history.newSnapshot");+ }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");}@@ -2926,8 +2932,10 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {}// 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!({}))+ // Selecting a snapshot changes the document, so it waits for an open transform like the rows.+ let snap_cmd = snap_cmd.filter(|(cmd, _)| *cmd != "history.selectSnapshot" || app.ui.transform.is_none());+ if let Some((cmd, p)) = footer_cmd.map(|c| (c, json!({}))).filter(|_| app.ui.transform.is_none()).or(snap_cmd)+ && let Err(e) = app.run(cmd, p){app.ui.status = e;app.ui.status_error = true;@@ -2942,6 +2950,79 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {}}+/// The History panel's snapshot rows (#2966), under the opening row, each with its thumbnail and+/// name: a click returns to the snapshot (a new state), a double-click or right-click › Rename…+/// edits the name in place (Enter or a click elsewhere keeps it, Escape cancels), and+/// right-click › Delete removes it. Returns the command a row asks for.+fn snapshot_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> Option<(&'static str, Value)> {+ let t = Tokens::get(ui.ctx());+ let st = app.session.active()?;+ let (doc_id, snaps) = (st.doc.id, st.snapshots.clone());+ 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));+ let mut renaming: Option<(u64, String)> = ui.data(|d| d.get_temp(rename_id)).flatten();+ let mut cmd = None;+ let ctx = ui.ctx().clone();+ for snap in &snaps {+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 38.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &snap.name));+ if resp.hovered() {+ ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5));+ }+ let thumb = Rect::from_min_size(pos2(rect.left() + 28.0, rect.center().y - 14.0), vec2(28.0, 28.0));+ widgets::checker(ui.painter(), thumb, 4.0);+ let tex = app.snapshot_thumb(&ctx, doc_id, snap, &live);+ ui.painter().image(tex, thumb, Rect::from_min_max(egui::Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);+ ui.painter().rect_stroke(thumb, 0.0, Stroke::new(1.0, t.separator), StrokeKind::Outside);+ match renaming.as_mut().filter(|(id, _)| *id == snap.id) {+ Some((_, text)) => {+ let field = Rect::from_min_max(pos2(thumb.right() + 6.0, rect.center().y - 10.0), pos2(rect.right() - 6.0, rect.center().y + 10.0));+ let r = ui.put(field, egui::TextEdit::singleline(text));+ if r.lost_focus() {+ if !ui.input(|i| i.key_pressed(egui::Key::Escape)) {+ cmd = Some(("history.renameSnapshot", json!({"snapshot": snap.id, "name": text.clone()})));+ }+ renaming = None;+ } else if !r.has_focus() {+ // Starting to rename: focus the field with the whole name selected, so typing+ // replaces it (Photoshop).+ r.request_focus();+ if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), r.id) {+ let all = egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(text.chars().count()));+ state.cursor.set_char_range(Some(all));+ state.store(ui.ctx(), r.id);+ }+ }+ }+ None => {+ 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() {+ renaming = Some((snap.id, snap.name.clone()));+ } else if resp.clicked() {+ cmd = Some(("history.selectSnapshot", json!({"snapshot": snap.id})));+ }+ resp.context_menu(|ui| {+ if ui.button(tl!("Rename…")).clicked() {+ renaming = Some((snap.id, snap.name.clone()));+ ui.close();+ }+ if ui.button(tl!("Delete")).clicked() {+ cmd = Some(("history.deleteSnapshot", json!({"snapshot": snap.id})));+ ui.close();+ }+ });+ }+ if !snaps.is_empty() {+ let y = ui.cursor().top();+ ui.painter().hline(ui.max_rect().x_range(), y, Stroke::new(1.0, t.separator));+ }+ ui.data_mut(|d| d.insert_temp(rename_id, renaming));+ cmd+}+// ----------------------------------------------------------------------------- properties/// Floating Properties card anchored to the canvas' top-right corner.@@ -4274,8 +4355,8 @@ 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).+ /// The Photoshop-theme footer (#1117): trash deletes the current state, the camera takes a+ /// snapshot (#2966), and file-plus makes a new document from the current state.#[test]fn history_footer_buttons_run_their_commands() {let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());@@ -4296,7 +4377,12 @@ mod history_transform_tests {};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:?}");+ assert!(b.iter().all(|b| b.1), "all enabled: {b:?}");+ let steps = h.state().session.active().unwrap().history.entries().len();+ click(&mut h, b[1].0.center());+ let st = h.state().session.active().unwrap();+ assert_eq!(st.snapshots.len(), 1, "the camera takes a snapshot");+ assert_eq!(st.history.entries().len(), steps, "which is not a history state");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");@@ -4311,6 +4397,123 @@ mod history_transform_tests {}}+#[cfg(test)]+mod snapshot_row_tests {+ use egui::vec2;+ use egui_kittest::Harness;+ use egui_kittest::kittest::Queryable;+ use serde_json::json;++ use super::*;++ fn top_pixel(h: &Harness<'static, PhotocraftApp>) -> [f32; 4] {+ h.state().session.active().unwrap().doc.layers.last().unwrap().surface().unwrap().rgba(1, 1)+ }++ fn snapshot_names(h: &Harness<'static, PhotocraftApp>) -> Vec<String> {+ h.state().session.active().unwrap().snapshots.iter().map(|s| s.name.clone()).collect()+ }++ /// Snapshot rows (#2966) sit under the opening row: clicking one returns to it as a new+ /// state, and its right-click menu renames or deletes it.+ #[test]+ fn snapshot_rows_select_rename_and_delete() {+ 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();+ app.run("history.newSnapshot", json!({})).unwrap();+ app.run("edit.fill", json!({"color": "#0000ff"})).unwrap();+ // 60 fps steps, so two clicks a frame apart count as a double-click.+ let mut h =+ Harness::builder().with_size(vec2(300.0, 400.0)).with_step_dt(1.0 / 60.0).build_ui_state(|ui, app: &mut PhotocraftApp| history(app, ui), app);+ h.run_steps(3);+ let steps = h.state().session.active().unwrap().history.entries().len();+ h.get_by_label("Snapshot 1").click();+ h.run_steps(2);+ let st = h.state().session.active().unwrap();+ assert_eq!(st.history.entries().len(), steps + 1);+ assert_eq!(st.history.entries().last().map(String::as_str), Some("Snapshot 1"));+ assert_eq!(top_pixel(&h), [1.0, 0.0, 0.0, 1.0], "back to red");+ // Right-click › Rename…: type a name, Enter.+ h.get_by_label("Snapshot 1").click_secondary();+ h.run_steps(2);+ h.get_by_label("Rename…").click();+ h.run_steps(2);+ h.get_by_role(egui::accesskit::Role::TextInput).type_text("Lesson start");+ h.key_press(egui::Key::Enter);+ h.run_steps(2);+ assert_eq!(snapshot_names(&h), ["Lesson start"]);+ // A double-click renames too; Escape keeps the old name.+ let steps_now = h.state().session.active().unwrap().history.entries().len();+ // A real double-click (accessibility clicks are single clicks).+ let p = h.get_by_label("Lesson start").rect().center();+ let p = egui::pos2(p.x as f32, p.y as f32);+ h.event(egui::Event::PointerMoved(p));+ // Wait out the double-click window of the earlier clicks.+ h.run_steps(30);+ for pressed in [true, false, true, false] {+ h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });+ h.step();+ }+ h.run_steps(3);+ h.get_by_role(egui::accesskit::Role::TextInput).type_text("Oops");+ h.key_press(egui::Key::Escape);+ h.run_steps(2);+ assert_eq!(snapshot_names(&h), ["Lesson start"], "Escape cancels");+ assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps_now + 1, "the click selected it once");+ // Right-click › Delete.+ h.get_by_label("Lesson start").click_secondary();+ h.run_steps(2);+ h.get_by_label("Delete").click();+ h.run_steps(2);+ assert!(snapshot_names(&h).is_empty());+ assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps + 2, "deleting leaves the history alone");+ }++ /// Snapshot rows scroll with the states: many snapshots in a short dock leave the footer and+ /// its camera button in view.+ #[test]+ fn many_snapshots_keep_the_footer_in_a_short_panel() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 200, "height": 150})).unwrap();+ for _ in 0..6 {+ app.run("history.newSnapshot", json!({})).unwrap();+ }+ let mut h = Harness::builder().with_size(vec2(300.0, 250.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);+ let view = h.ctx.input(|i| i.viewport_rect());+ let buttons: Vec<Rect> = 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).collect());+ assert_eq!(buttons.len(), 3, "{buttons:?}");+ assert!(buttons.iter().all(|b| view.contains_rect(*b)), "footer in view: {buttons:?} in {view:?}");+ }++ /// Renaming belongs to one document: snapshot ids restart in each, so switching tabs must not+ /// carry the edit over to the other document's snapshot with the same id.+ #[test]+ fn a_rename_in_progress_stays_with_its_document() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ for _ in 0..2 {+ app.run("file.new", json!({"width": 200, "height": 150})).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(3);+ h.get_by_label("Snapshot 1").click_secondary();+ h.run_steps(2);+ h.get_by_label("Rename…").click();+ h.run_steps(2);+ assert!(h.query_by_role(egui::accesskit::Role::TextInput).is_some(), "renaming in document 2");+ h.state_mut().session.set_active(0);+ h.run_steps(2);+ assert!(h.query_by_role(egui::accesskit::Role::TextInput).is_none(), "not in document 1");+ }+}+#[cfg(test)]#[path = "layer_pct_slider_tests.rs"]mod layer_pct_slider_tests;diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 5a4989c32..c73a0be6a 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -104,7 +104,7 @@ store expose and persist the same setting; scripts keep using canonical command| `layer.newAdjustmentLayer.hueSaturation` | `{"hue":30,"saturation":10}` || `paint.stroke` | `{"points":[[x,y,pressure],…],"size":20,"color":"#ff0000"}` || `select.rect` | `{"x":0,"y":0,"width":100,"height":50,"mode":"add","ellipse":false}` |-| `document.inspect` | `{}`: layer tree, history, selection bounds |+| `document.inspect` | `{}`: layer tree, history, snapshots (`[{id, name}]`, for `history.selectSnapshot`), selection bounds || `document.pixel` | `{"x":10,"y":10}`: composite RGBA || `document.presets.list` | `{}` → `{presets:[{name,settings}]}`: saved New Document configurations || `document.presets.save` | `{"name":"Product square","settings":{"width":1600,"height":1600,"background":"transparent"}}`: save a snapshot; names are trimmed, 1–255 characters, and ASCII case-insensitive duplicates are rejected |diff --git a/docs/ui-parity.md b/docs/ui-parity.mdindex c901cad3a..cb8746b6f 100644--- a/docs/ui-parity.md+++ b/docs/ui-parity.md@@ -1,6 +1,6 @@# UI parity: tools, handles, modifiers and feel-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (Hand-tool flick panning) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (History snapshots) · **Target:** Adobe Photoshop 2026How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, thehandles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation,@@ -200,6 +200,7 @@ Paragraph; the rest open as in-app floating windows.| Command palette with recents | done | UI-217-7 || Every preference takes effect | partial | 46 of 149 do nothing (scorecard) || UI scale presets | missing | UI-217-9, #2492 |+| History snapshots: camera button, snapshot rows (click returns, rename, delete), `history.*Snapshot` commands | partial | `history_cmds.rs`, `snapshot_rows` in `panels.rs`; New Snapshot dialog, first snapshot and History Options to come (#2966) || Themes: Photoshop's four greys | partial | five themes; #2661 || Document tabs: overflow, context menu, reorder | done | UI-217-6; middle-click close #2570 || Layers panel: wheel steps blend modes, drop on New/Trash | partial | UI-217-14 |@@ -211,3 +212,4 @@ Paragraph; the rest open as in-app floating windows.| 2026-10-10 | major | First version, from a source audit against Photoshop 2026 27.11.0's shortcuts file and the open issues || 2026-10-10 | minor | Fixed Crop live resize snapping feedback and outdated-camera rendering, applied ratios immediately to centred inscribed previews, and removed two-point options-bar overflow; added pointer, rendering, dropdown/Enter, Swap/X and scrolling regressions || 2026-10-11 | minor | Flick panning done: releasing a moving Hand drag (tool, Space or middle button) glides and decays, gated by Enable Flick Panning |+| 2026-10-11 | minor | History snapshots: the camera button takes one, snapshot rows return to it as a new state, rename and delete it (#2966) |