From 0a83e254899fc943f268ae7ef3106d0134968c84 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 15 Oct 2026 12:48:20 +0200 Subject: [PATCH 1/6] WIP: History snapshots: follow-ups to #3567 (#6087) Co-Authored-By: Claude Opus 5.5 (1M context) From 15753a69a136f6426a18e47431005c40f00f4d04 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 15 Oct 2026 13:43:18 +0200 Subject: [PATCH 2/6] History snapshots: follow-ups to #3567 (#6087) - New Snapshot dialog: snapshot_dialog::open returns None while a Free Transform is open, so the Alt-click (and any other caller) no longer opens it under the transform box. - A cleared Name in the dialog now takes the next default snapshot name instead of failing; the engine still rejects an empty name from agents. - Snapshot thumbnails remember the snapshot document they show: a document reopened with the same id, or a refreshed first snapshot, gets a fresh thumbnail, and closing a document drops its thumbnails (sync_views). Pruning deleted snapshots runs once per panel draw, not per row. - Session::refresh_type_layers also re-renders the type layers of the first snapshot (the document as opened), so returning to it keeps the served font. - Housekeeping: snapshot_rows doc comment, the dialog's select-all uses field_tab::select_all, and the New Snapshot block no longer splits the Free Transform comment from its code. cargo fmt also reformats two test lines in rotate_view.rs and wheel_nav.rs that came in with main. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/lib.rs | 55 ++++++++++++++-------- crates/engine/src/type_cmds.rs | 35 ++++++++++++++ crates/ui-egui/src/lib.rs | 25 ++++++---- crates/ui-egui/src/panels.rs | 40 ++++++++++++++-- crates/ui-egui/src/rotate_view.rs | 5 +- crates/ui-egui/src/snapshot_dialog.rs | 66 ++++++++++++++++++++++++--- crates/ui-egui/src/wheel_nav.rs | 3 +- 7 files changed, 186 insertions(+), 43 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 33c6e6a5a4d..8b2c9692839 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -231,6 +231,20 @@ pub struct DocState { next_snapshot: u64, } +/// `doc` with its type layers among `ids` re-rendered (`Session::refresh_type_layers`), or `None` +/// when none of them is a type layer of `doc`. +fn refresh_text_layers(doc: &Arc, ids: &[LayerId]) -> Option { + let mut out = (**doc).clone(); + let mut changed = false; + for id in ids { + if let Some(photocraft_doc::Layer { content: photocraft_doc::LayerContent::Text(t), .. }) = out.layer_mut(*id) { + type_cmds::refresh(doc, t); + changed = true; + } + } + changed.then_some(out) +} + impl DocState { pub fn new(doc: Document, path: Option) -> Self { let active_layer = doc.top_layer(); @@ -795,30 +809,35 @@ impl Session { } } for doc_id in docs { - let mine = layers.iter().filter(|(d, _)| *d == doc_id); + let mine: Vec = layers.iter().filter(|(d, _)| *d == doc_id).map(|(_, id)| *id).collect(); if self.job_on(doc_id).is_some() { - busy.extend(mine); + busy.extend(mine.iter().map(|id| (doc_id, *id))); continue; } let Some(st) = self.docs.iter_mut().find(|st| st.doc.id == doc_id) else { continue }; - let snapshot = st.doc.clone(); - let mut doc = (*snapshot).clone(); - let mut changed = false; - for (_, id) in mine { - if let Some(photocraft_doc::Layer { content: photocraft_doc::LayerContent::Text(t), .. }) = doc.layer_mut(*id) { - type_cmds::refresh(&snapshot, t); - changed = true; - } + // The first snapshot is the document as opened (#2966, #6087): it was taken before the + // font arrived, so its type layers get the same refresh, or returning to it brings the + // fallback-font pixels back. While it still is the open document, it shares the + // refreshed one. + let first_is_doc = st.snapshots.iter().any(|s| s.id == 0 && Arc::ptr_eq(&s.doc, &st.doc)); + if !first_is_doc + && let Some(first) = st.snapshots.iter_mut().find(|s| s.id == 0) + && let Some(doc) = refresh_text_layers(&first.doc, &mine) + { + first.doc = Arc::new(doc); } - if changed { - let clean = st.saved_revision == st.revision; - st.doc = Arc::new(doc); - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = None; + let Some(doc) = refresh_text_layers(&st.doc, &mine) else { continue }; + let doc = Arc::new(doc); + if first_is_doc && let Some(first) = st.snapshots.iter_mut().find(|s| s.id == 0) { + first.doc = doc.clone(); } + let clean = st.saved_revision == st.revision; + st.doc = doc; + st.revision += 1; + if clean { + st.saved_revision = st.revision; + } + st.last_damage = None; } busy } diff --git a/crates/engine/src/type_cmds.rs b/crates/engine/src/type_cmds.rs index 4bf193b6796..52774706934 100644 --- a/crates/engine/src/type_cmds.rs +++ b/crates/engine/src/type_cmds.rs @@ -1195,6 +1195,41 @@ mod tests { assert!(s.active().unwrap().doc.layer(id).is_none()); } + /// The first History snapshot is the document as opened, taken before a served font arrived: + /// the refresh re-renders its type layers too, so returning to it keeps the real font (#6087). + #[test] + fn refreshing_type_layers_refreshes_the_first_snapshot() { + let mut s = session(); + let id = LayerId(s.execute("type.create", json!({"text": "Hello", "size": 24})).unwrap()["layer"].as_u64().unwrap()); + let mut stale = (*s.active().unwrap().doc).clone(); + let Some(Layer { content: LayerContent::Text(t), .. }) = stale.layer_mut(id) else { panic!("not a type layer") }; + t.cache = None; + let snap_cache = |s: &Session| match &s.active().unwrap().snapshots[0].doc.layer(id).unwrap().content { + LayerContent::Text(t) => t.cache.is_some(), + other => panic!("{}", other.kind_name()), + }; + // Opened with the fallback font: the first snapshot is the open document itself. + s.add_document(stale.clone(), None); + let doc_id = s.active().unwrap().doc.id; + assert!(!snap_cache(&s)); + assert!(s.refresh_type_layers(&[(doc_id, id)]).is_empty()); + assert!(text_layer(&s, id.0).cache.is_some()); + assert!(snap_cache(&s), "the first snapshot is refreshed with the document"); + let st = s.active().unwrap(); + assert!(Arc::ptr_eq(&st.snapshots[0].doc, &st.doc), "and still shares it"); + // Edited since it opened: the snapshot is refreshed on its own, the edit stays. + s.add_document(stale, None); + let doc_id = s.active().unwrap().doc.id; + s.execute("layer.new.layer", json!({})).unwrap(); + let layers = s.active().unwrap().doc.layers.len(); + assert!(s.refresh_type_layers(&[(doc_id, id), (doc_id, LayerId(9999))]).is_empty()); + assert!(snap_cache(&s)); + assert!(text_layer(&s, id.0).cache.is_some()); + let st = s.active().unwrap(); + assert_eq!(st.doc.layers.len(), layers); + assert_eq!(st.snapshots[0].doc.layers.len(), layers - 1, "the snapshot keeps the document as opened"); + } + #[test] fn create_renders_and_is_undoable() { let mut s = session(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c9f4605839b..05727e39084 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -621,9 +621,10 @@ 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>, + /// History snapshot thumbnails by (document, snapshot id), each with the snapshot document it + /// shows (`snapshot_thumb`, #2966): made once, and again only when that is a different one (a + /// preserved-ID reopen, or the first snapshot refreshed for a served font, #6087). + snapshot_thumbs: HashMap<(DocId, u64), (std::sync::Weak, 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. @@ -1162,6 +1163,7 @@ impl PhotocraftApp { } self.canvases.retain(|(doc, _), _| ids.contains(doc)); self.navigator_textures.retain(|doc, _| ids.contains(doc)); + self.snapshot_thumbs.retain(|(doc, _), _| ids.contains(doc)); self.view_docs = ids; self.prune_thumbs(); self.sync_mask_targets(); @@ -2069,11 +2071,18 @@ 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 { + /// Drops the thumbnails of `doc`'s snapshots not in `live` (deleted ones). Those of closed + /// documents go in `sync_views`. + pub fn retain_snapshot_thumbs(&mut self, doc: DocId, live: &[u64]) { self.snapshot_thumbs.retain(|(d, id), _| *d != doc || live.contains(id)); - if let Some(tex) = self.snapshot_thumbs.get(&(doc, snap.id)) { + } + + /// The History panel thumbnail of snapshot `snap` of document `doc` (#2966): its composite, + /// centred in a square. + pub fn snapshot_thumb(&mut self, ctx: &egui::Context, doc: DocId, snap: &photocraft_engine::history_cmds::Snapshot) -> egui::TextureId { + if let Some((shown, tex)) = self.snapshot_thumbs.get(&(doc, snap.id)) + && shown.ptr_eq(&std::sync::Arc::downgrade(&snap.doc)) + { return tex.id(); } let comp = photocraft_compose::thumbnail(&snap.doc, 56); @@ -2088,7 +2097,7 @@ impl PhotocraftApp { } 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); + self.snapshot_thumbs.insert((doc, snap.id), (std::sync::Arc::downgrade(&snap.doc), tex)); id } diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index cc33be095fe..3cb2e271d66 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -3153,11 +3153,11 @@ 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); } + // An open Free Transform owns Undo (transform_tool::intercept): stepping the document's history under + // its box would leave it transforming pixels that changed. // 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) @@ -3176,8 +3176,8 @@ 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… +/// The History panel's snapshot rows (#2966), at the top of the panel (the first is the document +/// as opened), 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)> { @@ -3185,6 +3185,7 @@ fn snapshot_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> Option<(&'static 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(); + app.retain_snapshot_thumbs(doc_id, &live); // 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(); @@ -3198,7 +3199,7 @@ fn snapshot_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> Option<(&'static } 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); + let tex = app.snapshot_thumb(&ctx, doc_id, snap); 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) { @@ -4762,6 +4763,35 @@ mod snapshot_row_tests { assert!(h.state().ui.dialogs.is_empty()); } + /// Snapshot thumbnails belong to the snapshot's document (#6087): closing a document drops + /// them, and a document reopened with the same id (a `.pcraft` keeps it) gets fresh ones + /// rather than the closed document's, even before the views are synced. + #[test] + fn snapshot_thumbnails_follow_their_document() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + let doc = (*app.session.active().unwrap().doc).clone(); + let doc_id = doc.id; + let mut h = Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state(|ui, app: &mut PhotocraftApp| history(app, ui), app); + h.run_steps(2); + let thumb = |h: &Harness<'static, PhotocraftApp>| h.state().snapshot_thumbs.get(&(doc_id, 0)).map(|(_, t)| t.id()); + let first = thumb(&h).expect("the first snapshot's thumbnail"); + // Closed: its thumbnails go with it. + h.state_mut().session.close(0); + h.state_mut().sync_views(); + assert!(h.state().snapshot_thumbs.keys().all(|(d, _)| *d != doc_id), "closing drops them"); + h.state_mut().session.add_document(doc.clone(), None); + h.run_steps(2); + let reopened = thumb(&h).expect("a thumbnail for the reopened document"); + assert_ne!(reopened, first); + // Closed and reopened between two frames, with no sync in between: still a fresh one. + h.state_mut().session.close(0); + h.state_mut().session.add_document(doc, None); + assert_eq!(h.state().session.active().unwrap().doc.id, doc_id, "same id"); + h.run_steps(2); + assert_ne!(thumb(&h).unwrap(), reopened); + } + /// 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/rotate_view.rs b/crates/ui-egui/src/rotate_view.rs index fa22ac98626..5e173da5dc8 100644 --- a/crates/ui-egui/src/rotate_view.rs +++ b/crates/ui-egui/src/rotate_view.rs @@ -322,10 +322,7 @@ mod tests { let ctx = egui::Context::default(); let mut enabled = None; let mut disabled = None; - let raw = egui::RawInput { - events: vec![Event::Rotate(std::f32::consts::FRAC_PI_6)], - ..Default::default() - }; + let raw = egui::RawInput { events: vec![Event::Rotate(std::f32::consts::FRAC_PI_6)], ..Default::default() }; let mut output = ctx.run_ui(raw, |ui| { enabled = trackpad_delta(ui.ctx(), true); disabled = trackpad_delta(ui.ctx(), false); diff --git a/crates/ui-egui/src/snapshot_dialog.rs b/crates/ui-egui/src/snapshot_dialog.rs index 3ee7553b845..0dab99fb799 100644 --- a/crates/ui-egui/src/snapshot_dialog.rs +++ b/crates/ui-egui/src/snapshot_dialog.rs @@ -17,7 +17,12 @@ pub fn owns(fields: &Map) -> bool { } /// Open the dialog on the active document, suggesting the name the camera button would give. +/// Not while a Free Transform is open: it owns the document until committed or cancelled, so the +/// camera button does nothing then either (#6087). pub fn open(app: &mut PhotocraftApp) -> Option { + if app.ui.transform.is_some() { + return None; + } let name = photocraft_engine::history_cmds::next_snapshot_name(app.session.active()?); let mut f = Map::new(); f.insert(MARK.into(), json!(true)); @@ -28,8 +33,17 @@ pub fn open(app: &mut PhotocraftApp) -> Option { Some(app.ui.open_dialog(crate::state::DialogKind::Command, f)) } +/// Takes the snapshot. A cleared Name gets the next default name, as the camera button would give +/// (#6087); agents calling the command with an empty name still get an error. pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result { - app.run(COMMAND, json!({"name": f.get("name"), "from": f.get("from")})) + let mut p = Map::new(); + if let Some(name) = f.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) { + p.insert("name".into(), json!(name)); + } + if let Some(from) = f.get("from") { + p.insert("from".into(), from.clone()); + } + app.run(COMMAND, Value::Object(p)) } fn label(ui: &mut egui::Ui, text: &str) { @@ -47,11 +61,7 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { // 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); - } + crate::field_tab::select_all(ui.ctx(), r.id, &name); f.insert("__named".into(), json!(true)); } f.insert("name".into(), json!(name)); @@ -69,3 +79,47 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { } }); } + +#[cfg(test)] +mod tests { + use serde_json::json; + + use crate::PhotocraftApp; + + fn app() -> PhotocraftApp { + 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 + } + + /// An open Free Transform owns the document: New Snapshot does not open under it, whoever + /// asks (#6087). + #[test] + fn does_not_open_during_free_transform() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::transform_tool::begin(&mut app, &ctx).unwrap(); + assert!(app.ui.transform.is_some()); + assert_eq!(super::open(&mut app), None); + assert!(app.ui.dialogs.is_empty()); + crate::transform_tool::cancel(&mut app); + assert!(super::open(&mut app).is_some()); + } + + /// A cleared Name takes the default name on OK, as the camera button would (#6087); a typed + /// one is trimmed. The command itself still refuses an empty name. + #[test] + fn a_cleared_name_gets_the_default_name() { + let mut app = app(); + for (typed, want) in [("", "Snapshot 1"), (" ", "Snapshot 2"), (" Mine ", "Mine")] { + let id = super::open(&mut app).unwrap(); + let d = app.ui.dialogs.iter_mut().find(|d| d.id == id).unwrap(); + d.fields.insert("name".into(), json!(typed)); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.active().unwrap().snapshots.last().unwrap().name, want); + } + assert!(app.run(super::COMMAND, json!({"name": ""})).is_err(), "agents still get the error"); + } +} diff --git a/crates/ui-egui/src/wheel_nav.rs b/crates/ui-egui/src/wheel_nav.rs index 4523fbc6471..c65ad1fe2c3 100644 --- a/crates/ui-egui/src/wheel_nav.rs +++ b/crates/ui-egui/src/wheel_nav.rs @@ -381,8 +381,7 @@ mod tests { assert!(matches!(legacy.events[0], Event::Zoom(_))); // Native magnification takes over before the synthetic gesture times out. - let mut native = - RawInput { time: Some(1.1), events: vec![Event::Zoom(1.1), wheel(Vec2::new(0.0, 0.25), CTRL)], ..Default::default() }; + let mut native = RawInput { time: Some(1.1), events: vec![Event::Zoom(1.1), wheel(Vec2::new(0.0, 0.25), CTRL)], ..Default::default() }; fold_legacy_pinch(&ctx, &mut native); assert!(matches!(native.events[0], Event::Zoom(f) if (f - 1.1).abs() < 1e-5)); assert!(matches!(native.events[1], Event::MouseWheel { .. })); From d8ad5a911660178ec93983101dc353fd4c211dd6 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 19:33:07 +0200 Subject: [PATCH 3/6] Merge follow-up: main's new History source tests count the first snapshot (id 0) The snapshot source-column test now takes Snapshot 1's row below the first snapshot's, and history.setSource's bad-param test no longer expects snapshot 0 to be missing. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/history_source_cmds.rs | 3 ++- crates/ui-egui/src/panels.rs | 10 +++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/history_source_cmds.rs b/crates/engine/src/history_source_cmds.rs index c84cbe84002..0c92c0e56ec 100644 --- a/crates/engine/src/history_source_cmds.rs +++ b/crates/engine/src/history_source_cmds.rs @@ -366,8 +366,9 @@ mod tests { json!({"state": 1.5}), json!({"state": "1"}), json!({"state": [1]}), - json!({"snapshot": 0}), + // Snapshot 0 is the first snapshot (the document as opened); no others exist. json!({"snapshot": 1}), + json!({"snapshot": 2}), json!({"snapshot": -1}), json!({"snapshot": "Open"}), json!({"snapshot": "Open", "state": 1}), diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 5bd7b7ab301..ebbe4750919 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -5136,11 +5136,15 @@ mod history_transform_tests { app.run("history.newSnapshot", json!({})).unwrap(); let mut h = Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state(|ui, app: &mut PhotocraftApp| history(app, ui), app); h.run_steps(2); - // The snapshot row's cell is the only 24×38 one (the opening row has no column). - let cells: Vec = h + // Snapshot rows have the only 24×38 cells: the first snapshot (the document as opened) + // on top, the new one below it. + let mut cells: Vec = h .ctx .viewport(|v| v.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).filter(|w| w.rect.size() == vec2(24.0, 38.0)).map(|w| w.rect).collect()); - let cell = *cells.first().expect("a snapshot source cell"); + cells.sort_by(|a, b| a.center().y.total_cmp(&b.center().y)); + cells.dedup(); + assert_eq!(cells.len(), 2, "the first snapshot and Snapshot 1: {cells:?}"); + let cell = cells[1]; click(&mut h, cell.center()); let st = h.state().session.active().unwrap(); assert_eq!(photocraft_engine::history_source_cmds::source(st), Some(HistorySource::Snapshot(1))); From 1541134b6ff404aa9b176f4e23ae03a354a383a3 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 23 Oct 2026 00:00:13 +0200 Subject: [PATCH 4/6] Adapt History snapshots to main: doc_id in the follow spot, one cs New Snapshot entry Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/cs.tsv | 1 - crates/ui-egui/src/panels.rs | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 764938726fb..4b38d1c73be 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1035,7 +1035,6 @@ 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/panels.rs b/crates/ui-egui/src/panels.rs index 0e84bf849c4..4b99a067107 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -3613,7 +3613,7 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // The newest past state is a new document on every step, Undo and Redo, also at the state // limit, where the counts and a repeated name stay the same. let newest = st.history.past_len().checked_sub(1).and_then(|i| st.history.state(i)).map(|d| std::sync::Arc::as_ptr(&d) as usize); - let spot = (doc.id, history_spot(st), newest); + let spot = (doc_id, history_spot(st), newest); let ctx = ui.ctx().clone(); // A row dragged onto the trash (#5324); a drag that never saw its release must not outlive it. if !ctx.input(|i| i.pointer.primary_down() || i.pointer.any_released()) { From 55673a1e490c2b65a4a951ff9fcc3303302a7120 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 01:42:42 +0100 Subject: [PATCH 5/6] Address CodeRabbit review: pick the first snapshot's type layers on their own (#6087) Served fonts chose the layers to redraw from the open document only, so the first History snapshot was refreshed only for layers the open document still had, and with the open layer's "shows our own layout" verdict. A type layer deleted since the document opened kept its fallback-font pixels in the snapshot, and a PSD layer edited since lost the file's pixels there. `served_fonts::pick` now checks the snapshot (when it no longer is the open document) on its own, and `Session::refresh_type_layers` takes `TypeLayerRef`s that say which version each layer was picked in. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lib.rs | 28 ++++++++---- crates/engine/src/type_cmds.rs | 38 +++++++++++++--- crates/ui-egui/src/served_fonts.rs | 69 ++++++++++++++++++++++++------ 3 files changed, 107 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 52f065b5fb5..70e2207cc29 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -255,6 +255,16 @@ pub struct DocState { pub(crate) source_snapshot: Option, } +/// A type layer for [`Session::refresh_type_layers`]: in the open document, or in its first +/// History snapshot (the document as opened) when `first_snapshot`. The caller picks each against +/// that version of the layer, which may differ from the open one or be gone from it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TypeLayerRef { + pub doc: photocraft_doc::DocId, + pub layer: LayerId, + pub first_snapshot: bool, +} + /// `doc` with its type layers among `ids` re-rendered (`Session::refresh_type_layers`), or `None` /// when none of them is a type layer of `doc`. fn refresh_text_layers(doc: &Arc, ids: &[LayerId]) -> Option { @@ -1019,33 +1029,33 @@ impl Session { /// unchanged, so this is no history step and leaves a clean document clean. Unknown documents /// and layers are skipped. A document a background job is computing from must not move under /// it: its layers are returned, to try again later. - pub fn refresh_type_layers(&mut self, layers: &[(photocraft_doc::DocId, LayerId)]) -> Vec<(photocraft_doc::DocId, LayerId)> { + pub fn refresh_type_layers(&mut self, layers: &[TypeLayerRef]) -> Vec { let mut busy = Vec::new(); let mut docs: Vec = Vec::new(); - for (d, _) in layers { - if !docs.contains(d) { - docs.push(*d); + for l in layers { + if !docs.contains(&l.doc) { + docs.push(l.doc); } } for doc_id in docs { - let mine: Vec = layers.iter().filter(|(d, _)| *d == doc_id).map(|(_, id)| *id).collect(); if self.job_on(doc_id).is_some() { - busy.extend(mine.iter().map(|id| (doc_id, *id))); + busy.extend(layers.iter().filter(|l| l.doc == doc_id)); continue; } + let ids = |first: bool| -> Vec { layers.iter().filter(|l| l.doc == doc_id && l.first_snapshot == first).map(|l| l.layer).collect() }; let Some(st) = self.docs.iter_mut().find(|st| st.doc.id == doc_id) else { continue }; // The first snapshot is the document as opened (#2966, #6087): it was taken before the // font arrived, so its type layers get the same refresh, or returning to it brings the // fallback-font pixels back. While it still is the open document, it shares the - // refreshed one. + // refreshed one; once edited, it is refreshed on its own, layers the edit removed too. let first_is_doc = st.snapshots.iter().any(|s| s.id == 0 && Arc::ptr_eq(&s.doc, &st.doc)); if !first_is_doc && let Some(first) = st.snapshots.iter_mut().find(|s| s.id == 0) - && let Some(doc) = refresh_text_layers(&first.doc, &mine) + && let Some(doc) = refresh_text_layers(&first.doc, &ids(true)) { first.doc = Arc::new(doc); } - let Some(doc) = refresh_text_layers(&st.doc, &mine) else { continue }; + let Some(doc) = refresh_text_layers(&st.doc, &ids(false)) else { continue }; let doc = Arc::new(doc); if first_is_doc && let Some(first) = st.snapshots.iter_mut().find(|s| s.id == 0) { first.doc = doc.clone(); diff --git a/crates/engine/src/type_cmds.rs b/crates/engine/src/type_cmds.rs index c5840cac6ce..ffa4bb11bb4 100644 --- a/crates/engine/src/type_cmds.rs +++ b/crates/engine/src/type_cmds.rs @@ -1291,8 +1291,9 @@ mod tests { st.saved_revision = st.revision; } let rev = s.active().unwrap().revision; - let unknown = [(doc_id, LayerId(u64::MAX)), (photocraft_doc::DocId(u64::MAX), id)]; - assert!(s.refresh_type_layers(&[&[(doc_id, id)][..], &unknown].concat()).is_empty()); + let layers = [(doc_id, id), (doc_id, LayerId(u64::MAX)), (photocraft_doc::DocId(u64::MAX), id)]; + let layers: Vec<_> = layers.iter().map(|&(doc, layer)| crate::TypeLayerRef { doc, layer, first_snapshot: false }).collect(); + assert!(s.refresh_type_layers(&layers).is_empty()); assert!(text_layer(&s, id.0).cache.is_some()); let st = s.active().unwrap(); assert!(st.revision > rev); @@ -1306,6 +1307,7 @@ mod tests { /// the refresh re-renders its type layers too, so returning to it keeps the real font (#6087). #[test] fn refreshing_type_layers_refreshes_the_first_snapshot() { + use crate::TypeLayerRef; let mut s = session(); let id = LayerId(s.execute("type.create", json!({"text": "Hello", "size": 24})).unwrap()["layer"].as_u64().unwrap()); let mut stale = (*s.active().unwrap().doc).clone(); @@ -1315,26 +1317,52 @@ mod tests { LayerContent::Text(t) => t.cache.is_some(), other => panic!("{}", other.kind_name()), }; + let open = |doc, layer| TypeLayerRef { doc, layer, first_snapshot: false }; + let first = |doc, layer| TypeLayerRef { doc, layer, first_snapshot: true }; // Opened with the fallback font: the first snapshot is the open document itself. s.add_document(stale.clone(), None); let doc_id = s.active().unwrap().doc.id; assert!(!snap_cache(&s)); - assert!(s.refresh_type_layers(&[(doc_id, id)]).is_empty()); + assert!(s.refresh_type_layers(&[open(doc_id, id)]).is_empty()); assert!(text_layer(&s, id.0).cache.is_some()); assert!(snap_cache(&s), "the first snapshot is refreshed with the document"); let st = s.active().unwrap(); assert!(Arc::ptr_eq(&st.snapshots[0].doc, &st.doc), "and still shares it"); // Edited since it opened: the snapshot is refreshed on its own, the edit stays. - s.add_document(stale, None); + s.add_document(stale.clone(), None); let doc_id = s.active().unwrap().doc.id; s.execute("layer.new.layer", json!({})).unwrap(); let layers = s.active().unwrap().doc.layers.len(); - assert!(s.refresh_type_layers(&[(doc_id, id), (doc_id, LayerId(9999))]).is_empty()); + assert!(s.refresh_type_layers(&[open(doc_id, id), first(doc_id, id), first(doc_id, LayerId(9999))]).is_empty()); assert!(snap_cache(&s)); assert!(text_layer(&s, id.0).cache.is_some()); let st = s.active().unwrap(); assert_eq!(st.doc.layers.len(), layers); assert_eq!(st.snapshots[0].doc.layers.len(), layers - 1, "the snapshot keeps the document as opened"); + // Each version is refreshed only for the layers picked in it: one picked in the open + // document (e.g. a PSD layer edited since, while the snapshot keeps the file's pixels) + // leaves the snapshot alone, and the other way round. + s.add_document(stale.clone(), None); + let doc_id = s.active().unwrap().doc.id; + s.execute("layer.new.layer", json!({})).unwrap(); + assert!(s.refresh_type_layers(&[open(doc_id, id)]).is_empty()); + assert!(text_layer(&s, id.0).cache.is_some()); + assert!(!snap_cache(&s), "the snapshot was not picked"); + s.add_document(stale.clone(), None); + let doc_id = s.active().unwrap().doc.id; + s.execute("layer.new.layer", json!({})).unwrap(); + let rev = s.active().unwrap().revision; + assert!(s.refresh_type_layers(&[first(doc_id, id)]).is_empty()); + assert!(snap_cache(&s)); + assert!(text_layer(&s, id.0).cache.is_none(), "the open layer was not picked"); + assert_eq!(s.active().unwrap().revision, rev, "and the open document did not change"); + // The layer is gone from the open document: the snapshot still gets the real font. + s.add_document(stale, None); + let doc_id = s.active().unwrap().doc.id; + s.execute("layer.delete", json!({"layer": id.0})).unwrap(); + assert!(s.active().unwrap().doc.layer(id).is_none()); + assert!(s.refresh_type_layers(&[first(doc_id, id)]).is_empty()); + assert!(snap_cache(&s), "a layer deleted since it opened is refreshed in the snapshot"); } #[test] diff --git a/crates/ui-egui/src/served_fonts.rs b/crates/ui-egui/src/served_fonts.rs index b7ae085f41e..142cedd7daf 100644 --- a/crates/ui-egui/src/served_fonts.rs +++ b/crates/ui-egui/src/served_fonts.rs @@ -2,15 +2,16 @@ //! see `photocraft_text::served`): reading the manifest, the families to fetch, and installing //! what arrived, which registers the files and re-renders the type layers drawn without them. -use std::sync::{Mutex, PoisonError}; +use std::sync::{Arc, Mutex, PoisonError}; -use photocraft_doc::{DocId, LayerContent, LayerId, TextLayer}; +use photocraft_doc::{LayerContent, TextLayer}; +use photocraft_engine::TypeLayerRef; pub use photocraft_text::served::{ServedFont, add_families, add_fonts, is_relative_path, parse_manifest, request_for_languages, take_requests}; use crate::PhotocraftApp; /// Layers whose document was busy with a background job when their font arrived. -static PENDING: Mutex> = Mutex::new(Vec::new()); +static PENDING: Mutex> = Mutex::new(Vec::new()); /// Registers delivered font files (`(family, bytes)`, the family as the manifest lists it) and /// re-renders the type layers that use those families, or whose text falls back to them (a script @@ -23,17 +24,7 @@ pub fn install(app: &mut PhotocraftApp, delivered: Vec<(String, Vec)>) { let families: Vec = delivered.iter().map(|(f, _)| f.clone()).collect(); // Decided before the fonts are in: "shows our own layout" compares the layer's pixels // with what the engine draws now, that is with the fallback font. - for st in app.session.documents() { - for (_, _, l) in st.doc.walk() { - if let LayerContent::Text(t) = &l.content - && redraws_for(t, &families) - && crate::type_tool::shows_own_layout(&st.doc, t) - && !layers.contains(&(st.doc.id, l.id)) - { - layers.push((st.doc.id, l.id)); - } - } - } + pick(&app.session, &families, &mut layers); let mut eng = photocraft_text::shared().lock().unwrap_or_else(PoisonError::into_inner); for (family, bytes) in delivered { let added = eng.fonts.register_font_data(bytes); @@ -48,6 +39,28 @@ pub fn install(app: &mut PhotocraftApp, delivered: Vec<(String, Vec)>) { } } +/// Adds to `layers` the type layers to redraw once `families` arrive, in every open document and +/// in its first History snapshot (the document as opened), which is checked on its own: since +/// then its layers may have been edited (a PSD layer re-rendered) or deleted (#6087). +fn pick(session: &photocraft_engine::Session, families: &[String], layers: &mut Vec) { + for st in session.documents() { + // While it still is the open document, the engine refreshes it with it. + let first = st.snapshots.iter().find(|s| s.id == 0 && !Arc::ptr_eq(&s.doc, &st.doc)).map(|s| &s.doc); + for (doc, first_snapshot) in std::iter::once((&st.doc, false)).chain(first.map(|d| (d, true))) { + for (_, _, l) in doc.walk() { + let key = TypeLayerRef { doc: st.doc.id, layer: l.id, first_snapshot }; + if let LayerContent::Text(t) = &l.content + && redraws_for(t, families) + && crate::type_tool::shows_own_layout(doc, t) + && !layers.contains(&key) + { + layers.push(key); + } + } + } + } +} + /// Should the layer be redrawn when `families` arrive: it uses one of them, or its text is in a /// script one of them is the served fallback for? fn redraws_for(t: &TextLayer, families: &[String]) -> bool { @@ -79,6 +92,34 @@ mod tests { assert!(uses_family(&psd, &["Lato".into()])); } + /// #6087: the first History snapshot is picked on its own, so a type layer deleted since the + /// document opened still gets the font there, and one still shared with the open document is + /// picked once. + #[test] + fn the_first_snapshot_is_picked_on_its_own() { + use photocraft_doc::LayerId; + use serde_json::json; + let family = "Served Test Pick"; + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 200, "height": 100, "background": "transparent"})).unwrap(); + let id = LayerId(s.execute("type.create", json!({"text": "Hello", "size": 24, "font": family})).unwrap()["layer"].as_u64().unwrap()); + let doc = (*s.active().unwrap().doc).clone(); + s.add_document(doc, None); + let doc_id = s.active().unwrap().doc.id; + let key = |first_snapshot| TypeLayerRef { doc: doc_id, layer: id, first_snapshot }; + let picked = |s: &photocraft_engine::Session| { + let mut layers = Vec::new(); + pick(s, &[family.into()], &mut layers); + layers.retain(|l| l.doc == doc_id); + layers + }; + assert_eq!(picked(&s), [key(false)], "the snapshot still is the open document"); + s.execute("layer.new.layer", json!({})).unwrap(); + assert_eq!(picked(&s), [key(false), key(true)]); + s.execute("layer.delete", json!({"layer": id.0})).unwrap(); + assert_eq!(picked(&s), [key(true)], "deleted from the open document, still in the snapshot"); + } + #[test] fn a_layer_in_a_script_redraws_when_that_scripts_fallback_arrives() { // Thai: other tests use other scripts (the served catalog is process-wide). From dd8af8e98800bb2a546e230d4ef940eb2869601d Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 29 Oct 2026 18:40:25 +0100 Subject: [PATCH 6/6] Address CodeRabbit review: refresh first-snapshot picks in the open document that is the snapshot again A layer picked in the first History snapshot while the document had moved on (e.g. deleted since it opened) was only refreshed in the snapshot. If the document was busy and Undo took it back to the snapshot before the retry, the open document kept the fallback font. While the two share one document, its refresh now covers both kinds of pick. The mirror case: while shared, pick listed only the open document, so a finished job moving the document on before the retry left the snapshot with the fallback font. Pick now lists the layer for the snapshot too. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/type_cmds/tests.rs | 26 ++++++++++++++++++++++++ crates/engine/src/session/layers.rs | 12 ++++++++++- crates/ui-egui/src/text/served_fonts.rs | 22 +++++++++++++------- 3 files changed, 52 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/type_cmds/tests.rs b/crates/engine/src/cmd/type_cmds/tests.rs index dfd973734d7..f254684a779 100644 --- a/crates/engine/src/cmd/type_cmds/tests.rs +++ b/crates/engine/src/cmd/type_cmds/tests.rs @@ -178,6 +178,32 @@ fn refreshing_type_layers_refreshes_the_first_snapshot() { assert!(snap_cache(&s), "a layer deleted since it opened is refreshed in the snapshot"); } +/// A layer picked in the first snapshot while the document had moved on is refreshed in the open +/// document too when, by the time of the refresh (a busy document's retry), Undo has taken it back +/// to the snapshot: the two share one document, which must not keep the fallback font. +#[test] +fn a_layer_picked_in_the_first_snapshot_refreshes_the_open_document_it_is_again() { + let mut s = session(); + let id = LayerId(s.execute("type.create", json!({"text": "Hello", "size": 24})).unwrap()["layer"].as_u64().unwrap()); + let mut stale = (*s.active().unwrap().doc).clone(); + let Some(Layer { content: LayerContent::Text(t), .. }) = stale.layer_mut(id) else { panic!("not a type layer") }; + t.cache = None; + s.add_document(stale, None); + let doc_id = s.active().unwrap().doc.id; + // Picked while the layer was deleted from the open document: only in the snapshot. + s.execute("layer.delete", json!({"layer": id.0})).unwrap(); + let picked = [crate::TypeLayerRef { doc: doc_id, layer: id, first_snapshot: true }]; + assert!(s.undo()); + let st = s.active().unwrap(); + assert!(Arc::ptr_eq(&st.snapshots[0].doc, &st.doc), "Undo is back at the snapshot itself"); + let rev = st.revision; + assert!(s.refresh_type_layers(&picked).is_empty()); + assert!(text_layer(&s, id.0).cache.is_some(), "the open document has the real font"); + let st = s.active().unwrap(); + assert!(Arc::ptr_eq(&st.snapshots[0].doc, &st.doc), "and still shares it with the snapshot"); + assert!(st.revision > rev); +} + #[test] fn create_renders_and_is_undoable() { let mut s = session(); diff --git a/crates/engine/src/session/layers.rs b/crates/engine/src/session/layers.rs index 83d880fef98..4511b7fbf14 100644 --- a/crates/engine/src/session/layers.rs +++ b/crates/engine/src/session/layers.rs @@ -79,7 +79,17 @@ impl Session { { first.doc = Arc::new(doc); } - let Some(doc) = refresh_text_layers(&st.doc, &ids(false)) else { continue }; + // While shared, a layer picked in the snapshot is a layer of the open document too + // (a document busy when its font arrived can be back at the snapshot by the retry). + let mut open = ids(false); + if first_is_doc { + for id in ids(true) { + if !open.contains(&id) { + open.push(id); + } + } + } + let Some(doc) = refresh_text_layers(&st.doc, &open) else { continue }; let doc = Arc::new(doc); if first_is_doc && let Some(first) = st.snapshots.iter_mut().find(|s| s.id == 0) { first.doc = doc.clone(); diff --git a/crates/ui-egui/src/text/served_fonts.rs b/crates/ui-egui/src/text/served_fonts.rs index ae0df25e569..57ce3264f88 100644 --- a/crates/ui-egui/src/text/served_fonts.rs +++ b/crates/ui-egui/src/text/served_fonts.rs @@ -116,17 +116,25 @@ pub fn install(app: &mut PhotocraftApp, ctx: &egui::Context, delivered: Vec<(Str /// then its layers may have been edited (a PSD layer re-rendered) or deleted (#6087). fn pick(session: &photocraft_engine::Session, families: &[String], layers: &mut Vec) { for st in session.documents() { - // While it still is the open document, the engine refreshes it with it. - let first = st.snapshots.iter().find(|s| s.id == 0 && !Arc::ptr_eq(&s.doc, &st.doc)).map(|s| &s.doc); + let first = st.snapshots.iter().find(|s| s.id == 0).map(|s| &s.doc); + // While it still is the open document, a layer picked there is picked in the snapshot too + // (without checking it twice): a busy document is refreshed later, and by then a finished + // job can have moved the open document on. + let shared = first.is_some_and(|f| Arc::ptr_eq(f, &st.doc)); + let first = first.filter(|_| !shared); for (doc, first_snapshot) in std::iter::once((&st.doc, false)).chain(first.map(|d| (d, true))) { for (_, _, l) in doc.walk() { - let key = TypeLayerRef { doc: st.doc.id, layer: l.id, first_snapshot }; if let LayerContent::Text(t) = &l.content && redraws_for(t, families) && crate::type_tool::shows_own_layout(doc, t) - && !layers.contains(&key) { - layers.push(key); + let also = (shared && !first_snapshot).then_some(true); + for first_snapshot in std::iter::once(first_snapshot).chain(also) { + let key = TypeLayerRef { doc: st.doc.id, layer: l.id, first_snapshot }; + if !layers.contains(&key) { + layers.push(key); + } + } } } } @@ -166,7 +174,7 @@ mod tests { /// #6087: the first History snapshot is picked on its own, so a type layer deleted since the /// document opened still gets the font there, and one still shared with the open document is - /// picked once. + /// picked in both without being checked twice. #[test] fn the_first_snapshot_is_picked_on_its_own() { use photocraft_doc::LayerId; @@ -185,7 +193,7 @@ mod tests { layers.retain(|l| l.doc == doc_id); layers }; - assert_eq!(picked(&s), [key(false)], "the snapshot still is the open document"); + assert_eq!(picked(&s), [key(false), key(true)], "the snapshot still is the open document"); s.execute("layer.new.layer", json!({})).unwrap(); assert_eq!(picked(&s), [key(false), key(true)]); s.execute("layer.delete", json!({"layer": id.0})).unwrap();