PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Make Smart Filter editors distinct and preserve alpha at partial strength
abc2cbf9f1d823cc14
diff --git a/crates/engine/src/fx_view_cmds.rs b/crates/engine/src/fx_view_cmds.rsindex 03241d840..7c35959df 100644--- a/crates/engine/src/fx_view_cmds.rs+++ b/crates/engine/src/fx_view_cmds.rs@@ -1,8 +1,8 @@-//! Layers panel: showing or hiding a layer's effects list under its row (the triangle beside-//! the fx badge, #144). View state ([`crate::DocState::fx_collapsed`]): no history step, and a+//! Layers panel: showing or hiding a layer's effects and Smart Filters under its row (the+//! shared disclosure triangle). View state ([`crate::DocState::fx_collapsed`]): no history step, and a//! clean document stays clean.-use photocraft_doc::LayerId;+use photocraft_doc::{Layer, LayerContent, LayerId};use serde_json::{Value, json};use crate::commands::CommandSpec;@@ -16,7 +16,11 @@ fn bad(msg: impl Into<String>) -> EngineError {fn has_effects(s: &Session) -> std::result::Result<(), String> {let d = s.active().ok_or("no document open")?;- if d.doc.walk().iter().any(|(_, _, l)| !l.effects.items.is_empty()) { Ok(()) } else { Err("no layer has effects".into()) }+ if d.doc.walk().iter().any(|(_, _, l)| has_children(l)) { Ok(()) } else { Err("no layer has effects or smart filters".into()) }+}++fn has_children(l: &Layer) -> bool {+ !l.effects.items.is_empty() || matches!(&l.content, LayerContent::Smart(sm) if !sm.smart_filters.is_empty())}fn opt_bool(p: &Value, key: &str) -> Result<Option<bool>> {@@ -37,12 +41,12 @@ fn set_expanded(s: &mut Session, p: &Value) -> Result<Value> {None | Some(Value::Null) => Some(st.active_layer.ok_or_else(|| bad("no layer given and no active layer"))?),Some(v) => Some(LayerId(v.as_u64().ok_or_else(|| bad("`layer` must be a layer id"))?)),};- let with_fx: Vec<LayerId> = st.doc.walk().iter().filter(|(_, _, l)| !l.effects.items.is_empty()).map(|(_, _, l)| l.id).collect();+ let with_fx: Vec<LayerId> = st.doc.walk().iter().filter(|(_, _, l)| has_children(l)).map(|(_, _, l)| l.id).collect();let current = match layer {Some(id) => {let l = st.doc.layer(id).ok_or(EngineError::NoLayer(id))?;- if l.effects.items.is_empty() {- return Err(bad(format!("layer {} has no effects", id.0)));+ if !has_children(l) {+ return Err(bad(format!("layer {} has no effects or smart filters", id.0)));}!st.fx_collapsed.contains(&id)}@@ -65,7 +69,7 @@ pub fn specs() -> Vec<CommandSpec> {label: "Expand/Collapse Effects",menu: &[],shortcut: None,- params: r##"{"layer":id?,"expanded":bool?,"all":bool?} (no expanded: toggle; all: every layer with effects; view state, not an undo step)"##,+ params: r##"{"layer":id?,"expanded":bool?,"all":bool?} (no expanded: toggle; all: every layer with effects or smart filters; view state, not an undo step)"##,enabled: has_effects,run: set_expanded,journal: false,@@ -92,6 +96,28 @@ mod tests {!s.active().unwrap().fx_collapsed.contains(&LayerId(id))}+ #[test]+ fn smart_filters_share_the_effects_disclosure_without_an_edit() {+ let (mut s, a, b) = session();+ s.execute("layer.select", json!({"layer": a})).unwrap();+ s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();+ s.execute("image.adjustments.invert", json!({})).unwrap();+ let smart = s.active().unwrap().active_layer.unwrap();+ let doc = s.active().unwrap().doc.clone();+ let revision = s.active().unwrap().revision;+ let steps = s.active().unwrap().history.past_len();+ s.execute(ID, json!({"layer": smart.0, "expanded": false})).unwrap();+ assert!(!open(&s, smart.0));+ assert!(open(&s, b));+ assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc));+ assert_eq!(s.active().unwrap().revision, revision);+ assert_eq!(s.active().unwrap().history.past_len(), steps);+ s.execute(ID, json!({"expanded": false, "all": true})).unwrap();+ assert!(!open(&s, smart.0) && !open(&s, b));+ s.execute(ID, json!({"expanded": true, "all": true})).unwrap();+ assert!(s.active().unwrap().fx_collapsed.is_empty());+ }+#[test]fn toggles_one_layer_or_all_without_history() {let (mut s, a, b) = session();diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rsindex 6e0c04357..d80596a68 100644--- a/crates/engine/src/smart_cmds.rs+++ b/crates/engine/src/smart_cmds.rs@@ -278,8 +278,11 @@ pub fn stack_image(file_name: &str, bytes: &[u8], fmt: PixelFormat, mode: photoc// ---------- rendering -----------/// `top` blended over `base` with `mode` at `opacity` (a smart filter's blending options).+/// Mix a filter's result with its input, without stacking the same pixel coverage twice.fn blend_surfaces(base: &Surface, top: &Surface, mode: BlendMode, opacity: f32) -> Surface {+ if opacity <= 0.0 {+ return base.clone();+ }let fmt = base.format();let area = base.content_bounds().union(&top.content_bounds());let mut out = base.clone();@@ -290,7 +293,25 @@ fn blend_surfaces(base: &Surface, top: &Surface, mode: BlendMode, opacity: f32)let (b, t) = (base.read_region(area), top.read_region(area));let mut o = vec![0.0f32; b.len()];for ((bp, tp), op) in b.chunks_exact(n).zip(t.chunks_exact(n)).zip(o.chunks_exact_mut(n)) {- let rgba = photocraft_color::blend::composite(mode, photocraft_raster::to_rgba(&fmt, bp), photocraft_raster::to_rgba(&fmt, tp), opacity);+ let b = photocraft_raster::to_rgba(&fmt, bp);+ let t = photocraft_raster::to_rgba(&fmt, tp);+ let cb = [b[0], b[1], b[2]];+ let ct = [t[0], t[1], t[2]];+ let color = if fmt.sample == photocraft_color::SampleType::F32 {+ photocraft_color::blend::blend_rgb_hdr(mode, cb, ct)+ } else {+ photocraft_color::blend::blend_rgb(mode, cb, ct)+ };+ // A filter edits this surface, rather than adding a second source-over layer. Mix+ // premultiplied results so alpha-preserving filters keep coverage at every opacity,+ // while filters that actually change coverage (e.g. blur) interpolate it too.+ let a = b[3] + (t[3] - b[3]) * opacity;+ let mut rgba = [0.0, 0.0, 0.0, a];+ if a > 0.0 {+ for c in 0..3 {+ rgba[c] = (cb[c] * b[3] * (1.0 - opacity) + color[c] * t[3] * opacity) / a;+ }+ }photocraft_raster::from_rgba_into(&fmt, rgba, op);}out.write_region(area, &o);diff --git a/crates/engine/src/smart_cmds/tests.rs b/crates/engine/src/smart_cmds/tests.rsindex 2ee54322b..b496e0451 100644--- a/crates/engine/src/smart_cmds/tests.rs+++ b/crates/engine/src/smart_cmds/tests.rs@@ -7,6 +7,41 @@ const DEPTHS: [u64; 3] = [8, 16, 32];const W: i32 = 64;const H: i32 = 48;+#[test]+fn filter_strength_preserves_alpha_and_interpolates_changed_coverage() {+ for sample in photocraft_color::SampleType::ALL {+ let fmt = PixelFormat { mode: photocraft_color::ColorMode::Rgb, sample, alpha: true };+ let mut base = Surface::new(fmt);+ let mut filtered = Surface::new(fmt);+ base.fill_rect(Rect::new(0, 0, 1, 1), &[0.2, 0.4, 0.6, 0.5]);+ filtered.fill_rect(Rect::new(0, 0, 1, 1), &[0.8, 0.6, 0.4, 0.5]);+ let before = base.pixel(0, 0);+ let after = filtered.pixel(0, 0);+ let tolerance = match sample {+ photocraft_color::SampleType::U8 => 1.0 / 255.0,+ photocraft_color::SampleType::U16 => 1.0 / 65535.0,+ photocraft_color::SampleType::F32 => 1e-6,+ };+ for opacity in [0.0, 0.01, 0.5, 1.0] {+ for mode in [BlendMode::Normal, BlendMode::Multiply, BlendMode::Luminosity] {+ let mixed = blend_surfaces(&base, &filtered, mode, opacity).pixel(0, 0);+ assert!((mixed[3] - before[3]).abs() <= tolerance);+ if mode == BlendMode::Normal {+ for c in 0..3 {+ assert!((mixed[c] - (before[c] + (after[c] - before[c]) * opacity)).abs() <= tolerance);+ }+ }+ }+ }+ filtered.fill_rect(Rect::new(0, 0, 1, 1), &[0.8, 0.6, 0.4, 0.0]);+ let mixed = blend_surfaces(&base, &filtered, BlendMode::Normal, 0.5).pixel(0, 0);+ assert!((mixed[3] - before[3] * 0.5).abs() <= tolerance);+ for c in 0..3 {+ assert!((mixed[c] - before[c]).abs() <= tolerance);+ }+ }+}+fn session(depth: u64) -> Session {let mut s = Session::new();s.execute("file.new", json!({"width": W, "height": H, "depth": depth})).unwrap();diff --git a/crates/ui-egui/src/adjust_dialog.rs b/crates/ui-egui/src/adjust_dialog.rsindex a4b831ed2..7c6157f38 100644--- a/crates/ui-egui/src/adjust_dialog.rs+++ b/crates/ui-egui/src/adjust_dialog.rs@@ -176,7 +176,12 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map<String,ui.add_space(4.0);}let mut values = crate::filter_dialog::params_of(fields);- let active = app.session.active().and_then(|s| s.active_layer);+ let active = fields+ .get("__smartFilter")+ .and_then(|f| f.get("layer"))+ .and_then(Value::as_u64)+ .map(photocraft_doc::LayerId)+ .or_else(|| app.session.active().and_then(|s| s.active_layer));let gray = app.session.active().is_some_and(|s| adjust_editors::is_gray(s.doc.mode));let hist = match active {Some(id) if adjust_editors::needs_histogram(&kind) => Some(tone::histograms(app, HistSource::Layer(id), adjust_editors::space_of(&values))),diff --git a/crates/ui-egui/src/adjust_preview.rs b/crates/ui-egui/src/adjust_preview.rsindex d94d58bff..c6aa8fc52 100644--- a/crates/ui-egui/src/adjust_preview.rs+++ b/crates/ui-egui/src/adjust_preview.rs@@ -186,6 +186,9 @@ struct GpuProxy {/// The open adjustment dialog: (kind, params, Preview on).fn dialog(app: &PhotocraftApp) -> Option<(String, Value, bool)> {let d = app.ui.dialogs.iter().find(|d| crate::adjust_dialog::owns(&d.fields))?;+ if d.fields.contains_key("__smartFilter") {+ return None;+ }let kind = d.fields.get("__adjust")?.as_str()?.to_string();let preview = d.fields.get("__preview").and_then(Value::as_bool).unwrap_or(true);Some((kind, crate::filter_dialog::params_of(&d.fields), preview))diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex a1fcda0ad..f5f29af83 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -1373,10 +1373,14 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e}let cmd = d.fields.get("__command")?.as_str()?.to_string();// Previews edit what the command will: a targeted layer mask included (#780).- let params = app.with_mask_target(&cmd, crate::filter_dialog::params_of(&d.fields));+ let (cmd, params) = if d.fields.contains_key("__smartFilter") {+ crate::smart_filter_dialog::edit_command(app, &d.fields).ok()?+ } else {+ (cmd.clone(), app.with_mask_target(&cmd, crate::filter_dialog::params_of(&d.fields)))+ };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, ¶ms, crate::proxy::preview_factor(&st.doc, crate::proxy::reduced_previews(app)));+ let k = crate::filter_dialog::smart_preview_factor(&st.doc, &cmd, ¶ms, 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 key = request.doc.0 ^ (1u64 << 61);diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex c4a700aef..b1c3d678b 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -226,6 +226,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {DialogKind::Command if fields.contains_key("__export") => crate::export_dialog::body(app, ui, &mut fields),// Image Size and Canvas Size open on Width, selected (#2329).DialogKind::Command if fields.contains_key("__sizing") => first_field_focused(ui, id, |ui| crate::sizing::body(ui, &mut fields)),+ DialogKind::Command if crate::smart_filter_dialog::owns(&fields) => crate::smart_filter_dialog::body(app, ui, &mut fields),DialogKind::Command if crate::adjust_dialog::owns(&fields) => crate::adjust_dialog::body(app, ui, &mut fields),DialogKind::Command if fields.contains_key("__filter") => {// Color Settings: the monitor profile in use can change while it is open.@@ -385,6 +386,9 @@ fn about_tab_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, tab: &str) {/// The dialog title as shown: [`title`] in the UI language.fn display_title(d: &Dialog) -> String {+ if crate::smart_filter_dialog::owns(&d.fields) {+ return crate::smart_filter_dialog::title(&d.fields);+ }match d.kind {DialogKind::Command => {let label = d.fields.get("__label").and_then(Value::as_str).unwrap_or("Command");@@ -441,7 +445,13 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {app.filter_preview = None;return Err("dialog has no command".into());};- let (cmd, params) = crate::smart_ui::confirm_command(&d.fields, cmd, crate::filter_dialog::params_of(&d.fields));+ let (cmd, params) = match crate::smart_ui::confirm_command(app, &d.fields, cmd, crate::filter_dialog::params_of(&d.fields)) {+ Ok(edit) => edit,+ Err(e) => {+ app.filter_preview = None;+ return Err(e);+ }+ };let result = app.run(&cmd, params.clone());// A filter that runs as a background job keeps its preview on screen until the job// lands (`canvas::committed_filter_preview`) instead of flashing the unfiltered image.diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rsindex d0c79d4fa..cb27d604c 100644--- a/crates/ui-egui/src/filter_dialog.rs+++ b/crates/ui-egui/src/filter_dialog.rs@@ -296,7 +296,7 @@ fn restore_remembered(app: &PhotocraftApp, command: &str, spec: &str, fields: &m/// Remember successful built-in schema dialogs; failed or cancelled dialogs do not persist.pub(crate) fn remember(app: &mut PhotocraftApp, command: &str, fields: &Map<String, Value>) {- if !fields.contains_key("__filter") || fields.contains_key("__spec") {+ if !fields.contains_key("__filter") || fields.contains_key("__spec") || fields.contains_key("__smartFilter") {return;}let Some(spec) = photocraft_engine::commands::find(command) else { return };@@ -625,16 +625,72 @@ pub fn preview_document_with(// Warp Text renders the type again from the layer model (font size, position), which a// reduced proxy doesn't scale: it runs at full size and the result is reduced (#218).let (run_k, reduce_k) = if command == "type.warpText" { (1, k) } else { (k, 1) };- let proxy = crate::proxy::proxy_document(doc, run_k);+ let mut proxy = crate::proxy::proxy_document(doc, run_k);+ let mut p = params.clone();+ if is_smart_edit(command) {+ let layer = photocraft_doc::LayerId(params.get("layer")?.as_u64()?);+ let index = usize::try_from(params.get("index")?.as_u64()?).ok()?;+ let photocraft_doc::LayerContent::Smart(sm) = &mut proxy.layer_mut(layer)?.content else { return None };+ // Proxy_document scales the visible cache only. Editing a filter re-renders its source:+ // scale the placement, every filter's lengths and the shared mask as well.+ if run_k > 1 {+ let divisor = f64::from(run_k);+ sm.transform.m = sm.transform.m.map(|v| v / divisor);+ if let Some(h) = &mut sm.perspective {+ for v in h.iter_mut().take(6) {+ *v /= divisor;+ }+ }+ if let Some(mask) = &mut sm.filter_mask {+ mask.surface = crate::proxy::downsample(&mask.surface, run_k);+ mask.feather /= run_k as f32;+ }+ for f in &mut sm.smart_filters {+ scale_preview_params(&f.command, &mut f.params, run_k);+ }+ if command == "layer.smartFilter.setParams" {+ let f = sm.smart_filters.get(index)?;+ scale_preview_params(&f.command, p.get_mut("params")?, run_k);+ }+ }+ } else {+ scale_preview_params(command, &mut p, run_k);+ }let mut s = photocraft_engine::Session::new();s.set_inline_job_ctx(cancel.cloned());s.add_document(proxy, None);if let Some(id) = active {s.select_layer(id).ok()?;}- let mut p = params.clone();- if run_k > 1- && let Some(o) = p.as_object_mut()+ s.execute(command, p).ok()?;+ s.active().map(|d| crate::proxy::proxy_document(&d.doc, reduce_k))+}++fn is_smart_edit(command: &str) -> bool {+ matches!(command, "layer.smartFilter.setParams" | "layer.smartFilter.blendingOptions")+}++/// Each stage constrains the proxy factor; an unscalable filter keeps full-resolution preview.+pub(crate) fn smart_preview_factor(doc: &Document, command: &str, params: &Value, k: u32) -> u32 {+ if !is_smart_edit(command) {+ return preview_factor(command, params, k);+ }+ let Some(layer) = params.get("layer").and_then(Value::as_u64).and_then(|id| doc.layer(photocraft_doc::LayerId(id))) else { return 1 };+ let photocraft_doc::LayerContent::Smart(sm) = &layer.content else { return 1 };+ let mut factor = sm.smart_filters.iter().fold(k, |k, f| preview_factor(&f.command, &f.params, k));+ if command == "layer.smartFilter.setParams"+ && let Some(index) = params.get("index").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok())+ && let Some(f) = sm.smart_filters.get(index)+ && let Some(p) = params.get("params")+ {+ factor = preview_factor(&f.command, p, factor);+ }+ factor+}++fn scale_preview_params(command: &str, params: &mut Value, k: u32) {+ if k > 1+ && let Some(o) = params.as_object_mut(){let spec = photocraft_engine::commands::find(command).map(|c| parse_spec(c.params)).unwrap_or_default();for (key, v) in o.iter_mut() {@@ -650,13 +706,11 @@ pub fn preview_document_with(let floor = minimum.unwrap_or(0.0).max(if key == "cellSize" { 1.0 } else { 0.1 });// Negative lengths (Offset's left/up shift, Displace's inverted scale) keep their// sign: the floor that keeps a radius positive turned them into +0.1 (#2063).- let x = x / run_k as f64;+ let x = x / k as f64;*v = json!(if x > 0.0 { x.max(floor) } else { minimum.map_or(x, |m| x.max(m)) });}}}- s.execute(command, p).ok()?;- s.active().map(|d| crate::proxy::proxy_document(&d.doc, reduce_k))}/// Cached preview state on the app.diff --git a/crates/ui-egui/src/filter_preview_worker.rs b/crates/ui-egui/src/filter_preview_worker.rsindex 2704f8a6a..a1490656c 100644--- a/crates/ui-egui/src/filter_preview_worker.rs+++ b/crates/ui-egui/src/filter_preview_worker.rs@@ -95,8 +95,11 @@ impl Worker {/// Stop and release previews of closed dialogs even when their canvas is no longer being drawn.pub(crate) fn discard_closed(app: &mut crate::PhotocraftApp) {- let visible =- app.ui.dialogs.iter().any(|d| d.fields.contains_key("__filter") && d.fields.get("__preview").and_then(serde_json::Value::as_bool) == Some(true));+ let visible = app.ui.dialogs.iter().any(|d| {+ d.fields.contains_key("__filter")+ && d.fields.get("__preview").and_then(serde_json::Value::as_bool) == Some(true)+ && d.fields.get("__smartFilter").is_none_or(|target| crate::smart_filter_dialog::validate_target(app, target).is_ok())+ });if !visible {if let Some(r) = &app.filter_preview_worker.running {r.job.cancel();diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex c0912a544..e496dd91f 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -2466,3 +2466,11 @@ cameraData Lens ObjektivFront Image Přední obrazSearch settings… Hledat nastavení…No matching settings Žádná odpovídající nastavení++# Smart Filter editors+ Blending Options ({filter}) Volby prolnutí ({filter})+ Hide the layer's effects and Smart Filters ({key}-click: all layers) Skrýt efekty vrstvy a inteligentní filtry (kliknutí s {key}: všechny vrstvy)+ Show the layer's effects and Smart Filters ({key}-click: all layers) Zobrazit efekty vrstvy a inteligentní filtry (kliknutí s {key}: všechny vrstvy)+ Wait for the current job to finish. Počkejte na dokončení aktuální úlohy.+ The document or Smart Filter changed. Reopen its dialog. Dokument nebo inteligentní filtr se změnil. Znovu otevřete jeho dialog.+ Opacity must be between 0% and 100%. Krytí musí být mezi 0% a 100%.diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex f51f35698..a8340e6cf 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2504,3 +2504,11 @@ cameraData Lens ObjektivFront Image Vorderes BildSearch settings… Einstellungen durchsuchen…No matching settings Keine passenden Einstellungen++# Smart Filter editors+ Blending Options ({filter}) Fülloptionen ({filter})+ Hide the layer's effects and Smart Filters ({key}-click: all layers) Ebeneneffekte und Smartfilter ausblenden ({key}-Klick: alle Ebenen)+ Show the layer's effects and Smart Filters ({key}-click: all layers) Ebeneneffekte und Smartfilter einblenden ({key}-Klick: alle Ebenen)+ Wait for the current job to finish. Warten Sie, bis der aktuelle Auftrag abgeschlossen ist.+ The document or Smart Filter changed. Reopen its dialog. Das Dokument oder der Smartfilter wurde geändert. Öffnen Sie den Dialog erneut.+ Opacity must be between 0% and 100%. Die Deckkraft muss zwischen 0% und 100% liegen.diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex bf9617d2c..249168cea 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -3572,3 +3572,11 @@ cameraData Lens ΦακόςFront Image Μπροστινή εικόναSearch settings… Αναζήτηση ρυθμίσεων…No matching settings Δεν βρέθηκαν ρυθμίσεις++# Smart Filter editors+ Blending Options ({filter}) Επιλογές ανάμειξης ({filter})+ Hide the layer's effects and Smart Filters ({key}-click: all layers) Απόκρυψη εφέ επιπέδου και έξυπνων φίλτρων ({key}-κλικ: όλα τα επίπεδα)+ Show the layer's effects and Smart Filters ({key}-click: all layers) Εμφάνιση εφέ επιπέδου και έξυπνων φίλτρων ({key}-κλικ: όλα τα επίπεδα)+ Wait for the current job to finish. Περιμένετε να ολοκληρωθεί η τρέχουσα εργασία.+ The document or Smart Filter changed. Reopen its dialog. Το έγγραφο ή το έξυπνο φίλτρο άλλαξε. Ανοίξτε ξανά το παράθυρό του.+ Opacity must be between 0% and 100%. Η αδιαφάνεια πρέπει να είναι μεταξύ 0% και 100%.diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex 42eab0e04..a40cabe71 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2545,3 +2545,11 @@ cameraData Lens ObjetivoFront Image Imagen frontalSearch settings… Buscar ajustes…No matching settings No hay ajustes que coincidan++# Smart Filter editors+ Blending Options ({filter}) Opciones de fusión ({filter})+ Hide the layer's effects and Smart Filters ({key}-click: all layers) Ocultar efectos de capa y filtros inteligentes ({key}-clic: todas las capas)+ Show the layer's effects and Smart Filters ({key}-click: all layers) Mostrar efectos de capa y filtros inteligentes ({key}-clic: todas las capas)+ Wait for the current job to finish. Espere a que termine la tarea actual.+ The document or Smart Filter changed. Reopen its dialog. El documento o el filtro inteligente ha cambiado. Vuelva a abrir su diálogo.+ Opacity must be between 0% and 100%. La opacidad debe estar entre 0% y 100%.diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex c4dd364a0..53661137d 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -2882,3 +2882,11 @@ cameraData Lens ObjectifFront Image Image de premier planSearch settings… Rechercher des réglages…No matching settings Aucun réglage correspondant++# Smart Filter editors+ Blending Options ({filter}) Options de fusion ({filter})+ Hide the layer's effects and Smart Filters ({key}-click: all layers) Masquer les effets du calque et les filtres dynamiques ({key}-clic : tous les calques)+ Show the layer's effects and Smart Filters ({key}-click: all layers) Afficher les effets du calque et les filtres dynamiques ({key}-clic : tous les calques)+ Wait for the current job to finish. Attendez la fin de la tâche en cours.+ The document or Smart Filter changed. Reopen its dialog. Le document ou le filtre dynamique a changé. Rouvrez sa boîte de dialogue.+ Opacity must be between 0% and 100%. L'opacité doit être comprise entre 0% et 100%.diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex b78e40ace..9647097ff 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -2869,3 +2869,11 @@ cameraData Lens LensaFront Image Gambar DepanSearch settings… Cari pengaturan…No matching settings Tidak ada pengaturan yang cocok++# Smart Filter editors+ Blending Options ({filter}) Opsi Pencampuran ({filter})+ Hide the layer's effects and Smart Filters ({key}-click: all layers) Sembunyikan efek lapisan dan Filter Cerdas (klik-{key}: semua lapisan)+ Show the layer's effects and Smart Filters ({key}-click: all layers) Tampilkan efek lapisan dan Filter Cerdas (klik-{key}: semua lapisan)+ Wait for the current job to finish. Tunggu hingga tugas saat ini selesai.+ The document or Smart Filter changed. Reopen its dialog. Dokumen atau Filter Cerdas berubah. Buka kembali dialognya.+ Opacity must be between 0% and 100%. Opasitas harus antara 0% dan 100%.diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex 62526f3c7..1882e07b0 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -2535,3 +2535,11 @@ cameraData Lens ObiettivoFront Image Immagine in primo pianoSearch settings… Cerca impostazioni…No matching settings Nessuna impostazione corrispondente++# Smart Filter editors+ Blending Options ({filter}) Opzioni di fusione ({filter})+ Hide the layer's effects and Smart Filters ({key}-click: all layers) Nascondi effetti del livello e filtri avanzati ({key}-clic: tutti i livelli)+ Show the layer's effects and Smart Filters ({key}-click: all layers) Mostra effetti del livello e filtri avanzati ({key}-clic: tutti i livelli)+ Wait for the current job to finish. Attendi il completamento dell'attività corrente.+ The document or Smart Filter changed. Reopen its dialog. Il documento o il filtro avanzato è cambiato. Riapri la sua finestra di dialogo.+ Opacity must be between 0% and 100%. L'opacità deve essere compresa tra 0% e 100%.diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex d4b422958..838339b0d 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -3483,3 +3483,11 @@ cameraData Lens レンズFront Image 前面の画像Search settings… 設定を検索…No matching settings 一致する設定はありません++# Smart Filter editors+ Blending Options ({filter}) 描画オプション ({filter})+ Hide the layer's effects and Smart Filters ({key}-click: all layers) レイヤー効果とスマートフィルターを非表示 ({key}+クリック: すべてのレイヤー)+ Show the layer's effects and Smart Filters ({key}-click: all layers) レイヤー効果とスマートフィルターを表示 ({key}+クリック: すべてのレイヤー)+ Wait for the current job to finish. 現在の処理が完了するまでお待ちください。+ The document or Smart Filter changed. Reopen its dialog. ドキュメントまたはスマートフィルターが変更されました。ダイアログを開き直してください。+ Opacity must be between 0% and 100%. 不透明度は0%から100%の範囲で指定してください。diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex ca5b9d257..9f261a8a5 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -3044,3 +3044,11 @@ cameraData Lens 렌즈Front Image 전면 이미지Search settings… 설정 검색…No matching settings 일치하는 설정 없음++# Smart Filter editors+ Blending Options ({filter}) 혼합 옵션 ({filter})+ Hide the layer's effects and Smart Filters ({key}-click: all layers) 레이어 효과 및 스마트 필터 숨기기 ({key}+클릭: 모든 레이어)+ Show the layer's effects and Smart Filters ({key}-click: all layers) 레이어 효과 및 스마트 필터 표시 ({key}+클릭: 모든 레이어)+ Wait for the current job to finish. 현재 작업이 완료될 때까지 기다리세요.+ The document or Smart Filter changed. Reopen its dialog. 문서 또는 스마트 필터가 변경되었습니다. 대화 상자를 다시 여세요.+ Opacity must be between 0% and 100%. 불투명도는 0%에서 100% 사이여야 합니다.diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex 4a8edcb3f..db188435c 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -3642,3 +3642,11 @@ cameraData Lens LensSearch settings… Instellingen zoeken…No matching settings Geen overeenkomende instellingenPhotoCraft — Screen Color Picker PhotoCraft — Schermkleurkiezer++# Smart Filter editors+ Blending Options ({filter}) Overvloeiopties ({filter})+ Hide the layer's effects and Smart Filters ({key}-click: all layers) Laageffecten en slimme filters verbergen ({key}-klik: alle lagen)+ Show the layer's effects and Smart Filters ({key}-click: all layers) Laageffecten en slimme filters tonen ({key}-klik: alle lagen)+ Wait for the current job to finish. Wacht tot de huidige taak is voltooid.+ The document or Smart Filter changed. Reopen its dialog. Het document of het slimme filter is gewijzigd. Open het dialoogvenster opnieuw.+ Opacity must be between 0% and 100%. De dekking moet tussen 0% en 100% liggen.diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 5b4ad1144..51b62acf7 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -3483,3 +3483,11 @@ cameraData Lens ObiektywFront Image Obraz na wierzchuSearch settings… Szukaj ustawień…No matching settings Brak pasujących ustawień++# Smart Filter editors+ Blending Options ({filter}) Opcje mieszania ({filter})+ Hide the layer's effects and Smart Filters ({key}-click: all layers) Ukryj efekty warstwy i inteligentne filtry (kliknięcie z {key}: wszystkie warstwy)+ Show the layer's effects and Smart Filters ({key}-click: all layers) Pokaż efekty warstwy i inteligentne filtry (kliknięcie z {key}: wszystkie warstwy)+ Wait for the current job to finish. Poczekaj na zakończenie bieżącego zadania.+ The document or Smart Filter changed. Reopen its dialog. Dokument lub inteligentny filtr został zmieniony. Otwórz ponownie jego okno dialogowe.+ Opacity must be between 0% and 100%. Krycie musi wynosić od 0% do 100%.diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex b24e76fbc..acfba6986 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -2890,3 +2890,11 @@ cameraData Lens LenteFront Image Imagem frontalSearch settings… Pesquisar configurações…No matching settings Nenhuma configuração encontrada++# Smart Filter editors+ Blending Options ({filter}) Opções de mesclagem ({filter})+ Hide the layer's effects and Smart Filters ({key}-click: all layers) Ocultar efeitos da camada e Filtros Inteligentes ({key}-clique: todas as camadas)+ Show the layer's effects and Smart Filters ({key}-click: all layers) Mostrar efeitos da camada e Filtros Inteligentes ({key}-clique: todas as camadas)+ Wait for the current job to finish. Aguarde a conclusão da tarefa atual.+ The document or Smart Filter changed. Reopen its dialog. O documento ou o Filtro Inteligente mudou. Reabra sua caixa de diálogo.+ Opacity must be between 0% and 100%. A opacidade deve estar entre 0% e 100%.diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex db32045a9..60b026ca4 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -2749,3 +2749,11 @@ cameraData Lens ОбъективRasterize Layer Style Растрировать стиль слояSearch settings… Поиск настроек…No matching settings Нет подходящих настроек++# Smart Filter editors+ Blending Options ({filter}) Параметры наложения ({filter})+ Hide the layer's effects and Smart Filters ({key}-click: all layers) Скрыть эффекты слоя и смарт-фильтры ({key}-клик: все слои)+ Show the layer's effects and Smart Filters ({key}-click: all layers) Показать эффекты слоя и смарт-фильтры ({key}-клик: все слои)+ Wait for the current job to finish. Дождитесь завершения текущей задачи.+ The document or Smart Filter changed. Reopen its dialog. Документ или смарт-фильтр изменился. Откройте его диалог заново.+ Opacity must be between 0% and 100%. Непрозрачность должна быть от 0% до 100%.diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex da80fc3a6..34c09db34 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -3570,3 +3570,11 @@ cameraData Lens Об'єктивSearch settings… Пошук налаштувань…No matching settings Немає відповідних налаштуваньPhotoCraft — Screen Color Picker PhotoCraft — Піпетка кольору екрана++# Smart Filter editors+ Blending Options ({filter}) Параметри накладання ({filter})+ Hide the layer's effects and Smart Filters ({key}-click: all layers) Приховати ефекти шару та смарт-фільтри ({key}-клік: усі шари)+ Show the layer's effects and Smart Filters ({key}-click: all layers) Показати ефекти шару та смарт-фільтри ({key}-клік: усі шари)+ Wait for the current job to finish. Дочекайтеся завершення поточного завдання.+ The document or Smart Filter changed. Reopen its dialog. Документ або смарт-фільтр змінився. Відкрийте його діалог знову.+ Opacity must be between 0% and 100%. Непрозорість має бути від 0% до 100%.diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex 7b2fac170..994d4424e 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2473,3 +2473,11 @@ cameraData Lens 镜头Front Image 前面的图像Search settings… 搜索设置…No matching settings 没有匹配的设置++# Smart Filter editors+ Blending Options ({filter}) 混合选项 ({filter})+ Hide the layer's effects and Smart Filters ({key}-click: all layers) 隐藏图层效果和智能滤镜 ({key} 单击:所有图层)+ Show the layer's effects and Smart Filters ({key}-click: all layers) 显示图层效果和智能滤镜 ({key} 单击:所有图层)+ Wait for the current job to finish. 请等待当前任务完成。+ The document or Smart Filter changed. Reopen its dialog. 文档或智能滤镜已更改。请重新打开其对话框。+ Opacity must be between 0% and 100%. 不透明度必须介于 0% 和 100% 之间。diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex 38671e3cd..85c713847 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2443,3 +2443,11 @@ cameraData Lens 鏡頭Front Image 前面的影像Search settings… 搜尋設定…No matching settings 沒有符合的設定++# Smart Filter editors+ Blending Options ({filter}) 混合選項 ({filter})+ Hide the layer's effects and Smart Filters ({key}-click: all layers) 隱藏圖層效果和智慧型濾鏡 ({key} 點擊:所有圖層)+ Show the layer's effects and Smart Filters ({key}-click: all layers) 顯示圖層效果和智慧型濾鏡 ({key} 點擊:所有圖層)+ Wait for the current job to finish. 請等待目前的工作完成。+ The document or Smart Filter changed. Reopen its dialog. 文件或智慧型濾鏡已變更。請重新開啟其對話框。+ Opacity must be between 0% and 100%. 不透明度必須介於 0% 和 100% 之間。diff --git a/crates/ui-egui/src/layer_row_ui.rs b/crates/ui-egui/src/layer_row_ui.rsindex d26569059..4f5dcf3b2 100644--- a/crates/ui-egui/src/layer_row_ui.rs+++ b/crates/ui-egui/src/layer_row_ui.rs@@ -33,6 +33,7 @@ pub enum Indicator {Lock,FxTriangle,Fx,+ SmartFilters,Link,Blend,}@@ -74,8 +75,15 @@ pub fn reserved_width(l: &Layer) -> f32 {if l.locks.transparency || l.locks.position || l.locks.all {w += ICON_W + GAP;}+ let smart = crate::smart_ui::has_filters(l);+ if !l.effects.items.is_empty() || smart {+ w += TRIANGLE_W + GAP;+ }if !l.effects.items.is_empty() {- w += TRIANGLE_W + 1.0 + 13.0 + GAP;+ w += 13.0 + GAP;+ }+ if smart {+ w += ICON_W + GAP;}if l.link_group.is_some() {w += ICON_W + GAP;@@ -117,6 +125,7 @@ pub fn indicators(let fx_font = theme::semibold(11.0);let blend_font = FontId::proportional(10.5);let has_fx = !l.effects.items.is_empty();+ let has_smart = crate::smart_ui::has_filters(l);let show_blend = l.blend != BlendMode::Normal && l.blend != BlendMode::PassThrough;let fx_galley = has_fx.then(|| painter.layout_no_wrap("fx".into(), fx_font, t.text_dim));let blend_galley = show_blend.then(|| painter.layout_no_wrap(tl!(l.blend.label()).into(), blend_font, t.text_faint));@@ -124,8 +133,13 @@ pub fn indicators(if locked {items.push((Indicator::Lock, ICON_W));}- if let Some(g) = &fx_galley {+ if has_fx || has_smart {items.push((Indicator::FxTriangle, TRIANGLE_W));+ }+ if has_smart {+ items.push((Indicator::SmartFilters, ICON_W));+ }+ if let Some(g) = &fx_galley {items.push((Indicator::Fx, g.size().x));}if l.link_group.is_some() {@@ -151,6 +165,11 @@ pub fn indicators(painter.galley(pos2(r.left(), cy - g.size().y / 2.0), g, t.text_faint);}}+ Indicator::SmartFilters => {+ let enabled = matches!(&l.content, photocraft_doc::LayerContent::Smart(sm) if sm.filters_enabled);+ crate::smart_ui::paint_badge(painter, r.center(), if enabled { t.icon } else { t.text_faint });+ ui.interact(r, ui.id().with(("smart-filters-badge", l.id.0)), Sense::hover()).on_hover_text(tl!("Smart Filters"));+ }Indicator::FxTriangle => {let resp = ui.interact(r, ui.id().with(("fx-disclosure", l.id.0)), Sense::click());paint_triangle(painter, r.center(), fx_open, if resp.hovered() { t.text } else { t.icon });@@ -160,7 +179,11 @@ pub fn indicators(actions.push(("layer.setEffectsExpanded".into(), json!({"layer": l.id.0, "expanded": !fx_open, "all": all})));}let (verb, name) = (if fx_open { tl!("Collapse") } else { tl!("Expand") }, l.name.clone());- let tip = if fx_open {+ let tip = if has_smart && fx_open {+ tl!("Hide the layer's effects and Smart Filters ({key}-click: all layers)")+ } else if has_smart {+ tl!("Show the layer's effects and Smart Filters ({key}-click: all layers)")+ } else if fx_open {tl!("Hide the layer's effects ({key}-click: all layers)")} else {tl!("Show the layer's effects ({key}-click: all layers)")diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex c30796a5d..ec0c9f95f 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -144,6 +144,7 @@ pub mod shortcut_dispatch;pub mod shortcuts;mod sizing;pub mod slice_ui;+pub mod smart_filter_dialog;pub mod smart_ui;pub mod snap_ui;pub(crate) mod solid_fill_ui;@@ -530,6 +531,7 @@ pub struct PhotocraftApp {/// Selection outline cache: (doc, revision, segments)./// Live filter preview (proxy document with the filter applied).pub(crate) filter_preview: Option<filter_dialog::FilterPreview>,+ pub(crate) smart_filter_targets: smart_filter_dialog::Targets,#[cfg(not(target_arch = "wasm32"))]filter_preview_worker: filter_preview_worker::Worker,/// Select › Color Range dialog preview (proxy document + mask / image textures).@@ -690,6 +692,7 @@ impl PhotocraftApp {proxy_uploaded: None,outline_cache: None,filter_preview: None,+ smart_filter_targets: Default::default(),#[cfg(not(target_arch = "wasm32"))]filter_preview_worker: Default::default(),color_range: None,@@ -1654,6 +1657,9 @@ impl PhotocraftApp {if layer.vector_mask.is_some() {live.insert((layer.id, mask_thumbs_ui::THUMB_VECTOR));}+ if matches!(&layer.content, photocraft_doc::LayerContent::Smart(sm) if sm.filter_mask.is_some()) {+ live.insert((layer.id, mask_thumbs_ui::THUMB_SMART_MASK));+ }if let Some(children) = layer.children() {pending.extend(children);}@@ -1702,8 +1708,19 @@ impl PhotocraftApp {}pub fn mask_thumb(&mut self, ctx: &egui::Context, doc: &Document, id: photocraft_doc::LayerId, mask: &photocraft_doc::LayerMask) -> egui::TextureId {+ self.mask_thumb_kind(ctx, doc, id, mask, mask_thumbs_ui::THUMB_MASK)+ }++ pub(crate) fn mask_thumb_kind(+ &mut self,+ ctx: &egui::Context,+ doc: &Document,+ id: photocraft_doc::LayerId,+ mask: &photocraft_doc::LayerMask,+ kind: u8,+ ) -> egui::TextureId {let rev = surface_fingerprint(&mask.surface) ^ (doc.size.width as u64) << 40;- let key = (id, mask_thumbs_ui::THUMB_MASK);+ let key = (id, kind);if let Some((r, tex)) = self.thumbs.get(&key)&& *r == rev{diff --git a/crates/ui-egui/src/mask_thumbs_ui.rs b/crates/ui-egui/src/mask_thumbs_ui.rsindex 562b2b752..5ab2181bc 100644--- a/crates/ui-egui/src/mask_thumbs_ui.rs+++ b/crates/ui-egui/src/mask_thumbs_ui.rs@@ -22,6 +22,7 @@ pub const CHAIN_W: f32 = 12.0;pub const THUMB_LAYER: u8 = 0;pub const THUMB_MASK: u8 = 1;pub const THUMB_VECTOR: u8 = 2;+pub const THUMB_SMART_MASK: u8 = 3;/// Which of a layer's masks.#[derive(Clone, Copy, Debug, PartialEq, Eq)]diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex a717a1219..a8a83366d 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -378,6 +378,18 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:crate::export_dialog::quick_export_layer_png(app, layer)}}+ "layer.smartFilter.blendingOptions" if params.get("blend").is_none() && params.get("opacity").is_none() => {+ let st = app.session.active().ok_or("no document open")?;+ let layer = params.get("layer").and_then(Value::as_u64).map(photocraft_doc::LayerId).or(st.active_layer).ok_or("no layer selected")?;+ let Some(photocraft_doc::LayerContent::Smart(sm)) = st.doc.layer(layer).map(|l| &l.content) else {+ return Err("the layer is not a Smart Object".into());+ };+ let index = match params.get("index") {+ Some(v) => v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or("invalid Smart Filter index")?,+ None => sm.smart_filters.len().checked_sub(1).ok_or("the Smart Object has no Smart Filters")?,+ };+ crate::smart_filter_dialog::open(app, layer, index).map(|id| json!({"dialog": id}))+ }"layer.layerStyle.blendingOptions" if params.as_object().is_none_or(|o| o.is_empty()) => {crate::layer_style::open(app, Some(crate::layer_style::BLENDING)).map(|d| json!({"dialog": d})).ok_or_else(|| "no active layer".to_string())}diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex 444036c57..1badd413d 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -2131,7 +2131,9 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {if !l.effects.items.is_empty() && fx_collapsed.iter().all(|id| *id != l.id) {effect_rows(app, ui, l, depth, &mut actions);}- crate::smart_ui::filter_rows(app, ui, l, depth, &mut actions);+ if !fx_collapsed.contains(&l.id) {+ crate::smart_ui::filter_rows(app, ui, &doc, l, depth, &mut actions);+ }}// #1721: the list takes drops everywhere, not only on a row (Photoshop): the space// between two rows lands above the lower one, the empty space below the bottom-mostdiff --git a/crates/ui-egui/src/smart_filter_dialog.rs b/crates/ui-egui/src/smart_filter_dialog.rsnew file mode 100644index 000000000..b8db81693--- /dev/null+++ b/crates/ui-egui/src/smart_filter_dialog.rs@@ -0,0 +1,227 @@+//! Per-filter blending and shared target validation for Smart Filter editors.+//! Preview and commit dispatch the existing engine commands against the captured filter.++use std::sync::{Arc, Weak};++use photocraft_color::BlendMode;+use photocraft_doc::{Document, LayerContent, LayerId};+use serde_json::{Map, Value, json};++use crate::{PhotocraftApp, state::DialogKind, theme::Tokens, widgets};++pub const COMMAND: &str = "layer.smartFilter.blendingOptions";+const TARGET: &str = "__smartFilter";++/// Private document snapshots; public dialog fields carry an opaque counter, never an address.+#[derive(Default)]+pub(crate) struct Targets {+ next: u64,+ snapshots: Vec<(u64, Weak<Document>)>,+}++impl Targets {+ 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);+ // Dialogs normally are modal. Bound retained snapshots even if automation opens many.+ if self.snapshots.len() >= 64 {+ self.snapshots.remove(0);+ }+ self.snapshots.push((self.next, Arc::downgrade(doc)));+ Ok(self.next)+ }++ 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))+ }+}++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() {+ return Err(tl!("Wait for the current job to finish.").into());+ }+ let sm = match &st.doc.layer(layer).ok_or("Smart Object no longer exists")?.content {+ LayerContent::Smart(sm) => sm,+ _ => return Err("the layer is not a Smart Object".into()),+ };+ let filter = sm.smart_filters.get(index).ok_or("Smart Filter no longer exists")?;+ Ok(json!({"doc": st.doc.id.0, "revision": st.revision, "layer": layer.0, "index": index, "filter": filter}))+}++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;+ let token = app.smart_filter_targets.capture(doc)?;+ if let Some(fields) = target.as_object_mut() {+ fields.insert("guard".into(), json!(token));+ }+ Ok(target)+}++/// Revision/filter identity catches edits; the weak snapshot also rejects a same-id reopen.+pub(crate) fn validate_target(app: &PhotocraftApp, target: &Value) -> Result<(LayerId, usize), String> {+ let layer = LayerId(target.get("layer").and_then(Value::as_u64).ok_or("invalid Smart Filter target")?);+ let index = target.get("index").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).ok_or("invalid Smart Filter index")?;+ let token = target.get("guard").and_then(Value::as_u64).ok_or("invalid Smart Filter snapshot")?;+ let doc = &app.session.active().ok_or("no document open")?.doc;+ let current = snapshot(app, layer, index)?;+ let mut captured = target.clone();+ if let Some(fields) = captured.as_object_mut() {+ fields.remove("guard");+ }+ if current != captured || !app.smart_filter_targets.matches(token, doc) {+ return Err(tl!("The document or Smart Filter changed. Reopen its dialog.").into());+ }+ Ok((layer, index))+}++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")?;+ let Some(LayerContent::Smart(sm)) = st.doc.layer(layer).map(|l| &l.content) else { return Err("the layer is not a Smart Object".into()) };+ let filter = sm.smart_filters.get(index).ok_or("Smart Filter no longer exists")?;+ let mut fields = Map::new();+ fields.insert("__command".into(), json!(COMMAND));+ fields.insert("__label".into(), json!("Blending Options"));+ fields.insert("__filterName".into(), json!(crate::smart_ui::filter_label(filter)));+ fields.insert("__filter".into(), json!(true));+ fields.insert("__preview".into(), json!(true));+ fields.insert(TARGET.into(), target);+ fields.insert("blend".into(), json!(filter.blend.label()));+ fields.insert("opacity".into(), json!(filter.opacity * 100.0));+ let fit = (220.0 / st.doc.size.width.max(st.doc.size.height).max(1) as f64 * 100.0).min(100.0);+ fields.insert("__zoom".into(), json!(fit));+ fields.insert("__imageSize".into(), json!([st.doc.size.width, st.doc.size.height]));+ app.filter_preview = None;+ Ok(app.ui.open_dialog(DialogKind::Command, fields))+}++pub fn owns(fields: &Map<String, Value>) -> bool {+ fields.get("__command").and_then(Value::as_str) == Some(COMMAND) && fields.contains_key(TARGET)+}++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())])+}++/// UI opacity is always percent; the engine gets a fraction, including 1% = 0.01.+fn blend_params(fields: &Map<String, Value>) -> Result<Value, String> {+ let opacity = fields+ .get("opacity")+ .and_then(Value::as_f64)+ .filter(|v| v.is_finite() && (0.0..=100.0).contains(v))+ .ok_or(tl!("Opacity must be between 0% and 100%."))?;+ let blend = fields.get("blend").and_then(Value::as_str).ok_or("choose a blend mode")?;+ Ok(json!({"blend": blend, "opacity": opacity / 100.0}))+}++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) {+ let mut params = blend_params(fields)?;+ if let Some(p) = params.as_object_mut() {+ p.insert("layer".into(), json!(layer.0));+ p.insert("index".into(), json!(index));+ }+ Ok((COMMAND.into(), params))+ } else {+ Ok(("layer.smartFilter.setParams".into(), json!({"layer": layer.0, "index": index, "params": crate::filter_dialog::params_of(fields)})))+ }+}++pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map<String, Value>) {+ ui.horizontal(|ui| {+ ui.label(tl!("Mode"));+ let mut blend = fields.get("blend").and_then(Value::as_str).unwrap_or("Normal").to_string();+ let options: Vec<_> = BlendMode::LAYER_MODES.iter().map(|m| (m.label().to_string(), m.label())).collect();+ if widgets::dropdown(ui, "smart-filter-blend", &mut blend, &options, 200.0) {+ fields.insert("blend".into(), json!(blend));+ }+ });+ let mut opacity = fields.get("opacity").and_then(Value::as_f64).unwrap_or(100.0) as f32;+ if widgets::slider_row(ui, tl!("Opacity"), &mut opacity, 0.0..=100.0, "%", None).changed() {+ fields.insert("opacity".into(), json!(opacity));+ }+ let mut preview = fields.get("__preview").and_then(Value::as_bool).unwrap_or(true);+ if widgets::checkbox(ui, &mut preview, tl!("Preview")).changed() {+ fields.insert("__preview".into(), json!(preview));+ }+ if let Err(e) = fields.get(TARGET).ok_or("no Smart Filter target").map_err(str::to_string).and_then(|t| validate_target(app, t)) {+ ui.colored_label(Tokens::get(ui.ctx()).danger, e);+ return;+ }+ viewport(app, ui, fields, preview);+}++#[derive(Clone)]+struct ViewImage {+ doc: Arc<Document>,+ texture: egui::TextureHandle,+}++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 {+ app.filter_preview.as_ref().filter(|p| p.key.doc == st.doc.id && p.key.revision == st.revision && !p.committing).and_then(|p| p.result.clone())+ } else {+ Some(st.doc.clone())+ };+ let Some(doc) = doc else {+ ui.allocate_ui(egui::vec2(360.0, 220.0), |ui| {+ ui.centered_and_justified(|ui| {+ ui.spinner();+ });+ });+ return;+ };+ let key = ui.id().with("smart-filter-view-image");+ let mut image = ui.ctx().data(|d| d.get_temp::<ViewImage>(key));+ if image.as_ref().is_none_or(|i| !Arc::ptr_eq(&i.doc, &doc)) {+ // Fixed thumbnail size and content identity: never composite a full surface per frame.+ let buffer = photocraft_compose::thumbnail_buffer(&doc, 256);+ match app.session.color.canvas_display(&doc) {+ Ok(display) => {+ let thumb = display.to_rgba8(&buffer);+ let texture = ui.ctx().load_texture(+ "smart-filter-view-image",+ egui::ColorImage::from_rgba_unmultiplied([thumb.width as usize, thumb.height as usize], &thumb.pixels),+ egui::TextureOptions::LINEAR,+ );+ image = Some(ViewImage { doc, texture });+ if let Some(i) = &image {+ ui.ctx().data_mut(|d| d.insert_temp(key, i.clone()));+ }+ }+ Err(e) => {+ ui.colored_label(Tokens::get(ui.ctx()).danger, e.to_string());+ return;+ }+ }+ }+ let Some(image) = image else { return };+ let zoom = fields.get("__zoom").and_then(Value::as_f64).unwrap_or(100.0).clamp(0.1, 800.0) as f32;+ let size = fields+ .get("__imageSize")+ .and_then(Value::as_array)+ .and_then(|a| Some(egui::vec2(a.first()?.as_u64()? as f32, a.get(1)?.as_u64()? as f32)))+ .unwrap_or(image.texture.size_vec2());+ egui::Frame::new().fill(Tokens::get(ui.ctx()).canvas).stroke(egui::Stroke::new(1.0, Tokens::get(ui.ctx()).field_border)).show(ui, |ui| {+ ui.set_width(360.0);+ egui::ScrollArea::both().id_salt("smart-filter-image").auto_shrink([false, false]).min_scrolled_height(220.0).max_height(220.0).show(ui, |ui| {+ ui.add(egui::Image::new(&image.texture).fit_to_exact_size(size * zoom / 100.0));+ });+ });+ ui.horizontal(|ui| {+ if widgets::secondary_button(ui, "−", 32.0).clicked() {+ fields.insert("__zoom".into(), json!((zoom / 2.0).max(0.1)));+ }+ ui.label(format!("{zoom:.1}%"));+ if widgets::secondary_button(ui, "+", 32.0).clicked() {+ fields.insert("__zoom".into(), json!((zoom * 2.0).min(800.0)));+ }+ });+}++#[cfg(test)]+pub(crate) mod tests;diff --git a/crates/ui-egui/src/smart_filter_dialog/tests.rs b/crates/ui-egui/src/smart_filter_dialog/tests.rsnew file mode 100644index 000000000..04b838913--- /dev/null+++ b/crates/ui-egui/src/smart_filter_dialog/tests.rs@@ -0,0 +1,246 @@+use super::*;+use photocraft_doc::{SmartFilter, SmartObject};++#[test]+fn a_same_id_reopened_document_rejects_the_previous_dialog() {+ let (mut app, layer) = app(8, "rgb");+ let saved = app.session.active().unwrap().doc.as_ref().clone();+ app.session.close(0).unwrap();+ app.session.add_document(saved.clone(), None);+ let id = open(&mut app, layer, 0).unwrap();+ let old = app.session.active().unwrap().doc.clone();+ app.session.close(0).unwrap();+ app.session.add_document(saved, None);+ assert_eq!(app.session.active().unwrap().revision, 1);+ assert_eq!(old.id, app.session.active().unwrap().doc.id);+ let before = app.session.active().unwrap().doc.clone();+ assert!(crate::dialogs::confirm(&mut app, id).is_err());+ assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc));+}++#[test]+fn tiny_images_keep_a_usable_preview_viewport() {+ let (mut app, layer) = app(8, "rgb");+ let id = open(&mut app, layer, 0).unwrap();+ let mut fields = app.ui.dialog_mut(id).unwrap().fields.clone();+ fields.insert("__imageSize".into(), json!([8, 8]));+ fields.insert("__zoom".into(), json!(100));+ let ctx = egui::Context::default();+ PhotocraftApp::setup_context(&ctx, Default::default());+ let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(480.0, 480.0))), ..Default::default() };+ ctx.run_ui(input, |ui| {+ let start = ui.cursor().top();+ super::viewport(&mut app, ui, &mut fields, false);+ assert!(ui.cursor().top() - start >= 220.0, "tiny image must not collapse the preview");+ })+ .textures_delta+ .clear();+}++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();+ s.execute("layer.new.layer", json!({"name": "Smart Object"})).unwrap();+ s.execute("edit.fill", json!({"contents": "color", "color": "#305080"})).unwrap();+ s.execute("select.rect", json!({"x":0,"y":0,"width":32,"height":48})).unwrap();+ s.execute("edit.fill", json!({"contents": "color", "color": "#e09040"})).unwrap();+ s.execute("select.deselect", json!({})).unwrap();+ s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();+ let layer = s.active().unwrap().active_layer.unwrap();+ s.execute("filter.blur.boxBlur", json!({"radius": 4})).unwrap();+ s.execute("filter.sharpen.smartSharpen", json!({"amount": 125, "radius": 2})).unwrap();+ let mut app = PhotocraftApp::new(s, Default::default());+ app.background_jobs = false;+ (app, layer)+}++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+}++fn filters(app: &PhotocraftApp, layer: LayerId) -> Vec<SmartFilter> {+ smart(app, layer).smart_filters.clone()+}++#[test]+fn blending_edits_one_filter_with_percent_opacity_and_undo_redo() {+ for depth in [8, 16, 32] {+ for mode in ["rgb", "gray"] {+ let (mut app, layer) = app(depth, mode);+ let original = filters(&app, layer);+ let source = photocraft_engine::smart_cmds::contents_of(&app.session.active().unwrap().doc, layer).unwrap();+ for opacity in [0.0, 1.0, 50.0, 100.0] {+ for blend in ["Normal", "Multiply", "Screen", "Luminosity"] {+ let steps = app.session.active().unwrap().history.past_len();+ let id = open(&mut app, layer, 0).unwrap();+ let f = &mut app.ui.dialog_mut(id).unwrap().fields;+ f.insert("opacity".into(), json!(opacity));+ f.insert("blend".into(), json!(blend));+ let fields = f.clone();+ let (cmd, params) = edit_command(&app, &fields).unwrap();+ let before = app.session.active().unwrap().doc.clone();+ let expected = crate::filter_dialog::preview_document(&before, Some(layer), &cmd, ¶ms, 1).unwrap();+ assert_eq!(app.session.active().unwrap().history.past_len(), steps);+ crate::dialogs::confirm(&mut app, id).unwrap();+ let changed = filters(&app, layer);+ assert!((changed[0].opacity - opacity as f32 / 100.0).abs() < 1e-6);+ assert_eq!(changed[0].blend.label(), blend);+ assert_eq!(serde_json::to_value(&changed[1]).unwrap(), serde_json::to_value(&original[1]).unwrap());+ assert_eq!(photocraft_engine::smart_cmds::contents_of(&app.session.active().unwrap().doc, layer).unwrap(), source);+ assert_eq!(app.session.active().unwrap().doc.layer(layer).unwrap().blend, BlendMode::Normal);+ assert_eq!(+ smart(&app, layer).cache.as_ref().unwrap().read_region(before.bounds()),+ expected.layer(layer).unwrap().surface().unwrap().read_region(expected.bounds())+ );+ assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1);+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(serde_json::to_value(filters(&app, layer)).unwrap(), serde_json::to_value(&original).unwrap());+ app.run("edit.redo", json!({})).unwrap();+ let id = open(&mut app, layer, 0).unwrap();+ assert_eq!(app.ui.dialog_mut(id).unwrap().fields["opacity"].as_f64().unwrap(), opacity);+ crate::dialogs::cancel(&mut app, id).unwrap();+ app.run("edit.undo", json!({})).unwrap();+ }+ }+ }+ }+}++#[test]+fn preview_toggle_and_cancel_leave_document_and_history_untouched() {+ let (mut app, layer) = app(8, "rgb");+ let st = app.session.active().unwrap();+ let before = st.doc.clone();+ let steps = st.history.past_len();+ let id = open(&mut app, layer, 0).unwrap();+ app.ui.dialog_mut(id).unwrap().fields.insert("opacity".into(), json!(1));+ let ctx = egui::Context::default();+ let idx = app.session.active_index().unwrap();+ assert!(crate::canvas::ensure_filter_preview(&mut app, idx, &ctx).is_some());+ assert_eq!(app.filter_preview.as_ref().unwrap().key.params["opacity"], json!(0.01));+ app.ui.dialog_mut(id).unwrap().fields.insert("__preview".into(), json!(false));+ assert!(crate::canvas::ensure_filter_preview(&mut app, idx, &ctx).is_none());+ app.ui.dialog_mut(id).unwrap().fields.insert("__preview".into(), json!(true));+ assert!(crate::canvas::ensure_filter_preview(&mut app, idx, &ctx).is_some());+ crate::dialogs::cancel(&mut app, id).unwrap();+ assert!(app.filter_preview.is_none());+ assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc));+ assert_eq!(app.session.active().unwrap().history.past_len(), steps);+}++#[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"] {+ let (mut app, layer) = app(8, "rgb");+ let id = open(&mut app, layer, 0).unwrap();+ let params = match command {+ "file.new" => json!({"width": 16,"height":16}),+ "layer.smartFilter.move" => json!({"layer":layer.0,"index":0,"to":1}),+ _ => json!({"layer":layer.0,"index":0}),+ };+ app.run(command, params).unwrap();+ let before = app.session.active().unwrap().doc.clone();+ assert!(crate::dialogs::confirm(&mut app, id).is_err(), "{command}");+ assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc));+ }+}++#[test]+fn reduced_preview_scales_placement_stack_and_mask_without_adding_filters() {+ let (mut app, layer) = app(16, "rgb");+ // A half-visible shared mask, different from the layer mask.+ let st = app.session.active_mut().unwrap();+ let doc = Arc::make_mut(&mut st.doc);+ let LayerContent::Smart(sm) = &mut doc.layer_mut(layer).unwrap().content else { panic!() };+ let mut mask = photocraft_doc::LayerMask::reveal_all();+ mask.surface.fill_rect(photocraft_geom::Rect::new(32, 0, 64, 48), &[0.0]);+ sm.filter_mask = Some(mask);+ let id = open(&mut app, layer, 0).unwrap();+ app.ui.dialog_mut(id).unwrap().fields.insert("opacity".into(), json!(50));+ let (command, params) = edit_command(&app, &app.ui.dialogs[0].fields).unwrap();+ let original = app.session.active().unwrap().doc.clone();+ let preview = crate::filter_dialog::preview_document(&original, Some(layer), &command, ¶ms, 2).unwrap();+ assert_eq!(preview.size.width, 32);+ let LayerContent::Smart(sm) = &preview.layer(layer).unwrap().content else { panic!() };+ assert_eq!(sm.smart_filters.len(), 2);+ assert_eq!(sm.smart_filters[0].params["radius"], json!(2.0));+ assert_eq!(sm.smart_filters[1].params["radius"], json!(1.0));+ assert_eq!(sm.filter_mask.as_ref().unwrap().surface.pixel(17, 0)[0], 0.0);+ assert!(sm.cache.as_ref().unwrap().content_bounds().x1 <= 32);+ assert!(Arc::ptr_eq(&original, &app.session.active().unwrap().doc));+}++#[test]+fn native_save_preserves_edited_blending_and_existing_invert() {+ let (mut app, layer) = app(8, "rgb");+ let ctx = egui::Context::default();+ crate::menus::invoke(&mut app, &ctx, "image.adjustments.invert", json!({})).unwrap();+ assert_eq!(smart(&app, layer).smart_filters.last().unwrap().command, "image.adjustments.invert");+ let id = open(&mut app, layer, 2).unwrap();+ app.ui.dialog_mut(id).unwrap().fields.insert("opacity".into(), json!(1));+ crate::dialogs::confirm(&mut app, id).unwrap();+ let doc = &app.session.active().unwrap().doc;+ let loaded = photocraft_format::load_from_bytes(&photocraft_format::save_to_bytes(doc, &Default::default()).unwrap()).unwrap();+ let LayerContent::Smart(sm) = &loaded.layers.last().unwrap().content else { panic!() };+ assert_eq!(serde_json::to_value(&sm.smart_filters).unwrap(), serde_json::to_value(filters(&app, layer)).unwrap());+}++#[test]+fn invalid_opacity_fails_without_an_edit() {+ let (mut app, layer) = app(8, "rgb");+ for opacity in [json!(-1), json!(101), json!("x"), Value::Null] {+ let id = open(&mut app, layer, 0).unwrap();+ app.ui.dialog_mut(id).unwrap().fields.insert("opacity".into(), opacity);+ let before = app.session.active().unwrap().doc.clone();+ assert!(crate::dialogs::confirm(&mut app, id).is_err());+ assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc));+ }+}++#[test]+fn blending_does_not_follow_layer_selection_or_the_layer_mask_target() {+ let (mut app, layer) = app(8, "rgb");+ app.run("layer.new.layer", json!({"name":"Selected pixel layer"})).unwrap();+ let selected = app.session.active().unwrap().active_layer.unwrap();+ app.run("layer.layerMask.revealAll", json!({"layer":selected.0})).unwrap();+ app.ui.mask_target = true;+ let doc = app.session.active().unwrap().doc.clone();+ let mask = doc.layer(selected).unwrap().mask.as_ref().unwrap().surface.clone();+ let id = open(&mut app, layer, 0).unwrap();+ app.ui.dialog_mut(id).unwrap().fields.insert("opacity".into(), json!(25));+ let idx = app.session.active_index().unwrap();+ assert!(crate::canvas::ensure_filter_preview(&mut app, idx, &Default::default()).is_some());+ crate::dialogs::confirm(&mut app, id).unwrap();+ assert_eq!(smart(&app, layer).smart_filters[0].opacity, 0.25);+ assert_eq!(app.session.active().unwrap().active_layer, Some(selected));+ assert_eq!(+ crate::surface_fingerprint(&app.session.active().unwrap().doc.layer(selected).unwrap().mask.as_ref().unwrap().surface),+ crate::surface_fingerprint(&mask)+ );+}++#[test]+fn invert_blending_keeps_transparency_at_every_depth() {+ for depth in [8, 16, 32] {+ let mut s = photocraft_engine::Session::new();+ s.execute("file.new", json!({"width":8,"height":8,"depth":depth})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ s.edit("synthetic translucent pixels", |doc, active| {+ let bounds = doc.bounds();+ doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(bounds, &[0.2, 0.4, 0.6, 0.5]);+ Ok(())+ })+ .unwrap();+ s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();+ let layer = s.active().unwrap().active_layer.unwrap();+ let before = s.active().unwrap().doc.layer(layer).unwrap().surface().unwrap().pixel(3, 3);+ s.execute("image.adjustments.invert", json!({})).unwrap();+ let mut app = PhotocraftApp::new(s, Default::default());+ app.background_jobs = false;+ let id = open(&mut app, layer, 0).unwrap();+ app.ui.dialog_mut(id).unwrap().fields.insert("opacity".into(), json!(1));+ crate::dialogs::confirm(&mut app, id).unwrap();+ assert_eq!(smart(&app, layer).cache.as_ref().unwrap().pixel(3, 3)[3], before[3]);+ }+}diff --git a/crates/ui-egui/src/smart_ui.rs b/crates/ui-egui/src/smart_ui.rsindex 99deaa60f..614a1898e 100644--- a/crates/ui-egui/src/smart_ui.rs+++ b/crates/ui-egui/src/smart_ui.rs@@ -1,8 +1,8 @@//! Layers-panel pieces for smart objects: the thumbnail badge and the Smart Filters sub-rows//! (eye toggles; double-click a filter to re-open its dialog with the recorded parameters).-use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2};-use photocraft_doc::{Layer, LayerContent, SmartObject};+use egui::{Color32, Rect, Sense, Stroke, pos2, vec2};+use photocraft_doc::{Document, Layer, LayerContent, SmartObject};use serde_json::{Value, json};use crate::theme::Tokens;@@ -22,7 +22,7 @@ pub fn thumb_badge(ui: &egui::Ui, l: &Layer, thumb: Rect) {/// The display name of a smart filter (its command's label without the ellipsis). A Photoshop/// filter PhotoCraft doesn't implement shows its own name and is marked as kept as is.-fn filter_label(f: &photocraft_doc::SmartFilter) -> String {+pub(crate) fn filter_label(f: &photocraft_doc::SmartFilter) -> String {let command = f.command.as_str();if command == photocraft_engine::smart_cmds::UNSUPPORTED_FILTER {let name = f.params.get("name").and_then(Value::as_str).unwrap_or("Smart filter");@@ -34,16 +34,27 @@ fn filter_label(f: &photocraft_doc::SmartFilter) -> String {/// Smart Filters header + one row per filter (top filter first, as in Photoshop) under a smart/// layer. Edits are queued in `actions` as engine commands.-pub fn filter_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, depth: usize, actions: &mut Vec<(String, Value)>) {+pub fn has_filters(l: &Layer) -> bool {+ matches!(&l.content, LayerContent::Smart(sm) if !sm.smart_filters.is_empty())+}++/// The two rings in the layer row indicate an attached Smart Filters stack.+pub fn paint_badge(painter: &egui::Painter, center: egui::Pos2, color: Color32) {+ for dx in [-2.5, 2.5] {+ painter.circle_stroke(center + vec2(dx, 0.0), 3.5, Stroke::new(1.0, color));+ }+}++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() {return;}let t = Tokens::get(ui.ctx());- let indent = 30.0 + depth as f32 * 14.0 + 34.0;+ let indent = 30.0 + crate::layer_row_ui::indent(depth, ui.available_width(), 130.0);let rows = std::iter::once(None).chain((0..sm.smart_filters.len()).rev().map(Some));for index in rows {- let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), if index.is_none() { 30.0 } else { 22.0 }), Sense::hover());if resp.hovered() {ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.35));}@@ -51,35 +62,70 @@ pub fn filter_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, depth:ui.painter().line_segment([pos2(rect.left() + 30.0, rect.top()), pos2(rect.left() + 30.0, rect.bottom())], Stroke::new(1.0, t.separator));}let (name, on) = match index {- None => ("Smart Filters".to_string(), sm.filters_enabled),+ None => (tl!("Smart Filters").to_string(), sm.filters_enabled),Some(i) => (filter_label(&sm.smart_filters[i]), sm.smart_filters[i].visible && sm.filters_enabled),};- let eye = Rect::from_min_size(pos2(rect.left() + 6.0, rect.center().y - 9.0), vec2(18.0, 18.0));+ let eye = Rect::from_center_size(pos2(rect.left() + indent + if index.is_none() { 9.0 } else { 41.0 }, rect.center().y), vec2(18.0, 18.0));let eye_resp = ui.interact(eye, ui.id().with(("sf-eye", l.id.0, index)), Sense::click());let shown = match index {None => sm.filters_enabled,Some(i) => sm.smart_filters[i].visible,};if shown {- icons::paint(ui, eye, "eye", 12.0, t.icon);+ icons::paint(ui, eye, "eye", 12.0, if on { t.icon } else { t.text_faint });}+ eye_resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Checkbox, true, shown, format!("{} {name}", tl!("Visibility"))));if eye_resp.clicked() {actions.push(match index {None => ("layer.smartFilter.disableSmartFilters".into(), json!({"layer": l.id.0})),Some(i) => ("layer.smartFilter.setVisible".into(), json!({"layer": l.id.0, "index": i})),});}- let x = rect.left() + indent + if index.is_none() { 0.0 } else { 16.0 };+ let x = rect.left() + indent + 60.0;if index.is_none() {- let sw = Rect::from_center_size(pos2(x - 12.0, rect.center().y), vec2(14.0, 10.0));- ui.painter().rect_filled(sw, 1.0, if sm.filter_mask.as_ref().is_some_and(|m| m.enabled) { Color32::from_gray(200) } else { Color32::WHITE });+ let sw = Rect::from_center_size(pos2(x - 20.0, rect.center().y), vec2(24.0, 24.0));+ if let Some(mask) = &sm.filter_mask {+ let tex = app.mask_thumb_kind(ui.ctx(), doc, l.id, mask, crate::mask_thumbs_ui::THUMB_SMART_MASK);+ ui.painter().image(tex, sw, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);+ if !mask.enabled {+ ui.painter().line_segment([sw.left_top(), sw.right_bottom()], Stroke::new(1.0, t.danger));+ ui.painter().line_segment([sw.right_top(), sw.left_bottom()], Stroke::new(1.0, t.danger));+ }+ } else {+ ui.painter().rect_filled(sw, 0.0, Color32::WHITE);+ }ui.painter().rect_stroke(sw, 1.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);}- ui.painter().text(pos2(x, rect.center().y), Align2::LEFT_CENTER, name, egui::FontId::proportional(11.5), if on { t.text_dim } else { t.text_faint });- if let Some(i) = index- && resp.double_clicked()- {- open_editor(app, ui.ctx(), l.id.0, sm, i);+ let blend = index.map(|_| Rect::from_center_size(pos2(rect.right() - crate::layer_row_ui::RIGHT_PAD - 9.0, rect.center().y), vec2(18.0, 18.0)));+ let right = blend.map_or(rect.right() - crate::layer_row_ui::RIGHT_PAD, |r| r.left() - 4.0);+ crate::layer_row_ui::label(+ ui.painter(),+ x,+ rect.center().y,+ right,+ &name,+ egui::FontId::proportional(11.5),+ if on { t.text_dim } else { t.text_faint },+ );+ if let Some(i) = index {+ let name_rect = Rect::from_min_max(pos2(x.min(right), rect.top()), pos2(right, rect.bottom()));+ let name_resp = ui.interact(name_rect, ui.id().with(("sf-name", l.id.0, i)), Sense::click());+ name_resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &name));+ if name_resp.double_clicked() {+ open_editor(app, ui.ctx(), l.id.0, sm, i);+ }+ if let Some(r) = blend {+ let blend_resp = ui.interact(r, ui.id().with(("sf-blend", l.id.0, i)), Sense::click());+ icons::paint(ui, r, "sliders-horizontal", 13.0, if blend_resp.hovered() { t.text } else { t.icon });+ let label = crate::i18n::fmt(tl!("Blending Options ({filter})"), &[("filter", &name)]);+ blend_resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &label));+ if blend_resp.double_clicked()+ && let Err(e) = crate::smart_filter_dialog::open(app, l.id, i)+ {+ crate::notices::error(app, e);+ }+ blend_resp.on_hover_text(label);+ }}}}@@ -96,17 +142,23 @@ pub fn open_editor(app: &mut PhotocraftApp, ctx: &egui::Context, layer: u64, sm:}return;}- if !crate::filter_dialog::has_dialog(&f.command) {+ let target = match crate::smart_filter_dialog::target(app, photocraft_doc::LayerId(layer), index) {+ Ok(target) => target,+ Err(e) => {+ crate::notices::error(app, e);+ return;+ }+ };+ let Some(id) = crate::adjust_dialog::open(app, &f.command)+ .or_else(|| crate::filter_dialog::has_dialog(&f.command).then(|| crate::filter_dialog::open(app, &f.command)).flatten())+ else {return;- }- let Some(id) = crate::filter_dialog::open(app, &f.command) else { return };+ };if let Some(d) = app.ui.dialog_mut(id) {- // The live preview would stack a second copy of the filter on the smart object.- d.fields.remove("__preview");- d.fields.insert("__smartFilter".into(), json!({"layer": layer, "index": index}));+ d.fields.insert("__smartFilter".into(), target);if let Value::Object(p) = &f.params {for (k, v) in p {- if d.fields.contains_key(k) {+ if !k.starts_with("__") {d.fields.insert(k.clone(), v.clone());}}@@ -115,9 +167,18 @@ pub fn open_editor(app: &mut PhotocraftApp, ctx: &egui::Context, layer: u64, sm:}/// The command a confirmed filter dialog runs: smart-filter edits update the recorded filter.-pub fn confirm_command(fields: &serde_json::Map<String, Value>, command: String, params: Value) -> (String, Value) {+pub fn confirm_command(app: &PhotocraftApp, fields: &serde_json::Map<String, Value>, command: String, params: Value) -> Result<(String, Value), String> {+ if crate::smart_filter_dialog::owns(fields) {+ return crate::smart_filter_dialog::edit_command(app, fields);+ }match fields.get("__smartFilter") {- Some(sf) => ("layer.smartFilter.setParams".into(), json!({"layer": sf["layer"], "index": sf["index"], "params": params})),- None => (command, params),+ Some(sf) => {+ let (layer, index) = crate::smart_filter_dialog::validate_target(app, sf)?;+ Ok(("layer.smartFilter.setParams".into(), json!({"layer": layer.0, "index": index, "params": params})))+ }+ None => Ok((command, params)),}}++#[cfg(test)]+mod tests;diff --git a/crates/ui-egui/src/smart_ui/tests.rs b/crates/ui-egui/src/smart_ui/tests.rsnew file mode 100644index 000000000..c007b2ca6--- /dev/null+++ b/crates/ui-egui/src/smart_ui/tests.rs@@ -0,0 +1,154 @@+use egui::{Modifiers, PointerButton, vec2};+use egui_kittest::{Harness, kittest::Queryable};+use serde_json::json;++use crate::{+ PhotocraftApp,+ smart_filter_dialog::tests::{app, smart},+};++fn harness(width: f32, scale: f32, theme: crate::theme::ThemeKind) -> Harness<'static, PhotocraftApp> {+ let (app, _) = app(8, "rgb");+ let mut h =+ Harness::builder().with_size(vec2(1200.0, 850.0)).with_pixels_per_point(scale).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(move |cc| {+ PhotocraftApp::setup_context(&cc.egui_ctx, theme);+ app+ });+ let ctx = h.ctx.clone();+ let (req, _rx) = crate::control::ControlRequest::new(+ "ui.set",+ json!({"theme":theme.id(),"dockWidth":width,"dock":{"collapsed":["color","properties","history","navigator"]}}),+ );+ crate::control::handle(h.state_mut(), &ctx, &req);+ h.run_steps(5);+ h+}++fn click(h: &mut Harness<'_, PhotocraftApp>, at: egui::Pos2) {+ h.hover_at(at);+ h.run_steps(1);+ h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });+ h.run_steps(1);+ h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });+ h.run_steps(2);+}++#[test]+fn names_and_blend_icons_have_separate_double_click_targets_and_no_overlap() {+ for theme in crate::theme::ThemeKind::ALL {+ for width in [250.0, 420.0] {+ let mut h = harness(width, 1.0, theme);+ let layer = h.state().session.active().unwrap().active_layer.unwrap();+ let rows = crate::layer_row_ui::recorded(&h.ctx);+ let row = rows.iter().find(|r| r.layer == layer.0).unwrap();+ assert!(row.indicators.iter().any(|(k, _)| *k == crate::layer_row_ui::Indicator::SmartFilters));+ let blend = h.get_by_label("Blending Options (Box Blur)").rect();+ let edit = h.get_by_label("Box Blur").rect();+ assert!(edit.right() <= blend.left(), "{width} {theme:?}: {edit:?} {blend:?}");+ click(&mut h, blend.center());+ assert!(h.state().ui.dialogs.is_empty(), "single click does not open blending");+ click(&mut h, blend.center());+ assert!(crate::smart_filter_dialog::owns(&h.state().ui.dialogs.last().unwrap().fields));+ assert_eq!(h.state().ui.dialogs.last().unwrap().fields["__smartFilter"]["index"], json!(0));+ let id = h.state().ui.dialogs.last().unwrap().id;+ crate::dialogs::cancel(h.state_mut(), id).unwrap();+ // Start a new gesture after egui's triple-click interval, as native users do.+ for _ in 0..40 {+ h.step();+ }+ click(&mut h, edit.center());+ click(&mut h, edit.center());+ assert_eq!(h.state().ui.dialogs.last().unwrap().fields["__command"], json!("filter.blur.boxBlur"));+ assert_eq!(h.state().ui.dialogs.last().unwrap().fields["radius"].as_f64(), Some(4.0));+ }+ }+}++#[test]+fn disclosure_hides_both_stacks_without_changing_pixels_history_or_selection() {+ let mut h = harness(290.0, 1.5, Default::default());+ let layer = h.state().session.active().unwrap().active_layer.unwrap();+ h.state_mut().run("layer.layerStyle.dropShadow", json!({"layer":layer.0})).unwrap();+ h.state_mut().run("layer.new.layer", json!({"name":"Selected elsewhere"})).unwrap();+ h.run_steps(5);+ let before = h.state().session.active().unwrap().doc.clone();+ let revision = h.state().session.active().unwrap().revision;+ let steps = h.state().session.active().unwrap().history.past_len();+ let active = h.state().session.active().unwrap().active_layer;+ let at = h.get_by_label("Collapse effects Smart Object").rect().center();+ click(&mut h, at);+ assert!(h.state().session.active().unwrap().fx_collapsed.contains(&layer));+ assert!(h.query_by_label("Blending Options (Box Blur)").is_none());+ assert!(h.query_by_label("Drop Shadow").is_none());+ assert!(std::sync::Arc::ptr_eq(&before, &h.state().session.active().unwrap().doc));+ assert_eq!(h.state().session.active().unwrap().revision, revision);+ assert_eq!(h.state().session.active().unwrap().history.past_len(), steps);+ assert_eq!(h.state().session.active().unwrap().active_layer, active);+ let at = h.get_by_label("Expand effects Smart Object").rect().center();+ click(&mut h, at);+ assert!(h.query_by_label("Blending Options (Box Blur)").is_some());+}++#[test]+fn adjustment_editor_reopens_stored_parameters_and_updates_instead_of_appending() {+ let (mut app, layer) = app(8, "rgb");+ app.run("image.adjustments.hueSaturation", json!({"hue":35,"saturation":12,"lightness":-7})).unwrap();+ let ctx = egui::Context::default();+ let sm = smart(&app, layer).clone();+ super::open_editor(&mut app, &ctx, layer.0, &sm, 2);+ let id = app.ui.dialogs.last().unwrap().id;+ let fields = &mut app.ui.dialog_mut(id).unwrap().fields;+ assert_eq!(fields["hue"], json!(35));+ assert!(crate::adjust_dialog::owns(fields));+ fields.insert("hue".into(), json!(75));+ let idx = app.session.active_index().unwrap();+ assert!(!crate::adjust_preview::on_layer(&mut app, idx));+ assert!(crate::canvas::ensure_filter_preview(&mut app, idx, &ctx).is_some());+ let steps = app.session.active().unwrap().history.past_len();+ crate::dialogs::confirm(&mut app, id).unwrap();+ assert_eq!(smart(&app, layer).smart_filters.len(), 3);+ assert_eq!(smart(&app, layer).smart_filters[2].params["hue"], json!(75));+ assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1);+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(smart(&app, layer).smart_filters[2].params["hue"], json!(35));+ app.run("image.adjustments.invert", json!({})).unwrap();+ let sm = smart(&app, layer).clone();+ super::open_editor(&mut app, &ctx, layer.0, &sm, 3);+ assert!(app.ui.dialogs.is_empty(), "Invert has no parameter editor");+}++#[test]+fn smart_and_layer_masks_have_separate_thumbnail_cache_entries() {+ let (mut app, layer) = app(8, "rgb");+ app.run("layer.layerMask.revealAll", json!({"layer":layer.0})).unwrap();+ let doc = app.session.active().unwrap().doc.clone();+ let mask = doc.layer(layer).unwrap().mask.as_ref().unwrap();+ let ctx = egui::Context::default();+ let first = app.mask_thumb(&ctx, &doc, layer, mask);+ let mut other = mask.clone();+ other.surface.fill_rect(photocraft_geom::Rect::new(0, 0, 64, 48), &[0.0]);+ let second = app.mask_thumb_kind(&ctx, &doc, layer, &other, crate::mask_thumbs_ui::THUMB_SMART_MASK);+ assert_ne!(first, second);+ assert_eq!(first, app.mask_thumb(&ctx, &doc, layer, mask));+}++#[test]+fn ctrl_i_uses_existing_invert_command_and_undo_redo_keep_the_source() {+ let mut h = harness(290.0, 1.0, Default::default());+ let layer = h.state().session.active().unwrap().active_layer.unwrap();+ let before = smart(h.state(), layer).clone();+ let source = photocraft_engine::smart_cmds::contents_of(&h.state().session.active().unwrap().doc, layer).unwrap();+ let steps = h.state().session.active().unwrap().history.past_len();+ h.key_press_modifiers(Modifiers::COMMAND, egui::Key::I);+ h.run_steps(4);+ let sm = smart(h.state(), layer);+ assert_eq!(sm.smart_filters.len(), 3);+ assert_eq!(sm.smart_filters[2].command, "image.adjustments.invert");+ assert_eq!(photocraft_engine::smart_cmds::contents_of(&h.state().session.active().unwrap().doc, layer).unwrap(), source);+ assert_ne!(sm.cache.as_ref().unwrap().pixel(8, 8), before.cache.as_ref().unwrap().pixel(8, 8));+ assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1);+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(smart(h.state(), layer).smart_filters.len(), 2);+ h.state_mut().run("edit.redo", json!({})).unwrap();+ assert_eq!(smart(h.state(), layer).smart_filters.len(), 3);+}diff --git a/docs/smart-filters.md b/docs/smart-filters.mdnew file mode 100644index 000000000..74c32ea46--- /dev/null+++ b/docs/smart-filters.md@@ -0,0 +1,51 @@+# Smart Filters in the Layers panel++A Smart Object with filters has a rings indicator and a disclosure arrow beside+its name. The arrow hides or shows both its layer effects and Smart Filters; it+does not disable them or change the document. Alt-click applies that view choice+to all layers with effects or Smart Filters.++The Smart Filters header shows the shared filter mask and the stack's visibility+control. Filters appear newest first, while the engine evaluates them from bottom+to top. Each filter has its own visibility control.++Double-click a filter's name to edit its saved parameters in its existing editor.+OK updates that filter; it does not append a second copy. Parameter-free filters+such as Invert have no settings dialog. Camera Raw retains its dedicated editor.++Double-click the sliders icon at the right of a filter to open **Blending Options**.+Mode and Opacity belong to that filter, independently of the layer and other+filters. Opacity is shown as a percentage (1% means 0.01). Preview changes the+temporary canvas composite and the dialog's image viewport. Zoom controls and+scrolling affect only that viewport. The viewport uses a bounded image thumbnail;+it is a navigation preview, not a full-resolution detail inspection.++OK applies one undoable edit. Cancel or Escape leaves the document untouched.+Editors capture their document snapshot, revision, layer and filter. Reopening+the same saved document also invalidates a retained dialog. A document switch,+Undo/Redo, filter deletion/reorder or pending document job requires reopening the+dialog rather than applying settings to a changed target.++Ctrl+I / Image > Adjustments > Invert on Smart Object content uses the existing+engine adjustment command to add an Invert Smart Filter, preserving the source.+When a layer mask or channel is targeted, its existing adjustment semantics apply.++## Storage and current limits++`.pcraft` stores the complete Smart Filter stack, parameters, shared mask,+visibility and per-filter blending. PSD only supports the filters mapped by+`crates/io/src/smart_map.rs`: Invert and Smart Sharpen currently lack live PSD+mappings. PSD export can warn and omit unmapped live filters. This interface+change does not extend the PSD mapping table or unknown-descriptor support.++Preview reuses the native filter worker and reduced document pipeline. Some+filters require full-resolution previews. Committing edits and toggling filter+eyes retain the cached stages and background jobs already supplied by the engine+(PR #2739). This change does not add a new GPU filter implementation or establish+large-image performance budgets.++Filter opacity interpolates premultiplied input and filtered results, so+alpha-preserving filters retain translucent coverage at partial strength. This+is scoped to Smart Filters; global layer compositing is unchanged. Dissolve+currently follows the inherited Smart Filter color-blending path without+per-pixel coverage sampling; exact Dissolve parity remains a separate task.