From a564ea2c76e29c1f07e9411d9df935d523d39d5c Mon Sep 17 00:00:00 2001 From: itsF4LCON <107556180+itsF4LCON@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:43:05 +0200 Subject: [PATCH 1/5] History panel: snapshots (camera button, snapshot rows) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Part of #2966. The History panel's camera button takes a named snapshot of the document ("Snapshot N", not a history state). Snapshots are listed under the opening state with a thumbnail and scroll with the states; clicking one returns the document to it as one new, undoable state named after it. A double-click or right-click › Rename… renames it in place, and right-click › Delete removes it. Snapshots live for the session only, as in Photoshop. For agents: history.newSnapshot {name?, from?: fullDocument | mergedLayers | currentLayer}, history.selectSnapshot, renameSnapshot and deleteSnapshot, addressed by ids that are never reused, and doc.inspect reports snapshots. --- crates/engine/src/history_cmds.rs | 269 +++++++++++++++++++++++++++++- crates/engine/src/inspect.rs | 1 + crates/engine/src/lib.rs | 7 + crates/ui-egui/src/lib.rs | 27 +++ crates/ui-egui/src/panels.rs | 217 +++++++++++++++++++++++- docs/control-protocol.md | 2 +- docs/ui-parity.md | 4 +- 7 files changed, 517 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/history_cmds.rs b/crates/engine/src/history_cmds.rs index d9ca98f962..bb9cb34391 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, + pub layers: LayerTarget, +} + fn bad(cmd: &str, msg: impl Into) -> EngineError { EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } } @@ -72,6 +92,105 @@ fn new_document(s: &mut Session, p: &Value) -> Result { 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 { + 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> { + 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 { + 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 { + 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 { + 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 { + 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 { 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.rs index 1d1c7e0c72..acfebc7f9f 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -39,6 +39,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::>(), "history": d.history.entries(), + "snapshots": d.snapshots.iter().map(|snap| json!({"id": snap.id, "name": snap.name})).collect::>(), "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.rs index 1fffd0bdc1..9a926f86f1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -213,6 +213,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, + /// The id the next snapshot gets; ids are never reused, so deleting one keeps the others. + next_snapshot: u64, } impl DocState { @@ -239,6 +244,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.rs index 49a0332bcb..4beb2a8c35 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -548,6 +548,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)>, /// Content bounds cached per (key, revision): scanning a 36 MP layer every frame cost ~77 ms. @@ -722,6 +725,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, @@ -1814,6 +1818,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.rs index b893521aa5..e85f5aa8db 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -2840,12 +2840,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 = 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 { @@ -2883,8 +2887,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"); } @@ -2892,8 +2898,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; @@ -2908,6 +2916,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 = 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. @@ -4102,8 +4183,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()); @@ -4124,7 +4205,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"); @@ -4139,6 +4225,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 { + 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 = 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.md index b8d38b558a..db2251dfdc 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -101,7 +101,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.md index 270214e1f9..af0992b6af 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 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -198,6 +198,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 | @@ -209,3 +210,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) | From b00adf4287d963b8ec43baad4ea1ef49fa61eefd Mon Sep 17 00:00:00 2001 From: itsF4LCON <107556180+itsF4LCON@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:17:06 +0200 Subject: [PATCH 2/5] History panel: New Snapshot dialog and the first snapshot Part of #2966. Every document starts with a snapshot of itself as opened, named after it, as Photoshop does: the History panel's top row is now that snapshot, so clicking it brings the opened document back as one new state, even after History has dropped its oldest states. Option-click on the camera button opens New Snapshot: Name (suggested "Snapshot N", selected) and From (Full Document, Merged Layers, Current Layer). "From:", "Full Document" and "Merged Layers" are translated in all 16 catalogs, and "New Snapshot" in the 7 that lacked it. --- crates/engine/src/history_cmds.rs | 35 ++++++++- crates/engine/src/lib.rs | 16 ++-- crates/ui-egui/src/dialogs.rs | 2 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/panels.rs | 105 +++++++++++++++++++++----- crates/ui-egui/src/snapshot_dialog.rs | 71 +++++++++++++++++ docs/control-protocol.md | 2 +- docs/ui-parity.md | 3 +- 24 files changed, 260 insertions(+), 30 deletions(-) create mode 100644 crates/ui-egui/src/snapshot_dialog.rs diff --git a/crates/engine/src/history_cmds.rs b/crates/engine/src/history_cmds.rs index bb9cb34391..e49633e324 100644 --- a/crates/engine/src/history_cmds.rs +++ b/crates/engine/src/history_cmds.rs @@ -99,6 +99,12 @@ fn snapshot_index(s: &Session, cmd: &str, p: &Value) -> Result { st.snapshots.iter().position(|snap| snap.id == id).ok_or_else(|| bad(cmd, format!("no snapshot {id}"))) } +/// The name `history.newSnapshot` gives a snapshot without one: "Snapshot N" (the New Snapshot +/// dialog suggests it too). +pub fn next_snapshot_name(st: &crate::DocState) -> String { + format!("Snapshot {}", st.next_snapshot) +} + /// A non-blank `name` param, trimmed; `None` when absent. fn name_param(cmd: &str, p: &Value) -> Result> { match p.get("name") { @@ -138,9 +144,9 @@ fn new_snapshot(s: &mut Session, p: &Value) -> Result { _ => (st.doc.clone(), st.layer_target()), }; let st = s.active_mut().ok_or(EngineError::NoDocument)?; + let name = name.unwrap_or_else(|| next_snapshot_name(st)); 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 })) } @@ -370,7 +376,8 @@ mod tests { 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"}])); + let first = json!({"id": 0, "name": s.active().unwrap().doc.name}); + assert_eq!(snapshots(&s), json!([first, {"id": 1, "name": "Snapshot 1"}, {"id": 2, "name": "Before green"}])); } #[test] @@ -390,7 +397,7 @@ mod tests { 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"); + assert_eq!(snapshots(&s).as_array().unwrap().len(), 2, "snapshots are not history"); } #[test] @@ -418,11 +425,31 @@ mod tests { } 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"}])); + s.execute("history.deleteSnapshot", json!({"snapshot": 0})).unwrap(); + assert_eq!(snapshots(&s), json!([{"id": 2, "name": "Lesson start"}, {"id": 3, "name": "Snapshot 3"}]), "the first snapshot can go too"); let r = s.execute("history.newSnapshot", json!({})).unwrap(); assert_eq!(r["snapshot"], json!(4), "ids are never reused"); } + /// Photoshop's first snapshot (#2966): every document starts with a snapshot of itself as + /// opened, named after it, so the opening state can always be brought back, even after + /// History has dropped its oldest states. + #[test] + fn a_document_starts_with_a_first_snapshot_of_itself() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); + let name = s.active().unwrap().doc.name.clone(); + assert_eq!(snapshots(&s), json!([{"id": 0, "name": name}])); + let opened = top_pixel(&s); + for _ in 0..3 { + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + } + s.active_mut().unwrap().history.purge_last(); + s.execute("history.selectSnapshot", json!({"snapshot": 0})).unwrap(); + assert_eq!(top_pixel(&s), opened, "back to the document as opened"); + assert_eq!(entries(&s).last(), Some(&name), "a state named after the document"); + } + #[test] fn snapshot_commands_refuse_bad_params() { let mut s = Session::new(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 9a926f86f1..4390575479 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -213,8 +213,9 @@ 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. + /// History panel snapshots, oldest first (`history.newSnapshot`, #2966): the first (id 0) is + /// the document as opened. Kept for the session only, as in Photoshop: not history states, + /// and not saved with the document. pub snapshots: Vec, /// The id the next snapshot gets; ids are never reused, so deleting one keeps the others. next_snapshot: u64, @@ -224,9 +225,14 @@ impl DocState { pub fn new(doc: Document, path: Option) -> Self { let active_layer = doc.top_layer(); let mut history = History::default(); - history.set_current_layers(LayerTarget { active: active_layer, selected: active_layer.into_iter().collect() }); + let target = LayerTarget { active: active_layer, selected: active_layer.into_iter().collect() }; + history.set_current_layers(target.clone()); + let doc = Arc::new(doc); + // Photoshop's first snapshot: the document as opened, named after it, so the History + // panel's top row can always bring it back (#2966). + let first = history_cmds::Snapshot { id: 0, name: doc.name.clone(), doc: doc.clone(), layers: target }; Self { - doc: Arc::new(doc), + doc, history, active_layer, selected_layers: active_layer.into_iter().collect(), @@ -244,7 +250,7 @@ impl DocState { show_only: None, floating: None, color_samplers: Vec::new(), - snapshots: Vec::new(), + snapshots: vec![first], next_snapshot: 1, } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e57c01b4c9..2f8215655f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -229,6 +229,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { DialogKind::Command if crate::fill_ui::owns(&fields) => crate::fill_ui::body(app, ui, &mut fields), DialogKind::Command if crate::pattern_fill_ui::owns(&fields) => crate::pattern_fill_ui::body(app, ui, &mut fields), DialogKind::Command if crate::stroke_ui::owns(&fields) => crate::stroke_ui::body(ui, &mut fields), + DialogKind::Command if crate::snapshot_dialog::owns(&fields) => crate::snapshot_dialog::body(ui, &mut fields), DialogKind::Command if crate::shape_dialog::owns(&fields) => crate::shape_dialog::body(app, ui, &mut fields), DialogKind::Command if crate::delete_layer_prompt::owns(&fields) => crate::delete_layer_prompt::body(ui, &mut fields), DialogKind::Command if crate::rasterize_prompt::owns(&fields) => crate::rasterize_prompt::body(ui, &fields), @@ -464,6 +465,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { DialogKind::Command if crate::fill_ui::owns(&d.fields) => crate::fill_ui::confirm(app, &d.fields), DialogKind::Command if crate::pattern_fill_ui::owns(&d.fields) => crate::pattern_fill_ui::confirm(app, &d.fields), DialogKind::Command if crate::stroke_ui::owns(&d.fields) => crate::stroke_ui::confirm(app, &d.fields), + DialogKind::Command if crate::snapshot_dialog::owns(&d.fields) => crate::snapshot_dialog::confirm(app, &d.fields), DialogKind::Command if crate::shape_dialog::owns(&d.fields) => crate::shape_dialog::confirm(app, &d.fields), DialogKind::Command if crate::delete_layer_prompt::owns(&d.fields) => crate::delete_layer_prompt::confirm(app, &d.fields), DialogKind::Command if crate::rasterize_prompt::owns(&d.fields) => crate::rasterize_prompt::confirm(app, &d.fields), diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 93f8fd5956..60068225a1 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -974,6 +974,10 @@ Create new pattern from the selection Vytvořit nový vzorek z výběru Create new shape from the current path Vytvořit nový tvar z aktuální cesty Create new snapshot Vytvořit nový snímek + From: Z: + Full Document Celý dokument + Merged Layers Sloučené vrstvy + New Snapshot Nový snímek Create new tool preset Vytvořit nové přednastavení nástroje Crop Factor Crop faktor Ctrl Ctrl diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 26871a1e68..b325827b05 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -952,6 +952,10 @@ Create new pattern from the selection Neues Muster aus der Auswahl erstellen Create new shape from the current path Neue Form aus dem aktuellen Pfad erstellen Create new snapshot Neuen Snapshot erstellen + From: Von: + Full Document Gesamtes Dokument + Merged Layers Zusammengefügte Ebenen + New Snapshot Neuer Snapshot Create new style (from the selected type) Neuen Stil erstellen (aus dem ausgewählten Text) Create new style from the selected layer Neuen Stil aus der ausgewählten Ebene erstellen Create new tool preset Neue Werkzeugvorgabe erstellen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index dc39a34150..22b56a00f9 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -719,6 +719,9 @@ Create new pattern from the selection Δημιουργία μοτίβου από την επιλογή Create new shape from the current path Δημιουργία σχήματος από την τρέχουσα διαδρομή Create new snapshot Δημιουργία νέου στιγμιότυπου + From: Από: + Full Document Ολόκληρο έγγραφο + Merged Layers Συγχωνευμένα επίπεδα Create new style (from the selected type) Δημιουργία στυλ από τον επιλεγμένο τύπο Create new style from the selected layer Δημιουργία στυλ από το επιλεγμένο επίπεδο Current & Below Τρέχον και υποκείμενα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c65d4dd089..52a7f5799c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -960,6 +960,10 @@ Create new pattern from the selection Crear un motivo nuevo a partir de la selección Create new shape from the current path Crear una forma nueva a partir del trazado actual Create new snapshot Crear una instantánea nueva + From: De: + Full Document Documento completo + Merged Layers Capas combinadas + New Snapshot Instantánea nueva Create new tool preset Crear un ajuste preestablecido de herramienta nuevo Crop Factor Factor de recorte Ctrl Ctrl diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6a20c3521b..a4a6d86563 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -948,6 +948,9 @@ Create new pattern from the selection Créer un nouveau motif à partir de la sélection Create new shape from the current path Créer une nouvelle forme à partir du tracé actif Create new snapshot Créer un nouvel instantané + From: À partir de : + Full Document Document entier + Merged Layers Calques fusionnés Create new tool preset Créer un nouveau préréglage d'outil Crop Factor Facteur de recadrage Ctrl Ctrl diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 9f1b970db2..061b2c7e11 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -942,6 +942,9 @@ Create new pattern from the selection Buat pola baru dari seleksi Create new shape from the current path Buat bentuk baru dari path saat ini Create new snapshot Buat snapshot baru + From: Dari: + Full Document Seluruh Dokumen + Merged Layers Layer Gabungan Create new tool preset Buat preset alat baru Crop Factor Faktor Crop Ctrl Ctrl diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 4924ecfc71..83bfe28abf 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -959,6 +959,10 @@ Create new pattern from the selection Crea nuovo pattern dalla selezione Create new shape from the current path Crea nuova forma dal tracciato corrente Create new snapshot Crea nuova istantanea + From: Da: + Full Document Documento intero + Merged Layers Livelli uniti + New Snapshot Nuova istantanea Create new style (from the selected type) Crea nuovo stile (dal testo selezionato) Create new style from the selected layer Crea nuovo stile dal livello selezionato Create new tool preset Crea nuovo predefinito strumento diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index be6169e806..dbef0bf2e5 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -961,6 +961,9 @@ Create new pattern from the selection 選択範囲から新規パターンを作成 Create new shape from the current path 現在のパスから新規シェイプを作成 Create new snapshot 新規スナップショットを作成 + From: 作成元: + Full Document ドキュメント全体 + Merged Layers 結合されたレイヤー Create new tool preset 新規ツールプリセットを作成 Crop Factor 切り抜き係数 Ctrl Ctrl diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index b9ee70a4e1..87937ad59e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -934,6 +934,10 @@ Create new pattern from the selection 선택 영역으로 새 패턴 만들기 Create new shape from the current path 현재 패스로 새 모양 만들기 Create new snapshot 새 스냅샷 만들기 + From: 원본: + Full Document 전체 문서 + Merged Layers 병합된 레이어 + New Snapshot 새 스냅샷 Create new style (from the selected type) 새 스타일 만들기(선택한 문자에서) Create new style from the selected layer 선택한 레이어로 새 스타일 만들기 Create new tool preset 새 도구 사전 설정 만들기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 00d793cbf5..908f761495 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -942,6 +942,9 @@ Create new pattern from the selection Nieuw patroon maken van de selectie Create new shape from the current path Nieuwe vorm maken van het huidige pad Create new snapshot Nieuwe momentopname maken + From: Van: + Full Document Volledig document + Merged Layers Samengevoegde lagen Create new style (from the selected type) Nieuwe stijl maken (van de geselecteerde tekst) Create new style from the selected layer Nieuwe stijl maken van de geselecteerde laag Create new tool preset Nieuwe gereedschapsvoorinstelling maken diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index d6018ec9a3..1681a8156c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -958,6 +958,9 @@ Create new pattern from the selection Utwórz nowy wzór z zaznaczenia Create new shape from the current path Utwórz nowy kształt z bieżącej ścieżki Create new snapshot Utwórz nową migawkę + From: Z: + Full Document Cały dokument + Merged Layers Scalone warstwy Create new style (from the selected type) Utwórz nowy styl (z zaznaczonego tekstu) Create new style from the selected layer Utwórz nowy styl z zaznaczonej warstwy Create new tool preset Utwórz nowe ustawienie wstępne narzędzia diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 7373a3a8a3..1896c8fddb 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -944,6 +944,9 @@ Create new pattern from the selection Criar novo padrão a partir da seleção Create new shape from the current path Criar nova forma a partir do demarcador atual Create new snapshot Criar novo instantâneo + From: De: + Full Document Documento inteiro + Merged Layers Camadas mescladas Create new style (from the selected type) Criar novo estilo (a partir do texto selecionado) Create new style from the selected layer Criar novo estilo a partir da camada selecionada Create new tool preset Criar nova predefinição de ferramenta diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 25e240377b..4a0fcb8530 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2799,6 +2799,9 @@ fontWeight Italic Курсив Create new document from current state Создать новый документ из текущего состояния Create new fill or adjustment layer Создать новый слой-заливку или корректирующий слой Create new snapshot Создать новый снимок + From: Из: + Full Document Весь документ + Merged Layers Объединённые слои Delete Cropped Pixels Удалить отсечённые пикселы Delete current state Удалить текущее состояние Delete layer Удалить слой diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index a28efb4a5f..c583cc9d99 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2656,6 +2656,9 @@ fontWeight Italic Курсивний Create new document from current state Створити новий документ із поточного стану Create new fill or adjustment layer Створити новий шар заливки або корекції Create new snapshot Створити новий знімок стану + From: З: + Full Document Увесь документ + Merged Layers Об'єднані шари Delete Cropped Pixels Видаляти обрізані пікселі Delete current state Видалити поточний стан diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5c7caba0f8..6515a4aba7 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -962,6 +962,10 @@ Create new pattern from the selection 从选区创建图案 Create new shape from the current path 从当前路径创建形状 Create new snapshot 创建快照 + From: 自: + Full Document 完整文档 + Merged Layers 合并的图层 + New Snapshot 新建快照 Create new tool preset 创建工具预设 Crop Factor 裁切系数 Ctrl Ctrl diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 08a7c3bee8..752c3ca44b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -965,6 +965,10 @@ Create new pattern from the selection 從選取範圍建立新圖樣 Create new shape from the current path 從目前路徑建立新形狀 Create new snapshot 建立新快照 + From: 自: + Full Document 完整文件 + Merged Layers 合併的圖層 + New Snapshot 新增快照 Create new tool preset 建立新工具預設集 Crop Factor 裁切係數 Ctrl Ctrl diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4beb2a8c35..496c68588c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -161,6 +161,7 @@ mod sizing; pub mod slice_ui; pub mod smart_ui; pub mod snap_ui; +pub mod snapshot_dialog; pub(crate) mod solid_fill_ui; pub mod state; pub mod stroke_constraint; diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index e85f5aa8db..5c0992bfa5 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -2822,24 +2822,9 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { empty(ui, tl!("No document")); return; }; - let doc = st.doc.clone(); let entries = st.history.entries(); let current = entries.len() - 1; let redo: Vec = st.history.redo_labels().map(str::to_string).collect(); - // Snapshot row (Photoshop shows the document's opening state with a thumbnail). - { - let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 38.0), Sense::hover()); - let thumb = Rect::from_min_size(pos2(rect.left() + 28.0, rect.center().y - 14.0), vec2(28.0, 28.0)); - let ctx = ui.ctx().clone(); - if let Some(layer) = doc.layers.first() { - widgets::checker(ui.painter(), thumb, 4.0); - let tex = app.layer_thumb(&ctx, &doc, layer); - 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); - 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 = None; let all = entries.iter().map(|e| (e.clone(), false)).chain(redo.iter().map(|e| (e.clone(), true))); @@ -2880,6 +2865,7 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } }); let mut footer_cmd: Option<&str> = None; + let mut snapshot_dialog = false; if t.pro { let can_delete = app.session.is_enabled("history.deleteState"); let can_new = app.session.is_enabled("history.newDocument"); @@ -2888,8 +2874,13 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { footer_cmd = Some("history.deleteState"); } let can_snap = app.session.is_enabled("history.newSnapshot"); + // ⌥-click opens New Snapshot (name, From) instead, as in Photoshop. 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.input(|i| i.modifiers.alt) { + snapshot_dialog = true; + } else { + 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"); @@ -2898,6 +2889,9 @@ 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 snapshot_dialog { + crate::snapshot_dialog::open(app); + } // 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) @@ -4209,7 +4203,7 @@ mod history_transform_tests { 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.snapshots.len(), 2, "the camera takes a snapshot, after the first one"); 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()); @@ -4229,7 +4223,7 @@ mod history_transform_tests { mod snapshot_row_tests { use egui::vec2; use egui_kittest::Harness; - use egui_kittest::kittest::Queryable; + use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use super::*; @@ -4238,8 +4232,9 @@ mod snapshot_row_tests { h.state().session.active().unwrap().doc.layers.last().unwrap().surface().unwrap().rgba(1, 1) } + /// The names of the snapshots taken after the first one (the document as opened). fn snapshot_names(h: &Harness<'static, PhotocraftApp>) -> Vec { - h.state().session.active().unwrap().snapshots.iter().map(|s| s.name.clone()).collect() + h.state().session.active().unwrap().snapshots.iter().skip(1).map(|s| s.name.clone()).collect() } /// Snapshot rows (#2966) sit under the opening row: clicking one returns to it as a new @@ -4320,6 +4315,78 @@ mod snapshot_row_tests { assert!(buttons.iter().all(|b| view.contains_rect(*b)), "footer in view: {buttons:?} in {view:?}"); } + /// The top row is the first snapshot, the document as opened: clicking it brings that back + /// (the Discord report on #2966: "History original file click does not work"). + #[test] + fn the_top_row_returns_to_the_document_as_opened() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + let opened = app.session.active().unwrap().doc.layers[0].surface().unwrap().rgba(1, 1); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let name = app.session.active().unwrap().doc.name.clone(); + 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(&name).click(); + h.run_steps(2); + let st = h.state().session.active().unwrap(); + assert_eq!(st.doc.layers[0].surface().unwrap().rgba(1, 1), opened); + assert_eq!(st.history.entries().last(), Some(&name)); + } + + /// ⌥-click on the camera opens New Snapshot (#2966): the name, selected so typing replaces + /// it, and From (Full Document, Merged Layers, Current Layer); OK takes the snapshot. + #[test] + fn alt_click_on_the_camera_opens_new_snapshot() { + 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(900.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + history(app, ui); + crate::dialogs::show(app, &ctx); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.state_mut().ui.theme = crate::theme::ThemeKind::ProMedium; + h.run_steps(4); + let mut buttons: Vec = 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()); + buttons.sort_by(|a, b| b.center().x.total_cmp(&a.center().x)); + let camera = buttons[1].center(); + let alt = egui::Modifiers::ALT; + h.event(egui::Event::ModifiersChanged(alt)); + h.event(egui::Event::PointerMoved(camera)); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: camera, button: egui::PointerButton::Primary, pressed, modifiers: alt }); + h.run_steps(1); + } + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.run_steps(3); + assert_eq!(h.state().session.active().unwrap().snapshots.len(), 1, "⌥-click opens the dialog instead"); + assert!(h.state().ui.dialogs.last().is_some_and(|d| crate::snapshot_dialog::owns(&d.fields))); + h.get_by_role(egui::accesskit::Role::TextInput).type_text("Red layer only"); + h.run_steps(1); + h.get_all_by_role(egui::accesskit::Role::ComboBox).find(|n| n.accesskit_node().value().as_deref() == Some("Full Document")).unwrap().click(); + h.run_steps(3); + h.get_by_label("Current Layer").click(); + h.run_steps(3); + h.get_by_label("OK").click(); + h.run_steps(3); + let st = h.state().session.active().unwrap(); + let snap = st.snapshots.last().unwrap(); + assert_eq!(snap.name, "Red layer only"); + assert_eq!(snap.doc.layers.len(), 1, "only the current layer"); + assert!(h.state().ui.dialogs.is_empty()); + } + /// 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] diff --git a/crates/ui-egui/src/snapshot_dialog.rs b/crates/ui-egui/src/snapshot_dialog.rs new file mode 100644 index 0000000000..3ee7553b84 --- /dev/null +++ b/crates/ui-egui/src/snapshot_dialog.rs @@ -0,0 +1,71 @@ +//! History › New Snapshot (⌥-click the History panel's camera button, #2966): Photoshop's dialog +//! for `history.newSnapshot`, with the snapshot's Name and what it is taken From (the full +//! document, its layers merged, or only the current layer). The command stays directly callable +//! with the same params by agents and Actions. + +use egui::{Align2, Sense, pos2, vec2}; +use serde_json::{Map, Value, json}; + +use crate::PhotocraftApp; +use crate::theme::Tokens; + +pub const COMMAND: &str = "history.newSnapshot"; +const MARK: &str = "__newSnapshot"; + +pub fn owns(fields: &Map) -> bool { + fields.contains_key(MARK) +} + +/// Open the dialog on the active document, suggesting the name the camera button would give. +pub fn open(app: &mut PhotocraftApp) -> Option { + let name = photocraft_engine::history_cmds::next_snapshot_name(app.session.active()?); + let mut f = Map::new(); + f.insert(MARK.into(), json!(true)); + f.insert("__command".into(), json!(COMMAND)); + f.insert("__label".into(), json!("New Snapshot")); + f.insert("name".into(), json!(name)); + f.insert("from".into(), json!("fullDocument")); + Some(app.ui.open_dialog(crate::state::DialogKind::Command, f)) +} + +pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result { + app.run(COMMAND, json!({"name": f.get("name"), "from": f.get("from")})) +} + +fn label(ui: &mut egui::Ui, text: &str) { + let t = Tokens::get(ui.ctx()); + let (r, _) = ui.allocate_exact_size(vec2(64.0, 22.0), Sense::hover()); + ui.painter().text(pos2(r.right() - 6.0, r.center().y), Align2::RIGHT_CENTER, text, egui::FontId::proportional(12.0), t.text_dim); +} + +pub fn body(ui: &mut egui::Ui, f: &mut Map) { + ui.spacing_mut().item_spacing.y = 6.0; + ui.horizontal(|ui| { + label(ui, tl!("Name:")); + let mut name = f.get("name").and_then(Value::as_str).unwrap_or_default().to_string(); + let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(260.0)); + // Opens on the name, selected, so typing replaces it (Photoshop). + if !ui.is_sizing_pass() && !f.contains_key("__named") { + 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(name.chars().count())); + state.cursor.set_char_range(Some(all)); + state.store(ui.ctx(), r.id); + } + f.insert("__named".into(), json!(true)); + } + f.insert("name".into(), json!(name)); + }); + ui.horizontal(|ui| { + label(ui, tl!("From:")); + let mut from = f.get("from").and_then(Value::as_str).unwrap_or("fullDocument").to_string(); + let opts = [ + ("fullDocument".to_string(), tl!("Full Document")), + ("mergedLayers".to_string(), tl!("Merged Layers")), + ("currentLayer".to_string(), tl!("Current Layer")), + ]; + if crate::widgets::dropdown(ui, "new-snapshot-from", &mut from, &opts, 170.0) { + f.insert("from".into(), json!(from)); + } + }); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index db2251dfdc..0ebf13f340 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -101,7 +101,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, snapshots (`[{id, name}]`, for `history.selectSnapshot`), selection bounds | +| `document.inspect` | `{}`: layer tree, history, snapshots (`[{id, name}]`, for `history.selectSnapshot`; id 0 is the document as opened), 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.md index af0992b6af..544cf381b4 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -198,7 +198,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) | +| History snapshots: camera button, New Snapshot dialog (⌥-click: Name, From), the first snapshot (the document as opened), snapshot rows (click returns, rename, delete), `history.*Snapshot` commands | partial | `history_cmds.rs`, `snapshot_rows` in `panels.rs`, `snapshot_dialog.rs`; the snapshot History Options and History Brush sources 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 +211,4 @@ Paragraph; the rest open as in-app floating windows. | 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) | +| 2026-10-11 | minor | History snapshots: the New Snapshot dialog (⌥-click the camera), and the first snapshot of the document as opened as the panel's top row (#2966) | From ab0b4080f557f1476db11b7a320da86905e49a69 Mon Sep 17 00:00:00 2001 From: itsF4LCON <107556180+itsF4LCON@users.noreply.github.com> Date: Mon, 12 Oct 2026 14:01:20 +0200 Subject: [PATCH 3/5] CLI orientation test: the first snapshot is named after the document The .pcraft round trip compares document.inspect of a.pcraft and b.pcraft with the per-file fields removed. The first snapshot (#2966) is named after the document, so it differs in the same way as the name: check each one's name, then compare the rest. --- apps/photocraft-cli/tests/orientation.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/apps/photocraft-cli/tests/orientation.rs b/apps/photocraft-cli/tests/orientation.rs index 101195581f..3895df367a 100644 --- a/apps/photocraft-cli/tests/orientation.rs +++ b/apps/photocraft-cli/tests/orientation.rs @@ -125,7 +125,8 @@ fn orientation_6_jpeg_converts_upright_and_rotates_back() { let (a, b) = (d.join("a.pcraft"), d.join("b.pcraft")); ok(bin().arg("convert").arg(&jpg).arg(&a)); ok(bin().arg("convert").arg(&a).arg(&b)); - // Everything but the file's own path and saved document name must match. + // Everything but the file's own path and saved document name (which the first snapshot is + // named after) must match. let info = |p: &Path| { let mut v = serde_json::from_str::(&ok(bin().arg("info").arg(p))).unwrap(); v.as_object_mut().unwrap().remove("file"); @@ -136,8 +137,12 @@ fn orientation_6_jpeg_converts_upright_and_rotates_back() { assert_eq!((ia["width"].as_u64(), ia["height"].as_u64()), (Some(16), Some(32))); assert_eq!(ia["name"], "a.pcraft"); assert_eq!(ib["name"], "b.pcraft"); - ia.as_object_mut().unwrap().remove("name"); - ib.as_object_mut().unwrap().remove("name"); + assert_eq!(ia["snapshots"][0]["name"], "a.pcraft"); + assert_eq!(ib["snapshots"][0]["name"], "b.pcraft"); + for v in [&mut ia, &mut ib] { + v.as_object_mut().unwrap().remove("name"); + v["snapshots"][0].as_object_mut().unwrap().remove("name"); + } assert_eq!(ia, ib); let (pa, pb) = (d.join("a.png"), d.join("b.png")); ok(bin().arg("convert").arg(&a).arg(&pa)); From 1a0e9972218927fa0f8829245eeb04fe5f91130c Mon Sep 17 00:00:00 2001 From: itsF4LCON <107556180+itsF4LCON@users.noreply.github.com> Date: Mon, 12 Oct 2026 21:15:29 +0200 Subject: [PATCH 4/5] i18n: New Snapshot dialog strings in the Hungarian and Turkish catalogs (#2966) --- crates/ui-egui/src/i18n/hu.tsv | 3 +++ crates/ui-egui/src/i18n/tr.tsv | 3 +++ 2 files changed, 6 insertions(+) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 080e204aaa..39fdea0e2f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3820,6 +3820,9 @@ cameraRaw Yellow Sárga New document… ⌘N Új dokumentum… ⌘N New Layer from Brush Új réteg ecsetből New Path Új útvonal + From: Forrás: + Full Document Teljes dokumentum + Merged Layers Egyesített rétegek New Snapshot Új pillanatkép New Video Group Új videócsoport Newspaper Újságpapír diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 617ad81fd9..49cce672fb 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2639,6 +2639,9 @@ cameraRaw Color Renk Color indicates Renk şunu gösterir: Create Snapshot Anlık Görüntü Oluştur Delete Snapshot Anlık Görüntüyü Sil + From: Kaynak: + Full Document Tam Belge + Merged Layers Birleştirilmiş Katmanlar New Snapshot Yeni Anlık Görüntü Snapshot 1 Anlık Görüntü 1 Nonlinear History Doğrusal Olmayan Geçmiş From 051a4d6778b6f0a7e85491f77d863dbe3b7452df Mon Sep 17 00:00:00 2001 From: itsF4LCON <107556180+itsF4LCON@users.noreply.github.com> Date: Tue, 13 Oct 2026 05:00:20 +0200 Subject: [PATCH 5/5] History panel: the snapshot strings in the Serbian catalog (#2966) --- crates/ui-egui/src/i18n/sr.tsv | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 9d8aebef63..54567192ce 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -2236,6 +2236,9 @@ Create Snapshot Napravi snimak stanja Delete Snapshot Obriši snimak stanja New Snapshot Novi snimak stanja + From: Od: + Full Document Ceo dokument + Merged Layers Spojeni slojevi Snapshot 1 Snimak stanja 1 Step Forward Korak napred Step Backward Korak nazad