PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Smart Filters: document the functions and tests the PR adds
abc2cb79793acefe60
diff --git a/crates/engine/src/fx_view_cmds.rs b/crates/engine/src/fx_view_cmds.rsindex 0d68230ba..76bbc781e 100644--- a/crates/engine/src/fx_view_cmds.rs+++ b/crates/engine/src/fx_view_cmds.rs@@ -19,6 +19,7 @@ fn has_effects(s: &Session) -> std::result::Result<(), String> {if d.doc.walk().iter().any(|(_, _, l)| has_children(l)) { Ok(()) } else { Err("no layer has effects or smart filters".into()) }}+/// Whether the layer has a list to disclose: effects, or Smart Filters on a Smart Object.fn has_children(l: &Layer) -> bool {!l.effects.items.is_empty() || matches!(&l.content, LayerContent::Smart(sm) if !sm.smart_filters.is_empty())}@@ -96,6 +97,7 @@ mod tests {!s.active().unwrap().fx_collapsed.contains(&LayerId(id))}+ /// Smart Filters hide and show with the layer's effects, as view state: no document edit, revision or history step.#[test]fn smart_filters_share_the_effects_disclosure_without_an_edit() {let (mut s, a, b) = session();diff --git a/crates/engine/src/smart_cmds/tests.rs b/crates/engine/src/smart_cmds/tests.rsindex b7a282698..3666a4818 100644--- a/crates/engine/src/smart_cmds/tests.rs+++ b/crates/engine/src/smart_cmds/tests.rs@@ -7,6 +7,7 @@ const DEPTHS: [u64; 3] = [8, 16, 32];const W: i32 = 64;const H: i32 = 48;+/// A partial filter strength keeps the source alpha and interpolates the filtered coverage, at every sample depth.#[test]fn filter_strength_preserves_alpha_and_interpolates_changed_coverage() {for sample in photocraft_color::SampleType::ALL {@@ -42,6 +43,7 @@ fn filter_strength_preserves_alpha_and_interpolates_changed_coverage() {}}+/// Blending a filter result in Screen, Multiply or Luminosity keeps source-over coverage where the filter changed alpha.#[test]fn non_normal_coverage_changes_retain_source_over_semantics() {for sample in photocraft_color::SampleType::ALL {diff --git a/crates/engine/tests/photoshop_oracles.rs b/crates/engine/tests/photoshop_oracles.rsindex e07b451ef..1b3e37d3e 100644--- a/crates/engine/tests/photoshop_oracles.rs+++ b/crates/engine/tests/photoshop_oracles.rs@@ -80,6 +80,7 @@ fn rerender(doc: &mut Document) -> Result<usize, String> {Ok(n)}+/// Re-rendering Photoshop's Screen/Motion Blur oracle matches its merged composite, so the result retains the input's coverage.#[test]fn screen_motion_blur_retains_input_coverage() {let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/photoshop/smart-filters/sf-blend-screen-100.psd");diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rsindex 4ba1774b5..74d8bd9de 100644--- a/crates/ui-egui/src/filter_dialog.rs+++ b/crates/ui-egui/src/filter_dialog.rs@@ -953,6 +953,7 @@ pub(crate) fn preview_document_for_target(s.active().map(|d| crate::proxy::proxy_document(&d.doc, reduce_k))}+/// Whether `command` is a Smart Filter edit (its parameters or its blending) rather than a filter run on its own.fn is_smart_edit(command: &str) -> bool {matches!(command, "layer.smartFilter.setParams" | "layer.smartFilter.blendingOptions")}@@ -975,6 +976,7 @@ pub(crate) fn smart_preview_factor(doc: &Document, command: &str, params: &Valuefactor}+/// Scale the pixel-sized parameters of `command` down by the preview proxy factor `k`, keeping each above its minimum and negative lengths negative.fn scale_preview_params(command: &str, params: &mut Value, k: u32) {if k > 1&& let Some(o) = params.as_object_mut()diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 6f0e11f7c..584d0928d 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -2334,6 +2334,7 @@ impl PhotocraftApp {self.mask_thumb_kind(ctx, doc, id, mask, mask_thumbs_ui::THUMB_MASK)}+ /// The thumbnail of `mask` under cache `kind`, re-rendered only when the mask's pixels or the document width change; Smart Filter and layer masks are cached apart.pub(crate) fn mask_thumb_kind(&mut self,ctx: &egui::Context,diff --git a/crates/ui-egui/src/smart_filter_dialog.rs b/crates/ui-egui/src/smart_filter_dialog.rsindex d510ed74c..cf184c567 100644--- a/crates/ui-egui/src/smart_filter_dialog.rs+++ b/crates/ui-egui/src/smart_filter_dialog.rs@@ -20,6 +20,7 @@ pub(crate) struct Targets {}impl Targets {+ /// Remember a weak handle to `doc` and return the opaque token that stands for it in a dialog's target.fn capture(&mut self, doc: &Arc<Document>) -> Result<u64, String> {self.next = self.next.checked_add(1).ok_or("Smart Filter target counter exhausted")?;self.snapshots.retain(|(_, doc)| doc.strong_count() > 0);@@ -31,11 +32,13 @@ impl Targets {Ok(self.next)}+ /// Whether `token` was captured from this very document allocation, not just one with the same id.fn matches(&self, token: u64, doc: &Arc<Document>) -> bool {self.snapshots.iter().find(|(id, _)| *id == token).and_then(|(_, doc)| doc.upgrade()).is_some_and(|old| Arc::ptr_eq(&old, doc))}}+/// Identify the Smart Filter at `layer`/`index` (document, revision, filter) so a stale dialog can be told apart from a current one.fn snapshot(app: &PhotocraftApp, layer: LayerId, index: usize) -> Result<Value, String> {let st = app.session.active().ok_or("no document open")?;if app.session.job_on(st.doc.id).is_some() {@@ -49,6 +52,7 @@ fn snapshot(app: &PhotocraftApp, layer: LayerId, index: usize) -> Result<Value,Ok(json!({"doc": st.doc.id.0, "revision": st.revision, "layer": layer.0, "index": index, "filter": filter}))}+/// The `__smartFilter` dialog field: the filter's snapshot plus a guard token for the document it was taken from.pub(crate) fn target(app: &mut PhotocraftApp, layer: LayerId, index: usize) -> Result<Value, String> {let mut target = snapshot(app, layer, index)?;let doc = &app.session.active().ok_or("no document open")?.doc;@@ -76,6 +80,7 @@ pub(crate) fn validate_target(app: &PhotocraftApp, target: &Value) -> Result<(LaOk((layer, index))}+/// Open the Blending Options dialog for one Smart Filter, starting from its recorded mode and opacity (shown as a percentage).pub fn open(app: &mut PhotocraftApp, layer: LayerId, index: usize) -> Result<u64, String> {let target = self::target(app, layer, index)?;let st = app.session.active().ok_or("no document open")?;@@ -97,10 +102,12 @@ pub fn open(app: &mut PhotocraftApp, layer: LayerId, index: usize) -> Result<u64Ok(app.ui.open_dialog(DialogKind::Command, fields))}+/// Whether `fields` belong to this Blending Options dialog rather than another Smart Filter editor.pub fn owns(fields: &Map<String, Value>) -> bool {fields.get("__command").and_then(Value::as_str) == Some(COMMAND) && fields.contains_key(TARGET)}+/// The dialog title, naming the filter being edited.pub(crate) fn title(fields: &Map<String, Value>) -> String {crate::i18n::fmt(tl!("Blending Options ({filter})"), &[("filter", fields.get("__filterName").and_then(Value::as_str).unwrap_or_default())])}@@ -116,6 +123,7 @@ fn blend_params(fields: &Map<String, Value>) -> Result<Value, String> {Ok(json!({"blend": blend, "opacity": opacity / 100.0}))}+/// The command a confirmed Smart Filter dialog runs on the validated target: its blending, or `layer.smartFilter.setParams` for a parameter editor.pub(crate) fn edit_command(app: &PhotocraftApp, fields: &Map<String, Value>) -> Result<(String, Value), String> {let (layer, index) = validate_target(app, fields.get(TARGET).ok_or("no Smart Filter target")?)?;if owns(fields) {@@ -135,6 +143,7 @@ fn mode_note(blend: Option<&str>) -> Option<&'static str> {(blend == Some(BlendMode::Dissolve.label())).then(|| tl!("Dissolve is approximated: it blends without Photoshop's dither."))}+/// The Blending Options form: Mode (with the Dissolve note), Opacity, Preview and the result viewport.pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map<String, Value>) {ui.horizontal(|ui| {ui.label(tl!("Mode"));@@ -168,6 +177,7 @@ struct ViewImage {texture: egui::TextureHandle,}+/// Show the document as the dialog will leave it (the live preview, or the unchanged document while Preview is off) as a fixed-size thumbnail.fn viewport(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map<String, Value>, preview: bool) {let Some(st) = app.session.active() else { return };let doc = if preview {diff --git a/crates/ui-egui/src/smart_filter_dialog/tests.rs b/crates/ui-egui/src/smart_filter_dialog/tests.rsindex 6e1ce5708..b3fb099d6 100644--- a/crates/ui-egui/src/smart_filter_dialog/tests.rs+++ b/crates/ui-egui/src/smart_filter_dialog/tests.rs@@ -1,6 +1,7 @@use super::*;use photocraft_doc::{SmartFilter, SmartObject};+/// A document reopened with the same id is a different allocation, so a dialog opened on the old one cannot edit it.#[test]fn a_same_id_reopened_document_rejects_the_previous_dialog() {let (mut app, layer) = app(8, "rgb");@@ -18,6 +19,7 @@ fn a_same_id_reopened_document_rejects_the_previous_dialog() {assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc));}+/// An 8×8 image still gets the full-height preview area instead of collapsing it.#[test]fn tiny_images_keep_a_usable_preview_viewport() {let (mut app, layer) = app(8, "rgb");@@ -37,7 +39,9 @@ fn tiny_images_keep_a_usable_preview_viewport() {.clear();}+/// Run `body` for one frame and return every string it painted.fn painted_text(app: &mut PhotocraftApp, fields: &mut Map<String, Value>) -> Vec<String> {+ /// Gather the text of `shape`, descending into nested shape groups.fn collect(shape: &egui::Shape, out: &mut Vec<String>) {match shape {egui::Shape::Text(text) => out.push(text.galley.job.text.clone()),@@ -55,6 +59,7 @@ fn painted_text(app: &mut PhotocraftApp, fields: &mut Map<String, Value>) -> Vecpainted}+/// Of all the blend modes, only Dissolve shows the approximation note beside the Mode control.#[test]fn only_dissolve_shows_the_approximation_note_near_the_mode_control() {let note = "Dissolve is approximated: it blends without Photoshop's dither.";@@ -72,6 +77,7 @@ fn only_dissolve_shows_the_approximation_note_near_the_mode_control() {assert_eq!(mode_note(Some("Dissolve")), Some(note));}+/// A document with one Smart Object holding Box Blur and Smart Sharpen, wrapped in an app that renders on the calling thread.pub(crate) fn app(depth: u32, mode: &str) -> (PhotocraftApp, LayerId) {let mut s = photocraft_engine::Session::new();s.execute("file.new", json!({"width": 64, "height": 48, "depth": depth, "mode": mode})).unwrap();@@ -89,15 +95,18 @@ pub(crate) fn app(depth: u32, mode: &str) -> (PhotocraftApp, LayerId) {(app, layer)}+/// The Smart Object content of `layer` in the active document.pub(crate) fn smart(app: &PhotocraftApp, layer: LayerId) -> &SmartObject {let LayerContent::Smart(sm) = &app.session.active().unwrap().doc.layer(layer).unwrap().content else { panic!("smart") };sm}+/// A copy of the Smart Object's filters, for comparing before and after an edit.fn filters(app: &PhotocraftApp, layer: LayerId) -> Vec<SmartFilter> {smart(app, layer).smart_filters.clone()}+/// Blending edits one filter in a single history step, opacity is entered as a percentage, and undo/redo restore it.#[test]fn blending_edits_one_filter_with_percent_opacity_and_undo_redo() {for depth in [8, 16, 32] {@@ -142,6 +151,7 @@ fn blending_edits_one_filter_with_percent_opacity_and_undo_redo() {}}+/// The preview, switching it off and on, and Cancel never change the document or its history.#[test]fn preview_toggle_and_cancel_leave_document_and_history_untouched() {let (mut app, layer) = app(8, "rgb");@@ -164,6 +174,7 @@ fn preview_toggle_and_cancel_leave_document_and_history_untouched() {assert_eq!(app.session.active().unwrap().history.past_len(), steps);}+/// A dialog whose document or filter has since changed, or been switched away from, refuses to confirm.#[test]fn stale_filter_dialogs_cannot_edit_a_switched_or_changed_target() {for command in ["file.new", "edit.undo", "layer.smartFilter.delete", "layer.smartFilter.move"] {@@ -181,6 +192,7 @@ fn stale_filter_dialogs_cannot_edit_a_switched_or_changed_target() {}}+/// A reduced-size preview scales the filters' pixel parameters and the shared mask, and still contains the same number of filters.#[test]fn reduced_preview_scales_placement_stack_and_mask_without_adding_filters() {let (mut app, layer) = app(16, "rgb");@@ -206,6 +218,7 @@ fn reduced_preview_scales_placement_stack_and_mask_without_adding_filters() {assert!(Arc::ptr_eq(&original, &app.session.active().unwrap().doc));}+/// An edited blend and an Invert recorded earlier survive a save and reload of the native format.#[test]fn native_save_preserves_edited_blending_and_existing_invert() {let (mut app, layer) = app(8, "rgb");@@ -221,6 +234,7 @@ fn native_save_preserves_edited_blending_and_existing_invert() {assert_eq!(serde_json::to_value(&sm.smart_filters).unwrap(), serde_json::to_value(filters(&app, layer)).unwrap());}+/// An opacity outside 0–100% or not a number fails the dialog and leaves the document alone.#[test]fn invalid_opacity_fails_without_an_edit() {let (mut app, layer) = app(8, "rgb");@@ -233,6 +247,7 @@ fn invalid_opacity_fails_without_an_edit() {}}+/// Blending edits the filter the dialog opened on, whatever layer is selected and whether or not a layer mask is targeted.#[test]fn blending_does_not_follow_layer_selection_or_the_layer_mask_target() {let (mut app, layer) = app(8, "rgb");@@ -255,6 +270,7 @@ fn blending_does_not_follow_layer_selection_or_the_layer_mask_target() {);}+/// Blending an Invert smart filter keeps the translucent pixels' alpha at 8, 16 and 32 bits.#[test]fn invert_blending_keeps_transparency_at_every_depth() {for depth in [8, 16, 32] {diff --git a/crates/ui-egui/src/smart_ui.rs b/crates/ui-egui/src/smart_ui.rsindex 2cd61a300..1d8e6d68c 100644--- a/crates/ui-egui/src/smart_ui.rs+++ b/crates/ui-egui/src/smart_ui.rs@@ -83,6 +83,7 @@ pub fn paint_badge(painter: &egui::Painter, center: egui::Pos2, color: Color32)}}+/// Paint the Smart Filters header and one row per filter of Smart Object `l` (top filter first), with their drag, drop and click handling; actions go to `actions`.pub fn filter_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, doc: &Document, l: &Layer, depth: usize, actions: &mut Vec<(String, Value)>) {let LayerContent::Smart(sm) = &l.content else { return };if sm.smart_filters.is_empty() {diff --git a/crates/ui-egui/src/smart_ui/editor_tests.rs b/crates/ui-egui/src/smart_ui/editor_tests.rsindex c5814b8d1..6e0b9d14f 100644--- a/crates/ui-egui/src/smart_ui/editor_tests.rs+++ b/crates/ui-egui/src/smart_ui/editor_tests.rs@@ -7,6 +7,7 @@ use crate::{smart_filter_dialog::tests::{app, smart},};+/// The app with a recorded Smart Object, in a `width`-point dock and the given theme, ready to click.fn harness(width: f32, scale: f32, theme: crate::theme::ThemeKind) -> Harness<'static, PhotocraftApp> {let (app, _) = app(8, "rgb");let mut h =@@ -24,6 +25,7 @@ fn harness(width: f32, scale: f32, theme: crate::theme::ThemeKind) -> Harness<'sh}+/// Click `at` with the primary button, hovering first so the row reacts.fn click(h: &mut Harness<'_, PhotocraftApp>, at: egui::Pos2) {h.hover_at(at);h.run_steps(1);@@ -33,6 +35,7 @@ fn click(h: &mut Harness<'_, PhotocraftApp>, at: egui::Pos2) {h.run_steps(2);}+/// A filter row's name and blend icon are separate double-click targets, side by side without overlap, in every theme and dock width.#[test]fn names_and_blend_icons_have_separate_double_click_targets_and_no_overlap() {for theme in crate::theme::ThemeKind::ALL {@@ -64,6 +67,7 @@ fn names_and_blend_icons_have_separate_double_click_targets_and_no_overlap() {}}+/// The effects disclosure hides the effects and Smart Filters stacks together, as a view change only.#[test]fn disclosure_hides_both_stacks_without_changing_pixels_history_or_selection() {let mut h = harness(290.0, 1.5, Default::default());@@ -89,6 +93,7 @@ fn disclosure_hides_both_stacks_without_changing_pixels_history_or_selection() {assert!(h.query_by_label("Blending Options (Box Blur)").is_some());}+/// An adjustment on a Smart Object reopens its editor with the stored values and OK updates it in one step; Invert has no editor.#[test]fn adjustment_editor_reopens_stored_parameters_and_updates_instead_of_appending() {let (mut app, layer) = app(8, "rgb");@@ -117,6 +122,7 @@ fn adjustment_editor_reopens_stored_parameters_and_updates_instead_of_appending(assert!(app.ui.dialogs.is_empty(), "Invert has no parameter editor");}+/// The Smart Filters mask and the layer mask of one layer are cached as separate thumbnails.#[test]fn smart_and_layer_masks_have_separate_thumbnail_cache_entries() {let (mut app, layer) = app(8, "rgb");@@ -132,6 +138,7 @@ fn smart_and_layer_masks_have_separate_thumbnail_cache_entries() {assert_eq!(first, app.mask_thumb(&ctx, &doc, layer, mask));}+/// ⌘I on a Smart Object adds the ordinary Invert as a smart filter, and undo/redo leave the source contents alone.#[test]fn ctrl_i_uses_existing_invert_command_and_undo_redo_keep_the_source() {let mut h = harness(290.0, 1.0, Default::default());