Delete files no module compiles (widgets, point curve, brush controls, analysis_ui, old cursors, dead editors and tests, nefc tests)

This commit is contained in:
aiongg committed 2026-11-23 05:50:07 +00:00
1 parent e23da5f248
commit 9cf019ed37
15 files changed
+2 -5413

No files matched your search

-581
View File
@@ -1,581 +0,0 @@
use super::*;
/// MSB-first bit writer for the test encoder.
#[derive(Default)]
struct Writer {
out: Vec<u8>,
acc: u64,
n: u32,
}
impl Writer {
fn put(&mut self, v: u32, len: u32) {
for i in (0..len).rev() {
self.acc = (self.acc << 1) | u64::from((v >> i) & 1);
self.n += 1;
if self.n == 8 {
self.out.push(self.acc as u8);
self.acc = 0;
self.n = 0;
}
}
}
fn finish(mut self) -> Vec<u8> {
if self.n > 0 {
self.out.push((self.acc << (8 - self.n)) as u8);
}
self.out.extend_from_slice(&[0; 4]);
self.out
}
}
/// `(code, length)` per category, from the canonical table.
fn codes(t: &Table) -> Vec<(u32, u32)> {
let mut out = vec![(0, 0); 17];
let mut code = 0u32;
let mut symbols = t.symbols.iter();
for (i, &n) in t.counts.iter().enumerate() {
for _ in 0..n {
let s = *symbols.next().unwrap();
if s != UNSEEN {
out[s as usize] = (code, i as u32 + 1);
}
code += 1;
}
code <<= 1;
}
out
}
/// Encodes `values` (samples or curve indices) the way the camera does.
fn encode(values: &[i32], w: usize, t: &Table, seeds: [[i32; 2]; 2]) -> Vec<u8> {
let codes = codes(t);
let mut wr = Writer::default();
let mut vpred = seeds;
for (y, row) in values.chunks(w).enumerate() {
for (x, &v) in row.iter().enumerate() {
let pred = if x < 2 { vpred[y & 1][x] } else { row[x - 2] };
if x < 2 {
vpred[y & 1][x] = v;
}
let d = v - pred;
let k = 32 - d.unsigned_abs().leading_zeros();
let (code, len) = codes[k as usize];
assert!(len > 0, "no code for category {k}");
wr.put(code, len);
wr.put(if d < 0 { (d + (1 << k) - 1) as u32 } else { d as u32 }, k);
}
}
wr.finish()
}
/// Smooth gradient + texture + hard edges, within `0..=max`.
fn image(w: usize, h: usize, max: i32, seed: u32) -> Vec<i32> {
let mut s = seed;
(0..w * h)
.map(|i| {
let (x, y) = ((i % w) as i32, (i / w) as i32);
s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
let noise = (s >> 24) as i32 % 9 - 4;
let base = (x * 37 + y * 11) % (max / 2) + if (x / 7 + y / 5) % 3 == 0 { max / 3 } else { 0 };
(base + noise).clamp(0, max)
})
.collect()
}
fn lossless(bits: u32) -> DecodeTable {
let s = 1 << (bits - 3);
DecodeTable { encoding: Encoding::Lossless, seeds: [[s, s], [s, s]], split: 0 }
}
fn lossy_table(bits: u32, le: bool) -> Vec<u8> {
let mut t = vec![0x44, 0x20];
let put = |t: &mut Vec<u8>, v: u16| t.extend_from_slice(&if le { v.to_le_bytes() } else { v.to_be_bytes() });
for _ in 0..4 {
put(&mut t, 300);
}
put(&mut t, 257);
let max = f64::from((1u32 << bits) - 1);
for i in 0..257u32 {
put(&mut t, (max * (f64::from(i) / 64.0).min(1.0).sqrt()) as u16);
}
t.resize(624, 0);
t
}
#[test]
fn tables_are_prefix_codes() {
for t in [LOSSLESS_12, LOSSLESS_14, LOSSY_12, LOSSY_14] {
assert_eq!(t.counts.iter().map(|&c| c as usize).sum::<usize>(), t.symbols.len());
let kraft: f64 = t.counts.iter().enumerate().map(|(i, &c)| f64::from(c) / f64::from(1u32 << (i + 1))).sum();
assert!(kraft <= 1.0);
assert!(Huffman::new(&t).is_ok());
}
}
#[test]
fn lossless_round_trip_12_and_14() {
for (bits, t) in [(12, LOSSLESS_12), (14, LOSSLESS_14)] {
let (w, h) = (64, 9);
let max = (1 << bits) - 1;
let mut img = image(w, h, max, bits);
img[5] = 0;
img[7] = max;
img[w + 9] = max;
let table = lossless(bits);
let out = decode(&encode(&img, w, &t, table.seeds), w, h, bits, &table).unwrap();
assert_eq!(out, img.iter().map(|&v| v as u16).collect::<Vec<_>>(), "{bits}-bit");
}
}
#[test]
fn lossy_type2_curve_and_round_trip() {
for (bits, t) in [(12u32, LOSSY_12), (14, LOSSY_14)] {
for le in [false, true] {
let table = parse_table(&lossy_table(bits, le), le, bits).unwrap();
assert_eq!(table.seeds, [[300, 300], [300, 300]]);
let Encoding::Lossy(curve) = &table.encoding else { panic!() };
let step = (1usize << bits) / 256;
assert_eq!(curve.len(), (1 << bits) + 1);
assert_eq!(curve[64 * step], (1 << bits) - 1);
assert!(curve.windows(2).all(|p| p[0] <= p[1]));
let (w, h) = (48, 7);
let img = image(w, h, 64 * step as i32 - 1, 7);
let out = decode(&encode(&img, w, &t, table.seeds), w, h, bits, &table).unwrap();
assert_eq!(out, img.iter().map(|&v| curve[v as usize]).collect::<Vec<_>>());
}
}
}
#[test]
fn lossy_type1_full_curve() {
let mut t = vec![0x44, 0x10, 0, 10, 0, 10, 0, 10, 0, 10, 0, 5];
for v in [0u16, 100, 400, 900, 1600] {
t.extend_from_slice(&v.to_be_bytes());
}
let table = parse_table(&t, false, 12).unwrap();
assert_eq!(table.encoding, Encoding::Lossy(vec![0, 100, 400, 900, 1600]));
let img = vec![0, 4, 1, 3, 2, 2, 4, 0];
assert_eq!(decode(&encode(&img, 4, &LOSSY_12, table.seeds), 4, 2, 12, &table).unwrap(), vec![0, 1600, 100, 900, 400, 400, 1600, 0]);
}
#[test]
fn unsupported_and_malformed_tables() {
let unsupported = |r: Result<DecodeTable>| matches!(r, Err(RawError::Unsupported(_)));
let malformed = |r: Result<DecodeTable>| matches!(r, Err(RawError::Malformed(_)));
let mut split = lossy_table(12, false);
split[562..564].copy_from_slice(&345u16.to_be_bytes());
assert_eq!(parse_table(&split, false, 12).unwrap().split, 345);
assert!(unsupported(parse_table(&[0x49, 0x30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], false, 12)));
assert!(unsupported(parse_table(&lossy_table(12, false), false, 16)));
assert!(malformed(parse_table(&[], false, 12)));
assert!(malformed(parse_table(&[0x46, 0x30, 8], false, 14)));
assert!(malformed(parse_table(&lossy_table(12, false)[..100], false, 12)));
let mut odd = lossy_table(12, false);
odd[10..12].copy_from_slice(&300u16.to_be_bytes());
assert!(parse_table(&odd, false, 12).is_err());
assert!(parse_table(&[0x44, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], false, 12).is_err());
}
#[test]
fn modern_lossy_curve_preserves_sensor_adus_at_both_depths() {
for bits in [12u32, 14] {
for le in [false, true] {
let put = |v: u16| if le { v.to_le_bytes() } else { v.to_be_bytes() };
let mut t = vec![0x44, 0x40];
for _ in 0..4 {
t.extend(put(256));
}
t.extend(put(257));
let white = (1u16 << bits) - 1;
for i in 0..=256u32 {
t.extend(put(((i * 64).min(u32::from(white))) as u16));
}
t.resize(624, 0);
let parsed = parse_table(&t, le, bits).unwrap();
let Encoding::Lossy(curve) = &parsed.encoding else { panic!() };
let range = 1usize << (bits - 2);
assert_eq!(curve.len(), range + 1);
assert_eq!(curve[range], white);
// Stored point 16 is 1024 ADU. It belongs to encoded code 256
// at 14 bits, code 64 at 12 bits, independent of end-point clipping.
assert_eq!(curve[range / 16], 1024.min(white));
let indices = vec![0, (range / 16) as i32, (range / 8) as i32, (range / 32) as i32];
let huffman = if bits == 12 { &LOSSY_12 } else { &LOSSY_14 };
let src = encode(&indices, 2, huffman, parsed.seeds);
assert_eq!(decode(&src, 2, 2, bits, &parsed).unwrap(), vec![0, 1024, 2048, 512]);
}
}
}
/// A 14-bit lossless table (version 0x46) with the given seeds.
fn lossless_table(seed: u16, le: bool) -> Vec<u8> {
let mut t = vec![0x46, 0x30];
for _ in 0..4 {
t.extend_from_slice(&if le { seed.to_le_bytes() } else { seed.to_be_bytes() });
}
t.resize(46, 0);
t
}
#[test]
fn decodes_through_the_nef_container() {
use crate::testgen::{Val, nef_compressed};
use crate::{Limits, RawFormat, identify};
let (w, h) = (40usize, 6usize);
// lossless 14-bit, big-endian maker note, with a BlackLevel tag
let img = image(w, h, 16383, 11);
let src = encode(&img, w, &LOSSLESS_14, [[2048; 2]; 2]);
let note = vec![(0x0096, Val::Undefined(lossless_table(2048, false))), (0x003d, Val::Short(vec![600, 600, 600, 600]))];
let b = nef_compressed(w, h, 14, src, [0, 1, 1, 2], true, note);
assert_eq!(identify(&b), Some(RawFormat::Nef));
let s = crate::decode(&b, &Limits::default()).unwrap();
assert_eq!(s.data, img.iter().map(|&v| v as u16).collect::<Vec<_>>());
assert_eq!(s.black.values, vec![600.0; 4]);
// lossy 12-bit type 2, little-endian maker note (newer bodies); the
// 12-bit BlackLevel is scaled from 14-bit units
let table = lossy_table(12, true);
let t = parse_table(&table, true, 12).unwrap();
let Encoding::Lossy(curve) = &t.encoding else { panic!() };
let img = image(w, h, 1023, 5);
let src = encode(&img, w, &LOSSY_12, t.seeds);
let note = vec![(0x0096, Val::Undefined(table.clone())), (0x003d, Val::Short(vec![600, 600, 600, 600]))];
let s = crate::decode(&nef_compressed(w, h, 12, src.clone(), [2, 1, 1, 0], false, note), &Limits::default()).unwrap();
assert_eq!(s.data, img.iter().map(|&v| curve[v as usize]).collect::<Vec<_>>());
assert_eq!(s.black.values, vec![150.0; 4]);
assert!(crate::develop_sensor(&s, &crate::DevelopOptions::default()).is_ok());
// a split row over a stream that does not follow the fixed-rate rule, and a missing
// table, stay unsupported (preview fallback)
let mut split = table;
split[562..564].copy_from_slice(&3u16.to_le_bytes());
let e = crate::decode(&nef_compressed(w, h, 12, src.clone(), [2, 1, 1, 0], false, vec![(0x0096, Val::Undefined(split))]), &Limits::default());
assert!(matches!(e, Err(RawError::Unsupported(_))), "{e:?}");
let e = crate::decode(&nef_compressed(w, h, 12, src, [2, 1, 1, 0], false, vec![(0x0001, Val::Short(vec![0]))]), &Limits::default());
assert!(matches!(&e, Err(RawError::Unsupported(m)) if m.contains("Nikon compressed NEF")), "{e:?}");
}
#[test]
fn nikon_without_black_level_tag_is_black_subtracted() {
use crate::testgen::{Val, nef_compressed};
let (w, h) = (32usize, 8usize);
let img = image(w, h, 16383, 4);
let src = encode(&img, w, &LOSSLESS_14, [[2048; 2]; 2]);
let b = nef_compressed(w, h, 14, src, [0, 1, 1, 2], true, vec![(0x0096, Val::Undefined(lossless_table(2048, false)))]);
let s = crate::decode(&b, &crate::Limits::default()).unwrap();
assert_eq!(s.black.values, vec![0.0]);
assert!(!s.warnings.iter().any(|w| w.contains("black level")), "{:?}", s.warnings);
}
#[test]
fn truncated_container_never_panics() {
use crate::testgen::{Val, nef_compressed};
let (w, h) = (32usize, 8usize);
let img = image(w, h, 16383, 2);
let src = encode(&img, w, &LOSSLESS_14, [[2048; 2]; 2]);
let b = nef_compressed(w, h, 14, src, [0, 1, 1, 2], true, vec![(0x0096, Val::Undefined(lossless_table(2048, false)))]);
for n in 0..b.len() {
let _ = crate::decode(&b[..n], &crate::Limits::default());
}
}
#[test]
fn truncated_and_corrupt_streams_error_never_panic() {
let (w, h) = (64, 16);
let table = lossless(14);
let img = image(w, h, 16383, 3);
let src = encode(&img, w, &LOSSLESS_14, table.seeds);
for cut in [0, 1, 10, src.len() / 2, src.len() - 40] {
assert!(decode(&src[..cut], w, h, 14, &table).is_err(), "cut {cut}");
}
let mut s = 12345u32;
for i in 0..200 {
let mut bad = src.clone();
for _ in 0..1 + i % 8 {
s = s.wrapping_mul(1_103_515_245).wrapping_add(12345);
let at = (s >> 8) as usize % bad.len();
bad[at] ^= 1 << (s % 8);
}
let _ = decode(&bad, w, h, 14, &table);
let noise: Vec<u8> = (0..src.len()).map(|k| ((k as u32).wrapping_mul(2_654_435_761) >> (i % 24)) as u8).collect();
let _ = decode(&noise, w, h, 14, &table);
let _ = decode(&noise, w, h, 12, &lossless(12));
}
let lossy = parse_table(&lossy_table(12, false), false, 12).unwrap();
assert!(decode(&[0xff; 64], 8, 8, 12, &lossy).is_err());
assert!(decode(&src, usize::MAX, 2, 14, &table).is_err());
assert!(decode(&src, 0, 2, 14, &table).is_err());
}
/// Encodes `values` the way a "lossy after split" camera does: Huffman (`t`) for rows above
/// `split` (exact differences), then fixed-rate words of `bits - 4` bits, then one-bits up to the
/// byte boundary. The fixed-rate words keep only the top bits of large differences, so the
/// encoder runs the decoder's own predictor on what it reconstructs (closed loop) and returns the
/// strip together with the values the decoder must produce.
fn encode_split(values: &[i32], w: usize, t: &Table, seeds: [[i32; 2]; 2], bits: u32, split: usize) -> (Vec<u8>, Vec<i32>) {
let codes = codes(t);
let (word, fixed) = if bits == 12 { (8, FIXED_12) } else { (10, FIXED_14) };
let lut = fixed_words(bits);
let mut wr = Writer::default();
let mut vpred = seeds;
let mut recon = Vec::with_capacity(values.len());
for (y, row) in values.chunks(w).enumerate() {
let mut hpred = [0i32; 2];
for (x, &v) in row.iter().enumerate() {
let pred = if x < 2 { vpred[y & 1][x] } else { hpred[x & 1] };
let d = v - pred;
let k = 32 - d.unsigned_abs().leading_zeros();
let extra = if d < 0 { (d + (1 << k) - 1) as u32 } else { d as u32 };
let got = if y < split {
let (code, len) = codes[k as usize];
assert!(len > 0, "no Huffman code for category {k}");
wr.put(code, len);
wr.put(extra, k);
d
} else {
let &(prefix, len, _) = fixed.iter().find(|c| c.2 == k).unwrap_or_else(|| panic!("no fixed-rate code for category {k}"));
let kept = word - len;
let field = if k <= kept { extra << (kept - k) } else { extra >> (k - kept) };
wr.put(prefix, len);
wr.put(field, kept);
lut[((prefix << kept) | field) as usize].unwrap()
};
let r = pred + got;
if x < 2 {
vpred[y & 1][x] = r;
}
hpred[x & 1] = r;
recon.push(r);
}
}
while wr.n > 0 {
wr.put(1, 1);
}
(wr.out, recon)
}
/// Samples with large jumps (differences up to about ±1000 codes, the largest category both
/// lossy Huffman tables and the 12-bit fixed-rate words code) as well as small steps.
fn rough(w: usize, h: usize, seed: u32) -> Vec<i32> {
let mut s = seed;
(0..w * h)
.map(|i| {
s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
let jump = if (s >> 28) < 3 { ((s >> 8) % 900) as i32 - 450 } else { ((s >> 8) % 23) as i32 - 11 };
700 + jump + ((i % w) as i32 * 7) % 40
})
.collect()
}
fn split_table(bits: u32, split: usize) -> DecodeTable {
let mut table = lossy_table(bits, false);
table[562..564].copy_from_slice(&(split as u16).to_be_bytes());
let t = parse_table(&table, false, bits).unwrap();
assert_eq!(t.split, split);
t
}
#[test]
fn lossy_after_split_known_answers() {
for bits in [12u32, 14] {
let huff = if bits == 12 { &LOSSY_12 } else { &LOSSY_14 };
// Split right after the first row, in the middle and before the last row.
for (h, split) in [(7usize, 1usize), (7, 3), (7, 6)] {
let w = 24usize;
let t = split_table(bits, split);
let Encoding::Lossy(curve) = &t.encoding else { panic!() };
let max = curve.len() as i32 - 1;
// Large jumps: the fixed-rate words drop low bits and decode to bin centres, which
// the closed-loop encoder reproduces; the running value may leave 0..=max.
let img = rough(w, h, 7 + split as u32);
let (src, recon) = encode_split(&img, w, huff, t.seeds, bits, split);
let want: Vec<u16> = recon.iter().map(|&r| curve[r.clamp(0, max) as usize]).collect();
assert_eq!(decode(&src, w, h, bits, &t).unwrap(), want, "{bits}-bit split {split}");
// Some differences really were quantised.
assert!(recon.iter().zip(&img).any(|(r, v)| r != v), "{bits}-bit split {split}: nothing quantised");
}
}
}
#[test]
fn lossy_after_split_dequantises_to_symmetric_bin_centres() {
for bits in [12u32, 14] {
let lut = fixed_words(bits);
let values: Vec<i32> = lut.iter().flatten().copied().collect();
// Every word but the all-ones one codes a difference, and the codes are symmetric.
assert_eq!(values.len(), lut.len() - 1, "{bits}-bit");
assert!(lut.last().unwrap().is_none());
for v in &values {
assert!(values.contains(&-v), "{bits}-bit: {v} has no negative twin");
}
// Small differences are exact; the largest category (10 at 12 bit, 12 at 14 bit) reaches
// past half its range.
for d in -31..=31 {
assert!(values.contains(&d), "{bits}-bit: {d}");
}
let top = *values.iter().max().unwrap();
assert!(top >= if bits == 12 { 1 << 9 } else { 1 << 11 }, "{bits}-bit: {top}");
}
}
#[test]
fn split_files_that_break_the_rule_fall_back_to_the_preview() {
let unsupported = |r: Result<Vec<u16>>| matches!(r, Err(RawError::Unsupported(_)));
for bits in [12u32, 14] {
let huff = if bits == 12 { &LOSSY_12 } else { &LOSSY_14 };
let (w, h, split) = (24usize, 7usize, 3usize);
let t = split_table(bits, split);
let (src, _) = encode_split(&gentle(w, h, 600), w, huff, t.seeds, bits, split);
assert!(decode(&src, w, h, bits, &t).is_ok());
// Trailing data, a truncated strip, a split row past the image, zero padding and the
// all-ones word: all unsupported (the embedded preview opens), none a panic.
let mut longer = src.clone();
longer.extend_from_slice(&[0x12; 9]);
assert!(unsupported(decode(&longer, w, h, bits, &t)), "{bits}-bit: trailing data");
assert!(unsupported(decode(&src[..src.len() - 12], w, h, bits, &t)), "{bits}-bit: truncated");
assert!(unsupported(decode(&src, w, split, bits, &t)), "{bits}-bit: split past the image");
let mut zeros = src.clone();
let last = zeros.len() - 1;
zeros[last] &= 0xf0;
assert_ne!(zeros, src, "{bits}-bit: the fixture must end in padding bits");
assert!(unsupported(decode(&zeros, w, h, bits, &t)), "{bits}-bit: zero padding");
let mut all_ones = src.clone();
let fixed_start = all_ones.len() - (w * (h - split) * (bits as usize - 4)).div_ceil(8);
all_ones[fixed_start + 2..fixed_start + 6].fill(0xff);
assert!(unsupported(decode(&all_ones, w, h, bits, &t)), "{bits}-bit: all-ones word");
}
// A split row on a lossless table is malformed (no parsed table makes one).
let lossless_split = DecodeTable { split: 3, ..lossless(12) };
assert!(unsupported(decode(&[0; 64], 24, 7, 12, &lossless_split)));
// A curve long enough to cover byte 562 has no split field: refused as before.
let mut long = vec![0x44, 0x20];
long.extend(std::iter::repeat_n([0u8, 9], 4).flatten());
long.extend_from_slice(&513u16.to_be_bytes());
long.extend((0..513u32).flat_map(|i| ((i * 7) as u16).to_be_bytes()));
assert!(matches!(parse_table(&long, false, 12), Err(RawError::Unsupported(_))));
}
#[test]
fn split_nef_decodes_through_the_container() {
use crate::testgen::{Val, nef_compressed};
use crate::{Limits, decode as decode_raw};
let (w, h, split) = (40usize, 6usize, 2usize);
let mut table = lossy_table(12, true);
table[562..564].copy_from_slice(&(split as u16).to_le_bytes());
let t = parse_table(&table, true, 12).unwrap();
let Encoding::Lossy(curve) = &t.encoding else { panic!() };
let (src, recon) = encode_split(&rough(w, h, 3), w, &LOSSY_12, t.seeds, 12, split);
let note = vec![(0x0096, Val::Undefined(table))];
let s = decode_raw(&nef_compressed(w, h, 12, src, [2, 1, 1, 0], false, note), &Limits::default()).unwrap();
let max = curve.len() as i32 - 1;
assert_eq!(s.data, recon.iter().map(|&r| curve[r.clamp(0, max) as usize]).collect::<Vec<_>>());
assert!(crate::develop_sensor(&s, &crate::DevelopOptions::default()).is_ok());
}
/// Small steps around a level (every difference below 32), so fixed-rate words keep them whole.
fn gentle(w: usize, h: usize, base: i32) -> Vec<i32> {
(0..w * h).map(|i| base + ((i % w) as i32 * 3 + (i / w) as i32 * 5) % 13 + if i % 7 == 0 { 7 } else { 0 }).collect()
}
#[test]
fn fixed_rate_running_value_is_not_clamped() {
// A jump from 900 down to 0 is category 10: its 12-bit word keeps 5 of 10 additional bits
// and decodes to -912, so the running value sits at -12. The next same-colour pixel codes +12
// exactly and must land on 0 again; clamping the running value would give 12.
let (w, h, split) = (12usize, 4usize, 1usize);
let t = split_table(12, split);
let Encoding::Lossy(curve) = &t.encoding else { panic!() };
let img: Vec<i32> = (0..w * h).map(|i| if i % w < 2 { 900 } else { 0 }).collect();
let (src, recon) = encode_split(&img, w, &LOSSY_12, t.seeds, 12, split);
assert!(recon.iter().any(|&r| r < 0), "{recon:?}");
let max = curve.len() as i32 - 1;
let want: Vec<u16> = recon.iter().map(|&r| curve[r.clamp(0, max) as usize]).collect();
assert_eq!(decode(&src, w, h, 12, &t).unwrap(), want);
}
#[test]
fn fixed_rate_words_known_answers() {
// Worked by hand from the rule: prefix -> category n; the word keeps the top `kept` of n
// additional bits; T.81: a leading 0 bit is a negative difference; the difference is the
// centre of the kept bin (low dropped bits = half the bin).
let (w12, w14) = (fixed_words(12), fixed_words(14));
for (word, want) in [
(0b1111_1110, Some(0)), // category 0
(0b1110_0000, Some(-15)), // category 4, all 4 bits kept: 0000 = -15
(0b1110_1111, Some(15)), // 1111 = +15
(0b101_00000, Some(-63)), // category 6, 5 of 6 bits kept: bin -63..-62, centre -63
(0b101_10000, Some(33)), // bin 32..33, centre 33
(0b010_00011, Some(-912)), // category 10, 5 of 10 bits: 00011xxxxx = 96..127 -> -927..-896
(0b010_11111, Some(1008)), // 11111xxxxx = 992..1023, centre 1008
(0b1111_1111, None), // the all-ones word codes nothing
] {
assert_eq!(w12[word], want, "12-bit word {word:#010b}");
}
for (word, want) in [
(0b11_1111_1110, Some(0)), // category 0
(0b010_0000000, Some(-4080)), // category 12, 7 of 12 bits: -4095..-4064, centre -4080
(0b010_1111111, Some(4080)), // 4064..4095, centre 4080
(0b011_1000000, Some(1032)), // category 11, 7 of 11 bits: 1024..1039, centre 1032
(0b00_00000000, Some(-255)), // category 8, all 8 bits kept: 00000000 = -255
(0b11_1111_1111, None), // the all-ones word
] {
assert_eq!(w14[word], want, "14-bit word {word:#012b}");
}
}
#[test]
fn out_of_range_fixed_rate_values_are_not_counted_as_clipped() {
// Many jumps down to 0 leave the running value just below 0 (see the test above), far more
// than the 16 + n/1000 out-of-range values tolerated in Huffman rows. They are legitimate in
// the fixed-rate section and must not fail the decode.
let (w, h, split) = (40usize, 5usize, 1usize);
let t = split_table(12, split);
let Encoding::Lossy(curve) = &t.encoding else { panic!() };
let img: Vec<i32> = (0..w * h).map(|i| if (i % w) % 4 < 2 { 900 } else { 0 }).collect();
let (src, recon) = encode_split(&img, w, &LOSSY_12, t.seeds, 12, split);
assert!(recon.iter().filter(|&&r| r < 0).count() > 16 + w * h / 1000, "{recon:?}");
let max = curve.len() as i32 - 1;
assert_eq!(decode(&src, w, h, 12, &t).unwrap(), recon.iter().map(|&r| curve[r.clamp(0, max) as usize]).collect::<Vec<_>>());
}
#[test]
fn split_files_failing_after_the_table_still_fall_back_to_the_preview() {
use crate::testgen::{Val, nef_compressed};
use crate::{Limits, decode as decode_raw};
let (w, h, split) = (40usize, 6usize, 2usize);
let mut table = lossy_table(12, true);
table[562..564].copy_from_slice(&(split as u16).to_le_bytes());
let t = parse_table(&table, true, 12).unwrap();
let (src, _) = encode_split(&gentle(w, h, 600), w, &LOSSY_12, t.seeds, 12, split);
let note = || vec![(0x0096, Val::Undefined(table.clone()))];
// The refusal must come from the split path, not from some other part of the file.
let unsupported = |r: Result<crate::Sensor>| matches!(&r, Err(RawError::Unsupported(m)) if m.contains("lossy after split"));
// Over the size limits, and with the strip cut off by the end of the file.
let small = Limits { max_pixels: 100, ..Limits::default() };
assert!(unsupported(decode_raw(&nef_compressed(w, h, 12, src.clone(), [2, 1, 1, 0], false, note()), &small)));
let file = nef_compressed(w, h, 12, src, [2, 1, 1, 0], false, note());
let cut = file.len() - 40;
assert!(unsupported(decode_raw(&file[..cut], &Limits::default())));
}
#[test]
fn split_strips_with_up_to_four_extra_rows_are_accepted() {
// A strip may hold whole fixed-rate rows past the image (one body stores 4022 rows for
// 4020): up to 4 such rows decode, the image rows unchanged; a fifth is refused.
for bits in [12u32, 14] {
let huff = if bits == 12 { &LOSSY_12 } else { &LOSSY_14 };
let (w, h, split) = (24usize, 7usize, 3usize);
let t = split_table(bits, split);
let Encoding::Lossy(curve) = &t.encoding else { panic!() };
let max = curve.len() as i32 - 1;
for extra in 1..=5 {
let (src, recon) = encode_split(&gentle(w, h + extra, 600), w, huff, t.seeds, bits, split);
let got = decode(&src, w, h, bits, &t);
if extra <= 4 {
let want: Vec<u16> = recon[..w * h].iter().map(|&r| curve[r.clamp(0, max) as usize]).collect();
assert_eq!(got.unwrap(), want, "{bits}-bit, {extra} extra rows");
} else {
assert!(matches!(got, Err(RawError::Unsupported(_))), "{bits}-bit, {extra} extra rows: {got:?}");
}
}
}
}
-488
View File
@@ -1,488 +0,0 @@
use super::tool_input::ToolEvent;
use super::view_xform::ViewXform;
use super::{Color32, PhotocraftApp, Pos2, Rect, Stroke, Tool, json, pos2, vec2};
/// Windows' crosshair cursor inverts the pixels under it, so over mid-grey (the pasteboard, many
/// photos) it vanishes (#737), and the Linux themes' and macOS's differ. Use the same black-and-white
/// bitmap on every desktop platform, carried by the OS so its movement does not wait for the canvas
/// to render (#1343).
pub(super) fn visible_crosshair(icon: egui::CursorIcon, painter: &egui::Painter, p: Pos2, draw: bool) -> egui::CursorIcon {
if !draw || icon != egui::CursorIcon::Crosshair {
return icon;
}
crate::tool_cursor::standard_crosshair(painter, p)
}
/// The Pencil's cursor at `doc` (document pixels): the whole-pixel square its dab fills
/// (`paint::grid_square`), in screen points with its edges on physical pixels (`ppp` = pixels
/// per point), so it lines up with the pixel grid at any zoom.
pub(crate) fn pencil_cursor_rect(xf: &ViewXform, doc: [f64; 2], size: f32, ppp: f32) -> Rect {
let [x0, y0, x1, y1] = photocraft_engine::paint::grid_square(doc[0], doc[1], size);
let r = Rect::from_two_pos(xf.to_screen(x0 as f32, y0 as f32), xf.to_screen(x1 as f32, y1 as f32));
let ppp = if ppp.is_finite() && ppp > 0.0 { ppp } else { 1.0 };
let snap = |v: f32| (v * ppp).round() / ppp;
Rect::from_min_max(pos2(snap(r.min.x), snap(r.min.y)), pos2(snap(r.max.x), snap(r.max.y)))
}
/// Whether an aliased (Pencil) dab of `size` pixels is round rather than its whole
/// [`pencil_cursor_rect`] square. The dab fills the pixels whose centres lie within its radius of
/// the grid centre (`paint::grid_center`), so up to 3 px the corner pixels are in and the dab is
/// a square; from 4 px on they fall outside and it is a disc (#2662).
pub(crate) fn pencil_tip_is_round(size: f32) -> bool {
let n = if size.is_finite() { size.round().clamp(1.0, 100_000.0) } else { 1.0 };
let h = n / 2.0;
(h - 0.5) * std::f32::consts::SQRT_2 > h
}
/// Whether a brush-tip circle draws its centre mark, for Normal and Full Size Brush Tip cursors
/// alike (both draw through this). Quick Selection never draws one. Clone Stamp and Healing Brush
/// stay an empty circle until Option is held, the source-point cursor (the Healing Brush's ⌥ with
/// Normal Brush Tip shows the sample target instead, #12113). Other brushes follow
/// Preferences › Cursors › Show Crosshair in Brush Tip, as in Photoshop; the Background Eraser
/// and the Color Replacement tool (#11934) always show their sampling hotspot, and the Remove
/// tool its centre + (#12550).
pub(super) fn brush_tip_centre(tool: Tool, option: bool, show_crosshair: bool) -> bool {
if tool == Tool::QuickSelection {
return false;
}
if matches!(tool, Tool::CloneStamp | Tool::Healing) {
return option || show_crosshair;
}
show_crosshair || matches!(tool, Tool::BackgroundEraser | Tool::ColorReplacement | Tool::Remove)
}
/// The display colour of an RGB triple (0..1 per channel) as an egui colour.
fn display_color(c: [f32; 3]) -> Color32 {
let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
Color32::from_rgb(b(c[0]), b(c[1]), b(c[2]))
}
/// The Eyedropper ring's two colours at document point (x, y): the colour under the pointer
/// (what a click would pick) and the current foreground, or `None` where there is no colour
/// to sample (#213).
pub(crate) fn eyedropper_ring_colors(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<(Color32, Color32)> {
let new = eyedropper_color(app, x, y)?;
let fg = app.session.tools.foreground;
Some((display_color(new), display_color([fg[0], fg[1], fg[2]])))
}
/// Draw the Eyedropper's comparison ring at `p`: an opaque neutral grey band around the
/// pointer with the sampled colour on its upper half and the current one on the lower,
/// framed by thin dark and light hairlines so every edge reads on any image, and the
/// pipette at its centre marking the sampled pixel (#213, #6973). Like Photoshop it shows
/// only while the mouse button is held (`held`): hovering shows the plain pipette and
/// samples nothing. `None` when not held, there is nothing to sample, or the Precise-cursor
/// preference wants the plain crosshair.
pub(super) fn eyedropper_ring(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, p: Pos2, held: bool) -> Option<egui::CursorIcon> {
// The options bar's Show Sampling Ring turns it off (#1649).
if !held || !app.ui.tool_options.eyedropper_ring || app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise {
return None;
}
let [x, y] = xf.to_doc(p);
let (new, current) = eyedropper_ring_colors(app, x, y)?;
// Photoshop's proportions (#6973): a ring about 210 pt across whose opaque grey outer
// band and coloured inner band are each about 17 pt wide, over a transparent centre.
// In points, so the ring scales with Interface › UI Scale like the rest of the cursor.
let (r_out, band) = (105.0_f32, 17.0_f32);
let r_in = r_out - 2.0 * band;
// Screen y grows down, so PI..TAU is the upper half (the sampled colour) and 0..PI the
// lower (the current one); the halves meet at 3 and 9 o'clock, as in Photoshop.
use std::f32::consts::{PI, TAU};
let upper: Vec<Pos2> = (0..=48)
.map(|i| {
let a = PI + (TAU - PI) * i as f32 / 48.0;
p + vec2(a.cos(), a.sin()) * (r_in + band / 2.0)
})
.collect();
// `circle_stroke` paints its stroke outside the radius, `Shape::line` centres it.
painter.circle_stroke(p, r_in, Stroke::new(band, current));
painter.add(egui::Shape::line(upper, Stroke::new(band, new)));
painter.circle_stroke(p, r_in + band, Stroke::new(band, RING_GREY));
// Thin dark and light hairlines on the ring's two edges, one physical pixel wide, so it
// reads on any colour including a flat mid-grey that matches the band itself (#6973).
let px = 1.0 / painter.ctx().pixels_per_point().max(1.0);
let (dark, light) = (Stroke::new(px, Color32::from_black_alpha(160)), Stroke::new(px, Color32::from_white_alpha(160)));
painter.circle_stroke(p, r_out, dark);
painter.circle_stroke(p, r_out + px, light);
painter.circle_stroke(p, r_in - px, dark);
painter.circle_stroke(p, r_in - 2.0 * px, light);
// Photoshop keeps the pipette visible at the centre, its tip on the sampled pixel; a
// ring this size says nothing about where it samples without it.
Some(pipette_cursor(painter.ctx(), p))
}
/// The Eyedropper ring's opaque neutral grey, as Photoshop measures it (#6973).
const RING_GREY: Color32 = Color32::from_gray(127);
/// Tools on which holding ⌥ (Alt) switches to the Eyedropper: a click or drag sets the
/// foreground colour, as with the Eyedropper itself (#417, the Background Eraser #11906, the Color
/// Replacement tool #11914).
pub(crate) fn alt_samples(tool: Tool, mods: egui::Modifiers) -> bool {
// Control+Alt is the brush-resize drag (`brush_resize`), not sampling.
mods.alt && !mods.ctrl && matches!(tool, Tool::Brush | Tool::Pencil | Tool::Gradient | Tool::PaintBucket | Tool::BackgroundEraser | Tool::ColorReplacement)
}
/// Preferences › Cursors › Other Cursors asks for the precise crosshair, or Caps Lock swaps the
/// standard cursor for it (and back), as in Photoshop (#4639).
pub(crate) fn precise_other_cursor(app: &PhotocraftApp) -> bool {
(app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise) != app.caps_lock
}
/// A pen tool's standard cursor: its toolbar icon with the nib (the Convert Point tool: the
/// anchor) on `p`. Uses an OS cursor bitmap where supported so its movement tracks hardware
/// pointer input without waiting for canvas frames (#9122); falls back to drawing the tooltip icon.
pub fn pen_cursor(ctx: &egui::Context, tool: Tool, p: Pos2) -> egui::CursorIcon {
if let Some(icon) = crate::tool_cursor::pen(ctx, tool) {
return icon;
}
// Where each icon's point is in its 24-unit box: the full-size pen's nib at (2.3, 2.3); the
// Freeform and Curvature pens draw it at 0.68 × from (7, 7); Convert Point's apex anchor.
let hot = match tool {
Tool::FreeformPen | Tool::CurvaturePen => vec2(8.56, 8.56),
Tool::ConvertPoint => vec2(12.0, 7.0),
_ => vec2(2.3, 2.3),
};
crate::icons::cursor(ctx, crate::icons::tool_icon(tool), p, hot / 24.0, 22.0);
egui::CursorIcon::None
}
/// The Color Sampler's cursor over an existing sampler point: the arrow with the sampler target,
/// or with Alt the arrow with scissors (#11744).
pub(crate) fn sampler_hover_cursor(ctx: &egui::Context, p: Pos2, alt: bool) -> egui::CursorIcon {
if alt {
crate::icons::cursor_badge(ctx, "scissors", p);
} else {
crate::icons::cursor_badge(ctx, "sampler", p);
}
egui::CursorIcon::Default
}
/// The Color Sampler's cursor: an eyedropper with a small sampler target at its top-left,
/// hotspot at the pipette tip (#11744).
pub(crate) fn color_sampler_cursor(ctx: &egui::Context, p: Pos2) -> egui::CursorIcon {
pipette_cursor(ctx, p);
let size = 11.0;
// The pipette tip is at (2, 22) in its 24-unit box of size 20.0. The top-left region is
// around (5, 5), which is offset by (3, -17) * (20/24) = (2.5, -14.17) from the tip.
let target_center = p + vec2(2.5, -14.0);
let rect = Rect::from_center_size(target_center, egui::Vec2::splat(size));
let area = egui::Area::new(egui::Id::unique("pc-sampler-badge")).order(egui::Order::Tooltip).fixed_pos(rect.min).constrain(false).interactable(false);
area.show(ctx, |ui| {
let outline = crate::icons::image("sampler", size, Color32::from_black_alpha(200));
for (dx, dy) in [(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0), (-1.0, -1.0), (1.0, 1.0), (-1.0, 1.0), (1.0, -1.0)] {
outline.paint_at(ui, rect.translate(vec2(dx, dy)));
}
crate::icons::image("sampler", size, Color32::WHITE).paint_at(ui, rect);
});
egui::CursorIcon::None
}
/// The sampling cursor: a pipette whose tip is the sampled pixel. Draws it at `p` and returns the
/// OS cursor to set. Native windows use a cached bitmap that moves independently of rendering.
pub(crate) fn pipette_cursor(ctx: &egui::Context, p: Pos2) -> egui::CursorIcon {
crate::tool_cursor::pipette(ctx, p)
}
/// The filter dialogs' preview locator: a small square centred on `p`, the point a click centres
/// the dialog's preview window on (#9648), white between dark edges so it reads on any image.
/// Draws it at `p` and returns the OS cursor to set (hidden).
pub(crate) fn preview_locator_cursor(ctx: &egui::Context, p: Pos2) -> egui::CursorIcon {
const SIDE: f32 = 9.0;
let rect = Rect::from_center_size(p, vec2(SIDE, SIDE));
let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("pc-preview-locator")));
let dark = Stroke::new(1.0, Color32::from_black_alpha(200));
painter.rect_stroke(rect.expand(1.0), 0.0, dark, egui::StrokeKind::Inside);
painter.rect_stroke(rect.shrink(1.0), 0.0, dark, egui::StrokeKind::Inside);
painter.rect_stroke(rect, 0.0, Stroke::new(1.0, Color32::WHITE), egui::StrokeKind::Inside);
egui::CursorIcon::None
}
/// The cursor while ⌥ turns a painting tool into the Eyedropper (`alt_eyedropper`): the pipette,
/// or the comparison ring while it samples with the button `held` (#213), or the precise crosshair
/// with Preferences › Cursors › Other Cursors = Precise. The Mixer Brush's ⌥ loads paint instead:
/// its sample target, with no ring (#11957).
pub(super) fn alt_pick_cursor(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, p: Pos2, held: bool, tool: Tool) -> egui::CursorIcon {
let precise = app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise;
if tool == Tool::MixerBrush && !app.alt_sampling {
return if precise { egui::CursorIcon::Crosshair } else { sample_target_cursor(painter, p) };
}
if let Some(icon) = eyedropper_ring(app, painter, xf, p, held) {
icon
} else if precise {
egui::CursorIcon::Crosshair
} else {
pipette_cursor(painter.ctx(), p)
}
}
/// The Mixer Brush's and the Healing Brush's ⌥ cursor, the reference's sample target (#11957,
/// #12113): a small circle with a crosshair through it, centred on the hotspot. Draws it at `p`
/// and returns the OS cursor to set.
pub(crate) fn sample_target_cursor(painter: &egui::Painter, p: Pos2) -> egui::CursorIcon {
let across = vec![vec2(-8.0, 0.0), vec2(8.0, 0.0)];
let down = vec![vec2(0.0, -8.0), vec2(0.0, 8.0)];
super::tool_cursor::outline(painter, p, vec![ring(5.0), across, down], false)
}
/// A no-entry sign, a circle with a diagonal bar centred on the hotspot: the Mixer Brush over a
/// layer it can't paint (Lock All, #11957). Draws it at `p` and returns the OS cursor to set.
pub(crate) fn no_entry_cursor(painter: &egui::Painter, p: Pos2) -> egui::CursorIcon {
let bar = vec![vec2(-4.5, -4.5), vec2(4.5, 4.5)];
super::tool_cursor::outline(painter, p, vec![ring(6.5), bar], false)
}
/// A closed circle of `radius` points around the hotspot.
fn ring(radius: f32) -> Vec<egui::Vec2> {
(0..32).map(|i| i as f32 / 32.0 * std::f32::consts::TAU).map(|a| vec2(a.cos(), a.sin()) * radius).collect()
}
/// Whether the Mixer Brush's target layer has Lock All on, so it shows [`no_entry_cursor`].
pub(crate) fn mixer_target_locked(app: &PhotocraftApp) -> bool {
app.session.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))).is_some_and(|layer| layer.locks.all)
}
#[cfg(test)]
#[path = "../mixer_cursor_tests.rs"]
mod mixer_cursor_tests;
#[cfg(test)]
#[path = "../healing_alt_cursor_tests.rs"]
mod healing_alt_cursor_tests;
/// The Paint Bucket artwork and target share one cached cursor image. Report rasterization
/// failures once per distinct message, with the same concise error in the dialog and status bar.
pub(crate) fn paint_bucket_cursor(app: &mut PhotocraftApp, painter: &egui::Painter, p: Pos2) -> egui::CursorIcon {
let ctx = painter.ctx();
let id = egui::Id::unique("photocraft-bucket-cursor-error");
match crate::tool_cursor::bucket(painter, p) {
Ok(icon) => {
// The failure belonged to another scale: its status goes, and a new one reports again.
if let Some(error) = ctx.data(|data| data.get_temp::<String>(id)) {
ctx.data_mut(|data| data.remove::<String>(id));
if app.ui.status == error {
app.ui.status.clear();
app.ui.status_error = false;
}
}
icon
}
Err(error) => {
if ctx.data(|data| data.get_temp::<String>(id)).as_ref() != Some(&error) {
if !app.ui.dialogs.iter().any(|dialog| {
dialog.kind == crate::state::DialogKind::Error && dialog.fields.get("message").and_then(serde_json::Value::as_str) == Some(&error)
}) {
let mut fields = serde_json::Map::new();
fields.insert("message".into(), json!(error));
app.ui.open_dialog(crate::state::DialogKind::Error, fields);
}
ctx.data_mut(|data| data.insert_temp(id, error.clone()));
}
app.ui.status = error;
app.ui.status_error = true;
egui::CursorIcon::Default
}
}
}
/// Decided when the press starts, so ⌥ pressed or released mid-stroke never switches between
/// painting and sampling.
pub(super) fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool {
if let ToolEvent::Down { x, y, .. } = ev {
let physical_right = app.services.right_button_down.as_ref().is_some_and(|f| f());
app.alt_sampling = !physical_right && !app.secondary_erase && (alt_samples(app.active_tool(), mods) || shape_alt_samples(app, mods, x, y));
}
if !app.alt_sampling {
return false;
}
// The Triangle and Custom Shape tools' ⇧⌥ at the press samples as ⌥ does, and the release
// point's colour is the one they keep (#13364, #13467).
let shape_tool = shape_samples_fill(app.active_tool());
match ev {
// ⇧⌥-click adds a colour sampler at the clicked pixel instead, as the Color Sampler tool
// places one: no foreground change, nothing painted (#11890). A refused point (the
// document's limit) reports in the status bar as that tool's does; off the canvas, as that
// tool, it places none and says nothing. A press on an existing point wasn't measured, so
// it samples the foreground as before.
ToolEvent::Down { x, y, .. } if mods.shift && !shape_tool && !on_sampler(app, x, y) => {
let size = app.session.active().map(|d| d.doc.size);
let inside = size.is_some_and(|s| (0.0..f64::from(s.width)).contains(&x) && (0.0..f64::from(s.height)).contains(&y));
if inside && let Err(e) = app.run("view.colorSamplers.add", json!({"x": x, "y": y})) {
// Only the limit is a plain report; any other refusal (a failed Pen draft left in
// another document) stays an error, also when the document is full.
let limit = e == photocraft_engine::sampler_cmds::limit_message();
app.ui.status = e;
app.ui.status_error = !limit;
}
}
// While ⇧⌥ stay held after that press, moves sample nothing.
ToolEvent::Move { .. } if mods.shift && !shape_tool => {}
ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } if shape_tool => sample_shape_fill(app, x, y),
// Without ⌥: the sample sets the foreground colour, whatever the Eyedropper would do.
ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } => sample_eyedropper(app, x, y, egui::Modifiers::NONE),
ToolEvent::Up { x, y } => {
if shape_tool {
sample_shape_fill(app, x, y);
}
app.alt_sampling = false;
}
}
true
}
/// The Triangle and Custom Shape tools sample with ⌥ held at the press at (x, y) only in Shape
/// mode and with no shape layer active (#13364, #13467): with one, ⌥ subtracts from it. Path or Pixels mode and a press
/// with nothing to sample (off the image, over transparency) weren't measured and keep drawing
/// from the centre. Control+⌥ stays the brush-resize drag, as in [`alt_samples`].
fn shape_alt_samples(app: &mut PhotocraftApp, mods: egui::Modifiers, x: f64, y: f64) -> bool {
mods.alt
&& !mods.ctrl
&& shape_samples_fill(app.active_tool())
&& app.ui.tool_options.shape_mode == "shape"
&& crate::vector_ui::active_shape_path(app).is_none()
&& eyedropper_color(app, x, y).is_some()
}
/// Does this tool's ⌥ sample also set its Fill? The Triangle (#13364) and Custom Shape (#13467)
/// tools.
fn shape_samples_fill(tool: Tool) -> bool {
matches!(tool, Tool::Triangle | Tool::CustomShape)
}
/// The Triangle or Custom Shape tool's ⌥ sample: the colour at (x, y) becomes the foreground and
/// the tool's Fill, a solid fill, which follows the foreground. Where nothing is sampled, both stay.
fn sample_shape_fill(app: &mut PhotocraftApp, x: f64, y: f64) {
if sampled_eyedropper(app, x, y, egui::Modifiers::NONE) {
app.ui.tool_options.shape_fill = true;
app.ui.tool_options.shape_fill_gradient = None;
}
}
/// Is document point (x, y) on a colour sampler, within the Color Sampler tool's reach of one (7
/// screen pixels)?
fn on_sampler(app: &PhotocraftApp, x: f64, y: f64) -> bool {
let tol = 7.0 / f64::from(app.point_zoom().max(0.01));
app.session.active().is_some_and(|d| d.color_samplers.iter().any(|q| (q[0] - x).hypot(q[1] - y) <= tol))
}
#[cfg(test)]
#[path = "triangle_alt_eyedropper_tests.rs"]
mod triangle_alt_eyedropper_tests;
#[cfg(test)]
#[path = "../brush_shift_alt_sampler_tests.rs"]
mod brush_shift_alt_sampler_tests;
/// Sample the image or targeted raster mask at (x, y) using the configured Sample Size.
/// Write a valid sample to the foreground swatch, or to the background swatch with Alt.
pub(super) fn sample_eyedropper(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) {
sampled_eyedropper(app, x, y, mods);
}
/// [`sample_eyedropper`], true when it set a swatch.
fn sampled_eyedropper(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) -> bool {
let rgb = if let Some((surface, canvas)) = eyedropper_mask_source(app) {
sample_layer_mask(surface, canvas, x, y, app.ui.tool_options.eyedropper_size)
} else {
eyedropper_color(app, x, y).map(|rgb| if super::paint_target(app) == json!("pixels") { rgb } else { [photocraft_color::convert::rgb_to_gray(rgb); 3] })
};
if let Some(rgb) = rgb {
let key = if mods.alt { "background" } else { "foreground" };
return app.run("tools.setColors", json!({ key: [rgb[0],rgb[1],rgb[2],1.0] })).is_ok();
}
false
}
/// Only the Eyedropper's Current Layer and Current & Below modes pick the targeted raster mask.
fn eyedropper_mask_source(app: &PhotocraftApp) -> Option<(&photocraft_raster::Surface, photocraft_geom::Rect)> {
use photocraft_engine::{channel_cmds::ChannelTarget, mask_view_cmds};
if app.active_tool() != Tool::Eyedropper
|| app.ui.vector_mask_target
|| !matches!(app.ui.tool_options.eyedropper_sample.as_str(), "current" | "currentAndBelow")
{
return None;
}
let st = app.session.active()?;
// Painting can implicitly edit an adjustment's mask even with its content thumbnail selected.
let targeted = app.ui.mask_target || st.channel_view.target == ChannelTarget::LayerMask || mask_view_cmds::current(st).is_some_and(|v| !v.filter);
if !targeted || st.doc.quick_mask.is_some() || !app.layer_mask_targeted() {
return None;
}
let mask = st.doc.layer(st.active_layer?)?.mask.as_ref()?;
Some((&mask.surface, st.doc.bounds()))
}
/// Read the stored mask channel, including its sparse default, rather than its composited coverage.
fn sample_layer_mask(surface: &photocraft_raster::Surface, canvas: photocraft_geom::Rect, x: f64, y: f64, size: u32) -> Option<[f32; 3]> {
let rect = photocraft_engine::cmd::sample_cmds::sample_rect(x, y, size, canvas)?;
let mut sum = 0.0;
for y in rect.y0..rect.y1 {
for x in rect.x0..rect.x1 {
sum += f64::from(surface.sample_channel(x, y, 0));
}
}
let gray = (sum / (f64::from(rect.width()) * f64::from(rect.height()))) as f32;
gray.is_finite().then_some([gray; 3])
}
/// The colour at document point (x, y) with the Eyedropper's Sample Size (the composite pixel,
/// or the average of the square around it) from the layers `sample_layer` names (`document.sampleColor`).
/// `None` off the image or over transparency.
fn sample_color(app: &mut PhotocraftApp, x: f64, y: f64, sample_layer: &str) -> Option<[f32; 3]> {
if !(x.is_finite() && y.is_finite()) {
return None;
}
let size = app.ui.tool_options.eyedropper_size;
// The box depends on the view zoom at 100 % and below, as in Photoshop (#11751).
let zoom = f64::from(app.current_zoom());
let v = app.run("document.sampleColor", json!({"x": x, "y": y, "size": size, "sampleLayer": sample_layer, "zoom": zoom})).ok()?;
match serde_json::from_value::<Vec<f32>>(v).ok()?[..] {
[r, g, b, a] if a > 0.0 => Some([r, g, b]),
_ => None,
}
}
/// What the Eyedropper tool (and a painting tool's ⌥-click) picks at document point (x, y): its
/// options bar's Sample Size and Sample (#1649).
pub(crate) fn eyedropper_color(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<[f32; 3]> {
let layers = app.ui.tool_options.eyedropper_sample.clone();
sample_color(app, x, y, &layers)
}
/// The active document's composite colour at document point (x, y), averaged over the
/// Eyedropper's Sample Size as Photoshop's dialog eyedroppers (Curves, Color Picker) do.
/// `None` off the image or over transparency.
pub(crate) fn composite_color(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<[f32; 3]> {
sample_color(app, x, y, "all")
}
pub(crate) fn alt_loads_mixer(tool: Tool, mods: egui::Modifiers) -> bool {
mods.alt && !mods.ctrl && tool == Tool::MixerBrush
}
pub(crate) fn alt_picks(tool: Tool, mods: egui::Modifiers) -> bool {
alt_samples(tool, mods) || alt_loads_mixer(tool, mods)
}
#[cfg(test)]
#[path = "../eyedropper_mask_sample_tests.rs"]
mod eyedropper_mask_sample_tests;
#[cfg(test)]
#[path = "../color_replacement_cursor_tests.rs"]
mod color_replacement_cursor_tests;
#[cfg(test)]
#[path = "../color_replacement_alt_click_tests.rs"]
mod color_replacement_alt_click_tests;
#[cfg(test)]
#[path = "../background_eraser_alt_click_tests.rs"]
mod background_eraser_alt_click_tests;
#[cfg(test)]
#[path = "remove_cursor_tests.rs"]
mod remove_cursor_tests;
#[cfg(test)]
#[path = "paint_bucket_cursor_tests.rs"]
mod paint_bucket_cursor_tests;
@@ -1,913 +0,0 @@
use super::{
Color32, CurveUi, Edit, EditorCx, Pos2, Rect, RichText, Sense, Stroke, StrokeKind, Tokens, ToneSpace, Value, adjust_params, curve_edit, json, label, pos2,
space_of, tone, vec2, widgets,
};
// ---------------------------------------------------------------------------------------------
// Channels of Levels / Curves
/// A channel of a tone editor: the params key (None = the top-level / composite keys for Levels;
/// Curves uses "points"), its label, and its colour name.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ToneChannel {
pub key: &'static str,
pub label: &'static str,
}
/// The channels a tone editor lists for `space` (histogram index = position).
pub fn tone_channels(space: ToneSpace, gray: bool) -> &'static [ToneChannel] {
const RGB: [ToneChannel; 4] = [
ToneChannel { key: "", label: "RGB" },
ToneChannel { key: "red", label: "Red" },
ToneChannel { key: "green", label: "Green" },
ToneChannel { key: "blue", label: "Blue" },
];
const GRAY: [ToneChannel; 1] = [ToneChannel { key: "", label: "Gray" }];
const CMYK: [ToneChannel; 5] = [
ToneChannel { key: "", label: "CMYK" },
ToneChannel { key: "cyan", label: "Cyan" },
ToneChannel { key: "magenta", label: "Magenta" },
ToneChannel { key: "yellow", label: "Yellow" },
ToneChannel { key: "black", label: "Black" },
];
const LAB: [ToneChannel; 3] =
[ToneChannel { key: "lightness", label: "Lightness" }, ToneChannel { key: "a", label: "a" }, ToneChannel { key: "b", label: "b" }];
match space {
ToneSpace::Rgb if gray => &GRAY,
ToneSpace::Rgb => &RGB,
ToneSpace::Cmyk => &CMYK,
ToneSpace::Lab => &LAB,
}
}
/// Visible tone records and their histogram indices. A partial selection has a neutral combined
/// entry followed by the selected native components; Properties keeps the complete editor.
pub(super) fn editor_channels(cx: &EditorCx, space: ToneSpace) -> Vec<(ToneChannel, String, usize)> {
let channels = tone_channels(space, cx.gray);
if let Some(iso) = &cx.isolated_curve {
if let Some(colors) = iso.components {
let keys = adjust_params::channel_keys(space);
let mut result = vec![(ToneChannel { key: "", label: "" }, iso.name.clone(), 0)];
for k in colors.indices() {
if let Some(key) = keys.get(k) {
// HistSource::Colors reserves slot 0 for the combined set, including Lab.
let histogram = k + 1;
let channel = channels.iter().find(|c| c.key == *key).copied().unwrap_or(ToneChannel { key, label: key });
result.push((channel, tl!(channel.label).to_owned(), histogram));
}
}
return result;
}
return vec![(ToneChannel { key: iso.key, label: "" }, if iso.translate { tl!(&iso.name).to_owned() } else { iso.name.clone() }, iso.hist)];
}
channels.iter().enumerate().map(|(i, c)| (*c, tl!(c.label).to_owned(), i)).collect()
}
pub(super) fn editor_channel_picker(ui: &mut egui::Ui, id: egui::Id, channels: &[(ToneChannel, String, usize)]) -> usize {
let options: Vec<_> = channels.iter().enumerate().map(|(i, (_, name, _))| (i, name.as_str())).collect();
channel_picker_opts(ui, id, &options, tl!("Channel:"), false)
}
/// The popup, with `translate` for whether the built-in labels follow the interface language;
/// a user-typed channel name is shown exactly as entered (#5335).
pub(super) fn channel_picker_opts(ui: &mut egui::Ui, id: egui::Id, opts: &[(usize, &str)], text: &str, translate: bool) -> usize {
let mut ch: usize = ui.data(|d| d.get_temp(id)).unwrap_or(0);
if ch >= opts.len() {
ch = 0;
}
ui.horizontal(|ui| {
label(ui, text);
let width = if opts.len() == 1 { 160.0 } else { 110.0 };
let key = format!("{id:?}-ch");
if translate {
widgets::dropdown(ui, &key, text, &mut ch, opts, width);
} else {
widgets::dropdown_literal(ui, &key, text, &mut ch, opts, width);
}
});
ui.data_mut(|d| d.insert_temp(id, ch));
ch
}
pub(super) fn hist_color(ch: &ToneChannel, t: &Tokens) -> Color32 {
match ch.key {
"" | "lightness" | "black" => Color32::from_gray(if t.pro { 150 } else { 110 }),
k => tone::channel_color(k, t),
}
}
pub(super) fn bar_color(ch: &ToneChannel, t: &Tokens) -> Color32 {
match ch.key {
"" | "lightness" | "black" => Color32::WHITE,
k => tone::channel_color(k, t),
}
}
/// Horizontal (or vertical) black → `to` gradient bar.
pub(super) fn gradient_bar(p: &egui::Painter, r: Rect, from: Color32, to: Color32, vertical: bool) {
let mut mesh = egui::Mesh::default();
let (a, b, c, d) = if vertical {
(r.left_bottom(), r.right_bottom(), r.right_top(), r.left_top())
} else {
(r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom())
};
let (ca, cb) = if vertical { (from, from) } else { (from, to) };
let (cc, cd) = if vertical { (to, to) } else { (to, from) };
mesh.colored_vertex(a, ca);
mesh.colored_vertex(b, cb);
mesh.colored_vertex(c, cc);
mesh.colored_vertex(d, cd);
mesh.add_triangle(0, 1, 2);
mesh.add_triangle(0, 2, 3);
p.add(mesh);
}
// ---------------------------------------------------------------------------------------------
// Curves
pub(super) const CURVE_HANDLE_SIZE: f32 = 7.0;
const CURVE_GRAPH_PADDING: f32 = 5.0;
const CURVE_SAMPLES: usize = 256;
/// One entry per editor/channel, independent of selection, tint and stroke width.
#[derive(Clone, Default)]
struct CurvePolyline {
points: Vec<[f32; 2]>,
graph: Option<Rect>,
line: Vec<Pos2>,
}
impl CurvePolyline {
/// Returns whether the screen geometry changed. Moving the graph also invalidates screen
/// coordinates (for example when scrolling the Properties panel or moving the dialog).
fn update(&mut self, points: &[[f32; 2]], graph: Rect) -> bool {
if self.points == points && self.graph == Some(graph) {
return false;
}
let cp: Vec<photocraft_doc::adjust::CurvePoint> =
points.iter().map(|q| photocraft_doc::adjust::CurvePoint { input: q[0] / 255.0, output: q[1] / 255.0 }).collect();
self.line = photocraft_compose::adjust::curve_samples::<CURVE_SAMPLES>(&cp)
.into_iter()
.enumerate()
.map(|(i, y)| pos2(graph.left() + i as f32 / (CURVE_SAMPLES - 1) as f32 * graph.width(), graph.bottom() - y * graph.height()))
.collect();
self.points.clear();
self.points.extend_from_slice(points);
self.graph = Some(graph);
true
}
}
fn cached_curve_line(ctx: &egui::Context, id: egui::Id, points: &[[f32; 2]], graph: Rect) -> Vec<Pos2> {
ctx.data_mut(|d| {
let cache = d.get_temp_mut_or_default::<CurvePolyline>(id);
cache.update(points, graph);
// egui owns the submitted path. Only this small copy is needed on a cache hit;
// normalization, spline solving, sampling and screen mapping are all skipped.
cache.line.clone()
})
}
/// The room left on screen for the Curves dialog's other rows (title, channel and mode, Input and
/// Output, eyedroppers, buttons) when its graph is as tall as it can be.
const CURVES_CHROME: f32 = 360.0;
/// The smallest and the default largest side of the Curves graph: 300 points was the fixed
/// size until #8984.
const CURVE_SIDE: (f32, f32) = (120.0, 300.0);
/// The Curves graph's side (#8984): the width it is given, in the Properties panel and in the
/// resizable dialog, and no taller than the window leaves room for beside the other rows.
fn curve_side(ui: &egui::Ui) -> f32 {
let tallest = curve_side_max(ui.ctx());
let width = ui.available_width();
if width.is_finite() { width.clamp(CURVE_SIDE.0, tallest) } else { CURVE_SIDE.1 }
}
/// The largest the Curves graph gets in this window: as tall as the window leaves room for beside
/// the dialog's other rows, and never under the old 300 points. The Curves dialog is no wider.
pub(crate) fn curve_side_max(ctx: &egui::Context) -> f32 {
(ctx.content_rect().height() - CURVES_CHROME).max(CURVE_SIDE.1)
}
pub(super) fn curve_graph(full: Rect, side: f32) -> Rect {
let base = Rect::from_min_size(full.min + vec2(14.0, 0.0), vec2(side - 14.0, side - 14.0));
Rect::from_min_max(base.min + vec2(CURVE_GRAPH_PADDING, CURVE_GRAPH_PADDING), base.max - vec2(CURVE_GRAPH_PADDING, CURVE_GRAPH_PADDING))
}
pub(crate) fn read_curve(v: &Value, key: &str) -> Vec<[f32; 2]> {
let pts: Vec<[f32; 2]> = v
.get(key)
.and_then(Value::as_array)
.map(|a| {
a.iter()
.filter_map(|q| {
let q = q.as_array()?;
Some([q.first()?.as_f64()? as f32, q.get(1)?.as_f64()? as f32])
})
.collect()
})
.unwrap_or_default();
if pts.len() < 2 { vec![[0.0, 0.0], [255.0, 255.0]] } else { pts }
}
fn curve_key(ch: &ToneChannel) -> &'static str {
if ch.key.is_empty() { "points" } else { ch.key }
}
/// A pencil-drawn channel: its 256 output levels (identity when absent or not a map).
fn read_map(v: &Value, key: &str) -> Vec<f32> {
let map: Option<Vec<f32>> = v
.get(key)
.and_then(Value::as_array)
.filter(|a| a.len() == photocraft_doc::adjust::CURVE_MAP_LEN)
.and_then(|a| a.iter().map(|o| o.as_f64().map(|o| o as f32)).collect());
map.unwrap_or_else(|| (0..photocraft_doc::adjust::CURVE_MAP_LEN).map(|k| k as f32).collect())
}
fn write_map(v: &mut Value, key: &str, map: &[f32]) {
v[key] = json!(map.iter().map(|o| (o * 100.0).round() / 100.0).collect::<Vec<_>>());
}
/// Switches the Curves values between point editing and the pencil: the engine draws the point
/// curves into maps, or fits points to the drawn maps (Photoshop's two curve buttons).
fn set_pencil(v: &mut Value, pencil: bool, gray: bool) -> bool {
let mut p = v.clone();
p["pencil"] = json!(pencil);
let mode = if gray { photocraft_doc::ColorMode::Grayscale } else { photocraft_doc::ColorMode::Rgb };
let Ok(a) = adjust_params::from_params("curves", &p, None, mode) else { return false };
*v = adjust_params::to_params(&a);
// Explicit, so an update over a pencil-drawn layer leaves the pencil.
v["pencil"] = json!(pencil);
true
}
/// Partial sets have a combined record even in Lab. Convert each displayed curve separately,
/// so the normal Lab serializer (which aliases the composite to Lightness) cannot discard it.
fn set_editor_pencil(v: &mut Value, pencil: bool, cx: &EditorCx) -> bool {
if cx.isolated_curve.as_ref().is_none_or(|c| c.components.is_none()) {
return set_pencil(v, pencil, cx.gray);
}
let mut next = v.clone();
for (channel, _, _) in editor_channels(cx, space_of(v)) {
let key = curve_key(&channel);
let mut scalar = json!({"pencil":v.get("pencil").and_then(Value::as_bool).unwrap_or(false)});
if let Some(curve) = v.get(key) {
scalar["points"] = curve.clone();
}
if !set_pencil(&mut scalar, pencil, true) {
return false;
}
if let Some(curve) = scalar.get("points") {
next[key] = curve.clone();
}
}
next["pencil"] = json!(pencil);
*v = next;
true
}
/// Mode buttons above the graph: points, pencil, and Smooth for the shown channel's drawing.
fn curves_mode_row(ui: &mut egui::Ui, v: &mut Value, key: &str, cx: &EditorCx) -> Edit {
let pencil = v.get("pencil").and_then(Value::as_bool).unwrap_or(false);
let mut e = Edit::default();
ui.horizontal(|ui| {
if crate::icons::button(ui, "spline", 24.0, !pencil, tl!("Edit points to modify the curve")).clicked() && pencil {
e.add(Edit::discrete(set_editor_pencil(v, false, cx)));
}
if crate::icons::button(ui, "pencil", 24.0, pencil, tl!("Draw to modify the curve")).clicked() && !pencil {
e.add(Edit::discrete(set_editor_pencil(v, true, cx)));
}
let label = crate::i18n::tr_ctx(crate::i18n::current(), "curves", "Smooth");
let smooth = ui
.add_enabled_ui(pencil, |ui| widgets::secondary_button(ui, label, 0.0))
.inner
.on_hover_text(tl!("Smooth the curve values"))
.on_disabled_hover_text(tl!("Smooth the curve values"));
if smooth.clicked() {
let mut map = read_map(v, key);
adjust_params::smooth_curve_map(&mut map);
write_map(v, key, &map);
e.add(Edit::discrete(true));
}
});
e
}
/// The channel position an Alt/Option+digit selects: 2 is the first channel (the composite),
/// 3 the next, and so on (#7325). Reads the physical key, which Option changes on macOS.
fn channel_for_key(event: &egui::Event) -> Option<usize> {
let egui::Event::Key { key, physical_key, pressed: true, modifiers, .. } = event else {
return None;
};
if !modifiers.alt || modifiers.command || modifiers.ctrl || modifiers.shift {
return None;
}
let digit = |k: egui::Key| match k {
egui::Key::Num2 => Some(0),
egui::Key::Num3 => Some(1),
egui::Key::Num4 => Some(2),
egui::Key::Num5 => Some(3),
egui::Key::Num6 => Some(4),
_ => None,
};
digit(physical_key.unwrap_or(*key))
}
/// Consumes this frame's Alt/Option+2..6 presses, and the character Option types right after
/// each one on macOS, and selects that entry of the channel popup.
fn select_channel_by_key(ui: &egui::Ui, id: egui::Id, count: usize) {
let picked = ui.input_mut(|i| {
let mut last = None;
let mut typed = false;
i.events.retain(|e| match (channel_for_key(e), e) {
(Some(n), _) => {
last = Some(n);
typed = true;
false
}
(None, egui::Event::Text(_)) if typed => {
typed = false;
false
}
_ => {
typed = false;
true
}
});
last
});
if let Some(n) = picked.filter(|&n| n < count) {
ui.data_mut(|d| d.insert_temp(id, n));
}
}
pub(super) fn curves(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {
let t = Tokens::get(ui.ctx());
let space = space_of(v);
let channels = editor_channels(cx, space);
let state_id = cx.mem.with("curves");
let mut st: CurveUi = ui.data(|d| d.get_temp(state_id)).unwrap_or_default();
let isolated = cx.isolated_curve.as_ref();
if cx.dialog {
select_channel_by_key(ui, cx.mem.with("curves-ch"), channels.len());
}
let ch = editor_channel_picker(ui, cx.mem.with("curves-ch"), &channels);
if ch != st.channel {
st = CurveUi { channel: ch, ..Default::default() };
}
let (chan, _, hist_i) = channels.get(ch).cloned().unwrap_or((ToneChannel { key: "", label: "" }, String::new(), 0));
let overlay_others = isolated.is_none();
let tinted = isolated.is_some_and(|c| c.tint) || (isolated.is_none_or(|c| c.components.is_some()) && ch != 0);
let key = curve_key(&chan);
let mut e = curves_mode_row(ui, v, key, cx);
let pencil = v.get("pencil").and_then(Value::as_bool).unwrap_or(false);
let mut pts = read_curve(v, key);
let mut map = read_map(v, key);
let side = curve_side(ui);
ui.add_space(4.0);
let (full, resp) = ui.allocate_exact_size(vec2(side, side + 14.0), Sense::click_and_drag());
let graph = curve_graph(full, side);
ui.data_mut(|d| d.insert_temp(cx.mem.with("curves-graph"), graph));
let to_scr = |q: [f32; 2]| pos2(graph.left() + q[0] / 255.0 * graph.width(), graph.bottom() - q[1] / 255.0 * graph.height());
let mut changed = false;
let mut drawn = false;
if pencil {
// Pencil: a stroke draws while the button is down and commits on release; Shift
// continues from the previous stroke's end in a straight line.
let stroke_id = cx.mem.with("curves-pencil");
let (mut active, mut last): (bool, Option<[f32; 2]>) = ui.data(|d| d.get_temp(stroke_id)).unwrap_or_default();
if resp.is_pointer_button_down_on()
&& let Some(pos) = resp.interact_pointer_pos()
{
let q = [
((pos.x - graph.left()) / graph.width().max(1.0) * 255.0).clamp(0.0, 255.0),
((graph.bottom() - pos.y) / graph.height().max(1.0) * 255.0).clamp(0.0, 255.0),
];
let from = if active || ui.input(|i| i.modifiers.shift) { last.unwrap_or(q) } else { q };
drawn = curve_edit::pencil_line(&mut map, from, q);
active = true;
last = Some(q);
} else if active {
active = false;
e.commit = true;
}
ui.data_mut(|d| d.insert_temp(stroke_id, (active, last)));
} else {
let interaction =
crate::point_curve::interact_with_hit_radius(ui, &resp, graph, &mut pts, &mut st.gesture, crate::point_curve::curves_grab_radius(cx.dialog));
changed = interaction.changed;
e.commit |= interaction.commit;
}
// Draw: histogram, quarter grid, baseline, gradient bars, other channels, the curve, points.
let p = ui.painter_at(full.expand(2.0));
p.rect_filled(graph, 0.0, t.field);
if let Some(h) = &cx.hist {
tone::draw_histogram(&p, graph, &h[hist_i], Color32::from_gray(if t.pro { 88 } else { 190 }).gamma_multiply(0.75));
}
for i in 1..4 {
let f = i as f32 / 4.0;
let g = Stroke::new(1.0, t.separator);
p.line_segment([pos2(graph.left() + f * graph.width(), graph.top()), pos2(graph.left() + f * graph.width(), graph.bottom())], g);
p.line_segment([pos2(graph.left(), graph.top() + f * graph.height()), pos2(graph.right(), graph.top() + f * graph.height())], g);
}
p.line_segment([graph.left_bottom(), graph.right_top()], Stroke::new(1.0, t.separator.gamma_multiply(1.6)));
p.rect_stroke(
graph,
0.0,
Stroke::new(if resp.has_focus() { 1.5 } else { 1.0 }, if resp.has_focus() { t.accent } else { t.field_border }),
StrokeKind::Outside,
);
let hbar = Rect::from_min_max(pos2(graph.left(), graph.bottom() + 4.0), pos2(graph.right(), graph.bottom() + 12.0));
let vbar = Rect::from_min_max(pos2(full.left(), graph.top()), pos2(full.left() + 8.0, graph.bottom()));
gradient_bar(&p, hbar, Color32::BLACK, bar_color(&chan, &t), false);
gradient_bar(&p, vbar, Color32::BLACK, bar_color(&chan, &t), true);
let draw_curve = |key: &str, pts: &[[f32; 2]], color: Color32, width: f32| {
let line = cached_curve_line(ui.ctx(), cx.mem.with(("curves-polyline", key)), pts, graph);
p.add(egui::Shape::line(line, Stroke::new(width, color)));
};
let draw_map = |map: &[f32], color: Color32, width: f32| {
let last = map.len().saturating_sub(1).max(1) as f32;
let line: Vec<Pos2> = map.iter().enumerate().map(|(k, o)| to_scr([k as f32 / last * 255.0, *o])).collect();
p.add(egui::Shape::line(line, Stroke::new(width, color)));
};
if overlay_others && ch == 0 {
// Photoshop overlays the edited channel curves on the composite.
for c in tone_channels(space, cx.gray).iter().skip(1) {
if pencil {
let m = read_map(v, c.key);
if m.iter().enumerate().any(|(k, o)| (o - k as f32).abs() > 0.5) {
draw_map(&m, bar_color(c, &t).gamma_multiply(0.8), 1.0);
}
continue;
}
let cp = read_curve(v, c.key);
if cp.len() > 2 || cp.first().is_some_and(|q| q[1] != 0.0) || cp.last().is_some_and(|q| q[1] != 255.0) {
draw_curve(c.key, &cp, bar_color(c, &t).gamma_multiply(0.8), 1.0);
}
}
}
let color = if tinted { bar_color(&chan, &t) } else { t.text };
if pencil {
draw_map(&map, color, 1.5);
} else {
draw_curve(key, &pts, color, 1.5);
}
for (i, q) in pts.iter().enumerate().filter(|_| !pencil) {
let r = Rect::from_center_size(to_scr(*q), vec2(CURVE_HANDLE_SIZE, CURVE_HANDLE_SIZE));
if Some(i) == st.gesture.selected {
p.rect_filled(r, 0.0, t.text);
p.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::BLACK), StrokeKind::Outside);
} else {
p.rect_filled(r, 0.0, t.field);
p.rect_stroke(r, 0.0, Stroke::new(1.0, t.text), StrokeKind::Inside);
}
}
// Input / Output of the selected point.
ui.add_space(6.0);
ui.horizontal(|ui| {
let i = st.gesture.selected.filter(|i| *i < pts.len() && !pencil);
let (mut vi, mut vo) = i.map_or((0.0, 0.0), |i| (pts[i][0], pts[i][1]));
label(ui, tl!("Input:"));
let ri = ui.add_enabled_ui(i.is_some(), |ui| widgets::value_field(ui, &mut vi, 0.0..=255.0, "", 52.0).accessible_name(tl!("Input:"))).inner;
label(ui, tl!("Output:"));
let ro = ui.add_enabled_ui(i.is_some(), |ui| widgets::value_field(ui, &mut vo, 0.0..=255.0, "", 52.0).accessible_name(tl!("Output:"))).inner;
if let Some(i) = i
&& (ri.changed() || ro.changed())
&& curve_edit::move_to(&mut pts, i, [vi, vo])
{
changed = true;
e.commit |= !(ri.dragged() || ro.dragged());
}
if ri.drag_stopped() || ro.drag_stopped() {
e.commit = true;
}
});
let t2 = Tokens::get(ui.ctx());
let hint = if pencil {
crate::i18n::fmt(tl!("Drag to draw the curve · {key}-click draws a straight line"), &[("key", &crate::shortcuts::pretty("Shift"))])
} else {
crate::i18n::fmt(tl!("Click to add a point · drag off or {key}-click or Delete to remove"), &[("key", &crate::shortcuts::pretty("Cmd"))])
};
ui.label(RichText::new(hint).color(t2.text_faint).size(11.0));
ui.data_mut(|d| d.insert_temp(state_id, st));
if drawn {
write_map(v, key, &map);
if space == ToneSpace::Lab
&& isolated.is_none_or(|c| c.components.is_none())
&& let Some(o) = v.as_object_mut()
{
o.remove("points");
}
e.changed = true;
}
if changed && !pencil {
v[key] = json!(pts.iter().map(|q| [q[0].round(), q[1].round()]).collect::<Vec<_>>());
if space == ToneSpace::Lab && isolated.is_none_or(|c| c.components.is_none()) {
// Lab has no composite: "points" would alias lightness.
if let Some(o) = v.as_object_mut() {
o.remove("points");
}
}
e.changed = true;
}
e
}
#[cfg(test)]
mod multi_channel_tests {
use super::super::levels::read_levels;
use super::super::{auto_levels, editor};
use super::*;
use crate::{PhotocraftApp, tone::HistSource};
use photocraft_engine::{Session, channel_cmds};
use std::sync::Arc;
fn context(mode: &str) -> EditorCx {
let mut s = Session::new();
s.execute("file.new", json!({"width":32,"height":24,"mode":mode})).unwrap();
s.execute("channel.target", json!({"colors":[0,2]})).unwrap();
EditorCx {
mem: egui::Id::unique("subset-tone-test"),
hist: None,
gray: false,
swatches: [[0.0; 3], [1.0; 3]],
gradients: Vec::new(),
dialog: true,
dynamic_color_sliders: false,
isolated_curve: channel_cmds::isolated_curve_channel(s.active().unwrap()),
}
}
#[test]
fn combined_tone_entry_is_neutral_and_only_selected_components_are_listed() {
for (mode, space, keys, label) in [
("rgb", ToneSpace::Rgb, vec!["", "red", "blue"], "RB"),
("cmyk", ToneSpace::Cmyk, vec!["", "cyan", "yellow"], "CY"),
("lab", ToneSpace::Lab, vec!["", "lightness", "b"], "Lb"),
] {
let cx = context(mode);
let options = editor_channels(&cx, space);
assert_eq!(options.iter().map(|(c, _, _)| c.key).collect::<Vec<_>>(), keys);
assert_eq!(options.first().unwrap().1, label);
assert!(!cx.isolated_curve.as_ref().unwrap().tint);
}
}
#[test]
fn both_tone_editors_render_subset_choices_without_mutating_values() {
for kind in ["levels", "curves"] {
let cx = context("rgb");
let base =
photocraft_engine::adjust_params::to_params(&photocraft_engine::adjust_params::default_for(kind, photocraft_doc::ColorMode::Rgb).unwrap());
let mut values = base.clone();
let mut harness = egui_kittest::Harness::new_ui(|ui| {
if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
editor(ui, kind, &mut values, &cx);
}
});
PhotocraftApp::setup_context(&harness.ctx, Default::default());
harness.run();
drop(harness);
assert_eq!(values, base);
}
}
#[test]
fn subset_histograms_match_both_editors_in_all_native_spaces_and_depths() {
use egui_kittest::kittest::Queryable;
use photocraft_geom::Rect as PixelRect;
for mode in ["rgb", "cmyk", "lab"] {
for depth in [8, 16, 32] {
let mut s = Session::new();
s.execute("file.new", json!({"width":32,"height":24,"mode":mode,"depth":depth})).unwrap();
s.edit("Distinct native histogram bins", |doc, id| {
let surface = doc.layer_mut(id.unwrap()).unwrap().surface_mut().unwrap();
let mut pixel = vec![0.25, 0.5, 0.75];
pixel.resize(surface.format().mode.color_channels(), 0.0);
pixel.push(1.0);
surface.fill_rect(PixelRect::new(0, 0, 32, 24), &pixel);
pixel[0] = 0.375;
pixel[2] = 0.875;
surface.fill_rect(PixelRect::new(16, 0, 32, 24), &pixel);
Ok(())
})
.unwrap();
s.execute("channel.target", json!({"colors":[0,2]})).unwrap();
let st = s.active().unwrap();
let isolated = channel_cmds::isolated_curve_channel(st).unwrap();
let colors = isolated.components.unwrap();
let mut cx = context(mode);
cx.isolated_curve = Some(isolated);
for kind in ["levels", "curves"] {
let base = adjust_params::to_params(&adjust_params::default_for(kind, st.doc.mode).unwrap());
let space = space_of(&base);
let hist = Arc::new(tone::compute_histograms(
&st.doc,
HistSource::Colors { layer: st.active_layer.unwrap(), colors },
space,
tone::HistScope::WholeInput,
));
// Native subset histograms have their own combined slot even in Lab, whose
// ordinary composite histograms instead start with Lightness at slot 0.
assert_eq!(hist.ch.len(), 1 + st.doc.pixel_format().mode.color_channels());
assert_eq!(hist[0].iter().sum::<u32>(), 2 * 32 * 24);
assert_eq!(hist[1].iter().sum::<u32>(), 32 * 24);
assert_eq!(hist[2], [0; 256]);
assert_eq!(hist[3].iter().sum::<u32>(), 32 * 24);
assert_ne!(hist[1], hist[3]);
cx.hist = Some(hist.clone());
for (choice, (channel, _, histogram)) in editor_channels(&cx, space).into_iter().enumerate() {
assert!(hist[histogram].iter().any(|n| *n > 0));
let mut values = base.clone();
let mut harness = egui_kittest::Harness::new_ui(|ui| {
if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
editor(ui, kind, &mut values, &cx);
}
});
PhotocraftApp::setup_context(&harness.ctx, Default::default());
harness.ctx.data_mut(|d| d.insert_temp(cx.mem.with(format!("{kind}-ch")), choice));
harness.run_steps(4);
if kind == "levels" {
harness.get_by_label("Auto").click();
harness.run_steps(2);
}
drop(harness);
if kind == "levels" {
let (lo, hi) = auto_levels(&hist[histogram]);
let levels = read_levels(&values, channel.key);
assert_eq!((levels[0], levels[2]), (lo, hi), "{mode}@{depth} {}", channel.key);
} else {
assert_eq!(values, base);
}
}
}
}
}
}
#[test]
fn lab_subset_keeps_combined_curve_in_point_pencil_and_component_edits() {
for pencil in [false, true] {
for channel in [0usize, 2] {
let cx = context("lab");
let mut values = adjust_params::to_params(&adjust_params::default_for("curves", photocraft_doc::ColorMode::Lab).unwrap());
values["points"] = json!([[0, 0], [100, 150], [255, 255]]);
if pencil {
assert!(set_editor_pencil(&mut values, true, &cx));
}
let combined = values["points"].clone();
let component = values["b"].clone();
let mut harness = egui_kittest::Harness::new_ui(|ui| {
if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
editor(ui, "curves", &mut values, &cx);
}
});
PhotocraftApp::setup_context(&harness.ctx, Default::default());
harness.ctx.data_mut(|d| d.insert_temp(cx.mem.with("curves-ch"), channel));
harness.run_steps(4);
let graph = harness.ctx.data(|d| d.get_temp::<Rect>(cx.mem.with("curves-graph"))).unwrap();
let pos = pos2(graph.left() + graph.width() * 0.45, graph.top() + graph.height() * 0.25);
harness.event(egui::Event::PointerMoved(pos));
for pressed in [true, false] {
harness.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
harness.step();
}
harness.run_steps(2);
drop(harness);
assert!(values.get("points").is_some(), "combined record lost");
if channel == 0 {
assert_ne!(values["points"], combined);
} else {
assert_eq!(values["points"], combined);
assert_ne!(values["b"], component);
}
assert!(set_editor_pencil(&mut values, !pencil, &cx));
assert!(values.get("points").is_some());
assert!(values.get("b").is_some());
}
}
}
}
#[cfg(test)]
mod polyline_tests {
use super::*;
#[test]
fn curve_polyline_reuses_static_geometry_and_refreshes_edits_and_rect() {
let mut cache = CurvePolyline::default();
let mut points = [[0.0, 0.0], [128.0, 180.0], [255.0, 255.0]];
let graph = Rect::from_min_size(pos2(20.0, 30.0), vec2(256.0, 256.0));
assert!(cache.update(&points, graph));
assert_eq!(cache.line.len(), CURVE_SAMPLES);
assert_eq!(cache.line.first(), Some(&graph.left_bottom()));
assert_eq!(cache.line.last(), Some(&graph.right_top()));
let line = cache.line.clone();
assert!(!cache.update(&points, graph));
assert_eq!(cache.line, line);
points[1][1] = 80.0;
assert!(cache.update(&points, graph));
assert_ne!(cache.line, line);
points[1][1] = 180.0; // Undo/preset restore must also invalidate.
assert!(cache.update(&points, graph));
assert_eq!(cache.line, line);
let moved = graph.translate(vec2(13.0, 25.0));
assert!(cache.update(&points, moved));
for (before, after) in line.iter().zip(&cache.line) {
assert!((*after - (*before + vec2(13.0, 25.0))).length() < 1e-4);
}
let resized = Rect::from_min_size(moved.min, vec2(128.0, 180.0));
assert!(cache.update(&points, resized));
assert_eq!(cache.line.last(), Some(&resized.right_top()));
assert!(!cache.update(&points, resized));
}
#[test]
fn curve_polyline_memory_is_separate_per_editor_and_channel() {
let ctx = egui::Context::default();
let graph = Rect::from_min_size(Pos2::ZERO, vec2(256.0, 256.0));
let identity = [[0.0, 0.0], [255.0, 255.0]];
let inverted = [[0.0, 255.0], [255.0, 0.0]];
let editor = egui::Id::unique("dialog");
let master = editor.with(("curves-polyline", "points"));
let red = editor.with(("curves-polyline", "red"));
let other_editor = egui::Id::unique("properties").with(("curves-polyline", "points"));
let line = cached_curve_line(&ctx, master, &identity, graph);
assert_ne!(cached_curve_line(&ctx, red, &inverted, graph), line);
assert_ne!(cached_curve_line(&ctx, other_editor, &inverted, graph), line);
assert_eq!(cached_curve_line(&ctx, master, &identity, graph), line);
ctx.data_mut(|d| {
assert!(!d.get_temp_mut_or_default::<CurvePolyline>(master).update(&identity, graph));
assert!(!d.get_temp_mut_or_default::<CurvePolyline>(red).update(&inverted, graph));
assert!(!d.get_temp_mut_or_default::<CurvePolyline>(other_editor).update(&inverted, graph));
});
assert_ne!(cached_curve_line(&ctx, master, &inverted, graph), line);
}
#[test]
#[ignore = "release timing probe; run on GitHub Actions with --release --ignored --nocapture"]
fn curve_polyline_release_comparison() {
use std::{hint::black_box, time::Instant};
let graph = Rect::from_min_size(pos2(20.0, 30.0), vec2(300.0, 300.0));
let points = [[0.0, 0.0], [64.0, 48.0], [192.0, 208.0], [255.0, 255.0]];
let iterations = 10_000;
let start = Instant::now();
for _ in 0..iterations {
let cp: Vec<_> = black_box(&points).iter().map(|q| photocraft_doc::adjust::CurvePoint { input: q[0] / 255.0, output: q[1] / 255.0 }).collect();
let lut = photocraft_compose::adjust::curve_lut(&cp);
let line: Vec<_> = lut
.iter()
.enumerate()
.step_by(16)
.map(|(i, y)| pos2(graph.left() + i as f32 / 4095.0 * graph.width(), graph.bottom() - y * graph.height()))
.collect();
black_box(line);
}
let old = start.elapsed();
let start = Instant::now();
for _ in 0..iterations {
let mut cache = CurvePolyline::default();
cache.update(black_box(&points), graph);
black_box(cache.line.clone());
}
let miss = start.elapsed();
let ctx = egui::Context::default();
let id = egui::Id::unique("curve-perf");
cached_curve_line(&ctx, id, &points, graph);
let start = Instant::now();
for _ in 0..iterations {
black_box(cached_curve_line(&ctx, id, black_box(&points), graph));
}
let hit = start.elapsed();
println!("{iterations} polylines: old 4096 samples {old:?}; direct 256 samples {miss:?}; cached screen line {hit:?}");
}
}
#[cfg(test)]
mod channel_key_tests {
use super::*;
use egui::{Event, Key, Modifiers};
fn press(key: Key, modifiers: Modifiers) -> Event {
Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers }
}
fn cx(dialog: bool, gray: bool) -> EditorCx {
EditorCx {
mem: egui::Id::unique("channel-key-test"),
hist: None,
gray,
swatches: [[0.0; 3], [1.0; 3]],
gradients: Vec::new(),
dialog,
dynamic_color_sliders: false,
isolated_curve: None,
}
}
/// Runs one frame of the Curves editor with `events`; returns the selected channel and how
/// many key events were left unconsumed.
fn frame(ctx: &egui::Context, v: &mut Value, cx: &EditorCx, events: Vec<Event>) -> (usize, usize) {
let mut left = 0;
let mut output = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| {
curves(ui, v, cx);
left = ui.input(|i| i.events.iter().filter(|e| matches!(e, Event::Key { .. })).count());
});
output.textures_delta.clear();
(ctx.data(|d| d.get_temp(cx.mem.with("curves-ch"))).unwrap_or(0), left)
}
#[test]
fn alt_digits_select_rgb_channels_by_position() {
let cx = cx(true, false);
for (key, want) in [(Key::Num3, 1), (Key::Num4, 2), (Key::Num5, 3), (Key::Num2, 0), (Key::Num6, 0)] {
let ctx = egui::Context::default();
let mut v = json!({});
let (ch, left) = frame(&ctx, &mut v, &cx, vec![press(key, Modifiers::ALT)]);
assert_eq!(ch, want, "{key:?}");
assert_eq!(left, 0, "{key:?} is consumed");
}
}
#[test]
fn alt_digits_cover_cmyk_and_ignore_keys_past_the_list() {
let cx = cx(true, false);
let cmyk = || json!({"cyan": {}, "black": {}});
for (key, want) in [(Key::Num2, 0), (Key::Num3, 1), (Key::Num6, 4)] {
let ctx = egui::Context::default();
let (ch, _) = frame(&ctx, &mut cmyk(), &cx, vec![press(key, Modifiers::ALT)]);
assert_eq!(ch, want, "{key:?}");
}
// Gray lists one channel: Alt+3 does nothing.
let gray = self::cx(true, true);
let ctx = egui::Context::default();
let (ch, _) = frame(&ctx, &mut json!({}), &gray, vec![press(Key::Num3, Modifiers::ALT)]);
assert_eq!(ch, 0);
}
/// Lab lists Lightness, a and b (no composite); Gray lists one channel. Keys past the list
/// select nothing but are still consumed.
#[test]
fn alt_digits_cover_lab_and_gray() {
let rgb = cx(true, false);
let lab = || json!({"a": {}});
for (key, want) in [(Key::Num2, 0), (Key::Num3, 1), (Key::Num4, 2), (Key::Num5, 0), (Key::Num6, 0)] {
let ctx = egui::Context::default();
let (ch, left) = frame(&ctx, &mut lab(), &rgb, vec![press(key, Modifiers::ALT)]);
assert_eq!((ch, left), (want, 0), "Lab {key:?}");
}
let gray = cx(true, true);
for (key, want) in [(Key::Num2, 0), (Key::Num3, 0), (Key::Num6, 0)] {
let ctx = egui::Context::default();
let (ch, left) = frame(&ctx, &mut json!({}), &gray, vec![press(key, Modifiers::ALT)]);
assert_eq!((ch, left), (want, 0), "Gray {key:?}");
}
// Past the list after a valid pick: the earlier channel stays.
let ctx = egui::Context::default();
let mut v = lab();
frame(&ctx, &mut v, &rgb, vec![press(Key::Num4, Modifiers::ALT)]);
assert_eq!(frame(&ctx, &mut v, &rgb, vec![press(Key::Num5, Modifiers::ALT)]), (2, 0));
}
#[test]
fn other_modifiers_and_the_properties_panel_leave_the_keys_alone() {
let ctx = egui::Context::default();
let dialog = cx(true, false);
for m in [Modifiers::NONE, Modifiers::COMMAND, Modifiers::ALT | Modifiers::SHIFT, Modifiers::ALT | Modifiers::COMMAND] {
let (ch, left) = frame(&ctx, &mut json!({}), &dialog, vec![press(Key::Num3, m)]);
assert_eq!((ch, left), (0, 1), "{m:?}");
}
let panel = cx(false, false);
let (ch, left) = frame(&ctx, &mut json!({}), &panel, vec![press(Key::Num3, Modifiers::ALT)]);
assert_eq!((ch, left), (0, 1));
}
#[test]
fn the_physical_key_decides_when_it_is_known() {
let ctx = egui::Context::default();
let cx = cx(true, false);
let remapped = Event::Key { key: Key::Num3, physical_key: Some(Key::Q), pressed: true, repeat: false, modifiers: Modifiers::ALT };
assert_eq!(frame(&ctx, &mut json!({}), &cx, vec![remapped]), (0, 1));
let logical_only = Event::Key { key: Key::Num3, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::ALT };
assert_eq!(frame(&ctx, &mut json!({}), &cx, vec![logical_only]), (1, 0));
}
#[test]
fn the_character_option_types_is_consumed_with_the_key() {
let ctx = egui::Context::default();
let cx = cx(true, false);
let mut left = Vec::new();
let events = vec![press(Key::Num4, Modifiers::ALT), Event::Text("¢".into()), Event::Text("7".into())];
let mut output = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| {
curves(ui, &mut json!({}), &cx);
left = ui.input(|i| i.events.clone());
});
output.textures_delta.clear();
assert_eq!(left, vec![Event::Text("7".into())]);
assert_eq!(ctx.data(|d| d.get_temp::<usize>(cx.mem.with("curves-ch"))), Some(2));
}
}
@@ -1,421 +0,0 @@
use super::basic::{sliders, track_stops};
use super::curves::gradient_bar;
use super::levels::nearest;
use super::{
Color32, Edit, EditorCx, HUE_RANGES, HueRange, Rect, RichText, Sense, Stroke, StrokeKind, Tokens, Value, color32, flag, hue_color, json, num, nums, pos2,
vec2, widgets,
};
// ---------------------------------------------------------------------------------------------
// Hue/Saturation
pub(super) const RANGE_LABELS: [&str; 6] = ["Reds", "Yellows", "Greens", "Cyans", "Blues", "Magentas"];
/// The range picker's swatches in order (#14753): Master, then the six colour ranges.
pub(super) const SWATCH_LABELS: [&str; 7] = ["Master", "Red", "Yellow", "Green", "Cyan", "Blue", "Magenta"];
/// A range swatch's diameter, in points.
const SWATCH: f32 = 18.0;
/// The Saturation slider's track: grey to the hue at full saturation (UI-217-16).
pub(super) fn saturation_track(hue_deg: f32) -> [Color32; 2] {
[Color32::from_gray(128), hue_color(hue_deg)]
}
/// The Lightness slider's track: black, mid grey, white, whatever the hue, as in Photoshop
/// (UI-217-16, #6539).
pub(super) fn lightness_track() -> [Color32; 3] {
[Color32::BLACK, Color32::from_gray(128), Color32::WHITE]
}
pub(super) fn move_hue_range_handle(bounds: [f32; 4], k: usize, deg: f32) -> [f32; 4] {
let mut b = HueRange::canonical_bounds(bounds);
if k >= b.len() {
return b;
}
if k == 0 {
let delta = (deg - b[0] + 180.0).rem_euclid(360.0) - 180.0;
b[0] = (b[0] + delta).min(b[1]).max(b[1] - 180.0);
} else {
let rel = (deg - b[0]).rem_euclid(360.0);
let hi = if k == 3 { b[0] + 359.0 } else { b[k + 1] };
b[k] = (b[0] + rel).clamp(b[k - 1], hi);
}
b
}
/// The range handle a press at `x` grabs, given the four handles' x positions on a bar `w` wide:
/// the nearest within 10 points, or within a third of the gap to the next handle on that side, so
/// the middle third of a narrow zone still drags the zone (at least 3 points, for handles that
/// coincide). The bar is a hue circle: the next handle past an edge is the first from the other.
pub(super) fn hue_range_handle_at(xs: [f32; 4], x: f32, w: f32) -> Option<u8> {
let k = nearest(&xs, x)?;
let (xk, d) = (xs[k as usize], x - xs[k as usize]);
let gap = xs
.iter()
.enumerate()
.filter(|&(j, _)| j != k as usize)
.map(|(_, &o)| if d >= 0.0 { (o - xk).rem_euclid(w) } else { (xk - o).rem_euclid(w) })
.fold(f32::INFINITY, f32::min);
(d.abs() < (gap / 3.0).clamp(3.0, 10.0)).then_some(k)
}
/// Which zone of a colour range a hue `deg` falls in, between its handles: 0 = the left fade
/// (between the first two), 1 = the fully-on span, 2 = the right fade; `None` outside the range.
pub(super) fn hue_range_zone(bounds: [f32; 4], deg: f32) -> Option<u8> {
let b = HueRange::canonical_bounds(bounds);
let rel = (deg - b[0]).rem_euclid(360.0);
let (one, two, three) = (b[1] - b[0], b[2] - b[0], b[3] - b[0]);
if rel <= one {
Some(0)
} else if rel <= two {
Some(1)
} else if rel <= three {
Some(2)
} else {
None
}
}
/// A drag of `delta` degrees on a zone of a colour range (#9252), as in Photoshop: the left fade
/// moves the two left handles, the fully-on span all four, the right fade the two right handles;
/// a side never crosses the other or grows the range past a turn.
pub(super) fn move_hue_range_zone(start: [f32; 4], zone: u8, delta: f32) -> [f32; 4] {
let b = HueRange::canonical_bounds(start);
if !delta.is_finite() {
return b;
}
let moved = match zone {
0 => {
let d = delta.min(b[2] - b[1]).max(b[3] - 359.0 - b[0]);
[b[0] + d, b[1] + d, b[2], b[3]]
}
1 => b.map(|v| v + delta),
2 => {
let d = delta.max(b[1] - b[2]).min(b[0] + 359.0 - b[3]);
[b[0], b[1], b[2] + d, b[3] + d]
}
_ => b,
};
HueRange::canonical_bounds(moved)
}
/// The spectrum bar after the adjustment (what each hue becomes), sampled at `n` hues.
fn adjusted_spectrum(v: &Value, n: usize) -> Vec<Color32> {
let hues: Vec<[f32; 3]> = (0..n).map(|i| photocraft_color::convert::hsb_to_rgb([i as f32 / (n - 1).max(1) as f32 * 360.0, 1.0, 1.0])).collect();
adjusted_colors(v, &hues)
}
/// What the adjustment `v` makes of each colour in `rgb`.
fn adjusted_colors(v: &Value, rgb: &[[f32; 3]]) -> Vec<Color32> {
let adj = photocraft_engine::commands::adjustment_from_params("hueSaturation", v);
let rect = photocraft_geom::Rect::new(0, 0, rgb.len() as i32, 1);
let px = rgb.iter().map(|c| [c[0], c[1], c[2], 1.0]).collect();
let mut buf = photocraft_compose::Buffer { rect, px };
photocraft_compose::adjust::apply(&adj, &mut buf);
buf.px.iter().map(|p| color32([p[0], p[1], p[2]])).collect()
}
/// The centre of a colour range: the middle of its fully-on span, in 0..360.
fn range_centre(bounds: [f32; 4]) -> f32 {
let b = HueRange::canonical_bounds(bounds);
((b[1] + b[2]) / 2.0).rem_euclid(360.0)
}
/// The label above the Hue field (#14753): the centre of colour range `range` (1 = Reds …
/// 6 = Magentas) and, once its Hue moves it, where it goes ("0° / 30°"); none for Master (0).
pub(super) fn range_centre_label(v: &Value, range: usize) -> Option<String> {
let i = range.checked_sub(1)?;
let o = &v[*HUE_RANGES.get(i)?];
let c = range_centre(nums(o, "range", HueRange::neutral(i).bounds)).round();
let h = num(o, "hue", 0.0).round();
// `+ 0.0` turns a -0 into 0, so no "-0°".
let deg = |d: f32| format!("{:.0}°", d.rem_euclid(360.0) + 0.0);
Some(if h == 0.0 { deg(c) } else { format!("{} / {}", deg(c), deg(c + h)) })
}
/// What colour range `i` (0 = Reds … 5 = Magentas) shows on its swatch (#14753): the colour at its
/// centre and, once its own Hue, Saturation or Lightness is not zero, what they make of it.
pub(super) fn range_swatch(v: &Value, i: usize) -> (Color32, Option<Color32>) {
let Some(key) = HUE_RANGES.get(i) else { return (Color32::TRANSPARENT, None) };
let o = &v[*key];
let c = range_centre(nums(o, "range", HueRange::neutral(i).bounds));
let before = photocraft_color::convert::hsb_to_rgb([c, 1.0, 1.0]);
let edited = ["hue", "saturation", "lightness"].iter().any(|k| num(o, k, 0.0) != 0.0);
let after = edited.then(|| {
// This range alone: Master and the other ranges don't change its swatch.
let mut only = json!({});
only[*key] = o.clone();
adjusted_colors(&only, &[before]).first().copied().unwrap_or(Color32::TRANSPARENT)
});
(color32(before), after)
}
/// The colorize colour, as Colorize makes a mid grey (#14753).
pub(super) fn colorize_color(v: &Value) -> Color32 {
adjusted_colors(v, &[[0.5; 3]]).first().copied().unwrap_or(Color32::TRANSPARENT)
}
/// Half a disc of radius `r` at `c`: the left half or the right one.
fn half_disc(p: &egui::Painter, c: egui::Pos2, r: f32, left: bool, fill: Color32) {
let start = if left { std::f32::consts::FRAC_PI_2 } else { -std::f32::consts::FRAC_PI_2 };
let pts = (0..=16).map(|k| start + std::f32::consts::PI * k as f32 / 16.0).map(|a| c + vec2(a.cos(), a.sin()) * r).collect();
p.add(egui::Shape::convex_polygon(pts, fill, Stroke::NONE));
}
/// A hue wheel of radius `r` at `c`, red at the top: the Master swatch.
fn hue_wheel(p: &egui::Painter, c: egui::Pos2, r: f32) {
let at = |deg: f32| {
let a = (deg - 90.0).to_radians();
c + vec2(a.cos(), a.sin()) * r
};
for k in 0..36 {
let (a, z) = (k as f32 * 10.0, (k + 1) as f32 * 10.0);
// Each wedge overlaps the next by a little, so no background shows through the seams.
p.add(egui::Shape::convex_polygon(vec![c, at(a - 0.5), at(z + 0.5)], hue_color(a + 5.0), Stroke::NONE));
}
}
/// The range picker (#14753): seven round swatches, Master (a hue wheel) then the six colour
/// ranges, the selected one ringed; a click selects that range. An edited range shows its colour
/// before and after, split down the middle, with a dot under it. Colorize collapses the row into
/// one disc in the colorize colour.
fn range_swatches(ui: &mut egui::Ui, v: &Value, range: &mut usize, colorize: bool) {
let t = Tokens::get(ui.ctx());
let size = vec2(SWATCH, SWATCH + 6.0);
let r = SWATCH / 2.0 - 2.0;
let centre = |rect: Rect| pos2(rect.center().x, rect.top() + SWATCH / 2.0);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 6.0;
if colorize {
let (rect, resp) = ui.allocate_exact_size(size, Sense::hover());
ui.painter().circle(centre(rect), r, colorize_color(v), Stroke::new(1.0, t.field_border));
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Colorize")));
return;
}
let swatches: Vec<(Rect, egui::Response)> = SWATCH_LABELS.iter().map(|_| ui.allocate_exact_size(size, Sense::click())).collect();
if let Some(i) = swatches.iter().position(|(_, resp)| resp.clicked()) {
*range = i;
}
let p = ui.painter();
for (i, ((rect, resp), label)) in swatches.into_iter().zip(SWATCH_LABELS).enumerate() {
let c = centre(rect);
if i == 0 {
hue_wheel(p, c, r);
} else {
match range_swatch(v, i - 1) {
(before, Some(after)) => {
half_disc(p, c, r, true, before);
half_disc(p, c, r, false, after);
p.circle_filled(pos2(c.x, rect.bottom() - 1.5), 1.5, t.text_dim);
}
(before, None) => {
p.circle_filled(c, r, before);
}
}
}
let selected = i == *range;
if selected {
p.circle_stroke(c, r + 1.0, Stroke::new(2.0, t.text));
} else {
p.circle_stroke(c, r, Stroke::new(1.0, t.field_border));
}
// Keyboard focus gets its own accent ring, clear of the selection ring, so tabbing to
// a swatch shows where Space or Enter will act without moving the selection.
if resp.has_focus() {
p.circle_stroke(c, r + 3.0, Stroke::new(1.0, t.accent));
}
let label = tl!(label);
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, selected, label));
resp.on_hover_text(label);
}
});
}
pub(super) fn spectrum_bar(p: &egui::Painter, r: Rect, colors: &[Color32]) {
let n = colors.len().saturating_sub(1).max(1);
for (i, w) in colors.windows(2).enumerate() {
let x0 = r.left() + r.width() * i as f32 / n as f32;
let x1 = r.left() + r.width() * (i + 1) as f32 / n as f32;
gradient_bar(p, Rect::from_min_max(pos2(x0, r.top()), pos2(x1, r.bottom())), w[0], w[1], false);
}
}
pub(super) fn hue_saturation(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {
let t = Tokens::get(ui.ctx());
let range_id = cx.mem.with("hs-range");
let mut range: usize = ui.data(|d| d.get_temp(range_id)).unwrap_or(0);
let colorize = flag(v, "colorize", false);
if colorize {
range = 0;
}
range_swatches(ui, v, &mut range, colorize);
ui.data_mut(|d| d.insert_temp(range_id, range));
let mut e = Edit::default();
let hue_grad = widgets::hue_stops();
if range == 0 {
let (hlo, hhi, slo) = if colorize { (0.0, 360.0, 0.0) } else { (-180.0, 180.0, -100.0) };
let mut h = num(v, "hue", 0.0).clamp(hlo, hhi);
let r = widgets::slider_row(ui, tl!("Hue"), &mut h, hlo..=hhi, "°", track_stops(cx, &hue_grad));
if r.changed() {
v["hue"] = json!(h.round());
}
e.add(Edit::of(&r));
// The Saturation track follows the current hue; the Lightness track is a fixed
// black-grey-white ramp, as in Photoshop (UI-217-16).
let sat_track = saturation_track(h);
let mut s = num(v, "saturation", 0.0).clamp(slo, 100.0);
let r = widgets::slider_row(ui, tl!("Saturation"), &mut s, slo..=100.0, "%", track_stops(cx, &sat_track));
if r.changed() {
v["saturation"] = json!(s.round());
}
e.add(Edit::of(&r));
let light_track = lightness_track();
let mut l = num(v, "lightness", 0.0).clamp(-100.0, 100.0);
let r = widgets::slider_row(ui, tl!("Lightness"), &mut l, -100.0..=100.0, "%", track_stops(cx, &light_track));
if r.changed() {
v["lightness"] = json!(l.round());
}
e.add(Edit::of(&r));
} else {
let key = HUE_RANGES[range - 1];
if !v.get(key).is_some_and(Value::is_object) {
v[key] = json!({});
}
if let Some(centre) = range_centre_label(v, range) {
// One row, right-aligned: a bare right-to-left layout would centre it in all the height left.
ui.horizontal(|ui| ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(RichText::new(centre).color(t.text_dim))));
}
let mut o = v[key].clone();
let mut sub = Edit::default();
let mut h = num(&o, "hue", 0.0);
let r = widgets::slider_row(ui, tl!("Hue"), &mut h, -180.0..=180.0, "°", track_stops(cx, &hue_grad));
if r.changed() {
o["hue"] = json!(h.round());
}
sub.add(Edit::of(&r));
sub.add(sliders(
ui,
&mut o,
&[("saturation", tl!("Saturation"), -100.0, 100.0, 0.0, "%", None), ("lightness", tl!("Lightness"), -100.0, 100.0, 0.0, "%", None)],
));
if sub.changed {
v[key] = o;
}
e.add(sub);
}
let mut c = colorize;
if widgets::checkbox(ui, &mut c, tl!("Colorize")).changed() {
v["colorize"] = json!(c);
let h = num(v, "hue", 0.0);
v["hue"] = json!(if c {
h.rem_euclid(360.0)
} else if h > 180.0 {
h - 360.0
} else {
h
});
if c {
v["saturation"] = json!(num(v, "saturation", 25.0).max(0.0).max(25.0));
}
e.add(Edit::discrete(true));
}
// Spectrum bars: input hues above, adjusted below; the selected range's sliders between.
ui.add_space(6.0);
// As wide as the sliders above, whatever the panel's width (#9242).
let w = ui.available_width();
let (bars, bresp) = ui.allocate_exact_size(vec2(w, 40.0), Sense::click_and_drag());
ui.data_mut(|d| d.insert_temp(cx.mem.with("hs-bars"), bars));
let top = Rect::from_min_size(bars.min, vec2(w, 10.0));
let bottom = Rect::from_min_size(pos2(bars.left(), bars.bottom() - 10.0), vec2(w, 10.0));
let p = ui.painter_at(bars.expand(4.0));
let input: Vec<Color32> = (0..=36).map(|i| hue_color(i as f32 * 10.0)).collect();
spectrum_bar(&p, top, &input);
spectrum_bar(&p, bottom, &adjusted_spectrum(v, 37));
if range > 0 {
let key = HUE_RANGES[range - 1];
let neutral = photocraft_doc::adjust::HueRange::neutral(range - 1).bounds;
let mut b = HueRange::canonical_bounds(nums(&v[key], "range", neutral));
let xof = |deg: f32| bars.left() + deg.rem_euclid(360.0) / 360.0 * w;
let deg_of = |x: f32| ((x - bars.left()) / w * 360.0).clamp(0.0, 360.0);
let mid = bars.center().y;
// Range band (fully affected) and fall-off.
let band = |a: f32, z: f32, color: Color32| {
let (xa, xz) = (xof(a), xof(z));
if xa <= xz {
p.rect_filled(Rect::from_min_max(pos2(xa, mid - 3.0), pos2(xz, mid + 3.0)), 0.0, color);
} else {
p.rect_filled(Rect::from_min_max(pos2(xa, mid - 3.0), pos2(bars.right(), mid + 3.0)), 0.0, color);
p.rect_filled(Rect::from_min_max(pos2(bars.left(), mid - 3.0), pos2(xz, mid + 3.0)), 0.0, color);
}
};
band(b[0], b[3], t.text_faint);
band(b[1], b[2], t.text_dim);
for (k, d) in b.iter().enumerate() {
let x = xof(*d);
let fill = if k == 1 || k == 2 { t.text } else { t.field };
p.rect_filled(Rect::from_center_size(pos2(x, mid), vec2(5.0, 12.0)), 1.0, fill);
p.rect_stroke(Rect::from_center_size(pos2(x, mid), vec2(5.0, 12.0)), 1.0, Stroke::new(1.0, t.text_dim), StrokeKind::Inside);
}
ui.data_mut(|d| d.insert_temp(cx.mem.with("hs-range-bars"), bars));
let drag_id = cx.mem.with("hs-range-drag");
let zone_id = cx.mem.with("hs-range-zone");
let mut which: Option<u8> = ui.data(|d| d.get_temp(drag_id)).flatten();
// A press between the handles drags a zone (#9252): its zone, the bounds and x it began at.
let mut zone: Option<(u8, [f32; 4], f32)> = ui.data(|d| d.get_temp(zone_id)).flatten();
if bresp.is_pointer_button_down_on()
&& ui.input(|i| i.pointer.primary_pressed())
&& let Some(pos) = ui.input(|i| i.pointer.press_origin())
{
which = hue_range_handle_at(b.map(xof), pos.x, w);
zone = if which.is_none() { hue_range_zone(b, deg_of(pos.x)).map(|z| (z, b, pos.x)) } else { None };
}
// The release frame applies its position too: a move and a release that land in one frame
// would otherwise commit the bounds from before the move. It ends where the button let go,
// not where the pointer went after that in the same frame.
let released_at = ui.input(|i| {
i.events.iter().find_map(|e| match e {
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, .. } => Some(*pos),
_ => None,
})
});
let live = bresp.is_pointer_button_down_on() || released_at.is_some();
let drag_pos = released_at.or_else(|| ui.input(|i| i.pointer.interact_pos()));
if live && let (Some((z, start, x0)), Some(pos)) = (zone, drag_pos) {
let before = b;
b = move_hue_range_zone(start, z, (pos.x - x0) / w * 360.0);
if b != before {
v[key]["range"] = json!(b.map(|x| x.round()));
e.changed = true;
}
}
if zone.is_some() && !bresp.is_pointer_button_down_on() {
zone = None;
e.commit = true;
}
ui.data_mut(|d| d.insert_temp(zone_id, zone));
if live && let (Some(k), Some(pos)) = (which, drag_pos) {
let k = k as usize;
let deg = deg_of(pos.x);
let before = b;
b = move_hue_range_handle(b, k, deg);
if b != before {
v[key]["range"] = json!(b.map(|x| x.round()));
e.changed = true;
}
}
if which.is_some() && !bresp.is_pointer_button_down_on() {
which = None;
e.commit = true;
}
ui.data_mut(|d| d.insert_temp(drag_id, which));
let lab =
format!("{:.0}° / {:.0}° · {:.0}° \\ {:.0}°", b[0].rem_euclid(360.0), b[1].rem_euclid(360.0), b[2].rem_euclid(360.0), b[3].rem_euclid(360.0));
ui.label(RichText::new(lab).font(crate::theme::mono(11.0)).color(t.text_faint));
}
e
}
#[cfg(test)]
#[path = "hue_saturation_swatches_tests.rs"]
mod swatches_tests;
@@ -1,197 +0,0 @@
//! #14753: Hue/Saturation picks its range with seven round swatches (Master, then Red, Yellow,
//! Green, Cyan, Blue, Magenta) instead of a dropdown; an edited range shows its colour before and
//! after with a dot under it, a label above the Hue field gives the range's centre, and Colorize
//! collapses the row into one disc in the colorize colour.
use egui::accesskit::{Role, Toggled};
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::{Value, json};
use super::super::EditorCx;
use super::{SWATCH_LABELS, colorize_color, hue_saturation, range_centre_label, range_swatch};
fn cx(mem: egui::Id) -> EditorCx {
EditorCx {
mem,
hist: None,
gray: false,
swatches: [[0.0; 3], [1.0; 3]],
gradients: Vec::new(),
dialog: false,
dynamic_color_sliders: true,
isolated_curve: None,
}
}
fn mem() -> egui::Id {
egui::Id::unique("hue-saturation-swatches-test")
}
/// The Hue/Saturation editor over `v`, as the Properties panel hosts it.
fn harness(v: Value) -> Harness<'static, Value> {
let mut h = Harness::builder().with_size(vec2(320.0, 400.0)).build_ui_state(
|ui, v: &mut Value| {
// The app's fonts load over a few frames; draw once they're in.
if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
hue_saturation(ui, v, &cx(mem()));
}
},
v,
);
crate::PhotocraftApp::setup_context(&h.ctx, Default::default());
h.run_steps(4);
h
}
fn swatches(h: &Harness<'_, Value>) -> Vec<(String, bool)> {
h.query_all_by_role(Role::RadioButton)
.map(|n| {
let a = n.accesskit_node();
(a.label().unwrap_or_default(), a.toggled() == Some(Toggled::True))
})
.collect()
}
fn text_rect(h: &Harness<'_, Value>, text: &str) -> Option<egui::Rect> {
h.query_all_by_role(Role::Label)
.find(|n| {
let a = n.accesskit_node();
a.value().as_deref() == Some(text) || a.label().as_deref() == Some(text)
})
.map(|n| n.rect())
}
fn has_text(h: &Harness<'_, Value>, text: &str) -> bool {
text_rect(h, text).is_some()
}
fn range(h: &Harness<'_, Value>) -> Option<usize> {
h.ctx.data(|d| d.get_temp(mem().with("hs-range")))
}
#[test]
fn seven_swatches_replace_the_dropdown_with_master_selected() {
let h = harness(json!({}));
let want: Vec<(String, bool)> = SWATCH_LABELS.iter().enumerate().map(|(i, l)| (l.to_string(), i == 0)).collect();
assert_eq!(swatches(&h), want, "Master, Red, Yellow, Green, Cyan, Blue, Magenta; Master selected");
assert!(h.query_all_by_role(Role::ComboBox).next().is_none(), "no range dropdown");
}
#[test]
fn a_click_selects_that_range_and_shows_its_centre() {
let mut h = harness(json!({}));
assert!(!has_text(&h, "0°") && !has_text(&h, "240°"), "no centre label for Master");
h.query_all_by_role_and_label(Role::RadioButton, "Blue").next().expect("the Blue swatch").click();
h.run_steps(3);
assert_eq!(range(&h), Some(5), "Blues selected");
assert!(swatches(&h).iter().all(|(l, on)| *on == (l == "Blue")), "only Blue is selected: {:?}", swatches(&h));
// Right-aligned just above the Hue row (title, field and slider), which now edits Blues.
let label = text_rect(&h, "240°").expect("the Blues centre");
let hue = h.query_all_by_role(Role::Slider).find(|n| n.accesskit_node().label().as_deref() == Some("Hue")).expect("the Hue slider").rect();
assert!(label.bottom() <= hue.top() + 1.0 && hue.top() - label.bottom() < 48.0, "label {label:?} right above Hue {hue:?}");
assert!(label.center().x > 160.0, "right-aligned: {label:?}");
h.query_all_by_role_and_label(Role::RadioButton, "Red").next().expect("the Red swatch").click();
h.run_steps(3);
assert_eq!(range(&h), Some(1));
assert!(has_text(&h, "0°"), "the Reds centre");
h.query_all_by_role_and_label(Role::RadioButton, "Master").next().expect("the Master swatch").click();
h.run_steps(3);
assert_eq!(range(&h), Some(0));
assert!(!has_text(&h, "0°"), "no centre label for Master");
}
#[test]
fn reds_after_a_hue_shift_label_both_centres() {
let mut h = harness(json!({"reds": {"hue": 30}}));
h.query_all_by_role_and_label(Role::RadioButton, "Red").next().expect("the Red swatch").click();
h.run_steps(3);
assert!(has_text(&h, "0° / 30°"));
}
/// Circles stroked in `color` whose centre lies inside `rect`.
fn rings_in(h: &Harness<'_, Value>, rect: egui::Rect, color: egui::Color32) -> usize {
h.output()
.shapes
.iter()
.filter(|s| matches!(&s.shape, egui::Shape::Circle(c) if c.stroke.color == color && c.stroke.width > 0.0 && rect.contains(c.center)))
.count()
}
#[test]
fn a_focused_swatch_shows_focus_apart_from_the_selection() {
let mut h = harness(json!({}));
let accent = crate::theme::Tokens::get(&h.ctx).accent;
let blue = h.query_all_by_role_and_label(Role::RadioButton, "Blue").next().expect("the Blue swatch").rect();
let master = h.query_all_by_role_and_label(Role::RadioButton, "Master").next().expect("the Master swatch").rect();
assert_eq!(rings_in(&h, blue, accent), 0, "no focus ring before focus");
h.query_all_by_role_and_label(Role::RadioButton, "Blue").next().expect("the Blue swatch").focus();
h.run_steps(3);
assert_eq!(range(&h), Some(0), "focus alone keeps Master selected");
assert_eq!(rings_in(&h, blue, accent), 1, "the focused Blue swatch has a focus ring");
assert_eq!(rings_in(&h, master, accent), 0, "the selected Master swatch has none");
assert!(swatches(&h).iter().all(|(l, on)| *on == (l == "Master")), "selection unchanged: {:?}", swatches(&h));
h.key_press(egui::Key::Space);
h.run_steps(3);
assert_eq!(range(&h), Some(5), "Space selects the focused swatch");
}
#[test]
fn colorize_collapses_the_row_into_one_disc() {
let h = harness(json!({"colorize": true, "hue": 120, "saturation": 25}));
assert!(swatches(&h).is_empty(), "no range swatches with Colorize on");
assert_eq!(h.query_all_by_role_and_label(Role::Image, "Colorize").count(), 1, "one colorize disc");
}
#[test]
fn centre_labels() {
let v = json!({});
assert_eq!(range_centre_label(&v, 0), None, "Master");
assert_eq!(range_centre_label(&v, 1).as_deref(), Some("0°"), "Reds");
assert_eq!(range_centre_label(&v, 2).as_deref(), Some("60°"), "Yellows");
assert_eq!(range_centre_label(&v, 5).as_deref(), Some("240°"), "Blues");
assert_eq!(range_centre_label(&v, 6).as_deref(), Some("300°"), "Magentas");
assert_eq!(range_centre_label(&v, 7), None, "past the ranges: no label, no panic");
assert_eq!(range_centre_label(&json!({"reds": {"hue": 30}}), 1).as_deref(), Some("0° / 30°"));
assert_eq!(range_centre_label(&json!({"reds": {"hue": -30}}), 1).as_deref(), Some("0° / 330°"));
// A moved range: its centre is the middle of its fully-on span.
assert_eq!(range_centre_label(&json!({"blues": {"range": [190, 220, 240, 270]}}), 5).as_deref(), Some("230°"));
// Saturation or Lightness alone moves no hue.
assert_eq!(range_centre_label(&json!({"blues": {"saturation": 50}}), 5).as_deref(), Some("240°"));
}
#[test]
fn an_edited_range_shows_before_and_after() {
let close = |a: egui::Color32, b: [u8; 3]| [a.r(), a.g(), a.b()].iter().zip(b).all(|(x, y)| x.abs_diff(y) <= 2);
let (before, after) = range_swatch(&json!({}), 0);
assert!(close(before, [255, 0, 0]), "Reds: red, {before:?}");
assert_eq!(after, None, "an untouched range has no after half");
let (before, after) = range_swatch(&json!({"reds": {"hue": 30}}), 0);
assert!(close(before, [255, 0, 0]));
let after = after.expect("Hue +30 edits Reds");
assert!(close(after, [255, 128, 0]), "red turned 30° towards yellow: {after:?}");
let (_, after) = range_swatch(&json!({"blues": {"lightness": -100}}), 4);
assert!(close(after.expect("Lightness edits Blues"), [0, 0, 0]), "Blues at Lightness -100 is black");
// Master and the other ranges leave a range's swatch alone.
assert_eq!(range_swatch(&json!({"hue": 90, "greens": {"saturation": -50}}), 0).1, None);
// Reset puts every range back to zero: the after halves go.
let reset = json!({"reds": {"hue": 0, "saturation": 0, "lightness": 0}});
assert_eq!(range_swatch(&reset, 0).1, None);
assert_eq!(range_swatch(&json!({}), 6), (egui::Color32::TRANSPARENT, None), "past the ranges: no panic");
}
#[test]
fn the_colorize_disc_takes_the_colorize_colour() {
let c = colorize_color(&json!({"colorize": true, "hue": 120, "saturation": 100}));
assert!(c.g() > c.r() + 64 && c.g() > c.b() + 64, "green: {c:?}");
let c = colorize_color(&json!({"colorize": true, "hue": 240, "saturation": 100}));
assert!(c.b() > c.r() + 64 && c.b() > c.g() + 64, "blue: {c:?}");
}
@@ -1,144 +0,0 @@
//! The Mixer Brush's Current Brush Load swatch shows what the reservoir holds (#11953): a solid
//! colour after Load Brush, the sampled 64 × 64 tip image after an ⌥-click (an edge between green
//! and blue shows green on the left and blue on the right), and a checkerboard after Clean Brush.
use egui::{Modifiers, Rect, Shape, TextureId, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
use super::{mixer_load_image, mixer_load_texture};
use crate::PhotocraftApp;
use crate::canvas::{ToolEvent, tool_event};
use crate::state::Tool;
const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0];
/// A pixel layer green left of x 100 and blue from there on, with the Mixer Brush active.
fn app() -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 100, "background": "white"})).unwrap();
app.run("layer.new.layer", json!({})).unwrap();
app.run("select.rect", json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap();
app.run("edit.fill", json!({"contents": "color", "color": GREEN})).unwrap();
app.run("select.rect", json!({"x": 100, "y": 0, "width": 100, "height": 100})).unwrap();
app.run("edit.fill", json!({"contents": "color", "color": BLUE})).unwrap();
app.run("select.deselect", json!({})).unwrap();
app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#ffffff"})).unwrap();
app.ui.tool = Tool::MixerBrush;
crate::paint_mouse::sync_tool_brush(&mut app);
app.run("tools.setBrush", json!({"brush": {"size": 40, "hardness": 1.0}})).unwrap();
app
}
fn harness() -> Harness<'static, PhotocraftApp> {
let mut h = Harness::builder().with_size(vec2(1600.0, 120.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, crate::theme::ThemeKind::Studio);
h.run_steps(4);
h
}
fn flatten<'a>(shape: &'a Shape, out: &mut Vec<&'a Shape>) {
if let Shape::Vec(v) = shape {
v.iter().for_each(|s| flatten(s, out));
} else {
out.push(shape);
}
}
/// What the swatch draws this frame: the fill colours of its rectangles and the textures of its
/// images, inside the swatch's chip.
fn swatch(h: &Harness<'static, PhotocraftApp>) -> (Vec<egui::Color32>, Vec<TextureId>) {
let r = h.get_by_label("Current Brush Load").rect();
let chip = Rect::from_min_size(egui::pos2(r.left() + 4.0, r.center().y - 8.0), vec2(16.0, 16.0)).expand(0.5);
let (mut fills, mut textures) = (Vec::new(), Vec::new());
for clipped in &h.output().shapes {
let mut all = Vec::new();
flatten(&clipped.shape, &mut all);
for s in all {
match s {
Shape::Rect(rs) if chip.contains_rect(rs.rect) => fills.push(rs.fill),
Shape::Mesh(m) if m.texture_id != TextureId::default() && chip.contains_rect(m.calc_bounds()) => textures.push(m.texture_id),
_ => {}
}
}
}
(fills, textures)
}
fn has_fonts(h: &Harness<'static, PhotocraftApp>) -> bool {
h.ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into())))
}
#[test]
fn the_sampled_image_keeps_its_left_right_top_and_bottom() {
let load: Vec<[f32; 4]> = (0..64 * 64).map(|i| if i % 64 < 32 { GREEN } else { BLUE }).collect();
let image = mixer_load_image(&load);
assert_eq!(image.size, [64, 64]);
assert_eq!(image[(10, 32)], egui::Color32::from_rgb(0, 255, 0));
assert_eq!(image[(54, 32)], egui::Color32::from_rgb(0, 0, 255));
// Row 0 is the tip's top, as `load_at` reads it; alpha is kept and values past 0..1 clamp.
let load: Vec<[f32; 4]> = (0..64 * 64).map(|i| if i < 32 * 64 { [1.0, 0.0, 0.0, 0.5] } else { [1.5, -0.2, 0.0, 1.0] }).collect();
let image = mixer_load_image(&load);
let (top, bottom) = (image[(32, 10)], image[(32, 54)]);
assert_eq!((top.r() > 0, top.g(), top.b(), top.a()), (true, 0, 0, 128), "top of the image {top:?}");
assert_eq!(bottom, egui::Color32::from_rgb(255, 0, 0), "bottom of the image");
}
#[test]
fn the_swatch_shows_the_load_the_tip_image_or_a_checkerboard() {
let mut h = harness();
if !has_fonts(&h) {
return;
}
// Load Brush: one solid red, no image.
h.state_mut().run("brush.mixer.load", json!({})).unwrap();
h.run_steps(3);
let (fills, textures) = swatch(&h);
assert!(fills.contains(&egui::Color32::from_rgb(255, 0, 0)) && textures.is_empty(), "{fills:?} {textures:?}");
// ⌥-click on the green/blue edge: the sampled tip image, green left and blue right.
tool_event(h.state_mut(), ToolEvent::Down { x: 100.0, y: 50.0, pressure: 1.0 }, Modifiers::ALT);
tool_event(h.state_mut(), ToolEvent::Up { x: 100.0, y: 50.0 }, Modifiers::ALT);
h.run_steps(3);
let load = h.state().session.tools.mixer.spatial.clone().expect("the ⌥-click loads the tip image");
let (_, textures) = swatch(&h);
let sampled = mixer_load_texture(&h.ctx, &load).id();
assert_eq!(textures, [sampled], "the swatch draws the texture of the sampled load");
let image = mixer_load_image(&load);
let (left, right) = (image[(16, 32)], image[(48, 32)]);
assert!(left.g() > 200 && left.b() < 50, "left of the image {left:?}");
assert!(right.b() > 200 && right.g() < 50, "right of the image {right:?}");
h.run_steps(3);
assert_eq!(swatch(&h).1, [sampled], "an unchanged load keeps its texture");
// ⌥-click in the green: a new load, uploaded again.
tool_event(h.state_mut(), ToolEvent::Down { x: 30.0, y: 50.0, pressure: 1.0 }, Modifiers::ALT);
tool_event(h.state_mut(), ToolEvent::Up { x: 30.0, y: 50.0 }, Modifiers::ALT);
h.run_steps(3);
let green = h.state().session.tools.mixer.spatial.clone().expect("the second ⌥-click loads the tip image");
let (_, textures) = swatch(&h);
assert!(textures != [sampled] && textures == [mixer_load_texture(&h.ctx, &green).id()], "the new load's texture {textures:?}");
// A new foreground: the next stroke loads it, so the swatch shows that colour, not the image.
h.state_mut().run("tools.setColors", json!({"foreground": "#ffff00"})).unwrap();
h.run_steps(3);
let (fills, textures) = swatch(&h);
assert!(fills.contains(&egui::Color32::from_rgb(255, 255, 0)) && textures.is_empty(), "the new foreground {fills:?} {textures:?}");
// Clean Brush: a checkerboard of two greys, no image.
h.state_mut().run("brush.mixer.clean", json!({})).unwrap();
h.run_steps(3);
let (fills, textures) = swatch(&h);
let greys: std::collections::BTreeSet<_> = fills.iter().filter(|c| c.r() == c.g() && c.g() == c.b() && c.r() > 150).map(|c| c.r()).collect();
assert!(greys.len() >= 2 && textures.is_empty(), "checkerboard {fills:?} {textures:?}");
}
@@ -1,181 +0,0 @@
//! Move tool Auto-Select (#296), as in Photoshop: on by default, a press picks the topmost
//! visible layer with pixels under the pointer (or its outermost group in Group mode) and the drag
//! then moves it; ⌘/Ctrl held at the press inverts the option for that click.
use photocraft_doc::LayerId;
use photocraft_geom::Rect;
use serde_json::json;
use crate::PhotocraftApp;
use crate::canvas::ToolEvent;
use crate::state::Tool;
/// A 64×64 document with two painted layers: A covers (8..24)², B covers (40..56)². B is active.
fn app() -> (Box<PhotocraftApp>, LayerId, LayerId) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap();
app.sync_views();
let mut ids = Vec::new();
for at in [8, 40] {
app.session.execute("layer.new.layer", json!({})).unwrap();
app.session
.edit("paint", |doc, a| {
doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(at, at, at + 16, at + 16), &[1.0, 0.0, 0.0, 1.0]);
Ok(())
})
.unwrap();
ids.push(app.session.active().unwrap().active_layer.unwrap());
}
app.ui.tool = Tool::Move;
// Snapping (to the document centre with a 1:1 test view) would shift the expected offsets.
app.ui.extras.snap = false;
app.ui.view.show.smart_guides = false;
(app, ids[0], ids[1])
}
fn bounds(app: &PhotocraftApp, id: LayerId) -> Rect {
app.session.active().unwrap().doc.layer(id).unwrap().surface().unwrap().content_bounds()
}
fn active(app: &PhotocraftApp) -> Option<LayerId> {
app.session.active().unwrap().active_layer
}
fn drag(app: &mut PhotocraftApp, from: [f64; 2], by: [f64; 2], mods: egui::Modifiers) {
crate::canvas::tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods);
let mid = [from[0] + by[0] / 2.0, from[1] + by[1] / 2.0];
crate::canvas::tool_event(app, ToolEvent::Move { x: mid[0], y: mid[1], pressure: 1.0 }, mods);
let end = [from[0] + by[0], from[1] + by[1]];
crate::canvas::tool_event(app, ToolEvent::Move { x: end[0], y: end[1], pressure: 1.0 }, mods);
crate::canvas::tool_event(app, ToolEvent::Up { x: end[0], y: end[1] }, mods);
}
#[test]
fn a_press_picks_the_layer_under_the_pointer_and_drags_it() {
let (mut app, a, b) = app();
assert_eq!(active(&app), Some(b));
drag(&mut app, [16.0, 16.0], [10.0, 4.0], egui::Modifiers::NONE);
assert_eq!(active(&app), Some(a), "the click selected A");
assert_eq!(bounds(&app, a), Rect::new(18, 12, 34, 28), "and the drag moved A");
assert_eq!(bounds(&app, b), Rect::new(40, 40, 56, 56), "B stays put");
}
#[test]
fn command_click_suspends_auto_select_for_that_drag() {
let (mut app, a, b) = app();
drag(&mut app, [16.0, 16.0], [-10.0, 0.0], egui::Modifiers::COMMAND);
assert_eq!(active(&app), Some(b), "⌘ held: no pick");
assert_eq!(bounds(&app, b), Rect::new(30, 40, 46, 56), "the selected layer moved");
assert_eq!(bounds(&app, a), Rect::new(8, 8, 24, 24));
}
#[test]
fn command_click_picks_when_auto_select_is_off() {
let (mut app, a, b) = app();
app.ui.tool_options.move_auto_select = false;
drag(&mut app, [16.0, 16.0], [0.0, 6.0], egui::Modifiers::NONE);
assert_eq!(active(&app), Some(b), "off: the selected layer moves");
assert_eq!(bounds(&app, a), Rect::new(8, 8, 24, 24));
drag(&mut app, [16.0, 16.0], [0.0, 6.0], egui::Modifiers::COMMAND);
assert_eq!(active(&app), Some(a), "⌘-click picks while the option is off");
assert_eq!(bounds(&app, a), Rect::new(8, 14, 24, 30));
}
#[test]
fn group_mode_picks_and_moves_the_outermost_group() {
let (mut app, a, b) = app();
app.session.execute("layer.select", json!({"layer": a.0})).unwrap();
let group = LayerId(app.session.execute("layer.new.groupFromLayers", json!({"name": "G"})).unwrap()["layer"].as_u64().unwrap());
app.session.execute("layer.select", json!({"layer": b.0})).unwrap();
app.ui.tool_options.move_target = "group".into();
drag(&mut app, [16.0, 16.0], [0.0, 10.0], egui::Modifiers::NONE);
assert_eq!(active(&app), Some(group));
assert_eq!(bounds(&app, a), Rect::new(8, 18, 24, 34), "moving the group moves its layer");
assert_eq!(bounds(&app, b), Rect::new(40, 40, 56, 56));
}
#[test]
fn dragging_one_of_several_selected_layers_moves_them_all() {
let (mut app, a, b) = app();
app.session.execute("layer.select", json!({"layer": a.0})).unwrap();
app.session.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap();
drag(&mut app, [16.0, 16.0], [-4.0, -4.0], egui::Modifiers::NONE);
assert_eq!(bounds(&app, a), Rect::new(4, 4, 20, 20));
assert_eq!(bounds(&app, b), Rect::new(36, 36, 52, 52));
}
#[test]
fn shift_click_adds_the_layer_under_the_pointer() {
let (mut app, a, b) = app();
// A click without a drag only selects.
drag(&mut app, [16.0, 16.0], [0.0, 0.0], egui::Modifiers::SHIFT);
let st = app.session.active().unwrap();
assert!(st.is_layer_selected(a) && st.is_layer_selected(b));
assert_eq!(bounds(&app, a), Rect::new(8, 8, 24, 24));
}
#[test]
fn shift_click_adds_shape_layers_one_after_another() {
// Shapes, as in Photoshop: a click selects one, each ⇧-click adds the one under it.
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap();
for rect in [[10, 10, 40, 40], [80, 10, 40, 40], [10, 100, 40, 40]] {
app.session.execute("shape.create", json!({"kind": "rect", "rect": rect, "fill": "#ff0000"})).unwrap();
}
app.sync_views();
app.ui.tool = Tool::Move;
app.ui.extras.snap = false;
app.ui.view.show.smart_guides = false;
let ids: Vec<LayerId> = app.session.active().unwrap().doc.layers.iter().skip(1).map(|l| l.id).collect();
drag(&mut app, [30.0, 30.0], [0.0, 0.0], egui::Modifiers::NONE);
drag(&mut app, [100.0, 30.0], [0.0, 0.0], egui::Modifiers::SHIFT);
drag(&mut app, [30.0, 120.0], [0.0, 0.0], egui::Modifiers::SHIFT);
let mut selected = app.session.active().unwrap().selected_layers().to_vec();
selected.sort_by_key(|l| l.0);
assert_eq!(selected, ids);
}
/// Opens B's transform controls (Show Transform Controls on) and resizes the box to twice B's
/// size from its top-left corner, so it covers (40..72)².
fn resized_box() -> (Box<PhotocraftApp>, LayerId, LayerId) {
let (mut app, a, b) = app();
app.ui.tool_options.move_show_transform = true;
crate::transform_tool::begin(&mut app, &egui::Context::default()).unwrap();
let t = app.ui.transform.as_mut().unwrap();
t.quad[2] = [t.quad[2][0] + 16.0, t.quad[2][1] + 16.0];
t.quad[1][0] += 16.0;
t.quad[3][1] += 16.0;
(app, a, b)
}
/// A plain click (press and release without moving) at document point `p`.
fn click(app: &mut PhotocraftApp, p: [f64; 2]) {
crate::canvas::tool_event(app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, egui::Modifiers::NONE);
crate::canvas::tool_event(app, ToolEvent::Up { x: p[0], y: p[1] }, egui::Modifiers::NONE);
}
/// #8208, #11100, as measured in the reference application: a click outside a resized box on
/// another layer's pixels commits the resize as one Free Transform step and keeps the transformed
/// layer selected; the second click on that layer is the one that picks it.
#[test]
fn a_click_on_another_layer_accepts_a_resized_box_and_the_next_one_picks_it() {
let (mut app, a, b) = resized_box();
click(&mut app, [16.0, 16.0]);
assert!(app.ui.transform.is_none(), "the click on A accepted the box");
assert_eq!(bounds(&app, b), Rect::new(40, 40, 72, 72), "B keeps its resize");
let last = app.session.active().unwrap().history.entries().last().map(ToString::to_string);
assert_eq!(last.as_deref(), Some("Free Transform"));
assert_eq!(active(&app), Some(b), "the accepting click leaves B selected");
click(&mut app, [16.0, 16.0]);
assert_eq!(active(&app), Some(a), "the second click picks A");
}
/// #11100: a click outside the box where only the Background has pixels keeps it open, B still
/// selected.
#[test]
fn a_click_on_the_background_alone_keeps_the_resized_box_open() {
let (mut app, _, b) = resized_box();
click(&mut app, [30.0, 30.0]);
assert!(app.ui.transform.is_some(), "the box stays open");
assert_eq!(active(&app), Some(b));
}
-297
View File
@@ -1,297 +0,0 @@
use super::{Align2, BlendMode, Color32, PhotocraftApp, Rect, Sense, Stroke, StrokeKind, Tokens, c32, icons, json, pos2, starts_blend_group, vec2, widgets};
/// A painting tool's Mode dropdown over `modes` (`None` is Clear); the wheel over it steps the
/// mode. Returns the mode picked this frame. A list of every blend mode draws the Layers panel's
/// group lines (#5532; Clear starts none); a short one (the Healing Brush's) draws none.
/// `threshold` names Normal "Threshold", as the reference does in an Indexed Color document.
pub(super) fn tool_mode_dropdown(
ui: &mut egui::Ui,
id: &str,
modes: &[Option<BlendMode>],
current: Option<BlendMode>,
threshold: bool,
) -> Option<Option<BlendMode>> {
let label = |m: &Option<BlendMode>| match m {
Some(BlendMode::Normal) if threshold => tl!("Threshold"),
_ => m.map_or("Clear", BlendMode::label),
};
let opts: Vec<(Option<BlendMode>, &str)> = modes.iter().map(|m| (*m, label(m))).collect();
let grouped = BlendMode::LAYER_MODES.iter().all(|m| modes.contains(&Some(*m)));
let mut mode = current;
let chosen = widgets::dropdown_wheel_grouped(ui, id, tl!("Mode"), &mut mode, &opts, 96.0, |m| grouped && m.is_some_and(starts_blend_group)).0;
chosen.last().copied()
}
/// The Brush's or Pencil's Mode dropdown: the blend modes, with Photoshop's painting-only Clear
/// after Dissolve (#3439). Clear erases with the brush (`clear`); it shows while chosen, or while
/// `~` is held (`held`). The wheel over it steps the mode, as over the Layers panel's (#2061).
pub(super) fn paint_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraft_engine::BrushSettings, clear: &mut bool, held: bool) {
let opts = crate::brush_mode_menu::choices();
let mut mode = if *clear || held {
(None, false)
} else if b.behind {
(None, true)
} else {
(Some(b.mode), false)
};
if !widgets::dropdown_wheel_grouped(ui, id, tl!("Mode"), &mut mode, &opts, 96.0, |m| m.0.is_some_and(starts_blend_group)).0.is_empty() {
*clear = mode == (None, false);
b.behind = mode.1;
if mode.1 {
b.mode = BlendMode::Normal;
}
if let Some(m) = mode.0 {
b.mode = m;
}
}
}
/// The Pattern Stamp's Mode dropdown: the blend modes with Behind after Dissolve and no Clear, as
/// the reference application lists them (#12879). Behind is the tool's own brush's, as its mode;
/// picking another mode leaves it. The wheel steps it as it steps the other Mode dropdowns.
/// Without `behind_enabled` (the Background is the active layer) Behind is greyed, as in the
/// Shift+right-click menu, and the wheel and the keys step past it.
pub(super) fn pattern_stamp_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraft_engine::BrushSettings, behind_enabled: bool, threshold: bool) {
let mut opts = crate::brush_mode_menu::pattern_stamp_choices();
if threshold && let Some(normal) = opts.iter_mut().find(|o| o.0 == (Some(BlendMode::Normal), false)) {
normal.1 = tl!("Threshold");
}
let before = if b.behind { (None, true) } else { (Some(b.mode), false) };
let mut mode = before;
let groups = |m: &(Option<BlendMode>, bool)| m.0.is_some_and(starts_blend_group);
if !widgets::dropdown_wheel_grouped_enabled(ui, id, tl!("Mode"), &mut mode, &opts, 96.0, groups, |m| behind_enabled || !m.1).0.is_empty() {
let mode = crate::brush_mode_menu::pattern_stamp_pick(before, mode, behind_enabled);
b.behind = mode.1;
b.mode = mode.0.unwrap_or(BlendMode::Normal);
}
}
/// The Eraser's Smoothing %: whole numbers 0..100 that say when a typed value was past them, for
/// the reference's alert (#11938). Returns the field and whether to show the alert.
pub(super) fn smoothing_field_alerting(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings, width: f32) -> (egui::Response, bool) {
let mut sm = b.smoothing.amount * 100.0;
let (r, alert) = widgets::value_field_whole_alerting(ui, tl!("Smoothing"), &mut sm, 0.0..=100.0, "%", width);
if r.changed() {
b.smoothing.enabled = true;
b.smoothing.amount = (sm / 100.0).clamp(0.0, 1.0);
}
(r, alert)
}
/// Options-bar Smoothing % (the brush's stroke smoothing; the live stroke and the commit use it).
pub(super) fn smoothing_field(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings, width: f32) -> egui::Response {
let mut sm = (b.smoothing.amount * 100.0).round();
let r = widgets::value_field_named(ui, tl!("Smoothing"), &mut sm, 0.0..=100.0, "%", width);
if r.changed() {
b.smoothing.enabled = true;
b.smoothing.amount = (sm / 100.0).clamp(0.0, 1.0);
}
r
}
/// Options-bar gear beside Smoothing: Photoshop's smoothing options popup, edited on the brush
/// like the Smoothing % (so they stay per tool and reach the live stroke and the commit).
/// `brush` adds the Brush's "Smoothing Options" title (#11813); the Eraser keeps its popup as it was.
pub(super) fn smoothing_options(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings, brush: bool) {
let resp = icons::button(ui, "settings", 24.0, false, tl!("Set additional smoothing options"));
let resp = crate::brush_picker::named(resp, "Set additional smoothing options");
egui::Popup::from_toggle_button_response(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
let s = &mut b.smoothing;
if brush {
ui.label(egui::RichText::new(tl!("Smoothing Options")).strong());
}
// At 0 % there is no smoothing to tune: the four are greyed and keep their values, as in
// the reference application (#11939). Rounded like the Smoothing field, so a value that
// shows as 0 % greys them too.
let on = (s.amount * 100.0).round() > 0.0;
ui.add_enabled_ui(on, |ui| {
widgets::checkbox(ui, &mut s.pulled_string, tl!("Pulled String Mode"));
widgets::checkbox(ui, &mut s.catch_up, tl!("Stroke Catch-up"));
widgets::checkbox(ui, &mut s.catch_up_on_end, tl!("Catch-up on Stroke End"));
widgets::checkbox(ui, &mut s.adjust_for_zoom, tl!("Adjust for Zoom"));
});
});
}
/// The sampled tip image of a Mixer Brush load (64 × 64 straight RGBA cells, row by row) as the
/// Current Brush Load swatch draws it.
pub(crate) fn mixer_load_image(load: &[[f32; 4]]) -> egui::ColorImage {
let bytes: Vec<u8> = load.iter().flat_map(|c| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)).collect();
egui::ColorImage::from_rgba_unmultiplied([64, 64], &bytes)
}
/// The swatch's texture of `load`, uploaded again only when the load changes.
fn mixer_load_texture(ctx: &egui::Context, load: &[[f32; 4]]) -> egui::TextureHandle {
use std::hash::{Hash, Hasher};
let image = mixer_load_image(load);
let mut hasher = std::collections::hash_map::DefaultHasher::new();
image.as_raw().hash(&mut hasher);
let hash = hasher.finish();
let key = egui::Id::unique("mixer-load-swatch-image");
if let Some((_, tex)) = ctx.data(|d| d.get_temp::<(u64, egui::TextureHandle)>(key)).filter(|(h, _)| *h == hash) {
return tex;
}
let tex = ctx.load_texture("mixer-load-swatch", image, egui::TextureOptions::LINEAR);
ctx.data_mut(|d| d.insert_temp(key, (hash, tex.clone())));
tex
}
#[cfg(test)]
#[path = "../mixer_load_swatch_tests.rs"]
mod mixer_load_swatch_tests;
/// A Useful mixer brush combinations entry: its label and the Wet, Load and Mix it sets.
type MixerCombination = (&'static str, Option<(f32, f32, f32)>);
/// The Mixer Brush's Useful mixer brush combinations, in the reference's order: each entry's label
/// and the Wet, Load and Mix (0..1) it sets. Custom, the first, sets nothing.
pub(crate) const MIXER_COMBINATIONS: [MixerCombination; 13] = [
("Custom", None),
("Dry", Some((0.0, 0.5, 0.0))),
("Dry, Light Load", Some((0.0, 0.05, 0.0))),
("Dry, Heavy Load", Some((0.0, 1.0, 0.0))),
("Moist", Some((0.1, 0.05, 0.5))),
("Moist, Light Mix", Some((0.1, 0.05, 0.0))),
("Moist, Heavy Mix", Some((0.1, 0.05, 1.0))),
("Wet", Some((0.5, 0.5, 0.5))),
("Wet, Light Mix", Some((0.5, 0.5, 0.0))),
("Wet, Heavy Mix", Some((0.5, 0.5, 1.0))),
("Very Wet", Some((1.0, 0.5, 0.5))),
("Very Wet, Light Mix", Some((1.0, 0.5, 0.0))),
("Very Wet, Heavy Mix", Some((1.0, 0.5, 1.0))),
];
/// The entries of [`MIXER_COMBINATIONS`] a separator line goes above: Dry, Moist, Wet, Very Wet.
const MIXER_COMBINATION_GROUPS: [usize; 4] = [1, 4, 7, 10];
/// Mixer Brush: the Useful mixer brush combinations dropdown (#11946). Picking an entry sets Wet,
/// Load and Mix together (Flow stays) and keeps showing it, also after a value is typed; Custom
/// sets nothing. `picked` is the entry shown.
pub(super) fn mixer_combination_dropdown(
ui: &mut egui::Ui,
picked: &mut usize,
m: &mut photocraft_engine::paint::mixer::MixerSettings,
) -> Option<egui::Response> {
const ID: &str = "mixer-combination";
let opts: Vec<(usize, &str)> = MIXER_COMBINATIONS.iter().enumerate().map(|(i, (label, _))| (i, *label)).collect();
let mut shown = (*picked).min(MIXER_COMBINATIONS.len() - 1);
let chosen =
widgets::dropdown_wheel_grouped(ui, ID, tl!("Useful mixer brush combinations"), &mut shown, &opts, 132.0, |i| MIXER_COMBINATION_GROUPS.contains(i)).0;
if let Some(&i) = chosen.last() {
*picked = i;
if let Some((wet, load, mix)) = MIXER_COMBINATIONS[i].1 {
(m.wet, m.load, m.mix) = (wet, load, mix);
}
}
ui.ctx().read_response(ui.make_persistent_id(egui::IdSalt::new(ID)))
}
#[cfg(test)]
#[path = "../mixer_blend_combination_tests.rs"]
mod mixer_blend_combination_tests;
#[cfg(test)]
#[path = "../mixer_load_solid_colors_tests.rs"]
mod mixer_load_solid_colors_tests;
/// Mixer Brush: the Current Brush Load swatch shows the paint the next stroke starts with: the
/// loaded colour, the sampled tip image after an ⌥-click, or a transparency checkerboard when the
/// brush is clean. Its menu holds Load Brush, Clean Brush, a separator and the checkable Load Solid
/// Colors Only.
pub(super) fn mixer_load_swatch(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
let (r, _) = ui.allocate_exact_size(vec2(40.0, 26.0), Sense::hover());
let resp = ui.interact(r, ui.scope_id().with("mixer-brush-load"), Sense::click());
if resp.hovered() {
ui.painter().rect_filled(r, t.radius_sm, t.hover);
}
let chip = Rect::from_min_size(pos2(r.left() + 4.0, r.center().y - 8.0), vec2(16.0, 16.0));
let p = ui.painter();
// What the reservoir holds (#11953): the loaded colour, the sampled tip image of an ⌥-click
// (kept while the foreground stays), or a transparency checkerboard when the brush is clean.
let mixer = &app.session.tools.mixer;
let foreground = app.session.tools.foreground;
match mixer.next_load(foreground) {
Some(c) => match mixer.spatial.as_deref().filter(|load| load.len() == 64 * 64 && mixer.color == Some(foreground)) {
Some(load) => {
widgets::checker(p, chip, 4.0);
let tex = mixer_load_texture(ui.ctx(), load);
p.image(tex.id(), chip, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}
None => {
p.rect_filled(chip, 2.0, c32(c));
}
},
None => widgets::checker(p, chip, 4.0),
}
p.rect_stroke(chip, 2.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
icons::paint(ui, Rect::from_center_size(pos2(r.right() - 9.0, r.center().y), vec2(10.0, 10.0)), "chevron-down", 9.0, t.text_faint);
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Current Brush Load")));
let resp = resp.on_hover_text(tl!("Current Brush Load"));
let (mut run, mut solid_colors) = (None, None);
egui::Popup::menu(&resp).show(|ui| {
if ui.button(tl!("Load Brush")).clicked() {
run = Some("brush.mixer.load");
}
if ui.button(tl!("Clean Brush")).clicked() {
run = Some("brush.mixer.clean");
}
ui.separator();
// Load Solid Colors Only: ⌥-click loads one colour, not the tip image (#11952).
let mut solid = app.session.tools.brush.mixer.solid_colors_only;
if ui.checkbox(&mut solid, tl!("Load Solid Colors Only")).changed() {
solid_colors = Some(solid);
}
});
if let Some(id) = run
&& let Err(e) = app.run(id, json!({}))
{
app.ui.status = e;
app.ui.status_error = true;
}
if let Some(on) = solid_colors
&& let Err(e) = app.run("tools.setBrush", json!({"brush": {"mixer": {"solidColorsOnly": on}}}))
{
app.ui.status = e;
app.ui.status_error = true;
}
}
/// Options-bar brush chip: a click shows or hides Photoshop's Brush Preset picker below it (size,
/// hardness, the preset library), the one a right-click on the canvas opens.
pub(super) fn brush_preset_chip(ui: &mut egui::Ui, b: &photocraft_engine::BrushSettings, state: &mut crate::state::UiState) {
let t = Tokens::get(ui.ctx());
let (r, _) = ui.allocate_exact_size(vec2(44.0, 30.0), Sense::hover());
let resp = ui.interact(r, crate::brush_picker::chip_id(), Sense::click());
if resp.hovered() || state.brush_picker.is_some() {
ui.painter().rect_filled(r, t.radius_sm, t.hover);
}
let c = pos2(r.left() + 14.0, r.top() + 11.0);
// Photoshop's white tip vanishes on light chrome; light themes use their icon colour.
let tip = if t.dark() { Color32::WHITE } else { t.icon };
// The brush's own tip, as the Brush Preset picker's thumbnails draw it: the engine's falloff
// for its hardness, its angle and roundness, a sampled tip's shape.
let tex = crate::brush_preview::tip_texture(ui.ctx(), "options-bar-chip", &b.tip, (b.hardness, b.angle, b.roundness), 32, tip);
let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
ui.painter().image(tex.id(), Rect::from_center_size(c, vec2(14.0, 14.0)), uv, Color32::WHITE);
ui.painter().text(pos2(c.x, r.bottom() - 5.0), Align2::CENTER_CENTER, format!("{}", b.size.round() as i64), egui::FontId::proportional(9.5), t.text_dim);
icons::paint(ui, Rect::from_center_size(pos2(r.right() - 9.0, c.y), vec2(10.0, 10.0)), "chevron-down", 9.0, t.text_faint);
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Brush Preset picker")));
// The Brush's and the Background Eraser's own text (#11813, #11909); the other tools keep theirs.
let tip = if matches!(state.tool, crate::state::Tool::Brush | crate::state::Tool::BackgroundEraser) {
tl!("Click to open the Brush Preset picker")
} else {
tl!("Brush Preset picker")
};
if resp.on_hover_text(tip).clicked() {
if state.brush_picker.is_some() {
crate::brush_picker::close(state);
} else {
crate::brush_picker::open(state, ui.ctx(), [r.left(), r.bottom() + 2.0]);
}
}
}
#[cfg(test)]
#[path = "../smoothing_options_greyed_tests.rs"]
mod smoothing_options_greyed_tests;
@@ -1,202 +0,0 @@
//! #14443: in the Curves graph a click up to 15 screen px from an existing point selects that
//! point instead of adding a second one next to it, while a click clearly away still adds.
//! The other hosts of the shared widget were not measured in the reference application, so they
//! keep today's 9 px radius.
use egui::{Event, Modifiers, PointerButton, Pos2, Rect, Sense, vec2};
use egui_kittest::Harness;
use crate::state::PointCurveState;
use crate::widgets::point_curve::{self, CURVES_HIT_RADIUS};
/// One egui point per input level (one screen pixel at scale 1.0, the scale the issue measures at):
/// the graph is exactly 255 points on a side, so a distance in points and an input distance in
/// levels are the same number.
const SIDE: f32 = 255.0;
/// The radius of the hosts that stay as they are today.
const TODAY: f32 = 9.0;
#[derive(Clone, Debug)]
struct Host {
pts: Vec<[f32; 2]>,
gesture: PointCurveState,
graph: Rect,
radius: f32,
}
/// A bare point-curve graph of `radius` grab pixels: identity curve, one point at level 128.
fn graph(radius: f32) -> Harness<'static, Host> {
let mut h = Harness::builder().with_size(vec2(600.0, 600.0)).build_ui_state(
|ui, host: &mut Host| {
let (rect, resp) = ui.allocate_exact_size(vec2(SIDE, SIDE), Sense::click_and_drag());
host.graph = rect;
point_curve::interact_with_hit_radius(ui, &resp, rect, &mut host.pts, &mut host.gesture, host.radius);
},
Host { pts: vec![[0.0, 0.0], [128.0, 128.0], [255.0, 255.0]], gesture: PointCurveState::default(), graph: Rect::NOTHING, radius },
);
h.run_steps(2); // The first frame lays the graph out.
h
}
/// Screen position of the input/output level pair `level` (1 px per level).
fn at(host: &Host, level: [f32; 2]) -> Pos2 {
Pos2::new(host.graph.left() + level[0], host.graph.bottom() - level[1])
}
/// Press and release at `pos`, a frame each: one click.
fn click(h: &mut Harness<'static, Host>, pos: Pos2) {
h.event(Event::PointerMoved(pos));
h.run_steps(1);
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.run_steps(1);
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(2);
}
/// Press at `from`, move to `to`, release there: one drag.
fn drag(h: &mut Harness<'static, Host>, from: Pos2, to: Pos2) {
h.event(Event::PointerMoved(from));
h.run_steps(1);
h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.run_steps(1);
h.event(Event::PointerMoved(to));
h.run_steps(1);
h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(2);
}
/// The Curves dialog's own geometry (#8984): `curves()` allocates a square of `side` plus the 14
/// points of the vertical bar and draws the graph 5 points inside that, so with the default 300
/// points the graph is 276 points wide and the allocated area reaches 19 points left of it and 33
/// points below it.
const DIALOG_SIDE: f32 = 300.0;
/// The same bare graph as [`graph`], laid out the way the Curves dialog lays it out, with an
/// interior point at input 2, right against the left edge of the graph.
fn curves_dialog_graph(radius: f32) -> Harness<'static, Host> {
let mut h = Harness::builder().with_size(vec2(600.0, 600.0)).build_ui_state(
|ui, host: &mut Host| {
let (full, resp) = ui.allocate_exact_size(vec2(DIALOG_SIDE, DIALOG_SIDE + 14.0), Sense::click_and_drag());
host.graph = Rect::from_min_max(full.min + vec2(19.0, 5.0), full.min + vec2(DIALOG_SIDE - 5.0, DIALOG_SIDE - 19.0));
point_curve::interact_with_hit_radius(ui, &resp, host.graph, &mut host.pts, &mut host.gesture, host.radius);
},
Host { pts: vec![[0.0, 0.0], [2.0, 128.0], [255.0, 255.0]], gesture: PointCurveState::default(), graph: Rect::NOTHING, radius },
);
h.run_steps(2);
h
}
/// Screen position of the level pair `v` in the current host's graph, at that graph's scale.
fn at_scaled(host: &Host, v: [f32; 2]) -> Pos2 {
let g = host.graph;
Pos2::new(g.left() + v[0] / 255.0 * g.width(), g.bottom() - v[1] / 255.0 * g.height())
}
/// A click `d` px right of the middle point.
fn click_right_of_point(h: &mut Harness<'static, Host>, d: f32) {
let pos = at(h.state(), [128.0 + d, 128.0]);
click(h, pos);
}
/// The measured case: at 1 px per level a click 8, 13 or 15 px from a point selects it and adds
/// nothing. The point does not move either: the press keeps the grab offset through the release.
#[test]
fn curves_selects_a_point_clicked_up_to_fifteen_pixels_away() {
for d in [8.0, 13.0, 15.0] {
let mut h = graph(CURVES_HIT_RADIUS);
click_right_of_point(&mut h, d);
let host = h.state();
assert_eq!(host.pts, vec![[0.0, 0.0], [128.0, 128.0], [255.0, 255.0]], "a click {d} px away adds a point next to the existing one");
assert_eq!(host.gesture.selected, Some(1), "a click {d} px away does not select the existing point");
}
}
/// The same 15 px measured diagonally (9 right, 12 up): the radius is a screen disc.
#[test]
fn curves_selects_the_point_across_a_diagonal_click() {
let mut h = graph(CURVES_HIT_RADIUS);
let pos = at(h.state(), [137.0, 140.0]);
click(&mut h, pos);
let host = h.state();
assert_eq!(host.pts, vec![[0.0, 0.0], [128.0, 128.0], [255.0, 255.0]], "the 15 px diagonal click adds a point");
assert_eq!(host.gesture.selected, Some(1), "the 15 px diagonal click does not select the point");
}
/// A click clearly away from every point still adds a point there and selects it.
#[test]
fn curves_still_adds_a_point_clicked_thirty_pixels_away() {
let mut h = graph(CURVES_HIT_RADIUS);
click_right_of_point(&mut h, 30.0);
let host = h.state();
assert_eq!(host.pts, vec![[0.0, 0.0], [128.0, 128.0], [158.0, 128.0], [255.0, 255.0]], "the 30 px click adds no new point");
assert_eq!(host.gesture.selected, Some(2), "the added point is the selected one");
}
/// The radius has to reach the measured 15 px select and stay clear of the 30 px add.
#[test]
fn the_curves_hit_radius_sits_inside_the_measured_window() {
assert!((15.0..30.0).contains(&CURVES_HIT_RADIUS), "the Curves grab radius is {CURVES_HIT_RADIUS} px, outside the measured 15..30 px window");
}
/// The issue lists layer Properties among the hosts that were not measured: the Curves editor
/// there keeps today's radius, only the dialog gets the measured one.
#[test]
fn the_properties_panel_keeps_todays_radius_and_the_dialog_gets_the_curves_radius() {
assert_eq!(point_curve::curves_grab_radius(true), CURVES_HIT_RADIUS);
assert_eq!(point_curve::curves_grab_radius(false), TODAY);
}
/// Not measured in the reference application, so the other hosts keep today's radius exactly: a
/// click 8 or 9 px away grabs the point, one 10 px away still adds a second point.
#[test]
fn the_unmeasured_hosts_keep_todays_nine_pixel_radius() {
for (d, added) in [(8.0, false), (9.0, false), (10.0, true)] {
let mut h = graph(TODAY);
click_right_of_point(&mut h, d);
let host = h.state();
assert_eq!(host.pts.len(), if added { 4 } else { 3 }, "a click {d} px away through the default radius changes the point count");
assert_eq!(host.gesture.selected, Some(if added { 2 } else { 1 }), "a click {d} px away selects the wrong point");
}
}
/// The review case: the Curves graph now grabs 16 points, which reaches past the 12-point band where
/// a drag removes a point. An interior point at input 2 (2.2 points inside the left edge of the
/// 276-point graph), pressed 13 points left of that edge - inside the allocated area, 15.2 points
/// from the point, so the grab radius reaches it - and released without the pointer moving. The
/// press selects the point, so the release must not delete it.
#[test]
fn a_stationary_click_that_grabs_a_point_outside_the_graph_does_not_delete_it() {
let mut h = curves_dialog_graph(CURVES_HIT_RADIUS);
let y = at_scaled(h.state(), [2.0, 128.0]).y;
let pos = Pos2::new(h.state().graph.left() - 13.0, y);
click(&mut h, pos);
let host = h.state();
assert_eq!(host.pts, vec![[0.0, 0.0], [2.0, 128.0], [255.0, 255.0]], "the stationary click outside the graph deleted or moved the point it grabbed");
assert_eq!(host.gesture.selected, Some(1), "the grabbed point is not selected after the release");
}
/// The removal band has to stay where it is for a host that keeps today's 9-point grab radius: a
/// point dragged 13 points past the graph edge still goes. Guard test, green before and after.
#[test]
fn a_nine_pixel_host_still_removes_a_point_dragged_thirteen_points_off_the_graph() {
let mut h = graph(TODAY);
let from = at(h.state(), [128.0, 128.0]);
let to = Pos2::new(h.state().graph.left() - 13.0, from.y);
drag(&mut h, from, to);
let host = h.state();
assert_eq!(host.pts, vec![[0.0, 0.0], [255.0, 255.0]], "the 9 px host stopped removing a point past its 12 point band");
assert_eq!(host.gesture.selected, None, "the removed point is still selected");
}
/// The Curves graph can still remove a point by dragging it off, one point further out: 20 points
/// past the edge is outside the 16-point grab radius. Guard test, green before and after.
#[test]
fn the_curves_graph_still_removes_a_point_dragged_past_its_grab_radius() {
let mut h = curves_dialog_graph(CURVES_HIT_RADIUS);
let from = at_scaled(h.state(), [2.0, 128.0]);
let to = Pos2::new(h.state().graph.left() - 20.0, from.y);
drag(&mut h, from, to);
let host = h.state();
assert_eq!(host.pts, vec![[0.0, 0.0], [255.0, 255.0]], "a point dragged 20 points off the Curves graph is not removed");
assert_eq!(host.gesture.selected, None, "the removed point is still selected");
}
File diff suppressed because it is too large. Load diff
@@ -1,85 +0,0 @@
//! #11793: the Notes panel with no note selected shows an empty, inactive text box with the
//! placeholder "Click a note to view or edit", a blank counter and greyed arrows and trash,
//! and selects no note by itself; the author line is empty for a note without author; the
//! counter reads "N / M"; a note made with a click puts the caret in its text.
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use super::*;
/// A 300 × 200 document with two notes (the second without author) and the Notes panel open,
/// nothing selected; the harness draws the analysis windows.
fn harness() -> Harness<'static, PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
app.run("notes.add", json!({"x": 20, "y": 20, "author": "Ann", "text": "first"})).unwrap();
app.run("notes.add", json!({"x": 120, "y": 80, "author": "", "text": "second"})).unwrap();
app.ui.analysis.notes = true;
app.ui.analysis.note_selected = None;
let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state(
|ui, app: &mut PhotocraftApp| {
if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
return;
}
super::windows(app, ui.ctx());
},
app,
);
PhotocraftApp::setup_context(&h.ctx, Default::default());
h.run_steps(4);
h
}
fn disabled(h: &Harness<'static, PhotocraftApp>, label: &str) -> bool {
h.get_by_label(label).accesskit_node().is_disabled()
}
#[test]
fn the_counter_reads_n_of_m_with_a_slash() {
assert_eq!(note_counter(Some(0), 4), "1 / 4");
assert_eq!(note_counter(Some(3), 4), "4 / 4");
assert_eq!(note_counter(None, 4), "");
assert_eq!(note_counter(Some(5), 4), "", "a stale selection reads as none");
}
#[test]
fn no_selection_stays_empty_with_greyed_controls() {
let h = harness();
assert_eq!(h.state().ui.analysis.note_selected, None, "note 1 isn't selected by itself");
assert!(h.query_by_label("1 / 2").is_none() && h.query_by_label("2 / 2").is_none(), "blank counter");
for label in ["Previous note", "Next note", "Delete note"] {
assert!(disabled(&h, label), "{label} is greyed out");
}
assert!(h.query_by_label("first").is_none(), "no note's text is shown");
}
#[test]
fn a_selected_note_shows_its_counter_and_an_empty_author_line() {
let mut h = harness();
h.state_mut().ui.analysis.note_selected = Some(1);
h.run_steps(3);
assert!(h.query_by_label("2 / 2").is_some());
assert!(h.query_by_label("No author").is_none(), "an empty author stays empty");
assert!(!disabled(&h, "Next note") && !disabled(&h, "Delete note"));
h.state_mut().ui.analysis.note_selected = Some(0);
h.run_steps(3);
assert!(h.query_by_label("1 / 2").is_some());
assert!(h.query_by_label("Ann").is_some(), "the stored author");
}
#[test]
fn a_note_made_with_a_click_takes_the_keyboard() {
let mut h = harness();
h.state_mut().ui.tool = Tool::Note;
crate::canvas::tool_event(h.state_mut(), ToolEvent::Down { x: 200.0, y: 150.0, pressure: 1.0 }, egui::Modifiers::NONE);
crate::canvas::tool_event(h.state_mut(), ToolEvent::Up { x: 200.0, y: 150.0 }, egui::Modifiers::NONE);
h.run_steps(3);
assert_eq!(h.state().ui.analysis.note_selected, Some(2));
assert!(h.ctx.memory(|m| m.focused().is_some()), "the note's text box has the keyboard");
h.event(egui::Event::Text("hello".into()));
h.run_steps(3);
assert_eq!(h.state().session.active().unwrap().doc.notes[2].text, "hello", "typing goes into the new note");
}
-94
View File
@@ -1,94 +0,0 @@
//! Custom widgets for the PhotoCraft look: cards with pill tabs, thin sliders with round knobs,
//! monospace value fields with dimmed units, toggle switches, primary/secondary buttons.
use egui::{Align2, Color32, CornerRadius, Pos2, Rect, Response, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2};
use crate::theme::{self, Tokens};
mod angle_dial;
mod color_count;
pub use angle_dial::{angle_dial_line, angle_dial_row, angle_dial_row_whole_alerting};
pub use color_count::color_count_row;
mod type_ahead;
pub use type_ahead::close_list as close_dropdown_list;
pub use type_ahead::list_open as dropdown_list_open;
mod buttons;
mod color;
mod dropdown;
pub mod field_tab;
pub mod field_wheel;
mod fields;
mod label_column;
pub(super) mod numeric_expression;
mod panel;
pub mod point_curve;
pub mod press_menu;
mod scrub;
mod slider;
pub mod swap_arrow;
pub(super) mod tab_strip;
pub mod task_bar;
mod text_field;
pub mod text_field_menu;
pub mod tone;
mod units;
pub use buttons::{
ButtonRole, DialogButton, button_height, button_width, check_box, check_box_fill, checkbox, compact_button, dialog_buttons, primary_button,
secondary_button, toggle,
};
pub(crate) use color::color_swatch;
pub use color::{
checker, checker_at, checker_rounded, color_edit_button_rgb, color_edit_button_srgb, color_edit_button_srgba, color_swatch_button, hue_color, hue_stops,
pick_pos, rgb_histogram,
};
#[cfg(test)]
use color::{checker_tile_id, checker_uv};
pub use dropdown::{
combo_list, dropdown, dropdown_enabled, dropdown_hovered, dropdown_literal, dropdown_wheel_grouped, dropdown_wheel_grouped_enabled, dropdown_wheel_hovered,
dropdown_with_tooltips, menu_scroll, swatch_popup,
};
pub(crate) use fields::compact_wrapping_value_field;
#[cfg(test)]
use fields::{FieldOpts, NUMERIC_INPUT_LIMIT, value_field_in};
pub use fields::{
POPUP_ARROW_W, PopupFieldResponse, VALUE_FIELD_H, compact_value_field, elided_label, elided_label_sensed, popup_value_field, typed_text_parses,
value_field, value_field_alerting, value_field_alerting_prec, value_field_named, value_field_whole, value_field_whole_alerting, value_field_with_trailing,
};
pub use label_column::{LABEL_COLUMN_GAP, column_label, column_label_padded, label_column_width};
pub(crate) use panel::body_margin;
pub use panel::{
FOOTER_BAR, chevron_icon, drop_line, footer_height, hairline, panel_footer, panel_menu_button, pill_tab, section_label, style_spectrum_popup_menu, surface,
vline,
};
pub(crate) use scrub::scrub_label_within;
pub use scrub::{scrub_label, scrub_option_icon, scrub_option_label};
#[cfg(test)]
use slider::DOUBLE_CLICK_S;
pub(crate) use slider::count_notches;
pub use slider::{RowGestures, row_label, second_click, slider, slider_line, slider_row, slider_row_prec, slider_row_with};
#[cfg(test)]
pub(crate) use slider::{curve_fraction, curve_value};
pub use text_field::{
INPUT_EVENT_LIMIT, TEXT_FIELD_H, TEXT_FIELD_LIMIT, cap_text_events, focus_first_field, text_field, text_field_ex, text_field_with_trailing,
};
pub use units::{
FieldUnits, fmt_num, fmt_num_prec, fmt_num2, parse_num, set_field_resolution, unit_decimals, unit_of_key, value_field_extent, value_field_fixed,
value_field_int, value_field_len, value_field_prec, value_field_prec_blank, value_field_units,
};
#[cfg(test)]
mod tests;
#[cfg(test)]
#[path = "widgets/color_button_tests.rs"]
mod color_button_tests;
#[cfg(test)]
#[path = "widgets/numeric_input_tests.rs"]
mod numeric_input_tests;
#[cfg(test)]
#[path = "widgets/point_curve_hit_radius_tests.rs"]
mod point_curve_hit_radius_tests;
-328
View File
@@ -1,328 +0,0 @@
//! Shared point-curve semantics for Camera Raw, adjustment dialogs and layer Properties.
//! Hosts own typed gesture state and rendering; this module only edits their point data.
use crate::state::{PointCurveDrag, PointCurveState};
use egui::{Key, Modifiers, Pos2, Rect, Response, Ui, pos2};
#[derive(Clone, Copy, Debug, Default)]
pub struct Interaction {
pub changed: bool,
pub commit: bool,
}
/// Grab radius of the hosts the reference application was not measured in, so it stays as it is.
const HIT_RADIUS: f32 = 9.0;
/// Screen pixels a click in the **Curves graph** may sit from an existing point and still select it.
/// The reference application selects a point clicked 8, 13 and 15 px away at 1 px per input level
/// and still adds a point 30 px away, so this has to sit in that window; 16.0 is the smallest clean
/// screen distance above the measured 15, and it is one pixel per level for 16 input levels.
pub const CURVES_HIT_RADIUS: f32 = 16.0;
/// Grab radius of the Curves editor: the measured [`CURVES_HIT_RADIUS`] in the Image > Adjustments
/// dialog; the Properties panel hosts the same editor but was not measured, so it keeps today's.
pub fn curves_grab_radius(in_dialog: bool) -> f32 {
if in_dialog { CURVES_HIT_RADIUS } else { HIT_RADIUS }
}
/// Interior points disappear outside this margin and return on re-entry during the same drag.
const DRAG_OFF: f32 = 12.0;
/// Most points a curve can hold (Photoshop's limit).
pub const MAX_POINTS: usize = 16;
/// Points closer than this (input levels) are the same point.
pub const MIN_GAP: f32 = 2.0;
/// Index of the point nearest `pos` (screen) within `radius` pixels.
pub fn hit(pts: &[[f32; 2]], to_scr: impl Fn([f32; 2]) -> Pos2, pos: Pos2, radius: f32) -> Option<usize> {
pts.iter().enumerate().map(|(i, q)| (i, to_scr(*q).distance(pos))).filter(|(_, d)| *d <= radius).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i)
}
/// Adds a point at `v` (kept sorted). A point already at that input is selected instead; a
/// full curve takes no more points.
pub fn insert(pts: &mut Vec<[f32; 2]>, v: [f32; 2]) -> Option<usize> {
if !v.iter().all(|x| x.is_finite()) {
return None;
}
let v = [v[0].clamp(0.0, 255.0), v[1].clamp(0.0, 255.0)];
if let Some(i) = pts.iter().position(|q| (q[0] - v[0]).abs() < MIN_GAP) {
return Some(i);
}
if pts.len() >= MAX_POINTS {
return None;
}
let i = pts.iter().position(|q| q[0] > v[0]).unwrap_or(pts.len());
pts.insert(i, v);
Some(i)
}
/// Endpoints stay, and a curve keeps at least two points.
pub fn can_delete(pts: &[[f32; 2]], i: usize) -> bool {
pts.len() > 2 && i > 0 && i < pts.len().saturating_sub(1)
}
pub fn delete(pts: &mut Vec<[f32; 2]>, i: usize) -> bool {
if !can_delete(pts, i) {
return false;
}
pts.remove(i);
true
}
/// Moves point `i` to `v`, kept strictly between its neighbours' inputs.
pub fn move_to(pts: &mut [[f32; 2]], i: usize, v: [f32; 2]) -> bool {
let Some(old) = pts.get(i).copied() else { return false };
if !v.iter().chain(old.iter()).all(|x| x.is_finite()) {
return false;
}
let lo = i.checked_sub(1).and_then(|j| pts.get(j)).map_or(0.0, |p| p[0] + 1.0);
let hi = i.checked_add(1).and_then(|j| pts.get(j)).map_or(255.0, |p| p[0] - 1.0);
if !lo.is_finite() || !hi.is_finite() {
return false;
}
let new = [v[0].round().clamp(lo, hi.max(lo)), v[1].round().clamp(0.0, 255.0)];
let changed = new != old;
if let Some(point) = pts.get_mut(i) {
*point = new;
}
changed
}
/// Capture a point at button-down, preserve its grab offset, and keep it through release.
/// `commit` ends a gesture; hosts decide how that becomes document history.
///
/// Uses today's 9 px grab radius, which the hosts the reference application was not measured in
/// keep; the Curves graph asks for its own through [`interact_with_hit_radius`].
pub fn interact(ui: &mut Ui, resp: &Response, graph: Rect, pts: &mut Vec<[f32; 2]>, state: &mut PointCurveState) -> Interaction {
interact_with_hit_radius(ui, resp, graph, pts, state, HIT_RADIUS)
}
/// [`interact`], with the host's grab radius in egui points (screen pixels at scale 1.0): the Curves graph passes
/// [`CURVES_HIT_RADIUS`]; a host the reference application was not measured in passes the 9 px
/// default.
pub fn interact_with_hit_radius(
ui: &mut Ui,
resp: &Response,
graph: Rect,
pts: &mut Vec<[f32; 2]>,
state: &mut PointCurveState,
hit_radius: f32,
) -> Interaction {
// Hosts pass a constant; a hostile value must not leave every point ungrabbable.
let hit_radius = if hit_radius.is_finite() { hit_radius.max(0.0) } else { HIT_RADIUS };
if !graph.is_finite() || graph.width() <= 0.0 || graph.height() <= 0.0 {
*state = PointCurveState::default();
return Interaction::default();
}
state.selected = state.selected.filter(|i| *i < pts.len());
if state.drag.is_some_and(|drag| drag.index.is_some_and(|i| i >= pts.len())) {
state.drag = None;
}
let to_scr = |q: [f32; 2]| pos2(graph.left() + q[0] / 255.0 * graph.width(), graph.bottom() - q[1] / 255.0 * graph.height());
let to_val =
|s: Pos2| [((s.x - graph.left()) / graph.width() * 255.0).clamp(0.0, 255.0), ((graph.bottom() - s.y) / graph.height() * 255.0).clamp(0.0, 255.0)];
let mut e = Interaction::default();
if resp.secondary_clicked()
&& let Some(pos) = resp.interact_pointer_pos()
{
if let Some(i) = hit(pts, to_scr, pos, hit_radius)
&& delete(pts, i)
{
e.changed = true;
e.commit = true;
}
state.selected = None;
state.drag = None;
}
// Press: hit-test where the button went down (not where a drag is first recognised).
let press = (resp.is_pointer_button_down_on() || resp.clicked_by(egui::PointerButton::Primary)) && ui.input(|i| i.pointer.primary_pressed());
// A press and release may arrive in the same native frame; egui then clears press_origin.
// A recognised click still owns its interaction position, so it can select without a drag.
let press_pos =
ui.input(|i| i.pointer.press_origin()).or_else(|| if resp.clicked_by(egui::PointerButton::Primary) { resp.interact_pointer_pos() } else { None });
if press && let Some(pos) = press_pos {
resp.request_focus();
let delete_pressed = ui.input(|i| i.modifiers.command);
match hit(pts, to_scr, pos, hit_radius) {
Some(i) if delete_pressed => {
if delete(pts, i) {
e.changed = true;
e.commit = true;
}
state.selected = None;
state.drag = None;
}
Some(i) => {
state.selected = Some(i);
let g = to_val(pos);
state.drag = pts.get(i).map(|point| PointCurveDrag { index: Some(i), offset: [point[0] - g[0], point[1] - g[1]], removed: false });
}
None if graph.contains(pos) && !delete_pressed => {
let before = pts.len();
state.selected = insert(pts, to_val(pos));
e.changed = pts.len() != before;
state.drag = state.selected.map(|i| PointCurveDrag { index: Some(i), offset: [0.0, 0.0], removed: false });
}
None => state.drag = None,
}
}
// Drag: follow the pointer; off the graph the point is removed (back on, it returns).
if (resp.is_pointer_button_down_on() || ui.input(|i| i.pointer.primary_released()))
&& !press
&& let (Some(PointCurveDrag { index, offset: off, removed }), Some(pos)) = (state.drag, ui.input(|i| i.pointer.interact_pos()))
{
// A press grabs a point up to `hit_radius` away, which can be that far outside the graph,
// so the band where a drag removes a point must never sit inside the band where a press
// still selects one: it is at least the host's active grab radius.
let outside = !graph.expand(DRAG_OFF.max(hit_radius)).contains(pos);
let g = to_val(pos);
let target = [g[0] + off[0], g[1] + off[1]];
match index {
Some(i) if outside && can_delete(pts, i) => {
delete(pts, i);
state.drag = Some(PointCurveDrag { index: None, offset: off, removed: true });
state.selected = None;
e.changed = true;
}
Some(i) => e.changed |= move_to(pts, i, target),
None if removed && !outside => {
state.selected = insert(pts, target);
state.drag = Some(PointCurveDrag { index: state.selected, offset: off, removed: true });
e.changed |= state.selected.is_some();
}
None => {}
}
}
if state.drag.is_some() && !resp.is_pointer_button_down_on() {
state.drag = None;
e.commit = true;
}
// Arrows edit this graph rather than navigating to another widget on the next frame.
ui.memory_mut(|m| m.set_focus_lock_filter(resp.id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }));
// Keys while the graph has focus: Delete/Backspace removes, arrows nudge (Shift: ×10).
if resp.has_focus() {
crate::shortcut_dispatch::claim_delete_keys(ui.ctx(), resp.id);
}
if resp.has_focus()
&& let Some(i) = state.selected.filter(|i| *i < pts.len())
{
let del = ui.input_mut(|inp| inp.consume_key(Modifiers::NONE, Key::Delete) || inp.consume_key(Modifiers::NONE, Key::Backspace));
if del && delete(pts, i) {
state.selected = None;
e.changed = true;
e.commit = true;
} else {
let step = if ui.input(|inp| inp.modifiers.shift) { 10.0 } else { 1.0 };
let mut d = [0.0f32; 2];
for (k, dx, dy) in [(Key::ArrowLeft, -1.0, 0.0), (Key::ArrowRight, 1.0, 0.0), (Key::ArrowUp, 0.0, 1.0), (Key::ArrowDown, 0.0, -1.0)] {
if ui.input_mut(|inp| inp.consume_key(Modifiers::NONE, k) || inp.consume_key(Modifiers::SHIFT, k)) {
d = [d[0] + dx * step, d[1] + dy * step];
}
}
let Some(point) = pts.get(i) else { return e };
let to = [point[0] + d[0], point[1] + d[1]];
if d != [0.0, 0.0] && move_to(pts, i, to) {
e.changed = true;
e.commit = true;
}
}
}
e
}
/// Curves' pencil: draws a straight stroke from `from` to `to` ([input, output] levels, 0..255)
/// into a pencil-drawn map (one output level per input level), so a fast drag leaves no gaps.
pub fn pencil_line(map: &mut [f32], from: [f32; 2], to: [f32; 2]) -> bool {
if !from.iter().chain(to.iter()).all(|x| x.is_finite()) || map.is_empty() {
return false;
}
let last = (map.len() - 1) as f32;
let level = |x: f32| x.clamp(0.0, 255.0) / 255.0 * last;
let (a, b) = if from[0] <= to[0] { (from, to) } else { (to, from) };
let (i0, i1) = (level(a[0]).round() as usize, level(b[0]).round() as usize);
let mut changed = false;
for i in i0..=i1 {
let t = if i1 > i0 { (i - i0) as f32 / (i1 - i0) as f32 } else { 1.0 };
let o = (a[1] + (b[1] - a[1]) * t).clamp(0.0, 255.0);
if let Some(slot) = map.get_mut(i)
&& *slot != o
{
*slot = o;
changed = true;
}
}
changed
}
#[cfg(test)]
mod tests {
use super::*;
fn line() -> Vec<[f32; 2]> {
vec![[0.0, 0.0], [255.0, 255.0]]
}
#[test]
fn insert_keeps_order_dedupes_and_respects_the_limit() {
let mut p = line();
assert_eq!(insert(&mut p, [128.0, 150.0]), Some(1));
assert_eq!(insert(&mut p, [64.0, 40.0]), Some(1));
assert_eq!(p, vec![[0.0, 0.0], [64.0, 40.0], [128.0, 150.0], [255.0, 255.0]]);
// A click on an existing input selects that point instead of stacking a second one.
assert_eq!(insert(&mut p, [129.0, 10.0]), Some(2));
assert_eq!(p.len(), 4);
let mut full: Vec<[f32; 2]> = (0..MAX_POINTS).map(|i| [i as f32 * 10.0, 0.0]).collect();
assert_eq!(insert(&mut full, [255.0, 0.0]), None);
assert_eq!(insert(&mut p, [-50.0, 900.0]), Some(0), "clamped onto the black point");
}
#[test]
fn endpoints_and_the_last_two_points_stay() {
let mut p = vec![[0.0, 0.0], [100.0, 120.0], [255.0, 255.0]];
assert!(!delete(&mut p, 0) && !delete(&mut p, 2) && !delete(&mut p, 7));
assert!(delete(&mut p, 1));
assert_eq!(p, line());
assert!(!delete(&mut p, 1) && !delete(&mut p, 0));
assert_eq!(p.len(), 2);
}
#[test]
fn moves_stay_between_neighbours() {
let mut p = vec![[0.0, 0.0], [100.0, 120.0], [200.0, 180.0], [255.0, 255.0]];
assert!(move_to(&mut p, 1, [250.0, 300.0]));
assert_eq!(p[1], [199.0, 255.0]);
move_to(&mut p, 0, [150.0, 10.0]);
assert_eq!(p[0], [150.0, 10.0]);
move_to(&mut p, 3, [10.0, 5.0]);
assert_eq!(p[3], [201.0, 5.0]);
assert!(!move_to(&mut p, 9, [0.0, 0.0]));
}
#[test]
fn pencil_strokes_fill_every_level_they_cross() {
let mut map: Vec<f32> = (0..256).map(|k| k as f32).collect();
assert!(pencil_line(&mut map, [200.0, 10.0], [100.0, 210.0]));
assert_eq!((map[100], map[150], map[200]), (210.0, 110.0, 10.0));
assert_eq!((map[99], map[201]), (99.0, 201.0));
assert!(!pencil_line(&mut map, [f32::NAN, 0.0], [5.0, 5.0]));
assert!(pencil_line(&mut map, [-50.0, 900.0], [-40.0, 900.0]));
assert_eq!(map[0], 255.0);
}
#[test]
fn hit_test_picks_the_nearest_point_in_radius() {
let p = vec![[0.0, 0.0], [100.0, 100.0], [110.0, 110.0], [255.0, 255.0]];
let to_scr = |q: [f32; 2]| Pos2::new(q[0], 255.0 - q[1]);
assert_eq!(hit(&p, to_scr, Pos2::new(108.0, 146.0), 9.0), Some(2));
assert_eq!(hit(&p, to_scr, Pos2::new(50.0, 50.0), 9.0), None);
}
#[test]
fn hostile_points_and_indices_cannot_panic_or_pollute_a_curve() {
let mut p = line();
for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
assert_eq!(insert(&mut p, [bad, 128.0]), None);
assert!(!move_to(&mut p, 0, [128.0, bad]));
}
assert!(!can_delete(&p, usize::MAX));
assert!(!delete(&mut p, usize::MAX));
assert!(!move_to(&mut p, usize::MAX, [128.0, 128.0]));
assert_eq!(p, line());
}
}
+1 -1
View File
@@ -191,7 +191,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu
| TOOL-214-5 | Right-click menu during Free Transform (scale, rotate, skew, warp, flip, rotate 90/180) | done | [#214](https://github.com/storytold/photocraft/issues/214) | canvas_tool_menu.rs TRANSFORM_MENU: modes, Content-Aware Scale / Puppet Warp greyed, Rotate 180 / 90 CW / 90 CCW and Flip turn the open box (transform_tool::intercept, #2832) |
| TOOL-214-6 | Puppet Warp mesh follows the object outline (constrained triangulation) | done | [#214](https://github.com/storytold/photocraft/issues/214) | algo/puppet.rs build_mesh: traced outline of the opaque region grown by Expansion, triangulated with a Density-spaced lattice (conforming Delaunay); separate shapes get separate meshes (#3105) |
| TOOL-214-7 | Content-Aware Scale through the Free Transform box with a live proxy preview | done | [#214](https://github.com/storytold/photocraft/issues/214) | Edit > Content-Aware Scale opens a scale-only Free Transform box (cas_transform.rs) with Amount, Protect and Protect Skin Tones in the options bar; edit.contentAwareScale carves a 384 px copy in the background for the live preview, and Enter runs it with the box's size and x/y as one step (#3096) |
| TOOL-214-8 | A measured ruler angle prefills Image Rotation > Arbitrary (0.01 deg) | done | [#214](https://github.com/storytold/photocraft/issues/214) | analysis_ui.rs: image.rotation.arbitrary opens seeded with the ruler angle and the direction that straightens it; arbitrary_rotation_starts_at_the_ruler_angle checks 5.7106 deg within 1e-3 and cw/ccw for three measured lines |
| TOOL-214-8 | A measured ruler angle prefills Image Rotation > Arbitrary (0.01 deg) | done | [#214](https://github.com/storytold/photocraft/issues/214) | tools/analysis: image.rotation.arbitrary opens seeded with the ruler angle and the direction that straightens it; arbitrary_rotation_starts_at_the_ruler_angle checks 5.7106 deg within 1e-3 and cw/ccw for three measured lines |
| TOOL-214-9 | Crop: W x H x Resolution with units, saved crop presets, Straighten in the options bar | done | [#214](https://github.com/storytold/photocraft/issues/214) | Ratio dropdown and fields, Straighten (TOOL-214-21); W x H x Resolution with units, built-in size presets and Front Image (crop_size.rs, image.crop targetWidth/targetHeight/resolution, #2443); New / Delete Crop Preset save and delete crop tool presets (crop_presets.rs, tool.presets.* with tool crop, persisted with the preferences) |
| TOOL-214-10 | Pen: Alt breaks a handle, Shift 45 deg, Ctrl direct-selects, Backspace, close-drag handle | done | [#214](https://github.com/storytold/photocraft/issues/214) | Ctrl/Cmd = Direct Selection and Alt = Convert Point on existing paths (direct_select.rs, #790); Backspace/Delete retracts the last point while drawing (#1466); Alt during a drag breaks the handle pair, Alt-drag turns the last anchor's outgoing handle alone, and dragging on the first anchor closes with that anchor's handles (vector_ui.rs, #3306); Shift-click puts the next anchor on the nearest 45 deg ray from the previous one and Shift-drag turns the handles to 45 deg steps, live (vector_ui.rs pen_shift_click_puts_the_next_anchor_on_a_45_degree_ray, pen_shift_drag_turns_handles_to_45_degrees_live, #3751) |
| TOOL-214-11 | Stroke Path dialog: pick any brush-based tool, Simulate Pressure | done | [#214](https://github.com/storytold/photocraft/issues/214) | path.stroke tool: Brush, Pencil, Eraser and every other brush-based tool (Background Eraser, Clone/Pattern Stamp, Healing/Spot Healing Brush, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Color Replacement, Mixer Brush: their paint.* command along the path, one step) plus simulatePressure (taper both ends); Stroke Path dialog from the Pen menu, the Paths panel menu and Alt-click on its Stroke button (#2978) |
+1 -1
View File
@@ -164,7 +164,7 @@ id = "TOOL-214-8"
target = "A measured ruler angle prefills Image Rotation > Arbitrary (0.01 deg)"
status = "done"
issue = 214
note = "analysis_ui.rs: image.rotation.arbitrary opens seeded with the ruler angle and the direction that straightens it; arbitrary_rotation_starts_at_the_ruler_angle checks 5.7106 deg within 1e-3 and cw/ccw for three measured lines"
note = "tools/analysis: image.rotation.arbitrary opens seeded with the ruler angle and the direction that straightens it; arbitrary_rotation_starts_at_the_ruler_angle checks 5.7106 deg within 1e-3 and cw/ccw for three measured lines"
[[item]]
id = "TOOL-214-9"