From 2c9d18b6dca06762dff9e7283918b32c8506f587 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 12:13:10 -0800 Subject: [PATCH] Effect Gallery: preview, filter folders and settings side by side The gallery showed a small preview above a categories list and a single long column of filters, so the dialog grew tall and narrow. The dialog now lays out three columns: the preview at the start, the category folders with their filter thumbnails in the middle, and the filter settings with the effect layers at the end. The preview is a side menu's width (`LeastWidth::SideMenu`) and is drawn one texel to a device pixel, so it keeps its size in points on high-density screens; the filters draw at the same document size at every density. --- crates/ui-egui/src/dialogs/effect_gallery.rs | 159 ++++++++++++++++--- 1 file changed, 136 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index 6965493c9c..c1faac4a58 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -14,15 +14,14 @@ use std::sync::{Arc, Weak}; use craft::imaging::ui::filter_gallery::{ EffectChange, EffectLayer, EffectParameters, EffectStack, FilterCatalog, FilterCategory, FilterGallerySession, FilterIndex, FilterTree, - FilterTreeLayout, GalleryFilter, GalleryThumb, LayerId, SessionField, + GalleryFilter, GalleryThumb, LayerId, SessionField, }; use craft::theme::variant::Tone; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Props as _, Sampler as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, LeastWidth, Props as _, Sampler as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, HoldsOk, StackDialog, dialog_id}; use craft::ui::display::{Picture, PictureSize}; use craft::ui::layout_components::{Row, Stack}; -use craft::ui::list::{ThumbAspect, ThumbSize}; use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue}; use craft::ui::primitives::textures::{Revision, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails}; @@ -46,9 +45,28 @@ use crate::file_asks::Owner; /// Thumbnail of one filter, in pixels at most. The drawing is original; the filter is this app's. const THUMB: usize = 36; -/// Sample image dimensions before the dialog scales the image to its display size. -const PREVIEW_W: usize = 120; -const PREVIEW_H: usize = 84; +/// The preview's height over its width. +const PREVIEW_ASPECT: (usize, usize) = (10, 7); + +/// The preview's raster: `width` points wide at the screen's density, one device pixel to a texel, with `px` +/// document points to a pixel so the filters draw the same at every density. +#[derive(Clone, Copy, Debug, PartialEq)] +struct PreviewSample { + width: usize, + height: usize, + px: f64, +} + +impl PreviewSample { + /// A sample `points` wide at `pixels_per_point`; a degenerate width or density gives one pixel. + fn new(points: f32, pixels_per_point: f32) -> Self { + let ppp = if pixels_per_point.is_finite() && pixels_per_point > 0.0 { pixels_per_point } else { 1.0 }; + let pixels = f64::from(points * ppp); + let width = if pixels.is_finite() { pixels.round().max(1.0) as usize } else { 1 }; + let (wide, high) = PREVIEW_ASPECT; + PreviewSample { width, height: (width * high / wide).max(1), px: 1.0 / f64::from(ppp) } + } +} /// The command the preview and OK run: the whole stack as one undo step. const COMMAND: &str = "command.batch"; @@ -435,9 +453,11 @@ impl StackDialog for EffectGalleryDialog { let refusal = held.refusal().map(|(reason, _)| reason.clone()); let current = (*selected).min(session.effects.len().saturating_sub(1)); let visible = entries_of(&session.effects, index, true); + let sample = PreviewSample::new(LeastWidth::SideMenu.points(Env::of(ui).tokens.tokens()), ui.ctx().pixels_per_point()); let key = { let mut hasher = DefaultHasher::new(); serde_json::to_string(&stack_batch_params(&visible)).unwrap_or_default().hash(&mut hasher); + (sample.width, sample.height).hash(&mut hasher); hasher.finish() }; let thumbs = Thumbnails::::in_context(ui.ctx(), "effectGallery.thumbs", ThumbnailOptions::new()); @@ -465,15 +485,17 @@ impl StackDialog for EffectGalleryDialog { cx.keep_view_open(canvas); } let Some(layer) = effects.get(current) else { return }; - let image = || color_image(&preview_rgba(&visible, PREVIEW_W, PREVIEW_H), PREVIEW_W, PREVIEW_H); + let image = || color_image(&preview_rgba(&visible, sample.width, sample.height, sample.px), sample.width, sample.height); + // The preview at the start, the category folders in the middle and the settings with the effect layers at + // the end, as the Filter Gallery page lays them out. Stack::new().show(ui, |ui, _| { - Picture::new(tl!("Preview"), key, &image).aspect(ThumbAspect::new(10, 7)).extent(PictureSize::Sample(ThumbSize::Large)).show(ui); Row::new().show(ui, |ui, _| { - let tree = FilterTree::new(index, &layer.filter, &thumbs, &Thumbs).layout(FilterTreeLayout::Lists).show(ui); + Picture::new(tl!("Preview"), key, &image).extent(PictureSize::DevicePixels).show(ui); + let tree = FilterTree::new(index, &layer.filter, &thumbs, &Thumbs).show(ui); if let Some(filter) = tree.picked { changes.push(EffectChange::set_filter(current, filter)); } - Stack::new().show(ui, |ui, _| { + Stack::new().least_width(LeastWidth::SideMenu).show(ui, |ui, _| { let params = EffectParameters::new(current, layer, index).show(ui); changes.extend(params.change); if params.path.is_some() { @@ -574,12 +596,12 @@ fn effect_label(id: &str) -> String { crate::i18n::effect_name(crate::i18n::current(), id).unwrap_or_else(|| id.to_string()) } -/// Where the preview rasters sit: one document point per pixel, origin at the top-left. -fn preview_space(w: usize, h: usize) -> PixelSpace { - let (wf, hf) = (w as f64, h as f64); +/// Where the preview rasters sit: `px` document points per pixel, origin at the top-left. +fn preview_space(w: usize, h: usize, px: f64) -> PixelSpace { + let (wf, hf) = (w as f64 * px, h as f64 * px); PixelSpace { - to_doc: Affine::IDENTITY, - px: 1.0, + to_doc: Affine::scale(px), + px, center: Point::new(wf / 2.0, hf / 2.0), size: vectorcraft_geom::Vec2::new(wf, hf), channels: vectorcraft_effects::pixel::Channels::Rgb, @@ -637,9 +659,9 @@ fn sample_drawing(w: usize, h: usize) -> Vec { out } -/// Run one raster filter on a premultiplied RGBA buffer. Leaves it unchanged when `id` -/// is not one of those filters or the buffer is the wrong size. -fn apply_pixel(id: &str, params: &Map, data: &mut [u8], w: usize, h: usize) { +/// Run one raster filter on a premultiplied RGBA buffer of `px` document points to a pixel. Leaves it unchanged when +/// `id` is not one of those filters or the buffer is the wrong size. +fn apply_pixel(id: &str, params: &Map, data: &mut [u8], w: usize, h: usize, px: f64) { let Some(n) = w.checked_mul(h).and_then(|n| n.checked_mul(4)) else { return }; if n != data.len() || w == 0 || h == 0 { return; @@ -648,20 +670,21 @@ fn apply_pixel(id: &str, params: &Map, data: &mut [u8], w: usize, let Some(vectorcraft_effects::RasterFx::Pixel(fx)) = vectorcraft_effects::raster_effects(std::slice::from_ref(&effect)).into_iter().next() else { return; }; - fx.apply(data, w, h, &preview_space(w, h)); + fx.apply(data, w, h, &preview_space(w, h, px)); } +/// A filter's thumbnail: the drawing at one point to a pixel with the filter applied. fn filtered(id: &str, params: &Map, w: usize, h: usize) -> Vec { let mut data = sample_drawing(w, h); - apply_pixel(id, params, &mut data, w, h); + apply_pixel(id, params, &mut data, w, h, 1.0); data } -/// The drawing with `layers` applied in order. -fn preview_rgba(layers: &[StackEntry], w: usize, h: usize) -> Vec { +/// The drawing at `px` document points to a pixel with `layers` applied in order. +fn preview_rgba(layers: &[StackEntry], w: usize, h: usize, px: f64) -> Vec { let mut data = sample_drawing(w, h); for layer in layers { - apply_pixel(&layer.effect, &layer.params, &mut data, w, h); + apply_pixel(&layer.effect, &layer.params, &mut data, w, h, px); } data } @@ -845,6 +868,96 @@ mod tests { assert!(preview_heights.iter().all(|(_, height)| *height >= 64.0), "the preview is an artwork sample: {preview_heights:?}"); } + /// The bounds of the first accessibility node named `label` (and of `role`, when given), in `window` points, at + /// `scale` pixels to a point. + fn bounds(app: &mut VectorcraftApp, window: egui::Rect, scale: f32, label: &str, role: Option) -> Option { + let ctx = app.ui_ctx.clone().unwrap(); + let mut nodes = Vec::new(); + for _ in 0..3 { + ctx.enable_accesskit(); + let mut input = egui::RawInput { screen_rect: Some(window), ..Default::default() }; + input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(scale); + nodes = crate::testing::app_frame(app, &ctx, input).platform_output.accesskit_update.map(|update| update.nodes).unwrap_or_default(); + } + let node = nodes.iter().map(|(_, node)| node).find(|node| { + let named = node.label() == Some(label) + || node.labelled_by().iter().any(|id| nodes.iter().any(|(key, name)| key == id && name.label() == Some(label))); + named && role.is_none_or(|role| node.role() == role) && node.bounds().is_some() + })?; + let b = node.bounds()?; + Some(egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))) + } + + /// The preview stands at the start beside the category folders and the settings, side by side, and is larger + /// than a filter's thumbnail; in a short window the dialog still fits, and at twice the density the preview keeps + /// its size in points. Brazilian Portuguese has the longest labels of the reported layout. + #[test] + fn gallery_layout_puts_preview_folders_and_settings_side_by_side() { + use egui::accesskit::Role; + use egui::{Pos2, Rect, vec2}; + + let cases = [ + ("en", vec2(1280.0, 800.0), 1.0), + ("en", vec2(1280.0, 800.0), 2.0), + ("pt-br", vec2(1280.0, 800.0), 1.0), + ("pt-br", vec2(900.0, 560.0), 1.0), + ]; + let mut widths = Vec::new(); + for (language, size, scale) in cases { + let window = Rect::from_min_size(Pos2::ZERO, size); + let bounds = |app: &mut VectorcraftApp, label: &str, role| bounds(app, window, scale, label, role); + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.session.prefs.interface_language = language.to_owned(); + let lang = app.ui_language(); + let label = |name: &'static str| crate::i18n::tr(lang, name); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + bounds(&mut app, "", None); + app.run("ui.effectGalleryDialog", json!({})).unwrap(); + let at = format!("{language} at {size:?} scale {scale}"); + let gallery = bounds(&mut app, label("Effect Gallery"), Some(Role::Dialog)).expect("the gallery"); + let preview = bounds(&mut app, label("Preview"), Some(Role::Image)).expect("the preview"); + // A filter of the folder that opens with the gallery; the stack's one layer is another filter. + let cutout = crate::i18n::effect_name(lang, "artistic.cutout").unwrap(); + let tile = bounds(&mut app, &cutout, None).expect("the Cutout tile"); + // The settings' Filter select is named by the framework's own words, which this check reads in English. + let filter = bounds(&mut app, "Filter", None); + assert!(filter.is_some() || language != "en", "{at}: the settings' Filter select"); + let ok = bounds(&mut app, label("OK"), Some(Role::Button)).expect("OK"); + assert_eq!(app.ui_ctx.as_ref().unwrap().pixels_per_point(), scale, "{at}: the window's density"); + if language == "en" { + widths.push(preview.width()); + } + eprintln!("{at}: gallery {gallery:?}, preview {preview:?}, tile {tile:?}, filter {filter:?}, OK {ok:?}"); + assert!(window.contains_rect(gallery), "{at}: the gallery fits the window: {gallery:?}"); + assert!(gallery.contains_rect(preview) && gallery.contains_rect(ok), "{at}: the preview and OK are inside the gallery"); + assert!(preview.right() <= tile.left(), "{at}: the folders stand after the preview: {preview:?} {tile:?}"); + assert!(preview.top() < tile.bottom() && tile.top() < preview.bottom(), "{at}: the preview and the folders share a line"); + assert!(preview.width() > 2.0 * tile.width(), "{at}: the preview is larger than a thumbnail: {preview:?} {tile:?}"); + if let Some(filter) = filter { + assert!(tile.right() <= filter.left(), "{at}: the settings stand after the folders: {tile:?} {filter:?}"); + } + } + assert!((widths[0] - widths[1]).abs() <= 1.0, "the preview keeps its size in points at twice the density: {widths:?}"); + } + + /// The preview's raster has a texel per device pixel and draws its filters at document size whatever the + /// density; a density that is not a positive number counts as one pixel to a point. + #[test] + fn preview_sample_follows_the_density() { + use super::PreviewSample; + let one = PreviewSample::new(200.0, 1.0); + let two = PreviewSample::new(200.0, 2.0); + assert_eq!((two.width, two.height), (2 * one.width, 2 * one.height)); + assert_eq!(two.width as f64 * two.px, one.width as f64 * one.px, "the same document width at both densities"); + assert!(one.height < one.width, "the preview is wider than it is high"); + for bad in [0.0, -1.0, f32::NAN, f32::INFINITY] { + assert_eq!(PreviewSample::new(200.0, bad), one, "density {bad}"); + } + let empty = PreviewSample::new(0.0, 1.0); + assert!(empty.width >= 1 && empty.height >= 1, "{empty:?}"); + } + #[test] fn stack_preview_is_one_interaction() { let (mut app, ctx, node) = drawing();