PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Curves: pencil mode, Smooth and Edit points (#3088) (#3108)
Valentin Kleinaba9b2b4efd9
diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rsindex 80c971e7a..641a983f6 100644--- a/crates/compose/src/adjust.rs+++ b/crates/compose/src/adjust.rs@@ -276,9 +276,9 @@ pub fn tone_luts_q(adj: &Adjustment, quantum: Option<f32>) -> [Vec<f32>; 4] {let row = |c: &LevelsChannel| (0..LUT_SIZE).map(|k| levels_q(m, levels_q(c, x(k), quantum), quantum)).collect();[row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), row(if *space == ToneSpace::Cmyk { black } else { &ident })]}- Adjustment::Curves { master, per_channel, space, black } => {- let m = if *space == ToneSpace::Lab { curve_lut(&[]) } else { curve_lut(master) };- let row = |c: &[CurvePoint]| curve_lut(c).iter().map(|&v| lut(&m, v)).collect();+ Adjustment::Curves { master, per_channel, space, black, pencil } => {+ let m = if *space == ToneSpace::Lab { curve_lut(&[]) } else { curve_lut_mode(master, *pencil) };+ let row = |c: &[CurvePoint]| curve_lut_mode(c, *pencil).iter().map(|&v| lut(&m, v)).collect();[row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), row(if *space == ToneSpace::Cmyk { black } else { &[] })]}_ => std::array::from_fn(|_| (0..LUT_SIZE).map(x).collect()),@@ -688,6 +688,39 @@ pub fn levels_float(ch: &LevelsChannel, v: f32) -> f32 {ch.out_black + t * (ch.out_white - ch.out_black)}+/// The LUT of one Curves curve: [`curve_map_lut`] for a pencil-drawn map, else [`curve_lut`].+pub fn curve_lut_mode(points: &[CurvePoint], pencil: bool) -> Vec<f32> {+ if pencil { curve_map_lut(points) } else { curve_lut(points) }+}++/// A pencil-drawn Curves map (see [`photocraft_doc::adjust::curve_map`]): straight segments+/// between its entries, constant outside the first/last, clamped to 0..=1, sampled into a LUT.+pub fn curve_map_lut(points: &[CurvePoint]) -> Vec<f32> {+ let mut pts: Vec<(f32, f32)> = points.iter().filter(|p| p.input.is_finite() && p.output.is_finite()).map(|p| (p.input, p.output)).collect();+ pts.sort_by(|a, b| a.0.total_cmp(&b.0));+ pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6);+ let ident = |k: usize| k as f32 / (LUT_SIZE - 1) as f32;+ let (Some(&first), Some(&last)) = (pts.first(), pts.last()) else { return (0..LUT_SIZE).map(ident).collect() };+ let mut seg = 0;+ (0..LUT_SIZE)+ .map(|k| {+ let xv = ident(k);+ if xv <= first.0 {+ return first.1.clamp(0.0, 1.0);+ }+ if xv >= last.0 {+ return last.1.clamp(0.0, 1.0);+ }+ while pts.get(seg + 1).is_some_and(|p| p.0 < xv) {+ seg += 1;+ }+ let (Some(&(x0, y0)), Some(&(x1, y1))) = (pts.get(seg), pts.get(seg + 1)) else { return last.1.clamp(0.0, 1.0) };+ let t = if x1 > x0 { (xv - x0) / (x1 - x0) } else { 0.0 };+ (y0 + (y1 - y0) * t).clamp(0.0, 1.0)+ })+ .collect()+}+/// Photoshop curve: a natural cubic spline through the points (it may/// overshoot between points, as Photoshop's does), constant outside the/// first/last point, clamped to 0..=1, sampled into a LUT.@@ -946,8 +979,13 @@ mod tone_tests {space: ToneSpace::Rgb,black: Default::default(),};- let curves =- Adjustment::Curves { master: line(0.0, 0.5), per_channel: std::array::from_fn(|_| line(0.5, 1.0)), space: ToneSpace::Rgb, black: Vec::new() };+ let curves = Adjustment::Curves {+ master: line(0.0, 0.5),+ per_channel: std::array::from_fn(|_| line(0.5, 1.0)),+ space: ToneSpace::Rgb,+ black: Vec::new(),+ pencil: false,+ };for depth in [None, Some(SampleType::U8), Some(SampleType::U16), Some(SampleType::F32)] {let ll = tone_luts_depth(&levels, depth);let cl = tone_luts_depth(&curves, depth);@@ -1012,6 +1050,7 @@ mod tone_tests {per_channel: [line(0.0, 1.0), line(0.0, 1.0), line(0.0, 1.0)],space: ToneSpace::Cmyk,black: line(0.0, 0.5),+ pencil: false,};let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.8, 0.8, 0.8, 1.0]] };apply(&a, &mut b);@@ -1022,6 +1061,7 @@ mod tone_tests {per_channel: [line(0.2, 1.0), line(0.0, 1.0), line(0.0, 1.0)],space: ToneSpace::Lab,black: Vec::new(),+ pencil: false,};let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.2, 0.2, 0.2, 1.0]] };apply(&a, &mut b);diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rsindex a141f42ff..1bb4afc16 100644--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@ -1587,10 +1587,14 @@ fn float_adjustments_preserve_hdr_range() {per_channel: std::array::from_fn(|_| identity.clone()),space: Default::default(),black: Vec::new(),+ pencil: false,},[4.0, 2.0, 0.5],),- (Adjustment::Curves { master: Vec::new(), per_channel: Default::default(), space: Default::default(), black: Vec::new() }, [4.0, 2.0, 0.5]),+ (+ Adjustment::Curves { master: Vec::new(), per_channel: Default::default(), space: Default::default(), black: Vec::new(), pencil: false },+ [4.0, 2.0, 0.5],+ ),];for (adj, want) in adjustments {let mut d = Document::new("HDR", Size::new(1, 1), ColorMode::Rgb, SampleType::F32);@@ -1615,7 +1619,13 @@ fn float_tone_adjustments_preserve_negative_and_untouched_channels() {[-0.1, 4.0, 0.5],),(- Adjustment::Curves { master: identity.clone(), per_channel: [identity.clone(), Vec::new(), edited], space: Default::default(), black: Vec::new() },+ Adjustment::Curves {+ master: identity.clone(),+ per_channel: [identity.clone(), Vec::new(), edited],+ space: Default::default(),+ black: Vec::new(),+ pencil: false,+ },[-0.1, 4.0, 0.25],),] {diff --git a/crates/doc/src/adjust.rs b/crates/doc/src/adjust.rsindex accf7de9e..855cd1f39 100644--- a/crates/doc/src/adjust.rs+++ b/crates/doc/src/adjust.rs@@ -17,6 +17,54 @@ pub fn is_identity_curve(points: &[CurvePoint]) -> bool {}}+/// Entries in a pencil-drawn Curves map (one per 8-bit level, as in PSD `curv` maps).+pub const CURVE_MAP_LEN: usize = 256;++/// A pencil-mode curve from its map: `outputs[k]` (0..=1) is the output at input `k / 255`.+/// Missing entries repeat the last one; extra entries are ignored.+pub fn curve_map(outputs: &[f32]) -> Vec<CurvePoint> {+ let last = (CURVE_MAP_LEN - 1) as f32;+ let mut prev = 0.0;+ (0..CURVE_MAP_LEN)+ .map(|k| {+ let out = outputs.get(k).copied().filter(|v| v.is_finite()).map_or(prev, |v| v.clamp(0.0, 1.0));+ prev = out;+ CurvePoint { input: k as f32 / last, output: out }+ })+ .collect()+}++/// The [`CURVE_MAP_LEN`] outputs (0..=1) of `points` read as a pencil-mode curve: straight+/// segments between the points, constant outside the first/last (identity without two points).+pub fn curve_map_outputs(points: &[CurvePoint]) -> Vec<f32> {+ let mut pts: Vec<(f32, f32)> = points.iter().filter(|p| p.input.is_finite() && p.output.is_finite()).map(|p| (p.input, p.output)).collect();+ pts.sort_by(|a, b| a.0.total_cmp(&b.0));+ let last = (CURVE_MAP_LEN - 1) as f32;+ (0..CURVE_MAP_LEN)+ .map(|k| {+ let x = k as f32 / last;+ let y = match (pts.first(), pts.last()) {+ (Some(a), Some(b)) if pts.len() >= 2 => {+ if x <= a.0 {+ a.1+ } else if x >= b.0 {+ b.1+ } else {+ let i = pts.partition_point(|p| p.0 < x);+ match (pts.get(i.wrapping_sub(1)), pts.get(i)) {+ (Some(p0), Some(p1)) if p1.0 > p0.0 => p0.1 + (p1.1 - p0.1) * (x - p0.0) / (p1.0 - p0.0),+ (_, Some(p1)) => p1.1,+ _ => b.1,+ }+ }+ }+ _ => x,+ };+ y.clamp(0.0, 1.0)+ })+ .collect()+}+/// Number of values in the table of a `size`³ Color Lookup (`size³ × 3`). `None` for a size/// below 2 or one whose table length overflows: a stored document's size is untrusted.pub fn lut3d_len(size: u32) -> Option<usize> {@@ -157,6 +205,11 @@ pub enum Adjustment {/// The black ink curve when `space` is [`ToneSpace::Cmyk`] (empty = identity).#[serde(default)]black: Vec<CurvePoint>,+ /// Drawn with the pencil (Photoshop's "Draw to modify the curve", PSD `curv` map form):+ /// every curve is a [`CURVE_MAP_LEN`]-entry map (see [`curve_map`]) evaluated+ /// piecewise-linearly instead of a spline through its points.+ #[serde(default)]+ pencil: bool,},Exposure {exposure: f32,@@ -264,7 +317,7 @@ impl Adjustment {pub fn identity_curves() -> Self {let line = || vec![CurvePoint { input: 0.0, output: 0.0 }, CurvePoint { input: 1.0, output: 1.0 }];- Adjustment::Curves { master: line(), per_channel: [line(), line(), line()], space: ToneSpace::Rgb, black: Vec::new() }+ Adjustment::Curves { master: line(), per_channel: [line(), line(), line()], space: ToneSpace::Rgb, black: Vec::new(), pencil: false }}pub fn identity_levels() -> Self {@@ -300,7 +353,7 @@ mod tests {let a: Adjustment = serde_json::from_str(r#"{"HueSaturation":{"hue":1.0,"saturation":2.0,"lightness":3.0,"colorize":false}}"#).unwrap();assert!(matches!(a, Adjustment::HueSaturation { ranges, .. } if ranges == HueRange::defaults()));let c: Adjustment = serde_json::from_str(r#"{"Curves":{"master":[],"per_channel":[[],[],[]]}}"#).unwrap();- assert!(matches!(c, Adjustment::Curves { space: ToneSpace::Rgb, .. }));+ assert!(matches!(c, Adjustment::Curves { space: ToneSpace::Rgb, pencil: false, .. }));let g: Adjustment = serde_json::from_str(r#"{"GradientMap":{"stops":[],"reverse":true}}"#).unwrap();assert!(matches!(g, Adjustment::GradientMap { dither: false, .. }));}diff --git a/crates/engine/src/adjust_params.rs b/crates/engine/src/adjust_params.rsindex 00fb67dd0..e4459cdfb 100644--- a/crates/engine/src/adjust_params.rs+++ b/crates/engine/src/adjust_params.rs@@ -11,7 +11,7 @@use photocraft_color::ColorMode;use photocraft_doc::Adjustment;-use photocraft_doc::adjust::{CurvePoint, HueRange, LevelsChannel, ToneSpace};+use photocraft_doc::adjust::{CURVE_MAP_LEN, CurvePoint, HueRange, LevelsChannel, ToneSpace, curve_map, curve_map_outputs};use serde_json::{Map, Value, json};use crate::{EngineError, Result};@@ -236,15 +236,19 @@ pub fn to_params(adj: &Adjustment) -> Value {}v}- Adjustment::Curves { master, per_channel, space, black } => {- let mut v = json!({"points": curve_arr(master)});+ Adjustment::Curves { master, per_channel, space, black, pencil } => {+ let arr = |c: &[CurvePoint]| if *pencil { map_arr(c) } else { curve_arr(c) };+ let mut v = json!({"points": arr(master)});let ink = if black.len() >= 2 { black.clone() } else { identity_curve() };let chans = per_channel.iter().cloned().chain(std::iter::once(ink));for (key, c) in channel_keys(*space).iter().zip(chans) {- v[*key] = curve_arr(&c);+ v[*key] = arr(&c);}if *space == ToneSpace::Lab {- v["points"] = curve_arr(&per_channel[0]);+ v["points"] = arr(&per_channel[0]);+ }+ if *pencil {+ v["pencil"] = json!(true);}v}@@ -487,6 +491,80 @@ fn curve_arr(c: &[CurvePoint]) -> Value {/// Most points a curve may have (Photoshop allows 16; the PSD record holds 19).pub const MAX_CURVE_POINTS: usize = 19;+/// Points Photoshop's "Edit points to modify the curve" places on a pencil-drawn curve at most.+const MAX_FITTED_POINTS: usize = 16;++/// Most Smooth passes one `smooth` param applies.+pub const MAX_SMOOTH_PASSES: f32 = 10.0;++/// A pencil-mode curve as params: its [`CURVE_MAP_LEN`] outputs in 0..255.+fn map_arr(c: &[CurvePoint]) -> Value {+ json!(curve_map_outputs(c).iter().map(|o| (o * 255.0 * CURVE_COORDINATE_PRECISION).round() / CURVE_COORDINATE_PRECISION).collect::<Vec<_>>())+}++/// `lut` (evenly spaced over 0..=1) at `x`, linearly interpolated.+fn lut_at(lut: &[f32], x: f32) -> f32 {+ let Some(last) = lut.len().checked_sub(1) else { return x };+ let f = x.clamp(0.0, 1.0) * last as f32;+ let i = (f.floor() as usize).min(last);+ let (a, b) = (lut.get(i).copied().unwrap_or(x), lut.get((i + 1).min(last)).copied().unwrap_or(x));+ a + (b - a) * (f - i as f32)+}++/// A point curve drawn into a pencil-mode map (Photoshop switching to "Draw to modify the curve").+pub fn points_to_map(points: &[CurvePoint]) -> Vec<CurvePoint> {+ let lut = photocraft_compose::adjust::curve_lut(points);+ let last = (CURVE_MAP_LEN - 1) as f32;+ curve_map(&(0..CURVE_MAP_LEN).map(|k| lut_at(&lut, k as f32 / last)).collect::<Vec<_>>())+}++/// A pencil-mode map turned back into a point curve (Photoshop's "Edit points to modify the+/// curve"): the endpoints, then the worst-fitting input until the spline is within one level of+/// the map or [`MAX_FITTED_POINTS`] are placed.+pub fn map_to_points(map: &[CurvePoint]) -> Vec<CurvePoint> {+ let target = curve_map_outputs(map);+ let last = CURVE_MAP_LEN - 1;+ let at = |k: usize| CurvePoint { input: k as f32 / last as f32, output: target.get(k).copied().unwrap_or(0.0) };+ let mut pts = vec![at(0), at(last)];+ while pts.len() < MAX_FITTED_POINTS {+ let lut = photocraft_compose::adjust::curve_lut(&pts);+ let worst = (0..CURVE_MAP_LEN)+ .map(|k| (k, (lut_at(&lut, k as f32 / last as f32) - target.get(k).copied().unwrap_or(0.0)).abs()))+ .max_by(|a, b| a.1.total_cmp(&b.1));+ let Some((k, _)) = worst.filter(|w| w.1 > 1.0 / 255.0) else { break };+ let p = at(k);+ if pts.iter().any(|q| (q.input - p.input).abs() < CURVE_POINT_DUPLICATE_DISTANCE) {+ break;+ }+ pts.push(p);+ pts.sort_by(|a, b| a.input.total_cmp(&b.input));+ }+ pts+}++/// One pass of Curves' Smooth button over pencil-mode outputs (any scale): each value becomes+/// the mean of a symmetric window of up to three neighbours a side, so straight runs and the two+/// endpoints stay put while jagged strokes even out.+pub fn smooth_curve_map(outputs: &mut [f32]) {+ const RADIUS: usize = 3;+ let src = outputs.to_vec();+ let n = src.len();+ for (k, out) in outputs.iter_mut().enumerate() {+ let r = RADIUS.min(k).min(n.saturating_sub(k + 1));+ if r == 0 {+ continue;+ }+ let window = src.get(k - r..=k + r).unwrap_or_default();+ *out = window.iter().sum::<f32>() / window.len().max(1) as f32;+ }+}++/// Whether a pencil-mode curve maps every level to itself.+fn is_identity_map(c: &[CurvePoint]) -> bool {+ let last = (CURVE_MAP_LEN - 1) as f32;+ curve_map_outputs(c).iter().enumerate().all(|(k, o)| (o - k as f32 / last).abs() < 0.5 / 255.0)+}+/// Fixed-target Curves eyedroppers. The UI keeps the sampled operation provisional; this helper/// only resolves a sample into an ordinary Curves adjustment that the existing command can apply.#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -639,7 +717,16 @@ pub fn curves_eyedropper(base: &Value, picker: CurvesEyedropper, sample: [f32; 3if mode == ColorMode::Grayscale && picker == CurvesEyedropper::NeutralGray {return Err(bad("curves eyedropper", "Neutral Gray is unavailable for Grayscale documents"));}- let mut adjustment = from_params("curves", base, None, mode)?;+ // The pickers place points: a pencil-drawn curve is first fitted with points, as when+ // Photoshop leaves the pencil for point editing.+ let mut base = base.clone();+ if let Some(o) = base.as_object_mut() {+ o.remove("smooth");+ if o.get("pencil").and_then(Value::as_bool) == Some(true) {+ o.insert("pencil".into(), json!(false));+ }+ }+ let mut adjustment = from_params("curves", &base, None, mode)?;let Adjustment::Curves { master, per_channel, .. } = &mut adjustment else {return Err(bad("curves eyedropper", "expected a Curves adjustment"));};@@ -738,20 +825,53 @@ pub fn parse_curve(cmd: &str, key: &str, v: &Value) -> Result<Vec<CurvePoint>> {Ok(pts)}+/// A pencil-mode map param: exactly [`CURVE_MAP_LEN`] outputs in 0..255.+fn parse_map(cmd: &str, key: &str, v: &Value) -> Result<Vec<CurvePoint>> {+ let err = || bad(cmd, format!("`{key}` must be {CURVE_MAP_LEN} output levels in 0..255 (a pencil-drawn map) or [input, output] pairs"));+ let a = v.as_array().filter(|a| a.len() == CURVE_MAP_LEN).ok_or_else(err)?;+ let outs =+ a.iter().map(|x| x.as_f64().filter(|x| x.is_finite()).map(|x| (x as f32).clamp(0.0, 255.0) / 255.0)).collect::<Option<Vec<_>>>().ok_or_else(err)?;+ Ok(curve_map(&outs))+}++/// A Curves channel param in the adjustment's mode: `[[in, out], …]` points (drawn into a map in+/// pencil mode) or a [`CURVE_MAP_LEN`]-level map (fitted with points outside pencil mode).+fn parse_curve_in(cmd: &str, key: &str, v: &Value, pencil: bool) -> Result<Vec<CurvePoint>> {+ if v.as_array().and_then(|a| a.first()).is_some_and(Value::is_number) {+ let map = parse_map(cmd, key, v)?;+ Ok(if pencil { map } else { map_to_points(&map) })+ } else {+ let pts = parse_curve(cmd, key, v)?;+ Ok(if pencil { points_to_map(&pts) } else { pts })+ }+}+fn curves(r: &Reader<'_>, base: Option<&Adjustment>, mode: ColorMode) -> Result<Adjustment> {- let (mut master, mut chans, base_space) = match base {- Some(Adjustment::Curves { master, per_channel, space, black }) => {- (master.clone(), [per_channel[0].clone(), per_channel[1].clone(), per_channel[2].clone(), black.clone()], Some(*space))+ let (mut master, mut chans, base_space, base_pencil) = match base {+ Some(Adjustment::Curves { master, per_channel, space, black, pencil }) => {+ (master.clone(), [per_channel[0].clone(), per_channel[1].clone(), per_channel[2].clone(), black.clone()], Some(*space), *pencil)}- _ => (identity_curve(), std::array::from_fn(|_| identity_curve()), None),+ _ => (identity_curve(), std::array::from_fn(|_| identity_curve()), None, false),};let space = space_of(r, base_space, mode);if base_space.is_some_and(|b| b != space) {chans = std::array::from_fn(|_| identity_curve());}+ let pencil = r.boolean("pencil", base_pencil)?;+ // Every stored curve in the adjustment's mode: maps are drawn from the spline when switching+ // to the pencil, fitted with points when switching back, and filled out to full maps.+ let convert = |c: Vec<CurvePoint>| match (base_pencil, pencil) {+ (false, true) => points_to_map(&c),+ (true, false) => map_to_points(&c),+ (true, true) if c.len() != CURVE_MAP_LEN => curve_map(&curve_map_outputs(&c)),+ _ => c,+ };+ let [c0, c1, c2, k] = chans;+ let [m, c0, c1, c2, k] = [master, c0, c1, c2, k].map(convert);+ (master, chans) = (m, [c0, c1, c2, k]);let composite = r.get("points").or_else(|| r.get("gray"));if let Some(v) = composite {- let c = parse_curve(r.cmd, "points", v)?;+ let c = parse_curve_in(r.cmd, "points", v, pencil)?;if space == ToneSpace::Lab {chans[0] = c;} else {@@ -762,12 +882,25 @@ fn curves(r: &Reader<'_>, base: Option<&Adjustment>, mode: ColorMode) -> Result<if let Some(v) = r.get(key)&& let Some(slot) = chans.get_mut(i){- *slot = parse_curve(r.cmd, key, v)?;+ *slot = parse_curve_in(r.cmd, key, v, pencil)?;+ }+ }+ let passes = r.num("smooth", 0.0, 0.0, MAX_SMOOTH_PASSES)?.round() as usize;+ if pencil {+ // Smoothed, then held at the params' precision so `to_params` round-trips exactly.+ let level = |o: f32| (o * 255.0 * CURVE_COORDINATE_PRECISION).round() / CURVE_COORDINATE_PRECISION / 255.0;+ for c in std::iter::once(&mut master).chain(chans.iter_mut()) {+ let mut outs = curve_map_outputs(c);+ for _ in 0..passes {+ smooth_curve_map(&mut outs);+ }+ *c = curve_map(&outs.into_iter().map(level).collect::<Vec<_>>());}}let [c0, c1, c2, black] = chans;- let black = if space == ToneSpace::Cmyk && !photocraft_doc::adjust::is_identity_curve(&black) { black } else { Vec::new() };- Ok(Adjustment::Curves { master, per_channel: [c0, c1, c2], space, black })+ let identity = if pencil { is_identity_map(&black) } else { photocraft_doc::adjust::is_identity_curve(&black) };+ let black = if space == ToneSpace::Cmyk && !identity { black } else { Vec::new() };+ Ok(Adjustment::Curves { master, per_channel: [c0, c1, c2], space, black, pencil })}fn levels_obj(c: &LevelsChannel) -> Value {@@ -908,6 +1041,9 @@ mod tests {("curves", json!({"points": [[0, 0]]})),("curves", json!({"red": [[0, 0], [1]]})),("curves", json!({"points": [[5, 5], [5, 9]]})),+ ("curves", json!({"pencil": true, "points": [1, 2, 3]})),+ ("curves", json!({"pencil": "yes"})),+ ("curves", json!({"points": (0..256).map(|k| if k == 9 { json!("x") } else { json!(k) }).collect::<Vec<_>>()})),("levels", json!({"red": 3})),("levels", json!({"inBlack": "x"})),("hueSaturation", json!({"reds": {"range": [1, 2]}})),@@ -1237,6 +1373,35 @@ mod tests {}}+ #[test]+ fn curves_pencil_maps_draw_smooth_and_convert_back() {+ // A drawn inversion: 256 output levels.+ let inverted: Vec<f32> = (0..256).rev().map(|k| k as f32).collect();+ let a = from_params("curves", &json!({"pencil": true, "points": inverted}), None, ColorMode::Rgb).unwrap();+ assert!(matches!(&a, Adjustment::Curves { pencil: true, master, .. } if master.len() == CURVE_MAP_LEN));+ assert!((tone_output(&a, [0.25; 3])[0] - 0.75).abs() < 1e-3);+ assert_eq!(from_params("curves", &to_params(&a), None, ColorMode::Rgb).unwrap(), a);+ // Smooth evens out a hard step but keeps the endpoints.+ let step: Vec<f32> = (0..256).map(|k| if k < 128 { 0.0 } else { 255.0 }).collect();+ let s = from_params("curves", &json!({"red": step, "smooth": 2}), Some(&a), ColorMode::Rgb).unwrap();+ let (_, chans) = curves_parts(&s);+ assert!(chans[0][127].output > 0.2 && chans[0][128].output < 0.8, "{:?}", &chans[0][120..136]);+ assert_eq!((chans[0][0].output, chans[0][255].output), (0.0, 1.0));+ // Edit points: the map is fitted with a point curve that still inverts.+ let pts = from_params("curves", &json!({"pencil": false}), Some(&a), ColorMode::Rgb).unwrap();+ let (master, _) = curves_parts(&pts);+ assert!(matches!(&pts, Adjustment::Curves { pencil: false, .. }) && master.len() <= MAX_FITTED_POINTS, "{master:?}");+ assert!((tone_output(&pts, [0.25; 3])[0] - 0.75).abs() < 2.0 / 255.0);+ // The command draws it at every depth.+ for depth in [8, 16, 32] {+ let mut s = colourful("rgb", depth);+ let before = pixels(&s);+ s.execute("image.adjustments.curves", to_params(&a)).unwrap();+ let after = pixels(&s);+ assert!((after[0][0] - (1.0 - before[0][0])).abs() < 2.0 / 255.0, "@{depth}: {after:?} vs {before:?}");+ }+ }+#[test]fn destructive_levels_dont_clip_in_32_bit() {// Input 15..230, gamma 1.3, output 10..245: black and white land on the output range indiff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex e71aad6ea..5882e93dc 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -1034,7 +1034,7 @@ fn build() -> Vec<CommandSpec> {("curves","Curves…",- r##"{"points":json,"red":json,"green":json,"blue":json,"eyedropper":json} (curves as [[in,out],…] in 0..255, 2..19 points: points = composite; red/green/blue, gray, cyan/magenta/yellow/black or lightness/a/b per channel; eyedropper = the dialog's Set Black/Neutral Gray/White Point picker {"point":"black|gray|white","at":[x,y]} or {"point",…,"color":[r,g,b] 0..1}, RGB and Grayscale (no gray) only, applied over the given curves)"##,+ r##"{"points":json,"red":json,"green":json,"blue":json,"pencil":bool=false,"smooth":0..10=0,"eyedropper":json} (curves as [[in,out],…] in 0..255, 2..19 points: points = composite; red/green/blue, gray, cyan/magenta/yellow/black or lightness/a/b per channel; pencil = drawn curves (Draw to modify the curve): each curve is 256 output levels in 0..255 (point curves given are drawn in, and turning pencil off fits points to the drawing); smooth = Smooth passes over the drawn curves; eyedropper = the dialog's Set Black/Neutral Gray/White Point picker {"point":"black|gray|white","at":[x,y]} or {"point",…,"color":[r,g,b] 0..1}, RGB and Grayscale (no gray) only, applied over the given curves)"##,),("exposure", "Exposure…", r##"{"exposure":-20..20=0,"offset":-0.5..0.5=0,"gamma":0.01..9.99=1}"##),("vibrance", "Vibrance…", r##"{"vibrance":-100..100=0,"saturation":-100..100=0}"##),diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rsindex 6b5e29d10..9681a0756 100644--- a/crates/gpu/tests/parity.rs+++ b/crates/gpu/tests/parity.rs@@ -45,12 +45,19 @@ fn hdr_adjustments_preserve_range_and_cpu_parity() {space: Default::default(),black: Default::default(),},- Adjustment::Curves { master: identity.clone(), per_channel: std::array::from_fn(|_| identity.clone()), space: Default::default(), black: Vec::new() },+ Adjustment::Curves {+ master: identity.clone(),+ per_channel: std::array::from_fn(|_| identity.clone()),+ space: Default::default(),+ black: Vec::new(),+ pencil: false,+ },Adjustment::Curves {master: Vec::new(),per_channel: [Vec::new(), identity.clone(), vec![CurvePoint { input: 0.0, output: 0.0 }, CurvePoint { input: 1.0, output: 0.5 }]],space: Default::default(),black: Vec::new(),+ pencil: false,},] {let mut d = Document::new("HDR adjustments", Size::new(3, 1), ColorMode::Rgb, SampleType::F32);@@ -484,6 +491,7 @@ fn adjustments() -> Vec<Adjustment> {per_channel: [pts(&[(0.0, 0.0), (0.5, 0.3), (1.0, 1.0)]), pts(&[(0.0, 0.0), (1.0, 1.0)]), pts(&[(0.0, 0.2), (1.0, 1.0)])],space: Default::default(),black: Vec::new(),+ pencil: false,},Adjustment::HueSaturation { hue: 40.0, saturation: 30.0, lightness: -10.0, colorize: false, ranges: HueRange::defaults() },Adjustment::HueSaturation { hue: 200.0, saturation: 50.0, lightness: 20.0, colorize: true, ranges: HueRange::defaults() },diff --git a/crates/io/src/adjust_map.rs b/crates/io/src/adjust_map.rsindex 4ea5c2787..03f3180b0 100644--- a/crates/io/src/adjust_map.rs+++ b/crates/io/src/adjust_map.rs@@ -11,7 +11,7 @@//! stay [`Adjustment::Unsupported`] and are written back verbatim.use photocraft_doc::Adjustment;-use photocraft_doc::adjust::{CurvePoint, HueRange, LevelsChannel, ToneSpace};+use photocraft_doc::adjust::{CURVE_MAP_LEN, CurvePoint, HueRange, LevelsChannel, ToneSpace, curve_map, curve_map_outputs};use photocraft_psd::descriptor::{Descriptor, Value, VersionedDescriptor};/// All PSD adjustment keys recognized as adjustment layers.@@ -43,7 +43,9 @@ fn levels_rec(d: &[u8], at: usize) -> Option<LevelsChannel> {}fn parse_curves(d: &[u8]) -> Option<Adjustment> {- // pad(1) version(2) bitmap(4)+ // map flag(1) version(2) bitmap(4). A map (Photoshop's pencil-drawn curves) stores 256 output+ // bytes per channel instead of a point list (psd-tools reads the flag as `is_map`).+ let pencil = *d.first()? != 0;let version = be16(d, 1)?;if version != 1 && version != 4 {return None;@@ -56,6 +58,14 @@ fn parse_curves(d: &[u8]) -> Option<Adjustment> {if bits & (1 << bit) == 0 {continue;}+ if pencil {+ let map = d.get(at..at + CURVE_MAP_LEN)?;+ at += CURVE_MAP_LEN;+ if let Some(slot) = curves.get_mut(bit) {+ *slot = curve_map(&map.iter().map(|&b| f32::from(b) / 255.0).collect::<Vec<_>>());+ }+ continue;+ }let n = usize::from(be16(d, at)?);at += 2;let mut pts = Vec::with_capacity(n.min(64));@@ -72,7 +82,7 @@ fn parse_curves(d: &[u8]) -> Option<Adjustment> {let mut it = curves.into_iter();let master = it.next()?;let (r, g, b, k) = (it.next()?, it.next()?, it.next()?, it.next()?);- Some(Adjustment::Curves { master, per_channel: [r, g, b], space: ToneSpace::Rgb, black: k })+ Some(Adjustment::Curves { master, per_channel: [r, g, b], space: ToneSpace::Rgb, black: k, pencil })}fn desc_num(d: &Descriptor, key: &str) -> Option<f32> {@@ -616,12 +626,16 @@ pub fn write(adj: &Adjustment) -> Vec<([u8; 4], Vec<u8>)> {}return vec![(*b"levl", v)];}- Adjustment::Curves { master, per_channel, space, black } => {- v.push(0);+ Adjustment::Curves { master, per_channel, space, black, pencil } => {+ v.push(u8::from(*pencil));put16(&mut v, 1);let ink = *space == ToneSpace::Cmyk && black.len() >= 2;v.extend_from_slice(&(if ink { 0b11111u32 } else { 0b1111 }).to_be_bytes());for c in std::iter::once(master).chain(per_channel.iter()).chain(ink.then_some(black)) {+ if *pencil {+ v.extend(curve_map_outputs(c).iter().map(|&o| u8::try_from(q255(o)).unwrap_or(u8::MAX)));+ continue;+ }put16(&mut v, c.len().min(19) as u16);for p in c.iter().take(19) {put16(&mut v, q255(p.output));@@ -788,6 +802,28 @@ mod tests {assert!(matches!(parse(b"grdm", &[0, 1, 0, 0, 0, 0, 0, 0, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. }));}+ #[test]+ fn pencil_curves_read_and_write_the_map_form() {+ // Photoshop's pencil-drawn curves: map flag 1, then 256 output bytes per channel.+ let mut block = vec![1, 0, 1, 0, 0, 0, 0b1111];+ let maps: [Vec<u8>; 4] = [+ (0..=255u8).rev().collect(),+ (0..=255u8).map(|k| if k < 128 { 0 } else { 255 }).collect(),+ (0..=255u8).collect(),+ (0..=255u8).map(|k| k / 2).collect(),+ ];+ for m in &maps {+ block.extend_from_slice(m);+ }+ let a = parse(b"curv", &block, None, Channels::Rgb);+ let Adjustment::Curves { master, per_channel, pencil, .. } = &a else { panic!("{a:?}") };+ assert!(*pencil);+ assert_eq!(master.len(), CURVE_MAP_LEN);+ assert_eq!((master[0].output, master[255].output), (1.0, 0.0));+ assert_eq!((per_channel[0][127].output, per_channel[0][128].output), (0.0, 1.0));+ assert_eq!(write(&a)[0].1, block);+ }+fn rt(a: Adjustment) {let blocks = write(&a);assert!(!blocks.is_empty(), "{a:?}");@@ -823,6 +859,7 @@ mod tests {per_channel: [pts(&[(0, 10), (255, 255)]), pts(&[(0, 0), (255, 245)]), pts(&[(0, 0), (64, 32), (255, 255)])],space: ToneSpace::Rgb,black: Vec::new(),+ pencil: false,});// CMYK ink curves and levels keep their black record.let ink = Adjustment::Curves {@@ -830,6 +867,7 @@ mod tests {per_channel: [pts(&[(0, 0), (255, 255)]), pts(&[(0, 30), (255, 255)]), pts(&[(0, 0), (255, 255)])],space: ToneSpace::Cmyk,black: pts(&[(0, 0), (128, 100), (255, 255)]),+ pencil: false,};let b = write(&ink);assert_eq!(parse(&b[0].0, &b[0].1, None, Channels::Cmyk), ink);diff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rsindex 7423de9a5..f1fb78e91 100644--- a/crates/io/src/smart_map.rs+++ b/crates/io/src/smart_map.rs@@ -231,6 +231,13 @@ fn curves_params(f: &Descriptor) -> Option<J> {let mut out = Map::new();for a in adjustment_list(f)? {let key = channel_key(a)?;+ // A pencil-drawn curve is a mapping of 256 output levels (`Mpng`) instead of points.+ if let Some(Value::List(map)) = a.get("Mpng") {+ let map: Option<Vec<J>> = map.iter().map(|v| int_value(v).map(|o| json!(o.clamp(0, 255)))).collect();+ out.insert(if key.is_empty() { "points".into() } else { key.into() }, J::Array(map.filter(|m| m.len() == 256)?));+ out.insert("pencil".into(), J::Bool(true));+ continue;+ }let Some(Value::List(pts)) = a.get("Crv ") else { return None };let pts: Option<Vec<J>> = pts.iter()@@ -370,7 +377,7 @@ fn channel_ref(code: &[u8; 4]) -> Value {fn adjustments(p: &J, curves: bool) -> Result<Value, String> {let obj = p.as_object().ok_or("parameters are not an object")?;let allowed: &[&str] =- if curves { &["points", "red", "green", "blue"] } else { &["inBlack", "inWhite", "gamma", "outBlack", "outWhite", "red", "green", "blue"] };+ if curves { &["points", "red", "green", "blue", "pencil"] } else { &["inBlack", "inWhite", "gamma", "outBlack", "outWhite", "red", "green", "blue"] };if let Some(k) = obj.keys().find(|k| !is_meta(k) && !allowed.contains(&k.as_str())) {return Err(format!("setting `{k}` has no PSD equivalent"));}@@ -382,6 +389,13 @@ fn adjustments(p: &J, curves: bool) -> Result<Value, String> {if curves {let src = if key.is_empty() { p.get("points") } else { Some(o) };let Some(pts) = src.and_then(J::as_array) else { continue };+ if p.get("pencil").and_then(J::as_bool) == Some(true) {+ let map: Option<Vec<Value>> =+ pts.iter().map(|o| o.as_f64().filter(|o| o.is_finite()).map(|o| Value::Integer(o.round().clamp(0.0, 255.0) as i32))).collect();+ a = a.with("Mpng", Value::List(map.filter(|m| m.len() == 256).ok_or("a pencil-drawn curve is not 256 output levels")?));+ list.push(Value::Descriptor(a));+ continue;+ }let pts: Option<Vec<Value>> = pts.iter().map(|q| {@@ -824,6 +838,8 @@ mod tests {sf("image.adjustments.levels", json!({"inBlack": 20, "inWhite": 220, "gamma": 1.4, "red": {"inBlack": 0, "inWhite": 255, "gamma": 0.8}})),sf("image.adjustments.curves", json!({"points": [[0.0, 0.0], [64.0, 40.0], [255.0, 255.0]], "blue": [[0.0, 20.0], [255.0, 235.0]]})),sf("image.adjustments.shadowsHighlights", json!({})),+ // A pencil-drawn curve: 256 output levels (`Mpng`).+ sf("image.adjustments.curves", json!({"pencil": true, "points": (0..256).rev().collect::<Vec<i32>>()})),];for mut f in filters {f.blend = BlendMode::Overlay;diff --git a/crates/io/tests/adjust_blend_roundtrip.rs b/crates/io/tests/adjust_blend_roundtrip.rsindex b067cc705..4e8b727af 100644--- a/crates/io/tests/adjust_blend_roundtrip.rs+++ b/crates/io/tests/adjust_blend_roundtrip.rs@@ -61,6 +61,7 @@ fn adjustments() -> Vec<(Adjustment, bool)> {per_channel: [pts(&[(0, 10), (255, 255)]), pts(&[(0, 0), (255, 245)]), pts(&[(0, 0), (64, 32), (255, 255)])],space: ToneSpace::Rgb,black: Vec::new(),+ pencil: false,},true,),diff --git a/crates/io/tests/common/mod.rs b/crates/io/tests/common/mod.rsindex 710763cda..f175badb3 100644--- a/crates/io/tests/common/mod.rs+++ b/crates/io/tests/common/mod.rs@@ -170,6 +170,7 @@ pub fn gen_doc(mode: ColorMode, depth: SampleType, f: Features) -> Document {],space: tone_space(mode),black: Vec::new(),+ pencil: false,},Adjustment::Unsupported { psd_key: "selc".into(), raw: vec![0, 1, 0, 0] },];diff --git a/crates/ui-egui/src/adjust_dialog.rs b/crates/ui-egui/src/adjust_dialog.rsindex a4b831ed2..54f7155d3 100644--- a/crates/ui-egui/src/adjust_dialog.rs+++ b/crates/ui-egui/src/adjust_dialog.rs@@ -434,6 +434,36 @@ mod tests {assert!(std::sync::Arc::ptr_eq(&before, &after));assert!(harness.state().ui.dialogs.is_empty());}+ #[test]+ fn curves_pencil_drag_draws_the_map_and_confirm_applies_it() {+ let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image());+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);+ let steps = h.state().session.active().unwrap().history.past_len();+ let id = open(h.state_mut(), "image.adjustments.curves").unwrap();+ let fields = &mut h.state_mut().ui.dialog_mut(id).unwrap().fields;+ fields.insert("pencil".into(), json!(true));+ fields.insert("points".into(), json!((0..256).collect::<Vec<_>>()));+ h.run_steps(4);+ let graph = h.ctx.data(|d| d.get_temp::<egui::Rect>(egui::Id::new(("adjust-dialog", "curves")).with("curves-graph"))).unwrap();+ let at = |i: f32, o: f32| egui::pos2(graph.left() + i / 255.0 * graph.width(), graph.bottom() - o / 255.0 * graph.height());+ h.hover_at(at(64.0, 200.0));+ h.run_steps(1);+ h.drag_at(at(64.0, 200.0));+ h.run_steps(1);+ for i in [100.0, 150.0, 192.0] {+ h.hover_at(at(i, 200.0));+ h.run_steps(1);+ }+ h.drop_at(at(192.0, 200.0));+ h.run_steps(3);+ let map = h.state().ui.dialogs[0].fields["points"].as_array().unwrap().clone();+ assert_eq!(map.len(), 256);+ assert!((70..185).all(|k| (map[k].as_f64().unwrap() - 200.0).abs() < 3.0), "{map:?}");+ assert_eq!(map[20].as_f64(), Some(20.0), "outside the stroke the map is untouched");+ crate::dialogs::confirm(h.state_mut(), id).unwrap();+ assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1);+ }+#[test]fn curves_pointer_drag_previews_until_confirm_and_cancel_preserves_document() {for confirm in [false, true] {diff --git a/crates/ui-egui/src/adjust_editors.rs b/crates/ui-egui/src/adjust_editors.rsindex 6900301f3..9f5d5b413 100644--- a/crates/ui-egui/src/adjust_editors.rs+++ b/crates/ui-egui/src/adjust_editors.rs@@ -349,6 +349,60 @@ fn curve_key(ch: &ToneChannel) -> &'static str {if ch.key.is_empty() { "points" } else { ch.key }}+/// A pencil-drawn channel: its 256 output levels (identity when absent or not a map).+fn read_map(v: &Value, key: &str) -> Vec<f32> {+ let map: Option<Vec<f32>> = v+ .get(key)+ .and_then(Value::as_array)+ .filter(|a| a.len() == photocraft_doc::adjust::CURVE_MAP_LEN)+ .and_then(|a| a.iter().map(|o| o.as_f64().map(|o| o as f32)).collect());+ map.unwrap_or_else(|| (0..photocraft_doc::adjust::CURVE_MAP_LEN).map(|k| k as f32).collect())+}++fn write_map(v: &mut Value, key: &str, map: &[f32]) {+ v[key] = json!(map.iter().map(|o| (o * 100.0).round() / 100.0).collect::<Vec<_>>());+}++/// Switches the Curves values between point editing and the pencil: the engine draws the point+/// curves into maps, or fits points to the drawn maps (Photoshop's two curve buttons).+fn set_pencil(v: &mut Value, pencil: bool, gray: bool) -> bool {+ let mut p = v.clone();+ p["pencil"] = json!(pencil);+ let mode = if gray { photocraft_doc::ColorMode::Grayscale } else { photocraft_doc::ColorMode::Rgb };+ let Ok(a) = adjust_params::from_params("curves", &p, None, mode) else { return false };+ *v = adjust_params::to_params(&a);+ // Explicit, so an update over a pencil-drawn layer leaves the pencil.+ v["pencil"] = json!(pencil);+ true+}++/// Mode buttons above the graph: points, pencil, and Smooth for the shown channel's drawing.+fn curves_mode_row(ui: &mut egui::Ui, v: &mut Value, key: &str, gray: bool) -> Edit {+ let pencil = v.get("pencil").and_then(Value::as_bool).unwrap_or(false);+ let mut e = Edit::default();+ ui.horizontal(|ui| {+ if crate::icons::button(ui, "spline", 24.0, !pencil, tl!("Edit points to modify the curve")).clicked() && pencil {+ e.add(Edit::discrete(set_pencil(v, false, gray)));+ }+ if crate::icons::button(ui, "pencil", 24.0, pencil, tl!("Draw to modify the curve")).clicked() && !pencil {+ e.add(Edit::discrete(set_pencil(v, true, gray)));+ }+ let label = crate::i18n::tr_ctx(crate::i18n::current(), "curves", "Smooth");+ let smooth = ui+ .add_enabled_ui(pencil, |ui| widgets::secondary_button(ui, label, 0.0))+ .inner+ .on_hover_text(tl!("Smooth the curve values"))+ .on_disabled_hover_text(tl!("Smooth the curve values"));+ if smooth.clicked() {+ let mut map = read_map(v, key);+ adjust_params::smooth_curve_map(&mut map);+ write_map(v, key, &map);+ e.add(Edit::discrete(true));+ }+ });+ e+}+fn curves(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {let t = Tokens::get(ui.ctx());let space = space_of(v);@@ -361,17 +415,44 @@ fn curves(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {}let chan = chans.get(ch).copied().unwrap_or(ToneChannel { key: "", label: "" });let key = curve_key(&chan);+ let mut e = curves_mode_row(ui, v, key, cx.gray);+ let pencil = v.get("pencil").and_then(Value::as_bool).unwrap_or(false);let mut pts = read_curve(v, key);+ let mut map = read_map(v, key);let side = ui.available_width().clamp(120.0, 300.0);ui.add_space(4.0);let (full, resp) = ui.allocate_exact_size(vec2(side, side + 14.0), Sense::click_and_drag());let graph = curve_graph(full, side);ui.data_mut(|d| d.insert_temp(cx.mem.with("curves-graph"), graph));let to_scr = |q: [f32; 2]| pos2(graph.left() + q[0] / 255.0 * graph.width(), graph.bottom() - q[1] / 255.0 * graph.height());- let mut e = Edit::default();- let interaction = crate::point_curve::interact(ui, &resp, graph, &mut pts, &mut st.gesture);- let mut changed = interaction.changed;- e.commit = interaction.commit;+ let mut changed = false;+ let mut drawn = false;+ if pencil {+ // Pencil: a stroke draws while the button is down and commits on release; Shift+ // continues from the previous stroke's end in a straight line.+ let stroke_id = cx.mem.with("curves-pencil");+ let (mut active, mut last): (bool, Option<[f32; 2]>) = ui.data(|d| d.get_temp(stroke_id)).unwrap_or_default();+ if resp.is_pointer_button_down_on()+ && let Some(pos) = resp.interact_pointer_pos()+ {+ let q = [+ ((pos.x - graph.left()) / graph.width().max(1.0) * 255.0).clamp(0.0, 255.0),+ ((graph.bottom() - pos.y) / graph.height().max(1.0) * 255.0).clamp(0.0, 255.0),+ ];+ let from = if active || ui.input(|i| i.modifiers.shift) { last.unwrap_or(q) } else { q };+ drawn = curve_edit::pencil_line(&mut map, from, q);+ active = true;+ last = Some(q);+ } else if active {+ active = false;+ e.commit = true;+ }+ ui.data_mut(|d| d.insert_temp(stroke_id, (active, last)));+ } else {+ let interaction = crate::point_curve::interact(ui, &resp, graph, &mut pts, &mut st.gesture);+ changed = interaction.changed;+ e.commit |= interaction.commit;+ }// Draw: histogram, quarter grid, baseline, gradient bars, other channels, the curve, points.let p = ui.painter_at(full.expand(2.0));@@ -405,17 +486,34 @@ fn curves(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {(0..n).step_by((n / 256).max(1)).map(|i| to_scr([i as f32 / (n - 1) as f32 * 255.0, lut.get(i).copied().unwrap_or(0.0) * 255.0])).collect();p.add(egui::Shape::line(line, Stroke::new(width, color)));};+ let draw_map = |map: &[f32], color: Color32, width: f32| {+ let last = map.len().saturating_sub(1).max(1) as f32;+ let line: Vec<Pos2> = map.iter().enumerate().map(|(k, o)| to_scr([k as f32 / last * 255.0, *o])).collect();+ p.add(egui::Shape::line(line, Stroke::new(width, color)));+ };if ch == 0 {// Photoshop overlays the edited channel curves on the composite.for c in chans.iter().skip(1) {+ if pencil {+ let m = read_map(v, c.key);+ if m.iter().enumerate().any(|(k, o)| (o - k as f32).abs() > 0.5) {+ draw_map(&m, bar_color(c, &t).gamma_multiply(0.8), 1.0);+ }+ continue;+ }let cp = read_curve(v, c.key);if cp.len() > 2 || cp.first().is_some_and(|q| q[1] != 0.0) || cp.last().is_some_and(|q| q[1] != 255.0) {draw_curve(&cp, bar_color(c, &t).gamma_multiply(0.8), 1.0);}}}- draw_curve(&pts, if ch == 0 { t.text } else { bar_color(&chan, &t) }, 1.5);- for (i, q) in pts.iter().enumerate() {+ let color = if ch == 0 { t.text } else { bar_color(&chan, &t) };+ if pencil {+ draw_map(&map, color, 1.5);+ } else {+ draw_curve(&pts, color, 1.5);+ }+ for (i, q) in pts.iter().enumerate().filter(|_| !pencil) {let r = Rect::from_center_size(to_scr(*q), vec2(CURVE_HANDLE_SIZE, CURVE_HANDLE_SIZE));if Some(i) == st.gesture.selected {p.rect_filled(r, 0.0, t.text);@@ -429,7 +527,7 @@ fn curves(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {// Input / Output of the selected point.ui.add_space(6.0);ui.horizontal(|ui| {- let i = st.gesture.selected.filter(|i| *i < pts.len());+ let i = st.gesture.selected.filter(|i| *i < pts.len() && !pencil);let (mut vi, mut vo) = i.map_or((0.0, 0.0), |i| (pts[i][0], pts[i][1]));label(ui, tl!("Input:"));let ri = ui.add_enabled_ui(i.is_some(), |ui| widgets::value_field(ui, &mut vi, 0.0..=255.0, "", 52.0)).inner;@@ -447,16 +545,23 @@ fn curves(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {}});let t2 = Tokens::get(ui.ctx());- ui.label(- RichText::new(crate::i18n::fmt(- tl!("Click to add a point · drag off or {key}-click or Delete to remove"),- &[("key", &crate::shortcuts::pretty("Cmd"))],- ))- .color(t2.text_faint)- .size(11.0),- );+ let hint = if pencil {+ crate::i18n::fmt(tl!("Drag to draw the curve · {key}-click draws a straight line"), &[("key", &crate::shortcuts::pretty("Shift"))])+ } else {+ crate::i18n::fmt(tl!("Click to add a point · drag off or {key}-click or Delete to remove"), &[("key", &crate::shortcuts::pretty("Cmd"))])+ };+ ui.label(RichText::new(hint).color(t2.text_faint).size(11.0));ui.data_mut(|d| d.insert_temp(state_id, st));- if changed {+ if drawn {+ write_map(v, key, &map);+ if space == ToneSpace::Lab+ && let Some(o) = v.as_object_mut()+ {+ o.remove("points");+ }+ e.changed = true;+ }+ if changed && !pencil {v[key] = json!(pts.iter().map(|q| [q[0].round(), q[1].round()]).collect::<Vec<_>>());if space == ToneSpace::Lab {// Lab has no composite: "points" would alias lightness.diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex a4fb9ebbe..62e843e99 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -3445,6 +3445,11 @@ layerLabel No Color Žádná barvaAmount: Míra:Protect: Chránit:Protect skin tones Chránit tóny pleti+ Edit points to modify the curve Upravit body pro změnu křivky+ Draw to modify the curve Kreslit pro změnu křivky+curves Smooth Vyhladit+ Smooth the curve values Vyhladit hodnoty křivky+ Drag to draw the curve · {key}-click draws a straight line Tažením nakreslíte křivku · {key}-klik nakreslí rovnou čáru# Select and Mask view modes (#1754)Onion Skin Cibulová slupkaMarching Ants Pochodující mravencidiff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex d9448f882..c3f5d6789 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2621,6 +2621,11 @@ cameraData Lens ObjektivAmount: Stärke:Protect: Schützen:Protect skin tones Hauttöne schützen+ Edit points to modify the curve Punkte bearbeiten, um die Kurve zu ändern+ Draw to modify the curve Zeichnen, um die Kurve zu ändern+curves Smooth Glätten+ Smooth the curve values Kurvenwerte glätten+ Drag to draw the curve · {key}-click draws a straight line Ziehen, um die Kurve zu zeichnen · {key}-Klick zeichnet eine gerade Linie# Select and Mask view modes (#1754)Onion Skin ZwiebelschichtMarching Ants Laufende Ameisendiff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex ca540f319..ebdd56fc4 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -3682,6 +3682,11 @@ cameraData Lens ΦακόςAmount: Ποσότητα:Protect: Προστασία:Protect skin tones Προστασία τόνων δέρματος+ Edit points to modify the curve Επεξεργασία σημείων για αλλαγή της καμπύλης+ Draw to modify the curve Σχεδίαση για αλλαγή της καμπύλης+curves Smooth Εξομάλυνση+ Smooth the curve values Εξομάλυνση των τιμών της καμπύλης+ Drag to draw the curve · {key}-click draws a straight line Σύρετε για να σχεδιάσετε την καμπύλη · {key}-κλικ σχεδιάζει ευθεία γραμμή# Select and Mask view modes (#1754)Onion Skin Φλούδα κρεμμυδιούMarching Ants Κινούμενο περίγραμμαdiff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex 7f1a7af37..025ccee27 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2662,6 +2662,11 @@ cameraData Lens ObjetivoAmount: Cantidad:Protect: Proteger:Protect skin tones Proteger tonos de piel+ Edit points to modify the curve Editar puntos para modificar la curva+ Draw to modify the curve Dibujar para modificar la curva+curves Smooth Suavizar+ Smooth the curve values Suavizar los valores de la curva+ Drag to draw the curve · {key}-click draws a straight line Arrastre para dibujar la curva · {key}-clic traza una línea recta# Select and Mask view modes (#1754)Onion Skin Papel cebollaMarching Ants Hormigas en marchadiff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex 4b286943e..bfe437394 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -2999,6 +2999,11 @@ cameraData Lens ObjectifAmount: Quantité :Protect: Protéger :Protect skin tones Protéger les tons chair+ Edit points to modify the curve Modifier les points pour changer la courbe+ Draw to modify the curve Dessiner pour changer la courbe+curves Smooth Lisser+ Smooth the curve values Lisser les valeurs de la courbe+ Drag to draw the curve · {key}-click draws a straight line Faites glisser pour dessiner la courbe · {key}-clic trace une ligne droite# Select and Mask view modes (#1754)Onion Skin Pelure d'oignonMarching Ants Fourmis en marchediff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex d51b5a413..825976fb3 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -2986,6 +2986,11 @@ cameraData Lens LensaAmount: Jumlah:Protect: Lindungi:Protect skin tones Lindungi warna kulit+ Edit points to modify the curve Edit titik untuk mengubah kurva+ Draw to modify the curve Gambar untuk mengubah kurva+curves Smooth Haluskan+ Smooth the curve values Haluskan nilai kurva+ Drag to draw the curve · {key}-click draws a straight line Seret untuk menggambar kurva · {key}-klik menggambar garis lurus# Select and Mask view modes (#1754)Onion Skin Kulit BawangMarching Ants Semut Berbarisdiff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex dd569eb73..219bb4a92 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -2653,6 +2653,11 @@ cameraData Lens ObiettivoAmount: Quantità:Protect: Proteggi:Protect skin tones Proteggi toni pelle+ Edit points to modify the curve Modifica i punti per cambiare la curva+ Draw to modify the curve Disegna per modificare la curva+curves Smooth Leviga+ Smooth the curve values Leviga i valori della curva+ Drag to draw the curve · {key}-click draws a straight line Trascina per disegnare la curva · {key}-clic traccia una linea retta# Select and Mask view modes (#1754)Onion Skin VelinaMarching Ants Formiche in marciadiff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex 524891cf3..b0f7e074c 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -3593,6 +3593,11 @@ cameraData Lens レンズAmount: 量:Protect: 保護:Protect skin tones 肌色を保護+ Edit points to modify the curve ポイントを編集してカーブを変更+ Draw to modify the curve 描画してカーブを変更+curves Smooth スムーズ+ Smooth the curve values カーブの値を滑らかにする+ Drag to draw the curve · {key}-click draws a straight line ドラッグしてカーブを描画 · {key}+クリックで直線を描画# Select and Mask view modes (#1754)Onion Skin オニオンスキンMarching Ants 点線の境界diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex 93ae26f9f..1eaf557cf 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -3166,6 +3166,11 @@ cameraData Lens 렌즈Amount: 양:Protect: 보호:Protect skin tones 피부톤 보호+ Edit points to modify the curve 점을 편집하여 곡선 수정+ Draw to modify the curve 그려서 곡선 수정+curves Smooth 매끄럽게+ Smooth the curve values 곡선 값을 매끄럽게 하기+ Drag to draw the curve · {key}-click draws a straight line 드래그하여 곡선 그리기 · {key}-클릭으로 직선 그리기# Select and Mask view modes (#1754)Onion Skin 어니언 스킨Marching Ants 점선 윤곽diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex 97134c953..b0880cb21 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -3738,6 +3738,11 @@ cameraData Lens LensAmount: Hoeveelheid:Protect: Beschermen:Protect skin tones Huidtinten beschermen+ Edit points to modify the curve Punten bewerken om de curve te wijzigen+ Draw to modify the curve Tekenen om de curve te wijzigen+curves Smooth Vloeiend maken+ Smooth the curve values Curvewaarden vloeiend maken+ Drag to draw the curve · {key}-click draws a straight line Sleep om de curve te tekenen · {key}-klik tekent een rechte lijn# Select and Mask view modes (#1754)Onion Skin UienschilMarching Ants Mierenmarsdiff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 29f93cdde..887ef7c2d 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -3595,6 +3595,11 @@ cameraData Lens ObiektywAmount: Wartość:Protect: Chroń:Protect skin tones Chroń odcienie skóry+ Edit points to modify the curve Edytuj punkty, aby zmienić krzywą+ Draw to modify the curve Rysuj, aby zmienić krzywą+curves Smooth Wygładź+ Smooth the curve values Wygładź wartości krzywej+ Drag to draw the curve · {key}-click draws a straight line Przeciągnij, aby narysować krzywą · {key}-klik rysuje linię prostą# Select and Mask view modes (#1754)Onion Skin Skórka cebuliMarching Ants Maszerujące mrówkidiff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex 1b113329e..b84cf2c6a 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -3004,6 +3004,11 @@ cameraData Lens LenteAmount: Quantidade:Protect: Proteger:Protect skin tones Proteger tons de pele+ Edit points to modify the curve Editar pontos para modificar a curva+ Draw to modify the curve Desenhar para modificar a curva+curves Smooth Suavizar+ Smooth the curve values Suavizar os valores da curva+ Drag to draw the curve · {key}-click draws a straight line Arraste para desenhar a curva · {key}-clique traça uma linha reta# Select and Mask view modes (#1754)Onion Skin Papel vegetalMarching Ants Formigas marchandodiff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex b0c4c5e7c..e314fc4f8 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -2922,6 +2922,11 @@ cameraData Lens ОбъективAmount: Эффект:Protect: Защитить:Protect skin tones Защищать тона кожи+ Edit points to modify the curve Изменять кривую по точкам+ Draw to modify the curve Рисовать кривую+curves Smooth Сгладить+ Smooth the curve values Сгладить значения кривой+ Drag to draw the curve · {key}-click draws a straight line Перетащите, чтобы нарисовать кривую · {key}-щелчок рисует прямую линию# Select and Mask view modes (#1754)Onion Skin КалькаMarching Ants Бегущие муравьиdiff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex d1250ad62..6e6ca92dc 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -3669,6 +3669,11 @@ cameraData Lens Об'єктивAmount: Величина:Protect: Захистити:Protect skin tones Захистити тони шкіри+ Edit points to modify the curve Змінювати криву за точками+ Draw to modify the curve Малювати криву+curves Smooth Згладити+ Smooth the curve values Згладити значення кривої+ Drag to draw the curve · {key}-click draws a straight line Перетягніть, щоб намалювати криву · {key}-клацання малює пряму лінію# Select and Mask view modes (#1754)Onion Skin КалькаMarching Ants Мурашкиdiff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex e89319eb6..dbdbe8589 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2595,6 +2595,11 @@ cameraData Lens 镜头Amount: 数量:Protect: 保护:Protect skin tones 保护肤色+ Edit points to modify the curve 编辑点以修改曲线+ Draw to modify the curve 绘制以修改曲线+curves Smooth 平滑+ Smooth the curve values 平滑曲线值+ Drag to draw the curve · {key}-click draws a straight line 拖动以绘制曲线 · 按住 {key} 单击可绘制直线# Select and Mask view modes (#1754)Onion Skin 洋葱皮Marching Ants 蚂蚁线diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex 05c8b24ba..4010050be 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2565,6 +2565,11 @@ cameraData Lens 鏡頭Amount: 總量:Protect: 保護:Protect skin tones 保護膚色+ Edit points to modify the curve 編輯點以修改曲線+ Draw to modify the curve 繪製以修改曲線+curves Smooth 平滑+ Smooth the curve values 平滑曲線數值+ Drag to draw the curve · {key}-click draws a straight line 拖曳以繪製曲線 · 按住 {key} 按一下可繪製直線# Select and Mask view modes (#1754)Onion Skin 洋蔥皮Marching Ants 螞蟻線diff --git a/crates/ui-egui/src/point_curve.rs b/crates/ui-egui/src/point_curve.rsindex 74e542b8b..e3928e8fa 100644--- a/crates/ui-egui/src/point_curve.rs+++ b/crates/ui-egui/src/point_curve.rs@@ -194,6 +194,30 @@ pub fn interact(ui: &mut Ui, resp: &Response, graph: Rect, pts: &mut Vec<[f32; 2e}+/// Curves' pencil: draws a straight stroke from `from` to `to` ([input, output] levels, 0..255)+/// into a pencil-drawn map (one output level per input level), so a fast drag leaves no gaps.+pub fn pencil_line(map: &mut [f32], from: [f32; 2], to: [f32; 2]) -> bool {+ if !from.iter().chain(to.iter()).all(|x| x.is_finite()) || map.is_empty() {+ return false;+ }+ let last = (map.len() - 1) as f32;+ let level = |x: f32| x.clamp(0.0, 255.0) / 255.0 * last;+ let (a, b) = if from[0] <= to[0] { (from, to) } else { (to, from) };+ let (i0, i1) = (level(a[0]).round() as usize, level(b[0]).round() as usize);+ let mut changed = false;+ for i in i0..=i1 {+ let t = if i1 > i0 { (i - i0) as f32 / (i1 - i0) as f32 } else { 1.0 };+ let o = (a[1] + (b[1] - a[1]) * t).clamp(0.0, 255.0);+ if let Some(slot) = map.get_mut(i)+ && *slot != o+ {+ *slot = o;+ changed = true;+ }+ }+ changed+}+#[cfg(test)]mod tests {use super::*;@@ -237,6 +261,17 @@ mod tests {assert!(!move_to(&mut p, 9, [0.0, 0.0]));}+ #[test]+ fn pencil_strokes_fill_every_level_they_cross() {+ let mut map: Vec<f32> = (0..256).map(|k| k as f32).collect();+ assert!(pencil_line(&mut map, [200.0, 10.0], [100.0, 210.0]));+ assert_eq!((map[100], map[150], map[200]), (210.0, 110.0, 10.0));+ assert_eq!((map[99], map[201]), (99.0, 201.0));+ assert!(!pencil_line(&mut map, [f32::NAN, 0.0], [5.0, 5.0]));+ assert!(pencil_line(&mut map, [-50.0, 900.0], [-40.0, 900.0]));+ assert_eq!(map[0], 255.0);+ }+#[test]fn hit_test_picks_the_nearest_point_in_radius() {let p = vec![[0.0, 0.0], [100.0, 100.0], [110.0, 110.0], [255.0, 255.0]];diff --git a/docs/scorecard.md b/docs/scorecard.mdindex 8d1839f7e..e75771380 100644--- a/docs/scorecard.md+++ b/docs/scorecard.md@@ -196,7 +196,7 @@ Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_w| UI-217-12 | Save custom New Document presets; a real Recent category | partial | [#217](https://github.com/storytold/photocraft/issues/217) | document_preset_cmds.rs and new_doc_ui.rs: named presets save/select/delete through preferences; Recent remains a static list plus Clipboard || UI-217-13 | Numeric fields accept arithmetic and units; scrubby labels; double-click resets a slider | done | [#217](https://github.com/storytold/photocraft/issues/217) | widgets::value_field: arithmetic plus units (1in, 5mm, 72pt, 50%) converted at the document resolution (#3099); widgets::scrub_label makes options-bar, slider-row and Character labels scrubby (Shift x10, Alt fine); slider rows with a known default reset on double-click || UI-217-14 | Layers panel: wheel steps blend modes, drop on New/Trash duplicates/deletes, checker behind art | done | [#217](https://github.com/storytold/photocraft/issues/217) | panels.rs: the wheel steps the blend-mode dropdown (widgets::dropdown_wheel_hovered, #1747); rows dropped on New Layer/Group/Delete duplicate/group/delete them (footer_drop, #736), effect rows dropped on Delete delete that effect or the whole style (fx_trash_drop, #3102); pixel thumbnails draw widgets::checker behind the art; Shift+Plus/Minus step the layer's or the painting tool's blend mode (blend_keys.rs, #3102) |-| UI-217-15 | Curves: smoothing / pencil mode, black/grey/white eyedroppers, tooltips | partial | [#217](https://github.com/storytold/photocraft/issues/217) | adjust_dialog.rs adds black/gray/white eyedroppers; smoothing and pencil modes remain missing |+| UI-217-15 | Curves: smoothing / pencil mode, black/grey/white eyedroppers, tooltips | partial | [#217](https://github.com/storytold/photocraft/issues/217) | Curves editor (adjust_editors.rs, dialog and Properties): Edit points / Draw (pencil) buttons and Smooth, all with tooltips; pencil curves are 256-level maps (Adjustment::Curves pencil, params pencil/smooth, PSD curv map form and smart-filter Mpng; #3088). The Image > Adjustments > Curves dialog has the black/gray/white eyedroppers (adjust_dialog.rs, #873); the adjustment layer's Properties panel has none yet || UI-217-16 | Hue/Saturation: Saturation and Lightness sliders get hue-following colour tracks | done | [#217](https://github.com/storytold/photocraft/issues/217) | saturation_track/lightness_track (adjust_editors.rs): grey -> the hue and black -> the hue -> white, recolouring as the Hue slider moves; saturation_and_lightness_tracks_follow_the_hue || UI-217-17 | Color panel: wheel plus RGB/HSB/CMYK/Lab/Gray/Web slider modes; resizes with its group | missing | [#217](https://github.com/storytold/photocraft/issues/217) | panels.rs:1837 single field + hex/RGB readout || UI-217-18 | Alt+wheel zooms in gentle ~5 % steps; zoom controls uncramped | missing | [#217](https://github.com/storytold/photocraft/issues/217) | canvas.rs:1107-1125 no Alt handling |diff --git a/scorecard/ui.toml b/scorecard/ui.tomlindex 7565c98ff..7367eb581 100644--- a/scorecard/ui.toml+++ b/scorecard/ui.toml@@ -108,7 +108,7 @@ id = "UI-217-15"target = "Curves: smoothing / pencil mode, black/grey/white eyedroppers, tooltips"status = "partial"issue = 217-note = "adjust_dialog.rs adds black/gray/white eyedroppers; smoothing and pencil modes remain missing"+note = "Curves editor (adjust_editors.rs, dialog and Properties): Edit points / Draw (pencil) buttons and Smooth, all with tooltips; pencil curves are 256-level maps (Adjustment::Curves pencil, params pencil/smooth, PSD curv map form and smart-filter Mpng; #3088). The Image > Adjustments > Curves dialog has the black/gray/white eyedroppers (adjust_dialog.rs, #873); the adjustment layer's Properties panel has none yet"[[item]]id = "UI-217-16"