diff --git a/crates/engine/src/cmd/layer_multi_cmds/tile_damage_tests.rs b/crates/engine/src/cmd/layer_multi_cmds/tile_damage_tests.rs index c7acbff4a06..af70e8c9fe5 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/tile_damage_tests.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/tile_damage_tests.rs @@ -243,7 +243,7 @@ fn refreshing_type_layers_damages_only_those_layers() { let one = LayerId(s.execute("type.create", json!({"x": 100, "y": 100, "text": "One", "size": 20})).unwrap()["layer"].as_u64().unwrap()); let two = LayerId(s.execute("type.create", json!({"x": 1000, "y": 800, "text": "Two", "size": 20})).unwrap()["layer"].as_u64().unwrap()); let before = doc(&s); - let busy = s.refresh_type_layers(&[(before.id, one)]); + let busy = s.refresh_type_layers(&[crate::TypeLayerRef { doc: before.id, layer: one, first_snapshot: false }]); assert!(busy.is_empty()); let after = doc(&s); let d = damage(&s).expect("a bounded refresh"); diff --git a/crates/engine/src/cmd/type_cmds/tests.rs b/crates/engine/src/cmd/type_cmds/tests.rs index 225a20ab154..066e0f5a8a4 100644 --- a/crates/engine/src/cmd/type_cmds/tests.rs +++ b/crates/engine/src/cmd/type_cmds/tests.rs @@ -104,8 +104,9 @@ fn refreshing_type_layers_takes_no_history_step() { 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); @@ -115,6 +116,94 @@ fn refreshing_type_layers_takes_no_history_step() { 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() { + 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(); + 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()), + }; + 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(&[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.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(&[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"); +} + +/// 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/lib.rs b/crates/engine/src/lib.rs index f03911220ac..e74b7845194 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -175,6 +175,16 @@ pub use session::move_item; use session::restore_target; pub(crate) use session::{carry_visibility, fix_selection, visibility_changes}; +/// 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, +} + /// The pixels of a raster layer (typically one a command just created), as an error instead /// of a panic if the layer has none. pub(crate) fn pixels_mut(l: &mut photocraft_doc::Layer) -> Result<&mut photocraft_raster::Surface> { diff --git a/crates/engine/src/session/layers.rs b/crates/engine/src/session/layers.rs index 2e6009d16f3..4511b7fbf14 100644 --- a/crates/engine/src/session/layers.rs +++ b/crates/engine/src/session/layers.rs @@ -1,5 +1,6 @@ use super::history::fix_selection; use super::{Arc, EngineError, LayerId, Result, Session, channel_cmds, layer_multi_cmds, type_cmds}; +use crate::TypeLayerRef; impl Session { /// Replace the active document's active layer without creating a history step. @@ -52,41 +53,70 @@ 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 = layers.iter().filter(|(d, _)| *d == doc_id); if self.job_on(doc_id).is_some() { - busy.extend(mine); + 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 }; - 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; 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, &ids(true)) + { + first.doc = Arc::new(doc); + } + // 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); + } } } - if changed { - let clean = st.saved_revision == st.revision; - st.doc = Arc::new(doc); - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - // Only the refreshed layers' caches changed: their changed tiles. - st.last_damage = layer_multi_cmds::step_damage(&snapshot, &st.doc); + 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(); } + let clean = st.saved_revision == st.revision; + let before = std::mem::replace(&mut st.doc, doc); + st.revision += 1; + if clean { + st.saved_revision = st.revision; + } + // Only the refreshed layers' caches changed: their changed tiles. + st.last_damage = layer_multi_cmds::step_damage(&before, &st.doc); } busy } } + +/// `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) +} diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 93cb879777c..df4bc779865 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -355,6 +355,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)); // Closing a document cancels its page work; its GPU pages go with `retain_gpu_documents`. self.streams.retain(|doc, _| ids.contains(doc)); self.view_docs = ids; diff --git a/crates/ui-egui/src/app/thumbs.rs b/crates/ui-egui/src/app/thumbs.rs index 7ba8fb1db68..36cf9834f00 100644 --- a/crates/ui-egui/src/app/thumbs.rs +++ b/crates/ui-egui/src/app/thumbs.rs @@ -63,11 +63,18 @@ impl PhotocraftApp { (self.store_thumb(ctx, key, rev, img), frame) } - /// 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); @@ -82,7 +89,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/dialogs/snapshot_dialog.rs b/crates/ui-egui/src/dialogs/snapshot_dialog.rs index 052b9b4f84e..04c0430dc6b 100644 --- a/crates/ui-egui/src/dialogs/snapshot_dialog.rs +++ b/crates/ui-egui/src/dialogs/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/lib.rs b/crates/ui-egui/src/lib.rs index 0612021bea1..b7a5f226a58 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -502,9 +502,10 @@ pub struct PhotocraftApp { /// The document area each layer thumbnail in `thumbs` frames (the canvas, or the layer's /// bounds with Clip Thumbnails to Layer Bounds; #4281). thumb_frames: HashMap, - /// 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. diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index ab5475ff9bf..222b1829f14 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1001,6 +1001,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/panels/history.rs b/crates/ui-egui/src/panels/history.rs index 939ef07e6bb..aad55b96d24 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -160,11 +160,11 @@ pub(super) fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if ctx.input(|i| i.pointer.any_released()) { ctx.data_mut(|d| d.remove::(history_drag_key())); } - // 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.filter(|_| app.ui.transform.is_none()).or(snap_cmd) { @@ -253,17 +253,18 @@ pub(crate) fn selected_snapshot(ctx: &egui::Context, st: &photocraft_engine::Doc live.then_some(id) } -/// 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) and selects it, a double-click or -/// right-click › Rename… edits the name in place (Enter or a click elsewhere keeps it, Escape -/// cancels), right-click › Delete removes it, and a drag onto the trash too (#5324). Returns the -/// command a row asks for. +/// 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) +/// and selects it, a double-click or right-click › Rename… edits the name in place (Enter or a +/// click elsewhere keeps it, Escape cancels), right-click › Delete removes it, and a drag onto the +/// trash too (#5324). Returns the command a row asks for. fn snapshot_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, selected: Option) -> 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 source = photocraft_engine::history_source_cmds::source(st); 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::unique(("history-snapshot-rename", doc_id)); let mut renaming: Option<(u64, String)> = ui.data(|d| d.get_temp(rename_id)).flatten(); @@ -283,7 +284,7 @@ fn snapshot_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, selected: Option> = Mutex::new(Vec::new()); +static PENDING: Mutex> = Mutex::new(Vec::new()); /// Served script fallbacks in the UI's font stack, by egui font name, unscaled: kept so the stack /// `theme::install_fonts` rebuilds on a language change includes them again. @@ -89,17 +90,7 @@ pub fn install(app: &mut PhotocraftApp, ctx: &egui::Context, delivered: Vec<(Str 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 fallbacks = photocraft_text::served::script_fallback_families(); for (family, bytes) in &delivered { if fallbacks.contains(family) { @@ -120,6 +111,36 @@ pub fn install(app: &mut PhotocraftApp, ctx: &egui::Context, delivered: Vec<(Str } } +/// 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() { + 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() { + if let LayerContent::Text(t) = &l.content + && redraws_for(t, families) + && crate::type_tool::shows_own_layout(doc, t) + { + 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); + } + } + } + } + } + } +} + /// 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 { @@ -151,6 +172,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 in both without being checked twice. + #[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), 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(); + 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).