mirror of
https://github.com/storytold/photocraft.git
synced 2026-11-21 17:37:14 +00:00
Merge remote-tracking branch 'origin/main' into fix/psd-size-encoded
This commit is contained in:
commit
f754b7e7ea
14 files changed
+451
-24
No files matched your search
@@ -79,23 +79,48 @@ fn mirror(i: isize, n: usize) -> usize {
|
||||
|
||||
const TAPS: [f32; 5] = [1.0 / 16.0, 4.0 / 16.0, 6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0];
|
||||
|
||||
/// Planes smaller than this run their rows on one thread: the filter builds a whole pyramid per
|
||||
/// reference (up to 96), and splitting its small levels into one-row tasks cost more in rayon's
|
||||
/// scheduling than the rows themselves (a fifth of a Shadows render on 36 MP, measured).
|
||||
const PAR_MIN: usize = 1 << 15;
|
||||
|
||||
/// [`par_rows`] for a plane, on one thread when it is small (see [`PAR_MIN`]).
|
||||
fn rows(buf: &mut [f32], w: usize, f: impl Fn(usize, &mut [f32]) + Sync + Send) {
|
||||
if buf.len() < PAR_MIN {
|
||||
buf.chunks_mut(w.max(1)).enumerate().for_each(|(y, row)| f(y, row));
|
||||
} else {
|
||||
par_rows(buf, w, 1, f);
|
||||
}
|
||||
}
|
||||
|
||||
/// The binomial 5-tap blur, sampled every `step` pixels from 0 (1 = full resolution).
|
||||
fn blur_step(p: &Plane, step: usize) -> Plane {
|
||||
let (w2, h2) = (p.w.div_ceil(step), p.h.div_ceil(step));
|
||||
// Columns first at the kept rows, then rows at the kept columns.
|
||||
// Columns first at the kept rows, then rows at the kept columns. Each sum adds the same terms
|
||||
// in the same order as a `mirror` per tap would, so the result is bit for bit the same; the
|
||||
// source rows are found once per row and the columns mirrored only near the edges.
|
||||
let mut tmp = vec![0.0f32; p.w * h2];
|
||||
par_rows(&mut tmp, p.w, 1, |y2, row| {
|
||||
rows(&mut tmp, p.w, |y2, row| {
|
||||
let y = (y2 * step) as isize;
|
||||
let src: [&[f32]; 5] = std::array::from_fn(|k| {
|
||||
let r = mirror(y + k as isize - 2, p.h);
|
||||
&p.v[r * p.w..(r + 1) * p.w]
|
||||
});
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
*o = (0..5).map(|k| TAPS[k] * p.v[mirror(y + k as isize - 2, p.h) * p.w + x]).sum();
|
||||
*o = (0..5).map(|k| TAPS[k] * src[k][x]).sum();
|
||||
}
|
||||
});
|
||||
let mut out = vec![0.0f32; w2 * h2];
|
||||
par_rows(&mut out, w2, 1, |y2, row| {
|
||||
rows(&mut out, w2, |y2, row| {
|
||||
let src = &tmp[y2 * p.w..(y2 + 1) * p.w];
|
||||
for (x2, o) in row.iter_mut().enumerate() {
|
||||
let x = (x2 * step) as isize;
|
||||
*o = (0..5).map(|k| TAPS[k] * src[mirror(x + k as isize - 2, p.w)]).sum();
|
||||
let x = x2 * step;
|
||||
*o = if x >= 2 && x + 2 < p.w {
|
||||
let s = &src[x - 2..x + 3];
|
||||
(0..5).map(|k| TAPS[k] * s[k]).sum()
|
||||
} else {
|
||||
(0..5).map(|k| TAPS[k] * src[mirror(x as isize + k as isize - 2, p.w)]).sum()
|
||||
};
|
||||
}
|
||||
});
|
||||
Plane { w: w2, h: h2, v: out }
|
||||
@@ -107,14 +132,45 @@ fn down(p: &Plane) -> Plane {
|
||||
}
|
||||
|
||||
/// `p` brought up to `w × h`: zeros between samples, then the blur times four.
|
||||
///
|
||||
/// Three samples in four are zero, so their taps are skipped instead of blurring a zero-filled
|
||||
/// plane: the nonzero terms are added in the same order (skipping `+0.0` terms changes at most the
|
||||
/// sign of a zero, and the filter only adds and exponentiates these values).
|
||||
fn up(p: &Plane, w: usize, h: usize) -> Plane {
|
||||
let mut z = Plane { w, h, v: vec![0.0; w * h] };
|
||||
for y in 0..p.h.min(h.div_ceil(2)) {
|
||||
for x in 0..p.w.min(w.div_ceil(2)) {
|
||||
z.v[2 * y * w + 2 * x] = p.v[y * p.w + x] * 4.0;
|
||||
}
|
||||
let (lh, lw) = (p.h.min(h.div_ceil(2)), p.w.min(w.div_ceil(2)));
|
||||
// The source sample behind index `i` of a zero-stuffed axis of length `n` holding `lim` samples.
|
||||
let src = |i: isize, n: usize, lim: usize| {
|
||||
let m = mirror(i, n);
|
||||
(m.is_multiple_of(2) && m / 2 < lim).then_some(m / 2)
|
||||
};
|
||||
// Columns first, only at the even columns (the odd ones are all zero).
|
||||
let mut tmp = vec![0.0f32; lw * h];
|
||||
if lw > 0 {
|
||||
rows(&mut tmp, lw, |y, row| {
|
||||
let taps: [Option<&[f32]>; 5] = std::array::from_fn(|k| src(y as isize + k as isize - 2, h, lh).map(|r| &p.v[r * p.w..r * p.w + lw]));
|
||||
for (j, o) in row.iter_mut().enumerate() {
|
||||
*o = (0..5).filter_map(|k| taps[k].map(|s| TAPS[k] * (s[j] * 4.0))).sum();
|
||||
}
|
||||
});
|
||||
}
|
||||
blur_step(&z, 1)
|
||||
let mut out = vec![0.0f32; w * h];
|
||||
rows(&mut out, w, |y, row| {
|
||||
let t = &tmp[y * lw..(y + 1) * lw];
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
*o = if x >= 2 && x + 2 < w {
|
||||
// Away from the edges no tap mirrors.
|
||||
(0..5)
|
||||
.filter_map(|k| {
|
||||
let i = x + k - 2;
|
||||
(i.is_multiple_of(2) && i / 2 < lw).then(|| TAPS[k] * t[i / 2])
|
||||
})
|
||||
.sum()
|
||||
} else {
|
||||
(0..5).filter_map(|k| src(x as isize + k as isize - 2, w, lw).map(|j| TAPS[k] * t[j])).sum()
|
||||
};
|
||||
}
|
||||
});
|
||||
Plane { w, h, v: out }
|
||||
}
|
||||
|
||||
/// Levels down to about 2 pixels on the short side.
|
||||
@@ -154,7 +210,7 @@ fn llf(u: &Plane, remap: impl Fn(f32, f32) -> f32 + Sync) -> Plane {
|
||||
for k in 0..refs {
|
||||
let r = lo + step * k as f32;
|
||||
let mut m = Plane { w: u.w, h: u.h, v: u.v.clone() };
|
||||
par_rows(&mut m.v, u.w, 1, |_, row| {
|
||||
rows(&mut m.v, u.w, |_, row| {
|
||||
for v in row.iter_mut() {
|
||||
*v = remap(*v, r);
|
||||
}
|
||||
@@ -163,7 +219,7 @@ fn llf(u: &Plane, remap: impl Fn(f32, f32) -> f32 + Sync) -> Plane {
|
||||
for l in 0..n - 1 {
|
||||
let coarse = up(&gr[l + 1], gr[l].w, gr[l].h);
|
||||
let (gl, fine, lw) = (&g[l].v, &gr[l].v, g[l].w);
|
||||
par_rows(&mut lap[l], lw, 1, |y, row| {
|
||||
rows(&mut lap[l], lw, |y, row| {
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
let i = y * lw + x;
|
||||
let wgt = (1.0 - (gl[i].clamp(lo, hi) - r).abs() / step).max(0.0);
|
||||
@@ -337,6 +393,62 @@ mod tests {
|
||||
|
||||
const SRGB: Encoding = Encoding(0.0);
|
||||
|
||||
/// The plain blur: a `mirror` per tap over the whole plane, the reference for [`blur_step`].
|
||||
fn blur_step_reference(p: &Plane, step: usize) -> Plane {
|
||||
let (w2, h2) = (p.w.div_ceil(step), p.h.div_ceil(step));
|
||||
let mut tmp = vec![0.0f32; p.w * h2];
|
||||
for y2 in 0..h2 {
|
||||
for x in 0..p.w {
|
||||
tmp[y2 * p.w + x] = (0..5).map(|k| TAPS[k] * p.v[mirror((y2 * step) as isize + k as isize - 2, p.h) * p.w + x]).sum();
|
||||
}
|
||||
}
|
||||
let mut out = vec![0.0f32; w2 * h2];
|
||||
for y2 in 0..h2 {
|
||||
for x2 in 0..w2 {
|
||||
out[y2 * w2 + x2] = (0..5).map(|k| TAPS[k] * tmp[y2 * p.w + mirror((x2 * step) as isize + k as isize - 2, p.w)]).sum();
|
||||
}
|
||||
}
|
||||
Plane { w: w2, h: h2, v: out }
|
||||
}
|
||||
|
||||
/// The plain upsampling: a zero-stuffed plane blurred whole, the reference for [`up`].
|
||||
fn up_reference(p: &Plane, w: usize, h: usize) -> Plane {
|
||||
let mut z = Plane { w, h, v: vec![0.0; w * h] };
|
||||
for y in 0..p.h.min(h.div_ceil(2)) {
|
||||
for x in 0..p.w.min(w.div_ceil(2)) {
|
||||
z.v[2 * y * w + 2 * x] = p.v[y * p.w + x] * 4.0;
|
||||
}
|
||||
}
|
||||
blur_step_reference(&z, 1)
|
||||
}
|
||||
|
||||
fn noise_plane(w: usize, h: usize, seed: u32) -> Plane {
|
||||
let mut s = seed.wrapping_mul(2_654_435_761).max(1);
|
||||
let v = (0..w * h)
|
||||
.map(|_| {
|
||||
s ^= s << 13;
|
||||
s ^= s >> 17;
|
||||
s ^= s << 5;
|
||||
(s % 20_000) as f32 / 1000.0 - 16.0
|
||||
})
|
||||
.collect();
|
||||
Plane { w, h, v }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fast_pyramid_matches_the_plain_one_exactly() {
|
||||
// Odd, even, tiny and large-enough-to-run-in-parallel sizes, as the pyramid's levels are.
|
||||
for (i, (w, h)) in [(1, 1), (1, 7), (2, 2), (3, 5), (5, 3), (8, 6), (37, 23), (64, 64), (301, 211)].into_iter().enumerate() {
|
||||
let p = noise_plane(w, h, i as u32 + 1);
|
||||
for step in [1, 2] {
|
||||
assert_eq!(blur_step(&p, step).v, blur_step_reference(&p, step).v, "blur {w}×{h} step {step}");
|
||||
}
|
||||
for (uw, uh) in [(w * 2, h * 2), (w * 2 - 1, h * 2 - 1), (w * 2, h * 2 - 1), (w.max(2) * 2 - 3, h * 2)] {
|
||||
assert_eq!(up(&p, uw, uh).v, up_reference(&p, uw, uh).v, "up {w}×{h} → {uw}×{uh}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn grey(w: usize, h: usize, f: impl Fn(usize, usize) -> f32) -> Vec<[f32; 4]> {
|
||||
(0..w * h).map(|i| f(i % w, i / w)).map(|v| [v, v, v, 1.0]).collect()
|
||||
}
|
||||
|
||||
@@ -66,6 +66,21 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// PAM ends its header with an LF-terminated line, unlike P4–P6's single separator.
|
||||
fn pam_endhdr(&mut self) -> Result<(), CodecError> {
|
||||
while let Some(&c) = self.b.get(self.pos) {
|
||||
self.pos += 1;
|
||||
if c == b'\n' {
|
||||
// Stop at the first LF: whitespace and '#' after it are raster bytes.
|
||||
return Ok(());
|
||||
}
|
||||
if !c.is_ascii_whitespace() {
|
||||
return Err(err("unexpected data after PAM ENDHDR"));
|
||||
}
|
||||
}
|
||||
Err(err("unterminated PAM ENDHDR line"))
|
||||
}
|
||||
|
||||
fn rest(&self) -> &'a [u8] {
|
||||
&self.b[self.pos.min(self.b.len())..]
|
||||
}
|
||||
@@ -269,7 +284,7 @@ fn decode_pam(r: &mut Reader<'_>, limits: &Limits) -> Result<Image, CodecError>
|
||||
_ => return Err(err("unknown PAM header field")),
|
||||
}
|
||||
}
|
||||
r.single_ws()?;
|
||||
r.pam_endhdr()?;
|
||||
let (w, h, depth, maxval) = match (w, h, depth, maxval) {
|
||||
(Some(a), Some(b), Some(c), Some(d)) => (a, b, c, d),
|
||||
_ => return Err(err("incomplete PAM header")),
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
use photocraft_codecs::{ChannelLayout, CodecError, Format, SampleType, decode, decode_as};
|
||||
|
||||
const PAM_GRAY: &[u8] = b"P7\nWIDTH 1\nHEIGHT 1\nDEPTH 1\nMAXVAL 255\nENDHDR";
|
||||
const ENDINGS: &[&[u8]] = &[b"\n", b" \n", b"\t \n", b"\r\n", b" \t\r\n"];
|
||||
|
||||
#[test]
|
||||
fn pam_consumes_the_complete_endhdr_line() {
|
||||
for ending in ENDINGS {
|
||||
let mut bytes = PAM_GRAY.to_vec();
|
||||
bytes.extend_from_slice(ending);
|
||||
bytes.push(0x80);
|
||||
let img = decode(&bytes).unwrap();
|
||||
assert_eq!(img.dimensions(), (1, 1));
|
||||
assert_eq!(img.layout(), ChannelLayout::Gray);
|
||||
assert_eq!(img.data(), &[0x80], "ENDHDR ending {ending:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pam_preserves_every_possible_first_raster_byte() {
|
||||
// In particular, LF, CR, space, tab and '#' must not be skipped as header syntax.
|
||||
for ending in ENDINGS {
|
||||
for first in 0..=255u8 {
|
||||
let mut bytes = PAM_GRAY.to_vec();
|
||||
bytes.extend_from_slice(ending);
|
||||
bytes.push(first);
|
||||
assert_eq!(decode(&bytes).unwrap().data(), &[first], "ENDHDR ending {ending:?}, raster byte {first}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pam_crlf_header_preserves_u16_samples_and_alpha() {
|
||||
for ending in ENDINGS {
|
||||
let mut bytes = b"P7\r\nWIDTH 1\r\nHEIGHT 1\r\nDEPTH 2\r\nMAXVAL 65535\r\nTUPLTYPE GRAYSCALE_ALPHA\r\nENDHDR".to_vec();
|
||||
bytes.extend_from_slice(ending);
|
||||
bytes.extend_from_slice(b" \n#\r");
|
||||
let img = decode(&bytes).unwrap();
|
||||
assert_eq!(img.layout(), ChannelLayout::GrayA);
|
||||
assert_eq!(img.sample_type(), SampleType::U16);
|
||||
assert_eq!(img.to_u16_samples().unwrap(), vec![0x200a, 0x230d], "ENDHDR ending {ending:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pam_rejects_unterminated_or_invalid_endhdr_lines() {
|
||||
for suffix in [b"".as_slice(), b" ", b"\r", b" \t\r", b" \x80", b" \x80\n\x7f", b"#comment\n\x7f"] {
|
||||
let mut bytes = PAM_GRAY.to_vec();
|
||||
bytes.extend_from_slice(suffix);
|
||||
assert!(matches!(decode_as(Format::Pnm, &bytes), Err(CodecError::Malformed { .. })), "ENDHDR suffix {suffix:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pam_truncation_never_uses_header_whitespace_as_pixels() {
|
||||
for ending in ENDINGS {
|
||||
let mut bytes = PAM_GRAY.to_vec();
|
||||
bytes.extend_from_slice(ending);
|
||||
bytes.push(0x80);
|
||||
for cut in 0..bytes.len() {
|
||||
assert!(decode_as(Format::Pnm, &bytes[..cut]).is_err(), "ENDHDR ending {ending:?}, truncated at {cut}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_pnm_keeps_its_single_whitespace_separator() {
|
||||
for separator in *b" \t\r\n" {
|
||||
for first in *b" \t\r\n#" {
|
||||
for (header, channels) in [(b"P5\n1 1\n255".as_slice(), 1), (b"P6\n1 1\n255", 3)] {
|
||||
let mut bytes = header.to_vec();
|
||||
bytes.push(separator);
|
||||
bytes.extend(std::iter::repeat_n(first, channels));
|
||||
assert_eq!(decode(&bytes).unwrap().data(), vec![first; channels]);
|
||||
}
|
||||
let mut bytes = b"P4\n8 1".to_vec();
|
||||
bytes.extend_from_slice(&[separator, first]);
|
||||
let expected: Vec<u8> = (0..8).map(|bit| if first & (0x80 >> bit) == 0 { 255 } else { 0 }).collect();
|
||||
assert_eq!(decode(&bytes).unwrap().data(), expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -586,6 +586,12 @@ impl Layouter {
|
||||
for p in style_props(&out.styles[si0], k, &fallback, si0 as u32, small_caps[si0]) {
|
||||
b.push_default(p);
|
||||
}
|
||||
// Paragraph text breaks a word wider than the box at the box edge, as Photoshop
|
||||
// does (#6694): parley's default only breaks at UAX #14 opportunities and lets the
|
||||
// word run out of the box. Point text has no width to overflow.
|
||||
if is_box {
|
||||
b.push_default(StyleProperty::OverflowWrap(parley::style::OverflowWrap::BreakWord));
|
||||
}
|
||||
for (ri, st) in out.styles.iter().enumerate() {
|
||||
let rs = run_starts[ri];
|
||||
let (a, z) = (rs.max(prange.start), (rs + runs[ri].len).min(content_end));
|
||||
|
||||
@@ -2008,3 +2008,37 @@ fn hyphenless_postscript_names_split_trailing_styles() {
|
||||
assert_eq!((r.family.as_str(), r.weight, r.italic), (family, weight, italic), "{ps}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A word wider than its paragraph box wraps at the box edge instead of running past it (#6694);
|
||||
/// a normal break opportunity still wins, and a box that fits the word lays out exactly as before.
|
||||
#[test]
|
||||
fn a_word_wider_than_the_paragraph_box_breaks_at_the_box_edge() {
|
||||
let mut e = TextEngine::new();
|
||||
let word = "BLOQUEADO?!";
|
||||
let alone = e.layout(&point(word, 12.0), 72.0);
|
||||
assert_eq!(alone.lines.len(), 1, "{:?}", alone.lines);
|
||||
let word_width = width(&alone);
|
||||
let narrow = 30.0;
|
||||
assert!(word_width > narrow * 2.0, "{word_width}");
|
||||
|
||||
let mut t = point(word, 12.0);
|
||||
t.shape = TextShape::Box { x: 0.0, y: 0.0, width: narrow, height: 200.0 };
|
||||
let l = e.layout(&t, 72.0);
|
||||
assert!(l.lines.len() >= 2, "{:?}", l.lines);
|
||||
for line in &l.lines {
|
||||
assert!(line.x1 <= narrow + 0.5, "{line:?}");
|
||||
}
|
||||
let joined: String = l.lines.iter().map(|l| &word[l.range.clone()]).collect();
|
||||
assert_eq!(joined, word);
|
||||
|
||||
t.shape = TextShape::Box { x: 0.0, y: 0.0, width: word_width + 20.0, height: 200.0 };
|
||||
let fits = e.layout(&t, 72.0);
|
||||
assert_eq!(fits.lines.len(), 1, "{:?}", fits.lines);
|
||||
assert!((width(&fits) - word_width).abs() < 0.01, "{} vs {word_width}", width(&fits));
|
||||
|
||||
let mut spaced = point("ab cd", 12.0);
|
||||
spaced.shape = TextShape::Box { x: 0.0, y: 0.0, width: narrow, height: 200.0 };
|
||||
let l = e.layout(&spaced, 72.0);
|
||||
assert_eq!(l.lines.len(), 2, "{:?}", l.lines);
|
||||
assert_eq!(l.lines[1].range.start, 3, "{:?}", l.lines);
|
||||
}
|
||||
@@ -4091,6 +4091,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
if primary && hand_pan && response.dragged() {
|
||||
crate::transform_tool::draw_content(app, &painter, &xf);
|
||||
crate::transform_tool::draw_overlay(app, &painter, &xf);
|
||||
// The Pen's path in progress survives a Space pan, and stays on screen through it (#6592).
|
||||
crate::vector_ui::draw_overlay(app, &painter, &xf, &doc);
|
||||
}
|
||||
app.tool_override = None;
|
||||
if let Some(b) = layer_edges_rect(app, idx) {
|
||||
|
||||
@@ -109,7 +109,7 @@ pub fn savable(o: &ToolOptions) -> Option<(Map<String, Value>, String)> {
|
||||
if !(a.is_finite() && b.is_finite() && a > 0.0 && b > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let name = format!("{} : {}", crate::widgets::fmt_num(a), crate::widgets::fmt_num(b));
|
||||
let name = format!("{} : {}", crop_size::fmt_ratio(a), crop_size::fmt_ratio(b));
|
||||
let mut fields = Map::new();
|
||||
fields.insert("crop_ratio".into(), json!(o.crop_ratio));
|
||||
Some((fields, name))
|
||||
|
||||
@@ -146,6 +146,14 @@ pub fn ratio(o: &ToolOptions, doc_dpi: f64) -> Option<f64> {
|
||||
Some(w / h).filter(|k| k.is_finite() && *k > 0.0)
|
||||
}
|
||||
|
||||
/// Decimals a custom ratio side keeps and shows: 1.414 : 1 (ISO A sizes) as in Photoshop (#6487).
|
||||
pub const RATIO_DECIMALS: u32 = 3;
|
||||
|
||||
/// A ratio side as stored in a `crop_ratio` key ("1.414", "16").
|
||||
pub fn fmt_ratio(v: f64) -> String {
|
||||
crate::widgets::fmt_num_prec(v, RATIO_DECIMALS)
|
||||
}
|
||||
|
||||
/// Editable W and H shown for a custom aspect ratio. An existing valid ratio is authoritative;
|
||||
/// when either side is zero, use the in-progress values retained in ToolOptions.
|
||||
pub fn custom_ratio_fields(o: &ToolOptions, doc_size: (f64, f64)) -> (f32, f32) {
|
||||
@@ -170,7 +178,7 @@ pub fn set_custom_ratio_fields(o: &mut ToolOptions, width: f32, height: f32) {
|
||||
o.crop_custom_ratio_width = width;
|
||||
o.crop_custom_ratio_height = height;
|
||||
if width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0 {
|
||||
o.crop_ratio = format!("{}:{}", crate::widgets::fmt_num(f64::from(width)), crate::widgets::fmt_num(f64::from(height)));
|
||||
o.crop_ratio = format!("{}:{}", fmt_ratio(f64::from(width)), fmt_ratio(f64::from(height)));
|
||||
} else {
|
||||
o.crop_ratio.clear();
|
||||
}
|
||||
@@ -347,6 +355,15 @@ mod tests {
|
||||
assert_eq!(width / height, 4.0 / 3.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_ratio_keeps_three_decimals() {
|
||||
// #6487: 1.414 : 1 (ISO A sizes) stays 1.414, not 1.4, as in Photoshop.
|
||||
let mut options = ToolOptions::default();
|
||||
set_custom_ratio_fields(&mut options, 1.414, 1.0);
|
||||
assert_eq!(options.crop_ratio, "1.414:1");
|
||||
assert_eq!(custom_ratio_fields(&options, (0.0, 0.0)), (1.414, 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selecting_free_ratio_clears_previous_custom_dimensions() {
|
||||
let mut options = ToolOptions { crop_ratio: "16:9".into(), ..ToolOptions::default() };
|
||||
|
||||
@@ -645,7 +645,7 @@ pub fn swapped(r: [f64; 4]) -> [f64; 4] {
|
||||
/// no ratio is set; "original" becomes the document's size turned on its side.
|
||||
pub fn swapped_ratio(key: &str, doc_w: f64, doc_h: f64) -> Option<String> {
|
||||
let (w, h) = crate::chrome_ui::crop_ratio(key, doc_w, doc_h).filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0)?;
|
||||
Some(format!("{}:{}", crate::widgets::fmt_num(h), crate::widgets::fmt_num(w)))
|
||||
Some(format!("{}:{}", crate::crop_size::fmt_ratio(h), crate::crop_size::fmt_ratio(w)))
|
||||
}
|
||||
|
||||
/// X: swaps the pending frame between portrait and landscape about its centre, keeping its angle,
|
||||
@@ -1949,6 +1949,7 @@ mod tests {
|
||||
app.ui.tool_options.crop_ratio = String::new();
|
||||
assert!(swap_orientation(&mut app));
|
||||
assert_eq!(app.ui.tool_options.crop_ratio, "", "no ratio stays none");
|
||||
assert_eq!(swapped_ratio("1.414:1", 1.0, 1.0).as_deref(), Some("1:1.414"), "decimals survive the swap (#6487)");
|
||||
assert_eq!(swapped_ratio("0:5", 1.0, 1.0), None);
|
||||
assert_eq!(swapped_ratio("nonsense", 1.0, 1.0), None);
|
||||
// No frame, or another tool: X is Switch Foreground and Background Colors.
|
||||
|
||||
@@ -1279,9 +1279,10 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
// Keep partial edits in ToolOptions so the first side survives a frame;
|
||||
// Original Ratio shows the document's numbers, as Photoshop does.
|
||||
let (mut rw, mut rh) = crate::crop_size::custom_ratio_fields(o, doc_size);
|
||||
let cw = widgets::value_field(ui, &mut rw, 0.0..=99_999.0, "", 54.0).changed();
|
||||
let decimals = crate::crop_size::RATIO_DECIMALS;
|
||||
let cw = widgets::value_field_prec(ui, &mut rw, 0.0..=99_999.0, "", 54.0, decimals).changed();
|
||||
let swap = icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked();
|
||||
let ch = widgets::value_field(ui, &mut rh, 0.0..=99_999.0, "", 54.0).changed();
|
||||
let ch = widgets::value_field_prec(ui, &mut rh, 0.0..=99_999.0, "", 54.0, decimals).changed();
|
||||
if swap {
|
||||
std::mem::swap(&mut rw, &mut rh);
|
||||
}
|
||||
@@ -6217,6 +6218,40 @@ mod compact_visual_regressions {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_crop_ratio_fields_show_three_decimals() {
|
||||
// #6487: a 1.414 : 1 ratio reads 1.414 in the bar, not 1.4.
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let Some(kind) = crate::theme::ThemeKind::ALL.into_iter().find(|k| {
|
||||
crate::theme::apply(&ctx, *k);
|
||||
Tokens::get(&ctx).pro
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
crate::theme::apply(&ctx, kind);
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
app.ui.tool = Tool::Crop;
|
||||
app.ui.tool_options.crop_ratio = "1.414:1".into();
|
||||
let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 120.0));
|
||||
let mut out = ctx.run_ui(input_at_scale(screen, 1.0), |ui| options_bar(&mut app, ui));
|
||||
for _ in 0..3 {
|
||||
out.textures_delta.clear();
|
||||
out = ctx.run_ui(input_at_scale(screen, 1.0), |ui| options_bar(&mut app, ui));
|
||||
}
|
||||
out.textures_delta.clear();
|
||||
let texts: Vec<&str> = out
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|s| match &s.shape {
|
||||
egui::Shape::Text(t) => Some(t.galley.job.text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(texts.contains(&"1.414"), "{texts:?}");
|
||||
assert_eq!(app.ui.tool_options.crop_ratio, "1.414:1", "showing the ratio leaves it alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_narrow_options_bar_preference_shortens_the_bar() {
|
||||
assert_eq!(options_bar_height(true, false), 36.0);
|
||||
|
||||
@@ -219,3 +219,59 @@ fn delete_with_the_pen_deletes_the_finished_work_path_not_the_pixels() {
|
||||
h.run_steps(2);
|
||||
assert!(work(&h), "another tool's Delete is Edit › Clear, not Delete Path");
|
||||
}
|
||||
|
||||
fn space(h: &mut Harness<'static, PhotocraftApp>, down: bool) {
|
||||
h.event(egui::Event::Key { key: Key::Space, physical_key: None, pressed: down, repeat: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
}
|
||||
|
||||
/// Did the last frame paint the Pen's path in progress: an accent polyline starting at `at`, its
|
||||
/// first anchor on screen (`vector_ui::draw_overlay`)?
|
||||
fn pen_path_painted(h: &Harness<'static, PhotocraftApp>, at: Pos2) -> bool {
|
||||
let accent = crate::theme::Tokens::get(&h.ctx).accent;
|
||||
h.output().shapes.iter().any(|c| match &c.shape {
|
||||
egui::Shape::Path(p) => {
|
||||
p.stroke.width == 1.5
|
||||
&& matches!(p.stroke.color, egui::epaint::ColorMode::Solid(col) if col == accent)
|
||||
&& p.points.len() >= 2
|
||||
&& p.points[0].distance(at) < 1.0
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// #6592: holding Space to pan with the Hand keeps the Pen's path in progress, and shows it, as in
|
||||
/// Photoshop.
|
||||
#[test]
|
||||
fn space_pan_keeps_the_pen_path_in_progress_visible() {
|
||||
let mut h = harness();
|
||||
click(&mut h, [20.0, 20.0]);
|
||||
click(&mut h, [100.0, 20.0]);
|
||||
assert_eq!(h.state().ui.pen.as_ref().map(|p| p.knots.len()), Some(2));
|
||||
let p = screen(&h, [150.0, 100.0]);
|
||||
h.event(egui::Event::PointerMoved(p));
|
||||
h.run_steps(1);
|
||||
assert!(pen_path_painted(&h, screen(&h, [20.0, 20.0])), "drawn before Space");
|
||||
space(&mut h, true);
|
||||
assert!(pen_path_painted(&h, screen(&h, [20.0, 20.0])), "drawn with Space held, before the drag");
|
||||
let c0 = h.state().ui.views[0].center;
|
||||
button(&mut h, p, true, Modifiers::NONE);
|
||||
for i in 1..=5 {
|
||||
// A pan frame paints the image and its overlays with the view it started with.
|
||||
let first = screen(&h, [20.0, 20.0]);
|
||||
h.event(egui::Event::PointerMoved(p + vec2(10.0 * i as f32, 0.0)));
|
||||
h.run_steps(1);
|
||||
let pen = h.state().ui.pen.as_ref().map(|p| p.knots.len());
|
||||
let painted = pen_path_painted(&h, first);
|
||||
assert_eq!(pen, Some(2), "the path in progress is kept while panning (step {i})");
|
||||
assert!(painted, "the path in progress is drawn while panning (step {i})");
|
||||
}
|
||||
button(&mut h, p + vec2(50.0, 0.0), false, Modifiers::NONE);
|
||||
space(&mut h, false);
|
||||
h.run_steps(1);
|
||||
let c1 = h.state().ui.views[0].center;
|
||||
assert!((c1[0] - (c0[0] - 50.0)).abs() < 0.5, "Space-drag panned: {c0:?} -> {c1:?}");
|
||||
assert_eq!(h.state().ui.tool, Tool::Pen);
|
||||
assert_eq!(h.state().ui.pen.as_ref().map(|p| p.knots.len()), Some(2), "the path in progress survives the pan");
|
||||
assert!(pen_path_painted(&h, screen(&h, [20.0, 20.0])), "drawn after the pan");
|
||||
}
|
||||
@@ -217,11 +217,17 @@ pub fn keep_after_commit(app: &mut PhotocraftApp, layer: LayerId, before: Option
|
||||
}
|
||||
}
|
||||
|
||||
/// Display scale for a 256-bin histogram: bar heights are `v / top` clamped to 1, linear
|
||||
/// to the tallest bin like Photoshop. A percentile of the sorted bins degenerates on
|
||||
/// sparse histograms (few occupied levels sort 0 into every low index), drawing tiny
|
||||
/// counts as tall as the real peaks (#6574).
|
||||
/// Extracted from [`draw_histogram`] so the scaling is unit-testable.
|
||||
pub fn histogram_scale_top(h: &[u32; 256]) -> f32 {
|
||||
h.iter().copied().max().unwrap_or(1).max(1) as f32 * 1.1
|
||||
}
|
||||
|
||||
pub fn draw_histogram(p: &egui::Painter, r: Rect, h: &[u32; 256], color: Color32) {
|
||||
// Scale to a high percentile so a single spike (e.g. pure white) doesn't flatten the rest.
|
||||
let mut sorted: Vec<u32> = h.to_vec();
|
||||
sorted.sort_unstable();
|
||||
let top = sorted.get(250).copied().unwrap_or(1).max(1) as f32 * 1.1;
|
||||
let top = histogram_scale_top(h);
|
||||
let mut pts = vec![egui::pos2(r.left(), r.bottom())];
|
||||
for (i, v) in h.iter().enumerate() {
|
||||
let x = r.left() + (i as f32 + 0.5) / 256.0 * r.width();
|
||||
@@ -452,6 +458,34 @@ mod tests {
|
||||
);
|
||||
assert_ne!(tag(HistSource::Channel { layer, surface: GraySurface::LayerMask }, ToneSpace::Rgb), tag(HistSource::Layer(layer), ToneSpace::Rgb));
|
||||
}
|
||||
|
||||
/// #6574: bar heights scale linearly to the tallest bin. A 90/10 black/white
|
||||
/// histogram draws the small bar at a ninth of the big one, not full height.
|
||||
#[test]
|
||||
fn histogram_scale_is_proportional_for_two_level_images() {
|
||||
let mut h = [0u32; 256];
|
||||
h[0] = 100_000;
|
||||
h[255] = 900_000;
|
||||
let top = histogram_scale_top(&h);
|
||||
let small = (h[0] as f32 / top).min(1.0);
|
||||
let big = (h[255] as f32 / top).min(1.0);
|
||||
assert!((small / big - 1.0 / 9.0).abs() < 0.02, "small/big = {}, top = {top}", small / big);
|
||||
}
|
||||
|
||||
/// #6574: a sparse histogram (few occupied levels) must not scale to a bin
|
||||
/// index that is 0: the old `sorted.get(250)` degenerated to `top = 1.1`,
|
||||
/// drawing a few hundred samples as tall as hundreds of thousands.
|
||||
#[test]
|
||||
fn histogram_scale_does_not_degenerate_on_sparse_histograms() {
|
||||
let mut h = [0u32; 256];
|
||||
h[0] = 500_000;
|
||||
h[128] = 300;
|
||||
h[255] = 500_000;
|
||||
let top = histogram_scale_top(&h);
|
||||
assert!(top > h[128] as f32, "scale {top} must exceed the tiny middle bin");
|
||||
let tiny = (h[128] as f32 / top).min(1.0);
|
||||
assert!(tiny < 0.05, "tiny bin draws near-flat, got {tiny}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -53,6 +53,16 @@ integrate() {
|
||||
break
|
||||
fi
|
||||
done
|
||||
# AM / AppMan (#6392) install their own launcher, whose Exec runs a command on
|
||||
# PATH rather than this AppImage, so the check above misses it. AM's author
|
||||
# names the only two places it writes one: system-wide for AM, per user for
|
||||
# AppMan and rootless installs.
|
||||
for f in /usr/local/share/applications/photocraft-AM.desktop "$apps/photocraft-AM.desktop"; do
|
||||
if [ -f "$f" ]; then
|
||||
external=1
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [ "$external" = 1 ]; then
|
||||
if [ -f "$apps/$DESK_ID.desktop" ]; then
|
||||
rm -f "$apps/$DESK_ID.desktop" 2>/dev/null || true
|
||||
|
||||
@@ -129,4 +129,27 @@ out="$(APPIMAGE="$odd" "$APPDIR/AppRun" x)" || fail "launch with an odd path exi
|
||||
[ "$out" = "stub: x" ] || fail "odd path: $out"
|
||||
[ ! -e "$XDG_DATA_HOME" ] || fail "integrated an AppImage path that needs escaping"
|
||||
|
||||
# 12. AM / AppMan (#6392): a photocraft-AM.desktop launcher in the user's applications
|
||||
# dir owns the menu entry. AppRun removes its own entry left from an earlier run,
|
||||
# writes no second one and still installs the icons.
|
||||
rm -rf "$XDG_DATA_HOME"
|
||||
"$APPDIR/AppRun" >/dev/null || fail "launch before AM install exited non-zero"
|
||||
[ -f "$DESKTOP" ] || fail "no desktop entry before AM install"
|
||||
am_desktop="$XDG_DATA_HOME/applications/photocraft-AM.desktop"
|
||||
printf '[Desktop Entry]
|
||||
Type=Application
|
||||
Name=PhotoCraft
|
||||
Exec=photocraft %%F
|
||||
Icon=%s
|
||||
' "$APP_ID" >"$am_desktop"
|
||||
"$APPDIR/AppRun" >/dev/null || fail "launch with AM launcher exited non-zero"
|
||||
[ ! -e "$DESKTOP" ] || fail "duplicate desktop entry kept alongside AM launcher (#6392)"
|
||||
[ -f "$am_desktop" ] || fail "AM launcher was removed"
|
||||
[ -f "$XDG_DATA_HOME/icons/hicolor/256x256/apps/$APP_ID.png" ] || fail "icons missing with AM launcher"
|
||||
|
||||
# 13. Once AM removes its launcher, AppRun writes its own entry again.
|
||||
rm -f "$am_desktop"
|
||||
"$APPDIR/AppRun" >/dev/null || fail "launch after AM removal exited non-zero"
|
||||
[ -f "$DESKTOP" ] || fail "no desktop entry after the AM launcher was removed"
|
||||
|
||||
echo "AppRun desktop integration ok"
|
||||
Reference in new issue
Block a user