Merge remote-tracking branch 'origin/main' into HEAD

This commit is contained in:
Claude committed 2026-10-09 01:24:20 +00:00
commit 2722ea8b24
22 files changed
+934 -102

No files matched your search

+245
View File
@@ -573,9 +573,140 @@ pub(crate) fn surface(src: &Image, out: Rect, ctx: &Ctx, radius: f32, threshold:
{
return res;
}
// 16-bit and float (and 8-bit where the histogram declined): the ranked sums overtake the
// direct sum near radius 8 on a 256 px tile and are about 10x faster at radius 100.
if r >= RANKED_MIN_RADIUS
&& let Some(res) = surface_ranked(src, out, ctx, r, t)
{
return res;
}
surface_direct(src, out, ctx, r, t)
}
/// Radius from which [`surface_ranked`] beats [`surface_direct`] (measured by `surface_timing`).
const RANKED_MIN_RADIUS: i32 = 10;
/// Fenwick tree over value ranks, each node holding (count, Σv, Σv²) of its range.
struct RankSums(Vec<[f64; 3]>);
impl RankSums {
fn add(&mut self, rank: usize, sign: f64, v: f64) {
let mut i = rank + 1;
while let Some(node) = self.0.get_mut(i) {
node[0] += sign;
node[1] += sign * v;
node[2] += sign * v * v;
i += i & i.wrapping_neg();
}
}
/// Sums over the ranks `0..end`.
fn prefix(&self, end: usize) -> [f64; 3] {
let mut acc = [0.0; 3];
let mut i = end.min(self.0.len().saturating_sub(1));
while i > 0 {
if let Some(node) = self.0.get(i) {
acc[0] += node[0];
acc[1] += node[1];
acc[2] += node[2];
}
i -= i & i.wrapping_neg();
}
acc
}
/// Sums over the ranks `start..end`.
fn range(&self, start: usize, end: usize) -> [f64; 3] {
let (a, b) = (self.prefix(start), self.prefix(end));
[b[0] - a[0], b[1] - a[1], b[2] - a[2]]
}
}
/// [`surface`] at any bit depth. The weight `1 - |v - v0| / t` is linear in `v` on each side of
/// the centre value, so over the samples within the threshold below it `Σw = ((t - v0)·n + Σv) / t`
/// and `Σv·w = ((t - v0)·Σv + Σv²) / t`, and symmetrically above it. A Fenwick tree over the
/// window's distinct values holds the count, Σv and Σv² and slides along the row (one column out
/// and one in per step), so a pixel costs O(radius · log n) instead of O(radius^2). `None` when a
/// sample isn't finite; the direct sum handles those.
fn surface_ranked(src: &Image, out: Rect, ctx: &Ctx, r: i32, t: f32) -> Option<Vec<f32>> {
let n = src.ch;
let cc = if ctx.alpha { n - 1 } else { n };
let win = out.inflate(r);
let (ww, wh) = (win.width() as usize, win.height() as usize);
// Every colour sample of the window (outside the source reads as 0, as `Image::get` does),
// and whether its pixel counts (the direct sum skips transparent ones).
let mut vals = Vec::with_capacity(ww * wh * cc);
let mut opaque = Vec::with_capacity(ww * wh);
for y in win.y0..win.y1 {
for x in win.x0..win.x1 {
opaque.push(!(ctx.alpha && src.get(x, y, n - 1) <= 0.0));
for c in 0..cc {
let v = src.get(x, y, c);
if !v.is_finite() {
return None;
}
// `+ 0.0` turns -0.0 into 0.0, so equal values share a rank.
vals.push(v + 0.0);
}
}
}
let mut levels = vals.clone();
levels.sort_unstable_by(f32::total_cmp);
levels.dedup();
let rank: Vec<usize> = vals.iter().map(|v| levels.partition_point(|l| l < v)).collect();
let mut tree = RankSums(vec![[0.0; 3]; levels.len() + 1]);
let (ow, oh) = (out.width() as usize, out.height() as usize);
if ow == 0 || oh == 0 {
return Some(Vec::new());
}
let side = (2 * r + 1) as usize;
let t64 = f64::from(t);
let mut res = vec![0.0f32; ow * oh * n];
for oy in 0..oh {
for c in 0..cc {
let column = |tree: &mut RankSums, wx: usize, sign: f64| {
for wy in oy..oy + side {
let p = wy * ww + wx;
if opaque.get(p) == Some(&true)
&& let (Some(&k), Some(&v)) = (rank.get(p * cc + c), vals.get(p * cc + c))
{
tree.add(k, sign, f64::from(v));
}
}
};
for wx in 0..side {
column(&mut tree, wx, 1.0);
}
for ox in 0..ow {
let v0 = src.px(out.x0 + ox as i32, out.y0 + oy as i32)[c];
// Ranks strictly within the threshold below v0 (and v0 itself), then above it.
let lo = levels.partition_point(|&l| 1.0 - (l - v0).abs() / t <= 0.0 && l < v0);
let mid = levels.partition_point(|&l| l <= v0);
let hi = levels.partition_point(|&l| l <= v0 || 1.0 - (l - v0).abs() / t > 0.0);
let (below, above) = (tree.range(lo, mid), tree.range(mid, hi));
let v0d = f64::from(v0);
let wsum = ((t64 - v0d) * below[0] + below[1] + (t64 + v0d) * above[0] - above[1]) / t64;
let acc = ((t64 - v0d) * below[1] + below[2] + (t64 + v0d) * above[1] - above[2]) / t64;
res[(oy * ow + ox) * n + c] = if below[0] + above[0] > 0.0 && wsum > 0.0 { (acc / wsum) as f32 } else { v0 };
if ox + 1 < ow {
column(&mut tree, ox, -1.0);
column(&mut tree, ox + side, 1.0);
}
}
// Empty the tree for the next row and channel.
for wx in ow - 1..ow - 1 + side {
column(&mut tree, wx, -1.0);
}
}
if ctx.alpha {
for ox in 0..ow {
res[(oy * ow + ox) * n + n - 1] = src.px(out.x0 + ox as i32, out.y0 + oy as i32)[n - 1];
}
}
}
Some(res)
}
/// [`surface`] by summing the whole (2r + 1)^2 window of every pixel.
fn surface_direct(src: &Image, out: Rect, ctx: &Ctx, r: i32, t: f32) -> Vec<f32> {
let n = src.ch;
@@ -869,4 +1000,118 @@ mod tests {
}
}
}
/// The direct sum with f64 accumulators: the reference both fast paths are held to.
fn surface_reference(src: &Image, out: Rect, ctx: &Ctx, r: i32, t: f32) -> Vec<f32> {
let n = src.ch;
let cc = if ctx.alpha { n - 1 } else { n };
let mut res = Vec::new();
for y in out.y0..out.y1 {
for x in out.x0..out.x1 {
let p = src.px(x, y);
for &v0 in p.iter().take(cc) {
let c = res.len() % n;
let (mut acc, mut wsum) = (0.0f64, 0.0f64);
for yy in y - r..=y + r {
for xx in x - r..=x + r {
if ctx.alpha && src.get(xx, yy, n - 1) <= 0.0 {
continue;
}
let v = src.get(xx, yy, c);
let w = (1.0 - (v - v0).abs() / t).max(0.0);
acc += f64::from(v) * f64::from(w);
wsum += f64::from(w);
}
}
res.push(if wsum > 0.0 { (acc / wsum) as f32 } else { v0 });
}
if ctx.alpha {
res.push(p[n - 1]);
}
}
}
res
}
#[test]
fn surface_blur_ranked_sums_match_the_weighted_window_at_any_depth() {
// 16-bit levels and arbitrary floats (including negatives and values above 1), with some
// fully transparent pixels, which the sum skips.
for (quant, channels, alpha) in [(Some(65535.0f32), 4, true), (None, 4, true), (None, 1, false)] {
let src_rect = Rect::new(-20, -20, 48, 40);
let mut img = Image::new(src_rect, channels);
let mut s = 0x1b87_3593u32;
for px in img.data.chunks_mut(channels) {
for v in px.iter_mut() {
s ^= s << 13;
s ^= s >> 17;
s ^= s << 5;
let raw = (s % 10_000) as f32 / 10_000.0;
*v = quant.map_or(raw * 1.5 - 0.25, |q| (raw * q).round() / q);
}
if alpha && s.is_multiple_of(7) {
px[channels - 1] = 0.0;
}
}
let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha };
// The output reaches the source edge, where samples read as 0.
let out = Rect::new(-6, 0, 30, 22);
for (r, threshold) in [(1, 2.0), (4, 15.0), (12, 60.0), (16, 255.0)] {
let t = (threshold / 255.0) * 2.5;
let ranked = surface_ranked(&img, out, &ctx, r, t).expect("finite input");
let reference = surface_reference(&img, out, &ctx, r, t);
assert_eq!(ranked.len(), reference.len());
let err = reference.iter().zip(&ranked).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
assert!(err < 1e-6, "{quant:?} r {r} threshold {threshold}: max error {err}");
}
}
}
#[test]
fn surface_blur_ranked_declines_non_finite_samples_and_handles_empty_output() {
let src_rect = Rect::new(0, 0, 8, 8);
let mut img = Image::new(src_rect, 1);
img.data.fill(0.5);
let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Grayscale, alpha: false };
assert_eq!(surface_ranked(&img, Rect::new(2, 2, 2, 6), &ctx, 2, 0.1), Some(Vec::new()));
img.data[9] = f32::NAN;
assert!(surface_ranked(&img, Rect::new(0, 0, 8, 8), &ctx, 2, 0.1).is_none());
// The public entry still answers, through the direct sum.
assert_eq!(surface(&img, Rect::new(0, 0, 8, 8), &ctx, 12.0, 15.0).len(), 64);
}
/// Release-mode timings of the direct sum and the ranked path on one 256 px tile of
/// 16-bit-like and float noise (`cargo test -p photocraft-algo --release -- --ignored --nocapture surface_timing`).
#[test]
#[ignore]
fn surface_timing() {
for (label, quant) in [("16-bit", Some(65535.0f32)), ("float", None)] {
for r in [2, 4, 8, 16, 32, 64, 100] {
let out = Rect::new(0, 0, 256, 256);
let src_rect = out.inflate(r);
let mut img = Image::new(src_rect, 4);
let mut s = 0x2545_f491u32;
let len = img.data.len();
for (i, v) in img.data.iter_mut().enumerate() {
s ^= s << 13;
s ^= s >> 17;
s ^= s << 5;
// Smooth gradient plus noise, so the threshold keeps a realistic share.
let x = (i / 4) as f32 / len as f32 * 4.0;
let raw = (0.5 + 0.4 * (x * 6.0).sin() + (s % 1000) as f32 / 20000.0).clamp(0.0, 1.0);
*v = quant.map_or(raw, |q| (raw * q).round() / q);
}
let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha: true };
let t = (15.0 / 255.0) * 2.5;
let a = std::time::Instant::now();
let direct = surface_direct(&img, out, &ctx, r, t);
let td = a.elapsed();
let a = std::time::Instant::now();
let ranked = surface_ranked(&img, out, &ctx, r, t).expect("finite");
let tr = a.elapsed();
let err = direct.iter().zip(&ranked).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
println!("{label} r {r:3}: direct {td:>10.2?} ranked {tr:>10.2?} max err {err:.2e}");
}
}
}
}
+3 -2
View File
@@ -288,8 +288,9 @@ impl ColorState {
self.proofs.get(&doc).cloned().unwrap_or_else(|| ProofView { gamut_threshold: photocraft_cms::gamut::DEFAULT_THRESHOLD, ..Default::default() })
}
/// The document's proofing state when it was ever changed (no default allocated).
pub(crate) fn proof_ref(&self, doc: DocId) -> Option<&ProofView> {
/// Borrow the document's proofing state without cloning its profile or allocating defaults.
/// `None` means the unchanged defaults documented by [`Self::proof`].
pub fn proof_ref(&self, doc: DocId) -> Option<&ProofView> {
self.proofs.get(&doc)
}
+205 -72
View File
@@ -150,6 +150,147 @@ fn pixels_to_lab(t: &photocraft_cms::Transform, px: &[[f32; 4]]) -> Vec<[f32; 4]
out
}
/// Prepared Sampled Colors query shared by the command and its interactive preview.
/// Samples always come from the original document; reducing an image must not change them.
pub struct ColorRangeSamples {
to_lab: std::sync::Arc<photocraft_cms::Transform>,
range: sel::LabRange,
grid: bool,
fuzziness: f32,
localized: Option<f32>,
plus_at: Vec<(f32, f32)>,
}
impl ColorRangeSamples {
/// Prepare the query without allocating a full-resolution composite. Point samples use
/// exactly the same compositor/profile as the final selection.
pub fn new(s: &Session, p: &Value) -> Result<Self> {
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
let area = doc.bounds();
let bad = |msg: String| EngineError::BadParams { cmd: "select.colorRange".into(), msg };
let sample = |key: &str| -> Result<Vec<sel::RangeSample>> {
let Some(pts) = p.get(key) else { return Ok(Vec::new()) };
let pts = pts.as_array().ok_or_else(|| bad(format!("`{key}` must be [[x, y], …]")))?;
let mut samples = Vec::new();
for point in pts {
let q = point.as_array().and_then(|v| match v.as_slice() {
[x, y] => Some((x.as_f64()?, y.as_f64()?)),
_ => None,
});
let Some((x, y)) = q.filter(|(x, y)| x.is_finite() && y.is_finite()) else {
return Err(bad(format!("bad point {point} in `{key}` (want [x, y])")));
};
let (x, y) = (x.floor() as i32, y.floor() as i32);
if !area.contains(x, y) {
return Err(bad(format!("point [{x}, {y}] in `{key}` is outside the canvas")));
}
let r = Rect::from_xywh(x, y, 1, 1);
let pixel = if !b(p, "sampleAllLayers", true) {
s.active().and_then(|d| d.active_layer.and_then(|id| d.doc.layer(id))).and_then(|l| l.surface()).map(|surf| {
let mut px = [[0.0; 4]];
surf.read_rgba_into(r, &mut px);
px[0]
})
} else {
None
};
let px = match pixel {
Some(px) => px,
None => photocraft_compose::render(doc, r).px.first().copied().unwrap_or([0.0; 4]),
};
samples.push(sel::RangeSample { color: [px[0], px[1], px[2]], at: Some(((x - area.x0) as f32, (y - area.y0) as f32)) });
}
Ok(samples)
};
Self::with_samples(s, p, area, &sample("points")?, &sample("subtractPoints")?)
}
fn with_samples(s: &Session, p: &Value, area: Rect, plus: &[sel::RangeSample], minus: &[sel::RangeSample]) -> Result<Self> {
let bad = |msg: String| EngineError::BadParams { cmd: "select.colorRange".into(), msg };
let fuzz = |d: f32| f(p, "fuzziness", d).max(0.0);
// The order the eyedropper clicks came in ("+" a point, "-" a subtracted point):
// Photoshop applies them one after another. Without it, all additions come first.
let order: Vec<bool> = match p.get("order") {
None => std::iter::repeat_n(true, plus.len()).chain(std::iter::repeat_n(false, minus.len())).collect(),
Some(o) => {
let o = o.as_array().ok_or_else(|| bad("`order` must be a list of \"+\" and \"-\"".into()))?;
let order = o
.iter()
.map(|v| match v.as_str() {
Some("+") => Ok(true),
Some("-") => Ok(false),
_ => Err(bad(format!("bad entry {v} in `order` (want \"+\" or \"-\")"))),
})
.collect::<Result<Vec<bool>>>()?;
if order.iter().filter(|x| **x).count() != plus.len() || order.iter().filter(|x| !**x).count() != minus.len() {
return Err(bad("`order` must list each of `points` (\"+\") and `subtractPoints` (\"-\") once".into()));
}
order
}
};
let mut fixed: Vec<[f32; 3]> = Vec::new();
if let Some(cs) = p.get("colors") {
let cs = cs.as_array().ok_or_else(|| bad("`colors` must be a list of colours".into()))?;
fixed.extend(cs.iter().map(|c| parse_color(&json!({ "color": c }))));
}
if p.get("color").is_some() {
fixed.push(parse_color(p));
}
// Localized Color Clusters: Range is a percentage of the canvas's longer side.
let plus_at: Vec<(f32, f32)> = plus.iter().filter_map(|x| x.at).collect();
let localized = if b(p, "localized", false) {
if plus_at.is_empty() {
return Err(bad("localized clusters need eyedropper `points`".into()));
}
Some(f(p, "range", 100.0).clamp(0.0, 100.0) / 100.0 * area.width().max(area.height()) as f32)
} else {
None
};
// Photoshop compares colours in Lab, through the document's profile
// (sel::lab_range_coverage). The samples span one Lab box; "Add to Sample" grows it,
// "Subtract from Sample" reshapes it (sel::LabRange::subtract).
let to_lab = lab_transform(s)?;
// 8-bit documents are compared on the 8-bit Lab grid, samples and pixels alike.
let grid = s.active().is_some_and(|d| d.doc.depth == photocraft_doc::SampleType::U8);
let q = |c: [f32; 3]| if grid { sel::quantize_lab8(c) } else { c };
let colour_to_lab = |t: &photocraft_cms::Transform, c: [f32; 3]| q(colour_to_lab(t, c));
let foreground = || {
let [r, g, b, _] = s.tools.foreground;
sel::LabRange::point(colour_to_lab(&to_lab, [r, g, b]))
};
let fixed_lab: Vec<[f32; 3]> = fixed.iter().map(|c| colour_to_lab(&to_lab, *c)).collect();
let mut range = sel::LabRange::spanning(&fixed_lab);
let (mut pi, mut mi) = (plus.iter(), minus.iter());
for add in order {
if add {
if let Some(x) = pi.next() {
let c = colour_to_lab(&to_lab, x.color);
range = Some(range.map_or(sel::LabRange::point(c), |r| r.grow(&c)));
}
} else if let Some(x) = mi.next() {
range = Some(range.unwrap_or_else(foreground).subtract(&colour_to_lab(&to_lab, x.color), fuzz(40.0)));
}
}
let range = range.unwrap_or_else(foreground);
Ok(Self { to_lab, range, grid, fuzziness: fuzz(40.0), localized, plus_at })
}
/// Coverage of a composite rectangle. `scale` is the original document pixels represented
/// by one input pixel; `origin` is in original document pixels (for a visible canvas crop).
pub fn coverage(&self, px: &[[f32; 4]], width: usize, scale: f32, origin: [f32; 2]) -> Vec<f32> {
let mut lab = pixels_to_lab(&self.to_lab, px);
if self.grid {
for p in &mut lab {
let [l, a, b] = sel::quantize_lab8([p[0], p[1], p[2]]);
*p = [l, a, b, p[3]];
}
}
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
let points: Vec<_> = self.plus_at.iter().map(|(x, y)| ((x - origin[0]) / scale, (y - origin[1]) / scale)).collect();
sel::color_range_lab(&lab, width, &self.range, self.fuzziness, self.grid, self.localized.map(|r| (r / scale, points.as_slice())))
}
}
fn color_range(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "select.colorRange";
let bad = |msg: String| EngineError::BadParams { cmd: CMD.into(), msg };
@@ -163,78 +304,8 @@ fn color_range(s: &mut Session, p: &Value) -> Result<Value> {
// The dialog's eyedroppers: colours picked on the image, at their positions.
let plus = eyedropper_samples(p, "points", area, &px, &bad)?;
let minus = eyedropper_samples(p, "subtractPoints", area, &px, &bad)?;
// The order the eyedropper clicks came in ("+" a point, "-" a subtracted point):
// Photoshop applies them one after another. Without it, all additions come first.
let order: Vec<bool> = match p.get("order") {
None => std::iter::repeat_n(true, plus.len()).chain(std::iter::repeat_n(false, minus.len())).collect(),
Some(o) => {
let o = o.as_array().ok_or_else(|| bad("`order` must be a list of \"+\" and \"-\"".into()))?;
let order = o
.iter()
.map(|v| match v.as_str() {
Some("+") => Ok(true),
Some("-") => Ok(false),
_ => Err(bad(format!("bad entry {v} in `order` (want \"+\" or \"-\")"))),
})
.collect::<Result<Vec<bool>>>()?;
if order.iter().filter(|x| **x).count() != plus.len() || order.iter().filter(|x| !**x).count() != minus.len() {
return Err(bad("`order` must list each of `points` (\"+\") and `subtractPoints` (\"-\") once".into()));
}
order
}
};
let mut fixed: Vec<[f32; 3]> = Vec::new();
if let Some(cs) = p.get("colors") {
let cs = cs.as_array().ok_or_else(|| bad("`colors` must be a list of colours".into()))?;
fixed.extend(cs.iter().map(|c| parse_color(&json!({ "color": c }))));
}
if p.get("color").is_some() {
fixed.push(parse_color(p));
}
// Localized Color Clusters: Range is a percentage of the canvas's longer side.
let plus_at: Vec<(f32, f32)> = plus.iter().filter_map(|x| x.at).collect();
let localized = if b(p, "localized", false) {
if plus_at.is_empty() {
return Err(bad("localized clusters need eyedropper `points`".into()));
}
Some(f(p, "range", 100.0).clamp(0.0, 100.0) / 100.0 * area.width().max(area.height()) as f32)
} else {
None
};
// Photoshop compares colours in Lab, through the document's profile
// (sel::lab_range_coverage). The samples span one Lab box; "Add to Sample" grows it,
// "Subtract from Sample" reshapes it (sel::LabRange::subtract).
let to_lab = lab_transform(s)?;
// 8-bit documents are compared on the 8-bit Lab grid, samples and pixels alike.
let grid = s.active().is_some_and(|d| d.doc.depth == photocraft_doc::SampleType::U8);
let q = |c: [f32; 3]| if grid { sel::quantize_lab8(c) } else { c };
let mut lab = pixels_to_lab(&to_lab, &px);
if grid {
for p in &mut lab {
let [l, a, b] = sel::quantize_lab8([p[0], p[1], p[2]]);
*p = [l, a, b, p[3]];
}
}
let colour_to_lab = |t: &photocraft_cms::Transform, c: [f32; 3]| q(colour_to_lab(t, c));
let foreground = || {
let [r, g, b, _] = s.tools.foreground;
sel::LabRange::point(colour_to_lab(&to_lab, [r, g, b]))
};
let fixed_lab: Vec<[f32; 3]> = fixed.iter().map(|c| colour_to_lab(&to_lab, *c)).collect();
let mut range = sel::LabRange::spanning(&fixed_lab);
let (mut pi, mut mi) = (plus.iter(), minus.iter());
for add in order {
if add {
if let Some(x) = pi.next() {
let c = colour_to_lab(&to_lab, x.color);
range = Some(range.map_or(sel::LabRange::point(c), |r| r.grow(&c)));
}
} else if let Some(x) = mi.next() {
range = Some(range.unwrap_or_else(foreground).subtract(&colour_to_lab(&to_lab, x.color), fuzz(40.0)));
}
}
let range = range.unwrap_or_else(foreground);
let mask = sel::color_range_lab(&lab, w, &range, fuzz(40.0), grid, localized.map(|r| (r, plus_at.as_slice())));
let query = ColorRangeSamples::with_samples(s, p, area, &plus, &minus)?;
let mask = query.coverage(&px, w, 1.0, [0.0, 0.0]);
(area, mask)
}
"reds" | "yellows" | "greens" | "cyans" | "blues" | "magentas" => {
@@ -555,6 +626,68 @@ mod tests {
assert_eq!(coverage(&s, 30, 10), 1.0);
}
#[test]
fn color_range_prepared_query_matches_the_command_at_all_depths() {
use photocraft_doc::{Color, ColorMode, SampleType, Size};
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
for profile in [None, Some(photocraft_cms::Builtin::DisplayP3.profile().to_bytes())] {
let mut doc = Document::with_background("samples", Size::new(24, 12), ColorMode::Rgb, depth, Color::WHITE);
doc.icc_profile = profile;
let layer = doc.layers[0].surface_mut().unwrap();
layer.fill_rect(Rect::new(0, 0, 8, 12), &[0.65, 0.3, 0.2, 1.0]);
layer.fill_rect(Rect::new(8, 0, 16, 12), &[0.2, 0.3, 0.65, 1.0]);
let mut s = Session::new();
s.add_document(doc, None);
for p in [
json!({"points": [[2, 3]], "fuzziness": 0}),
json!({"points": [[2, 3], [10, 3]], "subtractPoints": [[10, 3]], "order": ["+", "+", "-"], "fuzziness": 40}),
json!({"points": [[2, 3]], "localized": true, "range": 50, "fuzziness": 80}),
] {
let q = ColorRangeSamples::new(&s, &p).unwrap();
let doc = s.active().unwrap().doc.clone();
let pixels = photocraft_compose::render(&doc, doc.bounds());
let preview = q.coverage(&pixels.px, 24, 1.0, [0.0, 0.0]);
s.execute("select.colorRange", p).unwrap();
let actual = current_mask(&s.active().unwrap().doc).1;
for (shown, selected) in preview.iter().zip(actual) {
let rounded = (shown.clamp(0.0, 1.0) * 255.0 + 0.5).floor() / 255.0;
assert_eq!(rounded, selected, "{depth:?}: original-pixel preview and OK differ");
}
}
}
}
}
#[test]
fn color_range_prepared_query_samples_visible_layers_not_the_active_layer() {
use photocraft_doc::{Layer, LayerContent};
let mut s = session_colours();
let doc = s.active().unwrap().doc.clone();
let mut top = Layer::new("blue foreground", LayerContent::Raster(doc.layers[0].surface().unwrap().clone()));
top.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 40, 30), &[0.0, 0.0, 1.0, 1.0]);
let mut hidden = Layer::new("hidden green", LayerContent::Raster(top.surface().unwrap().clone()));
hidden.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 40, 30), &[0.0, 1.0, 0.0, 1.0]);
hidden.visible = false;
s.edit("layers", |doc, _| {
doc.layers.push(top);
doc.layers.push(hidden);
Ok(())
})
.unwrap();
for all_layers in [false, true] {
let p = json!({"points": [[7, 7]], "sampleAllLayers": all_layers, "fuzziness": 0});
let query = ColorRangeSamples::new(&s, &p).unwrap();
let (area, px) = sample_pixels(&s, all_layers).unwrap();
let shown = query.coverage(&px, area.width() as usize, 1.0, [0.0, 0.0]);
s.execute("select.colorRange", p).unwrap();
assert_eq!(shown[7 * 40 + 7], coverage(&s, 7, 7));
assert_eq!(shown[24 * 40 + 10], coverage(&s, 10, 24));
}
for p in [json!({"points": [[-1, 0]]}), json!({"points": [[40, 1]]}), json!({"points": "wrong"}), json!({"points": [[null, 0]]})] {
assert!(ColorRangeSamples::new(&s, &p).is_err(), "{p}");
}
}
#[test]
fn color_range_selects_by_colour() {
let mut s = session();
+8 -3
View File
@@ -1895,6 +1895,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) };
painter.image(tex, img_rect, uv, Color32::WHITE);
}
crate::color_range_ui::paint_selection_preview(app, &ctx, &painter, doc.id, img_rect, flip);
// Artboards: pasteboard between the boards, outlines and names (artboard_ui.rs).
if doc.has_artboards() {
let t = crate::theme::Tokens::get(&ctx);
@@ -2051,7 +2052,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
// 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;
let range_picking =
primary && app.ui.dialogs.last().is_some_and(|d| crate::color_range_ui::owns(&d.fields) && crate::color_range_ui::controls(&d.fields).sampling);
let hand = app.ui.tool == Tool::Hand && !picking && !range_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 };
view.center[1] -= d.y / view.zoom;
@@ -2074,10 +2077,12 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
}
} else if primary
&& !middle
&& let Some(p) = crate::dialogs::free_pointer_over(&ctx, rect)
&& let Some(p) = crate::dialogs::free_pointer_over(&ctx, rect).filter(|p| img_rect.contains(*p))
{
// Color Range samples colours with its eyedropper on the image itself.
let press = crate::dialogs::free_press(&ctx, rect).map(|q| xf.to_doc(q));
let press = crate::dialogs::free_press(&ctx, rect)
.filter(|p| img_rect.contains(*p) && ctx.input(|i| i.pointer.primary_pressed() || i.pointer.delta() != egui::Vec2::ZERO))
.map(|q| xf.to_doc(q));
crate::color_range_ui::canvas_eyedropper(app, &ctx, p, press);
}
}
+376 -9
View File
@@ -2,13 +2,15 @@
//! families, Highlights / Midtones / Shadows, Out Of Gamut), Fuzziness, Localized Color Clusters
//! with Range, the tonal range of Highlights / Midtones / Shadows, the three eyedroppers (sample,
//! add, subtract; they pick on the preview, Shift adds and Alt subtracts), a Selection / Image
//! preview and Invert. Controls a mode doesn't use are disabled, like Photoshop's.
//! preview, canvas Selection Preview modes and Invert. Controls a mode doesn't use are disabled, like Photoshop's.
//!
//! Everything lives in the dialog fields (`ui.dialog.set` drives it). The preview and OK run the
//! same engine command, `select.colorRange`, so the GUI, MCP and scripts select identically; the
//! preview runs it on a small proxy of the document, OK on the document itself (one history step).
//! preview compares a small proxy against samples from the original document; OK selects at
//! full resolution (one history step). Reduced previews approximate fine detail and effects.
//! Cancel never touches the document, so the previous selection stays as it was.
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use egui::{Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
@@ -41,6 +43,10 @@ pub const SELECTS: &[(&str, &str)] = &[
/// Longest side of the preview thumbnail, in points.
const PREVIEW: u32 = 200;
/// Canvas overlays are view state; keep their allocation bounded on very large documents.
const CANVAS_PREVIEW: u32 = 1024;
const PREVIEWS: &[(&str, &str)] =
&[("none", "None"), ("grayscale", "Grayscale"), ("blackMatte", "Black Matte"), ("whiteMatte", "White Matte"), ("quickMask", "Quick Mask")];
/// Which controls the current Select mode uses (the rest are disabled or hidden).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -101,6 +107,7 @@ pub fn open(app: &mut PhotocraftApp) -> u64 {
f.insert("__order".into(), json!([]));
f.insert("__tool".into(), json!("sample"));
f.insert("__view".into(), json!("selection"));
f.insert("__selectionPreview".into(), json!("none"));
app.color_range = None;
app.ui.open_dialog(DialogKind::Command, f)
}
@@ -168,16 +175,64 @@ pub struct Preview {
mask: Option<egui::TextureHandle>,
/// Why the preview couldn't be drawn (shown in the dialog and logged, never silent: #145).
error: Option<String>,
canvas_proxy: Option<(u32, Arc<Document>)>,
overlay: Option<egui::TextureHandle>,
overlay_key: u64,
}
fn hash(text: &str) -> u64 {
text.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3))
}
fn query_key(app: &PhotocraftApp, params: &Value) -> u64 {
let mut key = std::collections::hash_map::DefaultHasher::new();
params.to_string().hash(&mut key);
let foreground = app.session.tools.foreground;
foreground.map(f32::to_bits).hash(&mut key);
// This runs several times per frame, including mere pointer motion. Debug-formatting a
// ProofView serializes the whole ICC profile/LUT; proof() also clones the default profile.
// Borrow the state and use the profile's memoized content hash instead.
let proof = app.session.active().and_then(|st| app.session.color.proof_ref(st.doc.id));
proof.is_some().hash(&mut key);
if let Some(proof) = proof {
let setup = &proof.setup;
(setup.profile.content_hash(), setup.intent, setup.bpc, setup.simulate_paper, setup.kind).hash(&mut key);
(proof.enabled, proof.gamut_warning, proof.gamut_threshold.to_bits()).hash(&mut key);
}
key.finish().max(1)
}
/// The selection mask `params` would make, on the proxy: the engine command run on a scratch
/// session (Out Of Gamut uses the document's own proof setup).
fn proxy_mask(app: &PhotocraftApp, proxy: &Document, k: u32, params: &Value) -> Result<Vec<f32>, String> {
let area = proxy.bounds();
if params.get("select").and_then(Value::as_str).unwrap_or("sampledColors") == "sampledColors" {
// Pick on the original document, not the thumbnail's nearest retained pixel. The
// prepared Lab query is the same one the command uses at full resolution.
let query = photocraft_engine::selection_cmds::ColorRangeSamples::new(&app.session, params).map_err(|e| e.to_string())?;
// Like the command (and OK): `sampleAllLayers: false` judges the active layer's own
// pixels, otherwise the composite.
let all_layers = params.get("sampleAllLayers").and_then(Value::as_bool).unwrap_or(true);
let layer = app.session.active().and_then(|d| d.active_layer).and_then(|id| proxy.layer(id)).and_then(|l| l.surface());
let px = match (all_layers, layer) {
(false, Some(surf)) => {
let mut px = vec![[0.0f32; 4]; area.width() as usize * area.height() as usize];
surf.read_rgba_into(area, &mut px);
px
}
_ => photocraft_compose::render(proxy, area).px,
};
let invert = params.get("invert").and_then(Value::as_bool).unwrap_or(false);
return Ok(query
.coverage(&px, area.width() as usize, k as f32, [0.0, 0.0])
.into_iter()
.map(|v| {
let v = if invert { 1.0 - v } else { v };
// Match the command's GRAY8 mask rounding, before display interpolation.
(v.clamp(0.0, 1.0) * 255.0 + 0.5).floor() / 255.0
})
.collect());
}
if params.get("select").and_then(Value::as_str) == Some("outOfGamut") {
let pv = app.session.color.proof(proxy.id);
let (m, _) = photocraft_engine::color_cmds::gamut_mask(proxy, &pv.setup, pv.gamut_threshold).map_err(|e| e.to_string())?;
@@ -236,11 +291,23 @@ fn preview(app: &mut PhotocraftApp, ctx: &egui::Context, f: &Map<String, Value>)
let side = doc.size.width.max(doc.size.height).max(1);
let k = side.div_ceil(PREVIEW).max(1);
let proxy = Arc::new(crate::proxy::proxy_document(&doc, k));
app.color_range = Some(Preview { doc: doc_id, revision, k, proxy, image: None, mask_key: 0, mask: None, error: None });
app.color_range = Some(Preview {
doc: doc_id,
revision,
k,
proxy,
image: None,
mask_key: 0,
mask: None,
error: None,
canvas_proxy: None,
overlay: None,
overlay_key: 0,
});
}
let image_view = s(f, "__view", "selection") == "image";
let image_view = (s(f, "__view", "selection") == "image") ^ ctx.input(|i| i.modifiers.command || (!cfg!(target_os = "macos") && i.modifiers.ctrl));
let params = params(f);
let key = hash(&params.to_string()).max(1);
let key = query_key(app, &params);
let (proxy, k) = {
let p = app.color_range.as_ref()?;
(p.proxy.clone(), p.k)
@@ -248,7 +315,14 @@ fn preview(app: &mut PhotocraftApp, ctx: &egui::Context, f: &Map<String, Value>)
let (w, h) = (proxy.size.width as usize, proxy.size.height as usize);
if image_view {
if app.color_range.as_ref().is_some_and(|p| p.image.is_none()) {
let thumb = photocraft_compose::thumbnail(&proxy, proxy.size.width.max(proxy.size.height));
let buf = photocraft_compose::thumbnail_buffer(&proxy, proxy.size.width.max(proxy.size.height));
let thumb = match app.session.color.canvas_display(&proxy) {
Ok(display) => display.to_rgba8(&buf),
Err(e) => {
report(app, Some(e.to_string()));
return None;
}
};
let size = [thumb.width as usize, thumb.height as usize];
if size != [w, h] || thumb.pixels.len() != w * h * 4 {
report(app, Some(format!("the image thumbnail is {}×{}, expected {w}×{h}", thumb.width, thumb.height)));
@@ -380,7 +454,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
ui.horizontal_top(|ui| {
// Preview: the selection as a grayscale mask, or the image to pick colours from.
let box_size = vec2(PREVIEW as f32, PREVIEW as f32);
let (frame, resp) = ui.allocate_exact_size(box_size, Sense::click());
let (frame, resp) = ui.allocate_exact_size(box_size, Sense::click_and_drag());
ui.painter().rect_filled(frame, 0.0, t.canvas);
let shown = preview(app, ui.ctx(), f);
if let Some((tex, [w, h], k)) = shown {
@@ -388,7 +462,13 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
let img_rect = Rect::from_center_size(frame.center(), vec2(w as f32 * scale, h as f32 * scale));
ui.painter().image(tex, img_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
// Eyedropper on the preview (Photoshop also samples in the preview area).
if let Some(p) = resp.interact_pointer_pos().filter(|p| resp.clicked() && c.sampling && img_rect.contains(*p)) {
// Response::clicked may consume accessibility input (a write lock): query it
// before reading PointerState, never from inside Ui::input's read lock.
let clicked = resp.clicked();
let held = resp.is_pointer_button_down_on();
let sample =
ui.input(|i| (clicked && i.pointer.primary_pressed()) || (held && (i.pointer.primary_pressed() || i.pointer.delta() != egui::Vec2::ZERO)));
if let Some(p) = resp.interact_pointer_pos().filter(|p| c.sampling && sample && img_rect.contains(*p)) {
let at = [
((p.x - img_rect.left()) / scale).floor().max(0.0) as f64 * f64::from(k) + f64::from(k / 2),
((p.y - img_rect.top()) / scale).floor().max(0.0) as f64 * f64::from(k) + f64::from(k / 2),
@@ -459,11 +539,80 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
f.insert("__view".into(), json!("image"));
}
});
ui.add_space(6.0);
ui.horizontal(|ui| {
ui.label(egui::RichText::new(tl!("Selection Preview:")).color(t.text_dim));
let mode = s(f, "__selectionPreview", "none").to_string();
let mut chosen = mode.as_str();
if widgets::dropdown(ui, "color-range-selection-preview", &mut chosen, PREVIEWS, 170.0) {
f.insert("__selectionPreview".into(), json!(chosen));
}
});
if app.session.active().is_none() {
ui.label(egui::RichText::new(tl!("Open a document to select a colour range.")).color(t.text_faint));
}
}
/// A selection view is an overlay only: eyedroppers always sample the original image below it.
/// White = selected, black = unselected, gray = partial; matte/Quick Mask cover unselected pixels.
fn overlay_pixel(mode: &str, coverage: f32) -> Color32 {
let coverage = coverage.clamp(0.0, 1.0);
let q = |v: f32| (v * 255.0 + 0.5) as u8;
match mode {
"grayscale" => Color32::from_gray(q(coverage)),
"blackMatte" => Color32::from_black_alpha(q(1.0 - coverage)),
"whiteMatte" => Color32::from_rgba_unmultiplied(255, 255, 255, q(1.0 - coverage)),
"quickMask" => Color32::from_rgba_unmultiplied(255, 0, 0, q(0.5 * (1.0 - coverage))),
_ => Color32::TRANSPARENT,
}
}
/// Photoshop's Selection Preview on the image, shared by CPU/GPU canvases and all platforms.
/// This never edits the real selection, image, channels or history; closing the dialog removes it.
pub(crate) fn paint_selection_preview(app: &mut PhotocraftApp, ctx: &egui::Context, painter: &egui::Painter, doc: DocId, image: Rect, flip: bool) {
let Some(fields) = app.ui.dialogs.last().filter(|d| owns(&d.fields)).map(|d| d.fields.clone()) else { return };
let mode = s(&fields, "__selectionPreview", "none");
if mode == "none" || !app.session.active().is_some_and(|st| st.doc.id == doc) {
return;
}
// Refresh the document/revision cache before borrowing its canvas proxy.
let _ = preview(app, ctx, &fields);
if app.color_range.as_ref().is_some_and(|p| p.canvas_proxy.is_none()) {
let Some(original) = app.session.active().map(|st| st.doc.clone()) else { return };
let k = original.size.width.max(original.size.height).max(1).div_ceil(CANVAS_PREVIEW);
let proxy = Arc::new(crate::proxy::proxy_document(&original, k));
if let Some(p) = app.color_range.as_mut() {
p.canvas_proxy = Some((k, proxy));
}
}
let params = params(&fields);
let key = (query_key(app, &params) ^ hash(mode)).max(1);
if app.color_range.as_ref().is_some_and(|p| p.overlay_key != key || p.overlay.is_none()) {
let Some((k, proxy)) = app.color_range.as_ref().and_then(|p| p.canvas_proxy.clone()) else { return };
let mask = match proxy_mask(app, &proxy, k, &params) {
Ok(mask) => mask,
Err(e) => {
report(app, Some(e));
return;
}
};
let size = [proxy.size.width as usize, proxy.size.height as usize];
let pixels = mask.into_iter().map(|v| overlay_pixel(mode, v)).collect();
let img = egui::ColorImage::new(size, pixels);
if let Some(p) = app.color_range.as_mut() {
match &mut p.overlay {
Some(t) => t.set(img, egui::TextureOptions::LINEAR),
None => p.overlay = Some(ctx.load_texture("color-range-canvas-preview", img, egui::TextureOptions::LINEAR)),
}
p.overlay_key = key;
}
}
if let Some(tex) = app.color_range.as_ref().and_then(|p| p.overlay.as_ref()) {
let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)) };
painter.image(tex.id(), image, uv, Color32::WHITE);
}
}
/// The top dialog's fields when it is Color Range in a mode that takes eyedropper samples.
fn sampling_top(app: &PhotocraftApp) -> Option<Map<String, Value>> {
app.ui.dialogs.last().map(|d| &d.fields).filter(|f| owns(f) && controls(f).sampling).cloned()
@@ -474,6 +623,10 @@ fn sampling_top(app: &PhotocraftApp) -> Option<Map<String, Value>> {
/// on the image does in Photoshop. Returns whether it picked.
pub fn pick_top(app: &mut PhotocraftApp, at: [f64; 2], mods: egui::Modifiers) -> bool {
let Some(mut f) = sampling_top(app) else { return false };
let Some(doc) = app.session.active().map(|st| &st.doc) else { return false };
if !at[0].is_finite() || !at[1].is_finite() || at[0] < 0.0 || at[1] < 0.0 || at[0] >= f64::from(doc.size.width) || at[1] >= f64::from(doc.size.height) {
return false;
}
pick(app, &mut f, at, mods);
match app.ui.dialogs.last_mut() {
Some(d) => {
@@ -529,7 +682,7 @@ pub fn pick(app: &PhotocraftApp, f: &mut Map<String, Value>, at: [f64; 2], mods:
let Some(st) = app.session.active() else { return };
let (w, h) = (f64::from(st.doc.size.width.max(1)), f64::from(st.doc.size.height.max(1)));
let [x, y] = at;
let at = [x.clamp(0.0, w - 1.0), y.clamp(0.0, h - 1.0)];
let at = [x.floor().clamp(0.0, w - 1.0), y.floor().clamp(0.0, h - 1.0)];
let tool = if mods.shift {
"add"
} else if mods.alt {
@@ -635,6 +788,67 @@ mod tests {
h.get_by_label(label).accesskit_node().is_disabled()
}
#[test]
fn preview_cache_refreshes_after_foreground_and_proof_changes() {
let mut app = app_with_doc();
let p = json!({"select": "outOfGamut"});
let mut previous = query_key(&app, &p);
app.session.tools.foreground = [0.2, 0.3, 0.4, 1.0];
let key = query_key(&app, &p);
assert_ne!(key, previous);
previous = key;
for setup in [
json!({"profile": "srgb"}),
json!({"profile": "linear-srgb"}),
json!({"profile": "linear-srgb", "intent": "perceptual"}),
json!({"profile": "linear-srgb", "intent": "perceptual", "bpc": false}),
json!({"profile": "linear-srgb", "intent": "perceptual", "bpc": false, "simulatePaper": true}),
] {
app.run("view.proofSetup", setup).unwrap();
let key = query_key(&app, &p);
assert_ne!(key, previous, "changed proof settings must invalidate the preview");
assert_eq!(key, query_key(&app, &p), "an unchanged ICC profile must keep its cache key");
previous = key;
}
app.run("view.gamutWarning", json!({"on": true, "threshold": 8})).unwrap();
assert_ne!(previous, query_key(&app, &p));
previous = query_key(&app, &p);
app.run("view.gamutWarning", json!({"on": true, "threshold": 16})).unwrap();
assert_ne!(previous, query_key(&app, &p));
assert_ne!(query_key(&app, &p), query_key(&app, &json!({"select": "outOfGamut", "invert": true})));
}
#[test]
fn eyedropper_hover_reuses_preview_textures_without_sampling() {
let mut h = Harness::builder().with_size(vec2(1200.0, 900.0)).build_eframe(|cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
app_with_doc()
});
h.state_mut().ui.views[0].zoom = 20.0;
h.state_mut().ui.views[0].center = [20.0, 15.0];
h.state_mut().ui.views[0].fit_pending = false;
h.run_steps(3);
let id = open(h.state_mut());
set(&mut h, "__selectionPreview", json!("quickMask"));
let fields = h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone();
let cached = |app: &PhotocraftApp| {
let p = app.color_range.as_ref().unwrap();
(p.mask_key, p.overlay_key, p.mask.as_ref().unwrap().id(), p.overlay.as_ref().unwrap().id(), Arc::as_ptr(&p.proxy))
};
let before = cached(h.state());
let st = h.state().session.active().unwrap();
let document = (st.revision, st.history.past_len());
for i in 0..12 {
let at = crate::canvas::ViewXform::active(h.state()).unwrap().to_screen(4.0 + i as f32 * 0.5, 15.0);
h.hover_at(at);
h.run_steps(1);
assert_eq!(cached(h.state()), before, "hover must reuse the mask, overlay and proxy");
}
assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields, fields, "hover must not pick a colour");
let st = h.state().session.active().unwrap();
assert_eq!((st.revision, st.history.past_len()), document);
}
#[test]
fn opens_from_the_select_menu_without_touching_the_document() {
let mut h = harness(app_with_doc());
@@ -806,6 +1020,159 @@ mod tests {
assert_eq!(coverage(app, 5, 22), 0.0);
}
#[test]
fn selection_preview_modes_cover_only_unselected_pixels() {
assert_eq!(overlay_pixel("grayscale", 1.0), Color32::WHITE);
assert_eq!(overlay_pixel("grayscale", 0.0), Color32::BLACK);
assert_eq!(overlay_pixel("grayscale", 0.5), Color32::from_gray(128));
for mode in ["blackMatte", "whiteMatte", "quickMask"] {
assert_eq!(overlay_pixel(mode, 1.0).a(), 0, "{mode}: selected pixels stay visible");
}
assert_eq!(overlay_pixel("blackMatte", 0.0), Color32::BLACK);
assert_eq!(overlay_pixel("whiteMatte", 0.0), Color32::WHITE);
assert_eq!(overlay_pixel("quickMask", 0.0).a(), 128);
assert_eq!(overlay_pixel("quickMask", 0.5).a(), 64);
assert_eq!(overlay_pixel("none", 0.0), Color32::TRANSPARENT);
}
#[test]
fn preview_mode_is_view_state_and_cancel_preserves_selection() {
let mut h = harness(app_with_doc());
h.state_mut().run("select.rect", json!({"x": 0, "y": 20, "width": 5, "height": 5})).unwrap();
let original = h.state().session.active().unwrap();
let past = original.history.past_len();
let revision = original.revision;
let id = open(h.state_mut());
h.run_steps(3);
for (mode, _) in PREVIEWS {
set(&mut h, "__selectionPreview", json!(mode));
let f = &h.state().ui.dialogs.last().unwrap().fields;
assert!(params(f).get("__selectionPreview").is_none());
let painter = h.ctx.layer_painter(egui::LayerId::background());
let doc = h.state().session.active().unwrap().doc.id;
let ctx = h.ctx.clone();
paint_selection_preview(h.state_mut(), &ctx, &painter, doc, Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)), false);
let st = h.state().session.active().unwrap();
assert_eq!((st.revision, st.history.past_len()), (revision, past));
assert_eq!(coverage(h.state(), 2, 22), 1.0);
}
h.state_mut().ui.close_dialog(id);
let painter = h.ctx.layer_painter(egui::LayerId::background());
let ctx = h.ctx.clone();
let doc = h.state().session.active().unwrap().doc.id;
paint_selection_preview(h.state_mut(), &ctx, &painter, doc, Rect::EVERYTHING, false);
assert_eq!(coverage(h.state(), 2, 22), 1.0);
}
#[test]
fn repeated_subtraction_clicks_are_not_discarded() {
let mut app = app_with_doc();
let id = open(&mut app);
let mut f = app.ui.dialog_mut(id).unwrap().fields.clone();
pick(&app, &mut f, [2.0, 2.0], egui::Modifiers::NONE);
pick(&app, &mut f, [30.0, 2.0], egui::Modifiers::SHIFT);
pick(&app, &mut f, [30.0, 2.0], egui::Modifiers::ALT);
pick(&app, &mut f, [30.0, 2.0], egui::Modifiers::ALT);
assert_eq!(params(&f)["order"], json!(["+", "+", "-", "-"]));
}
#[test]
fn control_pointer_drag_samples_and_never_paints_under_the_dialog() {
let mut h = harness(app_with_doc());
let app = h.state_mut();
open(app);
let doc = app.session.active().unwrap();
let before = doc.revision;
let history = doc.history.past_len();
let ctx = h.ctx.clone();
for (events, shift) in [
(json!([{"kind":"down","x":2,"y":2},{"kind":"move","x":3,"y":2},{"kind":"up","x":3,"y":2}]), false),
(json!([{"kind":"down","x":30,"y":2},{"kind":"move","x":31,"y":2},{"kind":"up","x":31,"y":2}]), true),
] {
let (req, _) = crate::control::ControlRequest::new("ui.pointer", json!({"events":events,"shift":shift}));
let _ = crate::control::handle(h.state_mut(), &ctx, &req);
}
let fields = &h.state().ui.dialogs.last().unwrap().fields;
assert_eq!(points(fields, "points"), [[3.0, 2.0], [30.0, 2.0], [31.0, 2.0]]);
let doc = h.state().session.active().unwrap();
assert_eq!((doc.revision, doc.history.past_len()), (before, history));
assert!(h.state().drag.is_none());
assert!(!pick_top(h.state_mut(), [-1.0, 0.0], egui::Modifiers::NONE));
}
#[test]
fn modifier_temporarily_swaps_image_and_selection_thumbnail() {
let mut h = harness(app_with_doc());
let id = open(h.state_mut());
h.run_steps(3);
let f = h.state().ui.dialogs.last().unwrap().fields.clone();
let ctx = h.ctx.clone();
let selection = preview(h.state_mut(), &ctx, &f).unwrap().0;
h.event(egui::Event::ModifiersChanged(egui::Modifiers::COMMAND));
h.run_steps(2);
let image = preview(h.state_mut(), &ctx, &f).unwrap().0;
assert_ne!(image, selection);
assert_eq!(h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields["__view"], "selection");
h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
h.run_steps(2);
assert_eq!(preview(h.state_mut(), &ctx, &f).unwrap().0, selection);
}
/// A sample between thumbnail pixels must use the original pixel, not its neighbour.
#[test]
fn reduced_preview_matches_the_original_eyedropper_sample() {
let mut doc = Document::with_background("fine detail", Size::new(400, 4), ColorMode::Rgb, SampleType::U8, Color::rgb(1.0, 0.0, 0.0));
let surface = doc.layers[0].surface_mut().unwrap();
surface.fill_rect(GRect::new(200, 0, 400, 4), &[0.0, 0.0, 1.0, 1.0]);
surface.fill_rect(GRect::new(101, 0, 102, 4), &[0.0, 0.0, 1.0, 1.0]);
let mut session = photocraft_engine::Session::new();
session.add_document(doc, None);
let mut app = PhotocraftApp::new(session, crate::Services::default());
let id = open(&mut app);
let mut fields = app.ui.dialog_mut(id).unwrap().fields.clone();
pick(&app, &mut fields, [101.0, 1.0], egui::Modifiers::NONE);
fields.insert("fuzziness".into(), json!(0.0));
let original = app.session.active().unwrap().doc.clone();
let proxy = crate::proxy::proxy_document(&original, 2);
let mut old = photocraft_engine::Session::new();
old.add_document(proxy.clone(), None);
old.execute(COMMAND, json!({"points": [[50, 0]], "fuzziness": 0})).unwrap();
assert_eq!(
old.active().unwrap().doc.selection.as_ref().unwrap().sample_channel(150, 0, 0),
0.0,
"sampling the thumbnail instead selects the red neighbour"
);
let shown = proxy_mask(&app, &proxy, 2, &params(&fields)).unwrap();
confirm(&mut app, &fields).unwrap();
assert_eq!(coverage(&app, 300, 0), 1.0);
assert_eq!(shown[150], coverage(&app, 300, 0), "preview must show the same blue pixels as OK");
assert_eq!(shown[0], coverage(&app, 0, 0), "preview must leave the red background unselected");
}
/// `sampleAllLayers: false` judges the active layer in the preview, as OK does.
#[test]
fn preview_honours_sample_all_layers_like_ok() {
let mut app = app_with_doc();
let doc = app.session.active().unwrap().doc.clone();
let mut top = photocraft_doc::Layer::new("blue cover", photocraft_doc::LayerContent::Raster(doc.layers[0].surface().unwrap().clone()));
top.surface_mut().unwrap().fill_rect(GRect::new(0, 0, 40, 30), &[0.0, 0.0, 1.0, 1.0]);
app.session
.edit("layers", |doc, _| {
doc.layers.push(top);
Ok(())
})
.unwrap();
for all_layers in [false, true] {
let p = json!({"select": "sampledColors", "points": [[5, 5]], "fuzziness": 0, "sampleAllLayers": all_layers});
let proxy = crate::proxy::proxy_document(&app.session.active().unwrap().doc, 1);
let shown = proxy_mask(&app, &proxy, 1, &p).unwrap();
app.run(COMMAND, p).unwrap();
for (x, y) in [(5, 5), (30, 5), (5, 20), (30, 20)] {
assert_eq!(shown[y * 40 + x], coverage(&app, x as i32, y as i32), "all_layers={all_layers} at ({x}, {y})");
}
}
}
#[test]
fn params_send_only_what_the_mode_uses() {
let mut app = app_with_doc();
+14 -4
View File
@@ -567,6 +567,20 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
}
continue;
}
// The dialog owns all pointer events, including Up: no underlying brush stroke
// or context menu may leak through while inspecting a Color Range preview.
if app.ui.dialogs.last().is_some_and(|d| crate::color_range_ui::owns(&d.fields)) {
let down = matches!(ev, ToolEvent::Down { .. });
let up = matches!(ev, ToolEvent::Up { .. });
let held = app.ui.dialogs.last().and_then(|d| d.fields.get("__pointerDown")).and_then(Value::as_bool).unwrap_or(false);
if let Some(d) = app.ui.dialogs.last_mut() {
d.fields.insert("__pointerDown".into(), json!(!up && (down || held)));
}
if !up && (down || held) && !space && !matches!(s("button"), Some("secondary" | "right" | "middle")) {
crate::color_range_ui::pick_top(app, [x, y], mods);
}
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.
@@ -597,10 +611,6 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
if let Some(d) = app.drag.as_mut().filter(|d| crate::hold_keys::repositions(d.tool)) {
d.reposition = space;
}
// Color Range › Sampled Colors on top: a press is its eyedropper on the image.
if matches!(ev, ToolEvent::Down { .. }) && crate::color_range_ui::pick_top(app, [x, y], mods) {
continue;
}
tool_event(app, ev, mods);
}
app.stylus.feed.set(None);
+3
View File
@@ -2191,6 +2191,9 @@ cameraRaw Color Barvy
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
Selection Preview: Náhled výběru:
Black Matte Černý podklad
White Matte Bílý podklad
# Layer colour labels.
Seafoam Mořská pěna
Can't render this file because it contains an unexpected character in line 6 and column 47.
+3
View File
@@ -2230,6 +2230,9 @@
Set Neutral Gray Point Neutralen Graupunkt festlegen
Set White Point Weißpunkt festlegen
Unavailable in this color mode In diesem Farbmodus nicht verfügbar
Selection Preview: Auswahlvorschau:
Black Matte Schwarzer Hintergrund
White Matte Weißer Hintergrund
# Layer colour labels.
layerLabel No Color Keine Farbe
Can't render this file because it contains an unexpected character in line 6 and column 47.
+3
View File
@@ -2261,6 +2261,9 @@ cameraRaw Amount Cantidad
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
Selection Preview: Previsualización de selección:
Black Matte Fondo negro
White Matte Fondo blanco
# Layer colour labels.
Seafoam Espuma de mar
Can't render this file because it contains an unexpected character in line 4 and column 47.
+3
View File
@@ -2620,6 +2620,9 @@ cameraRaw Blending Fusion
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
Selection Preview: Aperçu de la sélection :
Black Matte Fond noir
White Matte Fond blanc
# Layer colour labels.
Seafoam Écume de mer
Can't render this file because it contains an unexpected character in line 6 and column 47.
+3
View File
@@ -2607,6 +2607,9 @@ cameraRaw Blending Pembauran
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
Selection Preview: Pratinjau Seleksi:
Black Matte Latar Hitam
White Matte Latar Putih
# Layer colour labels.
Seafoam Busa Laut
Can't render this file because it contains an unexpected character in line 4 and column 47.
+3
View File
@@ -2263,6 +2263,9 @@ cameraRaw Amount Quantità
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
Selection Preview: Anteprima selezione:
Black Matte Sfondo nero
White Matte Sfondo bianco
# Layer colour labels.
Seafoam Schiuma marina
1 # Italian (it) catalog. Columns, separated by a TAB: context <TAB> source <TAB> translation
2263 fontWeight
2264 fontWeight
2265 fontWeight
2266 fontWeight
2267 fontWeight
2268 fontWeight
2269 fontWeight
2270 # Pattern Stamp tool
2271
+3
View File
@@ -2174,6 +2174,9 @@ cameraRaw Color カラー
Set Neutral Gray Point 中間調のグレーポイントを設定
Set White Point 白色点を設定
Unavailable in this color mode このカラーモードでは使用できません
Selection Preview: 選択範囲のプレビュー:
Black Matte 黒の背景
White Matte 白の背景
# Layer colour labels.
Seafoam シーフォーム
Can't render this file because it contains an unexpected character in line 6 and column 47.
+3
View File
@@ -2776,6 +2776,9 @@ cameraRaw Color 색상
Click a red pupil to neutralize it 빨간 동공을 클릭하여 보정합니다
open source 오픈 소스
…and {n} more …외 {n}개
Selection Preview: 선택 영역 미리 보기:
Black Matte 검정 배경
White Matte 흰색 배경
# Layer colour labels.
Seafoam 바다 거품색
1 # Korean (ko) catalog. UTF-8: context<TAB>English source<TAB>translation.
2776 fontWeight
2777 fontWeight
2778 fontWeight
2779 fontWeight
2780 fontWeight
2781 fontWeight
2782 fontWeight
2783 fontWeight
2784 fontWeight
+3
View File
@@ -3235,6 +3235,9 @@ cameraRaw Roughness Chropowatość
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
Selection Preview: Podgląd zaznaczenia:
Black Matte Czarne tło
White Matte Białe tło
# Layer colour labels.
Seafoam Morski
Can't render this file because it contains an unexpected character in line 6 and column 47.
+3
View File
@@ -2627,6 +2627,9 @@ cameraRaw Whites Brancos
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
Selection Preview: Visualização da seleção:
Black Matte Fundo preto
White Matte Fundo branco
# Layer colour labels.
Seafoam Espuma do mar
Can't render this file because it contains an unexpected character in line 6 and column 47.
+4
View File
@@ -2467,6 +2467,10 @@ cameraRaw Roughness Неровность
Set Neutral Gray Point Задать нейтральную серую точку
Set White Point Задать точку белого
Unavailable in this color mode Недоступно в этом цветовом режиме
Selection Preview: Просмотр выделения:
Black Matte На чёрном фоне
White Matte На белом фоне
Quick Mask Быстрая маска
# Layer colour labels.
Seafoam Морская пена
Can't render this file because it contains an unexpected character in line 6 and column 47.
+3
View File
@@ -2199,6 +2199,9 @@ cameraRaw Blending 混合
Set Neutral Gray Point 设置中性灰场
Set White Point 设置白场
Unavailable in this color mode 此颜色模式下不可用
Selection Preview: 选区预览:
Black Matte 黑色背景
White Matte 白色背景
# Layer colour labels.
Seafoam 海沫色
1 # Simplified Chinese (zh-hans) catalog. UTF-8, TAB-separated columns:
2199
2200
2201
2202
2203
2204
2205 fontWeight
2206 fontWeight
2207 fontWeight
+3
View File
@@ -2168,6 +2168,9 @@ cameraRaw Blending 混合
Set Neutral Gray Point 設定中性灰點
Set White Point 設定白點
Unavailable in this color mode 此色彩模式無法使用
Selection Preview: 選取範圍預視:
Black Matte 黑色背景
White Matte 白色背景
# Layer colour labels.
Seafoam 海沫色
Can't render this file because it contains an unexpected character in line 6 and column 47.
+15
View File
@@ -131,6 +131,21 @@ fn color_range_eyedropper_picks_on_the_canvas() {
// ⇧-click adds another sample; the dialog never closes.
click(&mut h, screen([60.5, 40.5]), Modifiers::SHIFT);
assert_eq!(points(&h).0, 2);
click(&mut h, screen([60.5, 40.5]), Modifiers::ALT);
assert_eq!(h.state().ui.dialogs.last().unwrap().fields["subtractPoints"].as_array().unwrap().len(), 1);
// A stationary held button must not subtract again on every redraw.
let p = screen([60.5, 40.5]);
h.event_modifiers(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::ALT }, Modifiers::ALT);
h.run_steps(4);
assert_eq!(h.state().ui.dialogs.last().unwrap().fields["subtractPoints"].as_array().unwrap().len(), 2);
h.event_modifiers(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::ALT }, Modifiers::ALT);
h.run_steps(2);
// The modal eyedropper overrides a previously selected Hand tool.
h.state_mut().ui.tool = crate::state::Tool::Hand;
let center = h.state().ui.views[0].center;
click(&mut h, screen([30.5, 40.5]), Modifiers::NONE);
assert_eq!(points(&h).0, 1);
assert_eq!(h.state().ui.views[0].center, center);
assert_eq!(h.state().ui.dialogs.len(), 1);
// The document is untouched until OK.
assert!(h.state().session.active().unwrap().doc.selection.is_none());
+20 -10
View File
@@ -171,20 +171,20 @@ pub fn import_bytes(app: &mut PhotocraftApp, name: &str, bytes: &[u8], replace:
}
fn import_dialog(app: &mut PhotocraftApp, replace: bool) -> Result<Value, String> {
let (name, bytes) = app.pick_file_bytes().ok_or("cancelled")??;
import_bytes(app, &name, &bytes, replace)
app.pick_file_bytes(move |app, name, bytes| import_bytes(app, &name, &bytes, replace))
}
fn export_dialog(app: &mut PhotocraftApp, format: &str) -> Result<Value, String> {
let r = app.run("swatches.export", json!({"format": format}))?;
let bytes = r["data"].as_str().and_then(photocraft_engine::paint::tile::b64_decode).ok_or("the export returned no data")?;
let path = app.services.pick_save.as_mut().and_then(|f| f(&format!("Swatches.{format}"))).ok_or("cancelled")?;
let write = app.services.write.as_mut().ok_or("no writer configured")?;
write(&path, &bytes)?;
let n = r["count"].as_u64().unwrap_or(0);
app.ui.status_error = false;
app.ui.status = format!("Exported {n} swatches to {}", crate::file_open::display_name(&path));
Ok(json!({"path": path, "count": n}))
app.pick_save(&format!("Swatches.{format}"), move |app, path| {
let write = app.services.write.as_mut().ok_or("no writer configured")?;
write(&path, &bytes)?;
app.ui.status_error = false;
app.ui.status = format!("Exported {n} swatches to {}", crate::file_open::display_name(&path));
Ok(json!({"path": path, "count": n}))
})
}
/// The Swatches entries of the panel group's menu ("…").
@@ -348,9 +348,14 @@ mod tests {
let aco =
photocraft_psd::aco::write(&[photocraft_psd::aco::AcoSwatch { name: "Teal".into(), color: photocraft_psd::aco::AcoColor::Rgb([0, 32768, 32768]) }])
.unwrap();
use crate::file_dialog::FileDialogAnswer;
let answers = vec![
Some(FileDialogAnswer::Contents("Ocean.aco".into(), aco.clone())),
Some(FileDialogAnswer::Contents("Ocean.aco".into(), aco)),
Some(FileDialogAnswer::SaveTo("out/Swatches.ase".into())),
];
let services = crate::Services {
pick_open: Some(Box::new(move || Some(("Ocean.aco".to_string(), Ok(aco.clone()))))),
pick_save: Some(Box::new(|s: &str| Some(format!("out/{s}")))),
file_dialog: Some(crate::file_dialog::fake(answers).0),
write: Some(Box::new(move |p: &str, b: &[u8]| {
w.lock().unwrap().push((p.to_string(), b.to_vec()));
Ok(())
@@ -358,11 +363,16 @@ mod tests {
..Default::default()
};
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
// Each dialog answers at the end of the frame.
let frame = |app: &mut PhotocraftApp| app.poll_file_dialog(&egui::Context::default(), None);
import_dialog(&mut app, false).unwrap();
frame(&mut app);
assert_eq!(app.session.presets.swatches.last().unwrap().name, "Ocean");
import_dialog(&mut app, true).unwrap();
frame(&mut app);
assert_eq!(app.session.presets.swatches.len(), 1, "replace");
export_dialog(&mut app, "ase").unwrap();
frame(&mut app);
let out = written.lock().unwrap();
assert_eq!(out[0].0, "out/Swatches.ase");
assert!(out[0].1.starts_with(b"ASEF"));
+8 -2
View File
@@ -6,7 +6,7 @@ use std::rc::Rc;
use std::sync::Arc;
use egui_kittest::kittest::Queryable;
use photocraft_ui_egui::{PhotocraftApp, Services, menus};
use photocraft_ui_egui::{FileDialogAnswer, FileDialogRequest, PhotocraftApp, Services, menus};
use serde_json::json;
type Harness = egui_kittest::Harness<'static, PhotocraftApp>;
@@ -20,7 +20,13 @@ fn harness() -> Option<(Harness, Writes)> {
move |cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
let services = Services {
pick_save: Some(Box::new(|suggested| Some(suggested.to_string()))),
// Save dialogs answer with the suggested name.
file_dialog: Some(Box::new(|request, _parent, reply| {
reply.send(match request {
FileDialogRequest::Save { suggested } => Some(FileDialogAnswer::SaveTo(suggested)),
FileDialogRequest::Open { .. } => None,
})
})),
export: Some(Box::new(|doc, path, settings| {
let opts = photocraft_io::ExportOptions {
xmp: if settings.xmp_all { photocraft_io::XmpEmbed::All } else { photocraft_io::XmpEmbed::None },