From f9f1d823cc14aa377707d4fc17134ea83b5e3db4 Mon Sep 17 00:00:00 2001 From: abc2cb <271337822+abc2cb@users.noreply.github.com> Date: Sun, 11 Oct 2026 09:59:42 +0300 Subject: [PATCH 01/54] Make Smart Filter editors distinct and preserve alpha at partial strength --- crates/engine/src/fx_view_cmds.rs | 42 ++- crates/engine/src/smart_cmds.rs | 25 +- crates/engine/src/smart_cmds/tests.rs | 35 +++ crates/ui-egui/src/adjust_dialog.rs | 7 +- crates/ui-egui/src/adjust_preview.rs | 3 + crates/ui-egui/src/canvas.rs | 8 +- crates/ui-egui/src/dialogs.rs | 12 +- crates/ui-egui/src/filter_dialog.rs | 70 ++++- crates/ui-egui/src/filter_preview_worker.rs | 7 +- crates/ui-egui/src/i18n/cs.tsv | 8 + crates/ui-egui/src/i18n/de.tsv | 8 + crates/ui-egui/src/i18n/el.tsv | 8 + crates/ui-egui/src/i18n/es.tsv | 8 + crates/ui-egui/src/i18n/fr.tsv | 8 + crates/ui-egui/src/i18n/id.tsv | 8 + crates/ui-egui/src/i18n/it.tsv | 8 + crates/ui-egui/src/i18n/ja.tsv | 8 + crates/ui-egui/src/i18n/ko.tsv | 8 + crates/ui-egui/src/i18n/nl.tsv | 8 + crates/ui-egui/src/i18n/pl.tsv | 8 + crates/ui-egui/src/i18n/pt-br.tsv | 8 + crates/ui-egui/src/i18n/ru.tsv | 8 + crates/ui-egui/src/i18n/uk.tsv | 8 + crates/ui-egui/src/i18n/zh-hans.tsv | 8 + crates/ui-egui/src/i18n/zh-hant.tsv | 8 + crates/ui-egui/src/layer_row_ui.rs | 29 ++- crates/ui-egui/src/lib.rs | 19 +- crates/ui-egui/src/mask_thumbs_ui.rs | 1 + crates/ui-egui/src/menus.rs | 12 + crates/ui-egui/src/panels.rs | 4 +- crates/ui-egui/src/smart_filter_dialog.rs | 227 ++++++++++++++++ .../ui-egui/src/smart_filter_dialog/tests.rs | 246 ++++++++++++++++++ crates/ui-egui/src/smart_ui.rs | 115 ++++++-- crates/ui-egui/src/smart_ui/tests.rs | 154 +++++++++++ docs/smart-filters.md | 51 ++++ 35 files changed, 1139 insertions(+), 56 deletions(-) create mode 100644 crates/ui-egui/src/smart_filter_dialog.rs create mode 100644 crates/ui-egui/src/smart_filter_dialog/tests.rs create mode 100644 crates/ui-egui/src/smart_ui/tests.rs create mode 100644 docs/smart-filters.md diff --git a/crates/engine/src/fx_view_cmds.rs b/crates/engine/src/fx_view_cmds.rs index 03241d8405..7c35959df0 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) -> 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> { @@ -37,12 +41,12 @@ fn set_expanded(s: &mut Session, p: &Value) -> Result { 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 = st.doc.walk().iter().filter(|(_, _, l)| !l.effects.items.is_empty()).map(|(_, _, l)| l.id).collect(); + let with_fx: Vec = 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 { 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.rs index 6e0c043578..d80596a681 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.rs index 2ee54322bf..b496e04514 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.rs index a4b831ed2f..7c6157f389 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 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.rs index d94d58bff6..c6aa8fc529 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.rs index a1fcda0adb..f5f29af832 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.rs index c4a700aef7..b1c3d678b9 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 { 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.rs index d0c79d4faa..cb27d604cb 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) { - 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.rs index 2704f8a6ac..a1490656c7 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.tsv index c0912a5448..e496dd91fd 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2466,3 +2466,11 @@ cameraData Lens Objektiv Front Image Přední obraz Search 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.tsv index f51f35698d..a8340e6cf7 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2504,3 +2504,11 @@ cameraData Lens Objektiv Front Image Vorderes Bild Search 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.tsv index bf9617d2c7..249168cea2 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.tsv index 42eab0e04a..a40cabe716 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2545,3 +2545,11 @@ cameraData Lens Objetivo Front Image Imagen frontal Search 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.tsv index c4dd364a00..53661137dd 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2882,3 +2882,11 @@ cameraData Lens Objectif Front Image Image de premier plan Search 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.tsv index b78e40ace7..9647097ffe 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2869,3 +2869,11 @@ cameraData Lens Lensa Front Image Gambar Depan Search 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.tsv index 62526f3c7d..1882e07b00 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2535,3 +2535,11 @@ cameraData Lens Obiettivo Front Image Immagine in primo piano Search 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.tsv index d4b422958e..838339b0da 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.tsv index ca5b9d257d..9f261a8a58 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.tsv index 4a8edcb3fe..db188435c0 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3642,3 +3642,11 @@ cameraData Lens Lens Search settings… Instellingen zoeken… No matching settings Geen overeenkomende instellingen PhotoCraft — 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.tsv index 5b4ad11441..51b62acf74 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3483,3 +3483,11 @@ cameraData Lens Obiektyw Front Image Obraz na wierzchu Search 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.tsv index b24e76fbc1..acfba69860 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 Lente Front Image Imagem frontal Search 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.tsv index db32045a95..60b026ca45 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.tsv index da80fc3a6c..34c09db34f 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.tsv index 7b2fac1702..994d4424ee 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.tsv index 38671e3cd4..85c713847f 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.rs index d265690597..4f5dcf3b23 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.rs index c30796a5dd..ec0c9f95fb 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, + 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.rs index 562b2b7521..5ab2181bc4 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.rs index a717a12190..a8a83366db 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.rs index 444036c57f..1badd413de 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-most diff --git a/crates/ui-egui/src/smart_filter_dialog.rs b/crates/ui-egui/src/smart_filter_dialog.rs new file mode 100644 index 0000000000..b8db816939 --- /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)>, +} + +impl Targets { + fn capture(&mut self, doc: &Arc) -> Result { + 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) -> 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 { + 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 { + 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 { + 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) -> bool { + fields.get("__command").and_then(Value::as_str) == Some(COMMAND) && fields.contains_key(TARGET) +} + +pub(crate) fn title(fields: &Map) -> 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) -> Result { + 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) -> 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) { + 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, + texture: egui::TextureHandle, +} + +fn viewport(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map, 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::(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.rs new file mode 100644 index 0000000000..04b8389133 --- /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 { + 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.rs index 99deaa60fe..614a1898e8 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, command: String, params: Value) -> (String, Value) { +pub fn confirm_command(app: &PhotocraftApp, fields: &serde_json::Map, 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.rs new file mode 100644 index 0000000000..c007b2ca6b --- /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.md new file mode 100644 index 0000000000..74c32ea46c --- /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. From 1515cafae4919da8f8fb4227d5ff79f813f87788 Mon Sep 17 00:00:00 2001 From: abc2cb <271337822+abc2cb@users.noreply.github.com> Date: Sun, 11 Oct 2026 10:31:23 +0300 Subject: [PATCH 02/54] fix(engine): retain Smart Filter coverage around blur edges --- crates/engine/src/smart_cmds.rs | 13 ++++++++- crates/engine/src/smart_cmds/tests.rs | 35 +++++++++++++++++++++++- crates/engine/tests/photoshop_oracles.rs | 12 ++++++++ docs/smart-filters.md | 6 +++- 4 files changed, 63 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rs index d80596a681..366011daf1 100644 --- a/crates/engine/src/smart_cmds.rs +++ b/crates/engine/src/smart_cmds.rs @@ -291,10 +291,21 @@ fn blend_surfaces(base: &Surface, top: &Surface, mode: BlendMode, opacity: f32) } let n = fmt.channels(); let (b, t) = (base.read_region(area), top.read_region(area)); + // Alpha-preserving filters edit the same coverage. A non-Normal filter that + // changes coverage (e.g. blur) must also retain input-only pixels and admit + // filtered-only pixels, as Photoshop's Smart Filter blend oracles require. + // Classify the whole result so unchanged pixels do not switch blend rules + // independently at the edge of a blur. + let composite_coverage = mode != BlendMode::Normal && fmt.alpha && b.chunks_exact(n).zip(t.chunks_exact(n)).any(|(bp, tp)| bp.last() != tp.last()); 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 b = photocraft_raster::to_rgba(&fmt, bp); let t = photocraft_raster::to_rgba(&fmt, tp); + if composite_coverage { + let rgba = photocraft_color::blend::composite(mode, b, t, opacity); + photocraft_raster::from_rgba_into(&fmt, rgba, op); + continue; + } 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 { @@ -304,7 +315,7 @@ fn blend_surfaces(base: &Surface, top: &Surface, mode: BlendMode, opacity: f32) }; // 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. + // while Normal-mode filters that change coverage 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 { diff --git a/crates/engine/src/smart_cmds/tests.rs b/crates/engine/src/smart_cmds/tests.rs index b496e04514..55d5fa9642 100644 --- a/crates/engine/src/smart_cmds/tests.rs +++ b/crates/engine/src/smart_cmds/tests.rs @@ -23,7 +23,7 @@ fn filter_strength_preserves_alpha_and_interpolates_changed_coverage() { 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] { + for mode in [BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen, BlendMode::Luminosity] { let mixed = blend_surfaces(&base, &filtered, mode, opacity).pixel(0, 0); assert!((mixed[3] - before[3]).abs() <= tolerance); if mode == BlendMode::Normal { @@ -42,6 +42,39 @@ fn filter_strength_preserves_alpha_and_interpolates_changed_coverage() { } } +#[test] +fn non_normal_coverage_changes_retain_source_over_semantics() { + 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); + // Input-only, output-only, opaque input with blurred output, and a + // translucent pixel whose alpha happens to be unchanged by this filter. + for (x, (ba, ta)) in [(0.5, 0.0), (0.0, 0.5), (1.0, 0.25), (0.5, 0.5)].into_iter().enumerate() { + let x = x as i32; + base.fill_rect(Rect::new(x, 0, 1, 1), &[0.2, 0.4, 0.6, ba]); + filtered.fill_rect(Rect::new(x, 0, 1, 1), &[0.8, 0.6, 0.4, ta]); + } + for mode in [BlendMode::Screen, BlendMode::Multiply, BlendMode::Luminosity] { + for opacity in [0.0, 0.01, 0.5, 1.0] { + let mixed = blend_surfaces(&base, &filtered, mode, opacity); + for x in 0..4 { + if opacity == 0.0 { + assert_eq!(mixed.pixel(x, 0), base.pixel(x, 0)); + continue; + } + let b = photocraft_raster::to_rgba(&fmt, &base.pixel(x, 0)); + let t = photocraft_raster::to_rgba(&fmt, &filtered.pixel(x, 0)); + let expected = photocraft_color::blend::composite(mode, b, t, opacity); + let mut reference = Surface::new(fmt); + reference.fill_rect(Rect::new(x, 0, 1, 1), &expected); + assert_eq!(mixed.pixel(x, 0), reference.pixel(x, 0), "{sample:?} {mode:?} {opacity} x={x}"); + } + } + } + } +} + 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/engine/tests/photoshop_oracles.rs b/crates/engine/tests/photoshop_oracles.rs index 2edd13b2ba..e07b451efc 100644 --- a/crates/engine/tests/photoshop_oracles.rs +++ b/crates/engine/tests/photoshop_oracles.rs @@ -80,6 +80,18 @@ fn rerender(doc: &mut Document) -> Result { Ok(n) } +#[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"); + let bytes = std::fs::read(&path).expect("Screen/Motion Blur oracle missing: run cargo xtask corpus --all"); + let file = PsdFile::from_bytes(&bytes).expect("parse Screen/Motion Blur oracle"); + let mut doc = photocraft_io::import("sf-blend-screen-100.psd", &bytes).expect("import Screen/Motion Blur oracle").document; + assert!(rerender(&mut doc).expect("re-render Screen/Motion Blur oracle") > 0); + let merged = photocraft_io::merged_composite(&file).expect("Photoshop merged composite"); + let (error, bad) = max_diff(&photocraft_compose::flatten(&doc).px, &merged); + assert!(error <= PASS_TOL, "Screen/Motion Blur error {error}, {bad}% pixels exceed 2/255"); +} + #[test] fn photoshop_oracles_rerendered() { let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/photoshop"); diff --git a/docs/smart-filters.md b/docs/smart-filters.md index 74c32ea46c..278c989966 100644 --- a/docs/smart-filters.md +++ b/docs/smart-filters.md @@ -46,6 +46,10 @@ 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 +also applies to Normal mode when a filter changes coverage. Non-Normal modes +use source-over compositing when the filtered surface changes alpha, preserving +input-only and filtered-only pixels around blur edges. The choice applies to +the whole filtered surface. 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. From 05af9b146bf10d9a119394365a52e5117e48ddb8 Mon Sep 17 00:00:00 2001 From: abc2cb <271337822+abc2cb@users.noreply.github.com> Date: Sun, 11 Oct 2026 22:26:13 +0300 Subject: [PATCH 03/54] test(engine): expect signed HDR outputs from destructive Levels --- crates/engine/src/adjust_params.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/adjust_params.rs b/crates/engine/src/adjust_params.rs index 00fb67dd03..8bc99a40bc 100644 --- a/crates/engine/src/adjust_params.rs +++ b/crates/engine/src/adjust_params.rs @@ -1240,9 +1240,12 @@ mod tests { #[test] fn destructive_levels_dont_clip_in_32_bit() { // Input 15..230, gamma 1.3, output 10..245: black and white land on the output range in - // integer documents, but in a 32-bit document the curve runs on past it (then 0..1). + // integer documents. A 32-bit document evaluates the signed power curve beyond both + // ranges, retaining negative values and highlights above 1. The float expectations + // below were evaluated independently from the configured curve, not a clipped LUT. let params = json!({"inBlack": 15, "inWhite": 230, "gamma": 1.3, "outBlack": 10, "outWhite": 245}); - for (depth, low, high) in [(8, 10.0, 245.0), (16, 10.0, 245.0), (32, 0.0, 255.0)] { + for depth in [8, 16, 32] { + let (low, high, tolerance) = if depth == 32 { (-0.079_642_7, 1.042_158, 1e-6) } else { (10.0 / 255.0, 245.0 / 255.0, 0.6 / 255.0) }; let mut s = crate::Session::new(); s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "white"})).unwrap(); s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 16})).unwrap(); @@ -1250,8 +1253,10 @@ mod tests { s.execute("select.deselect", json!({})).unwrap(); s.execute("image.adjustments.levels", params.clone()).unwrap(); let px = pixels(&s); - assert!((px[0][0] * 255.0 - low).abs() < 0.6, "black @{depth}: {:?}", px[0]); - assert!((px[1][0] * 255.0 - high).abs() < 0.6, "white @{depth}: {:?}", px[1]); + assert!((px[0][0] - low).abs() < tolerance, "black @{depth}: {:?}", px[0]); + assert!((px[1][0] - high).abs() < tolerance, "white @{depth}: {:?}", px[1]); + assert_eq!(px[0][3], 1.0, "Levels keeps alpha"); + assert_eq!(px[1][3], 1.0, "Levels keeps alpha"); } } From 69b1f2544d3bada482f5c9ea5e01a40f191a518f Mon Sep 17 00:00:00 2001 From: abc2cb <271337822+abc2cb@users.noreply.github.com> Date: Sun, 11 Oct 2026 23:29:14 +0300 Subject: [PATCH 04/54] Deny ambient installed profile discovery in automation --- crates/automation/src/workspace.rs | 19 ++++++++++++++++++- docs/control-protocol.md | 2 +- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index d8e82503eb..400c0d9e15 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -307,7 +307,8 @@ fn params_contain_ambient_path(id: &str, params: &Value) -> bool { } fn profile_command_may_read_ambient(id: &str, params: &Value) -> bool { - if matches!(id, "color.profileMismatch" | "edit.colorSettings" | "view.proofSetup") { + // Installed profiles scan OS and user directories even without a request path. + if matches!(id, "color.profileMismatch" | "edit.colorSettings" | "edit.installedProfiles" | "view.proofSetup") { return true; } matches!(id, "edit.assignProfile" | "edit.convertToProfile" | "edit.profileInfo") @@ -752,6 +753,22 @@ mod tests { assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "interface.language", "value": "fr"})).is_ok()); } + #[test] + fn installed_profile_discovery_requires_filesystem_authority() { + for params in [serde_json::json!({}), serde_json::json!({"class": "output", "colorSpace": "cmyk"}), serde_json::json!({"path": "/outside/profile.icc"})] + { + assert!(authorize_engine_command("edit.installedProfiles", ¶ms).is_err()); + assert!(authorize_desktop_engine_command("edit.installedProfiles", ¶ms).is_err()); + assert!(authorize_engine_step("edit.installedProfiles", ¶ms).is_err()); + assert!(authorize_desktop_engine_step("edit.installedProfiles", ¶ms).is_err()); + } + // Built-in profiles remain usable without reading installed profile files. + for id in ["edit.assignProfile", "edit.convertToProfile", "edit.profileInfo"] { + assert!(authorize_engine_command(id, &serde_json::json!({"profile": "srgb"})).is_ok()); + assert!(authorize_desktop_engine_command(id, &serde_json::json!({"profile": "srgb"})).is_ok()); + } + } + #[test] fn registry_filesystem_path_params_are_classified() { let probe = serde_json::json!({ diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 87d1bbf65f..cf4a1159a3 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -145,7 +145,7 @@ automation permissions. UI-level commands (`view.zoomIn`, `window.theme.pro`, `edit.search`, …) are also accepted by `engine.execute` and `ui.menu.invoke`. -Commands that read or write files by path, instead of through the automation roots, are refused with "automation command `…` uses ambient filesystem paths and is disabled; use capability-scoped document methods". That covers every `file.*` command except `file.new`, the `file.close*` commands and a few path-free ones such as `file.fileInfo`, so `file.open`, `file.save`, `file.saveAs` and `file.saveACopy` always fail here: open and save with `app.open` / `app.save`. Path parameters of other commands (`layer.exportAs {path}`, `filter.distort.displace {mapPath}`, preset imports, and plug-in install/reload) are refused the same way. `prefs.set` rejects whole-preference updates and file-backed sections (`colorSettings`, `scriptEvents`, `historyLog`, `plugIns` and `scratchDisks`) so automation cannot configure ambient file access indirectly. The desktop app also refuses `image.mode.*`, which can load the colour profiles set in its preferences. The rules are in `crates/automation/src/workspace.rs`. +Commands that read or write files by path, instead of through the automation roots, are refused with "automation command `…` uses ambient filesystem paths and is disabled; use capability-scoped document methods". That covers every `file.*` command except `file.new`, the `file.close*` commands and a few path-free ones such as `file.fileInfo`, so `file.open`, `file.save`, `file.saveAs` and `file.saveACopy` always fail here: open and save with `app.open` / `app.save`. Path parameters of other commands (`layer.exportAs {path}`, `filter.distort.displace {mapPath}`, preset imports, and plug-in install/reload) are refused the same way. `prefs.set` rejects whole-preference updates and file-backed sections (`colorSettings`, `scriptEvents`, `historyLog`, `plugIns` and `scratchDisks`) so automation cannot configure ambient file access indirectly. `edit.installedProfiles` is also refused because it scans OS and user profile directories outside the automation roots, even without a request path. The desktop app also refuses `image.mode.*`, which can load the colour profiles set in its preferences. The rules are in `crates/automation/src/workspace.rs`. Embedded Smart Objects can be opened with `layer.smartObjects.editContents {layer?}` or unpacked with `layer.smartObjects.convertToLayers {layer?}`. This includes Photoshop sources From a33b7929a040541bd6725f417d7a5cad1f40c98b Mon Sep 17 00:00:00 2001 From: abc2cb <271337822+abc2cb@users.noreply.github.com> Date: Mon, 12 Oct 2026 08:10:47 +0300 Subject: [PATCH 05/54] Remove shared main repairs from Smart Filters feature scope --- Cargo.toml | 5 ----- crates/automation/src/workspace.rs | 19 +------------------ crates/engine/src/adjust_params.rs | 13 ++++--------- docs/control-protocol.md | 2 +- 4 files changed, 6 insertions(+), 33 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 36e608b71e..7502ff4fd5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -100,11 +100,6 @@ opt-level = "s" [profile.wasm-release.package.photocraft-ui-egui] opt-level = "z" -# Prefer compact command dispatch and parameter handling in the browser. Native profiles -# and the speed-oriented pixel-processing crates below keep their existing settings. -[profile.wasm-release.package.photocraft-engine] -opt-level = "z" - [profile.wasm-release.package.photocraft-raster] opt-level = 3 [profile.wasm-release.package.photocraft-color] diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 400c0d9e15..d8e82503eb 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -307,8 +307,7 @@ fn params_contain_ambient_path(id: &str, params: &Value) -> bool { } fn profile_command_may_read_ambient(id: &str, params: &Value) -> bool { - // Installed profiles scan OS and user directories even without a request path. - if matches!(id, "color.profileMismatch" | "edit.colorSettings" | "edit.installedProfiles" | "view.proofSetup") { + if matches!(id, "color.profileMismatch" | "edit.colorSettings" | "view.proofSetup") { return true; } matches!(id, "edit.assignProfile" | "edit.convertToProfile" | "edit.profileInfo") @@ -753,22 +752,6 @@ mod tests { assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "interface.language", "value": "fr"})).is_ok()); } - #[test] - fn installed_profile_discovery_requires_filesystem_authority() { - for params in [serde_json::json!({}), serde_json::json!({"class": "output", "colorSpace": "cmyk"}), serde_json::json!({"path": "/outside/profile.icc"})] - { - assert!(authorize_engine_command("edit.installedProfiles", ¶ms).is_err()); - assert!(authorize_desktop_engine_command("edit.installedProfiles", ¶ms).is_err()); - assert!(authorize_engine_step("edit.installedProfiles", ¶ms).is_err()); - assert!(authorize_desktop_engine_step("edit.installedProfiles", ¶ms).is_err()); - } - // Built-in profiles remain usable without reading installed profile files. - for id in ["edit.assignProfile", "edit.convertToProfile", "edit.profileInfo"] { - assert!(authorize_engine_command(id, &serde_json::json!({"profile": "srgb"})).is_ok()); - assert!(authorize_desktop_engine_command(id, &serde_json::json!({"profile": "srgb"})).is_ok()); - } - } - #[test] fn registry_filesystem_path_params_are_classified() { let probe = serde_json::json!({ diff --git a/crates/engine/src/adjust_params.rs b/crates/engine/src/adjust_params.rs index 8bc99a40bc..00fb67dd03 100644 --- a/crates/engine/src/adjust_params.rs +++ b/crates/engine/src/adjust_params.rs @@ -1240,12 +1240,9 @@ mod tests { #[test] fn destructive_levels_dont_clip_in_32_bit() { // Input 15..230, gamma 1.3, output 10..245: black and white land on the output range in - // integer documents. A 32-bit document evaluates the signed power curve beyond both - // ranges, retaining negative values and highlights above 1. The float expectations - // below were evaluated independently from the configured curve, not a clipped LUT. + // integer documents, but in a 32-bit document the curve runs on past it (then 0..1). let params = json!({"inBlack": 15, "inWhite": 230, "gamma": 1.3, "outBlack": 10, "outWhite": 245}); - for depth in [8, 16, 32] { - let (low, high, tolerance) = if depth == 32 { (-0.079_642_7, 1.042_158, 1e-6) } else { (10.0 / 255.0, 245.0 / 255.0, 0.6 / 255.0) }; + for (depth, low, high) in [(8, 10.0, 245.0), (16, 10.0, 245.0), (32, 0.0, 255.0)] { let mut s = crate::Session::new(); s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "white"})).unwrap(); s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 16})).unwrap(); @@ -1253,10 +1250,8 @@ mod tests { s.execute("select.deselect", json!({})).unwrap(); s.execute("image.adjustments.levels", params.clone()).unwrap(); let px = pixels(&s); - assert!((px[0][0] - low).abs() < tolerance, "black @{depth}: {:?}", px[0]); - assert!((px[1][0] - high).abs() < tolerance, "white @{depth}: {:?}", px[1]); - assert_eq!(px[0][3], 1.0, "Levels keeps alpha"); - assert_eq!(px[1][3], 1.0, "Levels keeps alpha"); + assert!((px[0][0] * 255.0 - low).abs() < 0.6, "black @{depth}: {:?}", px[0]); + assert!((px[1][0] * 255.0 - high).abs() < 0.6, "white @{depth}: {:?}", px[1]); } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index cf4a1159a3..87d1bbf65f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -145,7 +145,7 @@ automation permissions. UI-level commands (`view.zoomIn`, `window.theme.pro`, `edit.search`, …) are also accepted by `engine.execute` and `ui.menu.invoke`. -Commands that read or write files by path, instead of through the automation roots, are refused with "automation command `…` uses ambient filesystem paths and is disabled; use capability-scoped document methods". That covers every `file.*` command except `file.new`, the `file.close*` commands and a few path-free ones such as `file.fileInfo`, so `file.open`, `file.save`, `file.saveAs` and `file.saveACopy` always fail here: open and save with `app.open` / `app.save`. Path parameters of other commands (`layer.exportAs {path}`, `filter.distort.displace {mapPath}`, preset imports, and plug-in install/reload) are refused the same way. `prefs.set` rejects whole-preference updates and file-backed sections (`colorSettings`, `scriptEvents`, `historyLog`, `plugIns` and `scratchDisks`) so automation cannot configure ambient file access indirectly. `edit.installedProfiles` is also refused because it scans OS and user profile directories outside the automation roots, even without a request path. The desktop app also refuses `image.mode.*`, which can load the colour profiles set in its preferences. The rules are in `crates/automation/src/workspace.rs`. +Commands that read or write files by path, instead of through the automation roots, are refused with "automation command `…` uses ambient filesystem paths and is disabled; use capability-scoped document methods". That covers every `file.*` command except `file.new`, the `file.close*` commands and a few path-free ones such as `file.fileInfo`, so `file.open`, `file.save`, `file.saveAs` and `file.saveACopy` always fail here: open and save with `app.open` / `app.save`. Path parameters of other commands (`layer.exportAs {path}`, `filter.distort.displace {mapPath}`, preset imports, and plug-in install/reload) are refused the same way. `prefs.set` rejects whole-preference updates and file-backed sections (`colorSettings`, `scriptEvents`, `historyLog`, `plugIns` and `scratchDisks`) so automation cannot configure ambient file access indirectly. The desktop app also refuses `image.mode.*`, which can load the colour profiles set in its preferences. The rules are in `crates/automation/src/workspace.rs`. Embedded Smart Objects can be opened with `layer.smartObjects.editContents {layer?}` or unpacked with `layer.smartObjects.convertToLayers {layer?}`. This includes Photoshop sources From 8bc312ac59c59155be3d4aca896fb43f561d7668 Mon Sep 17 00:00:00 2001 From: abc2cb <271337822+abc2cb@users.noreply.github.com> Date: Tue, 13 Oct 2026 01:11:08 +0300 Subject: [PATCH 06/54] i18n: translate the Smart Filter editor strings in hu, tr and vi Main gained Hungarian, Turkish and Vietnamese catalogs after this branch was written, so every_tl_literal_is_translated fails on the merged tree. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/hu.tsv | 8 ++++++++ crates/ui-egui/src/i18n/tr.tsv | 8 ++++++++ crates/ui-egui/src/i18n/vi.tsv | 8 ++++++++ 3 files changed, 24 insertions(+) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e0eff7b8a7..a0843549db 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3972,3 +3972,11 @@ cameraRaw Yellow Sárga Transform On Drop Átalakítás elengedéskor Vanishing Point is not active Az Enyészpont nem aktív Vanishing Point: click four corners to create a plane Enyészpont: sík létrehozásához kattintson a négy sarokra + +# Layers panel options and Smart Filter editors + Blending Options ({filter}) Keverési beállítások ({filter}) + Hide the layer's effects and Smart Filters ({key}-click: all layers) A réteg effektusainak és intelligens szűrőinek elrejtése ({key}+kattintás: minden réteg) + Opacity must be between 0% and 100%. Az átlátszatlanságnak 0% és 100% között kell lennie. + Show the layer's effects and Smart Filters ({key}-click: all layers) A réteg effektusainak és intelligens szűrőinek megjelenítése ({key}+kattintás: minden réteg) + The document or Smart Filter changed. Reopen its dialog. A dokumentum vagy az intelligens szűrő megváltozott. Nyissa meg újra a párbeszédablakát. + Wait for the current job to finish. Várja meg, amíg az aktuális feladat befejeződik. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 8401f8e5ac..48aac2cdf7 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3784,3 +3784,11 @@ cameraData Lens Lens @plural {n} step|{n} steps {n} adım @plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (+{n} fırça ön ayarı uyarısı daha) @plural {what} with {n} warning|{what} with {n} warnings {what}, {n} uyarı ile + +# Layers panel options and Smart Filter editors + Blending Options ({filter}) Karışım Seçenekleri ({filter}) + Hide the layer's effects and Smart Filters ({key}-click: all layers) Katmanın efektlerini ve Akıllı Filtrelerini gizle ({key}-tık: tüm katmanlar) + Opacity must be between 0% and 100%. Opaklık %0 ile %100 arasında olmalıdır. + Show the layer's effects and Smart Filters ({key}-click: all layers) Katmanın efektlerini ve Akıllı Filtrelerini göster ({key}-tık: tüm katmanlar) + The document or Smart Filter changed. Reopen its dialog. Belge veya Akıllı Filtre değişti. İletişim kutusunu yeniden açın. + Wait for the current job to finish. Geçerli işin bitmesini bekleyin. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f7cd59aebb..9394c4238d 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3536,3 +3536,11 @@ curves Smooth Làm mượt Remove after each stroke Xóa sau mỗi nét vẽ Apply the removal ({key}) Áp dụng việc xóa ({key}) Strokes to remove: {n} (Enter applies, Esc cancels) Nét vẽ cần xóa: {n} (Enter áp dụng, Esc hủy) + +# Layers panel options and Smart Filter editors + Blending Options ({filter}) Tùy chọn hòa trộn ({filter}) + Hide the layer's effects and Smart Filters ({key}-click: all layers) Ẩn hiệu ứng và bộ lọc thông minh của lớp ({key}-bấm: tất cả các lớp) + Opacity must be between 0% and 100%. Độ mờ phải nằm trong khoảng từ 0% đến 100%. + Show the layer's effects and Smart Filters ({key}-click: all layers) Hiện hiệu ứng và bộ lọc thông minh của lớp ({key}-bấm: tất cả các lớp) + The document or Smart Filter changed. Reopen its dialog. Tài liệu hoặc bộ lọc thông minh đã thay đổi. Hãy mở lại hộp thoại của nó. + Wait for the current job to finish. Hãy chờ tác vụ hiện tại hoàn tất. From 6d37936db37f45aa884c6a9cc1186f1a2bfe7c93 Mon Sep 17 00:00:00 2001 From: abc2cb <271337822+abc2cb@users.noreply.github.com> Date: Tue, 13 Oct 2026 19:51:50 +0300 Subject: [PATCH 07/54] i18n(sr): translate this PR's strings in the new Serbian catalog Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/sr.tsv | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 72c6b4bee7..f5487f55ab 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4202,3 +4202,11 @@ shape Appearance Izgled Color Indicates: Boja označava: Ink Characteristics Karakteristike mastila Solidity: Punoća: + +# Smart Filter editors + Blending Options ({filter}) Opcije stapanja ({filter}) + Hide the layer's effects and Smart Filters ({key}-click: all layers) Sakrij efekte i pametne filtere sloja ({key}-klik: svi slojevi) + Opacity must be between 0% and 100%. Neprozirnost mora biti između 0% i 100%. + Show the layer's effects and Smart Filters ({key}-click: all layers) Prikaži efekte i pametne filtere sloja ({key}-klik: svi slojevi) + The document or Smart Filter changed. Reopen its dialog. Dokument ili pametni filter se promenio. Ponovo otvorite njegov dijalog. + Wait for the current job to finish. Sačekajte da se trenutni posao završi. From 0e009c246f4e797e1beaf47ad6c388f4a7580993 Mon Sep 17 00:00:00 2001 From: abc2cb <271337822+abc2cb@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:34:47 +0000 Subject: [PATCH 08/54] Name layerFilter in the ui_set tool description main's UI_SET_FIELDS gained layerFilter (#5268) but the ui_set description did not, so ui_set_description_names_every_accepted_field fails on ubuntu. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01F8jU8SSgnSWm5L17agT9ZT (cherry picked from commit 1d1cb4e4620a4c239d5c17e3d23a68fc4ba50982) --- crates/automation/src/server.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index c5a0c3b180..be0764e6d9 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -325,7 +325,9 @@ pub struct UiSetParams { /// dashes, dashOffset and opacity; null disables the stroke). Shape stroke fields use /// `shape.edit` names and units; colour comes from `tools.setColors`. camTransformOnDrop (bool, /// the Content-Aware Move tool's Transform On Drop). tileGrid (bool, a developer overlay of the - /// active layer's storage tiles). Other fields are an error. + /// active layer's storage tiles). layerFilter (an object patching by (kind, name, mode), kinds + /// (a list of pixel, adjustment, type, shape, smart), name and mode, the Layers panel's filter). + /// Other fields are an error. pub fields: Value, } From eae5eecab5577867e625948283a1c8a43119f2e6 Mon Sep 17 00:00:00 2001 From: abc2cb <271337822+abc2cb@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:59:13 +0300 Subject: [PATCH 09/54] Smart filter preview: don't scale the placement and mask twice Main's proxy_document now scales a smart object's placement, perspective and filter mask with the proxy (#5779). The smart-edit preview still did it again, so a reduced preview drew the object and its mask at a quarter size (reduced_preview_scales_placement_stack_and_mask_without_adding_filters). Only the filter lengths and the mask's feather are left to scale here. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/filter_dialog.rs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rs index 018eaa21cf..08cab91741 100644 --- a/crates/ui-egui/src/filter_dialog.rs +++ b/crates/ui-egui/src/filter_dialog.rs @@ -904,18 +904,10 @@ pub(crate) fn preview_document_for_target( 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. + // Proxy_document scales the cache, placement and shared mask (#5766). Editing a filter + // re-renders its source: scale every filter's lengths and the mask's feather 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 { From 21970407993f1abdd20c8bdbd1492eaab51cafb5 Mon Sep 17 00:00:00 2001 From: abc2cb <271337822+abc2cb@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:17:36 +0300 Subject: [PATCH 10/54] Filter preview: main's view-capped factor follows the whole smart filter stack The merge with main kept both factor lines in ensure_filter_preview, and the second (main's filter_preview_factor, #6351) shadowed smart_preview_factor, so a smart filter edit was sized by the edited command alone again. The shared filter_preview_factor now starts from smart_preview_factor, which falls back to preview_factor for ordinary filters, and caps that by the view as before. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f29d6c6509..55e7979a37 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1737,7 +1737,8 @@ fn budget_allowance(app: &PhotocraftApp) -> (u64, u64) { /// [`crate::filter_dialog::FilterPreviewKey`] under a finished preview and recompute it inline, /// the very stall this avoids. pub(crate) fn filter_preview_factor(app: &PhotocraftApp, doc: &Document, cmd: &str, params: &serde_json::Value) -> u32 { - let k = crate::filter_dialog::preview_factor(cmd, params, crate::proxy::preview_factor(doc, crate::proxy::reduced_previews(app))); + // A smart filter edit re-renders the whole stack: every stage constrains the factor. + let k = crate::filter_dialog::smart_preview_factor(doc, cmd, params, crate::proxy::preview_factor(doc, crate::proxy::reduced_previews(app))); if cfg!(target_arch = "wasm32") { k } else { crate::proxy::view_factor(k, app.current_zoom()) } } @@ -1776,8 +1777,6 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e params = crate::select_mask_view::request_params(&d.fields, params); } 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::smart_preview_factor(&st.doc, &cmd, ¶ms, crate::proxy::preview_factor(&st.doc, crate::proxy::reduced_previews(app))); let k = filter_preview_factor(app, &st.doc, &cmd, ¶ms); let request = crate::filter_dialog::FilterPreviewKey { doc: st.doc.id, From 2430664dd3e407b53f8ca6cd61a73ab007c95d42 Mon Sep 17 00:00:00 2001 From: abc2cb <271337822+abc2cb@users.noreply.github.com> Date: Sat, 17 Oct 2026 17:01:16 +0300 Subject: [PATCH 11/54] Smart Filters: note under Mode when Dissolve is selected Dissolve in Smart Filter blending follows the inherited color-blending path without per-pixel coverage sampling (docs/smart-filters.md). Show a short faint note under the Mode control in Blending Options when Dissolve is chosen, so the limitation is visible where the mode is picked. No behaviour change. The note is added to all 20 catalogs. The test renders the dialog body for every layer blend mode and checks that only Dissolve paints the note. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sr.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/smart_filter_dialog.rs | 8 +++++ .../ui-egui/src/smart_filter_dialog/tests.rs | 35 +++++++++++++++++++ 22 files changed, 63 insertions(+) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index f16a4e56ad..b363cd2a0d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2649,6 +2649,7 @@ cameraData Lens Objektiv 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%. + Dissolve is approximated: it blends without Photoshop's dither. Režim Rozpustit je pouze aproximován: prolíná bez ditheringu Photoshopu. # Dynamic labels the tl! literal scanner cannot see: filter and Filter Gallery parameter names and # choices (humanized from their keys), Camera Raw controls, render filters (Flame, Picture Frame, Tree), diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 05fb3d2d18..63cce37694 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2683,6 +2683,7 @@ cameraData Lens Objektiv 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. + Dissolve is approximated: it blends without Photoshop's dither. Sprenkeln wird nur angenähert: Es wird ohne das Dithering von Photoshop gemischt. Loading fonts… Schriften werden geladen… Response curve Reaktionskurve diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index ae57871745..32f815459e 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3739,6 +3739,7 @@ cameraData Lens Φακός 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%. + Dissolve is approximated: it blends without Photoshop's dither. Η Διάλυση προσεγγίζεται: η ανάμειξη γίνεται χωρίς το dither του Photoshop. Loading fonts… Φόρτωση γραμματοσειρών… Response curve Καμπύλη απόκρισης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 42c0472953..7e32c1164a 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2725,6 +2725,7 @@ cameraData Lens Objetivo 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%. + Dissolve is approximated: it blends without Photoshop's dither. Disolver es aproximado: se fusiona sin el tramado de Photoshop. Loading fonts… Cargando fuentes… Response curve Curva de respuesta diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index eb27bbdd4e..99b58f9dce 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3059,6 +3059,7 @@ cameraData Lens Objectif 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%. + Dissolve is approximated: it blends without Photoshop's dither. Le mode Fondu est approximé : il fusionne sans le tramage de Photoshop. Loading fonts… Chargement des polices… Response curve Courbe de réponse diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f3b8cd861..9d13417b26 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4112,6 +4112,7 @@ cameraRaw Yellow Sárga Blending Options ({filter}) Keverési beállítások ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) A réteg effektusainak és intelligens szűrőinek elrejtése ({key}+kattintás: minden réteg) Opacity must be between 0% and 100%. Az átlátszatlanságnak 0% és 100% között kell lennie. + Dissolve is approximated: it blends without Photoshop's dither. A Szétszórás csak közelítés: a Photoshop raszterezése nélkül keveredik. Show the layer's effects and Smart Filters ({key}-click: all layers) A réteg effektusainak és intelligens szűrőinek megjelenítése ({key}+kattintás: minden réteg) The document or Smart Filter changed. Reopen its dialog. A dokumentum vagy az intelligens szűrő megváltozott. Nyisd meg újra a párbeszédablakát. Wait for the current job to finish. Várd meg, amíg az aktuális feladat befejeződik. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index b330f96227..65128a63e0 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3046,6 +3046,7 @@ cameraData Lens Lensa 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%. + Dissolve is approximated: it blends without Photoshop's dither. Dissolve hanya didekati: pencampuran berjalan tanpa dither Photoshop. Loading fonts… Memuat font… Response curve Kurva respons diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b9935c70b9..47e1aa0d50 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2713,6 +2713,7 @@ cameraData Lens Obiettivo 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%. + Dissolve is approximated: it blends without Photoshop's dither. Dissolvi è approssimato: la fusione avviene senza il dither di Photoshop. Loading fonts… Caricamento font… Response curve Curva di risposta diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index e1767912fb..73d988bd79 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3654,6 +3654,7 @@ cameraData Lens レンズ 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%の範囲で指定してください。 + Dissolve is approximated: it blends without Photoshop's dither. ディザ合成は近似です。Photoshop のディザなしでブレンドします。 Loading fonts… フォントを読み込み中… Response curve 応答カーブ diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 5e0ac90aa1..8627b889c1 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3227,6 +3227,7 @@ cameraData Lens 렌즈 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% 사이여야 합니다. + Dissolve is approximated: it blends without Photoshop's dither. 디졸브는 근사치입니다. Photoshop의 디더링 없이 혼합됩니다. Loading fonts… 글꼴 불러오는 중… Response curve 응답 곡선 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d02b977e12..d446b92f49 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3798,6 +3798,7 @@ cameraData Lens Lens 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. + Dissolve is approximated: it blends without Photoshop's dither. Verspreiden is benaderd: het mengt zonder de dither van Photoshop. Loading fonts… Lettertypen laden… Response curve Responscurve diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 86518395b0..51170d6c74 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3656,6 +3656,7 @@ cameraData Lens Obiektyw 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%. + Dissolve is approximated: it blends without Photoshop's dither. Rozpuszczanie jest przybliżone: miesza się bez ditheringu Photoshopa. Loading fonts… Wczytywanie czcionek… Response curve Krzywa odpowiedzi diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 296520f723..cfc7a5dd6b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3062,6 +3062,7 @@ cameraData Lens Lente 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%. + Dissolve is approximated: it blends without Photoshop's dither. Dissolver é aproximado: a mesclagem ocorre sem o dither do Photoshop. Loading fonts… Carregando fontes… Response curve Curva de resposta diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 69aa764698..35ec3e2c1a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2983,6 +2983,7 @@ cameraData Lens Объектив 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%. + Dissolve is approximated: it blends without Photoshop's dither. Растворение приближённое: смешивание без дизеринга Photoshop. Loading fonts… Загрузка шрифтов… Response curve Кривая отклика diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 48d43c0c9e..f00a538142 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4266,6 +4266,7 @@ shape Appearance Izgled Blending Options ({filter}) Opcije stapanja ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Sakrij efekte i pametne filtere sloja ({key}-klik: svi slojevi) Opacity must be between 0% and 100%. Neprozirnost mora biti između 0% i 100%. + Dissolve is approximated: it blends without Photoshop's dither. Rastapanje je približno: mešanje se vrši bez diteringa programa Photoshop. Show the layer's effects and Smart Filters ({key}-click: all layers) Prikaži efekte i pametne filtere sloja ({key}-klik: svi slojevi) The document or Smart Filter changed. Reopen its dialog. Dokument ili pametni filter se promenio. Ponovo otvorite njegov dijalog. Wait for the current job to finish. Sačekajte da se trenutni posao završi. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 2233e90ddd..e95a0e5e76 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3923,6 +3923,7 @@ cameraData Lens Lens Blending Options ({filter}) Karışım Seçenekleri ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Katmanın efektlerini ve Akıllı Filtrelerini gizle ({key}-tık: tüm katmanlar) Opacity must be between 0% and 100%. Opaklık %0 ile %100 arasında olmalıdır. + Dissolve is approximated: it blends without Photoshop's dither. Eritme yaklaşık olarak uygulanır: Photoshop'un dither'ı olmadan karıştırır. Show the layer's effects and Smart Filters ({key}-click: all layers) Katmanın efektlerini ve Akıllı Filtrelerini göster ({key}-tık: tüm katmanlar) The document or Smart Filter changed. Reopen its dialog. Belge veya Akıllı Filtre değişti. İletişim kutusunu yeniden açın. Wait for the current job to finish. Geçerli işin bitmesini bekleyin. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 759077cdd0..dc086f98d5 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3730,6 +3730,7 @@ cameraData Lens Об'єктив 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%. + Dissolve is approximated: it blends without Photoshop's dither. Розчинення наближене: змішування без дизерингу Photoshop. Loading fonts… Завантаження шрифтів… Response curve Крива відгуку diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 0c072faa7f..36379d5155 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3679,6 +3679,7 @@ curves Smooth Làm mượt Blending Options ({filter}) Tùy chọn hòa trộn ({filter}) Hide the layer's effects and Smart Filters ({key}-click: all layers) Ẩn hiệu ứng và bộ lọc thông minh của lớp ({key}-bấm: tất cả các lớp) Opacity must be between 0% and 100%. Độ mờ phải nằm trong khoảng từ 0% đến 100%. + Dissolve is approximated: it blends without Photoshop's dither. Hoà tan chỉ được mô phỏng gần đúng: hòa trộn không có dither của Photoshop. Show the layer's effects and Smart Filters ({key}-click: all layers) Hiện hiệu ứng và bộ lọc thông minh của lớp ({key}-bấm: tất cả các lớp) The document or Smart Filter changed. Reopen its dialog. Tài liệu hoặc bộ lọc thông minh đã thay đổi. Hãy mở lại hộp thoại của nó. Wait for the current job to finish. Hãy chờ tác vụ hiện tại hoàn tất. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 8475e4172d..57631d3c44 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2655,6 +2655,7 @@ cameraData Lens 镜头 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% 之间。 + Dissolve is approximated: it blends without Photoshop's dither. “溶解”为近似效果:混合时没有 Photoshop 的抖动。 Loading fonts… 正在加载字体… Response curve 响应曲线 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 96206e13b2..0ddbfbab23 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2625,6 +2625,7 @@ cameraData Lens 鏡頭 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% 之間。 + Dissolve is approximated: it blends without Photoshop's dither. 「溶解」為近似效果:混合時沒有 Photoshop 的仿色。 Loading fonts… 正在載入字體… Response curve 回應曲線 diff --git a/crates/ui-egui/src/smart_filter_dialog.rs b/crates/ui-egui/src/smart_filter_dialog.rs index b8db816939..d510ed74c5 100644 --- a/crates/ui-egui/src/smart_filter_dialog.rs +++ b/crates/ui-egui/src/smart_filter_dialog.rs @@ -130,6 +130,11 @@ pub(crate) fn edit_command(app: &PhotocraftApp, fields: &Map) -> } } +/// Dissolve has no per-pixel coverage sampling in Smart Filter blending yet (docs/smart-filters.md). +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.")) +} + pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map) { ui.horizontal(|ui| { ui.label(tl!("Mode")); @@ -139,6 +144,9 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map) -> Vec { + fn collect(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Text(text) => out.push(text.galley.job.text.clone()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| collect(s, out)), + _ => {} + } + } + 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, 640.0))), ..Default::default() }; + let mut output = ctx.run_ui(input, |ui| super::body(app, ui, fields)); + output.textures_delta.clear(); + let mut painted = Vec::new(); + output.shapes.iter().for_each(|s| collect(&s.shape, &mut painted)); + painted +} + +#[test] +fn only_dissolve_shows_the_approximation_note_near_the_mode_control() { + let note = "Dissolve is approximated: it blends without Photoshop's dither."; + 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(); + for blend in BlendMode::LAYER_MODES { + fields.insert("blend".into(), json!(blend.label())); + let painted = painted_text(&mut app, &mut fields); + assert!(painted.iter().any(|s| s == "Mode"), "the Mode control paints for {}", blend.label()); + assert_eq!(painted.iter().any(|s| s == note), blend == BlendMode::Dissolve, "note for {}", blend.label()); + } + assert_eq!(mode_note(None), None); + assert_eq!(mode_note(Some("Normal")), None); + assert_eq!(mode_note(Some("Dissolve")), Some(note)); +} + 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(); From f7942efd1d6869a9c788799108a2d348201bc61a Mon Sep 17 00:00:00 2001 From: abc2cb <271337822+abc2cb@users.noreply.github.com> Date: Sun, 18 Oct 2026 17:49:38 +0300 Subject: [PATCH 12/54] Smart Filter editor starts missing parameters from the spec defaults open_editor opened the filter's dialog and copied the recorded parameters over its fields. filter_dialog::open starts from the user's last-used values, so a recorded filter that lacked a key (an older file, or a command that gained a parameter) showed, and on OK saved, the remembered value instead of the default. Reset the freshly opened filter dialog to the schema defaults, as Alt+Cancel does, before the recorded parameters are copied in. Adjustment editors are unchanged, and a plain Filter menu dialog still remembers. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/smart_ui.rs | 12 +++++++--- crates/ui-egui/src/smart_ui/editor_tests.rs | 26 +++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/smart_ui.rs b/crates/ui-egui/src/smart_ui.rs index 6ce5f9c7fe..2cd61a3000 100644 --- a/crates/ui-egui/src/smart_ui.rs +++ b/crates/ui-egui/src/smart_ui.rs @@ -356,9 +356,15 @@ pub fn open_editor(app: &mut PhotocraftApp, ctx: &egui::Context, layer: u64, sm: 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 { + let Some(id) = crate::adjust_dialog::open(app, &f.command).or_else(|| { + let id = crate::filter_dialog::has_dialog(&f.command).then(|| crate::filter_dialog::open(app, &f.command)).flatten()?; + // The filter dialog opens on the user's last-used values; a recorded filter that lacks a + // key must show (and save) the schema default instead. + let mut fields = app.ui.dialog_mut(id)?.fields.clone(); + crate::filter_dialog::reset_fields(app, &mut fields); + app.ui.dialog_mut(id)?.fields = fields; + Some(id) + }) else { return; }; if let Some(d) = app.ui.dialog_mut(id) { diff --git a/crates/ui-egui/src/smart_ui/editor_tests.rs b/crates/ui-egui/src/smart_ui/editor_tests.rs index c007b2ca6b..c5814b8d17 100644 --- a/crates/ui-egui/src/smart_ui/editor_tests.rs +++ b/crates/ui-egui/src/smart_ui/editor_tests.rs @@ -152,3 +152,29 @@ fn ctrl_i_uses_existing_invert_command_and_undo_redo_keep_the_source() { h.state_mut().run("edit.redo", json!({})).unwrap(); assert_eq!(smart(h.state(), layer).smart_filters.len(), 3); } + +/// A recorded filter that lacks a parameter reopens with the schema default for it, not with the +/// value the user last used in that filter's dialog; the parameters it does hold still win. +#[test] +fn filter_editor_starts_missing_parameters_from_defaults_not_remembered_values() { + let (mut app, layer) = app(8, "rgb"); + let command = "filter.sharpen.smartSharpen"; + app.session.prefs.edit(|p| { + p.dialogs.insert(command.into(), json!({"reduceNoise": 60, "radius": 9})); + }); + let ctx = egui::Context::default(); + let mut sm = smart(&app, layer).clone(); + let index = sm.smart_filters.iter().position(|f| f.command == command).unwrap(); + sm.smart_filters[index].params = json!({"amount": 125, "radius": 2}); + + super::open_editor(&mut app, &ctx, layer.0, &sm, index); + let fields = &app.ui.dialogs.last().unwrap().fields; + assert!(fields.contains_key("__smartFilter"), "it edits the recorded filter"); + assert_eq!(fields["reduceNoise"].as_f64(), Some(10.0), "the spec default, not the remembered 60"); + assert_eq!(fields["amount"].as_f64(), Some(125.0)); + assert_eq!(fields["radius"].as_f64(), Some(2.0), "recorded values beat the remembered 9"); + + // A plain Filter menu dialog still starts from the remembered values. + let id = crate::filter_dialog::open(&mut app, command).unwrap(); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields["reduceNoise"].as_f64(), Some(60.0)); +} From 79793acefe6002b4a0d6dd512725f2612bb85438 Mon Sep 17 00:00:00 2001 From: abc2cb <271337822+abc2cb@users.noreply.github.com> Date: Sun, 18 Oct 2026 17:50:28 +0300 Subject: [PATCH 13/54] Smart Filters: document the functions and tests the PR adds CodeRabbit measured the docstring coverage of the PR at 59.49%, under its 80% threshold. Add short doc comments saying what each helper does and which behaviour each test pins. Comments only; no code changes. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/fx_view_cmds.rs | 2 ++ crates/engine/src/smart_cmds/tests.rs | 2 ++ crates/engine/tests/photoshop_oracles.rs | 1 + crates/ui-egui/src/filter_dialog.rs | 2 ++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/smart_filter_dialog.rs | 10 ++++++++++ crates/ui-egui/src/smart_filter_dialog/tests.rs | 16 ++++++++++++++++ crates/ui-egui/src/smart_ui.rs | 1 + crates/ui-egui/src/smart_ui/editor_tests.rs | 7 +++++++ 9 files changed, 42 insertions(+) diff --git a/crates/engine/src/fx_view_cmds.rs b/crates/engine/src/fx_view_cmds.rs index 0d68230ba5..76bbc781ee 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.rs index b7a282698d..3666a4818c 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.rs index e07b451efc..1b3e37d3e9 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 { 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.rs index 4ba1774b52..74d8bd9de6 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: &Value factor } +/// 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.rs index 6f0e11f7ce..584d0928df 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.rs index d510ed74c5..cf184c5671 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) -> Result { 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) -> 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 { 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 Result { 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<(La Ok((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 { 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) -> 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 { 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) -> Result { 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) -> 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) { 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, 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.rs index 6e1ce5708e..b3fb099d60 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) -> Vec { + /// Gather the text of `shape`, descending into nested shape groups. fn collect(shape: &egui::Shape, out: &mut Vec) { 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) -> Vec painted } +/// 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 { 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.rs index 2cd61a3000..1d8e6d68ce 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.rs index c5814b8d17..6e0b9d14f8 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<'s h } +/// 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()); From 25b79243f1ea2f7f4100fdb91c331ca7f2225f66 Mon Sep 17 00:00:00 2001 From: abc2cb <271337822+abc2cb@users.noreply.github.com> Date: Sun, 18 Oct 2026 17:54:43 +0300 Subject: [PATCH 14/54] Smart Filters: document the functions next to the ones the PR changes CodeRabbit counts the functions around the lines a PR changes, not only the changed ones, so the PR's docstring coverage stays low (59.49%, threshold 80%) unless the untouched neighbours are documented too. Comments only; no code changes. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/fx_view_cmds.rs | 6 ++++++ crates/engine/src/smart_cmds/tests.rs | 1 + crates/engine/tests/photoshop_oracles.rs | 1 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/smart_ui.rs | 1 + 5 files changed, 10 insertions(+) diff --git a/crates/engine/src/fx_view_cmds.rs b/crates/engine/src/fx_view_cmds.rs index 76bbc781ee..af550a367b 100644 --- a/crates/engine/src/fx_view_cmds.rs +++ b/crates/engine/src/fx_view_cmds.rs @@ -10,10 +10,12 @@ use crate::{EngineError, Result, Session}; const ID: &str = "layer.setEffectsExpanded"; +/// A `layer.setEffectsExpanded` parameter error. fn bad(msg: impl Into) -> EngineError { EngineError::BadParams { cmd: ID.into(), msg: msg.into() } } +/// The command is available while some layer has effects or Smart Filters to disclose. 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)| has_children(l)) { Ok(()) } else { Err("no layer has effects or smart filters".into()) } @@ -24,6 +26,7 @@ fn has_children(l: &Layer) -> bool { !l.effects.items.is_empty() || matches!(&l.content, LayerContent::Smart(sm) if !sm.smart_filters.is_empty()) } +/// An optional boolean param: `None` when absent or null, an error when it is anything but true or false. fn opt_bool(p: &Value, key: &str) -> Result> { match p.get(key) { None | Some(Value::Null) => Ok(None), @@ -64,6 +67,7 @@ fn set_expanded(s: &mut Session, p: &Value) -> Result { Ok(json!({"expanded": expanded, "layers": targets.len()})) } +/// Register `layer.setEffectsExpanded`: view state, so it is not journaled and adds no undo step. pub fn specs() -> Vec { vec![CommandSpec { id: ID, @@ -93,6 +97,7 @@ mod tests { (s, a, b) } + /// Whether the layer's effects list is shown, i.e. it is not in the document's collapsed set. fn open(s: &Session, id: u64) -> bool { !s.active().unwrap().fx_collapsed.contains(&LayerId(id)) } @@ -120,6 +125,7 @@ mod tests { assert!(s.active().unwrap().fx_collapsed.is_empty()); } + /// Toggling one layer or all of them flips only the disclosure state: no history step, no duplicates, and the document stays clean. #[test] fn toggles_one_layer_or_all_without_history() { let (mut s, a, b) = session(); diff --git a/crates/engine/src/smart_cmds/tests.rs b/crates/engine/src/smart_cmds/tests.rs index 3666a4818c..f955a21ee5 100644 --- a/crates/engine/src/smart_cmds/tests.rs +++ b/crates/engine/src/smart_cmds/tests.rs @@ -77,6 +77,7 @@ fn non_normal_coverage_changes_retain_source_over_semantics() { } } +/// A `depth`-bit document with one empty layer. 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/engine/tests/photoshop_oracles.rs b/crates/engine/tests/photoshop_oracles.rs index 1b3e37d3e9..b1f0a133a1 100644 --- a/crates/engine/tests/photoshop_oracles.rs +++ b/crates/engine/tests/photoshop_oracles.rs @@ -93,6 +93,7 @@ fn screen_motion_blur_retains_input_coverage() { assert!(error <= PASS_TOL, "Screen/Motion Blur error {error}, {bad}% pixels exceed 2/255"); } +/// Re-render every Photoshop oracle in the corpus with PhotoCraft's filters and compare it with Photoshop's own merged composite. #[test] fn photoshop_oracles_rerendered() { let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/photoshop"); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 584d0928df..893401ba85 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2330,6 +2330,7 @@ impl PhotocraftApp { id } + /// The cached thumbnail of `mask`, the layer mask of layer `id`. 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) } diff --git a/crates/ui-egui/src/smart_ui.rs b/crates/ui-egui/src/smart_ui.rs index 1d8e6d68ce..8afc3578ea 100644 --- a/crates/ui-egui/src/smart_ui.rs +++ b/crates/ui-egui/src/smart_ui.rs @@ -206,6 +206,7 @@ pub fn filter_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, doc: &Document, l /// Filters row, all of them). Also what a click selects. pub(crate) type FilterDrag = (u64, Option); +/// Memory key of the smart filter row being dragged. pub(crate) fn drag_key() -> egui::Id { egui::Id::new("smart-filter-drag") } From 17f149e73c3e1ef5a288294c2f37195f0b71bfd0 Mon Sep 17 00:00:00 2001 From: abc2cb <271337822+abc2cb@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:14:11 +0300 Subject: [PATCH 15/54] Smart Filters: one command builder for OK, mask thumbnails keyed by size - smart_ui.rs: confirm_command sends every Smart Filter edit through smart_filter_dialog::edit_command, the builder the canvas preview already uses, so preview and OK cannot build different payloads. - lib.rs: the mask thumbnail cache revision includes the document height as well as the width. Two documents that restore the same layer id and width no longer share a thumbnail framed for the other's height. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 4 ++-- crates/ui-egui/src/smart_ui.rs | 11 +++-------- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bac2d588e6..7297dde8f8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2475,7 +2475,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. + /// The thumbnail of `mask` under cache `kind`, re-rendered only when the mask's pixels or the document size change; Smart Filter and layer masks are cached apart. pub(crate) fn mask_thumb_kind( &mut self, ctx: &egui::Context, @@ -2484,7 +2484,7 @@ impl PhotocraftApp { mask: &photocraft_doc::LayerMask, kind: u8, ) -> egui::TextureId { - let rev = surface_fingerprint(&mask.surface) ^ (doc.size.width as u64) << 40; + let rev = surface_fingerprint(&mask.surface) ^ (doc.size.width as u64) << 40 ^ (doc.size.height as u64) << 16; let key = (id, kind); if let Some((r, tex)) = self.thumbs.get(&key) && *r == rev diff --git a/crates/ui-egui/src/smart_ui.rs b/crates/ui-egui/src/smart_ui.rs index f924323b7d..65dbc45b73 100644 --- a/crates/ui-egui/src/smart_ui.rs +++ b/crates/ui-egui/src/smart_ui.rs @@ -396,16 +396,11 @@ pub fn preview_command<'a>(fields: &serde_json::Map, command: &'a /// The command a confirmed filter dialog runs: smart-filter edits update the recorded filter. pub fn confirm_command(app: &PhotocraftApp, fields: &serde_json::Map, command: String, params: Value) -> Result<(String, Value), String> { - if crate::smart_filter_dialog::owns(fields) { + // One builder for the preview and for OK, so the two cannot differ. + if fields.contains_key("__smartFilter") { return crate::smart_filter_dialog::edit_command(app, fields); } - match fields.get("__smartFilter") { - 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)), - } + Ok((command, params)) } #[cfg(test)] From e07d293d5b5c751fecb9d872721a152fbe75202a Mon Sep 17 00:00:00 2001 From: abc2cb <271337822+abc2cb@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:29:46 +0300 Subject: [PATCH 16/54] Mask thumbnail test: expect the key to include the document height 17f149e7 keys mask thumbnails on the document height as well as the width; main's #2117 test still computed the old width-only key. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/mask_thumb_refresh_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/mask_thumb_refresh_tests.rs b/crates/ui-egui/src/mask_thumb_refresh_tests.rs index 4987501ad0..3f486708e0 100644 --- a/crates/ui-egui/src/mask_thumb_refresh_tests.rs +++ b/crates/ui-egui/src/mask_thumb_refresh_tests.rs @@ -45,5 +45,5 @@ fn inverting_a_tileless_mask_refreshes_its_thumbnail() { assert_eq!(mask.surface.default_pixel(), vec![0.0], "and now hides everything"); let after = h.state().thumbs.get(&key).map(|(r, _)| *r).expect("mask thumbnail drawn"); assert_ne!(before, after, "the thumbnail was rebuilt after Invert"); - assert_eq!(after, surface_fingerprint(&mask.surface) ^ 200u64 << 40, "keyed on the inverted mask"); + assert_eq!(after, surface_fingerprint(&mask.surface) ^ 200u64 << 40 ^ 100u64 << 16, "keyed on the inverted mask and the document size"); } From 08fa0ed4fbc832b87d30df1f1434860265996fc3 Mon Sep 17 00:00:00 2001 From: abc2cb <271337822+abc2cb@users.noreply.github.com> Date: Thu, 22 Oct 2026 01:13:10 +0300 Subject: [PATCH 17/54] Smart Filters: keep main's thumbnail scaling tests test-only The merge of main kept `#[cfg(test)]` on `mod editor_tests;` only, so `layer_thumbnail_scaling_tests` (which uses the dev-only egui_kittest) was compiled into normal builds. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/smart_ui.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/smart_ui.rs b/crates/ui-egui/src/smart_ui.rs index d7136dfd7b..edb4e84b29 100644 --- a/crates/ui-egui/src/smart_ui.rs +++ b/crates/ui-egui/src/smart_ui.rs @@ -426,6 +426,7 @@ pub fn confirm_command(app: &PhotocraftApp, fields: &serde_json::Map Date: Wed, 21 Oct 2026 20:11:03 -0400 Subject: [PATCH 18/54] security: enforce HTTPS on curl downloads (SonarCloud S6506) (#8369) Add --proto '=https' to curl invocations so redirects cannot downgrade to plaintext HTTP. Resolves SonarCloud S6506 (shell/docker/githubactions). --- .github/workflows/ci.yml | 2 +- Dockerfile | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 238029a860..d2ef8943dd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -361,7 +361,7 @@ jobs: cache-on-failure: true - name: Install trunk run: | - curl -fsSL "https://github.com/trunk-rs/trunk/releases/download/v${TRUNK_VERSION}/trunk-x86_64-unknown-linux-gnu.tar.gz" \ + curl --proto '=https' -fsSL "https://github.com/trunk-rs/trunk/releases/download/v${TRUNK_VERSION}/trunk-x86_64-unknown-linux-gnu.tar.gz" \ | tar -xz -C "$HOME/.cargo/bin" trunk trunk --version # package.sh runs Trunk's release builds, validates relative URLs, cuts the wasm into diff --git a/Dockerfile b/Dockerfile index 66734f255a..1803d3a2e9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -25,8 +25,8 @@ RUN set -eu; \ asset="trunk-${arch}-unknown-linux-musl.tar.gz"; \ url="https://github.com/trunk-rs/trunk/releases/download/v${TRUNK_VERSION}"; \ cd /tmp; \ - curl -fsSL --retry 3 -A Photocraft-dev "$url/$asset" -o "$asset"; \ - curl -fsSL --retry 3 -A Photocraft-dev "$url/$asset.sha256" -o "$asset.sha256"; \ + curl --proto '=https' -fsSL --retry 3 -A Photocraft-dev "$url/$asset" -o "$asset"; \ + curl --proto '=https' -fsSL --retry 3 -A Photocraft-dev "$url/$asset.sha256" -o "$asset.sha256"; \ printf '%s %s\n' "$(cat "$asset.sha256")" "$asset" | sha256sum -c -; \ tar -xzf "$asset" -C /usr/local/bin trunk; \ rm "$asset" "$asset.sha256"; \ From f4bc90b93f27d5a509671c480b8b80097c5160f1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 20:12:22 -0400 Subject: [PATCH 19/54] ci: pin GitHub Actions to full commit SHA (SonarCloud githubactions:S7637) (#8368) Pin third-party actions to full-length commit SHAs (with version comments) instead of mutable tags/branches to prevent supply-chain tampering via retagged releases. Resolves SonarCloud rule githubactions:S7637. --- .github/workflows/ci.yml | 24 ++++++++++++------------ .github/workflows/docs.yml | 2 +- .github/workflows/perf-nightly.yml | 4 ++-- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d2ef8943dd..735986c355 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -113,7 +113,7 @@ jobs: libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev \ libgl1-mesa-dev libgtk-3-dev - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: components: clippy, rustfmt @@ -122,7 +122,7 @@ jobs: # A failing test still saves: the cache holds compiled dependencies, not test results. # The Windows legs share one key (same dependencies); the integration leg saves it, # because it also runs Clippy and so leaves Clippy's dependency metadata in it. - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: save-if: ${{ github.ref == 'refs/heads/main' && (matrix.part == 'all' || matrix.part == 'integration') }} cache-on-failure: true @@ -251,9 +251,9 @@ jobs: libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev \ libgl1-mesa-dev libgtk-3-dev - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: shared-key: test save-if: false @@ -306,8 +306,8 @@ jobs: CARGO_PROFILE_RELEASE_CODEGEN_UNITS: "16" steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - - uses: Swatinem/rust-cache@v2 + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: key: corpus save-if: ${{ github.ref == 'refs/heads/main' }} @@ -328,10 +328,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: targets: wasm32-unknown-unknown - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: key: wasm32 save-if: ${{ github.ref == 'refs/heads/main' }} @@ -351,10 +351,10 @@ jobs: TRUNK_VERSION: 0.21.14 steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: targets: wasm32-unknown-unknown - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: key: ci-web save-if: ${{ github.ref == 'refs/heads/main' }} @@ -419,8 +419,8 @@ jobs: - { crate: format, name: load } steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@nightly - - uses: Swatinem/rust-cache@v2 + - uses: dtolnay/rust-toolchain@2c76c034f9e32a5d6e2c104dc4df23a22476db04 # nightly + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: workspaces: crates/${{ matrix.target.crate }}/fuzz - name: Install cargo-fuzz diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 67e6b31894..dca0dacfbb 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -32,7 +32,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - name: Install mdBook run: cargo install mdbook --version 0.4.52 --locked - name: Build documentation diff --git a/.github/workflows/perf-nightly.yml b/.github/workflows/perf-nightly.yml index 10d22292d2..4b09278804 100644 --- a/.github/workflows/perf-nightly.yml +++ b/.github/workflows/perf-nightly.yml @@ -44,9 +44,9 @@ jobs: with: persist-credentials: false - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: key: perf-release From 38bc5e916c4d0d8536d8d81f2a4d3f2950b4c749 Mon Sep 17 00:00:00 2001 From: Zuujis <160198409+zuujiscom@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:28:12 -0500 Subject: [PATCH 20/54] refactor(atn): build the clipping-mask and three adjustment events with macros (#8401) Create/Release Clipping Mask and Brightness/Contrast, Black & White and Gradient Map were written out by hand with the same body as adjustment_event! or each other, which SonarCloud counts as duplicated new code (photocraft's quality gate fails on 9.8% duplication from the GrpL entry). adjustment_event! takes an optional command id, and clipping_event! builds the two clipping events. The mapping table is unchanged. --- crates/engine/src/atn_cmds.rs | 69 +++++++++-------------------------- 1 file changed, 18 insertions(+), 51 deletions(-) diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs index a2ae991b0c..afba793027 100644 --- a/crates/engine/src/atn_cmds.rs +++ b/crates/engine/src/atn_cmds.rs @@ -2799,14 +2799,18 @@ fn levels_event_to(id: &str, p: &Value) -> Option { }) } -/// A direct adjustment event (Image › Adjustments › …). +/// A direct adjustment event (Image › Adjustments › …). The command id is `image.adjustments.` +/// unless it is given. macro_rules! adjustment_event { ($code:literal, $class:literal, $name:literal, $label:literal) => { + adjustment_event!($code, $class, $name, $label, concat!("image.adjustments.", $name)) + }; + ($code:literal, $class:literal, $name:literal, $label:literal, $id:expr) => { Event { code: $code, name: $name, label: $label, - ids: &[concat!("image.adjustments.", $name)], + ids: &[$id], from: |d| match adjustment_by_class($class) { Some(a) => adjustment_steps(a, "image.adjustments.", Some(d)), None => Mapped::Unsupported { harmless: false }, @@ -2993,6 +2997,13 @@ fn clipping_to(_: &str, p: &Value) -> Option { Some(desc("null").with("null", layer_ref(p))) } +/// A clipping mask event: `clipping_from` / `clipping_to` with one command id. +macro_rules! clipping_event { + ($code:literal, $name:literal, $label:literal, $id:literal) => { + Event { code: $code, name: $name, label: $label, ids: &[$id], from: |d| clipping_from(d, $id), to: clipping_to } + }; +} + /// Every Photoshop event PhotoCraft maps. The order matters only for the panel label. const EVENTS: &[Event] = &[ // Filters. @@ -3086,17 +3097,7 @@ const EVENTS: &[Event] = &[ }, adjustment_event!("Crvs", "Crvs", "curves", "Curves"), adjustment_event!("HStr", "HStr", "hueSaturation", "Hue/Saturation"), - Event { - code: "BrgC", - name: "brightnessEvent", - label: "Brightness/Contrast", - ids: &["image.adjustments.brightnessContrast"], - from: |d| match adjustment_by_class("BrgC") { - Some(a) => adjustment_steps(a, "image.adjustments.", Some(d)), - None => Mapped::Unsupported { harmless: false }, - }, - to: |_, p| adjustment_by_class("BrgC").and_then(|a| (a.to)(p)), - }, + adjustment_event!("BrgC", "BrgC", "brightnessEvent", "Brightness/Contrast", "image.adjustments.brightnessContrast"), adjustment_event!("Thrs", "Thrs", "threshold", "Threshold"), adjustment_event!("Pstr", "Pstr", "posterize", "Posterize"), adjustment_event!("Invr", "Invr", "invert", "Invert"), @@ -3104,29 +3105,9 @@ const EVENTS: &[Event] = &[ adjustment_event!("Vbrn", "Vbrn", "vibrance", "Vibrance"), adjustment_event!("Exps", "Exps", "exposure", "Exposure"), adjustment_event!("PhtF", "PhtF", "photoFilter", "Photo Filter"), - Event { - code: "", - name: "blackAndWhite", - label: "Black & White", - ids: &["image.adjustments.blackWhite"], - from: |d| match adjustment_by_class("BlnW") { - Some(a) => adjustment_steps(a, "image.adjustments.", Some(d)), - None => Mapped::Unsupported { harmless: false }, - }, - to: |_, p| adjustment_by_class("BlnW").and_then(|a| (a.to)(p)), - }, + adjustment_event!("", "BlnW", "blackAndWhite", "Black & White", "image.adjustments.blackWhite"), adjustment_event!("ChnM", "ChnM", "channelMixer", "Channel Mixer"), - Event { - code: "GdMp", - name: "gradientMapEvent", - label: "Gradient Map", - ids: &["image.adjustments.gradientMap"], - from: |d| match adjustment_by_class("GdMp") { - Some(a) => adjustment_steps(a, "image.adjustments.", Some(d)), - None => Mapped::Unsupported { harmless: false }, - }, - to: |_, p| adjustment_by_class("GdMp").and_then(|a| (a.to)(p)), - }, + adjustment_event!("GdMp", "GdMp", "gradientMapEvent", "Gradient Map", "image.adjustments.gradientMap"), adjustment_event!("SlcC", "SlcC", "selectiveColor", "Selective Color"), ev!("Dstt", "desaturate", "Desaturate", "image.adjustments.desaturate", &[]), ev!("Eqlz", "equalize", "Equalize", "image.adjustments.equalize", &[]), @@ -3316,27 +3297,13 @@ const EVENTS: &[Event] = &[ to: merge_visible_to, }, ev!("Mrg2", "mergeLayersNew", "Merge Layers", "layer.mergeLayers", &[]), - Event { - code: "Ungr", - name: "ungroup", - label: "Release Clipping Mask", - ids: &["layer.releaseClippingMask"], - from: |d| clipping_from(d, "layer.releaseClippingMask"), - to: clipping_to, - }, + clipping_event!("Ungr", "ungroup", "Release Clipping Mask", "layer.releaseClippingMask"), ev!("CpTL", "copyToLayer", "Layer Via Copy", "layer.new.layerViaCopy", &[]), ev!("CtTL", "cutToLayer", "Layer Via Cut", "layer.new.layerViaCut", &[]), ev!("", "rasterizeLayer", "Rasterize", "layer.rasterize.layer", &[]), ev!("", "selectAllLayers", "Select All Layers", "select.allLayers", &[]), ev!("", "selectNoLayers", "Deselect Layers", "select.deselectLayers", &[]), - Event { - code: "GrpL", - name: "groupEvent", - label: "Create Clipping Mask", - ids: &["layer.createClippingMask"], - from: |d| clipping_from(d, "layer.createClippingMask"), - to: clipping_to, - }, + clipping_event!("GrpL", "groupEvent", "Create Clipping Mask", "layer.createClippingMask"), ev!("", "ungroupLayersEvent", "Ungroup Layers", "layer.ungroupLayers", &[]), ev!("", "copyEffects", "Copy Layer Style", "layer.layerStyle.copyLayerStyle", &[]), ev!("", "pasteEffects", "Paste Layer Style", "layer.layerStyle.pasteLayerStyle", &[]), From d2e349ee6c46bd9990a7cdbc11633b4af7124a40 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 22 Oct 2026 17:58:16 +0700 Subject: [PATCH 21/54] README: the app icon above the title --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 1de756458a..538e34d047 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,10 @@

+

+ PhotoCraft icon: an engraved nine-tailed fox on a blue tile +

+

PhotoCraft

From f65832931b00e5fd27b384219baf10fd3edb4f53 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:43:52 -0400 Subject: [PATCH 22/54] security(compose): cap uncached pattern conversion When a pattern exceeded the preparation cache budget, every lookup still called Tile::new_in, expanding the whole sparse pattern into RGBA floats on each output tile (and possibly concurrently). The cache budget only controlled retained entries, not this conversion work. Reject patterns whose full RGBA conversion would exceed an absolute 256 MiB cap on the uncached path, so oversized patterns are skipped instead of re-expanded per tile. The cap is independent of the cache budget, so small patterns still convert on demand when nothing is cached. Finding: cc0b2f77-5578-48ed-aba0-1f3beccd21cd (CWE-400) --- crates/compose/src/pattern.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs index d107ecf4e7..b66ab0ad1e 100644 --- a/crates/compose/src/pattern.rs +++ b/crates/compose/src/pattern.rs @@ -12,6 +12,10 @@ use photocraft_doc::{ColorMode, Pattern, PixelFormat, Rect, SampleType}; pub(crate) const PREPARED_PATTERN_BYTES: usize = 64 << 20; const MAX_PREPARED_PATTERNS: usize = 64; +/// Absolute cap on a single pattern's RGBA conversion on the uncached path. A pattern this +/// large cannot be cached, so re-expanding it for every output tile would be a DoS; above the +/// cap it is skipped instead. Independent of the cache budget so small patterns still convert. +const MAX_UNCACHED_PATTERN_BYTES: usize = 256 << 20; type PreparedSlot = Arc>>>; struct PreparedState { @@ -78,6 +82,13 @@ impl<'a> PreparedPatterns<'a> { // Run on the requesting worker to preserve its active CMYK profile. slot.get_or_init(|| Tile::new_in(p, self.mode).map(Arc::new)).clone() } + // Uncached path: a pattern whose full conversion would exceed an absolute cap is + // not materialized at all. Otherwise every output tile would re-expand the entire + // sparse pattern into RGBA floats (and could do so concurrently), exhausting CPU and + // memory even though cache admission already refused to retain it. The cap is + // independent of the (possibly zero) cache budget, so small patterns still convert + // on demand when nothing is cached. + None if bytes.is_none_or(|b| b > MAX_UNCACHED_PATTERN_BYTES) => None, None => Tile::new_in(p, self.mode).map(Arc::new), } } From 7016152f224c36f46d7d154ef1096918557f7fc6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:42:34 -0400 Subject: [PATCH 23/54] security(compose): bound dense mask working set build_mask derives its working area from sparse mask geometry grown by feather, so two distant changed pixels could span a canvas-sized rectangle. It then allocated f32 planes (coverage, pixel-mask values, blur scratch) over that area, gigabytes during even a one-pixel render. Check the estimated working bytes before the dense allocation and fall back to the constant default mask above 512 MiB, so pathological geometry degrades feather detail instead of exhausting memory. Finding: 8c04c5ef-a5bd-48f4-bfcf-83615bcf11c0 (CWE-770) --- crates/compose/src/masks.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/compose/src/masks.rs b/crates/compose/src/masks.rs index 802a0f2df9..7335be90d0 100644 --- a/crates/compose/src/masks.rs +++ b/crates/compose/src/masks.rs @@ -221,7 +221,14 @@ fn build_mask(layer: &Layer, canvas: Rect) -> Surface { } let area = area.intersect(&canvas); let mut s = Surface::with_default(FORMAT, &[p_def * v_out]); - if !area.is_empty() { + // Bound the transient dense working set: `area` is derived from sparse mask geometry grown + // by feather, so two distant changed pixels could span a canvas-sized rectangle. Building + // f32 planes over it (coverage, pixel-mask values, blur scratch) could be gigabytes during + // a one-pixel render. Above the budget, fall back to the constant default mask rather than + // allocating; feather detail is lost only for pathological geometry. + const MAX_MASK_WORKING_BYTES: u64 = 512 << 20; + let working = (area.width() as u64).saturating_mul(area.height() as u64).saturating_mul(std::mem::size_of::() as u64).saturating_mul(3); + if !area.is_empty() && working <= MAX_MASK_WORKING_BYTES { let (w, h) = (area.width() as usize, area.height() as usize); // A slot initializer must not enter Rayon: another tile requesting the // same mask could be stolen onto its stack and wait for its own build. From bd109515a91602939f5c955da8e73cc8dfc15737 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:41:08 -0400 Subject: [PATCH 24/54] security(io): bound XCF copied layer metadata The XCF importer reparses every layer offset and allocates a new owned name and item path per reference. Repeated offsets referencing one record with a large name or path could retain gigabytes of metadata, which the per-field and per-layer limits did not bound in aggregate. Add a document-wide metadata budget (32 MiB) to the Image reader and charge each copied layer name and item path against it, erroring when exhausted. Finding: 1631d2df-fe8f-4734-b14e-380db11afb26 (CWE-789) --- crates/io/src/xcf.rs | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/io/src/xcf.rs b/crates/io/src/xcf.rs index 15586a55dd..4bb62cacbb 100644 --- a/crates/io/src/xcf.rs +++ b/crates/io/src/xcf.rs @@ -42,6 +42,10 @@ pub(crate) const MAX_LAYERS: usize = 8192; const MAX_CHANNELS: usize = 1024; /// Group nesting. const MAX_DEPTH: usize = 64; +/// Total copied layer metadata (names and item paths). A single reused record with a large +/// name is bounded by MAX_STRING, but repeated layer offsets referencing it must not multiply +/// into unbounded retained metadata. +const MAX_METADATA_BYTES: usize = 32 << 20; /// A string field (layer names, parasite names). const MAX_STRING: usize = 1 << 20; /// A property payload or a parasite that is read into memory. @@ -381,6 +385,10 @@ struct Image<'a> { base_type: u32, colormap: Vec<[u8; 3]>, budget: usize, + /// Remaining allowance for copied layer metadata (names, item paths). Repeated layer + /// offsets referencing one record with a large name would otherwise allocate an owned + /// copy per reference, multiplying a small file into gigabytes of retained metadata. + meta_budget: usize, warnings: Warnings, /// Layers GIMP composites with "Clip to backdrop" (its default for every mode but Normal). clipped_to_backdrop: usize, @@ -685,7 +693,18 @@ pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result Image<'a> { let mut c = self.c.at(ptr); let (lw, lh, kind) = (c.u32()?, c.u32()?, c.u32()?); let name = c.string()?; + // Charge the owned name against the document-wide metadata budget: repeated layer + // offsets referencing one large name must not retain unbounded copies. + self.meta_budget = self.meta_budget.checked_sub(name.len()).ok_or_else(|| invalid("layer metadata exceeds the budget"))?; let lprops = props(&mut c)?; let hptr = c.ptr()?; let mptr = c.ptr()?; @@ -902,7 +924,11 @@ impl<'a> Image<'a> { 26 => text = true, 28 => locks.pixels = v != 0, 29 => group = true, - 30 => path = p.data.as_chunks::<4>().0.iter().map(|s| u32::from_be_bytes(*s)).collect(), + 30 => { + path = p.data.as_chunks::<4>().0.iter().map(|s| u32::from_be_bytes(*s)).collect(); + self.meta_budget = + self.meta_budget.checked_sub(path.len().saturating_mul(4)).ok_or_else(|| invalid("layer metadata exceeds the budget"))?; + } 31 => expanded = v & 1 != 0, 32 => locks.position = v != 0, 34 => tag = label(v), From 0e1a7a8b2a9533508e32cd86be3c4969233389c5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:39:17 -0400 Subject: [PATCH 25/54] security(io): bound PDN layer-name copies PDN conversion copied a referenced name into an owned String for every output layer, while the NRBF budget charged the shared string only once. Repeated references to one large name could multiply a small document into gigabytes of retained metadata. Cap each layer name at 64 KiB and the aggregate copied name bytes at 4 MiB, checked before each copy. Finding: fd77f4b2-39a2-48b5-b9d8-4ad69cf69469 (CWE-770) --- crates/io/src/pdn.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/io/src/pdn.rs b/crates/io/src/pdn.rs index 08e294b7bc..1e2d99f7af 100644 --- a/crates/io/src/pdn.rs +++ b/crates/io/src/pdn.rs @@ -154,6 +154,12 @@ pub(super) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result) -> Result 255 { return Err(invalid("opacity exceeds 255")); } - let mut l = Layer::raster(graph.string(graph.field(props, "name")?)?, PixelFormat::RGBA8); + let mut l = Layer::raster( + { + let name = graph.string(graph.field(props, "name")?)?; + if name.len() > MAX_NAME_BYTES { + return Err(invalid("layer name is too long")); + } + name_bytes = name_bytes.saturating_add(name.len()); + if name_bytes > MAX_TOTAL_NAME_BYTES { + return Err(invalid("layer names exceed the total metadata budget")); + } + name.to_string() + }, + PixelFormat::RGBA8, + ); l.visible = graph.boolean(graph.field(props, "visible")?)?; l.opacity = opacity as f32 / 255.0; l.blend = blend(&graph, layer, props)?; From 8c0a9cb1851f5386b18d64601e7939b627a1c6b5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:36:53 -0400 Subject: [PATCH 26/54] security(raw): bound cumulative retained tile memory read_plane decodes every tile in parallel and retains all decoded tile buffers in before assembly copies only the useful pixels. Each tile is charged individually, but file-controlled padding and repeated source ranges can make the cumulative retained samples far exceed both the input and the useful image. Sum the padded tile samples (two bytes each) and reject the plane before decoding when that total exceeds max_alloc. Finding: e66981b1-0d7a-4738-a64c-37b5e8bf28d1 (CWE-770) --- crates/raw/src/sensor.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/crates/raw/src/sensor.rs b/crates/raw/src/sensor.rs index f2cffdb808..cab5ce2a05 100644 --- a/crates/raw/src/sensor.rs +++ b/crates/raw/src/sensor.rs @@ -255,6 +255,19 @@ pub(crate) fn read_plane(t: &Tiff, ifd: &Ifd, limits: &Limits, layout: JpegLayou } limits.check(width as u64, height as u64, samples as u64 * 2)?; let segments = segments(t, ifd, width, height)?; + // The decoded tiles are all retained in `decoded` before assembly copies only the useful + // pixels. Each tile is charged individually below, but file-controlled padding and repeated + // source ranges can make the *cumulative* retained samples far exceed both the input and the + // useful image. Reject that up front: the sum of padded tile samples (two bytes each) must + // fit the allocation budget. + let mut total_tile_samples: u64 = 0; + for s in &segments { + let tile = (s.w as u64).saturating_mul(s.h as u64).saturating_mul(samples as u64); + total_tile_samples = total_tile_samples.saturating_add(tile); + } + if total_tile_samples.saturating_mul(2) > limits.max_alloc { + return Err(RawError::LimitExceeded(format!("{} bytes of retained raw tiles exceed {}", total_tile_samples.saturating_mul(2), limits.max_alloc))); + } let le = t.le; let tiled = t.tag_uint(ifd, tag::TILE_WIDTH).is_some(); let decoded: Vec>> = par::map(segments.len(), |i| { From 2e2faec1a35a9db7c9a0fe55c830ffdadfba0fee Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:36:01 -0400 Subject: [PATCH 27/54] security(raw): cap lossless-JPEG Huffman table builds Each DHT definition for table id 0..3 calls Huffman::new, which allocates and fills a ~48 KiB lookup pair. A stream repeating DHT definitions (and DNG tiles referencing such a stream) could rebuild tables thousands of times, multiplying header-processing cost and memory churn while producing little output. A real lossless JPEG uses a handful of Huffman tables; cap cumulative table builds per stream at 64 and reject streams that exceed it. Finding: 7a31b581-d1b7-4f9c-91e5-ce42b47db87f (CWE-400) --- crates/raw/src/ljpeg.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/crates/raw/src/ljpeg.rs b/crates/raw/src/ljpeg.rs index e9c42bdeb4..4ab32df8b8 100644 --- a/crates/raw/src/ljpeg.rs +++ b/crates/raw/src/ljpeg.rs @@ -299,6 +299,11 @@ fn parse(data: &[u8]) -> Result> { let mut pos = 2; let mut frame: Option = None; let mut comp_ids: Vec = Vec::new(); + // A lossless JPEG uses at most a handful of Huffman tables. Each Huffman::new allocates a + // ~48 KiB lookup pair and fills it, so a stream that repeats DHT definitions could rebuild + // tables thousands of times. Cap the cumulative builds to bound that header-processing work. + const MAX_HUFFMAN_BUILDS: usize = 64; + let mut huffman_builds = 0usize; let mut huff: [Option; 4] = [None, None, None, None]; let mut restart = 0usize; loop { @@ -355,6 +360,10 @@ fn parse(data: &[u8]) -> Result> { let total: usize = counts.iter().map(|&c| usize::from(c)).sum(); let vals = seg.get(p + 17..p + 17 + total).ok_or_else(|| RawError::malformed("short DHT"))?; if id < 4 { + huffman_builds += 1; + if huffman_builds > MAX_HUFFMAN_BUILDS { + return Err(RawError::malformed("lossless JPEG defines too many Huffman tables")); + } huff[id] = Some(Huffman::new(&counts, vals)?); } p += 17 + total; @@ -573,4 +582,26 @@ mod tests { let lossy = [0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x0B, 8, 0, 1, 0, 1, 1, 1, 0x11, 0]; assert!(matches!(decode(&lossy, usize::MAX), Err(RawError::Unsupported(_)))); } + + #[test] + fn too_many_huffman_tables_are_rejected() { + // A valid stream still decodes; the same stream with thousands of repeated DHT + // definitions injected after the SOI is rejected before rebuilding tables endlessly. + let (w, h) = (8, 8); + let v = samples(w * h, 12, 5); + let j = lj92_encode(&v, w, h, 1, 12, 1, None); + assert!(decode(&j, usize::MAX).is_ok()); + + // Minimal DHT for id 0 (one length-1 code, value 0): FF C4, len=0x0014, then + // tc_th, 16 count bytes, one value. + let mut dht = vec![0xFF, 0xC4, 0x00, 0x14, 0x00]; + dht.extend_from_slice(&[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); // counts + dht.push(0x00); // one value + let mut flooded = j[..2].to_vec(); // SOI + for _ in 0..5000 { + flooded.extend_from_slice(&dht); + } + flooded.extend_from_slice(&j[2..]); // the rest of the valid stream + assert!(matches!(decode(&flooded, usize::MAX), Err(RawError::Malformed(_)))); + } } From bf98617e2060acec5f8964aa977531977c4e8ee4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:34:12 -0400 Subject: [PATCH 28/54] security(io): apply caller limits to RAW preview decoding upright_preview decoded a raw file's embedded JPEG with default codec options, discarding the caller's DevelopOptions.limits. A compressed embedded preview could therefore allocate and process far more pixel data than the caller authorized during the fallback and color-fit paths. Pass the caller's limits into upright_preview and translate them into the JPEG DecodeOptions, so both the Unsupported fallback and the preview look-fit respect the same policy. Finding: d17bc286-6765-41ce-bd41-579ee5b75cfa (CWE-409) --- crates/io/src/raw.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/io/src/raw.rs b/crates/io/src/raw.rs index 5ce761b521..820de8935b 100644 --- a/crates/io/src/raw.rs +++ b/crates/io/src/raw.rs @@ -35,8 +35,13 @@ fn limits() -> Limits { /// has one; otherwise the raw's IFD0 orientation applies (TIFF-based raws record it there, and /// their previews are usually stored as the sensor reads out). Developed raws are oriented by /// `photocraft-raw` and their EXIF carries no orientation, so nothing is turned twice. -fn upright_preview(raw: &[u8], jpeg: &[u8]) -> Result { - let img = codecs::decode_as_with(Format::Jpeg, jpeg, &codecs::DecodeOptions { keep_orientation: true, ..Default::default() })?; +fn upright_preview(raw: &[u8], jpeg: &[u8], limits: &photocraft_raw::Limits) -> Result { + // Decode the embedded preview under the caller's limits, not the codec defaults: an + // embedded JPEG can declare far more decoded pixels than the raw development the caller + // authorized, so the preview fallback must honor the same policy. + let codec_limits = + codecs::Limits { max_width: limits.max_width, max_height: limits.max_height, max_pixels: limits.max_pixels, max_alloc: limits.max_alloc }; + let img = codecs::decode_as_with(Format::Jpeg, jpeg, &codecs::DecodeOptions { keep_orientation: true, limits: codec_limits })?; let own = img.meta.exif.as_deref().map_or(1, codecs::exif_orientation); let o = if own != 1 { own } else { photocraft_raw::orientation(raw).unwrap_or_else(|| codecs::exif_orientation(raw)) }; Ok(img.oriented(o)?) @@ -216,7 +221,7 @@ pub fn fit_preview_look(raw: &[u8], sensor: &Sensor, opts: &DevelopOptions) -> R .min_by_key(|p| long(p)) .or_else(|| previews.iter().max_by_key(|p| long(p))) .ok_or("no embedded JPEG preview")?; - let img = upright_preview(raw, pick.jpeg).map_err(|e| format!("the embedded preview does not decode: {e}"))?; + let img = upright_preview(raw, pick.jpeg, &opts.limits).map_err(|e| format!("the embedded preview does not decode: {e}"))?; if img.layout() != ChannelLayout::Rgb || img.sample_type() != SampleType::U8 { return Err("the embedded preview is not 8-bit RGB".into()); } @@ -260,7 +265,7 @@ pub fn import_raw_with(name: &str, bytes: &[u8], opts: &DevelopOptions) -> Resul } Err(RawError::Unsupported(reason)) => match photocraft_raw::embedded_preview(bytes) { Some(p) => { - let img = upright_preview(bytes, p.jpeg)?; + let img = upright_preview(bytes, p.jpeg, &opts.limits)?; let mut r = image_to_document(name, &img)?; r.warnings.insert( 0, From 53bee4aa81406b4425a176ad9267f6e2b3878b41 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:31:27 -0400 Subject: [PATCH 29/54] security(raw): interpolate gain maps per pixel, not per full row GainMap::row materialized the entire horizontal gain grid (points_h floats) once per applicable image row, even though each output pixel only needs two neighboring points. File-controlled image height and horizontal map size multiplied into processing and allocation churn far beyond the input size. Add GainMap::at_rv, a direct four-corner bilinear lookup, and use it per output column in gain_row so no points_h-wide row is built per image row. A test proves at_rv matches the former row() + at() path. Finding: 7ebec8df-1a7a-4d33-915f-097f8e9be0e5 (CWE-400) --- crates/raw/src/develop.rs | 3 +-- crates/raw/src/opcodes.rs | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/crates/raw/src/develop.rs b/crates/raw/src/develop.rs index 5d28508750..71a8384cd0 100644 --- a/crates/raw/src/develop.rs +++ b/crates/raw/src/develop.rs @@ -460,12 +460,11 @@ fn gain_row(s: &Sensor, y: usize, x0: usize, w: usize, k: usize) -> Option= m.plane.saturating_add(m.planes) || ay < m.top || ay >= m.bottom || !(ay - m.top).is_multiple_of(m.row_pitch) { continue; } - let row = m.row(rv, k - m.plane); let o = out.get_or_insert_with(|| vec![1.0; w]); for (i, f) in o.iter_mut().enumerate() { let x = x0 + i; if x >= a.x && m.covers(x - a.x, ay) { - *f *= m.at(&row, ((x - a.x) as f64 + 0.5) / a.width as f64); + *f *= m.at_rv(rv, k - m.plane, ((x - a.x) as f64 + 0.5) / a.width as f64); } } } diff --git a/crates/raw/src/opcodes.rs b/crates/raw/src/opcodes.rs index 9dc231ca61..6be6d45077 100644 --- a/crates/raw/src/opcodes.rs +++ b/crates/raw/src/opcodes.rs @@ -58,6 +58,27 @@ impl GainMap { a + (b - a) * t } + /// Bilinearly interpolates the gain at image-relative row `rv` and column `rh` for map + /// plane `mp`, touching only the four surrounding grid points. This avoids building the + /// whole `points_h`-wide row per image row, which made development work proportional to + /// image height times horizontal map size even when each output row needs few values. + #[inline] + pub fn at_rv(&self, rv: f64, mp: usize, rh: f64) -> f32 { + let mp = mp.min(self.map_planes.saturating_sub(1)); + let fv = ((rv - self.origin_v) / self.spacing_v).clamp(0.0, (self.points_v - 1) as f64); + let i0 = (fv.floor() as usize).min(self.points_v - 1); + let i1 = (i0 + 1).min(self.points_v - 1); + let tv = (fv - i0 as f64) as f32; + let fh = ((rh - self.origin_h) / self.spacing_h).clamp(0.0, (self.points_h - 1) as f64); + let j0 = (fh.floor() as usize).min(self.points_h - 1); + let j1 = (j0 + 1).min(self.points_h - 1); + let th = (fh - j0 as f64) as f32; + let g = |i: usize, j: usize| self.gains.get((i * self.points_h + j) * self.map_planes + mp).copied().unwrap_or(1.0); + let top = g(i0, j0) + (g(i0, j1) - g(i0, j0)) * th; + let bot = g(i1, j0) + (g(i1, j1) - g(i1, j0)) * th; + top + (bot - top) * tv + } + /// `true` if the map covers active-area pixel (`ax`, `ay`). #[inline] pub fn covers(&self, ax: usize, ay: usize) -> bool { @@ -216,4 +237,21 @@ mod tests { huge[4 + 16 + 32..4 + 16 + 40].copy_from_slice(&[0xFF; 8]); // points assert!(parse(&huge).0.is_empty()); } + + #[test] + fn at_rv_matches_row_then_at() { + // at_rv (direct 4-corner bilinear) must equal the old row() + at() path for a range of + // sample positions, including points outside the grid that clamp. + let b = list(&[(9, gain_map_params([0, 0, 10, 10], 1, &[[1.0, 2.0], [3.0, 4.5]]))]); + let (maps, _) = parse(&b); + let m = &maps[0]; + for &rv in &[-1.0, 0.0, 0.17, 0.5, 0.83, 1.0, 2.0] { + let row = m.row(rv, 0); + for &rh in &[-1.0, 0.0, 0.1, 0.5, 0.9, 1.0, 3.0] { + let want = m.at(&row, rh); + let got = m.at_rv(rv, 0, rh); + assert!((got - want).abs() < 1e-6, "rv={rv} rh={rh}: {got} vs {want}"); + } + } + } } From 163a0000a5dbbae209637ddd455bf8a17c4109f7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:29:12 -0400 Subject: [PATCH 30/54] security(raw): position RW2 bit cursor in constant time compressed_row positioned the bit cursor by replaying every preceding byte within its page (skip % PAGE calls of get(8)). For narrow images this replay runs per row, so a small file could consume disproportionate CPU just setting up cursors. Add Bits::new_at, which sets the page position and remaining-bit count directly from the row offset in O(1), and use it in compressed_row. A unit test proves it matches the old byte-by-byte replay. Finding: 2a7d3d4b-90ab-4887-9dba-c3884e224990 (CWE-407) --- crates/raw/src/rw2.rs | 38 ++++++++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/crates/raw/src/rw2.rs b/crates/raw/src/rw2.rs index c50d32c09c..ac9ada4189 100644 --- a/crates/raw/src/rw2.rs +++ b/crates/raw/src/rw2.rs @@ -138,10 +138,20 @@ struct Bits<'a> { } impl<'a> Bits<'a> { + #[cfg(test)] fn new(buf: &'a [u8], base: usize) -> Self { Bits { buf, base, pos: 0, nbits: 0 } } + /// Positions the cursor `skip_in_page` bytes into the page at `base`, in constant time. + /// Equivalent to `new(buf, base)` followed by `skip_in_page` calls of `get(8)`: the first + /// read loads one page (`pos = PAGE`), and each byte skipped consumes 8 bits. Narrow images + /// repeated this replay per row, which made cursor setup quadratic. + fn new_at(buf: &'a [u8], base: usize, skip_in_page: usize) -> Self { + debug_assert!(skip_in_page < PAGE); + Bits { buf, base, pos: PAGE, nbits: PAGE as u32 * 8 - 8 * skip_in_page as u32 } + } + #[inline] fn get(&mut self, num: u32) -> u32 { if num > self.nbits { @@ -162,10 +172,7 @@ impl<'a> Bits<'a> { /// Decodes one row of the vendor-compressed stream. fn compressed_row(buf: &[u8], row_bytes: usize, row: usize, out: &mut [u16]) { let skip = row_bytes * row; - let mut bits = Bits::new(buf, skip / PAGE * PAGE); - for _ in 0..(skip % PAGE) { - bits.get(8); - } + let mut bits = Bits::new_at(buf, skip / PAGE * PAGE, skip % PAGE); let mut sh: i32 = 0; for group in out.as_chunks_mut::<14>().0 { let mut pred = [0i32; 2]; @@ -354,6 +361,29 @@ mod tests { assert_eq!(b.get(8), 0x55); } + #[test] + fn new_at_matches_byte_replay() { + // new_at must position the cursor identically to new() followed by skip_in_page + // get(8) calls, so the quadratic per-row replay can be removed safely. + let mut buf = vec![0u8; 0x8000]; + for (i, b) in buf.iter_mut().enumerate() { + *b = (i * 7 + 3) as u8; + } + for base in [0usize, PAGE, 2 * PAGE] { + for skip in [0usize, 1, 7, 100, PAGE - 1] { + let mut replay = Bits::new(&buf, base); + for _ in 0..skip { + replay.get(8); + } + let mut direct = Bits::new_at(&buf, base, skip); + for _ in 0..20 { + assert_eq!(replay.get(5), direct.get(5), "base {base} skip {skip}"); + assert_eq!(replay.get(8), direct.get(8), "base {base} skip {skip}"); + } + } + } + } + #[test] fn compressed_group_walks_predictors() { // One 14-pixel group: both parities start absolute, a delta of 0x80 From c5a6afcf68f4906257c4d717859a165431f44947 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:27:22 -0400 Subject: [PATCH 31/54] security(raw): reject tiled Sony cRAW and cap row references read_craw treats every segment as a run of full-width image rows and grew the row-reference vector before checking coverage. A tiled layout (which does not describe full-width rows) with repeated tile offsets could push far more than height rows, allocating gigabytes before the post-loop coverage check ran. Reject tiled cRAW layouts up front (cRAW is only stored as strips) and stop collecting rows once the image height is reached. Finding: 3c2601a1-ad92-45b6-96f7-be5da87d97eb (CWE-400) --- crates/raw/src/sony.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/raw/src/sony.rs b/crates/raw/src/sony.rs index e1961680df..b00fd0360a 100644 --- a/crates/raw/src/sony.rs +++ b/crates/raw/src/sony.rs @@ -114,11 +114,23 @@ pub(crate) fn read_craw(t: &Tiff, ifd: &Ifd, limits: &Limits) -> Result { } let lut = tone_lut(&t.tag_uints(ifd, SONY_TONE_CURVE)).ok_or_else(|| RawError::unsupported("Sony compressed ARW without a usable tone curve (0x7010)"))?; limits.check(width as u64, height as u64, 2)?; + // The cRAW reader treats every segment as a sequence of full-width image rows. A tiled + // layout does not describe full-width rows, so accepting one would let repeated tile + // offsets push far more than `height` row references before the coverage check below. + // cRAW is only stored as strips, so reject tiles outright. + if t.tag_uint(ifd, tag::TILE_WIDTH).is_some() || t.tag_uint(ifd, tag::TILE_LENGTH).is_some() { + return Err(RawError::unsupported("tiled Sony compressed ARW is not supported")); + } // One byte per pixel: locate every row in the strips. let mut rows: Vec<&[u8]> = Vec::with_capacity(height); for s in segments(t, ifd, width, height)? { let n = s.h.min(height.saturating_sub(s.y)); for r in 0..n { + // Never collect more rows than the image has; a malformed strip layout cannot + // grow the reference buffer past the image height. + if rows.len() >= height { + return Err(RawError::malformed("compressed ARW strips describe more rows than the image")); + } let at = s.offset.checked_add(r * width).ok_or_else(|| RawError::malformed("raw strip offset overflows"))?; if (r + 1) * width > s.len { return Err(RawError::malformed("compressed ARW strip is shorter than its rows")); From 1f2be700579871f50e71d549164caba5761caa80 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:26:09 -0400 Subject: [PATCH 32/54] security(raw): bound TIFF structure-dump output Tiff::dump appended each entry's full ASCII value with no per-value or total-output limit. Thousands of entries can reference one large aliased ASCII value, expanding a small diagnostic input into a multi-gigabyte String. Cap each ASCII preview to 256 bytes (truncated at a char boundary) and stop the listing once the accumulated output reaches 1 MiB, marking it truncated. Finding: d994ec7f-25dd-4ae7-9673-04adc0aa8a3c (CWE-400) --- crates/raw/src/tiff.rs | 52 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/crates/raw/src/tiff.rs b/crates/raw/src/tiff.rs index 671ab11fbe..cfcadee730 100644 --- a/crates/raw/src/tiff.rs +++ b/crates/raw/src/tiff.rs @@ -328,13 +328,32 @@ pub(crate) fn orientation(v: Option) -> u16 { /// A human-readable listing of every IFD and entry (debugging aid). pub(crate) fn dump(data: &[u8]) -> String { use std::fmt::Write; + // Caps so a crafted TIFF (many entries aliasing one large ASCII value) cannot expand a + // small diagnostic input into a multi-gigabyte String. + const MAX_ASCII_PREVIEW: usize = 256; + const MAX_OUTPUT: usize = 1 << 20; let Some(t) = Tiff::new(data) else { return "not a TIFF-structured file".into() }; let mut s = String::new(); - for ifd in t.all_ifds() { + 'ifds: for ifd in t.all_ifds() { let _ = writeln!(s, "IFD @{}", ifd.offset); for e in &ifd.entries { + if s.len() >= MAX_OUTPUT { + s.push_str("… (output truncated)\n"); + break 'ifds; + } let preview: String = if e.typ == 2 { - t.ascii(e).unwrap_or_default() + let mut a = t.ascii(e).unwrap_or_default(); + if a.len() > MAX_ASCII_PREVIEW { + // Truncate at a char boundary at or below the cap (lossy UTF-8 can hold + // multi-byte replacement chars). + let mut cut = MAX_ASCII_PREVIEW; + while cut > 0 && !a.is_char_boundary(cut) { + cut -= 1; + } + a.truncate(cut); + a.push('…'); + } + a } else { let n = (e.count as usize).min(12); let v: Vec = (0..n).map(|i| t.float(e, i).map(|f| format!("{f}")).unwrap_or_else(|| "?".into())).collect(); @@ -401,4 +420,33 @@ mod tests { let ifd = t.ifd_at(8, 0).unwrap(); assert_eq!(t.float(ifd.get(50730).unwrap(), 0), None); } + + #[test] + fn dump_output_is_bounded_for_aliased_ascii() { + // Many ASCII entries all pointing at one large value must not expand the diagnostic + // dump without bound. Build an IFD whose entries alias a big ASCII blob. + const ENTRIES: usize = 4000; + const BLOB: usize = 100_000; + let header = 8u32; + let ifd_at = header; + let entry_count_bytes = 2; + let entries_bytes = ENTRIES * 12; + let next_ptr_bytes = 4; + let blob_at = ifd_at as usize + entry_count_bytes + entries_bytes + next_ptr_bytes; + let mut b = b"II*\0".to_vec(); + b.extend_from_slice(&ifd_at.to_le_bytes()); + b.extend_from_slice(&(ENTRIES as u16).to_le_bytes()); + for i in 0..ENTRIES { + b.extend_from_slice(&(1000 + i as u16).to_le_bytes()); // tag + b.extend_from_slice(&2u16.to_le_bytes()); // type ASCII + b.extend_from_slice(&(BLOB as u32).to_le_bytes()); // count + b.extend_from_slice(&(blob_at as u32).to_le_bytes()); // value offset (aliased) + } + b.extend_from_slice(&0u32.to_le_bytes()); // next IFD = none + b.resize(blob_at + BLOB, b'A'); + let out = dump(&b); + // Comfortably below entries * blob (~400 MB); the caps keep it near 1 MiB. + assert!(out.len() < 2 << 20, "dump output was {} bytes", out.len()); + assert!(out.contains("output truncated") || out.len() < 1 << 20); + } } From 9edcb97687aa15b8cee5b614fd0cb360f361f95f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:24:26 -0400 Subject: [PATCH 33/54] security(codecs): admit HEIF coded image size, not just transformed When transforms (orientation/clean-aperture crop) are applied, admission checked only the transformed output size. The delegated HEVC decoder allocates the full coded image before cropping, so a HEIF with a small visible aperture over a large coded image bypassed the limit policy. Always check the coded dimensions against the full limits before delegating, in addition to the transformed size. Note: the related SPS-driven and grid-tile allocations (findings 75048229 and 2db4c59e) occur inside the pinned heic-rs dependency from parameter sets the container does not expose; fully bounding those needs a decoder-side change and is tracked separately. Finding: ec5cec31-8a62-4963-8045-e3ec9d9e4931 (CWE-400) --- crates/codecs/src/codecs/heif.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/codecs/src/codecs/heif.rs b/crates/codecs/src/codecs/heif.rs index 31da309ca3..efd9d2073a 100644 --- a/crates/codecs/src/codecs/heif.rs +++ b/crates/codecs/src/codecs/heif.rs @@ -45,6 +45,13 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits, keep_orientation: bool) -> R let sample = if info.sixteen_bit { SampleType::U16 } else { SampleType::U8 }; let (w, h) = if keep_orientation { (info.coded_width, info.coded_height) } else { (info.width, info.height) }; limits.check(w, h, layout, sample)?; + // The delegated decoder allocates the full coded image before applying any clean-aperture + // crop or orientation transform, so the coded dimensions must pass the limit policy even + // when the displayed (transformed) size is small. Checking only the transformed size let a + // tiny visible image hide a large coded allocation. + if !keep_orientation && (info.coded_width, info.coded_height) != (w, h) { + limits.check(info.coded_width, info.coded_height, layout, sample)?; + } let options = photocraft_heif::Options { max_pixels: limits.max_pixels, apply_transforms: !keep_orientation }; let decoded = photocraft_heif::decode(bytes, &options).map_err(err)?; // The decoder re-reads the container; trust its output's shape, not the probe's. From 867caefb5c789f03b8c1ce5e7b44299115c2b043 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:22:41 -0400 Subject: [PATCH 34/54] security(codecs): admit deep-EXR output size and validate chunks first Two deep-EXR allocation gaps: - flatten() allocated the flattened output and the full display-window stage (nc f32 samples per pixel) without a limit check; the deep decode only admitted the data window at four bytes per pixel, before the channel layout was known. Pass Limits into flatten and re-check both buffers at the real f32 layout size. - decode_deep built a per-pixel usize block index before validating the chunk's declared packed sizes. Compute the block bounds first, validate the payload is present, then materialize the index, so a truncated or lying chunk is rejected before the index is allocated. Findings: - feb6fcd8-58df-47e2-a04a-d4d81d5565aa (CWE-789, display-stage allocation) - 9c53025d-65f8-4bcc-9161-143a4c5d7f46 (CWE-789, index before payload check) --- crates/codecs/src/codecs/deep_exr.rs | 41 ++++++++++++++++++++-------- crates/codecs/src/codecs/exr.rs | 2 +- 2 files changed, 31 insertions(+), 12 deletions(-) diff --git a/crates/codecs/src/codecs/deep_exr.rs b/crates/codecs/src/codecs/deep_exr.rs index 29f3762ebc..4fe9def532 100644 --- a/crates/codecs/src/codecs/deep_exr.rs +++ b/crates/codecs/src/codecs/deep_exr.rs @@ -341,15 +341,17 @@ pub(crate) fn decode_deep(meta: &MetaData, bytes: &[u8], limits: &Limits) -> Res return Err(err(format!("chunk declares part {part}, expected {header_index}"))); } } - // Block coordinates → the block's global pixel range and its slot. - let (block_pixels, slot, row_w): (Vec, usize, usize) = match &header.blocks { + // Block coordinates → the block's pixel bounds and its slot. The per-pixel index is + // built only after the chunk's declared payload sizes are validated below, so a + // truncated or lying chunk cannot drive a large index allocation first. + let (block_rows, block_cols, slot, row_w, scanline_row): (std::ops::Range, std::ops::Range, usize, usize, bool) = match &header.blocks { BlockDescription::ScanLines => { let y = i32(&mut cur)?; let row = match y.checked_sub(y0) { Some(d) if d >= 0 && (d as usize) < h => d as usize, _ => return Err(err(format!("scan line block y={y} is outside the data window"))), }; - ((0..w).map(|x| row * w + x).collect(), row, w) + (row..row + 1, 0..w, row, w, true) } BlockDescription::Tiles(_) => { let (tx, ty, lx, ly) = (i32(&mut cur)?, i32(&mut cur)?, i32(&mut cur)?, i32(&mut cur)?); @@ -362,16 +364,11 @@ pub(crate) fn decode_deep(meta: &MetaData, bytes: &[u8], limits: &Limits) -> Res let (bx, by) = ((tx as usize) * tile_w, (ty as usize) * tile_h); let rows = (by + tile_h).min(h); let cols = (bx + tile_w).min(w); - let mut px = Vec::with_capacity((rows - by) * (cols - bx)); - for yy in by..rows { - for xx in bx..cols { - px.push(yy.saturating_mul(w).saturating_add(xx)); - } - } let slot = (ty as usize).saturating_mul(tiles_x) + tx as usize; - (px, slot, cols - bx) + (by..rows, bx..cols, slot, cols - bx, false) } }; + let block_len = block_rows.len().saturating_mul(block_cols.len()); if seen.get(slot).copied().unwrap_or(true) { return Err(err(format!("two chunks cover block {slot}"))); } @@ -386,6 +383,20 @@ pub(crate) fn decode_deep(meta: &MetaData, bytes: &[u8], limits: &Limits) -> Res if packed_table > remaining || packed_data > remaining.saturating_sub(packed_table) { return Err(err("deep chunk sizes point past the end of the file")); } + // The chunk's payload is present; now materialize the block's global pixel index. For + // scan lines this is one row; for tiles the clipped tile rectangle. + let block_pixels: Vec = if scanline_row { + let row = block_rows.start; + (0..w).map(|x| row * w + x).collect() + } else { + let mut px = Vec::with_capacity(block_len); + for yy in block_rows.clone() { + for xx in block_cols.clone() { + px.push(yy.saturating_mul(w).saturating_add(xx)); + } + } + px + }; let what = "the sample-count table"; let table_bytes = read_exact(&mut cur, packed_table as usize, what)?; let expected_table = block_pixels.len().checked_mul(4).ok_or_else(|| err("count table overflows"))?; @@ -552,7 +563,7 @@ fn header_end(bytes: &[u8]) -> Result { /// into straight alpha at the end. Without any alpha channel the front-most sample wins, /// opaque. Z, ZBack and other deep channels influence the flat result only through the /// ordering; volume samples (with ZBack) are approximated as point samples. -pub(crate) fn flatten(deep: &DeepImage) -> Result { +pub(crate) fn flatten(deep: &DeepImage, limits: &Limits) -> Result { let npx = deep.width as usize * deep.height as usize; let has = |n: &str| deep.channel(n).is_some(); let rgb = has("R") && has("G") && has("B"); @@ -569,6 +580,10 @@ pub(crate) fn flatten(deep: &DeepImage) -> Result { return Err(CodecError::unsupported(F, "no R/G/B or Y channels in the deep part")); }; let nc = layout.channels(); + // Admit the flattened output at its true size: nc f32 samples per pixel. The deep decode + // admitted the data window at four bytes per pixel, before the flattened channel layout + // was known, so re-check here with the actual layout and f32 sample size. + limits.check_bytes(deep.width, deep.height, nc as u64 * 4)?; let samples = |n: &str| -> &[f32] { deep.channel(n).map(|c| c.samples.as_slice()).unwrap_or(&[]) }; let (r, g, b) = (samples("R"), samples("G"), samples("B")); let (ar, ag, ab) = (samples("AR"), samples("AG"), samples("AB")); @@ -665,6 +680,10 @@ pub(crate) fn flatten(deep: &DeepImage) -> Result { // pads to the stage at its offset, transparent elsewhere (limits validated the size). let mut img = match deep.stage { Some((sw, sh)) => { + // The display stage can be larger than the data window; admit it at the real f32 + // layout size before allocating, since the earlier deep-decode check used four + // bytes per pixel and did not know the flattened channel count. + limits.check_bytes(sw, sh, nc as u64 * 4)?; let mut padded = vec![0f32; sw as usize * sh as usize * nc]; let row_len = deep.width as usize * nc; let dx = deep.origin.0.max(0) as usize; diff --git a/crates/codecs/src/codecs/exr.rs b/crates/codecs/src/codecs/exr.rs index 1b268ac559..2b32a2b7c4 100644 --- a/crates/codecs/src/codecs/exr.rs +++ b/crates/codecs/src/codecs/exr.rs @@ -164,7 +164,7 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result // composite the samples into the flat image (a warning says what was lost). if meta.requirements.has_deep_data { let deep = super::deep_exr::decode_deep(&meta, bytes, limits)?; - return super::deep_exr::flatten(&deep); + return super::deep_exr::flatten(&deep, limits); } let pick = pick_part(&meta); From fed04ecef3ddca7e2058b96c37ec37e18ef50487 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:19:08 -0400 Subject: [PATCH 35/54] security(codecs): budget Cryptomatte per-pixel pair capacity The decode admission counted each pixel's channel samples and vector header but not the heap capacity of the per-pixel (id, coverage) pair lists. A compressed Cryptomatte document could therefore return pixel storage exceeding the caller's max_alloc budget. Include the maximum pair capacity (one pair per rank, 8 bytes each) in the per-pixel byte count before check_bytes. Finding: 5482ed4a-bc95-43fc-84d1-d5bfb6373761 (CWE-400) --- crates/codecs/src/codecs/exr_cryptomatte.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/codecs/src/codecs/exr_cryptomatte.rs b/crates/codecs/src/codecs/exr_cryptomatte.rs index 5f13f98621..91a5ede22d 100644 --- a/crates/codecs/src/codecs/exr_cryptomatte.rs +++ b/crates/codecs/src/codecs/exr_cryptomatte.rs @@ -217,14 +217,18 @@ pub(crate) fn decode(bytes: &[u8], layer_name: &str, limits: &Limits) -> Result< let too_large = || CodecError::malformed(F, "the layer is too large"); let (w32, h32) = (u32::try_from(w).map_err(|_| too_large())?, u32::try_from(h).map_err(|_| too_large())?); // Each pixel also gets a pair list, so count its header with the channel samples (four - // f32 channels per set: two ranks of ID and coverage). - let per_pixel = (layer.channels.len().max(1) as u64).saturating_mul(16).saturating_add(std::mem::size_of::>() as u64); + // f32 channels per set: two ranks of ID and coverage). Include the heap capacity the pair + // list can reach: up to one (id, coverage) pair per rank, 8 bytes each. Without this the + // returned per-pixel vectors could exceed the caller's max_alloc budget. + let ranks = layer.channels.len().saturating_mul(2); + let pair_capacity = (ranks as u64).saturating_mul(std::mem::size_of::<(f32, f32)>() as u64); + let per_pixel = + (layer.channels.len().max(1) as u64).saturating_mul(16).saturating_add(std::mem::size_of::>() as u64).saturating_add(pair_capacity); limits.check_bytes(w32, h32, per_pixel)?; let ex_layer = super::exr::read_layer(bytes, layer.part)?; // Two (ID, coverage) ranks per set: rank `slot * 2 + stream.rank`. - let ranks = layer.channels.len().saturating_mul(2); let mut ids: Vec> = vec![Vec::new(); ranks]; let mut coverages: Vec> = vec![Vec::new(); ranks]; for c in &ex_layer.channel_data.list { From 9e8a3eecf06a4ba70e29bede20786ce2cd7397ae Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:18:04 -0400 Subject: [PATCH 36/54] security(cms): bound inverse-curve and CLUT interpolation work Two per-pixel/per-sample amplifiers driven by a crafted ICC profile: - table_inverse recomputed a sampled curve's flat-run edge indices by scanning the whole table on every call, and transform construction inverts each destination curve OUT_TABLE times. Compute the edges once per curve via a new Curve::inverse_table batch method. - eval_multilinear enumerated 2^inputs cube corners over every declared input, including single-grid-point (degenerate) dimensions that contribute nothing. Interpolate over the effective dimensions only, so a 15-channel CLUT of one-point dims no longer does 2^15 iterations per pixel. Findings: - acfbe3a3-ee58-4b7e-b72a-5a4877dd15c9 (CWE-407, repeated flat-run scans) - 9fcc72e7-46d6-4f75-9333-cb14a65eeafd (CWE-407, degenerate-dim corner blowup) --- crates/cms/src/clut.rs | 27 +++++++++++++++++--- crates/cms/src/curve.rs | 49 +++++++++++++++++++++++++++++++++++-- crates/cms/src/transform.rs | 11 ++++----- 3 files changed, 76 insertions(+), 11 deletions(-) diff --git a/crates/cms/src/clut.rs b/crates/cms/src/clut.rs index 186cd3f9f1..38992a2ed4 100644 --- a/crates/cms/src/clut.rs +++ b/crates/cms/src/clut.rs @@ -172,11 +172,16 @@ impl Clut { } let o = self.outputs; out[..o].iter_mut().for_each(|v| *v = 0.0); - for corner in 0..(1usize << n) { + // Only dimensions with more than one grid point contribute a cube axis. Degenerate + // dimensions have step 0 and ratio 0, so they always multiply the corner weight by 1 + // and never change the offset; enumerating 2^n corners over all declared inputs would + // do 2^(degenerate) redundant iterations. Interpolate over the effective dims only. + let eff: Vec = (0..n).filter(|&d| s[d] != 0).collect(); + for corner in 0..(1usize << eff.len()) { let mut w = 1.0f32; let mut off = base; - for d in 0..n { - if corner & (1 << d) != 0 { + for (bit, &d) in eff.iter().enumerate() { + if corner & (1 << bit) != 0 { w *= r[d]; off += s[d]; } else { @@ -245,4 +250,20 @@ mod tests { c.eval(&[0.5, 0.25], &mut o); assert!((o[0] - 0.75).abs() < 1e-6); } + + #[test] + fn degenerate_dimensions_do_not_change_the_result() { + // Dimensions with a single grid point contribute nothing, but the old code still + // enumerated 2^inputs corners over them. Interpolating over effective dims only must + // give the same answer as a reference built without the degenerate axes. + let f = |p: &[f32], o: &mut [f32]| o[0] = 0.25 * p[0] + 0.5 * p[2] + 0.125 * p[4]; + // Axes 1 and 3 have a single grid point (degenerate); axes 0, 2, 4 vary. + let c = Clut::sample(vec![3, 1, 4, 1, 5], 1, f); + let mut got = [0.0]; + for p in [[0.2f32, 0.0, 0.7, 0.0, 0.4], [1.0, 0.0, 0.0, 0.0, 1.0], [0.5, 0.0, 0.5, 0.0, 0.5]] { + c.eval_multilinear(&p, &mut got); + let want = 0.25 * p[0] + 0.5 * p[2] + 0.125 * p[4]; + assert!((got[0] - want).abs() < 1e-5, "got {} want {want}", got[0]); + } + } } diff --git a/crates/cms/src/curve.rs b/crates/cms/src/curve.rs index fe23e6e059..8b619842d1 100644 --- a/crates/cms/src/curve.rs +++ b/crates/cms/src/curve.rs @@ -99,6 +99,20 @@ impl Curve { (0..n).map(|i| self.eval64(i as f64 / (n - 1) as f64) as f32).collect() } + /// Inverse of the curve at each `y` in `ys`. For sampled-table curves the flat-run edge + /// indices are computed once for the whole batch instead of rescanning the table on every + /// call, so inverting a long constant table many times stays linear. + pub fn inverse_table(&self, ys: impl Iterator) -> Vec { + match self { + Curve::Table(t) if t.len() >= 2 => { + let increasing = t[t.len() - 1] >= t[0]; + let (edge_start, edge_end) = (edge_index(t, true), edge_index(t, false)); + ys.map(|y| table_inverse_with(t, y as f32, increasing, edge_start, edge_end)).collect() + } + _ => ys.map(|y| self.eval_inverse64(y) as f32).collect(), + } + } + /// `true` when the curve never decreases over `[0, 1]`. pub fn is_monotonic(&self) -> bool { let s = self.sample(1024); @@ -244,13 +258,24 @@ fn table_inverse(t: &[f32], y: f32) -> f32 { return y; } let increasing = t[n - 1] >= t[0]; + table_inverse_with(t, y, increasing, edge_index(t, true), edge_index(t, false)) +} + +/// [`table_inverse`] with the flat-run edge indices supplied. Computing those edges scans the +/// whole table, and transform construction inverts the same table thousands of times, so the +/// edges are computed once and reused across a batch (see [`Curve::inverse_table`]). +fn table_inverse_with(t: &[f32], y: f32, increasing: bool, edge_start: f32, edge_end: f32) -> f32 { + let n = t.len(); + if n < 2 { + return y; + } let (lo_v, hi_v) = if increasing { (t[0], t[n - 1]) } else { (t[n - 1], t[0]) }; if y <= lo_v { // Flat start: choose the last index still at the lowest value. - return if increasing { edge_index(t, true) } else { edge_index(t, false) }; + return if increasing { edge_start } else { edge_end }; } if y >= hi_v { - return if increasing { edge_index(t, false) } else { edge_index(t, true) }; + return if increasing { edge_end } else { edge_start }; } let (mut lo, mut hi) = (0usize, n - 1); while hi - lo > 1 { @@ -336,4 +361,24 @@ mod tests { let g = Curve::Gamma(2.2); assert!((g.eval64(-0.5) + 0.5f64.powf(2.2)).abs() < 1e-12); } + + #[test] + fn inverse_table_matches_per_call_including_flat_runs() { + // Batch inverse must equal calling eval_inverse64 per point. Include a table with flat + // runs at both ends (the case that used to rescan the table on every call). + let tables = [ + Curve::Table(vec![0.0, 0.0, 0.0, 0.25, 0.5, 1.0, 1.0, 1.0]), + Curve::Table(vec![0.0, 0.2, 0.4, 0.6, 0.8, 1.0]), + Curve::Table(vec![1.0, 0.5, 0.0]), + Curve::Gamma(2.2), + ]; + let ys: Vec = (0..=40).map(|i| i as f64 / 40.0).collect(); + for c in &tables { + let batch = c.inverse_table(ys.iter().copied()); + for (i, &y) in ys.iter().enumerate() { + let one = c.eval_inverse64(y) as f32; + assert!((batch[i] - one).abs() < 1e-6, "y={y}: batch {} vs per-call {one}", batch[i]); + } + } + } } diff --git a/crates/cms/src/transform.rs b/crates/cms/src/transform.rs index 04d11247f4..f30c17c82e 100644 --- a/crates/cms/src/transform.rs +++ b/crates/cms/src/transform.rs @@ -133,12 +133,11 @@ impl Transform { let tables = cs .iter() .map(|c| { - (0..OUT_TABLE) - .map(|i| { - let u = i as f64 / (OUT_TABLE - 1) as f64; - c.eval_inverse64(u * u * u * u).clamp(0.0, 1.0) as f32 - }) - .collect() + let ys = (0..OUT_TABLE).map(|i| { + let u = i as f64 / (OUT_TABLE - 1) as f64; + u * u * u * u + }); + c.inverse_table(ys).into_iter().map(|v| v.clamp(0.0, 1.0)).collect() }) .collect(); post = Some(Post { tables }); From 58cd22d4ff09a45357fc45b1563afd6a2b0a4632 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:15:37 -0400 Subject: [PATCH 37/54] security(doc): compute auto-slice coverage per band, not per cell auto_slices tested every grid cell against the full slice-rectangle list (covered(x, y) = taken.iter().any(...)). With slice edges forming the grid, that is cubic in the slice count, so a crafted document's slice arrangement could stall ordinary canvas drawing on the UI thread. For each row band, mark covered x-cells in a single pass over the rects that span the band, then scan the precomputed cells. This drops the inner work from O(rects) per cell to O(1), while producing the same tiling. Finding: 9fbea43b-3096-4cdc-b005-86d44a8fe57e (CWE-400) --- crates/doc/src/slices.rs | 77 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 71 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/slices.rs b/crates/doc/src/slices.rs index e22fcc0b79..7fb6ba3ad5 100644 --- a/crates/doc/src/slices.rs +++ b/crates/doc/src/slices.rs @@ -202,24 +202,42 @@ pub fn auto_slices(canvas: Rect, taken: &[Rect]) -> Vec { xs.dedup(); ys.sort_unstable(); ys.dedup(); - let covered = |x0: i32, y0: i32| taken.iter().any(|r| x0 >= r.x0 && x0 < r.x1 && y0 >= r.y0 && y0 < r.y1); - // Horizontal runs per row band. + // Clip the taken rectangles to the canvas once, so band coverage only considers rects that + // can actually cover a cell. + let clipped: Vec = taken.iter().map(|r| r.intersect(&canvas)).filter(|r| !r.is_empty()).collect(); + // Map an x edge to its cell index in `xs` (xs is sorted/deduped). + let x_cell = |x: i32| xs.partition_point(|&e| e <= x).saturating_sub(1); + // Horizontal runs per row band. For each band, mark covered x-cells in a single pass over + // the rects intersecting that band, instead of scanning every rect for every cell (which + // was cubic in the slice count and let a crafted document stall canvas drawing). + let ncells = xs.len().saturating_sub(1); let mut runs: Vec = Vec::new(); for yw in ys.windows(2) { + let (band_y0, band_y1) = (yw[0], yw[1]); + let mut covered_cell = vec![false; ncells]; + for r in &clipped { + if r.y0 <= band_y0 && band_y1 <= r.y1 { + // Rect spans this whole band vertically; mark the x-cells it covers. + let (c0, c1) = (x_cell(r.x0), x_cell(r.x1)); + for c in covered_cell.iter_mut().take(c1).skip(c0) { + *c = true; + } + } + } let mut start: Option = None; - for xw in xs.windows(2) { - let free = !covered(xw[0], yw[0]); + for (ci, xw) in xs.windows(2).enumerate() { + let free = !covered_cell.get(ci).copied().unwrap_or(false); match (free, start) { (true, None) => start = Some(xw[0]), (false, Some(s)) => { - runs.push(Rect::new(s, yw[0], xw[0], yw[1])); + runs.push(Rect::new(s, band_y0, xw[0], band_y1)); start = None; } _ => {} } } if let Some(s) = start { - runs.push(Rect::new(s, yw[0], *xs.last().unwrap_or(&canvas.x1), yw[1])); + runs.push(Rect::new(s, band_y0, *xs.last().unwrap_or(&canvas.x1), band_y1)); } } // Merge vertically adjacent runs with the same columns. @@ -299,6 +317,53 @@ mod tests { assert_eq!(auto_slices(canvas, &[]), vec![canvas]); } + #[test] + fn auto_slices_cover_exactly_with_many_overlapping_slices() { + // Several overlapping slices form a non-trivial grid. The per-band coverage pass must + // still tile the complement exactly: auto area + taken-union area == canvas, with no + // auto slice overlapping a taken rect or another auto slice. + let canvas = Rect::new(0, 0, 200, 150); + let taken = [Rect::new(10, 10, 90, 70), Rect::new(50, 40, 160, 120), Rect::new(120, 0, 200, 50), Rect::new(0, 100, 60, 150)]; + let auto = auto_slices(canvas, &taken); + // No auto slice intersects any taken rect. + for a in &auto { + for t in &taken { + assert!(a.intersect(t).is_empty(), "{a:?} overlaps taken {t:?}"); + } + } + // Auto slices do not overlap each other. + for (i, a) in auto.iter().enumerate() { + for b in &auto[i + 1..] { + assert!(a.intersect(b).is_empty(), "{a:?} overlaps {b:?}"); + } + } + // Auto area equals the canvas minus the union of taken rects (computed on the same grid). + let union_cells: i64 = { + // Sum cell areas covered by at least one taken rect, over the fine grid. + let mut xs = vec![canvas.x0, canvas.x1]; + let mut ys = vec![canvas.y0, canvas.y1]; + for t in &taken { + xs.extend([t.x0, t.x1]); + ys.extend([t.y0, t.y1]); + } + xs.sort_unstable(); + xs.dedup(); + ys.sort_unstable(); + ys.dedup(); + let mut sum = 0i64; + for yw in ys.windows(2) { + for xw in xs.windows(2) { + let covered = taken.iter().any(|r| xw[0] >= r.x0 && xw[0] < r.x1 && yw[0] >= r.y0 && yw[0] < r.y1); + if covered { + sum += i64::from(xw[1] - xw[0]) * i64::from(yw[1] - yw[0]); + } + } + } + sum + }; + assert_eq!(area(&auto) + union_cells, i64::from(canvas.width()) * i64::from(canvas.height())); + } + #[test] fn resolve_numbers_top_to_bottom() { let mut d = Document::new("site.psd", Size::new(100, 80), ColorMode::Rgb, SampleType::U8); From d0ad7ddb6fa085081d184b7d67ea5ce2b2e6ba7c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:13:56 -0400 Subject: [PATCH 38/54] security(psd): check padding length before scanning it FilterEffects::parse tested the trailing bytes with rest.iter().all(|b| b == 0) before checking rest.len() <= 3, so every loop iteration scanned the whole remaining buffer. A block with many empty sections produced quadratic CPU work. Reorder the short-circuiting && so the three-byte length check gates the zero scan, making each padding check constant work. Behavior is otherwise identical. Finding: 4887ae49-cfda-43b0-9296-a1816fc1ddba (CWE-407) --- crates/psd/src/filter_effects.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/psd/src/filter_effects.rs b/crates/psd/src/filter_effects.rs index e8b5efb698..cadb3ac8d0 100644 --- a/crates/psd/src/filter_effects.rs +++ b/crates/psd/src/filter_effects.rs @@ -170,7 +170,10 @@ impl FilterEffects { let pad = ((4 - len % 4) % 4).min(r.remaining() as u64); r.skip(pad as usize)?; let rest = r.peek_rest(); - if rest.iter().all(|&b| b == 0) && rest.len() <= 3 { + // Padding is at most three bytes. Check the length before scanning the suffix for + // zeros: otherwise each iteration scans the whole remaining buffer, which is + // quadratic when a block contains many empty sections. + if rest.len() <= 3 && rest.iter().all(|&b| b == 0) { break; } if rest.len() < 8 { From 7c07280b660ca937529a97f4e9176c79861e2667 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:13:17 -0400 Subject: [PATCH 39/54] security(affinity): bound raw child-slot traversal work Reader::children re-collected a group's child objects by scanning every raw Chld array slot, discarding nulls before the node budget counted anything. A shared group holding a large null-filled child array, linked many times, multiplied into excessive CPU work the MAX_NODES limit never observed. Charge every raw child slot (nulls included) against a document-wide MAX_CHILD_SLOTS budget before filtering, via a new Stream::array_len helper, and return a limit error when it is exhausted. Finding: 3973fcd0-acda-4312-b538-d986dcffeb1c (CWE-400) --- crates/affinity/src/access.rs | 9 +++++++++ crates/affinity/src/model.rs | 15 +++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/crates/affinity/src/access.rs b/crates/affinity/src/access.rs index 0b60ed7dbd..732feeef49 100644 --- a/crates/affinity/src/access.rs +++ b/crates/affinity/src/access.rs @@ -20,6 +20,15 @@ impl Stream { self.class(id) == Some(Tag::of(class)) } + /// The raw slot count of an object's array field (including null slots), for charging + /// traversal work before nulls are filtered out. `None` when the field is not an array. + pub fn array_len(&self, id: ObjId, tag: &[u8; 4]) -> Option { + match self.field(id, tag)? { + Value::Array(a) => Some(a.len()), + _ => None, + } + } + /// A child object (shared, linked or inline); `None` for null or missing. pub fn obj(&self, id: ObjId, tag: &[u8; 4]) -> Option { match self.field(id, tag)? { diff --git a/crates/affinity/src/model.rs b/crates/affinity/src/model.rs index 7c05072419..f77c970ae2 100644 --- a/crates/affinity/src/model.rs +++ b/crates/affinity/src/model.rs @@ -283,6 +283,12 @@ const MAX_TREE_DEPTH: usize = 128; /// Total layer nodes imported. const MAX_NODES: usize = 500_000; +/// Total raw `Chld` slots inspected across the whole traversal, including null slots and slots +/// reached through repeated references to a shared group. The node limit only counts produced +/// nodes, so a shared group holding a large null-filled child array could still be rescanned +/// many times; this bounds that work. Generous relative to MAX_NODES for real documents. +const MAX_CHILD_SLOTS: usize = 8_000_000; + /// Read a document: archive, `doc.dat` and the model. pub fn read(bytes: &[u8], limits: Limits) -> Result { let mut archive = Archive::open(bytes, limits)?; @@ -297,6 +303,7 @@ pub(crate) struct Reader<'s, 'a, 'b> { pub(crate) dpi: f64, warnings: BTreeMap, nodes: usize, + child_slots: usize, active: HashSet, pub(crate) geometry_budget: crate::geometry::Budget, /// Decoded pixels still available ([`Limits::max_pixel_bytes`] less what the layers read so @@ -312,6 +319,7 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> { dpi: 72.0, warnings: BTreeMap::new(), nodes: 0, + child_slots: 0, active: HashSet::new(), geometry_budget: crate::geometry::Budget::default(), pixels_left: limits.max_pixel_bytes, @@ -383,6 +391,13 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> { let s = self.s; let mut out = Vec::new(); let mut mask = None; + // Charge every raw child slot (null slots included) against a document-wide budget + // before filtering. A shared group with a large null-filled Chld array could otherwise + // be rescanned through each reference without the node limit noticing. + self.child_slots = self.child_slots.saturating_add(s.array_len(parent, b"Chld").unwrap_or(0)); + if self.child_slots > MAX_CHILD_SLOTS { + return Err(Error::Limit("too many child slots in the layer tree")); + } for c in s.objs(parent, b"Chld") { if s.is(c, b"MRst") { // A mask layer inside a group or layer masks that container. From 29e555c2f655676c71c26ccea20e6371da9248b2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:12:12 -0400 Subject: [PATCH 40/54] security(affinity): index live-corner radii by record subpath() looked up each polyline anchor's corner radius by scanning the entire radius list, O(anchors * radii). A file supplying large anchor and radius arrays could cause quadratic CPU work before geometry limits inspected the path. Build a record-to-maximum-radius map once and look each anchor up in it, preserving the previous fold(0.0, f64::max) behavior for duplicate record indices. Finding: 89f65d65-f637-44fc-9a81-a9039a413a4b (CWE-407) --- crates/affinity/src/geometry.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/affinity/src/geometry.rs b/crates/affinity/src/geometry.rs index 6c8ea602c9..6825abd511 100644 --- a/crates/affinity/src/geometry.rs +++ b/crates/affinity/src/geometry.rs @@ -210,7 +210,16 @@ fn anchors(records: &[Value]) -> Option> { fn subpath(anchors: &[Anchor], closed: bool, radii: Option<&Vec<(usize, f64)>>) -> Option { let first = anchors.first()?; if let Some(radii) = radii.filter(|r| !r.is_empty()) { - let corner = |a: &Anchor| radii.iter().filter(|(rec, _)| *rec == a.record).map(|(_, r)| *r).fold(0.0, f64::max); + // Index each record's maximum radius once. Scanning the whole radius list per anchor + // was O(anchors * radii), which a file with large anchor and radius arrays could drive + // into quadratic work. Duplicate record indices keep the maximum, matching the prior + // fold(0.0, f64::max) behavior. + let mut radius_by_record: std::collections::HashMap = std::collections::HashMap::with_capacity(radii.len()); + for &(rec, r) in radii { + let slot = radius_by_record.entry(rec).or_insert(0.0); + *slot = slot.max(r); + } + let corner = |a: &Anchor| radius_by_record.get(&a.record).copied().unwrap_or(0.0); let polyline = anchors.iter().all(|a| a.inh.is_none_or(|h| h == a.p) && a.out.is_none_or(|h| h == a.p)); if polyline { let mut pts: Vec<(Point, f64)> = anchors.iter().map(|a| (a.p, corner(a))).collect(); From 5adebc5d6df46a104547f1b9d872ee314ae1945c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:11:40 -0400 Subject: [PATCH 41/54] security(affinity): index object fields for O(1) lookup Object::get scanned the field vector linearly. An Affinity file can define one large shared object and reference it repeatedly as sibling layers, so repeated property lookups multiplied into quadratic CPU work without the fields appearing more than once in the file. Build a first-occurrence tag index when an object's fields are set (via Object::new and set_fields, the latter covering the root object that is filled after it is pushed). Positional fields (tag 0) stay out of the index, and first-match semantics are preserved. Finding: c315c4b0-dceb-459e-b39a-fa9c68ae6f40 (CWE-407) --- crates/affinity/src/stream.rs | 43 +++++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/crates/affinity/src/stream.rs b/crates/affinity/src/stream.rs index a755747c45..2ffe12b7e5 100644 --- a/crates/affinity/src/stream.rs +++ b/crates/affinity/src/stream.rs @@ -73,11 +73,40 @@ pub struct Object { pub chain: Vec, /// Fields in stream order; positional fields have tag 0. pub fields: Vec<(Tag, Value)>, + /// First-occurrence index of each non-positional tag, so `get` is O(1). A shared object + /// can be referenced by many sibling layers, and each reference used to rescan all of its + /// fields; indexing once keeps repeated lookups from multiplying into quadratic work. + index: std::collections::HashMap, } impl Object { + pub fn new(class: Tag, kind: Kind, chain: Vec, fields: Vec<(Tag, Value)>) -> Self { + let mut index = std::collections::HashMap::with_capacity(fields.len()); + for (i, (t, _)) in fields.iter().enumerate() { + // Positional fields share tag 0 and are not looked up by tag; keep first-match + // semantics for real tags. + if t.0 != 0 { + index.entry(*t).or_insert(i); + } + } + Object { class, kind, chain, fields, index } + } + pub fn get(&self, tag: Tag) -> Option<&Value> { - self.fields.iter().find(|(t, _)| *t == tag).map(|(_, v)| v) + self.index.get(&tag).map(|&i| &self.fields[i].1) + } + + /// Replaces the fields (the root object is filled in after it is pushed) and rebuilds the + /// tag index so `get` stays correct. + fn set_fields(&mut self, fields: Vec<(Tag, Value)>) { + self.index.clear(); + self.index.reserve(fields.len()); + for (i, (t, _)) in fields.iter().enumerate() { + if t.0 != 0 { + self.index.entry(*t).or_insert(i); + } + } + self.fields = fields; } } @@ -124,10 +153,10 @@ pub fn parse(bytes: &[u8]) -> Result { c.u32()?; } let mut p = Parser { c, objects: Vec::new(), shared: std::collections::HashMap::new(), depth: 0, values: 0 }; - let root = p.push(Object { class, kind: Kind::Root, chain: vec![class], fields: Vec::new() })?; + let root = p.push(Object::new(class, Kind::Root, vec![class], Vec::new()))?; let fields = p.fields(true, class)?; if let Some(o) = p.objects.get_mut(root) { - o.fields = fields; + o.set_fields(fields); } Ok(Stream { root, objects: p.objects }) } @@ -252,7 +281,7 @@ impl Parser<'_> { } 0x30 => { let fields = self.fields(false, class)?; - let id = self.push(Object { class, kind: Kind::Positional, chain: Vec::new(), fields })?; + let id = self.push(Object::new(class, Kind::Positional, Vec::new(), fields))?; Value::Obj(Some(id)) } 0x31 | 0x32 if !tagged => return Err(Error::Malformed("object without a field tag")), @@ -350,7 +379,7 @@ impl Parser<'_> { } }; let fields = self.fields(true, class)?; - let id = self.push(Object { class, kind: Kind::Inline, chain: vec![class], fields })?; + let id = self.push(Object::new(class, Kind::Inline, vec![class], fields))?; Ok(Value::Obj(Some(id))) } @@ -369,7 +398,7 @@ impl Parser<'_> { return Err(Error::Malformed("object defined twice")); } // Register before the fields: an object's own fields may refer back to it. - let id = self.push(Object { class: Tag(0), kind: Kind::Shared, chain: Vec::new(), fields: Vec::new() })?; + let id = self.push(Object::new(Tag(0), Kind::Shared, Vec::new(), Vec::new()))?; self.shared.insert(key, id); let mut chain = Vec::new(); let mut fields = Vec::new(); @@ -395,7 +424,7 @@ impl Parser<'_> { let class = chain.first().copied().unwrap_or(Tag(0)); fields.extend(self.fields(true, class)?); if let Some(o) = self.objects.get_mut(id) { - *o = Object { class, kind: Kind::Shared, chain, fields }; + *o = Object::new(class, Kind::Shared, chain, fields); } Ok(Value::Obj(Some(id))) } From ef6092b12506d5c4587445c7590721d1b0c11e21 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 21:24:39 -0400 Subject: [PATCH 42/54] security(xtask): validate corpus paths and bound symlink traversal Row 16 (9f6a3c79): preserve platform filename semantics in corpus scans (no backslash-to-separator rewrite on Unix) and enforce destination containment before copying files into the corpus directory. Row 20 (6e2a985b): skip directory symlinks, dedupe visited directories by canonical identity, and cap total directories/files so symlink cycles can no longer drive exponential traversal. Fixes findings 9f6a3c79-8bdf-4751-8eb4-87d3154074c9 and 6e2a985b-6b14-4b97-af07-7ca8333b9b75. --- xtask/src/pinned.rs | 175 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 168 insertions(+), 7 deletions(-) diff --git a/xtask/src/pinned.rs b/xtask/src/pinned.rs index d480051599..baf798f1de 100644 --- a/xtask/src/pinned.rs +++ b/xtask/src/pinned.rs @@ -71,13 +71,53 @@ impl PinnedCorpus { .collect() } + /// Upper bound on directories visited and files collected during a single `collect` walk. + /// A corpus clone is operator-selected but can still contain attacker-planted symlinks; these + /// budgets keep a malformed tree from expanding into an unbounded traversal before the + /// manifest check runs. Real corpora are a few thousand files at most. + const MAX_DIRS: usize = 100_000; + const MAX_FILES: usize = 1_000_000; + fn collect(&self, dir: &Path, base: &Path, out: &mut Vec) { + let mut visited = std::collections::HashSet::new(); + let mut dirs = 0usize; + self.collect_inner(dir, base, out, &mut visited, &mut dirs); + } + + /// Walks `dir`, skipping directory symlinks and directories already seen through another + /// alias, and stops once the traversal or file budget is reached. `visited` holds resolved + /// directory identities (canonical paths) so two links to the same ancestor cannot make the + /// walk revisit it. + fn collect_inner(&self, dir: &Path, base: &Path, out: &mut Vec, visited: &mut std::collections::HashSet, dirs: &mut usize) { + if out.len() >= Self::MAX_FILES || *dirs >= Self::MAX_DIRS { + return; + } + // Record this directory by its resolved identity; bail if we have already walked it + // (a symlink cycle) or cannot resolve it. + match std::fs::canonicalize(dir) { + Ok(real) => { + if !visited.insert(real) { + return; + } + } + Err(_) => return, + } + *dirs += 1; let Ok(rd) = std::fs::read_dir(dir) else { return }; for e in rd.flatten() { + if out.len() >= Self::MAX_FILES || *dirs >= Self::MAX_DIRS { + return; + } let p = e.path(); - if p.is_dir() { - self.collect(&p, base, out); - } else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| self.exts.iter().any(|x| e.eq_ignore_ascii_case(x))) { + // Use the entry's own metadata (do not follow links) to classify it. A directory + // symlink is skipped entirely so aliases to ancestors cannot drive the recursion. + let Ok(ft) = e.file_type() else { continue }; + if ft.is_symlink() { + continue; + } + if ft.is_dir() { + self.collect_inner(&p, base, out, visited, dirs); + } else if ft.is_file() && p.extension().and_then(|e| e.to_str()).is_some_and(|e| self.exts.iter().any(|x| e.eq_ignore_ascii_case(x))) { out.push(p.strip_prefix(base).unwrap_or(&p).to_path_buf()); } } @@ -89,7 +129,11 @@ impl PinnedCorpus { self.collect(dir, dir, &mut found); let mut out = Vec::new(); for f in found { - let rel = f.to_string_lossy().replace('\\', "/"); + // Build the manifest-relative path from the path's own components, joined with `/`. + // This preserves platform filename semantics: a Unix file literally named `a\b` keeps + // its backslash instead of being split into a fake `a/b` traversal component. Reject + // anything that is not a sequence of plain names (absolute roots, `..`, etc.). + let rel = rel_manifest_path(&f).ok_or_else(|| format!("unsafe corpus path {}", f.display()))?; let bytes = std::fs::read(dir.join(&f)).map_err(|e| format!("read {rel}: {e}"))?; out.push((sha256::hex(&bytes), format!("{prefix}{rel}"))); } @@ -144,12 +188,14 @@ impl PinnedCorpus { } }; for (_, file) in files { + let to = safe_dest_join(&dest, file).ok_or_else(|| format!("{file}: escapes corpus destination"))?; let from = locate(file).ok_or_else(|| format!("{file}: no upstream"))?; - place(&from, &dest.join(file))?; + place(&from, &to)?; } - for (from, to) in extras { + for (from, to_rel) in extras { if from.is_file() { - place(from, &dest.join(to))?; + let to = safe_dest_join(&dest, to_rel).ok_or_else(|| format!("{to_rel}: escapes corpus destination"))?; + place(from, &to)?; } } std::fs::write(dest.join("SOURCES.md"), (self.sources_md)(self)).map_err(|e| format!("write SOURCES.md: {e}"))?; @@ -269,6 +315,49 @@ impl PinnedCorpus { } } +/// Builds a `/`-joined manifest-relative path from a scanned relative path, using only the path's +/// own `Normal` components. Returns `None` if any component is a root, prefix, current-dir, or +/// parent-dir (`..`) element, so a scanned entry can never introduce traversal. Literal +/// backslashes inside a single Unix filename are preserved (they are part of the name, not a +/// separator). +fn rel_manifest_path(rel: &Path) -> Option { + use std::path::Component; + let mut parts = Vec::new(); + for comp in rel.components() { + match comp { + Component::Normal(os) => parts.push(os.to_str()?.to_string()), + // Root, prefix, `.` and `..` are all rejected: a corpus entry must be a plain, + // forward relative path beneath the scan root. + _ => return None, + } + } + if parts.is_empty() { + return None; + } + Some(parts.join("/")) +} + +/// Joins a manifest-relative corpus path onto `dest`, guaranteeing the result stays within +/// `dest`. Rejects absolute paths, parent-directory components, and any entry that would resolve +/// outside the destination. Returns the concrete target path on success. +fn safe_dest_join(dest: &Path, rel: &str) -> Option { + use std::path::Component; + let rel_path = Path::new(rel); + let mut out = dest.to_path_buf(); + for comp in rel_path.components() { + match comp { + Component::Normal(os) => out.push(os), + // Any non-plain component (root, prefix, `.`, `..`) could escape the destination. + _ => return None, + } + } + // The join must have added at least one component and must remain under `dest`. + if out == *dest || !out.starts_with(dest) { + return None; + } + Some(out) +} + /// Hex sha256 of a corpus file (reused by every corpus fetch, `xtask/pixls.sha256` included). fn file_hex(path: &std::path::Path) -> Option { std::fs::read(path).ok().map(|b| crate::sha256::hex(&b)) @@ -317,3 +406,75 @@ pub fn fetch_pixls(update: bool) -> Result<(), String> { println!("pixls: {} files verified in {}", crate::corpus_pins::PIXLS_FILES.len(), dest.display()); Ok(()) } + +#[cfg(test)] +mod tests { + use super::{rel_manifest_path, safe_dest_join}; + use std::path::{Path, PathBuf}; + + #[test] + fn rel_manifest_joins_normal_components_with_forward_slash() { + assert_eq!(rel_manifest_path(Path::new("a/b/c.psd")).as_deref(), Some("a/b/c.psd")); + assert_eq!(rel_manifest_path(Path::new("file.psd")).as_deref(), Some("file.psd")); + } + + #[test] + #[cfg(unix)] + fn rel_manifest_preserves_literal_backslash_in_unix_filename() { + // On Unix a backslash is an ordinary filename character, not a separator. The old code + // turned `weird\name.psd` into `weird/name.psd`, inventing a path component that the + // installer would then treat as a subdirectory. The component must be kept intact. + let rel = Path::new("weird\\name.psd"); + assert_eq!(rel_manifest_path(rel).as_deref(), Some("weird\\name.psd")); + } + + #[test] + fn rel_manifest_rejects_traversal_and_absolute() { + assert_eq!(rel_manifest_path(Path::new("../escape.psd")), None); + assert_eq!(rel_manifest_path(Path::new("a/../../escape.psd")), None); + assert_eq!(rel_manifest_path(Path::new("/abs/path.psd")), None); + assert_eq!(rel_manifest_path(Path::new("")), None); + } + + #[test] + fn safe_dest_join_contains_normal_paths() { + let dest = PathBuf::from("/corpus/psd"); + let got = safe_dest_join(&dest, "sub/dir/file.psd").expect("normal path allowed"); + assert!(got.starts_with(&dest)); + assert!(got.ends_with("sub/dir/file.psd")); + } + + #[test] + fn safe_dest_join_rejects_escapes() { + let dest = PathBuf::from("/corpus/psd"); + assert_eq!(safe_dest_join(&dest, "../../etc/passwd"), None); + assert_eq!(safe_dest_join(&dest, "/etc/passwd"), None); + assert_eq!(safe_dest_join(&dest, "a/../../b"), None); + // An empty relative path would resolve to `dest` itself, not a file within it. + assert_eq!(safe_dest_join(&dest, ""), None); + } + + #[test] + #[cfg(unix)] + fn collect_skips_directory_symlinks_and_cycles() { + use std::os::unix::fs::symlink; + + let tmp = std::env::temp_dir().join(format!("pinned-collect-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&tmp); + std::fs::create_dir_all(tmp.join("real")).unwrap(); + std::fs::write(tmp.join("real/a.psd"), b"data").unwrap(); + // A symlink back to an ancestor: the old collector would follow it and recurse forever. + symlink(&tmp, tmp.join("real/loop")).unwrap(); + // A symlink to a sibling directory also must not be descended into. + symlink(tmp.join("real"), tmp.join("alias")).unwrap(); + + let corpus = + super::PinnedCorpus { name: "t", dest: "t", upstreams: &[], manifest: "t.sha256", exts: &["psd"], subset: false, sources_md: |_| String::new() }; + let mut out = Vec::new(); + corpus.collect(&tmp, &tmp, &mut out); + // Exactly one real file is found; symlinked directories are skipped (no cycle, no dupes). + assert_eq!(out, vec![PathBuf::from("real/a.psd")]); + + let _ = std::fs::remove_dir_all(&tmp); + } +} From 2c02d06392fae1aeeac1360c7925a28a19c25e19 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:05:47 -0400 Subject: [PATCH 43/54] security(engine): count GIF frame delays with a map fps_from_delays counted each frame's delay by scanning a growing vector with iter_mut().find(), O(n^2) for a GIF with many distinct delays. A crafted animation within the frame limit could stall the synchronous import path. Count delays in a HashMap and keep a first-seen order vector so the most-common delay still wins, breaking ties toward the earliest-seen delay exactly as before. Finding: 23d54421-8e26-41b9-9690-ae1125ee2f85 (CWE-407) --- crates/engine/src/video_cmds.rs | 24 ++++++++++++++++-------- crates/engine/src/video_cmds/tests.rs | 16 ++++++++++++++++ 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/video_cmds.rs b/crates/engine/src/video_cmds.rs index 0d27d3c827..ddee127f2b 100644 --- a/crates/engine/src/video_cmds.rs +++ b/crates/engine/src/video_cmds.rs @@ -227,16 +227,24 @@ struct Footage { /// do, since they would otherwise play at an unintended 50-100 fps. fn fps_from_delays(delays: &[u32]) -> Option { let clean = |d: u32| if d < 20 { 100 } else { d }; - let mut counts: Vec<(u32, usize)> = Vec::new(); + // Count delays with a map keyed on the cleaned delay, recording first-seen order + // separately. A linear scan per frame (iter_mut().find) was O(n^2) for a GIF with many + // distinct delays. order[] preserves the tie-break: the earliest-seen delay wins. + let mut counts: std::collections::HashMap = std::collections::HashMap::new(); + let mut order: Vec = Vec::new(); for d in delays.iter().copied().map(clean) { - match counts.iter_mut().find(|(k, _)| *k == d) { - Some((_, n)) => *n += 1, - None => counts.push((d, 1)), - } + let n = counts.entry(d).or_insert_with(|| { + order.push(d); + 0 + }); + *n += 1; } - let best = counts.iter().fold(None::<(u32, usize)>, |best, &(d, n)| match best { - Some((_, bn)) if bn >= n => best, - _ => Some((d, n)), + let best = order.iter().fold(None::<(u32, usize)>, |best, &d| { + let n = counts[&d]; + match best { + Some((_, bn)) if bn >= n => best, + _ => Some((d, n)), + } }); best.map(|(d, _)| 1000.0 / d as f32) } diff --git a/crates/engine/src/video_cmds/tests.rs b/crates/engine/src/video_cmds/tests.rs index 3cdda8adc0..c97eb3b18d 100644 --- a/crates/engine/src/video_cmds/tests.rs +++ b/crates/engine/src/video_cmds/tests.rs @@ -579,3 +579,19 @@ fn render_video_rejects_gif_frames_too_large_to_stage() { let err = s.execute("file.export.renderVideo", json!({"dir": tmpdir("large-gif"), "format": "gif"})).unwrap_err(); assert!(err.to_string().contains("too large"), "{err}"); } + +#[test] +fn fps_from_delays_picks_most_common_and_breaks_ties_by_first_seen() { + // Most common delay wins: 100 ms appears twice, 40 ms once -> 10 fps. + assert_eq!(fps_from_delays(&[100, 40, 100]), Some(10.0)); + // Tie between 40 ms (25 fps) and 50 ms (20 fps): the first seen (40) wins. + assert_eq!(fps_from_delays(&[40, 50]), Some(25.0)); + // Delays under 20 ms are treated as 100 ms. + assert_eq!(fps_from_delays(&[0, 10, 5]), Some(10.0)); + assert_eq!(fps_from_delays(&[]), None); + // Many distinct delays used to be quadratic; this must stay fast and correct. Delay 20 + // (the one appearing twice) wins at 50 fps. + let mut many: Vec = (20..5_020).collect(); + many.push(20); + assert_eq!(fps_from_delays(&many), Some(50.0)); +} From ac7eca536aa8c9ac0eee622139511307aa3d8482 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:03:50 -0400 Subject: [PATCH 44/54] security(engine): convert spelling offsets in one pass The spelling list converted each misspelling's start and end byte offset to a character offset with char_at, which recounts the text prefix from the start every call. A layer with many short misspellings therefore caused quadratic rescanning on the synchronous UI thread. Collect the ascending offsets and map them to character offsets in a single forward walk over the text. char_at is removed (byte_at still handles the reverse direction in change()). Finding: 392eb136-b836-4400-8ed7-f1e4549ff0ae (CWE-407) --- crates/engine/src/type_spell_cmds.rs | 52 ++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/type_spell_cmds.rs b/crates/engine/src/type_spell_cmds.rs index 12a63a364c..c544634e5a 100644 --- a/crates/engine/src/type_spell_cmds.rs +++ b/crates/engine/src/type_spell_cmds.rs @@ -27,8 +27,30 @@ fn byte_at(text: &str, ci: usize) -> usize { text.char_indices().nth(ci).map_or(text.len(), |(b, _)| b) } -fn char_at(text: &str, bi: usize) -> usize { - text[..bi.min(text.len())].chars().count() +/// Maps ascending byte offsets to character offsets in a single forward pass. Calling +/// `char_at` per offset rescans the text prefix each time, which is quadratic when a layer +/// has many misspellings; this walks the text once for the whole batch. `offsets` must be +/// sorted ascending (misspelling start/end pairs are, since words are found left to right). +fn char_offsets(text: &str, offsets: &[usize]) -> Vec { + // (byte offset, char index) for each char boundary, plus the end-of-text boundary. + let mut boundaries = text.char_indices().map(|(b, _)| b); + let mut char_index = 0usize; + let mut current = boundaries.next(); + let mut result = Vec::with_capacity(offsets.len()); + for &target in offsets { + let clamped = target.min(text.len()); + // Advance to the first boundary at or past `clamped`; byte offsets from char + // boundaries land exactly on one, so the char index there is the answer. + while let Some(b) = current { + if b >= clamped { + break; + } + char_index += 1; + current = boundaries.next(); + } + result.push(char_index); + } + result } /// Type layers top to bottom (Layers panel order), skipping fully locked ones. @@ -76,10 +98,17 @@ fn list(s: &Session, p: &Value) -> Result { let mut out = Vec::new(); for id in layers_param(s, p) { let Some(t) = text(&st.doc, id) else { continue }; - for m in dict.misspellings(t, &ok) { - out.push( - json!({ "layer": id.0, "start": char_at(t, m.start), "end": char_at(t, m.end), "word": m.word, "suggestions": dict.suggest(&m.word, max) }), - ); + let found = dict.misspellings(t, &ok); + // Convert every start/end byte offset to a character offset in one pass over the + // text, instead of rescanning the prefix with char_at twice per misspelling. + let mut offsets = Vec::with_capacity(found.len() * 2); + for m in &found { + offsets.push(m.start); + offsets.push(m.end); + } + let chars = char_offsets(t, &offsets); + for (i, m) in found.iter().enumerate() { + out.push(json!({ "layer": id.0, "start": chars[i * 2], "end": chars[i * 2 + 1], "word": m.word, "suggestions": dict.suggest(&m.word, max) })); } } Ok(json!({ "misspellings": out, "count": out.len() })) @@ -263,6 +292,17 @@ pub fn specs() -> Vec { mod tests { use super::*; + #[test] + fn char_offsets_matches_per_offset_counting() { + // Multibyte text so byte offsets and char offsets differ. The batch result must + // equal counting chars in each prefix individually, including the end-of-text offset. + let text = "café naïve ☃ résumé"; + let targets: Vec = text.char_indices().map(|(b, _)| b).chain(std::iter::once(text.len())).collect(); + let got = char_offsets(text, &targets); + let want: Vec = targets.iter().map(|&b| text[..b.min(text.len())].chars().count()).collect(); + assert_eq!(got, want); + } + fn session(text: &str) -> (Session, u64) { let mut s = Session::new(); s.execute("file.new", json!({"width": 300, "height": 100, "background": "white"})).unwrap(); From 19e8c0d7cd14ae14b2f3b97b61597263e63e9ae0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 22:00:01 -0400 Subject: [PATCH 45/54] security(codecs): stop quadratic rescans in XMP value scanning xmp_values advanced its cursor only past the matched key, so the value-closing search (find(close)) rescanned the remaining packet for every property-like substring. Repeating text such as ' tiff:ResolutionUnit>' inside the packet produced quadratic CPU work even when no real resolution property existed. Advance the cursor past each located value; a missing close delimiter means the value is unterminated, so no later value can parse and the scan stops. Valid multi-value extraction is unchanged. Finding: 6ce55e33-27f0-4fb9-a22f-737382e1d328 (CWE-407) --- crates/codecs/src/resolution.rs | 8 +++++++- crates/codecs/tests/resolution.rs | 11 +++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/codecs/src/resolution.rs b/crates/codecs/src/resolution.rs index cb86001ac9..a787cacbc3 100644 --- a/crates/codecs/src/resolution.rs +++ b/crates/codecs/src/resolution.rs @@ -429,8 +429,14 @@ fn xmp_values(xmp: &str, key: &str) -> Vec<(usize, usize)> { continue; }; let start = xmp.len() - value.len(); - let Some(len) = value.find(close) else { continue }; + // Advance past this value before searching for the next key. Without this, `from` + // only moved past the key text, so property-like text repeated inside an unrelated + // attribute re-ran this full-suffix `find(close)` for every occurrence, which is + // quadratic in the packet size. A missing close means the value is unterminated, so + // no later value can parse either; stop scanning in that case. + let Some(len) = value.find(close) else { break }; out.push((start, start + len)); + from = start + len + close.len_utf8(); } out } diff --git a/crates/codecs/tests/resolution.rs b/crates/codecs/tests/resolution.rs index 15ddc95749..28c8203c96 100644 --- a/crates/codecs/tests/resolution.rs +++ b/crates/codecs/tests/resolution.rs @@ -284,6 +284,17 @@ fn truncated_metadata_never_panics_and_falls_back() { assert_eq!(xmp_resolution(x), None, "{x}"); let _ = xmp_with_resolution(x, (1.0, 1.0)); } + + // Property-like text repeated inside the packet must not trigger a full-suffix rescan + // per occurrence (it used to be quadratic). With the cursor advancing past each located + // value, this completes well under a second even with many decoys; a timeout here would + // indicate the quadratic scan returned. A clean packet still extracts correctly. + let start = std::time::Instant::now(); + let decoys = " tiff:ResolutionUnit>".repeat(50_000); + let _ = xmp_resolution(&decoys); + assert!(start.elapsed() < std::time::Duration::from_secs(2), "xmp scan took too long: {:?}", start.elapsed()); + let clean = "300/1300/12"; + near(xmp_resolution(clean), 300.0); } proptest! { From 3495a4b22517973edc23012fab0b0d6a888a84cd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 21:57:49 -0400 Subject: [PATCH 46/54] security(codecs): dedup Cryptomatte keys and cache stream lists Cryptomatte metadata enumeration had two file-driven amplifiers: - cryptomatte_keys() tested key membership with iter().any(), O(n^2) in the number of distinct cryptomatte// attribute groups; - layers() called layer_streams() for every key, rescanning all channels and allocating a fresh owned stream list even when many keys name the same layer. Use a HashSet for key membership (keeping file order) and cache layer_streams results by resolved layer name within each header, so repeated keys reuse the discovered streams. Findings: - 120f4d51-b981-4fcc-abec-26f45f3efd29 (CWE-407, quadratic key membership) - dae6e76b-a491-4089-892f-4cf34b911f36 (CWE-400, repeated per-key stream scans) --- crates/codecs/src/codecs/exr_cryptomatte.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/codecs/src/codecs/exr_cryptomatte.rs b/crates/codecs/src/codecs/exr_cryptomatte.rs index 91a5ede22d..370c7c7e56 100644 --- a/crates/codecs/src/codecs/exr_cryptomatte.rs +++ b/crates/codecs/src/codecs/exr_cryptomatte.rs @@ -156,9 +156,13 @@ pub(crate) fn layers(bytes: &[u8], limits: &Limits) -> Result> = std::collections::HashMap::new(); for key in cryptomatte_keys(&header.own_attributes.other) { let Some(name) = attribute(&header.own_attributes.other, &key, "name") else { continue }; - let channels = layer_streams(header, name.as_str()); + let channels = streams_for.entry(name.clone()).or_insert_with(|| layer_streams(header, name.as_str())).clone(); if channels.is_empty() { continue; } @@ -184,11 +188,15 @@ pub(crate) fn layers(bytes: &[u8], limits: &Limits) -> Result/` key of a header, in file order, without duplicates. fn cryptomatte_keys(other: &std::collections::HashMap) -> Vec { let mut keys = Vec::new(); + // Track seen keys in a set: the attribute names are file-controlled, so membership with + // keys.iter().any() is O(n^2) in the number of distinct `cryptomatte//` + // groups. The Vec still records file order; the set only answers "seen before". + let mut seen = std::collections::HashSet::new(); for name in other.keys() { let full = name.to_string(); let Some(rest) = full.strip_prefix("cryptomatte/") else { continue }; let Some((key, _field)) = rest.split_once('/') else { continue }; - if !key.is_empty() && !keys.iter().any(|k| k == key) { + if !key.is_empty() && seen.insert(key.to_string()) { keys.push(key.to_string()); } } From dc6057d3f2cd425859cddeb485453d1b1498b107 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 21:56:22 -0400 Subject: [PATCH 47/54] security(engine): deduplicate ATN action names in near-linear time actions.load gave each imported action a unique name with a helper that restarted suffix numbering at 2 and linearly scanned all accepted names for every candidate. A file repeating one base name many times caused cubic comparison work during load. Replace it with a UniqueNames helper backed by a HashSet for membership and a per-base-name next-suffix cache, preserving the name, name 2, name 3 ... sequence and first-match behavior. Finding: 9c7a5fdb-131e-4687-8175-58d72007b0c5 (CWE-407) --- crates/engine/src/atn_cmds.rs | 37 ++++++++++++++++++++++------- crates/engine/src/atn_cmds/tests.rs | 12 ++++++++++ 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs index afba793027..3be9ee217a 100644 --- a/crates/engine/src/atn_cmds.rs +++ b/crates/engine/src/atn_cmds.rs @@ -3631,12 +3631,34 @@ pub fn export( // ------------------------------------------------------------------ commands -/// A name not used by any action in `taken`: `name`, `name 2`, `name 3`… -fn unique(name: &str, taken: &[String]) -> String { - if !taken.iter().any(|t| t == name) { - return name.to_string(); +/// Assigns names not already used, as `name`, `name 2`, `name 3`… A plain linear scan of the +/// taken list per candidate is cubic when an action file repeats one base name many times, so +/// membership uses a set and the next suffix to try is cached per base name. +struct UniqueNames { + taken: std::collections::HashSet, + next_suffix: std::collections::HashMap, +} + +impl UniqueNames { + fn new>(existing: I) -> Self { + UniqueNames { taken: existing.into_iter().collect(), next_suffix: std::collections::HashMap::new() } + } + + /// Reserves and returns a unique name derived from `name`, recording it as taken. + fn claim(&mut self, name: &str) -> String { + if self.taken.insert(name.to_string()) { + return name.to_string(); + } + let mut i = self.next_suffix.get(name).copied().unwrap_or(2); + loop { + let candidate = format!("{name} {i}"); + i += 1; + if self.taken.insert(candidate.clone()) { + self.next_suffix.insert(name.to_string(), i); + return candidate; + } + } } - (2..).map(|i| format!("{name} {i}")).find(|n| !taken.contains(n)).unwrap_or_else(|| name.to_string()) } fn load(s: &mut Session, p: &Value) -> Result { @@ -3664,19 +3686,18 @@ fn load(s: &mut Session, p: &Value) -> Result { if replace { s.actions.list.retain(|a| a.set.as_deref() != Some(imp.set.as_str())); } - let mut taken: Vec = s.actions.list.iter().map(|a| a.name.clone()).collect(); + let mut taken = UniqueNames::new(s.actions.list.iter().map(|a| a.name.clone())); let mut names = Vec::with_capacity(imp.actions.len()); // The file's name of each action that had to be renamed, and its new name. let mut renamed: std::collections::HashMap = std::collections::HashMap::new(); let mut steps = 0usize; let mut added = Vec::with_capacity(imp.actions.len()); for mut a in imp.actions { - let name = unique(&a.name, &taken); + let name = taken.claim(&a.name); if name != a.name { renamed.entry(a.name.clone()).or_insert_with(|| name.clone()); } a.name = name.clone(); - taken.push(name.clone()); steps = steps.saturating_add(a.steps.len()); names.push(name); added.push(a); diff --git a/crates/engine/src/atn_cmds/tests.rs b/crates/engine/src/atn_cmds/tests.rs index bbec1def43..e8595086ac 100644 --- a/crates/engine/src/atn_cmds/tests.rs +++ b/crates/engine/src/atn_cmds/tests.rs @@ -163,6 +163,18 @@ fn load_renames_each_play_target_once() { assert_eq!(s.actions.list[1].steps[0].1, json!({"action": "A"}), "B still plays the A it had"); } +#[test] +fn load_many_duplicate_names_get_sequential_suffixes() { + // Several actions share one base name. Deduplication must stay O(n) overall and produce + // the sequence A, A 2, A 3, A 4 (the next-suffix cache cannot skip or repeat a number). + let mut s = Session::new(); + let dupes: Vec = (0..4).map(|_| Action::new("A", vec![])).collect(); + let refs: Vec<&Action> = dupes.iter().collect(); + let (bytes, _) = export("File", &refs, &[], false).unwrap(); + let r = s.execute("actions.load", json!({"data": b64(&bytes)})).unwrap(); + assert_eq!(r["actions"], json!(["A", "A 2", "A 3", "A 4"])); +} + #[test] fn save_round_trips_through_photoshop_events() { let mut s = Session::new(); From f42d7ef41ac4cf5b9bde70052c6e157d14911eef Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 21:51:23 -0400 Subject: [PATCH 48/54] security(codecs): index FITS header keywords for O(1) lookup Header::get scanned every card linearly, and axis resolution looks up NAXIS1..NAXISn while find_image/data_len re-resolve the axes. Both the commentary-card count and the NAXIS count are file-controlled, so a crafted header multiplied them into quadratic header-processing work without a correspondingly large decoded image. Build a first-occurrence keyword index once in parse_header (skipping HIERARCH cards, matching the prior filter) and use it in get(). Finding: eb2121d8-9dee-4422-bd57-f78dce60a61b (CWE-407) --- crates/codecs/src/codecs/fits.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/codecs/src/codecs/fits.rs b/crates/codecs/src/codecs/fits.rs index 7e3f92ae67..214d968944 100644 --- a/crates/codecs/src/codecs/fits.rs +++ b/crates/codecs/src/codecs/fits.rs @@ -22,6 +22,8 @@ //! (strings longer than one card on `CONTINUE` cards). //! Tile-compressed files (fpack `ZIMAGE` tables) are recognised and refused. +use std::collections::HashMap; + use crate::Format; use crate::error::CodecError; use crate::fidelity::Plan; @@ -106,13 +108,19 @@ fn parse_card(raw: &[u8]) -> Card { struct Header { cards: Vec, + /// First-occurrence index of each non-HIERARCH keyword, so `get` is O(1). The card + /// count and the number of looked-up keywords (NAXIS1..NAXISn) are both file-controlled, + /// so a linear scan per lookup lets a crafted header multiply commentary cards by axis + /// count into quadratic work. + index: HashMap, /// Offset of the data unit. data_start: usize, } impl Header { fn get(&self, key: &str) -> Option<&Value> { - self.cards.iter().find(|c| !c.hierarch && c.key == key).and_then(|c| c.value.as_ref()) + let c = &self.cards[*self.index.get(key)?]; + c.value.as_ref() } fn int(&self, key: &str) -> Option { @@ -167,7 +175,15 @@ fn parse_header(b: &[u8], start: usize) -> Result { cards.push(card); } let data_start = pos.div_ceil(BLOCK).checked_mul(BLOCK).ok_or_else(|| err("header too long"))?; - Ok(Header { cards, data_start }) + // Index each non-HIERARCH keyword to its first occurrence, matching the previous + // `find(|c| !c.hierarch && c.key == key)` lookup while making `get` O(1). + let mut index = HashMap::with_capacity(cards.len()); + for (i, c) in cards.iter().enumerate() { + if !c.hierarch { + index.entry(c.key.clone()).or_insert(i); + } + } + Ok(Header { cards, index, data_start }) } /// The axis lengths (`NAXIS1`, `NAXIS2`, …). From e75790b8780fd77204ca7a255f34f854ec6e89af Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 21:50:14 -0400 Subject: [PATCH 49/54] security(io): index XCF parasite names for duplicate replacement parasites() implemented last-duplicate-wins by scanning all previously collected names with iter_mut().find() per record. Parasite records are file-controlled, so many distinct names caused O(n^2) CPU work before unrecognized metadata was discarded. Maintain a name-to-index map so replacement is O(1) while preserving insertion order and last-value-wins behavior. Finding: 6107f41e-9b17-4632-a9df-f88a74a796a8 (CWE-407) --- crates/io/src/xcf.rs | 15 ++++++++++++--- crates/io/src/xcf/tests.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/crates/io/src/xcf.rs b/crates/io/src/xcf.rs index 4bb62cacbb..d5cda4aa4d 100644 --- a/crates/io/src/xcf.rs +++ b/crates/io/src/xcf.rs @@ -17,6 +17,7 @@ #[cfg(test)] mod tests; +use std::collections::HashMap; use std::io::Read; use std::sync::Arc; @@ -294,13 +295,21 @@ fn be_f32(b: &[u8]) -> Option { fn parasites(data: &[u8]) -> Vec<(String, Vec)> { let mut c = Cursor { b: data, pos: 0, wide: false }; let mut out: Vec<(String, Vec)> = Vec::new(); + // Map each name to its output slot so duplicate replacement is O(1). The parasite + // records are file-controlled, so scanning `out` with iter_mut().find() per record is + // O(n^2) and lets a crafted payload with many distinct names stall import. The map + // preserves insertion order and last-value-wins behavior. + let mut index: HashMap = HashMap::new(); while c.pos < data.len() { let Ok(name) = c.string() else { break }; let (Ok(_flags), Ok(len)) = (c.u32(), c.u32()) else { break }; let Ok(payload) = c.take(len as usize) else { break }; - match out.iter_mut().find(|(n, _)| *n == name) { - Some(slot) => slot.1 = payload.to_vec(), - None => out.push((name, payload.to_vec())), + match index.get(&name) { + Some(&i) => out[i].1 = payload.to_vec(), + None => { + index.insert(name.clone(), out.len()); + out.push((name, payload.to_vec())); + } } } out diff --git a/crates/io/src/xcf/tests.rs b/crates/io/src/xcf/tests.rs index ee96f16509..400887f92b 100644 --- a/crates/io/src/xcf/tests.rs +++ b/crates/io/src/xcf/tests.rs @@ -702,3 +702,33 @@ fn a_path_failing_below_the_top_level_lands_at_the_top_level() { assert_eq!(children, ["A"], "the valid sibling placed after the stray one still lands in the group"); assert!(r.warnings.iter().any(|w| w.contains("Stray") && w.contains("item path")), "{:?}", r.warnings); } + +/// A parasite name field: u32 `len+1`, then the bytes and a trailing NUL. +fn parasite_name(out: &mut Vec, name: &str) { + out.extend_from_slice(&((name.len() as u32) + 1).to_be_bytes()); + out.extend_from_slice(name.as_bytes()); + out.push(0); +} + +/// One PROP_PARASITES record: name, u32 flags, u32 len, then the payload. +fn parasite_record(out: &mut Vec, name: &str, payload: &[u8]) { + parasite_name(out, name); + out.extend_from_slice(&0u32.to_be_bytes()); + out.extend_from_slice(&(payload.len() as u32).to_be_bytes()); + out.extend_from_slice(payload); +} + +#[test] +fn duplicate_parasites_keep_order_and_last_value() { + // Duplicate names must resolve to the last payload while keeping first-seen order. + // This is the behavior the name->index map must preserve versus the old linear scan. + let mut data = Vec::new(); + parasite_record(&mut data, "gimp-comment", b"first"); + parasite_record(&mut data, "gimp-image-grid", b"grid"); + parasite_record(&mut data, "gimp-comment", b"second"); + let out = parasites(&data); + assert_eq!(out.len(), 2, "duplicate collapses to one slot"); + assert_eq!(out[0].0, "gimp-comment"); + assert_eq!(out[0].1, b"second", "last value wins"); + assert_eq!(out[1].0, "gimp-image-grid", "insertion order preserved"); +} From 7c78c951e44f6f92869679522a80a57be4c22d74 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 21:47:53 -0400 Subject: [PATCH 50/54] security(io): index comp IDs in PSD layer-comp import decode_comps matched each nonzero layer-setting comp ID against the comp vector with iter_mut().find(), an O(n*m) scan over two file-controlled collections. A crafted PSD could cause quadratic CPU work during import. Build a comp-ID-to-first-index map once and use it for setting lookups. or_insert preserves first-match behavior for duplicate comp IDs; comp 0 (Last Document State) is still handled separately. Finding: 47567ac0-a75f-4557-b127-ffc855e5bd8d (CWE-407) --- crates/io/src/comps_map.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/io/src/comps_map.rs b/crates/io/src/comps_map.rs index 4cade56e2e..3348061b34 100644 --- a/crates/io/src/comps_map.rs +++ b/crates/io/src/comps_map.rs @@ -12,6 +12,8 @@ //! Both are re-emitted verbatim while they still decode to the document's state, and are //! regenerated otherwise (comp appearance is not written to PSD; `.pcraft` keeps it). +use std::collections::HashMap; + use photocraft_doc::comps::layer_position; use photocraft_doc::{Artboard, ArtboardBackground, CompLayerState, Document, Guides, Layer, LayerComp}; use photocraft_geom::Rect; @@ -203,6 +205,14 @@ pub(crate) fn decode_comps(resource: Option<&[u8]>, doc: &Document) -> (Vec = HashMap::with_capacity(comps.len()); + for (i, c) in comps.iter().enumerate() { + id_to_index.entry(c.id).or_insert(i); + } let mut last = LayerComp { id: 0, name: "Last Document State".into(), @@ -239,7 +249,7 @@ pub(crate) fn decode_comps(resource: Option<&[u8]>, doc: &Document) -> (Vec None, }; for id in &s.comps { - let target = if *id == 0 { Some(&mut last) } else { comps.iter_mut().find(|c| c.id == *id) }; + let target = if *id == 0 { Some(&mut last) } else { id_to_index.get(id).map(|&i| &mut comps[i]) }; let Some(c) = target else { continue }; let visible = if *id != 0 && c.apply_visibility { Some(resolved) } else { s.visible }; if visible.is_none() && s.offset.is_none() { From 81c694a3f99da438231aff292232a75741db74f9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 21:13:12 -0400 Subject: [PATCH 51/54] security: bound RAW linked-directory metadata reads --- crates/raw/src/preview.rs | 13 +++++++------ crates/raw/src/tiff.rs | 25 ++++++++++++++++++++++--- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/crates/raw/src/preview.rs b/crates/raw/src/preview.rs index d5dd013310..9f63173bf6 100644 --- a/crates/raw/src/preview.rs +++ b/crates/raw/src/preview.rs @@ -74,12 +74,13 @@ pub fn embedded_previews(bytes: &[u8]) -> Vec> { if let (Some(off), Some(len)) = (t.tag_uint(&ifd, tag::JPEG_INTERCHANGE_FORMAT), t.tag_uint(&ifd, tag::JPEG_INTERCHANGE_FORMAT_LENGTH)) { found.extend(candidate(bytes, off as usize, len as usize)); } - if matches!(t.tag_uint(&ifd, tag::COMPRESSION), Some(6 | 7)) { - let offs = t.tag_uints(&ifd, tag::STRIP_OFFSETS); - let lens = t.tag_uints(&ifd, tag::STRIP_BYTE_COUNTS); - if let ([off], [len]) = (offs.as_slice(), lens.as_slice()) { - found.extend(candidate(bytes, *off as usize, *len as usize)); - } + if matches!(t.tag_uint(&ifd, tag::COMPRESSION), Some(6 | 7)) + && let (Some(offsets), Some(lengths)) = (ifd.get(tag::STRIP_OFFSETS), ifd.get(tag::STRIP_BYTE_COUNTS)) + && offsets.count == 1 + && lengths.count == 1 + && let (Some(off), Some(len)) = (t.uint(offsets, 0), t.uint(lengths, 0)) + { + found.extend(candidate(bytes, off as usize, len as usize)); } // Panasonic RW2 JpgFromRaw (0x002E) holds a complete JPEG. if let Some(e) = ifd.get(0x002E).filter(|e| e.typ == 7) diff --git a/crates/raw/src/tiff.rs b/crates/raw/src/tiff.rs index cfcadee730..0fa11685f7 100644 --- a/crates/raw/src/tiff.rs +++ b/crates/raw/src/tiff.rs @@ -213,9 +213,11 @@ impl<'a> Tiff<'a> { } for t in [tag::SUB_IFDS, tag::EXIF_IFD] { if let Some(e) = ifd.get(t) { - // Reverse so the first SubIFD is visited first. - let mut v = self.uints(e); - v.truncate(16); + // Linked-directory traversal only needs the first sixteen offsets. Read + // those values directly instead of expanding the complete file-controlled + // array and truncating it afterward. + let n = (e.count as usize).min(16); + let v = (0..n).map(|i| self.uint(e, i)).collect::>>().unwrap_or_default(); stack.extend(v.into_iter().rev().map(|o| o as usize)); } } @@ -450,3 +452,20 @@ mod tests { assert!(out.contains("output truncated") || out.len() < 1 << 20); } } + +#[test] +fn linked_directory_values_are_read_only_as_needed() { + // The traversal limit is independent of the TIFF entry count: callers should + // never need a complete attacker-controlled offset array to visit SubIFDs. + let mut b = b"II*\0\x08\0\0\0".to_vec(); + b.extend_from_slice(&1u16.to_le_bytes()); + b.extend_from_slice(&330u16.to_le_bytes()); + b.extend_from_slice(&4u16.to_le_bytes()); + b.extend_from_slice(&(1_000_000u32).to_le_bytes()); + b.extend_from_slice(&26u32.to_le_bytes()); + b.extend_from_slice(&0u32.to_le_bytes()); + b.extend_from_slice(&0u32.to_le_bytes()); + b.resize(26 + 16 * 4, 0); + let t = Tiff::new(&b).unwrap(); + assert!(t.all_ifds().len() <= 17); +} From 5338f1de46aa58e4bb119302e126eed07250f844 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 21:13:11 -0400 Subject: [PATCH 52/54] security: budget nested action playback and preserve batch auth --- crates/engine/src/actions_cmds.rs | 34 +++++++++++++++++++++++++++++++ crates/engine/src/file_cmds.rs | 4 +++- crates/ui-egui/src/actions.rs | 4 ++++ 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/actions_cmds.rs b/crates/engine/src/actions_cmds.rs index 9babc5a50a..8820439a0d 100644 --- a/crates/engine/src/actions_cmds.rs +++ b/crates/engine/src/actions_cmds.rs @@ -81,6 +81,8 @@ pub struct ActionsFile { pub actions: Vec, } +pub const MAX_PLAYBACK_STEPS: u64 = 100_000; + /// Actions list and the recording / playback flags. Only `list` is persisted. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default)] @@ -95,6 +97,9 @@ pub struct ActionState { /// Active action names, for cycle detection in engine and desktop playback. #[serde(skip)] pub playback_stack: Vec, + /// Number of steps executed by the current top-level playback tree. + #[serde(skip)] + pub playback_steps: u64, /// Bumped whenever `list` changes, so the preset store can skip unchanged writes. #[serde(skip)] pub rev: u64, @@ -143,6 +148,15 @@ pub fn save_target_closed(s: &Session, id: &str, target: Option bool { + if s.actions.playback_steps >= MAX_PLAYBACK_STEPS { + false + } else { + s.actions.playback_steps += 1; + true + } +} /// View-only menu commands recorded by the desktop shell. Headless playback reports /// them as unsupported instead of silently dropping them; Batch and droplets skip them. pub fn shell_view_command(id: &str) -> bool { @@ -348,6 +362,10 @@ fn run_recorded(s: &mut Session, action: &Action, from: usize) -> (u64, Option (u64, Option Result> { flush_recording(s)?; + if s.actions.playing == 0 { + s.actions.playback_steps = 0; + } let recording = s.actions.recording.take(); s.actions.playing = s.actions.playing.saturating_add(1); s.actions.playback_stack.push(action.name.clone()); @@ -1583,3 +1604,16 @@ mod tests { assert!(s.actions.list[0].color.is_empty(), "rejected colours change nothing"); } } + +#[cfg(test)] +mod security_tests { + use super::*; + + #[test] + fn playback_budget_is_shared_by_nested_calls() { + let mut session = Session::new(); + session.actions.playback_steps = MAX_PLAYBACK_STEPS - 1; + assert!(consume_playback_step(&mut session)); + assert!(!consume_playback_step(&mut session)); + } +} diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 0bb2b78928..1833d0a616 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -1259,7 +1259,9 @@ fn batch(s: &mut Session, p: &Value) -> Result { let actions = crate::actions_cmds::ActionState { list, playing: s.actions.playing, playback_stack: s.actions.playback_stack.clone(), ..Default::default() }; let names = batch_naming::plan(&inputs, &output, &format, p)?; let save = SaveOpts::from_params(s, p, cmd)?; - let run = |scratch: &mut Session| { + let authorize = s.authorize; + let run = move |scratch: &mut Session| { + scratch.authorize = authorize; scratch.actions = actions.clone(); for (id, params) in &steps { let r = scratch.execute(id, params.clone())?; diff --git a/crates/ui-egui/src/actions.rs b/crates/ui-egui/src/actions.rs index 8a7ce9bf39..a9fbc56add 100644 --- a/crates/ui-egui/src/actions.rs +++ b/crates/ui-egui/src/actions.rs @@ -101,6 +101,10 @@ pub(crate) fn play(app: &mut PhotocraftApp, params: &Value) -> Result Date: Wed, 21 Oct 2026 21:13:12 -0400 Subject: [PATCH 53/54] security: encode printer names in IPP request paths --- crates/ipp/src/lib.rs | 17 ++++++++++++++--- crates/ipp/src/tests.rs | 6 ++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/ipp/src/lib.rs b/crates/ipp/src/lib.rs index 9f1209df45..0f8f303ee0 100644 --- a/crates/ipp/src/lib.rs +++ b/crates/ipp/src/lib.rs @@ -480,8 +480,19 @@ fn dechunk(mut b: &[u8]) -> Result> { } /// Where `/path` lands on the server: `/printers/` or `/classes/`. -fn queue_path(name: &str, is_class: bool) -> String { - format!("/{}/{name}", if is_class { "classes" } else { "printers" }) +fn queue_path(name: &str, is_class: bool) -> Result { + if name.is_empty() || name.bytes().any(|b| b < 0x20 || b == 0x7f) { + return Err(Error::Protocol("printer name contains an invalid control character".into())); + } + let mut encoded = String::with_capacity(name.len()); + for &b in name.as_bytes() { + if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') { + encoded.push(char::from(b)); + } else { + encoded.push_str(&format!("%{b:02X}")); + } + } + Ok(format!("/{}/{encoded}", if is_class { "classes" } else { "printers" })) } /// The printers the server knows (CUPS-Get-Printers), then its classes (CUPS-Get-Classes, which @@ -568,7 +579,7 @@ pub struct Job<'a> { /// Submits `job` (Print-Job) and returns the job id. pub fn print_job(endpoint: &Endpoint, job: &Job<'_>) -> Result { let mut r = Request::new(OP_PRINT_JOB, 3); - let path = queue_path(job.printer, job.is_class); + let path = queue_path(job.printer, job.is_class)?; r.attr(TAG_URI, "printer-uri", format!("ipp://{}{path}", endpoint.host()).as_bytes()); r.attr(TAG_NAME, "requesting-user-name", job.user.as_bytes()); r.attr(TAG_NAME, "job-name", job.title.as_bytes()); diff --git a/crates/ipp/src/tests.rs b/crates/ipp/src/tests.rs index ff3ccb6a49..ab236d75ee 100644 --- a/crates/ipp/src/tests.rs +++ b/crates/ipp/src/tests.rs @@ -393,3 +393,9 @@ fn an_impossible_chunk_size_is_a_protocol_error_not_a_panic() { } } } + +#[test] +fn printer_names_are_encoded_as_one_request_target_segment() { + assert_eq!(queue_path("office printer/1", false).unwrap(), "/printers/office%20printer%2F1"); + assert!(queue_path("printer\r\nX-Injected: yes", false).is_err()); +} From 1104b6f2111a4c66adfe6b051d710712124a5bbc Mon Sep 17 00:00:00 2001 From: zuujiscom Date: Thu, 22 Oct 2026 00:26:35 -0500 Subject: [PATCH 54/54] ci(freebsd): run the photocraft-gpu tests one at a time The nightly FreeBSD run fails because the timing test binary crashes with SIGSEGV in the VM's software Vulkan driver when its tests set up devices in parallel. Run with --test-threads=1 it passed 3 of 3 times on GitHub's x86_64 and aarch64 VMs and on a native FreeBSD 15.1 aarch64 VM, where all 121 photocraft-gpu tests pass. Exclude photocraft-gpu from the workspace test run and test it serially, as ui-egui's integration tests already are. --- .github/workflows/freebsd.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index 970c6577a4..56d1ad0831 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -32,5 +32,7 @@ jobs: with: craft-fonts-ref: abb83316d96aa59c1cf64784289e378fe9fa5695 cargo-build-extra-args: "--features heif" - custom-test-command: "CARGO_PROFILE_DEV_DEBUG=0 cargo test --workspace --locked --features heif --exclude photocraft-ui-egui && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-ui-egui --locked --lib && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-ui-egui --locked --doc && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-ui-egui --locked --test '*' -- --test-threads=1" + # The VM's software Vulkan driver crashes (SIGSEGV) when several tests set up a device at + # once, so photocraft-gpu's tests run one at a time, like ui-egui's integration tests. + custom-test-command: "CARGO_PROFILE_DEV_DEBUG=0 cargo test --workspace --locked --features heif --exclude photocraft-ui-egui --exclude photocraft-gpu && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-gpu --locked -- --test-threads=1 && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-ui-egui --locked --lib && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-ui-egui --locked --doc && CARGO_PROFILE_DEV_DEBUG=0 cargo test -p photocraft-ui-egui --locked --test '*' -- --test-threads=1" run-package-check: true