From 877bc06a02d4b99b8ea0c62fd36b416766196f49 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 14 Nov 2026 08:46:49 -0800 Subject: [PATCH 01/46] Tests: accept only NotFound after refusing a manifest symlink --- crates/format/tests/it/roundtrip.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/format/tests/it/roundtrip.rs b/crates/format/tests/it/roundtrip.rs index ab74971342..539650778b 100644 --- a/crates/format/tests/it/roundtrip.rs +++ b/crates/format/tests/it/roundtrip.rs @@ -696,7 +696,12 @@ fn directory_save_rejects_manifest_symlink_without_overwriting_target() { assert!(PcraftWriter::new().save_dir(&doc, &dir, &SaveOptions::default()).is_err()); assert_eq!(std::fs::read(&external_manifest).unwrap(), b"keep manifest"); // Refused before any object is written: `tiles/` is missing or empty. - assert_eq!(std::fs::read_dir(dir.join("tiles")).map_or(0, |entries| entries.count()), 0); + let tile_count = match std::fs::read_dir(dir.join("tiles")) { + Ok(entries) => entries.count(), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => 0, + Err(error) => panic!("could not inspect the refused save's tiles: {error}"), + }; + assert_eq!(tile_count, 0); std::fs::remove_dir_all(dir).unwrap(); std::fs::remove_dir_all(outside).unwrap(); From 2957080e93df197d8160ba870929ba4d14b38e55 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 14 Nov 2026 08:59:24 -0800 Subject: [PATCH 02/46] Bound decoded embedded SVG content and report omitted images --- crates/io/src/svg.rs | 54 +++++++++++++++++++++++++++++--------- crates/io/src/svg/tests.rs | 49 +++++++++++++++++++++++++++++++++- 2 files changed, 90 insertions(+), 13 deletions(-) diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 93ad20e856..dd3b30ef9c 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -402,6 +402,13 @@ struct Parsed { /// text while parsing, before any node reaches the conversion, so this is the only place /// that knows why the text is missing. fontless_text: bool, + /// The resolver left images out; an ordinary import must report that lost content. + omitted_images: bool, +} + +fn omitted_images(resolver: &craft_svg::tree::ImageResolver) -> bool { + let usage = resolver.usage(); + usage.raster_limit_images > 0 || usage.svg_limit_images > 0 || usage.invalid_raster_images > 0 || usage.invalid_svg_images > 0 } /// Parses a drawing, `.svgz` included. The XML is inflated and checked here, before the parser @@ -452,7 +459,7 @@ fn parse_with(bytes: &[u8], fonts: fn() -> Arc) -> Resul // An embedded image over a budget was refused by the resolver and is left out of the // tree, so the rest of the drawing still opens (as before the craft-svg migration). // Only the bounded smart-object path refuses the whole drawing for it. - Ok(Parsed { tree, fontless_text }) + Ok(Parsed { tree, fontless_text, omitted_images: omitted_images(&image_resolver) }) }) .map_err(IoError::from) } @@ -556,7 +563,7 @@ fn parse_image_bounded_with( counter.svg_chain = usage.embedded_svg_depth as u64; if usage.raster_limit_images > 0 { counter.error.get_or_insert_with(|| "embedded SVG raster images exceed the decoded pixel budget".into()); - } else if usage.svg_limit_images > 0 && (counter.strict || refusals.over_budget.load(Ordering::Relaxed)) { + } else if refusals.over_budget.load(Ordering::Relaxed) || (counter.strict && usage.svg_limit_images > 0) { counter.error.get_or_insert_with(|| "embedded SVG images exceed the byte or nesting budget".into()); } else if counter.strict && (usage.invalid_raster_images > 0 || usage.invalid_svg_images > 0) { counter.error.get_or_insert_with(|| "can't parse an embedded SVG image".into()); @@ -597,10 +604,23 @@ struct SvgRefusals { /// everything the byte budget had left, and so does a readable image that fits the budget /// only without those charges. Neither is the drawing's content. unread_charges: AtomicUsize, + /// Decoded UTF-8 content, independent of unreadable images' phantom resolver charges. + content_bytes: AtomicUsize, /// Bytes unpacked again to tell those images apart, at most one byte budget per drawing. rechecked: AtomicUsize, } +fn charge_svg_content(bytes: usize, refusals: &SvgRefusals) { + let budget = usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap_or(usize::MAX); + if refusals + .content_bytes + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |used| used.checked_add(bytes).filter(|total| *total <= budget)) + .is_err() + { + refusals.over_budget.store(true, Ordering::Relaxed); + } +} + /// Note in `refusals` what craft-svg will do with an embedded SVG's `data` when its images have /// `used` bytes of the budget: it unpacks the data within what is left, accepts it and charges /// its text (decoded Latin-1 can be longer), or refuses it and charges everything left. Refused @@ -612,26 +632,33 @@ fn note_byte_refusal(data: &[u8], used: usize, refusals: &SvgRefusals) { let left = budget.saturating_sub(used); let unread = refusals.unread_charges.load(Ordering::Relaxed); match craft_svg::svgz::text(data, left) { - Ok(_) => {} + Ok(text) => charge_svg_content(text.len(), refusals), Err(craft_svg::svgz::Error::TooLarge(_)) if unread == 0 => refusals.over_budget.store(true, Ordering::Relaxed), Err(craft_svg::svgz::Error::TooLarge(_)) => { - let content_left = budget.saturating_sub(used.saturating_sub(unread)); + let content_left = budget.saturating_sub(refusals.content_bytes.load(Ordering::Relaxed)); // Plain data is only measured; compressed data is unpacked again. let compressed = data.starts_with(&[0x1f, 0x8b]); let limit = if compressed { content_left.min(budget.saturating_sub(refusals.rechecked.load(Ordering::Relaxed))) } else { content_left }; // Every unpack is charged at least what it unpacked, so together they stay within one // budget; plain data is only measured. - let (unpacked, too_large) = match craft_svg::svgz::inflate(data, limit) { - Ok(std::borrow::Cow::Borrowed(_)) => (0, false), - Ok(std::borrow::Cow::Owned(xml)) => (xml.len(), false), - Err(craft_svg::svgz::Error::Nested(len)) => (len, false), - Err(craft_svg::svgz::Error::TooLarge(_)) => (if compressed { limit } else { 0 }, true), - Err(_) => (limit, false), + let (unpacked, decoded, too_large) = match craft_svg::svgz::inflate(data, limit) { + Ok(xml) => { + // Decode the already-unpacked bytes, never inflate them again. Latin-1 can + // expand in UTF-8, so raw work and decoded content need separate charges. + let decoded = craft_svg::svgz::decode(&xml).ok().map(|text| text.len()); + (if compressed { xml.len() } else { 0 }, decoded, false) + } + Err(craft_svg::svgz::Error::Nested(len)) => (len, None, false), + Err(craft_svg::svgz::Error::TooLarge(_)) => (if compressed { limit } else { 0 }, None, true), + Err(_) => (limit, None, false), }; refusals.rechecked.fetch_add(unpacked, Ordering::Relaxed); if too_large { refusals.over_budget.store(true, Ordering::Relaxed); } else { + if let Some(decoded) = decoded { + charge_svg_content(decoded, refusals); + } refusals.unread_charges.fetch_add(left, Ordering::Relaxed); } } @@ -784,7 +811,7 @@ fn parse_bounded_work_with(bytes: &[u8], max_pixels: u64, strict: bool, fonts: f let counter = budget.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let decoded = max_pixels.min(MAX_RASTER_PIXELS).saturating_sub(counter.pixels); Ok(ParsedWork { - parsed: Parsed { tree, fontless_text: counter.fontless_text }, + parsed: Parsed { tree, fontless_text: counter.fontless_text, omitted_images: omitted_images(&counter.resolver) }, svg_images: counter.svg_images, svg_chain: counter.svg_chain, decoded, @@ -1078,11 +1105,14 @@ fn import_parsed_with_limits( reject_cache_overflow: bool, pixel_budget: u64, ) -> Result { - let Parsed { tree, fontless_text } = parsed; + let Parsed { tree, fontless_text, omitted_images } = parsed; let mut warnings = Vec::new(); if fontless_text { warnings.push("SVG: the text needs a font and none is installed, so it was dropped".to_string()); } + if omitted_images { + warnings.push("SVG: some embedded images were omitted because they exceeded an import limit or could not be read".to_string()); + } let cv = canvas(&tree, &mut warnings); check_filter_cost(&tree, cv.scale)?; let nodes = count_nodes(tree.root(), max_cached_pixels.is_some()); diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index 0979ffc2ff..e6d4b973dd 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -1144,7 +1144,8 @@ fn a_latin1_embedded_svg_that_decodes_past_the_budget_is_refused() { latin1.extend_from_slice(b"-->"); let wide = embedded_image("image/svg+xml", &gzip(&latin1)); let small = embedded_image("image/svg+xml", b""); - assert!(parse_bounded(image_svg(&wide).as_bytes(), MAX_RASTER_PIXELS).is_ok(), "on its own it parses"); + let error = parse_bounded(image_svg(&wide).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); + assert!(error.to_string().contains("byte or nesting budget"), "{error}"); let error = parse_bounded(image_svg(&format!("{wide}{small}")).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); assert!(error.to_string().contains("byte or nesting budget"), "{error}"); } @@ -1562,3 +1563,49 @@ fn every_raster_refusal_reason_is_reported_once() { assert_eq!(dropped("rasterising limit"), 1, "{:?}", result.warnings); assert_eq!(dropped("too much memory"), 1, "{:?}", result.warnings); } + + +/// Decoded content remains bounded even when an unreadable image spent the resolver's budget. +#[test] +fn damaged_images_do_not_hide_decoded_text_byte_overruns() { + let budget = usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap(); + let svg = b""; + let compressed = gzip(svg); + let damaged = embedded_image("image/svg+xml", &compressed[..compressed.len() / 2]); + let small = embedded_image("image/svg+xml", svg); + let latin1_image = |raw_bytes| { + let mut latin1 = b""); + embedded_image("image/svg+xml", &gzip(&latin1)) + }; + let fitting = latin1_image(budget * 5 / 16); // About 10 MiB decoded; about 5 MiB of inflation work. + assert!(parse_bounded(image_svg(&fitting).as_bytes(), MAX_RASTER_PIXELS).is_ok()); + assert!(parse_bounded(image_svg(&format!("{damaged}{fitting}{small}")).as_bytes(), MAX_RASTER_PIXELS).is_ok(), "unreadable content may still be omitted"); + let wide = latin1_image(budget * 5 / 8); // About 20 MiB decoded, though inflation fits 16 MiB. + for images in [format!("{damaged}{wide}{small}"), format!("{damaged}{fitting}{fitting}")] { + let error = parse_bounded(image_svg(&images).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); + assert!(error.to_string().contains("byte or nesting budget"), "{error}"); + } +} + +/// Ordinary import keeps the rest of the drawing, but reports omitted image content once. +#[test] +fn imports_warn_when_embedded_images_are_omitted() { + let rect = ""; + let oversized = embedded_image("image/png", &png_dimensions(u32::MAX, u32::MAX)); + let svg = image_svg(&format!("{oversized}{oversized}{rect}")); + let imported = import_svg("ordinary", svg.as_bytes()).unwrap(); + let omission_warnings = |imported: &ImportResult| imported.warnings.iter().filter(|warning| warning.contains("embedded images were omitted")).count(); + assert_eq!(omission_warnings(&imported), 1, "{:?}", imported.warnings); + assert!(!imported.document.layers.is_empty(), "the readable drawing still opens"); + let clean = import_svg("clean", image_svg(rect).as_bytes()).unwrap(); + assert_eq!(omission_warnings(&clean), 0, "{:?}", clean.warnings); + let compressed = gzip(b""); + let damaged = embedded_image("image/svg+xml", &compressed[..compressed.len() / 2]); + let svg = image_svg(&format!("{damaged}{rect}")); + let bounded = import_svg_bounded("bounded", svg.as_bytes(), MAX_RASTER_PIXELS).unwrap(); + assert_eq!(omission_warnings(&bounded), 1, "{:?}", bounded.warnings); + assert!(!bounded.document.layers.is_empty()); + assert!(parse_bounded_work_with(svg.as_bytes(), MAX_RASTER_PIXELS, true, fonts).is_err(), "stored previews must still be complete"); +} From 5044737b8de843d41bfeb606c620abf89586b18e Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 14 Nov 2026 09:04:44 -0800 Subject: [PATCH 03/46] Tests: prove damaged image omissions and retained SVG drawing content --- crates/io/src/svg/tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index e6d4b973dd..4e0143923e 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -1573,6 +1573,8 @@ fn damaged_images_do_not_hide_decoded_text_byte_overruns() { let compressed = gzip(svg); let damaged = embedded_image("image/svg+xml", &compressed[..compressed.len() / 2]); let small = embedded_image("image/svg+xml", svg); + let omitted = parse_bounded(image_svg(&format!("{damaged}{damaged}{small}")).as_bytes(), MAX_RASTER_PIXELS).unwrap(); + assert!(!omitted.tree.root().has_children(), "both damaged images and the later small image stay omitted"); let latin1_image = |raw_bytes| { let mut latin1 = b""); - let wide = embedded_image("image/svg+xml", &gzip(&latin1)); - let small = embedded_image("image/svg+xml", b""); - let error = parse_bounded(image_svg(&wide).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); - assert!(error.to_string().contains("byte or nesting budget"), "{error}"); - let error = parse_bounded(image_svg(&format!("{wide}{small}")).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); - assert!(error.to_string().contains("byte or nesting budget"), "{error}"); -} - -/// After a damaged image spent the budget, images refused for bytes are unpacked again to tell -/// whether they are too large themselves, but at most one budget's worth in all: past that the -/// drawing is refused rather than unpacking each one. -#[test] -fn images_after_a_damaged_svgz_are_unpacked_again_within_one_budget() { - let svg = ""; - let compressed = gzip(svg.as_bytes()); - let damaged = embedded_image("image/svg+xml", &compressed[..compressed.len() / 2]); - let mut large = b"".to_vec(); - large.resize(usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap() * 5 / 8, b' '); - large.extend_from_slice(b""); - let large = embedded_image("image/svg+xml", &gzip(&large)); - assert!(parse_bounded(image_svg(&format!("{damaged}{large}")).as_bytes(), MAX_RASTER_PIXELS).is_ok(), "one is left out"); - let error = parse_bounded(image_svg(&format!("{damaged}{large}{large}")).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); - assert!(error.to_string().contains("byte or nesting budget"), "{error}"); -} - -/// Each image unpacked again is charged at least what was unpacked, refused ones included, so -/// however many follow a damaged image the unpacking adds up to one budget, not one each. -#[test] -fn unpacking_images_again_adds_up_to_one_budget_however_many_there_are() { - let budget = usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap(); - let mut huge = b"".to_vec(); - huge.resize(budget * 2, b' '); - huge.extend_from_slice(b""); - let huge = gzip(&huge); - // A damaged image was charged the whole budget; every later image is refused for size. - let refusals = SvgRefusals { unread_charges: AtomicUsize::new(budget), ..SvgRefusals::default() }; - for _ in 0..64 { - note_byte_refusal(&huge, budget, &refusals); - assert!(refusals.over_budget.load(Ordering::Relaxed), "too large without the charges"); - assert_eq!(refusals.rechecked.load(Ordering::Relaxed), budget); - } -} - /// Only a stored display preview is strict about an embedded image it can't read; an edited SVG /// saved back from an external editor leaves it out, as placement does. #[test] @@ -1570,50 +1443,3 @@ fn every_raster_refusal_reason_is_reported_once() { assert_eq!(dropped("rasterising limit"), 1, "{:?}", result.warnings); assert_eq!(dropped("too much memory"), 1, "{:?}", result.warnings); } - -/// Decoded content remains bounded even when an unreadable image spent the resolver's budget. -#[test] -fn damaged_images_do_not_hide_decoded_text_byte_overruns() { - let budget = usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap(); - let svg = b""; - let compressed = gzip(svg); - let damaged = embedded_image("image/svg+xml", &compressed[..compressed.len() / 2]); - let small = embedded_image("image/svg+xml", svg); - let omitted = parse_bounded(image_svg(&format!("{damaged}{damaged}{small}")).as_bytes(), MAX_RASTER_PIXELS).unwrap(); - assert!(!omitted.tree.root().has_children(), "both damaged images and the later small image stay omitted"); - let latin1_image = |raw_bytes| { - let mut latin1 = b""); - embedded_image("image/svg+xml", &gzip(&latin1)) - }; - let fitting = latin1_image(budget * 5 / 16); // About 10 MiB decoded; about 5 MiB of inflation work. - assert!(parse_bounded(image_svg(&fitting).as_bytes(), MAX_RASTER_PIXELS).is_ok()); - assert!(parse_bounded(image_svg(&format!("{damaged}{fitting}{small}")).as_bytes(), MAX_RASTER_PIXELS).is_ok(), "unreadable content may still be omitted"); - let wide = latin1_image(budget * 5 / 8); // About 20 MiB decoded, though inflation fits 16 MiB. - for images in [format!("{damaged}{wide}{small}"), format!("{damaged}{fitting}{fitting}")] { - let error = parse_bounded(image_svg(&images).as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); - assert!(error.to_string().contains("byte or nesting budget"), "{error}"); - } -} - -/// Ordinary import keeps the rest of the drawing, but reports omitted image content once. -#[test] -fn imports_warn_when_embedded_images_are_omitted() { - let rect = ""; - let oversized = embedded_image("image/png", &png_dimensions(u32::MAX, u32::MAX)); - let svg = image_svg(&format!("{oversized}{oversized}{rect}")); - let imported = import_svg("ordinary", svg.as_bytes()).unwrap(); - let omission_warnings = |imported: &ImportResult| imported.warnings.iter().filter(|warning| warning.contains("embedded images were omitted")).count(); - assert_eq!(omission_warnings(&imported), 1, "{:?}", imported.warnings); - assert_eq!(photocraft_compose::flatten(&imported.document).to_rgba8().pixels, vec![255, 0, 0, 255], "the readable red rectangle is retained"); - let clean = import_svg("clean", image_svg(rect).as_bytes()).unwrap(); - assert_eq!(omission_warnings(&clean), 0, "{:?}", clean.warnings); - let compressed = gzip(b""); - let damaged = embedded_image("image/svg+xml", &compressed[..compressed.len() / 2]); - let svg = image_svg(&format!("{damaged}{rect}")); - let bounded = import_svg_bounded("bounded", svg.as_bytes(), MAX_RASTER_PIXELS).unwrap(); - assert_eq!(omission_warnings(&bounded), 1, "{:?}", bounded.warnings); - assert_eq!(photocraft_compose::flatten(&bounded.document).to_rgba8().pixels, vec![255, 0, 0, 255], "the bounded import retains the red rectangle"); - assert!(parse_bounded_work_with(svg.as_bytes(), MAX_RASTER_PIXELS, true, fonts).is_err(), "stored previews must still be complete"); -} diff --git a/crates/raw/src/develop.rs b/crates/raw/src/develop.rs index e43036800a..6254c2f877 100644 --- a/crates/raw/src/develop.rs +++ b/crates/raw/src/develop.rs @@ -87,7 +87,7 @@ pub struct Developed { pub warnings: Vec, } -/// Linearization + black/white scaling for one sample (pre white balance), without clipping. +/// Linearization + black/white scaling for one sample (pre white balance), 0..1. pub(crate) struct Scale<'a> { s: &'a Sensor, lin: Option<&'a [u16]>, @@ -115,9 +115,7 @@ impl<'a> Scale<'a> { let black = s.black.at(x.saturating_sub(s.active.x), y.saturating_sub(s.active.y), sample, s.samples); let white = s.white[sample.min(2)]; let range = white - black; - // Floating-point sensor levels use source units: a valid white-minus-black - // range may be smaller than one. Only invalid or nonpositive ranges fail. - if !range.is_finite() || range <= 0.0 { + if range.is_nan() || range < 1.0 { return 0.0; } let n = (v - black) / range; @@ -191,7 +189,7 @@ fn fill_samples(row: &mut [f32], raw: impl Iterator, table: &[[ phase = if phase + 1 == table.len() { 0 } else { phase + 1 }; for k in 0..3 { let (black, range) = t[k]; - let n = if !range.is_finite() || range <= 0.0 { + let n = if range.is_nan() || range < 1.0 { 0.0 } else { let n = (lin(raw[k]) - black) / range; @@ -403,45 +401,32 @@ fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result> = (0..period) + let k: Vec<(f32, f32)> = (0..period) .map(|p| { let x = c.x + p; let black = bl.at(x.saturating_sub(s.active.x), y.saturating_sub(s.active.y), 0, 1); let range = s.white[0] - black; - // A fractional range can overflow an inverse gain even when the scalar - // quotient is finite. Keep its division and non-finite fallback together. - if range.is_finite() && range > 0.0 && range < 1.0 { - return None; - } // A non-finite black (a BlackLevel DOUBLE beyond f32) gives 0, as // `Scale::value` does, instead of (raw - inf) * 0 = NaN. if !(range >= 1.0 && black.is_finite()) { - return Some((0.0, 0.0)); + return (0.0, 0.0); } - Some((black, mult[usize::from(cfa.color(x, y)).min(2)] / range)) + (black, mult[usize::from(cfa.color(x, y)).min(2)] / range) }) .collect(); - if let Some(k) = k { - let src = &s.data[y * s.width + c.x..y * s.width + c.x + w]; - let ks = k.iter().cycle(); - match &sc.lin { - None => { - for ((v, &raw), &(black, gain)) in row.iter_mut().zip(src).zip(ks) { - *v = ((f32::from(raw) - black) * gain).clamp(0.0, 1.0); - } - } - Some(l) => { - for ((v, &raw), &(black, gain)) in row.iter_mut().zip(src).zip(ks) { - let lin = f32::from(l.get(usize::from(raw)).or_else(|| l.last()).copied().unwrap_or(raw)); - *v = ((lin - black) * gain).clamp(0.0, 1.0); - } + let src = &s.data[y * s.width + c.x..y * s.width + c.x + w]; + let ks = k.iter().cycle(); + match &sc.lin { + None => { + for ((v, &raw), &(black, gain)) in row.iter_mut().zip(src).zip(ks) { + *v = ((f32::from(raw) - black) * gain).clamp(0.0, 1.0); } } - } else { - for (i, v) in row.iter_mut().enumerate() { - let x = c.x + i; - let ch = usize::from(cfa.color(x, y)).min(2); - *v = (sc.value(x, y, 0) * mult[ch]).clamp(0.0, 1.0); + Some(l) => { + for ((v, &raw), &(black, gain)) in row.iter_mut().zip(src).zip(ks) { + let lin = f32::from(l.get(usize::from(raw)).or_else(|| l.last()).copied().unwrap_or(raw)); + *v = ((lin - black) * gain).clamp(0.0, 1.0); + } } } } else { @@ -1191,178 +1176,4 @@ mod tests { assert_eq!(px(&orient(src.clone(), 3, 2, 5).0), vec![0, 3, 1, 4, 2, 5]); assert_eq!(px(&orient(src, 3, 2, 7).0), vec![5, 2, 4, 1, 3, 0]); } - - mod scale_review_tests { - use super::*; - - fn float_sensor(values: &[f32], black: f32, white: f32) -> Sensor { - let mut sensor = test_sensor(values.len(), 1, None, 1); - sensor.data.clear(); - sensor.float_data = Some(values.to_vec()); - sensor.black = crate::BlackLevels::uniform(black); - sensor.white = [white; 3]; - sensor.tone_curve.clear(); - sensor - } - - #[test] - fn fractional_float_levels_normalize_exactly_without_early_clipping() { - for (black, white, values, expected) in [ - (0., 0.5, vec![-0.25, 0., 0.125, 0.25, 0.5, 0.75], vec![-0.5, 0., 0.25, 0.5, 1., 1.5]), - (0.25, 0.75, vec![0., 0.25, 0.5, 0.75, 1.], vec![-0.5, 0., 0.5, 1., 1.5]), - ] { - let sensor = float_sensor(&values, black, white); - let scale = Scale::new(&sensor); - let actual: Vec<_> = (0..values.len()).map(|x| scale.value(x, 0, 0)).collect(); - assert_eq!(actual, expected); - let mut row = vec![0.; values.len() * 3]; - fill_linear_row(&scale, &[1.; 3], 0, 0, &mut row); - let clipped: Vec<_> = expected.iter().flat_map(|value| [value.clamp(0., 1.); 3]).collect(); - assert_eq!(row, clipped, "clipping remains at the existing develop boundary"); - } - } - - #[test] - fn invalid_ranges_and_nonfinite_samples_keep_the_existing_zero_fallback() { - for (black, white) in - [(0., 0.), (0.5, 0.25), (0., f32::NAN), (0., f32::INFINITY), (0., f32::NEG_INFINITY), (f32::NAN, 0.5), (f32::INFINITY, f32::INFINITY)] - { - let sensor = float_sensor(&[0.25], black, white); - assert_eq!(Scale::new(&sensor).value(0, 0, 0), 0.); - } - let sensor = float_sensor(&[f32::NAN, f32::INFINITY, f32::NEG_INFINITY], 0., 0.5); - for x in 0..3 { - assert_eq!(Scale::new(&sensor).value(x, 0, 0), 0.); - } - } - - #[test] - fn integer_unit_ranges_black_subtraction_and_linearization_remain_unchanged() { - let mut sensor = test_sensor(3, 1, None, 1); - sensor.data = vec![0, 1, 2]; - sensor.black = crate::BlackLevels::uniform(0.); - sensor.white = [1.; 3]; - assert_eq!((0..3).map(|x| Scale::new(&sensor).value(x, 0, 0)).collect::>(), [0., 1., 2.]); - sensor.data = vec![64, 1024, 4000]; - sensor.black = crate::BlackLevels::uniform(64.); - sensor.white = [4000.; 3]; - assert_eq!((0..3).map(|x| Scale::new(&sensor).value(x, 0, 0)).collect::>(), [0., 960. / 3936., 1.]); - sensor.data = vec![0, 1, 2]; - sensor.linearization = Some(vec![0, 64, 128]); - sensor.black = crate::BlackLevels::uniform(0.); - sensor.white = [128.; 3]; - assert_eq!((0..3).map(|x| Scale::new(&sensor).value(x, 0, 0)).collect::>(), [0., 0.5, 1.]); - - // Integer codes may have fractional metadata levels too. A zero delta changes - // dispatch only: both contiguous paths must retain the literal scalar results. - for (black, white, expected) in [ - (0.5, 1., [0., 1., 1.]), - (0., 2., [0., 0.5, 1.]), - (1., 1., [0.; 3]), - (1., 0.5, [0.; 3]), - (0., f32::NAN, [0.; 3]), - (0., f32::INFINITY, [0.; 3]), - (-1e-40, 0., [1., 0., 0.]), - ] { - for samples in [1, 3] { - let mut sensor = test_sensor(3, 1, None, samples); - sensor.data = [0, 1, 2].into_iter().flat_map(|raw| vec![raw; samples]).collect(); - sensor.black = crate::BlackLevels::uniform(black); - sensor.white = [white; 3]; - let mut row = vec![0.; 9]; - fill_linear_row(&Scale::new(&sensor), &[1.; 3], 0, 0, &mut row); - let wanted: Vec<_> = expected.into_iter().flat_map(|value| [value; 3]).collect(); - assert_eq!(row, wanted, "contiguous {samples} samples, black {black}, white {white}"); - for (x, value) in expected.into_iter().enumerate() { - assert_eq!(Scale::new(&sensor).value(x, 0, 0).clamp(0., 1.), value); - } - sensor.black.delta_h = vec![0.; 3]; - fill_linear_row(&Scale::new(&sensor), &[1.; 3], 0, 0, &mut row); - assert_eq!(row, wanted, "zero deltas preserve the same values"); - } - } - - // The periodic CFA optimization must also agree with scalar division, including - // a subnormal range whose precomputed reciprocal would overflow to infinity. - let options = DevelopOptions { demosaic: Demosaic::Bilinear, white_balance: WhiteBalance::Multipliers([1.; 3]), ..Default::default() }; - for (black, white, raw, expected) in [ - (0.5, 1., 1, 1.), - (0., 2., 1, 0.5), - (1., 1., 1, 0.), - (1., 0.5, 1, 0.), - (0., f32::NAN, 1, 0.), - (0., f32::INFINITY, 1, 0.), - (-1e-40, 0., 0, 1.), - (-1e-40, 0., 1, 0.), - ] { - let mut sensor = test_sensor(8, 8, crate::Cfa::bayer("RGGB"), 1); - sensor.data.fill(raw); - sensor.black = crate::BlackLevels::uniform(black); - sensor.white = [white; 3]; - sensor.tone_curve.clear(); - assert_eq!(Scale::new(&sensor).value(0, 0, 0).clamp(0., 1.), expected); - let mut reference = sensor.clone(); - reference.data.fill((expected * 2.) as u16); - reference.black = crate::BlackLevels::uniform(0.); - reference.white = [2.; 3]; - for fused in [false, true] { - let wanted = develop(&reference, &options, fused).unwrap().rgb; - assert_eq!(develop(&sensor, &options, fused).unwrap().rgb, wanted, "CFA black {black}, white {white}, raw {raw}"); - let mut fallback = sensor.clone(); - fallback.black.delta_h = vec![0.; sensor.width]; - assert_eq!(develop(&fallback, &options, fused).unwrap().rgb, wanted, "CFA zero deltas change dispatch only"); - } - } - } - - /// Independent TIFF/DNG strip layout: three little-endian IEEE754 binary32 - /// monochrome samples, with explicit fractional WhiteLevel and no calibration. - fn fractional_white_dng() -> Vec { - use crate::testgen::{TiffBuilder, Val}; - let mut file = TiffBuilder::default(); - let pixels = file.blob([0f32, 0.25, 0.5].iter().flat_map(|value| value.to_le_bytes()).collect()); - let image = file.ifd(vec![ - (256, Val::Long(vec![3])), - (257, Val::Long(vec![1])), - (258, Val::Short(vec![32])), - (259, Val::Short(vec![1])), - (262, Val::Short(vec![34892])), - (273, Val::Blobs(vec![pixels])), - (277, Val::Short(vec![1])), - (278, Val::Long(vec![1])), - (279, Val::Long(vec![12])), - (339, Val::Short(vec![3])), - (50706, Val::Byte(vec![1, 4, 0, 0])), - (50714, Val::Double(vec![0.])), - (50717, Val::Double(vec![0.5])), - ]); - file.chain = vec![image]; - file.build() - } - - #[test] - fn fractional_white_float_dng_develops_black_half_gray_and_white_instead_of_all_black() { - let bytes = fractional_white_dng(); - let sensor = crate::decode(&bytes, &crate::Limits::default()).unwrap(); - assert_eq!(sensor.float_data.as_deref(), Some([0., 0.25, 0.5].as_slice())); - assert_eq!(sensor.white, [0.5; 3]); - assert!(sensor.is_monochrome()); - let options = DevelopOptions { white_balance: WhiteBalance::Multipliers([1.; 3]), ..Default::default() }; - let developed = crate::develop(&bytes, &options).unwrap(); - assert_eq!((developed.width, developed.height), (3, 1)); - assert_eq!(developed.rgb.len(), 9); - for (pixel, expected) in developed.rgb.as_chunks::<3>().0.iter().zip([0u16, 44590, 65535]) { - // Half linear gray is 0.5^(1/1.8), with at most one output code - // of rounding/interpolation in the existing gamma-1.8 LUT. - if expected == 0 || expected == u16::MAX { - assert!(pixel.iter().all(|actual| *actual == expected), "{pixel:?} vs {expected}"); - } else { - assert!(pixel.iter().all(|actual| actual.abs_diff(expected) <= 1), "{pixel:?} vs {expected}"); - } - } - let mut broken = sensor; - broken.float_data.as_mut().unwrap().pop(); - assert!(matches!(develop_sensor(&broken, &options), Err(RawError::Malformed(_))), "a truncated buffer remains a data error, never silently black"); - } - } } diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index f1c144ce22..f0d82391e8 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -184,13 +184,8 @@ pub fn decode(bytes: &[u8], limits: &Limits) -> Result { let mut shared_limits = craft_raw::Limits::default(); shared_limits.max_samples = max_samples; let info = craft_raw::probe_info_with(bytes, &shared_limits).map_err(shared_error)?; - // A three-component sample allowance is not a pixel allowance: a CFA plane - // must still obey the caller's max_pixels before any sample allocation. - limits.check(info.width as u64, info.height as u64, (info.cpp as u64).saturating_mul(4))?; - // The shared parser supports additional component layouts; PhotoCraft's developer - // currently accepts only one CFA/monochrome plane or three RGB planes. - if !matches!(info.cpp, 1 | 3) { - return Err(RawError::unsupported(format!("{} samples per pixel", info.cpp))); + if info.width > limits.max_width as usize || info.height > limits.max_height as usize { + return Err(RawError::LimitExceeded(format!("dimensions {}×{} exceed {}×{}", info.width, info.height, limits.max_width, limits.max_height))); } let image = craft_raw::decode_with(bytes, &shared_limits).map_err(shared_error)?; Ok(crate::shared::adapt(image)) @@ -218,17 +213,3 @@ pub fn develop(bytes: &[u8], opts: &DevelopOptions) -> Result Vec { fn warnings(image: &craft_raw::RawImage) -> Vec { let mut out = Vec::new(); - if image.notices.default_crop_adjusted { - out.push("raw default crop was invalid, incomplete or out-of-range; adjusted within the active area".into()); - } - if image.notices.assumed_cfa { - out.push("raw colour filter phase (Bayer phase) was not recorded or recognized; the decoder's fallback pattern was used".into()); - } - // Unknown means the decoder has not annotated provenance; it does not mean - // the file omitted its levels. Report only an explicit fallback decision. - if image.format != craft_raw::RawFormat::Dng { - if image.level_sources.black == craft_raw::LevelSource::Fallback { - out.push("raw black level not recorded in a documented tag; assumed default".into()); - } - if image.level_sources.white == craft_raw::LevelSource::Fallback { - out.push("raw white level not recorded in a documented tag; assumed full sample range".into()); - } - } for op in image.opcodes.list1.iter().chain(&image.opcodes.list2).chain(&image.opcodes.list3) { if !matches!(op, craft_raw::Opcode::GainMap { .. } | craft_raw::Opcode::MapPolynomial { .. }) { out.push("some raw correction opcodes are not applied by PhotoCraft".to_string()); break; } } - if image.notices.gain_table_omitted || image.color.profile.gain_table_map.is_some() { - out.push("the raw camera profile's ProfileGainTableMap is not applied by PhotoCraft".to_string()); + if image.color.profile.gain_table_map.is_some() { + out.push("the raw camera profile's gain table map is not applied by PhotoCraft".to_string()); } out } @@ -146,15 +130,6 @@ pub(crate) fn adapt(image: craft_raw::RawImage) -> Sensor { as_shot_white_xy: image.color.as_shot_white_xy, }; let tone_curve = image.color.profile.tone_curve.map_or_else(Vec::new, |c| c.points); - // Non-DNG TIFF/EP bodies can state their balance through AsShotNeutral. - // Keep the public camera-WB field populated without changing DNG color policy. - let camera_wb = image.wb_multipliers.map(|v| v.map(f64::from)).or_else(|| { - (image.format != craft_raw::RawFormat::Dng) - .then_some(image.color.as_shot_neutral) - .flatten() - .filter(|values| values.iter().all(|value| value.is_finite() && *value > 0.0 && (1.0 / value).is_finite())) - .map(|values| values.map(|value| 1.0 / value)) - }); let (data, float_data) = match image.data { craft_raw::RawData::U16(v) => (v, None), craft_raw::RawData::F32(v) => (Vec::new(), Some(v)), @@ -162,7 +137,7 @@ pub(crate) fn adapt(image: craft_raw::RawImage) -> Sensor { let mut sensor = Sensor { format: format(image.format), make: image.camera.make, - model: image.camera.model.or(image.camera.unique_model), + model: image.camera.unique_model.or(image.camera.model), width: image.width, height: image.height, samples: image.cpp, @@ -175,7 +150,7 @@ pub(crate) fn adapt(image: craft_raw::RawImage) -> Sensor { active, crop, color, - camera_wb, + camera_wb: image.wb_multipliers.map(|v| v.map(f64::from)), orientation: image.orientation.to_exif(), baseline_exposure: image.color.baseline_exposure, gain_maps, @@ -185,90 +160,8 @@ pub(crate) fn adapt(image: craft_raw::RawImage) -> Sensor { warnings, }; crate::cameras::apply(&mut sensor, image.bits); - // DNG's declared white can exceed the stored clipping plateau. Other raw - // decoders have already chosen their camera-specific or measured levels; - // their decoded samples must not be silently rescaled a second time. - if sensor.float_data.is_none() && sensor.format == RawFormat::Dng { + if sensor.float_data.is_none() { sensor.lift_clipped_samples(); } sensor } - -#[cfg(test)] -mod tests { - use super::*; - - fn raw_image() -> craft_raw::RawImage { - let mut spec = crate::testgen::DngSpec::cfa(64, 64, (0..64 * 64).map(|i| (528 + ((i % 64) * 60 + (i / 64) * 7) as u16 % 4000).min(3567)).collect()); - spec.black = vec![528]; - spec.white = 4095; - let mut image = craft_raw::decode_with(&spec.build(), &Default::default()).unwrap(); - image.camera.make = None; - image.camera.model = None; - image.camera.unique_model = None; - image - } - - #[test] - fn only_declared_fallback_level_provenance_produces_missing_level_notices() { - let mut image = raw_image(); - image.format = craft_raw::RawFormat::Nef; - for source in - [craft_raw::LevelSource::Unknown, craft_raw::LevelSource::Metadata, craft_raw::LevelSource::MaskedPixels, craft_raw::LevelSource::Inferred] - { - image.level_sources.black = source; - image.level_sources.white = source; - assert!(warnings(&image).iter().all(|warning| !warning.contains("level")), "{source:?}"); - } - image.level_sources.black = craft_raw::LevelSource::Fallback; - image.level_sources.white = craft_raw::LevelSource::Fallback; - let notices = warnings(&image); - assert!(notices.iter().any(|warning| warning.contains("black level"))); - assert!(notices.iter().any(|warning| warning.contains("white level"))); - image.format = craft_raw::RawFormat::Dng; - assert!(warnings(&image).iter().all(|warning| !warning.contains("level")), "DNG's documented defaults are not missing camera metadata"); - } - - #[test] - fn non_dng_decode_preserves_samples_while_dng_clipping_policy_still_applies() { - let image = raw_image(); - let craft_raw::RawData::U16(stored) = &image.data else { panic!("integer fixture") }; - let original = stored.clone(); - let mut other = image.clone(); - other.format = craft_raw::RawFormat::Nef; - assert_eq!(adapt(other).data, original, "camera-specific levels must not trigger a second sample rewrite"); - let dng = adapt(image); - assert_ne!(dng.data, original, "independent early saturation fixture exercises DNG lifting"); - assert!(dng.data.iter().zip(original).all(|(actual, source)| *actual == source || *actual == 4095)); - } - - #[test] - fn non_dng_as_shot_neutral_populates_camera_balance_and_model_keeps_its_own_identity() { - let mut image = raw_image(); - image.format = craft_raw::RawFormat::CfaTiff; - image.camera.model = Some("X2D II 100C".into()); - image.camera.unique_model = Some("Hasselblad X2D II 100C".into()); - image.wb_multipliers = None; - image.color.as_shot_neutral = Some([0.375, 1., 0.617]); - let sensor = adapt(image.clone()); - assert_eq!(sensor.model.as_deref(), Some("X2D II 100C")); - assert_eq!(sensor.camera_wb, Some([1. / 0.375, 1., 1. / 0.617])); - image.color.as_shot_neutral = Some([0., 1., f64::NAN]); - assert_eq!(adapt(image).camera_wb, None, "invalid neutral must not create nonfinite balance"); - } - - #[test] - fn decoder_notices_remain_visible_without_inventing_loss_for_absent_metadata() { - let mut image = raw_image(); - image.notices = Default::default(); - assert!(warnings(&image).is_empty()); - image.notices.default_crop_adjusted = true; - assert!(warnings(&image).iter().any(|warning| warning.contains("default crop") && warning.contains("out-of-range"))); - image.notices.default_crop_adjusted = false; - image.notices.assumed_cfa = true; - assert!(warnings(&image).iter().any(|warning| warning.contains("colour filter phase") && warning.contains("Bayer phase"))); - image.notices.assumed_cfa = false; - image.notices.gain_table_omitted = true; - assert!(warnings(&image).iter().any(|warning| warning.contains("ProfileGainTableMap"))); - } -} diff --git a/crates/raw/src/testgen/canon.rs b/crates/raw/src/testgen/canon.rs index 19b5152376..2c4ad54f96 100644 --- a/crates/raw/src/testgen/canon.rs +++ b/crates/raw/src/testgen/canon.rs @@ -194,8 +194,7 @@ impl Cr2SrawSpec { // ---------------------------------------------------------------- TIFF/EP /// A synthetic uncompressed TIFF/EP raw (NEF / ARW-like): IFD0 with Make, the -/// CFA image in a SubIFD with 16-bit samples. An explicit Make in -/// `extra_raw_tags` overrides the `make` fallback argument. +/// CFA image in a SubIFD with 16-bit samples. pub fn tiff_ep(make: &str, width: usize, height: usize, data: &[u16], cfa: [u8; 4], bits: u16, extra_raw_tags: Vec<(u16, Val)>) -> Vec { let mut t = TiffBuilder::default(); let strip = t.blob(data.iter().flat_map(|v| v.to_le_bytes()).collect()); @@ -213,34 +212,21 @@ pub fn tiff_ep(make: &str, width: usize, height: usize, data: &[u16], cfa: [u8; (33421, Val::Short(vec![2, 2])), (33422, Val::Byte(cfa.to_vec())), ]; - // Make and Model belong to IFD0, where readers look for them; anything else is raw-IFD data. - let (mut ifd0_tags, raw_tags): (Vec<_>, Vec<_>) = extra_raw_tags.into_iter().partition(|(tag, _)| matches!(tag, 271 | 272)); - // Write a single Make. The first explicit IFD0 Make is the caller's vendor identity; - // otherwise use the argument as the fixture's fallback identity. - let make_tag = if let Some(index) = ifd0_tags.iter().position(|(tag, _)| *tag == 271) { - let make_tag = ifd0_tags.remove(index); - ifd0_tags.retain(|(tag, _)| *tag != 271); - make_tag - } else { - (271, Val::Ascii(make.into())) - }; - raw.extend(raw_tags); + raw.extend(extra_raw_tags); let raw_ifd = t.ifd(raw); let thumb = t.blob(vec![128; 12]); - let mut ifd0 = vec![ + let ifd0 = t.ifd(vec![ (254, Val::Long(vec![1])), (256, Val::Long(vec![2])), (257, Val::Long(vec![2])), (259, Val::Short(vec![1])), (262, Val::Short(vec![2])), + (271, Val::Ascii(make.into())), (273, Val::Blobs(vec![thumb])), (277, Val::Short(vec![3])), (279, Val::Long(vec![12])), (330, Val::Ifds(vec![raw_ifd])), - ]; - ifd0.push(make_tag); - ifd0.extend(ifd0_tags); - let ifd0 = t.ifd(ifd0); + ]); t.chain = vec![ifd0]; t.build() } diff --git a/crates/raw/src/testgen/dng.rs b/crates/raw/src/testgen/dng.rs index db8d787edb..f9d252c391 100644 --- a/crates/raw/src/testgen/dng.rs +++ b/crates/raw/src/testgen/dng.rs @@ -365,27 +365,7 @@ impl DngSpec { let bytes: Vec = match self.bits { 8 => v.iter().map(|&x| x as u8).collect(), 16 => v.iter().flat_map(|&x| if self.big_endian { x.to_be_bytes() } else { x.to_le_bytes() }).collect(), - // Other depths are bit-packed, most significant bit first, a row at a time (the TIFF layout). - bits => v - .chunks(n) - .flat_map(|row| { - let mut out = Vec::new(); - let (mut acc, mut have) = (0u32, 0u32); - for &x in row { - acc = acc << bits | u32::from(x) & ((1 << bits) - 1); - have += u32::from(bits); - while have >= 8 { - have -= 8; - out.push((acc >> have) as u8); - } - acc &= (1 << have) - 1; - } - if have > 0 { - out.push((acc << (8 - have)) as u8); - } - out - }) - .collect(), + _ => v.iter().flat_map(|x| x.to_le_bytes()).collect(), }; let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); e.write_all(&bytes).expect("zlib"); diff --git a/crates/raw/src/testgen/raf.rs b/crates/raw/src/testgen/raf.rs index e414ff35d4..9a2ddb7e38 100644 --- a/crates/raw/src/testgen/raf.rs +++ b/crates/raw/src/testgen/raf.rs @@ -154,28 +154,22 @@ impl RafSpec { } out } - // Rows of 14-bit samples, most significant bit first, in little-endian 32-bit words: each row - // starts on a word boundary (the stride is the raw IFD's 0xF005). - RafPacking::Words14 => self - .data - .chunks(self.width.max(1)) - .flat_map(|row| { - let (mut logical, mut acc, mut n) = (Vec::new(), 0u64, 0u32); - for &v in row { - acc = (acc << 14) | u64::from(v & 0x3FFF); - n += 14; - while n >= 8 { - logical.push((acc >> (n - 8)) as u8); - n -= 8; - } + RafPacking::Words14 => { + let (mut logical, mut acc, mut n) = (Vec::new(), 0u64, 0u32); + for &v in &self.data { + acc = (acc << 14) | u64::from(v & 0x3FFF); + n += 14; + while n >= 8 { + logical.push((acc >> (n - 8)) as u8); + n -= 8; } - if n > 0 { - logical.push((acc << (8 - n)) as u8); - } - logical.resize(logical.len().next_multiple_of(4), 0); - logical.chunks(4).flat_map(|w| w.iter().rev().copied().collect::>()).collect::>() - }) - .collect(), + } + if n > 0 { + logical.push((acc << (8 - n)) as u8); + } + logical.resize(logical.len().next_multiple_of(4), 0); + logical.chunks(4).flat_map(|w| w.iter().rev().copied().collect::>()).collect() + } RafPacking::Compressed { lossy } => { assert!(self.width == 780 && self.height.is_multiple_of(6) && self.data.iter().all(|&v| v == 0), "see RafPacking::Compressed"); let quantizers: Vec = (0..self.height / 6).map(|g| [2, 0, 5][g % 3]).collect(); @@ -200,8 +194,6 @@ impl RafSpec { (0xF00A, self.black.clone()), ] .into_iter() - .chain(matches!(self.packing, RafPacking::Words14).then(|| (0xF005, vec![(self.width * 14).div_ceil(32) as u32]))) - .chain(matches!(self.packing, RafPacking::Words14).then(|| (0xF006, vec![1]))) .chain(self.wb_grb.map(|w| (0xF00E, w.to_vec()))) .collect(); let mut out = if le { b"II*\0".to_vec() } else { b"MM\0*".to_vec() }; diff --git a/crates/raw/src/testgen/rw2.rs b/crates/raw/src/testgen/rw2.rs index 1b42350080..8dedfad007 100644 --- a/crates/raw/src/testgen/rw2.rs +++ b/crates/raw/src/testgen/rw2.rs @@ -95,17 +95,14 @@ impl V4Writer<'_> { self.nbits += (RW2_PAGE as u32) * 8; self.pos += RW2_PAGE; } - // The field is a little-endian 16-bit word at a byte of the logical page; each of its two bytes - // lands where the page split puts it (the word can straddle the split). - let logical = ((self.nbits - num) >> 3) as usize ^ 0x3FF0; - let page = self.base + self.pos - RW2_PAGE; - let physical = |l: usize| page + (l + RW2_PAGE - RW2_COMPRESSED_SPLIT) % RW2_PAGE; - let (lo, hi) = (physical(logical), physical(logical + 1)); + let mut at = ((self.nbits - num) >> 3) as usize ^ 0x3FF0; + at = (at + RW2_PAGE - RW2_COMPRESSED_SPLIT) % RW2_PAGE; + let at = self.base + at + self.pos - RW2_PAGE; self.nbits -= num; - let cur = u32::from(self.buf[lo]) | (u32::from(self.buf[hi]) << 8); + let cur = u32::from(self.buf[at]) | (u32::from(self.buf[at + 1]) << 8); let cur = cur | ((v & ((1 << num) - 1)) << (self.nbits & 7)); - self.buf[lo] = cur as u8; - self.buf[hi] = (cur >> 8) as u8; + self.buf[at] = cur as u8; + self.buf[at + 1] = (cur >> 8) as u8; } /// Encodes one row as 14-pixel groups: the scale selector is always 0 and diff --git a/crates/raw/tests/it/dng.rs b/crates/raw/tests/it/dng.rs index 616fd346e6..ca9d895960 100644 --- a/crates/raw/tests/it/dng.rs +++ b/crates/raw/tests/it/dng.rs @@ -8,19 +8,6 @@ fn sensor(bytes: &[u8]) -> Sensor { decode(bytes, &Limits::default()).unwrap() } -/// Float DNG samples remain in their source white-level units, without U16 quantization. -fn floats(s: &Sensor) -> &[f32] { - s.float_data.as_deref().expect("floating-point samples") -} - -fn unit(data: &[u16]) -> Vec { - data.iter().map(|&v| f32::from(v) / 65535.0).collect() -} - -fn near(got: &[f32], want: &[f32]) -> bool { - got.len() == want.len() && got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-6) -} - /// Deterministic sensor-like samples below `2^bits`. fn noise(n: usize, bits: u16) -> Vec { let mut s = 0x9E37_79B9_7F4A_7C15u64; @@ -256,8 +243,7 @@ fn metadata_is_read() { assert_eq!(s.color.as_shot_neutral, Some([0.5, 1.0, 0.8])); assert!((s.baseline_exposure - 0.5).abs() < 1e-6); assert_eq!(s.orientation, 6); - assert!(s.linearization.is_none(), "the shared decoder has already applied the table"); - assert!(s.data.iter().all(|&sample| sample == 3000), "all stored1000 samples use the3x table"); + assert_eq!(s.linearization.as_ref().map(Vec::len), Some(4096)); let d = develop_sensor(&s, &DevelopOptions::default()).unwrap(); // Orientation 6 swaps the cropped 20×16 to 16×20. assert_eq!((d.width, d.height), (16, 20)); @@ -267,47 +253,38 @@ fn metadata_is_read() { } #[test] -fn enormous_double_crop_origin_keeps_the_whole_active_area_with_warning() { +fn enormous_double_crop_origin_is_rejected() { let (w, h) = (16, 12); - for origin in [1e300, f64::INFINITY, f64::NAN, -1.] { - let mut spec = DngSpec::cfa(w, h, vec![1000; w * h]); - spec.active_area = Some([2, 3, 10, 14]); - spec.default_crop = Some(([0, 0], [11, 8])); - spec.default_crop_origin_double = Some([origin, 0.0]); - let s = sensor(&spec.build()); - assert_eq!(s.active, Rect::new(3, 2, 11, 8)); - assert_eq!(s.crop, Rect::new(3, 2, 11, 8), "invalid coordinates cannot create a clipped sliver"); - assert_eq!(s.data, spec.data, "fallback preserves every stored sensor value"); - assert!(s.warnings.iter().any(|warning| warning.contains("default crop")), "{origin}: {:?}", s.warnings); - } + let mut spec = DngSpec::cfa(w, h, vec![1000; w * h]); + spec.active_area = Some([2, 3, 10, 14]); + spec.default_crop = Some(([0, 0], [11, 8])); + spec.default_crop_origin_double = Some([1e300, 0.0]); + + assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Malformed(_)))); } #[test] -fn out_of_range_default_crop_uses_checked_intersection_with_warning() { +fn out_of_range_default_crop_falls_back_to_active_area_with_warning() { let (w, h) = (16, 12); let mut spec = DngSpec::cfa(w, h, vec![1000; w * h]); spec.active_area = Some([2, 3, 10, 14]); spec.default_crop = Some(([10, 0], [5, 4])); let s = sensor(&spec.build()); - assert_eq!(s.active, Rect::new(3, 2, 11, 8)); - assert_eq!(s.crop, Rect::new(13, 2, 1, 4), "[10,0,5,4] intersected with relative[0,0,11,8]"); - assert_eq!(s.data, spec.data, "crop adjustment does not rewrite sensor samples"); + assert_eq!(s.crop, s.active); assert!(s.warnings.iter().any(|warning| warning.contains("out-of-range") && warning.contains("default crop")), "{:?}", s.warnings); } -/// A missing DefaultCropSize uses the shared full-area default, intersected with the active area. +/// DefaultCropSize defaults to the whole image, which can't fit once the origin moves in. #[test] -fn default_crop_origin_without_size_uses_checked_intersection_with_warning() { +fn default_crop_origin_without_size_falls_back_to_active_area_with_warning() { let (w, h) = (16, 12); let mut spec = DngSpec::cfa(w, h, vec![1000; w * h]); spec.active_area = Some([2, 3, 10, 14]); spec.default_crop_origin_double = Some([1.0, 1.0]); let s = sensor(&spec.build()); - assert_eq!(s.active, Rect::new(3, 2, 11, 8)); - assert_eq!(s.crop, Rect::new(4, 3, 10, 7), "relative origin1,1 clips only the default area edges"); - assert_eq!(s.data, spec.data); + assert_eq!(s.crop, s.active); assert!(s.warnings.iter().any(|warning| warning.contains("out-of-range") && warning.contains("default crop")), "{:?}", s.warnings); } @@ -531,21 +508,8 @@ fn smooth_scene_develops_with_every_method() { #[test] fn unsupported_variants_say_so() { - // The shared reader now supports periodic non-Bayer CFA. Prove the source - // pattern and constant-scene development rather than deleting its coverage. - let mut spec = DngSpec::cfa(8, 8, vec![1000; 64]); - let mut bayer = spec.clone(); - bayer.white = 4000; - spec.white = 4000; - spec.cfa = [0, 1, 2, 1]; - let sensor = sensor(&spec.build()); - assert_eq!(sensor.data, spec.data); - assert_eq!(sensor.cfa.as_ref().unwrap().phase(0, 0), spec.cfa); - assert!(!sensor.cfa.as_ref().unwrap().is_bayer()); - let options = DevelopOptions { white_balance: WhiteBalance::Multipliers([1.; 3]), ..Default::default() }; - assert_eq!(develop_sensor(&sensor, &options).unwrap().rgb, develop(&bayer.build(), &options).unwrap().rgb); - // Integer sample widths above16 remain unsupported, never truncated toU16. - spec.bits = 17; + let mut spec = DngSpec::cfa(8, 8, vec![0; 64]); + spec.cfa = [0, 1, 2, 1]; // not Bayer assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Unsupported(_)))); } @@ -619,18 +583,22 @@ fn deflate_8_bit_predictor_and_packed_12_bit() { spec.white = 255; spec.storage = DngStorage::DeflateStrips { rows: h, predictor: 2 }; assert_eq!(sensor(&spec.build()).data, data8, "8-bit predictor 2"); - // Independently frame two 12-bit samples in three bytes, MSB first. The - // fixture writer now emits valid packed samples too: verify its actual - // compressed payload against this separate construction before decoding. + // 12-bit packed: two samples in three bytes, MSB first. Swap the testgen's 16-bit + // containers for a packed stream of the same samples. let data12: Vec = (0..w * h).map(|i| (i as u16 * 61) & 0xFFF).collect(); let mut spec = DngSpec::cfa(w, h, data12.clone()); spec.bits = 12; spec.white = 4095; spec.storage = DngStorage::DeflateStrips { rows: h, predictor: 1 }; - let bytes = spec.build(); + let mut bytes = spec.build(); + let containers: Vec = data12.iter().flat_map(|v| v.to_le_bytes()).collect(); + let old = zlib(&containers); let packed: Vec = data12.chunks(2).flat_map(|p| [(p[0] >> 4) as u8, ((p[0] & 0xF) << 4 | p[1] >> 8) as u8, p[1] as u8]).collect(); - let compressed = zlib(&packed); - assert!(bytes.windows(compressed.len()).any(|chunk| chunk == compressed.as_slice()), "fixture contains independently packed 12-bit strip"); + let mut new = zlib(&packed); + let at = bytes.windows(old.len()).position(|c| c == old.as_slice()).expect("the strip"); + assert!(new.len() <= old.len()); + new.resize(old.len(), 0); // trailing bytes after the zlib stream are ignored + bytes[at..at + old.len()].copy_from_slice(&new); assert_eq!(sensor(&bytes).data, data12, "12-bit packed"); } @@ -738,16 +706,15 @@ fn float_jxl_dng(data: &[u16], w: usize, h: usize, white: Option) -> DngSpe fn floating_point_jpeg_xl_linear_raw_decodes() { let (w, h) = (24, 16); let data = noise(w * h * 3, 16); - // White level 1.0 (the default): the samples read back as stored, as floats. + // White level 1.0 (the default) becomes 65535: the samples read back as stored. let s = sensor(&float_jxl_dng(&data, w, h, None).build()); assert_eq!((s.width, s.height, s.samples), (w, h, 3)); - assert!(s.data.is_empty()); - assert!(near(floats(&s), &unit(&data))); - assert_eq!(s.white, [1.0; 3]); - // A stated white level of 0.5 is kept in the floats' own unit. + assert_eq!(s.data, data); + assert_eq!(s.white, [65535.0; 3]); + // A stated white level of 0.5 becomes 65535 too: samples double, those above it clip. let s = sensor(&float_jxl_dng(&data, w, h, Some(0.5)).build()); - assert_eq!(s.white, [0.5; 3]); - assert!(near(floats(&s), &unit(&data))); + assert_eq!(s.white, [65535.0; 3]); + assert_eq!(s.data, data.iter().map(|&v| (u32::from(v) * 2).min(65535) as u16).collect::>()); // It develops like the same samples stored as integers. let pixels: Vec = scene(w, h).iter().flat_map(|p| p.map(|v| (v * 20000.0) as u16)).collect(); let float = develop(&float_jxl_dng(&pixels, w, h, None).build(), &DevelopOptions::default()).unwrap(); @@ -759,18 +726,14 @@ fn floating_point_jpeg_xl_linear_raw_decodes() { } #[test] -fn uncompressed_float_raw_preserves_known_half_values_including_signed_hdr() { +fn floating_point_raw_data_that_isnt_jpeg_xl_is_unsupported() { let (w, h) = (8, 4); - let mut spec = DngSpec::cfa(w, h, [0x3800u16, 0x3c00, 0x4000, 0xbc00].repeat(w * h * 3 / 4)); - spec.samples = 3; - spec.white = 0; - spec.raw_extra = vec![(339, Val::Short(vec![3; 3]))]; + let mut spec = float_jxl_dng(&noise(w * h * 3, 16), w, h, None); spec.storage = DngStorage::Strips { rows: h }; - let s = sensor(&spec.build()); - assert_eq!((s.width, s.height, s.samples), (w, h, 3)); - assert!(s.data.is_empty()); - assert_eq!(floats(&s), [0.5f32, 1.0, 2.0, -1.0].repeat(w * h * 3 / 4)); - assert_eq!(s.white, [1.0; 3]); + match decode(&spec.build(), &Limits::default()) { + Err(RawError::Unsupported(m)) => assert!(m.contains("floating-point"), "{m}"), + other => panic!("expected unsupported, got {other:?}"), + } } /// WhiteLevel has one value per sample plane: the floats are scaled by the highest, so a plane @@ -782,8 +745,8 @@ fn floating_point_white_levels_per_plane_scale_from_the_highest() { let mut spec = float_jxl_dng(&data, w, h, None); spec.raw_extra.push((50717, Val::Double(vec![0.5, 1.0, 0.5]))); let s = sensor(&spec.build()); - assert!(near(floats(&s), &unit(&data)), "the floats are not scaled"); - assert_eq!(s.white, [0.5, 1.0, 0.5]); + assert_eq!(s.data, data, "scaled by 1.0, the highest: nothing clipped"); + assert_eq!(s.white, [32767.5, 65535.0, 32767.5]); } /// `Σ cᵢ · xⁱ` at `x`, both clipped to 0..1 (as MapPolynomial). @@ -792,24 +755,6 @@ fn poly(c: &[f64], x: f64) -> f64 { c.iter().rev().fold(0.0, |acc, c| acc * x + c).clamp(0.0, 1.0) } -/// Compare deferred development against independently evaluated normalized samples. -/// The reference uses the source's F32 domain and then the public polynomial formula, -/// avoiding the old intermediate U16 quantization and any wider output tolerance. -fn assert_polynomial_development(actual: &Sensor, normalized: Vec) { - let mut expected = actual.clone(); - expected.float_data = Some(normalized); - expected.data.clear(); - expected.linearization = None; - expected.polynomials.clear(); - expected.white = [1.; 3]; - expected.black = BlackLevels::uniform(0.); - let options = DevelopOptions { white_balance: WhiteBalance::Multipliers([1.; 3]), ..Default::default() }; - let got = develop_sensor(actual, &options).unwrap(); - let want = develop_sensor(&expected, &options).unwrap(); - assert_eq!((got.width, got.height), (want.width, want.height)); - assert_eq!(got.rgb, want.rgb, "deferred polynomial matches independently mapped source samples"); -} - /// #8125: a lossy DNG's OpcodeList2 carries a MapPolynomial per plane, and its colours depend on /// it. Each plane's samples are mapped through its polynomial, on the linear reference values. #[test] @@ -824,9 +769,8 @@ fn map_polynomial_maps_each_plane_of_floating_point_data() { )); let bytes = spec.build(); let s = sensor(&bytes); - let want: Vec = data.iter().enumerate().map(|(i, &v)| poly(&planes[i % 3], f64::from(f32::from(v) / 65535.)) as f32).collect(); - assert!(near(floats(&s), &unit(&data)), "stored float values stay unprocessed until development"); - assert_polynomial_development(&s, want); + let want: Vec = data.iter().enumerate().map(|(i, &v)| (poly(&planes[i % 3], f64::from(v) / 65535.0) * 65535.0).round() as u16).collect(); + assert_eq!(s.data, want); assert!(s.warnings.iter().all(|w| !w.contains("MapPolynomial")), "{:?}", s.warnings); let d = develop(&bytes, &DevelopOptions::default()).unwrap(); assert!(d.warnings.iter().all(|w| !w.contains("MapPolynomial")), "{:?}", d.warnings); @@ -845,10 +789,9 @@ fn map_polynomial_follows_the_linearization_table() { spec.linearization = Some(table.clone()); spec.opcode_list2 = Some(testgen::map_polynomial_opcode_list([0, 0, h as u32, w as u32], &[(0, vec![0.0, 0.0, 1.0])])); let s = sensor(&spec.build()); - assert!(s.linearization.is_none(), "linearization applied at decode, polynomial deferred to development"); - assert_eq!(s.data, data.iter().map(|&value| table[usize::from(value)]).collect::>()); - let want: Vec = data.iter().map(|&v| poly(&[0.0, 0.0, 1.0], f64::from(f32::from(table[usize::from(v)]) / 8190.)) as f32).collect(); - assert_polynomial_development(&s, want); + assert!(s.linearization.is_none(), "applied with the polynomial"); + let want: Vec = data.iter().map(|&v| (poly(&[0.0, 0.0, 1.0], f64::from(table[usize::from(v)]) / 8190.0) * 8190.0).round() as u16).collect(); + assert_eq!(s.data, want); } /// A LinearizationTable maps integer samples: floating-point data ignores one. @@ -860,10 +803,10 @@ fn floating_point_raw_data_ignores_a_linearization_table() { spec.linearization = Some(vec![0; 4]); let s = sensor(&spec.build()); assert!(s.linearization.is_none()); - assert!(near(floats(&s), &unit(&data))); + assert_eq!(s.data, data); } -/// Floating-point samples stay four bytes each: the limits +/// Floating-point samples are read into four bytes each before they become 16-bit: the limits /// are charged for that buffer, not for the two-byte result. #[test] fn floating_point_jpeg_xl_is_charged_four_bytes_a_sample() { @@ -953,7 +896,7 @@ fn an_infinite_white_level_falls_back_to_the_default() { ints.raw_extra.push((50717, Val::Double(vec![1e300; 3]))); assert_eq!(sensor(&ints.build()).white, [65535.0; 3], "integer data"); let float = float_jxl_dng(&pixels, w, h, Some(1e300)).build(); - assert_eq!(sensor(&float).white, [1.0; 3], "floating-point data"); + assert_eq!(sensor(&float).white, [65535.0; 3], "floating-point data"); let default = develop(&float_jxl_dng(&pixels, w, h, None).build(), &DevelopOptions::default()).unwrap(); assert_eq!(develop(&float, &DevelopOptions::default()).unwrap().rgb, default.rgb); } @@ -968,10 +911,9 @@ fn jpeg_xl_mismatches_are_errors() { // Codestream smaller than the strip. spec.jxl_segments = vec![jxl(&data[..w * 4 * 3], w, 4, 3, 16)]; assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Malformed(_)))); - // A grey codestream contradicts the RGB IFD: this is damaged framing, - // not a supported one-plane image or a conversion request. + // Grey codestream for RGB samples. spec.jxl_segments = vec![jxl(&data[..w * h], w, h, 1, 16)]; - assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Malformed(_)))); + assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Unsupported(_)))); // Not a codestream at all. spec.jxl_segments = vec![vec![0xff, 0x0a, 1, 2, 3, 4, 5]]; assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Malformed(_)))); @@ -1113,8 +1055,7 @@ fn lossy_jpeg_levels_and_linearization_apply_to_stored_values() { spec.linearization = Some(table.clone()); spec.storage = storage; let s = sensor(&spec.build()); - assert!(s.linearization.is_none(), "table already applied to stored samples"); - assert_eq!(s.data, vec![40_000; w * h]); + assert_eq!(s.linearization.as_deref(), Some(table.as_slice())); assert_eq!(s.white, [65535.0; 3], "the table's maximum is white"); grey(&develop_sensor(&s, &DevelopOptions::default()).unwrap()) }; @@ -1133,37 +1074,31 @@ fn lossy_jpeg_truncated_tile_errors() { assert!(matches!(decode(cut, &Limits::default()), Err(RawError::Malformed(_))), "a cut JPEG tile must not decode"); } -/// JPEG tiles must cover all visible pixels within bounded MCU padding. Hostile -/// frame dimensions fail the header check before the decoder allocates pixels. +/// A tile JPEG whose header disagrees with the tile size fails the header check, before any +/// pixel decode (a hostile SOF must not be able to size the decoder's buffers first). #[test] fn lossy_jpeg_tile_dimension_mismatch_errors() { let (w, h) = (32, 32); let mut spec = lossy_spec(w, h, vec![100; w * h], DngStorage::LossyJpegTiles { width: 32, height: 32 }); let small: Vec = (0..16 * 16).map(|i| (i % 16 * 16) as u8).collect(); spec.lossy_segments = vec![baseline_jpeg(&small, 16, 16, 1)]; - let err = decode(&spec.build(), &Limits::default()).unwrap_err(); - assert!(matches!(&err, RawError::Malformed(message) if message.contains("16 x 16") && message.contains("32 x 32") && message.contains("tile")), "{err}"); - // Edge frames may cover only the visible image or bounded MCU padding. - // Neither path may omit visible rows or introduce zero-filled pixels. + let err = decode(&spec.build(), &Limits::default()).unwrap_err().to_string(); + assert!(err.contains("16x16") && err.contains("32x32"), "{err}"); + // A tile coded at the image's row count instead of the tile's is tolerated (a strip-like + // encoder); anything else is not. let (w, h) = (16, 12); let mut spec = lossy_spec(w, h, vec![100; w * h], DngStorage::LossyJpegTiles { width: 16, height: 16 }); - for (tw, th) in [(16, 12), (16, 14), (16, 18), (18, 16)] { - spec.lossy_segments = vec![baseline_jpeg(&vec![100u8; tw * th], tw, th, 1)]; - let s = sensor(&spec.build()); - assert_eq!((s.width, s.height, s.data.len()), (w, h, w * h)); - assert!(s.data.iter().all(|&v| v.abs_diff(100) <= 2), "{tw}x{th}: visible source pixels survive padding"); - } - for (tw, th) in [(16, 11), (15, 16), (12, 16), (16, 33), (33, 16)] { + spec.lossy_segments = vec![baseline_jpeg(&[100u8; 16 * 12], 16, 12, 1)]; + let s = sensor(&spec.build()); + assert_eq!((s.width, s.height), (w, h)); + assert!(s.data.iter().all(|&v| v.abs_diff(100) <= 2)); + for (tw, th) in [(16, 14), (16, 18), (12, 16), (18, 16)] { spec.lossy_segments = vec![baseline_jpeg(&vec![100u8; tw * th], tw, th, 1)]; assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Malformed(_))), "{tw}x{th}"); } - // The last strip can include padding, but it must cover its four visible rows. + // A strip must be coded at its own row count. let mut spec = lossy_spec(w, h, vec![100; w * h], DngStorage::LossyJpegStrips { rows: 8 }); spec.lossy_segments = vec![baseline_jpeg(&[100u8; 16 * 8], 16, 8, 1), baseline_jpeg(&[100u8; 16 * 8], 16, 8, 1)]; - let padded = sensor(&spec.build()); - assert_eq!(padded.data.len(), w * h); - assert!(padded.data.iter().all(|&v| v.abs_diff(100) <= 2)); - spec.lossy_segments[1] = baseline_jpeg(&[100u8; 16 * 3], 16, 3, 1); assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Malformed(_)))); } diff --git a/crates/raw/tests/it/hasselblad.rs b/crates/raw/tests/it/hasselblad.rs index 4eeefa7a36..8bdf5c2957 100644 --- a/crates/raw/tests/it/hasselblad.rs +++ b/crates/raw/tests/it/hasselblad.rs @@ -50,10 +50,7 @@ fn metadata() { assert!((wb[2] - 1.0 / 0.617).abs() < 1e-9, "{wb:?}"); assert_eq!((sensor.make.as_deref(), sensor.model.as_deref()), (Some("Hasselblad"), Some("X2D II 100C"))); assert_eq!(sensor.orientation, 1); - // This real-layout fixture deliberately has no CFAPattern tag. All source - // metadata is retained, while the decoder discloses its assumed RGGB phase. - assert_eq!(sensor.warnings.len(), 1, "{:?}", sensor.warnings); - assert!(sensor.warnings[0].contains("Bayer phase") && sensor.warnings[0].contains("fallback"), "{:?}", sensor.warnings); + assert!(sensor.warnings.is_empty(), "{:?}", sensor.warnings); } #[test] @@ -80,7 +77,7 @@ fn compressed_3fr_is_reported_unsupported() { let mut s = spec(); s.compression = 7; let e = decode(&s.build(), &Limits::default()).unwrap_err(); - assert!(matches!(&e, RawError::Unsupported(reason) if reason.contains("lossless JPEG")), "{e:?}"); + assert!(matches!(&e, RawError::Unsupported(reason) if reason.contains("lossless-JPEG")), "{e:?}"); } #[test] @@ -95,11 +92,8 @@ fn missing_levels_fall_back() { let sensor = decode(&s.build(), &Limits::default()).unwrap(); assert_eq!(sensor.black, BlackLevels::uniform(0.0)); assert!(sensor.warnings.iter().any(|w| w.contains("black level")), "{:?}", sensor.warnings); - // Shared provenance identifies this as the declared-depth default. The - // non-DNG adapter must not silently rescale the stored samples afterward. - assert_eq!(sensor.white, [f32::from(u16::MAX); 3]); - assert_eq!(sensor.data, s.data); - assert!(sensor.warnings.iter().any(|warning| warning.contains("white level")), "{:?}", sensor.warnings); + // clip_level backs the clipped plateau off slightly. + assert!((sensor.white[0] - f32::from(u16::MAX) * 0.995).abs() < 1.0, "{:?}", sensor.white); } #[test] diff --git a/crates/raw/tests/it/raf.rs b/crates/raw/tests/it/raf.rs index 9906171c29..4d54d8a4a0 100644 --- a/crates/raw/tests/it/raf.rs +++ b/crates/raw/tests/it/raf.rs @@ -28,15 +28,6 @@ fn every_storage_decodes_exactly() { assert_eq!((s.width, s.height), (30, 18)); assert_eq!(s.data, spec.data, "{packing:?}"); } - - // Four 14-bit samples occupy two padded words per row, as many bytes as - // unpacked 16-bit containers. The explicit packing flag must win over size. - let data = [1, 0x1FFF, 0x2000, 0x3FFF, 0x3FFE, 0x2001, 0x0100, 0].repeat(4); - let spec = RafSpec { packing: RafPacking::Words14, black: vec![0], ..RafSpec::new(4, 8, data, RGGB.to_vec()) }; - let s = decode(&spec.build(), &Limits::default()).unwrap(); - assert_eq!((s.width, s.height), (4, 8)); - assert_eq!(s.data, spec.data); - assert_eq!(s.black, BlackLevels::uniform(0.0)); } #[test] @@ -57,11 +48,7 @@ fn xtrans_metadata() { assert!((s.baseline_exposure - 0.72).abs() < 1e-9); assert_eq!(s.orientation, 6); assert_eq!((s.make.as_deref(), s.model.as_deref()), (Some("FUJIFILM"), Some("X-Synthetic"))); - // This RAF records black/WB but no white tag; the full 14-bit range is an - // explicit fallback, not a missing-CFA or missing-black warning. - assert_eq!(s.white, [16383.; 3]); - assert_eq!(s.warnings.len(), 1, "{:?}", s.warnings); - assert!(s.warnings[0].contains("white level") && s.warnings[0].contains("full sample range"), "{:?}", s.warnings); + assert!(s.warnings.is_empty(), "{:?}", s.warnings); } #[test] @@ -165,7 +152,7 @@ fn compressed_variants_that_cannot_be_decoded_fail_cleanly() { for cfa in [other.as_slice(), &[1, 0, 2, 1]] { let b = compressed(cfa, 14, false).build(); match decode(&b, &Limits::default()) { - Err(RawError::Unsupported(m)) => assert!(m.contains("layout"), "{m}"), + Err(RawError::Unsupported(m)) => assert!(m.contains("CFA"), "{m}"), other => panic!("expected unsupported, got {other:?}"), } } diff --git a/crates/raw/tests/it/raw_corpus.rs b/crates/raw/tests/it/raw_corpus.rs index 83f5388b2b..7d2ca341d2 100644 --- a/crates/raw/tests/it/raw_corpus.rs +++ b/crates/raw/tests/it/raw_corpus.rs @@ -26,8 +26,6 @@ struct Want<'a> { cfa: [u8; 4], black: &'a [f32], white: [f32; 3], - /// Exact source-sample maximum and its population at the pinned corpus revision. - sample_max: (u16, usize), } const WANTS: &[Want] = &[ @@ -39,8 +37,7 @@ const WANTS: &[Want] = &[ size: (4176, 3062), cfa: [0, 1, 1, 2], black: &[128.0; 4], - white: [4080.0; 3], - sample_max: (4095, 2207), + white: [4095.0; 3], }, // The same camera after DNG Converter: the sensor data round-trips identically. Want { @@ -52,7 +49,6 @@ const WANTS: &[Want] = &[ cfa: [0, 1, 1, 2], black: &[127.0], white: [4095.0; 3], - sample_max: (4093, 6886), }, Want { file: "JD1_8203.NEF", @@ -63,9 +59,8 @@ const WANTS: &[Want] = &[ cfa: [0, 1, 1, 2], black: &[0.0], white: [4095.0; 3], - sample_max: (4095, 222), }, - // Sony cRAW: white is the inferred lower edge of its saturated sample band. + // Sony cRAW: the saturation level comes from the compressed code's range. Want { file: "DSC00009.ARW", format: RawFormat::Arw, @@ -74,9 +69,8 @@ const WANTS: &[Want] = &[ size: (4832, 3224), cfa: [0, 1, 1, 2], // SR2SubIFD black levels, verified with the metadata oracle (not the 512 fallback). - black: &[800.0], - white: [16320.0; 3], - sample_max: (16383, 3326), + black: &[800.0; 4], + white: [16301.0; 3], }, // The G9's high-resolution mode: a 10480 × 7794 sensor cropped to 10368 × 7776. Want { @@ -87,8 +81,7 @@ const WANTS: &[Want] = &[ size: (10480, 7794), cfa: [0, 1, 1, 2], black: &[127.0, 128.0, 128.0, 127.0], - white: [4080.0; 3], - sample_max: (4095, 558549), + white: [4095.0; 3], }, // Four Thirds Olympus: GRBG instead of the usual RGGB. Want { @@ -100,7 +93,6 @@ const WANTS: &[Want] = &[ cfa: [1, 0, 2, 1], black: &[65.0; 4], white: [4095.0; 3], - sample_max: (4095, 10), }, ]; @@ -116,23 +108,7 @@ fn decode_matches_the_measured_oracles() { let cfa = s.cfa.as_ref().unwrap_or_else(|| panic!("{}: no CFA", w.file)); assert_eq!(cfa.colors, w.cfa, "{}", w.file); assert_eq!(s.black.values, w.black, "{}", w.file); - // An inferred white is a band boundary, not the largest decoded sample. - // Pin the sample maximum and its population independently of that policy. - let sample_max = s.data.iter().fold((0u16, 0usize), |(maximum, count), &value| { - if value > maximum { - (value, 1) - } else if value == maximum { - (maximum, count + 1) - } else { - (maximum, count) - } - }); - assert_eq!(sample_max, w.sample_max, "{} source maximum and population", w.file); if w.file == "DSC00009.ARW" { - for (x, y) in [(0, 0), (1, 0), (0, 1), (1, 1)] { - assert_eq!(s.black.at(x, y, 0, 1), 800.0, "Sony metadata black at CFA site ({x}, {y})"); - } - assert_eq!(s.data.iter().filter(|&&value| value == 16372).count(), 74490, "Sony saturated compressed-code population"); assert_eq!(s.camera_wb, Some([2056.0 / 1024.0, 1.0, 1908.0 / 1024.0])); } for ch in 0..3 { diff --git a/crates/raw/tests/it/vendor_codecs.rs b/crates/raw/tests/it/vendor_codecs.rs index 2bf3201fa8..7c9e53ba4f 100644 --- a/crates/raw/tests/it/vendor_codecs.rs +++ b/crates/raw/tests/it/vendor_codecs.rs @@ -144,9 +144,7 @@ fn craw_without_a_black_level_tag_reads_black_from_the_tone_curve() { fn rw2_round_trip_12_and_14_bit() { for (bits, w, h) in [(12u32, 120usize, 300usize), (14, 117, 260)] { let max = (1u16 << bits) - 1; - // Uniformly exercise the entire declared code range, without a sensor - // saturation plateau that would intentionally infer a lower white level. - let data: Vec = (0..w * h).map(|i| ((i * 23 + 191) % (usize::from(max) + 1)) as u16).collect(); + let data = mosaic(&scene(w, h), w, [0, 1, 1, 2], 128, max); let b = rw2(w, h, &data, bits); assert!(b.len() > 3 * 0x4000, "spans several pages"); assert_eq!(identify(&b), Some(RawFormat::Rw2)); @@ -163,36 +161,6 @@ fn rw2_round_trip_12_and_14_bit() { } } -/// Keep the original smooth scene as a separate source-preservation control: its plateau is -/// intentionally different from the uniform full-range samples in the packing regression above. -#[test] -fn rw2_scene_preserves_samples_and_infers_white_independently_of_linearity_tags() { - // The known active scene gives no accepted 12-bit plateau. At 14 bits, its top-band - // boundary is 12790 (maximum 12840, 50-code band), independently of decoded output. - for (bits, w, h, white) in [(12u32, 120usize, 300usize, 4095.0), (14, 117, 260, 12790.0)] { - let max = (1u16 << bits) - 1; - let data = mosaic(&scene(w, h), w, [0, 1, 1, 2], 128, max); - let bytes = rw2(w, h, &data, bits); - let sensor = decode(&bytes, &Limits::default()).unwrap(); - assert_eq!((sensor.width, sensor.height), (w, h)); - assert_eq!(sensor.data, data, "{bits}-bit scene samples are not lifted or quantized"); - assert_eq!(sensor.white, [white; 3]); - assert_eq!(sensor.cfa.as_ref().unwrap().phase(0, 0), [0, 1, 1, 2]); - assert_eq!(sensor.black.values, vec![128.0, 129.0, 129.0, 130.0]); - assert_eq!(sensor.camera_wb, Some([2.0, 1.0, 1.5])); - assert_eq!(sensor.crop, Rect::new(2, 2, w - 4, h - 4)); - // These standard tags are nominal linearity limits; craft-raw's documented - // policy infers white from active samples instead, including extended low ISO. - let mut lower_nominal = bytes.clone(); - for tag in [0x000E, 0x000F, 0x0010] { - patch_ifd0_short(&mut lower_nominal, tag, max / 2); - } - let lower = decode(&lower_nominal, &Limits::default()).unwrap(); - assert_eq!(lower.data, data); - assert_eq!(lower.white, [white; 3], "nominal linearity does not replace the scene-derived white"); - } -} - /// Sets the value of a SHORT entry of IFD0 in a little-endian TIFF-like file. fn patch_ifd0_short(b: &mut [u8], tag: u16, v: u16) { let ifd = u32::from_le_bytes(b[4..8].try_into().unwrap()) as usize; @@ -228,10 +196,7 @@ fn rw2_format4_round_trip_is_exact() { assert_eq!(s.white, [4095.0; 3]); assert_eq!(s.camera_wb, Some([2.0, 1.0, 1.5])); assert_eq!(s.crop, Rect::new(2, 2, w - 4, h - 4)); - // The decoded white is the full-range fallback. Keep every other decoder - // disclosure unexpected while preserving exact samples, CFA, levels and crop. - assert_eq!(s.warnings.len(), 1, "{:?}", s.warnings); - assert!(s.warnings[0].contains("white level") && s.warnings[0].contains("full sample range"), "{:?}", s.warnings); + assert!(s.warnings.is_empty(), "{:?}", s.warnings); let d = develop_sensor(&s, &DevelopOptions::default()).unwrap(); assert_eq!((d.width as usize, d.height as usize), (w - 4, h - 4)); } @@ -252,14 +217,12 @@ fn rw2_format4_crosses_pages() { } #[test] -fn rw2_format4_preserves_samples_with_a_partial_final_block() { +fn rw2_format4_rejects_other_block_widths() { let (w, h) = (42, 2); let data: Vec = (0..w * h).map(|i| 200 + (i % 14) as u16 * 3).collect(); let mut b = rw2_format4(w, h, &data); patch_ifd0_short(&mut b, 0x0002, 41); - let s = decode(&b, &Limits::default()).unwrap(); - assert_eq!((s.width, s.height), (41, h)); - assert_eq!(s.data, data[..41 * h]); + assert!(matches!(decode(&b, &Limits::default()), Err(RawError::Unsupported(_)))); } #[test] @@ -267,17 +230,15 @@ fn rw2_undecoded_formats_fall_back() { let data = vec![200u16; 20 * 4]; let mut b = rw2(20, 4, &data, 12); assert!(decode(&b, &Limits::default()).is_ok()); - patch_ifd0_short(&mut b, 0x002D, 9); + patch_ifd0_short(&mut b, 0x002D, 6); match decode(&b, &Limits::default()) { - Err(RawError::Unsupported(m)) => assert!(m.contains("raw format 9"), "{m}"), + Err(RawError::Unsupported(m)) => assert!(m.contains("raw format 6"), "{m}"), other => panic!("expected unsupported, got {other:?}"), } - // The stream is continuous: a final partial block keeps exactly the declared samples. + // Width not made of whole blocks. let mut b = rw2(20, 4, &data, 12); patch_ifd0_short(&mut b, 0x0002, 19); - let s = decode(&b, &Limits::default()).unwrap(); - assert_eq!((s.width, s.height), (19, 4)); - assert_eq!(s.data, data[..19 * 4]); + assert!(matches!(decode(&b, &Limits::default()), Err(RawError::Unsupported(_)))); // Sizes beyond the limits are refused before allocating. let mut b = rw2(20, 4, &data, 12); patch_ifd0_short(&mut b, 0x0003, 60000); @@ -298,10 +259,7 @@ fn orf_uncompressed_round_trip() { assert_eq!(s.white, [4095.0; 3]); assert_eq!(s.camera_wb, Some([2.0, 1.0, 1.5])); assert_eq!(s.crop, Rect::new(2, 2, w - 4, h - 4)); - // The decoded white is the full-range fallback. Keep every other decoder - // disclosure unexpected while preserving exact samples, CFA, levels and crop. - assert_eq!(s.warnings.len(), 1, "{:?}", s.warnings); - assert!(s.warnings[0].contains("white level") && s.warnings[0].contains("full sample range"), "{:?}", s.warnings); + assert!(s.warnings.is_empty(), "{:?}", s.warnings); assert!(develop_sensor(&s, &DevelopOptions::default()).is_ok()); // The maker-note preview is found too (used when the data is compressed). assert!(embedded_preview(&b).is_some()); diff --git a/crates/raw/tests/it/vendors.rs b/crates/raw/tests/it/vendors.rs index bd6d1ff6a7..20ceb152a5 100644 --- a/crates/raw/tests/it/vendors.rs +++ b/crates/raw/tests/it/vendors.rs @@ -62,7 +62,7 @@ fn cr2_srgb_raw_is_unsupported() { let sof = b.windows(2).position(|w| w == [0xFF, 0xC3]).unwrap(); b[sof + 11] = 0x21; match decode(&b, &Limits::default()) { - Err(RawError::Unsupported(m)) => assert!(m.contains("subsampled"), "{m}"), + Err(RawError::Unsupported(m)) => assert!(m.contains("sRAW"), "{m}"), other => panic!("expected unsupported sRAW, got {other:?}"), } } @@ -71,22 +71,9 @@ fn cr2_srgb_raw_is_unsupported() { fn nef_like_with_maker_tags() { let (w, h) = (24, 16); let data = mosaic(&scene(w, h), w, [2, 1, 1, 0], 0, 4095); - // The explicit IFD0 Make overrides the generator's fallback identity. - let b = tiff_ep("NIKON", w, h, &data, [2, 1, 1, 0], 12, vec![(271, Val::Ascii("NIKON CORPORATION".into()))]); - // TIFF/EP fixtures use a little-endian TIFF header; assert the IFD itself has one Make, - // regardless of which duplicate-tag policy the decoder uses. - let ifd0 = u32::from_le_bytes([b[4], b[5], b[6], b[7]]) as usize; - let entry_count = u16::from_le_bytes([b[ifd0], b[ifd0 + 1]]) as usize; - let make_count = (0..entry_count) - .filter(|index| { - let entry = ifd0 + 2 + *index * 12; - u16::from_le_bytes([b[entry], b[entry + 1]]) == 271 - }) - .count(); - assert_eq!(make_count, 1); + let b = tiff_ep("NIKON CORPORATION", w, h, &data, [2, 1, 1, 0], 12, vec![]); assert_eq!(identify(&b), Some(RawFormat::Nef)); let s = decode(&b, &Limits::default()).unwrap(); - assert_eq!(s.make.as_deref(), Some("NIKON CORPORATION")); assert_eq!(s.data, data); assert_eq!(s.cfa.as_ref().unwrap().phase(0, 0), [2, 1, 1, 0]); assert!(s.warnings.iter().any(|w| w.contains("black level"))); @@ -123,11 +110,11 @@ fn other_raw_containers_are_recognised_but_unsupported() { cr3.extend_from_slice(&[0; 12]); assert_eq!(identify(&cr3), Some(RawFormat::Cr3)); assert!(matches!(decode(&cr3, &Limits::default()), Err(RawError::Unsupported(_)))); - // A bare RAF signature has no declared raw data: recognized, but malformed. + // A bare RAF header has no CFA TIFF (like early FinePix files): recognised, unsupported. let mut raf = b"FUJIFILMCCD-RAW 0201FF383501".to_vec(); raf.resize(200, 0); assert_eq!(identify(&raf), Some(RawFormat::Raf)); - assert!(matches!(decode(&raf, &Limits::default()), Err(RawError::Malformed(_)))); + assert!(matches!(decode(&raf, &Limits::default()), Err(RawError::Unsupported(_)))); assert_eq!(decode(b"not a raw file", &Limits::default()).unwrap_err(), RawError::NotRaw); } @@ -207,10 +194,7 @@ fn cr2_cfa_phase_is_measured_for_every_row_phase_and_border_parity() { let b = cr2_phase_spec(cfa, l, t, None).build(); let s = decode(&b, &Limits::default()).unwrap(); assert_eq!(s.cfa.as_ref().unwrap().phase(0, 0), cfa, "cfa {cfa:?} borders ({l}, {t})"); - // No white-level tag is written by this independent phase fixture. - // Its documented full-range fallback must not hide any phase warning. - assert_eq!(s.warnings.len(), 1, "{:?}", s.warnings); - assert!(s.warnings[0].contains("white level") && s.warnings[0].contains("full sample range"), "{:?}", s.warnings); + assert!(s.warnings.is_empty(), "{:?}", s.warnings); let d = develop_sensor(&s, &DevelopOptions { orient: false, ..Default::default() }).unwrap(); let [r, g, bl] = grey_patch(&d, 192 / 2 - l); // Neutral grey decodes neutral (a swapped phase gives a strong magenta or green cast). diff --git a/crates/ui-egui/src/tools/type_tool/options_tooltips_tests.rs b/crates/ui-egui/src/tools/type_tool/options_tooltips_tests.rs index 700d00a073..a41a0e2f2c 100644 --- a/crates/ui-egui/src/tools/type_tool/options_tooltips_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/options_tooltips_tests.rs @@ -22,8 +22,6 @@ fn app() -> PhotocraftApp { /// `draw` in a row, once the app's fonts are set up (the first pass has none). fn harness(draw: fn(&mut PhotocraftApp, &mut egui::Ui)) -> Harness<'static, PhotocraftApp> { - // Load the fonts first: if they finish mid-test the bar swaps "Loading fonts…" for its menus and a click is lost (#13408). - let _ = photocraft_text::shared(); let mut h = Harness::builder().with_size(vec2(1400.0, 600.0)).build_ui_state( move |ui, app| { if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { diff --git a/crates/ui-egui/src/tools/type_tool/panels_toggle_tests.rs b/crates/ui-egui/src/tools/type_tool/panels_toggle_tests.rs index f1d3fd34a1..893a5a90ba 100644 --- a/crates/ui-egui/src/tools/type_tool/panels_toggle_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/panels_toggle_tests.rs @@ -47,8 +47,6 @@ fn editing(mut app: PhotocraftApp, id: LayerId) -> PhotocraftApp { /// The options bar in a row, once the app's fonts are set up (the first pass has none). fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { - // Load the fonts first: if they finish mid-test the bar swaps "Loading fonts…" for its menus and a click is lost (#13408). - let _ = photocraft_text::shared(); let mut h = Harness::builder().with_size(vec2(1400.0, 200.0)).with_max_steps(16).build_ui_state( |ui, app| { if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { diff --git a/crates/ui-egui/src/tools/type_tool/size_presets_tests.rs b/crates/ui-egui/src/tools/type_tool/size_presets_tests.rs index eb1e623d9e..f39294be5a 100644 --- a/crates/ui-egui/src/tools/type_tool/size_presets_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/size_presets_tests.rs @@ -39,8 +39,6 @@ fn app_with_layer(size: f32) -> (PhotocraftApp, LayerId) { /// `draw` in a window tall enough for the list, once the app's fonts are set up. Up to 16 passes, /// because the font list arrives in batches (see `canvas_tests::controls`). fn harness(app: PhotocraftApp, draw: fn(&mut PhotocraftApp, &mut egui::Ui)) -> Harness<'static, PhotocraftApp> { - // Load the fonts first: if they finish mid-test the bar swaps "Loading fonts…" for its menus and a click is lost (#13408). - let _ = photocraft_text::shared(); let mut h = Harness::builder().with_size(vec2(1400.0, 800.0)).with_max_steps(16).build_ui_state( move |ui, app| { if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { diff --git a/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs b/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs index 45ac0c9ae4..25b9993943 100644 --- a/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs @@ -31,8 +31,6 @@ fn text_layer(app: &mut PhotocraftApp, orientation: &str) -> LayerId { } pub(super) fn bar(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { - // Load the fonts first: if they finish mid-test the bar swaps "Loading fonts…" for its menus and a click is lost (#13408). - let _ = photocraft_text::shared(); let mut h = Harness::builder().with_size(egui::vec2(1200.0, 60.0)).build_ui_state( |ui, app: &mut PhotocraftApp| { ui.horizontal(|ui| super::options_bar(app, ui)); From badce605ad3a9db7fe63d4218fc24fda96df6689 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 01:56:11 -0800 Subject: [PATCH 21/46] Define brush presets from the visible document composite Use the existing banded compositor independently of the active layer. Preserve selection density, document profiles and preallocation resource bounds. --- crates/engine/src/cmd/brush_cmds.rs | 84 +++-- .../define_brush_merged_source_tests.rs | 311 ++++++++++++++++++ .../define_brush_no_selection_tests.rs | 7 +- 3 files changed, 366 insertions(+), 36 deletions(-) create mode 100644 crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 210409987e..2b9af776f0 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -1067,9 +1067,8 @@ fn presets_set_current(s: &mut Session, p: &Value) -> Result { } fn has_selection_and_pixels(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or("no document")?; - let l = d.active_layer.and_then(|id| d.doc.layer(id)).ok_or("no active layer")?; - if matches!(l.content, LayerContent::Raster(_)) { Ok(()) } else { Err("active layer is not a pixel layer".into()) } + s.active().ok_or("no document")?; + Ok(()) } /// Largest sampled tip side (like Photoshop's 5000 px limit, kept smaller for preset size). @@ -1080,8 +1079,6 @@ fn define_from_selection(s: &mut Session, p: &Value) -> Result { let name = name_param(p, cmd)?; let d = s.active().ok_or(EngineError::NoDocument)?; let sel = d.doc.selection.as_ref(); - let id = d.active_layer.ok_or(EngineError::Other("no active layer".into()))?; - let surf = d.doc.layer(id).and_then(|l| l.surface()).ok_or_else(|| bad(cmd, "not a pixel layer"))?; let area = sel.map_or_else(|| d.doc.bounds(), |sel| sel.content_bounds().intersect(&d.doc.bounds())); if area.is_empty() { return Err(bad(cmd, "the selection is empty")); @@ -1093,16 +1090,29 @@ fn define_from_selection(s: &mut Session, p: &Value) -> Result { // multiply is checked too: on a 32-bit target (wasm32) it can overflow where the rest of // this command is already fallible. let len = w.checked_mul(h).ok_or_else(|| crate::allocation::error("defining a brush from the selection", "requested size overflowed"))?; - // Sparse canvases can span huge areas: cap both live dense buffers before reserving either. + // Sparse canvases can span huge areas. Density and selection remain live while the + // compositor holds one RGBA band, not a full-canvas RGBA plane; account for that + // actual maximum band before allocating any sampling buffers. let mask_bytes = sel.map_or(0, |sel| (sel.channels() as u64).saturating_mul(4)); - crate::allocation::check_dense(area, 4u64.saturating_add(mask_bytes), "defining a brush from the selection")?; + let band_rows = area.height().min(photocraft_compose::band_rows_for(area.width(), 0) as u32); + let band_bytes = u64::from(area.width()).saturating_mul(u64::from(band_rows)).saturating_mul(16); + let dense_bytes = (len as u64).saturating_mul(4u64.saturating_add(mask_bytes)).saturating_add(band_bytes); + if dense_bytes > crate::allocation::MAX_DENSE_BYTES { + return Err(EngineError::Other(format!( + "defining a brush from the selection would need {} MB of working memory for a {} x {} px area (limit {} MB); the document was not changed", + dense_bytes >> 20, + area.width(), + area.height(), + crate::allocation::MAX_DENSE_BYTES >> 20 + ))); + } let mut v = crate::allocation::filled(len, 0.0, "defining a brush from the selection")?; let sc = sel.map_or(1, |sel| sel.channels()); // A selection mask, when present, is a second buffer of the same size; it must fail gracefully too // (review of #5469), so read it through the fallible allocator. let sv = sel.map(|sel| crate::allocation::read_region(sel, area, "defining a brush from the selection")).transpose()?; - // RGB surfaces keep the document's encoding. The other surface models are - // already read as the existing sRGB numeric view (gray repeats its value). + // The compositor keeps RGB document encoding; other document models produce + // the existing RGB numeric view (including the document-profile CMYK conversion). let source = if d.doc.mode == photocraft_color::ColorMode::Rgb { crate::color_cmds::document_profile(&d.doc) } else { @@ -1112,32 +1122,37 @@ fn define_from_selection(s: &mut Session, p: &Value) -> Result { let gray = craft_cms::cached(&source, craft_cms::Builtin::SGray.profile(), options).map_err(|e| bad(cmd, format!("cannot convert brush source to gray: {e}")))?; let mut converted = [0.0f32; 16]; - for y in 0..h { - for x in 0..w { - let selected = sv.as_ref().map_or(1.0, |sv| sv[(y * w + x) * sc]); - // Known-zero contributions leave the freshly zeroed density alone. - if selected == 0.0 { - continue; + // Keep the allocation boundary fallible before entering compositor-owned scratch storage. + crate::allocation::checkpoint("defining a brush from the selection")?; + photocraft_compose::render_bands(&d.doc, area, 0, |band| -> Result<()> { + for (row, pixels) in band.px.chunks_exact(w).enumerate() { + let y = (band.rect.y0 - area.y0) as usize + row; + for (x, c) in pixels.iter().enumerate() { + let selected = sv.as_ref().map_or(1.0, |sv| sv[(y * w + x) * sc]); + // Known-zero contributions leave the freshly zeroed density alone. + if selected == 0.0 { + continue; + } + if c[3] == 0.0 { + continue; + } + // A sampled profile curve can clamp infinity to a finite endpoint; + // reject contributing invalid source values before the CMS can hide them. + if c.iter().any(|channel| !channel.is_finite()) { + return Err(bad(cmd, "brush source contains a non-finite colour channel")); + } + // Composite over white before the nonlinear gray conversion. The + // selection scales the resulting density once; alpha is already in it. + let over_white = [c[0], c[1], c[2]].map(|channel| channel * c[3] + (1.0 - c[3])); + gray.eval(&over_white, &mut converted).map_err(|e| bad(cmd, format!("cannot convert brush source to gray: {e}")))?; + if !converted[0].is_finite() { + return Err(bad(cmd, "brush source converted to a non-finite gray value")); + } + v[y * w + x] = ((1.0 - converted[0]) * selected).clamp(0.0, 1.0); } - let c = surf.rgba(area.x0 + x as i32, area.y0 + y as i32); - if c[3] == 0.0 { - continue; - } - // A sampled profile curve can clamp infinity to a finite endpoint; - // reject contributing invalid source values before the CMS can hide them. - if c.iter().any(|channel| !channel.is_finite()) { - return Err(bad(cmd, "brush source contains a non-finite colour channel")); - } - // Composite over white before the nonlinear gray conversion. The - // selection scales the resulting density once; alpha is already in it. - let over_white = [c[0], c[1], c[2]].map(|channel| channel * c[3] + (1.0 - c[3])); - gray.eval(&over_white, &mut converted).map_err(|e| bad(cmd, format!("cannot convert brush source to gray: {e}")))?; - if !converted[0].is_finite() { - return Err(bad(cmd, "brush source converted to a non-finite gray value")); - } - v[y * w + x] = ((1.0 - converted[0]) * selected).clamp(0.0, 1.0); } - } + Ok(()) + })?; let (brush, tw, th) = sampled_brush(cmd, &v, w, h)?; upsert(s, BrushPreset { name: name.clone(), brush: brush.clone(), builtin: false, group: String::new(), folder: Vec::new(), captures: Default::default() }); s.tools.brush = brush; @@ -1525,3 +1540,6 @@ mod define_brush_no_selection_tests; #[cfg(test)] mod define_brush_color_density_tests; + +#[cfg(test)] +mod define_brush_merged_source_tests; diff --git a/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs b/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs new file mode 100644 index 0000000000..396268db4b --- /dev/null +++ b/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs @@ -0,0 +1,311 @@ +use super::*; +use photocraft_doc::Layer; + +const COMMANDS: [&str; 2] = ["edit.defineBrushPreset", "brush.defineFromSelection"]; + +fn tip(s: &Session) -> &GrayTile { + let TipShape::Sampled(tip) = &s.tools.brush.tip else { panic!("expected a sampled tip") }; + tip +} + +fn source(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 150, "depth": depth, "background": "#ffffff"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Tip"})).unwrap(); + s.edit("Two visible squares", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(Rect::new(50, 40, 90, 70), &[0.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(120, 60, 150, 90), &[128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +#[test] +fn visible_capture_is_identical_with_background_tip_group_or_no_active_layer() { + for command in COMMANDS { + for depth in [8, 16, 32] { + let mut s = source(depth); + let background = s.active().unwrap().doc.layers[0].id; + let painted = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.group", json!({"name": "Empty active group"})).unwrap(); + let group = s.active().unwrap().active_layer.unwrap(); + let mut expected = None; + for active in [Some(background), Some(painted), Some(group), None] { + s.edit("Choose capture-independent active layer", |_, current| { + *current = active; + Ok(()) + }) + .unwrap(); + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + assert!(s.is_enabled(command)); + let made = s.execute(command, json!({"name": "Merged tip"})).unwrap(); + assert_eq!((made["width"].as_u64(), made["height"].as_u64()), (Some(100), Some(50))); + assert_eq!(s.tools.brush.size, 100.0); + assert_eq!(tip(&s).get(0, 0), 1.0); + assert_eq!(tip(&s).get(60, 0), 0.0); + assert!((tip(&s).get(70, 20) - 127.0 / 255.0).abs() < 0.003); + let pixels: Vec<_> = (0..50).flat_map(|y| (0..100).map(move |x| (x, y))).map(|(x, y)| tip(&s).get(x, y)).collect(); + if let Some(expected) = &expected { + assert_eq!(&pixels, expected); + } else { + expected = Some(pixels); + } + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.active().unwrap().active_layer, active); + assert_eq!(s.active().unwrap().history.past_len(), history); + } + } + } +} + +#[test] +fn selection_limits_the_visible_composite_even_with_background_active() { + for command in COMMANDS { + let mut s = source(8); + s.edit("Activate background", |doc, active| { + *active = Some(doc.layers[0].id); + Ok(()) + }) + .unwrap(); + s.execute("select.rect", json!({"x": 115, "y": 55, "width": 40, "height": 40})).unwrap(); + let mask = s.active().unwrap().doc.selection.clone(); + s.execute(command, json!({"name": "Selected composite"})).unwrap(); + assert_eq!((tip(&s).width, tip(&s).height), (30, 30)); + assert!((tip(&s).get(0, 0) - 127.0 / 255.0).abs() < 0.003); + assert_eq!(s.active().unwrap().doc.selection, mask); + } +} + +#[test] +fn visible_group_children_and_occlusion_count_but_hidden_layers_and_groups_do_not() { + for command in COMMANDS { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + s.edit("Visible and hidden composite contributors", |doc, active| { + let mut black = Layer::raster("Nested visible black", doc.pixel_format()); + black.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 5, 5), &[0.0, 0.0, 0.0, 1.0]); + let visible = Layer::group("Visible group", vec![black]); + let mut hidden_black = Layer::raster("Hidden black", doc.pixel_format()); + hidden_black.surface_mut().unwrap().fill_rect(doc.bounds(), &[0.0, 0.0, 0.0, 1.0]); + hidden_black.visible = false; + let mut hidden_group = Layer::group("Hidden ancestor", vec![hidden_black.duplicate()]); + hidden_group.children_mut().unwrap()[0].visible = true; + hidden_group.visible = false; + let mut white = Layer::raster("Visible white occlusion", doc.pixel_format()); + white.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 3, 5), &[1.0, 1.0, 1.0, 1.0]); + *active = Some(hidden_black.id); + doc.layers.extend([visible, hidden_black, hidden_group, white]); + Ok(()) + }) + .unwrap(); + s.execute(command, json!({"name": "Only visible ink"})).unwrap(); + assert_eq!((tip(&s).width, tip(&s).height), (2, 4)); + for y in 0..4 { + for x in 0..2 { + assert_eq!(tip(&s).get(x, y), 1.0); + } + } + } +} + +#[test] +fn composite_transparency_and_selection_coverage_are_applied_once() { + for command in COMMANDS { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth, "background": "transparent"})).unwrap(); + s.edit("Nested translucent source", |doc, active| { + let mut black = Layer::raster("Half black", doc.pixel_format()); + black.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 6, 7), &[0.0, 0.0, 0.0, 0.5]); + let group = Layer::group("Active group", vec![black]); + *active = Some(group.id); + doc.layers.push(group); + Ok(()) + }) + .unwrap(); + for selected in [false, true] { + if selected { + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + s.edit("Quarter coverage", |doc, _| { + doc.selection.as_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[0.25]); + Ok(()) + }) + .unwrap(); + } + s.execute(command, json!({"name": "Translucent composite"})).unwrap(); + assert_eq!((tip(&s).width, tip(&s).height), (5, 6)); + let expected = if selected { 0.125 } else { 0.5 }; + for y in 0..6 { + for x in 0..5 { + assert!((tip(&s).get(x, y) - expected).abs() < 0.003); + } + } + } + } + } +} + +#[test] +fn a_hidden_black_source_over_white_or_transparency_is_empty_and_does_not_replace_a_preset() { + for command in COMMANDS { + for background in ["white", "transparent"] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": background})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Hidden ink"})).unwrap(); + s.edit("Hide all ink", |doc, active| { + let bounds = doc.bounds(); + let layer = doc.layer_mut(active.unwrap()).unwrap(); + layer.surface_mut().unwrap().fill_rect(bounds, &[0.0, 0.0, 0.0, 1.0]); + layer.visible = false; + Ok(()) + }) + .unwrap(); + s.execute("brush.presets.save", json!({"name": "Kept"})).unwrap(); + let brush = s.tools.brush.clone(); + let presets = s.tools.presets.clone(); + let current = s.tools.current_preset.clone(); + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let err = s.execute(command, json!({"name": "Kept"})).unwrap_err(); + assert!(err.to_string().contains("contain no paint"), "{err}"); + assert_eq!(s.tools.brush, brush); + assert_eq!(s.tools.presets, presets); + assert_eq!(s.tools.current_preset, current); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.active().unwrap().history.past_len(), history); + } + } +} + +#[test] +fn merged_rgb_retains_the_document_profile_before_gray_conversion() { + for command in COMMANDS { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": 32, "background": "transparent"})).unwrap(); + s.edit("Linear gray nested under active group", |doc, active| { + doc.icc_profile = Some(craft_cms::Builtin::LinearSrgb.profile().to_bytes()); + let mut layer = Layer::raster("Linear half gray", doc.pixel_format()); + layer.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 5, 5), &[0.5, 0.5, 0.5, 1.0]); + let group = Layer::group("Active group", vec![layer]); + *active = Some(group.id); + doc.layers.push(group); + Ok(()) + }) + .unwrap(); + s.execute(command, json!({"name": "Profiled merged tip"})).unwrap(); + assert_eq!((tip(&s).width, tip(&s).height), (4, 4)); + // Encoded sGray for linear RGB 0.5 is about 0.735, not encoded RGB 0.5. + assert!((tip(&s).get(0, 0) - 0.265).abs() < 0.01); + } +} + +fn sparse_budget_source(width: u32, height: u32, selected: bool) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": width, "height": height, "background": "transparent"})).unwrap(); + s.edit("Sparse composite budget fixture", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(Rect::new(0, 0, 1, 1), &[0.0, 0.0, 0.0, 1.0]); + assert_eq!(surf.tile_count(), 1); + if selected { + let mut mask = Surface::new(photocraft_color::PixelFormat::GRAY8); + mask.fill_rect(Rect::new(0, 0, 1, 1), &[1.0]); + mask.fill_rect(Rect::new(width as i32 - 1, height as i32 - 1, width as i32, height as i32), &[1.0]); + assert_eq!(mask.tile_count(), 2); + assert_eq!(mask.content_bounds(), doc.bounds()); + doc.selection = Some(mask); + } + Ok(()) + }) + .unwrap(); + s +} + +#[test] +fn composite_storage_is_counted_with_density_and_mask_before_any_allocation() { + const WIDTH: u32 = 32768; + for command in COMMANDS { + for selected in [false, true] { + // Density plus optional mask fit exactly; the simultaneously live RGBA band + // must also count, even though the document itself is sparse. + let bytes = if selected { 8 } else { 4 }; + let height = (crate::allocation::MAX_DENSE_BYTES / (bytes * u64::from(WIDTH))) as u32; + let mut s = sparse_budget_source(WIDTH, height, selected); + let doc = s.active().unwrap().doc.clone(); + let brush = s.tools.brush.clone(); + let presets = s.tools.presets.clone(); + let current = s.tools.current_preset.clone(); + let history = s.active().unwrap().history.past_len(); + crate::allocation::fail_next_for_test(); + let result = s.execute(command, json!({"name": "Composite over budget"})); + let unspent = crate::allocation::capacity::(0, "consume composite budget failpoint"); + let err = result.unwrap_err(); + assert!(err.to_string().contains("working memory"), "{err}"); + assert!(unspent.is_err(), "budget refusal must precede the first allocation"); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.active().unwrap().history.past_len(), history); + assert_eq!(s.tools.brush, brush); + assert_eq!(s.tools.presets, presets); + assert_eq!(s.tools.current_preset, current); + } + } +} + +#[test] +fn compositor_allocation_boundary_failure_preserves_source_and_preset_state() { + for command in COMMANDS { + for selected in [false, true] { + let mut s = source(8); + if selected { + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 150})).unwrap(); + } + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let brush = s.tools.brush.clone(); + let presets = s.tools.presets.clone(); + let current = s.tools.current_preset.clone(); + crate::allocation::fail_after_for_test(if selected { 2 } else { 1 }); + let result = s.execute(command, json!({"name": "Compositor allocation failure"})); + let _ = crate::allocation::capacity::(0, "reset compositor failpoint"); + let err = result.unwrap_err(); + assert!(err.to_string().contains("not enough memory"), "{err}"); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.active().unwrap().history.past_len(), history); + assert_eq!(s.tools.brush, brush); + assert_eq!(s.tools.presets, presets); + assert_eq!(s.tools.current_preset, current); + } + } +} + +#[test] +fn a_banded_capture_that_fits_the_budget_is_not_charged_for_a_full_rgba_canvas() { + const WIDTH: u32 = 32768; + let band_rows = photocraft_compose::band_rows_for(WIDTH, 0) as u64; + let band_bytes = u64::from(WIDTH) * band_rows * 16; + for command in COMMANDS { + for selected in [false, true] { + let sample_bytes = if selected { 8 } else { 4 }; + let height = ((crate::allocation::MAX_DENSE_BYTES - band_bytes) / (sample_bytes * u64::from(WIDTH))) as u32; + let pixels = u64::from(WIDTH) * u64::from(height); + assert!(pixels * sample_bytes + band_bytes <= crate::allocation::MAX_DENSE_BYTES); + assert!(pixels * (sample_bytes + 16) > crate::allocation::MAX_DENSE_BYTES, "a full-plane estimate would incorrectly reject this fixture"); + let mut s = sparse_budget_source(WIDTH, height, selected); + let doc = s.active().unwrap().doc.clone(); + let brush = s.tools.brush.clone(); + let presets = s.tools.presets.clone(); + // Refuse the first real allocation, after verifying that the budget allowed it. + crate::allocation::fail_next_for_test(); + let result = s.execute(command, json!({"name": "Fits with bands"})); + let unspent = crate::allocation::capacity::(0, "consume band acceptance failpoint"); + let err = result.unwrap_err().to_string(); + assert!(err.contains("not enough memory") && !err.contains("working memory"), "{err}"); + assert!(unspent.is_ok(), "the accepted budget must reach the first allocation"); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.tools.brush, brush); + assert_eq!(s.tools.presets, presets); + } + } +} diff --git a/crates/engine/src/cmd/brush_cmds/define_brush_no_selection_tests.rs b/crates/engine/src/cmd/brush_cmds/define_brush_no_selection_tests.rs index a4ba93696b..71e42f6308 100644 --- a/crates/engine/src/cmd/brush_cmds/define_brush_no_selection_tests.rs +++ b/crates/engine/src/cmd/brush_cmds/define_brush_no_selection_tests.rs @@ -87,7 +87,7 @@ fn a_partial_selection_keeps_coverage_alpha_and_canvas_clipping() { } #[test] -fn no_document_and_non_pixel_active_layers_keep_their_disabled_state() { +fn no_document_is_disabled_and_a_group_active_capture_uses_visible_pixels() { let mut s = Session::new(); for command in COMMANDS { assert!(!s.is_enabled(command)); @@ -96,8 +96,9 @@ fn no_document_and_non_pixel_active_layers_keep_their_disabled_state() { s = source(8); s.execute("layer.new.group", json!({"name": "Not pixels"})).unwrap(); for command in COMMANDS { - assert!(!s.is_enabled(command)); - assert!(s.execute(command, json!({"name": "No pixel layer"})).is_err()); + assert!(s.is_enabled(command)); + s.execute(command, json!({"name": "Visible pixels"})).unwrap(); + assert_eq!((tip(&s).width, tip(&s).height), (100, 50)); } } From 8c872b71b9aa856fbc79a1a5fe6ed5acf764d96d Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 02:05:48 -0800 Subject: [PATCH 22/46] Remove the obsolete active-layer content import --- crates/engine/src/cmd/brush_cmds.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 2b9af776f0..41c14bf0b5 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -6,7 +6,6 @@ //! (`{"scattering": {"enabled": true}}`). Strokes are deterministic: the jitter seed is the `seed` //! param or a hash of the points, so a journaled command replays to identical pixels. -use photocraft_doc::LayerContent; use photocraft_geom::Rect; use photocraft_paint::mixer::{MixerSettings, MixerState}; use photocraft_paint::replace::{Limits, ReplaceMode, ReplaceSettings, Sampling, apply_color_replacement, color_replacement_effect}; From 6201e36e31bce0d330786ded50f8e68e32c52b14 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 02:30:59 -0800 Subject: [PATCH 23/46] Refuse known embedded-image omissions in pixel-only SVG rasterizers Keep warning-bearing imports and non-strict bounded placement unchanged. --- crates/io/src/svg.rs | 14 ++++++++++++-- crates/io/src/svg/tests.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 8ccab63d59..ae150a349d 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -1168,11 +1168,21 @@ fn import_parsed_with_limits( Ok(ImportResult { document: doc, warnings: conv.warnings, source_read_only: false, preview_only: false }) } +// These entry points return only pixels, with no warning channel. Refuse a partial drawing +// instead of silently losing images; bounded placement deliberately retains its non-strict policy. +fn complete_rasterization_tree(bytes: &[u8]) -> Result { + let Parsed { tree, omitted_images, .. } = parse(bytes)?; + if omitted_images { + return Err(IoError::Svg("embedded images were omitted; the drawing cannot be rasterised completely".into())); + } + Ok(tree) +} + /// The whole drawing rendered at `scale` (1 = its own size), as a straight-alpha RGBA buffer at /// the origin. Smart objects use it to stay sharp at any placement. pub fn rasterize(bytes: &[u8], scale: f32) -> Result { on_svg_stack(|| { - let tree = parse(bytes)?.tree; + let tree = complete_rasterization_tree(bytes)?; rasterize_tree(&tree, scale) }) } @@ -1209,7 +1219,7 @@ fn rasterize_tree(tree: &usvg::Tree, scale: f32) -> Result Result<(u32, u32, Vec), IoError> { on_svg_stack(|| { - let tree = parse(bytes)?.tree; + let tree = complete_rasterization_tree(bytes)?; let cv = canvas(&tree, &mut Vec::new()); let (w, h) = (f64::from(tree.size().width() * cv.scale), f64::from(tree.size().height() * cv.scale)); // The largest k ≤ 1 with (w·k + 2)(h·k + 2) ≤ the limit: `render` rounds each side up, and diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index ad3839c67e..872e5a0448 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -1616,4 +1616,30 @@ fn imports_warn_when_embedded_images_are_omitted() { assert_eq!(omission_warnings(&bounded), 1, "{:?}", bounded.warnings); assert_eq!(photocraft_compose::flatten(&bounded.document).to_rgba8().pixels, vec![255, 0, 0, 255], "the bounded import retains the red rectangle"); assert!(parse_bounded_work_with(svg.as_bytes(), MAX_RASTER_PIXELS, true, fonts).is_err(), "stored previews must still be complete"); + // Pixel-only rasterizers cannot return the ordinary import's omission warning. + // Keep the original damaged and oversized inputs; a readable rectangle must not hide loss. + let oversized_svg = image_svg(&format!("{oversized}{oversized}{rect}")); + for source in [&oversized_svg, &svg] { + assert!(parse(source.as_bytes()).unwrap().omitted_images, "fixture must exercise a resolver omission"); + let scaled = rasterize(source.as_bytes(), 1.0).unwrap_err(); + let rgba8 = rasterize_rgba8(source.as_bytes()).unwrap_err(); + for error in [scaled, rgba8] { + assert!(matches!(&error, IoError::Svg(message) if message.contains("embedded images were omitted")), "{error}"); + } + } + // Externally edited SVG placement intentionally remains non-strict about unreadable images. + let placed = rasterize_bounded(svg.as_bytes(), 1.0, MAX_RASTER_PIXELS).unwrap(); + assert_eq!(placed.px, vec![[1.0, 0.0, 0.0, 1.0]]); + // Complete drawings still rasterize to the same literal pixels, with and without an image. + let blue = photocraft_codecs::Image::from_u8(1, 1, photocraft_codecs::ChannelLayout::Rgb, vec![0, 0, 255]).unwrap(); + let png = photocraft_codecs::encode(&blue, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + for (source, expected) in [(image_svg(rect), [255u8, 0, 0, 255]), (image_svg(&embedded_image("image/png", &png)), [0u8, 0, 255, 255])] { + assert!(!parse(source.as_bytes()).unwrap().omitted_images); + let (width, height, pixels) = rasterize_rgba8(source.as_bytes()).unwrap(); + assert_eq!((width, height), (1, 1)); + assert_eq!(pixels, expected); + let scaled = rasterize(source.as_bytes(), 1.0).unwrap(); + assert_eq!(scaled.rect, Rect::new(0, 0, 1, 1)); + assert_eq!(scaled.px, vec![expected.map(|channel| f32::from(channel) / 255.0)]); + } } From 9fdb35a8631e4a8f19de3ed89cedcdaa357f1c04 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 02:35:18 -0800 Subject: [PATCH 24/46] Preserve reported image omissions in pixel-only SVG APIs --- crates/io/src/svg.rs | 14 ++++++++++++-- crates/io/src/svg/tests.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 8ccab63d59..ae150a349d 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -1168,11 +1168,21 @@ fn import_parsed_with_limits( Ok(ImportResult { document: doc, warnings: conv.warnings, source_read_only: false, preview_only: false }) } +// These entry points return only pixels, with no warning channel. Refuse a partial drawing +// instead of silently losing images; bounded placement deliberately retains its non-strict policy. +fn complete_rasterization_tree(bytes: &[u8]) -> Result { + let Parsed { tree, omitted_images, .. } = parse(bytes)?; + if omitted_images { + return Err(IoError::Svg("embedded images were omitted; the drawing cannot be rasterised completely".into())); + } + Ok(tree) +} + /// The whole drawing rendered at `scale` (1 = its own size), as a straight-alpha RGBA buffer at /// the origin. Smart objects use it to stay sharp at any placement. pub fn rasterize(bytes: &[u8], scale: f32) -> Result { on_svg_stack(|| { - let tree = parse(bytes)?.tree; + let tree = complete_rasterization_tree(bytes)?; rasterize_tree(&tree, scale) }) } @@ -1209,7 +1219,7 @@ fn rasterize_tree(tree: &usvg::Tree, scale: f32) -> Result Result<(u32, u32, Vec), IoError> { on_svg_stack(|| { - let tree = parse(bytes)?.tree; + let tree = complete_rasterization_tree(bytes)?; let cv = canvas(&tree, &mut Vec::new()); let (w, h) = (f64::from(tree.size().width() * cv.scale), f64::from(tree.size().height() * cv.scale)); // The largest k ≤ 1 with (w·k + 2)(h·k + 2) ≤ the limit: `render` rounds each side up, and diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index ad3839c67e..872e5a0448 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -1616,4 +1616,30 @@ fn imports_warn_when_embedded_images_are_omitted() { assert_eq!(omission_warnings(&bounded), 1, "{:?}", bounded.warnings); assert_eq!(photocraft_compose::flatten(&bounded.document).to_rgba8().pixels, vec![255, 0, 0, 255], "the bounded import retains the red rectangle"); assert!(parse_bounded_work_with(svg.as_bytes(), MAX_RASTER_PIXELS, true, fonts).is_err(), "stored previews must still be complete"); + // Pixel-only rasterizers cannot return the ordinary import's omission warning. + // Keep the original damaged and oversized inputs; a readable rectangle must not hide loss. + let oversized_svg = image_svg(&format!("{oversized}{oversized}{rect}")); + for source in [&oversized_svg, &svg] { + assert!(parse(source.as_bytes()).unwrap().omitted_images, "fixture must exercise a resolver omission"); + let scaled = rasterize(source.as_bytes(), 1.0).unwrap_err(); + let rgba8 = rasterize_rgba8(source.as_bytes()).unwrap_err(); + for error in [scaled, rgba8] { + assert!(matches!(&error, IoError::Svg(message) if message.contains("embedded images were omitted")), "{error}"); + } + } + // Externally edited SVG placement intentionally remains non-strict about unreadable images. + let placed = rasterize_bounded(svg.as_bytes(), 1.0, MAX_RASTER_PIXELS).unwrap(); + assert_eq!(placed.px, vec![[1.0, 0.0, 0.0, 1.0]]); + // Complete drawings still rasterize to the same literal pixels, with and without an image. + let blue = photocraft_codecs::Image::from_u8(1, 1, photocraft_codecs::ChannelLayout::Rgb, vec![0, 0, 255]).unwrap(); + let png = photocraft_codecs::encode(&blue, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + for (source, expected) in [(image_svg(rect), [255u8, 0, 0, 255]), (image_svg(&embedded_image("image/png", &png)), [0u8, 0, 255, 255])] { + assert!(!parse(source.as_bytes()).unwrap().omitted_images); + let (width, height, pixels) = rasterize_rgba8(source.as_bytes()).unwrap(); + assert_eq!((width, height), (1, 1)); + assert_eq!(pixels, expected); + let scaled = rasterize(source.as_bytes(), 1.0).unwrap(); + assert_eq!(scaled.rect, Rect::new(0, 0, 1, 1)); + assert_eq!(scaled.px, vec![expected.map(|channel| f32::from(channel) / 255.0)]); + } } From a4a466b65a852f07ddbad7ba9cbaee625b4cb773 Mon Sep 17 00:00:00 2001 From: Yoris Date: Sun, 15 Nov 2026 10:59:02 -0800 Subject: [PATCH 25/46] Keep CI-produced photocraft-text lock dependencies canonical --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index d3935c94a4..03aadc6d20 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5859,8 +5859,8 @@ dependencies = [ name = "photocraft-text" version = "0.23.1" dependencies = [ - "craft-plist", "base64 0.23.1", + "craft-plist", "craft-psd", "flate2", "parley", From d4b3174d4af4e0d732ee25b95a0a6cb83d306d58 Mon Sep 17 00:00:00 2001 From: Yoris Date: Sun, 15 Nov 2026 13:37:13 -0800 Subject: [PATCH 26/46] Match upstream shortcut fixture initializer without changing assertions --- .../ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs index 31bc9bf711..68a82501d9 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs @@ -165,9 +165,8 @@ fn an_unmodified_set_switches_at_once() { fn an_action_function_key_is_no_edit() { let (mut h, first) = dialog(); h.state_mut().ui.dialogs.retain(|d| d.id != first); - let sepia = h.state().session.actions.list.len(); - h.state_mut().session.actions.list.push(photocraft_engine::actions_cmds::Action::new("Sepia", vec![])); - crate::actions::assign_shortcut(h.state_mut(), sepia, "F2").unwrap(); + h.state_mut().session.actions.list.push(photocraft_engine::actions_cmds::Action::new("Sepia", Vec::new())); + crate::actions::assign_shortcut(h.state_mut(), 0, "F2").unwrap(); let ctx = h.ctx.clone(); let id = crate::menus::invoke(h.state_mut(), &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); h.run_steps(4); From 785f38df56fded99a13c95bc89168b5eb0046136 Mon Sep 17 00:00:00 2001 From: Codex WORK source candidate Date: Sun, 15 Nov 2026 16:01:21 -0800 Subject: [PATCH 27/46] Narrow visible-source change to issue 14271 --- crates/engine/src/cmd/brush_cmds.rs | 51 +-- .../define_brush_color_density_tests.rs | 327 ------------------ .../define_brush_merged_source_tests.rs | 176 ++++------ .../define_brush_no_selection_tests.rs | 235 ------------- crates/engine/src/cmd/edit_menu_cmds/tests.rs | 2 +- 5 files changed, 87 insertions(+), 704 deletions(-) delete mode 100644 crates/engine/src/cmd/brush_cmds/define_brush_color_density_tests.rs delete mode 100644 crates/engine/src/cmd/brush_cmds/define_brush_no_selection_tests.rs diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 41c14bf0b5..6a2b8b0634 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -1066,7 +1066,13 @@ fn presets_set_current(s: &mut Session, p: &Value) -> Result { } fn has_selection_and_pixels(s: &Session) -> std::result::Result<(), String> { - s.active().ok_or("no document")?; + let d = s.active().ok_or("no document")?; + if d.doc.selection.is_none() { + return Err("no selection".into()); + } + if d.active_layer.and_then(|id| d.doc.layer(id)).is_none() { + return Err("no active layer".into()); + } Ok(()) } @@ -1077,8 +1083,8 @@ fn define_from_selection(s: &mut Session, p: &Value) -> Result { let cmd = "brush.defineFromSelection"; let name = name_param(p, cmd)?; let d = s.active().ok_or(EngineError::NoDocument)?; - let sel = d.doc.selection.as_ref(); - let area = sel.map_or_else(|| d.doc.bounds(), |sel| sel.content_bounds().intersect(&d.doc.bounds())); + let sel = d.doc.selection.as_ref().ok_or_else(|| bad(cmd, "no selection"))?; + let area = sel.content_bounds().intersect(&d.doc.bounds()); if area.is_empty() { return Err(bad(cmd, "the selection is empty")); } @@ -1092,7 +1098,7 @@ fn define_from_selection(s: &mut Session, p: &Value) -> Result { // Sparse canvases can span huge areas. Density and selection remain live while the // compositor holds one RGBA band, not a full-canvas RGBA plane; account for that // actual maximum band before allocating any sampling buffers. - let mask_bytes = sel.map_or(0, |sel| (sel.channels() as u64).saturating_mul(4)); + let mask_bytes = (sel.channels() as u64).saturating_mul(4); let band_rows = area.height().min(photocraft_compose::band_rows_for(area.width(), 0) as u32); let band_bytes = u64::from(area.width()).saturating_mul(u64::from(band_rows)).saturating_mul(16); let dense_bytes = (len as u64).saturating_mul(4u64.saturating_add(mask_bytes)).saturating_add(band_bytes); @@ -1106,28 +1112,17 @@ fn define_from_selection(s: &mut Session, p: &Value) -> Result { ))); } let mut v = crate::allocation::filled(len, 0.0, "defining a brush from the selection")?; - let sc = sel.map_or(1, |sel| sel.channels()); + let sc = sel.channels(); // A selection mask, when present, is a second buffer of the same size; it must fail gracefully too // (review of #5469), so read it through the fallible allocator. - let sv = sel.map(|sel| crate::allocation::read_region(sel, area, "defining a brush from the selection")).transpose()?; - // The compositor keeps RGB document encoding; other document models produce - // the existing RGB numeric view (including the document-profile CMYK conversion). - let source = if d.doc.mode == photocraft_color::ColorMode::Rgb { - crate::color_cmds::document_profile(&d.doc) - } else { - crate::color_cmds::working_profile(photocraft_color::ColorMode::Rgb) - }; - let options = craft_cms::TransformOptions { intent: craft_cms::Intent::RelativeColorimetric, bpc: true, ..Default::default() }; - let gray = - craft_cms::cached(&source, craft_cms::Builtin::SGray.profile(), options).map_err(|e| bad(cmd, format!("cannot convert brush source to gray: {e}")))?; - let mut converted = [0.0f32; 16]; + let sv = crate::allocation::read_region(sel, area, "defining a brush from the selection")?; // Keep the allocation boundary fallible before entering compositor-owned scratch storage. crate::allocation::checkpoint("defining a brush from the selection")?; photocraft_compose::render_bands(&d.doc, area, 0, |band| -> Result<()> { for (row, pixels) in band.px.chunks_exact(w).enumerate() { let y = (band.rect.y0 - area.y0) as usize + row; for (x, c) in pixels.iter().enumerate() { - let selected = sv.as_ref().map_or(1.0, |sv| sv[(y * w + x) * sc]); + let selected = sv[(y * w + x) * sc]; // Known-zero contributions leave the freshly zeroed density alone. if selected == 0.0 { continue; @@ -1135,19 +1130,8 @@ fn define_from_selection(s: &mut Session, p: &Value) -> Result { if c[3] == 0.0 { continue; } - // A sampled profile curve can clamp infinity to a finite endpoint; - // reject contributing invalid source values before the CMS can hide them. - if c.iter().any(|channel| !channel.is_finite()) { - return Err(bad(cmd, "brush source contains a non-finite colour channel")); - } - // Composite over white before the nonlinear gray conversion. The - // selection scales the resulting density once; alpha is already in it. - let over_white = [c[0], c[1], c[2]].map(|channel| channel * c[3] + (1.0 - c[3])); - gray.eval(&over_white, &mut converted).map_err(|e| bad(cmd, format!("cannot convert brush source to gray: {e}")))?; - if !converted[0].is_finite() { - return Err(bad(cmd, "brush source converted to a non-finite gray value")); - } - v[y * w + x] = ((1.0 - converted[0]) * selected).clamp(0.0, 1.0); + let lum = photocraft_color::blend::lum([c[0], c[1], c[2]]); + v[y * w + x] = ((1.0 - lum) * c[3] * selected).clamp(0.0, 1.0); } } Ok(()) @@ -1534,11 +1518,6 @@ mod mixer_live_tests; #[path = "color_replacement_history_name_tests.rs"] mod color_replacement_history_name_tests; -#[cfg(test)] -mod define_brush_no_selection_tests; - -#[cfg(test)] -mod define_brush_color_density_tests; #[cfg(test)] mod define_brush_merged_source_tests; diff --git a/crates/engine/src/cmd/brush_cmds/define_brush_color_density_tests.rs b/crates/engine/src/cmd/brush_cmds/define_brush_color_density_tests.rs deleted file mode 100644 index 44cd5e052a..0000000000 --- a/crates/engine/src/cmd/brush_cmds/define_brush_color_density_tests.rs +++ /dev/null @@ -1,327 +0,0 @@ -//! Numeric falsifier for issue #14273; this does not change brush capture. -//! -//! Inputs are encoded sRGB RGB8 samples, composited over encoded white before -//! the cached sRGB -> sGray transform. Density is one minus encoded gray, then -//! multiplied by selection coverage exactly once. Arbitrary document profiles, -//! HDR/non-RGB sources and actual stamping remain outside this probe. - -use std::sync::Arc; - -use craft_cms::{Builtin, Intent, TransformOptions}; - -#[test] -fn sgray_matches_six_literal_density_targets_and_alpha_selection_controls() { - let source = Arc::new(Builtin::Srgb.profile().clone()); - let gray = Arc::new(Builtin::SGray.profile().clone()); - let options = TransformOptions { intent: Intent::RelativeColorimetric, bpc: true, ..Default::default() }; - let transform = craft_cms::cached(&source, &gray, options).unwrap(); - let gray_value = |rgb: [f32; 3]| { - // Same public API and output scratch size as color_cmds::swatch_in_doc. - let mut output = [0.0f32; 16]; - transform.eval(&rgb, &mut output).unwrap(); - assert!(output[0].is_finite(), "the CMS must return a finite gray value"); - output[0].clamp(0.0, 1.0) - }; - let density = |rgb: [f32; 3], alpha: f32, selection: f32| { - let over_white = rgb.map(|channel| channel * alpha + (1.0 - alpha)); - (1.0 - gray_value(over_white)) * selection - }; - - // Independent measured targets from #14273, not values derived from the - // candidate transform or the command's existing fixed luminance weights. - let mut mismatches = Vec::new(); - for (name, rgb, expected, tolerance) in [ - ("red", [255u8, 0, 0], 0.49f32, 0.03f32), - ("green", [0, 255, 0], 0.14, 0.03), - ("blue", [0, 0, 255], 0.72, 0.03), - ("gray 128", [128, 128, 128], 0.50, 0.01), - ("gray 200", [200, 200, 200], 0.22, 0.01), - ("black", [0, 0, 0], 1.0, 0.0001), - ] { - let actual = density(rgb.map(|value| f32::from(value) / 255.0), 1.0, 1.0); - eprintln!("{name}: density {actual:.6}, target {expected:.6} +/- {tolerance:.6}"); - if (actual - expected).abs() > tolerance { - mismatches.push(format!("{name}: {actual:.6}, expected {expected:.6} +/- {tolerance:.6}")); - } - } - assert!(mismatches.is_empty(), "sGray candidate fails measured targets:\n{}", mismatches.join("\n")); - - // Transparency is white, not an extra multiplier applied after the CMS. - assert!(density([0.0, 0.0, 1.0], 0.0, 1.0).abs() <= 0.0001); - assert!((density([0.0; 3], 0.5, 1.0) - 0.5).abs() <= 0.01); - assert!((density([0.0; 3], 1.0, 0.25) - 0.25).abs() <= 0.0001); - assert!((density([0.0; 3], 0.5, 0.5) - 0.25).abs() <= 0.01, "alpha or selection must not be applied twice"); - assert_eq!(density([1.0, 0.0, 0.0], 1.0, 0.0), 0.0); - - // This is an ordering control, not a new measured coloured-alpha target: - // half-transparent red is the explicit RGB sample [1, .5, .5] over white. - let half_red = density([1.0, 0.0, 0.0], 0.5, 1.0); - let explicit_over_white = 1.0 - gray_value([1.0, 0.5, 0.5]); - assert_eq!(half_red, explicit_over_white); -} - -use super::{GrayTile, Session, TipShape, json}; - -const COMMANDS: [&str; 2] = ["brush.defineFromSelection", "edit.defineBrushPreset"]; - -fn rgb_source(depth: u32, rgba: [f32; 4]) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth, "background": "#ffffff"})).unwrap(); - s.edit("Colour square", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 10, 30, 30), &rgba); - Ok(()) - }) - .unwrap(); - s -} - -fn tip(s: &Session) -> &GrayTile { - let TipShape::Sampled(tip) = &s.tools.brush.tip else { panic!("expected a sampled tip") }; - tip -} - -fn define_square(s: &mut Session, command: &str, selected: bool) -> f32 { - if selected { - s.execute("select.rect", json!({"x": 8, "y": 8, "width": 24, "height": 24})).unwrap(); - } - let doc = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.past_len(); - let presets = s.tools.presets.len(); - let result = s.execute(command, json!({"name": "Colour density"})).unwrap(); - assert_eq!((result["width"].as_u64(), result["height"].as_u64()), (Some(20), Some(20))); - assert_eq!((tip(s).width, tip(s).height), (20, 20)); - assert_eq!(s.tools.presets.len(), presets + 1); - assert_eq!(s.tools.current_preset.as_deref(), Some("Colour density")); - assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); - assert_eq!(s.active().unwrap().history.past_len(), history); - assert_eq!(s.active().unwrap().doc.selection.is_some(), selected); - tip(s).get(10, 10) -} - -#[test] -fn defined_tips_match_the_six_measured_density_targets_at_all_depths() { - for command in COMMANDS { - for depth in [8, 16, 32] { - for selected in [false, true] { - for (name, rgb, expected, tolerance) in [ - ("red", [255u8, 0, 0], 0.49f32, 0.03f32), - ("green", [0, 255, 0], 0.14, 0.03), - ("blue", [0, 0, 255], 0.72, 0.03), - ("gray 128", [128, 128, 128], 0.50, 0.01), - ("gray 200", [200, 200, 200], 0.22, 0.01), - ("black", [0, 0, 0], 1.0, 0.0001), - ] { - let [r, g, b] = rgb.map(|v| f32::from(v) / 255.0); - let mut s = rgb_source(depth, [r, g, b, 1.0]); - let actual = define_square(&mut s, command, selected); - assert!((actual - expected).abs() <= tolerance, "{command}, {name}, depth {depth}, selected {selected}: {actual}"); - } - } - } - } -} - -#[test] -fn command_density_applies_alpha_before_gray_and_selection_once() { - for command in COMMANDS { - for (alpha, coverage, expected) in [(0.5, 1.0, 0.5), (1.0, 0.25, 0.25), (0.5, 0.5, 0.25)] { - let mut s = rgb_source(32, [0.0, 0.0, 0.0, alpha]); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - s.edit("Selection coverage", |doc, _| { - doc.selection.as_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 10, 30, 30), &[coverage]); - Ok(()) - }) - .unwrap(); - s.execute(command, json!({"name": "Coverage"})).unwrap(); - assert!((tip(&s).get(10, 10) - expected).abs() <= 0.01, "{command}, alpha {alpha}, coverage {coverage}"); - } - - // An explicit over-white RGB square is an independent way to provide the - // same colour; this is an ordering control, not a new reference target. - let mut half_red = rgb_source(32, [1.0, 0.0, 0.0, 0.5]); - let mut over_white = rgb_source(32, [1.0, 0.5, 0.5, 1.0]); - let half = define_square(&mut half_red, command, false); - let opaque = define_square(&mut over_white, command, false); - assert!((half - opaque).abs() <= 1.0 / 65535.0); - - let mut transparent = rgb_source(32, [0.0, 0.0, 1.0, 0.0]); - let brush = transparent.tools.brush.clone(); - let presets = transparent.tools.presets.clone(); - let err = transparent.execute(command, json!({"name": "Transparent colour"})).unwrap_err(); - assert!(err.to_string().contains("contain no paint"), "{err}"); - assert_eq!(transparent.tools.brush, brush); - assert_eq!(transparent.tools.presets, presets); - } -} - -#[test] -fn tagged_rgb_uses_the_document_encoding() { - for command in COMMANDS { - let mut tagged = rgb_source(32, [0.5, 0.5, 0.5, 1.0]); - tagged - .edit("Assign linear RGB", |doc, _| { - doc.icc_profile = Some(Builtin::LinearSrgb.profile().to_bytes()); - Ok(()) - }) - .unwrap(); - let explicit = craft_cms::cached(Builtin::LinearSrgb.profile(), Builtin::SGray.profile(), TransformOptions::default()).unwrap(); - let mut gray = [0.0f32; 16]; - explicit.eval(&[0.5, 0.5, 0.5], &mut gray).unwrap(); - let actual = define_square(&mut tagged, command, false); - assert!((actual - (1.0 - gray[0])).abs() <= 1.0 / 65535.0); - - let mut srgb = rgb_source(32, [0.5, 0.5, 0.5, 1.0]); - let untagged = define_square(&mut srgb, command, false); - assert!((actual - untagged).abs() > 0.1, "the fixture must distinguish profile encoding"); - } -} - -#[test] -fn native_gray_keeps_numeric_density_in_its_existing_rgb_view() { - for command in COMMANDS { - for depth in [8, 16, 32] { - for profile in [None, Some(Builtin::DotGain20Compat), Some(Builtin::GrayGamma22)] { - for value in [128.0 / 255.0, 200.0 / 255.0, 0.0] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 40, "mode": "gray", "depth": depth, "background": "white"})).unwrap(); - s.edit("Native gray square", |doc, active| { - doc.icc_profile = profile.map(|p| p.profile().to_bytes()); - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 10, 30, 30), &[value, 1.0]); - Ok(()) - }) - .unwrap(); - let actual = define_square(&mut s, command, false); - assert!((actual - (1.0 - value)).abs() <= 0.0001, "{command}, depth {depth}, profile {profile:?}, value {value}: {actual}"); - } - } - } - } -} - -#[test] -fn zero_alpha_and_zero_selection_skip_hidden_colour() { - for command in COMMANDS { - for transparent in [true, false] { - for rgb in [[0.0, 0.0, 1.0], [f32::NAN, f32::INFINITY, f32::NEG_INFINITY]] { - let mut s = rgb_source(32, [0.0, 0.0, 0.0, 1.0]); - let hole = photocraft_geom::Rect::new(15, 15, 25, 25); - s.edit("Hidden colour", |doc, active| { - let alpha = if transparent { 0.0 } else { 1.0 }; - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(hole, &[rgb[0], rgb[1], rgb[2], alpha]); - Ok(()) - }) - .unwrap(); - let st = s.active().unwrap(); - let stored = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(20, 20); - assert_eq!(stored[3], if transparent { 0.0 } else { 1.0 }); - for channel in 0..3 { - if rgb[channel].is_nan() { - assert!(stored[channel].is_nan(), "the non-finite fixture must reach the source read"); - } else { - assert_eq!(stored[channel], rgb[channel]); - } - } - if !transparent { - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - s.edit("Zero coverage hole", |doc, _| { - doc.selection.as_mut().unwrap().fill_rect(hole, &[0.0]); - Ok(()) - }) - .unwrap(); - // The hole stays inside the sampled area, rather than being - // removed by selection bounds before the per-pixel check. - assert_eq!(s.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(), photocraft_geom::Rect::new(10, 10, 30, 30)); - } - let doc = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.past_len(); - let presets = s.tools.presets.len(); - - let made = s.execute(command, json!({"name": "Visible black border"})).unwrap(); - - assert_eq!((made["width"].as_u64(), made["height"].as_u64()), (Some(20), Some(20))); - assert_eq!(tip(&s).get(0, 0), 1.0); - assert_eq!(tip(&s).get(19, 19), 1.0); - assert_eq!(tip(&s).get(5, 5), 0.0, "hidden colour contributes no paint"); - assert_eq!(tip(&s).get(14, 14), 0.0); - assert_eq!(s.tools.presets.len(), presets + 1); - assert_eq!(s.tools.current_preset.as_deref(), Some("Visible black border")); - assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); - assert_eq!(s.active().unwrap().history.past_len(), history); - } - } - } -} - -#[test] -fn sampled_trcs_cannot_hide_non_finite_contributing_channels() { - let mut profile = Builtin::Srgb.profile().clone(); - profile.trc = profile.trc.take().map(|curves| curves.map(|curve| craft_cms::Curve::Table(curve.sample(256)))); - // Reset the built-in's encoded bytes and cache key after replacing its curves. - let icc = profile.with_encoded_bytes().to_bytes(); - let parsed = craft_cms::Profile::parse(&icc).unwrap(); - assert!(parsed.trc.as_ref().unwrap().iter().all(|curve| matches!(curve, craft_cms::Curve::Table(_)))); - let options = TransformOptions { intent: Intent::RelativeColorimetric, bpc: true, ..Default::default() }; - let gray = craft_cms::cached(&parsed, Builtin::SGray.profile(), options).unwrap(); - let mut converted = [0.0f32; 16]; - gray.eval(&[f32::INFINITY, 0.0, 0.0], &mut converted).unwrap(); - assert!(converted[0].is_finite(), "the sampled-TRC fixture must expose clamping before the command's gray check"); - - for command in COMMANDS { - for selected in [false, true] { - let mut finite = rgb_source(32, [1.0, 0.0, 0.0, 1.0]); - finite - .edit("Assign sampled sRGB", |doc, _| { - doc.icc_profile = Some(icc.clone()); - Ok(()) - }) - .unwrap(); - assert!((define_square(&mut finite, command, selected) - 0.49).abs() <= 0.03); - - for rgba in [ - [f32::INFINITY, 0.0, 0.0, 1.0], - [0.0, f32::INFINITY, 0.0, 1.0], - [0.0, 0.0, f32::INFINITY, 1.0], - [0.0, 0.0, 0.0, f32::INFINITY], - [f32::NAN, 0.0, 0.0, 1.0], - [f32::NEG_INFINITY, 0.0, 0.0, 1.0], - ] { - let mut s = rgb_source(32, rgba); - s.edit("Assign sampled sRGB", |doc, _| { - doc.icc_profile = Some(icc.clone()); - Ok(()) - }) - .unwrap(); - if selected { - s.execute("select.rect", json!({"x": 8, "y": 8, "width": 24, "height": 24})).unwrap(); - } - // An accepted invalid source would replace this existing preset. - s.execute("brush.presets.save", json!({"name": "Kept preset"})).unwrap(); - let active = s.active().unwrap().active_layer.unwrap(); - let stored = s.active().unwrap().doc.layer(active).unwrap().surface().unwrap().rgba(20, 20).map(f32::to_bits); - assert_eq!(stored, rgba.map(f32::to_bits), "non-finite values must reach the source read unchanged"); - let doc = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.past_len(); - let brush = s.tools.brush.clone(); - let presets = s.tools.presets.clone(); - let current = s.tools.current_preset.clone(); - let revision = s.tools.brush_rev; - let journal = s.journal.clone(); - - let error = s.execute(command, json!({"name": "Kept preset"})).unwrap_err(); - - assert!(error.to_string().contains("non-finite"), "{command}: {error}"); - assert!(Arc::ptr_eq(&doc, &s.active().unwrap().doc)); - assert_eq!(s.active().unwrap().history.past_len(), history); - assert_eq!(s.active().unwrap().active_layer, Some(active)); - assert_eq!(s.active().unwrap().doc.selection.is_some(), selected); - assert_eq!(s.active().unwrap().doc.icc_profile.as_ref(), Some(&icc)); - assert_eq!(s.active().unwrap().doc.layer(active).unwrap().surface().unwrap().rgba(20, 20).map(f32::to_bits), stored); - assert_eq!(s.tools.brush, brush); - assert_eq!(s.tools.presets, presets); - assert_eq!(s.tools.current_preset, current); - assert_eq!(s.tools.brush_rev, revision); - assert_eq!(s.journal, journal); - } - } - } -} diff --git a/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs b/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs index 396268db4b..95afc7d5f0 100644 --- a/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs +++ b/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs @@ -23,7 +23,7 @@ fn source(depth: u32) -> Session { } #[test] -fn visible_capture_is_identical_with_background_tip_group_or_no_active_layer() { +fn selected_visible_capture_is_identical_with_background_tip_group() { for command in COMMANDS { for depth in [8, 16, 32] { let mut s = source(depth); @@ -31,8 +31,9 @@ fn visible_capture_is_identical_with_background_tip_group_or_no_active_layer() { let painted = s.active().unwrap().active_layer.unwrap(); s.execute("layer.new.group", json!({"name": "Empty active group"})).unwrap(); let group = s.active().unwrap().active_layer.unwrap(); + s.execute("select.rect", json!({"x": 50, "y": 40, "width": 100, "height": 50})).unwrap(); let mut expected = None; - for active in [Some(background), Some(painted), Some(group), None] { + for active in [Some(background), Some(painted), Some(group)] { s.edit("Choose capture-independent active layer", |_, current| { *current = active; Ok(()) @@ -80,27 +81,24 @@ fn selection_limits_the_visible_composite_even_with_background_active() { } #[test] -fn visible_group_children_and_occlusion_count_but_hidden_layers_and_groups_do_not() { +fn visible_composite_keeps_occlusion_and_ignores_hidden_source() { for command in COMMANDS { let mut s = Session::new(); s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); - s.edit("Visible and hidden composite contributors", |doc, active| { - let mut black = Layer::raster("Nested visible black", doc.pixel_format()); + s.edit("Visible composite with hidden source", |doc, active| { + let mut black = Layer::raster("Visible black", doc.pixel_format()); black.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 5, 5), &[0.0, 0.0, 0.0, 1.0]); - let visible = Layer::group("Visible group", vec![black]); let mut hidden_black = Layer::raster("Hidden black", doc.pixel_format()); hidden_black.surface_mut().unwrap().fill_rect(doc.bounds(), &[0.0, 0.0, 0.0, 1.0]); hidden_black.visible = false; - let mut hidden_group = Layer::group("Hidden ancestor", vec![hidden_black.duplicate()]); - hidden_group.children_mut().unwrap()[0].visible = true; - hidden_group.visible = false; let mut white = Layer::raster("Visible white occlusion", doc.pixel_format()); white.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 3, 5), &[1.0, 1.0, 1.0, 1.0]); *active = Some(hidden_black.id); - doc.layers.extend([visible, hidden_black, hidden_group, white]); + doc.layers.extend([black, hidden_black, white]); Ok(()) }) .unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); s.execute(command, json!({"name": "Only visible ink"})).unwrap(); assert_eq!((tip(&s).width, tip(&s).height), (2, 4)); for y in 0..4 { @@ -120,24 +118,23 @@ fn composite_transparency_and_selection_coverage_are_applied_once() { s.edit("Nested translucent source", |doc, active| { let mut black = Layer::raster("Half black", doc.pixel_format()); black.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 6, 7), &[0.0, 0.0, 0.0, 0.5]); - let group = Layer::group("Active group", vec![black]); - *active = Some(group.id); - doc.layers.push(group); + *active = Some(black.id); + doc.layers.push(black); Ok(()) }) .unwrap(); - for selected in [false, true] { - if selected { - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + for coverage in [1.0f32, 0.25] { + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + if coverage < 1.0 { s.edit("Quarter coverage", |doc, _| { - doc.selection.as_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[0.25]); + doc.selection.as_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[coverage]); Ok(()) }) .unwrap(); } s.execute(command, json!({"name": "Translucent composite"})).unwrap(); assert_eq!((tip(&s).width, tip(&s).height), (5, 6)); - let expected = if selected { 0.125 } else { 0.5 }; + let expected = 0.5 * coverage; for y in 0..6 { for x in 0..5 { assert!((tip(&s).get(x, y) - expected).abs() < 0.003); @@ -163,6 +160,7 @@ fn a_hidden_black_source_over_white_or_transparency_is_empty_and_does_not_replac Ok(()) }) .unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); s.execute("brush.presets.save", json!({"name": "Kept"})).unwrap(); let brush = s.tools.brush.clone(); let presets = s.tools.presets.clone(); @@ -180,28 +178,6 @@ fn a_hidden_black_source_over_white_or_transparency_is_empty_and_does_not_replac } } -#[test] -fn merged_rgb_retains_the_document_profile_before_gray_conversion() { - for command in COMMANDS { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "depth": 32, "background": "transparent"})).unwrap(); - s.edit("Linear gray nested under active group", |doc, active| { - doc.icc_profile = Some(craft_cms::Builtin::LinearSrgb.profile().to_bytes()); - let mut layer = Layer::raster("Linear half gray", doc.pixel_format()); - layer.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 5, 5), &[0.5, 0.5, 0.5, 1.0]); - let group = Layer::group("Active group", vec![layer]); - *active = Some(group.id); - doc.layers.push(group); - Ok(()) - }) - .unwrap(); - s.execute(command, json!({"name": "Profiled merged tip"})).unwrap(); - assert_eq!((tip(&s).width, tip(&s).height), (4, 4)); - // Encoded sGray for linear RGB 0.5 is about 0.735, not encoded RGB 0.5. - assert!((tip(&s).get(0, 0) - 0.265).abs() < 0.01); - } -} - fn sparse_budget_source(width: u32, height: u32, selected: bool) -> Session { let mut s = Session::new(); s.execute("file.new", json!({"width": width, "height": height, "background": "transparent"})).unwrap(); @@ -227,56 +203,48 @@ fn sparse_budget_source(width: u32, height: u32, selected: bool) -> Session { fn composite_storage_is_counted_with_density_and_mask_before_any_allocation() { const WIDTH: u32 = 32768; for command in COMMANDS { - for selected in [false, true] { - // Density plus optional mask fit exactly; the simultaneously live RGBA band - // must also count, even though the document itself is sparse. - let bytes = if selected { 8 } else { 4 }; - let height = (crate::allocation::MAX_DENSE_BYTES / (bytes * u64::from(WIDTH))) as u32; - let mut s = sparse_budget_source(WIDTH, height, selected); - let doc = s.active().unwrap().doc.clone(); - let brush = s.tools.brush.clone(); - let presets = s.tools.presets.clone(); - let current = s.tools.current_preset.clone(); - let history = s.active().unwrap().history.past_len(); - crate::allocation::fail_next_for_test(); - let result = s.execute(command, json!({"name": "Composite over budget"})); - let unspent = crate::allocation::capacity::(0, "consume composite budget failpoint"); - let err = result.unwrap_err(); - assert!(err.to_string().contains("working memory"), "{err}"); - assert!(unspent.is_err(), "budget refusal must precede the first allocation"); - assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); - assert_eq!(s.active().unwrap().history.past_len(), history); - assert_eq!(s.tools.brush, brush); - assert_eq!(s.tools.presets, presets); - assert_eq!(s.tools.current_preset, current); - } + // This selected case covers the density, selection mask and live compositor band. + let height = (crate::allocation::MAX_DENSE_BYTES / (8 * u64::from(WIDTH))) as u32; + let mut s = sparse_budget_source(WIDTH, height, true); + let doc = s.active().unwrap().doc.clone(); + let brush = s.tools.brush.clone(); + let presets = s.tools.presets.clone(); + let current = s.tools.current_preset.clone(); + let history = s.active().unwrap().history.past_len(); + crate::allocation::fail_next_for_test(); + let result = s.execute(command, json!({"name": "Composite over budget"})); + let unspent = crate::allocation::capacity::(0, "consume composite budget failpoint"); + let err = result.unwrap_err(); + assert!(err.to_string().contains("working memory"), "{err}"); + assert!(unspent.is_err(), "budget refusal must precede the first allocation"); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.active().unwrap().history.past_len(), history); + assert_eq!(s.tools.brush, brush); + assert_eq!(s.tools.presets, presets); + assert_eq!(s.tools.current_preset, current); } } #[test] fn compositor_allocation_boundary_failure_preserves_source_and_preset_state() { for command in COMMANDS { - for selected in [false, true] { - let mut s = source(8); - if selected { - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 150})).unwrap(); - } - let doc = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.past_len(); - let brush = s.tools.brush.clone(); - let presets = s.tools.presets.clone(); - let current = s.tools.current_preset.clone(); - crate::allocation::fail_after_for_test(if selected { 2 } else { 1 }); - let result = s.execute(command, json!({"name": "Compositor allocation failure"})); - let _ = crate::allocation::capacity::(0, "reset compositor failpoint"); - let err = result.unwrap_err(); - assert!(err.to_string().contains("not enough memory"), "{err}"); - assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); - assert_eq!(s.active().unwrap().history.past_len(), history); - assert_eq!(s.tools.brush, brush); - assert_eq!(s.tools.presets, presets); - assert_eq!(s.tools.current_preset, current); - } + let mut s = source(8); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 150})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let brush = s.tools.brush.clone(); + let presets = s.tools.presets.clone(); + let current = s.tools.current_preset.clone(); + crate::allocation::fail_after_for_test(2); + let result = s.execute(command, json!({"name": "Compositor allocation failure"})); + let _ = crate::allocation::capacity::(0, "reset compositor failpoint"); + let err = result.unwrap_err(); + assert!(err.to_string().contains("not enough memory"), "{err}"); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.active().unwrap().history.past_len(), history); + assert_eq!(s.tools.brush, brush); + assert_eq!(s.tools.presets, presets); + assert_eq!(s.tools.current_preset, current); } } @@ -286,26 +254,24 @@ fn a_banded_capture_that_fits_the_budget_is_not_charged_for_a_full_rgba_canvas() let band_rows = photocraft_compose::band_rows_for(WIDTH, 0) as u64; let band_bytes = u64::from(WIDTH) * band_rows * 16; for command in COMMANDS { - for selected in [false, true] { - let sample_bytes = if selected { 8 } else { 4 }; - let height = ((crate::allocation::MAX_DENSE_BYTES - band_bytes) / (sample_bytes * u64::from(WIDTH))) as u32; - let pixels = u64::from(WIDTH) * u64::from(height); - assert!(pixels * sample_bytes + band_bytes <= crate::allocation::MAX_DENSE_BYTES); - assert!(pixels * (sample_bytes + 16) > crate::allocation::MAX_DENSE_BYTES, "a full-plane estimate would incorrectly reject this fixture"); - let mut s = sparse_budget_source(WIDTH, height, selected); - let doc = s.active().unwrap().doc.clone(); - let brush = s.tools.brush.clone(); - let presets = s.tools.presets.clone(); - // Refuse the first real allocation, after verifying that the budget allowed it. - crate::allocation::fail_next_for_test(); - let result = s.execute(command, json!({"name": "Fits with bands"})); - let unspent = crate::allocation::capacity::(0, "consume band acceptance failpoint"); - let err = result.unwrap_err().to_string(); - assert!(err.contains("not enough memory") && !err.contains("working memory"), "{err}"); - assert!(unspent.is_ok(), "the accepted budget must reach the first allocation"); - assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); - assert_eq!(s.tools.brush, brush); - assert_eq!(s.tools.presets, presets); - } + let sample_bytes = 8; + let height = ((crate::allocation::MAX_DENSE_BYTES - band_bytes) / (sample_bytes * u64::from(WIDTH))) as u32; + let pixels = u64::from(WIDTH) * u64::from(height); + assert!(pixels * sample_bytes + band_bytes <= crate::allocation::MAX_DENSE_BYTES); + assert!(pixels * (sample_bytes + 16) > crate::allocation::MAX_DENSE_BYTES, "a full-plane estimate would incorrectly reject this fixture"); + let mut s = sparse_budget_source(WIDTH, height, true); + let doc = s.active().unwrap().doc.clone(); + let brush = s.tools.brush.clone(); + let presets = s.tools.presets.clone(); + // Refuse the first real allocation, after verifying that the budget allowed it. + crate::allocation::fail_next_for_test(); + let result = s.execute(command, json!({"name": "Fits with bands"})); + let unspent = crate::allocation::capacity::(0, "consume band acceptance failpoint"); + let err = result.unwrap_err().to_string(); + assert!(err.contains("not enough memory") && !err.contains("working memory"), "{err}"); + assert!(unspent.is_ok(), "the accepted budget must reach the first allocation"); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.tools.brush, brush); + assert_eq!(s.tools.presets, presets); } } diff --git a/crates/engine/src/cmd/brush_cmds/define_brush_no_selection_tests.rs b/crates/engine/src/cmd/brush_cmds/define_brush_no_selection_tests.rs deleted file mode 100644 index 71e42f6308..0000000000 --- a/crates/engine/src/cmd/brush_cmds/define_brush_no_selection_tests.rs +++ /dev/null @@ -1,235 +0,0 @@ -use super::*; - -const COMMANDS: [&str; 2] = ["edit.defineBrushPreset", "brush.defineFromSelection"]; - -fn source(depth: u32) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 150, "depth": depth, "background": "#ffffff"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Tip"})).unwrap(); - s.edit("BrushSrc", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - surf.fill_rect(Rect::new(50, 40, 90, 70), &[0.0, 0.0, 0.0, 1.0]); - surf.fill_rect(Rect::new(120, 60, 150, 90), &[128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]); - Ok(()) - }) - .unwrap(); - s -} - -fn tip(s: &Session) -> &GrayTile { - let TipShape::Sampled(tip) = &s.tools.brush.tip else { panic!("expected a sampled tip") }; - tip -} - -#[test] -fn without_selection_the_canvas_is_trimmed_to_the_measured_content() { - for command in COMMANDS { - for depth in [8, 16, 32] { - let mut s = source(depth); - assert!(s.active().unwrap().doc.selection.is_none()); - assert!(s.is_enabled(command), "{command}, depth {depth}"); - let doc = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.past_len(); - let presets = s.tools.presets.len(); - - let result = s.execute(command, json!({"name": "Canvas tip"})).unwrap(); - - assert_eq!((result["width"].as_u64(), result["height"].as_u64()), (Some(100), Some(50))); - assert_eq!(s.tools.brush.size, 100.0); - assert_eq!((tip(&s).width, tip(&s).height), (100, 50)); - assert_eq!(tip(&s).get(0, 0), 1.0); - assert_eq!(tip(&s).get(60, 0), 0.0, "transparent gap contributes no paint"); - assert!((tip(&s).get(70, 20) - 127.0 / 255.0).abs() < 0.003); - assert_eq!(s.tools.presets.len(), presets + 1); - assert_eq!(s.tools.current_preset.as_deref(), Some("Canvas tip")); - assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc), "source document is untouched"); - assert_eq!(s.active().unwrap().history.past_len(), history); - assert!(s.active().unwrap().doc.selection.is_none(), "no synthetic selection is left behind"); - } - } -} - -#[test] -fn an_existing_selection_still_limits_the_tip_to_the_grey_square() { - for command in COMMANDS { - let mut s = source(8); - s.execute("select.rect", json!({"x": 115, "y": 55, "width": 40, "height": 40})).unwrap(); - let result = s.execute(command, json!({"name": "Selected tip"})).unwrap(); - assert_eq!((result["width"].as_u64(), result["height"].as_u64()), (Some(30), Some(30))); - assert_eq!(s.tools.brush.size, 30.0); - assert!((tip(&s).get(0, 0) - 127.0 / 255.0).abs() < 0.003); - assert!(s.active().unwrap().doc.selection.is_some()); - } -} - -#[test] -fn a_partial_selection_keeps_coverage_alpha_and_canvas_clipping() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "background": "transparent"})).unwrap(); - s.edit("Half opaque source", |doc, active| { - let bounds = doc.bounds(); - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(bounds, &[0.0, 0.0, 0.0, 0.5]); - Ok(()) - }) - .unwrap(); - s.execute("select.rect", json!({"x": -3, "y": -2, "width": 8, "height": 8})).unwrap(); - s.edit("Partial coverage", |doc, _| { - doc.selection.as_mut().unwrap().fill_rect(Rect::new(0, 0, 5, 6), &[0.25]); - Ok(()) - }) - .unwrap(); - - s.execute("brush.defineFromSelection", json!({"name": "Masked tip"})).unwrap(); - - assert_eq!((tip(&s).width, tip(&s).height), (5, 6)); - assert!((tip(&s).get(0, 0) - 0.125).abs() < 0.003, "density includes source alpha and selection coverage"); - assert!((tip(&s).get(4, 5) - 0.125).abs() < 0.003); -} - -#[test] -fn no_document_is_disabled_and_a_group_active_capture_uses_visible_pixels() { - let mut s = Session::new(); - for command in COMMANDS { - assert!(!s.is_enabled(command)); - assert!(s.execute(command, json!({"name": "No document"})).is_err()); - } - s = source(8); - s.execute("layer.new.group", json!({"name": "Not pixels"})).unwrap(); - for command in COMMANDS { - assert!(s.is_enabled(command)); - s.execute(command, json!({"name": "Visible pixels"})).unwrap(); - assert_eq!((tip(&s).width, tip(&s).height), (100, 50)); - } -} - -#[test] -fn a_large_canvas_is_trimmed_before_the_existing_tip_side_limit() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": MAX_TIP + 1, "height": 2, "background": "#ffffff"})).unwrap(); - s.edit("One black pixel", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(MAX_TIP as i32, 0, MAX_TIP as i32 + 1, 1), &[0.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - let made = s.execute("edit.defineBrushPreset", json!({"name": "One pixel"})).unwrap(); - assert_eq!((made["width"].as_u64(), made["height"].as_u64()), (Some(1), Some(1))); - assert_eq!(tip(&s).get(0, 0), 1.0); - - s.edit("Too wide painted area", |doc, active| { - let bounds = doc.bounds(); - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(bounds, &[0.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - let brush = s.tools.brush.clone(); - let presets = s.tools.presets.clone(); - let err = s.execute("edit.defineBrushPreset", json!({"name": "Too wide"})).unwrap_err(); - assert!(err.to_string().contains("too large for a brush tip"), "{err}"); - assert_eq!(s.tools.brush, brush); - assert_eq!(s.tools.presets, presets); -} - -#[test] -fn a_canvas_capture_allocation_failure_leaves_the_source_and_presets_unchanged() { - let mut s = source(8); - let brush = s.tools.brush.clone(); - let presets = s.tools.presets.clone(); - let current = s.tools.current_preset.clone(); - let doc = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.past_len(); - crate::allocation::fail_next_for_test(); - let result = s.execute("brush.defineFromSelection", json!({"name": "Allocation failure"})); - let _ = crate::allocation::capacity::(0, "reset failpoint"); - let err = result.unwrap_err().to_string(); - assert!(err.contains("not enough memory") && err.contains("defining a brush from the selection"), "{err}"); - assert_eq!(s.tools.brush, brush); - assert_eq!(s.tools.presets, presets); - assert_eq!(s.tools.current_preset, current); - assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); - assert_eq!(s.active().unwrap().history.past_len(), history); -} - -// Sparse source and mask fixtures keep just one or two tiles, even when their -// bounds would require gigabytes of dense sampling buffers. -fn budget_source(width: u32, height: u32, selected: bool) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": width, "height": height, "background": "transparent"})).unwrap(); - s.edit("Sparse budget source", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - surf.fill_rect(Rect::new(0, 0, 1, 1), &[0.0, 0.0, 0.0, 1.0]); - assert_eq!(surf.tile_count(), 1); - if selected { - let mut mask = photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8); - mask.fill_rect(Rect::new(0, 0, 1, 1), &[1.0]); - mask.fill_rect(Rect::new(width as i32 - 1, height as i32 - 1, width as i32, height as i32), &[1.0]); - assert_eq!(mask.tile_count(), 2); - assert_eq!(mask.content_bounds(), doc.bounds()); - doc.selection = Some(mask); - } - Ok(()) - }) - .unwrap(); - s -} - -fn assert_budget_refusal(s: &mut Session, command: &str) { - let brush = s.tools.brush.clone(); - let presets = s.tools.presets.clone(); - let current = s.tools.current_preset.clone(); - let doc = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.past_len(); - let revision = s.active().unwrap().revision; - // This also makes the regression safe on the unfixed code: its first dense - // allocation fails instead of trying to fill the enormous buffer. - crate::allocation::fail_next_for_test(); - let result = s.execute(command, json!({"name": "Over budget"})); - let unspent = crate::allocation::capacity::(0, "consume budget test failpoint"); - let err = result.unwrap_err().to_string(); - assert!(err.contains("working memory") && err.contains("defining a brush from the selection"), "{err}"); - assert!(unspent.is_err(), "the budget refusal must precede the first fallible allocation"); - assert_eq!(s.tools.brush, brush); - assert_eq!(s.tools.presets, presets); - assert_eq!(s.tools.current_preset, current); - assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); - assert_eq!(s.active().unwrap().history.past_len(), history); - assert_eq!(s.active().unwrap().revision, revision); -} - -#[test] -fn an_over_budget_canvas_is_refused_before_sampling() { - const WIDTH: u32 = 32768; - // The pixel count fits usize on both targets, while its f32 density buffer - // alone is just over that target's dense-memory budget. - let height = (crate::allocation::MAX_DENSE_BYTES / (4 * u64::from(WIDTH))) as u32 + 1; - for command in COMMANDS { - let mut s = budget_source(WIDTH, height, false); - assert!(s.active().unwrap().doc.selection.is_none()); - assert_budget_refusal(&mut s, command); - } -} - -#[test] -fn selection_capture_counts_density_and_mask_buffers_together() { - const WIDTH: u32 = 32768; - let height = (crate::allocation::MAX_DENSE_BYTES / (4 * u64::from(WIDTH))) as u32; - let density_bytes = u64::from(WIDTH) * u64::from(height) * 4; - assert_eq!(density_bytes, crate::allocation::MAX_DENSE_BYTES, "density alone would fit; the live mask must also count"); - for command in COMMANDS { - let mut s = budget_source(WIDTH, height, true); - assert_eq!(s.active().unwrap().doc.selection.as_ref().unwrap().channels(), 1); - assert_budget_refusal(&mut s, command); - } -} - -#[test] -fn a_small_selection_on_an_over_budget_canvas_still_defines_a_tip() { - const WIDTH: u32 = 32768; - let height = (crate::allocation::MAX_DENSE_BYTES / (4 * u64::from(WIDTH))) as u32 + 1; - for command in COMMANDS { - let mut s = budget_source(WIDTH, height, false); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap(); - let result = s.execute(command, json!({"name": "Small selected tip"})).unwrap(); - assert_eq!((result["width"].as_u64(), result["height"].as_u64()), (Some(1), Some(1))); - assert_eq!(tip(&s).get(0, 0), 1.0); - } -} diff --git a/crates/engine/src/cmd/edit_menu_cmds/tests.rs b/crates/engine/src/cmd/edit_menu_cmds/tests.rs index 4d486330b3..069ff2573c 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/tests.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/tests.rs @@ -756,7 +756,7 @@ fn preset_manager_brush_delete_clears_current_preset() { #[test] fn define_brush_preset_wraps_define_from_selection() { let mut s = session(8); - assert!(s.is_enabled("edit.defineBrushPreset")); + assert!(!s.is_enabled("edit.defineBrushPreset")); s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); s.execute("select.rect", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); s.execute("edit.defineBrushPreset", json!({})).unwrap(); From 436693c1fad68415cad542da1bfb5536ffeca50f Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 16:12:14 -0800 Subject: [PATCH 28/46] Clarify compositor allocation test checkpoint --- crates/engine/src/cmd/brush_cmds.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 6a2b8b0634..a38948df62 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -1116,7 +1116,8 @@ fn define_from_selection(s: &mut Session, p: &Value) -> Result { // A selection mask, when present, is a second buffer of the same size; it must fail gracefully too // (review of #5469), so read it through the fallible allocator. let sv = crate::allocation::read_region(sel, area, "defining a brush from the selection")?; - // Keep the allocation boundary fallible before entering compositor-owned scratch storage. + // Keep a fault-injection checkpoint before entering compositor-owned scratch storage. + // The compositor's scratch allocation itself is not fallible through this call. crate::allocation::checkpoint("defining a brush from the selection")?; photocraft_compose::render_bands(&d.doc, area, 0, |band| -> Result<()> { for (row, pixels) in band.px.chunks_exact(w).enumerate() { From a1f16fb1bb8c27e3772657fbb3efb2b558f5eebe Mon Sep 17 00:00:00 2001 From: Yoris Wind Date: Mon, 16 Nov 2026 02:26:04 +0000 Subject: [PATCH 29/46] Format brush-density review files --- crates/engine/src/cmd/brush_cmds.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index a38948df62..04c65b49d6 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -1519,6 +1519,5 @@ mod mixer_live_tests; #[path = "color_replacement_history_name_tests.rs"] mod color_replacement_history_name_tests; - #[cfg(test)] mod define_brush_merged_source_tests; From 5fccd6347b5b75de56568cede3a7f6eb85112f0e Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 20:05:39 -0800 Subject: [PATCH 30/46] Make compositor RGBA band buffers fallible --- crates/compose/src/advanced.rs | 124 ++++++++- crates/compose/src/composite.rs | 260 ++++++++++++------ crates/compose/src/content.rs | 75 ++++- crates/compose/src/effects/composite.rs | 66 ++++- crates/compose/src/gradient_fill.rs | 21 +- crates/compose/src/lib.rs | 55 +++- crates/compose/src/multichannel.rs | 15 +- crates/compose/src/native.rs | 20 +- crates/compose/src/native_lab.rs | 20 +- crates/compose/src/pattern.rs | 14 +- crates/compose/src/render.rs | 214 ++++++++++++-- crates/engine/src/cmd/brush_cmds.rs | 26 +- .../define_brush_merged_source_tests.rs | 8 +- crates/engine/src/cmd/brush_cmds/tests.rs | 18 ++ crates/raster/src/scratch.rs | 14 +- crates/raster/tests/scratch.rs | 32 +++ 16 files changed, 801 insertions(+), 181 deletions(-) diff --git a/crates/compose/src/advanced.rs b/crates/compose/src/advanced.rs index 7a4068012d..13b55522a2 100644 --- a/crates/compose/src/advanced.rs +++ b/crates/compose/src/advanced.rs @@ -33,7 +33,7 @@ use photocraft_doc::{Knockout, Layer, LayerContent}; use photocraft_geom::Rect; use crate::extents::recycle_mask; -use crate::{Buffer, Ctx, composite_atop, composite_layer, effects, mask_vals, render_content}; +use crate::{Buffer, BufferAlloc, Ctx, InfallibleBufferAlloc, composite_atop, composite_layer, effects, mask_vals, render_content, render_content_with}; /// Where a layer stack sits, for knockouts: at the document's top level, and/or inside an /// isolated (non-pass-through) group. Photoshop stops a deep knockout at the bottom of the @@ -102,12 +102,19 @@ pub fn is_background(l: &Layer) -> bool { /// What a deep knockout reveals over `rect`: the document's initial backdrop with its Background /// layer (transparency when it has none, or when it is hidden). pub(crate) fn deep_target(cx: &Ctx, rect: Rect) -> Buffer { - let Some(doc) = cx.doc else { return Buffer::transparent(rect) }; - let mut b = crate::multichannel::backdrop(doc, rect); - if let Some(bg) = doc.layers.first().filter(|l| l.visible && is_background(l)) { - composite_layer(bg, &[], &mut b, cx, None, Scope::ROOT); + match deep_target_with(cx, rect, &InfallibleBufferAlloc) { + Ok(buffer) => buffer, + Err(never) => match never {}, } - b +} + +fn deep_target_with(cx: &Ctx, rect: Rect, alloc: &A) -> Result { + let Some(doc) = cx.doc else { return alloc.filled(rect, [0.0; 4]) }; + let mut b = crate::multichannel::backdrop_with(doc, rect, alloc)?; + if let Some(bg) = doc.layers.first().filter(|l| l.visible && is_background(l)) { + crate::composite::composite_layer_with(bg, &[], &mut b, cx, None, Scope::ROOT, alloc)?; + } + Ok(b) } /// The knockout target of a layer of a stack in `scope`, if it knocks out. `floor` is the @@ -122,6 +129,25 @@ pub(crate) fn knockout_target<'b>(layer: &Layer, floor: Option<&'b Buffer>, rect } } +pub(crate) fn knockout_target_with<'b, A: BufferAlloc>( + layer: &Layer, + floor: Option<&'b Buffer>, + rect: Rect, + cx: &Ctx, + scope: Scope, + alloc: &A, +) -> Result>, A::Error> { + let deep = || if scope.isolated { alloc.filled(rect, [0.0; 4]) } else { deep_target_with(cx, rect, alloc) }; + match layer.advanced.knockout { + Knockout::None => Ok(None), + Knockout::Shallow => match floor { + Some(floor) => Ok(Some(Cow::Borrowed(floor))), + None => Ok(Some(Cow::Owned(deep()?))), + }, + Knockout::Deep => Ok(Some(Cow::Owned(deep()?))), + } +} + /// Whether `layers` holds a visible unclipped shallow knockout (its stack then keeps a copy of /// its starting backdrop). pub(crate) fn needs_floor(layers: &[Layer]) -> bool { @@ -142,6 +168,16 @@ fn knockout_shape(layer: &Layer, rect: Rect, cx: &Ctx) -> Vec { } } +fn knockout_shape_with(layer: &Layer, rect: Rect, cx: &Ctx, alloc: &A) -> Result, A::Error> { + let n = rect.width() as usize * rect.height() as usize; + let masks = || mask_vals(layer, rect, cx).unwrap_or_else(|| vec![1.0; n]); + if !layer.advanced.transparency_shapes { return Ok(masks()) } + match render_content_with(layer, rect, cx, alloc)? { + Some(b) => Ok(b.px.iter().map(|p| p[3]).collect()), + None => Ok(masks()), + } +} + /// Composite `layer` with `draw` as a knockout onto `target`: inside its shape the backdrop /// becomes the target, then the layer draws (at its fill opacity), and layer opacity mixes the /// result with the untouched backdrop. Compositing at opacity `o` is linear in `o` @@ -151,18 +187,33 @@ fn knockout_shape(layer: &Layer, rect: Rect, cx: &Ctx) -> Vec { /// `clip_alpha` keeps alpha from growing (clipped layers stay inside their base's alpha; a /// knockout to transparency may still lower it). pub(crate) fn knockout(layer: &Layer, backdrop: &mut Buffer, target: &Buffer, clip_alpha: bool, cx: &Ctx, draw: impl FnOnce(&mut Buffer)) { + match knockout_with(layer, backdrop, target, clip_alpha, cx, &InfallibleBufferAlloc, |buffer| { draw(buffer); Ok(()) }) { + Ok(()) => {} + Err(never) => match never {}, + } +} + +pub(crate) fn knockout_with( + layer: &Layer, + backdrop: &mut Buffer, + target: &Buffer, + clip_alpha: bool, + cx: &Ctx, + alloc: &A, + draw: impl FnOnce(&mut Buffer) -> Result<(), A::Error>, +) -> Result<(), A::Error> { // Coverage knocks out proportionally. (Photoshop knocks out a little more at anti-aliased // shape edges: psd-tools knockout-isolated-groups differs on 0.45 % of its pixels, along // ellipse edges; a binary shape matched worse.) - let shape = knockout_shape(layer, backdrop.rect, cx); + let shape = knockout_shape_with(layer, backdrop.rect, cx, alloc)?; if target.rect != backdrop.rect || shape.len() != backdrop.px.len() { // Never reached (targets are built over the backdrop's rect); compositing without the // knockout beats a wrong pixel or a panic. recycle_mask(Some(shape)); - draw(backdrop); - return; + draw(backdrop)?; + return Ok(()); } - let before = backdrop.clone(); + let before = alloc.clone(backdrop)?; for ((p, t), k) in backdrop.px.iter_mut().zip(&target.px).zip(&shape) { if *k > 0.0 { let a = p[3]; @@ -172,11 +223,11 @@ pub(crate) fn knockout(layer: &Layer, backdrop: &mut Buffer, target: &Buffer, cl } } } - let knocked = (layer.opacity < 1.0).then(|| backdrop.clone()); - draw(backdrop); + let knocked = if layer.opacity < 1.0 { Some(alloc.clone(backdrop)?) } else { None }; + draw(backdrop)?; let Some(knocked) = knocked else { recycle_mask(Some(shape)); - return; + return Ok(()); }; let rest = 1.0 - layer.opacity.clamp(0.0, 1.0); for (((p, b), k), s) in backdrop.px.iter_mut().zip(&before.px).zip(&knocked.px).zip(&shape) { @@ -192,6 +243,7 @@ pub(crate) fn knockout(layer: &Layer, backdrop: &mut Buffer, target: &Buffer, cl *p = if a > 0.0 { [(pm[0] / a).clamp(0.0, 1.0), (pm[1] / a).clamp(0.0, 1.0), (pm[2] / a).clamp(0.0, 1.0), a] } else { [0.0; 4] }; } recycle_mask(Some(shape)); + Ok(()) } /// Composite a clipping group's clipped layers atop `base` (the base's isolated content, Blend @@ -208,6 +260,17 @@ pub(crate) fn composite_clipped(clipped: &[Layer], base: &mut Buffer, cx: &Ctx) } } +pub(crate) fn composite_clipped_with(clipped: &[Layer], base: &mut Buffer, cx: &Ctx, alloc: &A) -> Result<(), A::Error> { + let floor = if clipped.iter().any(|c| c.visible && c.advanced.knockout != Knockout::None) { Some(alloc.clone(base)?) } else { None }; + for c in clipped.iter().filter(|c| c.visible) { + match &floor { + Some(f) if c.advanced.knockout != Knockout::None => knockout_with(c, base, f, true, cx, alloc, |b| crate::composite::composite_atop_with(c, b, cx, alloc))?, + _ => crate::composite::composite_atop_with(c, base, cx, alloc)?, + } + } + Ok(()) +} + /// Whether `layer`'s clipped layers blend one by one (Blend Clipped Layers as Group off). /// Adjustment layers keep the grouped path (they have no pixels of their own to clip to). pub(crate) fn clips_individually(layer: &Layer, clipped: &[Layer]) -> bool { @@ -248,6 +311,41 @@ pub(crate) fn composite_clipped_individually(layer: &Layer, clipped: &[Layer], b } } +pub(crate) fn composite_clipped_individually_with( + layer: &Layer, + clipped: &[Layer], + backdrop: &mut Buffer, + cx: &Ctx, + ko: Option<&Buffer>, + scope: Scope, + alloc: &A, +) -> Result<(), A::Error> { + let rect = backdrop.rect; + let n = backdrop.px.len(); + let floor = if clipped.iter().any(|c| c.visible && c.advanced.knockout == Knockout::Shallow) { Some(alloc.clone(backdrop)?) } else { None }; + crate::composite::composite_layer_with(layer, &[], backdrop, cx, ko, scope, alloc)?; + let op = layer.opacity.clamp(0.0, 1.0); + let clip = match render_content_with(layer, rect, cx, alloc)? { + Some(b) => b.px.iter().map(|p| p[3] * op).collect::>(), + None => { + let mv = mask_vals(layer, rect, cx); + let clip = mv.as_ref().map_or_else(|| vec![op; n], |m| m.iter().map(|m| m * op).collect()); + recycle_mask(mv); + clip + } + }; + if clip.len() != n { return Ok(()) } + for c in clipped.iter().filter(|c| c.visible) { + let before = alloc.clone(backdrop)?; + let t = knockout_target_with(c, floor.as_ref(), rect, cx, Scope { root: false, ..scope }, alloc)?; + crate::composite::composite_layer_with(c, &[], backdrop, cx, t.as_deref(), scope, alloc)?; + for ((p, b), k) in backdrop.px.iter_mut().zip(&before.px).zip(&clip) { + if *k < 1.0 { *p = mix(*b, *p, k.max(0.0)); } + } + } + Ok(()) +} + /// Whether a mask of `layer` hides its effects instead of shaping them (Layer / Vector Mask /// Hides Effects on an enabled mask of a layer with effects). pub(crate) fn hides_effects(layer: &Layer) -> bool { diff --git a/crates/compose/src/composite.rs b/crates/compose/src/composite.rs index 679a2298c0..2d6008e01b 100644 --- a/crates/compose/src/composite.rs +++ b/crates/compose/src/composite.rs @@ -1,8 +1,11 @@ -use super::content::{channel_weights, empty_in, render_content, restore_channels, surface_to_buffer}; +use super::content::{channel_weights, empty_in, render_content_with, restore_channels, surface_to_buffer, surface_to_buffer_with}; use super::ctx::Ctx; use super::extents::{effects_frame, mask_k, mask_vals, recycle_mask, shapeless_stroke_bounds}; use super::fx_cache::effect_maps; -use super::{BlendMode, Buffer, Fill, Layer, LayerContent, Rect, Surface, advanced, blend, effects, psblend, shape_split}; +use super::{ + BlendMode, Buffer, BufferAlloc, Fill, InfallibleBufferAlloc, Layer, LayerContent, Rect, Surface, advanced, blend, effects, + psblend, shape_split, +}; /// Composite an isolated group's sibling list (bottom→top) onto `backdrop` (its own buffer). pub(crate) fn composite_stack(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx) { @@ -12,8 +15,21 @@ pub(crate) fn composite_stack(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx) /// Composite a sibling list (bottom→top) onto `backdrop`; `scope` says where the stack sits (see /// [`advanced::Scope`]: it decides what knockouts reveal). pub(crate) fn composite_stack_at(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { + match composite_stack_at_with(layers, backdrop, cx, scope, &InfallibleBufferAlloc) { + Ok(()) => {} + Err(never) => match never {}, + } +} + +pub(crate) fn composite_stack_at_with( + layers: &[Layer], + backdrop: &mut Buffer, + cx: &Ctx, + scope: advanced::Scope, + alloc: &A, +) -> Result<(), A::Error> { // Shallow knockouts stop at the bottom of this stack: the backdrop it starts from. - let floor = (!scope.root && advanced::needs_floor(layers)).then(|| backdrop.clone()); + let floor = if !scope.root && advanced::needs_floor(layers) { Some(alloc.clone(backdrop)?) } else { None }; let mut i = 0; while i < layers.len() { let base = &layers[i]; @@ -24,14 +40,15 @@ pub(crate) fn composite_stack_at(layers: &[Layer], backdrop: &mut Buffer, cx: &C } let clipped = &layers[i + 1..j]; if base.visible { - let ko = advanced::knockout_target(base, floor.as_ref(), backdrop.rect, cx, scope); - composite_layer(base, clipped, backdrop, cx, ko.as_deref(), scope); + let ko = advanced::knockout_target_with(base, floor.as_ref(), backdrop.rect, cx, scope, alloc)?; + composite_layer_with(base, clipped, backdrop, cx, ko.as_deref(), scope, alloc)?; if let (LayerContent::Adjustment(_), Some(q)) = (&base.content, adjustment_quantum(cx.depth)) { quantize(backdrop, q); } } i = j.max(i + 1); } + Ok(()) } /// Steps per unit of an integer document's samples: Photoshop applies adjustment layers to @@ -209,6 +226,13 @@ thread_local! { /// Mixing premultiplied colour by `k` equals compositing the layer at `k` × its alpha, since /// every blend mode's source-over result is linear in the source alpha. fn apply_blend_if(layer: &Layer, before: &Buffer, out: &mut Buffer, cx: &Ctx) { + match apply_blend_if_with(layer, before, out, cx, &InfallibleBufferAlloc) { + Ok(()) => {} + Err(never) => match never {}, + } +} + +fn apply_blend_if_with(layer: &Layer, before: &Buffer, out: &mut Buffer, cx: &Ctx, alloc: &A) -> Result<(), A::Error> { // "This Layer" is the layer's own colour. An adjustment layer (no content of its own) is // judged by its result at full strength, before Opacity and its mask mix it in, as Photoshop // does (#9542). Groups nested deeper than `MAX_BLEND_IF_GROUP_DEPTH` Blend Ifs are judged by @@ -217,16 +241,16 @@ fn apply_blend_if(layer: &Layer, before: &Buffer, out: &mut Buffer, cx: &Ctx) { let is_group = matches!(layer.content, LayerContent::Group(_)); let nested = BLEND_IF_GROUPS.with(std::cell::Cell::get); let own = if let LayerContent::Adjustment(adj) = &layer.content { - let mut result = before.clone(); + let mut result = alloc.clone(before)?; cx.apply_adjustment(adj, &mut result); Some(result) } else if is_group && nested >= MAX_BLEND_IF_GROUP_DEPTH { None } else { BLEND_IF_GROUPS.with(|d| d.set(nested + u32::from(is_group))); - let own = render_content(layer, out.rect, cx); + let own = render_content_with(layer, out.rect, cx, alloc); BLEND_IF_GROUPS.with(|d| d.set(nested)); - own + own? }; for (i, (p, b)) in out.px.iter_mut().zip(&before.px).enumerate() { let this = match &own { @@ -246,67 +270,94 @@ fn apply_blend_if(layer: &Layer, before: &Buffer, out: &mut Buffer, cx: &Ctx) { [0.0; 4] }; } + Ok(()) } /// Composite `layer` (plus its clipping group) onto `backdrop`, honouring its channel restrictions /// and Blend If, and knocking out to `ko` when it has a knockout (see [`advanced`]). pub(crate) fn composite_layer(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, ko: Option<&Buffer>, scope: advanced::Scope) { + match composite_layer_with(layer, clipped, backdrop, cx, ko, scope, &InfallibleBufferAlloc) { + Ok(()) => {} + Err(never) => match never {}, + } +} + +pub(crate) fn composite_layer_with( + layer: &Layer, + clipped: &[Layer], + backdrop: &mut Buffer, + cx: &Ctx, + ko: Option<&Buffer>, + scope: advanced::Scope, + alloc: &A, +) -> Result<(), A::Error> { // Blend Clipped Layers as Group off: the base alone, then each clipped layer in its own mode. if advanced::clips_individually(layer, clipped) { - advanced::composite_clipped_individually(layer, clipped, backdrop, cx, ko, scope); - return; + advanced::composite_clipped_individually_with(layer, clipped, backdrop, cx, ko, scope, alloc)?; + return Ok(()); } let w = channel_weights(layer, cx.mode); let blend_if = blend_if_active(layer, cx.mode); - let before = (w.is_some() || blend_if).then(|| backdrop.clone()); + let before = if w.is_some() || blend_if { Some(alloc.clone(backdrop)?) } else { None }; match ko { - Some(target) => advanced::knockout(layer, backdrop, target, false, cx, |b| composite_layer_any(layer, clipped, b, cx, scope)), - None => composite_layer_any(layer, clipped, backdrop, cx, scope), + Some(target) => advanced::knockout_with(layer, backdrop, target, false, cx, alloc, |b| composite_layer_any_with(layer, clipped, b, cx, scope, alloc))?, + None => composite_layer_any_with(layer, clipped, backdrop, cx, scope, alloc)?, } if let Some(before) = &before { if let Some(w) = w { restore_channels(backdrop, before, w); } if blend_if { - apply_blend_if(layer, before, backdrop, cx); + apply_blend_if_with(layer, before, backdrop, cx, alloc)?; } } + Ok(()) } -fn composite_layer_any(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { +fn composite_layer_any_with(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope, alloc: &A) -> Result<(), A::Error> { if let LayerContent::Group(g) = &layer.content && let Some(ab) = &g.artboard { - composite_artboard(layer, ab, clipped, backdrop, cx, scope); - return; + composite_artboard_with(layer, ab, clipped, backdrop, cx, scope, alloc)?; + return Ok(()); } - composite_layer_plain(layer, clipped, backdrop, cx, scope); + composite_layer_plain_with(layer, clipped, backdrop, cx, scope, alloc) } /// An artboard: its background and the group, composited only inside the board (contents and /// effects outside it are clipped away; the backdrop there is untouched). -fn composite_artboard(layer: &Layer, ab: &photocraft_doc::Artboard, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { +fn composite_artboard_with( + layer: &Layer, + ab: &photocraft_doc::Artboard, + clipped: &[Layer], + backdrop: &mut Buffer, + cx: &Ctx, + scope: advanced::Scope, + alloc: &A, +) -> Result<(), A::Error> { let board = ab.rect.intersect(&backdrop.rect); if board.is_empty() { - return; + return Ok(()); } let (bw, w) = (board.width() as usize, backdrop.rect.width() as usize); let row0 = |y: i32| (y - backdrop.rect.y0) as usize * w + (board.x0 - backdrop.rect.x0) as usize; - let mut sub = Buffer::transparent(board); + let mut sub = alloc.filled(board, [0.0; 4])?; for y in board.y0..board.y1 { let o = row0(y); let so = (y - board.y0) as usize * bw; sub.px[so..so + bw].copy_from_slice(&backdrop.px[o..o + bw]); } if let Some(bg) = ab.background.rgba() { - blend_into(&mut sub, &Buffer::filled(board, bg), BlendMode::Normal, 1.0); + let background = alloc.filled(board, bg)?; + blend_into(&mut sub, &background, BlendMode::Normal, 1.0); } - composite_layer_plain(layer, clipped, &mut sub, cx, scope); + composite_layer_plain_with(layer, clipped, &mut sub, cx, scope, alloc)?; for y in board.y0..board.y1 { let o = row0(y); let so = (y - board.y0) as usize * bw; backdrop.px[o..o + bw].copy_from_slice(&sub.px[so..so + bw]); } + Ok(()) } /// The surface `render_content` reads `layer`'s pixels from, when that is all it draws. @@ -343,12 +394,26 @@ pub(crate) fn composite_pixel_layer(layer: &Layer, surf: &Surface, backdrop: &mu } pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { + match composite_layer_plain_with(layer, clipped, backdrop, cx, scope, &InfallibleBufferAlloc) { + Ok(()) => {} + Err(never) => match never {}, + } +} + +fn composite_layer_plain_with( + layer: &Layer, + clipped: &[Layer], + backdrop: &mut Buffer, + cx: &Ctx, + scope: advanced::Scope, + alloc: &A, +) -> Result<(), A::Error> { let rect = backdrop.rect; // A TSL-off stroke base that is transparent here can still have visible clipped siblings; // keep the full clipping path for it instead of the stroke-bounds shortcut. Other bases keep // the usual skip (their clipped layers vanish with them). if (clipped.is_empty() || shapeless_stroke_bounds(layer).is_none()) && empty_in(layer, rect) { - return; + return Ok(()); } let opacity = layer.opacity * layer.fill_opacity; @@ -373,8 +438,8 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: let needs_mix = opacity < 1.0 || layer.mask.is_some() || layer.vector_mask.is_some(); let has_clipped = clipped.iter().any(|c| c.visible); // Children can draw directly unless mixing or clipping needs the original backdrop. - let before = (needs_mix || has_clipped).then(|| backdrop.clone()); - composite_stack_at(&g.children, backdrop, cx, scope.pass_through()); + let before = if needs_mix || has_clipped { Some(alloc.clone(backdrop)?) } else { None }; + composite_stack_at_with(&g.children, backdrop, cx, scope.pass_through(), alloc)?; if needs_mix && let Some(before) = &before { let mv = mask_vals(layer, rect, cx); for (i, (p, a)) in backdrop.px.iter_mut().zip(&before.px).enumerate() { @@ -395,33 +460,32 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: } // A Frame's stroke over the frame's content, at the group's opacity. if let Some(stroke) = shape_split::frame_stroke(layer, cx.canvas, cx.depth) { - blend_into(backdrop, &surface_to_buffer(&stroke, rect), BlendMode::Normal, opacity); + blend_into(backdrop, &surface_to_buffer_with(&stroke, rect, alloc)?, BlendMode::Normal, opacity); } // Layers clipped to a pass-through group sit atop the group's // isolated rendering; their effect (isolated result with vs. without // them, each placed over the original backdrop) is added to the // pass-through result. Exact when the children blend Normal, close // otherwise (matches psd-tools clipping-mask3/4/5). - if has_clipped && let (Some(before), Some(iso)) = (before, render_content(layer, rect, cx)) { - let mut clipped_iso = iso.clone(); - advanced::composite_clipped(clipped, &mut clipped_iso, cx); - let mut without = before.clone(); - blend_into(&mut without, &iso, BlendMode::Normal, opacity); - let mut with = before; - blend_into(&mut with, &clipped_iso, BlendMode::Normal, opacity); - for ((p, w), wo) in backdrop.px.iter_mut().zip(&with.px).zip(&without.px) { - // Work premultiplied so transparent areas stay consistent. - let pa = p[3]; - let mut pm = [p[0] * pa, p[1] * pa, p[2] * pa, pa]; - for c in 0..3 { - pm[c] += w[c] * w[3] - wo[c] * wo[3]; + if has_clipped { + if let (Some(before), Some(iso)) = (before, render_content_with(layer, rect, cx, alloc)?) { + let mut clipped_iso = alloc.clone(&iso)?; + advanced::composite_clipped_with(clipped, &mut clipped_iso, cx, alloc)?; + let mut without = alloc.clone(&before)?; + blend_into(&mut without, &iso, BlendMode::Normal, opacity); + let mut with = before; + blend_into(&mut with, &clipped_iso, BlendMode::Normal, opacity); + for ((p, w), wo) in backdrop.px.iter_mut().zip(&with.px).zip(&without.px) { + let pa = p[3]; + let mut pm = [p[0] * pa, p[1] * pa, p[2] * pa, pa]; + for c in 0..3 { pm[c] += w[c] * w[3] - wo[c] * wo[3]; } + pm[3] += w[3] - wo[3]; + let a = pm[3].clamp(0.0, 1.0); + *p = if a > 0.0 { [(pm[0] / a).clamp(0.0, 1.0), (pm[1] / a).clamp(0.0, 1.0), (pm[2] / a).clamp(0.0, 1.0), a] } else { [0.0; 4] }; } - pm[3] += w[3] - wo[3]; - let a = pm[3].clamp(0.0, 1.0); - *p = if a > 0.0 { [(pm[0] / a).clamp(0.0, 1.0), (pm[1] / a).clamp(0.0, 1.0), (pm[2] / a).clamp(0.0, 1.0), a] } else { [0.0; 4] }; } } - return; + return Ok(()); } // Adjustment layers transform the backdrop, then blend the result back in. @@ -429,13 +493,13 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: let mv = mask_vals(layer, rect, cx); if mv.as_ref().is_some_and(|values| values.iter().all(|&value| opacity * value <= 0.0)) { recycle_mask(mv); - return; + return Ok(()); } - let mut adjusted = Buffer::transparent(rect); + let mut adjusted = alloc.filled(rect, [0.0; 4])?; adjusted.px.copy_from_slice(&backdrop.px); cx.apply_adjustment(adj, &mut adjusted); // Clipped layers onto an adjustment are uncommon; they composite atop the adjusted result. - advanced::composite_clipped(clipped, &mut adjusted, cx); + advanced::composite_clipped_with(clipped, &mut adjusted, cx, alloc)?; if layer.blend == BlendMode::Dissolve { // An adjustment has no standalone source alpha. Its effective coverage comes from its // own opacity and mask, not a continuous RGB mix (#3050). @@ -460,7 +524,7 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: } } recycle_mask(mv); - return; + return Ok(()); } if effects::has_effects(layer) { @@ -468,23 +532,23 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: // hides the finished layer and effects. let src = advanced::effects_source(layer); let hide = advanced::hiding_mask(layer, rect, cx); - let before = hide.as_ref().map(|_| backdrop.clone()); - composite_layer_effects(&src, clipped, backdrop, cx); + let before = if hide.is_some() { Some(alloc.clone(backdrop)?) } else { None }; + composite_layer_effects_with(&src, clipped, backdrop, cx, alloc)?; if let (Some(m), Some(b)) = (&hide, &before) { advanced::apply_hiding_mask(backdrop, b, m); } recycle_mask(hide); - return; + return Ok(()); } - if let Some((mut content, stroke, mask)) = shape_parts(layer, clipped, rect, cx) { - advanced::composite_clipped(clipped, &mut content, cx); + if let Some((mut content, stroke, mask)) = shape_parts_with(layer, clipped, rect, cx, alloc)? { + advanced::composite_clipped_with(clipped, &mut content, cx, alloc)?; for (i, (p, s)) in content.px.iter_mut().zip(&stroke.px).enumerate() { *p = psblend::composite(BlendMode::Normal, *p, *s, 1.0); p[3] *= mask_k(&mask, i); } blend_layer_into(backdrop, &content, layer, cx, 1.0); recycle_mask(mask); - return; + return Ok(()); } if !matches!(layer.content, LayerContent::Group(_) | LayerContent::Fill(_) | LayerContent::Adjustment(_)) && let Some(s) = layer.surface() @@ -505,7 +569,7 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: *p = psblend::composite_normal_rgb([0.0; 4], *p, 1.0); } } - return; + return Ok(()); } // The row-at-a-time fast path blends like `blend_into_fill`; Transparency Shapes Layer off // with one of the special eight needs `blend_layer_into`'s per-pixel mask split. @@ -513,33 +577,35 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: && (layer.advanced.transparency_shapes || !psblend::fill_is_special(layer.blend)) && let Some(surf) = pixel_surface(layer) { - return composite_pixel_layer(layer, surf, backdrop, cx); + composite_pixel_layer(layer, surf, backdrop, cx); + return Ok(()); } - let Some(mut content) = render_content(layer, rect, cx) else { return }; - advanced::composite_clipped(clipped, &mut content, cx); + let Some(mut content) = render_content_with(layer, rect, cx, alloc)? else { return Ok(()) }; + advanced::composite_clipped_with(clipped, &mut content, cx, alloc)?; blend_layer_into(backdrop, &content, layer, cx, text_gamma(layer)); + Ok(()) } - /// A layer with effects (and its clipping group) onto `backdrop`. -fn composite_layer_effects(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx) { +fn composite_layer_effects_with(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, alloc: &A) -> Result<(), A::Error> { let rect = backdrop.rect; // Neighbourhoods are already captured by the full-region effect maps; // content and effect application only need the output rectangle. // A stroked shape's vector stroke stays above its clipped layers and interior effects. - let (mut content, parts) = match split_parts(layer, rect, cx) { + let (mut content, parts) = match split_parts_with(layer, rect, cx, alloc)? { Some((fill, stroke, mask)) => (fill, Some((stroke, mask))), None => { - let Some(content) = render_content(layer, rect, cx) else { return }; + let Some(content) = render_content_with(layer, rect, cx, alloc)? else { return Ok(()) }; (content, None) } }; - advanced::composite_clipped(clipped, &mut content, cx); + advanced::composite_clipped_with(clipped, &mut content, cx, alloc)?; let vstroke = parts.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); let maps = effect_maps(layer, rect, cx); - effects::composite_with_effects_prepared(layer, &content, backdrop, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke); + effects::composite_with_effects_prepared_with(layer, &content, backdrop, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke, alloc)?; if let Some((_, mask)) = parts { recycle_mask(mask); } + Ok(()) } /// The coverage-mixing gamma of a layer: the text blending gamma @@ -558,6 +624,19 @@ fn shape_parts(layer: &Layer, clipped: &[Layer], rect: Rect, cx: &Ctx) -> Option split_parts(layer, rect, cx) } +fn shape_parts_with( + layer: &Layer, + clipped: &[Layer], + rect: Rect, + cx: &Ctx, + alloc: &A, +) -> Result>)>, A::Error> { + if !clipped.iter().any(|c| c.visible) { + return Ok(None); + } + split_parts_with(layer, rect, cx, alloc) +} + /// A stroked shape layer's (fill, vector stroke, mask values) over `rect`; `None` for other /// layers. Fill and stroke are unmasked: the mask applies to them together. Layer effects paint /// the fill's interior effects beneath the vector stroke (psd-tools stroke-composite: a colour @@ -569,6 +648,20 @@ fn split_parts(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<(Buffer, Buffer, O Some((surface_to_buffer(&fs, rect), surface_to_buffer(&ss, rect), mask_vals(layer, rect, cx))) } +fn split_parts_with( + layer: &Layer, + rect: Rect, + cx: &Ctx, + alloc: &A, +) -> Result>)>, A::Error> { + let LayerContent::Shape(sh) = &layer.content else { return Ok(None) }; + if sh.stroke.is_none() { + return Ok(None); + } + let Some((fs, ss)) = shape_split::split(sh, cx.canvas, cx.depth) else { return Ok(None) }; + Ok(Some((surface_to_buffer_with(&fs, rect, alloc)?, surface_to_buffer_with(&ss, rect, alloc)?, mask_vals(layer, rect, cx)))) +} + pub(crate) fn texture_ctx<'a>(layer: &Layer, region: Rect, cx: &Ctx<'a>) -> effects::TextureCtx<'a> { let sb = effects_frame(layer, cx.canvas); effects::TextureCtx { rect: region, patterns: cx.patterns.source(), anchor: layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))) } @@ -577,24 +670,32 @@ pub(crate) fn texture_ctx<'a>(layer: &Layer, region: Rect, cx: &Ctx<'a>) -> effe /// Composite `layer` onto `base` restricted to the base's alpha (clipping mask semantics), /// honouring its channel restrictions and Blend If. pub(crate) fn composite_atop(layer: &Layer, base: &mut Buffer, cx: &Ctx) { + match composite_atop_with(layer, base, cx, &InfallibleBufferAlloc) { + Ok(()) => {} + Err(never) => match never {}, + } +} + +pub(crate) fn composite_atop_with(layer: &Layer, base: &mut Buffer, cx: &Ctx, alloc: &A) -> Result<(), A::Error> { let w = channel_weights(layer, cx.mode); let blend_if = blend_if_active(layer, cx.mode); - let before = (w.is_some() || blend_if).then(|| base.clone()); - composite_atop_any(layer, base, cx); + let before = if w.is_some() || blend_if { Some(alloc.clone(base)?) } else { None }; + composite_atop_any_with(layer, base, cx, alloc)?; if let Some(before) = &before { if let Some(w) = w { restore_channels(base, before, w); } if blend_if { - apply_blend_if(layer, before, base, cx); + apply_blend_if_with(layer, before, base, cx, alloc)?; } } + Ok(()) } -fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) { +fn composite_atop_any_with(layer: &Layer, base: &mut Buffer, cx: &Ctx, alloc: &A) -> Result<(), A::Error> { let rect = base.rect; if let LayerContent::Adjustment(adj) = &layer.content { - let mut adjusted = base.clone(); + let mut adjusted = alloc.clone(base)?; cx.apply_adjustment(adj, &mut adjusted); let mv = mask_vals(layer, rect, cx); for (i, p) in base.px.iter_mut().enumerate() { @@ -614,7 +715,7 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) { } } recycle_mask(mv); - return; + return Ok(()); } if effects::has_effects(layer) { // Effects of a clipped layer are clipped to the base too: render @@ -624,25 +725,27 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) { let hide = advanced::hiding_mask(layer, rect, cx); let src = advanced::effects_source(layer); let layer = src.as_ref(); - let (content, parts) = match split_parts(layer, rect, cx) { + let (content, parts) = match split_parts_with(layer, rect, cx, alloc)? { Some((fill, stroke, mask)) => (fill, Some((stroke, mask))), None => { - let Some(content) = render_content(layer, rect, cx) else { + let Some(content) = render_content_with(layer, rect, cx, alloc)? else { recycle_mask(hide); - return; + return Ok(()); }; (content, None) } }; let vstroke = parts.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); - let mut opaque = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() }; + let mut opaque = alloc.clone(base)?; + for p in &mut opaque.px { p[3] = 1.0; } let maps = effect_maps(layer, rect, cx); - effects::composite_with_effects_prepared(layer, &content, &mut opaque, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke); + effects::composite_with_effects_prepared_with(layer, &content, &mut opaque, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke, alloc)?; if let Some((_, mask)) = parts { recycle_mask(mask); } if let Some(m) = &hide { - let plain = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() }; + let mut plain = alloc.clone(base)?; + for p in &mut plain.px { p[3] = 1.0; } advanced::apply_hiding_mask(&mut opaque, &plain, m); } recycle_mask(hide); @@ -651,9 +754,9 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) { *p = [o[0], o[1], o[2], p[3]]; } } - return; + return Ok(()); } - let Some(content) = render_content(layer, rect, cx) else { return }; + let Some(content) = render_content_with(layer, rect, cx, alloc)? else { return Ok(()) }; let opacity = layer.opacity * layer.fill_opacity; let gamma = text_gamma(layer); for (i, p) in base.px.iter_mut().enumerate() { @@ -676,6 +779,7 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) { let r = blend::composite_gamma(layer.blend, [p[0], p[1], p[2], 1.0], s, opacity, gamma); *p = [r[0], r[1], r[2], alpha]; } + Ok(()) } /// Blend an isolated layer buffer into the backdrop. diff --git a/crates/compose/src/content.rs b/crates/compose/src/content.rs index 1f91c6a942..f65f93a475 100644 --- a/crates/compose/src/content.rs +++ b/crates/compose/src/content.rs @@ -1,8 +1,8 @@ -use super::composite::{adjustment_quantum, blend_into, composite_stack}; +use super::composite::{adjustment_quantum, blend_into}; use super::ctx::Ctx; use super::extents::{effect_shape, effect_source_bounds, mask_vals, recycle_mask, shapeless_stroke_bounds, transparent_outside}; use super::fx_cache::effect_maps; -use super::{BlendMode, Buffer, Document, Fill, Layer, LayerContent, Pattern, Rect, Surface, bounds, effects, gradient_fill, pattern, shape_split}; +use super::{BlendMode, Buffer, BufferAlloc, Document, Fill, InfallibleBufferAlloc, Layer, LayerContent, Pattern, Rect, Surface, bounds, effects, gradient_fill, pattern, shape_split}; /// Tile size for parallel rendering (tile results are independent). pub const RENDER_TILE: i32 = 256; @@ -29,30 +29,37 @@ fn scratch_reuse_preserves_pixels() { /// Render a layer's own content (no blending into the backdrop yet) into an isolated buffer. /// Returns None for layers that operate on the backdrop (adjustments, pass-through groups). pub(crate) fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option { + match render_content_with(layer, rect, cx, &InfallibleBufferAlloc) { + Ok(buffer) => buffer, + Err(never) => match never {}, + } +} + +pub(crate) fn render_content_with(layer: &Layer, rect: Rect, cx: &Ctx, alloc: &A) -> Result, A::Error> { let mut buf = match &layer.content { LayerContent::Group(g) => { - let mut b = Buffer::transparent(rect); - composite_stack(&g.children, &mut b, cx); + let mut b = alloc.filled(rect, [0.0; 4])?; + super::composite::composite_stack_at_with(&g.children, &mut b, cx, super::advanced::Scope::ISOLATED, alloc)?; b } LayerContent::Fill(f) => match &layer.fill_cache { // Photoshop's own rendering, valid while the fill is unchanged. - Some(c) if c.fill == *f => surface_to_scratch(&c.surface, rect), + Some(c) if c.fill == *f => surface_to_scratch_with(&c.surface, rect, alloc)?, _ if cx.mode == photocraft_color::ColorMode::Cmyk => { let frame = fill_frame(layer, cx.canvas); let native_rect = if matches!(f, Fill::Solid(_)) { Rect::new(0, 0, 1, 1) } else { rect }; match gradient_fill::render_cmyk_fill(f, native_rect, frame, cx.depth) { - Some(s) if matches!(f, Fill::Solid(_)) => Buffer::filled(rect, s.rgba(0, 0)), - Some(s) => surface_to_buffer(&s, rect), - None => render_fill(f, rect, frame, cx.patterns, adjustment_quantum(cx.depth)), + Some(s) if matches!(f, Fill::Solid(_)) => alloc.filled(rect, s.rgba(0, 0))?, + Some(s) => surface_to_buffer_with(&s, rect, alloc)?, + None => render_fill_with(f, rect, frame, cx.patterns, adjustment_quantum(cx.depth), alloc)?, } } - _ => render_fill(f, rect, fill_frame(layer, cx.canvas), cx.patterns, adjustment_quantum(cx.depth)), + _ => render_fill_with(f, rect, fill_frame(layer, cx.canvas), cx.patterns, adjustment_quantum(cx.depth), alloc)?, }, - LayerContent::Adjustment(_) => return None, + LayerContent::Adjustment(_) => return Ok(None), _ => match layer.surface() { - Some(s) => surface_to_scratch(s, rect), - None => Buffer::transparent(rect), + Some(s) => surface_to_scratch_with(s, rect, alloc)?, + None => alloc.filled(rect, [0.0; 4])?, }, }; if let Some(m) = mask_vals(layer, rect, cx) { @@ -63,9 +70,9 @@ pub(crate) fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option Buffer { buf } +pub(crate) fn surface_to_buffer_with(s: &Surface, rect: Rect, alloc: &A) -> Result { + let mut buf = alloc.filled(rect, [0.0; 4])?; + s.read_rgba_into(rect, &mut buf.px); + Ok(buf) +} + +fn render_fill_with( + fill: &Fill, + rect: Rect, + frame: Rect, + patterns: &pattern::PreparedPatterns<'_>, + quantum: Option, + alloc: &A, +) -> Result { + match fill { + Fill::Solid(c) => { + let rgb = c.to_rgb(); + alloc.filled(rect, [rgb[0], rgb[1], rgb[2], c.alpha]) + } + Fill::Gradient { .. } => { + let mut buffer = alloc.filled(rect, [0.0; 4])?; + gradient_fill::render_quantized_into(fill, rect, frame, quantum, &mut buffer.px); + Ok(buffer) + } + Fill::Pattern { name, id, scale, angle, link, phase } => { + let mut buffer = alloc.filled(rect, [0.0; 4])?; + if let Some(tile) = patterns.get(id, name) { + pattern::render_into(&tile, &pattern::Placement::new(frame, *link, *phase, *scale, *angle), rect, &mut buffer.px); + } + Ok(buffer) + } + } +} + fn surface_to_scratch(s: &Surface, rect: Rect) -> Buffer { let mut buf = Buffer::transparent(rect); s.read_rgba_into(rect, &mut buf.px); buf } +fn surface_to_scratch_with(s: &Surface, rect: Rect, alloc: &A) -> Result { + let mut buf = alloc.filled(rect, [0.0; 4])?; + s.read_rgba_into(rect, &mut buf.px); + Ok(buf) +} + /// The frame a fill layer's gradient is laid out in ("Align with layer", Photoshop's default): /// the layer's bounds, i.e. the area its masks reveal: a hide-all pixel mask's painted area, or /// the vector mask's path; otherwise the canvas. diff --git a/crates/compose/src/effects/composite.rs b/crates/compose/src/effects/composite.rs index 71e37594db..b570fe32fd 100644 --- a/crates/compose/src/effects/composite.rs +++ b/crates/compose/src/effects/composite.rs @@ -3,7 +3,7 @@ use super::distance::{INSIDE_EPS, Metric, dist_inside_by, dist_outside_by, local use super::paint::{dissolves_in, glow_map, paint_color, paint_fx, paint_glow, paint_pattern, rgb, shadow_map}; use super::{ Bevel, BevelStyle, BlendMode, Buffer, Effect, FxMaps, FxPaint, GlobalLight, Layer, MAX_REACH, Map, PREPARED_PATTERN_BYTES, Pattern, Placement, - PreparedPatterns, Rect, StrokePosition, psblend, + BufferAlloc, InfallibleBufferAlloc, PreparedPatterns, Rect, StrokePosition, psblend, }; /// Build every effect map for `layer` from its alpha `shape` over `rect`. @@ -242,13 +242,29 @@ pub(crate) fn composite_with_effects_prepared( patterns: &PreparedPatterns<'_>, vstroke: Option>, ) { + match composite_with_effects_prepared_with(layer, content, backdrop, maps, layer_bounds, patterns, vstroke, &InfallibleBufferAlloc) { + Ok(()) => {} + Err(never) => match never {}, + } +} + +pub(crate) fn composite_with_effects_prepared_with( + layer: &Layer, + content: &Buffer, + backdrop: &mut Buffer, + maps: &FxMaps, + layer_bounds: Rect, + patterns: &PreparedPatterns<'_>, + vstroke: Option>, + alloc: &A, +) -> Result<(), A::Error> { let pass = EffectPass::new(layer, maps, content.rect, layer_bounds, patterns, vstroke.as_ref()); let big = pass.big; let shape = pass.effect_shape(content); let rect = backdrop.rect; - let before = backdrop.clone(); + let before = alloc.clone(backdrop)?; // Exterior effects are painted on a backdrop copy extended to `big`. - let mut work = Buffer::transparent(big); + let mut work = alloc.filled(big, [0.0; 4])?; for y in rect.y0.max(big.y0)..rect.y1.min(big.y1) { for x in rect.x0.max(big.x0)..rect.x1.min(big.x1) { work.px[((y - big.y0) as usize) * pass.w + (x - big.x0) as usize] = before.get(x, y); @@ -262,7 +278,7 @@ pub(crate) fn composite_with_effects_prepared( // keeps its alpha, as in Photoshop. let gamma = crate::text_gamma(layer); let premerge = premerges_layer(layer); - let mut lay = pass.layer_pixels(content, &shape); + let mut lay = pass.layer_pixels_with(content, &shape, alloc)?; if premerge { for (lp, wp) in lay.px.iter_mut().zip(&work.px) { *lp = psblend::composite_gamma(layer.blend, *wp, *lp, 1.0, gamma); @@ -272,13 +288,13 @@ pub(crate) fn composite_with_effects_prepared( let fields = pass.stroke_fields(!strokes.is_empty()); pass.paint_interior(&mut lay, &shape); pass.paint_vector_stroke(&mut lay, &shape); - pass.paint_inside_strokes(&mut lay, &shape, &strokes, &fields); + pass.paint_inside_strokes_with(&mut lay, &shape, &strokes, &fields, alloc)?; pass.paint_bevel(&mut lay, BevelPaint::Inner, Some(&shape)); // The shape's own alpha. for (p, a) in lay.px.iter_mut().zip(&shape.v) { p[3] *= a.min(1.0); } - pass.paint_outside_strokes(&mut work, &lay, &shape, &strokes, &fields); + pass.paint_outside_strokes_with(&mut work, &lay, &shape, &strokes, &fields, alloc)?; pass.paint_bevel(&mut work, BevelPaint::Outer, None); // Layer (with interior effects) onto the exterior result, in the layer's mode. @@ -293,6 +309,7 @@ pub(crate) fn composite_with_effects_prepared( // to 6/255 dark (psd-tools layer_effects Emboss: 7.8 → 5.7/255). pass.paint_bevel(&mut work, BevelPaint::Both, None); pass.write_back(backdrop, &before, &work); + Ok(()) } /// `true` where the effect shape covers a pixel enough for interior effects to paint. @@ -435,7 +452,7 @@ impl<'a> EffectPass<'a> { } /// The layer's own pixels at fill opacity, with their alpha made relative to `shape`. - fn layer_pixels(&self, content: &Buffer, shape: &Map) -> Buffer { + fn layer_pixels_with(&self, content: &Buffer, shape: &Map, alloc: &A) -> Result { let content_fill = if self.interior_group() { 1.0 } else { self.layer.fill_opacity }; let relative = self.relative(); let lay_alpha = |i: usize, p: &[f32; 4], a: f32| { @@ -447,7 +464,11 @@ impl<'a> EffectPass<'a> { content_fill } }; - Buffer { rect: self.big, px: content.px.iter().zip(&shape.v).enumerate().map(|(i, (p, a))| [p[0], p[1], p[2], lay_alpha(i, p, *a)]).collect() } + let mut lay = alloc.filled(self.big, [0.0; 4])?; + for (i, (out, (p, a))) in lay.px.iter_mut().zip(content.px.iter().zip(&shape.v)).enumerate() { + *out = [p[0], p[1], p[2], lay_alpha(i, p, *a)]; + } + Ok(lay) } /// Paints the interior effects other than strokes and bevels: overlays, satin, inner glow @@ -535,7 +556,14 @@ impl<'a> EffectPass<'a> { /// Strokes. Inside parts are painted over the layer (bottom instance first); outside parts /// are slid beneath it, so the first listed (top) instance is processed first. - fn paint_inside_strokes(&self, lay: &mut Buffer, shape: &Map, strokes: &[&photocraft_doc::StrokeFx], fields: &StrokeFields) { + fn paint_inside_strokes_with( + &self, + lay: &mut Buffer, + shape: &Map, + strokes: &[&photocraft_doc::StrokeFx], + fields: &StrokeFields, + alloc: &A, + ) -> Result<(), A::Error> { for st in strokes.iter().rev().copied() { let (in_w, _) = stroke_widths(st); if in_w <= 0.0 { @@ -549,7 +577,7 @@ impl<'a> EffectPass<'a> { // A Normal stroke replaces the layer under it instead of blending with it // (Photoshop): at 50 % opacity an opaque pixel under the stroke turns into the // stroke colour at 50 % alpha, not a 50/50 mix. - let mut stroke_px = Buffer { rect: self.big, px: vec![[0.0; 4]; lay.px.len()] }; + let mut stroke_px = alloc.filled(self.big, [0.0; 4])?; paint_fx(&mut stroke_px, &m, &st.paint, self.stroke_frame(st), self.anchor, self.big, BlendMode::Normal, st.common.opacity, self.patterns); for ((p, s), cov) in lay.px.iter_mut().zip(&stroke_px.px).zip(&m.v) { if s[3] <= 0.0 { @@ -565,6 +593,7 @@ impl<'a> EffectPass<'a> { paint_fx(lay, &m, &st.paint, self.stroke_frame(st), self.anchor, self.big, st.common.blend, st.common.opacity, self.patterns); } } + Ok(()) } /// Bevel and emboss effects whose paint is `kind`. Inner ones paint into the layer relative @@ -589,12 +618,20 @@ impl<'a> EffectPass<'a> { /// above a wider Normal stroke multiplies the backdrop, not the lower stroke). Each stroke's /// share is its coverage × opacity not yet taken by strokes above; for Normal strokes this /// equals stacking them top over bottom. - fn paint_outside_strokes(&self, work: &mut Buffer, lay: &Buffer, shape: &Map, strokes: &[&photocraft_doc::StrokeFx], fields: &StrokeFields) { + fn paint_outside_strokes_with( + &self, + work: &mut Buffer, + lay: &Buffer, + shape: &Map, + strokes: &[&photocraft_doc::StrokeFx], + fields: &StrokeFields, + alloc: &A, + ) -> Result<(), A::Error> { if !strokes.iter().any(|st| stroke_widths(st).1 > 0.0) { - return; + return Ok(()); } let (w, h) = (self.w, self.h); - let base = work.clone(); + let base = alloc.clone(work)?; let mut acc = vec![[0.0f32; 4]; w * h]; // premultiplied Σ share·blended let mut cover = vec![0.0f32; w * h]; for st in strokes.iter().copied() { @@ -604,7 +641,7 @@ impl<'a> EffectPass<'a> { } let share = self.outside_share(st, out_w, shape, lay, fields, &mut cover); // The stroke blended over the backdrop at full coverage. - let mut blended = base.clone(); + let mut blended = alloc.clone(&base)?; let ones = Map { w, h, v: share.iter().map(|&s| if s > 0.0 { 1.0 } else { 0.0 }).collect() }; // The share already carries the Dissolve choice, so the paint itself composites as Normal. let paint_blend = if st.common.blend == BlendMode::Dissolve { BlendMode::Normal } else { st.common.blend }; @@ -628,6 +665,7 @@ impl<'a> EffectPass<'a> { *p = [(p[0] * p[3] * k + a[0]) / alpha, (p[1] * p[3] * k + a[1]) / alpha, (p[2] * p[3] * k + a[2]) / alpha, alpha.min(1.0)]; } } + Ok(()) } /// The share of each pixel an outside stroke `st` (outside width `out_w`) takes: its coverage diff --git a/crates/compose/src/gradient_fill.rs b/crates/compose/src/gradient_fill.rs index 21a7401b6a..995d420b6e 100644 --- a/crates/compose/src/gradient_fill.rs +++ b/crates/compose/src/gradient_fill.rs @@ -130,7 +130,15 @@ pub fn render(f: &Fill, rect: Rect, frame: Rect) -> Vec<[f32; 4]> { /// [`render`] with dithered pixels rounded to `quantum` steps (the document depth's levels, see /// [`crate::adjustment_quantum`]), as a gradient painted into a layer of that depth stores them. pub fn render_quantized(f: &Fill, rect: Rect, frame: Rect, quantum: Option) -> Vec<[f32; 4]> { - render_ramp(f, rect, frame, Ramp::new(f), quantum) + let mut px = vec![[0.0f32; 4]; rect.width() as usize * rect.height() as usize]; + render_quantized_into(f, rect, frame, quantum, &mut px); + px +} + +/// Render into caller-owned pixels so compositor paths can use fallible pooled storage. +pub(crate) fn render_quantized_into(f: &Fill, rect: Rect, frame: Rect, quantum: Option, px: &mut [[f32; 4]]) { + px.fill([0.0; 4]); + render_ramp_into(f, rect, frame, Ramp::new(f), quantum, px); } /// Native CMYK solid/gradient pixels at document depth; patterns return `None`. @@ -155,10 +163,16 @@ pub fn render_cmyk_fill(f: &Fill, rect: Rect, frame: Rect, depth: photocraft_col fn render_ramp(f: &Fill, rect: Rect, frame: Rect, ramp: Option>, quantum: Option) -> Vec<[f32; N]> { let mut px = vec![[0.0f32; N]; rect.width() as usize * rect.height() as usize]; - let (Some(ramp), Fill::Gradient { angle, scale, style, reverse, offset, dither: dith, .. }) = (ramp, f) else { return px }; + render_ramp_into(f, rect, frame, ramp, quantum, &mut px); + px +} + +fn render_ramp_into(f: &Fill, rect: Rect, frame: Rect, ramp: Option>, quantum: Option, px: &mut [[f32; N]]) { + px.fill([0.0; N]); + let (Some(ramp), Fill::Gradient { angle, scale, style, reverse, offset, dither: dith, .. }) = (ramp, f) else { return }; let w = rect.width() as usize; if w == 0 { - return px; + return; } // Linear and Reflected end points on whole pixels, as Photoshop (crate::fill_layout). let (angle, scale, offset) = &crate::fill_layout::gradient_layout(*style, *angle, *scale, *offset, frame); @@ -181,7 +195,6 @@ fn render_ramp(f: &Fill, rect: Rect, frame: Rect, ramp: Option (f32, f32) { diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index f91aef2211..75d5b5359f 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -86,8 +86,8 @@ use render::in_blend_space; use render::render_tiled_with; pub(crate) use render::visible_layers; pub use render::{ - BAND_PIXELS, MAX_RENDER_PIXELS, band_rows_for, cmyk_space, composite_to_surface, composite_to_surface_with_interrupt, flatten, flatten_to_surface, render, - render_bands, render_layer, render_layer_in, render_tiled, + BAND_PIXELS, MAX_RENDER_PIXELS, RenderBandsError, band_rows_for, cmyk_space, composite_to_surface, composite_to_surface_with_interrupt, flatten, + flatten_to_surface, render, render_bands, render_layer, render_layer_in, render_tiled, try_render_bands, }; /// Straight-alpha RGBA float buffer covering a rectangle. @@ -120,6 +120,27 @@ impl Buffer { pub fn filled(rect: Rect, c: [f32; 4]) -> Self { Self { rect, px: photocraft_raster::scratch::take(rect.width() as usize * rect.height() as usize, c) } } + /// Fallibly allocate a transparent RGBA buffer, preserving `filled`'s scratch-pool slack. + pub fn try_transparent(rect: Rect) -> Result { + Self::try_filled(rect, [0.0; 4]) + } + /// Fallibly allocate and fill an RGBA buffer. + pub fn try_filled(rect: Rect, c: [f32; 4]) -> Result { + let width = usize::try_from(rect.width()).map_err(|_| photocraft_raster::AllocationError::SizeOverflow)?; + let height = usize::try_from(rect.height()).map_err(|_| photocraft_raster::AllocationError::SizeOverflow)?; + let len = width.checked_mul(height).ok_or(photocraft_raster::AllocationError::SizeOverflow)?; + let bytes = len.checked_mul(std::mem::size_of::<[f32; 4]>()).ok_or(photocraft_raster::AllocationError::SizeOverflow)?; + let px = photocraft_raster::scratch::try_take(len, c).ok_or(photocraft_raster::AllocationError::NotEnoughMemory { bytes })?; + Ok(Self { rect, px }) + } + /// Fallibly clone the pixel storage while keeping the same rectangle. + pub fn try_clone(&self) -> Result { + let bytes = self.px.len().checked_mul(std::mem::size_of::<[f32; 4]>()).ok_or(photocraft_raster::AllocationError::SizeOverflow)?; + let mut px = photocraft_raster::scratch::try_take(self.px.len(), [0.0; 4]) + .ok_or(photocraft_raster::AllocationError::NotEnoughMemory { bytes })?; + px.copy_from_slice(&self.px); + Ok(Self { rect: self.rect, px }) + } /// The pixels, taken out of the buffer (it can't be destructured: it returns them to the /// pool on drop). pub fn into_px(mut self) -> Vec<[f32; 4]> { @@ -164,6 +185,36 @@ impl Buffer { } } +/// Selects infallible compatibility behavior or propagating buffer allocation errors in the +/// shared compositor core. +pub(crate) trait BufferAlloc { + type Error: Send; + fn filled(&self, rect: Rect, color: [f32; 4]) -> Result; + fn clone(&self, buffer: &Buffer) -> Result; +} + +pub(crate) struct InfallibleBufferAlloc; +impl BufferAlloc for InfallibleBufferAlloc { + type Error = std::convert::Infallible; + fn filled(&self, rect: Rect, color: [f32; 4]) -> Result { + Ok(Buffer::filled(rect, color)) + } + fn clone(&self, buffer: &Buffer) -> Result { + Ok(buffer.clone()) + } +} + +pub(crate) struct FallibleBufferAlloc; +impl BufferAlloc for FallibleBufferAlloc { + type Error = photocraft_raster::AllocationError; + fn filled(&self, rect: Rect, color: [f32; 4]) -> Result { + Buffer::try_filled(rect, color) + } + fn clone(&self, buffer: &Buffer) -> Result { + buffer.try_clone() + } +} + #[cfg(test)] mod soft_shape_tests; #[cfg(test)] diff --git a/crates/compose/src/multichannel.rs b/crates/compose/src/multichannel.rs index a92ee3a7fe..1b58b3aa2c 100644 --- a/crates/compose/src/multichannel.rs +++ b/crates/compose/src/multichannel.rs @@ -193,7 +193,20 @@ pub fn inks(doc: &Document, rect: Rect) -> Buffer { /// The starting backdrop of a document render: the inks for Multichannel, else transparent. pub(crate) fn backdrop(doc: &Document, rect: Rect) -> Buffer { - if doc.mode == ColorMode::Multichannel { inks(doc, rect) } else { Buffer::transparent(rect) } + match backdrop_with(doc, rect, &crate::InfallibleBufferAlloc) { + Ok(buffer) => buffer, + Err(never) => match never {}, + } +} + +pub(crate) fn backdrop_with(doc: &Document, rect: Rect, alloc: &A) -> Result { + if doc.mode == ColorMode::Multichannel { + let mut buf = alloc.filled(rect, [1.0; 4])?; + overprint(&mut buf, doc, |_| true); + Ok(buf) + } else { + alloc.filled(rect, [0.0; 4]) + } } /// [`crate::thumbnail_buffer`] of an RGB or CMYK document with its spot channels printed over it diff --git a/crates/compose/src/native.rs b/crates/compose/src/native.rs index 98f87f75a9..c605e4c948 100644 --- a/crates/compose/src/native.rs +++ b/crates/compose/src/native.rs @@ -286,12 +286,19 @@ pub fn flatten_cmyk(doc: &Document, rect: Rect, fmt: PixelFormat, paper: bool) - /// whose stack has adjustment layers the inks carry exactly, worked out on the inks; `None` for /// any other document, which the RGB compositor renders. Rows of `tile` render in parallel. pub fn render_cmyk(doc: &Document, rect: Rect, tile: i32) -> Option { - let stack = InkStack::new(doc).filter(InkStack::adjusts)?; + match render_cmyk_with(doc, rect, tile, &crate::InfallibleBufferAlloc) { + Ok(result) => result, + Err(never) => match never {}, + } +} + +pub(crate) fn render_cmyk_with(doc: &Document, rect: Rect, tile: i32, alloc: &A) -> Result, A::Error> { + let Some(stack) = InkStack::new(doc).filter(InkStack::adjusts) else { return Ok(None) }; let cmyk = crate::cmyk_space(doc); let w = rect.width() as usize; - let mut out = Buffer::transparent(rect); + let mut out = alloc.filled(rect, [0.0; 4])?; if w == 0 || rect.is_empty() { - return Some(out); + return Ok(Some(out)); } let rows = tile.max(1) as usize; let band = |i: usize, px: &mut [[f32; 4]]| { @@ -311,11 +318,12 @@ pub fn render_cmyk(doc: &Document, rect: Rect, tile: i32) -> Option { #[cfg(not(target_arch = "wasm32"))] { use rayon::prelude::*; - out.px.par_chunks_mut(w * rows).enumerate().for_each(|(i, px)| band(i, px)); + let chunk_len = w.saturating_mul(rows).min(out.px.len()).max(1); + out.px.par_chunks_mut(chunk_len).enumerate().for_each(|(i, px)| band(i, px)); } #[cfg(target_arch = "wasm32")] - for (i, px) in out.px.chunks_mut(w * rows).enumerate() { + for (i, px) in out.px.chunks_mut(w.saturating_mul(rows).min(out.px.len()).max(1)).enumerate() { band(i, px); } - Some(out) + Ok(Some(out)) } diff --git a/crates/compose/src/native_lab.rs b/crates/compose/src/native_lab.rs index 771240a46b..a59c634131 100644 --- a/crates/compose/src/native_lab.rs +++ b/crates/compose/src/native_lab.rs @@ -227,11 +227,18 @@ pub fn flatten_lab(doc: &Document, rect: Rect, fmt: PixelFormat, white: bool) -> /// work on L, a and b, worked out on the stored values; `None` for any other document, which the /// RGB compositor renders. Rows of `tile` render in parallel. pub fn render_lab(doc: &Document, rect: Rect, tile: i32) -> Option { - let stack = LabStack::new(doc).filter(LabStack::adjusts)?; + match render_lab_with(doc, rect, tile, &crate::InfallibleBufferAlloc) { + Ok(result) => result, + Err(never) => match never {}, + } +} + +pub(crate) fn render_lab_with(doc: &Document, rect: Rect, tile: i32, alloc: &A) -> Result, A::Error> { + let Some(stack) = LabStack::new(doc).filter(LabStack::adjusts) else { return Ok(None) }; let w = rect.width() as usize; - let mut out = Buffer::transparent(rect); + let mut out = alloc.filled(rect, [0.0; 4])?; if w == 0 || rect.is_empty() { - return Some(out); + return Ok(Some(out)); } let rows = tile.max(1) as usize; let band = |i: usize, px: &mut [[f32; 4]]| { @@ -249,11 +256,12 @@ pub fn render_lab(doc: &Document, rect: Rect, tile: i32) -> Option { #[cfg(not(target_arch = "wasm32"))] { use rayon::prelude::*; - out.px.par_chunks_mut(w * rows).enumerate().for_each(|(i, px)| band(i, px)); + let chunk_len = w.saturating_mul(rows).min(out.px.len()).max(1); + out.px.par_chunks_mut(chunk_len).enumerate().for_each(|(i, px)| band(i, px)); } #[cfg(target_arch = "wasm32")] - for (i, px) in out.px.chunks_mut(w * rows).enumerate() { + for (i, px) in out.px.chunks_mut(w.saturating_mul(rows).min(out.px.len()).max(1)).enumerate() { band(i, px); } - Some(out) + Ok(Some(out)) } diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs index fce5b0e832..c30db7f718 100644 --- a/crates/compose/src/pattern.rs +++ b/crates/compose/src/pattern.rs @@ -449,12 +449,22 @@ impl Placement { /// Renders `tile` over `rect` (row-major straight RGBA). pub fn render(tile: &Tile, place: &Placement, rect: Rect) -> Vec<[f32; 4]> { let mut out = Vec::with_capacity(rect.width() as usize * rect.height() as usize); + render_into(tile, place, rect, &mut out); + out +} + +/// Render into caller-owned storage for fallible compositor allocations. +pub(crate) fn render_into(tile: &Tile, place: &Placement, rect: Rect, out: &mut Vec<[f32; 4]>) { + let len = rect.width() as usize * rect.height() as usize; + out.clear(); + out.resize(len, [0.0; 4]); + let mut i = 0; for y in rect.y0..rect.y1 { for x in rect.x0..rect.x1 { - out.push(tile.sample_area(place, f64::from(x) + 0.5, f64::from(y) + 0.5)); + out[i] = tile.sample_area(place, f64::from(x) + 0.5, f64::from(y) + 0.5); + i += 1; } } - out } #[cfg(test)] diff --git a/crates/compose/src/render.rs b/crates/compose/src/render.rs index 4f5d629f3a..9d277c7bee 100644 --- a/crates/compose/src/render.rs +++ b/crates/compose/src/render.rs @@ -1,7 +1,10 @@ -use super::composite::composite_stack_at; +use super::composite::{composite_stack_at, composite_stack_at_with}; use super::content::RENDER_TILE; use super::ctx::{Ctx, RenderVectorMasks, prepare_effects, prepare_tones}; -use super::{Buffer, Document, Layer, Rect, Surface, adjust, advanced, cmyk, multichannel, native, native_lab, pattern, psblend}; +use super::{ + Buffer, BufferAlloc, Document, FallibleBufferAlloc, InfallibleBufferAlloc, Layer, Rect, Surface, adjust, advanced, cmyk, multichannel, native, + native_lab, pattern, psblend, +}; /// Every layer the compositor draws, groups before their children: hidden layers and everything /// inside hidden groups are left out. @@ -38,6 +41,13 @@ pub fn render_tiled(doc: &Document, rect: Rect, tile: i32) -> Buffer { } pub(crate) fn render_tiled_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) -> Buffer { + match render_tiled_with_alloc(doc, rect, tile, cx, &InfallibleBufferAlloc) { + Ok(buffer) => buffer, + Err(never) => match never {}, + } +} + +fn render_tiled_with_alloc(doc: &Document, rect: Rect, tile: i32, cx: &Ctx, alloc: &A) -> Result { let tile = tile.max(1); // Lab documents mix Normal blending in CIELAB, as Photoshop does (psblend::LAB_MIX); 32-bit // documents don't clip Add / Divide or Hue / Saturation / Color / Luminosity at 1 (psblend::HDR). @@ -47,26 +57,26 @@ pub(crate) fn render_tiled_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) let cmyk = cmyk_space(doc); let cmyk = cmyk.as_ref(); if rect.is_empty() { - return Buffer::transparent(rect); + return alloc.filled(rect, [0.0; 4]); } // Refuse rects too large to hold: an empty buffer, not an allocation failure. if u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS { - return Buffer::transparent(Rect::EMPTY); + return alloc.filled(Rect::EMPTY, [0.0; 4]); } - // A CMYK stack with adjustment layers the inks carry exactly composites on its inks. - if let Some(buf) = native::render_cmyk(doc, rect, tile) { - return buf; + // A CMYK stack with adjustment layers the inks carry exactly composites on the inks. + if let Some(buf) = native::render_cmyk_with(doc, rect, tile, alloc)? { + return Ok(buf); } // A Lab stack with adjustment layers that work on L, a and b composites on its stored values. - if let Some(buf) = native_lab::render_lab(doc, rect, tile) { - return buf; + if let Some(buf) = native_lab::render_lab_with(doc, rect, tile, alloc)? { + return Ok(buf); } cx.set_fx_clip(rect); if i64::from(rect.width()) <= i64::from(tile) && i64::from(rect.height()) <= i64::from(tile) { - return photocraft_color::convert::with_cmyk_space(cmyk, || { - let mut buf = multichannel::backdrop(doc, rect); - in_blend_space(lab, hdr, || composite_stack_at(&doc.layers, &mut buf, cx, advanced::Scope::ROOT)); - buf + return photocraft_color::convert::with_cmyk_space(cmyk, || -> Result<_, A::Error> { + let mut buf = multichannel::backdrop_with(doc, rect, alloc)?; + in_blend_space(lab, hdr, || composite_stack_at_with(&doc.layers, &mut buf, cx, advanced::Scope::ROOT, alloc))?; + Ok(buf) }); } // Effect maps are built once, here, before any tile needs them (#276). @@ -74,16 +84,16 @@ pub(crate) fn render_tiled_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) photocraft_color::convert::with_cmyk_space(cmyk, || in_blend_space(lab, hdr, f)); }); let run = |t: Rect| { - photocraft_color::convert::with_cmyk_space(cmyk, || { - let mut b = multichannel::backdrop(doc, t); - in_blend_space(lab, hdr, || composite_stack_at(&doc.layers, &mut b, cx, advanced::Scope::ROOT)); - b + photocraft_color::convert::with_cmyk_space(cmyk, || -> Result<_, A::Error> { + let mut b = multichannel::backdrop_with(doc, t, alloc)?; + in_blend_space(lab, hdr, || composite_stack_at_with(&doc.layers, &mut b, cx, advanced::Scope::ROOT, alloc))?; + Ok(b) }) }; // Tiles are written straight into the output, one row of tiles (a band) at a time, so the // peak is the output plus the tiles in flight, not a second full-size copy. let w = rect.width() as usize; - let mut out = Buffer::transparent(rect); + let mut out = alloc.filled(rect, [0.0; 4])?; let band_tiles = |y0: i32| { let y1 = y0.saturating_add(tile).min(rect.y1); let mut v = Vec::new(); @@ -102,42 +112,46 @@ pub(crate) fn render_tiled_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) band[o..o + pw].copy_from_slice(src); } }; - let band_len = w * tile as usize; + let band_len = w.saturating_mul(tile as usize).min(out.px.len()).max(1); #[cfg(not(target_arch = "wasm32"))] { use rayon::prelude::*; let bands = rect.height().div_ceil(tile as u32) as usize; if bands >= 2 * rayon::current_num_threads() { // Enough bands to keep every core busy: one band per task, its tiles in turn. - out.px.par_chunks_mut(band_len).enumerate().for_each(|(i, band)| { + out.px.par_chunks_mut(band_len).enumerate().try_for_each(|(i, band)| { let y0 = rect.y0 + i as i32 * tile; for t in band_tiles(y0) { - put(band, y0, &run(t)); + let part = run(t)?; + put(band, y0, &part); } - }); + Ok::<(), A::Error>(()) + })?; } else { // Few, wide bands: the tiles of each band in parallel, and the bands too, so a band's // slowest tile doesn't leave the other cores idle until the next band starts. Each // tile is written as soon as it is done, so only the tiles in flight are held. - out.px.par_chunks_mut(band_len).enumerate().for_each(|(i, band)| { + out.px.par_chunks_mut(band_len).enumerate().try_for_each(|(i, band)| { let y0 = rect.y0 + i as i32 * tile; let band = std::sync::Mutex::new(band); - band_tiles(y0).into_par_iter().for_each(|t| { - let part = run(t); + band_tiles(y0).into_par_iter().try_for_each(|t| { + let part = run(t)?; let mut band = band.lock().unwrap_or_else(std::sync::PoisonError::into_inner); put(&mut band, y0, &part); - }); - }); + Ok::<(), A::Error>(()) + }) + })?; } } #[cfg(target_arch = "wasm32")] for (i, band) in out.px.chunks_mut(band_len).enumerate() { let y0 = rect.y0 + i as i32 * tile; for t in band_tiles(y0) { - put(band, y0, &run(t)); + let part = run(t)?; + put(band, y0, &part); } } - out + Ok(out) } /// Runs `f` with this thread's document blend flags set ([`psblend::LAB_MIX`], [`psblend::HDR`]), @@ -160,11 +174,149 @@ pub fn cmyk_space(doc: &Document) -> Option { + /// The compositor could not reserve or size one of its RGBA buffers. Earlier complete bands + /// may already have been delivered to the sink. + Allocation(photocraft_raster::AllocationError), + /// The caller's sink rejected a completed band. + Sink(E), +} + +#[cfg(test)] +mod fallible_bands_tests { + use super::*; + use photocraft_color::{Color, ColorMode, SampleType}; + use photocraft_doc::{Document, Fill, Knockout, Layer, LayerContent}; + use photocraft_geom::Size; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct FailBufferAt { fail_at: usize, attempts: AtomicUsize } + + impl FailBufferAt { + fn attempt(&self) -> Result<(), usize> { + let n = self.attempts.fetch_add(1, Ordering::Relaxed) + 1; + if n == self.fail_at { Err(n) } else { Ok(()) } + } + } + + impl BufferAlloc for FailBufferAt { + type Error = usize; + + fn filled(&self, rect: Rect, color: [f32; 4]) -> Result { + self.attempt()?; + Buffer::try_filled(rect, color).map_err(|_| usize::MAX) + } + + fn clone(&self, buffer: &Buffer) -> Result { + self.attempt()?; + buffer.try_clone().map_err(|_| usize::MAX) + } + } + + fn nested_document() -> Document { + let mut doc = Document::new("fallible bands", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); + let mut fill = Layer::new("fill", LayerContent::Fill(Fill::Solid(Color::BLACK))); + fill.advanced.knockout = Knockout::Shallow; + doc.layers.push(Layer::group("nested", vec![fill])); + doc + } + + #[test] + fn fail_nth_buffer_constructor_propagates_through_nested_rendering() { + let doc = nested_document(); + let rect = doc.bounds(); + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + let ctx = Ctx::for_doc(&doc, &patterns); + let count = { + let mut backdrop = Buffer::filled(rect, [0.0; 4]); + let alloc = FailBufferAt { fail_at: usize::MAX, attempts: AtomicUsize::new(0) }; + composite_stack_at_with(&doc.layers, &mut backdrop, &ctx, advanced::Scope::ROOT, &alloc).unwrap(); + alloc.attempts.load(Ordering::Relaxed) + }; + assert!(count >= 4, "nested shallow knockout exercises buffers and clones"); + for fail_at in 1..=count { + let mut backdrop = Buffer::filled(rect, [0.0; 4]); + let alloc = FailBufferAt { fail_at, attempts: AtomicUsize::new(0) }; + assert!(composite_stack_at_with(&doc.layers, &mut backdrop, &ctx, advanced::Scope::ROOT, &alloc).is_err()); + assert_eq!(alloc.attempts.load(Ordering::Relaxed), fail_at); + } + let regular = render_tiled(&doc, rect, 8); + let mut composited = Buffer::filled(rect, [0.0; 4]); + composite_stack_at_with(&doc.layers, &mut composited, &ctx, advanced::Scope::ROOT, &InfallibleBufferAlloc).unwrap(); + assert_eq!(composited, regular); + let alloc = FallibleBufferAlloc; + assert_eq!(render_tiled_with_alloc(&doc, rect, 8, &ctx, &alloc).unwrap(), regular); + } + + #[test] + fn tiled_renderer_returns_buffer_allocation_error_before_delivering_a_band() { + let doc = Document::new("fallible tile", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + let ctx = Ctx::for_doc(&doc, &patterns); + let alloc = FailBufferAt { fail_at: 1, attempts: AtomicUsize::new(0) }; + assert!(render_tiled_with_alloc(&doc, doc.bounds(), RENDER_TILE, &ctx, &alloc).is_err()); + assert_eq!(alloc.attempts.load(Ordering::Relaxed), 1); + } + + #[test] + fn fallible_bands_preserves_sink_errors_as_a_separate_variant() { + let doc = nested_document(); + let result = try_render_bands(&doc, doc.bounds(), 4, |_| Err::<(), _>("sink stopped")); + assert_eq!(result, Err(RenderBandsError::Sink("sink stopped"))); + } + + #[test] + fn legacy_and_fallible_band_apis_deliver_the_same_pixels() { + let doc = nested_document(); + let mut legacy = Vec::new(); + render_bands(&doc, doc.bounds(), 8, |band| { legacy.push(band); Ok::<(), ()>(()) }).unwrap(); + let mut fallible = Vec::new(); + try_render_bands(&doc, doc.bounds(), 8, |band| { fallible.push(band); Ok::<(), ()>(()) }).unwrap(); + assert_eq!(legacy, fallible); + } +} + +enum RenderBandsCoreError { + Allocation(A), + Sink(E), +} + /// Composite `rect` in horizontal bands, top to bottom, handing each band to `sink` (tiles inside /// a band render in parallel). Peak memory is one band instead of the whole composite, so huge /// documents can be exported or displayed without a full-size float copy. `band_rows` of 0 picks /// about [`BAND_PIXELS`] per band; bands are whole multiples of [`RENDER_TILE`] rows. pub fn render_bands(doc: &Document, rect: Rect, band_rows: i32, mut sink: impl FnMut(Buffer) -> Result<(), E>) -> Result<(), E> { + match render_bands_with_alloc(doc, rect, band_rows, &InfallibleBufferAlloc, &mut sink) { + Ok(()) => Ok(()), + Err(RenderBandsCoreError::Sink(error)) => Err(error), + Err(RenderBandsCoreError::Allocation(never)) => match never {}, + } +} + +/// Fallible `render_bands` variant that reports compositor-owned RGBA buffer allocation failures. +pub fn try_render_bands( + doc: &Document, + rect: Rect, + band_rows: i32, + mut sink: impl FnMut(Buffer) -> Result<(), E>, +) -> Result<(), RenderBandsError> { + match render_bands_with_alloc(doc, rect, band_rows, &FallibleBufferAlloc, &mut sink) { + Ok(()) => Ok(()), + Err(RenderBandsCoreError::Allocation(error)) => Err(RenderBandsError::Allocation(error)), + Err(RenderBandsCoreError::Sink(error)) => Err(RenderBandsError::Sink(error)), + } +} + +fn render_bands_with_alloc( + doc: &Document, + rect: Rect, + band_rows: i32, + alloc: &A, + sink: &mut impl FnMut(Buffer) -> Result<(), E>, +) -> Result<(), RenderBandsCoreError> { if rect.is_empty() { return Ok(()); } @@ -175,7 +327,9 @@ pub fn render_bands(doc: &Document, rect: Rect, band_rows: i32, mut sink: imp let mut y = rect.y0; while y < rect.y1 { let y1 = y.saturating_add(rows).min(rect.y1); - sink(render_tiled_with(doc, Rect::new(rect.x0, y, rect.x1, y1), RENDER_TILE, &cx))?; + let band = render_tiled_with_alloc(doc, Rect::new(rect.x0, y, rect.x1, y1), RENDER_TILE, &cx, alloc) + .map_err(RenderBandsCoreError::Allocation)?; + sink(band).map_err(RenderBandsCoreError::Sink)?; y = y1; } Ok(()) diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 04c65b49d6..04ddf2a544 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -1080,6 +1080,18 @@ fn has_selection_and_pixels(s: &Session) -> std::result::Result<(), String> { pub const MAX_TIP: u32 = 2500; fn define_from_selection(s: &mut Session, p: &Value) -> Result { + define_from_selection_with_renderer(s, p, |doc, area, sink| photocraft_compose::try_render_bands(doc, area, 0, sink)) +} + +fn define_from_selection_with_renderer( + s: &mut Session, + p: &Value, + render: impl FnOnce( + &photocraft_doc::Document, + photocraft_geom::Rect, + &mut dyn FnMut(photocraft_compose::Buffer) -> Result<()>, + ) -> std::result::Result<(), photocraft_compose::RenderBandsError>, +) -> Result { let cmd = "brush.defineFromSelection"; let name = name_param(p, cmd)?; let d = s.active().ok_or(EngineError::NoDocument)?; @@ -1116,10 +1128,7 @@ fn define_from_selection(s: &mut Session, p: &Value) -> Result { // A selection mask, when present, is a second buffer of the same size; it must fail gracefully too // (review of #5469), so read it through the fallible allocator. let sv = crate::allocation::read_region(sel, area, "defining a brush from the selection")?; - // Keep a fault-injection checkpoint before entering compositor-owned scratch storage. - // The compositor's scratch allocation itself is not fallible through this call. - crate::allocation::checkpoint("defining a brush from the selection")?; - photocraft_compose::render_bands(&d.doc, area, 0, |band| -> Result<()> { + let rendered = render(&d.doc, area, &mut |band| -> Result<()> { for (row, pixels) in band.px.chunks_exact(w).enumerate() { let y = (band.rect.y0 - area.y0) as usize + row; for (x, c) in pixels.iter().enumerate() { @@ -1136,7 +1145,14 @@ fn define_from_selection(s: &mut Session, p: &Value) -> Result { } } Ok(()) - })?; + }); + match rendered { + Ok(()) => {} + Err(photocraft_compose::RenderBandsError::Sink(error)) => return Err(error), + Err(photocraft_compose::RenderBandsError::Allocation(error)) => { + return Err(crate::allocation::error("defining a brush from the selection", &error.to_string())); + } + } let (brush, tw, th) = sampled_brush(cmd, &v, w, h)?; upsert(s, BrushPreset { name: name.clone(), brush: brush.clone(), builtin: false, group: String::new(), folder: Vec::new(), captures: Default::default() }); s.tools.brush = brush; diff --git a/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs b/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs index 95afc7d5f0..f9bfd4dfe4 100644 --- a/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs +++ b/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs @@ -226,7 +226,7 @@ fn composite_storage_is_counted_with_density_and_mask_before_any_allocation() { } #[test] -fn compositor_allocation_boundary_failure_preserves_source_and_preset_state() { +fn selection_buffer_failure_preserves_source_and_preset_state() { for command in COMMANDS { let mut s = source(8); s.execute("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 150})).unwrap(); @@ -235,9 +235,9 @@ fn compositor_allocation_boundary_failure_preserves_source_and_preset_state() { let brush = s.tools.brush.clone(); let presets = s.tools.presets.clone(); let current = s.tools.current_preset.clone(); - crate::allocation::fail_after_for_test(2); - let result = s.execute(command, json!({"name": "Compositor allocation failure"})); - let _ = crate::allocation::capacity::(0, "reset compositor failpoint"); + crate::allocation::fail_after_for_test(1); + let result = s.execute(command, json!({"name": "Selection buffer failure"})); + let _ = crate::allocation::capacity::(0, "reset selection failpoint"); let err = result.unwrap_err(); assert!(err.to_string().contains("not enough memory"), "{err}"); assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index 428fc21137..b978c85efa 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -687,6 +687,24 @@ fn define_brush_from_selection_survives_failure_of_the_second_allocation() { assert!(same_pixels(&pixels_before, &surface(&s), s.active().unwrap().doc.bounds()), "the document pixels are unchanged"); } +#[test] +fn define_brush_from_selection_propagates_compositor_allocation_error_transactionally() { + let mut s = session(40, 40); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 20, "height": 20})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let brush_before = s.tools.brush.clone(); + let presets_before = s.tools.presets.clone(); + let history_before = s.active().unwrap().history.past_len(); + let result = define_from_selection_with_renderer(&mut s, &json!({"name": "Blob"}), |_, _, _| { + Err(photocraft_compose::RenderBandsError::Allocation(photocraft_raster::AllocationError::NotEnoughMemory { bytes: 64 })) + }); + assert!(result.is_err_and(|e| e.to_string().contains("defining a brush from the selection"))); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.tools.brush, brush_before); + assert_eq!(s.tools.presets, presets_before); + assert_eq!(s.active().unwrap().history.past_len(), history_before); +} + #[test] fn works_on_cmyk_and_16_bit() { for (mode, depth) in [("cmyk", 8), ("rgb", 16), ("grayscale", 32)] { diff --git a/crates/raster/src/scratch.rs b/crates/raster/src/scratch.rs index cb0f898306..05971d3f8a 100644 --- a/crates/raster/src/scratch.rs +++ b/crates/raster/src/scratch.rs @@ -255,11 +255,21 @@ fn take_with(len: usize, fill: T, slack: usize) -> Vec { } } +/// Fallible [`take`]: on a pool miss the heap allocation is `try_reserve_exact`, so `None` means +/// the allocation failed rather than aborting. The pool lookup keeps `take`'s existing 2x slack. +pub fn try_take(len: usize, fill: T) -> Option> { + try_take_with_slack(len, fill, 2) +} + /// Fallible [`take_exact`]: on a pool miss the heap allocation is `try_reserve_exact`, so -/// `None` means the allocation failed rather than aborting. +/// `None` means the allocation failed rather than aborting. Only exact-capacity buffers are reused. pub fn try_take_exact(len: usize, fill: T) -> Option> { + try_take_with_slack(len, fill, 1) +} + +fn try_take_with_slack(len: usize, fill: T, slack: usize) -> Option> { USES.fetch_add(1, Ordering::Relaxed); - let mut v = match pop::(len, 1) { + let mut v = match pop::(len, slack) { Some(v) => v, None => { let mut v = Vec::new(); diff --git a/crates/raster/tests/scratch.rs b/crates/raster/tests/scratch.rs index a0f532f174..fbd2982320 100644 --- a/crates/raster/tests/scratch.rs +++ b/crates/raster/tests/scratch.rs @@ -100,6 +100,38 @@ fn try_take_exact_reuses_and_allocates() { release(); } +#[test] +/// Verifies fallible takes preserve the slack policy of their infallible counterparts. +fn try_take_preserves_slack_and_exact_variant_stays_exact() { + let _g = serial(); + release(); + let pooled = Vec::::with_capacity(150_000); + let pooled_ptr = pooled.as_ptr(); + give(pooled); + let slack = try_take(100_000, 1.0f32); + assert_eq!(slack.as_ref().map(|v| v.as_ptr()), Some(pooled_ptr)); + assert!(slack.is_some_and(|v| v.len() == 100_000 && v.iter().all(|&sample| sample == 1.0))); + release(); + + let pooled = Vec::::with_capacity(150_000); + let pooled_ptr = pooled.as_ptr(); + give(pooled); + let exact = try_take_exact(100_000, 2.0f32); + assert!(exact.is_some()); + assert_ne!(exact.as_ref().map(|v| v.as_ptr()), Some(pooled_ptr)); + assert!(exact.is_some_and(|v| v.iter().all(|&sample| sample == 2.0))); + release(); +} + +#[test] +/// A request beyond Vec's representable capacity returns an allocation failure, not a panic. +fn fallible_take_reports_capacity_overflow() { + let _g = serial(); + release(); + assert!(try_take::<[f32; 4]>(usize::MAX, [0.0; 4]).is_none()); + release(); +} + #[test] /// Verifies buffers below the pooling threshold are not retained. fn small_buffers_are_not_retained() { From 4edad0d7be421e418a44be8d8bce33ccbf19882e Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 20:11:54 -0800 Subject: [PATCH 31/46] Fix allocator policy imports and prune unused wrappers --- crates/compose/src/advanced.rs | 89 +------------------------ crates/compose/src/composite.rs | 27 +------- crates/compose/src/content.rs | 1 + crates/compose/src/effects.rs | 2 +- crates/compose/src/effects/composite.rs | 3 +- crates/compose/src/multichannel.rs | 8 --- 6 files changed, 7 insertions(+), 123 deletions(-) diff --git a/crates/compose/src/advanced.rs b/crates/compose/src/advanced.rs index 13b55522a2..672d793e52 100644 --- a/crates/compose/src/advanced.rs +++ b/crates/compose/src/advanced.rs @@ -32,8 +32,9 @@ use std::borrow::Cow; use photocraft_doc::{Knockout, Layer, LayerContent}; use photocraft_geom::Rect; +use crate::content::render_content_with; use crate::extents::recycle_mask; -use crate::{Buffer, BufferAlloc, Ctx, InfallibleBufferAlloc, composite_atop, composite_layer, effects, mask_vals, render_content, render_content_with}; +use crate::{Buffer, BufferAlloc, Ctx, effects, mask_vals}; /// Where a layer stack sits, for knockouts: at the document's top level, and/or inside an /// isolated (non-pass-through) group. Photoshop stops a deep knockout at the bottom of the @@ -99,15 +100,6 @@ pub fn is_background(l: &Layer) -> bool { l.has_background_traits() } -/// What a deep knockout reveals over `rect`: the document's initial backdrop with its Background -/// layer (transparency when it has none, or when it is hidden). -pub(crate) fn deep_target(cx: &Ctx, rect: Rect) -> Buffer { - match deep_target_with(cx, rect, &InfallibleBufferAlloc) { - Ok(buffer) => buffer, - Err(never) => match never {}, - } -} - fn deep_target_with(cx: &Ctx, rect: Rect, alloc: &A) -> Result { let Some(doc) = cx.doc else { return alloc.filled(rect, [0.0; 4]) }; let mut b = crate::multichannel::backdrop_with(doc, rect, alloc)?; @@ -117,18 +109,6 @@ fn deep_target_with(cx: &Ctx, rect: Rect, alloc: &A) -> Result(layer: &Layer, floor: Option<&'b Buffer>, rect: Rect, cx: &Ctx, scope: Scope) -> Option> { - let deep = || if scope.isolated { Buffer::transparent(rect) } else { deep_target(cx, rect) }; - match layer.advanced.knockout { - Knockout::None => None, - Knockout::Shallow => Some(floor.map_or_else(|| Cow::Owned(deep()), Cow::Borrowed)), - Knockout::Deep => Some(Cow::Owned(deep())), - } -} - pub(crate) fn knockout_target_with<'b, A: BufferAlloc>( layer: &Layer, floor: Option<&'b Buffer>, @@ -154,20 +134,6 @@ pub(crate) fn needs_floor(layers: &[Layer]) -> bool { layers.iter().any(|l| l.visible && !l.clipped && l.advanced.knockout == Knockout::Shallow) } -/// The shape a layer knocks out over `rect` (row-major): its content's alpha with its masks; -/// with Transparency Shapes Layer off (and for adjustment layers) just the masks. -fn knockout_shape(layer: &Layer, rect: Rect, cx: &Ctx) -> Vec { - let n = rect.width() as usize * rect.height() as usize; - let masks = || mask_vals(layer, rect, cx).unwrap_or_else(|| vec![1.0; n]); - if !layer.advanced.transparency_shapes { - return masks(); - } - match render_content(layer, rect, cx) { - Some(b) => b.px.iter().map(|p| p[3]).collect(), - None => masks(), - } -} - fn knockout_shape_with(layer: &Layer, rect: Rect, cx: &Ctx, alloc: &A) -> Result, A::Error> { let n = rect.width() as usize * rect.height() as usize; let masks = || mask_vals(layer, rect, cx).unwrap_or_else(|| vec![1.0; n]); @@ -186,13 +152,6 @@ fn knockout_shape_with(layer: &Layer, rect: Rect, cx: &Ctx, allo /// /// `clip_alpha` keeps alpha from growing (clipped layers stay inside their base's alpha; a /// knockout to transparency may still lower it). -pub(crate) fn knockout(layer: &Layer, backdrop: &mut Buffer, target: &Buffer, clip_alpha: bool, cx: &Ctx, draw: impl FnOnce(&mut Buffer)) { - match knockout_with(layer, backdrop, target, clip_alpha, cx, &InfallibleBufferAlloc, |buffer| { draw(buffer); Ok(()) }) { - Ok(()) => {} - Err(never) => match never {}, - } -} - pub(crate) fn knockout_with( layer: &Layer, backdrop: &mut Buffer, @@ -246,20 +205,6 @@ pub(crate) fn knockout_with( Ok(()) } -/// Composite a clipping group's clipped layers atop `base` (the base's isolated content, Blend -/// Clipped Layers as Group on). The grouped clipping layers composite in isolation, like an -/// isolated group, so a clipped layer's knockout (shallow or deep) stops at the bottom of the -/// clipping group: the base's content. -pub(crate) fn composite_clipped(clipped: &[Layer], base: &mut Buffer, cx: &Ctx) { - let floor = clipped.iter().any(|c| c.visible && c.advanced.knockout != Knockout::None).then(|| base.clone()); - for c in clipped.iter().filter(|c| c.visible) { - match &floor { - Some(f) if c.advanced.knockout != Knockout::None => knockout(c, base, f, true, cx, |b| composite_atop(c, b, cx)), - _ => composite_atop(c, base, cx), - } - } -} - pub(crate) fn composite_clipped_with(clipped: &[Layer], base: &mut Buffer, cx: &Ctx, alloc: &A) -> Result<(), A::Error> { let floor = if clipped.iter().any(|c| c.visible && c.advanced.knockout != Knockout::None) { Some(alloc.clone(base)?) } else { None }; for c in clipped.iter().filter(|c| c.visible) { @@ -281,36 +226,6 @@ pub(crate) fn clips_individually(layer: &Layer, clipped: &[Layer]) -> bool { /// clipped layer composited in its own mode onto the result, inside the base's shape (its alpha /// with masks, times its opacity). A clipped layer's shallow knockout stops at the backdrop /// beneath the base (the bottom of the clipping group). -pub(crate) fn composite_clipped_individually(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, ko: Option<&Buffer>, scope: Scope) { - let rect = backdrop.rect; - let n = backdrop.px.len(); - let floor = clipped.iter().any(|c| c.visible && c.advanced.knockout == Knockout::Shallow).then(|| backdrop.clone()); - composite_layer(layer, &[], backdrop, cx, ko, scope); - let op = layer.opacity.clamp(0.0, 1.0); - let clip: Vec = match render_content(layer, rect, cx) { - Some(b) => b.px.iter().map(|p| p[3] * op).collect(), - None => { - let mv = mask_vals(layer, rect, cx); - let clip = mv.as_ref().map_or_else(|| vec![op; n], |m| m.iter().map(|m| m * op).collect()); - recycle_mask(mv); - clip - } - }; - if clip.len() != n { - return; - } - for c in clipped.iter().filter(|c| c.visible) { - let before = backdrop.clone(); - let t = knockout_target(c, floor.as_ref(), rect, cx, Scope { root: false, ..scope }); - composite_layer(c, &[], backdrop, cx, t.as_deref(), scope); - for ((p, b), k) in backdrop.px.iter_mut().zip(&before.px).zip(&clip) { - if *k < 1.0 { - *p = mix(*b, *p, k.max(0.0)); - } - } - } -} - pub(crate) fn composite_clipped_individually_with( layer: &Layer, clipped: &[Layer], diff --git a/crates/compose/src/composite.rs b/crates/compose/src/composite.rs index 2d6008e01b..7e42a6455a 100644 --- a/crates/compose/src/composite.rs +++ b/crates/compose/src/composite.rs @@ -7,11 +7,6 @@ use super::{ psblend, shape_split, }; -/// Composite an isolated group's sibling list (bottom→top) onto `backdrop` (its own buffer). -pub(crate) fn composite_stack(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx) { - composite_stack_at(layers, backdrop, cx, advanced::Scope::ISOLATED); -} - /// Composite a sibling list (bottom→top) onto `backdrop`; `scope` says where the stack sits (see /// [`advanced::Scope`]: it decides what knockouts reveal). pub(crate) fn composite_stack_at(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { @@ -225,13 +220,6 @@ thread_local! { /// is mixed back towards `before` (the backdrop without it) where the ranges hide the layer. /// Mixing premultiplied colour by `k` equals compositing the layer at `k` × its alpha, since /// every blend mode's source-over result is linear in the source alpha. -fn apply_blend_if(layer: &Layer, before: &Buffer, out: &mut Buffer, cx: &Ctx) { - match apply_blend_if_with(layer, before, out, cx, &InfallibleBufferAlloc) { - Ok(()) => {} - Err(never) => match never {}, - } -} - fn apply_blend_if_with(layer: &Layer, before: &Buffer, out: &mut Buffer, cx: &Ctx, alloc: &A) -> Result<(), A::Error> { // "This Layer" is the layer's own colour. An adjustment layer (no content of its own) is // judged by its result at full strength, before Opacity and its mask mix it in, as Photoshop @@ -275,13 +263,6 @@ fn apply_blend_if_with(layer: &Layer, before: &Buffer, out: &mut /// Composite `layer` (plus its clipping group) onto `backdrop`, honouring its channel restrictions /// and Blend If, and knocking out to `ko` when it has a knockout (see [`advanced`]). -pub(crate) fn composite_layer(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, ko: Option<&Buffer>, scope: advanced::Scope) { - match composite_layer_with(layer, clipped, backdrop, cx, ko, scope, &InfallibleBufferAlloc) { - Ok(()) => {} - Err(never) => match never {}, - } -} - pub(crate) fn composite_layer_with( layer: &Layer, clipped: &[Layer], @@ -393,6 +374,7 @@ pub(crate) fn composite_pixel_layer(layer: &Layer, surf: &Surface, backdrop: &mu recycle_mask(mv); } +#[cfg(test)] pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { match composite_layer_plain_with(layer, clipped, backdrop, cx, scope, &InfallibleBufferAlloc) { Ok(()) => {} @@ -669,13 +651,6 @@ pub(crate) fn texture_ctx<'a>(layer: &Layer, region: Rect, cx: &Ctx<'a>) -> effe /// Composite `layer` onto `base` restricted to the base's alpha (clipping mask semantics), /// honouring its channel restrictions and Blend If. -pub(crate) fn composite_atop(layer: &Layer, base: &mut Buffer, cx: &Ctx) { - match composite_atop_with(layer, base, cx, &InfallibleBufferAlloc) { - Ok(()) => {} - Err(never) => match never {}, - } -} - pub(crate) fn composite_atop_with(layer: &Layer, base: &mut Buffer, cx: &Ctx, alloc: &A) -> Result<(), A::Error> { let w = channel_weights(layer, cx.mode); let blend_if = blend_if_active(layer, cx.mode); diff --git a/crates/compose/src/content.rs b/crates/compose/src/content.rs index f65f93a475..972fe4f943 100644 --- a/crates/compose/src/content.rs +++ b/crates/compose/src/content.rs @@ -138,6 +138,7 @@ fn render_fill_with( } } +#[cfg(test)] fn surface_to_scratch(s: &Surface, rect: Rect) -> Buffer { let mut buf = Buffer::transparent(rect); s.read_rgba_into(rect, &mut buf.px); diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index 077fae98b2..08b946abb7 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -44,7 +44,7 @@ use bevel::{bevel_maps, satin_map}; #[cfg(test)] use blur::{blur, box_line, dilate, tent, tent_direct}; pub use blur::{size_one_kernel, tent_kernel}; -pub(crate) use composite::{VectorStroke, build_maps_prepared, composite_with_effects_prepared, map_count}; +pub(crate) use composite::{VectorStroke, build_maps_prepared, composite_with_effects_prepared, composite_with_effects_prepared_with, map_count}; pub use composite::{build_maps, composite_with_effects, outline_share, premerges_layer, shadow_see_through, stroke_widths}; pub use distance::{FieldKind, STROKE_CHAMFER_MAX, bevel_distance_fields, distance_field, stroke_outside_exact}; #[cfg(test)] diff --git a/crates/compose/src/effects/composite.rs b/crates/compose/src/effects/composite.rs index b570fe32fd..ca57389b25 100644 --- a/crates/compose/src/effects/composite.rs +++ b/crates/compose/src/effects/composite.rs @@ -3,8 +3,9 @@ use super::distance::{INSIDE_EPS, Metric, dist_inside_by, dist_outside_by, local use super::paint::{dissolves_in, glow_map, paint_color, paint_fx, paint_glow, paint_pattern, rgb, shadow_map}; use super::{ Bevel, BevelStyle, BlendMode, Buffer, Effect, FxMaps, FxPaint, GlobalLight, Layer, MAX_REACH, Map, PREPARED_PATTERN_BYTES, Pattern, Placement, - BufferAlloc, InfallibleBufferAlloc, PreparedPatterns, Rect, StrokePosition, psblend, + PreparedPatterns, Rect, StrokePosition, psblend, }; +use crate::{BufferAlloc, InfallibleBufferAlloc}; /// Build every effect map for `layer` from its alpha `shape` over `rect`. pub fn build_maps(layer: &Layer, shape: Vec, rect: Rect, light: &GlobalLight, tex: &TextureCtx) -> FxMaps { diff --git a/crates/compose/src/multichannel.rs b/crates/compose/src/multichannel.rs index 1b58b3aa2c..d06e990c55 100644 --- a/crates/compose/src/multichannel.rs +++ b/crates/compose/src/multichannel.rs @@ -191,14 +191,6 @@ pub fn inks(doc: &Document, rect: Rect) -> Buffer { buf } -/// The starting backdrop of a document render: the inks for Multichannel, else transparent. -pub(crate) fn backdrop(doc: &Document, rect: Rect) -> Buffer { - match backdrop_with(doc, rect, &crate::InfallibleBufferAlloc) { - Ok(buffer) => buffer, - Err(never) => match never {}, - } -} - pub(crate) fn backdrop_with(doc: &Document, rect: Rect, alloc: &A) -> Result { if doc.mode == ColorMode::Multichannel { let mut buf = alloc.filled(rect, [1.0; 4])?; From 1fdc8a0fc0f99c4074bb0426d11f2071085d3288 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 20:21:13 -0800 Subject: [PATCH 32/46] Propagate compositor allocation errors through effect shapes --- crates/compose/src/composite.rs | 6 +- crates/compose/src/content.rs | 15 +---- crates/compose/src/ctx.rs | 37 +++++++++--- crates/compose/src/extents.rs | 22 ++++++-- crates/compose/src/fx_cache.rs | 63 ++++++++++++++++----- crates/compose/src/gradient_fill.rs | 7 ++- crates/compose/src/pattern.rs | 6 +- crates/compose/src/render.rs | 88 ++++++++++++++++++++++++++--- 8 files changed, 186 insertions(+), 58 deletions(-) diff --git a/crates/compose/src/composite.rs b/crates/compose/src/composite.rs index 7e42a6455a..73e54d8911 100644 --- a/crates/compose/src/composite.rs +++ b/crates/compose/src/composite.rs @@ -1,7 +1,7 @@ use super::content::{channel_weights, empty_in, render_content_with, restore_channels, surface_to_buffer, surface_to_buffer_with}; use super::ctx::Ctx; use super::extents::{effects_frame, mask_k, mask_vals, recycle_mask, shapeless_stroke_bounds}; -use super::fx_cache::effect_maps; +use super::fx_cache::effect_maps_with; use super::{ BlendMode, Buffer, BufferAlloc, Fill, InfallibleBufferAlloc, Layer, LayerContent, Rect, Surface, advanced, blend, effects, psblend, shape_split, @@ -582,7 +582,7 @@ fn composite_layer_effects_with(layer: &Layer, clipped: &[Layer] }; advanced::composite_clipped_with(clipped, &mut content, cx, alloc)?; let vstroke = parts.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); - let maps = effect_maps(layer, rect, cx); + let maps = effect_maps_with(layer, rect, cx, alloc)?; effects::composite_with_effects_prepared_with(layer, &content, backdrop, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke, alloc)?; if let Some((_, mask)) = parts { recycle_mask(mask); @@ -713,7 +713,7 @@ fn composite_atop_any_with(layer: &Layer, base: &mut Buffer, cx: let vstroke = parts.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); let mut opaque = alloc.clone(base)?; for p in &mut opaque.px { p[3] = 1.0; } - let maps = effect_maps(layer, rect, cx); + let maps = effect_maps_with(layer, rect, cx, alloc)?; effects::composite_with_effects_prepared_with(layer, &content, &mut opaque, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke, alloc)?; if let Some((_, mask)) = parts { recycle_mask(mask); diff --git a/crates/compose/src/content.rs b/crates/compose/src/content.rs index 972fe4f943..a77551b182 100644 --- a/crates/compose/src/content.rs +++ b/crates/compose/src/content.rs @@ -192,18 +192,9 @@ pub fn render_fill_content(layer: &Layer, f: &Fill, canvas: Rect, patterns: &[Pa /// `quantum`: the document depth's levels, which a dithered gradient is rounded to /// ([`gradient_fill::render_quantized`]); `None` keeps it in float. pub(crate) fn render_fill(f: &Fill, rect: Rect, canvas: Rect, patterns: &pattern::PreparedPatterns<'_>, quantum: Option) -> Buffer { - match f { - Fill::Solid(c) => { - let rgb = c.to_rgb(); - Buffer::filled(rect, [rgb[0], rgb[1], rgb[2], c.alpha]) - } - // Gradient geometry relative to the layer's frame, independent of the render rect. - Fill::Gradient { .. } => Buffer { rect, px: gradient_fill::render_quantized(f, rect, canvas, quantum) }, - // Laid out from the layer's frame when linked; transparent if the pattern is missing. - Fill::Pattern { name, scale, id, angle, link, phase } => match patterns.get(id, name) { - Some(tile) => Buffer { rect, px: pattern::render(&tile, &pattern::Placement::new(canvas, *link, *phase, *scale, *angle), rect) }, - None => Buffer::transparent(rect), - }, + match render_fill_with(f, rect, canvas, patterns, quantum, &InfallibleBufferAlloc) { + Ok(buffer) => buffer, + Err(never) => match never {}, } } diff --git a/crates/compose/src/ctx.rs b/crates/compose/src/ctx.rs index f54c79865b..db3b4fcd93 100644 --- a/crates/compose/src/ctx.rs +++ b/crates/compose/src/ctx.rs @@ -1,6 +1,6 @@ use super::content::empty_in; -use super::fx_cache::{effect_maps, fx_over_budget, layer_identity}; -use super::{Buffer, Document, Layer, LayerContent, Rect, adjust, advanced, effects, pattern}; +use super::fx_cache::{effect_maps_with, fx_over_budget, layer_identity}; +use super::{Buffer, BufferAlloc, Document, InfallibleBufferAlloc, Layer, LayerContent, Rect, adjust, advanced, effects, pattern}; type VectorMaskSlot = std::sync::Arc>; @@ -183,22 +183,41 @@ pub(crate) const PREPARE_DEPTH: u32 = 64; /// `rect` before tiles render in parallel, layers concurrently on native targets, each build /// inside `setting` (the tiles' thread-local colour setting). Tiles then only read finished maps: /// none builds one while others need it (#276), and none duplicates another's build. Builds never -/// wait on each other (`cached_effect_maps`), so building them in parallel can't deadlock. +/// wait on each other (`cached_effect_maps_with`), so building them in parallel can't deadlock. pub(crate) fn prepare_effects(layers: &[Layer], rect: Rect, cx: &Ctx, setting: impl Fn(&mut dyn FnMut()) + Sync) { + let _ = prepare_effects_with(layers, rect, cx, &InfallibleBufferAlloc, |build| { + let mut infallible = || match build() { + Ok(()) => (), + Err(never) => match never {}, + }; + setting(&mut infallible); + Ok(()) + }); +} + +/// Fallible counterpart of [`prepare_effects`], used by the compositor before it starts tiles. +pub(crate) fn prepare_effects_with( + layers: &[Layer], + rect: Rect, + cx: &Ctx, + alloc: &A, + setting: F, +) -> Result<(), A::Error> +where + A: BufferAlloc + Sync, + F: Fn(&mut dyn FnMut() -> Result<(), A::Error>) -> Result<(), A::Error> + Sync, +{ let mut todo = Vec::new(); effect_layers(layers, rect, 0, &mut todo); let build = |l: &std::borrow::Cow| { - setting(&mut || { - let _ = effect_maps(l, rect, cx); - }); + setting(&mut || effect_maps_with(l, rect, cx, alloc).map(|_| ())) }; #[cfg(not(target_arch = "wasm32"))] if todo.len() > 1 { use rayon::prelude::*; - todo.par_iter().for_each(build); - return; + return todo.par_iter().try_for_each(build); } - todo.iter().for_each(build); + todo.iter().try_for_each(build) } /// The visible layers of `layers` (groups included) with effects that can reach `rect`. diff --git a/crates/compose/src/extents.rs b/crates/compose/src/extents.rs index d111ab8b57..c9cf0d7fad 100644 --- a/crates/compose/src/extents.rs +++ b/crates/compose/src/extents.rs @@ -1,6 +1,6 @@ -use super::content::{render_content, surface_to_buffer}; +use super::content::{render_content_with, surface_to_buffer_with}; use super::ctx::Ctx; -use super::{BlendMode, Document, Layer, LayerContent, Rect, adjustment_quantum, advanced, bounds, effects, masks, shape_split}; +use super::{BlendMode, BufferAlloc, Document, InfallibleBufferAlloc, Layer, LayerContent, Rect, adjustment_quantum, advanced, bounds, effects, masks, shape_split}; /// Bounds of a layer's own pixels (union over group children; the canvas /// for fill layers; an artboard's board). @@ -114,17 +114,27 @@ pub fn effect_outline(layer: &Layer) -> Option<&photocraft_doc::vector::Path> { /// fill is opaque (it can differ from ours by a fraction of a pixel: psd-tools shape-fx2), the /// path where the fill fades out (psd-tools stroke-effects). pub(crate) fn effect_shape(layer: &Layer, rect: Rect, cx: &Ctx) -> Vec { + match effect_shape_with(layer, rect, cx, &InfallibleBufferAlloc) { + Ok(shape) => shape, + Err(never) => match never {}, + } +} + +pub(crate) fn effect_shape_with(layer: &Layer, rect: Rect, cx: &Ctx, alloc: &A) -> Result, A::Error> { let n = rect.width() as usize * rect.height() as usize; // Transparency Shapes Layer off: the effects take the whole layer as their shape (its masks // still apply). if !layer.advanced.transparency_shapes { - return mask_vals(layer, rect, cx).unwrap_or_else(|| vec![1.0; n]); + return Ok(mask_vals(layer, rect, cx).unwrap_or_else(|| vec![1.0; n])); } let Some(path) = effect_outline(layer).filter(|_| n > 0) else { - return render_content(layer, rect, cx).map(|b| b.px.iter().map(|p| p[3]).collect()).unwrap_or_else(|| vec![0.0; n]); + return Ok(render_content_with(layer, rect, cx, alloc)?.map(|b| b.px.iter().map(|p| p[3]).collect()).unwrap_or_else(|| vec![0.0; n])); }; // Unmasked: the masks scale the shape, they aren't the fill's transparency. - let a: Vec = layer.surface().map(|s| surface_to_buffer(s, rect).px.iter().map(|p| p[3]).collect()).unwrap_or_else(|| vec![0.0; n]); + let a: Vec = match layer.surface() { + Some(s) => surface_to_buffer_with(s, rect, alloc)?.px.iter().map(|p| p[3]).collect(), + None => vec![0.0; n], + }; let cov = photocraft_vector::path_coverage(path, rect); let mv = mask_vals(layer, rect, cx); let (w, h) = (rect.width() as usize, rect.height() as usize); @@ -148,7 +158,7 @@ pub(crate) fn effect_shape(layer: &Layer, rect: Rect, cx: &Ctx) -> Vec { } } recycle_mask(mv); - out + Ok(out) } /// The frame layer-effect gradients and linked patterns are laid out in, when it isn't the diff --git a/crates/compose/src/fx_cache.rs b/crates/compose/src/fx_cache.rs index 02dc8b21cc..9d6eb33c07 100644 --- a/crates/compose/src/fx_cache.rs +++ b/crates/compose/src/fx_cache.rs @@ -1,7 +1,7 @@ use super::composite::texture_ctx; use super::ctx::{Ctx, PREPARE_DEPTH}; -use super::extents::{effect_shape, effect_source_bounds}; -use super::{Layer, LayerContent, Rect, Surface, advanced, effects}; +use super::extents::{effect_shape_with, effect_source_bounds}; +use super::{BufferAlloc, InfallibleBufferAlloc, Layer, LayerContent, Rect, Surface, advanced, effects}; // --------------------------------------------------------------------------------------------- // Layer-effect map cache @@ -207,6 +207,18 @@ const MAX_FX_BUILD_BYTES: u64 = if cfg!(target_pointer_width = "64") { 4 << 30 } /// canvas grown likewise; see [`effect_region`]), built once per layer state and shared by every /// tile. `rect` is what the caller composites the layer over (see [`effect_region`]). pub(crate) fn effect_maps(layer: &Layer, rect: Rect, cx: &Ctx) -> std::sync::Arc { + match effect_maps_with(layer, rect, cx, &InfallibleBufferAlloc) { + Ok(maps) => maps, + Err(never) => match never {}, + } +} + +pub(crate) fn effect_maps_with( + layer: &Layer, + rect: Rect, + cx: &Ctx, + alloc: &A, +) -> Result, A::Error> { use std::hash::{Hash, Hasher}; let (mut region, clipped) = effect_region(layer, rect, cx); // Non-local effects keep their whole source region, which a few distant pixels stretch over @@ -217,8 +229,8 @@ pub(crate) fn effect_maps(layer: &Layer, rect: Rect, cx: &Ctx) -> std::sync::Arc } static NO_CACHE: std::sync::OnceLock = std::sync::OnceLock::new(); if *NO_CACHE.get_or_init(|| std::env::var_os("PHOTOCRAFT_FX_NOCACHE").is_some()) { - let shape = if region.is_empty() { Vec::new() } else { effect_shape(layer, region, cx) }; - return std::sync::Arc::new(effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns)); + let shape = if region.is_empty() { Vec::new() } else { effect_shape_with(layer, region, cx, alloc)? }; + return Ok(std::sync::Arc::new(effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns))); } let mut h = std::collections::hash_map::DefaultHasher::new(); cx.layer_keys.identity(layer, cx.doc).hash(&mut h); @@ -227,15 +239,22 @@ pub(crate) fn effect_maps(layer: &Layer, rect: Rect, cx: &Ctx) -> std::sync::Arc let key = h.finish(); // Prepared for this render (see `prepare_effects`): no global lookup, no build. if let Some((m, _)) = cx.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).get(&key) { - return m.clone(); + return Ok(m.clone()); } - let maps = cached_effect_maps(layer, region, key, cx); - cx.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).entry(key).or_insert((maps, clipped)).0.clone() + let maps = cached_effect_maps_with(layer, region, key, cx, alloc)?; + Ok(cx.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).entry(key).or_insert((maps, clipped)).0.clone()) } -fn build_fx_slot_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx, slot: &FxSlot) -> std::sync::Arc { +fn build_fx_slot_maps_with( + layer: &Layer, + region: Rect, + key: u64, + cx: &Ctx, + slot: &FxSlot, + alloc: &A, +) -> Result, A::Error> { let generation = photocraft_raster::spill::read_error_generation(); - let shape: Vec = if region.is_empty() { Vec::new() } else { effect_shape(layer, region, cx) }; + let shape: Vec = if region.is_empty() { Vec::new() } else { effect_shape_with(layer, region, cx, alloc)? }; let maps = effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns); let mut pin = Vec::new(); let mut readable = true; @@ -248,7 +267,7 @@ fn build_fx_slot_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx, slot: &Fx let maps = std::sync::Arc::new(maps); if !readable || photocraft_raster::spill::check_since(generation).is_err() { // Built from a scratch placeholder: use it for this frame, never cache it. - return maps; + return Ok(maps); } if slot.set(FxEntry { maps: maps.clone(), _pin: pin, bytes }).is_ok() { // Counted exactly once, by the build that filled the slot, and only while the @@ -259,7 +278,7 @@ fn build_fx_slot_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx, slot: &Fx } } // A concurrent build that finished first wins, so every tile shares one map. - slot.get().map_or(maps, |e| e.maps.clone()) + Ok(slot.get().map_or(maps, |e| e.maps.clone())) } fn evict_fx_cache_over_budget(key: u64) { @@ -291,7 +310,7 @@ fn evict_fx_cache_over_budget(key: u64) { /// the same layer; had it blocked on a once-init held further up its own stack, it would deadlock. /// Instead a miss builds the maps here and the first finished build is kept. Renders build every /// layer's maps before their parallel tiles (`prepare_effects`), so tiles rarely miss. -fn cached_effect_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx) -> std::sync::Arc { +fn cached_effect_maps_with(layer: &Layer, region: Rect, key: u64, cx: &Ctx, alloc: &A) -> Result, A::Error> { let slot = { let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); if let Some(s) = c.map.get(&key) { @@ -305,9 +324,25 @@ fn cached_effect_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx) -> std::s }; let maps = match slot.get() { Some(e) => e.maps.clone(), - None => build_fx_slot_maps(layer, region, key, cx, &slot), + None => match build_fx_slot_maps_with(layer, region, key, cx, &slot, alloc) { + Ok(maps) => maps, + Err(error) => { + // Allocation failures never publish a partial cache entry. If another renderer + // finished the same slot while this one failed, use that complete result. + let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); + if let Some(entry) = slot.get() { + entry.maps.clone() + } else { + if c.map.get(&key).is_some_and(|current| std::sync::Arc::ptr_eq(current, &slot)) { + c.map.remove(&key); + c.order.retain(|candidate| *candidate != key); + } + return Err(error); + } + } + }, }; // Evict the oldest entries over budget (never the one just used). evict_fx_cache_over_budget(key); - maps + Ok(maps) } diff --git a/crates/compose/src/gradient_fill.rs b/crates/compose/src/gradient_fill.rs index 995d420b6e..82274747b5 100644 --- a/crates/compose/src/gradient_fill.rs +++ b/crates/compose/src/gradient_fill.rs @@ -137,7 +137,6 @@ pub fn render_quantized(f: &Fill, rect: Rect, frame: Rect, quantum: Option) /// Render into caller-owned pixels so compositor paths can use fallible pooled storage. pub(crate) fn render_quantized_into(f: &Fill, rect: Rect, frame: Rect, quantum: Option, px: &mut [[f32; 4]]) { - px.fill([0.0; 4]); render_ramp_into(f, rect, frame, Ramp::new(f), quantum, px); } @@ -168,8 +167,10 @@ fn render_ramp(f: &Fill, rect: Rect, frame: Rect, ramp: Option(f: &Fill, rect: Rect, frame: Rect, ramp: Option>, quantum: Option, px: &mut [[f32; N]]) { - px.fill([0.0; N]); - let (Some(ramp), Fill::Gradient { angle, scale, style, reverse, offset, dither: dith, .. }) = (ramp, f) else { return }; + let (Some(ramp), Fill::Gradient { angle, scale, style, reverse, offset, dither: dith, .. }) = (ramp, f) else { + px.fill([0.0; N]); + return; + }; let w = rect.width() as usize; if w == 0 { return; diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs index c30db7f718..8a26fddcb4 100644 --- a/crates/compose/src/pattern.rs +++ b/crates/compose/src/pattern.rs @@ -456,8 +456,10 @@ pub fn render(tile: &Tile, place: &Placement, rect: Rect) -> Vec<[f32; 4]> { /// Render into caller-owned storage for fallible compositor allocations. pub(crate) fn render_into(tile: &Tile, place: &Placement, rect: Rect, out: &mut Vec<[f32; 4]>) { let len = rect.width() as usize * rect.height() as usize; - out.clear(); - out.resize(len, [0.0; 4]); + if out.len() != len { + out.clear(); + out.resize(len, [0.0; 4]); + } let mut i = 0; for y in rect.y0..rect.y1 { for x in rect.x0..rect.x1 { diff --git a/crates/compose/src/render.rs b/crates/compose/src/render.rs index 9d277c7bee..b0f658c596 100644 --- a/crates/compose/src/render.rs +++ b/crates/compose/src/render.rs @@ -1,6 +1,6 @@ use super::composite::{composite_stack_at, composite_stack_at_with}; use super::content::RENDER_TILE; -use super::ctx::{Ctx, RenderVectorMasks, prepare_effects, prepare_tones}; +use super::ctx::{Ctx, RenderVectorMasks, prepare_effects_with, prepare_tones}; use super::{ Buffer, BufferAlloc, Document, FallibleBufferAlloc, InfallibleBufferAlloc, Layer, Rect, Surface, adjust, advanced, cmyk, multichannel, native, native_lab, pattern, psblend, @@ -80,9 +80,9 @@ fn render_tiled_with_alloc(doc: &Document, rect: Rect, ti }); } // Effect maps are built once, here, before any tile needs them (#276). - prepare_effects(&doc.layers, rect, cx, |f| { - photocraft_color::convert::with_cmyk_space(cmyk, || in_blend_space(lab, hdr, f)); - }); + prepare_effects_with(&doc.layers, rect, cx, alloc, |f| { + photocraft_color::convert::with_cmyk_space(cmyk, || in_blend_space(lab, hdr, f)) + })?; let run = |t: Rect| { photocraft_color::convert::with_cmyk_space(cmyk, || -> Result<_, A::Error> { let mut b = multichannel::backdrop_with(doc, t, alloc)?; @@ -174,8 +174,9 @@ pub fn cmyk_space(doc: &Document) -> Option { /// The compositor could not reserve or size one of its RGBA buffers. Earlier complete bands @@ -224,6 +225,21 @@ mod fallible_bands_tests { doc } + fn outlined_effect_document() -> Document { + let mut doc = Document::new("fallible outlined effect", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); + let path = photocraft_doc::vector::Path { + subpaths: vec![photocraft_doc::vector::Subpath::polygon(&[(12.0, 12.0), (60.0, 12.0), (60.0, 60.0), (12.0, 60.0)])], + ..Default::default() + }; + let mut cache = photocraft_doc::Surface::new(photocraft_color::PixelFormat::RGBA8); + cache.fill_rect(Rect::new(12, 12, 60, 60), &[0.0, 0.0, 0.0, 1.0]); + let shape = photocraft_doc::vector::ShapeLayer { path, fill: Some(Fill::Solid(Color::BLACK)), cache: Some(cache), ..Default::default() }; + let mut layer = Layer::new("outlined shape", LayerContent::Shape(shape)); + layer.effects.items.push(photocraft_doc::Effect::default_drop_shadow()); + doc.layers.push(layer); + doc + } + #[test] fn fail_nth_buffer_constructor_propagates_through_nested_rendering() { let doc = nested_document(); @@ -252,13 +268,67 @@ mod fallible_bands_tests { } #[test] - fn tiled_renderer_returns_buffer_allocation_error_before_delivering_a_band() { + fn render_bands_with_alloc_reports_outer_and_tile_allocations_before_the_sink() { let doc = Document::new("fallible tile", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); let ctx = Ctx::for_doc(&doc, &patterns); + for fail_at in [1, 2] { + let alloc = FailBufferAt { fail_at, attempts: AtomicUsize::new(0) }; + let mut delivered = 0; + let result = render_bands_with_alloc(&doc, doc.bounds(), RENDER_TILE, &alloc, &mut |_| { + delivered += 1; + Ok::<(), ()>(()) + }); + assert!(matches!(result, Err(RenderBandsCoreError::Allocation(error)) if error == fail_at)); + assert_eq!(delivered, 0, "failed output or tile allocation must not deliver a partial band"); + if fail_at == 1 { + assert_eq!(alloc.attempts.load(Ordering::Relaxed), 1, "the output allocation is sequential"); + } else { + assert!(alloc.attempts.load(Ordering::Relaxed) >= 2, "parallel tile allocation may have other in-flight attempts"); + } + } + } + + #[test] + fn effect_shape_buffer_failure_is_not_cached_and_retry_uses_the_successful_cache() { + let mut doc = Document::new("fallible effect shape", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); + let fill = Layer::new("group fill", LayerContent::Fill(Fill::Solid(Color::BLACK))); + let mut layer = Layer::group("styled group", vec![fill]); + layer.effects.items.push(photocraft_doc::Effect::default_drop_shadow()); + doc.layers.push(layer); + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + let cx = Ctx::for_doc(&doc, &patterns); + + for _ in 0..2 { + let alloc = FailBufferAt { fail_at: 1, attempts: AtomicUsize::new(0) }; + let mut delivered = 0; + let result = render_bands_with_alloc(&doc, doc.bounds(), RENDER_TILE, &alloc, &mut |_| { + delivered += 1; + Ok::<(), ()>(()) + }); + assert!(matches!(result, Err(RenderBandsCoreError::Allocation(1)))); + assert_eq!(delivered, 0, "failed effect-shape allocation must happen before the sink"); + assert_eq!(alloc.attempts.load(Ordering::Relaxed), 1, "the cold effect shape requests an RGBA buffer before output"); + } + + let alloc = FallibleBufferAlloc; + render_tiled_with_alloc(&doc, doc.bounds(), RENDER_TILE, &cx, &alloc).unwrap(); + let cached_cx = Ctx::for_doc(&doc, &patterns); + let cache_hit_alloc = FailBufferAt { fail_at: 1, attempts: AtomicUsize::new(0) }; + crate::fx_cache::effect_maps_with(&doc.layers[0], doc.bounds(), &cached_cx, &cache_hit_alloc).unwrap(); + assert_eq!(cache_hit_alloc.attempts.load(Ordering::Relaxed), 0, "the successful cache avoids rebuilding its RGBA shape"); + + let outlined = outlined_effect_document(); + let patterns = pattern::PreparedPatterns::new(&outlined.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(outlined.pixel_format().mode); + let cx = Ctx::for_doc(&outlined, &patterns); let alloc = FailBufferAt { fail_at: 1, attempts: AtomicUsize::new(0) }; - assert!(render_tiled_with_alloc(&doc, doc.bounds(), RENDER_TILE, &ctx, &alloc).is_err()); - assert_eq!(alloc.attempts.load(Ordering::Relaxed), 1); + let mut delivered = 0; + let result = render_bands_with_alloc(&outlined, outlined.bounds(), RENDER_TILE, &alloc, &mut |_| { + delivered += 1; + Ok::<(), ()>(()) + }); + assert!(matches!(result, Err(RenderBandsCoreError::Allocation(1)))); + assert_eq!(delivered, 0, "outline alpha extraction must use the fallible surface buffer path"); } #[test] From 53eb4ead75868e33461acd3be8c2ae5431f5bfff Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 20:23:42 -0800 Subject: [PATCH 33/46] Tighten fallible compositor allocation regression --- crates/compose/src/render.rs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/crates/compose/src/render.rs b/crates/compose/src/render.rs index b0f658c596..7fe0bacf75 100644 --- a/crates/compose/src/render.rs +++ b/crates/compose/src/render.rs @@ -270,8 +270,6 @@ mod fallible_bands_tests { #[test] fn render_bands_with_alloc_reports_outer_and_tile_allocations_before_the_sink() { let doc = Document::new("fallible tile", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); - let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); - let ctx = Ctx::for_doc(&doc, &patterns); for fail_at in [1, 2] { let alloc = FailBufferAt { fail_at, attempts: AtomicUsize::new(0) }; let mut delivered = 0; @@ -313,14 +311,11 @@ mod fallible_bands_tests { let alloc = FallibleBufferAlloc; render_tiled_with_alloc(&doc, doc.bounds(), RENDER_TILE, &cx, &alloc).unwrap(); - let cached_cx = Ctx::for_doc(&doc, &patterns); let cache_hit_alloc = FailBufferAt { fail_at: 1, attempts: AtomicUsize::new(0) }; - crate::fx_cache::effect_maps_with(&doc.layers[0], doc.bounds(), &cached_cx, &cache_hit_alloc).unwrap(); - assert_eq!(cache_hit_alloc.attempts.load(Ordering::Relaxed), 0, "the successful cache avoids rebuilding its RGBA shape"); + crate::fx_cache::effect_maps_with(&doc.layers[0], doc.bounds(), &cx, &cache_hit_alloc).unwrap(); + assert_eq!(cache_hit_alloc.attempts.load(Ordering::Relaxed), 0, "the successful render-context cache avoids rebuilding its RGBA shape"); let outlined = outlined_effect_document(); - let patterns = pattern::PreparedPatterns::new(&outlined.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(outlined.pixel_format().mode); - let cx = Ctx::for_doc(&outlined, &patterns); let alloc = FailBufferAt { fail_at: 1, attempts: AtomicUsize::new(0) }; let mut delivered = 0; let result = render_bands_with_alloc(&outlined, outlined.bounds(), RENDER_TILE, &alloc, &mut |_| { From 138b591c3c34a3d41ea2503fdeb0694757c07e0f Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 20:27:07 -0800 Subject: [PATCH 34/46] Remove stale compositor wrapper imports --- crates/compose/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 75d5b5359f..bc9f3d4c0c 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -56,7 +56,7 @@ mod render; pub use composite::{adjustment_quantum, blend_if_active, occludes_below, text_gamma}; #[cfg(test)] use composite::{blend_into_fill, blend_into_g, branchless_floor, composite_layer_plain, composite_pixel_layer, pixel_surface, quantize}; -use composite::{composite_atop, composite_layer, composite_stack_at, dissolve_noise}; +use composite::{composite_stack_at, dissolve_noise}; #[cfg(test)] use content::render_fill; pub use content::{RENDER_TILE, channel_weights, fill_frame, layer_shape, render_fill_content, stroke_frame, surface_to_buffer}; From 1c0db80938fbbb5b37928f5d7f2e5774ca637ea4 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 20:28:25 -0800 Subject: [PATCH 35/46] Remove obsolete infallible compositor wrappers --- crates/compose/src/composite.rs | 18 ++---------------- crates/compose/src/content.rs | 1 + crates/compose/src/lib.rs | 4 +++- 3 files changed, 6 insertions(+), 17 deletions(-) diff --git a/crates/compose/src/composite.rs b/crates/compose/src/composite.rs index 73e54d8911..e53b492fc5 100644 --- a/crates/compose/src/composite.rs +++ b/crates/compose/src/composite.rs @@ -1,4 +1,4 @@ -use super::content::{channel_weights, empty_in, render_content_with, restore_channels, surface_to_buffer, surface_to_buffer_with}; +use super::content::{channel_weights, empty_in, render_content_with, restore_channels, surface_to_buffer_with}; use super::ctx::Ctx; use super::extents::{effects_frame, mask_k, mask_vals, recycle_mask, shapeless_stroke_bounds}; use super::fx_cache::effect_maps_with; @@ -598,14 +598,7 @@ pub fn text_gamma(layer: &Layer) -> f32 { /// A stroked shape layer with visible clipped layers: Photoshop draws the shape's vector stroke /// above the clipped layers, so the base content is the fill alone and the stroke is laid on top -/// after clipping. See [`split_parts`]. -fn shape_parts(layer: &Layer, clipped: &[Layer], rect: Rect, cx: &Ctx) -> Option<(Buffer, Buffer, Option>)> { - if !clipped.iter().any(|c| c.visible) { - return None; - } - split_parts(layer, rect, cx) -} - +/// after clipping. See [`split_parts_with`]. fn shape_parts_with( layer: &Layer, clipped: &[Layer], @@ -623,13 +616,6 @@ fn shape_parts_with( /// layers. Fill and stroke are unmasked: the mask applies to them together. Layer effects paint /// the fill's interior effects beneath the vector stroke (psd-tools stroke-composite: a colour /// overlay leaves the stroke, the stroke effect covers it). -fn split_parts(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<(Buffer, Buffer, Option>)> { - let LayerContent::Shape(sh) = &layer.content else { return None }; - sh.stroke.as_ref()?; - let (fs, ss) = shape_split::split(sh, cx.canvas, cx.depth)?; - Some((surface_to_buffer(&fs, rect), surface_to_buffer(&ss, rect), mask_vals(layer, rect, cx))) -} - fn split_parts_with( layer: &Layer, rect: Rect, diff --git a/crates/compose/src/content.rs b/crates/compose/src/content.rs index a77551b182..d42055471a 100644 --- a/crates/compose/src/content.rs +++ b/crates/compose/src/content.rs @@ -28,6 +28,7 @@ fn scratch_reuse_preserves_pixels() { /// Render a layer's own content (no blending into the backdrop yet) into an isolated buffer. /// Returns None for layers that operate on the backdrop (adjustments, pass-through groups). +#[cfg(test)] pub(crate) fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option { match render_content_with(layer, rect, cx, &InfallibleBufferAlloc) { Ok(buffer) => buffer, diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index bc9f3d4c0c..898c8faa05 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -60,7 +60,9 @@ use composite::{composite_stack_at, dissolve_noise}; #[cfg(test)] use content::render_fill; pub use content::{RENDER_TILE, channel_weights, fill_frame, layer_shape, render_fill_content, stroke_frame, surface_to_buffer}; -use content::{empty_in, render_content}; +use content::empty_in; +#[cfg(test)] +use content::render_content; use ctx::{Ctx, prepare_effects}; #[cfg(test)] use ctx::{LayerKeys, PREPARE_DEPTH, effect_layers, prepare_tones}; From 2277c6719538ff38504a9125cf4b430632c84a6d Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 20:30:41 -0800 Subject: [PATCH 36/46] Remove unused effects wrapper re-export --- crates/compose/src/effects.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index 08b946abb7..57a836fc1e 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -44,7 +44,7 @@ use bevel::{bevel_maps, satin_map}; #[cfg(test)] use blur::{blur, box_line, dilate, tent, tent_direct}; pub use blur::{size_one_kernel, tent_kernel}; -pub(crate) use composite::{VectorStroke, build_maps_prepared, composite_with_effects_prepared, composite_with_effects_prepared_with, map_count}; +pub(crate) use composite::{VectorStroke, build_maps_prepared, composite_with_effects_prepared_with, map_count}; pub use composite::{build_maps, composite_with_effects, outline_share, premerges_layer, shadow_see_through, stroke_widths}; pub use distance::{FieldKind, STROKE_CHAMFER_MAX, bevel_distance_fields, distance_field, stroke_outside_exact}; #[cfg(test)] From 2ea1f2b91642bc85f5a27d63faea80b381963d22 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 15 Nov 2026 20:36:37 -0800 Subject: [PATCH 37/46] Apply rustfmt to fallible compositor candidate --- crates/compose/src/advanced.rs | 16 +++++++++++---- crates/compose/src/composite.rs | 33 ++++++++++++++++++------------- crates/compose/src/content.rs | 5 ++++- crates/compose/src/ctx.rs | 12 ++--------- crates/compose/src/extents.rs | 4 +++- crates/compose/src/fx_cache.rs | 7 +------ crates/compose/src/lib.rs | 9 ++++----- crates/compose/src/render.rs | 35 ++++++++++++++++++--------------- 8 files changed, 64 insertions(+), 57 deletions(-) diff --git a/crates/compose/src/advanced.rs b/crates/compose/src/advanced.rs index 672d793e52..add4485526 100644 --- a/crates/compose/src/advanced.rs +++ b/crates/compose/src/advanced.rs @@ -137,7 +137,9 @@ pub(crate) fn needs_floor(layers: &[Layer]) -> bool { fn knockout_shape_with(layer: &Layer, rect: Rect, cx: &Ctx, alloc: &A) -> Result, A::Error> { let n = rect.width() as usize * rect.height() as usize; let masks = || mask_vals(layer, rect, cx).unwrap_or_else(|| vec![1.0; n]); - if !layer.advanced.transparency_shapes { return Ok(masks()) } + if !layer.advanced.transparency_shapes { + return Ok(masks()); + } match render_content_with(layer, rect, cx, alloc)? { Some(b) => Ok(b.px.iter().map(|p| p[3]).collect()), None => Ok(masks()), @@ -209,7 +211,9 @@ pub(crate) fn composite_clipped_with(clipped: &[Layer], base: &m let floor = if clipped.iter().any(|c| c.visible && c.advanced.knockout != Knockout::None) { Some(alloc.clone(base)?) } else { None }; for c in clipped.iter().filter(|c| c.visible) { match &floor { - Some(f) if c.advanced.knockout != Knockout::None => knockout_with(c, base, f, true, cx, alloc, |b| crate::composite::composite_atop_with(c, b, cx, alloc))?, + Some(f) if c.advanced.knockout != Knockout::None => { + knockout_with(c, base, f, true, cx, alloc, |b| crate::composite::composite_atop_with(c, b, cx, alloc))? + } _ => crate::composite::composite_atop_with(c, base, cx, alloc)?, } } @@ -249,13 +253,17 @@ pub(crate) fn composite_clipped_individually_with( clip } }; - if clip.len() != n { return Ok(()) } + if clip.len() != n { + return Ok(()); + } for c in clipped.iter().filter(|c| c.visible) { let before = alloc.clone(backdrop)?; let t = knockout_target_with(c, floor.as_ref(), rect, cx, Scope { root: false, ..scope }, alloc)?; crate::composite::composite_layer_with(c, &[], backdrop, cx, t.as_deref(), scope, alloc)?; for ((p, b), k) in backdrop.px.iter_mut().zip(&before.px).zip(&clip) { - if *k < 1.0 { *p = mix(*b, *p, k.max(0.0)); } + if *k < 1.0 { + *p = mix(*b, *p, k.max(0.0)); + } } } Ok(()) diff --git a/crates/compose/src/composite.rs b/crates/compose/src/composite.rs index e53b492fc5..5c13f249dd 100644 --- a/crates/compose/src/composite.rs +++ b/crates/compose/src/composite.rs @@ -2,10 +2,7 @@ use super::content::{channel_weights, empty_in, render_content_with, restore_cha use super::ctx::Ctx; use super::extents::{effects_frame, mask_k, mask_vals, recycle_mask, shapeless_stroke_bounds}; use super::fx_cache::effect_maps_with; -use super::{ - BlendMode, Buffer, BufferAlloc, Fill, InfallibleBufferAlloc, Layer, LayerContent, Rect, Surface, advanced, blend, effects, - psblend, shape_split, -}; +use super::{BlendMode, Buffer, BufferAlloc, Fill, InfallibleBufferAlloc, Layer, LayerContent, Rect, Surface, advanced, blend, effects, psblend, shape_split}; /// Composite a sibling list (bottom→top) onto `backdrop`; `scope` says where the stack sits (see /// [`advanced::Scope`]: it decides what knockouts reveal). @@ -295,7 +292,14 @@ pub(crate) fn composite_layer_with( Ok(()) } -fn composite_layer_any_with(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope, alloc: &A) -> Result<(), A::Error> { +fn composite_layer_any_with( + layer: &Layer, + clipped: &[Layer], + backdrop: &mut Buffer, + cx: &Ctx, + scope: advanced::Scope, + alloc: &A, +) -> Result<(), A::Error> { if let LayerContent::Group(g) = &layer.content && let Some(ab) = &g.artboard { @@ -460,7 +464,9 @@ fn composite_layer_plain_with( for ((p, w), wo) in backdrop.px.iter_mut().zip(&with.px).zip(&without.px) { let pa = p[3]; let mut pm = [p[0] * pa, p[1] * pa, p[2] * pa, pa]; - for c in 0..3 { pm[c] += w[c] * w[3] - wo[c] * wo[3]; } + for c in 0..3 { + pm[c] += w[c] * w[3] - wo[c] * wo[3]; + } pm[3] += w[3] - wo[3]; let a = pm[3].clamp(0.0, 1.0); *p = if a > 0.0 { [(pm[0] / a).clamp(0.0, 1.0), (pm[1] / a).clamp(0.0, 1.0), (pm[2] / a).clamp(0.0, 1.0), a] } else { [0.0; 4] }; @@ -616,12 +622,7 @@ fn shape_parts_with( /// layers. Fill and stroke are unmasked: the mask applies to them together. Layer effects paint /// the fill's interior effects beneath the vector stroke (psd-tools stroke-composite: a colour /// overlay leaves the stroke, the stroke effect covers it). -fn split_parts_with( - layer: &Layer, - rect: Rect, - cx: &Ctx, - alloc: &A, -) -> Result>)>, A::Error> { +fn split_parts_with(layer: &Layer, rect: Rect, cx: &Ctx, alloc: &A) -> Result>)>, A::Error> { let LayerContent::Shape(sh) = &layer.content else { return Ok(None) }; if sh.stroke.is_none() { return Ok(None); @@ -698,7 +699,9 @@ fn composite_atop_any_with(layer: &Layer, base: &mut Buffer, cx: }; let vstroke = parts.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); let mut opaque = alloc.clone(base)?; - for p in &mut opaque.px { p[3] = 1.0; } + for p in &mut opaque.px { + p[3] = 1.0; + } let maps = effect_maps_with(layer, rect, cx, alloc)?; effects::composite_with_effects_prepared_with(layer, &content, &mut opaque, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke, alloc)?; if let Some((_, mask)) = parts { @@ -706,7 +709,9 @@ fn composite_atop_any_with(layer: &Layer, base: &mut Buffer, cx: } if let Some(m) = &hide { let mut plain = alloc.clone(base)?; - for p in &mut plain.px { p[3] = 1.0; } + for p in &mut plain.px { + p[3] = 1.0; + } advanced::apply_hiding_mask(&mut opaque, &plain, m); } recycle_mask(hide); diff --git a/crates/compose/src/content.rs b/crates/compose/src/content.rs index d42055471a..6e902dab18 100644 --- a/crates/compose/src/content.rs +++ b/crates/compose/src/content.rs @@ -2,7 +2,10 @@ use super::composite::{adjustment_quantum, blend_into}; use super::ctx::Ctx; use super::extents::{effect_shape, effect_source_bounds, mask_vals, recycle_mask, shapeless_stroke_bounds, transparent_outside}; use super::fx_cache::effect_maps; -use super::{BlendMode, Buffer, BufferAlloc, Document, Fill, InfallibleBufferAlloc, Layer, LayerContent, Pattern, Rect, Surface, bounds, effects, gradient_fill, pattern, shape_split}; +use super::{ + BlendMode, Buffer, BufferAlloc, Document, Fill, InfallibleBufferAlloc, Layer, LayerContent, Pattern, Rect, Surface, bounds, effects, gradient_fill, + pattern, shape_split, +}; /// Tile size for parallel rendering (tile results are independent). pub const RENDER_TILE: i32 = 256; diff --git a/crates/compose/src/ctx.rs b/crates/compose/src/ctx.rs index db3b4fcd93..6fe541678d 100644 --- a/crates/compose/src/ctx.rs +++ b/crates/compose/src/ctx.rs @@ -196,22 +196,14 @@ pub(crate) fn prepare_effects(layers: &[Layer], rect: Rect, cx: &Ctx, setting: i } /// Fallible counterpart of [`prepare_effects`], used by the compositor before it starts tiles. -pub(crate) fn prepare_effects_with( - layers: &[Layer], - rect: Rect, - cx: &Ctx, - alloc: &A, - setting: F, -) -> Result<(), A::Error> +pub(crate) fn prepare_effects_with(layers: &[Layer], rect: Rect, cx: &Ctx, alloc: &A, setting: F) -> Result<(), A::Error> where A: BufferAlloc + Sync, F: Fn(&mut dyn FnMut() -> Result<(), A::Error>) -> Result<(), A::Error> + Sync, { let mut todo = Vec::new(); effect_layers(layers, rect, 0, &mut todo); - let build = |l: &std::borrow::Cow| { - setting(&mut || effect_maps_with(l, rect, cx, alloc).map(|_| ())) - }; + let build = |l: &std::borrow::Cow| setting(&mut || effect_maps_with(l, rect, cx, alloc).map(|_| ())); #[cfg(not(target_arch = "wasm32"))] if todo.len() > 1 { use rayon::prelude::*; diff --git a/crates/compose/src/extents.rs b/crates/compose/src/extents.rs index c9cf0d7fad..587689e9bb 100644 --- a/crates/compose/src/extents.rs +++ b/crates/compose/src/extents.rs @@ -1,6 +1,8 @@ use super::content::{render_content_with, surface_to_buffer_with}; use super::ctx::Ctx; -use super::{BlendMode, BufferAlloc, Document, InfallibleBufferAlloc, Layer, LayerContent, Rect, adjustment_quantum, advanced, bounds, effects, masks, shape_split}; +use super::{ + BlendMode, BufferAlloc, Document, InfallibleBufferAlloc, Layer, LayerContent, Rect, adjustment_quantum, advanced, bounds, effects, masks, shape_split, +}; /// Bounds of a layer's own pixels (union over group children; the canvas /// for fill layers; an artboard's board). diff --git a/crates/compose/src/fx_cache.rs b/crates/compose/src/fx_cache.rs index 9d6eb33c07..791a102c59 100644 --- a/crates/compose/src/fx_cache.rs +++ b/crates/compose/src/fx_cache.rs @@ -213,12 +213,7 @@ pub(crate) fn effect_maps(layer: &Layer, rect: Rect, cx: &Ctx) -> std::sync::Arc } } -pub(crate) fn effect_maps_with( - layer: &Layer, - rect: Rect, - cx: &Ctx, - alloc: &A, -) -> Result, A::Error> { +pub(crate) fn effect_maps_with(layer: &Layer, rect: Rect, cx: &Ctx, alloc: &A) -> Result, A::Error> { use std::hash::{Hash, Hasher}; let (mut region, clipped) = effect_region(layer, rect, cx); // Non-local effects keep their whole source region, which a few distant pixels stretch over diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 898c8faa05..a1376dcf28 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -57,12 +57,12 @@ pub use composite::{adjustment_quantum, blend_if_active, occludes_below, text_ga #[cfg(test)] use composite::{blend_into_fill, blend_into_g, branchless_floor, composite_layer_plain, composite_pixel_layer, pixel_surface, quantize}; use composite::{composite_stack_at, dissolve_noise}; -#[cfg(test)] -use content::render_fill; -pub use content::{RENDER_TILE, channel_weights, fill_frame, layer_shape, render_fill_content, stroke_frame, surface_to_buffer}; use content::empty_in; #[cfg(test)] use content::render_content; +#[cfg(test)] +use content::render_fill; +pub use content::{RENDER_TILE, channel_weights, fill_frame, layer_shape, render_fill_content, stroke_frame, surface_to_buffer}; use ctx::{Ctx, prepare_effects}; #[cfg(test)] use ctx::{LayerKeys, PREPARE_DEPTH, effect_layers, prepare_tones}; @@ -138,8 +138,7 @@ impl Buffer { /// Fallibly clone the pixel storage while keeping the same rectangle. pub fn try_clone(&self) -> Result { let bytes = self.px.len().checked_mul(std::mem::size_of::<[f32; 4]>()).ok_or(photocraft_raster::AllocationError::SizeOverflow)?; - let mut px = photocraft_raster::scratch::try_take(self.px.len(), [0.0; 4]) - .ok_or(photocraft_raster::AllocationError::NotEnoughMemory { bytes })?; + let mut px = photocraft_raster::scratch::try_take(self.px.len(), [0.0; 4]).ok_or(photocraft_raster::AllocationError::NotEnoughMemory { bytes })?; px.copy_from_slice(&self.px); Ok(Self { rect: self.rect, px }) } diff --git a/crates/compose/src/render.rs b/crates/compose/src/render.rs index 7fe0bacf75..14983ed73a 100644 --- a/crates/compose/src/render.rs +++ b/crates/compose/src/render.rs @@ -2,8 +2,8 @@ use super::composite::{composite_stack_at, composite_stack_at_with}; use super::content::RENDER_TILE; use super::ctx::{Ctx, RenderVectorMasks, prepare_effects_with, prepare_tones}; use super::{ - Buffer, BufferAlloc, Document, FallibleBufferAlloc, InfallibleBufferAlloc, Layer, Rect, Surface, adjust, advanced, cmyk, multichannel, native, - native_lab, pattern, psblend, + Buffer, BufferAlloc, Document, FallibleBufferAlloc, InfallibleBufferAlloc, Layer, Rect, Surface, adjust, advanced, cmyk, multichannel, native, native_lab, + pattern, psblend, }; /// Every layer the compositor draws, groups before their children: hidden layers and everything @@ -80,9 +80,7 @@ fn render_tiled_with_alloc(doc: &Document, rect: Rect, ti }); } // Effect maps are built once, here, before any tile needs them (#276). - prepare_effects_with(&doc.layers, rect, cx, alloc, |f| { - photocraft_color::convert::with_cmyk_space(cmyk, || in_blend_space(lab, hdr, f)) - })?; + prepare_effects_with(&doc.layers, rect, cx, alloc, |f| photocraft_color::convert::with_cmyk_space(cmyk, || in_blend_space(lab, hdr, f)))?; let run = |t: Rect| { photocraft_color::convert::with_cmyk_space(cmyk, || -> Result<_, A::Error> { let mut b = multichannel::backdrop_with(doc, t, alloc)?; @@ -194,7 +192,10 @@ mod fallible_bands_tests { use photocraft_geom::Size; use std::sync::atomic::{AtomicUsize, Ordering}; - struct FailBufferAt { fail_at: usize, attempts: AtomicUsize } + struct FailBufferAt { + fail_at: usize, + attempts: AtomicUsize, + } impl FailBufferAt { fn attempt(&self) -> Result<(), usize> { @@ -337,9 +338,17 @@ mod fallible_bands_tests { fn legacy_and_fallible_band_apis_deliver_the_same_pixels() { let doc = nested_document(); let mut legacy = Vec::new(); - render_bands(&doc, doc.bounds(), 8, |band| { legacy.push(band); Ok::<(), ()>(()) }).unwrap(); + render_bands(&doc, doc.bounds(), 8, |band| { + legacy.push(band); + Ok::<(), ()>(()) + }) + .unwrap(); let mut fallible = Vec::new(); - try_render_bands(&doc, doc.bounds(), 8, |band| { fallible.push(band); Ok::<(), ()>(()) }).unwrap(); + try_render_bands(&doc, doc.bounds(), 8, |band| { + fallible.push(band); + Ok::<(), ()>(()) + }) + .unwrap(); assert_eq!(legacy, fallible); } } @@ -362,12 +371,7 @@ pub fn render_bands(doc: &Document, rect: Rect, band_rows: i32, mut sink: imp } /// Fallible `render_bands` variant that reports compositor-owned RGBA buffer allocation failures. -pub fn try_render_bands( - doc: &Document, - rect: Rect, - band_rows: i32, - mut sink: impl FnMut(Buffer) -> Result<(), E>, -) -> Result<(), RenderBandsError> { +pub fn try_render_bands(doc: &Document, rect: Rect, band_rows: i32, mut sink: impl FnMut(Buffer) -> Result<(), E>) -> Result<(), RenderBandsError> { match render_bands_with_alloc(doc, rect, band_rows, &FallibleBufferAlloc, &mut sink) { Ok(()) => Ok(()), Err(RenderBandsCoreError::Allocation(error)) => Err(RenderBandsError::Allocation(error)), @@ -392,8 +396,7 @@ fn render_bands_with_alloc( let mut y = rect.y0; while y < rect.y1 { let y1 = y.saturating_add(rows).min(rect.y1); - let band = render_tiled_with_alloc(doc, Rect::new(rect.x0, y, rect.x1, y1), RENDER_TILE, &cx, alloc) - .map_err(RenderBandsCoreError::Allocation)?; + let band = render_tiled_with_alloc(doc, Rect::new(rect.x0, y, rect.x1, y1), RENDER_TILE, &cx, alloc).map_err(RenderBandsCoreError::Allocation)?; sink(band).map_err(RenderBandsCoreError::Sink)?; y = y1; } From ec81755e2bbc70dc71890f632e65f40f93cd3e61 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 00:06:59 -0800 Subject: [PATCH 38/46] Factor prepared compositor inputs and shape parts for strict lint --- crates/compose/src/composite.rs | 15 ++++++++------- crates/compose/src/effects/composite.rs | 6 +++--- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/crates/compose/src/composite.rs b/crates/compose/src/composite.rs index 5c13f249dd..a56f8605c6 100644 --- a/crates/compose/src/composite.rs +++ b/crates/compose/src/composite.rs @@ -453,8 +453,7 @@ fn composite_layer_plain_with( // them, each placed over the original backdrop) is added to the // pass-through result. Exact when the children blend Normal, close // otherwise (matches psd-tools clipping-mask3/4/5). - if has_clipped { - if let (Some(before), Some(iso)) = (before, render_content_with(layer, rect, cx, alloc)?) { + if has_clipped && let (Some(before), Some(iso)) = (before, render_content_with(layer, rect, cx, alloc)?) { let mut clipped_iso = alloc.clone(&iso)?; advanced::composite_clipped_with(clipped, &mut clipped_iso, cx, alloc)?; let mut without = alloc.clone(&before)?; @@ -471,7 +470,6 @@ fn composite_layer_plain_with( let a = pm[3].clamp(0.0, 1.0); *p = if a > 0.0 { [(pm[0] / a).clamp(0.0, 1.0), (pm[1] / a).clamp(0.0, 1.0), (pm[2] / a).clamp(0.0, 1.0), a] } else { [0.0; 4] }; } - } } return Ok(()); } @@ -589,7 +587,7 @@ fn composite_layer_effects_with(layer: &Layer, clipped: &[Layer] advanced::composite_clipped_with(clipped, &mut content, cx, alloc)?; let vstroke = parts.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); let maps = effect_maps_with(layer, rect, cx, alloc)?; - effects::composite_with_effects_prepared_with(layer, &content, backdrop, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke, alloc)?; + effects::composite_with_effects_prepared_with(layer, &content, backdrop, (&maps, vstroke), effects_frame(layer, cx.canvas), cx.patterns, alloc)?; if let Some((_, mask)) = parts { recycle_mask(mask); } @@ -602,6 +600,9 @@ pub fn text_gamma(layer: &Layer) -> f32 { if matches!(layer.content, LayerContent::Text(_)) { psblend::text_gamma() } else { 1.0 } } +/// Unmasked shape fill, vector stroke and shared mask values. +type ShapeParts = (Buffer, Buffer, Option>); + /// A stroked shape layer with visible clipped layers: Photoshop draws the shape's vector stroke /// above the clipped layers, so the base content is the fill alone and the stroke is laid on top /// after clipping. See [`split_parts_with`]. @@ -611,7 +612,7 @@ fn shape_parts_with( rect: Rect, cx: &Ctx, alloc: &A, -) -> Result>)>, A::Error> { +) -> Result, A::Error> { if !clipped.iter().any(|c| c.visible) { return Ok(None); } @@ -622,7 +623,7 @@ fn shape_parts_with( /// layers. Fill and stroke are unmasked: the mask applies to them together. Layer effects paint /// the fill's interior effects beneath the vector stroke (psd-tools stroke-composite: a colour /// overlay leaves the stroke, the stroke effect covers it). -fn split_parts_with(layer: &Layer, rect: Rect, cx: &Ctx, alloc: &A) -> Result>)>, A::Error> { +fn split_parts_with(layer: &Layer, rect: Rect, cx: &Ctx, alloc: &A) -> Result, A::Error> { let LayerContent::Shape(sh) = &layer.content else { return Ok(None) }; if sh.stroke.is_none() { return Ok(None); @@ -703,7 +704,7 @@ fn composite_atop_any_with(layer: &Layer, base: &mut Buffer, cx: p[3] = 1.0; } let maps = effect_maps_with(layer, rect, cx, alloc)?; - effects::composite_with_effects_prepared_with(layer, &content, &mut opaque, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke, alloc)?; + effects::composite_with_effects_prepared_with(layer, &content, &mut opaque, (&maps, vstroke), effects_frame(layer, cx.canvas), cx.patterns, alloc)?; if let Some((_, mask)) = parts { recycle_mask(mask); } diff --git a/crates/compose/src/effects/composite.rs b/crates/compose/src/effects/composite.rs index ca57389b25..91851b2aa5 100644 --- a/crates/compose/src/effects/composite.rs +++ b/crates/compose/src/effects/composite.rs @@ -243,7 +243,7 @@ pub(crate) fn composite_with_effects_prepared( patterns: &PreparedPatterns<'_>, vstroke: Option>, ) { - match composite_with_effects_prepared_with(layer, content, backdrop, maps, layer_bounds, patterns, vstroke, &InfallibleBufferAlloc) { + match composite_with_effects_prepared_with(layer, content, backdrop, (maps, vstroke), layer_bounds, patterns, &InfallibleBufferAlloc) { Ok(()) => {} Err(never) => match never {}, } @@ -253,12 +253,12 @@ pub(crate) fn composite_with_effects_prepared_with( layer: &Layer, content: &Buffer, backdrop: &mut Buffer, - maps: &FxMaps, + prepared: (&FxMaps, Option>), layer_bounds: Rect, patterns: &PreparedPatterns<'_>, - vstroke: Option>, alloc: &A, ) -> Result<(), A::Error> { + let (maps, vstroke) = prepared; let pass = EffectPass::new(layer, maps, content.rect, layer_bounds, patterns, vstroke.as_ref()); let big = pass.big; let shape = pass.effect_shape(content); From 949e2d4d7164f8411fbf94acbbb89670255383b8 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 00:15:54 -0800 Subject: [PATCH 39/46] Format compositor lint repair --- crates/compose/src/composite.rs | 38 ++++++++++++++------------------- 1 file changed, 16 insertions(+), 22 deletions(-) diff --git a/crates/compose/src/composite.rs b/crates/compose/src/composite.rs index a56f8605c6..96fe1aeb5a 100644 --- a/crates/compose/src/composite.rs +++ b/crates/compose/src/composite.rs @@ -454,22 +454,22 @@ fn composite_layer_plain_with( // pass-through result. Exact when the children blend Normal, close // otherwise (matches psd-tools clipping-mask3/4/5). if has_clipped && let (Some(before), Some(iso)) = (before, render_content_with(layer, rect, cx, alloc)?) { - let mut clipped_iso = alloc.clone(&iso)?; - advanced::composite_clipped_with(clipped, &mut clipped_iso, cx, alloc)?; - let mut without = alloc.clone(&before)?; - blend_into(&mut without, &iso, BlendMode::Normal, opacity); - let mut with = before; - blend_into(&mut with, &clipped_iso, BlendMode::Normal, opacity); - for ((p, w), wo) in backdrop.px.iter_mut().zip(&with.px).zip(&without.px) { - let pa = p[3]; - let mut pm = [p[0] * pa, p[1] * pa, p[2] * pa, pa]; - for c in 0..3 { - pm[c] += w[c] * w[3] - wo[c] * wo[3]; - } - pm[3] += w[3] - wo[3]; - let a = pm[3].clamp(0.0, 1.0); - *p = if a > 0.0 { [(pm[0] / a).clamp(0.0, 1.0), (pm[1] / a).clamp(0.0, 1.0), (pm[2] / a).clamp(0.0, 1.0), a] } else { [0.0; 4] }; + let mut clipped_iso = alloc.clone(&iso)?; + advanced::composite_clipped_with(clipped, &mut clipped_iso, cx, alloc)?; + let mut without = alloc.clone(&before)?; + blend_into(&mut without, &iso, BlendMode::Normal, opacity); + let mut with = before; + blend_into(&mut with, &clipped_iso, BlendMode::Normal, opacity); + for ((p, w), wo) in backdrop.px.iter_mut().zip(&with.px).zip(&without.px) { + let pa = p[3]; + let mut pm = [p[0] * pa, p[1] * pa, p[2] * pa, pa]; + for c in 0..3 { + pm[c] += w[c] * w[3] - wo[c] * wo[3]; } + pm[3] += w[3] - wo[3]; + let a = pm[3].clamp(0.0, 1.0); + *p = if a > 0.0 { [(pm[0] / a).clamp(0.0, 1.0), (pm[1] / a).clamp(0.0, 1.0), (pm[2] / a).clamp(0.0, 1.0), a] } else { [0.0; 4] }; + } } return Ok(()); } @@ -606,13 +606,7 @@ type ShapeParts = (Buffer, Buffer, Option>); /// A stroked shape layer with visible clipped layers: Photoshop draws the shape's vector stroke /// above the clipped layers, so the base content is the fill alone and the stroke is laid on top /// after clipping. See [`split_parts_with`]. -fn shape_parts_with( - layer: &Layer, - clipped: &[Layer], - rect: Rect, - cx: &Ctx, - alloc: &A, -) -> Result, A::Error> { +fn shape_parts_with(layer: &Layer, clipped: &[Layer], rect: Rect, cx: &Ctx, alloc: &A) -> Result, A::Error> { if !clipped.iter().any(|c| c.visible) { return Ok(None); } From 4a83953fc4ed1a901cdd6854d1a776302c55c48d Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 00:29:44 -0800 Subject: [PATCH 40/46] Move fallible render tests after production items --- crates/compose/src/render.rs | 338 +++++++++++++++++------------------ 1 file changed, 169 insertions(+), 169 deletions(-) diff --git a/crates/compose/src/render.rs b/crates/compose/src/render.rs index 14983ed73a..a031536107 100644 --- a/crates/compose/src/render.rs +++ b/crates/compose/src/render.rs @@ -184,175 +184,6 @@ pub enum RenderBandsError { Sink(E), } -#[cfg(test)] -mod fallible_bands_tests { - use super::*; - use photocraft_color::{Color, ColorMode, SampleType}; - use photocraft_doc::{Document, Fill, Knockout, Layer, LayerContent}; - use photocraft_geom::Size; - use std::sync::atomic::{AtomicUsize, Ordering}; - - struct FailBufferAt { - fail_at: usize, - attempts: AtomicUsize, - } - - impl FailBufferAt { - fn attempt(&self) -> Result<(), usize> { - let n = self.attempts.fetch_add(1, Ordering::Relaxed) + 1; - if n == self.fail_at { Err(n) } else { Ok(()) } - } - } - - impl BufferAlloc for FailBufferAt { - type Error = usize; - - fn filled(&self, rect: Rect, color: [f32; 4]) -> Result { - self.attempt()?; - Buffer::try_filled(rect, color).map_err(|_| usize::MAX) - } - - fn clone(&self, buffer: &Buffer) -> Result { - self.attempt()?; - buffer.try_clone().map_err(|_| usize::MAX) - } - } - - fn nested_document() -> Document { - let mut doc = Document::new("fallible bands", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); - let mut fill = Layer::new("fill", LayerContent::Fill(Fill::Solid(Color::BLACK))); - fill.advanced.knockout = Knockout::Shallow; - doc.layers.push(Layer::group("nested", vec![fill])); - doc - } - - fn outlined_effect_document() -> Document { - let mut doc = Document::new("fallible outlined effect", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); - let path = photocraft_doc::vector::Path { - subpaths: vec![photocraft_doc::vector::Subpath::polygon(&[(12.0, 12.0), (60.0, 12.0), (60.0, 60.0), (12.0, 60.0)])], - ..Default::default() - }; - let mut cache = photocraft_doc::Surface::new(photocraft_color::PixelFormat::RGBA8); - cache.fill_rect(Rect::new(12, 12, 60, 60), &[0.0, 0.0, 0.0, 1.0]); - let shape = photocraft_doc::vector::ShapeLayer { path, fill: Some(Fill::Solid(Color::BLACK)), cache: Some(cache), ..Default::default() }; - let mut layer = Layer::new("outlined shape", LayerContent::Shape(shape)); - layer.effects.items.push(photocraft_doc::Effect::default_drop_shadow()); - doc.layers.push(layer); - doc - } - - #[test] - fn fail_nth_buffer_constructor_propagates_through_nested_rendering() { - let doc = nested_document(); - let rect = doc.bounds(); - let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); - let ctx = Ctx::for_doc(&doc, &patterns); - let count = { - let mut backdrop = Buffer::filled(rect, [0.0; 4]); - let alloc = FailBufferAt { fail_at: usize::MAX, attempts: AtomicUsize::new(0) }; - composite_stack_at_with(&doc.layers, &mut backdrop, &ctx, advanced::Scope::ROOT, &alloc).unwrap(); - alloc.attempts.load(Ordering::Relaxed) - }; - assert!(count >= 4, "nested shallow knockout exercises buffers and clones"); - for fail_at in 1..=count { - let mut backdrop = Buffer::filled(rect, [0.0; 4]); - let alloc = FailBufferAt { fail_at, attempts: AtomicUsize::new(0) }; - assert!(composite_stack_at_with(&doc.layers, &mut backdrop, &ctx, advanced::Scope::ROOT, &alloc).is_err()); - assert_eq!(alloc.attempts.load(Ordering::Relaxed), fail_at); - } - let regular = render_tiled(&doc, rect, 8); - let mut composited = Buffer::filled(rect, [0.0; 4]); - composite_stack_at_with(&doc.layers, &mut composited, &ctx, advanced::Scope::ROOT, &InfallibleBufferAlloc).unwrap(); - assert_eq!(composited, regular); - let alloc = FallibleBufferAlloc; - assert_eq!(render_tiled_with_alloc(&doc, rect, 8, &ctx, &alloc).unwrap(), regular); - } - - #[test] - fn render_bands_with_alloc_reports_outer_and_tile_allocations_before_the_sink() { - let doc = Document::new("fallible tile", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); - for fail_at in [1, 2] { - let alloc = FailBufferAt { fail_at, attempts: AtomicUsize::new(0) }; - let mut delivered = 0; - let result = render_bands_with_alloc(&doc, doc.bounds(), RENDER_TILE, &alloc, &mut |_| { - delivered += 1; - Ok::<(), ()>(()) - }); - assert!(matches!(result, Err(RenderBandsCoreError::Allocation(error)) if error == fail_at)); - assert_eq!(delivered, 0, "failed output or tile allocation must not deliver a partial band"); - if fail_at == 1 { - assert_eq!(alloc.attempts.load(Ordering::Relaxed), 1, "the output allocation is sequential"); - } else { - assert!(alloc.attempts.load(Ordering::Relaxed) >= 2, "parallel tile allocation may have other in-flight attempts"); - } - } - } - - #[test] - fn effect_shape_buffer_failure_is_not_cached_and_retry_uses_the_successful_cache() { - let mut doc = Document::new("fallible effect shape", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); - let fill = Layer::new("group fill", LayerContent::Fill(Fill::Solid(Color::BLACK))); - let mut layer = Layer::group("styled group", vec![fill]); - layer.effects.items.push(photocraft_doc::Effect::default_drop_shadow()); - doc.layers.push(layer); - let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); - let cx = Ctx::for_doc(&doc, &patterns); - - for _ in 0..2 { - let alloc = FailBufferAt { fail_at: 1, attempts: AtomicUsize::new(0) }; - let mut delivered = 0; - let result = render_bands_with_alloc(&doc, doc.bounds(), RENDER_TILE, &alloc, &mut |_| { - delivered += 1; - Ok::<(), ()>(()) - }); - assert!(matches!(result, Err(RenderBandsCoreError::Allocation(1)))); - assert_eq!(delivered, 0, "failed effect-shape allocation must happen before the sink"); - assert_eq!(alloc.attempts.load(Ordering::Relaxed), 1, "the cold effect shape requests an RGBA buffer before output"); - } - - let alloc = FallibleBufferAlloc; - render_tiled_with_alloc(&doc, doc.bounds(), RENDER_TILE, &cx, &alloc).unwrap(); - let cache_hit_alloc = FailBufferAt { fail_at: 1, attempts: AtomicUsize::new(0) }; - crate::fx_cache::effect_maps_with(&doc.layers[0], doc.bounds(), &cx, &cache_hit_alloc).unwrap(); - assert_eq!(cache_hit_alloc.attempts.load(Ordering::Relaxed), 0, "the successful render-context cache avoids rebuilding its RGBA shape"); - - let outlined = outlined_effect_document(); - let alloc = FailBufferAt { fail_at: 1, attempts: AtomicUsize::new(0) }; - let mut delivered = 0; - let result = render_bands_with_alloc(&outlined, outlined.bounds(), RENDER_TILE, &alloc, &mut |_| { - delivered += 1; - Ok::<(), ()>(()) - }); - assert!(matches!(result, Err(RenderBandsCoreError::Allocation(1)))); - assert_eq!(delivered, 0, "outline alpha extraction must use the fallible surface buffer path"); - } - - #[test] - fn fallible_bands_preserves_sink_errors_as_a_separate_variant() { - let doc = nested_document(); - let result = try_render_bands(&doc, doc.bounds(), 4, |_| Err::<(), _>("sink stopped")); - assert_eq!(result, Err(RenderBandsError::Sink("sink stopped"))); - } - - #[test] - fn legacy_and_fallible_band_apis_deliver_the_same_pixels() { - let doc = nested_document(); - let mut legacy = Vec::new(); - render_bands(&doc, doc.bounds(), 8, |band| { - legacy.push(band); - Ok::<(), ()>(()) - }) - .unwrap(); - let mut fallible = Vec::new(); - try_render_bands(&doc, doc.bounds(), 8, |band| { - fallible.push(band); - Ok::<(), ()>(()) - }) - .unwrap(); - assert_eq!(legacy, fallible); - } -} - enum RenderBandsCoreError { Allocation(A), Sink(E), @@ -606,3 +437,172 @@ pub fn composite_to_surface_with_interrupt( out.prune(); Ok(out) } + +#[cfg(test)] +mod fallible_bands_tests { + use super::*; + use photocraft_color::{Color, ColorMode, SampleType}; + use photocraft_doc::{Document, Fill, Knockout, Layer, LayerContent}; + use photocraft_geom::Size; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct FailBufferAt { + fail_at: usize, + attempts: AtomicUsize, + } + + impl FailBufferAt { + fn attempt(&self) -> Result<(), usize> { + let n = self.attempts.fetch_add(1, Ordering::Relaxed) + 1; + if n == self.fail_at { Err(n) } else { Ok(()) } + } + } + + impl BufferAlloc for FailBufferAt { + type Error = usize; + + fn filled(&self, rect: Rect, color: [f32; 4]) -> Result { + self.attempt()?; + Buffer::try_filled(rect, color).map_err(|_| usize::MAX) + } + + fn clone(&self, buffer: &Buffer) -> Result { + self.attempt()?; + buffer.try_clone().map_err(|_| usize::MAX) + } + } + + fn nested_document() -> Document { + let mut doc = Document::new("fallible bands", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); + let mut fill = Layer::new("fill", LayerContent::Fill(Fill::Solid(Color::BLACK))); + fill.advanced.knockout = Knockout::Shallow; + doc.layers.push(Layer::group("nested", vec![fill])); + doc + } + + fn outlined_effect_document() -> Document { + let mut doc = Document::new("fallible outlined effect", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); + let path = photocraft_doc::vector::Path { + subpaths: vec![photocraft_doc::vector::Subpath::polygon(&[(12.0, 12.0), (60.0, 12.0), (60.0, 60.0), (12.0, 60.0)])], + ..Default::default() + }; + let mut cache = photocraft_doc::Surface::new(photocraft_color::PixelFormat::RGBA8); + cache.fill_rect(Rect::new(12, 12, 60, 60), &[0.0, 0.0, 0.0, 1.0]); + let shape = photocraft_doc::vector::ShapeLayer { path, fill: Some(Fill::Solid(Color::BLACK)), cache: Some(cache), ..Default::default() }; + let mut layer = Layer::new("outlined shape", LayerContent::Shape(shape)); + layer.effects.items.push(photocraft_doc::Effect::default_drop_shadow()); + doc.layers.push(layer); + doc + } + + #[test] + fn fail_nth_buffer_constructor_propagates_through_nested_rendering() { + let doc = nested_document(); + let rect = doc.bounds(); + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + let ctx = Ctx::for_doc(&doc, &patterns); + let count = { + let mut backdrop = Buffer::filled(rect, [0.0; 4]); + let alloc = FailBufferAt { fail_at: usize::MAX, attempts: AtomicUsize::new(0) }; + composite_stack_at_with(&doc.layers, &mut backdrop, &ctx, advanced::Scope::ROOT, &alloc).unwrap(); + alloc.attempts.load(Ordering::Relaxed) + }; + assert!(count >= 4, "nested shallow knockout exercises buffers and clones"); + for fail_at in 1..=count { + let mut backdrop = Buffer::filled(rect, [0.0; 4]); + let alloc = FailBufferAt { fail_at, attempts: AtomicUsize::new(0) }; + assert!(composite_stack_at_with(&doc.layers, &mut backdrop, &ctx, advanced::Scope::ROOT, &alloc).is_err()); + assert_eq!(alloc.attempts.load(Ordering::Relaxed), fail_at); + } + let regular = render_tiled(&doc, rect, 8); + let mut composited = Buffer::filled(rect, [0.0; 4]); + composite_stack_at_with(&doc.layers, &mut composited, &ctx, advanced::Scope::ROOT, &InfallibleBufferAlloc).unwrap(); + assert_eq!(composited, regular); + let alloc = FallibleBufferAlloc; + assert_eq!(render_tiled_with_alloc(&doc, rect, 8, &ctx, &alloc).unwrap(), regular); + } + + #[test] + fn render_bands_with_alloc_reports_outer_and_tile_allocations_before_the_sink() { + let doc = Document::new("fallible tile", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); + for fail_at in [1, 2] { + let alloc = FailBufferAt { fail_at, attempts: AtomicUsize::new(0) }; + let mut delivered = 0; + let result = render_bands_with_alloc(&doc, doc.bounds(), RENDER_TILE, &alloc, &mut |_| { + delivered += 1; + Ok::<(), ()>(()) + }); + assert!(matches!(result, Err(RenderBandsCoreError::Allocation(error)) if error == fail_at)); + assert_eq!(delivered, 0, "failed output or tile allocation must not deliver a partial band"); + if fail_at == 1 { + assert_eq!(alloc.attempts.load(Ordering::Relaxed), 1, "the output allocation is sequential"); + } else { + assert!(alloc.attempts.load(Ordering::Relaxed) >= 2, "parallel tile allocation may have other in-flight attempts"); + } + } + } + + #[test] + fn effect_shape_buffer_failure_is_not_cached_and_retry_uses_the_successful_cache() { + let mut doc = Document::new("fallible effect shape", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); + let fill = Layer::new("group fill", LayerContent::Fill(Fill::Solid(Color::BLACK))); + let mut layer = Layer::group("styled group", vec![fill]); + layer.effects.items.push(photocraft_doc::Effect::default_drop_shadow()); + doc.layers.push(layer); + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + let cx = Ctx::for_doc(&doc, &patterns); + + for _ in 0..2 { + let alloc = FailBufferAt { fail_at: 1, attempts: AtomicUsize::new(0) }; + let mut delivered = 0; + let result = render_bands_with_alloc(&doc, doc.bounds(), RENDER_TILE, &alloc, &mut |_| { + delivered += 1; + Ok::<(), ()>(()) + }); + assert!(matches!(result, Err(RenderBandsCoreError::Allocation(1)))); + assert_eq!(delivered, 0, "failed effect-shape allocation must happen before the sink"); + assert_eq!(alloc.attempts.load(Ordering::Relaxed), 1, "the cold effect shape requests an RGBA buffer before output"); + } + + let alloc = FallibleBufferAlloc; + render_tiled_with_alloc(&doc, doc.bounds(), RENDER_TILE, &cx, &alloc).unwrap(); + let cache_hit_alloc = FailBufferAt { fail_at: 1, attempts: AtomicUsize::new(0) }; + crate::fx_cache::effect_maps_with(&doc.layers[0], doc.bounds(), &cx, &cache_hit_alloc).unwrap(); + assert_eq!(cache_hit_alloc.attempts.load(Ordering::Relaxed), 0, "the successful render-context cache avoids rebuilding its RGBA shape"); + + let outlined = outlined_effect_document(); + let alloc = FailBufferAt { fail_at: 1, attempts: AtomicUsize::new(0) }; + let mut delivered = 0; + let result = render_bands_with_alloc(&outlined, outlined.bounds(), RENDER_TILE, &alloc, &mut |_| { + delivered += 1; + Ok::<(), ()>(()) + }); + assert!(matches!(result, Err(RenderBandsCoreError::Allocation(1)))); + assert_eq!(delivered, 0, "outline alpha extraction must use the fallible surface buffer path"); + } + + #[test] + fn fallible_bands_preserves_sink_errors_as_a_separate_variant() { + let doc = nested_document(); + let result = try_render_bands(&doc, doc.bounds(), 4, |_| Err::<(), _>("sink stopped")); + assert_eq!(result, Err(RenderBandsError::Sink("sink stopped"))); + } + + #[test] + fn legacy_and_fallible_band_apis_deliver_the_same_pixels() { + let doc = nested_document(); + let mut legacy = Vec::new(); + render_bands(&doc, doc.bounds(), 8, |band| { + legacy.push(band); + Ok::<(), ()>(()) + }) + .unwrap(); + let mut fallible = Vec::new(); + try_render_bands(&doc, doc.bounds(), 8, |band| { + fallible.push(band); + Ok::<(), ()>(()) + }) + .unwrap(); + assert_eq!(legacy, fallible); + } +} From 9be5842ab6867b1a27ec1a13e6e3e703595d3cde Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 01:34:16 -0800 Subject: [PATCH 41/46] Fix WASM compositor chunk borrow ordering --- crates/compose/src/native.rs | 7 +++++-- crates/compose/src/native_lab.rs | 7 +++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/compose/src/native.rs b/crates/compose/src/native.rs index c605e4c948..b5e05e49c6 100644 --- a/crates/compose/src/native.rs +++ b/crates/compose/src/native.rs @@ -322,8 +322,11 @@ pub(crate) fn render_cmyk_with(doc: &Document, rect: Rect out.px.par_chunks_mut(chunk_len).enumerate().for_each(|(i, px)| band(i, px)); } #[cfg(target_arch = "wasm32")] - for (i, px) in out.px.chunks_mut(w.saturating_mul(rows).min(out.px.len()).max(1)).enumerate() { - band(i, px); + { + let chunk_len = w.saturating_mul(rows).min(out.px.len()).max(1); + for (i, px) in out.px.chunks_mut(chunk_len).enumerate() { + band(i, px); + } } Ok(Some(out)) } diff --git a/crates/compose/src/native_lab.rs b/crates/compose/src/native_lab.rs index a59c634131..49ae62e405 100644 --- a/crates/compose/src/native_lab.rs +++ b/crates/compose/src/native_lab.rs @@ -260,8 +260,11 @@ pub(crate) fn render_lab_with(doc: &Document, rect: Rect, out.px.par_chunks_mut(chunk_len).enumerate().for_each(|(i, px)| band(i, px)); } #[cfg(target_arch = "wasm32")] - for (i, px) in out.px.chunks_mut(w.saturating_mul(rows).min(out.px.len()).max(1)).enumerate() { - band(i, px); + { + let chunk_len = w.saturating_mul(rows).min(out.px.len()).max(1); + for (i, px) in out.px.chunks_mut(chunk_len).enumerate() { + band(i, px); + } } Ok(Some(out)) } From 47eaef2f512caeda2f78c75dd4602a1599dcaaf3 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 01:52:40 -0800 Subject: [PATCH 42/46] Use explicit preset-store imports in the Web bridge --- apps/photocraft-web/src/preset_bridge.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/photocraft-web/src/preset_bridge.rs b/apps/photocraft-web/src/preset_bridge.rs index 51ab9a23c5..dd390f7a7b 100644 --- a/apps/photocraft-web/src/preset_bridge.rs +++ b/apps/photocraft-web/src/preset_bridge.rs @@ -6,7 +6,7 @@ use std::sync::{Arc, Mutex, MutexGuard}; use photocraft_engine::{ Session, actions_cmds::{ActionState, ActionsFile, is_action_key}, - preset_store::{self, PresetBackend, *}, + preset_store::{self, PresetBackend, MAX_GROUPS, MAX_PRESETS_PER_GROUP, INDEX_FILE, MAX_INDEX_BYTES, ACTIONS_FILE, MAX_ACTIONS_BYTES, PATTERNS_FILE, MAX_PATTERNS_BYTES, MAX_TIP_BYTES, MAX_GROUP_BYTES, MAX_STORE_BYTES}, }; use serde_json::{Value, json}; From 4f0cbe7477c4f6f029a98836612d897f9ec33a93 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 01:57:45 -0800 Subject: [PATCH 43/46] Format compositor test placement --- apps/photocraft-web/src/preset_bridge.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/photocraft-web/src/preset_bridge.rs b/apps/photocraft-web/src/preset_bridge.rs index dd390f7a7b..99f6841e34 100644 --- a/apps/photocraft-web/src/preset_bridge.rs +++ b/apps/photocraft-web/src/preset_bridge.rs @@ -6,7 +6,10 @@ use std::sync::{Arc, Mutex, MutexGuard}; use photocraft_engine::{ Session, actions_cmds::{ActionState, ActionsFile, is_action_key}, - preset_store::{self, PresetBackend, MAX_GROUPS, MAX_PRESETS_PER_GROUP, INDEX_FILE, MAX_INDEX_BYTES, ACTIONS_FILE, MAX_ACTIONS_BYTES, PATTERNS_FILE, MAX_PATTERNS_BYTES, MAX_TIP_BYTES, MAX_GROUP_BYTES, MAX_STORE_BYTES}, + preset_store::{ + self, ACTIONS_FILE, INDEX_FILE, MAX_ACTIONS_BYTES, MAX_GROUP_BYTES, MAX_GROUPS, MAX_INDEX_BYTES, MAX_PATTERNS_BYTES, MAX_PRESETS_PER_GROUP, + MAX_STORE_BYTES, MAX_TIP_BYTES, PATTERNS_FILE, PresetBackend, + }, }; use serde_json::{Value, json}; From f95c65faa5b583b505d3bf043a6d2edb79e33137 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 02:51:23 -0800 Subject: [PATCH 44/46] Restore accepted brush sampling and fallible outside stroke accumulation --- crates/compose/src/effects/composite.rs | 67 ++- crates/engine/src/cmd/brush_cmds.rs | 54 ++- .../define_brush_color_density_tests.rs | 327 ++++++++++++++ .../define_brush_merged_source_tests.rs | 420 ++++++++++++------ .../define_brush_no_selection_tests.rs | 235 ++++++++++ crates/engine/src/cmd/edit_menu_cmds/tests.rs | 2 +- 6 files changed, 939 insertions(+), 166 deletions(-) create mode 100644 crates/engine/src/cmd/brush_cmds/define_brush_color_density_tests.rs create mode 100644 crates/engine/src/cmd/brush_cmds/define_brush_no_selection_tests.rs diff --git a/crates/compose/src/effects/composite.rs b/crates/compose/src/effects/composite.rs index 91851b2aa5..565cfa2f47 100644 --- a/crates/compose/src/effects/composite.rs +++ b/crates/compose/src/effects/composite.rs @@ -633,7 +633,7 @@ impl<'a> EffectPass<'a> { } let (w, h) = (self.w, self.h); let base = alloc.clone(work)?; - let mut acc = vec![[0.0f32; 4]; w * h]; // premultiplied Σ share·blended + let mut acc = alloc.filled(self.big, [0.0; 4])?; // premultiplied Σ share·blended let mut cover = vec![0.0f32; w * h]; for st in strokes.iter().copied() { let (_, out_w) = stroke_widths(st); @@ -647,7 +647,7 @@ impl<'a> EffectPass<'a> { // The share already carries the Dissolve choice, so the paint itself composites as Normal. let paint_blend = if st.common.blend == BlendMode::Dissolve { BlendMode::Normal } else { st.common.blend }; paint_fx(&mut blended, &ones, &st.paint, self.stroke_frame(st), self.anchor, self.big, paint_blend, 1.0, self.patterns); - for ((a, b), s) in acc.iter_mut().zip(&blended.px).zip(&share) { + for ((a, b), s) in acc.px.iter_mut().zip(&blended.px).zip(&share) { if *s > 0.0 { for c in 0..3 { a[c] += s * b[c] * b[3]; @@ -656,7 +656,7 @@ impl<'a> EffectPass<'a> { } } } - for ((p, a), c) in work.px.iter_mut().zip(&acc).zip(&cover) { + for ((p, a), c) in work.px.iter_mut().zip(&acc.px).zip(&cover) { if *c <= 0.0 { continue; } @@ -790,3 +790,64 @@ fn mix_premul(a: [f32; 4], b: [f32; 4], k: f32) -> [f32; 4] { out[3] = alpha; out } + +#[cfg(test)] +mod outside_stroke_allocation_tests { + use super::*; + use photocraft_color::{Color, PixelFormat}; + use photocraft_doc::{FxCommon, StrokeFx}; + + struct RejectFilled; + + impl BufferAlloc for RejectFilled { + type Error = &'static str; + + fn filled(&self, _rect: Rect, _color: [f32; 4]) -> Result { + Err("outside stroke accumulator") + } + + fn clone(&self, buffer: &Buffer) -> Result { + buffer.try_clone().map_err(|_| "clone allocation") + } + } + + #[test] + fn enabled_outside_stroke_accumulator_propagates_allocation_failure_and_preserves_pixels() { + let rect = Rect::new(0, 0, 4, 4); + let mut layer = Layer::raster("outside stroke", PixelFormat::RGBA8); + layer.effects.items.push(Effect::Stroke(StrokeFx { + common: FxCommon::new(BlendMode::Normal, 1.0), + size: 1.0, + position: StrokePosition::Outside, + paint: FxPaint::Color(Color::rgb(0.0, 0.0, 1.0)), + overprint: false, + })); + let mut shape = Map::new(4, 4, 0.0); + for (index, value) in shape.v.iter_mut().enumerate() { + if matches!(index, 5 | 6 | 9 | 10) { + *value = 1.0; + } + } + let patterns = PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES); + let texture = TextureCtx { rect, patterns: &[], anchor: (0.0, 0.0) }; + let maps = build_maps(&layer, shape.v.clone(), rect, &GlobalLight::default(), &texture); + let pass = EffectPass::new(&layer, &maps, rect, rect, &patterns, None); + let strokes: Vec<_> = layer.effects.items.iter().filter_map(|effect| if let Effect::Stroke(stroke) = effect { Some(stroke) } else { None }).collect(); + assert!(strokes.iter().any(|stroke| stroke_widths(stroke).1 > 0.0)); + let fields = pass.stroke_fields(true); + let mut lay = Buffer::filled(rect, [0.0; 4]); + for (pixel, alpha) in lay.px.iter_mut().zip(&shape.v) { + pixel[3] = *alpha; + } + let original = Buffer::filled(rect, [1.0; 4]); + let mut failed = original.clone(); + assert_eq!(pass.paint_outside_strokes_with(&mut failed, &lay, &shape, &strokes, &fields, &RejectFilled), Err("outside stroke accumulator")); + assert_eq!(failed, original, "a rejected accumulator cannot publish partial stroke pixels"); + let mut legacy = original.clone(); + pass.paint_outside_strokes_with(&mut legacy, &lay, &shape, &strokes, &fields, &InfallibleBufferAlloc).unwrap(); + let mut fallible = original.clone(); + pass.paint_outside_strokes_with(&mut fallible, &lay, &shape, &strokes, &fields, &crate::FallibleBufferAlloc).unwrap(); + assert_ne!(legacy, original, "the enabled outside stroke must actually paint"); + assert_eq!(fallible, legacy); + } +} diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 04ddf2a544..f17b5b28b4 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -1066,13 +1066,7 @@ fn presets_set_current(s: &mut Session, p: &Value) -> Result { } fn has_selection_and_pixels(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or("no document")?; - if d.doc.selection.is_none() { - return Err("no selection".into()); - } - if d.active_layer.and_then(|id| d.doc.layer(id)).is_none() { - return Err("no active layer".into()); - } + s.active().ok_or("no document")?; Ok(()) } @@ -1095,8 +1089,8 @@ fn define_from_selection_with_renderer( let cmd = "brush.defineFromSelection"; let name = name_param(p, cmd)?; let d = s.active().ok_or(EngineError::NoDocument)?; - let sel = d.doc.selection.as_ref().ok_or_else(|| bad(cmd, "no selection"))?; - let area = sel.content_bounds().intersect(&d.doc.bounds()); + let sel = d.doc.selection.as_ref(); + let area = sel.map_or_else(|| d.doc.bounds(), |sel| sel.content_bounds().intersect(&d.doc.bounds())); if area.is_empty() { return Err(bad(cmd, "the selection is empty")); } @@ -1110,7 +1104,7 @@ fn define_from_selection_with_renderer( // Sparse canvases can span huge areas. Density and selection remain live while the // compositor holds one RGBA band, not a full-canvas RGBA plane; account for that // actual maximum band before allocating any sampling buffers. - let mask_bytes = (sel.channels() as u64).saturating_mul(4); + let mask_bytes = sel.map_or(0, |sel| (sel.channels() as u64).saturating_mul(4)); let band_rows = area.height().min(photocraft_compose::band_rows_for(area.width(), 0) as u32); let band_bytes = u64::from(area.width()).saturating_mul(u64::from(band_rows)).saturating_mul(16); let dense_bytes = (len as u64).saturating_mul(4u64.saturating_add(mask_bytes)).saturating_add(band_bytes); @@ -1124,15 +1118,28 @@ fn define_from_selection_with_renderer( ))); } let mut v = crate::allocation::filled(len, 0.0, "defining a brush from the selection")?; - let sc = sel.channels(); + let sc = sel.map_or(1, |sel| sel.channels()); // A selection mask, when present, is a second buffer of the same size; it must fail gracefully too // (review of #5469), so read it through the fallible allocator. - let sv = crate::allocation::read_region(sel, area, "defining a brush from the selection")?; + let sv = sel.map(|sel| crate::allocation::read_region(sel, area, "defining a brush from the selection")).transpose()?; + // The compositor keeps RGB document encoding; other document models produce + // the existing RGB numeric view (including the document-profile CMYK conversion). + let source = if d.doc.mode == photocraft_color::ColorMode::Rgb { + crate::color_cmds::document_profile(&d.doc) + } else { + crate::color_cmds::working_profile(photocraft_color::ColorMode::Rgb) + }; + let options = craft_cms::TransformOptions { intent: craft_cms::Intent::RelativeColorimetric, bpc: true, ..Default::default() }; + let gray = + craft_cms::cached(&source, craft_cms::Builtin::SGray.profile(), options).map_err(|e| bad(cmd, format!("cannot convert brush source to gray: {e}")))?; + let mut converted = [0.0f32; 16]; + // Keep the allocation boundary fallible before entering compositor-owned scratch storage. + crate::allocation::checkpoint("defining a brush from the selection")?; let rendered = render(&d.doc, area, &mut |band| -> Result<()> { for (row, pixels) in band.px.chunks_exact(w).enumerate() { let y = (band.rect.y0 - area.y0) as usize + row; for (x, c) in pixels.iter().enumerate() { - let selected = sv[(y * w + x) * sc]; + let selected = sv.as_ref().map_or(1.0, |sv| sv[(y * w + x) * sc]); // Known-zero contributions leave the freshly zeroed density alone. if selected == 0.0 { continue; @@ -1140,8 +1147,19 @@ fn define_from_selection_with_renderer( if c[3] == 0.0 { continue; } - let lum = photocraft_color::blend::lum([c[0], c[1], c[2]]); - v[y * w + x] = ((1.0 - lum) * c[3] * selected).clamp(0.0, 1.0); + // A sampled profile curve can clamp infinity to a finite endpoint; + // reject contributing invalid source values before the CMS can hide them. + if c.iter().any(|channel| !channel.is_finite()) { + return Err(bad(cmd, "brush source contains a non-finite colour channel")); + } + // Composite over white before the nonlinear gray conversion. The + // selection scales the resulting density once; alpha is already in it. + let over_white = [c[0], c[1], c[2]].map(|channel| channel * c[3] + (1.0 - c[3])); + gray.eval(&over_white, &mut converted).map_err(|e| bad(cmd, format!("cannot convert brush source to gray: {e}")))?; + if !converted[0].is_finite() { + return Err(bad(cmd, "brush source converted to a non-finite gray value")); + } + v[y * w + x] = ((1.0 - converted[0]) * selected).clamp(0.0, 1.0); } } Ok(()) @@ -1537,3 +1555,9 @@ mod color_replacement_history_name_tests; #[cfg(test)] mod define_brush_merged_source_tests; + +#[cfg(test)] +mod define_brush_no_selection_tests; + +#[cfg(test)] +mod define_brush_color_density_tests; diff --git a/crates/engine/src/cmd/brush_cmds/define_brush_color_density_tests.rs b/crates/engine/src/cmd/brush_cmds/define_brush_color_density_tests.rs new file mode 100644 index 0000000000..44cd5e052a --- /dev/null +++ b/crates/engine/src/cmd/brush_cmds/define_brush_color_density_tests.rs @@ -0,0 +1,327 @@ +//! Numeric falsifier for issue #14273; this does not change brush capture. +//! +//! Inputs are encoded sRGB RGB8 samples, composited over encoded white before +//! the cached sRGB -> sGray transform. Density is one minus encoded gray, then +//! multiplied by selection coverage exactly once. Arbitrary document profiles, +//! HDR/non-RGB sources and actual stamping remain outside this probe. + +use std::sync::Arc; + +use craft_cms::{Builtin, Intent, TransformOptions}; + +#[test] +fn sgray_matches_six_literal_density_targets_and_alpha_selection_controls() { + let source = Arc::new(Builtin::Srgb.profile().clone()); + let gray = Arc::new(Builtin::SGray.profile().clone()); + let options = TransformOptions { intent: Intent::RelativeColorimetric, bpc: true, ..Default::default() }; + let transform = craft_cms::cached(&source, &gray, options).unwrap(); + let gray_value = |rgb: [f32; 3]| { + // Same public API and output scratch size as color_cmds::swatch_in_doc. + let mut output = [0.0f32; 16]; + transform.eval(&rgb, &mut output).unwrap(); + assert!(output[0].is_finite(), "the CMS must return a finite gray value"); + output[0].clamp(0.0, 1.0) + }; + let density = |rgb: [f32; 3], alpha: f32, selection: f32| { + let over_white = rgb.map(|channel| channel * alpha + (1.0 - alpha)); + (1.0 - gray_value(over_white)) * selection + }; + + // Independent measured targets from #14273, not values derived from the + // candidate transform or the command's existing fixed luminance weights. + let mut mismatches = Vec::new(); + for (name, rgb, expected, tolerance) in [ + ("red", [255u8, 0, 0], 0.49f32, 0.03f32), + ("green", [0, 255, 0], 0.14, 0.03), + ("blue", [0, 0, 255], 0.72, 0.03), + ("gray 128", [128, 128, 128], 0.50, 0.01), + ("gray 200", [200, 200, 200], 0.22, 0.01), + ("black", [0, 0, 0], 1.0, 0.0001), + ] { + let actual = density(rgb.map(|value| f32::from(value) / 255.0), 1.0, 1.0); + eprintln!("{name}: density {actual:.6}, target {expected:.6} +/- {tolerance:.6}"); + if (actual - expected).abs() > tolerance { + mismatches.push(format!("{name}: {actual:.6}, expected {expected:.6} +/- {tolerance:.6}")); + } + } + assert!(mismatches.is_empty(), "sGray candidate fails measured targets:\n{}", mismatches.join("\n")); + + // Transparency is white, not an extra multiplier applied after the CMS. + assert!(density([0.0, 0.0, 1.0], 0.0, 1.0).abs() <= 0.0001); + assert!((density([0.0; 3], 0.5, 1.0) - 0.5).abs() <= 0.01); + assert!((density([0.0; 3], 1.0, 0.25) - 0.25).abs() <= 0.0001); + assert!((density([0.0; 3], 0.5, 0.5) - 0.25).abs() <= 0.01, "alpha or selection must not be applied twice"); + assert_eq!(density([1.0, 0.0, 0.0], 1.0, 0.0), 0.0); + + // This is an ordering control, not a new measured coloured-alpha target: + // half-transparent red is the explicit RGB sample [1, .5, .5] over white. + let half_red = density([1.0, 0.0, 0.0], 0.5, 1.0); + let explicit_over_white = 1.0 - gray_value([1.0, 0.5, 0.5]); + assert_eq!(half_red, explicit_over_white); +} + +use super::{GrayTile, Session, TipShape, json}; + +const COMMANDS: [&str; 2] = ["brush.defineFromSelection", "edit.defineBrushPreset"]; + +fn rgb_source(depth: u32, rgba: [f32; 4]) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth, "background": "#ffffff"})).unwrap(); + s.edit("Colour square", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 10, 30, 30), &rgba); + Ok(()) + }) + .unwrap(); + s +} + +fn tip(s: &Session) -> &GrayTile { + let TipShape::Sampled(tip) = &s.tools.brush.tip else { panic!("expected a sampled tip") }; + tip +} + +fn define_square(s: &mut Session, command: &str, selected: bool) -> f32 { + if selected { + s.execute("select.rect", json!({"x": 8, "y": 8, "width": 24, "height": 24})).unwrap(); + } + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let presets = s.tools.presets.len(); + let result = s.execute(command, json!({"name": "Colour density"})).unwrap(); + assert_eq!((result["width"].as_u64(), result["height"].as_u64()), (Some(20), Some(20))); + assert_eq!((tip(s).width, tip(s).height), (20, 20)); + assert_eq!(s.tools.presets.len(), presets + 1); + assert_eq!(s.tools.current_preset.as_deref(), Some("Colour density")); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.active().unwrap().history.past_len(), history); + assert_eq!(s.active().unwrap().doc.selection.is_some(), selected); + tip(s).get(10, 10) +} + +#[test] +fn defined_tips_match_the_six_measured_density_targets_at_all_depths() { + for command in COMMANDS { + for depth in [8, 16, 32] { + for selected in [false, true] { + for (name, rgb, expected, tolerance) in [ + ("red", [255u8, 0, 0], 0.49f32, 0.03f32), + ("green", [0, 255, 0], 0.14, 0.03), + ("blue", [0, 0, 255], 0.72, 0.03), + ("gray 128", [128, 128, 128], 0.50, 0.01), + ("gray 200", [200, 200, 200], 0.22, 0.01), + ("black", [0, 0, 0], 1.0, 0.0001), + ] { + let [r, g, b] = rgb.map(|v| f32::from(v) / 255.0); + let mut s = rgb_source(depth, [r, g, b, 1.0]); + let actual = define_square(&mut s, command, selected); + assert!((actual - expected).abs() <= tolerance, "{command}, {name}, depth {depth}, selected {selected}: {actual}"); + } + } + } + } +} + +#[test] +fn command_density_applies_alpha_before_gray_and_selection_once() { + for command in COMMANDS { + for (alpha, coverage, expected) in [(0.5, 1.0, 0.5), (1.0, 0.25, 0.25), (0.5, 0.5, 0.25)] { + let mut s = rgb_source(32, [0.0, 0.0, 0.0, alpha]); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.edit("Selection coverage", |doc, _| { + doc.selection.as_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 10, 30, 30), &[coverage]); + Ok(()) + }) + .unwrap(); + s.execute(command, json!({"name": "Coverage"})).unwrap(); + assert!((tip(&s).get(10, 10) - expected).abs() <= 0.01, "{command}, alpha {alpha}, coverage {coverage}"); + } + + // An explicit over-white RGB square is an independent way to provide the + // same colour; this is an ordering control, not a new reference target. + let mut half_red = rgb_source(32, [1.0, 0.0, 0.0, 0.5]); + let mut over_white = rgb_source(32, [1.0, 0.5, 0.5, 1.0]); + let half = define_square(&mut half_red, command, false); + let opaque = define_square(&mut over_white, command, false); + assert!((half - opaque).abs() <= 1.0 / 65535.0); + + let mut transparent = rgb_source(32, [0.0, 0.0, 1.0, 0.0]); + let brush = transparent.tools.brush.clone(); + let presets = transparent.tools.presets.clone(); + let err = transparent.execute(command, json!({"name": "Transparent colour"})).unwrap_err(); + assert!(err.to_string().contains("contain no paint"), "{err}"); + assert_eq!(transparent.tools.brush, brush); + assert_eq!(transparent.tools.presets, presets); + } +} + +#[test] +fn tagged_rgb_uses_the_document_encoding() { + for command in COMMANDS { + let mut tagged = rgb_source(32, [0.5, 0.5, 0.5, 1.0]); + tagged + .edit("Assign linear RGB", |doc, _| { + doc.icc_profile = Some(Builtin::LinearSrgb.profile().to_bytes()); + Ok(()) + }) + .unwrap(); + let explicit = craft_cms::cached(Builtin::LinearSrgb.profile(), Builtin::SGray.profile(), TransformOptions::default()).unwrap(); + let mut gray = [0.0f32; 16]; + explicit.eval(&[0.5, 0.5, 0.5], &mut gray).unwrap(); + let actual = define_square(&mut tagged, command, false); + assert!((actual - (1.0 - gray[0])).abs() <= 1.0 / 65535.0); + + let mut srgb = rgb_source(32, [0.5, 0.5, 0.5, 1.0]); + let untagged = define_square(&mut srgb, command, false); + assert!((actual - untagged).abs() > 0.1, "the fixture must distinguish profile encoding"); + } +} + +#[test] +fn native_gray_keeps_numeric_density_in_its_existing_rgb_view() { + for command in COMMANDS { + for depth in [8, 16, 32] { + for profile in [None, Some(Builtin::DotGain20Compat), Some(Builtin::GrayGamma22)] { + for value in [128.0 / 255.0, 200.0 / 255.0, 0.0] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 40, "mode": "gray", "depth": depth, "background": "white"})).unwrap(); + s.edit("Native gray square", |doc, active| { + doc.icc_profile = profile.map(|p| p.profile().to_bytes()); + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 10, 30, 30), &[value, 1.0]); + Ok(()) + }) + .unwrap(); + let actual = define_square(&mut s, command, false); + assert!((actual - (1.0 - value)).abs() <= 0.0001, "{command}, depth {depth}, profile {profile:?}, value {value}: {actual}"); + } + } + } + } +} + +#[test] +fn zero_alpha_and_zero_selection_skip_hidden_colour() { + for command in COMMANDS { + for transparent in [true, false] { + for rgb in [[0.0, 0.0, 1.0], [f32::NAN, f32::INFINITY, f32::NEG_INFINITY]] { + let mut s = rgb_source(32, [0.0, 0.0, 0.0, 1.0]); + let hole = photocraft_geom::Rect::new(15, 15, 25, 25); + s.edit("Hidden colour", |doc, active| { + let alpha = if transparent { 0.0 } else { 1.0 }; + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(hole, &[rgb[0], rgb[1], rgb[2], alpha]); + Ok(()) + }) + .unwrap(); + let st = s.active().unwrap(); + let stored = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(20, 20); + assert_eq!(stored[3], if transparent { 0.0 } else { 1.0 }); + for channel in 0..3 { + if rgb[channel].is_nan() { + assert!(stored[channel].is_nan(), "the non-finite fixture must reach the source read"); + } else { + assert_eq!(stored[channel], rgb[channel]); + } + } + if !transparent { + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.edit("Zero coverage hole", |doc, _| { + doc.selection.as_mut().unwrap().fill_rect(hole, &[0.0]); + Ok(()) + }) + .unwrap(); + // The hole stays inside the sampled area, rather than being + // removed by selection bounds before the per-pixel check. + assert_eq!(s.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(), photocraft_geom::Rect::new(10, 10, 30, 30)); + } + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let presets = s.tools.presets.len(); + + let made = s.execute(command, json!({"name": "Visible black border"})).unwrap(); + + assert_eq!((made["width"].as_u64(), made["height"].as_u64()), (Some(20), Some(20))); + assert_eq!(tip(&s).get(0, 0), 1.0); + assert_eq!(tip(&s).get(19, 19), 1.0); + assert_eq!(tip(&s).get(5, 5), 0.0, "hidden colour contributes no paint"); + assert_eq!(tip(&s).get(14, 14), 0.0); + assert_eq!(s.tools.presets.len(), presets + 1); + assert_eq!(s.tools.current_preset.as_deref(), Some("Visible black border")); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.active().unwrap().history.past_len(), history); + } + } + } +} + +#[test] +fn sampled_trcs_cannot_hide_non_finite_contributing_channels() { + let mut profile = Builtin::Srgb.profile().clone(); + profile.trc = profile.trc.take().map(|curves| curves.map(|curve| craft_cms::Curve::Table(curve.sample(256)))); + // Reset the built-in's encoded bytes and cache key after replacing its curves. + let icc = profile.with_encoded_bytes().to_bytes(); + let parsed = craft_cms::Profile::parse(&icc).unwrap(); + assert!(parsed.trc.as_ref().unwrap().iter().all(|curve| matches!(curve, craft_cms::Curve::Table(_)))); + let options = TransformOptions { intent: Intent::RelativeColorimetric, bpc: true, ..Default::default() }; + let gray = craft_cms::cached(&parsed, Builtin::SGray.profile(), options).unwrap(); + let mut converted = [0.0f32; 16]; + gray.eval(&[f32::INFINITY, 0.0, 0.0], &mut converted).unwrap(); + assert!(converted[0].is_finite(), "the sampled-TRC fixture must expose clamping before the command's gray check"); + + for command in COMMANDS { + for selected in [false, true] { + let mut finite = rgb_source(32, [1.0, 0.0, 0.0, 1.0]); + finite + .edit("Assign sampled sRGB", |doc, _| { + doc.icc_profile = Some(icc.clone()); + Ok(()) + }) + .unwrap(); + assert!((define_square(&mut finite, command, selected) - 0.49).abs() <= 0.03); + + for rgba in [ + [f32::INFINITY, 0.0, 0.0, 1.0], + [0.0, f32::INFINITY, 0.0, 1.0], + [0.0, 0.0, f32::INFINITY, 1.0], + [0.0, 0.0, 0.0, f32::INFINITY], + [f32::NAN, 0.0, 0.0, 1.0], + [f32::NEG_INFINITY, 0.0, 0.0, 1.0], + ] { + let mut s = rgb_source(32, rgba); + s.edit("Assign sampled sRGB", |doc, _| { + doc.icc_profile = Some(icc.clone()); + Ok(()) + }) + .unwrap(); + if selected { + s.execute("select.rect", json!({"x": 8, "y": 8, "width": 24, "height": 24})).unwrap(); + } + // An accepted invalid source would replace this existing preset. + s.execute("brush.presets.save", json!({"name": "Kept preset"})).unwrap(); + let active = s.active().unwrap().active_layer.unwrap(); + let stored = s.active().unwrap().doc.layer(active).unwrap().surface().unwrap().rgba(20, 20).map(f32::to_bits); + assert_eq!(stored, rgba.map(f32::to_bits), "non-finite values must reach the source read unchanged"); + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let brush = s.tools.brush.clone(); + let presets = s.tools.presets.clone(); + let current = s.tools.current_preset.clone(); + let revision = s.tools.brush_rev; + let journal = s.journal.clone(); + + let error = s.execute(command, json!({"name": "Kept preset"})).unwrap_err(); + + assert!(error.to_string().contains("non-finite"), "{command}: {error}"); + assert!(Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.active().unwrap().history.past_len(), history); + assert_eq!(s.active().unwrap().active_layer, Some(active)); + assert_eq!(s.active().unwrap().doc.selection.is_some(), selected); + assert_eq!(s.active().unwrap().doc.icc_profile.as_ref(), Some(&icc)); + assert_eq!(s.active().unwrap().doc.layer(active).unwrap().surface().unwrap().rgba(20, 20).map(f32::to_bits), stored); + assert_eq!(s.tools.brush, brush); + assert_eq!(s.tools.presets, presets); + assert_eq!(s.tools.current_preset, current); + assert_eq!(s.tools.brush_rev, revision); + assert_eq!(s.journal, journal); + } + } + } +} diff --git a/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs b/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs index f9bfd4dfe4..bb3ee38ea6 100644 --- a/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs +++ b/crates/engine/src/cmd/brush_cmds/define_brush_merged_source_tests.rs @@ -23,7 +23,7 @@ fn source(depth: u32) -> Session { } #[test] -fn selected_visible_capture_is_identical_with_background_tip_group() { +fn visible_capture_is_identical_with_background_tip_group_or_no_active_layer() { for command in COMMANDS { for depth in [8, 16, 32] { let mut s = source(depth); @@ -31,9 +31,8 @@ fn selected_visible_capture_is_identical_with_background_tip_group() { let painted = s.active().unwrap().active_layer.unwrap(); s.execute("layer.new.group", json!({"name": "Empty active group"})).unwrap(); let group = s.active().unwrap().active_layer.unwrap(); - s.execute("select.rect", json!({"x": 50, "y": 40, "width": 100, "height": 50})).unwrap(); let mut expected = None; - for active in [Some(background), Some(painted), Some(group)] { + for active in [Some(background), Some(painted), Some(group), None] { s.edit("Choose capture-independent active layer", |_, current| { *current = active; Ok(()) @@ -80,6 +79,277 @@ fn selection_limits_the_visible_composite_even_with_background_active() { } } +#[test] +fn visible_group_children_and_occlusion_count_but_hidden_layers_and_groups_do_not() { + for command in COMMANDS { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + s.edit("Visible and hidden composite contributors", |doc, active| { + let mut black = Layer::raster("Nested visible black", doc.pixel_format()); + black.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 5, 5), &[0.0, 0.0, 0.0, 1.0]); + let visible = Layer::group("Visible group", vec![black]); + let mut hidden_black = Layer::raster("Hidden black", doc.pixel_format()); + hidden_black.surface_mut().unwrap().fill_rect(doc.bounds(), &[0.0, 0.0, 0.0, 1.0]); + hidden_black.visible = false; + let mut hidden_group = Layer::group("Hidden ancestor", vec![hidden_black.duplicate()]); + hidden_group.children_mut().unwrap()[0].visible = true; + hidden_group.visible = false; + let mut white = Layer::raster("Visible white occlusion", doc.pixel_format()); + white.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 3, 5), &[1.0, 1.0, 1.0, 1.0]); + *active = Some(hidden_black.id); + doc.layers.extend([visible, hidden_black, hidden_group, white]); + Ok(()) + }) + .unwrap(); + s.execute(command, json!({"name": "Only visible ink"})).unwrap(); + assert_eq!((tip(&s).width, tip(&s).height), (2, 4)); + for y in 0..4 { + for x in 0..2 { + assert_eq!(tip(&s).get(x, y), 1.0); + } + } + } +} + +#[test] +fn composite_transparency_and_selection_coverage_are_applied_once() { + for command in COMMANDS { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth, "background": "transparent"})).unwrap(); + s.edit("Nested translucent source", |doc, active| { + let mut black = Layer::raster("Half black", doc.pixel_format()); + black.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 6, 7), &[0.0, 0.0, 0.0, 0.5]); + let group = Layer::group("Active group", vec![black]); + *active = Some(group.id); + doc.layers.push(group); + Ok(()) + }) + .unwrap(); + for selected in [false, true] { + if selected { + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + s.edit("Quarter coverage", |doc, _| { + doc.selection.as_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[0.25]); + Ok(()) + }) + .unwrap(); + } + s.execute(command, json!({"name": "Translucent composite"})).unwrap(); + assert_eq!((tip(&s).width, tip(&s).height), (5, 6)); + let expected = if selected { 0.125 } else { 0.5 }; + for y in 0..6 { + for x in 0..5 { + assert!((tip(&s).get(x, y) - expected).abs() < 0.003); + } + } + } + } + } +} + +#[test] +fn a_hidden_black_source_over_white_or_transparency_is_empty_and_does_not_replace_a_preset() { + for command in COMMANDS { + for background in ["white", "transparent"] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": background})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Hidden ink"})).unwrap(); + s.edit("Hide all ink", |doc, active| { + let bounds = doc.bounds(); + let layer = doc.layer_mut(active.unwrap()).unwrap(); + layer.surface_mut().unwrap().fill_rect(bounds, &[0.0, 0.0, 0.0, 1.0]); + layer.visible = false; + Ok(()) + }) + .unwrap(); + s.execute("brush.presets.save", json!({"name": "Kept"})).unwrap(); + let brush = s.tools.brush.clone(); + let presets = s.tools.presets.clone(); + let current = s.tools.current_preset.clone(); + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let err = s.execute(command, json!({"name": "Kept"})).unwrap_err(); + assert!(err.to_string().contains("contain no paint"), "{err}"); + assert_eq!(s.tools.brush, brush); + assert_eq!(s.tools.presets, presets); + assert_eq!(s.tools.current_preset, current); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.active().unwrap().history.past_len(), history); + } + } +} + +#[test] +fn merged_rgb_retains_the_document_profile_before_gray_conversion() { + for command in COMMANDS { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": 32, "background": "transparent"})).unwrap(); + s.edit("Linear gray nested under active group", |doc, active| { + doc.icc_profile = Some(craft_cms::Builtin::LinearSrgb.profile().to_bytes()); + let mut layer = Layer::raster("Linear half gray", doc.pixel_format()); + layer.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 5, 5), &[0.5, 0.5, 0.5, 1.0]); + let group = Layer::group("Active group", vec![layer]); + *active = Some(group.id); + doc.layers.push(group); + Ok(()) + }) + .unwrap(); + s.execute(command, json!({"name": "Profiled merged tip"})).unwrap(); + assert_eq!((tip(&s).width, tip(&s).height), (4, 4)); + // Encoded sGray for linear RGB 0.5 is about 0.735, not encoded RGB 0.5. + assert!((tip(&s).get(0, 0) - 0.265).abs() < 0.01); + } +} + +fn sparse_budget_source(width: u32, height: u32, selected: bool) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": width, "height": height, "background": "transparent"})).unwrap(); + s.edit("Sparse composite budget fixture", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(Rect::new(0, 0, 1, 1), &[0.0, 0.0, 0.0, 1.0]); + assert_eq!(surf.tile_count(), 1); + if selected { + let mut mask = Surface::new(photocraft_color::PixelFormat::GRAY8); + mask.fill_rect(Rect::new(0, 0, 1, 1), &[1.0]); + mask.fill_rect(Rect::new(width as i32 - 1, height as i32 - 1, width as i32, height as i32), &[1.0]); + assert_eq!(mask.tile_count(), 2); + assert_eq!(mask.content_bounds(), doc.bounds()); + doc.selection = Some(mask); + } + Ok(()) + }) + .unwrap(); + s +} + +#[test] +fn composite_storage_is_counted_with_density_and_mask_before_any_allocation() { + const WIDTH: u32 = 32768; + for command in COMMANDS { + for selected in [false, true] { + // Density plus optional mask fit exactly; the simultaneously live RGBA band + // must also count, even though the document itself is sparse. + let bytes = if selected { 8 } else { 4 }; + let height = (crate::allocation::MAX_DENSE_BYTES / (bytes * u64::from(WIDTH))) as u32; + let mut s = sparse_budget_source(WIDTH, height, selected); + let doc = s.active().unwrap().doc.clone(); + let brush = s.tools.brush.clone(); + let presets = s.tools.presets.clone(); + let current = s.tools.current_preset.clone(); + let history = s.active().unwrap().history.past_len(); + crate::allocation::fail_next_for_test(); + let result = s.execute(command, json!({"name": "Composite over budget"})); + let unspent = crate::allocation::capacity::(0, "consume composite budget failpoint"); + let err = result.unwrap_err(); + assert!(err.to_string().contains("working memory"), "{err}"); + assert!(unspent.is_err(), "budget refusal must precede the first allocation"); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.active().unwrap().history.past_len(), history); + assert_eq!(s.tools.brush, brush); + assert_eq!(s.tools.presets, presets); + assert_eq!(s.tools.current_preset, current); + } + } +} + +#[test] +fn compositor_allocation_boundary_failure_preserves_source_and_preset_state() { + for command in COMMANDS { + for selected in [false, true] { + let mut s = source(8); + if selected { + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 150})).unwrap(); + } + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let brush = s.tools.brush.clone(); + let presets = s.tools.presets.clone(); + let current = s.tools.current_preset.clone(); + crate::allocation::fail_after_for_test(if selected { 2 } else { 1 }); + let result = s.execute(command, json!({"name": "Compositor allocation failure"})); + let _ = crate::allocation::capacity::(0, "reset compositor failpoint"); + let err = result.unwrap_err(); + assert!(err.to_string().contains("not enough memory"), "{err}"); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.active().unwrap().history.past_len(), history); + assert_eq!(s.tools.brush, brush); + assert_eq!(s.tools.presets, presets); + assert_eq!(s.tools.current_preset, current); + } + } +} + +#[test] +fn a_banded_capture_that_fits_the_budget_is_not_charged_for_a_full_rgba_canvas() { + const WIDTH: u32 = 32768; + let band_rows = photocraft_compose::band_rows_for(WIDTH, 0) as u64; + let band_bytes = u64::from(WIDTH) * band_rows * 16; + for command in COMMANDS { + for selected in [false, true] { + let sample_bytes = if selected { 8 } else { 4 }; + let height = ((crate::allocation::MAX_DENSE_BYTES - band_bytes) / (sample_bytes * u64::from(WIDTH))) as u32; + let pixels = u64::from(WIDTH) * u64::from(height); + assert!(pixels * sample_bytes + band_bytes <= crate::allocation::MAX_DENSE_BYTES); + assert!(pixels * (sample_bytes + 16) > crate::allocation::MAX_DENSE_BYTES, "a full-plane estimate would incorrectly reject this fixture"); + let mut s = sparse_budget_source(WIDTH, height, selected); + let doc = s.active().unwrap().doc.clone(); + let brush = s.tools.brush.clone(); + let presets = s.tools.presets.clone(); + // Refuse the first real allocation, after verifying that the budget allowed it. + crate::allocation::fail_next_for_test(); + let result = s.execute(command, json!({"name": "Fits with bands"})); + let unspent = crate::allocation::capacity::(0, "consume band acceptance failpoint"); + let err = result.unwrap_err().to_string(); + assert!(err.contains("not enough memory") && !err.contains("working memory"), "{err}"); + assert!(unspent.is_ok(), "the accepted budget must reach the first allocation"); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.tools.brush, brush); + assert_eq!(s.tools.presets, presets); + } + } +} + +#[test] +fn selected_visible_capture_is_identical_with_background_tip_group() { + for command in COMMANDS { + for depth in [8, 16, 32] { + let mut s = source(depth); + let background = s.active().unwrap().doc.layers[0].id; + let painted = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.group", json!({"name": "Empty active group"})).unwrap(); + let group = s.active().unwrap().active_layer.unwrap(); + s.execute("select.rect", json!({"x": 50, "y": 40, "width": 100, "height": 50})).unwrap(); + let mut expected = None; + for active in [Some(background), Some(painted), Some(group)] { + s.edit("Choose capture-independent active layer", |_, current| { + *current = active; + Ok(()) + }) + .unwrap(); + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + assert!(s.is_enabled(command)); + let made = s.execute(command, json!({"name": "Merged tip"})).unwrap(); + assert_eq!((made["width"].as_u64(), made["height"].as_u64()), (Some(100), Some(50))); + assert_eq!(s.tools.brush.size, 100.0); + assert_eq!(tip(&s).get(0, 0), 1.0); + assert_eq!(tip(&s).get(60, 0), 0.0); + assert!((tip(&s).get(70, 20) - 127.0 / 255.0).abs() < 0.003); + let pixels: Vec<_> = (0..50).flat_map(|y| (0..100).map(move |x| (x, y))).map(|(x, y)| tip(&s).get(x, y)).collect(); + if let Some(expected) = &expected { + assert_eq!(&pixels, expected); + } else { + expected = Some(pixels); + } + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.active().unwrap().active_layer, active); + assert_eq!(s.active().unwrap().history.past_len(), history); + } + } + } +} + #[test] fn visible_composite_keeps_occlusion_and_ignores_hidden_source() { for command in COMMANDS { @@ -109,122 +379,6 @@ fn visible_composite_keeps_occlusion_and_ignores_hidden_source() { } } -#[test] -fn composite_transparency_and_selection_coverage_are_applied_once() { - for command in COMMANDS { - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth, "background": "transparent"})).unwrap(); - s.edit("Nested translucent source", |doc, active| { - let mut black = Layer::raster("Half black", doc.pixel_format()); - black.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 6, 7), &[0.0, 0.0, 0.0, 0.5]); - *active = Some(black.id); - doc.layers.push(black); - Ok(()) - }) - .unwrap(); - for coverage in [1.0f32, 0.25] { - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); - if coverage < 1.0 { - s.edit("Quarter coverage", |doc, _| { - doc.selection.as_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[coverage]); - Ok(()) - }) - .unwrap(); - } - s.execute(command, json!({"name": "Translucent composite"})).unwrap(); - assert_eq!((tip(&s).width, tip(&s).height), (5, 6)); - let expected = 0.5 * coverage; - for y in 0..6 { - for x in 0..5 { - assert!((tip(&s).get(x, y) - expected).abs() < 0.003); - } - } - } - } - } -} - -#[test] -fn a_hidden_black_source_over_white_or_transparency_is_empty_and_does_not_replace_a_preset() { - for command in COMMANDS { - for background in ["white", "transparent"] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "background": background})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Hidden ink"})).unwrap(); - s.edit("Hide all ink", |doc, active| { - let bounds = doc.bounds(); - let layer = doc.layer_mut(active.unwrap()).unwrap(); - layer.surface_mut().unwrap().fill_rect(bounds, &[0.0, 0.0, 0.0, 1.0]); - layer.visible = false; - Ok(()) - }) - .unwrap(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); - s.execute("brush.presets.save", json!({"name": "Kept"})).unwrap(); - let brush = s.tools.brush.clone(); - let presets = s.tools.presets.clone(); - let current = s.tools.current_preset.clone(); - let doc = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.past_len(); - let err = s.execute(command, json!({"name": "Kept"})).unwrap_err(); - assert!(err.to_string().contains("contain no paint"), "{err}"); - assert_eq!(s.tools.brush, brush); - assert_eq!(s.tools.presets, presets); - assert_eq!(s.tools.current_preset, current); - assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); - assert_eq!(s.active().unwrap().history.past_len(), history); - } - } -} - -fn sparse_budget_source(width: u32, height: u32, selected: bool) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": width, "height": height, "background": "transparent"})).unwrap(); - s.edit("Sparse composite budget fixture", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - surf.fill_rect(Rect::new(0, 0, 1, 1), &[0.0, 0.0, 0.0, 1.0]); - assert_eq!(surf.tile_count(), 1); - if selected { - let mut mask = Surface::new(photocraft_color::PixelFormat::GRAY8); - mask.fill_rect(Rect::new(0, 0, 1, 1), &[1.0]); - mask.fill_rect(Rect::new(width as i32 - 1, height as i32 - 1, width as i32, height as i32), &[1.0]); - assert_eq!(mask.tile_count(), 2); - assert_eq!(mask.content_bounds(), doc.bounds()); - doc.selection = Some(mask); - } - Ok(()) - }) - .unwrap(); - s -} - -#[test] -fn composite_storage_is_counted_with_density_and_mask_before_any_allocation() { - const WIDTH: u32 = 32768; - for command in COMMANDS { - // This selected case covers the density, selection mask and live compositor band. - let height = (crate::allocation::MAX_DENSE_BYTES / (8 * u64::from(WIDTH))) as u32; - let mut s = sparse_budget_source(WIDTH, height, true); - let doc = s.active().unwrap().doc.clone(); - let brush = s.tools.brush.clone(); - let presets = s.tools.presets.clone(); - let current = s.tools.current_preset.clone(); - let history = s.active().unwrap().history.past_len(); - crate::allocation::fail_next_for_test(); - let result = s.execute(command, json!({"name": "Composite over budget"})); - let unspent = crate::allocation::capacity::(0, "consume composite budget failpoint"); - let err = result.unwrap_err(); - assert!(err.to_string().contains("working memory"), "{err}"); - assert!(unspent.is_err(), "budget refusal must precede the first allocation"); - assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); - assert_eq!(s.active().unwrap().history.past_len(), history); - assert_eq!(s.tools.brush, brush); - assert_eq!(s.tools.presets, presets); - assert_eq!(s.tools.current_preset, current); - } -} - #[test] fn selection_buffer_failure_preserves_source_and_preset_state() { for command in COMMANDS { @@ -247,31 +401,3 @@ fn selection_buffer_failure_preserves_source_and_preset_state() { assert_eq!(s.tools.current_preset, current); } } - -#[test] -fn a_banded_capture_that_fits_the_budget_is_not_charged_for_a_full_rgba_canvas() { - const WIDTH: u32 = 32768; - let band_rows = photocraft_compose::band_rows_for(WIDTH, 0) as u64; - let band_bytes = u64::from(WIDTH) * band_rows * 16; - for command in COMMANDS { - let sample_bytes = 8; - let height = ((crate::allocation::MAX_DENSE_BYTES - band_bytes) / (sample_bytes * u64::from(WIDTH))) as u32; - let pixels = u64::from(WIDTH) * u64::from(height); - assert!(pixels * sample_bytes + band_bytes <= crate::allocation::MAX_DENSE_BYTES); - assert!(pixels * (sample_bytes + 16) > crate::allocation::MAX_DENSE_BYTES, "a full-plane estimate would incorrectly reject this fixture"); - let mut s = sparse_budget_source(WIDTH, height, true); - let doc = s.active().unwrap().doc.clone(); - let brush = s.tools.brush.clone(); - let presets = s.tools.presets.clone(); - // Refuse the first real allocation, after verifying that the budget allowed it. - crate::allocation::fail_next_for_test(); - let result = s.execute(command, json!({"name": "Fits with bands"})); - let unspent = crate::allocation::capacity::(0, "consume band acceptance failpoint"); - let err = result.unwrap_err().to_string(); - assert!(err.contains("not enough memory") && !err.contains("working memory"), "{err}"); - assert!(unspent.is_ok(), "the accepted budget must reach the first allocation"); - assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); - assert_eq!(s.tools.brush, brush); - assert_eq!(s.tools.presets, presets); - } -} diff --git a/crates/engine/src/cmd/brush_cmds/define_brush_no_selection_tests.rs b/crates/engine/src/cmd/brush_cmds/define_brush_no_selection_tests.rs new file mode 100644 index 0000000000..71e42f6308 --- /dev/null +++ b/crates/engine/src/cmd/brush_cmds/define_brush_no_selection_tests.rs @@ -0,0 +1,235 @@ +use super::*; + +const COMMANDS: [&str; 2] = ["edit.defineBrushPreset", "brush.defineFromSelection"]; + +fn source(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 150, "depth": depth, "background": "#ffffff"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Tip"})).unwrap(); + s.edit("BrushSrc", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(Rect::new(50, 40, 90, 70), &[0.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(120, 60, 150, 90), &[128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +fn tip(s: &Session) -> &GrayTile { + let TipShape::Sampled(tip) = &s.tools.brush.tip else { panic!("expected a sampled tip") }; + tip +} + +#[test] +fn without_selection_the_canvas_is_trimmed_to_the_measured_content() { + for command in COMMANDS { + for depth in [8, 16, 32] { + let mut s = source(depth); + assert!(s.active().unwrap().doc.selection.is_none()); + assert!(s.is_enabled(command), "{command}, depth {depth}"); + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let presets = s.tools.presets.len(); + + let result = s.execute(command, json!({"name": "Canvas tip"})).unwrap(); + + assert_eq!((result["width"].as_u64(), result["height"].as_u64()), (Some(100), Some(50))); + assert_eq!(s.tools.brush.size, 100.0); + assert_eq!((tip(&s).width, tip(&s).height), (100, 50)); + assert_eq!(tip(&s).get(0, 0), 1.0); + assert_eq!(tip(&s).get(60, 0), 0.0, "transparent gap contributes no paint"); + assert!((tip(&s).get(70, 20) - 127.0 / 255.0).abs() < 0.003); + assert_eq!(s.tools.presets.len(), presets + 1); + assert_eq!(s.tools.current_preset.as_deref(), Some("Canvas tip")); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc), "source document is untouched"); + assert_eq!(s.active().unwrap().history.past_len(), history); + assert!(s.active().unwrap().doc.selection.is_none(), "no synthetic selection is left behind"); + } + } +} + +#[test] +fn an_existing_selection_still_limits_the_tip_to_the_grey_square() { + for command in COMMANDS { + let mut s = source(8); + s.execute("select.rect", json!({"x": 115, "y": 55, "width": 40, "height": 40})).unwrap(); + let result = s.execute(command, json!({"name": "Selected tip"})).unwrap(); + assert_eq!((result["width"].as_u64(), result["height"].as_u64()), (Some(30), Some(30))); + assert_eq!(s.tools.brush.size, 30.0); + assert!((tip(&s).get(0, 0) - 127.0 / 255.0).abs() < 0.003); + assert!(s.active().unwrap().doc.selection.is_some()); + } +} + +#[test] +fn a_partial_selection_keeps_coverage_alpha_and_canvas_clipping() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "transparent"})).unwrap(); + s.edit("Half opaque source", |doc, active| { + let bounds = doc.bounds(); + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(bounds, &[0.0, 0.0, 0.0, 0.5]); + Ok(()) + }) + .unwrap(); + s.execute("select.rect", json!({"x": -3, "y": -2, "width": 8, "height": 8})).unwrap(); + s.edit("Partial coverage", |doc, _| { + doc.selection.as_mut().unwrap().fill_rect(Rect::new(0, 0, 5, 6), &[0.25]); + Ok(()) + }) + .unwrap(); + + s.execute("brush.defineFromSelection", json!({"name": "Masked tip"})).unwrap(); + + assert_eq!((tip(&s).width, tip(&s).height), (5, 6)); + assert!((tip(&s).get(0, 0) - 0.125).abs() < 0.003, "density includes source alpha and selection coverage"); + assert!((tip(&s).get(4, 5) - 0.125).abs() < 0.003); +} + +#[test] +fn no_document_is_disabled_and_a_group_active_capture_uses_visible_pixels() { + let mut s = Session::new(); + for command in COMMANDS { + assert!(!s.is_enabled(command)); + assert!(s.execute(command, json!({"name": "No document"})).is_err()); + } + s = source(8); + s.execute("layer.new.group", json!({"name": "Not pixels"})).unwrap(); + for command in COMMANDS { + assert!(s.is_enabled(command)); + s.execute(command, json!({"name": "Visible pixels"})).unwrap(); + assert_eq!((tip(&s).width, tip(&s).height), (100, 50)); + } +} + +#[test] +fn a_large_canvas_is_trimmed_before_the_existing_tip_side_limit() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": MAX_TIP + 1, "height": 2, "background": "#ffffff"})).unwrap(); + s.edit("One black pixel", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(MAX_TIP as i32, 0, MAX_TIP as i32 + 1, 1), &[0.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + let made = s.execute("edit.defineBrushPreset", json!({"name": "One pixel"})).unwrap(); + assert_eq!((made["width"].as_u64(), made["height"].as_u64()), (Some(1), Some(1))); + assert_eq!(tip(&s).get(0, 0), 1.0); + + s.edit("Too wide painted area", |doc, active| { + let bounds = doc.bounds(); + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(bounds, &[0.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + let brush = s.tools.brush.clone(); + let presets = s.tools.presets.clone(); + let err = s.execute("edit.defineBrushPreset", json!({"name": "Too wide"})).unwrap_err(); + assert!(err.to_string().contains("too large for a brush tip"), "{err}"); + assert_eq!(s.tools.brush, brush); + assert_eq!(s.tools.presets, presets); +} + +#[test] +fn a_canvas_capture_allocation_failure_leaves_the_source_and_presets_unchanged() { + let mut s = source(8); + let brush = s.tools.brush.clone(); + let presets = s.tools.presets.clone(); + let current = s.tools.current_preset.clone(); + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + crate::allocation::fail_next_for_test(); + let result = s.execute("brush.defineFromSelection", json!({"name": "Allocation failure"})); + let _ = crate::allocation::capacity::(0, "reset failpoint"); + let err = result.unwrap_err().to_string(); + assert!(err.contains("not enough memory") && err.contains("defining a brush from the selection"), "{err}"); + assert_eq!(s.tools.brush, brush); + assert_eq!(s.tools.presets, presets); + assert_eq!(s.tools.current_preset, current); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.active().unwrap().history.past_len(), history); +} + +// Sparse source and mask fixtures keep just one or two tiles, even when their +// bounds would require gigabytes of dense sampling buffers. +fn budget_source(width: u32, height: u32, selected: bool) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": width, "height": height, "background": "transparent"})).unwrap(); + s.edit("Sparse budget source", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(Rect::new(0, 0, 1, 1), &[0.0, 0.0, 0.0, 1.0]); + assert_eq!(surf.tile_count(), 1); + if selected { + let mut mask = photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8); + mask.fill_rect(Rect::new(0, 0, 1, 1), &[1.0]); + mask.fill_rect(Rect::new(width as i32 - 1, height as i32 - 1, width as i32, height as i32), &[1.0]); + assert_eq!(mask.tile_count(), 2); + assert_eq!(mask.content_bounds(), doc.bounds()); + doc.selection = Some(mask); + } + Ok(()) + }) + .unwrap(); + s +} + +fn assert_budget_refusal(s: &mut Session, command: &str) { + let brush = s.tools.brush.clone(); + let presets = s.tools.presets.clone(); + let current = s.tools.current_preset.clone(); + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let revision = s.active().unwrap().revision; + // This also makes the regression safe on the unfixed code: its first dense + // allocation fails instead of trying to fill the enormous buffer. + crate::allocation::fail_next_for_test(); + let result = s.execute(command, json!({"name": "Over budget"})); + let unspent = crate::allocation::capacity::(0, "consume budget test failpoint"); + let err = result.unwrap_err().to_string(); + assert!(err.contains("working memory") && err.contains("defining a brush from the selection"), "{err}"); + assert!(unspent.is_err(), "the budget refusal must precede the first fallible allocation"); + assert_eq!(s.tools.brush, brush); + assert_eq!(s.tools.presets, presets); + assert_eq!(s.tools.current_preset, current); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc)); + assert_eq!(s.active().unwrap().history.past_len(), history); + assert_eq!(s.active().unwrap().revision, revision); +} + +#[test] +fn an_over_budget_canvas_is_refused_before_sampling() { + const WIDTH: u32 = 32768; + // The pixel count fits usize on both targets, while its f32 density buffer + // alone is just over that target's dense-memory budget. + let height = (crate::allocation::MAX_DENSE_BYTES / (4 * u64::from(WIDTH))) as u32 + 1; + for command in COMMANDS { + let mut s = budget_source(WIDTH, height, false); + assert!(s.active().unwrap().doc.selection.is_none()); + assert_budget_refusal(&mut s, command); + } +} + +#[test] +fn selection_capture_counts_density_and_mask_buffers_together() { + const WIDTH: u32 = 32768; + let height = (crate::allocation::MAX_DENSE_BYTES / (4 * u64::from(WIDTH))) as u32; + let density_bytes = u64::from(WIDTH) * u64::from(height) * 4; + assert_eq!(density_bytes, crate::allocation::MAX_DENSE_BYTES, "density alone would fit; the live mask must also count"); + for command in COMMANDS { + let mut s = budget_source(WIDTH, height, true); + assert_eq!(s.active().unwrap().doc.selection.as_ref().unwrap().channels(), 1); + assert_budget_refusal(&mut s, command); + } +} + +#[test] +fn a_small_selection_on_an_over_budget_canvas_still_defines_a_tip() { + const WIDTH: u32 = 32768; + let height = (crate::allocation::MAX_DENSE_BYTES / (4 * u64::from(WIDTH))) as u32 + 1; + for command in COMMANDS { + let mut s = budget_source(WIDTH, height, false); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap(); + let result = s.execute(command, json!({"name": "Small selected tip"})).unwrap(); + assert_eq!((result["width"].as_u64(), result["height"].as_u64()), (Some(1), Some(1))); + assert_eq!(tip(&s).get(0, 0), 1.0); + } +} diff --git a/crates/engine/src/cmd/edit_menu_cmds/tests.rs b/crates/engine/src/cmd/edit_menu_cmds/tests.rs index 069ff2573c..4d486330b3 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/tests.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/tests.rs @@ -756,7 +756,7 @@ fn preset_manager_brush_delete_clears_current_preset() { #[test] fn define_brush_preset_wraps_define_from_selection() { let mut s = session(8); - assert!(!s.is_enabled("edit.defineBrushPreset")); + assert!(s.is_enabled("edit.defineBrushPreset")); s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); s.execute("select.rect", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); s.execute("edit.defineBrushPreset", json!({})).unwrap(); From 9cf0e44a53eda76ee1c62852eb758effba92db7d Mon Sep 17 00:00:00 2001 From: Yoris Wind Date: Mon, 16 Nov 2026 05:53:57 -0800 Subject: [PATCH 45/46] Make outside-stroke scalar scratch allocations fallible --- crates/compose/src/effects/composite.rs | 95 +++++++++++++++++++++++-- crates/compose/src/lib.rs | 12 ++++ crates/compose/src/render.rs | 6 ++ 3 files changed, 107 insertions(+), 6 deletions(-) diff --git a/crates/compose/src/effects/composite.rs b/crates/compose/src/effects/composite.rs index 565cfa2f47..98ba24bfb9 100644 --- a/crates/compose/src/effects/composite.rs +++ b/crates/compose/src/effects/composite.rs @@ -634,16 +634,20 @@ impl<'a> EffectPass<'a> { let (w, h) = (self.w, self.h); let base = alloc.clone(work)?; let mut acc = alloc.filled(self.big, [0.0; 4])?; // premultiplied Σ share·blended - let mut cover = vec![0.0f32; w * h]; + let mut cover = alloc.scalar_filled(self.big, 0.0)?; for st in strokes.iter().copied() { let (_, out_w) = stroke_widths(st); if out_w <= 0.0 { continue; } - let share = self.outside_share(st, out_w, shape, lay, fields, &mut cover); + let share = self.outside_share(st, shape, lay, fields, &mut cover, alloc)?; // The stroke blended over the backdrop at full coverage. let mut blended = alloc.clone(&base)?; - let ones = Map { w, h, v: share.iter().map(|&s| if s > 0.0 { 1.0 } else { 0.0 }).collect() }; + let mut ones = alloc.scalar_filled(self.big, 0.0)?; + for (one, &s) in ones.iter_mut().zip(&share) { + if s > 0.0 { *one = 1.0; } + } + let ones = Map { w, h, v: ones }; // The share already carries the Dissolve choice, so the paint itself composites as Normal. let paint_blend = if st.common.blend == BlendMode::Dissolve { BlendMode::Normal } else { st.common.blend }; paint_fx(&mut blended, &ones, &st.paint, self.stroke_frame(st), self.anchor, self.big, paint_blend, 1.0, self.patterns); @@ -671,7 +675,16 @@ impl<'a> EffectPass<'a> { /// The share of each pixel an outside stroke `st` (outside width `out_w`) takes: its coverage /// × opacity not yet taken by the strokes above, which `cover` accumulates. - fn outside_share(&self, st: &photocraft_doc::StrokeFx, out_w: f32, shape: &Map, lay: &Buffer, fields: &StrokeFields, cover: &mut [f32]) -> Vec { + fn outside_share( + &self, + st: &photocraft_doc::StrokeFx, + shape: &Map, + lay: &Buffer, + fields: &StrokeFields, + cover: &mut [f32], + alloc: &A, + ) -> Result, A::Error> { + let (_, out_w) = stroke_widths(st); let (w, big) = (self.w, self.big); // Shape layers without a filled outline stroke their vector outline, estimated from local // coverage; every other layer strokes its shape. The width then picks the field. @@ -688,7 +701,7 @@ impl<'a> EffectPass<'a> { (false, false) => fields.dout.as_deref(), } .unwrap_or_default(); - let mut share = vec![0.0f32; w * self.h]; + let mut share = alloc.scalar_filled(self.big, 0.0)?; for (i, sh) in share.iter_mut().enumerate() { let band = (out_w + 0.5 - d[i]).clamp(0.0, 1.0); let k = if inside(shape.v[i]) { if vector_outline { 0.0 } else { band * outline_share(shape.v[i], lay.px[i][3]) } } else { band }; @@ -700,7 +713,7 @@ impl<'a> EffectPass<'a> { *sh = k * (1.0 - cover[i]); cover[i] += *sh; } - share + Ok(share) } /// Writes the finished stack `work` into `backdrop` (over `before`) at layer opacity. @@ -796,6 +809,7 @@ mod outside_stroke_allocation_tests { use super::*; use photocraft_color::{Color, PixelFormat}; use photocraft_doc::{FxCommon, StrokeFx}; + use std::sync::atomic::{AtomicUsize, Ordering}; struct RejectFilled; @@ -809,6 +823,75 @@ mod outside_stroke_allocation_tests { fn clone(&self, buffer: &Buffer) -> Result { buffer.try_clone().map_err(|_| "clone allocation") } + + fn scalar_filled(&self, _rect: Rect, _value: f32) -> Result, Self::Error> { + Err("outside stroke scalar allocation") + } + } + + struct FailScalarAt { + fail_at: usize, + attempts: AtomicUsize, + } + + impl BufferAlloc for FailScalarAt { + type Error = usize; + + fn filled(&self, rect: Rect, color: [f32; 4]) -> Result { + Ok(Buffer::filled(rect, color)) + } + + fn clone(&self, buffer: &Buffer) -> Result { + Ok(buffer.clone()) + } + + fn scalar_filled(&self, rect: Rect, value: f32) -> Result, Self::Error> { + let attempt = self.attempts.fetch_add(1, Ordering::Relaxed) + 1; + if attempt == self.fail_at { + return Err(attempt); + } + Ok(photocraft_raster::scratch::take(rect.width() as usize * rect.height() as usize, value)) + } + } + + #[test] + fn enabled_outside_stroke_scalar_allocation_failures_preserve_pixels() { + let rect = Rect::new(0, 0, 4, 4); + let mut layer = Layer::raster("outside stroke", PixelFormat::RGBA8); + layer.effects.items.push(Effect::Stroke(StrokeFx { + common: FxCommon::new(BlendMode::Normal, 1.0), + size: 1.0, + position: StrokePosition::Outside, + paint: FxPaint::Color(Color::rgb(0.0, 0.0, 1.0)), + overprint: false, + })); + let mut shape = Map::new(4, 4, 0.0); + for (index, value) in shape.v.iter_mut().enumerate() { + if matches!(index, 5 | 6 | 9 | 10) { *value = 1.0; } + } + let patterns = PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES); + let texture = TextureCtx { rect, patterns: &[], anchor: (0.0, 0.0) }; + let maps = build_maps(&layer, shape.v.clone(), rect, &GlobalLight::default(), &texture); + let pass = EffectPass::new(&layer, &maps, rect, rect, &patterns, None); + let strokes: Vec<_> = layer.effects.items.iter().filter_map(|effect| if let Effect::Stroke(stroke) = effect { Some(stroke) } else { None }).collect(); + assert!(strokes.iter().any(|stroke| stroke_widths(stroke).1 > 0.0)); + let fields = pass.stroke_fields(true); + let mut lay = Buffer::filled(rect, [0.0; 4]); + for (pixel, alpha) in lay.px.iter_mut().zip(&shape.v) { pixel[3] = *alpha; } + let original = Buffer::filled(rect, [1.0; 4]); + + // The three scalar allocations are the accumulated cover, this stroke's share, and the + // paint-coverage map. Each failure is returned before any work pixels are written back. + for fail_at in 1..=3 { + let allocator = FailScalarAt { fail_at, attempts: AtomicUsize::new(0) }; + let mut work = original.clone(); + assert_eq!( + pass.paint_outside_strokes_with(&mut work, &lay, &shape, &strokes, &fields, &allocator), + Err(fail_at), + ); + assert_eq!(allocator.attempts.load(Ordering::Relaxed), fail_at); + assert_eq!(work, original, "a rejected scalar scratch buffer cannot publish partial stroke pixels"); + } } #[test] diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index a1376dcf28..8691a3f1b4 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -192,6 +192,7 @@ pub(crate) trait BufferAlloc { type Error: Send; fn filled(&self, rect: Rect, color: [f32; 4]) -> Result; fn clone(&self, buffer: &Buffer) -> Result; + fn scalar_filled(&self, rect: Rect, value: f32) -> Result, Self::Error>; } pub(crate) struct InfallibleBufferAlloc; @@ -203,6 +204,9 @@ impl BufferAlloc for InfallibleBufferAlloc { fn clone(&self, buffer: &Buffer) -> Result { Ok(buffer.clone()) } + fn scalar_filled(&self, rect: Rect, value: f32) -> Result, Self::Error> { + Ok(photocraft_raster::scratch::take(rect.width() as usize * rect.height() as usize, value)) + } } pub(crate) struct FallibleBufferAlloc; @@ -214,6 +218,14 @@ impl BufferAlloc for FallibleBufferAlloc { fn clone(&self, buffer: &Buffer) -> Result { buffer.try_clone() } + fn scalar_filled(&self, rect: Rect, value: f32) -> Result, Self::Error> { + let width = usize::try_from(rect.width()).map_err(|_| photocraft_raster::AllocationError::SizeOverflow)?; + let height = usize::try_from(rect.height()).map_err(|_| photocraft_raster::AllocationError::SizeOverflow)?; + let len = width.checked_mul(height).ok_or(photocraft_raster::AllocationError::SizeOverflow)?; + let bytes = len.checked_mul(std::mem::size_of::()).ok_or(photocraft_raster::AllocationError::SizeOverflow)?; + photocraft_raster::scratch::try_take(len, value) + .ok_or(photocraft_raster::AllocationError::NotEnoughMemory { bytes }) + } } #[cfg(test)] diff --git a/crates/compose/src/render.rs b/crates/compose/src/render.rs index a031536107..a31e227a3d 100644 --- a/crates/compose/src/render.rs +++ b/crates/compose/src/render.rs @@ -470,6 +470,12 @@ mod fallible_bands_tests { self.attempt()?; buffer.try_clone().map_err(|_| usize::MAX) } + + fn scalar_filled(&self, rect: Rect, value: f32) -> Result, Self::Error> { + self.attempt()?; + let len = (rect.width() as usize).checked_mul(rect.height() as usize).ok_or(usize::MAX)?; + photocraft_raster::scratch::try_take(len, value).ok_or(usize::MAX) + } } fn nested_document() -> Document { From ccfb68c86b06349c9e2633a5941d1d710fd1de14 Mon Sep 17 00:00:00 2001 From: Yoris Wind Date: Mon, 16 Nov 2026 06:07:06 -0800 Subject: [PATCH 46/46] Format outside-stroke scalar allocation controls --- crates/compose/src/effects/composite.rs | 17 ++++++++++------- crates/compose/src/lib.rs | 3 +-- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/crates/compose/src/effects/composite.rs b/crates/compose/src/effects/composite.rs index 98ba24bfb9..3d638c8a4e 100644 --- a/crates/compose/src/effects/composite.rs +++ b/crates/compose/src/effects/composite.rs @@ -645,7 +645,9 @@ impl<'a> EffectPass<'a> { let mut blended = alloc.clone(&base)?; let mut ones = alloc.scalar_filled(self.big, 0.0)?; for (one, &s) in ones.iter_mut().zip(&share) { - if s > 0.0 { *one = 1.0; } + if s > 0.0 { + *one = 1.0; + } } let ones = Map { w, h, v: ones }; // The share already carries the Dissolve choice, so the paint itself composites as Normal. @@ -867,7 +869,9 @@ mod outside_stroke_allocation_tests { })); let mut shape = Map::new(4, 4, 0.0); for (index, value) in shape.v.iter_mut().enumerate() { - if matches!(index, 5 | 6 | 9 | 10) { *value = 1.0; } + if matches!(index, 5 | 6 | 9 | 10) { + *value = 1.0; + } } let patterns = PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES); let texture = TextureCtx { rect, patterns: &[], anchor: (0.0, 0.0) }; @@ -877,7 +881,9 @@ mod outside_stroke_allocation_tests { assert!(strokes.iter().any(|stroke| stroke_widths(stroke).1 > 0.0)); let fields = pass.stroke_fields(true); let mut lay = Buffer::filled(rect, [0.0; 4]); - for (pixel, alpha) in lay.px.iter_mut().zip(&shape.v) { pixel[3] = *alpha; } + for (pixel, alpha) in lay.px.iter_mut().zip(&shape.v) { + pixel[3] = *alpha; + } let original = Buffer::filled(rect, [1.0; 4]); // The three scalar allocations are the accumulated cover, this stroke's share, and the @@ -885,10 +891,7 @@ mod outside_stroke_allocation_tests { for fail_at in 1..=3 { let allocator = FailScalarAt { fail_at, attempts: AtomicUsize::new(0) }; let mut work = original.clone(); - assert_eq!( - pass.paint_outside_strokes_with(&mut work, &lay, &shape, &strokes, &fields, &allocator), - Err(fail_at), - ); + assert_eq!(pass.paint_outside_strokes_with(&mut work, &lay, &shape, &strokes, &fields, &allocator), Err(fail_at),); assert_eq!(allocator.attempts.load(Ordering::Relaxed), fail_at); assert_eq!(work, original, "a rejected scalar scratch buffer cannot publish partial stroke pixels"); } diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 8691a3f1b4..6b41e4ecb1 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -223,8 +223,7 @@ impl BufferAlloc for FallibleBufferAlloc { let height = usize::try_from(rect.height()).map_err(|_| photocraft_raster::AllocationError::SizeOverflow)?; let len = width.checked_mul(height).ok_or(photocraft_raster::AllocationError::SizeOverflow)?; let bytes = len.checked_mul(std::mem::size_of::()).ok_or(photocraft_raster::AllocationError::SizeOverflow)?; - photocraft_raster::scratch::try_take(len, value) - .ok_or(photocraft_raster::AllocationError::NotEnoughMemory { bytes }) + photocraft_raster::scratch::try_take(len, value).ok_or(photocraft_raster::AllocationError::NotEnoughMemory { bytes }) } }