Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Curves: add black, gray, and white point eyedroppers (#873)

Mr. Alonso Coronadde8fcddce91
diff --git a/crates/engine/src/adjust_params.rs b/crates/engine/src/adjust_params.rs
index e4fc111c7..ee3b429d9 100644
--- a/crates/engine/src/adjust_params.rs
+++ b/crates/engine/src/adjust_params.rs
@@ -464,14 +464,255 @@ fn identity_curve() -> Vec<CurvePoint> {
vec![CurvePoint { input: 0.0, output: 0.0 }, CurvePoint { input: 1.0, output: 1.0 }]
}
+const CURVE_COORDINATE_PRECISION: f32 = 100.0;
+const CURVE_POINT_DUPLICATE_DISTANCE: f32 = 0.5 / 255.0;
+
fn curve_arr(c: &[CurvePoint]) -> Value {
let c = if c.len() >= 2 { c.to_vec() } else { identity_curve() };
- json!(c.iter().map(|p| [(p.input * 255.0 * 100.0).round() / 100.0, (p.output * 255.0 * 100.0).round() / 100.0]).collect::<Vec<_>>())
+ json!(
+ c.iter()
+ .map(|p| {
+ [
+ (p.input * 255.0 * CURVE_COORDINATE_PRECISION).round() / CURVE_COORDINATE_PRECISION,
+ (p.output * 255.0 * CURVE_COORDINATE_PRECISION).round() / CURVE_COORDINATE_PRECISION,
+ ]
+ })
+ .collect::<Vec<_>>()
+ )
}
/// Most points a curve may have (Photoshop allows 16; the PSD record holds 19).
pub const MAX_CURVE_POINTS: usize = 19;
+/// 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)]
+pub enum CurvesEyedropper {
+ Black,
+ NeutralGray,
+ White,
+}
+
+/// Verify that serializing and parsing `points` keeps every point and the requested anchor.
+fn curve_round_trip_keeps_anchor(points: &[CurvePoint], input: f32, output: f32) -> bool {
+ let Ok(parsed) = parse_curve("curves eyedropper", "curve", &curve_arr(points)) else { return false };
+ if parsed.len() != points.len() {
+ return false;
+ }
+ let serialized = |value: f32| ((value * 255.0 * CURVE_COORDINATE_PRECISION).round() / CURVE_COORDINATE_PRECISION) / 255.0;
+ let (input, output) = (serialized(input), serialized(output));
+ parsed.iter().any(|point| (point.input - input).abs() < 1e-6 && (point.output - output).abs() < 1e-6)
+}
+
+fn move_curve_endpoint(points: &mut [CurvePoint], sample: f32, black: bool) {
+ let sample = sample.clamp(0.0, 1.0);
+ let mut candidate = points.to_vec();
+ if black {
+ for p in &mut candidate {
+ p.input = sample + p.input * (1.0 - sample);
+ }
+ if let Some(first) = candidate.first_mut() {
+ first.input = sample;
+ first.output = 0.0;
+ }
+ } else {
+ for p in &mut candidate {
+ p.input *= sample;
+ }
+ if let Some(last) = candidate.last_mut() {
+ last.input = sample;
+ last.output = 1.0;
+ }
+ }
+
+ // `curve_arr` stores hundredths of a 0..255 level, while `parse_curve` drops points
+ // separated by less than half a level. Scaling an endpoint toward the sample can collapse
+ // several edited points together even when the target endpoint itself survives. Check that
+ // the full curve survives the actual serializer and parser.
+ let target = if black { 0.0 } else { 1.0 };
+ if curve_round_trip_keeps_anchor(&candidate, sample, target) {
+ points.clone_from_slice(&candidate);
+ return;
+ }
+
+ // If scaling collapses any points, keep the user's point positions and edits, and make the
+ // two points nearest the selected endpoint a target plateau. Near an endpoint sample, those
+ // two points bracket the sample; the plateau is representable and leaves the rest of the
+ // curve intact.
+ if black {
+ for point in points.iter_mut().rev().take(2) {
+ point.output = 0.0;
+ }
+ } else {
+ for point in points.iter_mut().take(2) {
+ point.output = 1.0;
+ }
+ }
+}
+
+fn anchor_curve(points: &mut Vec<CurvePoint>, input: f32, output: f32) {
+ let (input, output) = (input.clamp(0.0, 1.0), output.clamp(0.0, 1.0));
+ let mut candidate = points.clone();
+ if let Some(point) = candidate.iter_mut().find(|p| (p.input - input).abs() < CURVE_POINT_DUPLICATE_DISTANCE) {
+ point.input = input;
+ point.output = output;
+ } else if candidate.len() < MAX_CURVE_POINTS {
+ candidate.push(CurvePoint { input, output });
+ } else if let Some((index, _)) = candidate
+ .iter()
+ .enumerate()
+ .filter(|(index, _)| *index > 0 && *index + 1 < candidate.len())
+ .min_by(|(_, a), (_, b)| (a.input - input).abs().total_cmp(&(b.input - input).abs()))
+ && let Some(point) = candidate.get_mut(index)
+ {
+ *point = CurvePoint { input, output };
+ }
+ candidate.sort_by(|a, b| a.input.total_cmp(&b.input));
+ if curve_round_trip_keeps_anchor(&candidate, input, output) {
+ *points = candidate;
+ return;
+ }
+
+ // A channel sample can land between two points only half a level apart. Moving one point to
+ // the sample would then make the parser collapse the pair, so retain their positions and make
+ // the bracketing pair a deterministic neutral plateau instead.
+ let Some(last) = points.len().checked_sub(1) else { return };
+ let split = points.partition_point(|point| point.input < input);
+ let mut lower = split.saturating_sub(1).min(last);
+ let mut upper = split.min(last);
+ if lower == upper {
+ if upper < last {
+ upper += 1;
+ } else {
+ lower = lower.saturating_sub(1);
+ }
+ }
+ if let Some(point) = points.get_mut(lower) {
+ point.output = output;
+ }
+ if let Some(point) = points.get_mut(upper) {
+ point.output = output;
+ }
+}
+
+/// Rec. 709 luma in the sampled display-RGB values. This is the neutral level the gray picker
+/// should preserve when it removes a colour cast.
+fn rgb_luma(rgb: [f32; 3]) -> f32 {
+ rgb[0] * 0.2126 + rgb[1] * 0.7152 + rgb[2] * 0.0722
+}
+
+/// Find the master-curve input whose output is closest to `target`. The master curve is kept
+/// intact by the gray picker, so channel curves must target its inverse to preserve final luma.
+/// A non-monotone or flat curve may not have an exact inverse; the first nearest LUT entry gives
+/// a deterministic best fit.
+fn inverse_master_target(master: &[CurvePoint], target: f32) -> f32 {
+ if photocraft_doc::adjust::is_identity_curve(master) {
+ return target;
+ }
+ let lut = photocraft_compose::adjust::curve_lut(master);
+ let Some(denominator) = lut.len().checked_sub(1).filter(|last| *last > 0) else { return target };
+ let mut best_input = target;
+ let mut best_error = f32::INFINITY;
+ for (index, value) in lut.iter().enumerate() {
+ let error = (*value - target).abs();
+ if error < best_error {
+ best_error = error;
+ best_input = index as f32 / denominator as f32;
+ }
+ }
+ best_input
+}
+
+/// Resolve a merged-composite colour sample into the black, luma-preserving neutral-gray or white target.
+/// RGB uses the three channel curves. Grayscale uses the composite curve and has no gray picker.
+/// Other colour models stay unsupported until their native channel semantics can be sampled.
+pub fn curves_eyedropper(base: &Value, picker: CurvesEyedropper, sample: [f32; 3], mode: ColorMode) -> Result<Adjustment> {
+ if sample.iter().any(|v| !v.is_finite()) {
+ return Err(bad("curves eyedropper", "sample components must be finite"));
+ }
+ if !matches!(mode, ColorMode::Rgb | ColorMode::Grayscale) {
+ return Err(bad("curves eyedropper", "only RGB and Grayscale documents are supported"));
+ }
+ if 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)?;
+ let Adjustment::Curves { master, per_channel, .. } = &mut adjustment else {
+ return Err(bad("curves eyedropper", "expected a Curves adjustment"));
+ };
+ let sample = sample.map(|v| v.clamp(0.0, 1.0));
+ if mode == ColorMode::Grayscale {
+ let tone = (sample[0] + sample[1] + sample[2]) / 3.0;
+ move_curve_endpoint(master, tone, picker == CurvesEyedropper::Black);
+ return Ok(adjustment);
+ }
+ match picker {
+ CurvesEyedropper::Black | CurvesEyedropper::White => {
+ let black = picker == CurvesEyedropper::Black;
+ for (curve, value) in per_channel.iter_mut().zip(sample) {
+ move_curve_endpoint(curve, value, black);
+ }
+ if let Some(endpoint) = if black { master.first_mut() } else { master.last_mut() } {
+ endpoint.output = if black { 0.0 } else { 1.0 };
+ }
+ }
+ CurvesEyedropper::NeutralGray => {
+ // Use sampled luma instead of a fixed mid-gray so removing a cast keeps the sample's
+ // brightness. The per-channel curves precede the composite curve, so invert the
+ // existing master curve while preserving it.
+ let target = inverse_master_target(master, rgb_luma(sample));
+ for (curve, value) in per_channel.iter_mut().zip(sample) {
+ anchor_curve(curve, value, target);
+ }
+ }
+ }
+ Ok(adjustment)
+}
+
+/// The `eyedropper` param of the Curves commands, so agents and the CLI can drive the dialog's
+/// Set Black/Neutral Gray/White Point pickers: `{"point":"black"|"gray"|"white","at":[x,y]}`
+/// samples the merged composite at document pixel (x, y), or `"color":[r,g,b]` (0–1) gives the
+/// sample directly. The rest of `p` is the curve the picker edits. `None` without the key.
+pub fn curves_eyedropper_from_params(s: &crate::Session, p: &Value) -> Result<Option<Adjustment>> {
+ const CMD: &str = "curves eyedropper";
+ let Some(e) = p.get("eyedropper") else { return Ok(None) };
+ let picker = match e.get("point").and_then(Value::as_str) {
+ Some("black") => CurvesEyedropper::Black,
+ Some("gray") => CurvesEyedropper::NeutralGray,
+ Some("white") => CurvesEyedropper::White,
+ _ => return Err(bad(CMD, "`eyedropper.point` must be \"black\", \"gray\" or \"white\"")),
+ };
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let triple = |v: &Value| -> Option<[f64; 3]> {
+ let a = v.as_array().filter(|a| a.len() == 3)?;
+ Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?])
+ };
+ let sample = if let Some(c) = e.get("color") {
+ let c = triple(c).ok_or_else(|| bad(CMD, "`eyedropper.color` must be [r, g, b] in 0..1"))?;
+ c.map(|v| v as f32)
+ } else if let Some(at) = e.get("at") {
+ let xy = at.as_array().filter(|a| a.len() == 2).and_then(|a| Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?]));
+ let [x, y] = xy.filter(|xy| xy.iter().all(|v| v.is_finite())).ok_or_else(|| bad(CMD, "`eyedropper.at` must be [x, y] in document pixels"))?;
+ let (w, h) = (f64::from(d.doc.size.width), f64::from(d.doc.size.height));
+ if x < 0.0 || y < 0.0 || x >= w || y >= h {
+ return Err(bad(CMD, "`eyedropper.at` is outside the image"));
+ }
+ let rect = photocraft_geom::Rect::from_xywh(x.floor() as i32, y.floor() as i32, 1, 1);
+ let [r, g, b, a] = photocraft_compose::render(&d.doc, rect).px.first().copied().unwrap_or_default();
+ if a <= 0.0 {
+ return Err(bad(CMD, "the sampled pixel is transparent"));
+ }
+ [r, g, b]
+ } else {
+ return Err(bad(CMD, "`eyedropper` needs `at` [x, y] or `color` [r, g, b]"));
+ };
+ let mut base = p.clone();
+ if let Some(o) = base.as_object_mut() {
+ o.remove("eyedropper");
+ }
+ curves_eyedropper(&base, picker, sample, d.doc.mode).map(Some)
+}
+
/// `[[in, out], …]` in 0..255: sorted by input, duplicates collapsed, 2..=19 points.
pub fn parse_curve(cmd: &str, key: &str, v: &Value) -> Result<Vec<CurvePoint>> {
let err = || bad(cmd, format!("`{key}` must be an array of 2..={MAX_CURVE_POINTS} [input, output] pairs in 0..255"));
@@ -487,7 +728,7 @@ pub fn parse_curve(cmd: &str, key: &str, v: &Value) -> Result<Vec<CurvePoint>> {
pts.push(CurvePoint { input: (x as f32).clamp(0.0, 255.0) / 255.0, output: (y as f32).clamp(0.0, 255.0) / 255.0 });
}
pts.sort_by(|a, b| a.input.total_cmp(&b.input));
- pts.dedup_by(|later, earlier| (later.input - earlier.input).abs() < 0.5 / 255.0);
+ pts.dedup_by(|later, earlier| (later.input - earlier.input).abs() < CURVE_POINT_DUPLICATE_DISTANCE);
if pts.len() < 2 || pts.len() > MAX_CURVE_POINTS {
return Err(err());
}
@@ -680,6 +921,258 @@ mod tests {
assert!(matches!(a, Adjustment::Levels { master, .. } if master.in_white > master.in_black));
}
+ fn curves_parts(a: &Adjustment) -> (&[CurvePoint], &[Vec<CurvePoint>; 3]) {
+ match a {
+ Adjustment::Curves { master, per_channel, .. } => (master, per_channel),
+ _ => panic!("expected curves"),
+ }
+ }
+
+ fn tone_output(adjustment: &Adjustment, sample: [f32; 3]) -> [f32; 3] {
+ let luts = photocraft_compose::adjust::tone_luts(adjustment);
+ std::array::from_fn(|channel| {
+ let row = &luts[channel];
+ let position = sample[channel].clamp(0.0, 1.0) * (row.len().saturating_sub(1)) as f32;
+ let lower = position.floor() as usize;
+ let upper = lower.saturating_add(1).min(row.len().saturating_sub(1));
+ let fraction = position - lower as f32;
+ row.get(lower).copied().unwrap_or(0.0) * (1.0 - fraction) + row.get(upper).copied().unwrap_or(0.0) * fraction
+ })
+ }
+
+ #[test]
+ fn curves_black_and_white_eyedroppers_move_the_input_references() {
+ let base = json!({
+ "points": [[0, 8], [120, 150], [255, 245]],
+ "red": [[0, 0], [100, 130], [255, 255]],
+ "green": [[0, 0], [110, 125], [255, 255]],
+ "blue": [[0, 0], [90, 120], [255, 255]]
+ });
+ let black = curves_eyedropper(&base, CurvesEyedropper::Black, [0.2, 0.3, 0.4], ColorMode::Rgb).unwrap();
+ let (master, channels) = curves_parts(&black);
+ for (curve, sample) in channels.iter().zip([0.2, 0.3, 0.4]) {
+ assert!((curve[0].input - sample).abs() < 1e-6 && curve[0].output == 0.0, "{curve:?}");
+ assert_eq!(curve.len(), 3, "existing edit points are preserved");
+ }
+ assert_eq!(master[0].output, 0.0, "the composite cannot lift the sampled black");
+ assert!(tone_output(&black, [0.2, 0.3, 0.4]).iter().all(|value| *value < 1e-3));
+
+ let white = curves_eyedropper(&base, CurvesEyedropper::White, [0.6, 0.7, 0.8], ColorMode::Rgb).unwrap();
+ let (master, channels) = curves_parts(&white);
+ for (curve, sample) in channels.iter().zip([0.6, 0.7, 0.8]) {
+ let end = curve.last().unwrap();
+ assert!((end.input - sample).abs() < 1e-6 && end.output == 1.0, "{curve:?}");
+ assert_eq!(curve.len(), 3, "existing edit points are preserved");
+ }
+ assert_eq!(master.last().map(|p| p.output), Some(1.0), "the composite cannot lower the sampled white");
+ assert!(tone_output(&white, [0.6, 0.7, 0.8]).iter().all(|value| *value > 1.0 - 1e-3));
+
+ let edge_black = curves_eyedropper(&base, CurvesEyedropper::Black, [1.0, 0.3, 0.4], ColorMode::Rgb).unwrap();
+ let (_, edge_channels) = curves_parts(&edge_black);
+ assert_eq!(edge_channels[0].len(), 3, "edge samples preserve other curve points");
+ assert_eq!(edge_channels[0].last().map(|p| p.output), Some(0.0));
+ let edge_white = curves_eyedropper(&base, CurvesEyedropper::White, [0.0, 0.7, 0.8], ColorMode::Rgb).unwrap();
+ let (_, edge_channels) = curves_parts(&edge_white);
+ assert_eq!(edge_channels[0].len(), 3, "edge samples preserve other curve points");
+ assert_eq!(edge_channels[0].first().map(|p| p.output), Some(1.0));
+ }
+
+ #[test]
+ fn black_and_white_eyedroppers_round_trip_near_serialization_boundaries() {
+ let cases = [
+ (CurvesEyedropper::White, 0.0, 1.0),
+ (CurvesEyedropper::White, 0.001, 1.0),
+ (CurvesEyedropper::White, 0.494 / 255.0, 1.0),
+ // 0.496 level rounds to 0.50; the sample is just below that representable point.
+ (CurvesEyedropper::White, 0.496 / 255.0, 0.992),
+ (CurvesEyedropper::White, 0.2, 1.0),
+ (CurvesEyedropper::Black, 1.0, 0.0),
+ (CurvesEyedropper::Black, 0.999, 0.0),
+ (CurvesEyedropper::Black, 1.0 - 0.494 / 255.0, 0.0),
+ // 254.504 levels rounds to 254.50, leaving a representable 0.50-level gap.
+ (CurvesEyedropper::Black, 1.0 - 0.496 / 255.0, 0.008),
+ (CurvesEyedropper::Black, 0.8, 0.0),
+ ];
+ for (picker, sample, expected_output) in cases {
+ let resolved = curves_eyedropper(&json!({}), picker, [sample; 3], ColorMode::Rgb).unwrap();
+ let params = to_params(&resolved);
+ let parsed = from_params("curves", &params, None, ColorMode::Rgb).unwrap();
+ let (master, channels) = curves_parts(&parsed);
+ for curve in std::iter::once(master).chain(channels.iter().map(Vec::as_slice)) {
+ assert!(curve.len() >= 2, "{picker:?} sample={sample}: {curve:?}");
+ assert!(curve.len() <= MAX_CURVE_POINTS, "{picker:?} sample={sample}: {curve:?}");
+ assert!(curve.windows(2).all(|pair| pair[0].input < pair[1].input), "{picker:?} sample={sample}: {curve:?}");
+ assert!(curve.windows(2).all(|pair| pair[1].input - pair[0].input >= CURVE_POINT_DUPLICATE_DISTANCE), "{picker:?} sample={sample}: {curve:?}");
+ }
+ let output = tone_output(&parsed, [sample; 3]);
+ assert!(
+ output.iter().all(|value| (*value - expected_output).abs() < 1e-3),
+ "{picker:?} sample={sample} output={output:?} expected={expected_output}"
+ );
+ }
+ }
+
+ #[test]
+ fn endpoint_eyedroppers_fall_back_when_serialization_collapses_curve_points() {
+ let base = json!({
+ "points": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]],
+ "red": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]],
+ "green": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]],
+ "blue": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]]
+ });
+ let cases = [(CurvesEyedropper::Black, 0.995, 0.0, true), (CurvesEyedropper::White, 0.005, 1.0, false)];
+ for (picker, sample, target, black) in cases {
+ let resolved = curves_eyedropper(&base, picker, [sample; 3], ColorMode::Rgb).unwrap();
+ let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap();
+ let (master, channels) = curves_parts(&parsed);
+ for curve in std::iter::once(master).chain(channels.iter().map(Vec::as_slice)) {
+ assert_eq!(curve.len(), 5, "collapsed points use the deterministic fallback: {curve:?}");
+ for (point, input) in curve.iter().zip([0.0, 64.0, 128.0, 192.0, 255.0]) {
+ assert!((point.input * 255.0 - input).abs() < 1e-3, "existing point position was retained: {curve:?}");
+ }
+ }
+ for curve in channels {
+ let plateau: Vec<_> = if black { curve.iter().rev().take(2).collect() } else { curve.iter().take(2).collect() };
+ assert!(plateau.into_iter().all(|point| (point.output - target).abs() < 1e-6), "{curve:?}");
+ }
+ let output = tone_output(&parsed, [sample; 3]);
+ assert!(output.iter().all(|value| (*value - target).abs() < 0.01), "{picker:?}: {output:?}");
+ }
+ }
+
+ #[test]
+ fn black_and_white_round_trips_preserve_representable_curve_edits() {
+ let base = json!({
+ "points": [[0, 8], [120, 150], [255, 245]],
+ "red": [[0, 0], [100, 130], [255, 255]],
+ "green": [[0, 0], [110, 125], [255, 255]],
+ "blue": [[0, 0], [90, 120], [255, 255]]
+ });
+ let black = curves_eyedropper(&base, CurvesEyedropper::Black, [0.2, 0.3, 0.4], ColorMode::Rgb).unwrap();
+ let black = from_params("curves", &to_params(&black), None, ColorMode::Rgb).unwrap();
+ let (_, channels) = curves_parts(&black);
+ assert_eq!(channels[0].len(), 3);
+ assert!((channels[0][1].input * 255.0 - 131.0).abs() < 1e-3);
+ assert!((channels[0][1].output * 255.0 - 130.0).abs() < 1e-3);
+
+ let white = curves_eyedropper(&base, CurvesEyedropper::White, [0.6, 0.7, 0.8], ColorMode::Rgb).unwrap();
+ let white = from_params("curves", &to_params(&white), None, ColorMode::Rgb).unwrap();
+ let (_, channels) = curves_parts(&white);
+ assert_eq!(channels[0].len(), 3);
+ assert!((channels[0][1].input * 255.0 - 60.0).abs() < 1e-3);
+ assert!((channels[0][1].output * 255.0 - 130.0).abs() < 1e-3);
+ }
+
+ fn assert_gray_point_preserves_luma_and_existing_curve_edits(sample: [f32; 3]) {
+ let base = json!({
+ "points": [[0, 0], [128, 96], [255, 255]],
+ "red": [[0, 0], [80, 90], [255, 255]],
+ "green": [[0, 0], [90, 100], [255, 255]],
+ "blue": [[0, 0], [70, 80], [255, 255]]
+ });
+ let original = from_params("curves", &base, None, ColorMode::Rgb).unwrap();
+ let expected_luma = rgb_luma(sample);
+ let resolved = curves_eyedropper(&base, CurvesEyedropper::NeutralGray, sample, ColorMode::Rgb).unwrap();
+ let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap();
+ let (master, channels) = curves_parts(&parsed);
+ let (original_master, original_channels) = curves_parts(&original);
+ assert_eq!(master, original_master, "the existing master curve is retained");
+ for (curve, old_curve) in channels.iter().zip(original_channels) {
+ let old_edit = old_curve.get(1).expect("the test curve has an interior edit");
+ assert!(
+ curve.iter().any(|point| { (point.input - old_edit.input).abs() < 1e-6 && (point.output - old_edit.output).abs() < 1e-6 }),
+ "the existing channel edit is retained: {curve:?}"
+ );
+ }
+ let output = tone_output(&parsed, sample);
+ assert!((output[0] - output[1]).abs() < 0.002 && (output[1] - output[2]).abs() < 0.002, "sample must become neutral: {output:?}");
+ assert!((rgb_luma(output) - expected_luma).abs() < 0.003, "luma changed from {expected_luma} to {} ({output:?})", rgb_luma(output));
+ }
+
+ #[test]
+ fn curves_neutral_gray_preserves_luma_for_a_light_cast_sample() {
+ assert_gray_point_preserves_luma_and_existing_curve_edits([0.88, 0.76, 0.63]);
+ }
+
+ #[test]
+ fn curves_neutral_gray_preserves_luma_for_a_dark_cast_sample() {
+ assert_gray_point_preserves_luma_and_existing_curve_edits([0.17, 0.105, 0.075]);
+ }
+
+ #[test]
+ fn curves_neutral_gray_handles_near_black_and_near_white_samples() {
+ for sample in [[0.004, 0.006, 0.008], [0.992, 0.996, 0.999], [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]] {
+ let resolved = curves_eyedropper(&json!({}), CurvesEyedropper::NeutralGray, sample, ColorMode::Rgb).unwrap();
+ let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap();
+ let (master, channels) = curves_parts(&parsed);
+ for curve in std::iter::once(master).chain(channels.iter().map(Vec::as_slice)) {
+ assert!(curve.len() >= 2, "{sample:?}: {curve:?}");
+ assert!(curve.windows(2).all(|pair| pair[0].input < pair[1].input), "{sample:?}: {curve:?}");
+ assert!(curve.windows(2).all(|pair| pair[1].input - pair[0].input >= CURVE_POINT_DUPLICATE_DISTANCE), "{sample:?}: {curve:?}");
+ }
+ let output = tone_output(&parsed, sample);
+ assert!((output[0] - output[1]).abs() < 0.002 && (output[1] - output[2]).abs() < 0.002, "{sample:?}: {output:?}");
+ assert!((rgb_luma(output) - rgb_luma(sample)).abs() < 0.003, "{sample:?}: {output:?}");
+ }
+ }
+
+ #[test]
+ fn gray_point_fallback_keeps_tightly_spaced_points_round_trip_safe() {
+ let base = json!({
+ "red": [[0, 0], [100, 100], [100.51, 100], [255, 255]],
+ "green": [[0, 0], [100, 100], [100.51, 100], [255, 255]],
+ "blue": [[0, 0], [100, 100], [100.51, 100], [255, 255]]
+ });
+ let sample = [100.25 / 255.0, 100.1 / 255.0, 100.4 / 255.0];
+ let target = rgb_luma(sample);
+ let resolved = curves_eyedropper(&base, CurvesEyedropper::NeutralGray, sample, ColorMode::Rgb).unwrap();
+ let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap();
+ let (_, channels) = curves_parts(&parsed);
+ for (curve, input) in channels.iter().zip(sample) {
+ assert_eq!(curve.len(), 4, "the fallback keeps every serialized point: {curve:?}");
+ assert!(curve.windows(2).all(|pair| pair[1].input - pair[0].input >= CURVE_POINT_DUPLICATE_DISTANCE), "{curve:?}");
+ let sample_pair = curve.windows(2).find(|pair| pair[0].input <= input && input <= pair[1].input).unwrap();
+ assert!((sample_pair[0].output - sample_pair[1].output).abs() < 1e-6, "fallback forms a plateau around the sample: {curve:?}");
+ assert!((sample_pair[0].output - target).abs() < 0.001, "fallback uses the luma target: {curve:?}");
+ }
+ }
+
+ #[test]
+ fn curves_eyedropper_param_drives_the_command() {
+ let mut s = crate::Session::new();
+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
+ s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap();
+ s.execute("image.adjustments.curves", json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap();
+ let px: Vec<f32> = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap();
+ assert!(px.iter().take(3).all(|v| *v > 0.99), "the sample becomes white: {px:?}");
+ s.execute("image.adjustments.curves", json!({"eyedropper": {"point": "black", "color": [1.0, 1.0, 1.0]}})).unwrap();
+ let px: Vec<f32> = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap();
+ assert!(px.iter().take(3).all(|v| *v < 0.01), "the given colour becomes black: {px:?}");
+ for bad in [
+ json!("black"),
+ json!({"point": "nope", "at": [1, 1]}),
+ json!({"point": "black"}),
+ json!({"point": "black", "at": [99, 1]}),
+ json!({"point": "black", "at": [-1, 1]}),
+ json!({"point": "black", "at": [1]}),
+ json!({"point": "gray", "at": [f64::MAX, 1]}),
+ json!({"point": "black", "color": "red"}),
+ ] {
+ assert!(s.execute("image.adjustments.curves", json!({"eyedropper": bad})).is_err(), "{bad}");
+ }
+ }
+
+ #[test]
+ fn curves_eyedropper_support_is_explicit_and_bad_samples_fail() {
+ assert!(curves_eyedropper(&json!({}), CurvesEyedropper::Black, [0.4; 3], ColorMode::Grayscale).is_ok());
+ assert!(curves_eyedropper(&json!({}), CurvesEyedropper::White, [0.4; 3], ColorMode::Grayscale).is_ok());
+ assert!(curves_eyedropper(&json!({}), CurvesEyedropper::NeutralGray, [0.4; 3], ColorMode::Grayscale).is_err());
+ for mode in [ColorMode::Cmyk, ColorMode::Lab] {
+ assert!(curves_eyedropper(&json!({}), CurvesEyedropper::Black, [0.4; 3], mode).is_err());
+ }
+ assert!(curves_eyedropper(&json!({}), CurvesEyedropper::Black, [f32::NAN, 0.0, 0.0], ColorMode::Rgb).is_err());
+ }
+
#[test]
fn hue_range_sliders_stay_ordered() {
let a = from_params("hueSaturation", &json!({"greens": {"range": [100, 90, 200, 150]}}), None, ColorMode::Rgb).unwrap();
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index a1ea1928d..d37e3157e 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -897,7 +897,7 @@ fn build() -> Vec<CommandSpec> {
(
"curves",
"Curves…",
- r##"{"points":json,"red":json,"green":json,"blue":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)"##,
+ 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)"##,
),
("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}"##),
@@ -953,7 +953,11 @@ fn build() -> Vec<CommandSpec> {
enabled: has_doc,
run: |s, p| {
let kind = p.get("__kind").and_then(Value::as_str).unwrap_or("invert").to_string();
- let adj = crate::adjust_params::from_params(&kind, p, None, doc_mode(s))?;
+ let eyedropped = if kind == "curves" { crate::adjust_params::curves_eyedropper_from_params(s, p)? } else { None };
+ let adj = match eyedropped {
+ Some(adj) => adj,
+ None => crate::adjust_params::from_params(&kind, p, None, doc_mode(s))?,
+ };
new_adjustment(s, adj)
},
journal: true,
@@ -975,7 +979,11 @@ fn build() -> Vec<CommandSpec> {
enabled: has_pixel_or_channel,
run: |s, p| {
let kind = p.get("__kind").and_then(Value::as_str).unwrap_or("invert").to_string();
- let adj = crate::adjust_params::from_params(&kind, p, None, doc_mode(s))?;
+ let eyedropped = if kind == "curves" { crate::adjust_params::curves_eyedropper_from_params(s, p)? } else { None };
+ let adj = match eyedropped {
+ Some(adj) => adj,
+ None => crate::adjust_params::from_params(&kind, p, None, doc_mode(s))?,
+ };
let label = adj.label().to_string();
destructive_adjust(s, &label, adj, p)
},
diff --git a/crates/ui-egui/src/adjust_dialog.rs b/crates/ui-egui/src/adjust_dialog.rs
index 88e6909e4..ff6ace257 100644
--- a/crates/ui-egui/src/adjust_dialog.rs
+++ b/crates/ui-egui/src/adjust_dialog.rs
@@ -15,6 +15,107 @@ use crate::adjust_editors::{self, EditorCx};
use crate::tone::{self, HistSource};
const PREFIX: &str = "image.adjustments.";
+const CURVE_PICKER: &str = "__curvePicker";
+const CURVE_PICKER_BASE: &str = "__curvePickerBase";
+
+fn picker(value: Option<&Value>) -> Option<photocraft_engine::adjust_params::CurvesEyedropper> {
+ use photocraft_engine::adjust_params::CurvesEyedropper;
+ match value.and_then(Value::as_str) {
+ Some("black") => Some(CurvesEyedropper::Black),
+ Some("gray") => Some(CurvesEyedropper::NeutralGray),
+ Some("white") => Some(CurvesEyedropper::White),
+ _ => None,
+ }
+}
+
+fn picker_supported(mode: photocraft_doc::ColorMode, eyedropper: photocraft_engine::adjust_params::CurvesEyedropper) -> bool {
+ use photocraft_engine::adjust_params::CurvesEyedropper;
+ mode == photocraft_doc::ColorMode::Rgb || (mode == photocraft_doc::ColorMode::Grayscale && eyedropper != CurvesEyedropper::NeutralGray)
+}
+
+fn is_curves(fields: &Map<String, Value>) -> bool {
+ fields.get("__adjust").and_then(Value::as_str) == Some("curves")
+}
+
+/// Whether the top modal has a supported Curves eyedropper armed.
+pub fn picker_armed(app: &PhotocraftApp) -> bool {
+ let Some(dialog) = app.ui.dialogs.last().filter(|d| is_curves(&d.fields)) else { return false };
+ let Some(eyedropper) = picker(dialog.fields.get(CURVE_PICKER)) else { return false };
+ app.session.active().is_some_and(|s| picker_supported(s.doc.mode, eyedropper))
+}
+
+/// Sample the committed merged document through the regular canvas sampler and update only the
+/// open Curves dialog. Returns true when an armed Curves picker consumed the pointer event, even
+/// if the point was outside the image or transparent.
+pub fn sample_at(app: &mut PhotocraftApp, x: f64, y: f64) -> bool {
+ let Some((id, eyedropper, base)) = app.ui.dialogs.last().and_then(|dialog| {
+ let eyedropper = is_curves(&dialog.fields).then(|| picker(dialog.fields.get(CURVE_PICKER))).flatten()?;
+ let base = dialog.fields.get(CURVE_PICKER_BASE).cloned().unwrap_or_else(|| crate::filter_dialog::params_of(&dialog.fields));
+ Some((dialog.id, eyedropper, base))
+ }) else {
+ return false;
+ };
+ let Some(mode) = app.session.active().map(|s| s.doc.mode) else { return true };
+ if !picker_supported(mode, eyedropper) {
+ return true;
+ }
+ let Some(sample) = crate::canvas::composite_color(app, x, y) else { return true };
+ let params = match photocraft_engine::adjust_params::curves_eyedropper(&base, eyedropper, sample, mode) {
+ Ok(adjustment) => photocraft_engine::adjust_params::to_params(&adjustment),
+ Err(error) => {
+ app.ui.status = error.to_string();
+ return true;
+ }
+ };
+ let Some(dialog) = app.ui.dialog_mut(id) else { return true };
+ dialog.fields.insert(CURVE_PICKER_BASE.into(), base);
+ if let Value::Object(params) = params {
+ dialog.fields.retain(|key, _| key.starts_with("__"));
+ dialog.fields.extend(params);
+ }
+ true
+}
+
+fn picker_button(ui: &mut egui::Ui, selected: bool, enabled: bool, tooltip: &str, color: egui::Color32) -> egui::Response {
+ let response = ui.add_enabled_ui(enabled, |ui| crate::icons::button(ui, "pipette", 28.0, selected, tooltip)).inner;
+ let tokens = crate::theme::Tokens::get(ui.ctx());
+ ui.painter().circle_filled(response.rect.right_bottom() - egui::vec2(5.5, 5.5), 3.5, color);
+ ui.painter().circle_stroke(response.rect.right_bottom() - egui::vec2(5.5, 5.5), 3.5, egui::Stroke::new(1.0, tokens.field_border));
+ response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, enabled, selected, tooltip));
+ response
+}
+
+fn curves_picker_controls(ui: &mut egui::Ui, fields: &mut Map<String, Value>, mode: photocraft_doc::ColorMode) {
+ use photocraft_engine::adjust_params::CurvesEyedropper;
+ let current = picker(fields.get(CURVE_PICKER));
+ let mut chosen = None;
+ ui.horizontal(|ui| {
+ let tokens = crate::theme::Tokens::get(ui.ctx());
+ ui.label(egui::RichText::new(tl!("Eyedroppers:")).color(tokens.text_dim).size(12.0));
+ // The swatch is the tone the picker maps the sample to (image data, like the Curves
+ // gradient bars), not chrome, so it is the same in every theme; its ring is a token.
+ for (id, eyedropper, label, tone) in [
+ ("black", CurvesEyedropper::Black, tl!("Set Black Point"), 0),
+ ("gray", CurvesEyedropper::NeutralGray, tl!("Set Neutral Gray Point"), 128),
+ ("white", CurvesEyedropper::White, tl!("Set White Point"), 255),
+ ] {
+ let enabled = picker_supported(mode, eyedropper);
+ if picker_button(ui, current == Some(eyedropper), enabled, label, egui::Color32::from_gray(tone)).clicked() {
+ chosen = Some((id, eyedropper));
+ }
+ }
+ if !matches!(mode, photocraft_doc::ColorMode::Rgb | photocraft_doc::ColorMode::Grayscale) {
+ ui.label(egui::RichText::new(tl!("Unavailable in this color mode")).color(tokens.text_faint).size(11.0));
+ }
+ });
+ if let Some((id, selected)) = chosen
+ && current != Some(selected)
+ {
+ let base = crate::filter_dialog::params_of(fields);
+ fields.insert(CURVE_PICKER.into(), json!(id));
+ fields.insert(CURVE_PICKER_BASE.into(), base);
+ }
+}
/// Whether `command` opens an adjustment dialog (when run without params).
pub fn has_dialog(command: &str) -> bool {
@@ -46,6 +147,11 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {
/// Dialog body: the kind's editor over the fields, then the Preview checkbox.
pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map<String, Value>) {
let kind = fields.get("__adjust").and_then(Value::as_str).unwrap_or_default().to_string();
+ let mode = app.session.active().map_or(photocraft_doc::ColorMode::Rgb, |s| s.doc.mode);
+ if kind == "curves" {
+ curves_picker_controls(ui, fields, mode);
+ ui.add_space(4.0);
+ }
let mut values = crate::filter_dialog::params_of(fields);
let active = app.session.active().and_then(|s| s.active_layer);
let gray = app.session.active().is_some_and(|s| adjust_editors::is_gray(s.doc.mode));
@@ -61,6 +167,10 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map<String,
// Replace the parameter keys (an editor may remove one), keep the private ones.
fields.retain(|k, _| k.starts_with("__"));
fields.extend(v);
+ if picker(fields.get(CURVE_PICKER)).is_some() {
+ let base = crate::filter_dialog::params_of(fields);
+ fields.insert(CURVE_PICKER_BASE.into(), base);
+ }
}
let mut preview = fields.get("__preview").and_then(Value::as_bool).unwrap_or(true);
ui.add_space(6.0);
@@ -73,6 +183,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map<String,
mod tests {
use super::*;
use egui_kittest::Harness;
+ use egui_kittest::kittest::{NodeT, Queryable};
fn app_with_image() -> PhotocraftApp {
let mut s = photocraft_engine::Session::new();
@@ -83,6 +194,37 @@ mod tests {
PhotocraftApp::new(s, crate::Services::default())
}
+ fn app_in_mode(mode: &str) -> PhotocraftApp {
+ let mut session = photocraft_engine::Session::new();
+ session.execute("file.new", json!({"width": 32, "height": 24, "mode": mode})).unwrap();
+ PhotocraftApp::new(session, crate::Services::default())
+ }
+
+ fn arm(app: &mut PhotocraftApp, id: u64, picker: &str) {
+ let base = app.ui.dialog_mut(id).map(|dialog| crate::filter_dialog::params_of(&dialog.fields)).unwrap();
+ let dialog = app.ui.dialog_mut(id).unwrap();
+ dialog.fields.insert(CURVE_PICKER.into(), json!(picker));
+ dialog.fields.insert(CURVE_PICKER_BASE.into(), base);
+ }
+
+ fn channel_points(app: &PhotocraftApp, key: &str) -> Vec<[f64; 2]> {
+ app.ui
+ .dialogs
+ .last()
+ .and_then(|dialog| dialog.fields.get(key))
+ .and_then(Value::as_array)
+ .map(|points| {
+ points
+ .iter()
+ .filter_map(|point| {
+ let point = point.as_array()?;
+ Some([point.first()?.as_f64()?, point.get(1)?.as_f64()?])
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+ }
+
#[test]
fn every_adjustment_with_an_editor_has_a_dialog() {
for kind in adjust_editors::KINDS {
@@ -205,4 +347,162 @@ mod tests {
}
}
}
+
+ #[test]
+ fn curves_eyedroppers_sample_repeatedly_without_editing_the_document() {
+ let mut app = app_with_image();
+ let original = app.session.active().unwrap().doc.clone();
+ let revision = app.session.active().unwrap().revision;
+ let steps = app.session.active().unwrap().history.past_len();
+ let id = open(&mut app, "image.adjustments.curves").unwrap();
+ arm(&mut app, id, "black");
+ assert!(picker_armed(&app));
+ assert!(sample_at(&mut app, 8.0, 8.0));
+ let first = channel_points(&app, "red");
+ assert!((first[0][0] - 176.0).abs() < 0.6 && first[0][1] == 0.0, "{first:?}");
+ assert!(sample_at(&mut app, 8.0, 8.0));
+ assert_eq!(channel_points(&app, "red"), first, "the same repeated sample is deterministic");
+ assert!(sample_at(&mut app, 48.0, 8.0));
+ assert_ne!(channel_points(&app, "red"), first);
+ assert!(sample_at(&mut app, 8.0, 8.0));
+ assert_eq!(channel_points(&app, "red"), first, "repeated samples resolve from the armed baseline");
+ let st = app.session.active().unwrap();
+ assert!(std::sync::Arc::ptr_eq(&st.doc, &original));
+ assert_eq!(st.revision, revision);
+ assert_eq!(st.history.past_len(), steps);
+ }
+
+ #[test]
+ fn curves_picker_controls_arm_and_disable_by_document_mode() {
+ let harness = |app| {
+ 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);
+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
+ open(h.state_mut(), "image.adjustments.curves").unwrap();
+ h.run_steps(3);
+ h
+ };
+ let mut rgb = harness(app_in_mode("rgb"));
+ for label in ["Set Black Point", "Set Neutral Gray Point", "Set White Point"] {
+ assert!(!rgb.get_by_label(label).accesskit_node().is_disabled(), "{label}");
+ }
+ rgb.get_by_label("Set Black Point").click();
+ rgb.run_steps(2);
+ assert!(picker_armed(rgb.state()));
+ assert_eq!(rgb.state().ui.dialogs.last().and_then(|d| d.fields.get(CURVE_PICKER)).and_then(Value::as_str), Some("black"));
+
+ let gray = harness(app_in_mode("gray"));
+ assert!(!gray.get_by_label("Set Black Point").accesskit_node().is_disabled());
+ assert!(gray.get_by_label("Set Neutral Gray Point").accesskit_node().is_disabled());
+ assert!(!gray.get_by_label("Set White Point").accesskit_node().is_disabled());
+
+ for mode in ["cmyk", "lab"] {
+ let h = harness(app_in_mode(mode));
+ for label in ["Set Black Point", "Set Neutral Gray Point", "Set White Point"] {
+ assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{mode}: {label}");
+ }
+ }
+ }
+
+ #[test]
+ fn curves_picker_rejects_outside_and_transparent_samples() {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 32, "height": 24, "background": "transparent"})).unwrap();
+ let mut app = PhotocraftApp::new(s, crate::Services::default());
+ let id = open(&mut app, "image.adjustments.curves").unwrap();
+ arm(&mut app, id, "white");
+ let before = crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields);
+ assert!(sample_at(&mut app, -1.0, 4.0));
+ assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields), before);
+ assert!(sample_at(&mut app, 4.0, 4.0));
+ assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields), before);
+ assert!(picker_armed(&app), "an invalid sample does not disarm the picker");
+ }
+
+ #[test]
+ fn curves_picker_cancel_and_confirm_keep_one_transaction() {
+ for confirm in [false, true] {
+ let mut app = app_with_image();
+ let original = app.session.active().unwrap().doc.clone();
+ let steps = app.session.active().unwrap().history.past_len();
+ let id = open(&mut app, "image.adjustments.curves").unwrap();
+ arm(&mut app, id, "white");
+ assert!(sample_at(&mut app, 8.0, 8.0));
+ assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original));
+ assert_eq!(app.session.active().unwrap().history.past_len(), steps);
+ if confirm {
+ crate::dialogs::confirm(&mut app, id).unwrap();
+ let committed = app.session.active().unwrap().doc.clone();
+ assert!(!std::sync::Arc::ptr_eq(&committed, &original));
+ assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1);
+ app.run("edit.undo", json!({})).unwrap();
+ assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original));
+ app.run("edit.redo", json!({})).unwrap();
+ assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &committed));
+ } else {
+ app.ui.close_dialog(id);
+ assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original));
+ assert_eq!(app.session.active().unwrap().history.past_len(), steps);
+ }
+ }
+ }
+
+ #[test]
+ fn curves_picker_modes_and_depths_are_explicit() {
+ use photocraft_engine::adjust_params::CurvesEyedropper;
+ assert!(picker_supported(photocraft_doc::ColorMode::Rgb, CurvesEyedropper::NeutralGray));
+ assert!(picker_supported(photocraft_doc::ColorMode::Grayscale, CurvesEyedropper::Black));
+ assert!(picker_supported(photocraft_doc::ColorMode::Grayscale, CurvesEyedropper::White));
+ assert!(!picker_supported(photocraft_doc::ColorMode::Grayscale, CurvesEyedropper::NeutralGray));
+ assert!(!picker_supported(photocraft_doc::ColorMode::Cmyk, CurvesEyedropper::Black));
+ assert!(!picker_supported(photocraft_doc::ColorMode::Lab, CurvesEyedropper::White));
+
+ for depth in [8, 16, 32] {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth})).unwrap();
+ s.execute("edit.fill", json!({"color": [0.3142, 0.4821, 0.7137]})).unwrap();
+ let mut app = PhotocraftApp::new(s, crate::Services::default());
+ let sampled = crate::canvas::composite_color(&mut app, 4.0, 4.0).unwrap();
+ let id = open(&mut app, "image.adjustments.curves").unwrap();
+ arm(&mut app, id, "gray");
+ assert!(sample_at(&mut app, 4.0, 4.0), "RGB @{depth}");
+ let red = channel_points(&app, "red");
+ let target_level = (f64::from(sampled[0]) * 0.2126 + f64::from(sampled[1]) * 0.7152 + f64::from(sampled[2]) * 0.0722) * 255.0;
+ let sample_level = f64::from(sampled[0]) * 255.0;
+ let serialized_sample_level = (sample_level * 100.0).round() / 100.0;
+ let neutral_anchor = red.iter().find(|point| (point[0] - serialized_sample_level).abs() < 1e-5).unwrap();
+ let serialized_target_level = (target_level * 100.0).round() / 100.0;
+ assert!((neutral_anchor[1] - serialized_target_level).abs() < 1e-5, "depth={depth} anchor={neutral_anchor:?} sampled={sampled:?}");
+ assert!((neutral_anchor[0] - sample_level).abs() <= 0.0051, "depth={depth} anchor={neutral_anchor:?} sampled={}", sampled[0]);
+ if depth == 16 || depth == 32 {
+ assert!(
+ (sampled[0] * 255.0 - (sampled[0] * 255.0).round()).abs() > 0.01,
+ "depth={depth} sample was quantized to an 8-bit level: {}",
+ sampled[0]
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn ui_pointer_drives_an_armed_curves_picker() {
+ let mut app = app_with_image();
+ let id = open(&mut app, "image.adjustments.curves").unwrap();
+ arm(&mut app, id, "black");
+ let context = egui::Context::default();
+ let before = channel_points(&app, "red");
+ let (request, _receiver) = crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "move", "x": 48, "y": 8}]}));
+ let _ = crate::control::handle(&mut app, &context, &request);
+ assert_eq!(channel_points(&app, "red"), before, "pointer move does not sample");
+
+ let (request, _receiver) = crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "down", "x": 8, "y": 8}]}));
+ let _ = crate::control::handle(&mut app, &context, &request);
+ let red = channel_points(&app, "red");
+ assert!((red[0][0] - 176.0).abs() < 0.6 && red[0][1] == 0.0, "{red:?}");
+ assert_ne!(red, before, "pointer down samples");
+
+ let (request, _receiver) = crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "up", "x": 48, "y": 8}]}));
+ let _ = crate::control::handle(&mut app, &context, &request);
+ assert_eq!(channel_points(&app, "red"), red, "pointer up does not sample again");
+ assert!(picker_armed(&app));
+ }
}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 630d9f2c7..114941b6c 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -2034,9 +2034,11 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
};
if under_dialog {
- // With the Color Picker on top the image is its eyedropper, whatever the tool; Space and
- // the middle button still pan (`color_picker_ui::sample_at`).
- let picking = primary && crate::color_picker_ui::top(app).is_some();
+ // With a colour dialog picker armed the image is its eyedropper, whatever the tool; Space
+ // and the middle button still pan. Curves uses the same merged-composite sampler as the
+ // Color Picker, never the reduced adjustment preview.
+ let curves_picking = crate::adjust_dialog::picker_armed(app);
+ let picking = primary && (crate::color_picker_ui::top(app).is_some() || curves_picking);
let hand = app.ui.tool == Tool::Hand && !picking;
if let Some(d) = crate::dialogs::pan_delta(&ctx, rect, hand) {
view.center[0] -= d.x / view.zoom * if flip { -1.0 } else { 1.0 };
@@ -2052,7 +2054,11 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
}
if let Some(p) = crate::dialogs::free_press(&ctx, rect) {
let d = xf.to_doc(p);
- crate::color_picker_ui::sample_at(app, d[0], d[1]);
+ if curves_picking {
+ crate::adjust_dialog::sample_at(app, d[0], d[1]);
+ } else {
+ crate::color_picker_ui::sample_at(app, d[0], d[1]);
+ }
}
} else if primary
&& !middle
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index ce980e24b..bf877ebaa 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -559,6 +559,14 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
}
continue;
}
+ // Curves' modal eyedroppers use document coordinates here, matching the native
+ // canvas path after its ViewXform conversion. Sample on press only.
+ if !matches!(s("button"), Some("secondary" | "right")) && crate::adjust_dialog::picker_armed(app) {
+ if matches!(ev, ToolEvent::Down { .. }) {
+ crate::adjust_dialog::sample_at(app, x, y);
+ }
+ continue;
+ }
if matches!(s("button"), Some("secondary" | "right")) {
let down = matches!(ev, ToolEvent::Down { .. });
// Right-click with the Move tool, or ⌘/Ctrl+right-click: list the layers there.
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index c3c35f4a7..3b0940979 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -2172,3 +2172,9 @@ cameraRaw Color Barvy
Click a red pupil to neutralize it Klepněte na červenou zornici
open source otevřený zdrojový kód
…and {n} more …a dalších {n}
+
+ Eyedroppers: Kapátka:
+ Set Black Point Nastavit černý bod
+ Set Neutral Gray Point Nastavit neutrální šedý bod
+ Set White Point Nastavit bílý bod
+ Unavailable in this color mode V tomto barevném režimu není k dispozici
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index 4d882eae1..a53d886e2 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -2211,3 +2211,9 @@
Click a red pupil to neutralize it Klicken Sie auf eine rote Pupille
open source Open Source
…and {n} more …und {n} weitere
+
+ Eyedroppers: Pipetten:
+ Set Black Point Schwarzpunkt festlegen
+ Set Neutral Gray Point Neutralen Graupunkt festlegen
+ Set White Point Weißpunkt festlegen
+ Unavailable in this color mode In diesem Farbmodus nicht verfügbar
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 58b2bb1ff..9217a314f 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -2242,3 +2242,9 @@ cameraRaw Amount Cantidad
Click a red pupil to neutralize it Haga clic en una pupila roja para corregirla
open source código abierto
…and {n} more …y {n} más
+
+ Eyedroppers: Cuentagotas:
+ Set Black Point Definir punto negro
+ Set Neutral Gray Point Definir punto gris neutro
+ Set White Point Definir punto blanco
+ Unavailable in this color mode No disponible en este modo de color
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 72346b2a3..6b2d02605 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -2601,3 +2601,9 @@ cameraRaw Blending Fusion
Click a red pupil to neutralize it Cliquez sur une pupille rouge pour la corriger
open source code source ouvert
…and {n} more …et {n} de plus
+
+ Eyedroppers: Pipettes :
+ Set Black Point Définir le point noir
+ Set Neutral Gray Point Définir le point gris neutre
+ Set White Point Définir le point blanc
+ Unavailable in this color mode Indisponible dans ce mode colorimétrique
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 5f59cbe01..162d85350 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -2588,3 +2588,9 @@ cameraRaw Blending Pembauran
Click a red pupil to neutralize it Klik pupil merah untuk memperbaikinya
open source sumber terbuka
…and {n} more …dan {n} lagi
+
+ Eyedroppers: Eyedropper:
+ Set Black Point Atur Titik Hitam
+ Set Neutral Gray Point Atur Titik Abu-abu Netral
+ Set White Point Atur Titik Putih
+ Unavailable in this color mode Tidak tersedia dalam mode warna ini
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 196a8a4e5..828c7d38d 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -2244,3 +2244,9 @@ cameraRaw Amount Quantità
Click a red pupil to neutralize it Fai clic su una pupilla rossa per correggerla
open source open source
…and {n} more …e altri {n}
+
+ Eyedroppers: Contagocce:
+ Set Black Point Imposta punto nero
+ Set Neutral Gray Point Imposta il punto grigio neutro
+ Set White Point Imposta punto bianco
+ Unavailable in this color mode Non disponibile in questa modalità colore
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index 7f6dda6cb..8dec6a4b7 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -2155,3 +2155,9 @@ cameraRaw Color カラー
Click a red pupil to neutralize it 赤い瞳をクリックして補正します
open source オープンソース
…and {n} more …ほか {n} 件
+
+ Eyedroppers: スポイト:
+ Set Black Point 黒点を設定
+ Set Neutral Gray Point 中間調のグレーポイントを設定
+ Set White Point 白色点を設定
+ Unavailable in this color mode このカラーモードでは使用できません
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 8d85c5e60..47e89b719 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -2044,6 +2044,11 @@ cameraRaw Color 색상
# Type layer thumbnails (#598)
Edit Type 문자 편집
+ Eyedroppers: 스포이드:
+ Set Black Point 검은점 설정
+ Set Neutral Gray Point 중성 회색점 설정
+ Set White Point 흰점 설정
+ Unavailable in this color mode 이 색상 모드에서는 사용할 수 없음
# UI scale steps (#611)
75% 75%
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index 59a47c080..515b257d1 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -3207,3 +3207,8 @@ cameraRaw Roughness Chropowatość
Click a red pupil to neutralize it Kliknij czerwoną źrenicę, aby ją zneutralizować
open source otwarte oprogramowanie
…and {n} more …i {n} więcej
+ Eyedroppers: Zakraplacze:
+ Set Black Point Ustaw punkt czerni
+ Set Neutral Gray Point Ustaw punkt neutralnej szarości
+ Set White Point Ustaw punkt bieli
+ Unavailable in this color mode Niedostępne w tym trybie koloru
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index 32c8f1830..5a1d38765 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -2609,3 +2609,9 @@ cameraRaw Whites Brancos
Click a red pupil to neutralize it Clique em uma pupila vermelha para corrigi-la
open source código aberto
…and {n} more …e mais {n}
+
+ Eyedroppers: Conta-gotas:
+ Set Black Point Definir ponto preto
+ Set Neutral Gray Point Definir ponto cinza neutro
+ Set White Point Definir ponto branco
+ Unavailable in this color mode Indisponível neste modo de cor
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index e2e764fe5..2cd334d70 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -2448,3 +2448,9 @@ cameraRaw Roughness Неровность
Click a red pupil to neutralize it Щёлкните по красному зрачку, чтобы убрать блик
open source открытый исходный код
…and {n} more …и ещё {n}
+
+ Eyedroppers: Пипетки:
+ Set Black Point Задать точку чёрного
+ Set Neutral Gray Point Задать нейтральную серую точку
+ Set White Point Задать точку белого
+ Unavailable in this color mode Недоступно в этом цветовом режиме
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 3fc894b9b..e3ce1fee9 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -2180,3 +2180,9 @@ cameraRaw Blending 混合
Click a red pupil to neutralize it 单击红色瞳孔以消除反光
open source 开源
…and {n} more …以及另外 {n} 项
+
+ Eyedroppers: 吸管:
+ Set Black Point 设置黑场
+ Set Neutral Gray Point 设置中性灰场
+ Set White Point 设置白场
+ Unavailable in this color mode 此颜色模式下不可用
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 42e2909ef..bbc2e6f5d 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -2149,3 +2149,9 @@ cameraRaw Blending 混合
Click a red pupil to neutralize it 按一下紅色瞳孔以消除反光
open source 開源
…and {n} more …以及另外 {n} 項
+
+ Eyedroppers: 滴管:
+ Set Black Point 設定黑點
+ Set Neutral Gray Point 設定中性灰點
+ Set White Point 設定白點
+ Unavailable in this color mode 此色彩模式無法使用
diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rs
index 6f9b2a29f..4f3292b2d 100644
--- a/crates/ui-egui/src/input_tests.rs
+++ b/crates/ui-egui/src/input_tests.rs
@@ -259,6 +259,49 @@ fn color_picker_samples_the_image_under_its_pipette() {
assert_eq!(h.state().session.tools.foreground, [1.0, 0.0, 0.0, 1.0]);
}
+#[test]
+fn curves_picker_samples_document_coordinates_through_the_view_transform() {
+ let mut h = harness();
+ h.state_mut().run("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 300})).unwrap();
+ h.state_mut().run("edit.fill", json!({"color": "#804020"})).unwrap();
+ h.state_mut().run("select.rect", json!({"x": 200, "y": 0, "width": 200, "height": 300})).unwrap();
+ h.state_mut().run("edit.fill", json!({"color": "#20a0e0"})).unwrap();
+ h.state_mut().run("select.deselect", json!({})).unwrap();
+ let committed = h.state().session.active().unwrap().doc.clone();
+ let history = h.state().session.active().unwrap().history.past_len();
+ let view = &mut h.state_mut().ui.views[0];
+ (view.zoom, view.center, view.fit_pending) = (4.0, [200.0, 150.0], false);
+ h.state_mut().ui.view.flip_horizontal = true;
+ let dialog = crate::adjust_dialog::open(h.state_mut(), "image.adjustments.curves").unwrap();
+ h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("__curvePicker".into(), json!("black"));
+ h.run_steps(3);
+ let canvas = h.state().last_canvas_rect;
+ let left = pos2(canvas.left() + 60.0, canvas.center().y);
+ h.hover_at(left);
+ h.run_steps(1);
+ assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::None);
+ press(&mut h, left, true);
+ press(&mut h, left, false);
+ h.run_steps(3);
+ assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &committed));
+ assert_eq!(h.state().session.active().unwrap().history.past_len(), history);
+ assert!(crate::adjust_preview::display_doc(h.state_mut(), 0).is_some(), "the new curve is visible only through the preview");
+ let red = h
+ .state()
+ .ui
+ .dialogs
+ .iter()
+ .find(|candidate| candidate.id == dialog)
+ .and_then(|candidate| candidate.fields.get("red"))
+ .and_then(serde_json::Value::as_array)
+ .and_then(|points| points.first())
+ .and_then(serde_json::Value::as_array)
+ .and_then(|point| point.first())
+ .and_then(serde_json::Value::as_f64)
+ .unwrap();
+ assert!((red - 32.0).abs() < 0.6, "sampled document-right blue patch through the flipped 400% view: {red}");
+}
+
/// Type tool (#206): Alt+←/→ at a collapsed caret kerns the pair before it by 20/1000 em (100
/// with ⌘/Ctrl), one history step per press; ⌘/Ctrl+←/→ moves by word; Alt+Shift+→ extends
/// the selection by a word.
diff --git a/scorecard/ui.toml b/scorecard/ui.toml
index 9f0b1bfef..7e15fd5a2 100644
--- a/scorecard/ui.toml
+++ b/scorecard/ui.toml
@@ -106,9 +106,9 @@ note = "panels.rs:1108 plain dropdown; trash is click-only (panels.rs:1213)"
[[item]]
id = "UI-217-15"
target = "Curves: smoothing / pencil mode, black/grey/white eyedroppers, tooltips"
-status = "missing"
+status = "partial"
issue = 217
-note = "adjust_editors.rs:397 has none of them"
+note = "adjust_dialog.rs adds black/gray/white eyedroppers; smoothing and pencil modes remain missing"
[[item]]
id = "UI-217-16"