Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Background redraw: keep the last finished composites, so a solo's restore uploads instead of recompositing (part of #6528)

Higgs3258485acfeee65de
diff --git a/crates/ui-egui/src/background_redraw.rs b/crates/ui-egui/src/background_redraw.rs
index e8196bc1c..9b3837d53 100644
--- a/crates/ui-egui/src/background_redraw.rs
+++ b/crates/ui-egui/src/background_redraw.rs
@@ -10,7 +10,12 @@
//! the edit's own damage is drawn by the canvas as usual. A full change (a new preview, a new
//! display transform) starts over. Without background jobs (web, tests) the canvas keeps the
//! synchronous [`GpuCanvas::upload_composite`].
+//!
+//! The last finished redraws are kept ([`Kept`]), keyed by the whole document they drew (#6528):
+//! going back to a state drawn a moment ago (⌥-click on an eye and again, an undo and its redo)
+//! uploads those blocks instead of compositing every layer again.
+use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, SyncSender, TryRecvError};
@@ -32,6 +37,12 @@ const BLOCK: i32 = 1024;
/// finished blocks may wait for the UI thread: bounds the memory a redraw holds.
const BATCH: usize = 4;
+/// Finished redraws kept: a state and the one before it (a solo and its restore).
+const KEEP: usize = 2;
+
+/// [`GpuCanvas::refresh`] kind of a redraw served from a [`Kept`] composite.
+pub(crate) const KEPT: &str = "kept";
+
/// One finished block, as texels of the canvas texture.
struct Piece {
block: usize,
@@ -49,6 +60,15 @@ pub(crate) struct Redraw {
stop: Arc<AtomicBool>,
started_ms: f64,
fallback: Option<String>,
+ /// The state the blocks are drawn from, and what the texels depend on besides it.
+ doc: Arc<Document>,
+ display: u64,
+ format: eframe::wgpu::TextureFormat,
+ /// Uploaded blocks of `doc` kept for [`Kept`] (empty once over `cap`), and their bytes.
+ collected: Vec<Option<Vec<u8>>>,
+ collected_bytes: u64,
+ /// Bytes the kept composites may hold: what Memory Usage leaves beside the document.
+ cap: u64,
}
impl Redraw {
@@ -64,6 +84,72 @@ impl Drop for Redraw {
}
}
+/// A finished redraw: the canvas texels of every block of `doc`.
+pub(crate) struct Kept {
+ doc: Arc<Document>,
+ display: u64,
+ format: eframe::wgpu::TextureFormat,
+ blocks: Vec<Rect>,
+ texels: Vec<Vec<u8>>,
+ bytes: u64,
+}
+
+impl Kept {
+ /// Whether these are the texels a redraw of `doc` would draw. The key is the whole document
+ /// (layers and their pixels, visibility, opacity, blending, masks, adjustments and everything
+ /// else it holds), so a stale composite can't come back; Arc-shared tiles compare without
+ /// reading their pixels.
+ fn matches(&self, doc: &Arc<Document>, display: u64, format: eframe::wgpu::TextureFormat, blocks: &[Rect]) -> bool {
+ self.display == display && self.format == format && self.blocks == blocks && (Arc::ptr_eq(&self.doc, doc) || *self.doc == **doc)
+ }
+}
+
+/// The last [`KEEP`] finished redraws, newest first, within a byte cap.
+#[derive(Default)]
+pub(crate) struct KeptComposites {
+ entries: VecDeque<Kept>,
+}
+
+impl KeptComposites {
+ /// The kept redraw of exactly this state, now the newest.
+ fn find(&mut self, doc: &Arc<Document>, display: u64, format: eframe::wgpu::TextureFormat, blocks: &[Rect]) -> Option<&Kept> {
+ let i = self.entries.iter().position(|k| k.matches(doc, display, format, blocks))?;
+ let k = self.entries.remove(i)?;
+ self.entries.push_front(k);
+ self.entries.front()
+ }
+
+ /// Keep `k` (in place of an entry of the same state), within `cap` bytes in all.
+ fn store(&mut self, k: Kept, cap: u64) {
+ self.entries.retain(|e| !e.matches(&k.doc, k.display, k.format, &k.blocks));
+ self.entries.push_front(k);
+ self.trim(cap);
+ }
+
+ /// Drop the oldest entries until at most [`KEEP`], holding at most `cap` bytes, are left.
+ fn trim(&mut self, cap: u64) {
+ while self.entries.len() > KEEP || self.bytes() > cap {
+ self.entries.pop_back();
+ }
+ }
+
+ fn bytes(&self) -> u64 {
+ self.entries.iter().fold(0, |n, k| n.saturating_add(k.bytes))
+ }
+
+ fn retain(&mut self, live: impl Fn(DocId) -> bool) {
+ self.entries.retain(|k| live(k.doc.id));
+ }
+}
+
+/// Bytes kept composites of document `doc` may hold: what Memory Usage leaves beside its pixels
+/// and History. It shrinks as the document grows, which drops them under memory pressure.
+fn keep_cap(app: &PhotocraftApp, doc: DocId) -> u64 {
+ let budget = app.session.prefs().performance.history_budget_bytes() as u64;
+ let used = app.session.documents().iter().find(|st| st.doc.id == doc).map_or(u64::MAX, |st| st.memory_bytes() as u64);
+ budget.saturating_sub(used)
+}
+
/// Whether full CPU refreshes run in the background here.
pub(crate) fn enabled(app: &PhotocraftApp) -> bool {
cfg!(not(target_arch = "wasm32")) && app.background_jobs
@@ -112,16 +198,46 @@ pub(crate) fn start(
fallback: Option<String>,
) {
let all = blocks(doc.bounds());
- let (mut pending, since, fallback) = match app.redraws.remove(&doc.id) {
- Some(old) if old.blocks == all => (old.pending.clone(), (old.started_ms, old.drawn), fallback.or_else(|| old.fallback.clone())),
- _ => (vec![false; all.len()], (crate::gpu_canvas::now_ms(), 0), fallback),
+ let display_key = display.as_deref().map_or(0, |d| d.texture_key);
+ let (mut pending, since, fallback, mut keep) = match app.redraws.remove(&doc.id) {
+ Some(mut old) if old.blocks == all => {
+ // Blocks drawn from another state aren't part of this one's composite.
+ let same = old.display == display_key && (Arc::ptr_eq(&old.doc, &doc) || *old.doc == *doc);
+ let (collected, bytes) = if same { (std::mem::take(&mut old.collected), old.collected_bytes) } else { (vec![None; all.len()], 0) };
+ (std::mem::take(&mut old.pending), (old.started_ms, old.drawn), fallback.or_else(|| old.fallback.take()), (collected, bytes, old.cap))
+ }
+ _ => {
+ let cap = keep_cap(app, doc.id);
+ app.kept.trim(cap);
+ (vec![false; all.len()], (crate::gpu_canvas::now_ms(), 0), fallback, (vec![None; all.len()], 0, cap))
+ }
};
for (p, b) in pending.iter_mut().zip(&all) {
*p |= !b.intersect(&region).is_empty();
}
- if pending.contains(&true) {
- spawn(app, ctx, gpu, doc, display, visible, all, pending, since, fallback);
+ if !pending.contains(&true) {
+ return;
}
+ let Some(format) = gpu.prepare_texture(doc.id.0, &doc) else { return };
+ // This exact state was drawn a moment ago: upload its blocks rather than composite them.
+ if let Some(k) = app.kept.find(&doc, display_key, format, &all) {
+ let t0 = crate::gpu_canvas::now_ms();
+ let mut px = 0u64;
+ for (i, p) in pending.iter_mut().enumerate() {
+ if let (true, Some(b), Some(t)) = (*p, all.get(i), k.texels.get(i))
+ && gpu.upload_rect(doc.id.0, [b.x0 as u32, b.y0 as u32], [b.width(), b.height()], t)
+ {
+ *p = false;
+ px = px.saturating_add(b.width() as u64 * b.height() as u64);
+ }
+ }
+ if !pending.contains(&true) {
+ app.perf.record(KEPT, px, 0.0, crate::gpu_canvas::now_ms() - t0);
+ return;
+ }
+ keep = (vec![None; all.len()], 0, keep.2);
+ }
+ spawn(app, ctx, Spawn { doc, display, display_key, format, visible, blocks: all, pending, since, fallback, keep });
}
/// After an edit drew its own damage: continue document `doc.id`'s redraw, if one is running, on
@@ -145,22 +261,43 @@ pub(crate) fn poll(app: &mut PhotocraftApp, gpu: &GpuCanvas, doc: DocId) {
r.pending[p.block] = false;
r.left -= 1;
r.drawn += b.width() as u64 * b.height() as u64;
+ collect(r, p);
}
}
Err(TryRecvError::Empty) => return,
Err(TryRecvError::Disconnected) => break,
}
}
- let Some(r) = app.redraws.remove(&doc) else { return };
+ let Some(mut r) = app.redraws.remove(&doc) else { return };
if r.left > 0 {
log::warn!("canvas redraw stopped with {} of {} blocks left", r.left, r.blocks.len());
return;
}
+ if r.collected.len() == r.blocks.len() && r.collected.iter().all(Option::is_some) {
+ let texels = std::mem::take(&mut r.collected).into_iter().flatten().collect();
+ let k = Kept { doc: r.doc.clone(), display: r.display, format: r.format, blocks: r.blocks.clone(), texels, bytes: r.collected_bytes };
+ app.kept.store(k, r.cap);
+ }
let ms = crate::gpu_canvas::now_ms() - r.started_ms;
app.perf.record("background", r.drawn, ms, 0.0);
crate::notices::slow_cpu_refresh(app, doc.0, ms, r.fallback.as_deref());
}
+/// Keep uploaded block `p` for [`Kept`], unless the composite would pass the cap.
+fn collect(r: &mut Redraw, p: Piece) {
+ let len = p.texels.len() as u64;
+ let Some(slot) = r.collected.get_mut(p.block) else { return };
+ let before = slot.as_ref().map_or(0, |t| t.len() as u64);
+ let bytes = r.collected_bytes.saturating_sub(before).saturating_add(len);
+ if bytes > r.cap {
+ r.collected = Vec::new();
+ r.collected_bytes = 0;
+ return;
+ }
+ *slot = Some(p.texels);
+ r.collected_bytes = bytes;
+}
+
/// The active document's redraw in the status bar: "Redrawing" and how much is done.
pub(crate) fn status(app: &PhotocraftApp, ui: &mut egui::Ui) {
let Some(r) = app.session.active().and_then(|st| app.redraws.get(&st.doc.id)) else { return };
@@ -178,23 +315,30 @@ pub(crate) fn cancel(app: &mut PhotocraftApp, doc: DocId) {
pub(crate) fn retain(app: &mut PhotocraftApp) {
let docs = app.session.documents();
app.redraws.retain(|id, _| docs.iter().any(|st| st.doc.id == *id));
+ app.kept.retain(|id| docs.iter().any(|st| st.doc.id == id));
}
-#[allow(clippy::too_many_arguments)]
-fn spawn(
- app: &mut PhotocraftApp,
- ctx: &egui::Context,
- gpu: &GpuCanvas,
+/// What [`spawn`] starts a redraw with.
+struct Spawn {
doc: Arc<Document>,
display: Option<Arc<CanvasDisplay>>,
+ display_key: u64,
+ format: eframe::wgpu::TextureFormat,
visible: Rect,
blocks: Vec<Rect>,
pending: Vec<bool>,
- (started_ms, drawn): (f64, u64),
+ /// When it started and the pixels uploaded so far.
+ since: (f64, u64),
fallback: Option<String>,
-) {
+ /// Blocks collected for [`Kept`], their bytes, and the cap.
+ keep: (Vec<Option<Vec<u8>>>, u64, u64),
+}
+
+fn spawn(app: &mut PhotocraftApp, ctx: &egui::Context, s: Spawn) {
+ let Spawn { doc, display, display_key, format, visible, blocks, pending, since: (started_ms, drawn), fallback, keep: (collected, collected_bytes, cap) } =
+ s;
let id = doc.id;
- let Some(format) = gpu.prepare_texture(id.0, &doc) else { return };
+ let kept_doc = doc.clone();
let todo = order(&blocks, (0..blocks.len()).filter(|&i| pending[i]), visible);
let left = todo.len();
let (tx, rx) = std::sync::mpsc::sync_channel(BATCH);
@@ -210,7 +354,10 @@ fn spawn(
log::warn!("couldn't start the canvas redraw: {e}");
return;
}
- app.redraws.insert(id, Redraw { blocks, pending, left, drawn, rx, stop, started_ms, fallback });
+ app.redraws.insert(
+ id,
+ Redraw { blocks, pending, left, drawn, rx, stop, started_ms, fallback, doc: kept_doc, display: display_key, format, collected, collected_bytes, cap },
+ );
}
/// The worker: composite `todo`'s blocks of `doc` in batches and hand each over, until done or
diff --git a/crates/ui-egui/src/background_redraw_tests.rs b/crates/ui-egui/src/background_redraw_tests.rs
index 650fccaa3..220681fc7 100644
--- a/crates/ui-egui/src/background_redraw_tests.rs
+++ b/crates/ui-egui/src/background_redraw_tests.rs
@@ -31,6 +31,73 @@ fn visible_blocks_come_first_nearest_the_view_centre() {
assert_eq!(order(&b, [3, 9].into_iter(), visible).len(), 2);
}
+/// A kept composite of `doc`: `bytes` texels per block.
+fn kept(doc: &Arc<Document>, bytes: usize) -> Kept {
+ let all = blocks(doc.bounds());
+ let texels: Vec<Vec<u8>> = all.iter().map(|_| vec![1u8; bytes]).collect();
+ Kept { doc: doc.clone(), display: 7, format: eframe::wgpu::TextureFormat::Rgba8Unorm, bytes: (bytes * all.len()) as u64, blocks: all, texels }
+}
+
+#[test]
+fn kept_composites_come_back_only_for_the_exact_state_and_stay_bounded() {
+ use eframe::wgpu::TextureFormat::{Rgba8Unorm, Rgba16Float};
+ let mut a = Document::new("kept", photocraft_geom::Size::new(2000, 1500), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8);
+ let mut layer = photocraft_doc::Layer::raster("one", a.pixel_format());
+ if let photocraft_doc::LayerContent::Raster(s) = &mut layer.content {
+ s.fill_rect(Rect::new(0, 0, 300, 300), &[0.2, 0.4, 0.6, 1.0]);
+ }
+ a.layers.push(layer);
+ let a = Arc::new(a);
+ let all = blocks(a.bounds());
+ let changed = |f: &dyn Fn(&mut Document)| {
+ let mut d = (*a).clone();
+ f(&mut d);
+ Arc::new(d)
+ };
+ let mut cache = KeptComposites::default();
+ cache.store(kept(&a, 4), u64::MAX);
+ // The same state hits, also as an equal document that isn't the same Arc (a restore after a solo).
+ assert!(cache.find(&a, 7, Rgba8Unorm, &all).is_some());
+ assert!(cache.find(&Arc::new((*a).clone()), 7, Rgba8Unorm, &all).is_some());
+ // Any change to what the composite depends on misses.
+ let hidden = changed(&|d| d.layers[0].visible = false);
+ let faded = changed(&|d| d.layers[0].opacity = 0.5);
+ let multiplied = changed(&|d| d.layers[0].blend = photocraft_color::BlendMode::Multiply);
+ let painted = changed(&|d| {
+ if let photocraft_doc::LayerContent::Raster(s) = &mut d.layers[0].content {
+ s.fill_rect(Rect::new(10, 10, 11, 11), &[1.0, 0.0, 0.0, 1.0]);
+ }
+ });
+ for (what, d) in [("visibility", &hidden), ("opacity", &faded), ("blend mode", &multiplied), ("pixels", &painted)] {
+ assert!(cache.find(d, 7, Rgba8Unorm, &all).is_none(), "{what} changed");
+ }
+ assert!(cache.find(&a, 8, Rgba8Unorm, &all).is_none(), "another display transform");
+ assert!(cache.find(&a, 7, Rgba16Float, &all).is_none(), "another texture format");
+ assert!(cache.find(&a, 7, Rgba8Unorm, &all[1..]).is_none(), "other blocks");
+ // At most KEEP entries, the least recently used going first.
+ cache.store(kept(&hidden, 4), u64::MAX);
+ assert!(cache.find(&a, 7, Rgba8Unorm, &all).is_some());
+ cache.store(kept(&faded, 4), u64::MAX);
+ assert_eq!(cache.entries.len(), KEEP);
+ assert!(cache.find(&hidden, 7, Rgba8Unorm, &all).is_none(), "the least recently used went");
+ assert!(cache.find(&a, 7, Rgba8Unorm, &all).is_some() && cache.find(&faded, 7, Rgba8Unorm, &all).is_some());
+ // Storing a state again replaces its entry.
+ cache.store(kept(&faded, 4), u64::MAX);
+ assert_eq!(cache.entries.len(), 2);
+ // The byte cap: a smaller one drops the oldest, and a composite over it isn't kept.
+ let one = kept(&a, 4).bytes;
+ cache.trim(one);
+ assert_eq!(cache.entries.len(), 1);
+ assert!(cache.bytes() <= one);
+ cache.trim(0);
+ cache.store(kept(&a, 4), one - 1);
+ assert!(cache.entries.is_empty(), "over the cap");
+ // A closed document's composites go.
+ cache.store(kept(&a, 4), u64::MAX);
+ cache.retain(|id| id != a.id);
+ assert!(cache.entries.is_empty());
+}
+
struct Gpu {
harness: egui_kittest::Harness<'static, PhotocraftApp>,
observer: GpuCanvas,
@@ -157,6 +224,30 @@ fn an_edit_damaging_most_of_a_large_document_is_drawn_in_the_background_too() {
assert_matches_synchronous(&mut g, doc);
}
+#[test]
+fn showing_a_hidden_layer_again_reuses_the_redraw_from_before_it_was_hidden() {
+ let _gpu = photocraft_testkit::gpu_lock();
+ let Some(mut g) = gpu_app() else { return };
+ let doc = cpu_only_document(g.harness.state_mut(), 2600, 1700);
+ let layer = g.harness.state().session.active().and_then(|st| st.active_layer).expect("layer");
+ settle(&mut g);
+ assert_eq!(g.harness.state().perf.last_refresh, "background");
+ g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "visible": false})).expect("hide");
+ settle(&mut g);
+ // Back to the state drawn before: its blocks come back, nothing is composited.
+ g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "visible": true})).expect("show");
+ g.harness.step();
+ assert!(g.harness.state().redraws.is_empty(), "no redraw: {}", g.harness.state().perf.last_refresh);
+ assert_eq!(g.harness.state().perf.last_refresh, KEPT);
+ assert_matches_synchronous(&mut g, doc);
+ // A real change composites again.
+ g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "opacity": 0.3})).expect("opacity");
+ g.harness.step();
+ assert_ne!(g.harness.state().perf.last_refresh, KEPT);
+ settle(&mut g);
+ assert_matches_synchronous(&mut g, doc);
+}
+
#[test]
fn closing_the_document_stops_its_redraw() {
let _gpu = photocraft_testkit::gpu_lock();
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 4e82be710..2a6de1877 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -680,6 +680,8 @@ pub struct PhotocraftApp {
filter_preview_worker: filter_preview_worker::Worker,
/// Full CPU canvas redraws running in the background, by document (#4024).
pub(crate) redraws: std::collections::HashMap<photocraft_doc::DocId, background_redraw::Redraw>,
+ /// The last finished background redraws, for going back to a state drawn a moment ago (#6528).
+ pub(crate) kept: background_redraw::KeptComposites,
/// Select › Color Range dialog preview (proxy document + mask / image textures).
pub(crate) color_range: Option<color_range_ui::Preview>,
/// Image › Adjustments dialog preview through a temporary clipped adjustment layer.
@@ -886,6 +888,7 @@ impl PhotocraftApp {
#[cfg(not(target_arch = "wasm32"))]
filter_preview_worker: Default::default(),
redraws: Default::default(),
+ kept: Default::default(),
color_range: None,
adjust_preview: None,
synthetic: Vec::new(),