PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Red Eye tool in the J-group flyout (#1084)
Matt Van Horn869ecf3cff00
diff --git a/crates/algo/examples/bench_redeye.rs b/crates/algo/examples/bench_redeye.rsnew file mode 100644index 000000000..d98e64d13--- /dev/null+++ b/crates/algo/examples/bench_redeye.rs@@ -0,0 +1,95 @@+//! 24 MP timing of the red-eye kernel on a window around one click (not a full-image scan).+//! `cargo run --release -p photocraft-algo --example bench_redeye`+use std::time::Instant;++use photocraft_algo::redeye;++fn main() {+ let (doc_w, doc_h) = (6016usize, 4000usize);+ let click = (doc_w as i32 / 2, doc_h as i32 / 2);+ let pupil = 50.0f32;+ let radius = redeye::search_radius(pupil);+ let halo = redeye::halo_radius();+ let ext = radius.ceil() as i32 + halo;+ let x0 = click.0.saturating_sub(ext);+ let y0 = click.1.saturating_sub(ext);+ let area_w = (2 * ext + 1) as usize;+ let area_h = area_w;+ let window_px = area_w.saturating_mul(area_h);+ let doc_px = doc_w.saturating_mul(doc_h);+ if window_px == 0 || window_px > (redeye::MAX_WINDOW as usize).saturating_pow(2) {+ eprintln!("window {area_w}×{area_h} exceeds the 512² cap");+ std::process::exit(1);+ }+ if window_px >= doc_px {+ eprintln!("window {window_px} px is not smaller than the {doc_px} px document (full-image scan)");+ std::process::exit(1);+ }++ // Full 24.1 MP RGBA8 document; the kernel is given only the search window + halo.+ let mut doc = vec![0u8; doc_px.saturating_mul(4)];+ for y in 0..area_h {+ for x in 0..area_w {+ let dx = x0 + x as i32 - click.0;+ let dy = y0 + y as i32 - click.1;+ let d = (dx as f32).hypot(dy as f32);+ let gx = (x0 as usize).saturating_add(x);+ let gy = (y0 as usize).saturating_add(y);+ if gx >= doc_w || gy >= doc_h {+ continue;+ }+ let i = gy.saturating_mul(doc_w).saturating_add(gx).saturating_mul(4);+ let rgb = if d <= 1.5 {+ [255u8, 255, 255]+ } else if d <= 18.0 {+ [242, 26, 26]+ } else {+ [97, 71, 41]+ };+ if let Some(px) = doc.get_mut(i..i.saturating_add(4)) {+ px[0] = rgb[0];+ px[1] = rgb[1];+ px[2] = rgb[2];+ px[3] = 255;+ }+ }+ }++ let mut px = vec![[0.0f32; 4]; window_px];+ let origin = (x0, y0);+ for y in 0..area_h {+ for x in 0..area_w {+ let gx = (x0 as usize).saturating_add(x);+ let gy = (y0 as usize).saturating_add(y);+ let slot = match px.get_mut(y.saturating_mul(area_w).saturating_add(x)) {+ Some(s) => s,+ None => continue,+ };+ if gx >= doc_w || gy >= doc_h {+ *slot = [0.38, 0.28, 0.16, 1.0];+ continue;+ }+ let i = gy.saturating_mul(doc_w).saturating_add(gx).saturating_mul(4);+ let r = doc.get(i).copied().unwrap_or(0) as f32 / 255.0;+ let g = doc.get(i + 1).copied().unwrap_or(0) as f32 / 255.0;+ let b = doc.get(i + 2).copied().unwrap_or(0) as f32 / 255.0;+ let a = doc.get(i + 3).copied().unwrap_or(255) as f32 / 255.0;+ *slot = [r, g, b, a];+ }+ }++ let mut warm = px.clone();+ let _ = redeye::apply(&mut warm, area_w, area_h, click, origin, pupil, 50.0);++ let t = Instant::now();+ let n = redeye::apply(&mut px, area_w, area_h, click, origin, pupil, 50.0);+ let ms = t.elapsed().as_secs_f64() * 1000.0;+ println!(+ "redeye document {doc_w}×{doc_h} ({:.2} MP) window {area_w}×{area_h} (+{halo} px halo, {window_px} px) pixels {n} {ms:.3} ms",+ doc_px as f64 / 1_000_000.0+ );+ if n == 0 {+ eprintln!("expected to correct the synthetic pupil");+ std::process::exit(1);+ }+}diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rsindex 9eba8cfa3..7ef299213 100644--- a/crates/algo/src/lib.rs+++ b/crates/algo/src/lib.rs@@ -53,6 +53,7 @@ pub mod poisson;pub mod puppet;pub mod pyramid;pub mod quantize;+pub mod redeye;mod relight;mod render;pub mod render2;diff --git a/crates/algo/src/redeye.rs b/crates/algo/src/redeye.rsnew file mode 100644index 000000000..a5084c7c9--- /dev/null+++ b/crates/algo/src/redeye.rs@@ -0,0 +1,475 @@+//! Click-local red-eye correction: neutralize a red pupil around a click.+//!+//! The kernel never scans a full document. Callers pass the search window plus a+//! read halo that covers a 1 px morphological shrink and a Gaussian of σ = 0.8.++#![allow(clippy::needless_range_loop)]++/// Gaussian σ applied to the pupil mask after a 1 px shrink.+pub const SIGMA: f32 = 0.8;+/// Largest window (search + halo) the engine may allocate, in pixels on a side.+pub const MAX_WINDOW: u32 = 512;+/// Clicks one command may apply in a single history step.+pub const MAX_POINTS: usize = 64;++/// How far outside the search window the mask filter reads.+///+/// `1` (erode) + `ceil(σ × 3)` (Gaussian) + `1` (margin) — recompute if [`SIGMA`] changes.+pub fn halo_radius() -> i32 {+ let blur = (SIGMA * 3.0).ceil();+ let blur = if blur.is_finite() { blur.clamp(0.0, 64.0) as i32 } else { 3 };+ 1 + blur + 1+}++/// Search radius in document pixels for a Pupil Size in 1..=100.+pub fn search_radius(pupil_size: f32) -> f32 {+ let p = if pupil_size.is_finite() { pupil_size.clamp(1.0, 100.0) } else { 50.0 };+ (4.0 + 1.20 * p).clamp(8.0, 128.0)+}++/// Side length of the read rect (search + halo) before clamping Pupil Size to 1..=100.+///+/// `None` when `pupil_size` is non-finite or the side would overflow [`MAX_WINDOW`].+pub fn unclamped_window_side(pupil_size: f32) -> Option<u32> {+ if !pupil_size.is_finite() {+ return None;+ }+ let r = 4.0 + 1.20 * pupil_size;+ if !r.is_finite() {+ return None;+ }+ let half = r.abs() + halo_radius() as f32;+ if !half.is_finite() || half > (MAX_WINDOW as f32) {+ return None;+ }+ let side = (2.0 * half + 1.0).ceil();+ if !side.is_finite() || side > MAX_WINDOW as f32 {+ return None;+ }+ Some(side as u32)+}++fn luma(p: [f32; 4]) -> f32 {+ 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]+}++fn is_red_eye(p: [f32; 4]) -> bool {+ let (r, g, b) = (p[0], p[1], p[2]);+ if !(r.is_finite() && g.is_finite() && b.is_finite()) {+ return false;+ }+ if r <= g + 0.15 || r <= b + 0.15 {+ return false;+ }+ if luma(p) >= 0.92 {+ return false;+ }+ let max = r.max(g).max(b);+ let min = r.min(g).min(b);+ max - min >= 0.08+}++fn idx(x: usize, y: usize, w: usize) -> Option<usize> {+ y.checked_mul(w).and_then(|row| row.checked_add(x))+}++fn within_search(dx: i32, dy: i32, radius: f32) -> bool {+ let d = (dx as f32).hypot(dy as f32);+ d.is_finite() && d <= radius+}++fn nearest_seed(mask: &[bool], w: usize, h: usize, origin: (i32, i32), click: (i32, i32), radius: f32) -> Option<usize> {+ let mut best: Option<(usize, i64)> = None;+ for y in 0..h {+ for x in 0..w {+ let Some(i) = idx(x, y, w) else { continue };+ if !mask.get(i).copied().unwrap_or(false) {+ continue;+ }+ let dx = origin.0.saturating_add(x as i32).saturating_sub(click.0);+ let dy = origin.1.saturating_add(y as i32).saturating_sub(click.1);+ if !within_search(dx, dy, radius) {+ continue;+ }+ let d2 = (dx as i64).saturating_mul(dx as i64).saturating_add((dy as i64).saturating_mul(dy as i64));+ match best {+ Some((_, bd)) if d2 >= bd => {}+ _ => best = Some((i, d2)),+ }+ }+ }+ best.map(|(i, _)| i)+}++fn flood_keep(mask: &mut [bool], w: usize, h: usize, seed: usize) {+ let n = mask.len();+ if seed >= n || w == 0 {+ return;+ }+ let mut keep = vec![false; n];+ let mut stack = vec![seed];+ while let Some(i) = stack.pop() {+ let Some(slot) = keep.get_mut(i) else { continue };+ if *slot || !mask.get(i).copied().unwrap_or(false) {+ continue;+ }+ *slot = true;+ let x = i % w;+ let y = i / w;+ if x > 0 {+ stack.push(i - 1);+ }+ if x + 1 < w {+ stack.push(i + 1);+ }+ if y > 0+ && let Some(up) = i.checked_sub(w)+ {+ stack.push(up);+ }+ if y + 1 < h+ && let Some(down) = i.checked_add(w)+ {+ stack.push(down);+ }+ if stack.len() > n.saturating_mul(4) {+ break;+ }+ }+ for (m, k) in mask.iter_mut().zip(keep.iter()) {+ *m = *k;+ }+}++fn erode(mask: &[bool], w: usize, h: usize) -> Vec<bool> {+ let mut out = vec![false; mask.len()];+ for y in 0..h {+ for x in 0..w {+ let Some(i) = idx(x, y, w) else { continue };+ let mut on = true;+ for dy in -1i32..=1 {+ for dx in -1i32..=1 {+ let xx = x as i32 + dx;+ let yy = y as i32 + dy;+ if xx < 0 || yy < 0 || xx >= w as i32 || yy >= h as i32 {+ on = false;+ continue;+ }+ let Some(j) = idx(xx as usize, yy as usize, w) else {+ on = false;+ continue;+ };+ if !mask.get(j).copied().unwrap_or(false) {+ on = false;+ }+ }+ }+ if let Some(slot) = out.get_mut(i) {+ *slot = on;+ }+ }+ }+ out+}++fn blur(src: &[f32], w: usize, h: usize, sigma: f32) -> Vec<f32> {+ let n = w.saturating_mul(h);+ if w == 0 || h == 0 || src.len() < n {+ return vec![0.0; n];+ }+ if !sigma.is_finite() || sigma < 0.1 {+ return src.get(..n.min(src.len())).unwrap_or(src).to_vec();+ }+ let r = (sigma * 3.0).ceil();+ let r = if r.is_finite() { r.clamp(1.0, 32.0) as i32 } else { 3 };+ let mut k = Vec::new();+ let mut sum = 0.0f32;+ for i in -r..=r {+ let wgt = (-(i * i) as f32 / (2.0 * sigma * sigma)).exp();+ if !wgt.is_finite() {+ continue;+ }+ k.push(wgt);+ sum += wgt;+ }+ if k.is_empty() || !sum.is_finite() || sum <= 0.0 {+ return src.get(..n.min(src.len())).unwrap_or(src).to_vec();+ }+ for wgt in &mut k {+ *wgt /= sum;+ }+ let mut tmp = vec![0.0f32; n];+ let mut out = vec![0.0f32; n];+ for y in 0..h {+ for x in 0..w {+ let mut a = 0.0f32;+ for (ki, wgt) in k.iter().enumerate() {+ let xx = (x as i32 + ki as i32 - r).clamp(0, w.saturating_sub(1) as i32) as usize;+ let Some(j) = idx(xx, y, w) else { continue };+ a += src.get(j).copied().unwrap_or(0.0) * wgt;+ }+ if let Some(slot) = idx(x, y, w).and_then(|i| tmp.get_mut(i)) {+ *slot = a;+ }+ }+ }+ for y in 0..h {+ for x in 0..w {+ let mut a = 0.0f32;+ for (ki, wgt) in k.iter().enumerate() {+ let yy = (y as i32 + ki as i32 - r).clamp(0, h.saturating_sub(1) as i32) as usize;+ let Some(j) = idx(x, yy, w) else { continue };+ a += tmp.get(j).copied().unwrap_or(0.0) * wgt;+ }+ if let Some(slot) = idx(x, y, w).and_then(|i| out.get_mut(i)) {+ *slot = a;+ }+ }+ }+ out+}++/// Correct red-eye in `px` (row-major RGBA, including the [`halo_radius`] border).+///+/// `origin` is the document coordinate of `px[0]`. Returns how many pixels changed.+/// Pixels farther than [`search_radius`] from `click` are left untouched.+pub fn apply(px: &mut [[f32; 4]], w: usize, h: usize, click: (i32, i32), origin: (i32, i32), pupil_size: f32, darken: f32) -> u32 {+ let n = w.saturating_mul(h);+ if w == 0 || h == 0 || px.len() < n {+ return 0;+ }+ let radius = search_radius(pupil_size);+ let t_amt = if darken.is_finite() { (darken.clamp(0.0, 100.0) / 100.0).clamp(0.0, 1.0) } else { 0.5 };+ let mut hard = vec![false; n];+ for y in 0..h {+ for x in 0..w {+ let Some(i) = idx(x, y, w) else { continue };+ let Some(p) = px.get(i).copied() else { continue };+ let dx = origin.0.saturating_add(x as i32).saturating_sub(click.0);+ let dy = origin.1.saturating_add(y as i32).saturating_sub(click.1);+ if within_search(dx, dy, radius)+ && is_red_eye(p)+ && let Some(slot) = hard.get_mut(i)+ {+ *slot = true;+ }+ }+ }+ let Some(seed) = nearest_seed(&hard, w, h, origin, click, radius) else {+ return 0;+ };+ flood_keep(&mut hard, w, h, seed);+ let eroded = erode(&hard, w, h);+ let mut soft_in = vec![0.0f32; n];+ for (s, on) in soft_in.iter_mut().zip(eroded.iter()) {+ *s = if *on { 1.0 } else { 0.0 };+ }+ let soft = blur(&soft_in, w, h, SIGMA);+ let mut changed = 0u32;+ for y in 0..h {+ for x in 0..w {+ let Some(i) = idx(x, y, w) else { continue };+ let Some(p) = px.get_mut(i) else { continue };+ let dx = origin.0.saturating_add(x as i32).saturating_sub(click.0);+ let dy = origin.1.saturating_add(y as i32).saturating_sub(click.1);+ if !within_search(dx, dy, radius) {+ continue;+ }+ if luma(*p) >= 0.92 {+ continue;+ }+ let m = soft.get(i).copied().unwrap_or(0.0).clamp(0.0, 1.0);+ let t = m * t_amt;+ if t <= 1.0e-4 {+ continue;+ }+ let (r0, g0, b0, a0) = (p[0], p[1], p[2], p[3]);+ let neut = (g0 + b0) * 0.5;+ let r1 = r0 + (neut - r0) * t;+ let scale = 1.0 - 0.45 * t;+ let (r2, g2, b2) = (r1 * scale, g0 * scale, b0 * scale);+ if [r2, g2, b2].iter().any(|c| !c.is_finite()) {+ continue;+ }+ if (r2 - r0).abs() < 1.0e-6 && (g2 - g0).abs() < 1.0e-6 && (b2 - b0).abs() < 1.0e-6 {+ continue;+ }+ *p = [r2, g2, b2, a0];+ changed = changed.saturating_add(1);+ }+ }+ changed+}++#[cfg(test)]+mod tests {+ use super::*;++ fn sample(w: usize, h: usize, f: impl Fn(usize, usize) -> [f32; 4]) -> Vec<[f32; 4]> {+ let mut px = vec![[0.0; 4]; w * h];+ for y in 0..h {+ for x in 0..w {+ if let Some(slot) = px.get_mut(y * w + x) {+ *slot = f(x, y);+ }+ }+ }+ px+ }++ fn disc(x: usize, y: usize, cx: f32, cy: f32, r: f32) -> bool {+ (x as f32 - cx).hypot(y as f32 - cy) <= r+ }++ fn portrait_pixel(x: usize, y: usize) -> [f32; 4] {+ // Brown that fails R > G+0.15 so the iris is never in the red-eye mask.+ let iris = [0.38, 0.28, 0.16, 1.0];+ let red = [0.95, 0.10, 0.10, 1.0];+ let white = [1.0, 1.0, 1.0, 1.0];+ if disc(x, y, 16.0, 16.0, 1.2) {+ white+ } else if disc(x, y, 16.0, 16.0, 10.0) {+ red+ } else {+ iris+ }+ }++ #[test]+ fn halo_covers_erode_and_blur_reach() {+ let want = 1 + (SIGMA * 3.0).ceil() as i32 + 1;+ assert_eq!(halo_radius(), want);+ assert_eq!(halo_radius(), 5);+ assert_eq!(search_radius(50.0), 64.0);+ assert_eq!(search_radius(0.0), 8.0);+ assert_eq!(search_radius(101.0), search_radius(100.0));+ assert!(unclamped_window_side(50.0).is_some_and(|s| s < MAX_WINDOW));+ assert!(unclamped_window_side(10_000.0).is_none());+ assert!(unclamped_window_side(f32::NAN).is_none());+ }++ #[test]+ fn red_disc_is_neutralized_and_iris_is_left_alone() {+ let w = 32usize;+ let mut px = sample(w, w, portrait_pixel);+ let iris_before = px[2 * w + 2];+ let n = apply(&mut px, w, w, (16, 16), (0, 0), 50.0, 100.0);+ assert!(n > 0, "corrected {n} pixels");+ // 5 px from the centre: in the red ring, outside the catchlight, inside the eroded mask.+ let after = px[11 * w + 16];+ let neut = (0.10 + 0.10) / 2.0;+ assert!((after[0] - after[1]).abs() < 0.08 && (after[0] - after[2]).abs() < 0.08, "red no longer dominates: {after:?}");+ assert!((after[0] - neut * 0.55).abs() < 0.08, "R ≈ (G+B)/2 then darkened: {after:?}");+ assert!(luma(after) < luma([0.95, 0.10, 0.10, 1.0]) - 0.05, "pupil darkened");+ let iris_after = px[2 * w + 2];+ for c in 0..4 {+ assert!((iris_after[c] - iris_before[c]).abs() < 1e-5, "iris {iris_after:?} vs {iris_before:?}");+ }+ let catch = px[16 * w + 16];+ assert!(catch[0] >= 0.9 && catch[1] >= 0.9 && catch[2] >= 0.9, "catchlight {catch:?}");+ }++ #[test]+ fn gray_pixels_are_not_treated_as_red_eye() {+ let w = 16usize;+ let mut px = sample(w, w, |_, _| [0.4, 0.4, 0.4, 1.0]);+ let n = apply(&mut px, w, w, (8, 8), (0, 0), 50.0, 50.0);+ assert_eq!(n, 0);+ assert_eq!(px[8 * w + 8], [0.4, 0.4, 0.4, 1.0]);+ }++ #[allow(clippy::too_many_arguments)]+ fn apply_tiled(src: &[[f32; 4]], w: usize, h: usize, click: (i32, i32), pupil: f32, darken: f32, tile: usize, halo: i32) -> Vec<[f32; 4]> {+ let mut out = src.to_vec();+ let halo = halo.max(0) as usize;+ let mut y0 = 0;+ while y0 < h {+ let mut x0 = 0;+ while x0 < w {+ let x1 = (x0 + tile).min(w);+ let y1 = (y0 + tile).min(h);+ let rx0 = x0.saturating_sub(halo);+ let ry0 = y0.saturating_sub(halo);+ let rx1 = (x1 + halo).min(w);+ let ry1 = (y1 + halo).min(h);+ let bw = rx1 - rx0;+ let bh = ry1 - ry0;+ let mut buf = vec![[0.0; 4]; bw * bh];+ for yy in 0..bh {+ for xx in 0..bw {+ let s = (ry0 + yy) * w + (rx0 + xx);+ if let Some(slot) = buf.get_mut(yy * bw + xx) {+ *slot = src.get(s).copied().unwrap_or([0.0; 4]);+ }+ }+ }+ apply(&mut buf, bw, bh, click, (rx0 as i32, ry0 as i32), pupil, darken);+ for yy in y0..y1 {+ for xx in x0..x1 {+ let b = (yy - ry0) * bw + (xx - rx0);+ if let Some(slot) = out.get_mut(yy * w + xx) {+ *slot = buf.get(b).copied().unwrap_or(*slot);+ }+ }+ }+ x0 += tile;+ }+ y0 += tile;+ }+ out+ }++ fn max_neighbour_jump(px: &[[f32; 4]], w: usize, h: usize, x: usize) -> f32 {+ let mut m = 0.0f32;+ if x == 0 || x >= w {+ return 0.0;+ }+ for y in 0..h {+ let Some(a) = px.get(y * w + (x - 1)) else { continue };+ let Some(b) = px.get(y * w + x) else { continue };+ let d = (a[0] - b[0]).abs().max((a[1] - b[1]).abs()).max((a[2] - b[2]).abs());+ if d > m {+ m = d;+ }+ }+ m+ }++ #[test]+ fn tile_seam_matches_an_untiled_reference() {+ let w = 128usize;+ // A red half-plane ending on the 64 px tile boundary: the mask edge is where a short halo fails.+ let src = sample(w, w, |x, _y| if x < 64 { [0.95, 0.10, 0.10, 1.0] } else { [0.38, 0.28, 0.16, 1.0] });+ let mut reference = src.clone();+ apply(&mut reference, w, w, (60, 64), (0, 0), 50.0, 50.0);+ let tiled = apply_tiled(&src, w, w, (60, 64), 50.0, 50.0, 64, halo_radius());+ let mut err = 0.0f32;+ for (a, b) in reference.iter().zip(tiled.iter()) {+ for c in 0..3 {+ err = err.max((a[c] - b[c]).abs());+ }+ }+ assert!(err < 1e-4, "tiled vs reference max err {err}");+ let jump_ref = max_neighbour_jump(&reference, w, w, 64);+ let jump_tiled = max_neighbour_jump(&tiled, w, w, 64);+ assert!((jump_ref - jump_tiled).abs() < 1e-4, "seam jump {jump_tiled} vs {jump_ref}");++ // Reach is erode (1) + ceil(σ×3) (3). A 1 px halo cannot cover that; the documented halo can.+ let short = apply_tiled(&src, w, w, (60, 64), 50.0, 50.0, 64, 1);+ let mut short_err = 0.0f32;+ for (a, b) in reference.iter().zip(short.iter()) {+ for c in 0..3 {+ short_err = short_err.max((a[c] - b[c]).abs());+ }+ }+ assert!(short_err > err + 1e-4, "a halo smaller than the blur reach must diverge (short {short_err}, full {err})");+ }++ #[test]+ fn empty_or_mismatched_buffer_changes_nothing() {+ let mut px: Vec<[f32; 4]> = Vec::new();+ assert_eq!(apply(&mut px, 0, 0, (0, 0), (0, 0), 50.0, 50.0), 0);+ let mut tiny = vec![[0.95, 0.1, 0.1, 1.0]; 4];+ assert_eq!(apply(&mut tiny, 8, 8, (1, 1), (0, 0), 50.0, 50.0), 0);+ }+}diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rsindex 8687d4dcb..014a78aa9 100644--- a/crates/engine/src/channel_cmds.rs+++ b/crates/engine/src/channel_cmds.rs@@ -577,6 +577,7 @@ fn routed(id: &str) -> bool {| "paint.sharpen"| "paint.smudge"| "paint.historyBrush"+ | "paint.redEye")}diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex d0677219e..d3beb6dbd 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -1009,6 +1009,7 @@ fn build() -> Vec<CommandSpec> {v.extend(crate::eraser_cmds::specs());v.extend(crate::preset_import_cmds::specs());v.extend(crate::retouch_cmds::specs());+ v.extend(crate::redeye_cmds::specs());v.extend(crate::image_cmds::specs());v.extend(crate::selection_cmds::specs());v.extend(crate::magnetic_cmds::specs());diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex d7b93a52e..b3b94c564 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -70,6 +70,7 @@ pub mod preset_store;pub mod presets;pub mod print_cmds;pub mod proof_sim;+pub mod redeye_cmds;pub mod render_cmds;pub mod retouch_cmds;pub mod select_extra_cmds;diff --git a/crates/engine/src/redeye_cmds.rs b/crates/engine/src/redeye_cmds.rsnew file mode 100644index 000000000..f6a71da40--- /dev/null+++ b/crates/engine/src/redeye_cmds.rs@@ -0,0 +1,447 @@+//! Red Eye tool: click a pupil to neutralize the flash reflection.+//!+//! Toolbar-only (`paint.redEye`, empty menu path). The kernel in `photocraft-algo::redeye`+//! runs on a window around each click plus the mask-filter halo.++use photocraft_algo::redeye::{self, MAX_POINTS, MAX_WINDOW};+use photocraft_doc::LayerId;+use photocraft_geom::Rect;+use photocraft_raster::{Surface, from_rgba_into};+use serde_json::{Value, json};++use crate::commands::CommandSpec;+use crate::{EngineError, Result, Session};++const CMD: &str = "paint.redEye";+const MISS: &str = "no red-eye pixels near the click";++fn bad(msg: impl Into<String>) -> EngineError {+ EngineError::BadParams { cmd: CMD.into(), msg: msg.into() }+}++fn num(p: &Value, key: &str, default: f32) -> Result<f32> {+ match p.get(key) {+ None => Ok(default),+ Some(v) => v.as_f64().filter(|x| x.is_finite()).map(|x| x as f32).ok_or_else(|| bad(format!("`{key}` must be a finite number (got {v})"))),+ }+}++fn coord(v: &Value) -> Option<f64> {+ v.as_f64().filter(|x| x.is_finite())+}++fn pixel(x: f64, y: f64) -> Result<(i32, i32)> {+ if !x.is_finite() || !y.is_finite() {+ return Err(bad("click coordinates must be finite"));+ }+ let clamp = |v: f64| v.clamp(i32::MIN as f64, i32::MAX as f64).floor() as i32;+ Ok((clamp(x), clamp(y)))+}++/// One click, or a batch of clicks, as document pixels.+fn clicks(p: &Value) -> Result<Vec<(i32, i32)>> {+ if let Some(arr) = p.get("points").and_then(Value::as_array) {+ if arr.is_empty() {+ return Err(bad("`points` is empty"));+ }+ if arr.len() > MAX_POINTS {+ return Err(bad(format!("at most {MAX_POINTS} points")));+ }+ return arr+ .iter()+ .map(|q| match q.as_array().map(Vec::as_slice) {+ Some([x, y]) => match (coord(x), coord(y)) {+ (Some(x), Some(y)) => pixel(x, y),+ _ => Err(bad(format!("bad point {q} (want [x, y])"))),+ },+ _ => Err(bad(format!("bad point {q} (want [x, y])"))),+ })+ .collect();+ }+ match (p.get("x").and_then(coord), p.get("y").and_then(coord)) {+ (Some(x), Some(y)) => Ok(vec![pixel(x, y)?]),+ (None, None) if p.get("x").is_none() && p.get("y").is_none() => Err(bad("missing `x`,`y` or `points`")),+ _ => Err(bad("`x` and `y` must be finite numbers")),+ }+}++fn read_rect(cx: i32, cy: i32, radius: f32) -> Result<Rect> {+ let r = if radius.is_finite() { radius.ceil().clamp(0.0, 256.0) as i32 } else { 64 };+ let halo = redeye::halo_radius();+ let ext = r.saturating_add(halo);+ let area = Rect::new(cx.saturating_sub(ext), cy.saturating_sub(ext), cx.saturating_add(ext).saturating_add(1), cy.saturating_add(ext).saturating_add(1));+ let w = area.width() as u64;+ let h = area.height() as u64;+ let cap = MAX_WINDOW as u64;+ if area.is_empty() || w.saturating_mul(h) > cap.saturating_mul(cap) {+ return Err(bad(format!("pupil window is larger than {MAX_WINDOW}² px")));+ }+ Ok(area)+}++fn rgba_region(surf: &Surface, area: Rect) -> Vec<[f32; 4]> {+ let n = (area.width() as usize).saturating_mul(area.height() as usize);+ let mut v = vec![[0.0f32; 4]; n];+ if !area.is_empty() && v.len() == n {+ surf.read_rgba_into(area, &mut v);+ }+ v+}++/// Write back only the pixels whose RGBA changed. Untouched pixels keep their original channel+/// data, so CMYK (K) and Lab values outside the corrected pupil are never re-encoded.+fn write_rgba(surf: &mut Surface, area: Rect, before: &[[f32; 4]], px: &[[f32; 4]]) {+ if area.is_empty() {+ return;+ }+ let fmt = surf.format();+ let n = fmt.channels();+ let w = area.width() as usize;+ let h = area.height() as usize;+ let need = w.saturating_mul(h);+ let expect = need.saturating_mul(n);+ if px.len() < need || before.len() < need || n == 0 || expect / n != need {+ return;+ }+ let mut data = surf.read_region(area);+ if data.len() != expect {+ return;+ }+ for i in 0..need {+ let (Some(q), Some(o)) = (px.get(i), before.get(i)) else { continue };+ if !rgb_changed(o, q) {+ continue;+ }+ let Some(out) = data.get_mut(i.saturating_mul(n)..i.saturating_mul(n).saturating_add(n)) else { continue };+ let alpha = out.last().copied();+ from_rgba_into(&fmt, *q, out);+ if fmt.alpha+ && let (Some(dst), Some(src)) = (out.last_mut(), alpha)+ {+ *dst = src;+ }+ }+ surf.write_region(area, &data);+}++fn rgb_changed(a: &[f32; 4], b: &[f32; 4]) -> bool {+ (a[0] - b[0]).abs() > 1e-5 || (a[1] - b[1]).abs() > 1e-5 || (a[2] - b[2]).abs() > 1e-5+}++fn mix_selection(orig: &[[f32; 4]], px: &mut [[f32; 4]], area: Rect, sel: &Surface) {+ let w = area.width() as usize;+ if w == 0 {+ return;+ }+ let n = px.len().min(orig.len());+ for i in 0..n {+ let y = i / w;+ let x = i % w;+ let k = sel.sample_channel(area.x0.saturating_add(x as i32), area.y0.saturating_add(y as i32), 0).clamp(0.0, 1.0);+ if k >= 1.0 {+ continue;+ }+ let Some(o) = orig.get(i) else { continue };+ let Some(p) = px.get_mut(i) else { continue };+ if k <= 0.0 {+ *p = *o;+ continue;+ }+ p[0] = o[0] + (p[0] - o[0]) * k;+ p[1] = o[1] + (p[1] - o[1]) * k;+ p[2] = o[2] + (p[2] - o[2]) * k;+ p[3] = o[3];+ }+}++fn restore_locked(orig: &[[f32; 4]], px: &mut [[f32; 4]]) {+ let n = px.len().min(orig.len());+ for i in 0..n {+ let Some(o) = orig.get(i) else { continue };+ if o[3] > 1.0e-5 {+ continue;+ }+ if let Some(p) = px.get_mut(i) {+ *p = *o;+ }+ }+}++fn count_changed(orig: &[[f32; 4]], px: &[[f32; 4]]) -> u32 {+ let n = orig.iter().zip(px.iter()).filter(|(a, b)| rgb_changed(a, b)).count();+ u32::try_from(n).unwrap_or(u32::MAX)+}++fn apply_click(surf: &mut Surface, sel: Option<&Surface>, lock: bool, click: (i32, i32), pupil: f32, darken: f32, clip: Rect) -> Result<(Rect, u32)> {+ let area = read_rect(click.0, click.1, redeye::search_radius(pupil))?.intersect(&clip);+ if area.is_empty() {+ return Ok((Rect::EMPTY, 0));+ }+ let w = area.width() as usize;+ let h = area.height() as usize;+ let mut px = rgba_region(surf, area);+ let orig = px.clone();+ let n = redeye::apply(&mut px, w, h, click, (area.x0, area.y0), pupil, darken);+ if n == 0 {+ return Ok((area, 0));+ }+ if let Some(sel) = sel {+ mix_selection(&orig, &mut px, area, sel);+ }+ if lock {+ restore_locked(&orig, &mut px);+ }+ let changed = count_changed(&orig, &px);+ if changed == 0 {+ return Ok((area, 0));+ }+ write_rgba(surf, area, &orig, &px);+ Ok((area, changed))+}++fn enabled(s: &Session) -> std::result::Result<(), String> {+ crate::commands::has_paintable(s)?;+ if crate::channel_cmds::edits_channel(s) {+ return Ok(());+ }+ let d = s.active().ok_or("no document open")?;+ let id = d.active_layer.ok_or("no active layer")?;+ let locks = d.doc.effective_locks(id);+ if locks.pixels || locks.all {+ let name = d.doc.layer(id).map(|l| l.name.as_str()).unwrap_or("layer");+ return Err(format!("the layer \"{name}\" is locked"));+ }+ Ok(())+}++fn red_eye(s: &mut Session, p: &Value) -> Result<Value> {+ let pts = clicks(p)?;+ let pupil_raw = num(p, "pupilSize", 50.0)?;+ let darken = num(p, "darken", 50.0)?;+ if redeye::unclamped_window_side(pupil_raw).is_none() {+ return Err(bad(format!("pupil window is larger than {MAX_WINDOW}² px")));+ }+ let pupil = pupil_raw.clamp(1.0, 100.0);+ let darken = darken.clamp(0.0, 100.0);+ let id = match p.get("layer").and_then(Value::as_u64) {+ Some(id) => Some(LayerId(id)),+ None => s.active().and_then(|d| d.active_layer),+ };+ let (damage, total) = s.edit("Red Eye", |doc, active| {+ let canvas = doc.bounds();+ let sel = doc.selection.clone();+ let (surf, lock) = crate::channel_cmds::target_surface(doc, id.or(*active), p)?;+ let mut total = 0u32;+ let mut damage = Rect::EMPTY;+ for click in &pts {+ let (area, n) = apply_click(surf, sel.as_ref(), lock, *click, pupil, darken, canvas)?;+ total = total.saturating_add(n);+ damage = if damage.is_empty() { area } else { damage.union(&area) };+ }+ if total == 0 {+ return Err(EngineError::Other(MISS.into()));+ }+ Ok((damage, total))+ })?;+ if let Some(st) = s.active_mut() {+ st.last_damage = Some(damage);+ }+ Ok(json!({ "damage": [damage.x0, damage.y0, damage.width(), damage.height()], "pixels": total }))+}++/// Red Eye command specs.+pub fn specs() -> Vec<CommandSpec> {+ vec![CommandSpec {+ id: CMD,+ label: "Red Eye",+ menu: &[],+ shortcut: None,+ params: r#"{"x":px, "y":px} | {"points":[[x,y],…] (at most 64)},"pupilSize":1..100=50,"darken":0..100=50,"layer":id?=active,"target":"pixels"|"mask"|"quickMask"|{"channel":i} → {"damage":[x,y,w,h], "pixels":n}"#,+ enabled,+ run: red_eye,+ journal: true,+ }]+}++#[cfg(test)]+mod tests {+ use super::*;+ use photocraft_color::ColorMode;+ use serde_json::json;++ const DEPTHS: [u64; 3] = [8, 16, 32];++ fn session(w: u32, h: u32, depth: u64, mode: &str) -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": w, "height": h, "depth": depth, "mode": mode})).unwrap();+ s+ }++ fn rgba(s: &Session, x: i32, y: i32) -> [f32; 4] {+ let d = s.active().unwrap();+ d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)+ }++ fn paint_layer(s: &mut Session, f: impl Fn(i32, i32) -> [f32; 4]) {+ s.edit("setup", |doc, active| {+ let b = doc.bounds();+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();+ let fmt = surf.format();+ let mut data = Vec::new();+ for y in b.y0..b.y1 {+ for x in b.x0..b.x1 {+ data.extend(photocraft_raster::from_rgba(&fmt, f(x, y)));+ }+ }+ surf.write_region(b, &data);+ Ok(())+ })+ .unwrap();+ }++ fn red_disc(cx: i32, cy: i32, r: i32) -> impl Fn(i32, i32) -> [f32; 4] {+ move |x, y| {+ let dx = (x - cx) as f32;+ let dy = (y - cy) as f32;+ if dx.hypot(dy) <= 1.2 {+ [1.0, 1.0, 1.0, 1.0]+ } else if dx.hypot(dy) <= r as f32 {+ [0.95, 0.10, 0.10, 1.0]+ } else {+ [0.38, 0.28, 0.16, 1.0]+ }+ }+ }++ #[test]+ fn red_eye_corrects_a_disc_at_every_depth_and_undoes() {+ for depth in DEPTHS {+ let mut s = session(64, 64, depth, "rgb");+ paint_layer(&mut s, red_disc(32, 32, 8));+ let before = rgba(&s, 32, 26);+ assert!(before[0] > 0.8, "setup {before:?}");+ let r = s.execute("paint.redEye", json!({"x": 32, "y": 32})).unwrap();+ assert!(r["pixels"].as_u64().unwrap() > 0, "{r}");+ let after = rgba(&s, 32, 26);+ assert!(after[0] < before[0] - 0.2, "depth {depth}: {after:?} vs {before:?}");+ let catch = rgba(&s, 32, 32);+ assert!(catch[0] >= 0.9 && catch[1] >= 0.9, "catchlight {catch:?}");+ assert!(s.undo());+ let restored = rgba(&s, 32, 26);+ for c in 0..3 {+ assert!((restored[c] - before[c]).abs() < 0.02, "undo depth {depth}");+ }+ assert!(s.redo());+ let redone = rgba(&s, 32, 26);+ for c in 0..3 {+ assert!((redone[c] - after[c]).abs() < 0.02, "redo depth {depth}");+ }+ }+ }++ #[test]+ fn miss_and_bad_params_are_errors() {+ let mut s = session(32, 32, 8, "rgb");+ paint_layer(&mut s, |_, _| [0.1, 0.2, 0.8, 1.0]);+ let err = s.execute("paint.redEye", json!({"x": 16, "y": 16})).unwrap_err().to_string();+ assert!(err.contains(MISS), "{err}");+ assert!(s.execute("paint.redEye", json!({})).is_err());+ assert!(s.execute("paint.redEye", json!({"x": null, "y": 1})).is_err());+ let pts: Vec<[i32; 2]> = (0..65).map(|i| [i, 0]).collect();+ assert!(s.execute("paint.redEye", json!({"points": pts})).is_err());+ assert!(s.execute("paint.redEye", json!({"x": "nope", "y": 1})).is_err());+ assert!(s.execute("paint.redEye", json!({"points": []})).is_err());+ let huge = s.execute("paint.redEye", json!({"x": 8, "y": 8, "pupilSize": 10_000.0}));+ assert!(huge.unwrap_err().to_string().contains("512"), "window cap");+ s.execute("paint.redEye", json!({"x": 8, "y": 8, "pupilSize": 0})).ok();+ s.execute("paint.redEye", json!({"x": 8, "y": 8, "pupilSize": 101})).ok();+ let mut s = session(64, 64, 8, "rgb");+ paint_layer(&mut s, red_disc(32, 32, 8));+ assert!(s.execute("paint.redEye", json!({"x": 32, "y": 32, "pupilSize": 0})).is_ok(), "pupilSize 0 clamps");+ assert!(s.undo());+ assert!(s.execute("paint.redEye", json!({"x": 32, "y": 32, "pupilSize": 101})).is_ok(), "pupilSize 101 clamps");+ }++ #[test]+ fn disabled_without_a_paintable_target() {+ let s = Session::new();+ assert!(!s.is_enabled("paint.redEye"));+ let mut s = session(32, 32, 8, "rgb");+ assert!(s.is_enabled("paint.redEye"));+ s.execute("layer.setProps", json!({"locks": {"pixels": true}})).unwrap();+ assert!(!s.is_enabled("paint.redEye"), "locked pixels disable the tool");+ let err = s.execute("paint.redEye", json!({"x": 8, "y": 8})).unwrap_err().to_string();+ assert!(err.to_ascii_lowercase().contains("locked"), "{err}");+ let mut s = session(64, 64, 8, "rgb");+ s.execute("type.create", json!({"x": 8, "y": 24, "text": "Hi", "size": 12})).unwrap();+ assert!(!s.is_enabled("paint.redEye"));+ assert!(s.execute("paint.redEye", json!({"x": 8, "y": 8})).is_err());+ }++ #[test]+ fn several_points_are_one_history_step() {+ let mut s = session(80, 40, 8, "rgb");+ paint_layer(&mut s, |x, y| {+ if ((x - 20).abs() <= 6 && (y - 20).abs() <= 6) || ((x - 60).abs() <= 6 && (y - 20).abs() <= 6) {+ [0.95, 0.1, 0.1, 1.0]+ } else {+ [0.2, 0.2, 0.2, 1.0]+ }+ });+ let past = s.active().unwrap().history.past_len();+ s.execute("paint.redEye", json!({"points": [[20, 20], [60, 20]]})).unwrap();+ assert_eq!(s.active().unwrap().history.past_len(), past + 1);+ assert!(rgba(&s, 20, 20)[0] < 0.7);+ assert!(rgba(&s, 60, 20)[0] < 0.7);+ }++ #[test]+ fn cmyk_document_keeps_untouched_pixels_bit_exact() {+ let mut s = session(64, 64, 8, "cmyk");+ assert_eq!(s.active().unwrap().doc.pixel_format().mode, ColorMode::Cmyk);+ // Rich black (all four inks) around the eye: a naive RGBA round trip regenerates K.+ let disc = red_disc(32, 32, 8);+ s.edit("setup", |doc, active| {+ let b = doc.bounds();+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();+ let fmt = surf.format();+ let n = fmt.channels();+ let mut data = Vec::new();+ for y in b.y0..b.y1 {+ for x in b.x0..b.x1 {+ if (x - 32).abs() <= 10 && (y - 32).abs() <= 10 {+ data.extend(photocraft_raster::from_rgba(&fmt, disc(x, y)));+ } else {+ let mut px = vec![0.6f32, 0.5, 0.5, 0.7];+ px.resize(n, 1.0);+ data.extend(px);+ }+ }+ }+ surf.write_region(b, &data);+ Ok(())+ })+ .unwrap();+ let raw = |s: &Session, x: i32, y: i32| {+ let d = s.active().unwrap();+ let surf = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap();+ surf.read_region(Rect::new(x, y, x + 1, y + 1))+ };+ let probes = [(32, 18), (2, 2), (50, 40)];+ let before: Vec<Vec<f32>> = probes.iter().map(|&(x, y)| raw(&s, x, y)).collect();+ let r = s.execute("paint.redEye", json!({"x": 32, "y": 32})).unwrap();+ assert!(r["pixels"].as_u64().unwrap() > 0, "{r}");+ for (&(x, y), b) in probes.iter().zip(&before) {+ assert_eq!(&raw(&s, x, y), b, "untouched CMYK pixel ({x},{y}) inside the window changed");+ }+ assert!(rgba(&s, 32, 26)[0] < 0.7, "pupil corrected");+ }++ #[test]+ fn gray_document_misses() {+ let mut s = session(24, 24, 16, "gray");+ paint_layer(&mut s, |_, _| [0.5, 0.5, 0.5, 1.0]);+ assert_eq!(s.active().unwrap().doc.pixel_format().mode, ColorMode::Grayscale);+ assert!(s.execute("paint.redEye", json!({"x": 12, "y": 12})).is_err());+ }+}diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 185780cf1..82817136e 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -2389,6 +2389,18 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:}Tool::Type | Tool::VerticalType => egui::CursorIcon::Text,Tool::MagneticLasso => crate::magnetic_lasso_ui::cursor(app, &painter, p, view.zoom),+ Tool::RedEye => {+ let pupil = app.ui.tool_options.red_eye_pupil_size.clamp(1.0, 100.0);+ let r_doc = photocraft_algo::redeye::search_radius(pupil);+ let r = (r_doc * view.zoom).max(2.0);+ painter.circle_stroke(p, r + 0.5, Stroke::new(1.0, Color32::from_black_alpha(140)));+ painter.circle_stroke(p, r, Stroke::new(1.0, Color32::from_white_alpha(220)));+ for (w, c) in [(2.5, Color32::from_black_alpha(140)), (1.0, Color32::from_white_alpha(220))] {+ painter.line_segment([p - vec2(3.0, 0.0), p + vec2(3.0, 0.0)], Stroke::new(w, c));+ painter.line_segment([p - vec2(0.0, 3.0), p + vec2(0.0, 3.0)], Stroke::new(w, c));+ }+ egui::CursorIcon::None+ }_ => egui::CursorIcon::Crosshair,};let icon = visible_crosshair(icon, &painter, p, cfg!(target_os = "windows"));@@ -2958,6 +2970,20 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)let _ = app.run("paint.bucket", json!({"x": x.floor(), "y": y.floor(), "tolerance": o.tolerance, "contiguous": o.contiguous, "antiAlias": o.anti_alias, "opacity": o.fill_opacity, "contents": contents, "target": paint_target(app)}));return;}+ Tool::RedEye => {+ let o = app.ui.tool_options.clone();+ let _ = app.run(+ "paint.redEye",+ json!({+ "x": x.floor(),+ "y": y.floor(),+ "pupilSize": o.red_eye_pupil_size.clamp(1.0, 100.0),+ "darken": o.red_eye_darken.clamp(0.0, 100.0),+ "target": paint_target(app),+ }),+ );+ return;+ }Tool::PolygonLasso => {polygon_click(app, x, y, mods);return;diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex f4597bd3e..bf614d320 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -2112,6 +2112,7 @@ cameraRaw Color BarvyFrequency FrekvenceUse tablet pressure to change pen width Měnit šířku pera přítlakem tabletu+# About ▸ Contributors / Models (credits, craftrules standards/contributors.md)About O aplikaciContributors Přispěvatelé@@ -2159,3 +2160,9 @@ cameraRaw Color BarvyDomed KopuleDomed (Inverted) Kopule (obrácená)Diagonal (Descending) Diagonála (sestupná)++ Red Eye Tool Nástroj červené oči+ Red Eye Červené oči+ Pupil Size Velikost zornice+ Darken Amount Míra ztmavení+ Click a red pupil to neutralize it Klepněte na červenou zornicidiff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex 8feac1dc5..e33e26dcd 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2152,6 +2152,7 @@Magnetic Lasso Tool Magnetisches-Lasso-WerkzeugFrequency FrequenzUse tablet pressure to change pen width Tablettdruck zum Ändern der Stiftbreite verwenden+# About ▸ Contributors / Models (credits, craftrules standards/contributors.md)About ÜberContributors Mitwirkende@@ -2197,3 +2198,9 @@Domed GewölbtDomed (Inverted) Gewölbt (umgekehrt)Diagonal (Descending) Diagonal (absteigend)++ Red Eye Tool Rote-Augen-Werkzeug+ Red Eye Rote Augen+ Pupil Size Pupillengröße+ Darken Amount Abdunklungsgrad+ Click a red pupil to neutralize it Klicken Sie auf eine rote Pupillediff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex 0c70eab9b..486b0fed0 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2184,6 +2184,7 @@ cameraRaw Amount CantidadFrequency FrecuenciaUse tablet pressure to change pen width Usar la presión de la tableta para cambiar la anchura del lápiz+# About ▸ Contributors / Models (credits, craftrules standards/contributors.md)About Acerca deContributors Colaboradores@@ -2229,3 +2230,9 @@ cameraRaw Amount CantidadDomed AbovedadoDomed (Inverted) Abovedado (invertido)Diagonal (Descending) Diagonal (descendente)++ Red Eye Tool Herramienta Ojos rojos+ Red Eye Ojos rojos+ Pupil Size Tamaño de pupila+ Darken Amount Cantidad de oscurecimiento+ Click a red pupil to neutralize it Haga clic en una pupila roja para corregirladiff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex 7b9737bb8..825aeeaf9 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -2544,6 +2544,7 @@ cameraRaw Blending FusionFrequency FréquenceUse tablet pressure to change pen width Utiliser la pression de la tablette pour modifier la largeur de la plume+# About ▸ Contributors / Models (credits, craftrules standards/contributors.md)About À proposContributors Contributeurs@@ -2589,3 +2590,8 @@ cameraRaw Blending FusionDomed BombéDomed (Inverted) Bombé (inversé)Diagonal (Descending) Diagonale (descendante)++ Red Eye Tool Outil Yeux rouges+ Pupil Size Taille de la pupille+ Darken Amount Quantité d'assombrissement+ Click a red pupil to neutralize it Cliquez sur une pupille rouge pour la corrigerdiff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex a3ab716b7..329e252ea 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -2531,6 +2531,7 @@ cameraRaw Blending PembauranFrequency FrekuensiUse tablet pressure to change pen width Gunakan tekanan tablet untuk mengubah lebar pena+# About ▸ Contributors / Models (credits, craftrules standards/contributors.md)About TentangContributors Kontributor@@ -2576,3 +2577,8 @@ cameraRaw Blending PembauranDomed KubahDomed (Inverted) Kubah (Terbalik)Diagonal (Descending) Diagonal (Menurun)++ Red Eye Tool Alat Mata Merah+ Pupil Size Ukuran pupil+ Darken Amount Jumlah penggelapan+ Click a red pupil to neutralize it Klik pupil merah untuk memperbaikinyadiff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex 596d40566..1ee435056 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -2185,6 +2185,7 @@ cameraRaw Amount QuantitàFrequency FrequenzaUse tablet pressure to change pen width Usa pressione tavoletta per cambiare la larghezza della penna+# About ▸ Contributors / Models (credits, craftrules standards/contributors.md)About InformazioniContributors Collaboratori@@ -2216,6 +2217,7 @@ cameraRaw Amount Quantità% of all commits % di tutti i commitLines +/− Righe +/−@{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: {prs} PR, {commits} commit, +{added} / −{deleted} righe (Δ {delta}), +{binAdded} / −{binDeleted} risorse binarie, {first} – {last}+Convert to Layers Converti in livelliApply At Canvas Bounds Applica effetto ai limiti dell’area di lavoro@@ -2231,3 +2233,8 @@ cameraRaw Amount QuantitàDomed BombatoDomed (Inverted) Bombato (invertito)Diagonal (Descending) Diagonale (discendente)+ Red Eye Tool Strumento Occhi rossi+ Red Eye Occhi rossi+ Pupil Size Dimensione pupilla+ Darken Amount Quantità di scurimento+ Click a red pupil to neutralize it Fai clic su una pupilla rossa per correggerladiff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex cfa9c71be..c8f1b7987 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -2095,6 +2095,7 @@ cameraRaw Color カラーFrequency 頻度Use tablet pressure to change pen width タブレットの筆圧を使用してペンの幅を変更+# About ▸ Contributors / Models (credits, craftrules standards/contributors.md)About バージョン情報Contributors コントリビューター@@ -2142,3 +2143,9 @@ cameraRaw Color カラーDomed ドームDomed (Inverted) ドーム (反転)Diagonal (Descending) 斜め (下降)++ Red Eye Tool 赤目ツール+ Red Eye 赤目+ Pupil Size 瞳のサイズ+ Darken Amount 暗くする量+ Click a red pupil to neutralize it 赤い瞳をクリックして補正しますdiff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex c24c541e9..1f83a0972 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -2697,6 +2697,7 @@ cameraRaw Color 색상Frequency 빈도Use tablet pressure to change pen width 태블릿 압력을 사용하여 펜 폭 변경+# About ▸ Contributors / Models (credits, craftrules standards/contributors.md)About 정보Contributors 기여자@@ -2744,3 +2745,9 @@ cameraRaw Color 색상Domed 돔Domed (Inverted) 돔(반전)Diagonal (Descending) 대각선(내림)++ Red Eye Tool 적목 현상 도구+ Red Eye 적목 현상+ Pupil Size 동공 크기+ Darken Amount 어둡게 하기 정도+ Click a red pupil to neutralize it 빨간 동공을 클릭하여 보정합니다diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 79f65c5b8..ef7e48ca4 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -3198,3 +3198,7 @@ cameraRaw Roughness ChropowatośćDomed KopułaDomed (Inverted) Kopuła (odwrócona)Diagonal (Descending) Przekątna (malejąca)+ Red Eye Tool Narzędzie Czerwone oczy+ Pupil Size Rozmiar źrenicy+ Darken Amount Stopień przyciemnienia+ Click a red pupil to neutralize it Kliknij czerwoną źrenicę, aby ją zneutralizowaćdiff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex 392bcc1ea..35b9f3ad2 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -2551,6 +2551,7 @@ cameraRaw Whites BrancosMagnetic Lasso Tool Ferramenta Laço magnéticoFrequency FrequênciaUse tablet pressure to change pen width Usar a pressão da mesa digitalizadora para alterar a largura da caneta+# About ▸ Contributors / Models (credits, craftrules standards/contributors.md)About SobreContributors Colaboradores@@ -2596,3 +2597,8 @@ cameraRaw Whites BrancosDomed AbauladoDomed (Inverted) Abaulado (invertido)Diagonal (Descending) Diagonal (descendente)++ Red Eye Tool Ferramenta Olhos vermelhos+ Pupil Size Tamanho da pupila+ Darken Amount Quantidade de escurecimento+ Click a red pupil to neutralize it Clique em uma pupila vermelha para corrigi-ladiff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 6b706ae0f..1b7924c08 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -2390,6 +2390,7 @@ cameraRaw Roughness НеровностьFrequency ЧастотаUse tablet pressure to change pen width Использовать нажим планшета для изменения ширины пера+# About ▸ Contributors / Models (credits, craftrules standards/contributors.md)About О программеContributors Участники@@ -2436,3 +2437,8 @@ cameraRaw Roughness НеровностьDomed (Inverted) Купол (инвертированный)Diagonal (Descending) Диагональ (нисходящая)Linear Линейный++ Red Eye Tool Инструмент «Красные глаза»+ Pupil Size Размер зрачка+ Darken Amount Степень затемнения+ Click a red pupil to neutralize it Щёлкните по красному зрачку, чтобы убрать бликdiff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex 237c10f5c..6786e5950 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2120,6 +2120,7 @@ cameraRaw Blending 混合Frequency 频率Use tablet pressure to change pen width 使用绘图板压力以更改钢笔宽度+# About ▸ Contributors / Models (credits, craftrules standards/contributors.md)About 关于Contributors 贡献者@@ -2167,3 +2168,9 @@ cameraRaw Blending 混合Domed 圆顶Domed (Inverted) 圆顶(反转)Diagonal (Descending) 对角线(下降)++ Red Eye Tool 红眼工具+ Red Eye 红眼+ Pupil Size 瞳孔大小+ Darken Amount 变暗程度+ Click a red pupil to neutralize it 单击红色瞳孔以消除反光diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex d9a281e4f..9acdd90ed 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2089,6 +2089,7 @@ cameraRaw Blending 混合Frequency 頻率Use tablet pressure to change pen width 使用繪圖板壓力以變更鋼筆寬度+# About ▸ Contributors / Models (credits, craftrules standards/contributors.md)About 關於Contributors 貢獻者@@ -2136,3 +2137,9 @@ cameraRaw Blending 混合Domed 圓頂Domed (Inverted) 圓頂(反轉)Diagonal (Descending) 對角線(下降)++ Red Eye Tool 紅眼工具+ Red Eye 紅眼+ Pupil Size 瞳孔大小+ Darken Amount 變暗程度+ Click a red pupil to neutralize it 按一下紅色瞳孔以消除反光diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rsindex a510c16a9..00e501392 100644--- a/crates/ui-egui/src/icons.rs+++ b/crates/ui-egui/src/icons.rs@@ -87,6 +87,7 @@ pub fn tool_icon(t: Tool) -> &'static str {Tool::SpotHealing | Tool::Healing => "bandage",Tool::Patch => "lasso-select",Tool::ContentAwareMove => "arrow-left-right",+ Tool::RedEye => "eye",Tool::CloneStamp => "stamp",Tool::HistoryBrush => "clock",Tool::Blur => "droplet",diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex 5745ce2da..a0d8133b0 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -24,7 +24,7 @@ const TOOL_SECTIONS: &[&[&[Tool]]] = &[&[Tool::Eyedropper, Tool::Ruler, Tool::Note, Tool::Count],],&[- &[Tool::SpotHealing, Tool::Healing, Tool::Patch, Tool::ContentAwareMove],+ &[Tool::SpotHealing, Tool::Healing, Tool::Patch, Tool::ContentAwareMove, Tool::RedEye],&[Tool::Brush, Tool::Pencil, Tool::MixerBrush],&[Tool::CloneStamp],&[Tool::HistoryBrush],@@ -3228,6 +3228,13 @@ mod type_flyout_tests {assert_eq!(app.ui.tool, Tool::VerticalType);assert!(ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::new("tool-flyout"))).is_none());}++ #[test]+ fn red_eye_is_in_the_j_flyout() {+ let j = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).find(|slot| slot.contains(&Tool::SpotHealing)).expect("J group");+ assert!(j.contains(&Tool::RedEye), "{j:?}");+ assert_eq!(j.last(), Some(&Tool::RedEye));+ }}#[cfg(test)]diff --git a/crates/ui-egui/src/rasterize_prompt.rs b/crates/ui-egui/src/rasterize_prompt.rsindex dcb8b6e8c..a44fc1593 100644--- a/crates/ui-egui/src/rasterize_prompt.rs+++ b/crates/ui-egui/src/rasterize_prompt.rs@@ -64,7 +64,9 @@ impl Kind {/// Does `tool` paint the layer's pixels (so a vector or Smart Object layer must be rasterized)?pub fn paints_pixels(app: &PhotocraftApp, tool: Tool) -> bool {- tool.is_brushlike() || matches!(tool, Tool::PaintBucket | Tool::MagicEraser) || (tool == Tool::Gradient && app.ui.tool_options.gradient_classic)+ tool.is_brushlike()+ || matches!(tool, Tool::PaintBucket | Tool::MagicEraser | Tool::RedEye)+ || (tool == Tool::Gradient && app.ui.tool_options.gradient_classic)}/// The active layer's kind when painting its pixels needs rasterizing first: the tool targetsdiff --git a/crates/ui-egui/src/retouch_ui.rs b/crates/ui-egui/src/retouch_ui.rsindex 1ab730de2..8c9125fc6 100644--- a/crates/ui-egui/src/retouch_ui.rs+++ b/crates/ui-egui/src/retouch_ui.rs@@ -216,7 +216,7 @@ fn pct(ui: &mut egui::Ui, label: &str, v: &mut f32) {/// Options bar for the retouching and smart-selection tools. Returns false for other tools.pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool {- if !tool.is_brushlike() && !matches!(tool, Tool::QuickSelection | Tool::ObjectSelection | Tool::Patch | Tool::ContentAwareMove)+ if !tool.is_brushlike() && !matches!(tool, Tool::QuickSelection | Tool::ObjectSelection | Tool::Patch | Tool::ContentAwareMove | Tool::RedEye)|| matches!(tool, Tool::Brush | Tool::Pencil | Tool::MixerBrush | Tool::Eraser){return false;@@ -312,6 +312,14 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bolet _ = app.run("select.subject", json!({}));}}+ Tool::RedEye => {+ opt(ui, tl!("Pupil Size"));+ crate::widgets::value_field(ui, &mut o.red_eye_pupil_size, 1.0..=100.0, "", 50.0);+ opt(ui, tl!("Darken Amount"));+ crate::widgets::value_field(ui, &mut o.red_eye_darken, 0.0..=100.0, "", 50.0);+ crate::widgets::vline(ui, 22.0);+ opt(ui, tl!("Click a red pupil to neutralize it"));+ }_ => {}}true@@ -525,4 +533,56 @@ mod tests {assert!(sel.sample_channel(72, 30, 0) > 0.0 && sel.sample_channel(22, 30, 0) == 0.0, "{mode}: the selection follows");}}++ #[test]+ fn red_eye_click_corrects_a_pupil_and_errors_on_a_miss() {+ let mut app = app();+ app.run("paint.pencil", json!({"points": [[50, 30]], "size": 18, "hardness": 100, "color": "#f21818"})).unwrap();+ let before = active(&app).surface().unwrap().rgba(50, 30);+ assert!(before[0] > before[1] + 0.4, "{before:?}");+ app.ui.tool = Tool::RedEye;+ // Pupil Size 15 → search radius 22 px, so a click at (8,8) cannot reach the blob at (50,30).+ app.ui.tool_options.red_eye_pupil_size = 15.0;+ tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE);+ tool_event(&mut app, ToolEvent::Up { x: 50.0, y: 30.0 }, egui::Modifiers::NONE);+ assert!(!app.ui.status_error, "{}", app.ui.status);+ assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("paint.redEye"));+ let after = active(&app).surface().unwrap().rgba(50, 30);+ assert!(after[0] < before[0] - 0.15, "before {before:?} after {after:?}");+ tool_event(&mut app, ToolEvent::Down { x: 8.0, y: 8.0, pressure: 1.0 }, egui::Modifiers::NONE);+ tool_event(&mut app, ToolEvent::Up { x: 8.0, y: 8.0 }, egui::Modifiers::NONE);+ assert!(app.ui.status_error);+ assert!(app.ui.status.contains("no red-eye pixels"), "{}", app.ui.status);+ }++ #[test]+ fn red_eye_options_bar_shows_pupil_size_and_darken() {+ use crate::theme::ThemeKind;+ use egui::vec2;+ use egui_kittest::kittest::Queryable;+ let mut app = app();+ app.ui.tool = Tool::RedEye;+ let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 60.0)).build_ui_state(+ |ui, app: &mut PhotocraftApp| {+ if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {+ return;+ }+ crate::panels::options_bar(app, ui);+ },+ app,+ );+ PhotocraftApp::setup_context(&h.ctx, ThemeKind::Studio);+ h.run_steps(4);+ h.get_by_label("Pupil Size");+ h.get_by_label("Darken Amount");+ assert_eq!(h.state().ui.tool_options.red_eye_pupil_size, 50.0);+ assert_eq!(h.state().ui.tool_options.red_eye_darken, 50.0);+ }++ #[test]+ fn red_eye_is_in_the_j_flyout() {+ let j = [Tool::SpotHealing, Tool::Healing, Tool::Patch, Tool::ContentAwareMove, Tool::RedEye];+ assert!(j.contains(&Tool::RedEye));+ assert!(j.iter().all(|t| t.key() == 'J'));+ }}diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex 40f662998..d6b22c5ef 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -90,6 +90,7 @@ pub enum Tool {Healing,Patch,ContentAwareMove,+ RedEye,CloneStamp,HistoryBrush,Blur,@@ -114,7 +115,7 @@ pub enum Tool {}impl Tool {- pub const ALL: [Tool; 49] = [+ pub const ALL: [Tool; 50] = [Tool::Move,Tool::RectMarquee,Tool::EllipseMarquee,@@ -143,6 +144,7 @@ impl Tool {Tool::Healing,Tool::Patch,Tool::ContentAwareMove,+ Tool::RedEye,Tool::CloneStamp,Tool::HistoryBrush,Tool::Blur,@@ -198,6 +200,7 @@ impl Tool {Tool::Healing => "Healing Brush Tool",Tool::Patch => "Patch Tool",Tool::ContentAwareMove => "Content-Aware Move Tool",+ Tool::RedEye => "Red Eye Tool",Tool::CloneStamp => "Clone Stamp Tool",Tool::HistoryBrush => "History Brush Tool",Tool::Blur => "Blur Tool",@@ -259,7 +262,7 @@ impl Tool {Tool::Type | Tool::VerticalType => 'T',Tool::Hand => 'H',Tool::Zoom => 'Z',- Tool::SpotHealing | Tool::Healing | Tool::Patch | Tool::ContentAwareMove => 'J',+ Tool::SpotHealing | Tool::Healing | Tool::Patch | Tool::ContentAwareMove | Tool::RedEye => 'J',Tool::CloneStamp => 'S',Tool::HistoryBrush => 'Y',Tool::Blur | Tool::Sharpen | Tool::Smudge => '\0',@@ -494,6 +497,11 @@ pub struct ToolOptions {pub magnetic_contrast: f32,pub magnetic_frequency: f32,pub magnetic_pressure: bool,+ /// Red Eye: pupil search size (1–100) and how far corrected pixels darken (0–100).+ #[serde(default = "fifty")]+ pub red_eye_pupil_size: f32,+ #[serde(default = "fifty")]+ pub red_eye_darken: f32,}fn yes() -> bool {@@ -512,6 +520,10 @@ fn one() -> f32 {1.0}+fn fifty() -> f32 {+ 50.0+}+impl Default for ToolOptions {fn default() -> Self {Self {@@ -573,6 +585,8 @@ impl Default for ToolOptions {magnetic_contrast: 10.0,magnetic_frequency: 57.0,magnetic_pressure: false,+ red_eye_pupil_size: 50.0,+ red_eye_darken: 50.0,}}}@@ -972,6 +986,11 @@ mod tests {assert_eq!(Tool::from_name("Eraser Tool"), Some(Tool::Eraser));assert_eq!(Tool::from_name("mixerBrush"), Some(Tool::MixerBrush));assert_eq!(Tool::from_name("Mixer Brush Tool"), Some(Tool::MixerBrush));+ assert_eq!(Tool::from_name("redEye"), Some(Tool::RedEye));+ assert_eq!(Tool::from_name("Red Eye Tool"), Some(Tool::RedEye));+ assert_eq!(Tool::RedEye.key(), 'J');+ assert!(!Tool::RedEye.is_brushlike());+ assert_eq!(Tool::ALL.len(), 50);assert_eq!(Tool::from_name("nope"), None);}diff --git a/scorecard/tools.toml b/scorecard/tools.tomlindex 028759609..4ade01644 100644--- a/scorecard/tools.toml+++ b/scorecard/tools.toml@@ -214,3 +214,10 @@ target = "Liquify: redo (Cmd+Shift+Z)"status = "done"issue = 214note = "liquify_ui.rs supports bounded redo through Cmd+Shift+Z and the control channel; new strokes clear redo"++[[item]]+id = "TOOL-213-17"+target = "Red Eye tool: click a pupil to neutralize the red reflection"+status = "done"+issue = 213+note = "paint.redEye (redeye_cmds.rs) + Tool::RedEye in the J flyout; Pupil Size and Darken Amount; catchlights kept; a miss is an error"