From faaa42db958fe3b49db5c0414ceec109fe2918a7 Mon Sep 17 00:00:00 2001 From: BFlat Date: Wed, 7 Oct 2026 13:21:22 +0700 Subject: [PATCH] Gradients honour explicit transparency stops; smart filter commands accept an explicit layer target (#465, #466) (#544) * Gradients honour explicit transparency stops with colors, a preset or the current gradient (#465) `paint.gradient` and `gradient.fill.create` dropped `transparency` unless `stops` was given. Explicit transparency stops now replace the gradient's own opacity stops whatever supplies the colours. One shared parser (`transparency_param`) serves paint.gradient, gradient.fill.create/set and the presets; malformed stops are an error, not dropped. Co-Authored-By: Claude Opus 5.5 * Smart filter commands check an explicit layer target, not the active layer (#466) `layer.smartFilter.*` with `"layer":id` were refused when the active layer was not a smart object with filters, although they edit the named layer. Their precondition is now checked on that layer; the active layer stays unchanged, and without `layer` (menus) nothing changes. Co-Authored-By: Claude Opus 5.5 * Gradients: reword the opacity-merge doc comment Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/gradient_fill_cmds.rs | 25 ++-- crates/engine/src/gradient_fill_cmds/tests.rs | 16 +++ crates/engine/src/jobs.rs | 2 +- crates/engine/src/paint_cmds.rs | 8 +- crates/engine/src/presets/gradients.rs | 114 +++++++++++------- crates/engine/src/presets/tests.rs | 36 ++++++ crates/engine/src/smart_cmds.rs | 18 +++ crates/engine/src/smart_cmds/tests.rs | 30 +++++ 8 files changed, 185 insertions(+), 64 deletions(-) diff --git a/crates/engine/src/gradient_fill_cmds.rs b/crates/engine/src/gradient_fill_cmds.rs index 9a6635addf..05f88ce8cb 100644 --- a/crates/engine/src/gradient_fill_cmds.rs +++ b/crates/engine/src/gradient_fill_cmds.rs @@ -18,7 +18,7 @@ use photocraft_geom::Rect; use serde_json::{Value, json}; use crate::commands::{CommandSpec, blend_from_str, layer_param}; -use crate::presets::gradients::GradientPreset; +use crate::presets::gradients::{GradientPreset, transparency_param}; use crate::{EngineError, Result, Session}; pub const CREATE: &str = "gradient.fill.create"; @@ -110,8 +110,8 @@ fn hex(c: &Color) -> String { } } -/// The gradient a `gradient.fill.create` uses: a preset (`"gradient"`), explicit `"stops"` -/// (+ `"transparency"`), else the current gradient (Gradients panel). +/// The gradient a `gradient.fill.create` uses: a preset (`"gradient"`), explicit `"stops"`, +/// else the current gradient (Gradients panel); explicit `"transparency"` stops replace its own. fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result { if let Some(name) = p.get("gradient").and_then(Value::as_str) { let groups = &s.presets.gradients; @@ -120,12 +120,13 @@ fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result { .flat_map(|g| g.items.iter()) .find(|g| g.name.eq_ignore_ascii_case(name)) .cloned() - .ok_or_else(|| bad(cmd, format!("no gradient preset \"{name}\" (see gradient.presets.list)"))); + .ok_or_else(|| bad(cmd, format!("no gradient preset \"{name}\" (see gradient.presets.list)")))? + .with_transparency(p, cmd); } if p.get("stops").is_some() { return GradientPreset::from_params("Custom", p, cmd); } - Ok(s.presets.gradient.clone()) + s.presets.gradient.clone().with_transparency(p, cmd) } /// The fill and frame of gradient fill layer `id`. @@ -248,19 +249,7 @@ pub fn apply_set(layer: &Layer, f: &Fill, canvas: Rect, p: &Value, fg: [f32; 4], } *stops = new; } - if let Some(v) = p.get("transparency") { - let arr = v.as_array().ok_or_else(|| bad(CMD, "`transparency` is [[location, opacity %], …]"))?; - let mut new = Vec::with_capacity(arr.len()); - for s in arr { - let pair = s.as_array().filter(|a| a.len() == 2).ok_or_else(|| bad(CMD, "an opacity stop is [location 0..1, opacity 0..100]"))?; - let f = |i: usize| pair.get(i).and_then(Value::as_f64).map(|v| v as f32).filter(|v| v.is_finite()); - let (Some(t), Some(o)) = (f(0), f(1)) else { return Err(bad(CMD, "opacity stops are numbers")) }; - new.push((t.clamp(0.0, 1.0), (o / 100.0).clamp(0.0, 1.0))); - } - if new.len() > 1024 { - return Err(bad(CMD, "too many opacity stops (max 1024)")); - } - new.sort_by(|a, b| a.0.total_cmp(&b.0)); + if let Some(new) = transparency_param(p, CMD)? { *opacity_stops = new; } if let Some(v) = p.get("midpoints") { diff --git a/crates/engine/src/gradient_fill_cmds/tests.rs b/crates/engine/src/gradient_fill_cmds/tests.rs index 0b47024f3e..769712085e 100644 --- a/crates/engine/src/gradient_fill_cmds/tests.rs +++ b/crates/engine/src/gradient_fill_cmds/tests.rs @@ -113,6 +113,22 @@ fn live_gradient_renders_like_the_classic_gradient() { parity(8, "transparent", stops.clone(), false, 0.51 / 255.0); parity(8, "white", json!({"stops": [[0, "#ff2000"], [1, "#1010e0"]], "reverse": true, "dither": true}), true, 1.01 / 255.0); parity(16, "transparent", json!({"gradient": "Foreground to Transparent", "dither": true}), false, 1.01 / 255.0); + parity(32, "transparent", json!({"gradient": "Black, White", "transparency": [[0, 65], [1, 0]], "dither": false}), false, 1e-4); +} + +/// Issue #465: explicit `transparency` stops replace those of a preset or the current gradient. +#[test] +fn create_honours_explicit_transparency_stops() { + for extra in [json!({"gradient": "Foreground to Transparent"}), json!({"gradient": "black, white"}), json!({})] { + let mut s = session(8, "transparent"); + let mut p = json!({"from": [0, 0], "to": [48, 0], "transparency": [[1, 0], [0, 65]]}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + s.execute(CREATE, p).unwrap(); + let Fill::Gradient { opacity_stops, .. } = active_fill(&s) else { panic!("not a gradient fill") }; + assert_eq!(opacity_stops, vec![(0.0, 0.65), (1.0, 0.0)], "{extra}"); + } } #[test] diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index 203d59b6f3..dc948a82d0 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -588,7 +588,7 @@ impl Session { /// Run the command `id`: inline, or (with `background`) as a job when it is one. pub(crate) fn dispatch(&mut self, id: &str, params: Value, background: bool) -> Result { let spec = crate::commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; - if let Err(why) = (spec.enabled)(self) { + if let Err(why) = crate::smart_cmds::target_enabled(self, spec, ¶ms).unwrap_or_else(|| (spec.enabled)(self)) { return Err(EngineError::Disabled(id.to_string(), why)); } if let Some(why) = self.job_conflict(id, spec.journal) { diff --git a/crates/engine/src/paint_cmds.rs b/crates/engine/src/paint_cmds.rs index 1e9f572585..783753bdfd 100644 --- a/crates/engine/src/paint_cmds.rs +++ b/crates/engine/src/paint_cmds.rs @@ -4,6 +4,7 @@ use photocraft_algo::paint::{GradientShape, bucket_fill, bucket_fill_src, paint_ use serde_json::{Value, json}; use crate::commands::{CommandSpec, blend_from_str}; +use crate::presets::gradients; use crate::{EngineError, Result, Session}; fn f(p: &Value, k: &str, d: f32) -> f32 { @@ -83,14 +84,15 @@ fn gradient(s: &mut Session, p: &Value) -> Result { }; let (fg, bg) = (s.tools.foreground, s.tools.background); // A preset (`gradient`), explicit `stops`, or the current gradient (Gradients panel); the - // legacy `colors` list spaces its colours evenly. - let stops: Vec<(f32, [f32; 4])> = match crate::presets::gradients::tool_stops(s, p)? { + // legacy `colors` list spaces its colours evenly. Explicit `transparency` applies to all. + let stops: Vec<(f32, [f32; 4])> = match gradients::tool_stops(s, p)? { Some(st) => st, None => { let colors: Vec<[f32; 4]> = p.get("colors").and_then(Value::as_array).map(|a| a.iter().map(|v| color(Some(v), fg)).collect()).unwrap_or_else(|| vec![fg, bg]); let n = colors.len(); - colors.into_iter().enumerate().map(|(i, c)| (if n > 1 { i as f32 / (n - 1) as f32 } else { 0.0 }, c)).collect() + let cs = colors.into_iter().enumerate().map(|(i, c)| (if n > 1 { i as f32 / (n - 1) as f32 } else { 0.0 }, c)).collect(); + gradients::apply_opacity(cs, &gradients::transparency_param(p, "paint.gradient")?.unwrap_or_default()) } }; let reverse = b(p, "reverse", false); diff --git a/crates/engine/src/presets/gradients.rs b/crates/engine/src/presets/gradients.rs index acc66825fe..6a5e20641e 100644 --- a/crates/engine/src/presets/gradients.rs +++ b/crates/engine/src/presets/gradients.rs @@ -85,8 +85,7 @@ impl GradientPreset { GradientPreset { name: "Foreground to Background".into(), stops: vec![(0.0, StopColor::Foreground), (1.0, StopColor::Background)], opacity: Vec::new() } } - /// RGBA stops for painting: colour and transparency stops merged. Where both vary, extra - /// samples keep the product close to Photoshop's per-pixel interpolation. + /// RGBA stops for painting: colour and transparency stops merged (see [`apply_opacity`]). pub fn resolve(&self, fg: [f32; 4], bg: [f32; 4]) -> Vec<(f32, [f32; 4])> { let rgb = |c: StopColor| match c { StopColor::Foreground => [fg[0], fg[1], fg[2], 1.0], @@ -98,28 +97,7 @@ impl GradientPreset { if cs.is_empty() { cs = vec![(0.0, [fg[0], fg[1], fg[2], 1.0]), (1.0, [bg[0], bg[1], bg[2], 1.0])]; } - let mut os: Vec<(f32, f32)> = self.opacity.iter().map(|(t, a)| (t.clamp(0.0, 1.0), a.clamp(0.0, 1.0))).collect(); - os.sort_by(|a, b| a.0.total_cmp(&b.0)); - if os.is_empty() || os.iter().all(|o| (o.1 - 1.0).abs() < 1e-6) { - return cs; - } - let mut ts: Vec = cs.iter().map(|s| s.0).chain(os.iter().map(|s| s.0)).chain([0.0, 1.0]).collect(); - ts.sort_by(f32::total_cmp); - ts.dedup_by(|a, b| (*a - *b).abs() < 1e-6); - let mut all = Vec::new(); - for w in ts.windows(2) { - for k in 0..4 { - all.push(w[0] + (w[1] - w[0]) * k as f32 / 4.0); - } - } - all.push(1.0); - all.into_iter() - .map(|t| { - let mut c = sample(&cs, t, lerp4).unwrap_or([0.0; 4]); - c[3] = sample(&os, t, |a, b, u| a + (b - a) * u).unwrap_or(1.0); - (t, c) - }) - .collect() + apply_opacity(cs, &self.opacity) } /// Colour stops (live colours resolved now, sorted, opaque) and opacity stops (sorted; empty @@ -185,14 +163,64 @@ impl GradientPreset { return Err(bad(cmd, "a gradient needs at least 2 colour stops")); } stops.sort_by(|a, b| a.0.total_cmp(&b.0)); - let mut opacity: Vec<(f32, f32)> = p - .get("transparency") - .and_then(Value::as_array) - .map(|a| a.iter().filter_map(|o| Some((o.get(0)?.as_f64()? as f32, (o.get(1)?.as_f64()? as f32 / 100.0).clamp(0.0, 1.0)))).collect()) - .unwrap_or_default(); - opacity.sort_by(|a, b| a.0.total_cmp(&b.0)); - Ok(GradientPreset { name: name.into(), stops, opacity }) + GradientPreset { name: name.into(), stops, opacity: Vec::new() }.with_transparency(p, cmd) } + + /// This gradient with its transparency stops replaced by explicit `"transparency"` stops, + /// when `p` has them (see [`transparency_param`]). + pub fn with_transparency(mut self, p: &Value, cmd: &str) -> Result { + if let Some(opacity) = transparency_param(p, cmd)? { + self.opacity = opacity; + } + Ok(self) + } +} + +/// Sorted RGBA colour stops `cs` with transparency stops `(location, opacity 0..1)` multiplied +/// into their alpha. Where both vary, extra samples keep the product close to the reference app's +/// per-pixel interpolation. +pub fn apply_opacity(cs: Stops, opacity: &[(f32, f32)]) -> Stops { + let mut os: Vec<(f32, f32)> = opacity.iter().map(|(t, a)| (t.clamp(0.0, 1.0), a.clamp(0.0, 1.0))).collect(); + os.sort_by(|a, b| a.0.total_cmp(&b.0)); + if os.is_empty() || os.iter().all(|o| (o.1 - 1.0).abs() < 1e-6) { + return cs; + } + let mut ts: Vec = cs.iter().map(|s| s.0).chain(os.iter().map(|s| s.0)).chain([0.0, 1.0]).collect(); + ts.sort_by(f32::total_cmp); + ts.dedup_by(|a, b| (*a - *b).abs() < 1e-6); + let mut all = Vec::new(); + for w in ts.windows(2) { + for k in 0..4 { + all.push(w[0] + (w[1] - w[0]) * k as f32 / 4.0); + } + } + all.push(1.0); + all.into_iter() + .map(|t| { + let mut c = sample(&cs, t, lerp4).unwrap_or([0.0; 4]); + c[3] *= sample(&os, t, |a, b, u| a + (b - a) * u).unwrap_or(1.0); + (t, c) + }) + .collect() +} + +/// Explicit `"transparency":[[location 0..1, opacity 0..100], …]` as sorted `(location, +/// opacity 0..1)` stops (`[]` = opaque); `None` when `p` has none. +pub fn transparency_param(p: &Value, cmd: &str) -> Result>> { + let Some(v) = p.get("transparency") else { return Ok(None) }; + let arr = v.as_array().ok_or_else(|| bad(cmd, "`transparency` is [[location, opacity %], …]"))?; + if arr.len() > 1024 { + return Err(bad(cmd, "too many opacity stops (max 1024)")); + } + let mut stops = Vec::with_capacity(arr.len()); + for s in arr { + let pair = s.as_array().filter(|a| a.len() == 2).ok_or_else(|| bad(cmd, "an opacity stop is [location 0..1, opacity 0..100]"))?; + let f = |i: usize| pair.get(i).and_then(Value::as_f64).map(|v| v as f32).filter(|v| v.is_finite()); + let (Some(t), Some(o)) = (f(0), f(1)) else { return Err(bad(cmd, "opacity stops are numbers")) }; + stops.push((t.clamp(0.0, 1.0), (o / 100.0).clamp(0.0, 1.0))); + } + stops.sort_by(|a, b| a.0.total_cmp(&b.0)); + Ok(Some(stops)) } /// Built-in groups, laid out like Photoshop's default Gradients panel (Basics, then folders by @@ -334,21 +362,23 @@ pub type FillStops = (Vec<(f32, Color)>, Vec<(f32, f32)>); const CMD_SELECT: &str = "gradient.presets.select"; /// Gradient for the Gradient tool: `"gradient": preset name`, else explicit `"stops"`, else the -/// current gradient (Gradients panel selection). `None` when the caller gave `colors` (the -/// legacy evenly spaced form `paint.gradient` handles itself). +/// current gradient (Gradients panel selection); explicit `"transparency"` stops replace its +/// own. `None` when the caller gave `colors` (the legacy evenly spaced form `paint.gradient` +/// handles itself). pub fn tool_stops(s: &Session, p: &Value) -> Result> { - let (fg, bg) = (s.tools.foreground, s.tools.background); + const CMD: &str = "paint.gradient"; if p.get("colors").and_then(Value::as_array).is_some_and(|a| !a.is_empty()) { return Ok(None); } - if let Some(name) = str_param(p, "gradient") { - let (gi, ii) = find(&s.presets.gradients, name, None).ok_or_else(|| bad("paint.gradient", format!("no gradient preset \"{name}\"")))?; - return Ok(Some(s.presets.gradients[gi].items[ii].resolve(fg, bg))); - } - if p.get("stops").is_some() { - return Ok(Some(GradientPreset::from_params("Custom", p, "paint.gradient")?.resolve(fg, bg))); - } - Ok(Some(s.presets.gradient.resolve(fg, bg))) + let g = if let Some(name) = str_param(p, "gradient") { + let (gi, ii) = find(&s.presets.gradients, name, None).ok_or_else(|| bad(CMD, format!("no gradient preset \"{name}\"")))?; + s.presets.gradients[gi].items[ii].clone().with_transparency(p, CMD)? + } else if p.get("stops").is_some() { + GradientPreset::from_params("Custom", p, CMD)? + } else { + s.presets.gradient.clone().with_transparency(p, CMD)? + }; + Ok(Some(g.resolve(s.tools.foreground, s.tools.background))) } /// The preset named by `"preset"` (else the current gradient), or explicit `"stops"`. diff --git a/crates/engine/src/presets/tests.rs b/crates/engine/src/presets/tests.rs index 085b04ef7a..a0afca4612 100644 --- a/crates/engine/src/presets/tests.rs +++ b/crates/engine/src/presets/tests.rs @@ -65,6 +65,42 @@ fn foreground_to_transparent_paints_alpha() { assert!((mid - 0.5).abs() < 0.05, "{mid}"); } +/// Issue #465: explicit `transparency` stops apply with `colors`, a `gradient` preset, explicit +/// `stops` and the current gradient alike. +#[test] +fn paint_gradient_honours_explicit_transparency_stops() { + let transparency = json!([[0, 65], [1, 0]]); + for depth in [8, 16, 32] { + for extra in [ + json!({"colors": ["#07111d", "#07111d"]}), + json!({"gradient": "Black, White"}), + json!({"gradient": "Foreground to Transparent", "transparency": [[0, 65], [0.5, 65], [1, 0]]}), + json!({"stops": [[0, "#07111d"], [1, "#07111d"]]}), + json!({}), + ] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "transparent"})).unwrap(); + let mut p = json!({"from": [0, 0], "to": [0, 15], "transparency": transparency}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + s.execute("paint.gradient", p).unwrap(); + let (top, bottom) = (layer_px(&s, 8, 0)[3], layer_px(&s, 8, 15)[3]); + assert!((top - 0.65).abs() < 0.03, "depth {depth} {extra}: top alpha {top}"); + assert!(bottom < 0.03, "depth {depth} {extra}: bottom alpha {bottom}"); + } + } + // `colors` keeps its colour; a malformed stop list is an error, not a silent opaque fill. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "transparent"})).unwrap(); + s.execute("paint.gradient", json!({"from": [0, 0], "to": [0, 15], "colors": ["#07111d", "#07111d"], "transparency": transparency})).unwrap(); + let top = layer_px(&s, 8, 0); + assert!((top[2] - 29.0 / 255.0).abs() < 0.01, "{top:?}"); + for bad in [json!("65"), json!([[0]]), json!([[0, "a"]])] { + assert!(s.execute("paint.gradient", json!({"from": [0, 0], "to": [0, 15], "colors": ["#000000"], "transparency": bad})).is_err()); + } +} + #[test] fn gradient_apply_creates_fill_layer_and_select_recolours_it() { let mut s = session(8); diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rs index a912478e00..bb2d6017d9 100644 --- a/crates/engine/src/smart_cmds.rs +++ b/crates/engine/src/smart_cmds.rs @@ -762,6 +762,24 @@ fn move_filter(s: &mut Session, p: &Value) -> Result { // ---------- enablement ---------- +/// Whether smart-filter command `spec` can run with `p`: its precondition is checked on an +/// explicit `"layer"` of the active document (the layer it then edits) rather than on the +/// active layer, which stays active (#466). `None` for other commands or without that target. +pub(crate) fn target_enabled(s: &mut Session, spec: &CommandSpec, p: &Value) -> Option> { + if !spec.id.starts_with("layer.smartFilter.") { + return None; + } + let target = LayerId(p.get("layer")?.as_u64()?); + let d = s.active_mut()?; + d.doc.layer(target)?; + let active = d.active_layer.replace(target); + let r = (spec.enabled)(s); + if let Some(d) = s.active_mut() { + d.active_layer = active; + } + Some(r) +} + fn active_smart(s: &Session) -> std::result::Result<&SmartObject, String> { let d = s.active().ok_or("no document open")?; let id = d.active_layer.ok_or("no active layer")?; diff --git a/crates/engine/src/smart_cmds/tests.rs b/crates/engine/src/smart_cmds/tests.rs index 313303bff1..d28a5c2d29 100644 --- a/crates/engine/src/smart_cmds/tests.rs +++ b/crates/engine/src/smart_cmds/tests.rs @@ -189,6 +189,36 @@ fn filter_stack_order_blend_disable_and_clear() { assert!(!s.is_enabled("layer.smartFilter.clearSmartFilters")); } +/// Issue #466: an explicit `layer` target is checked instead of the active layer, which stays +/// active; without one the commands still follow the active layer (menus). +#[test] +fn smart_filter_commands_check_an_explicit_layer_target() { + let mut s = session(8); + paint(&mut s); + let so = convert(&mut s); + s.execute("filter.sharpen.smartSharpen", json!({"amount": 65, "radius": 1})).unwrap(); + let curves = s.execute("layer.newAdjustmentLayer.curves", json!({"points": [[0, 0], [255, 255]]})).unwrap()["layer"].as_u64().unwrap(); + let active = |s: &Session| s.active().unwrap().active_layer.unwrap().0; + assert_eq!(active(&s), curves); + let filter = |s: &Session| match &s.active().unwrap().doc.layer(LayerId(so)).unwrap().content { + LayerContent::Smart(sm) => sm.smart_filters[0].clone(), + other => panic!("not smart: {}", other.kind_name()), + }; + // No target: the active Curves layer decides, as the menu shows. + assert!(!s.is_enabled("layer.smartFilter.setParams")); + assert!(matches!(s.execute("layer.smartFilter.setParams", json!({"params": {"amount": 80}})), Err(EngineError::Disabled(..)))); + let r = s.execute("layer.smartFilter.setParams", json!({"layer": so, "index": 0, "params": {"amount": 80}})).unwrap(); + assert_eq!(r, json!({"layer": so})); + assert_eq!(filter(&s).params["amount"], json!(80)); + s.execute("layer.smartFilter.setVisible", json!({"layer": so, "visible": false})).unwrap(); + assert!(!filter(&s).visible); + assert_eq!(active(&s), curves, "the active layer stays"); + // A target that isn't a smart object with filters is still refused, and the active layer stays. + assert!(matches!(s.execute("layer.smartFilter.setParams", json!({"layer": curves, "params": {}})), Err(EngineError::Disabled(..)))); + assert!(s.execute("layer.smartFilter.setParams", json!({"layer": 999_999, "params": {}})).is_err()); + assert_eq!(active(&s), curves); +} + #[test] fn selection_becomes_the_filter_mask() { let mut s = session(8);