Merge #6088's current head (fix/snapshot-followups) into feat/history-snapshot-options

#3634 builds on #3567 with #6088's follow-ups and on #3535; it now carries the current head of each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
David MannandClaude Opus 5.5 committed 2026-10-21 11:36:42 +02:00
commit 87fbf348c1
5 files changed
+187 -40

No files matched your search

+37 -18
View File
@@ -247,6 +247,20 @@ pub struct DocState {
save_snapshot: Option<u64>,
}
/// `doc` with its type layers among `ids` re-rendered (`Session::refresh_type_layers`), or `None`
/// when none of them is a type layer of `doc`.
fn refresh_text_layers(doc: &Arc<photocraft_doc::Document>, ids: &[LayerId]) -> Option<photocraft_doc::Document> {
let mut out = (**doc).clone();
let mut changed = false;
for id in ids {
if let Some(photocraft_doc::Layer { content: photocraft_doc::LayerContent::Text(t), .. }) = out.layer_mut(*id) {
type_cmds::refresh(doc, t);
changed = true;
}
}
changed.then_some(out)
}
impl DocState {
/// Trim the history to its budget, counting the tiles only History panel snapshots hold
/// against it too (#4530). Returns how many states were dropped.
@@ -934,30 +948,35 @@ impl Session {
}
}
for doc_id in docs {
let mine = layers.iter().filter(|(d, _)| *d == doc_id);
let mine: Vec<LayerId> = layers.iter().filter(|(d, _)| *d == doc_id).map(|(_, id)| *id).collect();
if self.job_on(doc_id).is_some() {
busy.extend(mine);
busy.extend(mine.iter().map(|id| (doc_id, *id)));
continue;
}
let Some(st) = self.docs.iter_mut().find(|st| st.doc.id == doc_id) else { continue };
let snapshot = st.doc.clone();
let mut doc = (*snapshot).clone();
let mut changed = false;
for (_, id) in mine {
if let Some(photocraft_doc::Layer { content: photocraft_doc::LayerContent::Text(t), .. }) = doc.layer_mut(*id) {
type_cmds::refresh(&snapshot, t);
changed = true;
}
// The first snapshot is the document as opened (#2966, #6087): it was taken before the
// font arrived, so its type layers get the same refresh, or returning to it brings the
// fallback-font pixels back. While it still is the open document, it shares the
// refreshed one.
let first_is_doc = st.snapshots.iter().any(|s| s.id == 0 && Arc::ptr_eq(&s.doc, &st.doc));
if !first_is_doc
&& let Some(first) = st.snapshots.iter_mut().find(|s| s.id == 0)
&& let Some(doc) = refresh_text_layers(&first.doc, &mine)
{
first.doc = Arc::new(doc);
}
if changed {
let clean = st.saved_revision == st.revision;
st.doc = Arc::new(doc);
st.revision += 1;
if clean {
st.saved_revision = st.revision;
}
st.last_damage = None;
let Some(doc) = refresh_text_layers(&st.doc, &mine) else { continue };
let doc = Arc::new(doc);
if first_is_doc && let Some(first) = st.snapshots.iter_mut().find(|s| s.id == 0) {
first.doc = doc.clone();
}
let clean = st.saved_revision == st.revision;
st.doc = doc;
st.revision += 1;
if clean {
st.saved_revision = st.revision;
}
st.last_damage = None;
}
busy
}
+35
View File
@@ -1245,6 +1245,41 @@ mod tests {
assert!(s.active().unwrap().doc.layer(id).is_none());
}
/// The first History snapshot is the document as opened, taken before a served font arrived:
/// the refresh re-renders its type layers too, so returning to it keeps the real font (#6087).
#[test]
fn refreshing_type_layers_refreshes_the_first_snapshot() {
let mut s = session();
let id = LayerId(s.execute("type.create", json!({"text": "Hello", "size": 24})).unwrap()["layer"].as_u64().unwrap());
let mut stale = (*s.active().unwrap().doc).clone();
let Some(Layer { content: LayerContent::Text(t), .. }) = stale.layer_mut(id) else { panic!("not a type layer") };
t.cache = None;
let snap_cache = |s: &Session| match &s.active().unwrap().snapshots[0].doc.layer(id).unwrap().content {
LayerContent::Text(t) => t.cache.is_some(),
other => panic!("{}", other.kind_name()),
};
// Opened with the fallback font: the first snapshot is the open document itself.
s.add_document(stale.clone(), None);
let doc_id = s.active().unwrap().doc.id;
assert!(!snap_cache(&s));
assert!(s.refresh_type_layers(&[(doc_id, id)]).is_empty());
assert!(text_layer(&s, id.0).cache.is_some());
assert!(snap_cache(&s), "the first snapshot is refreshed with the document");
let st = s.active().unwrap();
assert!(Arc::ptr_eq(&st.snapshots[0].doc, &st.doc), "and still shares it");
// Edited since it opened: the snapshot is refreshed on its own, the edit stays.
s.add_document(stale, None);
let doc_id = s.active().unwrap().doc.id;
s.execute("layer.new.layer", json!({})).unwrap();
let layers = s.active().unwrap().doc.layers.len();
assert!(s.refresh_type_layers(&[(doc_id, id), (doc_id, LayerId(9999))]).is_empty());
assert!(snap_cache(&s));
assert!(text_layer(&s, id.0).cache.is_some());
let st = s.active().unwrap();
assert_eq!(st.doc.layers.len(), layers);
assert_eq!(st.snapshots[0].doc.layers.len(), layers - 1, "the snapshot keeps the document as opened");
}
#[test]
fn create_renders_and_is_undoable() {
let mut s = session();
+17 -8
View File
@@ -751,9 +751,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<photocraft_doc::LayerId, photocraft_geom::Rect>,
/// 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<Document>, egui::TextureHandle)>,
/// Snapshots whose live layer/mask keys were last used to prune thumbnail handles.
thumb_documents: Vec<(DocId, std::sync::Weak<Document>)>,
/// Content bounds cached per (key, revision): scanning a 36 MP layer every frame cost ~77 ms.
@@ -1371,6 +1372,7 @@ impl PhotocraftApp {
}
self.canvases.retain(|(doc, _), _| ids.contains(doc));
self.navigator_textures.retain(|doc, _| ids.contains(doc));
self.snapshot_thumbs.retain(|(doc, _), _| ids.contains(doc));
self.view_docs = ids;
self.prune_thumbs();
self.sync_mask_targets();
@@ -2437,11 +2439,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);
@@ -2456,7 +2465,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
}
+38 -8
View File
@@ -3453,11 +3453,11 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
if ctx.input(|i| i.pointer.any_released()) {
ctx.data_mut(|d| d.remove::<HistoryDrag>(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) {
@@ -3522,16 +3522,17 @@ fn selected_snapshot(ctx: &egui::Context, st: &photocraft_engine::DocState) -> O
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<u64>) -> Option<(&'static str, Value)> {
let t = Tokens::get(ui.ctx());
let st = app.session.active()?;
let (doc_id, snaps) = (st.doc.id, st.snapshots.clone());
let live: Vec<u64> = snaps.iter().map(|s| s.id).collect();
app.retain_snapshot_thumbs(doc_id, &live);
// Per document: snapshot ids restart in each, and a tab switch must not carry the edit over.
let rename_id = egui::Id::new(("history-snapshot-rename", doc_id));
let mut renaming: Option<(u64, String)> = ui.data(|d| d.get_temp(rename_id)).flatten();
@@ -3551,7 +3552,7 @@ fn snapshot_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, selected: Option<u6
}
let thumb = Rect::from_min_size(pos2(rect.left() + 28.0, rect.center().y - 14.0), vec2(28.0, 28.0));
widgets::checker(ui.painter(), thumb, 4.0);
let tex = app.snapshot_thumb(&ctx, doc_id, snap, &live);
let tex = app.snapshot_thumb(&ctx, doc_id, snap);
ui.painter().image(tex, thumb, Rect::from_min_max(egui::Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);
ui.painter().rect_stroke(thumb, 0.0, Stroke::new(1.0, t.separator), StrokeKind::Outside);
match renaming.as_mut().filter(|(id, _)| *id == snap.id) {
@@ -5394,6 +5395,35 @@ mod snapshot_row_tests {
}
}
/// 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]
+60 -6
View File
@@ -17,7 +17,12 @@ pub fn owns(fields: &Map<String, Value>) -> 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<u64> {
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<u64> {
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<String, Value>) -> Result<Value, String> {
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<String, Value>) {
// 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<String, Value>) {
}
});
}
#[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");
}
}