PhotoCraft: An open-source, photo editor written by scratch in pure Rust
perf(ui): Duotone and live-adjust display documents are built once per snapshot (#4527) (#4736)
FinnNk10b936f159bb
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 1cb3a14cb..231b4612c 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -1119,24 +1119,55 @@ pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Arreturn (doc.clone(), key);}}- if let Some((layer, params)) = &app.live_adjust- && let Some(l) = st.doc.layer(*layer)+ let snapshot = st.doc.clone();+ if let Some((layer, params)) = app.live_adjust.clone()+ && let Some(l) = snapshot.layer(layer)&& let LayerContent::Adjustment(a) = &l.content{- let kind = photocraft_engine::commands::adjustment_kind(a);- let preview = photocraft_engine::adjust_params::from_params(kind, params, Some(a), st.doc.mode).unwrap_or_else(|_| a.clone());- let mut doc = (*st.doc).clone();- if let Some(lm) = doc.layer_mut(*layer) {- lm.content = LayerContent::Adjustment(preview);- }let key = 1 + params.to_string().bytes().fold(0u64, |h, b| h.wrapping_mul(31).wrapping_add(b as u64));- return (std::sync::Arc::new(doc), key);+ let shown = memo_display(app, &snapshot, key, || {+ let kind = photocraft_engine::commands::adjustment_kind(a);+ let preview = photocraft_engine::adjust_params::from_params(kind, ¶ms, Some(a), snapshot.mode).unwrap_or_else(|_| a.clone());+ let mut doc = (*snapshot).clone();+ if let Some(lm) = doc.layer_mut(layer) {+ lm.content = LayerContent::Adjustment(preview);+ }+ Some(doc)+ });+ if let Some(doc) = shown {+ return (doc, key);+ }}// Duotone documents display through their inks.- if let Some(shown) = photocraft_engine::mode_cmds::display_document(&st.doc) {- return (std::sync::Arc::new(shown), 1 << 41);+ if let Some(shown) = memo_display(app, &snapshot, 1 << 41, || photocraft_engine::mode_cmds::display_document(&snapshot)) {+ return (shown, 1 << 41);}- (st.doc.clone(), 0)+ (snapshot, 0)+}++/// `display_doc`'s live-adjust and Duotone documents, built once per document snapshot and key+/// rather than on each of its 3–4 calls a frame (#4527): each build clones the whole document.+fn memo_display(+ app: &mut PhotocraftApp,+ snapshot: &std::sync::Arc<Document>,+ key: u64,+ build: impl FnOnce() -> Option<Document>,+) -> Option<std::sync::Arc<Document>> {+ let id = snapshot.id;+ if let Some((doc, k, shown)) = app.display_memo.get(&id)+ && *k == key+ && doc.ptr_eq(&std::sync::Arc::downgrade(snapshot))+ {+ return Some(shown.clone());+ }+ let Some(shown) = build().map(std::sync::Arc::new) else {+ app.display_memo.remove(&id);+ return None;+ };+ // Entries of closed documents go when another is stored.+ app.display_memo.retain(|_, (doc, _, _)| doc.strong_count() > 0);+ app.display_memo.insert(id, (std::sync::Arc::downgrade(snapshot), key, shown.clone()));+ Some(shown)}/// Longest side of the Navigator panel's image (about twice the panel's width, for HiDPI).@@ -7668,3 +7699,7 @@ mod rotation_preview_isolation_tests {assert!(ensure_filter_preview(&mut app, 0, &egui::Context::default()).is_none(), "an inactive tab must never inherit the command preview");}}++#[cfg(test)]+#[path = "canvas_display_memo_tests.rs"]+mod display_memo_tests;diff --git a/crates/ui-egui/src/canvas_display_memo_tests.rs b/crates/ui-egui/src/canvas_display_memo_tests.rsnew file mode 100644index 000000000..ec105be01--- /dev/null+++ b/crates/ui-egui/src/canvas_display_memo_tests.rs@@ -0,0 +1,46 @@+//! `display_doc` builds a Duotone or live-adjust document once per snapshot (#4527), not on each+//! of its calls in a frame.++use super::*;+use serde_json::json;++fn app() -> PhotocraftApp {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());+ app.run("file.new", json!({"width": 64, "height": 48, "mode": "gray"})).unwrap();+ app+}++#[test]+fn duotone_display_document_is_built_once_per_snapshot() {+ let mut app = app();+ app.run("image.mode.duotone", json!({"type": "duotone", "inks": [{"name": "Black"}, {"name": "Orange", "color": "#ff8000"}]})).unwrap();+ let (a, key) = display_doc(&mut app, 0);+ assert_eq!(key, 1 << 41);+ let (b, _) = display_doc(&mut app, 0);+ assert!(std::sync::Arc::ptr_eq(&a, &b), "the second call reuses the first's document");+ assert_eq!(a.layers.len(), app.session.documents()[0].doc.layers.len() + 1, "with the ink display layer");+ app.run("edit.fill", json!({"color": "#808080"})).unwrap();+ let (c, _) = display_doc(&mut app, 0);+ assert!(!std::sync::Arc::ptr_eq(&a, &c), "an edit builds it again");+ assert_eq!(c.layers.last().map(|l| l.name.as_str()), a.layers.last().map(|l| l.name.as_str()));+}++#[test]+fn live_adjust_document_is_built_once_per_setting() {+ let mut app = app();+ app.run("layer.newAdjustmentLayer.levels", json!({})).unwrap();+ let id = app.session.documents()[0].active_layer.unwrap();+ app.live_adjust = Some((id, json!({"inBlack": 20})));+ let (a, k1) = display_doc(&mut app, 0);+ let (b, k2) = display_doc(&mut app, 0);+ assert_eq!(k1, k2);+ assert!(std::sync::Arc::ptr_eq(&a, &b));+ app.live_adjust = Some((id, json!({"inBlack": 40})));+ let (c, k3) = display_doc(&mut app, 0);+ assert_ne!(k1, k3);+ assert!(!std::sync::Arc::ptr_eq(&a, &c), "a new setting builds it again");+ app.live_adjust = None;+ let (d, k4) = display_doc(&mut app, 0);+ assert_eq!(k4, 0);+ assert!(std::sync::Arc::ptr_eq(&d, &app.session.documents()[0].doc), "no preview: the document itself");+}diff --git a/crates/ui-egui/src/channels_panel.rs b/crates/ui-egui/src/channels_panel.rsindex e456cfabc..5d95cdffa 100644--- a/crates/ui-egui/src/channels_panel.rs+++ b/crates/ui-egui/src/channels_panel.rs@@ -65,7 +65,7 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {let ctx = ui.ctx().clone();let thumbs = app.channel_thumbs(&ctx);// The active layer's mask (Photoshop lists it, in italics, below the colour channels).- let masked = active_layer.and_then(|id| doc.layer(id)).filter(|l| l.mask.is_some()).cloned();+ let masked = active_layer.and_then(|id| doc.layer(id)).filter(|l| l.mask.is_some());let mask_tex = masked.as_ref().and_then(|l| Some(app.mask_thumb(&ctx, &doc, l.id, l.mask.as_ref()?)));let mask_targeted = masked.is_some()&& (app.ui.mask_target || view.target == ChannelTarget::LayerMask)diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 9792297eb..7781085cd 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -497,6 +497,9 @@ pub struct PhotocraftApp {canvases: HashMap<(DocId, u32), canvas::CanvasCache>,/// Navigator textures belong to open documents, not the lifetime of the egui context.navigator_textures: HashMap<DocId, canvas::NavigatorCache>,+ /// `canvas::display_doc`'s live-adjust and Duotone documents per document: (snapshot,+ /// preview key, the document shown).+ display_memo: HashMap<DocId, (std::sync::Weak<Document>, u64, std::sync::Arc<Document>)>,/// Display profile readings (#569).monitors: monitor_status::State,checker: Option<egui::TextureHandle>,@@ -743,6 +746,7 @@ impl PhotocraftApp {services,canvases: HashMap::new(),navigator_textures: HashMap::new(),+ display_memo: HashMap::new(),monitors: Default::default(),checker: None,drag: None,diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex ce9437da5..052bde3f7 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -3216,14 +3216,14 @@ pub fn properties_window(app: &mut PhotocraftApp, ctx: &egui::Context) {fn adjustment_controls(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj: &photocraft_doc::Adjustment) {crate::adjust_editors::layer_editor(app, ui, id, adj);ui.add_space(6.0);- let layer = app.session.active().and_then(|s| s.doc.layer(id).cloned());- if let Some(l) = layer {+ let layer = app.session.active().and_then(|s| s.doc.layer(id).map(|l| (l.visible, l.clipped)));+ if let Some((visible, clipped)) = layer {ui.horizontal(|ui| {- let mut vis = l.visible;+ let mut vis = visible;if widgets::toggle(ui, &mut vis, tl!("Adjustment visible")).changed() {let _ = app.run("layer.setProps", json!({"layer": id.0, "visible": vis}));}- let mut clip = l.clipped;+ let mut clip = clipped;if widgets::toggle(ui, &mut clip, tl!("Clip to layer below")).changed() {let _ = app.run("layer.setProps", json!({"layer": id.0, "clipped": clip}));}