From abedab1e4de751dd04e5cf18ab2b5f7ac1d48950 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 20:51:32 +0000 Subject: [PATCH] Cache History rows, artboard pages and the snap moving set on revisions History gets a generation that every change takes a fresh number from, and the snapshot list one through DocState::snapshots_mut, so the History rows rebuild only when either moves. Artboard pages and the layers a Move drag takes along are computed once per document revision; set_active_layer moves the revision like the other layer selection changes, through one bump_selection_revision. The view-only revision steps of history options, the channel eyes and Isolate Layers go through bump_view_revision; Isolate Layers still marks the document modified. DocQueries drops every entry when the open document set changes, and counts what it computes, which the idle trial asserts stays unchanged. Fill layers' thumbnails key on impl Hash for Fill. A new trial checks the Layers rows' revision follows a rename and both disclosure toggles. --- crates/automation/tests/it/save_snapshot.rs | 4 +- crates/doc/src/lib.rs | 54 +++---- crates/engine/src/cmd/actions_cmds/history.rs | 7 +- crates/engine/src/cmd/channel_cmds/view.rs | 10 +- crates/engine/src/cmd/edit_menu_cmds/purge.rs | 2 +- .../src/cmd/file_cmds/open_as_smart_object.rs | 2 +- .../file_cmds/open_as_smart_object_tests.rs | 4 +- crates/engine/src/cmd/fx_view_cmds.rs | 2 +- crates/engine/src/cmd/group_view_cmds.rs | 2 +- crates/engine/src/cmd/history_cmds.rs | 20 +-- crates/engine/src/cmd/history_options_cmds.rs | 19 +-- crates/engine/src/cmd/history_source_cmds.rs | 8 +- .../src/cmd/layer_multi_cmds/selection.rs | 10 +- crates/engine/src/cmd/select_extra_cmds.rs | 3 +- crates/engine/src/cmd/type_cmds/tests.rs | 10 +- crates/engine/src/doc_state.rs | 43 +++++- crates/engine/src/inspect.rs | 2 +- crates/engine/src/session/documents.rs | 10 +- crates/engine/src/session/layers.rs | 21 +-- .../engine/tests/it/actions_single_history.rs | 4 +- crates/ops/src/lib.rs | 50 +++++++ crates/ui-egui/src/app/doc_queries.rs | 132 +++++++++++++----- crates/ui-egui/src/app/thumbs.rs | 2 +- crates/ui-egui/src/canvas/artboard_ui.rs | 12 +- crates/ui-egui/src/canvas/snap_ui.rs | 11 +- crates/ui-egui/src/dialogs/snapshot_dialog.rs | 2 +- crates/ui-egui/src/doc_revision_trials.rs | 62 +++++++- crates/ui-egui/src/panels/history.rs | 8 +- crates/ui-egui/src/panels/history_menu_ui.rs | 4 +- .../src/panels/history_panel_select_tests.rs | 12 +- crates/ui-egui/src/panels/layers_tree.rs | 2 +- crates/ui-egui/src/save_identity_tests.rs | 6 +- crates/ui-egui/src/text/served_fonts.rs | 2 +- crates/ui-egui/src/tools/crop_ui/tests.rs | 2 +- .../src/tools/retouch_ui/bar/history.rs | 2 +- 35 files changed, 366 insertions(+), 180 deletions(-) diff --git a/crates/automation/tests/it/save_snapshot.rs b/crates/automation/tests/it/save_snapshot.rs index 95c922c4a3..1a3a9b54cb 100644 --- a/crates/automation/tests/it/save_snapshot.rs +++ b/crates/automation/tests/it/save_snapshot.rs @@ -16,7 +16,7 @@ fn tmp() -> std::path::PathBuf { } fn snapshots(h: &Headless) -> usize { - h.session.active().unwrap().snapshots.len() + h.session.active().unwrap().snapshots().len() } #[test] @@ -37,7 +37,7 @@ fn a_document_save_adds_a_snapshot_only_with_the_option() { h.handle("doc.save", json!({})).unwrap(); assert_eq!(snapshots(&h), 2, "the save added one"); let st = h.session.active().unwrap(); - assert!(std::sync::Arc::ptr_eq(&st.snapshots[1].doc, &st.doc), "of the document as saved"); + assert!(std::sync::Arc::ptr_eq(&st.snapshots()[1].doc, &st.doc), "of the document as saved"); assert!(!st.is_dirty(), "and the document stays saved"); // A flat export is a copy, not a save of the document. diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 482127cb08..751c73e63e 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -403,42 +403,44 @@ impl Fill { } self } +} - /// A hash of every field: equal fills give equal numbers, so a view keys on it instead of - /// comparing or formatting the fill. The patterns name every field, so a new field fails to - /// compile here until it is hashed. - pub fn fingerprint(&self) -> u64 { - use std::hash::{Hash, Hasher}; - let mut h = std::collections::hash_map::DefaultHasher::new(); - let color = |h: &mut std::collections::hash_map::DefaultHasher, c: &Color| { +/// Hashes every field, consistent with `PartialEq`: an `f32` hashes by its bits, with −0.0 as 0.0 (they compare +/// equal). A NaN never equals anything, so any hash agrees with `PartialEq`; it hashes by its own bits, so a fill +/// holding one keeps its hash. The patterns name every field, so a new field fails to compile here until it is hashed. +impl std::hash::Hash for Fill { + fn hash(&self, h: &mut H) { + fn bits(v: f32) -> u32 { + if v == 0.0 { 0 } else { v.to_bits() } + } + fn color(h: &mut H, c: &Color) { let Color { mode, c, alpha } = c; - std::mem::discriminant(mode).hash(h); - c.map(f32::to_bits).hash(h); - alpha.to_bits().hash(h); - }; - std::mem::discriminant(self).hash(&mut h); + mode.hash(h); + c.map(bits).hash(h); + bits(*alpha).hash(h); + } + std::mem::discriminant(self).hash(h); match self { - Fill::Solid(c) => color(&mut h, c), + Fill::Solid(c) => color(h, c), Fill::Gradient { stops, angle, scale, style, reverse, opacity_stops, midpoints, offset, dither, align } => { - stops.len().hash(&mut h); + stops.len().hash(h); for (at, c) in stops { - at.to_bits().hash(&mut h); - color(&mut h, c); + bits(*at).hash(h); + color(h, c); } - [*angle, *scale, offset.0, offset.1].map(f32::to_bits).hash(&mut h); - std::mem::discriminant(style).hash(&mut h); - (reverse, dither, align).hash(&mut h); - opacity_stops.len().hash(&mut h); - opacity_stops.iter().for_each(|(a, b)| [a.to_bits(), b.to_bits()].hash(&mut h)); - midpoints.len().hash(&mut h); - midpoints.iter().for_each(|m| m.to_bits().hash(&mut h)); + [*angle, *scale, offset.0, offset.1].map(bits).hash(h); + std::mem::discriminant(style).hash(h); + (reverse, dither, align).hash(h); + opacity_stops.len().hash(h); + opacity_stops.iter().for_each(|(a, b)| [bits(*a), bits(*b)].hash(h)); + midpoints.len().hash(h); + midpoints.iter().for_each(|m| bits(*m).hash(h)); } Fill::Pattern { name, scale, id, angle, link, phase } => { - (name, id, link).hash(&mut h); - [*scale, *angle, phase.0, phase.1].map(f32::to_bits).hash(&mut h); + (name, id, link).hash(h); + [*scale, *angle, phase.0, phase.1].map(bits).hash(h); } } - h.finish() } } diff --git a/crates/engine/src/cmd/actions_cmds/history.rs b/crates/engine/src/cmd/actions_cmds/history.rs index c6f5d52197..4ac680171a 100644 --- a/crates/engine/src/cmd/actions_cmds/history.rs +++ b/crates/engine/src/cmd/actions_cmds/history.rs @@ -153,7 +153,12 @@ fn consolidate(s: &mut Session, group: &ActionHistory) { // exact pixels. Snapshots already retain source pixels without adding an Undo row. let id = st.next_snapshot; st.next_snapshot = id.saturating_add(1); - st.snapshots.push(crate::history_cmds::Snapshot { id, name: format!("{}: {}", group.name, source.label), doc: source.doc, layers: source.layers }); + st.snapshots_mut().push(crate::history_cmds::Snapshot { + id, + name: format!("{}: {}", group.name, source.label), + doc: source.doc, + layers: source.layers, + }); if restore_on_clear_undo { history.set_cleared_brush_snapshot(id); } else { diff --git a/crates/engine/src/cmd/channel_cmds/view.rs b/crates/engine/src/cmd/channel_cmds/view.rs index 9b918656f4..4040be7e88 100644 --- a/crates/engine/src/cmd/channel_cmds/view.rs +++ b/crates/engine/src/cmd/channel_cmds/view.rs @@ -135,14 +135,10 @@ pub(crate) fn fix_view(st: &mut DocState) { } } -/// Bump the revision for a view-only change without dirtying a clean document. +/// Bump the revision for a view-only change without dirtying a clean document. The channels +/// shown change the picture, so the whole canvas is drawn again. pub(super) fn touch(st: &mut DocState) { - let clean = st.saved_revision == st.revision; - st.revision += 1; - st.view_revision += 1; - if clean { - st.saved_revision = st.revision; - } + st.bump_view_revision(!st.is_dirty()); st.last_damage = None; } diff --git a/crates/engine/src/cmd/edit_menu_cmds/purge.rs b/crates/engine/src/cmd/edit_menu_cmds/purge.rs index 5a9ce8c2c5..06e828ecea 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/purge.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/purge.rs @@ -7,7 +7,7 @@ fn history_bytes(s: &Session, all: bool) -> usize { // Purge keeps the snapshots, so the tiles they share with the states aren't freed. docs.iter() .map(|d| { - let snaps: Vec<&photocraft_doc::Document> = d.snapshots.iter().map(|s| &*s.doc).collect(); + let snaps: Vec<&photocraft_doc::Document> = d.snapshots().iter().map(|s| &*s.doc).collect(); d.history.unique_bytes_besides(&d.doc, &snaps) }) .sum() diff --git a/crates/engine/src/cmd/file_cmds/open_as_smart_object.rs b/crates/engine/src/cmd/file_cmds/open_as_smart_object.rs index 57bd8ce39f..7ca92ac1cb 100644 --- a/crates/engine/src/cmd/file_cmds/open_as_smart_object.rs +++ b/crates/engine/src/cmd/file_cmds/open_as_smart_object.rs @@ -106,7 +106,7 @@ pub fn admit_as_smart_object(s: &mut Session, mut doc: Document) -> usize { // Untitled: no path, so Save asks where to save. let index = s.add_document(doc, None); if let Some(st) = s.active_mut() { - if let (Some(first), Some(name)) = (st.snapshots.iter_mut().find(|snap| snap.id == 0), layer_name) { + if let (Some(first), Some(name)) = (st.snapshots_mut().iter_mut().find(|snap| snap.id == 0), layer_name) { first.name = name; } st.history.set_current_label(LABEL); diff --git a/crates/engine/src/cmd/file_cmds/open_as_smart_object_tests.rs b/crates/engine/src/cmd/file_cmds/open_as_smart_object_tests.rs index c205af3d71..436ab56d33 100644 --- a/crates/engine/src/cmd/file_cmds/open_as_smart_object_tests.rs +++ b/crates/engine/src/cmd/file_cmds/open_as_smart_object_tests.rs @@ -126,7 +126,7 @@ fn history_is_the_single_state_open_as_smart_object() { s.execute("file.openAsSmartObject", json!({"path": path})).unwrap(); let st = s.active().unwrap(); assert_eq!(st.history.entries(), ["Open As Smart Object"], "one state, as File > Open has"); - assert_eq!(st.snapshots.first().map(|snap| snap.name.as_str()), Some("a_test"), "the opening snapshot is named after the layer"); + assert_eq!(st.snapshots().first().map(|snap| snap.name.as_str()), Some("a_test"), "the opening snapshot is named after the layer"); } #[test] @@ -136,7 +136,7 @@ fn the_opening_snapshot_shows_the_placed_smart_object() { let mut s = Session::new(); s.execute("file.openAsSmartObject", json!({"path": path})).unwrap(); let st = s.active().unwrap(); - let first = st.snapshots.first().unwrap(); + let first = st.snapshots().first().unwrap(); assert_eq!(first.doc.layers.len(), 1, "snapshot 0 already holds the smart object"); assert!(matches!(first.doc.layers[0].content, LayerContent::Smart(_))); assert_eq!(first.layers.active, Some(first.doc.layers[0].id)); diff --git a/crates/engine/src/cmd/fx_view_cmds.rs b/crates/engine/src/cmd/fx_view_cmds.rs index b9c1a90016..dca29fe5b5 100644 --- a/crates/engine/src/cmd/fx_view_cmds.rs +++ b/crates/engine/src/cmd/fx_view_cmds.rs @@ -64,7 +64,7 @@ fn set_expanded(s: &mut Session, p: &Value) -> Result { if !expanded { st.fx_collapsed.extend(targets.iter().copied()); } - st.bump_view_revision(); + st.bump_view_revision(!st.is_dirty()); Ok(json!({"expanded": expanded, "layers": targets.len()})) } diff --git a/crates/engine/src/cmd/group_view_cmds.rs b/crates/engine/src/cmd/group_view_cmds.rs index bc0afec6f1..e9a9b4d1af 100644 --- a/crates/engine/src/cmd/group_view_cmds.rs +++ b/crates/engine/src/cmd/group_view_cmds.rs @@ -76,7 +76,7 @@ fn set_expanded(s: &mut Session, p: &Value) -> Result { _ => return Err(EngineError::NoLayer(id)), } }; - st.bump_view_revision(); + st.bump_view_revision(!st.is_dirty()); Ok(json!({"expanded": expanded, "groups": changed})) } diff --git a/crates/engine/src/cmd/history_cmds.rs b/crates/engine/src/cmd/history_cmds.rs index 30d8528545..e63bf32a7c 100644 --- a/crates/engine/src/cmd/history_cmds.rs +++ b/crates/engine/src/cmd/history_cmds.rs @@ -112,7 +112,7 @@ fn new_document(s: &mut Session, p: &Value) -> Result { 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}"))) + 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 @@ -165,9 +165,9 @@ fn new_snapshot(s: &mut Session, p: &Value) -> Result { st.next_snapshot = id.saturating_add(1); // An action's New Snapshot with "replace existing": a snapshot of that name gives way. if p.get("replaceExisting").and_then(Value::as_bool) == Some(true) { - st.snapshots.retain(|snap| snap.name != name); + st.snapshots_mut().retain(|snap| snap.name != name); } - st.snapshots.push(Snapshot { id, name: name.clone(), doc, layers }); + st.snapshots_mut().push(Snapshot { id, name: name.clone(), doc, layers }); Ok(json!({ "snapshot": id, "name": name })) } @@ -179,7 +179,7 @@ fn select_snapshot(s: &mut Session, p: &Value) -> Result { 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)?; + 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()); @@ -203,7 +203,7 @@ fn rename_snapshot(s: &mut Session, p: &Value) -> Result { 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"))?; + let snap = st.snapshots_mut().get_mut(i).ok_or_else(|| bad(CMD, "no such snapshot"))?; snap.name.clone_from(&name); Ok(json!({ "snapshot": snap.id, "name": name })) } @@ -213,8 +213,8 @@ 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() })) + let snap = st.snapshots_mut().remove(i); + Ok(json!({ "snapshot": snap.id, "snapshots": st.snapshots().len() })) } /// A state other than the oldest exists to delete: a past or the current one, and with Allow @@ -520,7 +520,7 @@ mod tests { let base = with.active().unwrap().memory_bytes(); with.execute("history.newSnapshot", json!({"from": "mergedLayers"})).unwrap(); let st = with.active().unwrap(); - let flat = tile_bytes(&st.snapshots.last().unwrap().doc); + let flat = tile_bytes(&st.snapshots().last().unwrap().doc); assert!(flat > 0); assert_eq!(st.memory_bytes(), base + flat); // Room for the document's tiles and four fill tiles. @@ -549,11 +549,11 @@ mod tests { s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); let st = s.active().unwrap(); // The snapshot's green layer tile, now only in it and the last state. - let shared = tile_bytes(&Document { layers: st.snapshots.last().unwrap().doc.layers[1..].to_vec().into(), ..(*st.doc).clone() }); + let shared = tile_bytes(&Document { layers: st.snapshots().last().unwrap().doc.layers[1..].to_vec().into(), ..(*st.doc).clone() }); let all = st.history.unique_bytes(&st.doc); let r = s.execute("edit.purge.histories", json!({})).unwrap(); assert_eq!(r["bytes"], json!(all - shared), "the green tile stays with the snapshot"); - assert_eq!(s.active().unwrap().snapshots.len(), 2, "the first snapshot and the new one"); + assert_eq!(s.active().unwrap().snapshots().len(), 2, "the first snapshot and the new one"); } #[test] diff --git a/crates/engine/src/cmd/history_options_cmds.rs b/crates/engine/src/cmd/history_options_cmds.rs index c2f814d008..e3af8bda11 100644 --- a/crates/engine/src/cmd/history_options_cmds.rs +++ b/crates/engine/src/cmd/history_options_cmds.rs @@ -79,7 +79,7 @@ pub fn snapshot_on_save(s: &mut Session) -> Option { let st = s.active_mut()?; // Saved again without a change: the previous save's snapshot already shows this document. if let Some(prev) = st.save_snapshot - && st.snapshots.iter().any(|snap| snap.id == prev && std::sync::Arc::ptr_eq(&snap.doc, &st.doc)) + && st.snapshots().iter().any(|snap| snap.id == prev && std::sync::Arc::ptr_eq(&snap.doc, &st.doc)) { return None; } @@ -88,7 +88,7 @@ pub fn snapshot_on_save(s: &mut Session) -> Option { st.next_snapshot = id.saturating_add(1); let (doc, layers) = (st.doc.clone(), st.layer_target()); // Like the camera button: the document and its saved state are unchanged. - st.snapshots.push(Snapshot { id, name, doc, layers }); + st.snapshots_mut().push(Snapshot { id, name, doc, layers }); st.save_snapshot = Some(id); // The snapshot's tiles count against the history budget. st.trim_history(); @@ -158,15 +158,8 @@ pub(crate) fn delete_state(s: &mut Session, i: usize, current: usize) -> Result< if !removed { return Err(EngineError::Other(format!("state {i} is not held"))); } - // The document is unchanged, but the History panel's rows are not: a view-only change - // that keeps a clean document clean. - let clean = st.saved_revision == st.revision; - st.revision += 1; - st.view_revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = Some(photocraft_geom::Rect::EMPTY); + // The document is unchanged: a view-only change that keeps a clean document clean. + st.bump_view_revision(!st.is_dirty()); return Ok(()); } // The step that made the current state: the layers whose visibility it changed get it back. @@ -454,7 +447,7 @@ mod tests { } fn snapshot_names(s: &Session) -> Vec { - s.active().unwrap().snapshots.iter().map(|snap| snap.name.clone()).collect() + s.active().unwrap().snapshots().iter().map(|snap| snap.name.clone()).collect() } /// PNG bytes of a small image, to open. @@ -505,7 +498,7 @@ mod tests { let states = entries(&s); let id = snapshot_on_save(&mut s).unwrap(); let st = s.active().unwrap(); - let snap = st.snapshots.last().unwrap(); + let snap = st.snapshots().last().unwrap(); assert_eq!(snap.id, id); assert!(std::sync::Arc::ptr_eq(&snap.doc, &st.doc), "the document as saved"); // HH:MM:SS, the local time of the save. diff --git a/crates/engine/src/cmd/history_source_cmds.rs b/crates/engine/src/cmd/history_source_cmds.rs index bc2b44229b..d377d1687e 100644 --- a/crates/engine/src/cmd/history_source_cmds.rs +++ b/crates/engine/src/cmd/history_source_cmds.rs @@ -44,7 +44,7 @@ pub enum HistorySource { /// The document's History Brush source, `None` once the source state or snapshot is gone. pub fn source(st: &DocState) -> Option { match st.source_snapshot.or_else(|| st.history.brush_source_snapshot()) { - Some(id) => st.snapshots.iter().any(|s| s.id == id).then_some(HistorySource::Snapshot(id)), + Some(id) => st.snapshots().iter().any(|s| s.id == id).then_some(HistorySource::Snapshot(id)), None => st.history.brush_source().map(HistorySource::State), } } @@ -52,7 +52,7 @@ pub fn source(st: &DocState) -> Option { fn source_of(st: &DocState, src: HistorySource) -> Option> { match src { HistorySource::State(i) => st.history.row_doc(i, &st.doc), - HistorySource::Snapshot(id) => st.snapshots.iter().find(|s| s.id == id).map(|s| s.doc.clone()), + HistorySource::Snapshot(id) => st.snapshots().iter().find(|s| s.id == id).map(|s| s.doc.clone()), } } @@ -71,7 +71,7 @@ fn parse(st: &DocState, p: &Value, cmd: &str) -> Result> { } (None, Some(v)) => { let id = index("snapshot", v)?; - if !st.snapshots.iter().any(|s| s.id == id) { + if !st.snapshots().iter().any(|s| s.id == id) { return Err(bad(format!("no snapshot {id}"))); } Ok(Some(HistorySource::Snapshot(id))) @@ -168,7 +168,7 @@ pub fn source_json(st: &DocState) -> Value { json!({ "state": i, "label": label }) } Some(HistorySource::Snapshot(id)) => { - json!({ "snapshot": id, "name": st.snapshots.iter().find(|s| s.id == id).map(|s| s.name.clone()) }) + json!({ "snapshot": id, "name": st.snapshots().iter().find(|s| s.id == id).map(|s| s.name.clone()) }) } } } diff --git a/crates/engine/src/cmd/layer_multi_cmds/selection.rs b/crates/engine/src/cmd/layer_multi_cmds/selection.rs index 9eb7f947af..aa2a44bc94 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/selection.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/selection.rs @@ -1,5 +1,5 @@ use super::moves::{link_groups, recorded_move}; -use super::{DocState, Document, EngineError, Layer, LayerContent, LayerId, Rect, Result, Session, Value, bad, json}; +use super::{DocState, Document, EngineError, Layer, LayerContent, LayerId, Result, Session, Value, bad, json}; // ---------- selection state ---------- @@ -62,13 +62,7 @@ pub fn set_selection(s: &mut Session, ids: Vec, active: Option st.active_layer = active; st.layer_anchor = anchor.or(active); crate::fix_selection(st); - // Selecting layers is not an edit: keep a clean document clean. - let clean = st.saved_revision == st.revision; - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = Some(Rect::EMPTY); + st.bump_selection_revision(); s.note_layer_change(before); Ok(()) } diff --git a/crates/engine/src/cmd/select_extra_cmds.rs b/crates/engine/src/cmd/select_extra_cmds.rs index d43f1158e9..9b95bb272e 100644 --- a/crates/engine/src/cmd/select_extra_cmds.rs +++ b/crates/engine/src/cmd/select_extra_cmds.rs @@ -79,7 +79,8 @@ fn isolate_layers(s: &mut Session, p: &Value) -> Result { let st = s.active_mut().ok_or(EngineError::NoDocument)?; let on = p.get("on").and_then(Value::as_bool).unwrap_or(st.isolated_layers.is_empty()); st.isolated_layers = if on { st.selected_layers() } else { Vec::new() }; - st.revision += 1; + // A filter of the Layers panel's rows, but turning it on or off marks the document modified. + st.bump_view_revision(false); Ok(json!({ "isolated": !st.isolated_layers.is_empty(), "layers": st.isolated_layers.iter().map(|l| l.0).collect::>() })) } diff --git a/crates/engine/src/cmd/type_cmds/tests.rs b/crates/engine/src/cmd/type_cmds/tests.rs index 1fa8bb89df..2db52b6047 100644 --- a/crates/engine/src/cmd/type_cmds/tests.rs +++ b/crates/engine/src/cmd/type_cmds/tests.rs @@ -126,7 +126,7 @@ fn refreshing_type_layers_refreshes_the_first_snapshot() { 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 { + 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()), }; @@ -140,7 +140,7 @@ fn refreshing_type_layers_refreshes_the_first_snapshot() { 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"); + 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; @@ -151,7 +151,7 @@ fn refreshing_type_layers_refreshes_the_first_snapshot() { 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"); + 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. @@ -195,12 +195,12 @@ fn a_layer_picked_in_the_first_snapshot_refreshes_the_open_document_it_is_again( 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"); + 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!(Arc::ptr_eq(&st.snapshots()[0].doc, &st.doc), "and still shares it with the snapshot"); assert!(st.revision > rev); } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 7c30247f6a..c23f71ad34 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -55,8 +55,10 @@ pub struct DocState { /// History panel snapshots, oldest first (`history.newSnapshot`, #2966): the first (id 0) is /// the document as opened (unless History Options › Automatically Create First Snapshot is /// off). Kept for the session only, as in Photoshop: not history states, - /// and not saved with the document. - pub snapshots: Vec, + /// and not saved with the document. Changed only through [`DocState::snapshots_mut`]. + snapshots: Vec, + /// See [`DocState::snapshots_generation`]. + snapshots_generation: u64, /// The id the next snapshot gets; ids are never reused, so deleting one keeps the others. pub(crate) next_snapshot: u64, /// The snapshot the latest save added (History Options › Automatically Create New Snapshot @@ -127,6 +129,7 @@ impl DocState { floating: None, color_samplers: Vec::new(), snapshots: vec![first], + snapshots_generation: next_snapshots_generation(), next_snapshot: 1, save_snapshot: None, source_snapshot: None, @@ -134,6 +137,21 @@ impl DocState { pixel_revision: 0, } } + /// The History panel snapshots, oldest first. + pub fn snapshots(&self) -> &[history_cmds::Snapshot] { + &self.snapshots + } + /// The snapshots to change: [`Self::snapshots_generation`] moves. + pub fn snapshots_mut(&mut self) -> &mut Vec { + self.snapshots_generation = next_snapshots_generation(); + &mut self.snapshots + } + /// A number that identifies the snapshot list: every [`Self::snapshots_mut`] takes a fresh + /// one, clones keep it, and no two lists that differ share one. With + /// [`photocraft_ops::History::generation`] it says when the History panel's rows change. + pub fn snapshots_generation(&self) -> u64 { + self.snapshots_generation + } /// The selected layers in bottom-to-top document order, always including the active layer. /// Robust against stale state: ids no longer in the document are skipped, and if the active /// layer was changed without updating the set, the selection is just the active layer. @@ -170,12 +188,20 @@ impl DocState { self.saved_revision = self.revision; } } + /// Move to the next revision for a change of the layer selection, which is not an edit: + /// readers keyed on the revision follow it, a clean document stays clean, and no pixels need + /// drawing again. + pub(crate) fn bump_selection_revision(&mut self) { + self.bump_revision(!self.is_dirty()); + self.last_damage = Some(photocraft_geom::Rect::EMPTY); + } /// Move to the next revision for a view-only change (a group opened, an effects list - /// collapsed): readers keyed on the revision follow it, pixel caches ignore it through - /// `view_revision`, and a clean document stays clean. - pub(crate) fn bump_view_revision(&mut self) { + /// collapsed, a history state deleted): readers keyed on the revision follow it, pixel caches + /// ignore it through `view_revision`, and no pixels need drawing again. `keep_clean` as for + /// [`Self::bump_revision`]. + pub(crate) fn bump_view_revision(&mut self, keep_clean: bool) { self.view_revision += 1; - self.bump_revision(self.revision == self.saved_revision); + self.bump_revision(keep_clean); self.last_damage = Some(photocraft_geom::Rect::EMPTY); } /// The targeted layers, as history stores them with each state. @@ -184,6 +210,11 @@ impl DocState { } } +fn next_snapshots_generation() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + /// App-wide tool state that commands read (foreground colour, brush…). #[derive(Clone, Debug)] pub struct ToolState { diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 1c6643f083..c4dd9b2c56 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -56,7 +56,7 @@ fn document_with(d: &DocState, detail: bool) -> Value { "layers": doc.layers.iter().rev().map(|l| layer_sel(l, &selected, &instances, Some(&doc.metadata), detail)).collect::>(), "history": d.history.entries(), "historySource": crate::history_source_cmds::source_json(d), - "snapshots": d.snapshots.iter().map(|snap| json!({"id": snap.id, "name": snap.name})).collect::>(), + "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/session/documents.rs b/crates/engine/src/session/documents.rs index 72ca474fe1..f633ff6584 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -81,11 +81,15 @@ impl Session { } /// Make `layer` the active document's active layer and nothing else (the selection list and - /// anchor are left as they are), counted in [`Self::active_layer_changes`]. + /// anchor are left as they are), counted in [`Self::active_layer_changes`]. Like + /// [`Self::select_layer`], not an edit. pub fn set_active_layer(&mut self, layer: Option) { let before = self.active_layer_stamp(); - if let Some(st) = self.active_mut() { + if let Some(st) = self.active_mut() + && st.active_layer != layer + { st.active_layer = layer; + st.bump_selection_revision(); } self.note_layer_change(before); } @@ -184,7 +188,7 @@ impl Session { // History Options › Automatically Create First Snapshot off: no snapshot of the document // as opened, so the History panel starts at the opening state (#2966). if !self.prefs.get().history_options.automatically_create_first_snapshot { - st.snapshots.clear(); + st.snapshots_mut().clear(); } self.docs.push(st); self.documents_generation = self.documents_generation.wrapping_add(1); diff --git a/crates/engine/src/session/layers.rs b/crates/engine/src/session/layers.rs index d7f8ed9997..6a270f81ce 100644 --- a/crates/engine/src/session/layers.rs +++ b/crates/engine/src/session/layers.rs @@ -14,13 +14,7 @@ impl Session { st.selected_layers = vec![id]; st.layer_anchor = Some(id); channel_cmds::fix_view(st); - // Selecting a layer is not an edit: keep a clean document clean. - let clean = st.saved_revision == st.revision; - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = Some(photocraft_geom::Rect::EMPTY); + st.bump_selection_revision(); self.note_layer_change(before); Ok(()) } @@ -42,12 +36,7 @@ impl Session { st.layer_anchor = anchor.filter(|_| active.is_some()); fix_selection(st); channel_cmds::fix_view(st); - let clean = st.saved_revision == st.revision; - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = Some(photocraft_geom::Rect::EMPTY); + st.bump_selection_revision(); self.note_layer_change(before); Ok(()) } @@ -76,9 +65,9 @@ impl Session { // 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)); + 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(first) = st.snapshots_mut().iter_mut().find(|s| s.id == 0) && let Some(doc) = refresh_text_layers(&first.doc, &ids(true)) { first.doc = Arc::new(doc); @@ -95,7 +84,7 @@ impl Session { } 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) { + if first_is_doc && let Some(first) = st.snapshots_mut().iter_mut().find(|s| s.id == 0) { first.doc = doc.clone(); } let clean = st.saved_revision == st.revision; diff --git a/crates/engine/tests/it/actions_single_history.rs b/crates/engine/tests/it/actions_single_history.rs index bcda301f20..edf895404c 100644 --- a/crates/engine/tests/it/actions_single_history.rs +++ b/crates/engine/tests/it/actions_single_history.rs @@ -876,8 +876,8 @@ fn recorded_user_purge_undo_case(suffix: bool) { assert!(result.get("failed").is_none(), "singleState={single_state}, prefix={prefix}, suffix={suffix}: {result}"); let st = s.active().unwrap(); let after = st.doc.clone(); - let boundary = st.snapshots.last().unwrap().doc.clone(); - let snapshot = st.snapshots.last().unwrap().id; + let boundary = st.snapshots().last().unwrap().doc.clone(); + let snapshot = st.snapshots().last().unwrap().id; assert_eq!(boundary.layers[0].surface().unwrap().rgba(0, 0), if prefix { [0.0, 0.0, 1.0, 1.0] } else { [0.0, 1.0, 0.0, 1.0] }); assert!(st.history.row_of(old[removed].0).is_none(), "Purge Undo's removed predecessor returned"); assert!(st.history.row_of(old[0].0).is_some()); diff --git a/crates/ops/src/lib.rs b/crates/ops/src/lib.rs index 9ec59adad4..0e647b1490 100644 --- a/crates/ops/src/lib.rs +++ b/crates/ops/src/lib.rs @@ -89,8 +89,12 @@ pub struct History { /// A snapshot-backed alias of a folded row. Clear History moves this with its row source; /// a snapshot selected explicitly by the user remains separate in the document state. brush_source_snapshot: Option, + /// See [`History::generation`]. + generation: u64, } +static NEXT_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + /// What [`History::rollback`] needs to take the most recent [`History::record`] back. #[derive(Clone, Debug)] struct LastRecord { @@ -147,9 +151,23 @@ impl History { next_id: 1, brush_source: None, brush_source_snapshot: None, + generation: NEXT_GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed), } } + /// A number that identifies what the history holds: every call that changes it takes a fresh one, clones keep + /// it, and no two histories that differ share one, so a history put back in place of another (an action's + /// consolidated steps) still reads as a change. The public settings fields ([`History::max_states`], + /// [`History::max_bytes`], [`History::non_linear`]) are not part of it; they change the states only through + /// the calls that apply them, such as [`History::trim`]. + pub fn generation(&self) -> u64 { + self.generation + } + + fn changed(&mut self) { + self.generation = NEXT_GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + /// Record that `before` was replaced by a new current document via step `label`, which left /// `layers` targeted. /// @@ -158,6 +176,7 @@ impl History { /// reads `…, before, the former redo states (oldest first), the new step`, so the new step is /// appended at the end and every earlier state can still be stepped to. pub fn record(&mut self, label: impl Into, before: Arc, layers: LayerTarget) { + self.changed(); if self.max_bytes == 0 { self.tiles = None; } @@ -225,6 +244,7 @@ impl History { /// Set the layers the current document targets from its creation on: when it is first /// opened, or when its step coalesces or changes the selection after recording. pub fn set_current_layers(&mut self, layers: LayerTarget) { + self.changed(); self.current_layers = layers; } @@ -240,6 +260,7 @@ impl History { /// Note layers whose visibility the current step changed (after [`History::record`], and /// again when a later change coalesces into the step). pub fn add_current_visibility(&mut self, ids: &[LayerId]) { + self.changed(); merge_ids(&mut self.current_visibility, ids); if let Some(capture) = &mut self.visibility_capture { merge_ids(Arc::make_mut(capture), ids); @@ -248,6 +269,7 @@ impl History { /// Retain only changes that recorded edits make undoable, across trimming and local purges. pub fn begin_visibility_capture(&mut self, prefix: &[LayerId]) { + self.changed(); self.visibility_capture = Some(Arc::new(prefix.to_vec())); } @@ -258,6 +280,7 @@ impl History { /// Release an action's accumulator when a purge leaves no grouped step to publish. pub fn end_visibility_capture(&mut self) { + self.changed(); self.visibility_capture = None; } @@ -270,6 +293,7 @@ impl History { /// intermediate state so the caller can retain its pixels as a normal history snapshot. /// A source already deleted before consolidation remains unresolved. pub fn preserve_action_brush_source(&mut self, later: &Self) -> Option { + self.changed(); let current = self.current_id; let prior_current = later.current_id; let collapsed = |id| { @@ -297,12 +321,14 @@ impl History { /// Retain a folded row through a native snapshot, without adding a visible Undo state. pub fn set_action_brush_snapshot(&mut self, snapshot: u64) { + self.changed(); self.brush_source = None; self.brush_source_snapshot = Some(snapshot); } /// Keep a folded source inactive until Undo Clear History restores its source context. pub fn set_cleared_brush_snapshot(&mut self, snapshot: u64) { + self.changed(); if let Some(cleared) = &mut self.cleared { cleared.brush_source = None; cleared.brush_source_snapshot = Some(snapshot); @@ -312,6 +338,7 @@ impl History { /// Undo: `current` becomes redoable; returns the document to make current and the layers it /// targeted when it was created. pub fn undo(&mut self, current: Arc) -> Option<(Arc, LayerTarget)> { + self.changed(); // Undo Clear History: the cleared states come back; the document doesn't change. if let Some(cleared) = self.cleared.take() { let Cleared { undo, redo, brush_source, brush_source_snapshot } = *cleared; @@ -341,6 +368,7 @@ impl History { /// Redo: the mirror of [`Self::undo`]. pub fn redo(&mut self, current: Arc) -> Option<(Arc, LayerTarget)> { + self.changed(); let next = self.redo.pop()?; self.last_record = None; if let Some(tiles) = &mut self.tiles { @@ -412,6 +440,7 @@ impl History { /// that state while older states fall off, and the state itself is kept when it would fall off /// the history (by count or memory); `false` if there is no such row. pub fn set_brush_source(&mut self, i: usize) -> bool { + self.changed(); let Some(id) = self.row_id(i) else { return false }; self.brush_source = Some(id); self.brush_source_snapshot = None; @@ -435,12 +464,14 @@ impl History { /// Rename the current step (e.g. after folding several steps into one with [`Self::purge_last`]). pub fn set_current_label(&mut self, label: impl Into) { + self.changed(); self.current_label = label.into(); } /// The user's Edit › Purge › Undo also starts a new action-history boundary. Internal /// compound commands use [`Self::purge_last`] to fold their records without this boundary. pub fn purge_undo(&mut self) -> bool { + self.changed(); let purged = self.purge_last(); if purged { self.purge_generation = self.purge_generation.wrapping_add(1); @@ -451,6 +482,7 @@ impl History { /// Forget the most recent undo state and every redo state: the /// last step can no longer be undone and its pixels are released. pub fn purge_last(&mut self) -> bool { + self.changed(); self.clear_redo(); self.last_record = None; if self.cleared.take().is_some() { @@ -472,6 +504,7 @@ impl History { /// either, since every later state would lose its starting point in the list. Returns /// whether a state was removed. pub fn remove(&mut self, i: usize) -> bool { + self.changed(); if i == 0 { return false; } @@ -492,6 +525,7 @@ impl History { /// them) and nothing else: the History panel's Delete on a dimmed state in non-linear /// history. Returns whether a state was removed. pub fn remove_later(&mut self, j: usize) -> bool { + self.changed(); let Some(k) = self.redo.len().checked_sub(j.saturating_add(1)) else { return false }; let state = self.redo.remove(k); self.last_record = None; @@ -510,6 +544,7 @@ impl History { /// redoable: the current state is deleted while the redo states (later states in the /// list) stay. Returns the document to make current and the layers it targeted. pub fn drop_current(&mut self) -> Option<(Arc, LayerTarget)> { + self.changed(); let prev = self.undo.pop_back()?; self.last_record = None; if let Some(tiles) = &mut self.tiles { @@ -534,6 +569,7 @@ impl History { /// (changing nothing) when something else changed the list since that record, e.g. an undo; /// the caller then falls back to [`History::undo`]. pub fn rollback(&mut self) -> Option<(Arc, LayerTarget)> { + self.changed(); let held = self.last_record.as_ref()?; if self.undo.len().saturating_add(held.evicted.len()) <= held.moved { return None; @@ -572,11 +608,13 @@ impl History { /// Keep identifiers consumed by a completed compound operation reserved when its history /// is consolidated from an earlier snapshot. Removed rows must not name a later state. pub fn reserve_ids_from(&mut self, later: &Self) { + self.changed(); self.next_id = self.next_id.max(later.next_id); } /// Forget the redo states, e.g. after undoing half of a compound step that failed. pub fn clear_redo(&mut self) { + self.changed(); if !self.redo.is_empty() { self.last_record = None; } @@ -592,6 +630,7 @@ impl History { /// goes back to the default, the oldest state held (now the current one): a source set on a /// state the purge removed would otherwise leave no source. pub fn clear(&mut self) { + self.changed(); self.purge_generation = self.purge_generation.wrapping_add(1); self.last_record = None; self.current_visibility.clear(); @@ -604,6 +643,7 @@ impl History { /// Make the History Brush's source the default again (the oldest state held), pinning no state. pub fn reset_brush_source(&mut self) { + self.changed(); self.brush_source = None; self.brush_source_snapshot = None; } @@ -614,6 +654,7 @@ impl History { /// The History Brush's source goes back to the default until that undo, as in [`Self::clear`]. /// Returns false (and changes nothing) when the current state is the only one. pub fn clear_states(&mut self) -> bool { + self.changed(); if self.undo.is_empty() && self.redo.is_empty() { return false; } @@ -624,6 +665,7 @@ impl History { /// Preserve a Clear already accepted during an action when its command-local rows fold /// into this captured history, which may have no rows. Ordinary empty Clear still refuses. pub fn preserve_action_clear(&mut self, later: &Self) { + self.changed(); if later.is_cleared() && !self.is_cleared() { self.clear_states_including_empty(); } @@ -718,6 +760,14 @@ impl History { /// so they can't take memory beyond it unseen (#4530). The most recent state is still always /// kept. pub fn trim_with(&mut self, current: &Document, pinned: &[&Document]) -> usize { + let dropped = self.drop_over_budget(current, pinned); + if dropped > 0 { + self.changed(); + } + dropped + } + + fn drop_over_budget(&mut self, current: &Document, pinned: &[&Document]) -> usize { // While Clear History can be undone, the cleared states are what history holds: the // oldest of them go first, as the list's would. The source set before it stays pinned. let (undo, redo, brush_source) = match &mut self.cleared { diff --git a/crates/ui-egui/src/app/doc_queries.rs b/crates/ui-egui/src/app/doc_queries.rs index ced9ba9730..5c7b09edfe 100644 --- a/crates/ui-egui/src/app/doc_queries.rs +++ b/crates/ui-egui/src/app/doc_queries.rs @@ -1,30 +1,38 @@ -//! What the chrome reads from a document at the cost of a walk or a parse, computed once per document revision: -//! the status bar's sizes and profile, the File Info copyright mark of the titles, the empty frames the canvas marks, -//! whether linked files need watching, and the pasteboard's uncovered work (once per revision of the document the -//! canvas shows). +//! What the chrome reads from a document at the cost of a walk, a parse or a list rebuild, computed once per change +//! of what it reads: the status bar's sizes and profile, the File Info copyright mark of the titles, the empty frames +//! the canvas marks, whether linked files need watching, the artboard pages, the layers a Move drag takes along and +//! the pasteboard's uncovered work (once per document revision, the last also per revision of the document the +//! canvas shows), and the History panel's rows (once per change of the history or its snapshots). use std::collections::HashMap; use std::sync::{Arc, Mutex, PoisonError}; use craft::behavior::kurbo::Rect as DocRect; use craft::ui::bars::StatusValues; +use craft::ui::canvas::PageFrame; +use craft::ui::patterns::panels::HistoryRow; use photocraft_doc::{DocId, LayerId}; use photocraft_engine::{DocState, Session}; use crate::i18n::Lang; -/// The derived values of every open document, each entry valid for one `DocState::revision`. Held behind a lock -/// because the chrome reads them through `&PhotocraftApp`. +/// The derived values of every open document. Held behind a lock because the chrome reads them through +/// `&PhotocraftApp`. #[derive(Default)] pub(crate) struct DocQueries(Mutex); #[derive(Default)] struct Entries { - /// `Session::documents_generation` when closed documents were last dropped. + /// `Session::documents_generation` the entries were made under. A document closed and another opened with the + /// same id starts at a revision the old entry may also have had, so the entries go whenever the set changes. documents: u64, by_doc: HashMap, + /// How many values were computed: the trials' count of rebuilds. + builds: u64, } +/// One document's values. Those keyed on the document revision are valid for `revision`; the History rows carry +/// their own key. #[derive(Default)] struct Entry { revision: u64, @@ -33,68 +41,124 @@ struct Entry { copyrighted: Option, empty_frames: Option>, has_links: Option, + pages: Option>, + moving: Option, /// The uncovered rects and the display revision of the document they were measured on. uncovered: Option<(u64, Arc<[DocRect]>)>, + /// The History rows and the history and snapshot generations they were built from. + history: Option<((u64, u64), Arc<[HistoryRow]>)>, +} + +/// The layers of a document a Move tool drag moves, before the live text edit and Free Transform are added. +#[derive(Clone)] +pub(crate) struct MovingLayers { + /// The selected layers. + pub(crate) selected: Arc<[LayerId]>, + /// What moves whole with them: the layers linked to them and everything inside a moved group. + pub(crate) whole: Arc<[LayerId]>, } impl DocQueries { - /// Runs `f` on the entry of `st`, emptied first when the document moved past the entry's revision. - fn with(&self, session: &Session, st: &DocState, f: impl FnOnce(&mut Entry) -> R) -> R { + /// Runs `f` on the entry of `st` and the build count, the revision-keyed values emptied first when the document + /// moved past the entry's revision. + fn with(&self, session: &Session, st: &DocState, f: impl FnOnce(&mut Entry, &mut u64) -> R) -> R { let mut entries = self.0.lock().unwrap_or_else(PoisonError::into_inner); - let documents = session.documents_generation(); - if entries.documents != documents { - entries.by_doc.retain(|id, _| session.documents().iter().any(|open| open.doc.id == *id)); - entries.documents = documents; + let Entries { documents, by_doc, builds } = &mut *entries; + let open = session.documents_generation(); + if *documents != open { + by_doc.clear(); + *documents = open; } - let entry = entries.by_doc.entry(st.doc.id).or_default(); + let entry = by_doc.entry(st.doc.id).or_default(); if entry.revision != st.revision { - *entry = Entry { revision: st.revision, ..Entry::default() }; + *entry = Entry { revision: st.revision, history: entry.history.take(), ..Entry::default() }; } - f(entry) + f(entry, builds) + } + + /// How many values have been computed since the app started; equal counts mean nothing was rebuilt. + #[cfg(test)] + pub(crate) fn builds(&self) -> u64 { + self.0.lock().unwrap_or_else(PoisonError::into_inner).builds } /// The status bar's values about `st` in the current language, `compute`d on the first read after a change. pub(crate) fn status(&self, session: &Session, st: &DocState, compute: impl FnOnce() -> StatusValues) -> StatusValues { let lang = crate::i18n::current(); - self.with(session, st, |entry| match &entry.status { + self.with(session, st, |entry, builds| match &entry.status { Some((made_in, values)) if *made_in == lang => values.clone(), - _ => entry.status.insert((lang, compute())).1.clone(), + _ => built(builds, &mut entry.status, || (lang, compute())).1.clone(), }) } /// Whether File Info marks `st` Copyrighted, read from its XMP on the first read after a change. pub(crate) fn copyrighted(&self, session: &Session, st: &DocState) -> bool { - self.with(session, st, |entry| *entry.copyrighted.get_or_insert_with(|| photocraft_engine::file_cmds::copyright_marked(st.doc.metadata.xmp.as_deref()))) + self.with(session, st, |entry, builds| { + *cached(builds, &mut entry.copyrighted, || photocraft_engine::file_cmds::copyright_marked(st.doc.metadata.xmp.as_deref())) + }) } /// The visible frames of `st` with nothing placed in them, which the canvas marks with a placeholder. pub(crate) fn empty_frames(&self, session: &Session, st: &DocState) -> Arc<[LayerId]> { - self.with(session, st, |entry| { - entry - .empty_frames - .get_or_insert_with(|| { - let doc = &st.doc; - doc.walk() - .into_iter() - .filter(|(path, _, l)| l.frame.is_some() && l.children().is_some_and(<[_]>::is_empty) && doc.shown_at(path)) - .map(|(_, _, l)| l.id) - .collect() - }) - .clone() + self.with(session, st, |entry, builds| { + cached(builds, &mut entry.empty_frames, || { + let doc = &st.doc; + doc.walk() + .into_iter() + .filter(|(path, _, l)| l.frame.is_some() && l.children().is_some_and(<[_]>::is_empty) && doc.shown_at(path)) + .map(|(_, _, l)| l.id) + .collect() + }) + .clone() }) } /// Whether `st` has linked smart objects, whose files the link watcher scans. pub(crate) fn has_linked_files(&self, session: &Session, st: &DocState) -> bool { - self.with(session, st, |entry| *entry.has_links.get_or_insert_with(|| !photocraft_engine::link_watch::linked_files(&st.doc).is_empty())) + self.with(session, st, |entry, builds| *cached(builds, &mut entry.has_links, || !photocraft_engine::link_watch::linked_files(&st.doc).is_empty())) + } + + /// The canvas's page frames of `st`, `compute`d on the first read after a change (the active layer, and so the + /// active frame, moves the revision). + pub(crate) fn pages(&self, session: &Session, st: &DocState, compute: impl FnOnce() -> Vec) -> Arc<[PageFrame]> { + self.with(session, st, |entry, builds| cached(builds, &mut entry.pages, || compute().into()).clone()) + } + + /// The layers of `st` a Move drag moves, `compute`d on the first read after a change (a layer selection moves the + /// revision). + pub(crate) fn moving(&self, session: &Session, st: &DocState, compute: impl FnOnce() -> MovingLayers) -> MovingLayers { + self.with(session, st, |entry, builds| cached(builds, &mut entry.moving, compute).clone()) } /// Where the shown layers draw outside the artboards of `st`, for the document the canvas shows at display /// revision `shown`, `compute`d when either changes. pub(crate) fn uncovered(&self, session: &Session, st: &DocState, shown: u64, compute: impl FnOnce() -> Vec) -> Arc<[DocRect]> { - self.with(session, st, |entry| match &entry.uncovered { + self.with(session, st, |entry, builds| match &entry.uncovered { Some((at, rects)) if *at == shown => rects.clone(), - _ => entry.uncovered.insert((shown, compute().into())).1.clone(), + _ => built(builds, &mut entry.uncovered, || (shown, compute().into())).1.clone(), + }) + } + + /// The History panel's rows of `st`, `compute`d when its history or its snapshots change. + pub(crate) fn history_rows(&self, session: &Session, st: &DocState, compute: impl FnOnce() -> Vec) -> Arc<[HistoryRow]> { + let key = (st.history.generation(), st.snapshots_generation()); + self.with(session, st, |entry, builds| match &entry.history { + Some((at, rows)) if *at == key => rows.clone(), + _ => built(builds, &mut entry.history, || (key, compute().into())).1.clone(), }) } } + +/// `slot`'s value, computed (and counted in `builds`) when it has none. +fn cached<'a, T>(builds: &mut u64, slot: &'a mut Option, compute: impl FnOnce() -> T) -> &'a T { + if slot.is_none() { + *builds += 1; + } + slot.get_or_insert_with(compute) +} + +/// Puts a freshly computed value in `slot`, counted in `builds`. +fn built<'a, T>(builds: &mut u64, slot: &'a mut Option, compute: impl FnOnce() -> T) -> &'a T { + *builds += 1; + slot.insert(compute()) +} diff --git a/crates/ui-egui/src/app/thumbs.rs b/crates/ui-egui/src/app/thumbs.rs index 619b306c10..0677b17c23 100644 --- a/crates/ui-egui/src/app/thumbs.rs +++ b/crates/ui-egui/src/app/thumbs.rs @@ -18,7 +18,7 @@ pub(crate) struct SnapshotThumbs<'a> { impl<'a> SnapshotThumbs<'a> { /// The thumbnails of the snapshots of document `doc` (none when it is not open). pub(crate) fn new(app: &'a PhotocraftApp, doc: DocId) -> Self { - let snapshots = app.session.documents().iter().find(|st| st.doc.id == doc).map_or(&[][..], |st| &st.snapshots[..]); + let snapshots = app.session.documents().iter().find(|st| st.doc.id == doc).map_or(&[][..], |st| st.snapshots()); Self { doc, snapshots } } } diff --git a/crates/ui-egui/src/canvas/artboard_ui.rs b/crates/ui-egui/src/canvas/artboard_ui.rs index 93ecee63a6..1966f9c2b8 100644 --- a/crates/ui-egui/src/canvas/artboard_ui.rs +++ b/crates/ui-egui/src/canvas/artboard_ui.rs @@ -3,6 +3,8 @@ //! the document is `layer.artboard.set` and friends. View › Fit Artboard on Screen is the //! canvas's `ViewCommands::FitArtboard`, aimed at the active frame `pages` marks. +use std::sync::Arc; + use craft::behavior::EditEvent; use craft::behavior::kurbo::{Rect as DocRect, Size}; use craft::draw::ui::artboard::{ArtboardBackground as BoardBackground, ArtboardItem, ArtboardPreset, ArtboardProperties}; @@ -23,10 +25,12 @@ fn doc_rect(r: photocraft_geom::Rect) -> DocRect { /// One frame per artboard of document `idx`, in `doc.artboards()` order. The active layer's board /// is the active frame, the others are marked inactive. The frames carry no fill: the document /// picture paints each board's background. -pub(crate) fn pages(app: &PhotocraftApp, idx: usize) -> Vec { - let Some(st) = app.session.documents().get(idx) else { return Vec::new() }; - let active = st.active_layer.and_then(|id| st.doc.artboard_of(id)); - st.doc.artboards().into_iter().map(|(id, name, a)| PageFrame::new(doc_rect(a.rect)).name(name).active(active == Some(id))).collect() +pub(crate) fn pages(app: &PhotocraftApp, idx: usize) -> Arc<[PageFrame]> { + let Some(st) = app.session.documents().get(idx) else { return Arc::new([]) }; + app.doc_queries.pages(&app.session, st, || { + let active = st.active_layer.and_then(|id| st.doc.artboard_of(id)); + st.doc.artboards().into_iter().map(|(id, name, a)| PageFrame::new(doc_rect(a.rect)).name(name).active(active == Some(id))).collect() + }) } /// Where visible layers outside the boards draw: Photoshop shows those over the pasteboard, so a diff --git a/crates/ui-egui/src/canvas/snap_ui.rs b/crates/ui-egui/src/canvas/snap_ui.rs index 8463bbff0a..a9e314dd45 100644 --- a/crates/ui-egui/src/canvas/snap_ui.rs +++ b/crates/ui-egui/src/canvas/snap_ui.rs @@ -18,6 +18,7 @@ use photocraft_engine::layer_multi_cmds::move_targets; use photocraft_engine::snap::{layer_rect, target_rect_of}; use crate::PhotocraftApp; +use crate::app::doc_queries::MovingLayers; use crate::state::Tool; /// What the cached targets were built from. @@ -60,13 +61,17 @@ fn moving_set(app: &PhotocraftApp) -> Vec { if moves_as_move_tool(app) && let Some(st) = app.session.active() { - let selected = st.selected_layers(); + let moving = app.doc_queries.moving(&app.session, st, || { + let selected = st.selected_layers(); + let whole = crate::move_ui::with_descendants(&st.doc, &move_targets(&st.doc, &selected)); + MovingLayers { selected: selected.into(), whole: whole.into() } + }); // Selected pixels float off the selected layers alone (a floating piece never snaps to its own layer), so // the layers linked to them stay put and stay targets. if !crate::move_ui::moves_selected_pixels_with(app, Tool::Move) { - set.extend(crate::move_ui::with_descendants(&st.doc, &move_targets(&st.doc, &selected))); + set.extend_from_slice(&moving.whole); } - set.extend(selected); + set.extend_from_slice(&moving.selected); } if let Some(edit) = app.ui.text_edit.as_ref() { set.push(LayerId(edit.layer)); diff --git a/crates/ui-egui/src/dialogs/snapshot_dialog.rs b/crates/ui-egui/src/dialogs/snapshot_dialog.rs index 8559d8bc26..7c4112fdf8 100644 --- a/crates/ui-egui/src/dialogs/snapshot_dialog.rs +++ b/crates/ui-egui/src/dialogs/snapshot_dialog.rs @@ -95,7 +95,7 @@ mod tests { let id = super::open(&mut app).unwrap(); set(&mut app, id, "name", json!(typed)).unwrap(); crate::dialogs::confirm(&mut app, &ctx, id).unwrap(); - assert_eq!(app.session.active().unwrap().snapshots.last().unwrap().name, want); + 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/doc_revision_trials.rs b/crates/ui-egui/src/doc_revision_trials.rs index ad03324a7b..f3d40b17d9 100644 --- a/crates/ui-egui/src/doc_revision_trials.rs +++ b/crates/ui-egui/src/doc_revision_trials.rs @@ -1,7 +1,9 @@ //! Count trials for what the chrome reads from the document each frame (#15709): a layer thumbnail follows its own -//! layer's pixels and nothing else, and a frame that changes nothing walks no document. +//! layer's pixels and nothing else, the Layers rows follow every change they show, and a frame that changes nothing +//! walks no document and rebuilds nothing derived from it. use craft::layers::ui::thumbs::{LayerThumb, ThumbContents}; +use craft::layers::ui::tree::LayerTree; use craft::ui::primitives::textures::{ThumbRequest, ThumbSource}; use egui_kittest::Harness; use photocraft_doc::{Fill, Layer, LayerContent, LayerId, PixelFormat}; @@ -9,7 +11,7 @@ use photocraft_engine::Session; use serde_json::json; use crate::PhotocraftApp; -use crate::panels::layers_tree::PhotoThumbs; +use crate::panels::layers_tree::{PhotoLayers, PhotoThumbs}; use crate::state::Tool; type H = Harness<'static, Box>; @@ -95,9 +97,46 @@ fn thumbnail_revisions_follow_only_their_own_layer() { ); } -/// With the status bar, the document tabs, the Layers panel and the Move tool's snapping on screen, a frame that -/// changes nothing walks no document and rebuilds no layer index; after an edit the next idle frames walk none -/// either, so what the chrome derives is rebuilt once per change, not per frame. The panels' command states +/// The Layers panel walks its rows again only when their revision moves: a rename and both disclosure toggles (a +/// layer's effects list, a group) move it, idle frames don't. +#[test] +fn layers_rows_follow_renames_and_both_toggles() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + let a = LayerId(s.execute("layer.new.layer", json!({"name": "A"})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.layerStyle.dropShadow", json!({"layer": a.0})).unwrap(); + let group = Layer::group("G", vec![Layer::raster("inner", PixelFormat::RGBA8)]); + let g = group.id; + s.edit("group", |doc, _| { + doc.layers.push(group); + Ok(()) + }) + .unwrap(); + let mut h = harness(s); + let revision = |h: &H| { + let app = h.state(); + PhotoLayers::new(app, app.session.active().unwrap(), &Default::default(), false, None).revision() + }; + let start = revision(&h); + assert!(start.is_some()); + h.run_steps(10); + assert_eq!(revision(&h), start, "idle frames keep the rows"); + + let moves = |h: &mut H, command: &str, params: serde_json::Value| { + let before = revision(h); + h.state_mut().run(command, params).unwrap(); + h.run_steps(2); + assert_ne!(revision(h), before, "{command} moves the rows' revision"); + }; + moves(&mut h, "layer.renameLayer", json!({"layer": a.0, "name": "Renamed"})); + moves(&mut h, "layer.setEffectsExpanded", json!({"layer": a.0, "expanded": false})); + moves(&mut h, "layer.setExpanded", json!({"layer": g.0, "expanded": false})); +} + +/// With the status bar, the document tabs, the Layers and History panels, an artboard's pasteboard and the Move +/// tool's snapping on screen, a frame that changes nothing walks no document, rebuilds no layer index and computes +/// no derived value (title, status, pages, uncovered work, moving layers, History rows); after an edit they are +/// computed again once, and the next idle frames compute none. The panels' command states /// (`panels::registry::states`, run once a frame) still ask some commands' preconditions, which walk; #15709 task a /// moves those onto revisions, and until then the trial counts the walks of one such run per frame. #[test] @@ -113,23 +152,32 @@ fn idle_frames_walk_no_document() { Ok(()) }) .unwrap(); + s.execute("layer.new.artboard", json!({"rect": [0, 0, 200, 150]})).unwrap(); let mut h = harness(s); + h.state_mut().run("window.toggle.history", json!({"show": true})).unwrap(); h.state_mut().ui.tool = Tool::Move; h.run_steps(4); let serial = |h: &H| h.state().session.active().unwrap().doc.layers.index().serial(); + let builds = |h: &H| h.state().doc_queries.builds(); let states = |h: &H| { let walks = photocraft_doc::walks(); drop(crate::panels::registry::states(h.state())); photocraft_doc::walks() - walks }; - let (walks, index) = (photocraft_doc::walks(), serial(&h)); + let (walks, index, built) = (photocraft_doc::walks(), serial(&h), builds(&h)); h.run_steps(10); assert_eq!((photocraft_doc::walks() - walks, serial(&h)), (10 * states(&h), index), "idle frames walk nothing outside the command states"); + assert_eq!(builds(&h), built, "idle frames compute nothing"); + // The new artboard is the active layer; the fill goes on a pixel layer. + let pixels = h.state().session.active().unwrap().doc.layers.iter().find(|l| l.name == "layer 0").unwrap().id; + h.state_mut().run("layer.select", json!({"layer": pixels.0})).unwrap(); h.state_mut().run("select.rect", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); h.state_mut().run("edit.fill", json!({"contents": "black"})).unwrap(); h.run_steps(4); - let (per_frame, walks) = (states(&h), photocraft_doc::walks()); + assert!(builds(&h) > built, "an edit computes the values again"); + let (per_frame, walks, built) = (states(&h), photocraft_doc::walks(), builds(&h)); h.run_steps(10); assert_eq!(photocraft_doc::walks() - walks, 10 * per_frame, "after an edit, idle frames walk nothing again"); + assert_eq!(builds(&h), built, "after an edit, idle frames compute nothing again"); } diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs index 4f7e76ee4a..420ae5de8b 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -16,7 +16,7 @@ pub(super) fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let events = { let shown: &PhotocraftApp = app; let st = shown.session.active(); - let rows = st.map(rows).unwrap_or_default(); + let rows: std::sync::Arc<[HistoryRow]> = st.map_or_else(|| Vec::new().into(), |st| shown.doc_queries.history_rows(&shown.session, st, || rows(st))); let thumbs = st.map(|st| SnapshotThumbs::new(shown, st.doc.id)); let mut panel = HistoryPanel::new(&rows, current_key(shown)).source(st.and_then(source_key)).can_delete(|key| can_delete(shown, key)).footer(footer(shown)); @@ -38,7 +38,7 @@ pub(super) fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { /// oldest to newest ending with the current one, then the redo states, next redo first. A state's key is /// its row id, which stays when the states before it go. pub(crate) fn rows(st: &photocraft_engine::DocState) -> Vec { - let mut rows: Vec = st.snapshots.iter().map(|snap| HistoryRow::snapshot(snap.id, snap.name.clone())).collect(); + let mut rows: Vec = st.snapshots().iter().map(|snap| HistoryRow::snapshot(snap.id, snap.name.clone())).collect(); let past = st.history.past_len(); let labels = st.history.entries().into_iter().chain(st.history.redo_labels().map(str::to_string)); for (i, label) in labels.enumerate() { @@ -71,7 +71,7 @@ fn source_key(st: &photocraft_engine::DocState) -> Option { pub(crate) fn can_delete(app: &PhotocraftApp, key: &HistoryKey) -> bool { let Some(st) = app.session.active() else { return false }; match *key { - HistoryKey::Snapshot(id) => st.snapshots.iter().any(|snap| snap.id == id), + HistoryKey::Snapshot(id) => st.snapshots().iter().any(|snap| snap.id == id), HistoryKey::State(id) => match st.history.row_of(id) { None | Some(0) => false, Some(row) if row > st.history.past_len() => st.history.non_linear && app.session.is_enabled("history.deleteState"), @@ -260,7 +260,7 @@ pub(crate) fn select_snapshot(app: &mut PhotocraftApp, id: u64) { pub(crate) fn selected_snapshot(app: &PhotocraftApp) -> Option { let st = app.session.active()?; let (doc, id, spot) = app.ui.history_snapshot.as_ref()?; - (*doc == st.doc.id && *spot == history_spot(st) && st.snapshots.iter().any(|snap| snap.id == *id)).then_some(*id) + (*doc == st.doc.id && *spot == history_spot(st) && st.snapshots().iter().any(|snap| snap.id == *id)).then_some(*id) } /// Drops a selection that no longer holds, so the history returning to the same spot later does not diff --git a/crates/ui-egui/src/panels/history_menu_ui.rs b/crates/ui-egui/src/panels/history_menu_ui.rs index 7ae5c1bcbe..b3f859a00a 100644 --- a/crates/ui-egui/src/panels/history_menu_ui.rs +++ b/crates/ui-egui/src/panels/history_menu_ui.rs @@ -163,9 +163,9 @@ mod tests { fn delete_removes_the_selected_snapshot() { let mut app = app(); app.run("history.newSnapshot", json!({})).unwrap(); - let snaps = |app: &PhotocraftApp| app.session.active().unwrap().snapshots.len(); + let snaps = |app: &PhotocraftApp| app.session.active().unwrap().snapshots().len(); let before = snaps(&app); - let id = app.session.active().unwrap().snapshots.last().unwrap().id; + let id = app.session.active().unwrap().snapshots().last().unwrap().id; crate::panels::select_snapshot(&mut app, id); let steps = states(&app); fire(&mut app, "history.deleteState"); diff --git a/crates/ui-egui/src/panels/history_panel_select_tests.rs b/crates/ui-egui/src/panels/history_panel_select_tests.rs index 6b35064de0..443a3d1f86 100644 --- a/crates/ui-egui/src/panels/history_panel_select_tests.rs +++ b/crates/ui-egui/src/panels/history_panel_select_tests.rs @@ -55,11 +55,11 @@ fn current_key(app: &PhotocraftApp) -> HistoryKey { } fn snapshots(app: &PhotocraftApp) -> usize { - app.session.active().unwrap().snapshots.len() + app.session.active().unwrap().snapshots().len() } fn last_snapshot(app: &PhotocraftApp) -> u64 { - app.session.active().unwrap().snapshots.last().unwrap().id + app.session.active().unwrap().snapshots().last().unwrap().id } fn top_pixel(app: &PhotocraftApp) -> [f32; 4] { @@ -169,7 +169,7 @@ fn snapshot_rows_select_rename_and_delete() { apply(&mut app, HistoryEvent::rename(id, "Lesson start")); assert_eq!(app.perf.last_command, "history.renameSnapshot"); - let names: Vec = app.session.active().unwrap().snapshots.iter().skip(1).map(|s| s.name.clone()).collect(); + let names: Vec = app.session.active().unwrap().snapshots().iter().skip(1).map(|s| s.name.clone()).collect(); assert_eq!(names, ["Lesson start"]); let kept = steps(&app); @@ -338,7 +338,7 @@ fn a_new_state_at_the_history_limit_deselects_the_snapshot() { let mut app = app(); app.run("history.newSnapshot", json!({})).unwrap(); // What a click on the snapshot row does: the command, then the selection at the state it made. - let id = app.session.active().unwrap().snapshots[0].id; + let id = app.session.active().unwrap().snapshots()[0].id; app.run("history.selectSnapshot", json!({"snapshot": id})).unwrap(); select_snapshot(&mut app, id); assert_eq!(selected_snapshot(&app), Some(id), "the snapshot is selected"); @@ -433,7 +433,7 @@ fn snapshot_thumbnails_follow_their_document() { assert_eq!(first, revision(&app), "the same picture keeps its revision"); // The revision follows the snapshot document's `Arc` address, so each closed document stays alive for the // test: a freed address handed to the next document would read as the same picture. - let mut closed = vec![app.session.active().unwrap().snapshots[0].doc.clone()]; + let mut closed = vec![app.session.active().unwrap().snapshots()[0].doc.clone()]; // Closed and reopened with the same id. app.session.close(0); app.sync_views(); @@ -442,7 +442,7 @@ fn snapshot_thumbnails_follow_their_document() { let reopened = revision(&app); assert_ne!(reopened, first); // Closed and reopened with no sync in between: still a fresh one. - closed.push(app.session.active().unwrap().snapshots[0].doc.clone()); + closed.push(app.session.active().unwrap().snapshots()[0].doc.clone()); app.session.close(0); app.session.add_document(doc, None); assert_ne!(revision(&app), reopened); diff --git a/crates/ui-egui/src/panels/layers_tree.rs b/crates/ui-egui/src/panels/layers_tree.rs index 16b95a8811..8517a35879 100644 --- a/crates/ui-egui/src/panels/layers_tree.rs +++ b/crates/ui-egui/src/panels/layers_tree.rs @@ -636,7 +636,7 @@ impl ThumbSource> for PhotoThumbs<'_> { let shown = crate::solid_fill_ui::thumbnail_color(self.app, self.doc.id, l.id, *color); Revision::of(&(shown.to_rgba8(), 1u8)).get() } - LayerContent::Fill(f) => f.fingerprint(), + LayerContent::Fill(f) => Revision::of(f).get(), _ => l.surface().map_or(0, generation), }, LayerThumbKind::Mask => l.mask.as_ref().map_or(0, |m| m.surface.generation()), diff --git a/crates/ui-egui/src/save_identity_tests.rs b/crates/ui-egui/src/save_identity_tests.rs index e4943e4529..4551cbe061 100644 --- a/crates/ui-egui/src/save_identity_tests.rs +++ b/crates/ui-egui/src/save_identity_tests.rs @@ -257,7 +257,7 @@ fn save_settings_start_at_the_opened_files_encoding() { /// The names of the active document's History panel snapshots. fn snapshots(app: &PhotocraftApp) -> Vec { - app.session.active().unwrap().snapshots.iter().map(|s| s.name.clone()).collect() + app.session.active().unwrap().snapshots().iter().map(|s| s.name.clone()).collect() } /// History Options › Automatically Create New Snapshot When Saving (#2966) through the desktop @@ -270,7 +270,7 @@ fn a_save_adds_one_snapshot_and_a_copy_none() { app.save_as(Some("saved.psd".into())).unwrap(); assert_eq!(snapshots(&app).len(), before + 1, "the save adds a snapshot"); let st = app.session.active().unwrap(); - assert!(std::sync::Arc::ptr_eq(&st.snapshots.last().unwrap().doc, &st.doc), "of the document as saved"); + assert!(std::sync::Arc::ptr_eq(&st.snapshots().last().unwrap().doc, &st.doc), "of the document as saved"); app.save_as(Some("saved.psd".into())).unwrap(); assert_eq!(snapshots(&app).len(), before + 1, "saving an unchanged document adds no duplicate"); @@ -301,7 +301,7 @@ fn a_background_save_snapshots_its_own_document() { assert_eq!(app.active_doc_id(), Ok(active), "the active document stays active"); assert_eq!(snapshots(&app).len(), active_snaps, "the active document gets no snapshot"); let st = app.session.documents().iter().find(|st| st.doc.id == saved_doc).unwrap(); - assert_eq!(st.snapshots.len(), saved_snaps + 1, "the saved document gets one"); + assert_eq!(st.snapshots().len(), saved_snaps + 1, "the saved document gets one"); assert_eq!(st.path.as_deref(), Some("background.psd")); } diff --git a/crates/ui-egui/src/text/served_fonts.rs b/crates/ui-egui/src/text/served_fonts.rs index ee52f89e23..44a1b6ecb5 100644 --- a/crates/ui-egui/src/text/served_fonts.rs +++ b/crates/ui-egui/src/text/served_fonts.rs @@ -104,7 +104,7 @@ 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() { - let first = st.snapshots.iter().find(|s| s.id == 0).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. diff --git a/crates/ui-egui/src/tools/crop_ui/tests.rs b/crates/ui-egui/src/tools/crop_ui/tests.rs index f230e48bc7..95a1ea379f 100644 --- a/crates/ui-egui/src/tools/crop_ui/tests.rs +++ b/crates/ui-egui/src/tools/crop_ui/tests.rs @@ -205,7 +205,7 @@ fn history_jumps_wait_for_a_pending_crop() { let mut app = app(SampleType::U8); app.run("history.newSnapshot", json!({})).unwrap(); app.run("image.canvasSize", json!({"width": 300, "height": 200})).unwrap(); - let snapshot = app.session.active().unwrap().snapshots[0].id; + let snapshot = app.session.active().unwrap().snapshots()[0].id; let frame = boxed(220.0, 120.0, 290.0, 190.0, 0.0); // A pass first: the tool holds a frame for the document it was made for, which Discard drops. crate::canvas::testing::frame(&mut app); diff --git a/crates/ui-egui/src/tools/retouch_ui/bar/history.rs b/crates/ui-egui/src/tools/retouch_ui/bar/history.rs index 45d908c1d5..7d22278db6 100644 --- a/crates/ui-egui/src/tools/retouch_ui/bar/history.rs +++ b/crates/ui-egui/src/tools/retouch_ui/bar/history.rs @@ -28,7 +28,7 @@ pub(crate) fn source_caption(app: &PhotocraftApp) -> SourceCaption { use photocraft_engine::history_source_cmds::{HistorySource, source}; let Some(st) = app.session.active() else { return SourceCaption::Deleted }; let named = || match source(st)? { - HistorySource::Snapshot(id) => st.snapshots.iter().find(|s| s.id == id).map(|s| SourceCaption::Named(s.name.clone())), + HistorySource::Snapshot(id) => st.snapshots().iter().find(|s| s.id == id).map(|s| SourceCaption::Named(s.name.clone())), HistorySource::State(idx) => { let entries = st.history.entries(); let name = if idx < entries.len() { entries.get(idx).cloned() } else { st.history.redo_labels().nth(idx - entries.len()).map(str::to_string) }?;