diff --git a/crates/ui-egui/src/app/thumbs.rs b/crates/ui-egui/src/app/thumbs.rs index 0677b17c23c..f8b25d555aa 100644 --- a/crates/ui-egui/src/app/thumbs.rs +++ b/crates/ui-egui/src/app/thumbs.rs @@ -26,7 +26,8 @@ impl<'a> SnapshotThumbs<'a> { impl ThumbSource for SnapshotThumbs<'_> { fn revision(&self, key: &u64, _request: &ThumbRequest) -> Revision { let shown = self.snapshots.iter().find(|s| s.id == *key).map(|s| std::sync::Arc::as_ptr(&s.doc) as usize); - Revision::of(&(self.doc.0, *key, shown)) + // A snapshot's tiles can fail to read and recover without a new `Arc` (`crate::scratch_reads`). + Revision::of(&(self.doc.0, *key, shown, crate::scratch_reads::generation())) } fn render(&self, key: &u64, request: &ThumbRequest) -> ThumbRender { @@ -36,6 +37,12 @@ impl ThumbSource for SnapshotThumbs<'_> { } } +/// What the bounds cache keys `surface`'s bounds by: its generation and the scratch read-error generation, as a tile +/// that fails to read scans as empty and moves neither (`crate::scratch_reads`). +pub(crate) fn bounds_revision(surface: &photocraft_raster::Surface) -> u64 { + crate::scratch_reads::with(surface.generation()) +} + /// The document area a layer thumbnail frames: the canvas, or with `clip` the layer's pixels on /// it (the canvas again when it has none there, so an empty layer still shows the page shape). pub(crate) fn layer_thumb_frame(layer: &photocraft_doc::Layer, canvas: photocraft_geom::Rect, clip: bool) -> photocraft_geom::Rect { @@ -47,9 +54,10 @@ pub(crate) fn layer_thumb_frame(layer: &photocraft_doc::Layer, canvas: photocraf } impl PhotocraftApp { - /// Cached `Surface::content_bounds` keyed by an id and the surface's generation. + /// Cached `Surface::content_bounds` keyed by an id and the surface's generation with the scratch read-error + /// generation ([`bounds_revision`]). pub fn cached_bounds(&mut self, key: u64, surface: &photocraft_raster::Surface) -> photocraft_geom::Rect { - let rev = surface.generation(); + let rev = bounds_revision(surface); if let Some((r, b)) = self.bounds_cache.get(&key) && *r == rev { @@ -67,7 +75,7 @@ impl PhotocraftApp { /// hasn't changed since, else a scan (not cached). pub fn known_bounds(&self, key: u64, surface: &photocraft_raster::Surface) -> photocraft_geom::Rect { match self.bounds_cache.get(&key) { - Some((r, b)) if *r == surface.generation() => *b, + Some((r, b)) if *r == bounds_revision(surface) => *b, _ => surface.content_bounds(), } } @@ -79,7 +87,7 @@ impl PhotocraftApp { match &layer.content { photocraft_doc::LayerContent::Shape(sh) if sh.has_soft_mask() => { // Cached per rendering, like the pixel bounds: the frame renders strips of the shape. - let (key, rev) = (layer.id.0 | 1 << 63, surface.generation()); + let (key, rev) = (layer.id.0 | 1 << 63, bounds_revision(surface)); if let Some((r, b)) = self.bounds_cache.get(&key) && *r == rev { @@ -176,10 +184,13 @@ impl ThumbSource for ChannelThumbs<'_> { fn revision(&self, key: &Row, _request: &ThumbRequest) -> Revision { let doc = &self.st.doc; let size = (doc.size.width, doc.size.height); + // A tile that fails to read and recovers moves neither the document's revision nor its surface's generation + // (`crate::scratch_reads`). + let scratch = crate::scratch_reads::generation(); match key { - Row::Composite | Row::Color(_) => Revision::of(&(doc.id.0, self.st.pixel_revision, self.show_color, size)), + Row::Composite | Row::Color(_) => Revision::of(&(doc.id.0, self.st.pixel_revision, self.show_color, size, scratch)), // A channel-list change with empty damage still refreshes these: they follow their own surface. - _ => Revision::of(&(doc.id.0, self.st.active_layer, self.surface(key).map(photocraft_raster::Surface::generation), size)), + _ => Revision::of(&(doc.id.0, self.st.active_layer, self.surface(key).map(photocraft_raster::Surface::generation), size, scratch)), } } diff --git a/crates/ui-egui/src/canvas/filter_preview.rs b/crates/ui-egui/src/canvas/filter_preview.rs index 2d81c234e29..648385077df 100644 --- a/crates/ui-egui/src/canvas/filter_preview.rs +++ b/crates/ui-egui/src/canvas/filter_preview.rs @@ -108,6 +108,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e params, k, tool_colors: (app.session.tools.foreground, app.session.tools.background), + scratch: crate::scratch_reads::generation(), }; app.filter_live.begin(session_of(&request), PixelRect::new(bounds.x0, bounds.y0, bounds.x1, bounds.y1)); let key = request.doc.0 ^ (1u64 << 61); diff --git a/crates/ui-egui/src/canvas/filter_preview/tests.rs b/crates/ui-egui/src/canvas/filter_preview/tests.rs index ae34f227d0a..481fcd8e598 100644 --- a/crates/ui-egui/src/canvas/filter_preview/tests.rs +++ b/crates/ui-egui/src/canvas/filter_preview/tests.rs @@ -37,6 +37,28 @@ fn set_fields(app: &mut PhotocraftApp, ctx: &egui::Context, values: &Value) { } } +/// A tile that fails to read and recovers changes the pixels without a new revision or new dialog values: the +/// preview is computed again, so it does not keep what it read during the error (`crate::scratch_reads`). +#[test] +fn the_preview_is_computed_again_after_a_scratch_read_error_transition() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + open_filter(&mut app, "filter.stylize.solarize"); + let ctx = app.ctx().clone(); + let result = |app: &PhotocraftApp| app.filter_preview.as_ref().and_then(|preview| preview.result.clone()).expect("a preview result"); + ensure_filter_preview(&mut app, 0, &ctx).expect("a preview"); + let before = result(&app); + ensure_filter_preview(&mut app, 0, &ctx).expect("the same preview"); + assert!(std::sync::Arc::ptr_eq(&result(&app), &before), "nothing changed: the same result"); + let (revision, values) = (app.session.active().unwrap().revision, fields(&app)); + crate::scratch_reads::tests::simulate_read_error_transition(); + ensure_filter_preview(&mut app, 0, &ctx).expect("a preview"); + assert_eq!(app.session.active().unwrap().revision, revision); + assert_eq!(fields(&app), values, "the dialog values did not change"); + assert!(!std::sync::Arc::ptr_eq(&result(&app), &before), "the preview is computed again"); +} + /// #7490: the inline (web) preview path composites and uploads each changed preview once, as /// the background worker does. It used to flatten and upload it twice and record it twice, /// so the frame's refresh time counted the preview twice. @@ -123,6 +145,7 @@ fn every_filter_previews_off_the_ui_thread_and_a_newer_value_cancels_the_old() { params: json!({"radius": 999.0}), k: 1, tool_colors: (app.session.tools.foreground, app.session.tools.background), + scratch: crate::scratch_reads::generation(), }; let (told, cancelled) = std::sync::mpsc::channel(); app.filter_preview_worker @@ -179,6 +202,7 @@ fn gated_blur_preview(app: &mut PhotocraftApp, ctx: &egui::Context) -> (std::syn params, k: 1, tool_colors: (app.session.tools.foreground, app.session.tools.background), + scratch: crate::scratch_reads::generation(), }; let doc = app.session.documents()[0].doc.clone(); let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); @@ -581,6 +605,7 @@ fn a_mid_drag_empty_result_leaves_the_preview_alone() { params: json!({"radius": moved}), k: 1, tool_colors: (app.session.tools.foreground, app.session.tools.background), + scratch: crate::scratch_reads::generation(), }; let (release_empty, wait) = std::sync::mpsc::channel::<()>(); app.filter_preview_worker diff --git a/crates/ui-egui/src/canvas/navigator.rs b/crates/ui-egui/src/canvas/navigator.rs index 8253334baab..88e53640c76 100644 --- a/crates/ui-egui/src/canvas/navigator.rs +++ b/crates/ui-egui/src/canvas/navigator.rs @@ -74,7 +74,9 @@ pub fn navigator_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usiz app.session.documents().get(idx).map(|st| (std::sync::Arc::downgrade(&st.doc), st.doc.id, st.revision, st.damage_from(), st.last_damage))?; let (doc, preview_key) = display_doc(app, idx); let (display, display_key) = canvas_display(app, &doc, None); - let preview_key = preview_key ^ display_key; + // A tile that fails to read and recovers keeps the snapshot and its revision: the picture and its partial updates + // follow the scratch read-error generation too (`crate::scratch_reads`). + let preview_key = crate::scratch_reads::with(preview_key ^ display_key); let cached = app.navigator_textures.get(&id).cloned(); if let Some((r, p, _, t)) = &cached && r.ptr_eq(&snapshot) diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 8e2e18bac06..cb46af475c8 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -24,8 +24,10 @@ impl MaskSource for SurfaceMask<'_> { self.size } + /// The mask's revision with the scratch read-error generation: a selection tile that fails to read traces as + /// empty, and as its pixels once it reads, without a new revision (`crate::scratch_reads`). fn revision(&self) -> u64 { - self.revision + crate::scratch_reads::with(self.revision) } /// The allocated tiles: every pixel that differs from the default lies in one, and the union of their rects is diff --git a/crates/ui-egui/src/canvas/tool_feedback.rs b/crates/ui-egui/src/canvas/tool_feedback.rs index 38bc614cf05..22821a53a20 100644 --- a/crates/ui-egui/src/canvas/tool_feedback.rs +++ b/crates/ui-egui/src/canvas/tool_feedback.rs @@ -102,7 +102,7 @@ mod tests { assert!(has_selection(&app), "nothing cached: scanned"); assert_eq!(selection_op(Tool::Lasso, 0, ALT, has_selection(&app)), SelectionOperation::Subtract); let st = app.session.active().unwrap(); - let (key, fingerprint) = (u64::MAX - st.doc.id.0, st.doc.selection.as_ref().unwrap().generation()); + let (key, fingerprint) = (u64::MAX - st.doc.id.0, crate::app::thumbs::bounds_revision(st.doc.selection.as_ref().unwrap())); // An empty box cached for this very selection is believed, so nothing is scanned. app.bounds_cache.insert(key, (fingerprint, photocraft_geom::Rect::EMPTY)); assert!(!has_selection(&app), "the cached bounds are used"); diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index 8b695b3525a..21b5a651c2d 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -203,9 +203,10 @@ pub(crate) struct ExportOpen { picking: bool, /// The newest preview the dialog asked for that is not fully answered yet. work: Option, - /// The newest request made, with the working profile it was made under: a change of the working - /// profile alters the preview of an untagged document without changing the settings. - last: Option<(u64, ExportOptions, Option)>, + /// The newest request made, with the working profile and the scratch read-error generation it was made under: a + /// change of the working profile alters the preview of an untagged document without changing the settings, and a + /// tile that fails to read and recovers alters the pixels without a new revision (`crate::scratch_reads`). + last: Option<(u64, ExportOptions, Option, u64)>, } /// One preview request being answered: the proxy preview first, then the exact size estimate. @@ -881,13 +882,14 @@ fn drive(app: &mut PhotocraftApp, ctx: &egui::Context, open: &mut ExportOpen) -> dialog.cancel_requests(); } } - // The settings did not change but the working profile did: ask again for the same revision. + // The settings did not change but the working profile or the scratch read-error generation did: ask again for the + // same revision. let wanted = wanted.or_else(|| { - let (revision, options, hash) = open.last.as_ref()?; - (working_profile_hash(app) != *hash).then(|| PreviewRequest::new(*revision, options.clone())) + let (revision, options, hash, scratch) = open.last.as_ref()?; + (working_profile_hash(app) != *hash || crate::scratch_reads::generation() != *scratch).then(|| PreviewRequest::new(*revision, options.clone())) }); if let Some(request) = wanted { - open.last = Some((request.revision, request.options.clone(), working_profile_hash(app))); + open.last = Some((request.revision, request.options.clone(), working_profile_hash(app), crate::scratch_reads::generation())); open.work = start_preview(app, open, request); } answer_preview(app, ctx, open); @@ -940,7 +942,7 @@ fn start_preview(app: &PhotocraftApp, open: &ExportOpen, request: PreviewRequest let profile = effective_source_profile(app, &doc); let signature = format!("{}:{}", Value::Object(settings.clone()), profile.content_hash()); let layer = open.layers.first().map(|layer| layer.0); - let key = egui::Id::unique(("export-preview", doc.id.0, st.revision, layer)); + let key = egui::Id::unique(("export-preview", doc.id.0, st.revision, layer, crate::scratch_reads::generation())); Some(PreviewWork { revision: request.revision, settings, signature, key, doc, profile, answered: None }) } diff --git a/crates/ui-egui/src/dialogs/export_dialog/tests.rs b/crates/ui-egui/src/dialogs/export_dialog/tests.rs index 24c1b0f6aba..ccbc1244db8 100644 --- a/crates/ui-egui/src/dialogs/export_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/export_dialog/tests.rs @@ -924,6 +924,29 @@ fn preview_cache_tracks_working_profiles_but_prefers_embedded_profiles() { } } +/// A tile that fails to read and recovers alters the pixels without a new revision or other settings: the preview +/// is made again, so it does not keep the zeros it read during the error (`crate::scratch_reads`). +#[test] +fn the_preview_is_made_again_after_a_scratch_read_error_transition() { + let app = export_app(20, 10); + let revision = app.session.active().unwrap().revision; + let mut h = harness(app); + open(h.state_mut()).unwrap(); + settle_preview(&mut h); + let texture = + |h: &AppHarness| h.state().export_open.as_ref().and_then(|open| open.texture.as_ref().map(egui::TextureHandle::id)).expect("a preview was made"); + let before = texture(&h); + let options = dialog_options(&h); + h.run_steps(3); + settle_preview(&mut h); + assert_eq!(texture(&h), before, "nothing changed: the same preview"); + crate::scratch_reads::tests::simulate_read_error_transition(); + settle_preview(&mut h); + assert_eq!(h.state().session.active().unwrap().revision, revision); + assert_eq!(dialog_options(&h), options, "the settings did not change"); + assert_ne!(texture(&h), before, "the preview is made again"); +} + /// The dialog's requests are taken once: a second take in the same frame (a frame can run two /// passes) starts no second preview and files no second save request. #[test] diff --git a/crates/ui-egui/src/dialogs/file_ui/print.rs b/crates/ui-egui/src/dialogs/file_ui/print.rs index 1ba51ac4e89..3da1ad4e521 100644 --- a/crates/ui-egui/src/dialogs/file_ui/print.rs +++ b/crates/ui-egui/src/dialogs/file_ui/print.rs @@ -402,9 +402,9 @@ fn fields_set_position(f: &mut DialogFields, left: f64, top: f64) { /// The document's flattened picture at the preview size, mirrored for Emulsion Down (the sheet /// draws the picture unmirrored in the box). The texture lives in the context's memory under the -/// document's id and revision. +/// document's id and revision, and the scratch read-error generation (`crate::scratch_reads`). fn picture(ctx: &egui::Context, doc: &photocraft_doc::Document, revision: u64, mirror: bool) -> egui::load::SizedTexture { - let key = egui::Id::unique(("print-thumb", doc.id.0, revision, mirror)); + let key = egui::Id::unique(("print-thumb", doc.id.0, revision, mirror, crate::scratch_reads::generation())); let tex: Option> = ctx.data(|d| d.get_temp(key)); let tex = tex.unwrap_or_else(|| { let th = photocraft_compose::thumbnail(doc, 400); @@ -570,3 +570,19 @@ pub(crate) fn print_status(app: &mut PhotocraftApp, r: &Value) { }; app.ui.status_error = false; } + +#[cfg(test)] +mod scratch_tests { + /// A tile that fails to read and recovers keeps the document's revision; the preview picture still draws again, + /// so it does not keep the zeros it read during the error. + #[test] + fn the_preview_picture_draws_again_after_a_scratch_read_error_transition() { + use photocraft_doc::{ColorMode, Document, SampleType}; + let ctx = egui::Context::default(); + let doc = Document::new("Print", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8); + let first = super::picture(&ctx, &doc, 3, false).id; + assert_eq!(super::picture(&ctx, &doc, 3, false).id, first, "the same revision keeps its picture"); + crate::scratch_reads::tests::simulate_read_error_transition(); + assert_ne!(super::picture(&ctx, &doc, 3, false).id, first, "the picture draws again after the transition"); + } +} diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index f52a73e5de2..df82081d160 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -1375,6 +1375,9 @@ pub struct FilterPreviewKey { pub params: Value, pub k: u32, pub tool_colors: ([f32; 4], [f32; 4]), + /// The scratch read-error generation (`crate::scratch_reads`): a tile that fails to read and recovers changes + /// the pixels without a new revision, and a preview computed during the error must not be kept. + pub scratch: u64, } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/filter_preview_ui.rs b/crates/ui-egui/src/dialogs/filter_preview_ui.rs index f0aaeb9f219..8bf8be55773 100644 --- a/crates/ui-egui/src/dialogs/filter_preview_ui.rs +++ b/crates/ui-egui/src/dialogs/filter_preview_ui.rs @@ -94,9 +94,10 @@ fn picture(app: &PhotocraftApp, ctx: &egui::Context, id: DialogId) -> Option(cache_id))); - // Channel visibility and the active mask can change without a document revision. Both the - // original (press-and-hold) and filtered textures must follow the canvas's current view. - let view = (st.channel_view.clone(), app.session.prefs().interface.show_channels_in_color, st.active_layer); + // Channel visibility and the active mask can change without a document revision, and so can a tile that fails + // to read and recovers (`crate::scratch_reads`). Both the original (press-and-hold) and filtered textures must + // follow the canvas's current view. + let view = (st.channel_view.clone(), app.session.prefs().interface.show_channels_in_color, st.active_layer, crate::scratch_reads::generation()); if cache.view.as_ref() != Some(&view) { cache = Cache { view: Some(view), ..Default::default() }; } @@ -221,7 +222,7 @@ struct CachedTex { struct Cache { filtered: Option, original: Option, - view: Option<(photocraft_engine::channel_cmds::ChannelView, bool, Option)>, + view: Option<(photocraft_engine::channel_cmds::ChannelView, bool, Option, u64)>, } #[cfg(test)] @@ -358,6 +359,26 @@ mod tests { assert!(pixels.unwrap().iter().all(|p| *p == Color32::BLACK)); } + /// A tile that fails to read and recovers moves no revision; the unfiltered texture still draws again then, so it + /// does not keep the zeros it read during the error. + #[test] + fn original_texture_refreshes_after_a_scratch_read_error_transition() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); + let id = top_dialog(&app); + let ctx = app.ctx().clone(); + let cache_id = egui::Id::unique(("filter-preview-ui", id.value())); + let original = |ctx: &egui::Context| ctx.data(|d| d.get_temp::(cache_id).unwrap().original.unwrap().tex.id()); + ctx.run_ui(Default::default(), |ui| feed(&mut app, ui.ctx())).textures_delta.clear(); + let before = original(&ctx); + ctx.run_ui(Default::default(), |ui| feed(&mut app, ui.ctx())).textures_delta.clear(); + assert_eq!(original(&ctx), before, "an unchanged picture is not uploaded again"); + crate::scratch_reads::tests::simulate_read_error_transition(); + ctx.run_ui(Default::default(), |ui| feed(&mut app, ui.ctx())).textures_delta.clear(); + assert_ne!(original(&ctx), before, "the picture draws again after the transition"); + } + #[test] fn only_filter_dialogs_get_the_preview_pane() { for (command, pane) in [ diff --git a/crates/ui-egui/src/dialogs/filter_preview_worker.rs b/crates/ui-egui/src/dialogs/filter_preview_worker.rs index fd440543b69..b6bafade7b6 100644 --- a/crates/ui-egui/src/dialogs/filter_preview_worker.rs +++ b/crates/ui-egui/src/dialogs/filter_preview_worker.rs @@ -131,6 +131,7 @@ mod tests { params: json!({"colors": colors}), k: 1, tool_colors: ([0.0, 0.0, 0.0, 1.0], [1.0; 4]), + scratch: 0, } } diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index de856173ae6..5b956a53478 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -641,11 +641,18 @@ fn paint_picture(cx: &ContentPainterCx, rect: Rect, key: impl std::hash::Hash + cx.picture(texture, rect, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), 0.0); } +/// The texture store key of the preview swatch: the draft's render hash and the scratch read-error generation, as the +/// swatch draws over the patterns' pixels, which a tile that fails to read shows as zeros until it reads again +/// (`crate::scratch_reads`). +fn swatch_key(draft: &LayerStyleDraft) -> (&'static str, u64, u64) { + ("layer-style-swatch", draft.render_hash(), crate::scratch_reads::generation()) +} + /// Paints the preview swatch: the draft's style on a sample square, rebuilt when its render hash changes. fn preview_thumb(app: &PhotocraftApp) -> impl Fn(&ContentPainterCx, Rect, &LayerStyleDraft) + Send + Sync + 'static { let patterns = app.session.patterns.clone(); move |cx, rect, draft| { - paint_picture(cx, rect, ("layer-style-swatch", draft.render_hash()), || { + paint_picture(cx, rect, swatch_key(draft), || { let mut scratch = Session::new(); scratch.patterns = patterns.clone(); match pending_style(&patterns, &draft.style) { diff --git a/crates/ui-egui/src/dialogs/layer_style/tests.rs b/crates/ui-egui/src/dialogs/layer_style/tests.rs index 7d836202085..3ee114f20ce 100644 --- a/crates/ui-egui/src/dialogs/layer_style/tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/tests.rs @@ -790,3 +790,16 @@ fn an_existing_outer_glow_is_edited_with_its_own_values() { let FxPaint::Color(c) = &g.paint else { panic!("{:?}", g.paint) }; assert_eq!(hex(c), "#ffffbe", "OK kept the colour"); } + +/// The preview swatch draws over the patterns' pixels: a tile that fails to read and recovers keeps the draft's render +/// hash, and the swatch still keys a new picture, so it does not keep the zeros it read during the error. +#[test] +fn the_preview_swatch_follows_a_scratch_read_error_transition() { + let mut app = app_with_layer(32); + let id = open(&mut app, Some(EffectKind::PatternOverlay.key())).unwrap(); + let key = swatch_key(draft(&app, id)); + assert_eq!(swatch_key(draft(&app, id)), key, "nothing changed: the same picture"); + crate::scratch_reads::tests::simulate_read_error_transition(); + assert_eq!(draft(&app, id).render_hash(), key.1, "the draft is unchanged"); + assert_ne!(swatch_key(draft(&app, id)), key, "the swatch draws again"); +} diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 1631cb54a99..dec11d58b4e 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -29,6 +29,7 @@ fn filter_dialog_with_preview(background: bool) -> (Box, DialogId params: serde_json::json!({"radius": 4.0}), k: 1, tool_colors: (app.session.tools.foreground, app.session.tools.background), + scratch: crate::scratch_reads::generation(), }; app.filter_preview = Some(crate::filter_dialog::FilterPreview { key, result: result.map(std::sync::Arc::new), committing: false }); (app, id) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d08be0f3520..0927c80a3ad 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -56,6 +56,7 @@ pub mod panels; pub mod preset_files_ui; pub mod proxy; pub mod render_path; +pub(crate) mod scratch_reads; pub mod state; pub mod texel_guard; pub mod theme; @@ -973,6 +974,8 @@ mod layer_thumb_bounds_tests; mod mask_thumb_refresh_tests; #[cfg(test)] mod menu_floor_trials; +#[cfg(test)] +mod scratch_read_keys_tests; #[cfg(test)] mod new_doc_remember_tests; diff --git a/crates/ui-egui/src/menus/facts.rs b/crates/ui-egui/src/menus/facts.rs index 4732b7800bf..aacc54fdfcb 100644 --- a/crates/ui-egui/src/menus/facts.rs +++ b/crates/ui-egui/src/menus/facts.rs @@ -205,7 +205,7 @@ impl<'a> RuleFacts<'a> { active_index: s.active_index(), active: s.active_tracked(), all: all_revisions(s.documents()), - scratch: photocraft_raster::spill::read_error_generation(), + scratch: crate::scratch_reads::generation(), jobs: (s.has_jobs(), s.active_job().map(|job| job.id.0)), smart_child: active.is_some_and(|d| s.smart_links.iter().any(|link| link.child == d.doc.id)), fade: s.edit_state.fade.as_ref().map(|fade| (fade.doc, fade.revision)), diff --git a/crates/ui-egui/src/panels/histogram_panel.rs b/crates/ui-egui/src/panels/histogram_panel.rs index 65cb7822400..7a241651c7c 100644 --- a/crates/ui-egui/src/panels/histogram_panel.rs +++ b/crates/ui-egui/src/panels/histogram_panel.rs @@ -351,7 +351,9 @@ fn committed_key(app: &PhotocraftApp) -> Option<(HistKey, ToneSpace, HistSource) Some((d, r, k)) if d == doc && r == revision => k, _ => tone::selection_key(&st.doc), }; - let source_tag = tone::tag(source, space, HistScope::Selection, sel); + // A tile that fails to read counts as zeros, and as its pixels again once it reads, without a new revision: the + // key follows the scratch read-error generation too (`crate::scratch_reads`). + let source_tag = crate::scratch_reads::with(tone::tag(source, space, HistScope::Selection, sel)); Some((HistKey { doc, revision, source: source_tag, preview: 0, max_level }, space, source)) } diff --git a/crates/ui-egui/src/panels/histogram_panel/tests.rs b/crates/ui-egui/src/panels/histogram_panel/tests.rs index fe539665261..0a85f3b0771 100644 --- a/crates/ui-egui/src/panels/histogram_panel/tests.rs +++ b/crates/ui-egui/src/panels/histogram_panel/tests.rs @@ -447,3 +447,21 @@ fn the_tone_histogram_cache_ignores_selection_changes() { app.run("select.deselect", json!({})).unwrap(); assert!(Arc::ptr_eq(&first, &tone::histograms(&mut app, src, ToneSpace::Rgb)), "deselecting keeps it too"); } + +/// A tile that fails to read counts as zeros, and as its pixels again once it reads, without a new revision or +/// selection: the panel's histogram goes stale and is counted again (`crate::scratch_reads`). +#[test] +fn the_panel_recounts_after_a_scratch_read_error_transition() { + let mut app = app_with(json!({"width": 64, "height": 48})); + settle(&mut app); + let counted = app.doc_hist.clone().expect("landed"); + frame(&mut app); + assert_eq!(inspect(&app)["current"], true, "nothing changed: still current"); + crate::scratch_reads::tests::simulate_read_error_transition(); + assert_eq!(inspect(&app)["current"], false, "stale after the transition"); + settle(&mut app); + let recounted = app.doc_hist.clone().expect("landed"); + assert_eq!(recounted.key.revision, counted.key.revision, "no new revision"); + assert_ne!(recounted.key.source, counted.key.source, "counted again for the new generation"); + assert_eq!(inspect(&app)["current"], true); +} diff --git a/crates/ui-egui/src/panels/layers_tree.rs b/crates/ui-egui/src/panels/layers_tree.rs index 25e10df30d3..4a6f0b42af9 100644 --- a/crates/ui-egui/src/panels/layers_tree.rs +++ b/crates/ui-egui/src/panels/layers_tree.rs @@ -746,7 +746,7 @@ impl ThumbSource> for PhotoThumbs<'_> { }; // A tile that fails to read shows zeros, and its pixels again once it reads, without moving its surface's // generation: the scratch read-error generation moves with both (#16252). - let scratch = photocraft_raster::spill::read_error_generation(); + let scratch = crate::scratch_reads::generation(); Revision::of(&(shown, clip, self.doc.size.width, self.doc.size.height, scratch)) } diff --git a/crates/ui-egui/src/panels/preset_browser.rs b/crates/ui-egui/src/panels/preset_browser.rs index 242b9a3d234..3b8cc76f2e8 100644 --- a/crates/ui-egui/src/panels/preset_browser.rs +++ b/crates/ui-egui/src/panels/preset_browser.rs @@ -160,9 +160,12 @@ type HeldPatterns = Arc<[Arc]>; type StylesStamp = (Revision, u64); /// A number for the library's patterns and their pixels: equal stamps mean the same patterns with the same pixels -/// (`Surface::generation` names a pixel state, and is shared by clones). +/// (`Surface::generation` names a pixel state, and is shared by clones). It also moves with the scratch read-error +/// generation: a pattern tile that fails to read draws zeros and its pixels again once it reads, under the same +/// generation (`crate::scratch_reads`), and the style thumbnails drawn over the patterns follow it through this. fn patterns_stamp(library: &PatternLibrary) -> u64 { let mut hasher = DefaultHasher::new(); + crate::scratch_reads::generation().hash(&mut hasher); for pattern in &library.items { (&pattern.id, &pattern.name, pattern.surface.generation()).hash(&mut hasher); } @@ -302,9 +305,9 @@ fn pattern_image(pattern: &photocraft_doc::Pattern) -> ColorImage { } /// The texture store key of `pattern`'s swatch: its id and its pixels, so a pattern replaced under the same id draws -/// anew. +/// anew, and a swatch drawn while a tile failed to read draws again once it reads (`crate::scratch_reads`). fn pattern_key(pattern: &photocraft_doc::Pattern) -> PictureKey { - ("pattern", pattern.id.clone(), pattern.surface.generation()) + ("pattern", pattern.id.clone(), crate::scratch_reads::with(pattern.surface.generation())) } /// A texture of `pattern`'s swatch that its holder owns: it stays while the handle lives, where a cached texture diff --git a/crates/ui-egui/src/panels/preset_browser/tests.rs b/crates/ui-egui/src/panels/preset_browser/tests.rs index ee3c9c66131..6044d8c57ef 100644 --- a/crates/ui-egui/src/panels/preset_browser/tests.rs +++ b/crates/ui-egui/src/panels/preset_browser/tests.rs @@ -172,6 +172,24 @@ fn a_pattern_replaced_under_its_id_keys_a_new_picture() { assert_eq!(pattern_key(&first), pattern_key(&first.clone()), "a clone holds the same pixels"); } +/// A pattern swatch drawn while a pattern tile failed to read shows zeros: once the tile reads again (no new +/// generation), the swatch keys a new picture, and so do the style thumbnails drawn over the patterns. +#[test] +fn pattern_and_style_pictures_follow_a_scratch_read_error_transition() { + let mut app = app(); + let pattern = app.session.patterns.items[0].clone(); + let (swatch, library) = (pattern_key(&pattern), StyleLibrary::held(&mut app)); + assert_eq!(pattern_key(&pattern), swatch); + assert!(Arc::ptr_eq(&library, &StyleLibrary::held(&mut app))); + crate::scratch_reads::tests::simulate_read_error_transition(); + assert_ne!(pattern_key(&pattern), swatch, "the swatch draws again"); + let after = StyleLibrary::held(&mut app); + assert!(!Arc::ptr_eq(&library, &after), "the style library is taken again"); + let stamps = |library: &StyleLibrary| library.styles.iter().map(|(stamp, _)| *stamp).collect::>(); + assert!(!stamps(&library).is_empty()); + assert!(stamps(&library).iter().zip(stamps(&after)).all(|(before, now)| *before != now), "every style thumbnail draws again"); +} + /// The flat list of the app's style presets. fn styles(app: &PhotocraftApp) -> Vec { app.session.presets.styles.iter().flat_map(|group| group.items.iter().cloned()).collect() diff --git a/crates/ui-egui/src/scratch_read_keys_tests.rs b/crates/ui-egui/src/scratch_read_keys_tests.rs new file mode 100644 index 00000000000..186d3a10335 --- /dev/null +++ b/crates/ui-egui/src/scratch_read_keys_tests.rs @@ -0,0 +1,116 @@ +//! The UI's pictures and derived values of document pixels follow the scratch read-error generation: a tile that +//! fails to read shows zeros and its real pixels again once it reads, without moving its surface's generation or its +//! document's revision (`crate::scratch_reads`). Each test simulates one such transition and checks that the key a +//! cache is held by moves with it, and stays put without it. + +use craft::imaging::trace::MaskSource; +use craft::layers::ui::thumbs::{LayerThumb, ThumbContents}; +use craft::ui::primitives::textures::{ThumbRequest, ThumbSource}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::channels_panel::Row; +use crate::scratch_reads::tests::simulate_read_error_transition; + +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.run("layer.new.layer", json!({"name": "Paint"})).unwrap(); + app.run("paint.stroke", json!({"points": [[4, 4], [40, 30]], "size": 8, "color": "#2060c0"})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.run("channel.new", json!({"name": "Alpha", "fill": "white"})).unwrap(); + app.run("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + app +} + +fn request() -> ThumbRequest { + ThumbRequest::for_cell(32.0, 1.0) +} + +/// Calls `revision` before, again without a change, and after one transition: the key must hold, then move. +fn holds_then_moves(what: &str, mut revision: impl FnMut() -> T) { + let before = revision(); + assert_eq!(revision(), before, "{what}: nothing changed, the same key"); + simulate_read_error_transition(); + assert_ne!(revision(), before, "{what}: a read error or its recovery moves the key"); +} + +#[test] +fn layer_thumbnails_follow_a_scratch_read_error_transition() { + let app = app(); + let st = app.session.active().unwrap(); + let layer = st.active_layer.unwrap(); + let keys = [LayerThumb::pixels(layer, ThumbContents::EntireDocument), LayerThumb::mask(layer)]; + holds_then_moves("layer thumbnails", || { + let thumbs = crate::panels::layers_tree::PhotoThumbs::new(&app, &st.doc); + keys.iter().map(|key| thumbs.revision(key, &request()).get()).collect::>() + }); +} + +#[test] +fn the_rule_facts_follow_a_scratch_read_error_transition() { + let app = app(); + holds_then_moves("rule facts", || crate::menus::facts::key(&app)); +} + +#[test] +fn channel_thumbnails_follow_a_scratch_read_error_transition() { + let app = app(); + let st = app.session.active().unwrap(); + holds_then_moves("channel thumbnails", || { + let thumbs = crate::app::thumbs::ChannelThumbs::new(&app, st); + [Row::Composite, Row::Color(0), Row::Alpha(0), Row::LayerMask].iter().map(|row| thumbs.revision(row, &request()).get()).collect::>() + }); +} + +#[test] +fn snapshot_thumbnails_follow_a_scratch_read_error_transition() { + let app = app(); + let st = app.session.active().unwrap(); + let snapshot = st.snapshots().first().map(|s| s.id).expect("a new document has its first snapshot"); + holds_then_moves("snapshot thumbnails", || crate::app::thumbs::SnapshotThumbs::new(&app, st.doc.id).revision(&snapshot, &request()).get()); +} + +/// A selection whose tile read as zeros scans as empty: once it reads again, the cached bounds are scanned anew. +#[test] +fn cached_bounds_are_scanned_again_after_a_scratch_read_error_transition() { + let mut app = app(); + let (doc, selection) = { + let st = app.session.active().unwrap(); + (st.doc.id, st.doc.selection.clone().unwrap()) + }; + let key = u64::MAX - doc.0; + let bounds = app.cached_bounds(key, &selection); + assert!(!bounds.is_empty()); + // The box a scan during the read error would have cached. + let fingerprint = crate::app::thumbs::bounds_revision(&selection); + app.bounds_cache.insert(key, (fingerprint, photocraft_geom::Rect::EMPTY)); + assert!(app.known_bounds(key, &selection).is_empty(), "without a transition the cached box is believed"); + simulate_read_error_transition(); + assert_eq!(app.known_bounds(key, &selection), bounds, "after it, the bounds are scanned again"); + assert_eq!(app.cached_bounds(key, &selection), bounds); +} + +#[test] +fn the_selection_outline_follows_a_scratch_read_error_transition() { + let app = app(); + let st = app.session.active().unwrap(); + let selection = st.doc.selection.as_ref().unwrap(); + let size = [st.doc.size.width, st.doc.size.height]; + holds_then_moves("selection outline", || crate::canvas::outline::SurfaceMask::new(selection, selection.generation(), size).revision()); +} + +#[test] +fn the_navigator_picture_draws_again_after_a_scratch_read_error_transition() { + let mut app = app(); + let ctx = app.ctx().clone(); + let doc = app.session.active().unwrap().doc.id; + crate::canvas::navigator_texture(&mut app, &ctx, 0).unwrap(); + let held = |app: &PhotocraftApp| app.navigator_textures.get(&doc).map(|(_, key, _, texture)| (*key, texture.id())).unwrap(); + let before = held(&app); + crate::canvas::navigator_texture(&mut app, &ctx, 0).unwrap(); + assert_eq!(held(&app), before, "nothing changed: the same picture"); + simulate_read_error_transition(); + crate::canvas::navigator_texture(&mut app, &ctx, 0).unwrap(); + assert_ne!(held(&app).0, before.0, "the picture is drawn again for the new generation"); +} diff --git a/crates/ui-egui/src/scratch_reads.rs b/crates/ui-egui/src/scratch_reads.rs new file mode 100644 index 00000000000..014eb823f34 --- /dev/null +++ b/crates/ui-egui/src/scratch_reads.rs @@ -0,0 +1,48 @@ +//! The scratch read-error generation as the UI's caches key on it. +//! +//! A tile whose scratch bytes fail to read shows a zero placeholder through `&self`, and its real pixels again once +//! a reload succeeds, without moving its surface's generation or its document's revision (the `PlainData` comment on +//! `photocraft_raster::Tile`). Both transitions move `spill::read_error_generation`, so every picture or derived +//! value the UI keeps of document or preset pixels keys on [`generation`] too; otherwise a thumbnail drawn during a +//! read error keeps its zeros after the tile recovers. + +/// The scratch read-error generation now: it moves when a tile fails to read and when it reads again. +pub(crate) fn generation() -> u64 { + let real = photocraft_raster::spill::read_error_generation(); + #[cfg(test)] + let real = real.wrapping_add(tests::BUMPS.with(std::cell::Cell::get)); + real +} + +/// [`generation`] folded with `revision`: one number for a cache keyed by a single `u64` that must follow both. +pub(crate) fn with(revision: u64) -> u64 { + use std::hash::{Hash, Hasher}; + let mut hasher = std::hash::DefaultHasher::new(); + (revision, generation()).hash(&mut hasher); + hasher.finish() +} + +#[cfg(test)] +pub(crate) mod tests { + use std::cell::Cell; + + thread_local! { + /// Read-error transitions simulated on this test's thread, so a test sees one without setting up the + /// process-wide scratch file, and tests on other threads never do. + pub(super) static BUMPS: Cell = const { Cell::new(0) }; + } + + /// Simulates one read-error transition (a tile failing, or one recovering) as the caches see it. + pub(crate) fn simulate_read_error_transition() { + BUMPS.with(|bumps| bumps.set(bumps.get().wrapping_add(1))); + } + + #[test] + fn a_simulated_transition_moves_the_generation_and_the_folded_key() { + let (generation, folded) = (super::generation(), super::with(7)); + assert_eq!(super::with(7), folded, "the same state folds to the same key"); + simulate_read_error_transition(); + assert_ne!(super::generation(), generation); + assert_ne!(super::with(7), folded); + } +}