diff --git a/crates/algo/src/content_aware.rs b/crates/algo/src/content_aware.rs index 955a911119..f9d84bd713 100644 --- a/crates/algo/src/content_aware.rs +++ b/crates/algo/src/content_aware.rs @@ -244,6 +244,208 @@ pub fn fill_owned( fill_cow(w, h, ch, Cow::Owned(img), hole, source, opts, ctl) } +/// The patch radius of the fill for the option set #14191 measured (Default colour adaptation, +/// no rotation, no scale, no mirror). The straight features of its document are 10 px bands and +/// 20 px stripes: the default 7x7 patch fits inside one stripe or inside one band gap, so it +/// carries no phase information and the completion decides from colour alone and runs one region +/// into the other. An 11x11 patch covers a feature and the one next to it, which is what keeps +/// their phase through the hole. Every other option set, and a sampling area other than the +/// Rectangular one, is marked "not measured" in #14191 and keeps [`CompleteParams`]' default radius. +const MEASURED_STRUCTURE_PATCH_RADIUS: usize = 5; + +/// Whether `opts` holds the option set #14191 measured on its test document: Default colour +/// adaptation, no rotation, no scale and no mirror. +fn structure_measured(opts: &FillOptions) -> bool { + opts.color_adaptation == color_level("default") && opts.rotations.is_empty() && !opts.scale && !opts.mirror +} + +/// Whether `source` is the Rectangular sampling area of the buffer: every pixel outside the hole. +/// #14191 measured Rectangular, and Auto where it keeps that same area; Auto where its +/// content-based choice differs (or any other area) is not measured. +fn rectangular_area(hole: &[bool], source: &[bool]) -> bool { + hole.iter().zip(source).all(|(h, s)| *h || *s) +} + +/// The variant specs of `opts`: mirror, the rotation set, the scaled pair. +fn variant_specs(opts: &FillOptions) -> Vec<(f32, f32, bool)> { + let mut specs: Vec<(f32, f32, bool)> = Vec::new(); + if opts.mirror { + specs.push((0.0, 1.0, true)); + } + for ° in &opts.rotations { + specs.push((deg, 1.0, false)); + } + if opts.scale { + specs.push((0.0, 0.8, false)); + specs.push((0.0, 1.25, false)); + } + specs +} + +/// The variants of `src` for `specs`, or none when none are asked for or their mosaic would not fit +/// in the budget. The mosaic gap follows `params`, so they are built again for every attempt. +fn mosaic_variants(src: Src, specs: &[(f32, f32, bool)], params: &CompleteParams, ctl: &Interrupt) -> Result, Cancelled> { + if specs.is_empty() { + return Ok(Vec::new()); + } + let gap = 2 * params.patch_radius + 2; + let dims: Vec<(usize, usize)> = specs.iter().map(|&(deg, scale, _)| variant_dims(src.w, src.h, deg, scale)).collect(); + if mosaic_size(src.w, src.h, gap, &dims).is_none() { + return Ok(Vec::new()); + } + let mut extra = Vec::new(); + for &(deg, scale, mirror) in specs { + extra.push(variant(src, deg, scale, mirror, ctl)?); + } + Ok(extra) +} + +/// The roles of the window's pixels: the hole, what may be copied from, and the rest of the image. +fn window_roles(hole: &[bool], ok: &[bool]) -> Vec { + par::map(hole.len(), true, |s| { + if hole[s] { + Px::Hole + } else if ok[s] { + Px::Source + } else { + Px::Known + } + }) +} + +/// The mosaic of the window and its variants: identity at the left, the variants in a column to its +/// right, gaps that are no image. `None` when the mosaic spans more than the budget (the variants +/// then go unused, as they did before they were built). +#[allow(clippy::too_many_arguments)] +fn mosaic_pixels( + w: usize, + h: usize, + ch: usize, + img: &[f32], + hole: &[bool], + ok: &[bool], + extra: &[Variant], + params: &CompleteParams, +) -> Option<(usize, usize, Vec, Vec)> { + let gap = 2 * params.patch_radius + 2; + if extra.is_empty() { + return None; + } + let (mw, mh) = mosaic_size(w, h, gap, &extra.iter().map(|v| (v.w, v.h)).collect::>())?; + let mut mimg = vec![0.0f32; mw * mh * ch]; + let mut roles = vec![Px::Void; mw * mh]; + for y in 0..h { + for x in 0..w { + let (s, d) = (y * w + x, y * mw + x); + mimg[d * ch..(d + 1) * ch].copy_from_slice(&img[s * ch..(s + 1) * ch]); + roles[d] = if hole[s] { + Px::Hole + } else if ok[s] { + Px::Source + } else { + Px::Known + }; + } + } + let mut oy = 0; + for v in extra { + for y in 0..v.h { + for x in 0..v.w { + let (s, d) = (y * v.w + x, (oy + y) * mw + w + gap + x); + mimg[d * ch..(d + 1) * ch].copy_from_slice(&v.img[s * ch..(s + 1) * ch]); + if v.ok[s] { + roles[d] = Px::Source; + } + } + } + oy += v.h + gap; + } + Some((mw, mh, mimg, roles)) +} + +/// One completion attempt: the variant mosaic to run it on, or the plain window when no variant was +/// asked for or the mosaic would not fit the budget. +struct Attempt { + /// The mosaic's dimensions (the window's own when there is no mosaic). + mw: usize, + mh: usize, + /// The mosaic pixels; empty when the attempt runs on the window itself. + mosaic: Vec, + /// The roles of the attempt's pixels (the window's own when there is no mosaic). + roles: Vec, +} + +/// Build one attempt: variants first (their pixels are expensive, so the mosaic budget is settled +/// on their dimensions before any variant is built), then the mosaic or the plain window's roles. +/// The mosaic gap follows `params`, so an attempt is built for every patch radius. +#[allow(clippy::too_many_arguments)] +fn fill_attempt( + w: usize, + h: usize, + ch: usize, + pixels: &[f32], + hole: &[bool], + ok: &[bool], + specs: &[(f32, f32, bool)], + params: &CompleteParams, + ctl: &Interrupt, +) -> Result { + let src = Src { w, h, ch, img: pixels, ok }; + let extra = mosaic_variants(src, specs, params, ctl)?; + ctl.check()?; + match mosaic_pixels(w, h, ch, pixels, hole, ok, &extra, params) { + Some((mw, mh, mosaic, roles)) => Ok(Attempt { mw, mh, mosaic, roles }), + // No variant was asked for, or its mosaic would not fit the budget: complete the window. + None => Ok(Attempt { mw: w, mh: h, mosaic: Vec::new(), roles: window_roles(hole, ok) }), + } +} + +/// The window's own pixels out of a finished mosaic (its left region, the variants and the gaps +/// beside it are no answer). +fn window_from_mosaic(w: usize, h: usize, ch: usize, mw: usize, mosaic: &[f32]) -> Vec { + let mut out = vec![0.0f32; w * h * ch]; + for y in 0..h { + for x in 0..w { + let (s, d) = ((y * mw + x) * ch, (y * w + x) * ch); + out[d..d + ch].copy_from_slice(&mosaic[s..s + ch]); + } + } + out +} + +/// The measured fill of #14191, asked again with today's radius when the 11x11 patch leaves no +/// donor: an 11x11 window needs room inside the buffer, and a hole can also use up every window of +/// a bigger one. Without that second attempt the fill would answer with the smooth membrane where +/// today's 7x7 patch still copies pieces; #14191 measures a 600x400 document and keeps every other +/// case on today's behaviour. +#[allow(clippy::too_many_arguments)] +fn fill_retry( + w: usize, + h: usize, + ch: usize, + img: &[f32], + hole: &[bool], + ok: &[bool], + specs: &[(f32, f32, bool)], + params: &mut CompleteParams, + inner: &Interrupt, + ctl: &Interrupt, +) -> Result>, Cancelled> { + let measured = params.patch_radius; + for radius in [measured, CompleteParams::default().patch_radius] { + params.patch_radius = radius; + let attempt = fill_attempt(w, h, ch, img, hole, ok, specs, params, ctl)?; + if attempt.mosaic.is_empty() { + if let Some(f) = complete_masked(w, h, ch, img, &attempt.roles, params, inner)? { + return Ok(Some(f)); + } + } else if let Some(f) = complete_masked(attempt.mw, attempt.mh, ch, &attempt.mosaic, &attempt.roles, params, inner)? { + return Ok(Some(window_from_mosaic(w, h, ch, attempt.mw, &f))); + } + } + Ok(None) +} + #[allow(clippy::too_many_arguments)] fn fill_cow( w: usize, @@ -261,111 +463,76 @@ fn fill_cow( if !hole.iter().any(|h| *h) { return Ok(img.into_owned()); } - let params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; - let gap = 2 * params.patch_radius + 2; + let mut params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + if structure_measured(opts) && rectangular_area(hole, source) { + params.patch_radius = MEASURED_STRUCTURE_PATCH_RADIUS; + } let ok: Vec = par::map(w * h, true, |i| !hole[i] && source[i]); - let src = Src { w, h, ch, img: &img, ok: &ok }; - // Variants: the identity (which holds the hole) first, then the adaptations. Their pixels are - // expensive, so the mosaic budget is settled on their dimensions before any variant is built; - // when the variants would not fit, the image itself is completed without them. - let mut specs: Vec<(f32, f32, bool)> = Vec::new(); - if opts.mirror { - specs.push((0.0, 1.0, true)); - } - for ° in &opts.rotations { - specs.push((deg, 1.0, false)); - } - if opts.scale { - specs.push((0.0, 0.8, false)); - specs.push((0.0, 1.25, false)); - } - let dims: Vec<(usize, usize)> = specs.iter().map(|&(deg, scale, _)| variant_dims(w, h, deg, scale)).collect(); - let size = if specs.is_empty() { None } else { mosaic_size(w, h, gap, &dims) }; - let mut extra: Vec = Vec::new(); - if size.is_some() { - for &(deg, scale, mirror) in &specs { - extra.push(variant(src, deg, scale, mirror, ctl)?); - } - } - let role = |s: usize| { - if hole[s] { - Px::Hole - } else if ok[s] { - Px::Source - } else { - Px::Known - } - }; - // Mosaic: identity at the left, variants in a column to its right, gaps that are no image. - // Without variants it is the image itself; so it is when the variants would not fit - // (`size` above is then None and `extra` is empty). - let (mw, mh, mosaic, roles): (usize, usize, Option>, Vec) = if let Some((mw, mh)) = size { - let mut mimg = vec![0.0f32; mw * mh * ch]; - let mut roles = vec![Px::Void; mw * mh]; - for y in 0..h { - for x in 0..w { - let (s, d) = (y * w + x, y * mw + x); - mimg[d * ch..(d + 1) * ch].copy_from_slice(&img[s * ch..(s + 1) * ch]); - roles[d] = role(s); - } - } - let mut oy = 0; - for v in &extra { - ctl.check()?; - for y in 0..v.h { - for x in 0..v.w { - let (s, d) = (y * v.w + x, (oy + y) * mw + w + gap + x); - mimg[d * ch..(d + 1) * ch].copy_from_slice(&v.img[s * ch..(s + 1) * ch]); - if v.ok[s] { - roles[d] = Px::Source; - } - } - } - oy += v.h + gap; - } - (mw, mh, Some(mimg), roles) - } else { - (w, h, None, par::map(w * h, true, role)) - }; - drop((extra, ok)); - ctl.check()?; + let specs = variant_specs(opts); // The completion is nearly all the work. let cancel = || ctl.cancelled(); let progress = |f: f32| ctl.progress(f * 0.99); let inner = photocraft_raster::Interrupt::new(&cancel, &progress); - let out = match mosaic { - // Without variants the image itself is completed (it changes only in the hole). - None => { - let filled: Result, Cow<[f32]>> = match img { - Cow::Owned(v) => complete_masked_owned(w, h, ch, v, &roles, ¶ms, &inner)?.map_err(Cow::Owned), - Cow::Borrowed(b) => complete_masked(w, h, ch, b, &roles, ¶ms, &inner)?.ok_or(Cow::Borrowed(b)), - }; - match filled { + // One completion for every option set but the measured one: it fills the caller's buffer in + // place when it owns one. The measured set may be asked a second time (see `fill_retry`). + if params.patch_radius != MEASURED_STRUCTURE_PATCH_RADIUS { + let mut pixels = img.into_owned(); + let attempt = fill_attempt(w, h, ch, &pixels, hole, &ok, &specs, ¶ms, ctl)?; + ctl.check()?; + let out = if attempt.mosaic.is_empty() { + match complete_masked_owned(w, h, ch, pixels, &attempt.roles, ¶ms, &inner)? { Ok(f) => f, - Err(img) => membrane_fill_with(w, h, ch, &img, hole, ctl)?, + // Nothing to copy from: the membrane, as today. + Err(v) => membrane_fill_with(w, h, ch, &v, hole, ctl)?, } - } - Some(mimg) => match complete_masked(mw, mh, ch, &mimg, &roles, ¶ms, &inner)? { - Some(f) => { - let mut out = img.into_owned(); - for y in 0..h { - for x in 0..w { - if hole[y * w + x] { - let (s, d) = ((y * mw + x) * ch, (y * w + x) * ch); - out[d..d + ch].copy_from_slice(&f[s..s + ch]); + } else { + match complete_masked(attempt.mw, attempt.mh, ch, &attempt.mosaic, &attempt.roles, ¶ms, &inner)? { + Some(f) => { + for y in 0..h { + for x in 0..w { + if hole[y * w + x] { + let (s, d) = ((y * attempt.mw + x) * ch, (y * w + x) * ch); + pixels[d..d + ch].copy_from_slice(&f[s..s + ch]); + } } } + pixels } - out + None => membrane_fill_with(w, h, ch, &pixels, hole, ctl)?, } - None => membrane_fill_with(w, h, ch, &img, hole, ctl)?, - }, - }; + }; + ctl.check()?; + ctl.progress(1.0); + return Ok(out); + } + let out = fill_cow_measured(w, h, ch, img.as_ref(), hole, &ok, &specs, &mut params, &inner, ctl)?; ctl.check()?; ctl.progress(1.0); Ok(out) } +/// The measured fill (#14191): the window is read where it stands, so both attempts see the same +/// pixels; the answer is a new buffer, as in [`fill_with`] (measured fills come from the command's +/// own copy of the sampling window). +#[allow(clippy::too_many_arguments)] +fn fill_cow_measured( + w: usize, + h: usize, + ch: usize, + img: &[f32], + hole: &[bool], + ok: &[bool], + specs: &[(f32, f32, bool)], + params: &mut CompleteParams, + inner: &Interrupt, + ctl: &photocraft_raster::Interrupt, +) -> Result, Cancelled> { + match fill_retry(w, h, ch, img, hole, ok, specs, params, inner, ctl)? { + Some(f) => Ok(f), + // Nothing to copy from at either radius: the membrane, as today. + None => membrane_fill_with(w, h, ch, img, hole, ctl), + } +} /// Box mean of radius `r` over a `w × h` plane (edge-clamped), by summed areas. fn box_mean(w: usize, h: usize, v: &[f32], r: usize) -> Vec { let w1 = w + 1; @@ -722,5 +889,7 @@ pub fn default_brush_size(hole: Rect) -> f64 { (0.4 * (w * h).sqrt()).round() } +#[cfg(test)] +mod structure_continue_tests; #[cfg(test)] mod tests; diff --git a/crates/algo/src/content_aware/structure_continue_tests.rs b/crates/algo/src/content_aware/structure_continue_tests.rs new file mode 100644 index 0000000000..895e9f5d02 --- /dev/null +++ b/crates/algo/src/content_aware/structure_continue_tests.rs @@ -0,0 +1,472 @@ +//! #14191: the fill continues straight bands and stripes through the hole. +//! +//! The measured document (both the reference application and PhotoCraft main f143ce5849): +//! 600 x 400, RGB, 8 bit, one Background layer. Top half blue 60,120,200 with a light 120,170,230 +//! band 10 px high every 40 px (at y 0, 40, 80, 120, 160); bottom half vertical stripes 20 px wide, +//! 40,140,60 at x = 0 mod 40 and 80,180,90 at x = 20 mod 40; a red 220,30,30 square from 260,160 to +//! 340,240; selection 250,150 to 350,250 (the square plus 10 px). The sampling window is 100,0 to +//! 500,400, which is what [`sampling_window`] gives for that selection, and Auto covers the same +//! area as Rectangular on this document. +//! +//! The reference application keeps the bands and the stripes in their original phase through the +//! hole and keeps the blue / green boundary at y 200. PhotoCraft main runs the blue half down into +//! the green one: 300,165 -> 64,124,201 instead of the light band 120,170,230, and 300,205 -> +//! 65,127,205, 285,220 -> 64,127,205, 300,240 -> 62,124,202 instead of the green stripes. + +use super::*; + +const DOC_W: usize = 600; +const DOC_H: usize = 400; +/// The measured selection: the red square plus 10 px. +const SEL: (i32, i32, i32, i32) = (250, 150, 350, 250); +/// The red square inside it. +const SQUARE: (usize, usize, usize, usize) = (260, 160, 340, 240); + +/// The document's colours without the square, in levels of 255: what the reference application +/// shows through the hole again. +fn background_levels(x: usize, y: usize) -> [i32; 3] { + if y < 200 { + if y % 40 < 10 { [120, 170, 230] } else { [60, 120, 200] } + } else if x % 40 < 20 { + [40, 140, 60] + } else { + [80, 180, 90] + } +} + +/// The measured document as interleaved normalised floats (`ch = 3`). +fn document() -> Vec { + let at = |x: usize, y: usize| -> [f32; 3] { + let v = if (SQUARE.0..SQUARE.2).contains(&x) && (SQUARE.1..SQUARE.3).contains(&y) { [220, 30, 30] } else { background_levels(x, y) }; + [v[0] as f32 / 255.0, v[1] as f32 / 255.0, v[2] as f32 / 255.0] + }; + (0..DOC_H).flat_map(|y| (0..DOC_W).flat_map(move |x| at(x, y))).collect() +} + +/// The sampling window of the measured selection on the measured canvas. +fn window() -> Rect { + sampling_window(Rect::new(SEL.0, SEL.1, SEL.2, SEL.3), Rect::new(0, 0, DOC_W as i32, DOC_H as i32)) +} + +/// The measured window's buffer and its hole: `edit.contentAwareFill` fills the sampling window, +/// with the selection as the hole and (for Auto) the area `auto_sampling` keeps within it. +fn window_buffers() -> (Vec, Vec, usize) { + let doc = document(); + let win = window(); + let (ww, wh) = (win.width() as usize, win.height() as usize); + let mut img = vec![0.0f32; ww * wh * 3]; + let mut hole = vec![false; ww * wh]; + for y in 0..wh { + let dy = (win.y0 + y as i32) as usize; + let s = (dy * DOC_W + win.x0 as usize) * 3; + img[y * ww * 3..(y + 1) * ww * 3].copy_from_slice(&doc[s..s + ww * 3]); + for x in 0..ww { + hole[y * ww + x] = (SEL.0..SEL.2).contains(&(win.x0 + x as i32)) && (SEL.1..SEL.3).contains(&(win.y0 + y as i32)); + } + } + (img, hole, ww) +} + +/// Fill the measured document the way the command does with `opts` and Auto or Rectangular +/// sampling, and return the filled window. +fn fill_measured_document(sampling: &str, opts: &FillOptions) -> Vec { + let (img, hole, ww) = window_buffers(); + let source = match sampling { + "auto" => auto_sampling(ww, 400, 3, &img, &hole), + _ => hole.iter().map(|h| !h).collect(), + }; + fill(ww, 400, 3, &img, &hole, &source, opts) +} + +/// The filled colour at document coordinates `(x, y)`, in levels of 255. +fn filled_at(win: &[f32], x: usize, y: usize) -> [i32; 3] { + let w = window().width() as usize; + let i = ((y - window().y0 as usize) * w + (x - window().x0 as usize)) * 3; + [0, 1, 2].map(|c| (win[i + c] * 255.0).round() as i32) +} + +/// The nine pixel samples of #14191, measured in the reference application (document coordinates +/// and the reference colour in levels of 255), in the order the issue lists them. +const SAMPLES: [((usize, usize), [i32; 3]); 9] = [ + ((300, 165), [120, 170, 230]), + ((300, 180), [60, 120, 200]), + ((300, 195), [60, 120, 200]), + ((300, 205), [80, 180, 90]), + ((285, 220), [40, 140, 60]), + ((265, 220), [77, 177, 88]), + ((300, 240), [80, 180, 90]), + ((255, 155), [60, 120, 200]), + ((345, 245), [80, 180, 90]), +]; + +/// The measured samples that are more than 12 levels per channel from the reference value. +fn samples_off(out: &[f32]) -> Vec { + SAMPLES + .iter() + .filter_map(|((x, y), want)| { + let got = filled_at(out, *x, *y); + let off = (0..3).map(|c| (got[c] - want[c]).abs()).max().unwrap_or(0); + (off > 12).then(|| format!("({x},{y}) -> {got:?}, reference {want:?}, off by {off}")) + }) + .collect() +} + +/// How far the fill is from the document's own background, over the whole hole: (worst deviation +/// in levels, number of pixels within 12, number of pixels counted). Every pixel of the hole +/// carries the colour the document has at that place, which is what "the bands and stripes run +/// through the hole with their original phase" means. +fn phase_through_the_hole(out: &[f32]) -> (i32, usize, usize) { + let (mut worst, mut within, mut n) = (0, 0, 0); + for y in 150..250 { + for x in 250..350 { + let want = background_levels(x, y); + let got = filled_at(out, x, y); + let off = (0..3).map(|c| (got[c] - want[c]).abs()).max().unwrap_or(0); + worst = worst.max(off); + within += usize::from(off <= 12); + n += 1; + } + } + (worst, within, n) +} + +/// The blue / light half and the green half of the document, by the palette colour a filled pixel +/// took: the boundary between them. +const PALETTE: [(&str, [i32; 3]); 5] = + [("blue", [60, 120, 200]), ("light", [120, 170, 230]), ("green-a", [40, 140, 60]), ("green-b", [80, 180, 90]), ("red", [220, 30, 30])]; + +fn palette_name(v: [i32; 3]) -> &'static str { + PALETTE.iter().min_by_key(|(_, c)| c.iter().zip(v).map(|(a, b): (&i32, i32)| (a - b) * (a - b)).sum::()).map(|(n, _)| *n).unwrap_or("?") +} + +fn cold(name: &str) -> bool { + name == "blue" || name == "light" +} + +fn green(name: &str) -> bool { + name == "green-a" || name == "green-b" +} + +/// Over the inside of the hole: how many pixels above y 200 took a colour of the green half, and +/// how many below it took a colour of the blue half. Rows within 3 px of the boundary are left +/// out: there the seams between copied pieces blend. +fn boundary_mismatches(out: &[f32]) -> (usize, usize) { + let (mut green_above, mut cold_below) = (0, 0); + for y in 153..248 { + if (197..204).contains(&y) { + continue; + } + for x in 253..348 { + let n = palette_name(filled_at(out, x, y)); + if y < 200 && green(n) { + green_above += 1; + } + if y > 200 && cold(n) { + cold_below += 1; + } + } + } + (green_above, cold_below) +} + +#[test] +fn auto_fill_continues_the_bands_and_stripes_at_the_measured_samples() { + assert_eq!(window(), Rect::new(100, 0, 500, 400), "the sampling window #14191 measured"); + let out = fill_measured_document("auto", &FillOptions::default()); + let off = samples_off(&out); + assert!(off.is_empty(), "Auto sampling: {} of 9 samples off\n{}", off.len(), off.join("\n")); +} + +#[test] +fn rectangular_fill_continues_the_bands_and_stripes_at_the_measured_samples() { + let out = fill_measured_document("rectangular", &FillOptions::default()); + let off = samples_off(&out); + assert!(off.is_empty(), "Rectangular sampling: {} of 9 samples off\n{}", off.len(), off.join("\n")); +} + +#[test] +fn auto_fill_keeps_the_blue_green_boundary_at_y_200() { + let out = fill_measured_document("auto", &FillOptions::default()); + let (green_above, cold_below) = boundary_mismatches(&out); + assert_eq!(green_above, 0, "pixels above y 200 that took a colour of the green half"); + assert_eq!(cold_below, 0, "pixels below y 200 that took a colour of the blue half"); +} + +#[test] +fn rectangular_fill_keeps_the_blue_green_boundary_at_y_200() { + let out = fill_measured_document("rectangular", &FillOptions::default()); + let (green_above, cold_below) = boundary_mismatches(&out); + assert_eq!(green_above, 0, "pixels above y 200 that took a colour of the green half"); + assert_eq!(cold_below, 0, "pixels below y 200 that took a colour of the blue half"); +} + +#[test] +fn auto_fill_keeps_the_band_and_stripe_phase_across_the_whole_hole() { + let out = fill_measured_document("auto", &FillOptions::default()); + let (worst, within, n) = phase_through_the_hole(&out); + assert_eq!((within, n), (10_000, 10_000), "{within} of {n} hole pixels carry the document's own colour within 12 levels (worst {worst})"); +} + +#[test] +fn rectangular_fill_keeps_the_band_and_stripe_phase_across_the_whole_hole() { + let out = fill_measured_document("rectangular", &FillOptions::default()); + let (worst, within, n) = phase_through_the_hole(&out); + assert_eq!((within, n), (10_000, 10_000), "{within} of {n} hole pixels carry the document's own colour within 12 levels (worst {worst})"); +} + +/// Per-channel slack for the unmeasured pins below. The exact values hold bit for bit on Windows +/// (also at RAYON_NUM_THREADS 4, 2 and 1), but not on every C library: the vote that blends the +/// seams between the copied pieces weights the patches with `(-cost / (2 sigma2)).exp()` of the +/// host C library (`inpaint/solver.rs`), and a filled pixel sitting right on a level boundary +/// rounds one level apart between glibc and the Windows runtime. CI run 43833457124 on +/// ubuntu-24.04 showed (300,180) under colour adaptation High at 64 instead of 65, and (285,220) +/// under rotation Low at 118 instead of 119, while all other 52 channels matched exactly. Nothing +/// on main changed these fills: between f143ce5849 and the branch parent eea585958 no commit +/// touches `content_aware` or `inpaint`. 2 levels is still a hard pin against what the guards +/// guard against: if the new patch radius leaked into one of these option sets, its fill would +/// move the way the measured set moves, and at (300,165) alone that is 60 levels (the None pin +/// 60,120,200 against the 120,170,230 the measured fill gives there). +const UNMEASURED_TOLERANCE: i32 = 2; + +/// The option sets #14191 marks *not measured* on this document keep today's fill: these are the +/// nine samples as main f143ce5849 (and as this branch without the change) gives them. Guard +/// tests: they pass before and after the change and pin it, so widening the new patch radius later +/// has to say what these settings now do. Compared within [`UNMEASURED_TOLERANCE`] levels per +/// channel, see there for why. +fn unmeasured_colour_adaptation() -> Vec<(&'static str, FillOptions, [i32; 27])> { + let at = |level: &str| FillOptions { color_adaptation: color_level(level), rotations: Vec::new(), scale: false, mirror: false, seed: 1 }; + vec![ + ("None", at("none"), [60, 120, 200, 60, 120, 200, 60, 120, 200, 60, 120, 200, 60, 120, 200, 80, 180, 90, 60, 120, 200, 60, 120, 200, 80, 180, 90]), + ("High", at("high"), [65, 122, 191, 65, 119, 186, 64, 117, 183, 48, 132, 70, 77, 162, 98, 70, 163, 91, 47, 129, 76, 60, 120, 198, 80, 180, 90]), + ( + "Very High", + at("veryHigh"), + [63, 121, 192, 64, 119, 187, 64, 117, 182, 80, 155, 103, 78, 152, 112, 65, 152, 94, 73, 146, 122, 60, 120, 199, 80, 180, 90], + ), + ] +} + +fn unmeasured_geometric_adaptation() -> Vec<(&'static str, FillOptions, [i32; 27])> { + let base = || FillOptions { color_adaptation: color_level("default"), rotations: Vec::new(), scale: false, mirror: false, seed: 1 }; + vec![ + ( + "rotation Low", + FillOptions { rotations: rotation_level("low"), ..base() }, + [61, 118, 192, 62, 119, 192, 62, 119, 198, 61, 119, 203, 60, 119, 206, 77, 172, 95, 60, 119, 208, 60, 120, 198, 80, 180, 90], + ), + ( + "rotation Full", + FillOptions { rotations: rotation_level("full"), ..base() }, + [65, 124, 200, 65, 123, 199, 64, 122, 199, 82, 184, 92, 63, 122, 192, 63, 122, 193, 61, 121, 194, 60, 120, 199, 80, 180, 90], + ), + ( + "Scale on", + FillOptions { scale: true, ..base() }, + [115, 163, 219, 58, 117, 190, 59, 118, 190, 77, 172, 88, 63, 126, 206, 76, 172, 94, 62, 124, 203, 60, 119, 197, 80, 179, 90], + ), + ( + "Mirror on", + FillOptions { mirror: true, ..base() }, + [64, 122, 198, 63, 121, 196, 62, 119, 194, 43, 137, 62, 62, 124, 202, 75, 172, 92, 61, 123, 201, 60, 120, 199, 80, 180, 90], + ), + ] +} + +fn check_unmeasured(what: &str, opts: &FillOptions, want: &[i32; 27]) { + let out = fill_measured_document("auto", opts); + let got: Vec = SAMPLES.iter().flat_map(|((x, y), _)| filled_at(&out, *x, *y)).collect(); + let off: Vec = SAMPLES + .iter() + .enumerate() + .filter_map(|(k, ((x, y), _))| { + let (g, w) = (&got[k * 3..k * 3 + 3], &want[k * 3..k * 3 + 3]); + let dev = (0..3).map(|c| (g[c] - w[c]).abs()).max().unwrap_or(0); + (dev > UNMEASURED_TOLERANCE).then(|| format!("({x},{y}) -> {g:?}, today's fill {w:?}, off by {dev}")) + }) + .collect(); + assert!( + off.is_empty(), + "{what}: the nine samples moved by more than {UNMEASURED_TOLERANCE} levels, although #14191 marks that case not measured\n{}", + off.join("\n") + ); +} + +#[test] +fn unmeasured_colour_adaptation_keeps_todays_fill() { + for (what, opts, want) in unmeasured_colour_adaptation() { + check_unmeasured(what, &opts, &want); + } +} + +#[test] +fn unmeasured_geometric_adaptation_keeps_todays_fill() { + for (what, opts, want) in unmeasured_geometric_adaptation() { + check_unmeasured(what, &opts, &want); + } +} + +#[test] +fn measured_auto_area_is_the_rectangular_one() { + // What the measured Auto and Rectangular fills above rest on: on this document Auto keeps the + // whole window, as in the reference application. + let (img, hole, ww) = window_buffers(); + assert_eq!(auto_sampling(ww, 400, 3, &img, &hole), hole.iter().map(|h| !h).collect::>()); +} + +/// #14191 marks Auto on a document where its content-based choice differs from Rectangular as not +/// measured, so that fill keeps today's 7x7 patch even with the measured options. The document: the +/// measured one with a white column 40 px wide at x 440 to 480 in the window, which Auto leaves +/// out. Today's fill is the completion with [`CompleteParams`]' default radius on the same roles. +#[test] +fn auto_fill_whose_area_differs_from_rectangular_keeps_todays_patch_radius() { + let (mut img, hole, ww) = window_buffers(); + let column = |i: usize| (440..480).contains(&(window().x0 as usize + i % ww)); + for (i, px) in img.chunks_mut(3).enumerate() { + if column(i) { + px.copy_from_slice(&[250.0 / 255.0; 3]); + } + } + let source = auto_sampling(ww, 400, 3, &img, &hole); + let rectangular: Vec = hole.iter().map(|h| !h).collect(); + assert_ne!(source, rectangular, "Auto must choose an area other than the Rectangular one here"); + let opts = FillOptions::default(); + let out = fill(ww, 400, 3, &img, &hole, &source, &opts); + let roles: Vec = (0..ww * 400) + .map(|i| { + if hole[i] { + Px::Hole + } else if source[i] { + Px::Source + } else { + Px::Known + } + }) + .collect(); + let params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + assert_eq!(params.patch_radius, 3, "today's radius"); + let today = complete_masked(ww, 400, 3, &img, &roles, ¶ms, &Interrupt::NONE).unwrap().unwrap(); + let moved = out.iter().zip(&today).filter(|(a, b)| a != b).count(); + assert_eq!(moved, 0, "{moved} channel values differ from today's radius-3 fill"); +} + +/// A small buffer that carries the measured option set and the Rectangular area, so the patch +/// radius is the only thing under test: vertical stripes (period 4) in two far-apart colours, with +/// the hole the 1 px border of the buffer. An off-centre 2 x 2 hole leaves no 7 x 7 donor either on +/// a buffer this small (every 7 x 7 window takes a hole pixel), so it proves nothing here. +fn small_stripes(n: usize) -> (Vec, Vec) { + let (a, b) = ([10.0 / 255.0, 200.0 / 255.0, 20.0 / 255.0], [200.0 / 255.0, 30.0 / 255.0, 180.0 / 255.0]); + let img: Vec = (0..n * n).flat_map(|i| if (i % n) % 4 < 2 { a } else { b }).collect(); + let hole: Vec = (0..n * n).map(|i| (i % n).min(i / n) < 1 || (i % n).max(i / n) > n - 2).collect(); + (img, hole) +} + +/// The completion of the same roles with a given patch radius: `None` when that radius leaves no +/// donor to copy from, which is what sends the fill to the membrane. +fn completion(n: usize, img: &[f32], hole: &[bool], params: &CompleteParams) -> Option> { + let roles: Vec = hole.iter().map(|h| if *h { Px::Hole } else { Px::Source }).collect(); + complete_masked(n, n, 3, img, &roles, params, &Interrupt::NONE).unwrap() +} + +/// The smallest side that still holds a fully interior 11 x 11 donor window. +const PATCH_SIDE: usize = MEASURED_STRUCTURE_PATCH_RADIUS * 2 + 1; + +/// Review round 2, real: on a buffer narrower than the 11 x 11 patch there is no window centre for +/// radius 5 at all, so the measured fill found no donor and answered with the smooth membrane where +/// today's radius 3 still copies pieces (#14191 measures 600 x 400 and keeps every other case on +/// today's behaviour, and its "no regression" bullet covers this). Measured at b2764ca1c: on the +/// 9 x 9 buffer the radius-3 completion fills the border hole with 96 channel values differing from +/// the membrane; the radius-5 completion has no donor, so the fill returned the membrane in all 243 +/// channel values of that buffer. The fill now gets today's radius-3 answer there again. +#[test] +fn measured_fill_on_a_small_image_keeps_todays_patch_radius() { + for n in [PATCH_SIDE - 2, PATCH_SIDE - 1] { + let (img, hole) = small_stripes(n); + let opts = FillOptions::default(); + let source: Vec = hole.iter().map(|h| !h).collect(); + assert!(structure_measured(&opts) && rectangular_area(&hole, &source), "n {n}: the measured configuration"); + let params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + assert_eq!(params.patch_radius, 3, "n {n}: today's radius"); + let today = completion(n, &img, &hole, ¶ms).unwrap_or_else(|| panic!("n {n}: today's radius-3 fill has no donor either")); + let out = fill(n, n, 3, &img, &hole, &source, &opts); + let moved = out.iter().zip(&today).filter(|(a, b)| a != b).count(); + let membrane = membrane_fill_with(n, n, 3, &img, &hole, &Interrupt::NONE).unwrap(); + let like_membrane = out.iter().zip(&membrane).filter(|(a, b)| *a == *b).count(); + assert_eq!( + moved, + 0, + "n {n}: {moved} of {} channel values differ from today's radius-3 fill; {like_membrane} of them equal the membrane fill", + img.len() + ); + } +} + +/// The other side of that border: when an 11 x 11 donor window does exist, the measured fill uses +/// it, also on a small buffer (18 x 18 with a 1 px border hole: 178 channel values differ from +/// today's radius-3 completion there). Guard test, passes before and after the change. +#[test] +fn measured_fill_uses_the_11x11_patch_when_a_window_fits() { + let n = 18; + let (img, hole) = small_stripes(n); + let opts = FillOptions::default(); + let source: Vec = hole.iter().map(|h| !h).collect(); + let wide = CompleteParams { patch_radius: MEASURED_STRUCTURE_PATCH_RADIUS, seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + let with_patch = completion(n, &img, &hole, &wide).expect("n 18: an 11 x 11 donor window must exist beside a 1 px border hole"); + let today = completion(n, &img, &hole, &CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }) + .expect("n 18: today's fill has donors"); + let out = fill(n, n, 3, &img, &hole, &source, &opts); + let from_patch = out.iter().zip(&with_patch).filter(|(a, b)| a != b).count(); + let from_today = out.iter().zip(&today).filter(|(a, b)| a != b).count(); + assert_eq!(from_patch, 0, "the measured fill is not the 11 x 11 completion ({from_patch} channel values differ)"); + assert_ne!(from_today, 0, "the 11 x 11 completion is the same as today's ({from_today} differ): the patch was never used"); +} + +/// The membrane fallback stays where it already is today: a buffer with no room even for the +/// default 7 x 7 patch has no donor at either radius, so the new radius never reaches it. +/// Guard test, passes before and after the change. +#[test] +fn measured_fill_without_room_for_todays_patch_still_falls_back_to_the_membrane() { + for n in 4..7 { + let (img, hole) = small_stripes(n); + let opts = FillOptions { color_adaptation: Adapt::NONE, ..FillOptions::default() }; + let source: Vec = hole.iter().map(|h| !h).collect(); + let params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + assert!(completion(n, &img, &hole, ¶ms).is_none(), "n {n}: no donor at today's radius either"); + let out = fill(n, n, 3, &img, &hole, &source, &opts); + let membrane = membrane_fill_with(n, n, 3, &img, &hole, &Interrupt::NONE).unwrap(); + let moved = out.iter().zip(&membrane).filter(|(a, b)| a != b).count(); + assert_eq!(moved, 0, "n {n}: {moved} channel values differ from the membrane fill"); + } +} + +/// The same buffer as [`small_stripes`] with an 8 x 8 hole in the middle instead of the border: at +/// 18 x 18 there are 11 x 11 windows (their centres are x and y 5 to 12), but the hole covers every +/// one of them, while a 7 x 7 window still fits in the 8-wide strips left and right of it. +fn stripes_hole_blocking_the_wide_windows(n: usize) -> (Vec, Vec) { + let (a, b) = ([10.0 / 255.0, 200.0 / 255.0, 20.0 / 255.0], [200.0 / 255.0, 30.0 / 255.0, 180.0 / 255.0]); + let img: Vec = (0..n * n).flat_map(|i| if (i % n) % 4 < 2 { a } else { b }).collect(); + let hole: Vec = + (0..n * n).map(|i| matches!(i % n, x if x >= n / 2 - 1 && x <= n / 2 + 6) && matches!(i / n, y if y >= n / 2 - 1 && y <= n / 2 + 6)).collect(); + (img, hole) +} + +/// The other way radius 5 can leave no donor: a buffer with room for 11 x 11 windows, and a hole +/// that uses up all of them. #14191 measured a hole four patches across in a 400 x 400 window, so a +/// fill that completes today with the default radius has to complete the same way here, before the +/// membrane fallback. +#[test] +fn measured_fill_falls_back_to_todays_radius_when_the_hole_leaves_no_room_for_the_patch() { + let n = 18; + let (img, hole) = stripes_hole_blocking_the_wide_windows(n); + let opts = FillOptions::default(); + let source: Vec = hole.iter().map(|h| !h).collect(); + assert!(structure_measured(&opts) && rectangular_area(&hole, &source), "the measured configuration"); + assert_eq!(hole.iter().filter(|h| **h).count(), 64, "an 8 x 8 hole"); + let wide = CompleteParams { patch_radius: MEASURED_STRUCTURE_PATCH_RADIUS, seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + assert!(completion(n, &img, &hole, &wide).is_none(), "radius 5 must leave no donor here, that is the case under test"); + let params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() }; + assert_eq!(params.patch_radius, 3, "today's radius"); + let today = completion(n, &img, &hole, ¶ms).expect("today's radius-3 fill has donors"); + let out = fill(n, n, 3, &img, &hole, &source, &opts); + let moved = out.iter().zip(&today).filter(|(a, b)| a != b).count(); + assert_eq!(moved, 0, "{moved} of {} channel values differ from today's radius-3 fill", img.len()); +} diff --git a/crates/engine/src/adjust_params.rs b/crates/engine/src/adjust_params.rs index 7e3def4e22..0823835d93 100644 --- a/crates/engine/src/adjust_params.rs +++ b/crates/engine/src/adjust_params.rs @@ -449,8 +449,12 @@ fn merge(mut a: Value, b: Value) -> Value { a } +/// One Channel Mixer output row: every coefficient and the constant is a whole percentage. +/// Scripted values round to the nearest whole percent before clamping, as the reference +/// application measures (0.4 to 0, 0.5 to 1, 50.6 to 51, 300 to 200, #14414); halves round away +/// from zero, which is what the dialog's own slider pass already does (`f32::round`). fn mixer_row(v: &[f32]) -> [f32; 4] { - std::array::from_fn(|i| v.get(i).copied().unwrap_or(0.0).clamp(-200.0, 200.0) / 100.0) + std::array::from_fn(|i| v.get(i).copied().unwrap_or(0.0).round().clamp(-200.0, 200.0) / 100.0) } fn hue_saturation(r: &Reader<'_>, base: Option<&Adjustment>) -> Result { diff --git a/crates/engine/src/adjust_params/tests.rs b/crates/engine/src/adjust_params/tests.rs index 0d8f5af141..5fbc44967a 100644 --- a/crates/engine/src/adjust_params/tests.rs +++ b/crates/engine/src/adjust_params/tests.rs @@ -707,6 +707,24 @@ fn gradient_map_source_params() { } } +/// #14414: the reference application mixes with whole percentages. Scripted values round to the +/// nearest whole percent before clamping; the dialog already sends whole percents. +#[test] +fn channel_mixer_percentages_are_whole_numbers() { + let a = from_params( + "channelMixer", + &json!({"red": [0.4, 0.5, 50.6, -0.5], "green": [33.3, 33.3, 33.3, 0.0], "blue": [-300.0, 300.0, 0.0, 0.0]}), + None, + ColorMode::Rgb, + ) + .unwrap(); + let Adjustment::ChannelMixer { matrix, .. } = a else { panic!("wrong kind") }; + assert_eq!(matrix[0], [0.0, 0.01, 0.51, -0.01], "0.4 to 0, 0.5 to 1, 50.6 to 51, halves away from zero"); + assert_eq!(matrix[1], [0.33, 0.33, 0.33, 0.0], "33.3 stores as 33"); + assert_eq!(matrix[2], [-2.0, 2.0, 0.0, 0.0], "clamps stay -200 and 200"); + assert_eq!(to_params(&a)["red"], json!([0.0, 1.0, 51.0, -1.0]), "the stored step reads back whole"); +} + /// #14417: tone values are whole percentages; scripted fractions round like the dialog's own /// slider pass (away from zero on halves, which no measured case pins to). #[test] diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 9e9bd0594e..f8d68e604f 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -73,6 +73,8 @@ pub mod history_source_cmds; pub mod image_cmds; pub mod layer_copy_cmds; pub mod layer_css_cmds; +#[cfg(test)] +mod layer_from_background_name_tests; pub mod layer_label_cmds; pub mod layer_list_cmds; pub mod layer_mask_props_cmds; diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index c6ffdf4ef2..d0ea23d03b 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -421,7 +421,7 @@ fn artboard_from_layers(s: &mut Session, p: &Value) -> Result { // A size of the user's own (a post, a story…) from the layers' top left; 0 or none keeps // their bounds on that axis (#9087). let size = [int(p, "width").filter(|v| *v != 0), int(p, "height").filter(|v| *v != 0)]; - let (gid, rect, shift) = s.edit("Artboard from Layers", |doc, active| { + let (gid, rect, shift) = s.edit("New Artboard From Layers", |doc, active| { let ids = crate::layer_multi_cmds::top_level(doc, &sel); if ids.is_empty() || ids.iter().any(|id| doc.artboard_of(*id).is_some()) { return Err(EngineError::Other("select layers that are not in an artboard".into())); @@ -1039,6 +1039,10 @@ mod file_names_tests; #[cfg(test)] #[path = "artboard_cmds/first_board_background_tests.rs"] mod first_board_background_tests; +#[cfg(test)] +#[path = "artboard_cmds/from_layers_history_name_tests.rs"] +mod from_layers_history_name_tests; + #[cfg(test)] #[path = "artboard_cmds/from_group_hidden_bounds_tests.rs"] mod from_group_hidden_bounds_tests; diff --git a/crates/engine/src/cmd/artboard_cmds/from_layers_history_name_tests.rs b/crates/engine/src/cmd/artboard_cmds/from_layers_history_name_tests.rs new file mode 100644 index 0000000000..34dbe6d306 --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/from_layers_history_name_tests.rs @@ -0,0 +1,44 @@ +//! Artboard from Layers adds one history step named "New Artboard From Layers" (#14578). + +use super::*; +use photocraft_geom::Rect; + +/// 100 x 80 RGB at `depth` with a pixel layer "Red" holding a square at 10,10 to 30,30. +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 80, "depth": depth, "background": "white"})).unwrap(); + s.edit("Red", |doc, active| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster("Red", fmt); + l.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 30), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + let id = doc.insert_above(None, l); + *active = Some(id); + Ok(id) + }) + .unwrap(); + s +} + +fn steps(s: &Session) -> Vec { + s.active().unwrap().history.entries() +} + +fn tree(s: &Session) -> Vec<(String, bool)> { + s.active().unwrap().doc.walk().iter().map(|(_, _, l)| (l.name.clone(), l.children().is_some())).collect() +} + +#[test] +fn artboard_from_layers_adds_one_new_artboard_from_layers_step() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let before_steps = steps(&s); + let before_tree = tree(&s); + s.execute("layer.new.artboardFromLayers", json!({"name": "Board"})).unwrap(); + let after = steps(&s); + assert_eq!(after.len(), before_steps.len() + 1, "exactly one step at {depth} bit: {after:?}"); + assert_eq!(after.last().map(String::as_str), Some("New Artboard From Layers"), "{depth} bit"); + s.undo(); + assert_eq!(tree(&s), before_tree, "one undo restores the layer tree at {depth} bit"); + assert!(s.active().unwrap().doc.artboards().is_empty()); + } +} diff --git a/crates/engine/src/cmd/export_preset_cmds.rs b/crates/engine/src/cmd/export_preset_cmds.rs index 5653784bc9..29fb8b4f0f 100644 --- a/crates/engine/src/cmd/export_preset_cmds.rs +++ b/crates/engine/src/cmd/export_preset_cmds.rs @@ -12,15 +12,17 @@ const MAX_PRESETS: usize = 256; const MAX_PX: u32 = 300_000; const FORMATS: [&str; 6] = ["png", "jpg", "webp", "tif", "tga", "ico"]; -/// Export As › Image Size › Resample, in Photoshop's order: the `image.imageSize` method each -/// choice sends, and its menu label. The first one is the default. -pub const RESAMPLE: [(&str, &str); 6] = [ - ("bicubicAutomatic", "Bicubic Automatic"), +/// Export As › Image Size › Resample, in the reference application's menu order (#13737): the +/// `image.imageSize` method each choice sends, and its menu label. The default is +/// [`DEFAULT_RESAMPLE`]; Preserve Details is Image Size's `preserveDetails` resampler. +pub const RESAMPLE: [(&str, &str); 7] = [ ("bicubic", "Bicubic"), - ("bicubicSmoother", "Bicubic Smoother"), + ("bicubicAutomatic", "Bicubic Automatic"), ("bicubicSharper", "Bicubic Sharper"), + ("bicubicSmoother", "Bicubic Smoother"), ("bilinear", "Bilinear"), ("nearest", "Nearest Neighbor"), + ("preserveDetails", "Preserve Details"), ]; /// Photoshop's Export As default: Bicubic Automatic. @@ -244,7 +246,7 @@ pub fn specs() -> Vec { label: "Save Export Preset", menu: &[], shortcut: None, - params: r#"{"name":str,"settings":{"format":"png|jpg|webp|tif|tga|ico","quality":1..100,"lossless":bool,"transparency":bool,"scale":1..1000,"width":px,"height":px,"lockAspect":bool,"sizing":"scale|pixels","metadata":"none|exif|all","profile":"document|srgb","embedProfile":bool,"tgaBits":"auto|24|32","resample":"bicubicAutomatic|bicubic|bicubicSmoother|bicubicSharper|bilinear|nearest"="bicubicAutomatic"}} (a saved name is replaced)"#, + params: r#"{"name":str,"settings":{"format":"png|jpg|webp|tif|tga|ico","quality":1..100,"lossless":bool,"transparency":bool,"scale":1..1000,"width":px,"height":px,"lockAspect":bool,"sizing":"scale|pixels","metadata":"none|exif|all","profile":"document|srgb","embedProfile":bool,"tgaBits":"auto|24|32","resample":"bicubic|bicubicAutomatic|bicubicSharper|bicubicSmoother|bilinear|nearest|preserveDetails"="bicubicAutomatic"}} (a saved name is replaced)"#, enabled: always, run: save, journal: false, diff --git a/crates/engine/src/cmd/extra_cmds.rs b/crates/engine/src/cmd/extra_cmds.rs index 7e09659db9..5cdeccd894 100644 --- a/crates/engine/src/cmd/extra_cmds.rs +++ b/crates/engine/src/cmd/extra_cmds.rs @@ -493,16 +493,36 @@ fn layer_from_background(s: &mut Session, p: &Value) -> Result { // names the Background while another layer is selected. let select = p.get("select").and_then(Value::as_bool).unwrap_or(true); let id = s.edit("Layer From Background", |doc, active| { + let bg = doc.background().ok_or(EngineError::Other("the document has no Background layer".into()))?; + let (id, name) = (bg.id, lowest_free_layer_name(doc, bg.id)); + // The name is read before the layer is unlocked, from the other layers' names. let l = doc.background_mut().ok_or(EngineError::Other("the document has no Background layer".into()))?; unlock_background(l); + l.name = name; if select || active.is_none() { - *active = Some(l.id); + *active = Some(id); } - Ok(l.id) + Ok(id) })?; Ok(json!({"layer": id.0})) } +/// The name `layer_from_background` gives the converted Background: "Layer N" with the lowest N of +/// 0 or more that no other top-level layer is named (#14821). `Document::next_layer_name` counts +/// from 1, so this is the 0-based variant the issue measures; it lives next to the command because +/// the rule is the command's alone - the other callers of `unlock_background` / +/// `background_to_layer` (an edit the Background can't take, artboards, the crop) keep naming the +/// layer "Layer 0" as today. +/// +/// Only top-level names count, and they are compared exactly: whether a name inside a group, or a +/// name written with other capitals ("LAYER 1"), blocks a number is not measured in #14821 (asked +/// on the issue), so the search stays with the measured cases. +fn lowest_free_layer_name(doc: &Document, renamed: LayerId) -> String { + let taken: std::collections::HashSet<&str> = doc.layers.iter().filter(|l| l.id != renamed).map(|l| l.name.as_str()).collect(); + // At most `taken.len() + 1` names from 0 are needed, so the search always succeeds. + (0..=taken.len()).map(|n| format!("Layer {n}")).find(|n| !taken.contains(n.as_str())).unwrap_or_else(|| "Layer".to_string()) +} + pub(crate) fn unlock_background(l: &mut Layer) { l.name = "Layer 0".into(); l.locks.transparency = false; diff --git a/crates/engine/src/cmd/layer_from_background_name_tests.rs b/crates/engine/src/cmd/layer_from_background_name_tests.rs new file mode 100644 index 0000000000..84e4e35f9f --- /dev/null +++ b/crates/engine/src/cmd/layer_from_background_name_tests.rs @@ -0,0 +1,84 @@ +//! #14821: Layer > New > Layer from Background names the converted layer "Layer N", with the +//! lowest free N counting from 0. Today `unlock_background` (`extra_cmds.rs`) always writes +//! "Layer 0", so a document that already has a layer of that name ends up with two layers called +//! "Layer 0". +//! +//! The five cases below are the ones measured in the issue. `Document::next_layer_name` counts from +//! 1, so the command needs its own 0-based rule. +//! +//! Not measured in the issue: whether a name inside a group takes part in the search, and whether a +//! differently cased name ("LAYER 1") counts as taken. Both keep the reading the measured cases +//! support: top-level layer names only, compared exactly, as `next_layer_name` compares them. The +//! group case is asked about on the issue. + +use photocraft_doc::LayerId; +use serde_json::json; + +use crate::Session; + +fn doc(s: &Session) -> &photocraft_doc::Document { + &s.active().unwrap().doc +} + +/// A document with the white Background `file.new` makes and top-level layers named `others` above +/// it, then Layer from Background: the name the converted Background ends with. +fn converted_name(others: &[&str]) -> String { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + let bg = doc(&s).layers[0].id; + for n in others { + let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.setProps", json!({"layer": id.0, "name": n})).unwrap(); + } + assert_eq!(doc(&s).layers.iter().skip(1).map(|l| l.name.as_str()).collect::>(), others, "the other layers are named as the issue's test document"); + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + doc(&s).layer(bg).unwrap().name.clone() +} + +#[test] +fn the_name_is_the_lowest_layer_n_that_no_other_layer_uses() { + let cases: Vec<(Vec<&str>, &str)> = vec![ + (vec!["Top"], "Layer 0"), + (vec!["Layer 0"], "Layer 1"), + (vec!["Layer 1"], "Layer 0"), + (vec!["Layer 5"], "Layer 0"), + (vec!["Layer 0", "Layer 1"], "Layer 2"), + ]; + for (others, want) in cases { + assert_eq!(converted_name(&others), want, "other layers: {others:?}"); + } +} + +#[test] +fn a_document_that_is_only_a_background_takes_layer_0() { + assert_eq!(converted_name(&[]), "Layer 0"); +} + +#[test] +fn undo_restores_the_background_with_its_old_name() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + let bg = doc(&s).layers[0].id; + s.execute("layer.new.layer", json!({"name": "Layer 0"})).unwrap(); + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + assert_eq!(doc(&s).layer(bg).unwrap().name, "Layer 1", "the taken name is skipped"); + assert!(s.undo(), "one history step"); + let l = doc(&s).layer(bg).unwrap(); + assert!(doc(&s).is_background(bg) && l.name == "Background", "the Background is back, named as before"); +} + +#[test] +fn the_other_callers_of_unlock_background_still_name_it_layer_0() { + // #14821 changes only Layer from Background. An edit the Background cannot take converts it + // through `background_to_layer`, which names it "Layer 0" as today, even when that name is + // already taken. + for (key, value) in [("opacity", json!(0.5)), ("fill", json!(0.5)), ("blend", json!("Multiply"))] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + let bg = doc(&s).layers[0].id; + s.execute("layer.new.layer", json!({"name": "Layer 0"})).unwrap(); + s.execute("layer.setProps", json!({"layer": bg.0, key: value})).unwrap(); + let l = doc(&s).layer(bg).unwrap(); + assert!(!doc(&s).is_background(bg) && l.name == "Layer 0", "{key}: still named Layer 0 as today"); + } +} diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 8944cf12d1..a521eb15e1 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -343,9 +343,9 @@ impl PhotocraftApp { /// Reconciles canvas view state with open documents in the session. pub fn sync_views(&mut self) { - // The Paths panel selection belongs to the active document. Ordinary edits replace the - // snapshot and advance its revision; a replaced snapshot without a newer revision is a - // reopened document, even with the same ID. + // The Paths panel selection and canvas context menu belong to the active document. + // Ordinary edits replace the snapshot and advance its revision; a replaced snapshot + // without a newer revision is a reopened document, even with the same ID. let document = self.session.active().map(|st| (st.doc.id, st.revision, std::sync::Arc::downgrade(&st.doc))); // Crop's Fill goes back to its default entry when another document that was already open // becomes active (a tab switch, or closing the active one), as in the reference @@ -364,6 +364,7 @@ impl PhotocraftApp { }; if !same_document { self.ui.selected_path = None; + self.ui.canvas_tool_menu = None; } self.path_document = document; vector_ui::cancel_stale_pen(self); diff --git a/crates/ui-egui/src/canvas/document_display.rs b/crates/ui-egui/src/canvas/document_display.rs index a3232685ab..6d42ed379c 100644 --- a/crates/ui-egui/src/canvas/document_display.rs +++ b/crates/ui-egui/src/canvas/document_display.rs @@ -439,17 +439,12 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, view.pending.drain(..queued.len().min(view.pending.len())); } let canvas_output = shown.output; - if let Some(next) = canvas_output.view.as_ref() { - view.set_from(next, ppp); - } - // The scroll bars' and the compass's change: the bars drag the view, the compass turns it. - if let Some(next) = turned.as_ref() { - view.set_from(next, ppp); - } let response = hosted.unwrap_or_default(); - // A view a tool set (the Crop tool's slide) is the one the app keeps; the canvas's own otherwise. - if let Some(next) = response.view.as_ref() { - view.set_from(next, ppp); + // The host also echoes the canvas's view (for example when rulers inset its rect). Only an actual tool + // edit takes precedence over the scroll bars or compass. + let tool_view = response.view.filter(|next| Some(*next) != canvas_output.view); + if let Some(next) = tool_view.or(turned).or(canvas_output.view) { + view.set_from(&next, ppp); } Shown { output: canvas_output, response, guides, overlay_context } } @@ -511,7 +506,7 @@ fn canvas_controls( if !app.ui.view.hides_chrome() { let size = app.session.documents()[host.idx].doc.size; let bounds = Rect64::from_origin_size(Point::ZERO, Size::new(f64::from(size.width), f64::from(size.height))); - CanvasScrollbars::new("Scroll bars", Bind::bound(&mut shown), bounds).show_at(ui, rect); + CanvasScrollbars::new("Scroll bars", Bind::bound(&mut shown), bounds).overscroll(app.session.prefs().tools.overscroll).show_at(ui, rect); } if RotateView::visible(shown.rotation) { let mut rotation = shown.rotation; @@ -622,6 +617,99 @@ mod tests { app } + /// #15529: a fitting document can still move through its scroll bars when Overscroll is on. + #[test] + fn canvas_scrollbars_follow_overscroll_for_a_fitting_document() { + check_canvas_scrollbar_overscroll(false); + } + + #[test] + fn canvas_scrollbars_follow_overscroll_with_rulers() { + check_canvas_scrollbar_overscroll(true); + } + + fn check_canvas_scrollbar_overscroll(rulers: bool) { + use egui::accesskit::Role; + use egui::{Event, PointerButton, pos2, vec2}; + use egui_kittest::kittest::{NodeT, Queryable}; + + let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).with_pixels_per_point(1.0).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.extras.rulers = rulers; + app + }); + h.run_steps(6); + let view = &mut h.state_mut().ui.views[0]; + view.zoom = 1.0; + view.center = [200.0, 150.0]; + view.clear_pending(); + h.run_steps(3); + + for overscroll in [false, true] { + h.state_mut().session.prefs.edit(|prefs| prefs.tools.overscroll = overscroll); + h.run_steps(3); + let view = testing::view(h.state()).expect("the document is shown"); + assert_eq!(view.zoom, 1.0, "100% at one pixel per point"); + assert_eq!(view.center, Point::new(200.0, 150.0)); + assert!(view.rect.width() > 600.0 && view.rect.height() > 450.0, "the 400 × 300 document fits"); + + let horizontal = h.get_by_role_and_label(Role::ScrollBar, "Horizontal scroll bar"); + let vertical = h.get_by_role_and_label(Role::ScrollBar, "Vertical scroll bar"); + let track = horizontal.rect(); + let thumb_center = vertical.rect().center(); + if rulers { + assert!(vertical.rect().top() < view.rect.top(), "the visible view is inset below the rulers"); + } + let room = |length: f32, document: f64| if overscroll { f64::from(length) - document } else { 0.0 }; + let x_room = room(view.rect.width(), 400.0); + let y_room = room(view.rect.height(), 300.0); + assert_eq!(horizontal.accesskit_node().max_numeric_value(), Some(x_room), "horizontal scroll room with Overscroll {overscroll}"); + assert_eq!(vertical.accesskit_node().max_numeric_value(), Some(y_room), "vertical scroll room with Overscroll {overscroll}"); + + // On a fitting document a page press reaches the end of the scrollable range. + let at = pos2(track.right() - 3.0, track.center().y); + h.hover_at(at); + h.run_steps(2); + for pressed in [true, false] { + h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(2); + } + let paged = testing::view(h.state()).expect("the document is shown"); + assert!((paged.center.x - (view.center.x + x_room / 2.0)).abs() < 0.5, "track page position with Overscroll {overscroll}: {paged:?}"); + assert_eq!(paged.center.y, view.center.y); + + // The vertical thumb is centred and its drag can move only its own axis. + h.hover_at(thumb_center); + h.run_steps(2); + h.drag_at(thumb_center); + h.run_steps(1); + for distance in [8.0, 24.0, 40.0] { + h.hover_at(thumb_center + vec2(0.0, distance)); + h.run_steps(1); + } + h.event(Event::PointerButton { pos: thumb_center + vec2(0.0, 40.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + let dragged = testing::view(h.state()).expect("the document is shown"); + assert_eq!(dragged.center.x, paged.center.x); + if overscroll { + assert!(dragged.center.y > view.center.y + 10.0 && dragged.center.y <= view.center.y + y_room / 2.0, "{dragged:?}"); + } else { + assert_eq!(dragged.center.y, view.center.y); + } + } + + // Turning Overscroll off after both axes have moved restores the centred view. + h.state_mut().session.prefs.edit(|prefs| prefs.tools.overscroll = false); + h.run_steps(3); + assert_eq!(testing::view(h.state()).expect("the document is shown").center, Point::new(200.0, 150.0)); + for label in ["Horizontal scroll bar", "Vertical scroll bar"] { + let bar = h.get_by_role_and_label(Role::ScrollBar, label); + assert_eq!(bar.accesskit_node().max_numeric_value(), Some(0.0), "{label} after turning Overscroll off"); + } + } + /// Four conditions decide whether the selection's ants show; each hides them alone, and Escape on an open polygon /// outline brings them back. #[test] diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index 0f9ca73ded..e9a6dbf967 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -123,6 +123,7 @@ pub(crate) fn options_of(f: &Map) -> ExportOptions { "bicubicSharper" => Resample::BicubicSharper, "bilinear" => Resample::Bilinear, "nearest" => Resample::NearestNeighbor, + "preserveDetails" => Resample::PreserveDetails, _ => Resample::Automatic, }; } @@ -152,6 +153,7 @@ pub(crate) fn settings_from(options: &ExportOptions, source: PixelSize) -> Map "bicubicSharper", Resample::Bilinear => "bilinear", Resample::NearestNeighbor => "nearest", + Resample::PreserveDetails => "preserveDetails", // The dialog offers only `RESAMPLE_CHOICES`; a method outside it cannot be chosen. _ => DEFAULT_RESAMPLE, }; @@ -225,9 +227,17 @@ fn dialog_formats() -> Vec { formats } -/// The resample methods the engine's Image Size implements, in `export_resample`'s order. -const RESAMPLE_CHOICES: [Resample; 6] = - [Resample::Automatic, Resample::Bicubic, Resample::BicubicSmoother, Resample::BicubicSharper, Resample::Bilinear, Resample::NearestNeighbor]; +/// The resample methods the engine's Image Size implements, Preserve Details included (#13737). The framework lists +/// them in its own order. +const RESAMPLE_CHOICES: [Resample; 7] = [ + Resample::Automatic, + Resample::Bicubic, + Resample::BicubicSmoother, + Resample::BicubicSharper, + Resample::Bilinear, + Resample::NearestNeighbor, + Resample::PreserveDetails, +]; /// The saved export presets as the dialog's library: the engine's list in its order, each preset's /// settings read with [`options_of`]. @@ -1297,6 +1307,8 @@ fn quick_export(app: &mut PhotocraftApp, p: Value) -> Result { Ok(r) } +#[cfg(test)] +mod preserve_details_tests; #[cfg(test)] mod srgb_default_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/export_dialog/preserve_details_tests.rs b/crates/ui-egui/src/dialogs/export_dialog/preserve_details_tests.rs new file mode 100644 index 0000000000..55aaff45e9 --- /dev/null +++ b/crates/ui-egui/src/dialogs/export_dialog/preserve_details_tests.rs @@ -0,0 +1,89 @@ +//! #13737: Export As's Resample lists seven methods in the reference order, Preserve Details +//! last, with Bicubic Automatic still the default. Preserve Details is Image Size's +//! `preserveDetails` resampler; presets and recorded steps accept it. + +use super::*; +use egui::accesskit::Role; +use egui_kittest::{Harness, kittest::Queryable}; +use photocraft_doc::{Color, SampleType, Size}; +use photocraft_engine::export_preset_cmds::RESAMPLE; +use photocraft_geom::Rect; + +/// 12 x 8 RGB/8 with a one-pixel checker, so resamplers differ when it is enlarged. +fn checker() -> Document { + let mut doc = Document::with_background("Checker", Size::new(12, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let surface = doc.layers[0].surface_mut().unwrap(); + let black = photocraft_raster::from_rgba(&surface.format(), [0.0, 0.0, 0.0, 1.0]); + for y in 0..8 { + for x in (y % 2..12).step_by(2) { + surface.fill_rect(Rect::new(x, y, x + 1, y + 1), &black); + } + } + doc +} + +fn pixels(doc: &Document) -> Vec<[f32; 4]> { + photocraft_compose::flatten(doc).into_px() +} + +fn export_with(resample: &str) -> Document { + let doc = checker(); + let f = json!({"scale": 300, "resample": resample, "profile": "document"}).as_object().unwrap().clone(); + export_document(&doc, &f, None, &photocraft_engine::color_cmds::document_profile(&doc)).unwrap() +} + +#[test] +fn seven_methods_in_the_reference_order_with_bicubic_automatic_the_default() { + let keys: Vec<&str> = RESAMPLE.iter().map(|(k, _)| *k).collect(); + assert_eq!(keys, ["bicubic", "bicubicAutomatic", "bicubicSharper", "bicubicSmoother", "bilinear", "nearest", "preserveDetails"]); + let labels: Vec<&str> = RESAMPLE.iter().map(|(_, l)| *l).collect(); + assert_eq!(labels, ["Bicubic", "Bicubic Automatic", "Bicubic Sharper", "Bicubic Smoother", "Bilinear", "Nearest Neighbor", "Preserve Details"]); + assert_eq!(DEFAULT_RESAMPLE, "bicubicAutomatic"); + assert_eq!(resample_method(&Map::new(), None).unwrap(), "bicubicAutomatic"); +} + +#[test] +fn preserve_details_is_image_sizes_resampler_and_differs_from_bicubic() { + let preserve = export_with("preserveDetails"); + assert_eq!((preserve.size.width, preserve.size.height), (36, 24)); + let mut s = photocraft_engine::Session::new(); + s.add_document(checker(), None); + s.execute("image.imageSize", json!({"width": 36, "height": 24, "resample": "preserveDetails"})).unwrap(); + assert_eq!(pixels(&preserve), pixels(&s.active().unwrap().doc), "the same pixels as Image Size's Preserve Details"); + assert_ne!(pixels(&preserve), pixels(&export_with("bicubic")), "an enlarged export differs from Bicubic"); +} + +#[test] +fn presets_and_recorded_steps_accept_preserve_details_and_unknown_names_still_fail() { + assert!(valid_setting("resample", &json!("preserveDetails"))); + let mut s = photocraft_engine::Session::new(); + s.execute("file.export.presets.save", json!({"name": "Detail", "settings": {"format": "png", "resample": "preserveDetails"}})).unwrap(); + let err = photocraft_engine::export_preset_cmds::export_resample("lanczos").unwrap_err(); + assert!(err.contains("preserveDetails") && err.contains("bicubicAutomatic"), "{err}"); + assert!(!valid_setting("resample", &json!("lanczos"))); +} + +/// The framework's Export As dialog offers Preserve Details (the host hands it `RESAMPLE_CHOICES`), and picking it +/// sets `resample` to `preserveDetails` in the settings the export, a preset and a recorded step read. +#[test] +fn the_dialog_offers_preserve_details_and_it_sets_preserve_details() { + let services = + crate::Services { export: Some(Box::new(|_, _, _| Ok((Vec::new(), Vec::new())))), write: Some(Box::new(|_, _| Ok(()))), ..Default::default() }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.session.add_document(checker(), None); + let mut h = Harness::builder() + .with_size(egui::vec2(1100.0, 900.0)) + .with_step_dt(1.0 / 60.0) + .with_context(app.ctx().clone()) + .build_ui_state(|ui, app: &mut Box| crate::dialogs::run(app, ui), app); + open(h.state_mut()).unwrap(); + h.run_steps(4); + h.get_by_role_and_label(Role::ComboBox, "Resample").click(); + h.run_steps(4); + h.get_by_label("Preserve Details").click(); + h.run_steps(4); + let options = h.state().framework.dialogs.get::().expect("Export As is open").options().clone(); + assert_eq!(options.resample, Resample::PreserveDetails); + assert_eq!(settings_from(&options, PixelSize::new(12, 8))["resample"], "preserveDetails"); + assert_eq!(options_of(&settings_from(&options, PixelSize::new(12, 8))).resample, Resample::PreserveDetails, "and reads back"); +} diff --git a/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs b/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs index ff9e44effa..2389fd03e4 100644 --- a/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs +++ b/crates/ui-egui/src/tools/analysis/sampler_menu_tests.rs @@ -43,10 +43,13 @@ fn delete_never_removes_another_sampler_after_the_list_changes_under_the_menu() // Another document with a sampler at the same index and spot: still not this menu's sampler. right_click(&mut app, 180.0, 90.0); assert_eq!(app.ui.canvas_tool_menu.as_ref().and_then(|m| m.sampler), Some(1)); + let original_menu = app.ui.canvas_tool_menu.clone().unwrap(); app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + assert!(app.ui.canvas_tool_menu.is_none(), "switching documents closes the menu"); for (x, y) in [(20, 20), (180, 90)] { app.run("view.colorSamplers.add", json!({"x": x, "y": y})).unwrap(); } + assert!(!crate::canvas_tool_menu::entry_enabled(&app, &original_menu, SAMPLER_DELETE), "the original menu cannot delete another document's sampler"); crate::canvas_tool_menu::close_stale(&mut app); crate::canvas_tool_menu::choose(&mut app, &ctx, SAMPLER_DELETE); assert_eq!(samplers(&app).len(), 2, "another document's sampler is not deleted"); diff --git a/crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs b/crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs index 2d24da7d4f..f99aae4869 100644 --- a/crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs +++ b/crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs @@ -1,6 +1,9 @@ //! The Magnetic Lasso through `tool_event` (mouse and `ui.pointer` alike): the `PcEdges` adapter and //! the commit mapping. +use craft::behavior::{Cursor, PaintedCursor}; +use craft::ui::primitives::ToolIcon; +use craft::ui::runtime::{cursor, windows::WindowHost}; use egui::Modifiers; use photocraft_geom::Rect; use serde_json::json; @@ -8,6 +11,7 @@ use serde_json::json; use super::inspect; use crate::PhotocraftApp; use crate::canvas::{ToolEvent, tool_event}; +use crate::guide_cursor_tests::{harness, hover}; use crate::state::Tool; const SQUARE: Rect = Rect::new(50, 40, 130, 110); @@ -117,3 +121,37 @@ fn a_document_edit_while_drawing_is_traced_on() { let y = end[1].as_f64().unwrap(); assert!((y - 30.0).abs() < 0.01, "on the new edge: {end}"); } + +/// The live Cursors preference reaches the Magnetic Lasso through the app's canvas (#15466). +#[test] +fn the_magnetic_lasso_cursor_follows_other_cursors_and_caps_lock() { + let mut h = harness(Tool::MagneticLasso); + h.state_mut().ui.tool_options.magnetic.width = 10.0; + let host = WindowHost::of(&h.ctx); + let lasso = ToolIcon::MagneticLasso.icon(); + + for (preference, caps_lock, zoom, radius) in [ + ("standard", false, 1.0, None), + ("precise", false, 1.0, Some(10.0)), + ("precise", true, 1.0, None), + ("standard", true, 1.0, Some(10.0)), + ("standard", true, 2.0, Some(20.0)), + ("standard", false, 2.0, None), + ] { + h.state_mut().run("prefs.set", json!({"path": "cursors.other", "value": preference})).unwrap(); + let view = &mut h.state_mut().ui.views[0]; + view.zoom = zoom; + view.clear_pending(); + host.set_caps_lock(Some(caps_lock)); + // The fixture's vertical guide is at x = 200. Hover clear of it. + hover(&mut h, 100.0, 100.0, Modifiers::NONE); + + let shown = cursor::current(&h.ctx); + let matches = match (radius, &shown) { + (Some(expected), Some(Cursor::Painted(PaintedCursor::Circle { radius, .. }))) => (*radius - expected).abs() < 1e-3, + (None, Some(Cursor::Painted(PaintedCursor::Tool { icon, .. }))) => *icon == lasso, + _ => false, + }; + assert!(matches, "{preference}, Caps Lock {caps_lock}, zoom {zoom}: expected radius {radius:?} or a lasso icon, got {shown:?}"); + } +} diff --git a/crates/ui-egui/src/tools/type_transform.rs b/crates/ui-egui/src/tools/type_transform.rs index de6fcfd91c..60cf615bfe 100644 --- a/crates/ui-egui/src/tools/type_transform.rs +++ b/crates/ui-egui/src/tools/type_transform.rs @@ -171,14 +171,21 @@ pub(crate) fn quad_of(rect: kurbo::Rect, aff: &Affine) -> Option<[kurbo::Point; } /// The text's frame: the open transform's, else the layer's bounds mapped by its existing affine (including -/// rotation and skew). `None` for a locked, hidden or position-locked layer, which cannot be moved. +/// rotation and skew). `None` for a locked, hidden or position-locked layer, which cannot be moved. The one +/// exception is a Type Mask session with ⌘/Ctrl held: its text is a hidden working layer, and the reference +/// application shows the same box over it as over an ordinary type layer (#12082). Without the modifier, and +/// for an invisible ordinary layer, the frame stays absent, so neither the box nor its move reach exists. pub(crate) fn frame(app: &mut PhotocraftApp) -> Option { - let id = LayerId(app.ui.text_edit.as_ref()?.layer); + let ed = app.ui.text_edit.as_ref()?; + let (id, mask_session) = (LayerId(ed.layer), ed.mask); if let Some(t) = &app.ui.type_transform { return Some(Frame { layer: id, rect: t.session.rect(), state: *t.session.state() }); } let layer = app.session.active()?.doc.layer(id)?; - if layer.locks.all || layer.locks.position || !layer.visible { + // Only the whole-box pass (⌘/Ctrl held, or a capture begun so - the early return above) asks the pointer + // frame; the move-reach pass without the modifier keeps a mask session frameless, as before. + let mask_frame = mask_session && craft::ui::runtime::pointer::frame(app.ctx()).mods.cmd; + if layer.locks.all || layer.locks.position || (!layer.visible && !mask_frame) { return None; } let (rect, aff) = source_rect(app, id)?; @@ -405,3 +412,7 @@ pub(crate) fn damage(app: &PhotocraftApp, doc: DocId, revision: u64, before: u64 let area = |key| if key == 0 { Some(p.original_area) } else { p.areas.iter().find(|(k, _)| *k == key).map(|(_, r)| *r) }; Some(area(before)?.union(&area(after)?)) } + +#[cfg(test)] +#[path = "type_transform_mask_tests.rs"] +mod mask_tests; diff --git a/crates/ui-egui/src/tools/type_transform_mask_tests.rs b/crates/ui-egui/src/tools/type_transform_mask_tests.rs new file mode 100644 index 0000000000..87ea063d4f --- /dev/null +++ b/crates/ui-egui/src/tools/type_transform_mask_tests.rs @@ -0,0 +1,210 @@ +//! #12082: ⌘/Ctrl over a Type Mask session shows the transform box and a Ctrl+drag inside it moves +//! the mask text. The session's text lives on a hidden working layer (`type_tool/pointer.rs` sets +//! `visible: false` when the mask starts), and `frame` refused invisible layers, so the box never +//! appeared. An invisible ORDINARY type layer keeps the refusal (Done-when 3), and without the +//! modifier the mask keeps today's behaviour: no frame, and the box's move reach is not armed. + +use egui::{Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use photocraft_doc::{LayerContent, LayerId, TextLayer}; +use photocraft_geom::Affine; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::app::framework::BuildApp; +use crate::canvas::testing::{ToolEvent, to_screen, tool_event}; +use crate::state::Tool; + +fn new_app(tool: Tool) -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 400})).unwrap(); + app.sync_views(); + // The drag's endpoints assert where they land, which snapping would move. + app.ui.extras.snap = false; + app.ui.tool_options.type_size = 48.0; + app.ui.tool = tool; + app +} + +fn click(app: &mut PhotocraftApp, x: f64, y: f64, mods: Modifiers) { + tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x, y }, mods); +} + +/// The canvas harness, as `type_tool/canvas_tests.rs` builds it. +fn harness(app: Box) -> Harness<'static, Box> { + let mut h = Harness::builder().allow_missing_glyphs().with_context(app.ctx().clone()).with_size(vec2(1200.0, 800.0)).with_pixels_per_point(1.0).build_app( + |ui, app: &mut PhotocraftApp| { + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + h.run_steps(4); + h +} + +/// The ⌘ key as the harness holds it on Windows/macOS (mirrors `canvas_tests::type_command`). +fn type_command() -> Modifiers { + Modifiers { command: true, ctrl: true, ..Modifiers::NONE } +} + +fn hold(h: &mut Harness<'static, Box>, mods: Modifiers) { + h.event(egui::Event::ModifiersChanged(mods)); + h.run_steps(1); +} + +/// Sets the main view's zoom and centre through the `ui.set` view command, as `canvas_tests` does. +fn set_view(h: &mut Harness<'static, Box>, zoom: f32, center: [f32; 2]) { + let ctx = h.ctx.clone(); + let (req, _rx) = crate::control::ControlRequest::new("ui.set", json!({"zoom": zoom, "center": center})); + let app = h.state_mut(); + assert!(matches!(crate::control::handle(app, &ctx, &req), crate::control::Reply::Done(_)), "ui.set sets the view"); + h.run_steps(2); +} + +fn transform_press(h: &mut Harness<'static, Box>, p: Pos2, down: bool, mods: Modifiers) { + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: down, modifiers: mods }); + h.run_steps(1); +} + +fn transform_drag(h: &mut Harness<'static, Box>, a: Pos2, b: Pos2, mods: Modifiers) { + hold(h, mods); + h.hover_at(a); + h.run_steps(1); + transform_press(h, a, true, mods); + for k in 1..=6 { + h.hover_at(a + (b - a) * (k as f32 / 6.0)); + h.run_steps(1); + } + transform_press(h, b, false, mods); + hold(h, Modifiers::NONE); +} + +fn text(app: &PhotocraftApp, id: LayerId) -> TextLayer { + let LayerContent::Text(t) = &app.session.active().unwrap().doc.layer(id).unwrap().content else { panic!("a text layer") }; + t.clone() +} + +fn selection_bounds(app: &PhotocraftApp) -> Option { + app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds()) +} + +fn assert_affine(a: Affine, b: Affine) { + for (x, y) in a.m.into_iter().zip(b.m) { + // Translations around 100 doc px at a fitted ppp cancel to ~1e-4 in f32 rounding. + assert!((x - y).abs() < 1e-3, "{a:?} != {b:?}"); + } +} + +/// Done-when 1: the frame (and with it the 8-handle box the overlay draws from it) exists over a +/// Horizontal and a Vertical Type Mask session while ⌘/Ctrl is held, and not without it. +/// Done-when 1: the frame (and with it the 8-handle box the overlay draws from it) exists over a +/// Horizontal and a Vertical Type Mask session while ⌘/Ctrl is held, and not without it. +#[test] +fn holding_ctrl_shows_the_transform_frame_over_a_type_mask() { + for tool in [Tool::HorizontalTypeMask, Tool::VerticalTypeMask] { + let mut app = new_app(tool); + click(&mut app, 300.0, 250.0, Modifiers::NONE); + assert!(app.ui.text_edit.as_ref().is_some_and(|ed| ed.mask && ed.created), "{tool:?}: a mask session"); + let mut h = harness(app); + assert!(crate::type_transform::frame(h.state_mut()).is_none(), "{tool:?}: no modifier, no frame"); + hold(&mut h, type_command()); + assert!(crate::type_transform::frame(h.state_mut()).is_some(), "{tool:?}: Ctrl over a Type Mask shows the frame"); + hold(&mut h, Modifiers::NONE); + assert!(crate::type_transform::frame(h.state_mut()).is_none(), "{tool:?}: letting go hides it again"); + } +} + +/// Done-when 2: a Ctrl+drag inside the box moves the mask text; committing then leaves the +/// selection at the same size, offset by the drag (reference: (+100, -40) at 100 %). +#[test] +fn ctrl_drag_inside_the_box_moves_the_mask_text_and_the_committed_selection_takes_the_offset() { + // Baseline: the same mask committed without any drag. + let mut base = new_app(Tool::HorizontalTypeMask); + click(&mut base, 100.0, 300.0, Modifiers::NONE); + crate::type_tool::commit_with(&mut base, Modifiers::NONE); + let b0 = selection_bounds(&base).expect("the mask commits as a selection"); + + let mut app = new_app(Tool::HorizontalTypeMask); + click(&mut app, 100.0, 300.0, Modifiers::NONE); + let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer); + let mut h = harness(app); + // Zoom 100 %: the reference drag (+100, -40) screen px is then the same in document units. + set_view(&mut h, 1.0, [400.0, 200.0]); + let zoom = f64::from(h.state().point_zoom()); + hold(&mut h, type_command()); + let f = crate::type_transform::frame(h.state_mut()).expect("the frame with Ctrl held"); + let before = text(h.state(), id); + let a = to_screen(h.state(), [f.state.pivot.x, f.state.pivot.y]); + // The reference drag: (+100, -40) screen pixels at 100 %. + let b = a + vec2(100.0, -40.0); + transform_drag(&mut h, a, b, type_command()); + let after = text(h.state(), id); + let (dx, dy) = (100.0 / zoom, -40.0 / zoom); + assert_affine(after.transform, Affine::translate(dx, dy).mul(&before.transform)); + assert_eq!(after.text, before.text, "the text itself is untouched"); + assert!(h.state().ui.text_edit.as_ref().is_some_and(|ed| ed.mask && ed.layer == id.0), "still the mask session"); + assert!(h.state().ui.type_transform.is_none(), "the capture ended with the release"); + + crate::type_tool::commit_with(h.state_mut(), Modifiers::NONE); + assert!(h.state().ui.text_edit.is_none(), "the commit ends the session"); + let b1 = selection_bounds(h.state()).expect("the committed outline"); + for (got, want) in [ + (f64::from(b1.x0), f64::from(b0.x0) + dx), + (f64::from(b1.y0), f64::from(b0.y0) + dy), + (f64::from(b1.x1), f64::from(b0.x1) + dx), + (f64::from(b1.y1), f64::from(b0.y1) + dy), + ] { + assert!((got - want).abs() < 1.0, "moved selection edge {got} != {want} (+{dx}, {dy})"); + } + assert!((f64::from(b1.x1 - b1.x0) - f64::from(b0.x1 - b0.x0)).abs() < 1.0, "the size is kept"); + assert!((f64::from(b1.y1 - b1.y0) - f64::from(b0.y1 - b0.y0)).abs() < 1.0, "the size is kept"); +} + +/// Done-when 3 (guard, passes before and after): the invisible-layer refusal stays for a NORMAL +/// layer - a hidden ordinary type layer being edited gets no frame even with ⌘/Ctrl held (pattern 14). +#[test] +fn an_invisible_ordinary_type_layer_keeps_todays_refusal() { + let mut app = new_app(Tool::Type); + let id = LayerId(app.run("type.create", json!({"text": "AB", "size": 48, "x": 300, "y": 250})).unwrap()["layer"].as_u64().unwrap()); + app.run("layer.setProps", json!({"layer": id.0, "visible": false})).unwrap(); + // The session over that layer: not a mask, `mask: false`. + app.ui.text_edit = Some(crate::state::TextEdit { layer: id.0, document: None, caret: 1, anchor: 0, session: "s".into(), created: false, mask: false }); + let mut h = harness(app); + hold(&mut h, type_command()); + assert!(crate::type_transform::frame(h.state_mut()).is_none(), "an invisible ordinary layer: no frame"); + assert!(h.state().ui.type_transform.is_none(), "and a hidden layer cannot be moved"); +} + +/// Guard: without the modifier the mask session keeps today's behaviour - no frame at all, so the +/// box's move reach is not armed: a drag beside the mask text never takes the box path, it is the +/// tool's own (the editor commits the session unchanged, and the selection is the plain outline). +/// This is the discriminating guard: with a wrongly armed reach the committed outline would move. +#[test] +fn without_ctrl_a_press_beside_the_mask_text_does_not_move_it() { + // Baseline: the same mask committed without any drag. + let mut base = new_app(Tool::HorizontalTypeMask); + click(&mut base, 100.0, 300.0, Modifiers::NONE); + crate::type_tool::commit_with(&mut base, Modifiers::NONE); + let base_sel = base.session.active().unwrap().doc.selection.clone(); + assert!(base_sel.is_some(), "the baseline commits"); + + let mut app = new_app(Tool::HorizontalTypeMask); + click(&mut app, 100.0, 300.0, Modifiers::NONE); + let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer); + let mut h = harness(app); + let zoom = f64::from(h.state().point_zoom()); + assert!(crate::type_transform::frame(h.state_mut()).is_none(), "no modifier, no frame: no move reach either"); + // Where the move reach would have reached: 20 screen points past the text's right edge. + let shown = text(h.state(), id).cache.expect("the laid-out glyphs").content_bounds(); + let a = to_screen(h.state(), [f64::from(shown.x1) + 20.0 / zoom, f64::from(shown.y0 + shown.y1) / 2.0]); + transform_drag(&mut h, a, a + vec2(60.0, 30.0), Modifiers::NONE); + assert!(h.state().ui.type_transform.is_none(), "the press is the tool's, never the box's"); + let sel = h.state().session.active().unwrap().doc.selection.clone(); + assert!( + sel == base_sel, + "the mask commits unchanged: {:?} vs the plain outline {:?}", + sel.as_ref().map(|s| s.content_bounds()), + base_sel.as_ref().map(|s| s.content_bounds()) + ); +} diff --git a/crates/ui-egui/src/view_sync_tests.rs b/crates/ui-egui/src/view_sync_tests.rs index 11a38ac77b..be36297dd8 100644 --- a/crates/ui-egui/src/view_sync_tests.rs +++ b/crates/ui-egui/src/view_sync_tests.rs @@ -44,3 +44,42 @@ fn every_document_keeps_its_own_view_through_syncs() { assert_eq!(app.ui.views[0].zoom, 3.2, "the first document's view is untouched"); assert_eq!(app.ui.views[1].zoom, 4.0, "the last document's view follows it to its new index"); } + +/// #11325: Zoom In/Out must never use a point right-clicked in another document. +#[test] +fn switching_documents_closes_the_canvas_view_menu() { + for tool in [crate::Tool::Zoom, crate::Tool::Hand] { + let mut app = app_with_two_documents(); + app.ui.tool = tool; + assert!(crate::canvas_tool_menu::open_at(&mut app, tool, Default::default(), egui::pos2(10.0, 10.0), [20.0, 20.0], None)); + assert!(matches!(app.ui.canvas_tool_menu.as_ref().map(|menu| &menu.kind), Some(crate::canvas_tool_menu::MenuKind::View))); + app.sync_views(); + assert!(app.ui.canvas_tool_menu.is_some(), "ordinary sync keeps the menu"); + app.run("layer.new.layer", json!({})).unwrap(); + assert!(app.ui.canvas_tool_menu.is_some(), "an edit in the same document keeps the menu"); + assert!(app.session.set_active(0)); + app.sync_views(); + assert!(app.ui.canvas_tool_menu.is_none(), "a document switch closes the old document's menu"); + } +} + +/// A tab closing can put another document at the same index, or move the menu's own document +/// to another index. Follow its identity, not its slot. +#[test] +fn closing_a_tab_keeps_the_canvas_menu_only_for_its_own_document() { + for close_menu_document in [false, true] { + let mut app = app_with_two_documents(); + if close_menu_document { + assert!(app.session.set_active(0)); + app.sync_views(); + } + app.ui.tool = crate::Tool::Hand; + let document = app.session.active().unwrap().doc.id; + assert!(crate::canvas_tool_menu::open_at(&mut app, crate::Tool::Hand, Default::default(), egui::pos2(10.0, 10.0), [20.0, 20.0], None)); + assert!(matches!(app.ui.canvas_tool_menu.as_ref().map(|menu| &menu.kind), Some(crate::canvas_tool_menu::MenuKind::View))); + app.run("file.close", json!({"document": 0})).unwrap(); + assert_eq!(app.session.active_index(), Some(0), "the survivor occupies the first slot"); + assert_eq!(app.session.active().unwrap().doc.id == document, !close_menu_document); + assert_eq!(app.ui.canvas_tool_menu.is_some(), !close_menu_document, "only a menu for the surviving document stays open"); + } +} diff --git a/docs/context-menu-parity.md b/docs/context-menu-parity.md index f441a2bc81..a04fb890f3 100644 --- a/docs/context-menu-parity.md +++ b/docs/context-menu-parity.md @@ -1,13 +1,13 @@ # Context-menu parity contract -> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-21 · **Change:** minor (Crop tool menu on a pending crop, #6561; Zoom tool menu order, #6005; Type tool menu over committed type, #7324; earlier: Path Selection canvas menu, #1056; pasteboard row: the menu exists, #2462) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-11-04 · **Change:** minor (canvas menus close when the active document changes, #11325; Crop tool menu on a pending crop, #6561; Zoom tool menu order, #6005; Type tool menu over committed type, #7324; earlier: Path Selection canvas menu, #1056; pasteboard row: the menu exists, #2462) · **Target:** Adobe Photoshop 2026 Status: implementation contract, updated 2026-10-09. Scope: canvas, document tabs, and panels. “Right-click” means a secondary pointer click; macOS Control-click should also open the same menu where the platform sends a context-menu gesture. Photoshop changes a context menu with the active tool, selection, and panel item. Adobe documents that principle but does not publish a complete current menu catalog. **Documented** means an Adobe source explicitly names the gesture or action. **Inferred** means a PhotoCraft design target or an item known from a main menu whose presence in a Photoshop context menu still needs a current-product capture. Do not present inferred rows as exact Photoshop menus. [Adobe: panels and menus](https://helpx.adobe.com/photoshop/using/panels-menus.html), [Adobe: shortcuts and context menus](https://helpx.adobe.com/sa_en/photoshop/using/customizing-keyboard-shortcuts.html). ## Dispatch contract 1. Hit-test the target before opening: modal operation/handle, text selection, canvas content, panel row or icon, tab, then empty workspace. A generic canvas menu must not swallow a more specific target. -2. Snapshot the target and selection when the menu opens. A row in an existing multiselection acts on that set; a row outside it becomes the target before its command runs. Apply the same rule to layers, channels, paths, and presets. +2. Snapshot the target and selection when the menu opens. A row in an existing multiselection acts on that set; a row outside it becomes the target before its command runs. Apply the same rule to layers, channels, paths, and presets. Canvas menus close when the active document changes, including when a closed tab leaves another document in its slot (#11325); ordinary edits in the same document keep the menu open. 3. Resolve items from a pure menu model keyed by target kind, active tool, document state, platform, and active operation. The model supplies label, command id, params, enabled state, and reason. Every mutating item dispatches an engine command; view-only items may update shell state. An unavailable feature is disabled with a reason or omitted, never a clickable no-op. 4. Preserve primary-button tool behavior. Secondary click only opens a menu unless a right-button drag gesture or the user's explicit right-erase preference owns the gesture. A drag must not briefly open a menu, and opening a menu must never paint, transform, sample, or commit. 5. Anchor at the pointer and clamp to the viewport; support keyboard context-menu key/Shift+F10 where available, Escape/outside click, separators only between nonempty groups, checked/radio state, keyboard navigation, and screen-reader labels. @@ -100,6 +100,7 @@ Each slice needs pure model tests (including every item dispatching a known comm | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Canvas menus close on an active-document change, so Zoom In/Out cannot reuse another document's clicked point (#11325) | | 2026-10-21 | minor | Crop tool menu on a pending crop (#6561) | | 2026-10-20 | trivial | Zoom tool menu order (#6005) | | 2026-10-18 | minor | Type tool menu over committed type (#7324) | diff --git a/xtask/src/cache_units.rs b/xtask/src/cache_units.rs index 892e3ffc86..5c48c92844 100644 --- a/xtask/src/cache_units.rs +++ b/xtask/src/cache_units.rs @@ -31,6 +31,19 @@ pub fn run(mut cmd: Command, what: &str) -> Result<(), String> { if status.success() { Ok(()) } else { Err(format!("{what}: exited with {status}")) } } +/// Capture non-Cargo output while recording Cargo messages, for a command whose output is data. +pub fn capture_recorded(mut cmd: Command, what: &str, file: &std::path::Path) -> Result, String> { + eprintln!("$ {what}"); + let mut record = OpenOptions::new().create(true).append(true).open(file).map_err(|e| format!("{}: {e}", file.display()))?; + let mut child = cmd.stdout(Stdio::piped()).spawn().map_err(|e| format!("{what}: failed to spawn: {e}"))?; + let stdout = child.stdout.take().expect("piped stdout"); + let mut output = Vec::new(); + let routed = route(BufReader::new(stdout), &mut record, &mut output); + let status = child.wait().map_err(|e| format!("{what}: {e}"))?; + routed.map_err(|e| format!("{what}: reading output: {e}"))?; + if status.success() { Ok(output) } else { Err(format!("{what}: exited with {status}")) } +} + /// Records xtask's own units: `cargo xtask` builds it before it can record anything, and an /// unrecorded unit is trimmed from the entry and rebuilt next run. The build is fresh, so this only /// prints the messages. @@ -73,4 +86,67 @@ mod tests { assert_eq!(String::from_utf8(record).unwrap(), "{\"reason\":\"compiler-artifact\",\"fresh\":true}\n{\"reason\":\"build-finished\",\"success\":true}\n"); assert_eq!(String::from_utf8(out).unwrap(), "running 3 tests\ntest a ... ok\n"); } + + #[test] + fn mixed_nextest_listing_keeps_json_separate_and_rejects_truncation() { + let input = b"{\"reason\":\"compiler-artifact\",\"fresh\":false}\n{\"rust-suites\":{}}\n"; + let (mut record, mut listing) = (Vec::new(), Vec::new()); + route(input.as_slice(), &mut record, &mut listing).unwrap(); + assert_eq!(record, b"{\"reason\":\"compiler-artifact\",\"fresh\":false}\n"); + assert!(serde_json::from_slice::(&listing).is_ok()); + listing.truncate(listing.len() - 3); + assert!(serde_json::from_slice::(&listing).is_err()); + } + + #[test] + fn real_nextest_list_records_build_without_rebuilding() { + if !crate::nextest_available() { + eprintln!("cargo-nextest unavailable; skipping mixed-stream integration test"); + return; + } + let dir = std::env::temp_dir().join(format!("photocraft-cache-units-{}", std::process::id())); + std::fs::create_dir_all(dir.join("src")).unwrap(); + std::fs::write(dir.join("Cargo.toml"), "[package]\nname = \"cache-unit-fixture\"\nversion = \"0.1.0\"\nedition = \"2021\"\n").unwrap(); + std::fs::write(dir.join("src/lib.rs"), "#[test] fn one() {}\n").unwrap(); + let list = || { + let out = crate::cargo() + .current_dir(&dir) + .env("CARGO_TARGET_DIR", dir.join("target")) + .env("CARGO_BUILD_BUILD_DIR", dir.join("target")) + .env("CARGO_NET_OFFLINE", "true") + .env("NEXTEST_PROFILE", "ci") + .args([ + "nextest", + "list", + "--profile", + "default", + "--list-type", + "binaries-only", + "--message-format", + "json", + "--cargo-message-format", + "json-render-diagnostics", + ]) + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + out + }; + for expected_fresh in [false, true] { + let output = list(); + let (mut record, mut listing) = (Vec::new(), Vec::new()); + route(output.stdout.as_slice(), &mut record, &mut listing).unwrap(); + let artifacts: Vec = record + .split(|&b| b == b'\n') + .filter(|line| !line.is_empty()) + .map(|line| serde_json::from_slice(line).unwrap()) + .filter(|message: &serde_json::Value| message["reason"] == "compiler-artifact") + .collect(); + assert!(!artifacts.is_empty()); + assert!(artifacts.iter().all(|message| message["fresh"].as_bool() == Some(expected_fresh))); + let json: serde_json::Value = serde_json::from_slice(&listing).unwrap(); + assert_eq!(json["rust-binaries"].as_object().unwrap().len(), 1); + } + std::fs::remove_dir_all(dir).unwrap(); + } } diff --git a/xtask/src/main.rs b/xtask/src/main.rs index fa1eae5e52..73a9fc8f6d 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -526,16 +526,25 @@ fn build_tests(o: &CiOptions) -> Result<(), String> { } /// `cargo nextest list --profile ci --message-format json` of the test build, with `args`. -fn nextest_list(o: &CiOptions, args: &[&str]) -> Result { +fn nextest_list(o: &CiOptions, args: &[&str], record: bool) -> Result { let mut c = cargo(); c.args(["nextest", "list", "--profile", "ci", "--message-format", "json"]).args(test_build_args(&o.exclude)).args(args); - let what = shown(&c); - eprintln!("$ {what}"); - let out = c.stderr(Stdio::inherit()).output().map_err(|e| format!("{what}: failed to spawn: {e}"))?; - if !out.status.success() { - return Err(format!("{what}: exited with {}", out.status)); + let record = record.then(cache_units::file).flatten(); + if record.is_some() { + c.args(["--cargo-message-format", "json-render-diagnostics"]); } - serde_json::from_slice(&out.stdout).map_err(|e| format!("{what}: bad JSON: {e}")) + let what = shown(&c); + let out = if let Some(file) = record { + cache_units::capture_recorded(c, &what, &file)? + } else { + eprintln!("$ {what}"); + let out = c.stderr(Stdio::inherit()).output().map_err(|e| format!("{what}: failed to spawn: {e}"))?; + if !out.status.success() { + return Err(format!("{what}: exited with {}", out.status)); + } + out.stdout + }; + serde_json::from_slice(&out).map_err(|e| format!("{what}: bad JSON: {e}")) } /// The gate's build job with per-shard archives: builds the tests, lists them, plans which binaries @@ -550,7 +559,7 @@ fn build_shard_archives(o: &CiOptions, dir: &Path, name: &str, shards: usize, gp }); let times = shards::Times::parse(&text, os)?; // The build itself, and every binary it made. - let built = nextest_list(o, &["--list-type", "binaries-only"])?; + let built = nextest_list(o, &["--list-type", "binaries-only"], true)?; let ids: Vec = built.get("rust-binaries").and_then(serde_json::Value::as_object).ok_or("nextest list: no rust-binaries")?.keys().cloned().collect(); // With a GPU shard every binary is listed against the gpu group; otherwise only the split ones. let filter = if gpu_shard { @@ -559,7 +568,7 @@ fn build_shard_archives(o: &CiOptions, dir: &Path, name: &str, shards: usize, gp let split: Vec = shards::binaries_to_list(&ids, ×, shards).iter().map(|b| format!("binary_id(={b})")).collect(); if split.is_empty() { "none()".to_string() } else { split.join(" | ") } }; - let listing = nextest_list(o, &["--run-ignored", "all", "-E", &filter])?; + let listing = nextest_list(o, &["--run-ignored", "all", "-E", &filter], false)?; let (binaries, target) = shards::parse_listing(&listing, gpu_shard)?; let plan = shards::plan(&binaries, ×, shards, gpu_shard)?; eprint!("{}", plan.summary());