PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Layer Style: contour picker and Contour Editor (#2912) (#2949)
Valentin Klein7c96e9e12084
diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rsindex deca6f7d5..d5b794e38 100644--- a/crates/compose/src/adjust.rs+++ b/crates/compose/src/adjust.rs@@ -706,6 +706,41 @@ pub fn curve_lut(points: &[CurvePoint]) -> Vec<f32> {.collect()}+/// A layer-style contour curve: [`curve_lut`], except that the curve bends sharply at corner+/// points (`corners[i]` true; Photoshop's Contour Editor "Corner"): each run between corners is+/// its own natural spline, so all-corner points make a polyline. Missing flags are smooth.+pub fn contour_curve_lut(points: &[CurvePoint], corners: &[bool]) -> Vec<f32> {+ let mut pts: Vec<(CurvePoint, bool)> = points.iter().enumerate().map(|(i, p)| (p.clone(), corners.get(i).copied().unwrap_or(false))).collect();+ if !pts.iter().any(|p| p.1) {+ return curve_lut(points);+ }+ pts.sort_by(|a, b| a.0.input.partial_cmp(&b.0.input).unwrap_or(std::cmp::Ordering::Equal));+ pts.dedup_by(|a, b| (a.0.input - b.0.input).abs() < 1e-6);+ let mut out: Vec<f32> = Vec::new();+ let mut start = 0usize;+ let last = pts.len().saturating_sub(1);+ for i in 1..=last {+ let corner = pts.get(i).is_some_and(|p| p.1);+ if !(corner || i == last) {+ continue;+ }+ let Some(seg) = pts.get(start..=i) else { break };+ let from = seg.first().map_or(0.0, |p| p.0.input);+ let lut = curve_lut(&seg.iter().map(|p| p.0.clone()).collect::<Vec<_>>());+ if out.is_empty() {+ out = lut;+ } else {+ for (k, (o, v)) in out.iter_mut().zip(lut).enumerate() {+ if k as f32 / (LUT_SIZE - 1) as f32 >= from {+ *o = v;+ }+ }+ }+ start = i;+ }+ if out.is_empty() { curve_lut(points) } else { out }+}+fn gradient(stops: &[(f32, [f32; 3])], t: f32) -> [f32; 3] {match stops {[] => [t; 3],diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rsindex c52b39dad..d77941847 100644--- a/crates/compose/src/effects.rs+++ b/crates/compose/src/effects.rs@@ -878,7 +878,7 @@ fn dilate(s: &Map, r: f32) -> Map {fn contour_lut(c: &Contour) -> Option<Vec<f32>> {match c {Contour::Linear => None,- Contour::Custom { points, .. } => Some(crate::adjust::curve_lut(points)),+ Contour::Custom { points, corners, .. } => Some(crate::adjust::contour_curve_lut(points, corners)),}}@@ -2832,7 +2832,11 @@ mod tests {photocraft_doc::adjust::CurvePoint { input: 0.5, output: 1.0 },photocraft_doc::adjust::CurvePoint { input: 1.0, output: 0.0 },];- c.contour = Some(photocraft_doc::BevelContour { contour: Contour::Custom { name: "fold".into(), points: fold }, range: 1.0, anti_alias: false });+ c.contour = Some(photocraft_doc::BevelContour {+ contour: Contour::Custom { name: "fold".into(), points: fold, corners: vec![] },+ range: 1.0,+ anti_alias: false,+ });let (b, _) = bevel_maps(&shape, &c, &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES));let diff: f32 = a[1].v.iter().zip(&b[1].v).map(|(x, y)| (x - y).abs()).sum();assert!(diff > 5.0, "{diff}");diff --git a/crates/doc/src/effects.rs b/crates/doc/src/effects.rsindex 1b502ca00..6ae790e26 100644--- a/crates/doc/src/effects.rs+++ b/crates/doc/src/effects.rs@@ -58,7 +58,24 @@ pub enum Contour {#[default]Linear,/// Custom curve (input → output), both `0..=1`.- Custom { name: String, points: Vec<CurvePoint> },+ Custom {+ name: String,+ points: Vec<CurvePoint>,+ /// Corner (non-continuous) flags, parallel to `points`: the curve bends sharply at a+ /// corner point instead of passing smoothly through it. Missing entries are smooth.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ corners: Vec<bool>,+ },+}++impl Contour {+ /// Whether point `i` of a custom contour is a corner.+ pub fn is_corner(&self, i: usize) -> bool {+ match self {+ Contour::Linear => false,+ Contour::Custom { corners, .. } => corners.get(i).copied().unwrap_or(false),+ }+ }}/// Paint used by strokes and glows.diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rsindex bf82093c9..f4339ed28 100644--- a/crates/engine/src/layer_style.rs+++ b/crates/engine/src/layer_style.rs@@ -68,13 +68,17 @@ fn gradient(p: &Value) -> Gradient {pub fn effect_defaults(kind: &str) -> Value {match kind {"dropShadow" => {- json!({"blend": "Multiply", "color": "#000000", "opacity": 75, "angle": 120, "useGlobalLight": true, "distance": 5, "spread": 0, "size": 5, "contour": "Linear", "noise": 0, "knocksOut": true})+ json!({"blend": "Multiply", "color": "#000000", "opacity": 75, "angle": 120, "useGlobalLight": true, "distance": 5, "spread": 0, "size": 5, "contour": "Linear", "antiAlias": false, "noise": 0, "knocksOut": true})}"innerShadow" => {- json!({"blend": "Multiply", "color": "#000000", "opacity": 75, "angle": 120, "useGlobalLight": true, "distance": 5, "choke": 0, "size": 5, "contour": "Linear", "noise": 0})+ json!({"blend": "Multiply", "color": "#000000", "opacity": 75, "angle": 120, "useGlobalLight": true, "distance": 5, "choke": 0, "size": 5, "contour": "Linear", "antiAlias": false, "noise": 0})+ }+ "outerGlow" => {+ json!({"blend": "Screen", "opacity": 75, "color": "#ffffbe", "spread": 0, "size": 5, "range": 50, "contour": "Linear", "antiAlias": false, "noise": 0})+ }+ "innerGlow" => {+ json!({"blend": "Screen", "opacity": 75, "color": "#ffffbe", "source": "edge", "choke": 0, "size": 5, "contour": "Linear", "antiAlias": false, "noise": 0})}- "outerGlow" => json!({"blend": "Screen", "opacity": 75, "color": "#ffffbe", "spread": 0, "size": 5, "range": 50, "contour": "Linear", "noise": 0}),- "innerGlow" => json!({"blend": "Screen", "opacity": 75, "color": "#ffffbe", "source": "edge", "choke": 0, "size": 5, "contour": "Linear", "noise": 0}),"stroke" => json!({"size": 3, "position": "outside", "blend": "Normal", "opacity": 100, "color": "#000000"}),"colorOverlay" => json!({"blend": "Normal", "color": "#ff0000", "opacity": 100}),"gradientOverlay" => {@@ -82,44 +86,169 @@ pub fn effect_defaults(kind: &str) -> Value {}"patternOverlay" => json!({"blend": "Normal", "opacity": 100, "pattern": "", "angle": 0, "scale": 100, "link": true}),"bevelEmboss" => {- json!({"style": "inner", "depth": 100, "direction": "up", "size": 5, "soften": 0, "angle": 120, "useGlobalLight": true, "altitude": 30})+ json!({"style": "inner", "depth": 100, "direction": "up", "size": 5, "soften": 0, "angle": 120, "useGlobalLight": true, "altitude": 30, "glossContour": "Linear", "contour": false, "contourName": "Linear", "contourRange": 50, "contourAntiAlias": false})+ }+ "satin" => {+ json!({"blend": "Multiply", "color": "#000000", "opacity": 50, "angle": 19, "distance": 11, "size": 14, "contour": "Linear", "antiAlias": true, "invert": true})}- "satin" => json!({"blend": "Multiply", "color": "#000000", "opacity": 50, "angle": 19, "distance": 11, "size": 14, "invert": true}),_ => json!({}),}}-/// Built-in contour presets (our own transfer curves; imported PSD contours keep-/// their own points). Points are (input, output) in 0..=1, sorted by input.-pub const CONTOURS: &[(&str, &[(f32, f32)])] = &[- ("Linear", &[(0.0, 0.0), (1.0, 1.0)]),- ("Cone", &[(0.0, 0.0), (0.5, 1.0), (1.0, 1.0)]),- ("Cone (Inverted)", &[(0.0, 1.0), (0.5, 0.0), (1.0, 0.0)]),- ("Domed", &[(0.0, 0.0), (0.25, 1.0), (0.75, 1.0), (1.0, 0.0)]),- ("Domed (Inverted)", &[(0.0, 1.0), (0.25, 0.0), (0.75, 0.0), (1.0, 1.0)]),- ("Diagonal (Descending)", &[(0.0, 1.0), (1.0, 0.0)]),+/// A contour preset point: input, output (both `0..=1`) and whether it is a corner.+pub type ContourPoint = (f32, f32, bool);++/// Built-in contour presets, in the order of Photoshop's default contour picker. The shapes are+/// our own control points, drawn to match each preset's visible curve; imported PSD contours keep+/// their own points. Points are sorted by input; a corner point bends the curve sharply.+pub const CONTOURS: &[(&str, &[ContourPoint])] = &[+ ("Linear", &[(0.0, 0.0, false), (1.0, 1.0, false)]),+ ("Cone", &[(0.0, 0.0, false), (0.5, 1.0, true), (1.0, 0.0, false)]),+ ("Cone - Inverted", &[(0.0, 1.0, false), (0.5, 0.0, true), (1.0, 1.0, false)]),+ ("Cove - Deep", &[(0.0, 0.0, false), (0.3, 0.02, false), (0.6, 0.12, false), (0.85, 0.4, false), (1.0, 1.0, false)]),+ ("Cove - Shallow", &[(0.0, 0.0, false), (0.5, 0.22, false), (1.0, 1.0, false)]),+ ("Gaussian", &[(0.0, 0.0, false), (0.25, 0.08, false), (0.5, 0.5, false), (0.75, 0.92, false), (1.0, 1.0, false)]),+ ("Half Round", &[(0.0, 0.0, false), (0.04, 0.28, false), (0.15, 0.53, false), (0.35, 0.8, false), (0.65, 0.95, false), (1.0, 1.0, false)]),+ ("Ring", &[(0.0, 0.0, false), (0.25, 0.7, false), (0.5, 1.0, false), (0.75, 0.7, false), (1.0, 0.0, false)]),+ ("Ring - Double", &[(0.0, 0.0, false), (0.25, 1.0, false), (0.5, 0.0, true), (0.75, 1.0, false), (1.0, 0.0, false)]),+ ("Rolling Slope - Descending", &[(0.0, 1.0, false), (0.25, 0.62, false), (0.5, 0.58, false), (0.75, 0.28, false), (1.0, 0.0, false)]),+ (+ "Rounded Steps",+ &[+ (0.0, 0.0, false),+ (0.08, 0.01, false),+ (0.165, 0.167, false),+ (0.25, 0.323, false),+ (0.333, 0.333, true),+ (0.413, 0.343, false),+ (0.5, 0.5, false),+ (0.587, 0.657, false),+ (0.667, 0.667, true),+ (0.747, 0.677, false),+ (0.833, 0.833, false),+ (0.92, 0.99, false),+ (1.0, 1.0, false),+ ],+ ),+ ("Sawtooth 1", &[(0.0, 0.0, false), (0.3, 1.0, true), (0.34, 0.0, true), (0.64, 1.0, true), (0.68, 0.0, true), (1.0, 1.0, false)]),+];++/// Names earlier versions offered, still accepted by `contour` params (scripts, saved defaults).+const LEGACY_CONTOURS: &[(&str, &[ContourPoint])] = &[+ ("Cone (Inverted)", &[(0.0, 1.0, false), (0.5, 0.0, false), (1.0, 0.0, false)]),+ ("Domed", &[(0.0, 0.0, false), (0.25, 1.0, false), (0.75, 1.0, false), (1.0, 0.0, false)]),+ ("Domed (Inverted)", &[(0.0, 1.0, false), (0.25, 0.0, false), (0.75, 0.0, false), (1.0, 1.0, false)]),+ ("Diagonal (Descending)", &[(0.0, 1.0, false), (1.0, 0.0, false)]),];+/// Most points a contour param may carry.+pub const MAX_CONTOUR_POINTS: usize = 64;++fn preset_contour(name: &str, pts: &[ContourPoint]) -> Contour {+ let corners: Vec<bool> = pts.iter().map(|p| p.2).collect();+ Contour::Custom {+ name: name.to_string(),+ points: pts.iter().map(|(input, output, _)| CurvePoint { input: *input, output: *output }).collect(),+ corners: if corners.contains(&true) { corners } else { Vec::new() },+ }+}+/// The built-in contour called `name` (`Linear` is the identity); `None` for/// names we don't ship, so imported contours are carried rather than clobbered.pub fn builtin_contour(name: &str) -> Option<Contour> {if name.eq_ignore_ascii_case("Linear") {return Some(Contour::Linear);}- CONTOURS.iter().skip(1).find(|(n, _)| *n == name).map(|(n, pts)| Contour::Custom {- name: (*n).to_string(),- points: pts.iter().map(|(input, output)| CurvePoint { input: *input, output: *output }).collect(),- })+ CONTOURS.iter().skip(1).chain(LEGACY_CONTOURS).find(|(n, _)| *n == name).map(|(n, pts)| preset_contour(n, pts))}-/// The param naming a contour (`"Linear"` or a preset/custom contour's name).+/// The param naming a contour: `"Linear"` or a built-in preset's name when the contour is that+/// preset, else the curve itself as `{"name", "points": [[input, output], …], "corners": [bool, …]}`+/// (inputs and outputs `0..=1`), so a round trip through the param keeps an imported or edited+/// curve exactly.pub fn contour_param(c: &Contour) -> Value {match c {Contour::Linear => json!("Linear"),- Contour::Custom { name, .. } => json!(name),+ Contour::Custom { name, .. } if builtin_contour(name).as_ref() == Some(c) => json!(name),+ Contour::Custom { name, points, corners } => {+ let pts: Vec<Value> = points.iter().map(|p| json!([short(p.input), short(p.output)])).collect();+ let corners: Vec<bool> = (0..points.len()).map(|i| corners.get(i).copied().unwrap_or(false)).collect();+ json!({"name": name, "points": pts, "corners": corners})+ }}}+/// `x` as the shortest decimal that reads back as the same `f32` (`0.2`, not `0.20000000298…`).+fn short(x: f32) -> Value {+ x.to_string().parse::<f64>().map_or(Value::Null, |v| json!(v))+}++/// The contour a `contour` param names: a built-in preset's name, or a curve object (see+/// [`contour_param`]). `None` for an unknown name or a malformed curve (fewer than two points,+/// more than [`MAX_CONTOUR_POINTS`], non-finite values), so the effect keeps its contour.+/// Points are clamped to `0..=1` and sorted by input; points at the same input collapse.+pub fn contour_from_param(v: &Value) -> Option<Contour> {+ match v {+ Value::String(name) => builtin_contour(name),+ Value::Object(o) => {+ let raw = o.get("points")?.as_array()?;+ if raw.len() < 2 || raw.len() > MAX_CONTOUR_POINTS {+ return None;+ }+ let flags = o.get("corners").and_then(Value::as_array);+ let mut pts: Vec<ContourPoint> = Vec::with_capacity(raw.len());+ for (i, q) in raw.iter().enumerate() {+ let q = q.as_array()?;+ let (x, y) = (q.first()?.as_f64()? as f32, q.get(1)?.as_f64()? as f32);+ if !x.is_finite() || !y.is_finite() {+ return None;+ }+ let corner = flags.and_then(|f| f.get(i)).and_then(Value::as_bool).unwrap_or(false);+ pts.push((x.clamp(0.0, 1.0), y.clamp(0.0, 1.0), corner));+ }+ pts.sort_by(|a, b| a.0.total_cmp(&b.0));+ pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6);+ if pts.len() < 2 {+ return None;+ }+ let name = o.get("name").and_then(Value::as_str).unwrap_or("Custom");+ Some(preset_contour(name, &pts))+ }+ _ => None,+ }+}++/// The contours of an `.shc` contour preset file (Contour Editor › Load…), as `contour` params.+/// Points are rescaled from the file's `0..=255` levels; unusable curves are skipped.+pub fn contours_from_shc(bytes: &[u8]) -> Result<Vec<Value>> {+ let file = photocraft_psd::shc::parse(bytes).map_err(|e| EngineError::Other(format!("not a contour file: {e}")))?;+ Ok(file+ .into_iter()+ .filter_map(|c| {+ let v = json!({+ "name": c.name,+ "points": c.points.iter().map(|p| json!([p.input / 255.0, p.output / 255.0])).collect::<Vec<_>>(),+ "corners": c.points.iter().map(|p| !p.continuous).collect::<Vec<_>>(),+ });+ contour_from_param(&v).map(|c| contour_param(&c))+ })+ .collect())+}++/// An `.shc` file holding `contour` (Contour Editor › Save…).+pub fn contour_to_shc(contour: &Contour) -> Result<Vec<u8>> {+ let (name, points) = match contour {+ Contour::Linear => ("Linear".to_string(), vec![CurvePoint { input: 0.0, output: 0.0 }, CurvePoint { input: 1.0, output: 1.0 }]),+ Contour::Custom { name, points, .. } => (name.clone(), points.clone()),+ };+ let points = points+ .iter()+ .enumerate()+ .map(|(i, p)| photocraft_psd::shc::ShcPoint { input: p.input * 255.0, output: p.output * 255.0, continuous: !contour.is_corner(i) })+ .collect();+ photocraft_psd::shc::write(&[photocraft_psd::shc::ShcContour { name, points }]).map_err(|e| EngineError::Other(format!("can't write the contour: {e}")))+}+/// An effect of `kind` with its factory settings (before params are applied).fn fresh_effect(kind: &str) -> Option<Effect> {let shadow = |inner: bool| Shadow {@@ -240,13 +369,16 @@ pub fn overlay_effect(fx: &mut Effect, p: &Value) {*c = x;}}- fn set_contour(p: &Value, c: &mut Contour) {- if let Some(name) = p.get("contour").and_then(Value::as_str)- && let Some(x) = builtin_contour(name)- {+ fn set_contour(p: &Value, key: &str, c: &mut Contour) {+ if let Some(x) = p.get(key).and_then(contour_from_param) {*c = x;}}+ fn set_bool(p: &Value, key: &str, b: &mut bool) {+ if let Some(x) = b_of(p, key) {+ *b = x;+ }+ }fn common(c: &mut FxCommon, p: &Value) {if let Some(x) = b_of(p, "enabled") {c.enabled = x;@@ -280,7 +412,8 @@ pub fn overlay_effect(fx: &mut Effect, p: &Value) {if let Some(x) = f_of(p, "size") {s.size = x;}- set_contour(p, &mut s.contour);+ set_contour(p, "contour", &mut s.contour);+ set_bool(p, "antiAlias", &mut s.anti_alias);if let Some(x) = f_of(p, "noise") {s.noise = (x / 100.0).clamp(0.0, 1.0);}@@ -303,7 +436,8 @@ pub fn overlay_effect(fx: &mut Effect, p: &Value) {if let Some(x) = f_of(p, "size") {g.size = x;}- set_contour(p, &mut g.contour);+ set_contour(p, "contour", &mut g.contour);+ set_bool(p, "antiAlias", &mut g.anti_alias);if let Some(x) = f_of(p, "range") {g.range = (x / 100.0).clamp(0.01, 1.0);}@@ -380,6 +514,8 @@ pub fn overlay_effect(fx: &mut Effect, p: &Value) {if let Some(x) = b_of(p, "invert") {s.invert = x;}+ set_contour(p, "contour", &mut s.contour);+ set_bool(p, "antiAlias", &mut s.anti_alias);}Effect::BevelEmboss(bv) => {if let Some(x) = b_of(p, "enabled") {@@ -422,21 +558,20 @@ pub fn overlay_effect(fx: &mut Effect, p: &Value) {if let Some(x) = b_of(p, "useGlobalLight") {bv.use_global_light = x;}- if let Some(x) = p.get("glossContour").and_then(Value::as_str)- && let Some(c) = builtin_contour(x)- {- bv.gloss_contour = c;+ set_contour(p, "glossContour", &mut bv.gloss_contour);+ // The Contour element: `contour` turns it on/off; its curve, Range and+ // Anti-aliased edit the element in place, so an imported curve survives.+ match b_of(p, "contour") {+ Some(false) => bv.contour = None,+ Some(true) if bv.contour.is_none() => bv.contour = Some(photocraft_doc::BevelContour::default()),+ _ => {}}- if let Some(x) = b_of(p, "contour") {- bv.contour = x.then(|| photocraft_doc::BevelContour {- contour: builtin_contour(p.get("contourName").and_then(Value::as_str).unwrap_or("Linear")).unwrap_or(Contour::Linear),- range: (f(p, "contourRange", 50.0) / 100.0).clamp(0.01, 1.0),- anti_alias: false,- });- } else if let Some(c) = &mut bv.contour- && let Some(x) = builtin_contour(p.get("contourName").and_then(Value::as_str).unwrap_or(""))- {- c.contour = x;+ if let Some(c) = &mut bv.contour {+ set_contour(p, "contourName", &mut c.contour);+ if let Some(x) = f_of(p, "contourRange") {+ c.range = (x / 100.0).clamp(0.01, 1.0);+ }+ set_bool(p, "contourAntiAlias", &mut c.anti_alias);}if let Some(t) = p.get("texture").and_then(Value::as_str).filter(|t| !t.is_empty()) {bv.texture = Some(photocraft_doc::BevelTexture {@@ -623,22 +758,22 @@ pub fn specs() -> Vec<CommandSpec> {style_cmd!("dropShadow","Drop Shadow…",- r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str="multiply","angle":deg=120,"useGlobalLight":bool,"distance":px=5,"spread":0..100,"size":px=5,"contour":"Linear|Cone|Cone (Inverted)|Domed|Domed (Inverted)|Diagonal (Descending)"="Linear","noise":0..100,"knocksOut":bool,"add":bool,"layer":id}"##+ r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str="multiply","angle":deg=120,"useGlobalLight":bool,"distance":px=5,"spread":0..100,"size":px=5,"contour":"Linear|Cone|Cone - Inverted|Cove - Deep|Cove - Shallow|Gaussian|Half Round|Ring|Ring - Double|Rolling Slope - Descending|Rounded Steps|Sawtooth 1"|{"name":str,"points":[[in 0..1,out 0..1],…],"corners":[bool,…]}="Linear","antiAlias":bool,"noise":0..100,"knocksOut":bool,"add":bool,"layer":id}"##),style_cmd!("innerShadow","Inner Shadow…",- r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str,"angle":deg,"distance":px,"choke":0..100,"size":px,"contour":name,"noise":0..100,"add":bool}"##+ r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str,"angle":deg,"distance":px,"choke":0..100,"size":px,"contour":name|curve,"antiAlias":bool,"noise":0..100,"add":bool}"##),style_cmd!("outerGlow","Outer Glow…",- r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str="screen","technique":"softer|precise","spread":0..100,"size":px,"range":0..100,"contour":name,"noise":0..100,"add":bool}"##+ r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str="screen","technique":"softer|precise","spread":0..100,"size":px,"range":0..100,"contour":name|curve,"antiAlias":bool,"noise":0..100,"add":bool}"##),style_cmd!("innerGlow","Inner Glow…",- r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str="screen","technique":"softer|precise","source":"edge|center","choke":0..100,"size":px,"contour":name,"noise":0..100,"add":bool}"##+ r##"{"color":"#rrggbb","opacity":0..100=75,"blend":str="screen","technique":"softer|precise","source":"edge|center","choke":0..100,"size":px,"contour":name|curve,"antiAlias":bool,"noise":0..100,"add":bool}"##),style_cmd!("stroke",@@ -659,9 +794,13 @@ pub fn specs() -> Vec<CommandSpec> {style_cmd!("bevelEmboss","Bevel & Emboss…",- r##"{"style":"inner|outer|emboss|pillow|stroke","technique":"smooth|chiselHard|chiselSoft","contour":bool,"contourRange":1..100=50,"texture":pattern id|name?,"textureScale":1..1000=100,"textureDepth":-1000..1000=100,"textureInvert":bool,"textureLink":bool=true,"depth":1..1000=100,"direction":"up|down","size":px=5,"soften":px,"angle":deg,"altitude":deg,"add":bool}"##+ r##"{"style":"inner|outer|emboss|pillow|stroke","technique":"smooth|chiselHard|chiselSoft","contour":bool,"contourName":name|curve,"contourRange":1..100=50,"contourAntiAlias":bool,"glossContour":name|curve,"texture":pattern id|name?,"textureScale":1..1000=100,"textureDepth":-1000..1000=100,"textureInvert":bool,"textureLink":bool=true,"depth":1..1000=100,"direction":"up|down","size":px=5,"soften":px,"angle":deg,"altitude":deg,"add":bool}"##+ ),+ style_cmd!(+ "satin",+ "Satin…",+ r##"{"color":"#rrggbb","opacity":0..100=50,"blend":str,"angle":deg,"distance":px,"size":px,"contour":name|curve,"antiAlias":bool=true,"invert":bool,"add":bool}"##),- style_cmd!("satin", "Satin…", r##"{"color":"#rrggbb","opacity":0..100=50,"blend":str,"angle":deg,"distance":px,"size":px,"invert":bool,"add":bool}"##),CommandSpec {id: "layer.layerStyle.replace",label: "Edit Layer Style",@@ -919,6 +1058,7 @@ mod tests {let imported = Contour::Custom {name: "Photoshop contour".into(),points: vec![photocraft_doc::adjust::CurvePoint { input: 0.0, output: 1.0 }, photocraft_doc::adjust::CurvePoint { input: 1.0, output: 0.0 }],+ corners: vec![],};let mut carried = before[0].clone();if let Effect::DropShadow(c) = &mut carried {@@ -934,6 +1074,61 @@ mod tests {assert_eq!(lin.contour, Contour::Linear);}+ #[test]+ fn contour_presets_and_custom_curves_apply_in_one_undo_step() {+ let mut s = session();+ // Picking Cone: the preset's own curve, its peak a corner, in one undo step.+ s.execute("layer.layerStyle.dropShadow", json!({"contour": "Cone", "antiAlias": true})).unwrap();+ let Effect::DropShadow(sh) = &effects(&s)[0] else { panic!() };+ assert_eq!(sh.contour, builtin_contour("Cone").unwrap());+ assert!(sh.contour.is_corner(1) && sh.anti_alias);+ let Contour::Custom { points, corners, .. } = &sh.contour else { panic!() };+ let lut = photocraft_compose::adjust::contour_curve_lut(points, corners);+ let at = |x: f32| lut[(x * (lut.len() - 1) as f32).round() as usize];+ assert!((at(0.5) - 1.0).abs() < 1e-3 && (at(0.25) - 0.5).abs() < 0.01, "a sharp Λ, not a rounded hump");+ assert_eq!(contour_param(&sh.contour), json!("Cone"));+ s.execute("edit.undo", json!({})).unwrap();+ assert!(effects(&s).is_empty(), "one undo removes it");++ // An edited curve (the Contour Editor's param) round trips exactly, in every effect.+ let curve = json!({"name": "Mine", "points": [[0.0, 0.2], [0.4, 0.9], [1.0, 0.1]], "corners": [false, true, false]});+ for kind in ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "satin"] {+ let mut fx = fresh_effect(kind).unwrap();+ overlay_effect(&mut fx, &json!({"contour": curve}));+ let v = values(&fx, "contour");+ assert_eq!(v, curve, "{kind}");+ }+ let mut bevel = fresh_effect("bevelEmboss").unwrap();+ overlay_effect(&mut bevel, &json!({"contour": true, "contourName": curve, "glossContour": "Ring"}));+ let Effect::BevelEmboss(b) = &bevel else { panic!() };+ assert_eq!(contour_param(&b.contour.as_ref().unwrap().contour), curve);+ assert_eq!(b.gloss_contour, builtin_contour("Ring").unwrap());+ // Malformed curves leave the contour alone.+ for bad in [json!({"points": [[0.5, 0.5]]}), json!({"points": [[0.0, "x"], [1.0, 1.0]]}), json!({"points": "no"}), json!(7)] {+ let mut fx = fresh_effect("dropShadow").unwrap();+ overlay_effect(&mut fx, &json!({"contour": bad}));+ assert_eq!(values(&fx, "contour"), json!("Linear"));+ }++ // `.shc` round trip of a curve with a corner.+ let mine = contour_from_param(&curve).unwrap();+ let back = contours_from_shc(&contour_to_shc(&mine).unwrap()).unwrap();+ let back = contour_from_param(&back[0]).unwrap();+ let Contour::Custom { points, corners, .. } = &back else { panic!() };+ assert_eq!(corners, &vec![false, true, false]);+ assert!((points[1].input - 0.4).abs() < 0.003 && (points[1].output - 0.9).abs() < 0.003, "{points:?}");+ }++ fn values(fx: &Effect, key: &str) -> Value {+ let c = match fx {+ Effect::DropShadow(s) | Effect::InnerShadow(s) => &s.contour,+ Effect::OuterGlow(g) | Effect::InnerGlow(g) => &g.contour,+ Effect::Satin(s) => &s.contour,+ _ => panic!("{key}: no contour"),+ };+ contour_param(c)+ }+#[test]fn make_default_then_reset_restores_it() {let mut s = session();diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rsindex edd4e87b6..48da34240 100644--- a/crates/gpu/src/fx.rs+++ b/crates/gpu/src/fx.rs@@ -267,7 +267,7 @@ pub(crate) fn blur_kernel(size: f32) -> Option<(i32, Vec<f32>)> {fn contour_lut(c: &Contour) -> Option<Vec<f32>> {match c {Contour::Linear => None,- Contour::Custom { points, .. } => Some(photocraft_compose::adjust::curve_lut(points)),+ Contour::Custom { points, corners, .. } => Some(photocraft_compose::adjust::contour_curve_lut(points, corners)),}}diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rsindex 0b931c8be..f5a6daa1c 100644--- a/crates/gpu/tests/parity.rs+++ b/crates/gpu/tests/parity.rs@@ -1048,7 +1048,11 @@ fn fx_doc(w: u32, h: u32, depth: SampleType) -> Document {}fn contour() -> Contour {- Contour::Custom { name: "cove".into(), points: vec![Cp { input: 0.0, output: 0.1 }, Cp { input: 0.4, output: 0.8 }, Cp { input: 1.0, output: 0.6 }] }+ Contour::Custom {+ name: "cove".into(),+ points: vec![Cp { input: 0.0, output: 0.1 }, Cp { input: 0.4, output: 0.8 }, Cp { input: 1.0, output: 0.6 }],+ corners: vec![],+ }}fn shadow(blend: BlendMode, opacity: f32, angle: f32, distance: f32, size: f32, spread: f32) -> Shadow {diff --git a/crates/io/src/effects_map.rs b/crates/io/src/effects_map.rsindex b45236736..4dfa42ffb 100644--- a/crates/io/src/effects_map.rs+++ b/crates/io/src/effects_map.rs@@ -106,27 +106,34 @@ fn contour(d: &Descriptor, key: &str) -> Contour {_ => String::new(),};let mut points = Vec::new();+ let mut corners = Vec::new();if let Some(Value::List(items)) = c.get("Crv ") {for it in items {if let Value::Descriptor(p) = it {points.push(CurvePoint { input: f(p, "Hrzn", 0.0) / 255.0, output: f(p, "Vrtc", 0.0) / 255.0 });+ // `Cnty` (continuity): false marks a corner point; absent means smooth.+ corners.push(matches!(p.get("Cnty"), Some(Value::Boolean(false))));}}}+ if !corners.contains(&true) {+ corners.clear();+ }let linear = points.len() == 2 && points[0].input == 0.0 && points[0].output == 0.0 && points[1].input == 1.0 && points[1].output == 1.0;- if points.is_empty() || (linear && (name.is_empty() || name == "Linear")) { Contour::Linear } else { Contour::Custom { name, points } }+ if points.is_empty() || (linear && (name.is_empty() || name == "Linear")) { Contour::Linear } else { Contour::Custom { name, points, corners } }}fn contour_value(c: &Contour) -> Value {let (name, points) = match c {Contour::Linear => ("Linear".to_string(), vec![CurvePoint { input: 0.0, output: 0.0 }, CurvePoint { input: 1.0, output: 1.0 }]),- Contour::Custom { name, points } => (name.clone(), points.clone()),+ Contour::Custom { name, points, .. } => (name.clone(), points.clone()),};let pts = points.iter()- .map(|p| {- Value::Descriptor(- Descriptor::new("CrPt").with("Hrzn", Value::Double(f64::from(p.input * 255.0))).with("Vrtc", Value::Double(f64::from(p.output * 255.0))),- )+ .enumerate()+ .map(|(i, p)| {+ let d = Descriptor::new("CrPt").with("Hrzn", Value::Double(f64::from(p.input * 255.0))).with("Vrtc", Value::Double(f64::from(p.output * 255.0)));+ // Photoshop writes no `Cnty` (continuity) on smooth points; a corner carries `Cnty` false.+ Value::Descriptor(if c.is_corner(i) { d.with("Cnty", Value::Boolean(false)) } else { d })}).collect();Value::Descriptor(Descriptor::new("ShpC").with("Nm ", Value::Text(UnicodeString::new_nul(&name))).with("Crv ", Value::List(pts)))@@ -628,6 +635,7 @@ mod tests {contour: Contour::Custom {name: "Cone".into(),points: vec![CurvePoint { input: 0.0, output: 0.0 }, CurvePoint { input: 0.5, output: 1.0 }, CurvePoint { input: 1.0, output: 0.0 }],+ corners: vec![false, true, false],},..match Effect::default_drop_shadow() {Effect::DropShadow(s) => s,diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rsindex a3fb3c42c..16d539b94 100644--- a/crates/psd/src/lib.rs+++ b/crates/psd/src/lib.rs@@ -61,6 +61,7 @@ pub mod path;pub mod patterns;pub mod pixels;pub mod resources;+pub mod shc;pub mod slices;pub mod tagged;#[cfg(any(test, feature = "testgen"))]diff --git a/crates/psd/src/shc.rs b/crates/psd/src/shc.rsnew file mode 100644index 000000000..dfe485571--- /dev/null+++ b/crates/psd/src/shc.rs@@ -0,0 +1,198 @@+//! Photoshop contour preset files (`.shc`), the Layer Style dialog's Contour Editor Load/Save.+//!+//! Layout from Adobe's public "Photoshop File Formats Specification" (Additional File Formats ›+//! Contours): a 4-byte type `8BFS`, a `u16` version (1) and a `u32` count of contours. Each+//! contour is a `u32` version (1 or 2), a Unicode name, a `u16` point count and the points as two+//! `u16`s each (vertical first, then horizontal). Version 2 then has one boolean byte per point+//! ("whether the point is continuous"); both versions end with a 4-byte minimum and maximum+//! input range. All values are big-endian.+//!+//! The spec leaves two details open, handled defensively:+//! - The name is read like the spec's other Unicode strings (a `u32` UTF-16 code-unit count that+//! includes a trailing null, as in `.aco`); a name whose count leaves out the null and is+//! followed by one is read too. Names are written with the null counted.+//! - Coordinates are read as 0..=255 levels, the scale of the layer-style contour descriptors+//! (`ShpC` points); the input range is written as 0..=255.++use crate::error::{PsdError, Result};+use crate::io::{Reader, WriteExt};++/// Most contours read from one file.+pub const MAX_CONTOURS: usize = 4096;+/// Most points in one contour (the counts are 16-bit; Photoshop allows far fewer).+pub const MAX_POINTS: usize = 256;+/// Longest name read or written, in UTF-16 code units.+pub const MAX_NAME_UNITS: usize = 1024;++/// One contour point: input (horizontal) and output (vertical), `0..=255`, and whether the curve+/// passes smoothly through it (`false` = a corner).+#[derive(Debug, Clone, Copy, PartialEq)]+pub struct ShcPoint {+ /// Input level, `0..=255`.+ pub input: f32,+ /// Output level, `0..=255`.+ pub output: f32,+ /// Smooth (`true`) or corner (`false`).+ pub continuous: bool,+}++/// One named contour.+#[derive(Debug, Clone, PartialEq)]+pub struct ShcContour {+ /// Preset name.+ pub name: String,+ /// Points, in file order.+ pub points: Vec<ShcPoint>,+}++fn read_name(r: &mut Reader<'_>) -> Result<String> {+ let n = u64::from(r.u32()?);+ r.check_count(n, 2)?;+ let n = usize::try_from(n).map_err(|_| PsdError::LimitExceeded("contour name length"))?;+ let mut units = Vec::with_capacity(n.min(MAX_NAME_UNITS));+ for _ in 0..n {+ let u = r.u16()?;+ if units.len() < MAX_NAME_UNITS {+ units.push(u);+ }+ }+ // A count that leaves out the terminator: the null follows (a point count is never 0).+ if units.last() != Some(&0) && r.peek_rest().get(..2) == Some(&[0, 0]) {+ r.u16()?;+ }+ while units.last() == Some(&0) {+ units.pop();+ }+ Ok(String::from_utf16_lossy(&units))+}++/// Parse an `.shc` file. Bad signatures, unknown versions, truncation and impossible counts are+/// errors; never panics.+pub fn parse(data: &[u8]) -> Result<Vec<ShcContour>> {+ let mut r = Reader::new(data);+ let sig = r.array::<4>()?;+ if &sig != b"8BFS" {+ return Err(PsdError::InvalidSignature { expected: "8BFS", found: sig });+ }+ let version = r.u16()?;+ if version != 1 {+ return Err(PsdError::UnsupportedVersion(version));+ }+ let count = u64::from(r.u32()?);+ // A contour takes at least 4 (version) + 4 (name) + 2 (points) + 8 (range) bytes.+ r.check_count(count, 18)?;+ let count = usize::try_from(count).map_err(|_| PsdError::LimitExceeded("contour count"))?;+ if count > MAX_CONTOURS {+ return Err(PsdError::LimitExceeded("too many contours in an .shc file"));+ }+ let mut out = Vec::with_capacity(count);+ for _ in 0..count {+ let v = r.u32()?;+ if v != 1 && v != 2 {+ return Err(PsdError::invalid(format!("unknown contour version {v}")));+ }+ let name = read_name(&mut r)?;+ let n = usize::from(r.u16()?);+ r.check_count(n as u64, if v == 2 { 5 } else { 4 })?;+ if n > MAX_POINTS {+ return Err(PsdError::LimitExceeded("too many points in a contour"));+ }+ let mut points = Vec::with_capacity(n);+ for _ in 0..n {+ let output = f32::from(r.u16()?).min(255.0);+ let input = f32::from(r.u16()?).min(255.0);+ points.push(ShcPoint { input, output, continuous: true });+ }+ if v == 2 {+ for p in &mut points {+ p.continuous = r.u8()? != 0;+ }+ }+ // Minimum and maximum input range: not needed to draw the curve.+ r.skip(8)?;+ out.push(ShcContour { name, points });+ }+ Ok(out)+}++/// Write an `.shc` file (every contour as version 2, with its corner flags). Fails when a contour+/// has more than [`MAX_POINTS`] points or there are more than [`MAX_CONTOURS`].+pub fn write(contours: &[ShcContour]) -> Result<Vec<u8>> {+ if contours.len() > MAX_CONTOURS {+ return Err(PsdError::LimitExceeded("too many contours for an .shc file"));+ }+ let mut out = Vec::with_capacity(10 + contours.len() * 64);+ out.put(b"8BFS");+ out.put_u16(1);+ out.put_u32(contours.len() as u32);+ for c in contours {+ let n = u16::try_from(c.points.len()).ok().filter(|n| usize::from(*n) <= MAX_POINTS).ok_or(PsdError::LimitExceeded("too many points in a contour"))?;+ out.put_u32(2);+ let units: Vec<u16> = c.name.encode_utf16().take(MAX_NAME_UNITS).collect();+ out.put_u32(units.len() as u32 + 1);+ for u in units {+ out.put_u16(u);+ }+ out.put_u16(0);+ out.put_u16(n);+ let level = |v: f32| if v.is_finite() { v.round().clamp(0.0, 255.0) as u16 } else { 0 };+ for p in &c.points {+ out.put_u16(level(p.output));+ out.put_u16(level(p.input));+ }+ for p in &c.points {+ out.put_u8(u8::from(p.continuous));+ }+ out.put_u32(0);+ out.put_u32(255);+ }+ Ok(out)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn shc_round_trips_and_rejects_hostile_input() {+ let cone = ShcContour {+ name: "Cone".into(),+ points: vec![+ ShcPoint { input: 0.0, output: 0.0, continuous: true },+ ShcPoint { input: 128.0, output: 255.0, continuous: false },+ ShcPoint { input: 255.0, output: 0.0, continuous: true },+ ],+ };+ let bytes = write(std::slice::from_ref(&cone)).unwrap();+ assert_eq!(&bytes[..4], b"8BFS");+ assert_eq!(parse(&bytes).unwrap(), vec![cone.clone()]);++ // Version 1 without corner flags, with a name count that leaves out the null.+ let mut v1 = b"8BFS".to_vec();+ v1.put_u16(1);+ v1.put_u32(1);+ v1.put_u32(1);+ v1.put_u32(2);+ v1.put_u16(u16::from(b'O'));+ v1.put_u16(u16::from(b'K'));+ v1.put_u16(0);+ v1.put_u16(2);+ for v in [0u16, 0, 255, 255] {+ v1.put_u16(v);+ }+ v1.put_u32(0);+ v1.put_u32(255);+ let c = parse(&v1).unwrap();+ assert_eq!(c[0].name, "OK");+ assert!(c[0].points.iter().all(|p| p.continuous) && c[0].points[1].input == 255.0);++ // Truncations, a wrong signature and absurd counts are errors, never panics.+ for cut in 0..bytes.len() {+ assert!(parse(&bytes[..cut]).is_err(), "cut at {cut}");+ }+ assert!(parse(b"8BFX\0\x01\0\0\0\0").is_err());+ assert!(parse(b"8BFS\0\x01\xff\xff\xff\xff").is_err());+ let many = ShcContour { name: String::new(), points: vec![ShcPoint { input: 0.0, output: 0.0, continuous: true }; MAX_POINTS + 1] };+ assert!(write(&[many]).is_err());+ }+}diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex 60e6a3474..b80a045ae 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -2322,6 +2322,21 @@ cameraRaw Color BarvyDomed KopuleDomed (Inverted) Kopule (obrácená)Diagonal (Descending) Diagonála (sestupná)+ Contour Editor Editor kontury+ Anti-aliased Vyhlazení+ Corner Roh+ Gloss Contour Kontura lesku+ Contour Kontura+ Cone - Inverted Kužel - obrácený+ Cove - Deep Zátoka - hluboká+ Cove - Shallow Zátoka - mělká+ Gaussian Gaussovský+ Half Round Půlkruh+ Ring Prstenec+ Ring - Double Prstenec - dvojitý+ Rolling Slope - Descending Zvlněný svah - sestupný+ Rounded Steps Zaoblené stupně+ Sawtooth 1 Pila 1Red Eye Tool Nástroj červené očiRed Eye Červené očidiff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex 13789303c..9ed88a0bf 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2358,6 +2358,21 @@Domed GewölbtDomed (Inverted) Gewölbt (umgekehrt)Diagonal (Descending) Diagonal (absteigend)+ Contour Editor Kontur-Editor+ Anti-aliased Glätten+ Corner Ecke+ Gloss Contour Glanzkontur+ Contour Kontur+ Cone - Inverted Kegel - umgekehrt+ Cove - Deep Bucht - tief+ Cove - Shallow Bucht - flach+ Gaussian Gauß+ Half Round Halbrund+ Ring Ring+ Ring - Double Ring - doppelt+ Rolling Slope - Descending Wellenhang - absteigend+ Rounded Steps Abgerundete Stufen+ Sawtooth 1 Sägezahn 1Red Eye Tool Rote-Augen-WerkzeugRed Eye Rote Augendiff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex 14833e03c..5fc57c9b6 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -3418,6 +3418,19 @@ cameraRaw Yellow ΚίτρινοCould not open Δεν ήταν δυνατό το άνοιγμαDefault PhotoCraft Size Προεπιλεγμένο μέγεθος PhotoCraftDiagonal (Descending) Διαγώνιος (φθίνουσα)+ Contour Editor Επεξεργαστής περιγράμματος+ Anti-aliased Εξομάλυνση+ Corner Γωνία+ Gloss Contour Περίγραμμα γυαλάδας+ Contour Περίγραμμα+ Cone - Inverted Κώνος - ανεστραμμένος+ Cove - Deep Όρμος - βαθύς+ Cove - Shallow Όρμος - ρηχός+ Half Round Ημικύκλιο+ Ring - Double Δακτύλιος - διπλός+ Rolling Slope - Descending Κυματιστή κλίση - φθίνουσα+ Rounded Steps Στρογγυλεμένα σκαλοπάτια+ Sawtooth 1 Πριονωτό 1DirectX 12 DirectX 12Display p3 Display P3Divide Διαίρεσηdiff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex 68500026d..b5f4c77d4 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2389,6 +2389,20 @@ cameraRaw Amount CantidadDomed AbovedadoDomed (Inverted) Abovedado (invertido)Diagonal (Descending) Diagonal (descendente)+ Contour Editor Editor de contorno+ Anti-aliased Suavizado+ Corner Esquina+ Gloss Contour Contorno de brillo+ Contour Contorno+ Cone - Inverted Cono - invertido+ Cove - Deep Ensenada - profunda+ Cove - Shallow Ensenada - poco profunda+ Half Round Medio redondo+ Ring Anillo+ Ring - Double Anillo - doble+ Rolling Slope - Descending Pendiente ondulada - descendente+ Rounded Steps Pasos redondeados+ Sawtooth 1 Diente de sierra 1Red Eye Tool Herramienta Ojos rojosRed Eye Ojos rojosdiff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex f5f7ccb4c..79d3e9a92 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -2743,6 +2743,21 @@ cameraRaw Blending FusionDomed BombéDomed (Inverted) Bombé (inversé)Diagonal (Descending) Diagonale (descendante)+ Contour Editor Éditeur de contour+ Anti-aliased Lissé+ Corner Angle+ Gloss Contour Contour brillant+ Contour Contour+ Cone - Inverted Cône - inversé+ Cove - Deep Crique - profonde+ Cove - Shallow Crique - peu profonde+ Gaussian Gaussienne+ Half Round Demi-arrondi+ Ring Anneau+ Ring - Double Anneau - double+ Rolling Slope - Descending Pente ondulée - descendante+ Rounded Steps Paliers arrondis+ Sawtooth 1 Dents de scie 1Red Eye Tool Outil Yeux rougesPupil Size Taille de la pupillediff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex c5c05f3cf..45f4f7714 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -2730,6 +2730,21 @@ cameraRaw Blending PembauranDomed KubahDomed (Inverted) Kubah (Terbalik)Diagonal (Descending) Diagonal (Menurun)+ Contour Editor Editor Kontur+ Anti-aliased Dihaluskan+ Corner Sudut+ Gloss Contour Kontur Kilap+ Contour Kontur+ Cone - Inverted Kerucut - Terbalik+ Cove - Deep Teluk - Dalam+ Cove - Shallow Teluk - Dangkal+ Gaussian Gaussian+ Half Round Setengah Bulat+ Ring Cincin+ Ring - Double Cincin - Ganda+ Rolling Slope - Descending Lereng Bergelombang - Menurun+ Rounded Steps Tangga Bulat+ Sawtooth 1 Gigi Gergaji 1Red Eye Tool Alat Mata MerahPupil Size Ukuran pupildiff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex c1f75bcc2..23800c3ef 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -2393,6 +2393,21 @@ cameraRaw Amount QuantitàDomed BombatoDomed (Inverted) Bombato (invertito)Diagonal (Descending) Diagonale (discendente)+ Contour Editor Editor contorno+ Anti-aliased Con antialiasing+ Corner Angolo+ Gloss Contour Contorno lucido+ Contour Contorno+ Cone - Inverted Cono - invertito+ Cove - Deep Insenatura - profonda+ Cove - Shallow Insenatura - poco profonda+ Gaussian Gaussiana+ Half Round Semicerchio+ Ring Anello+ Ring - Double Anello - doppio+ Rolling Slope - Descending Pendio ondulato - discendente+ Rounded Steps Gradini arrotondati+ Sawtooth 1 Dente di sega 1Red Eye Tool Strumento Occhi rossiRed Eye Occhi rossiPupil Size Dimensione pupilladiff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex e8d8eebee..d02efc1cd 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -2295,6 +2295,19 @@ cameraRaw Color カラーDomed ドームDomed (Inverted) ドーム (反転)Diagonal (Descending) 斜め (下降)+ Contour Editor 輪郭エディター+ Anti-aliased アンチエイリアス+ Corner コーナー+ Gloss Contour 光沢輪郭+ Contour 輪郭+ Cone - Inverted 円錐 - 反転+ Cove - Deep 入り江 - 深+ Cove - Shallow 入り江 - 浅+ Half Round 半円+ Ring - Double リング - ダブル+ Rolling Slope - Descending ローリングスロープ - 下降+ Rounded Steps 丸い階段+ Sawtooth 1 のこぎり波 1Red Eye Tool 赤目ツールRed Eye 赤目diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex 7b068773b..15a7a5266 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -2909,6 +2909,19 @@ cameraRaw Color 색상Domed 돔Domed (Inverted) 돔(반전)Diagonal (Descending) 대각선(내림)+ Contour Editor 윤곽선 편집기+ Anti-aliased 앤티 앨리어스+ Corner 모퉁이+ Gloss Contour 광택 윤곽선+ Contour 윤곽선+ Cone - Inverted 원뿔 - 반전+ Cove - Deep 후미 - 깊게+ Cove - Shallow 후미 - 얕게+ Half Round 반원+ Ring - Double 링 - 이중+ Rolling Slope - Descending 구르는 경사 - 내림차순+ Rounded Steps 둥근 계단+ Sawtooth 1 톱니 1Red Eye Tool 적목 현상 도구Red Eye 적목 현상diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex 2dbcc0277..6eecc2433 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -2329,6 +2329,19 @@Domed KoepelDomed (Inverted) Koepel (omgekeerd)Diagonal (Descending) Diagonaal (aflopend)+ Contour Editor Contoureditor+ Anti-aliased Anti-aliasing+ Corner Hoek+ Gloss Contour Glanscontour+ Contour Contour+ Cone - Inverted Kegel - omgekeerd+ Cove - Deep Inham - diep+ Cove - Shallow Inham - ondiep+ Half Round Halfrond+ Ring - Double Ring - dubbel+ Rolling Slope - Descending Glooiende helling - aflopend+ Rounded Steps Afgeronde treden+ Sawtooth 1 Zaagtand 1Red Eye Tool Rode-ogengereedschapRed Eye Rode ogenPupil Size Pupilgroottediff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 44e17ebb5..30d660a33 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -3358,6 +3358,19 @@ cameraRaw Roughness ChropowatośćDomed KopułaDomed (Inverted) Kopuła (odwrócona)Diagonal (Descending) Przekątna (malejąca)+ Contour Editor Edytor konturu+ Anti-aliased Wygładzanie+ Corner Narożnik+ Gloss Contour Kontur połysku+ Contour Kontur+ Cone - Inverted Stożek - odwrócony+ Cove - Deep Zatoka - głęboka+ Cove - Shallow Zatoka - płytka+ Half Round Półokrągły+ Ring - Double Pierścień - podwójny+ Rolling Slope - Descending Falisty spadek - malejący+ Rounded Steps Zaokrąglone stopnie+ Sawtooth 1 Piła 1Red Eye Tool Narzędzie Czerwone oczyPupil Size Rozmiar źrenicyDarken Amount Stopień przyciemnieniadiff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex e38325c37..2ff458f7d 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -2750,6 +2750,21 @@ cameraRaw Whites BrancosDomed AbauladoDomed (Inverted) Abaulado (invertido)Diagonal (Descending) Diagonal (descendente)+ Contour Editor Editor de contorno+ Anti-aliased Suavizado+ Corner Canto+ Gloss Contour Contorno de brilho+ Contour Contorno+ Cone - Inverted Cone - invertido+ Cove - Deep Enseada - profunda+ Cove - Shallow Enseada - rasa+ Gaussian Gaussiana+ Half Round Meio-círculo+ Ring Anel+ Ring - Double Anel - duplo+ Rolling Slope - Descending Declive ondulado - descendente+ Rounded Steps Degraus arredondados+ Sawtooth 1 Dente de serra 1Red Eye Tool Ferramenta Olhos vermelhosPupil Size Tamanho da pupiladiff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 905c0b417..35bf03100 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -2590,6 +2590,21 @@ cameraRaw Roughness НеровностьDomed КуполDomed (Inverted) Купол (инвертированный)Diagonal (Descending) Диагональ (нисходящая)+ Contour Editor Редактор контура+ Anti-aliased Сглаживание+ Corner Угол+ Gloss Contour Контур глянца+ Contour Контур+ Cone - Inverted Конус - инвертированный+ Cove - Deep Бухта - глубокая+ Cove - Shallow Бухта - мелкая+ Gaussian Гауссова+ Half Round Полукруг+ Ring Кольцо+ Ring - Double Кольцо - двойное+ Rolling Slope - Descending Волнистый склон - нисходящий+ Rounded Steps Скруглённые ступени+ Sawtooth 1 Пила 1Linear ЛинейныйRed Eye Tool Инструмент «Красные глаза»diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex 4cb207ecc..4d00a1903 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -2563,6 +2563,19 @@ cameraRaw Roughness ШорсткістьDomed КуполDomed (Inverted) Купол (інвертований)Diagonal (Descending) Діагональ (спадна)+ Contour Editor Редактор контуру+ Anti-aliased Згладжування+ Corner Кут+ Gloss Contour Контур глянцю+ Contour Контур+ Cone - Inverted Конус - інвертований+ Cove - Deep Бухта - глибока+ Cove - Shallow Бухта - мілка+ Half Round Півколо+ Ring - Double Кільце - подвійне+ Rolling Slope - Descending Хвилястий схил - низхідний+ Rounded Steps Заокруглені сходинки+ Sawtooth 1 Пилка 1Linear ЛінійнийRed Eye Tool Інструмент «Червоні очі»diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex f4156cbdc..c5432d7f4 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2329,6 +2329,21 @@ cameraRaw Blending 混合Domed 圆顶Domed (Inverted) 圆顶(反转)Diagonal (Descending) 对角线(下降)+ Contour Editor 等高线编辑器+ Anti-aliased 消除锯齿+ Corner 角点+ Gloss Contour 光泽等高线+ Contour 等高线+ Cone - Inverted 锥形 - 反转+ Cove - Deep 凹槽 - 深+ Cove - Shallow 凹槽 - 浅+ Gaussian 高斯+ Half Round 半圆+ Ring 环形+ Ring - Double 环形 - 双+ Rolling Slope - Descending 滚动斜坡 - 递减+ Rounded Steps 圆角梯形+ Sawtooth 1 锯齿 1Red Eye Tool 红眼工具Red Eye 红眼diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex 9ce516bf9..d483af7c4 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2299,6 +2299,21 @@ cameraRaw Blending 混合Domed 圓頂Domed (Inverted) 圓頂(反轉)Diagonal (Descending) 對角線(下降)+ Contour Editor 輪廓編輯器+ Anti-aliased 消除鋸齒+ Corner 角點+ Gloss Contour 光澤輪廓+ Contour 輪廓+ Cone - Inverted 錐形 - 反轉+ Cove - Deep 凹槽 - 深+ Cove - Shallow 凹槽 - 淺+ Gaussian 高斯+ Half Round 半圓+ Ring 環形+ Ring - Double 環形 - 雙+ Rolling Slope - Descending 滾動斜坡 - 遞減+ Rounded Steps 圓角梯形+ Sawtooth 1 鋸齒 1Red Eye Tool 紅眼工具Red Eye 紅眼diff --git a/crates/ui-egui/src/layer_style.rs b/crates/ui-egui/src/layer_style.rsindex b934b3d3e..775e33ae6 100644--- a/crates/ui-egui/src/layer_style.rs+++ b/crates/ui-egui/src/layer_style.rs@@ -22,6 +22,7 @@ use crate::theme::Tokens;use crate::{PhotocraftApp, widgets};pub(crate) mod color_picker;+mod contour;#[derive(Clone, Copy)]enum P {@@ -33,6 +34,9 @@ enum P {Angle,/// A pattern from the dialog's `patternList` field (`[[id, name], …]`).Pattern,+ /// A contour (thumbnail, preset picker, Contour Editor), with the key of its Anti-aliased+ /// checkbox when the effect has one.+ Contour(Option<&'static str>),}/// Effect kinds in Photoshop's list order: (command kind, label, params).@@ -84,15 +88,7 @@ fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] {const BSTYLE: &[(&str, &str)] = &[("inner", "Inner Bevel"), ("outer", "Outer Bevel"), ("emboss", "Emboss"), ("pillow", "Pillow Emboss")];const DIR: &[(&str, &str)] = &[("up", "Up"), ("down", "Down")];const SRC: &[(&str, &str)] = &[("edge", "Edge"), ("center", "Center")];- // The built-in contour presets (photocraft_engine::layer_style::CONTOURS).- const CONTOUR: &[(&str, &str)] = &[- ("Linear", "Linear"),- ("Cone", "Cone"),- ("Cone (Inverted)", "Cone (Inverted)"),- ("Domed", "Domed"),- ("Domed (Inverted)", "Domed (Inverted)"),- ("Diagonal (Descending)", "Diagonal (Descending)"),- ];+ const CONTOUR: P = P::Contour(Some("antiAlias"));match kind {"dropShadow" => &[("blend", "Blend Mode", P::Blend),@@ -103,7 +99,7 @@ fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] {("distance", "Distance", P::Slider(0.0, 300.0, "px")),("spread", "Spread", P::Slider(0.0, 100.0, "%")),("size", "Size", P::Slider(0.0, 250.0, "px")),- ("contour", "Contour", P::Choice(CONTOUR)),+ ("contour", "Contour", CONTOUR),("noise", "Noise", P::Slider(0.0, 100.0, "%")),("knocksOut", "Layer Knocks Out Drop Shadow", P::Check),],@@ -116,7 +112,7 @@ fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] {("distance", "Distance", P::Slider(0.0, 300.0, "px")),("choke", "Choke", P::Slider(0.0, 100.0, "%")),("size", "Size", P::Slider(0.0, 250.0, "px")),- ("contour", "Contour", P::Choice(CONTOUR)),+ ("contour", "Contour", CONTOUR),("noise", "Noise", P::Slider(0.0, 100.0, "%")),],"outerGlow" => &[@@ -126,7 +122,7 @@ fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] {("spread", "Spread", P::Slider(0.0, 100.0, "%")),("size", "Size", P::Slider(0.0, 250.0, "px")),("range", "Range", P::Slider(1.0, 100.0, "%")),- ("contour", "Contour", P::Choice(CONTOUR)),+ ("contour", "Contour", CONTOUR),("noise", "Noise", P::Slider(0.0, 100.0, "%")),],"innerGlow" => &[@@ -136,7 +132,7 @@ fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] {("source", "Source", P::Choice(SRC)),("choke", "Choke", P::Slider(0.0, 100.0, "%")),("size", "Size", P::Slider(0.0, 250.0, "px")),- ("contour", "Contour", P::Choice(CONTOUR)),+ ("contour", "Contour", CONTOUR),("noise", "Noise", P::Slider(0.0, 100.0, "%")),],"stroke" => &[@@ -174,6 +170,11 @@ fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] {("angle", "Angle", P::Angle),("useGlobalLight", "Use Global Light", P::Check),("altitude", "Altitude", P::Slider(0.0, 90.0, "°")),+ ("glossContour", "Gloss Contour", P::Contour(None)),+ // Bevel & Emboss › Contour element.+ ("contour", "Contour", P::Check),+ ("contourName", "", P::Contour(Some("contourAntiAlias"))),+ ("contourRange", "Range", P::Slider(1.0, 100.0, "%")),],"satin" => &[("blend", "Blend Mode", P::Blend),@@ -182,6 +183,7 @@ fn spec(kind: &str) -> &'static [(&'static str, &'static str, P)] {("angle", "Angle", P::Angle),("distance", "Distance", P::Slider(0.0, 250.0, "px")),("size", "Size", P::Slider(0.0, 250.0, "px")),+ ("contour", "Contour", CONTOUR),("invert", "Invert", P::Check),],BLENDING => &[@@ -225,6 +227,7 @@ fn values_of(e: &Effect, light: f32) -> Value {set(&mut v, if matches!(e, Effect::DropShadow(_)) { "spread" } else { "choke" }, json!((s.spread * 100.0).round()));set(&mut v, "size", json!(s.size));set(&mut v, "contour", photocraft_engine::layer_style::contour_param(&s.contour));+ set(&mut v, "antiAlias", json!(s.anti_alias));set(&mut v, "noise", json!((s.noise * 100.0).round()));if matches!(e, Effect::DropShadow(_)) {set(&mut v, "knocksOut", json!(s.knocks_out));@@ -242,6 +245,7 @@ fn values_of(e: &Effect, light: f32) -> Value {set(&mut v, "size", json!(g.size));set(&mut v, "range", json!((g.range * 100.0).round()));set(&mut v, "contour", photocraft_engine::layer_style::contour_param(&g.contour));+ set(&mut v, "antiAlias", json!(g.anti_alias));set(&mut v, "noise", json!((g.noise * 100.0).round()));}Effect::Stroke(s) => {@@ -315,6 +319,7 @@ fn values_of(e: &Effect, light: f32) -> Value {set(&mut v, "size", json!(s.size));set(&mut v, "invert", json!(s.invert));set(&mut v, "contour", photocraft_engine::layer_style::contour_param(&s.contour));+ set(&mut v, "antiAlias", json!(s.anti_alias));}Effect::BevelEmboss(b) => {set(@@ -345,6 +350,12 @@ fn values_of(e: &Effect, light: f32) -> Value {set(&mut v, "altitude", json!(b.altitude));set(&mut v, "direction", json!(if b.up { "up" } else { "down" }));set(&mut v, "glossContour", photocraft_engine::layer_style::contour_param(&b.gloss_contour));+ set(&mut v, "contour", json!(b.contour.is_some()));+ if let Some(c) = &b.contour {+ set(&mut v, "contourName", photocraft_engine::layer_style::contour_param(&c.contour));+ set(&mut v, "contourRange", json!((c.range * 100.0).round()));+ set(&mut v, "contourAntiAlias", json!(c.anti_alias));+ }}}v@@ -976,6 +987,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu}});}+ P::Contour(aa) => contour::row(ui, f, &selected, key, label, aa, &mut disp),P::Check => {let mut b = disp.get(key).and_then(Value::as_bool).unwrap_or(false);if widgets::checkbox(ui, &mut b, label).changed() {@@ -1015,6 +1027,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valuif new_style {save_new_style(app, f);}+ contour::editor(app, ui, f);}/// Colour channel names of a document mode, as Blending Options lists them (Channels, Blend If).@@ -1706,6 +1719,44 @@ mod tests {assert_eq!(blend_quad(Some(&json!(["x", null]))), [0, 0, 255, 255]);}+ #[test]+ fn contour_picker_and_editor_edit_the_effect_curve() {+ let mut s = session();+ s.execute("layer.layerStyle.dropShadow", json!({})).unwrap();+ let shadow = |s: &photocraft_engine::Session| {+ let d = s.active().unwrap();+ match &d.doc.layer(d.active_layer.unwrap()).unwrap().effects.items[0] {+ Effect::DropShadow(sh) => sh.contour.clone(),+ e => panic!("{e:?}"),+ }+ };+ let st = s.active().unwrap();+ let mut f = initial_fields(st.doc.layer(st.active_layer.unwrap()).unwrap(), None, 120.0);+ // The picker: Cone.+ contour::pick(&mut f, "fx1", "contour", "Cone");+ apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap();+ assert_eq!(shadow(&s), photocraft_engine::layer_style::builtin_contour("Cone").unwrap());++ // The Contour Editor: drag the peak to 40 % / 80 %, make the first point a corner.+ contour::open_editor(&mut f, "fx1", "contour");+ assert!(contour::set_point(&mut f, 1, 40.0, 80.0));+ assert!(contour::set_corner(&mut f, 0, true));+ assert!(!contour::set_point(&mut f, 9, 10.0, 10.0), "no such point");+ contour::close_editor(&mut f, true);+ apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap();+ let photocraft_doc::Contour::Custom { name, points, corners } = shadow(&s) else { panic!() };+ assert_eq!(name, "Custom", "an edited preset is no longer called Cone");+ assert!((points[1].input - 102.0 / 255.0).abs() < 1e-6 && (points[1].output - 204.0 / 255.0).abs() < 1e-6, "{points:?}");+ assert_eq!(corners, vec![true, true, false]);++ // Cancel restores the curve the editor opened with.+ let before = f.clone();+ contour::open_editor(&mut f, "fx1", "contour");+ contour::set_point(&mut f, 1, 10.0, 10.0);+ contour::close_editor(&mut f, false);+ assert_eq!(f, before);+ }+#[test]fn percent_fields_round_trip_through_the_engine() {let mut s = session();diff --git a/crates/ui-egui/src/layer_style/contour.rs b/crates/ui-egui/src/layer_style/contour.rsnew file mode 100644index 000000000..2f43c676c--- /dev/null+++ b/crates/ui-egui/src/layer_style/contour.rs@@ -0,0 +1,406 @@+//! Layer Style contours: the Contour row (thumbnail, preset picker, Anti-aliased) and the+//! Contour Editor. Everything edits the dialog's pending effect params, so the live preview+//! follows and OK applies it in the dialog's one `layer.layerStyle.replace`.+//!+//! Editor state lives in the dialog fields, so automation can drive it:+//! - `contourPicker`: `{effect, key}` while a preset picker is open.+//! - `contourEditor`: `{effect, key, original}` while the Contour Editor is open; `original` is+//! the param Cancel restores.++use egui::{Color32, Pos2, Rect, RichText, Sense, Stroke, StrokeKind, pos2, vec2};+use photocraft_doc::Contour;+use photocraft_doc::adjust::CurvePoint;+use photocraft_engine::layer_style::{CONTOURS, contour_from_param, contour_param, contour_to_shc, contours_from_shc};+use serde_json::{Map, Value, json};++use super::{entry, set_param};+use crate::state::{DialogKind, PointCurveState};+use crate::theme::Tokens;+use crate::{PhotocraftApp, point_curve, widgets};++pub(super) const PICKER: &str = "contourPicker";+pub(super) const EDITOR: &str = "contourEditor";++/// The contour a param names (Linear when it names none we know).+pub(super) fn contour_of(v: Option<&Value>) -> Contour {+ v.and_then(contour_from_param).unwrap_or_default()+}++/// A contour's points (`0..=255` levels, as the shared point editor works) and corner flags.+fn levels_of(c: &Contour) -> (Vec<[f32; 2]>, Vec<bool>) {+ match c {+ Contour::Linear => (vec![[0.0, 0.0], [255.0, 255.0]], vec![false, false]),+ Contour::Custom { points, .. } => {+ (points.iter().map(|p| [p.input * 255.0, p.output * 255.0]).collect(), (0..points.len()).map(|i| c.is_corner(i)).collect())+ }+ }+}++fn lut_of(c: &Contour) -> Vec<f32> {+ match c {+ Contour::Linear => (0..64).map(|i| i as f32 / 63.0).collect(),+ Contour::Custom { points, corners, .. } => photocraft_compose::adjust::contour_curve_lut(points, corners),+ }+}++fn sample(l: &[f32], x: f32) -> f32 {+ let i = (x.clamp(0.0, 1.0) * l.len().saturating_sub(1) as f32).round() as usize;+ l.get(i).copied().unwrap_or(0.0)+}++/// Draws `c` into `r` (field background, the curve, a border).+pub(super) fn draw(p: &egui::Painter, r: Rect, c: &Contour, line: Color32, t: &Tokens) {+ p.rect_filled(r, 0.0, t.field);+ let inner = r.shrink(2.0);+ let l = lut_of(c);+ let n = (inner.width() as usize).clamp(8, 512);+ let pts: Vec<Pos2> = (0..=n)+ .map(|k| {+ let x = k as f32 / n as f32;+ pos2(inner.left() + x * inner.width(), inner.bottom() - sample(&l, x) * inner.height())+ })+ .collect();+ p.add(egui::Shape::line(pts, Stroke::new(1.2, line)));+ p.rect_stroke(r, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);+}++fn picker_target(effect: &str, key: &str) -> Value {+ json!({"effect": effect, "key": key})+}++/// Picks a preset for `effect`'s `key` (the picker's click).+pub(super) fn pick(f: &mut Map<String, Value>, effect: &str, key: &str, name: &str) {+ set_param(f, effect, key, json!(name));+ f.remove(PICKER);+}++/// The Contour row of an effect page: label, thumbnail (opens the Contour Editor), the preset+/// picker arrow and, when the effect has one, Anti-aliased.+pub(super) fn row(ui: &mut egui::Ui, f: &mut Map<String, Value>, effect: &str, key: &str, label: &str, aa_key: Option<&str>, disp: &mut Value) {+ let t = Tokens::get(ui.ctx());+ ui.horizontal(|ui| {+ if label.is_empty() {+ ui.add_space(16.0);+ } else {+ ui.label(RichText::new(tl!(label)).color(t.text_dim));+ }+ let c = contour_of(disp.get(key));+ let (r, thumb) = ui.allocate_exact_size(vec2(36.0, 36.0), Sense::click());+ draw(ui.painter(), r, &c, t.text, &t);+ if thumb.hovered() {+ ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.accent), StrokeKind::Outside);+ }+ if thumb.on_hover_text(tl!("Contour Editor")).clicked() {+ open_editor(f, effect, key);+ }+ let (ar, arrow) = ui.allocate_exact_size(vec2(14.0, 36.0), Sense::click());+ let (cx, s) = (ar.center(), 3.2);+ let col = if arrow.hovered() { t.text } else { t.text_dim };+ ui.painter().line_segment([cx + vec2(-s, -s * 0.5), cx + vec2(0.0, s * 0.5)], Stroke::new(1.3, col));+ ui.painter().line_segment([cx + vec2(0.0, s * 0.5), cx + vec2(s, -s * 0.5)], Stroke::new(1.3, col));+ let target = picker_target(effect, key);+ let was = f.get(PICKER) == Some(&target);+ let mut open = was;+ if arrow.clicked() {+ open = !open;+ }+ let mut chosen: Option<&str> = None;+ egui::Popup::from_response(&arrow).open_bool(&mut open).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {+ ui.spacing_mut().item_spacing = vec2(4.0, 4.0);+ egui::Grid::new(("contour-presets", effect, key)).spacing(vec2(4.0, 4.0)).show(ui, |ui| {+ for (i, (name, _)) in CONTOURS.iter().enumerate() {+ let preset = photocraft_engine::layer_style::builtin_contour(name).unwrap_or_default();+ let (r, resp) = ui.allocate_exact_size(vec2(40.0, 40.0), Sense::click());+ draw(ui.painter(), r, &preset, t.text, &t);+ if preset == c || resp.hovered() {+ ui.painter().rect_stroke(r, 0.0, Stroke::new(1.5, t.accent), StrokeKind::Outside);+ }+ if resp.on_hover_text(tl!(name)).clicked() {+ chosen = Some(name);+ }+ if i % 4 == 3 {+ ui.end_row();+ }+ }+ });+ });+ if let Some(name) = chosen {+ disp[key] = json!(name);+ pick(f, effect, key, name);+ } else if open != was {+ if open {+ f.insert(PICKER.into(), target);+ } else {+ f.remove(PICKER);+ }+ }+ if let Some(aa_key) = aa_key {+ let mut on = disp.get(aa_key).and_then(Value::as_bool).unwrap_or(false);+ if widgets::checkbox(ui, &mut on, tl!("Anti-aliased")).changed() {+ disp[aa_key] = json!(on);+ set_param(f, effect, aa_key, json!(on));+ }+ }+ });+}++/// Opens the Contour Editor on `effect`'s `key`, remembering the param Cancel restores.+pub(super) fn open_editor(f: &mut Map<String, Value>, effect: &str, key: &str) {+ let original = current_param(f, effect, key);+ f.remove(PICKER);+ f.insert(EDITOR.into(), json!({"effect": effect, "key": key, "original": original}));+}++fn current_param(f: &Map<String, Value>, effect: &str, key: &str) -> Value {+ entry(f, effect)+ .and_then(|e| e.get("params"))+ .and_then(|p| p.get(key))+ .cloned()+ .or_else(|| entry(f, effect).and_then(|e| e.get("kind")).and_then(Value::as_str).and_then(|k| super::defaults(k).get(key).cloned()))+ .unwrap_or_else(|| json!("Linear"))+}++fn editor_target(f: &Map<String, Value>) -> Option<(String, String)> {+ let ed = f.get(EDITOR)?;+ let effect = ed.get("effect")?.as_str()?.to_string();+ let key = ed.get("key")?.as_str()?.to_string();+ entry(f, &effect)?;+ Some((effect, key))+}++/// The edited curve: its points (`0..=255`), corner flags and name.+fn editor_curve(f: &Map<String, Value>) -> Option<(String, String, Contour)> {+ let (effect, key) = editor_target(f)?;+ let c = contour_of(Some(¤t_param(f, &effect, &key)));+ Some((effect, key, c))+}++/// Stores an edited curve on the effect. Editing a built-in preset makes a "Custom" contour, so a+/// saved file doesn't call the edited curve by the preset's name.+fn store(f: &mut Map<String, Value>, effect: &str, key: &str, name: &str, pts: &[[f32; 2]], corners: &[bool]) -> bool {+ let name = if name.is_empty() || photocraft_engine::layer_style::builtin_contour(name).is_some() { "Custom" } else { name };+ let v = json!({+ "name": name,+ "points": pts.iter().map(|q| json!([q[0] / 255.0, q[1] / 255.0])).collect::<Vec<_>>(),+ "corners": corners,+ });+ let Some(c) = contour_from_param(&v) else { return false };+ set_param(f, effect, key, contour_param(&c));+ true+}++fn name_of(c: &Contour) -> &str {+ match c {+ Contour::Linear => "Linear",+ Contour::Custom { name, .. } => name,+ }+}++/// Contour Editor › Input/Output: moves point `i` to `input`/`output` percent.+pub(super) fn set_point(f: &mut Map<String, Value>, i: usize, input: f32, output: f32) -> bool {+ let Some((effect, key, c)) = editor_curve(f) else { return false };+ let (mut pts, corners) = levels_of(&c);+ point_curve::move_to(&mut pts, i, [input * 2.55, output * 2.55]) && store(f, &effect, &key, name_of(&c), &pts, &corners)+}++/// Contour Editor › Corner: whether point `i` is a corner.+pub(super) fn set_corner(f: &mut Map<String, Value>, i: usize, on: bool) -> bool {+ let Some((effect, key, c)) = editor_curve(f) else { return false };+ let (pts, mut corners) = levels_of(&c);+ let Some(flag) = corners.get_mut(i) else { return false };+ if *flag == on {+ return false;+ }+ *flag = on;+ store(f, &effect, &key, name_of(&c), &pts, &corners)+}++/// Closes the Contour Editor: OK keeps the edited curve, Cancel restores the original.+pub(super) fn close_editor(f: &mut Map<String, Value>, keep: bool) {+ if !keep+ && let Some((effect, key)) = editor_target(f)+ && let Some(original) = f.get(EDITOR).and_then(|e| e.get("original")).cloned()+ {+ set_param(f, &effect, &key, original);+ }+ f.remove(EDITOR);+}++/// Corner flags after the shared point editor added or removed a point: the flags follow their+/// points; a new point is smooth.+fn follow_corners(before: &[[f32; 2]], after: &[[f32; 2]], corners: &mut Vec<bool>) {+ let first_diff = |a: &[[f32; 2]], b: &[[f32; 2]]| (0..a.len()).find(|&i| a.get(i) != b.get(i)).unwrap_or(a.len());+ if after.len() == before.len() + 1 {+ let i = first_diff(after, before).min(corners.len());+ corners.insert(i, false);+ } else if after.len() + 1 == before.len() {+ let i = first_diff(before, after);+ if i < corners.len() {+ corners.remove(i);+ }+ }+ corners.resize(after.len(), false);+}++/// The Contour Editor (a modal over the Layer Style dialog), when one is open.+pub(super) fn editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>) {+ if !f.contains_key(EDITOR) {+ return;+ }+ let Some((effect, key, c)) = editor_curve(f) else {+ f.remove(EDITOR);+ return;+ };+ let t = Tokens::get(ui.ctx());+ let ctx = ui.ctx().clone();+ let mem = egui::Id::new(("contour-editor", effect.as_str(), key.as_str()));+ let mut st: PointCurveState = ctx.data(|d| d.get_temp(mem)).unwrap_or_default();+ let (mut pts, mut corners) = levels_of(&c);+ let mut close: Option<bool> = None;+ let mut load = false;+ let mut save = false;+ let mut preset: Option<String> = None;+ let modal = egui::Modal::new(mem.with("modal")).show(&ctx, |ui| {+ ui.label(RichText::new(tl!("Contour Editor")).font(crate::theme::semibold(14.0)).color(t.text));+ ui.add_space(6.0);+ ui.horizontal_top(|ui| {+ ui.vertical(|ui| {+ ui.horizontal(|ui| {+ ui.label(RichText::new(tl!("Preset:")).color(t.text_dim));+ let mut cur = name_of(&c).to_string();+ let opts: Vec<(String, &str)> = CONTOURS.iter().map(|(n, _)| (n.to_string(), *n)).collect();+ if widgets::dropdown(ui, "contour-editor-preset", &mut cur, &opts, 190.0) {+ preset = Some(cur);+ }+ });+ ui.add_space(6.0);+ let side = 220.0;+ let (graph, resp) = ui.allocate_exact_size(vec2(side, side), Sense::click_and_drag());+ let before = pts.clone();+ let it = point_curve::interact(ui, &resp, graph, &mut pts, &mut st);+ if it.changed {+ follow_corners(&before, &pts, &mut corners);+ store(f, &effect, &key, name_of(&c), &pts, &corners);+ }+ let p = ui.painter_at(graph.expand(4.0));+ p.rect_filled(graph, 0.0, t.field);+ for i in 1..4 {+ let k = i as f32 / 4.0;+ let g = Stroke::new(1.0, t.separator);+ p.line_segment([pos2(graph.left() + k * graph.width(), graph.top()), pos2(graph.left() + k * graph.width(), graph.bottom())], g);+ p.line_segment([pos2(graph.left(), graph.top() + k * graph.height()), pos2(graph.right(), graph.top() + k * graph.height())], g);+ }+ let shown = Contour::Custom {+ name: String::new(),+ points: pts.iter().map(|q| CurvePoint { input: q[0] / 255.0, output: q[1] / 255.0 }).collect(),+ corners: corners.clone(),+ };+ let l = lut_of(&shown);+ let line: Vec<Pos2> = (0..=256)+ .map(|k| {+ let x = k as f32 / 256.0;+ pos2(graph.left() + x * graph.width(), graph.bottom() - sample(&l, x) * graph.height())+ })+ .collect();+ p.add(egui::Shape::line(line, Stroke::new(1.5, t.text)));+ p.rect_stroke(+ graph,+ 0.0,+ Stroke::new(if resp.has_focus() { 1.5 } else { 1.0 }, if resp.has_focus() { t.accent } else { t.field_border }),+ StrokeKind::Outside,+ );+ for (i, q) in pts.iter().enumerate() {+ let at = pos2(graph.left() + q[0] / 255.0 * graph.width(), graph.bottom() - q[1] / 255.0 * graph.height());+ let r = Rect::from_center_size(at, vec2(7.0, 7.0));+ let corner = corners.get(i).copied().unwrap_or(false);+ if Some(i) == st.selected {+ p.rect_filled(r, 0.0, t.text);+ } else {+ p.rect_filled(r, 0.0, t.field);+ p.rect_stroke(r, if corner { 0.0 } else { 3.5 }, Stroke::new(1.0, t.text), StrokeKind::Inside);+ }+ }+ ui.add_space(6.0);+ let sel = st.selected.filter(|i| *i < pts.len());+ ui.horizontal(|ui| {+ let (mut vi, mut vo) = sel.and_then(|i| pts.get(i)).map_or((0.0, 0.0), |q| ((q[0] / 2.55).round(), (q[1] / 2.55).round()));+ ui.label(RichText::new(tl!("Input:")).color(t.text_dim));+ let ri = ui.add_enabled_ui(sel.is_some(), |ui| widgets::value_field(ui, &mut vi, 0.0..=100.0, "%", 52.0)).inner;+ ui.label(RichText::new(tl!("Output:")).color(t.text_dim));+ let ro = ui.add_enabled_ui(sel.is_some(), |ui| widgets::value_field(ui, &mut vo, 0.0..=100.0, "%", 52.0)).inner;+ if let Some(i) = sel+ && (ri.changed() || ro.changed())+ {+ set_point(f, i, vi, vo);+ }+ let mut corner = sel.and_then(|i| corners.get(i)).copied().unwrap_or(false);+ let rc = ui.add_enabled_ui(sel.is_some(), |ui| widgets::checkbox(ui, &mut corner, tl!("Corner"))).inner;+ if let Some(i) = sel+ && rc.changed()+ {+ set_corner(f, i, corner);+ }+ });+ });+ ui.add_space(10.0);+ ui.vertical(|ui| {+ if widgets::primary_button(ui, tl!("OK"), 84.0).clicked() {+ close = Some(true);+ }+ ui.add_space(4.0);+ if widgets::secondary_button(ui, tl!("Cancel"), 84.0).clicked() {+ close = Some(false);+ }+ ui.add_space(12.0);+ load = widgets::secondary_button(ui, tl!("Load…"), 84.0).clicked();+ ui.add_space(4.0);+ save = widgets::secondary_button(ui, tl!("Save…"), 84.0).clicked();+ });+ });+ });+ ctx.data_mut(|d| d.insert_temp(mem, st));+ if let Some(name) = preset {+ set_param(f, &effect, &key, json!(name));+ }+ if close.is_none() && modal.should_close() {+ close = Some(false);+ }+ if close.is_none() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) {+ close = Some(true);+ }+ if let Some(keep) = close {+ close_editor(f, keep);+ return;+ }+ if load {+ let r = app.pick_file_bytes_filtered(&["shc"], |app, name, bytes| {+ let list = contours_from_shc(&bytes).map_err(|e| format!("{}: {e}", crate::file_open::display_name(&name)))?;+ let first = list.into_iter().next().ok_or_else(|| format!("{}: no contours", crate::file_open::display_name(&name)))?;+ let d = app.ui.dialogs.iter_mut().find(|d| d.kind == DialogKind::LayerStyle && d.fields.contains_key(EDITOR)).ok_or("the Contour Editor closed")?;+ let (effect, key) = editor_target(&d.fields).ok_or("the Contour Editor closed")?;+ set_param(&mut d.fields, &effect, &key, first);+ Ok(Value::Null)+ });+ report(app, r);+ }+ if save {+ let r = contour_to_shc(&c).map_err(|e| e.to_string()).and_then(|bytes| {+ let file = format!("{}.shc", name_of(&c));+ app.pick_save(&file, move |app, path| {+ let write = app.services.write.as_mut().ok_or("no writer configured")?;+ write(&path, &bytes)?;+ Ok(json!({"path": path}))+ })+ });+ report(app, r);+ }+}++fn report(app: &mut PhotocraftApp, r: Result<Value, String>) {+ if let Err(e) = r+ && e != crate::file_dialog::CANCELLED+ {+ app.ui.status_error = true;+ app.ui.status = e;+ }+}diff --git a/docs/scorecard.md b/docs/scorecard.mdindex 8a2a062c1..300f06739 100644--- a/docs/scorecard.md+++ b/docs/scorecard.md@@ -7,7 +7,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js| Area | Done | Partial | Missing | Key numbers ||---|---:|---:|---:|---|| [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) |-| [File compatibility](#file-compatibility) | 6 | 11 | 10 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 |+| [File compatibility](#file-compatibility) | 6 | 12 | 9 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 || [Tools](#tools) | 25 | 16 | 2 | || [Workspace and UI](#workspace-and-ui) | 8 | 8 | 7 | settings that do nothing: 34 of 153 (target 0) || [Type](#type) | 1 | 4 | 4 | |@@ -112,7 +112,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t| FILE-215-12 | Camera Raw dialog shows a histogram; settings persist as a PSD Smart Filter | partial | [#215](https://github.com/storytold/photocraft/issues/215) | Interactive RGB/Lab scopes. PSD WB/Light/Presence, curves, HSL, grading, sharpening/noise detail, grain and numeric vignette controls mapped with descriptor preservation. Active manual Optics and unverified vignette style keep the updated ACR 18.4 fixture opaque; PSD/.pcraft saves preserve it. HDR, remaining settings and Photoshop acceptance still open || FILE-215-13 | Video layer frames persist in .pcraft; PSD video layers mapped | partial | [#215](https://github.com/storytold/photocraft/issues/215) | format convert.rs:89 + tests/roundtrip.rs:282 persist frames; no PSD video mapping || FILE-215-14 | User swatch model with ACO/ASE import and export | done | [#215](https://github.com/storytold/photocraft/issues/215) | engine presets/swatches.rs (RGB/HSB/CMYK/Lab/Gray + verbatim colour books, persisted in prefs) + swatch_cmds.rs (swatches.*); psd aco.rs (v1/v2) and ase.rs (groups, spot/global) read+write; ui swatches_ui.rs, Color Picker Add to Swatches |-| FILE-215-15 | Layer Style contour picker, curve editor, presets, .shc import/export | missing | [#215](https://github.com/storytold/photocraft/issues/215) | doc effects.rs:57 Contour model only |+| FILE-215-15 | Layer Style contour picker, curve editor, presets, .shc import/export | partial | [#2912](https://github.com/storytold/photocraft/issues/2912) | Layer Style dialog: contour thumbnail + preset picker (12 standard shapes, own control points) and Anti-aliased on Drop/Inner Shadow, Outer/Inner Glow, Satin, Bevel Gloss Contour and Contour element; Contour Editor (add/drag/delete, Corner, Input/Output, Preset, Load…/Save… .shc per Adobe's public spec, psd shc.rs); corner points render (compose contour_curve_lut) and map to PSD Cnty. Missing: a user contour library (New…, picker Load/Save/Replace Contours), Anti-aliased doesn't change the render yet, .shc not yet checked against a Photoshop-written file || FILE-215-16 | Advanced Blending (knockout, blend as group, mask hides effects) end to end | partial | [#215](https://github.com/storytold/photocraft/issues/215) | doc advanced.rs + .pcraft + PSD/layered TIFF (knko infx clbl tsly lmgm vmgm), CPU compose advanced.rs (GPU falls back), blendingOptions command + dialog; 7 psd-tools knockout oracles now pass; knockout-isolated-groups (0.45 % AA edges), advanced-blending, blend-and-clipping still differ || FILE-215-17 | CMYK/RGB documents preview spot inks; spot plates export (TIFF extra samples, PDF) | missing | [#215](https://github.com/storytold/photocraft/issues/215) | compose multichannel.rs:1 spot preview for Multichannel only || FILE-215-18 | Save for Web per-slice settings remembered; Export As remembers and offers nearest scaling | partial | [#215](https://github.com/storytold/photocraft/issues/215) | file_ui.rs:188 last_web in-session only; export_dialog.rs:16 fixed defaults |diff --git a/scorecard/file_compat.toml b/scorecard/file_compat.tomlindex 42cc76e48..48314a2c4 100644--- a/scorecard/file_compat.toml+++ b/scorecard/file_compat.toml@@ -106,9 +106,9 @@ note = "engine presets/swatches.rs (RGB/HSB/CMYK/Lab/Gray + verbatim colour book[[item]]id = "FILE-215-15"target = "Layer Style contour picker, curve editor, presets, .shc import/export"-status = "missing"-issue = 215-note = "doc effects.rs:57 Contour model only"+status = "partial"+issue = 2912+note = "Layer Style dialog: contour thumbnail + preset picker (12 standard shapes, own control points) and Anti-aliased on Drop/Inner Shadow, Outer/Inner Glow, Satin, Bevel Gloss Contour and Contour element; Contour Editor (add/drag/delete, Corner, Input/Output, Preset, Load…/Save… .shc per Adobe's public spec, psd shc.rs); corner points render (compose contour_curve_lut) and map to PSD Cnty. Missing: a user contour library (New…, picker Load/Save/Replace Contours), Anti-aliased doesn't change the render yet, .shc not yet checked against a Photoshop-written file"[[item]]id = "FILE-215-16"