PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Smart filter edits: re-render from cached stages, in a background job (#2739)
twentymlsd3ae5aad0f8f
diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rsindex edae7d64c..93ecd479c 100644--- a/crates/engine/src/edit_menu_cmds.rs+++ b/crates/engine/src/edit_menu_cmds.rs@@ -269,6 +269,11 @@ fn purge(s: &mut Session, what: &str) -> Result<Value> {freed = freed.saturating_add(masks);items.push("mask cache");}+ let stages = crate::smart_cmds::purge_stack_cache();+ if stages > 0 {+ freed = freed.saturating_add(stages);+ items.push("smart filter cache");+ }}s.edit_state.fade = None;let msg = if items.is_empty() { "nothing to purge".to_string() } else { format!("purged {}", items.join(", ")) };@@ -286,7 +291,11 @@ fn can_purge_histories(s: &Session) -> std::result::Result<(), String> {}fn can_purge_all(s: &Session) -> std::result::Result<(), String> {can_purge_histories(s).or_else(|_| can_purge_clipboard(s)).or_else(|_| {- if photocraft_compose::effect_cache_bytes() > 0 || photocraft_compose::masks::cache_bytes() > 0 { Ok(()) } else { Err("nothing to purge".into()) }+ if photocraft_compose::effect_cache_bytes() > 0 || photocraft_compose::masks::cache_bytes() > 0 || crate::smart_cmds::stack_cache_bytes() > 0 {+ Ok(())+ } else {+ Err("nothing to purge".into())+ }})}diff --git a/crates/engine/src/jobs_tests.rs b/crates/engine/src/jobs_tests.rsindex 043aa9db7..4f631e82e 100644--- a/crates/engine/src/jobs_tests.rs+++ b/crates/engine/src/jobs_tests.rs@@ -355,6 +355,27 @@ fn content_aware_fill_and_scale_run_as_jobs() {assert_eq!(v["to"][0], 120);}+#[test]+fn smart_filter_edits_run_as_jobs() {+ let mut inline = session(160, 120);+ let mut s = session(160, 120);+ for t in [&mut inline, &mut s] {+ t.execute("filter.convertForSmartFilters", json!({})).unwrap();+ t.execute("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap();+ t.execute("filter.blur.motionBlur", json!({"angle": 45, "distance": 8})).unwrap();+ }+ inline.execute("layer.smartFilter.setVisible", json!({"index": 0})).unwrap();+ let before = pixels(&s);+ let steps = s.active().unwrap().history.past_len();+ let id = job(s.start("layer.smartFilter.setVisible", json!({"index": 0})).unwrap());+ let e = wait_event(&mut s, id);+ assert!(matches!(e.outcome, JobOutcome::Done(_)), "{e:?}");+ assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "one undo step");+ assert_eq!(pixels(&s), pixels(&inline), "same pixels as the synchronous command");+ assert!(s.undo());+ assert_eq!(pixels(&s), before);+}+#[test]fn content_aware_move_runs_as_a_job() {let mut inline = session(160, 120);diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rsindex 459575ead..6e0c04357 100644--- a/crates/engine/src/smart_cmds.rs+++ b/crates/engine/src/smart_cmds.rs@@ -13,6 +13,9 @@//! ──filter mask mix (unfiltered ↔ filtered)───────► cache//! ```//!+//! The placed stage and the result after each filter are cached too (`stack_cache`), so a+//! re-render starts from the deepest stage it shares with an earlier one.+//!//! Converting a layer embeds it as an in-memory `.pcraft` bundle of a nested document (exactly//! lossless, layered, any depth/model). PSD placed layers keep their source in the preserved//! global `lnk2` block (found by uuid), and keep Photoshop's rendering until something changes,@@ -25,12 +28,14 @@ use std::sync::{Arc, Mutex};use photocraft_algo::resample::translate_surface;use photocraft_algo::transform::Homography;use photocraft_color::{BlendMode, PixelFormat};-use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId, LayerMask, Metadata, SmartContentsId, SmartObject, SmartSource};+use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId, LayerMask, Metadata, SmartContentsId, SmartFilter, SmartObject, SmartSource};use photocraft_geom::{Affine, Rect, Size};use photocraft_raster::Surface;use serde_json::{Value, json};+use stack_cache::{Stage, StageKey};use crate::commands::{CommandSpec, blend_from_str, layer_param};+use crate::jobs::JobCtx;use crate::{EngineError, Result, Session};/// An open Edit Contents document and the shared contents it updates when saved or closed.@@ -336,9 +341,7 @@ pub fn apply_smart_filters(placed: &Surface, sm: &SmartObject, canvas: Rect) ->// Edge pixels repeat at the canvas ∪ placed-content edge, as for layer filters.let extent = canvas.union(&placed.content_bounds());for f in sm.smart_filters.iter().filter(|f| f.visible) {- // Unknown ids (e.g. Photoshop filters we don't implement) leave the pixels alone.- let Some(out) = crate::filters::apply_filter_to_surface(&f.command, &f.params, &cur, canvas, None, extent) else { continue };- cur = if f.blend == BlendMode::Normal && f.opacity >= 1.0 { out } else { blend_surfaces(&cur, &out, f.blend, f.opacity.clamp(0.0, 1.0)) };+ cur = apply_smart_filter(f, &cur, canvas, extent);}match sm.filter_mask.as_ref().filter(|m| m.enabled) {Some(m) => mask_mix(placed, &cur, m),@@ -346,16 +349,21 @@ pub fn apply_smart_filters(placed: &Surface, sm: &SmartObject, canvas: Rect) ->}}-/// Renders a smart object from its source. `Ok(None)` when the source is unavailable (a missing-/// linked file, or a PSD placed layer without embedded data): callers keep the existing cache.-pub fn render(doc: &Document, sm: &SmartObject) -> Result<Option<Surface>> {- let Some((name, bytes)) = source_bytes(&doc.metadata, &sm.source) else { return Ok(None) };+/// One visible smart filter over `cur`, blended with its blend mode and opacity.+fn apply_smart_filter(f: &SmartFilter, cur: &Surface, canvas: Rect, extent: Rect) -> Surface {+ // Unknown ids (e.g. Photoshop filters we don't implement) leave the pixels alone.+ let Some(out) = crate::filters::apply_filter_to_surface(&f.command, &f.params, cur, canvas, None, extent) else { return cur.clone() };+ if f.blend == BlendMode::Normal && f.opacity >= 1.0 { out } else { blend_surfaces(cur, &out, f.blend, f.opacity.clamp(0.0, 1.0)) }+}++/// The source placed in document pixels, before any smart filter.+fn place(name: &str, bytes: &[u8], fmt: PixelFormat, sm: &SmartObject) -> Result<Surface> {// A vector source is rendered at the placement's scale, and the placement is divided by// that scale so the rendered pixels land where the source units would.- if sm.stack_mode.is_none() && sm.warp.is_none() && photocraft_io::svg::is_svg(&bytes) {+ if sm.stack_mode.is_none() && sm.warp.is_none() && photocraft_io::svg::is_svg(bytes) {let k = vector_scale(sm);- let img = svg_source_image(&bytes, doc.pixel_format(), k)?;- let placed = match &sm.perspective {+ let img = svg_source_image(bytes, fmt, k)?;+ return Ok(match &sm.perspective {Some(p) => {let [h0, h1, h2, h3, h4, h5, h6, h7, h8] = *p;let h = Homography([h0 / k, h1 / k, h2, h3 / k, h4 / k, h5, h6 / k, h7 / k, h8]);@@ -366,19 +374,80 @@ pub fn render(doc: &Document, sm: &SmartObject) -> Result<Option<Surface>> {let t = Affine { m: [a / k, b / k, c / k, d / k, e, f] };photocraft_algo::warp::place_source(&img.surface, img.bounds, &t, None)?}- };- return Ok(Some(apply_smart_filters(&placed, sm, doc.bounds())));+ });}let img = match sm.stack_mode {- Some(mode) => stack_image(&name, &bytes, doc.pixel_format(), mode)?,- None => source_image(&name, &bytes, doc.pixel_format())?,+ Some(mode) => stack_image(name, bytes, fmt, mode)?,+ None => source_image(name, bytes, fmt)?,};// Through the warp (source space) and the transform in one pass; whole-pixel moves are exact.- let placed = match &sm.perspective {+ Ok(match &sm.perspective {Some(p) => photocraft_algo::warp::place_source_projective(&img.surface, img.bounds, &Homography(*p), sm.warp.as_ref())?,None => photocraft_algo::warp::place_source(&img.surface, img.bounds, &sm.transform, sm.warp.as_ref())?,+ })+}++/// Renders a smart object from its source. `Ok(None)` when the source is unavailable (a missing+/// linked file, or a PSD placed layer without embedded data): callers keep the existing cache.+pub fn render(doc: &Document, sm: &SmartObject) -> Result<Option<Surface>> {+ render_in(doc, sm, &JobCtx::new())+}++/// [`render`], reporting progress per smart filter to `ctx` and stopping between filters once it+/// is cancelled. Gives the same pixels as [`apply_smart_filters`] on the placed source, but+/// starts from the deepest stage of the stack already rendered (see [`stack_cache`]).+fn render_in(doc: &Document, sm: &SmartObject, ctx: &JobCtx) -> Result<Option<Surface>> {+ let Some((name, bytes)) = source_bytes(&doc.metadata, &sm.source) else { return Ok(None) };+ let (fmt, canvas) = (doc.pixel_format(), doc.bounds());+ let placed_key = stack_cache::placed_key(&bytes, fmt, sm, canvas);+ let placed = || -> Result<Stage> {+ if let Some(stage) = stack_cache::get(&placed_key) {+ return Ok(stage);+ }+ let surface = place(&name, &bytes, fmt, sm)?;+ // Edge pixels repeat at the canvas ∪ placed-content edge, as for layer filters.+ let stage = Stage { extent: canvas.union(&surface.content_bounds()), surface };+ stack_cache::put(placed_key, &stage);+ Ok(stage)};- Ok(Some(apply_smart_filters(&placed, sm, doc.bounds())))+ let filters: Vec<&SmartFilter> = sm.smart_filters.iter().filter(|f| sm.filters_enabled && f.visible).collect();+ if filters.is_empty() {+ return Ok(Some(placed()?.surface));+ }+ let keys: Vec<StageKey> = filters+ .iter()+ .scan(placed_key, |key, f| {+ *key = stack_cache::filter_key(key, f);+ Some(*key)+ })+ .collect();+ let deepest = keys.iter().enumerate().rev().find_map(|(i, key)| stack_cache::get(key).map(|stage| (i + 1, stage)));+ let (done, mut cur) = match deepest {+ Some(hit) => hit,+ None => (0, placed()?),+ };+ let n = filters.len() as f32;+ for (i, (f, key)) in filters.iter().zip(&keys).enumerate().skip(done) {+ ctx.check()?;+ ctx.progress(i as f32 / n, "");+ cur = Stage { surface: apply_smart_filter(f, &cur.surface, canvas, cur.extent), extent: cur.extent };+ stack_cache::put(*key, &cur);+ }+ ctx.progress(1.0, "");+ Ok(Some(match sm.filter_mask.as_ref().filter(|m| m.enabled) {+ Some(m) => mask_mix(&placed()?.surface, &cur.surface, m),+ None => cur.surface,+ }))+}++/// Bytes held by rendered smart filter stages.+pub fn stack_cache_bytes() -> usize {+ stack_cache::bytes()+}++/// Drop every rendered smart filter stage (Edit › Purge › All). Returns the bytes released.+pub fn purge_stack_cache() -> usize {+ stack_cache::purge()}/// The smart object's pixels below smart filter `index` (the input that filter edits): the placed@@ -394,8 +463,12 @@ pub fn render_below_filter(doc: &Document, sm: &SmartObject, index: usize) -> Re/// Re-renders smart layer `l` (which lives in `doc`) in place. Returns false if its source is/// unavailable (the cache is then left alone).pub fn refresh_layer(doc: &Document, l: &mut Layer) -> Result<bool> {+ refresh_layer_in(doc, l, &JobCtx::new())+}++fn refresh_layer_in(doc: &Document, l: &mut Layer, ctx: &JobCtx) -> Result<bool> {let LayerContent::Smart(sm) = &mut l.content else { return Ok(false) };- match render(doc, sm)? {+ match render_in(doc, sm, ctx)? {Some(px) => {sm.cache = Some(px);Ok(true)@@ -406,11 +479,15 @@ pub fn refresh_layer(doc: &Document, l: &mut Layer) -> Result<bool> {/// Re-renders the smart object `id` of `doc`.pub fn refresh(doc: &mut Document, id: LayerId) -> Result<bool> {+ refresh_in(doc, id, &JobCtx::new())+}++fn refresh_in(doc: &mut Document, id: LayerId, ctx: &JobCtx) -> Result<bool> {let mut l = doc.layer(id).cloned().ok_or(EngineError::NoLayer(id))?;if !matches!(l.content, LayerContent::Smart(_)) {return Err(other("the layer is not a smart object"));}- let ok = refresh_layer(doc, &mut l)?;+ let ok = refresh_layer_in(doc, &mut l, ctx)?;if ok && let Some(dst) = doc.layer_mut(id) {dst.content = l.content;}@@ -418,7 +495,15 @@ pub fn refresh(doc: &mut Document, id: LayerId) -> Result<bool> {}fn refresh_or_fail(doc: &mut Document, id: LayerId) -> Result<()> {- if refresh(doc, id)? { Ok(()) } else { Err(other("the smart object's contents are unavailable (missing linked file?), so it can't be re-rendered")) }+ refresh_or_fail_in(doc, id, &JobCtx::new())+}++fn refresh_or_fail_in(doc: &mut Document, id: LayerId, ctx: &JobCtx) -> Result<()> {+ if refresh_in(doc, id, ctx)? {+ Ok(())+ } else {+ Err(other("the smart object's contents are unavailable (missing linked file?), so it can't be re-rendered"))+ }}fn smart(doc: &Document, id: LayerId) -> Result<&SmartObject> {@@ -873,13 +958,23 @@ fn update_all(s: &mut Session) -> Result<Value> {// ---------- smart filter editing ----------+/// Edits the smart filters of a smart object and re-renders it. The edit itself is instant, so its+/// errors (a bad index, say) are reported at once; the re-render runs as a background job when+/// started with `Session::start`, so the window keeps drawing (with progress, cancellable) while+/// a long filter stack recomputes.fn edit_filters(s: &mut Session, p: &Value, label: &str, f: impl FnOnce(&mut SmartObject) -> Result<()>) -> Result<Value> {let id = layer_param(s, p)?;- s.edit(label, |doc, _| {- f(smart_mut(doc, id)?)?;- refresh_or_fail(doc, id)?;- Ok(json!({"layer": id.0}))- })+ let mut edited = smart(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?.clone();+ f(&mut edited)?;+ crate::jobs::edit_job(+ s,+ label,+ move |doc, _, ctx| {+ *smart_mut(doc, id)? = edited;+ refresh_or_fail_in(doc, id, ctx)+ },+ move |()| json!({"layer": id.0}),+ )}fn filter_index(cmd: &str, p: &Value, sm: &SmartObject) -> Result<usize> {@@ -1173,6 +1268,7 @@ pub fn specs() -> Vec<CommandSpec> {]}+mod stack_cache;mod unpack;#[cfg(test)]diff --git a/crates/engine/src/smart_cmds/stack_cache.rs b/crates/engine/src/smart_cmds/stack_cache.rsnew file mode 100644index 000000000..b155e5282--- /dev/null+++ b/crates/engine/src/smart_cmds/stack_cache.rs@@ -0,0 +1,95 @@+//! Stages of smart object renders: the placed source and the result after each visible smart+//! filter, keyed by everything that produced them. A re-render starts from the deepest cached+//! stage, so editing filter `i` only reruns the filters from `i` up: hiding or tweaking the top+//! filter of a long stack doesn't rerun the expensive filters under it.++use std::sync::{Mutex, PoisonError};++use photocraft_color::PixelFormat;+use photocraft_doc::{SmartFilter, SmartObject};+use photocraft_geom::Rect;+use photocraft_raster::Surface;++/// blake3 of a stage's inputs: the source contents, the placement and the filters so far.+pub(super) type StageKey = [u8; 32];++#[derive(Clone)]+pub(super) struct Stage {+ pub surface: Surface,+ /// Where filters repeat edge pixels: the canvas ∪ the placed content.+ pub extent: Rect,+}++struct Entry {+ key: StageKey,+ stage: Stage,+ bytes: usize,+}++/// Most recently used last.+static STAGES: Mutex<Vec<Entry>> = Mutex::new(Vec::new());+const ENTRIES: usize = 64;+/// Accounted tile bytes; a stage larger than this on its own isn't kept.+pub const BUDGET: usize = 768 << 20;++/// The first stage: what placing `bytes` (the source contents) through the smart object's+/// transform, warp or perspective gives at pixel format `fmt` on `canvas`.+pub(super) fn placed_key(bytes: &[u8], fmt: PixelFormat, sm: &SmartObject, canvas: Rect) -> StageKey {+ let mut h = blake3::Hasher::new();+ h.update(bytes);+ for v in sm.transform.m {+ h.update(&v.to_bits().to_le_bytes());+ }+ h.update(format!("{fmt:?}|{:?}|{:?}|{:?}|{canvas:?}", sm.warp, sm.perspective, sm.stack_mode).as_bytes());+ *h.finalize().as_bytes()+}++/// The stage after applying `f` to stage `below`.+pub(super) fn filter_key(below: &StageKey, f: &SmartFilter) -> StageKey {+ let mut h = blake3::Hasher::new();+ h.update(below);+ h.update(format!("{}\0{}\0{:?}\0", f.command, f.params, f.blend).as_bytes());+ h.update(&f.opacity.to_bits().to_le_bytes());+ *h.finalize().as_bytes()+}++pub(super) fn get(key: &StageKey) -> Option<Stage> {+ let mut c = STAGES.lock().unwrap_or_else(PoisonError::into_inner);+ let i = c.iter().position(|e| e.key == *key)?;+ let e = c.remove(i);+ let stage = e.stage.clone();+ c.push(e);+ Some(stage)+}++pub(super) fn put(key: StageKey, stage: &Stage) {+ let bytes = surface_bytes(&stage.surface);+ if bytes > BUDGET {+ return;+ }+ let mut c = STAGES.lock().unwrap_or_else(PoisonError::into_inner);+ c.retain(|e| e.key != key);+ c.push(Entry { key, stage: stage.clone(), bytes });+ while c.len() > ENTRIES || c.iter().map(|e| e.bytes).sum::<usize>() > BUDGET {+ c.remove(0);+ }+}++/// Bytes held by cached stages.+pub fn bytes() -> usize {+ STAGES.lock().unwrap_or_else(PoisonError::into_inner).iter().map(|e| e.bytes).sum()+}++/// Drop every cached stage (Edit › Purge › All). Returns the bytes released.+pub fn purge() -> usize {+ let mut c = STAGES.lock().unwrap_or_else(PoisonError::into_inner);+ let freed = c.iter().map(|e| e.bytes).sum();+ c.clear();+ freed+}++fn surface_bytes(s: &Surface) -> usize {+ // Tiles shared with the document (or another stage) are charged anyway: the cache is what+ // keeps them alive once the document moves on.+ s.tiles().fold(s.default_bytes().len(), |n, (_, t)| n.saturating_add(t.bytes().len()))+}diff --git a/crates/engine/src/smart_cmds/tests.rs b/crates/engine/src/smart_cmds/tests.rsindex 726404f2e..2ee54322b 100644--- a/crates/engine/src/smart_cmds/tests.rs+++ b/crates/engine/src/smart_cmds/tests.rs@@ -1,6 +1,7 @@use super::*;mod selection;+mod stack_cache;const DEPTHS: [u64; 3] = [8, 16, 32];const W: i32 = 64;diff --git a/crates/engine/src/smart_cmds/tests/stack_cache.rs b/crates/engine/src/smart_cmds/tests/stack_cache.rsnew file mode 100644index 000000000..7675d7184--- /dev/null+++ b/crates/engine/src/smart_cmds/tests/stack_cache.rs@@ -0,0 +1,64 @@+use super::*;++/// A smart object with three smart filters, the middle one blended at half opacity.+fn filtered(depth: u64) -> Session {+ let mut s = session(depth);+ paint(&mut s);+ s.execute("filter.convertForSmartFilters", json!({})).unwrap();+ s.execute("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap();+ s.execute("filter.noise.addNoise", json!({"amount": 20, "distribution": "gaussian", "seed": 5})).unwrap();+ s.execute("filter.blur.motionBlur", json!({"angle": 30, "distance": 6})).unwrap();+ s.execute("layer.smartFilter.blendingOptions", json!({"index": 1, "blend": "multiply", "opacity": 0.5})).unwrap();+ s+}++/// The active smart object rendered without the stage cache.+fn uncached(s: &Session) -> Surface {+ let doc = &s.active().unwrap().doc;+ let sm = active_smart(s);+ let (name, bytes) = source_bytes(&doc.metadata, &sm.source).unwrap();+ apply_smart_filters(&place(&name, &bytes, doc.pixel_format(), &sm).unwrap(), &sm, doc.bounds())+}++#[test]+fn renders_from_cached_stages_match_full_renders_at_every_depth() {+ for depth in DEPTHS {+ let mut s = filtered(depth);+ let edits = [+ ("layer.smartFilter.setVisible", json!({"index": 2, "visible": false})),+ ("layer.smartFilter.setVisible", json!({"index": 2, "visible": true})),+ ("layer.smartFilter.setVisible", json!({"index": 0, "visible": false})),+ ("layer.smartFilter.setVisible", json!({"index": 0, "visible": true})),+ ("layer.smartFilter.setParams", json!({"index": 2, "params": {"distance": 9}})),+ ("layer.smartFilter.blendingOptions", json!({"index": 1, "opacity": 0.8})),+ ("layer.smartFilter.move", json!({"index": 0, "to": 2})),+ ("layer.smartFilter.disableSmartFilters", json!({"enabled": false})),+ ("layer.smartFilter.disableSmartFilters", json!({"enabled": true})),+ ("layer.smartFilter.delete", json!({"index": 1})),+ ];+ for (id, params) in edits {+ s.execute(id, params.clone()).unwrap();+ assert_eq!(active_smart(&s).cache.unwrap(), uncached(&s), "{id} {params} at {depth}-bit");+ }+ }+}++#[test]+fn a_cancelled_render_stops_before_an_uncached_filter() {+ let s = filtered(8);+ let mut sm = active_smart(&s);+ // A radius no other render uses, so the stack below it is cached but this stage isn't.+ sm.smart_filters[0].params["radius"] = json!(2.375);+ let ctx = JobCtx::new();+ ctx.cancel();+ assert!(matches!(render_in(&s.active().unwrap().doc, &sm, &ctx), Err(EngineError::Cancelled)));+}++#[test]+fn bad_smart_filter_edits_fail_at_once_with_start() {+ let mut s = filtered(8);+ let before = active_smart(&s);+ let r = s.start("layer.smartFilter.setVisible", json!({"index": 9}));+ assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}");+ assert_eq!(active_smart(&s), before);+}diff --git a/crates/engine/tests/smart_filter_stages.rs b/crates/engine/tests/smart_filter_stages.rsnew file mode 100644index 000000000..d26184542--- /dev/null+++ b/crates/engine/tests/smart_filter_stages.rs@@ -0,0 +1,53 @@+//! One integration-test process keeps the global smart filter stage cache isolated from parallel+//! unit tests, so these tests can tell a cached stage from a re-render.+use std::sync::Arc;++use photocraft_doc::LayerContent;+use photocraft_engine::{Session, smart_cmds};+use photocraft_raster::Surface;+use serde_json::json;++fn rendered(s: &Session) -> Surface {+ let d = s.active().unwrap();+ match &d.doc.layer(d.active_layer.unwrap()).unwrap().content {+ LayerContent::Smart(sm) => sm.cache.clone().unwrap(),+ other => panic!("not a smart object: {}", other.kind_name()),+ }+}++/// Same tiles, not just the same pixels: the surface came from the cache rather than a re-render.+fn same_tiles(a: &Surface, b: &Surface) -> bool {+ a.tile_count() == b.tile_count() && a.tiles().zip(b.tiles()).all(|((ca, ta), (cb, tb))| ca == cb && Arc::ptr_eq(ta, tb))+}++#[test]+fn toggling_the_top_filter_reuses_the_stages_below_it_until_purged() {+ for depth in [8, 16, 32] {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 96, "height": 64, "depth": depth})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ s.execute("paint.gradient", json!({"from": [0, 0], "to": [96, 64], "colors": ["#ff0000", "#0000ff"]})).unwrap();+ s.execute("filter.convertForSmartFilters", json!({})).unwrap();+ s.execute("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap();+ let blurred = rendered(&s);+ s.execute("filter.noise.addNoise", json!({"amount": 12, "seed": 1})).unwrap();+ let full = rendered(&s);++ s.execute("layer.smartFilter.setVisible", json!({"index": 1, "visible": false})).unwrap();+ let hidden = rendered(&s);+ assert!(same_tiles(&hidden, &blurred), "hiding the top filter shows the cached stage below it at {depth}-bit");+ s.execute("layer.smartFilter.setVisible", json!({"index": 1, "visible": true})).unwrap();+ assert!(same_tiles(&rendered(&s), &full), "showing it again reuses the full stack at {depth}-bit");++ assert!(smart_cmds::stack_cache_bytes() > 0);+ assert!(s.is_enabled("edit.purge.all"));+ let purged = s.execute("edit.purge.all", json!({})).unwrap();+ assert!(purged["purged"].as_array().unwrap().contains(&json!("smart filter cache")), "{purged}");+ assert_eq!(smart_cmds::stack_cache_bytes(), 0);++ s.execute("layer.smartFilter.setVisible", json!({"index": 1, "visible": false})).unwrap();+ let rerendered = rendered(&s);+ assert_eq!(rerendered, hidden, "a cold render gives the same pixels at {depth}-bit");+ assert!(!same_tiles(&rerendered, &hidden), "after a purge the stage is rendered again");+ }+}