Skip to content

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

Make channel filter previews match the committed edit (#3979)

jonathanwxh-cell3f0a633056d5
diff --git a/crates/compose/src/proxy.rs b/crates/compose/src/proxy.rs
index 4fe3b879f..7fe7fc398 100644
--- a/crates/compose/src/proxy.rs
+++ b/crates/compose/src/proxy.rs
@@ -79,6 +79,9 @@ pub fn proxy_document(doc: &Document, k: u32) -> Document {
c.surface = downsample(&c.surface, k);
}
p.selection = p.selection.as_ref().map(|s| downsample(s, k));
+ if let Some(mask) = &mut p.quick_mask {
+ mask.surface = downsample(&mask.surface, k);
+ }
p
}
@@ -172,6 +175,27 @@ mod tests {
assert!(proxy_document(&Document::new("n", Size::new(8, 8), ColorMode::Rgb, SampleType::U8), 4).selection.is_none());
}
+ #[test]
+ fn proxy_scales_quick_mask_at_every_depth() {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let mut doc = Document::new("mask", Size::new(16, 12), ColorMode::Rgb, depth);
+ let mut surface = Surface::new(PixelFormat::new(ColorMode::Grayscale, depth, false));
+ surface.fill_rect(Rect::new(0, 0, 8, 12), &[1.0]);
+ let mut mask = photocraft_doc::AlphaChannel::new("Quick Mask", surface);
+ mask.opacity = 0.25;
+ doc.quick_mask = Some(mask);
+ for k in [1, 2, 4] {
+ let proxy = proxy_document(&doc, k);
+ let mask = proxy.quick_mask.as_ref().unwrap();
+ assert_eq!(mask.surface.pixel((8 / k - 1) as i32, 0), vec![1.0]);
+ assert_eq!(mask.surface.pixel((8 / k) as i32, 0), vec![0.0], "depth {depth:?}, factor {k}");
+ assert_eq!(mask.opacity, 0.25);
+ assert_eq!(mask.surface.format().sample, depth);
+ }
+ assert_eq!(doc.quick_mask.as_ref().unwrap().surface.pixel(7, 0), vec![1.0], "source stays intact");
+ }
+ }
+
#[test]
fn proxy_accepts_empty_paths_but_keeps_geometry_and_effect_guards() {
let mut doc = two_colors(Size::new(32, 16), SampleType::F32);
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 17de8820e..5b6222b31 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -1466,8 +1466,16 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e
let st = app.session.documents().get(idx)?;
// Filters whose features don't scale with a proxy preview at full resolution (#2063).
let k = crate::filter_dialog::preview_factor(&cmd, &params, crate::proxy::preview_factor(&st.doc, crate::proxy::reduced_previews(app)));
- let request =
- crate::filter_dialog::FilterPreviewKey { doc: st.doc.id, revision: st.revision, dialog: d.id, active: st.active_layer, command: cmd, params, k };
+ let request = crate::filter_dialog::FilterPreviewKey {
+ doc: st.doc.id,
+ revision: st.revision,
+ dialog: d.id,
+ active: st.active_layer,
+ target: st.channel_view.target,
+ command: cmd,
+ params,
+ k,
+ };
let key = request.doc.0 ^ (1u64 << 61);
// Every filter's preview computes off the UI thread in the desktop app: Gaussian Blur at
// 1000 px takes long enough to freeze the window. Once the slider settles, a preview still
@@ -1492,10 +1500,13 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e
let task = request.clone();
if let Err(error) = app.filter_preview_worker.start(request.clone(), ctx.clone(), move |cancel| {
let t0 = crate::gpu_canvas::now_ms();
- let result = crate::filter_dialog::preview_document_with(&doc, task.active, &task.command, &task.params, task.k, Some(cancel)).map(|doc| {
- let buffer = photocraft_compose::flatten(&doc);
- (std::sync::Arc::new(doc), buffer)
- });
+ let result =
+ crate::filter_dialog::preview_document_for_target(&doc, task.active, &task.command, &task.params, task.k, Some(cancel), task.target).map(
+ |doc| {
+ let buffer = photocraft_compose::flatten(&doc);
+ (std::sync::Arc::new(doc), buffer)
+ },
+ );
crate::filter_preview_worker::Computed { result, ms: crate::gpu_canvas::now_ms() - t0 }
}) {
app.filter_preview = Some(crate::filter_dialog::FilterPreview { key: request.clone(), result: None, committing: false });
@@ -1512,6 +1523,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e
|| preview.key.revision != request.revision
|| preview.key.dialog != request.dialog
|| preview.key.active != request.active
+ || preview.key.target != request.target
|| preview.key.k != request.k
|| preview.key.command != request.command
{
@@ -1526,7 +1538,9 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e
if app.filter_preview.as_ref().is_none_or(|p| p.key != request) {
let doc = app.session.documents().get(idx)?.doc.clone();
let t0 = crate::gpu_canvas::now_ms();
- let result = crate::filter_dialog::preview_document(&doc, request.active, &request.command, &request.params, request.k).map(std::sync::Arc::new);
+ let result =
+ crate::filter_dialog::preview_document_for_target(&doc, request.active, &request.command, &request.params, request.k, None, request.target)
+ .map(std::sync::Arc::new);
if let Some(r) = &result {
let buf = photocraft_compose::flatten(r);
let t1 = crate::gpu_canvas::now_ms();
@@ -1544,6 +1558,18 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e
Some((preview.key.k, key, [result.size.width, result.size.height]))
}
+/// Channel overlays must use the filter's current proxy too, including on the CPU canvas.
+/// The cache key changes with the completed request; unchanged frames reuse the overlay texture.
+pub(crate) fn filter_channel_preview(app: &mut PhotocraftApp, idx: usize, ctx: &egui::Context) -> Option<(std::sync::Arc<Document>, u64)> {
+ use std::hash::{Hash, Hasher};
+ ensure_filter_preview(app, idx, ctx)?;
+ let preview = app.filter_preview.as_ref()?;
+ let doc = preview.result.as_ref()?.clone();
+ let mut key = std::collections::hash_map::DefaultHasher::new();
+ format!("{:?}", preview.key).hash(&mut key);
+ Some((doc, key.finish() | (1 << 59)))
+}
+
fn publish_filter_preview(
app: &mut PhotocraftApp,
idx: usize,
@@ -5407,6 +5433,7 @@ mod tests {
revision: st.revision,
dialog: d.id,
active: st.active_layer,
+ target: st.channel_view.target,
command: "filter.blur.gaussianBlur".into(),
params: json!({"radius": 999.0}),
k: 1,
@@ -5454,6 +5481,7 @@ mod tests {
revision: st.revision,
dialog: d.id,
active: st.active_layer,
+ target: st.channel_view.target,
command: "image.mode.indexedColor".into(),
params: app.with_mask_target("image.mode.indexedColor", crate::filter_dialog::params_of(&d.fields)),
k: 1,
@@ -7141,6 +7169,200 @@ mod rotation_preview_isolation_tests {
use super::*;
use serde_json::json;
+ #[test]
+ fn channel_overlay_shows_filter_preview_and_restores_on_cancel() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.background_jobs = false;
+ app.run("file.new", json!({"width":16,"height":16})).unwrap();
+ app.run("channel.new", json!({"name":"Alpha","fill":"black"})).unwrap();
+ app.session
+ .edit("Fixture", |doc, _| {
+ for y in 0..16 {
+ for x in 0..8 {
+ doc.channels[0].surface.write_pixel(x, y, &[1.0]);
+ }
+ }
+ Ok(())
+ })
+ .unwrap();
+ let before = app.session.active().unwrap().doc.clone();
+ let ctx = egui::Context::default();
+ let texture = crate::channel_view::ensure(&mut app, &ctx, 0).unwrap();
+ ctx.tex_manager().write().take_delta().clear();
+ let dialog = crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap();
+ app.ui.dialogs.last_mut().unwrap().fields.insert("radius".into(), json!(2.0));
+ ensure_filter_preview(&mut app, 0, &ctx).unwrap();
+ crate::channel_view::ensure(&mut app, &ctx, 0);
+ let mut delta = ctx.tex_manager().write().take_delta();
+ let egui::ImageData::Color(image) = &delta.set.get(&texture).expect("filter preview must update channel overlay")[0].image;
+ let st = app.session.active().unwrap();
+ let original = crate::channel_view::render(&before, &st.channel_view, before.bounds(), 1, false, st.active_layer).unwrap();
+ assert_ne!(image.pixels, original, "a nontrivial filter must be visible before OK");
+ delta.clear();
+ assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc));
+ app.ui.dialogs.last_mut().unwrap().fields.insert("__preview".into(), json!(false));
+ crate::channel_view::ensure(&mut app, &ctx, 0);
+ let mut delta = ctx.tex_manager().write().take_delta();
+ let egui::ImageData::Color(image) = &delta.set.get(&texture).expect("Preview off restores channel")[0].image;
+ assert_eq!(image.pixels, original);
+ delta.clear();
+ app.ui.dialogs.last_mut().unwrap().fields.insert("__preview".into(), json!(true));
+ crate::channel_view::ensure(&mut app, &ctx, 0);
+ ctx.tex_manager().write().take_delta().clear();
+ crate::dialogs::cancel(&mut app, dialog).unwrap();
+ crate::channel_view::ensure(&mut app, &ctx, 0);
+ let mut delta = ctx.tex_manager().write().take_delta();
+ let egui::ImageData::Color(image) = &delta.set.get(&texture).expect("Cancel restores channel")[0].image;
+ assert_eq!(image.pixels, original);
+ delta.clear();
+ assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc));
+ }
+
+ fn assert_filter_preview_target(target: photocraft_engine::channel_cmds::ChannelTarget) {
+ for depth in [8, 16, 32] {
+ let mut session = photocraft_engine::Session::new();
+ session.execute("file.new", json!({"width":16,"height":16,"depth":depth})).unwrap();
+ session.execute("channel.new", json!({"name":"Alpha","fill":"black"})).unwrap();
+ session
+ .edit("Fixture", |doc, active| {
+ let layer = doc.layer_mut(active.unwrap()).unwrap();
+ layer.mask = Some(photocraft_doc::LayerMask::hide_all());
+ for y in 0..16 {
+ for x in 0..8 {
+ layer.surface_mut().unwrap().write_pixel(x, y, &[0.0, 0.25, 0.5, 1.0]);
+ layer.mask.as_mut().unwrap().surface.write_pixel(x, y, &[1.0]);
+ }
+ }
+ for y in 0..16 {
+ for x in 0..8 {
+ doc.channels[0].surface.write_pixel(x, y, &[1.0]);
+ }
+ }
+ Ok(())
+ })
+ .unwrap();
+ session.active_mut().unwrap().channel_view.target = target;
+ let mut app = PhotocraftApp::new(session, crate::Services::default());
+ app.background_jobs = false;
+ let dialog = crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap();
+ app.ui.dialogs.last_mut().unwrap().fields.insert("radius".into(), json!(2.0));
+ ensure_filter_preview(&mut app, 0, &egui::Context::default()).unwrap();
+ let preview = app.filter_preview.as_ref().unwrap().result.as_ref().unwrap().clone();
+ crate::dialogs::confirm(&mut app, dialog).unwrap();
+ let final_doc = &app.session.active().unwrap().doc;
+ let bounds = final_doc.bounds();
+ assert_eq!(
+ preview.layers[0].surface().unwrap().read_region(bounds),
+ final_doc.layers[0].surface().unwrap().read_region(bounds),
+ "RGB: {depth} {target:?}"
+ );
+ assert_eq!(preview.channels[0].surface.read_region(bounds), final_doc.channels[0].surface.read_region(bounds), "alpha: {depth} {target:?}");
+ assert_eq!(
+ preview.layers[0].mask.as_ref().unwrap().surface.read_region(bounds),
+ final_doc.layers[0].mask.as_ref().unwrap().surface.read_region(bounds),
+ "mask: {depth} {target:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn filter_preview_matches_applied_alpha_target() {
+ assert_filter_preview_target(photocraft_engine::channel_cmds::ChannelTarget::Alpha(0));
+ }
+
+ #[test]
+ fn filter_preview_matches_applied_color_target() {
+ assert_filter_preview_target(photocraft_engine::channel_cmds::ChannelTarget::Color(0));
+ }
+
+ #[test]
+ fn filter_preview_matches_applied_layer_mask_target() {
+ assert_filter_preview_target(photocraft_engine::channel_cmds::ChannelTarget::LayerMask);
+ }
+
+ #[test]
+ fn filter_preview_refreshes_when_channel_target_changes() {
+ use photocraft_engine::channel_cmds::ChannelTarget;
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.background_jobs = false;
+ app.run("file.new", json!({"width":16,"height":16})).unwrap();
+ for name in ["First", "Second"] {
+ app.run("channel.new", json!({"name":name,"fill":"black"})).unwrap();
+ }
+ app.session
+ .edit("Fixture", |doc, _| {
+ for y in 0..16 {
+ for x in 0..8 {
+ doc.channels[1].surface.write_pixel(x, y, &[1.0]);
+ }
+ }
+ Ok(())
+ })
+ .unwrap();
+ app.session.active_mut().unwrap().channel_view.target = ChannelTarget::Alpha(0);
+ let revision = app.session.active().unwrap().revision;
+ let dialog = crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap();
+ app.ui.dialogs.last_mut().unwrap().fields.insert("radius".into(), json!(2.0));
+ let ctx = egui::Context::default();
+ let (first, first_key) = filter_channel_preview(&mut app, 0, &ctx).unwrap();
+ app.session.active_mut().unwrap().channel_view.target = ChannelTarget::Alpha(1);
+ let (second, second_key) = filter_channel_preview(&mut app, 0, &ctx).unwrap();
+ assert_eq!(app.session.active().unwrap().revision, revision);
+ assert_ne!(first_key, second_key);
+ assert_ne!(first.channels[1].surface.read_region(first.bounds()), second.channels[1].surface.read_region(second.bounds()));
+ let (unchanged, unchanged_key) = filter_channel_preview(&mut app, 0, &ctx).unwrap();
+ assert!(std::sync::Arc::ptr_eq(&second, &unchanged));
+ assert_eq!(second_key, unchanged_key);
+ crate::dialogs::confirm(&mut app, dialog).unwrap();
+ let applied = &app.session.active().unwrap().doc;
+ assert_eq!(second.channels[1].surface.read_region(second.bounds()), applied.channels[1].surface.read_region(applied.bounds()));
+ }
+
+ #[test]
+ fn filter_preview_overlay_matches_quick_mask_and_mixed_color_views() {
+ for quick_mask in [false, true] {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.background_jobs = false;
+ app.run("file.new", json!({"width":16,"height":16})).unwrap();
+ app.session
+ .edit("Fixture", |doc, active| {
+ if quick_mask {
+ doc.quick_mask =
+ Some(photocraft_doc::AlphaChannel::new("Quick Mask", photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8)));
+ }
+ for y in 0..16 {
+ for x in 0..8 {
+ if let Some(mask) = &mut doc.quick_mask {
+ mask.surface.write_pixel(x, y, &[1.0]);
+ } else {
+ doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().write_pixel(x, y, &[0.0, 0.25, 0.5, 1.0]);
+ }
+ }
+ }
+ Ok(())
+ })
+ .unwrap();
+ if !quick_mask {
+ let view = &mut app.session.active_mut().unwrap().channel_view;
+ view.target = photocraft_engine::channel_cmds::ChannelTarget::Color(0);
+ view.set_color_visible(2, false);
+ }
+ let ctx = egui::Context::default();
+ let texture = crate::channel_view::ensure(&mut app, &ctx, 0).unwrap();
+ ctx.tex_manager().write().take_delta().clear();
+ let dialog = crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap();
+ app.ui.dialogs.last_mut().unwrap().fields.insert("radius".into(), json!(2.0));
+ crate::channel_view::ensure(&mut app, &ctx, 0).unwrap();
+ let mut delta = ctx.tex_manager().write().take_delta();
+ let egui::ImageData::Color(image) = &delta.set.get(&texture).expect("preview must refresh overlay")[0].image;
+ crate::dialogs::confirm(&mut app, dialog).unwrap();
+ let st = app.session.active().unwrap();
+ let expected = crate::channel_view::render(&st.doc, &st.channel_view, st.doc.bounds(), 1, false, st.active_layer).unwrap();
+ assert_eq!(image.pixels, expected, "quick_mask={quick_mask}");
+ delta.clear();
+ }
+ }
+
/// A CPU-only app must be able to generate the actual rotation preview without a
/// GPU adapter; checking the result also verifies Preview off and document integrity.
#[test]
diff --git a/crates/ui-egui/src/channel_view.rs b/crates/ui-egui/src/channel_view.rs
index e4642d946..d7a8b190f 100644
--- a/crates/ui-egui/src/channel_view.rs
+++ b/crates/ui-egui/src/channel_view.rs
@@ -222,7 +222,7 @@ pub fn ensure(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize) -> Optio
// Mask and channel views are drawn over the canvas: show the same live document,
// otherwise an opaque grayscale mask hides the stroke until it is committed (#2078).
// The plain-composite path above needs no preview work.
- let (doc, preview_key) = crate::canvas::display_doc(app, idx);
+ let (doc, preview_key) = crate::canvas::filter_channel_preview(app, idx, ctx).unwrap_or_else(|| crate::canvas::display_doc(app, idx));
// Interface ▸ Show Channels in Color tints single colour channel views on the canvas too,
// not just the panel thumbnails (#2385). The view key carries the flag, so toggling it
// rebuilds the texture.
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 73f3357a8..7d36f2975 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -593,6 +593,7 @@ mod tests {
revision: st.revision,
dialog: id,
active: st.active_layer,
+ target: st.channel_view.target,
command: "filter.blur.gaussianBlur".into(),
params: serde_json::json!({"radius": 4.0}),
k: 1,
diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rs
index 29fc436e0..8f588fbc9 100644
--- a/crates/ui-egui/src/filter_dialog.rs
+++ b/crates/ui-egui/src/filter_dialog.rs
@@ -745,6 +745,19 @@ pub fn preview_document_with(
params: &Value,
k: u32,
cancel: Option<&photocraft_engine::jobs::JobCtx>,
+) -> Option<Document> {
+ preview_document_for_target(doc, active, command, params, k, cancel, photocraft_engine::channel_cmds::ChannelTarget::Composite)
+}
+
+/// Run the preview with the same pixel target as the final command, including individual channels.
+pub(crate) fn preview_document_for_target(
+ doc: &Document,
+ active: Option<photocraft_doc::LayerId>,
+ command: &str,
+ params: &Value,
+ k: u32,
+ cancel: Option<&photocraft_engine::jobs::JobCtx>,
+ target: photocraft_engine::channel_cmds::ChannelTarget,
) -> Option<Document> {
if command == crate::select_mask_view::COMMAND {
return crate::select_mask_view::preview_document(doc, active, params, k, cancel);
@@ -759,6 +772,7 @@ pub fn preview_document_with(
if let Some(id) = active {
s.select_layer(id).ok()?;
}
+ s.active_mut()?.channel_view.target = target;
let mut p = params.clone();
if run_k > 1
&& let Some(o) = p.as_object_mut()
@@ -802,6 +816,7 @@ pub struct FilterPreviewKey {
pub revision: u64,
pub dialog: u64,
pub active: Option<photocraft_doc::LayerId>,
+ pub target: photocraft_engine::channel_cmds::ChannelTarget,
pub command: String,
pub params: Value,
pub k: u32,
diff --git a/crates/ui-egui/src/filter_preview_ui.rs b/crates/ui-egui/src/filter_preview_ui.rs
index bf2cb47b5..f2b8f8956 100644
--- a/crates/ui-egui/src/filter_preview_ui.rs
+++ b/crates/ui-egui/src/filter_preview_ui.rs
@@ -54,6 +54,12 @@ pub(crate) fn window(app: &PhotocraftApp, dialog: u64, ui: &mut egui::Ui, f: &mu
let t = Tokens::get(ui.ctx());
let cache_id = egui::Id::new(("filter-preview-ui", dialog));
let mut cache: Cache = ui.ctx().data_mut(|d| std::mem::take(d.get_temp_mut_or_default::<Cache>(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);
+ if cache.view.as_ref() != Some(&view) {
+ cache = Cache { view: Some(view), ..Default::default() };
+ }
// Unfiltered proxy: built once per document revision and factor (cheap at the proxy factor).
let orig_key = TexKey::Original(doc_id, revision, base_k);
@@ -201,18 +207,18 @@ fn document_size(proxy: [u32; 2], k: u32) -> Vec2 {
/// A composite as monitor pixels, matching the canvas (`canvas::display_image`).
fn upload(ctx: &egui::Context, app: &PhotocraftApp, name: &str, doc: &Document) -> egui::TextureHandle {
- // Never exceed what the GPU accepts (egui panics on an oversized texture): with low-resolution
- // previews off the proxy is the full document. The view maps through UV fractions, so a reduced
- // texture still lines up.
- let k = texture_factor(doc.size.width, doc.size.height, ctx.input(|i| i.max_texture_side));
- let reduced;
- let doc = if k > 1 {
- reduced = crate::proxy::proxy_document(doc, k);
- &reduced
- } else {
- doc
- };
- let buf = photocraft_compose::flatten(doc);
+ // Reduce only the display texture when a full-resolution result exceeds the device limit.
+ // The cached document and the window's document-pixel zoom coordinates stay at full size.
+ let factor = texture_factor(doc.size.width, doc.size.height, ctx.input(|i| i.max_texture_side));
+ let (width, height) = (doc.size.width.div_ceil(factor), doc.size.height.div_ceil(factor));
+ if let Some(st) = app.session.active()
+ && let Some(pixels) =
+ crate::channel_view::render(doc, &st.channel_view, doc.bounds(), factor, app.session.prefs().interface.show_channels_in_color, st.active_layer)
+ {
+ let image = egui::ColorImage::new([width as usize, height as usize], pixels);
+ return ctx.load_texture(name, image, egui::TextureOptions::LINEAR);
+ }
+ let buf = if factor == 1 { photocraft_compose::flatten(doc) } else { photocraft_compose::render_reduced(doc, width, height) };
let (display, _) = crate::canvas::canvas_display(app, doc, None);
let img = crate::canvas::display_image(display.as_deref(), &buf);
ctx.load_texture(name, img, egui::TextureOptions::LINEAR)
@@ -244,12 +250,111 @@ struct CachedTex {
struct Cache {
filtered: Option<CachedTex>,
original: Option<CachedTex>,
+ view: Option<(photocraft_engine::channel_cmds::ChannelView, bool, Option<photocraft_doc::LayerId>)>,
}
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn full_resolution_preview_textures_respect_the_device_limit() {
+ let ctx = egui::Context::default();
+ let limit = ctx.input(|i| i.max_texture_side) as u32;
+ let width = limit + 2;
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": width, "height": 2})).unwrap();
+ for alpha in [false, true] {
+ if alpha {
+ app.run("channel.new", json!({"name": "Alpha", "fill": "black"})).unwrap();
+ app.session
+ .edit("Fixture", |doc, _| {
+ doc.channels[0].surface.fill_rect(photocraft_geom::Rect::new(0, 0, (width / 2) as i32, 2), &[1.0]);
+ Ok(())
+ })
+ .unwrap();
+ }
+ let doc = &app.session.active().unwrap().doc;
+ let texture = upload(&ctx, &app, "full-resolution-preview", doc);
+ let mut delta = ctx.tex_manager().write().take_delta();
+ let egui::ImageData::Color(image) = &delta.set.get(&texture.id()).unwrap()[0].image;
+ let pixels = image.pixels.clone();
+ delta.clear();
+ assert_eq!(texture.size(), [width.div_ceil(2) as usize, 1]);
+ assert!(texture.size().into_iter().all(|side| side <= limit as usize));
+ assert_eq!(doc.size.width, width, "display reduction must not resize the filter result");
+ assert_eq!(pixels[0], Color32::WHITE);
+ assert_eq!(*pixels.last().unwrap(), if alpha { Color32::BLACK } else { Color32::WHITE });
+ }
+ }
+
+ #[test]
+ fn uploaded_preview_shows_the_filtered_alpha_at_every_depth_and_proxy_scale() {
+ use photocraft_engine::channel_cmds::ChannelTarget;
+ for depth in [8, 16, 32] {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 16, "height": 16, "depth": depth})).unwrap();
+ app.run("channel.new", json!({"name": "Alpha", "fill": "black"})).unwrap();
+ app.session
+ .edit("Fixture", |doc, _| {
+ doc.channels[0].surface.fill_rect(photocraft_geom::Rect::new(0, 0, 8, 16), &[1.0]);
+ Ok(())
+ })
+ .unwrap();
+ let st = app.session.active().unwrap();
+ for k in [1, 2, 4] {
+ let preview = crate::filter_dialog::preview_document_for_target(
+ &st.doc,
+ st.active_layer,
+ "filter.blur.gaussianBlur",
+ &json!({"radius": 2.0}),
+ k,
+ None,
+ ChannelTarget::Alpha(0),
+ )
+ .unwrap();
+ let ctx = egui::Context::default();
+ let texture = upload(&ctx, &app, "alpha-preview", &preview);
+ let mut delta = ctx.tex_manager().write().take_delta();
+ let egui::ImageData::Color(image) = &delta.set.get(&texture.id()).unwrap()[0].image;
+ let pixels = image.pixels.clone();
+ delta.clear();
+ let expected = crate::channel_view::render(&preview, &st.channel_view, preview.bounds(), 1, false, st.active_layer).unwrap();
+ assert_eq!(pixels, expected, "depth {depth}, factor {k}");
+ assert_ne!(pixels[0], pixels[pixels.len() - 1], "the alpha edge is visible, not the white RGB layer");
+ assert!(pixels.iter().any(|p| p.r() > 0 && p.r() < 255), "the blurred edge is visible");
+ }
+ }
+ }
+
+ #[test]
+ fn original_texture_refreshes_when_the_channel_view_changes_without_an_edit() {
+ use photocraft_engine::channel_cmds::ChannelTarget;
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 16, "height": 16})).unwrap();
+ app.run("channel.new", json!({"name": "White", "fill": "white"})).unwrap();
+ app.run("channel.new", json!({"name": "Black", "fill": "black"})).unwrap();
+ app.session.active_mut().unwrap().channel_view.target = ChannelTarget::Alpha(0);
+ let revision = app.session.active().unwrap().revision;
+ let id = crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap();
+ let mut fields = app.ui.dialogs.last().unwrap().fields.clone();
+ let ctx = egui::Context::default();
+ let cache_id = egui::Id::new(("filter-preview-ui", id));
+ ctx.run_ui(Default::default(), |ui| window(&app, id, ui, &mut fields)).textures_delta.clear();
+ let before = ctx.data(|d| d.get_temp::<Cache>(cache_id).unwrap().original.unwrap().tex.id());
+ app.session.active_mut().unwrap().channel_view.target = ChannelTarget::Alpha(1);
+ assert_eq!(app.session.active().unwrap().revision, revision);
+ let mut output = ctx.run_ui(Default::default(), |ui| window(&app, id, ui, &mut fields));
+ let after = ctx.data(|d| d.get_temp::<Cache>(cache_id).unwrap().original.unwrap().tex.id());
+ let pixels = output.textures_delta.set.get(&after).map(|delta| {
+ let egui::ImageData::Color(image) = &delta[0].image;
+ image.pixels.clone()
+ });
+ output.textures_delta.clear();
+ assert_ne!(before, after, "press-and-hold must not reuse the old channel");
+ assert!(pixels.unwrap().iter().all(|p| *p == Color32::BLACK));
+ }
+
#[test]
fn zoom_steps_walk_the_levels_and_stay_in_bounds() {
assert_eq!(step_zoom(1.0, true), 2.0);
diff --git a/crates/ui-egui/src/filter_preview_worker.rs b/crates/ui-egui/src/filter_preview_worker.rs
index 2704f8a6a..48f29400f 100644
--- a/crates/ui-egui/src/filter_preview_worker.rs
+++ b/crates/ui-egui/src/filter_preview_worker.rs
@@ -116,6 +116,7 @@ mod tests {
revision,
dialog,
active: None,
+ target: Default::default(),
command: "image.mode.indexedColor".into(),
params: json!({"colors": colors}),
k: 1,