From ff193387ce444a2cc97661bdbbf197fce09be076 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Tue, 17 Nov 2026 03:59:30 +0800 Subject: [PATCH 01/85] Validate embedded SVG images and reuse checked XML --- Cargo.lock | 4 + Cargo.toml | 5 + crates/engine/src/cmd/smart_cmds.rs | 8 +- crates/engine/src/cmd/smart_cmds/rendering.rs | 142 +++++- crates/engine/src/cmd/smart_cmds/tests.rs | 1 + .../src/cmd/smart_cmds/tests/svg_profile.rs | 27 +- .../tests/svg_stack_completeness.rs | 150 +++++++ crates/engine/src/cmd/smart_svg_cmds.rs | 5 +- .../cmd/smart_svg_cmds/source_cache_tests.rs | 301 +++++++++++++ crates/engine/src/cmd/smart_svg_cmds/tests.rs | 25 +- crates/io/Cargo.toml | 6 + crates/io/src/svg.rs | 171 ++------ crates/io/src/svg/data_href_validation.rs | 415 ++++++++++++++++++ crates/io/src/svg/image_integrity.rs | 297 +++++++++++++ crates/io/src/svg/integrity_budget_tests.rs | 259 +++++++++++ crates/io/src/svg/mime_header_tests.rs | 119 +++++ .../io/src/svg/optional_image_review_tests.rs | 286 ++++++++++++ crates/io/src/svg/raster_validation.rs | 135 ++++++ crates/io/src/svg/tests.rs | 84 ++-- crates/io/src/svg/xml_reuse_tests.rs | 137 ++++++ crates/ui-egui/src/smart_svg_ui.rs | 2 +- crates/ui-egui/src/smart_svg_ui/tests.rs | 32 ++ 22 files changed, 2415 insertions(+), 196 deletions(-) create mode 100644 crates/engine/src/cmd/smart_cmds/tests/svg_stack_completeness.rs create mode 100644 crates/engine/src/cmd/smart_svg_cmds/source_cache_tests.rs create mode 100644 crates/io/src/svg/data_href_validation.rs create mode 100644 crates/io/src/svg/image_integrity.rs create mode 100644 crates/io/src/svg/integrity_budget_tests.rs create mode 100644 crates/io/src/svg/mime_header_tests.rs create mode 100644 crates/io/src/svg/raster_validation.rs create mode 100644 crates/io/src/svg/xml_reuse_tests.rs diff --git a/Cargo.lock b/Cargo.lock index cbff2d74c8..802df801b7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5797,7 +5797,10 @@ dependencies = [ "craft-xcf", "craft-xml", "crc32fast", + "data-url", "flate2", + "gif", + "image-webp", "kurbo 0.13.1", "lopdf", "miniz_oxide 0.9.1", @@ -5818,6 +5821,7 @@ dependencies = [ "thiserror 2.0.21", "ttf-parser", "zune-core", + "zune-jpeg", "zune-jpegxl", ] diff --git a/Cargo.toml b/Cargo.toml index fbf01b73dc..4a5cb02906 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,11 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] +# Match SVG renderer backends for exact optional-image validation. +zune-jpeg = "=0.5.15" +gif = "=0.14.2" +image-webp = "=0.2.4" +data-url = "=0.3.2" craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a", features = ["serde"] } # Feature flags shared with the launcher and the other Craft apps (craft-libs#1118, #1119). craft-flags = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } diff --git a/crates/engine/src/cmd/smart_cmds.rs b/crates/engine/src/cmd/smart_cmds.rs index 7b51d64184..a494f3552e 100644 --- a/crates/engine/src/cmd/smart_cmds.rs +++ b/crates/engine/src/cmd/smart_cmds.rs @@ -70,7 +70,7 @@ pub fn encode_source(doc: &Document) -> Result> { /// Decodes smart-object contents (a `.pcraft` bundle, PSD/PSB, or any flat image format). pub fn decode_source(file_name: &str, bytes: &[u8]) -> Result { - if photocraft_io::svg::is_svg(bytes) { + if photocraft_io::is_svg_input(file_name, bytes) { // This API has no warning channel. Stack/source caches and contents edits must not // turn a partial SVG import into silently complete smart-object contents. return photocraft_io::svg::import_svg_bounded_images_strict(file_name, bytes, 24_000_000) @@ -197,13 +197,13 @@ pub(crate) use placing::detach_psd; pub(crate) use placing::{affine_homography, set_placement, shift_smart, transform_placement}; use placing::{convert, reset_transform, shift_layer, via_copy}; pub use placing::{layer_to_smart, layers_to_smart, placement}; -#[cfg(test)] -pub(crate) use rendering::DISPLAY_NATIVE_HASH_BYTES; use rendering::refresh_or_fail; #[cfg(test)] +pub(crate) use rendering::{DISPLAY_NATIVE_HASH_BYTES, WARNING_SOURCE_DECODES, WARNING_SOURCE_LIMIT}; +#[cfg(test)] use rendering::{NativeDigests, blend_surfaces, place, render_in}; +pub(crate) use rendering::{WarningRenderSources, render_with_warnings, render_with_warnings_using, source_box}; pub use rendering::{apply_smart_filters, purge_stack_cache, refresh, refresh_layer, render, render_below_filter, stack_cache_bytes, stack_image}; -pub(crate) use rendering::{render_with_warnings, source_box}; #[cfg(test)] use source::svg_source_image_in; pub use source::{SourceImage, purge_source_cache, source_bytes, source_cache_bytes, source_decode_count, source_image, svg_source_image}; diff --git a/crates/engine/src/cmd/smart_cmds/rendering.rs b/crates/engine/src/cmd/smart_cmds/rendering.rs index 41901ad97f..eb19efdfff 100644 --- a/crates/engine/src/cmd/smart_cmds/rendering.rs +++ b/crates/engine/src/cmd/smart_cmds/rendering.rs @@ -13,7 +13,10 @@ use std::sync::Mutex; pub fn stack_image(file_name: &str, bytes: &[u8], fmt: PixelFormat, mode: photocraft_doc::StackMode) -> Result { use photocraft_algo::stack::Stat; let mut key = cache_key(bytes, fmt); - key.0 = *blake3::hash(&[&key.0[..], b"stack:", mode.id().as_bytes()].concat()).as_bytes(); + // Incomplete warning-aware imports must never share a strict Stack Mode cache. + let svg = photocraft_io::is_svg_input(file_name, bytes); + let domain: &[u8] = if svg { b"stack-svg-complete-v1:" } else { b"stack:" }; + key.0 = *blake3::hash(&[&key.0[..], domain, mode.id().as_bytes()].concat()).as_bytes(); if let Some(img) = cache_get(&key) { return Ok(img); } @@ -25,7 +28,7 @@ pub fn stack_image(file_name: &str, bytes: &[u8], fmt: PixelFormat, mode: photoc let bounds = doc.bounds(); // An SVG opens with one layer per shape, and every visible one gets its own float frame: // they may take 1 GiB together, the SVG import's own budget, before any is rendered. - if photocraft_io::svg::is_svg(bytes) { + if svg { let visible = u64::try_from(layers.iter().filter(|l| l.visible).count()).unwrap_or(u64::MAX); let frame_bytes = doc.size.area().saturating_mul(16); if visible.saturating_mul(frame_bytes) > 1 << 30 { @@ -182,7 +185,7 @@ fn place_with_svg(name: &str, bytes: &[u8], doc: &Document, sm: &SmartObject, sv let fmt = doc.pixel_format(); // A vector source is rendered at the placement's scale, and the placement is divided by // that scale so the rendered pixels land where the source units would. - if sm.stack_mode.is_none() && sm.warp.is_none() && photocraft_io::svg::is_svg(bytes) { + if sm.stack_mode.is_none() && sm.warp.is_none() && photocraft_io::is_svg_input(name, bytes) { let k = vector_scale(sm); let img = svg(bytes, k)?; return Ok(match &sm.perspective { @@ -201,8 +204,8 @@ fn place_with_svg(name: &str, bytes: &[u8], doc: &Document, sm: &SmartObject, sv }); } let img = match sm.stack_mode { - Some(mode) if photocraft_io::svg::is_svg(bytes) => convert_svg_source(stack_image(name, bytes, PixelFormat::RGBA32F, mode)?, doc)?, - None if photocraft_io::svg::is_svg(bytes) => svg(bytes, 1.0)?, + Some(mode) if photocraft_io::is_svg_input(name, bytes) => convert_svg_source(stack_image(name, bytes, PixelFormat::RGBA32F, mode)?, doc)?, + None if photocraft_io::is_svg_input(name, bytes) => svg(bytes, 1.0)?, Some(mode) => stack_image(name, bytes, fmt, mode)?, None => source_image(name, bytes, fmt)?, }; @@ -310,7 +313,7 @@ pub(crate) fn source_box(doc: &Document, sm: &SmartObject) -> Option<[f64; 4]> { let bytes = display_source(sm, &bytes); let fmt = doc.pixel_format(); let r = match sm.stack_mode { - None if photocraft_io::svg::is_svg(&bytes) => photocraft_io::svg::bounded_canvas_bounds(&bytes, 24_000_000).ok()?, + None if photocraft_io::is_svg_input(&name, &bytes) => photocraft_io::svg::bounded_canvas_bounds(&bytes, 24_000_000).ok()?, Some(mode) => stack_image(&name, &bytes, fmt, mode).ok()?.bounds, None => source_image(&name, &bytes, fmt).ok()?.bounds, }; @@ -324,28 +327,123 @@ pub fn render(doc: &Document, sm: &SmartObject) -> Result> { } /// Command-only rendering that retains usable SVG artwork and reports omitted embedded images. -/// It deliberately bypasses both source and filter-stage caches: a later warningless render -/// must not accidentally reuse an incomplete surface. Native previews remain strict. +/// Its local source cache never enters the strict process-wide source/filter caches. pub(crate) fn render_with_warnings(doc: &Document, sm: &SmartObject) -> Result<(Option, Vec)> { + render_with_warnings_using(sm, &mut WarningRenderSources::new(doc)) +} + +struct WarningSource { + source: Arc>, + key: (u64, PixelFormat, [u8; 32]), + image: SourceImage, + warnings: Vec, + bytes: usize, +} + +/// One command's bounded source-space renders. Placement, warp, filters and masks +/// are instance-specific and must never be cached here. Retaining the source Arc +/// makes allocation identity safe without hashing the same encoded SVG per instance. +pub(crate) struct WarningRenderSources<'a> { + document: &'a Document, + profile_context: Option<([u8; 32], bool)>, + entries: Vec, + budget: usize, + limit: usize, + bytes: usize, +} + +#[cfg(test)] +thread_local! { + pub(crate) static WARNING_SOURCE_DECODES: std::cell::Cell = const { std::cell::Cell::new(0) }; + pub(crate) static WARNING_SOURCE_LIMIT: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +impl<'a> WarningRenderSources<'a> { + pub(crate) fn new(document: &'a Document) -> Self { + #[cfg(test)] + let limit = WARNING_SOURCE_LIMIT.with(|limit| limit.get().unwrap_or(32)); + #[cfg(not(test))] + let limit = 32; + Self { document, profile_context: None, entries: Vec::new(), budget: if cfg!(target_arch = "wasm32") { 128 << 20 } else { 384 << 20 }, limit, bytes: 0 } + } + + #[cfg(test)] + pub(crate) fn with_limits(document: &'a Document, budget: usize, limit: usize) -> Self { + Self { budget, limit, ..Self::new(document) } + } + + #[cfg(test)] + pub(crate) fn profile_initialized(&self) -> bool { + self.profile_context.is_some() + } + + fn image(&mut self, bytes: &Arc>, scale: f64) -> Result<(SourceImage, Vec)> { + let doc = self.document; + // Non-SVG and unavailable sources keep their old fast path without + // materializing ICC bytes. This immutable document needs the context once. + let (profile_key, srgb) = *self.profile_context.get_or_insert_with(|| { + let profile = crate::color_cmds::document_profile(doc).to_bytes(); + ( + *blake3::hash(&profile).as_bytes(), + doc.mode == photocraft_color::ColorMode::Rgb && profile.as_ref() == craft_cms::Builtin::Srgb.profile().to_bytes().as_ref(), + ) + }); + let key = (scale.to_bits(), doc.pixel_format(), profile_key); + if let Some(index) = self.entries.iter().position(|entry| entry.key == key && Arc::ptr_eq(&entry.source, bytes)) { + let entry = self.entries.remove(index); + let result = (entry.image.clone(), entry.warnings.clone()); + self.entries.push(entry); + return Ok(result); + } + #[cfg(test)] + WARNING_SOURCE_DECODES.with(|count| count.set(count.get().saturating_add(1))); + let (buf, warnings) = photocraft_io::svg::rasterize_bounded_with_warnings(bytes, scale as f32, 24_000_000) + .map_err(|e| other(format!("can't render the SVG smart object: {e}")))?; + // Charge full native tiles and retained encoded bytes, not just logical pixels. + // This is a soft memo budget: oversize entries retain the existing uncached path. + let cost = usize::try_from(photocraft_raster::tile_storage_bytes(buf.rect, &doc.pixel_format())) + .unwrap_or(usize::MAX) + .saturating_add(bytes.capacity()) + .saturating_add(std::mem::size_of::()) + .saturating_add(warnings.capacity().saturating_mul(std::mem::size_of::())) + .saturating_add(warnings.iter().fold(0usize, |total, warning| total.saturating_add(warning.capacity()))); + let admitted = self.limit != 0 && cost <= self.budget; + if admitted { + while self.entries.len() >= self.limit || self.bytes > self.budget - cost { + let entry = self.entries.remove(0); + self.bytes = self.bytes.saturating_sub(entry.bytes); + } + } + // Preserve the normal renderer's exact built-in sRGB fast path. + let image = if srgb { + SourceImage { surface: Arc::new(super::source::buffer_to_surface(&buf, doc.pixel_format())), bounds: buf.rect } + } else { + let source = SourceImage { surface: Arc::new(super::source::buffer_to_surface(&buf, PixelFormat::RGBA32F)), bounds: buf.rect }; + convert_svg_source(source, doc)? + }; + if admitted && self.entries.try_reserve(1).is_ok() { + self.bytes += cost; // cost was admitted against budget - bytes above. + self.entries.push(WarningSource { source: Arc::clone(bytes), key, image: image.clone(), warnings: warnings.clone(), bytes: cost }); + } + Ok((image, warnings)) + } +} + +/// Reuse only warning-aware source pixels during one shared-content update. +pub(crate) fn render_with_warnings_using(sm: &SmartObject, sources: &mut WarningRenderSources<'_>) -> Result<(Option, Vec)> { + let doc = sources.document; let Some((name, bytes)) = source_bytes(&doc.metadata, &sm.source) else { return Ok((None, Vec::new())) }; - if !photocraft_io::svg::is_svg(&bytes) || sm.vector_preview.is_some() || sm.stack_mode.is_some() { + if !photocraft_io::is_svg_input(&name, &bytes) || sm.vector_preview.is_some() || sm.stack_mode.is_some() { return render(doc, sm).map(|surface| (surface, Vec::new())); } if !unapplied_filters(sm).is_empty() { return Err(other("the smart object has unsupported visible filters")); } let mut warnings = Vec::new(); - let placed = place_with_svg(&name, &bytes, doc, sm, &mut |bytes, scale| { - let (buf, omitted) = photocraft_io::svg::rasterize_bounded_with_warnings(bytes, scale as f32, 24_000_000) - .map_err(|e| other(format!("can't render the SVG smart object: {e}")))?; + let placed = place_with_svg(&name, &bytes, doc, sm, &mut |_, scale| { + let (image, omitted) = sources.image(&bytes, scale)?; warnings.extend(omitted); - // Preserve the normal renderer's exact built-in sRGB fast path. - let profile = crate::color_cmds::document_profile(doc); - if doc.mode == photocraft_color::ColorMode::Rgb && profile.to_bytes().as_ref() == craft_cms::Builtin::Srgb.profile().to_bytes().as_ref() { - return Ok(SourceImage { surface: Arc::new(super::source::buffer_to_surface(&buf, doc.pixel_format())), bounds: buf.rect }); - } - let source = SourceImage { surface: Arc::new(super::source::buffer_to_surface(&buf, PixelFormat::RGBA32F)), bounds: buf.rect }; - convert_svg_source(source, doc) + Ok(image) })?; Ok((Some(apply_smart_filters(&placed, sm, doc.bounds())?), warnings)) } @@ -363,9 +461,13 @@ pub(super) fn render_in(doc: &Document, sm: &SmartObject, ctx: &JobCtx) -> Resul let bytes = display_source(sm, &bytes); let (fmt, canvas) = (doc.pixel_format(), doc.bounds()); let mut placed_key = stack_cache::placed_key(&bytes, fmt, sm, canvas); - if photocraft_io::svg::is_svg(&bytes) { + if photocraft_io::is_svg_input(&name, &bytes) { let mut h = blake3::Hasher::new(); h.update(&placed_key); + if sm.stack_mode.is_some() { + // Old placed/filter stages may have been computed from omitted SVG data. + h.update(b"stack-svg-complete-v1:"); + } h.update(&crate::color_cmds::document_profile(doc).to_bytes()); placed_key = *h.finalize().as_bytes(); } diff --git a/crates/engine/src/cmd/smart_cmds/tests.rs b/crates/engine/src/cmd/smart_cmds/tests.rs index 2b1af57216..7ab56e89d6 100644 --- a/crates/engine/src/cmd/smart_cmds/tests.rs +++ b/crates/engine/src/cmd/smart_cmds/tests.rs @@ -5,6 +5,7 @@ mod selection; mod source_flatten; mod stack_cache; mod svg_profile; +mod svg_stack_completeness; const DEPTHS: [u64; 3] = [8, 16, 32]; const W: i32 = 64; diff --git a/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs b/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs index c7bb5eb22a..0a5c635d97 100644 --- a/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs +++ b/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs @@ -92,16 +92,23 @@ fn convert_to_layers_unpacks_full_canvas_shapes_in_a_4k_document() { /// and renders the rest of the drawing, as it did before the bounded render. #[test] fn svg_with_an_unreadable_embedded_image_still_places() { - let svg = ""; - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - let placed = crate::file_cmds::place_bytes(&mut s, "Logo.svg", svg.as_bytes().to_vec(), None, &json!({"smartObject": true})).unwrap(); - assert!(placed["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("embedded image was omitted"))); - let doc = &s.active().unwrap().doc; - let LayerContent::Smart(sm) = &doc.layer(LayerId(placed["layer"].as_u64().unwrap())).unwrap().content else { panic!("smart") }; - assert_eq!(sm.cache.as_ref().unwrap().rgba(6, 4), [1.0, 0.0, 0.0, 1.0]); - // A warning-bearing command must not poison the strict source/filter caches. - assert!(render(doc, sm).is_err()); + for href in ["data:image/x-foo,abc", "data:image/png;base64,A"] { + let svg = format!( + "" + ); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let placed = crate::file_cmds::place_bytes(&mut s, "Logo.svg", svg.as_bytes().to_vec(), None, &json!({"smartObject": true})).unwrap(); + let warnings = placed["warnings"].as_array().unwrap(); + assert_eq!(warnings.len(), 1, "{href}: {warnings:?}"); + assert!(warnings[0].as_str().unwrap().contains("embedded image was omitted")); + let doc = &s.active().unwrap().doc; + let LayerContent::Smart(sm) = &doc.layer(LayerId(placed["layer"].as_u64().unwrap())).unwrap().content else { panic!("smart") }; + assert_eq!(sm.cache.as_ref().unwrap().rgba(6, 4), [1.0, 0.0, 0.0, 1.0]); + assert!(matches!(&sm.source, SmartSource::Embedded { file_name, bytes } if file_name == "Logo.svg" && bytes.as_slice() == svg.as_bytes())); + // The warning render must neither repair the original bytes nor populate strict caches. + assert!(render(doc, sm).is_err(), "{href}"); + } } /// Warp setup needs only the source frame, found with the bounded parse and the exact canvas diff --git a/crates/engine/src/cmd/smart_cmds/tests/svg_stack_completeness.rs b/crates/engine/src/cmd/smart_cmds/tests/svg_stack_completeness.rs new file mode 100644 index 0000000000..2287bed438 --- /dev/null +++ b/crates/engine/src/cmd/smart_cmds/tests/svg_stack_completeness.rs @@ -0,0 +1,150 @@ +use super::super::{source, stack_cache}; +use super::*; + +fn incomplete_svg() -> Vec { + let image = photocraft_codecs::Image::from_u8(1, 1, photocraft_codecs::ChannelLayout::Rgba, vec![0, 255, 0, 255]).unwrap(); + let mut png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let idat = png.windows(4).position(|bytes| bytes == b"IDAT").unwrap(); + // Keep the complete IHDR and dimensions, but damage actual compressed pixels. + *png.get_mut(idat + 4).unwrap() ^= 0xff; + assert_eq!(photocraft_codecs::probe_allocation_size(&png).unwrap(), (1, 1)); + let data = png.iter().map(|byte| format!("%{byte:02X}")).collect::(); + format!("").into_bytes() +} + +fn smart_svg(bytes: Vec) -> SmartObject { + SmartObject::new(SmartSource::Embedded { file_name: "Stack completeness.svg".into(), bytes: Arc::new(bytes) }, Affine::IDENTITY, None) +} + +fn old_stack_key(bytes: &[u8], fmt: PixelFormat, mode: photocraft_doc::StackMode) -> ([u8; 32], PixelFormat) { + let mut key = source::cache_key(bytes, fmt); + key.0 = *blake3::hash(&[&key.0[..], b"stack:", mode.id().as_bytes()].concat()).as_bytes(); + key +} + +fn old_placed_key(bytes: &[u8], doc: &Document, smart: &SmartObject) -> StageKey { + let key = stack_cache::placed_key(bytes, doc.pixel_format(), smart, doc.bounds()); + let mut hash = blake3::Hasher::new(); + hash.update(&key); + hash.update(&crate::color_cmds::document_profile(doc).to_bytes()); + *hash.finalize().as_bytes() +} + +#[test] +fn gzipped_svg_sources_keep_omission_warnings_and_reject_legacy_stack_caches() { + use std::io::Write; + let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + encoder.write_all(&incomplete_svg()).unwrap(); + let bytes = encoder.finish().unwrap(); + let session = session(8); + let doc = &session.active().unwrap().doc; + for name in ["logo.gz", "without-extension"] { + let mut smart = SmartObject::new(SmartSource::Embedded { file_name: name.into(), bytes: Arc::new(bytes.clone()) }, Affine::IDENTITY, None); + let (ordinary, warnings) = render_with_warnings(doc, &smart).unwrap(); + assert_eq!(ordinary.unwrap().rgba(1, 1), [1., 0., 0., 1.]); + assert_eq!(warnings.len(), 1); + assert!(decode_source(name, &bytes).is_err(), "warningless source decoding must be complete"); + smart.stack_mode = Some(photocraft_doc::StackMode::Mean); + let mut poisoned = Surface::new(PixelFormat::RGBA32F); + poisoned.fill_rect(Rect::new(0, 0, 2, 2), &[0., 1., 0., 1.]); + source::cache_put( + old_stack_key(&bytes, PixelFormat::RGBA32F, photocraft_doc::StackMode::Mean), + source::SourceImage { surface: Arc::new(poisoned), bounds: Rect::new(0, 0, 2, 2) }, + ); + let mut poisoned = Surface::new(doc.pixel_format()); + poisoned.fill_rect(Rect::new(0, 0, 2, 2), &[0., 1., 0., 1.]); + stack_cache::put(old_placed_key(&bytes, doc, &smart), &Stage { surface: poisoned, extent: doc.bounds() }); + for _ in 0..2 { + assert!(stack_image(name, &bytes, PixelFormat::RGBA32F, photocraft_doc::StackMode::Mean).is_err()); + assert!(render(doc, &smart).is_err()); + assert!(render_with_warnings(doc, &smart).is_err()); + assert_eq!(source_box(doc, &smart), None); + } + } +} + +#[test] +fn svg_stack_rejects_incomplete_pixels_repeatedly_but_ordinary_placement_keeps_warnings() { + let session = session(8); + let doc = &session.active().unwrap().doc; + let bytes = incomplete_svg(); + let mut smart = smart_svg(bytes.clone()); + let (ordinary, warnings) = render_with_warnings(doc, &smart).unwrap(); + assert_eq!(ordinary.unwrap().rgba(1, 1), [1., 0., 0., 1.]); + assert_eq!(warnings.len(), 1); + assert!(warnings[0].contains("embedded image was omitted")); + smart.stack_mode = Some(photocraft_doc::StackMode::Mean); + for _ in 0..2 { + assert!(stack_image("Stack completeness.svg", &bytes, PixelFormat::RGBA32F, photocraft_doc::StackMode::Mean).is_err()); + assert!(render(doc, &smart).is_err()); + assert!(render_with_warnings(doc, &smart).is_err()); + assert_eq!(source_box(doc, &smart), None); + assert!(smart.cache.is_none()); + } +} + +#[test] +fn svg_stack_does_not_reuse_incomplete_legacy_source_or_filter_stages() { + let session = session(8); + let doc = &session.active().unwrap().doc; + let bytes = incomplete_svg(); + let mut smart = smart_svg(bytes.clone()); + smart.stack_mode = Some(photocraft_doc::StackMode::Mean); + let mut poisoned = Surface::new(PixelFormat::RGBA32F); + poisoned.fill_rect(Rect::new(0, 0, 2, 2), &[0., 1., 0., 1.]); + let key = old_stack_key(&bytes, PixelFormat::RGBA32F, photocraft_doc::StackMode::Mean); + source::cache_put(key, source::SourceImage { surface: Arc::new(poisoned), bounds: Rect::new(0, 0, 2, 2) }); + assert!(source::cache_get(&key).is_some(), "exercise a warm source entry from the old omission-permitting path"); + assert!(stack_image("Stack completeness.svg", &bytes, PixelFormat::RGBA32F, photocraft_doc::StackMode::Mean).is_err()); + + let mut poisoned = Surface::new(doc.pixel_format()); + poisoned.fill_rect(Rect::new(0, 0, 2, 2), &[0., 1., 0., 1.]); + let stage = Stage { surface: poisoned, extent: doc.bounds() }; + let placed = old_placed_key(&bytes, doc, &smart); + stack_cache::put(placed, &stage); + assert!(stack_cache::get(&placed).is_some()); + assert!(render(doc, &smart).is_err(), "old placed pixels must not bypass strict decoding"); + smart.smart_filters.push(SmartFilter { + command: "filter.blur.gaussianBlur".into(), + params: json!({"radius": 1}), + blend: BlendMode::Normal, + opacity: 1., + visible: true, + }); + let filtered = stack_cache::filter_key(&placed, &smart.smart_filters[0], None); + stack_cache::put(filtered, &stage); + assert!(stack_cache::get(&filtered).is_some()); + assert!(render(doc, &smart).is_err(), "old deepest filter stages must not bypass strict decoding"); + assert!(render_with_warnings(doc, &smart).is_err()); +} + +#[test] +fn complete_svg_stack_keeps_mean_pixels_across_source_stage_and_warning_render_caches() { + let bytes = br#""#; + let session = session(32); + let mut doc = (*session.active().unwrap().doc).clone(); + doc.icc_profile = Some(craft_cms::Builtin::Srgb.profile().to_bytes()); + let mut smart = smart_svg(bytes.to_vec()); + smart.stack_mode = Some(photocraft_doc::StackMode::Mean); + // The red/blue Mean is 0.5 in the SVG's U8 encoding. Existing source + // conversion rounds it to 128/255 before widening and decoding the sRGB + // transfer for F32. The explicit sRGB destination keeps the rendered result + // within ICC roundoff of that value (the matrix path is not bit-exact). + let expected = photocraft_color::convert::srgb_to_linear(128.0 / 255.0); + let check_mean = |pixel: [f32; 4]| { + assert!((pixel[0] - expected).abs() < 3e-5, "red Mean: {pixel:?}"); + assert!(pixel[1].abs() < 1e-6, "green Mean: {pixel:?}"); + assert!((pixel[2] - expected).abs() < 3e-5, "blue Mean: {pixel:?}"); + assert_eq!(pixel[3], 1.0); + }; + for _ in 0..2 { + let source = stack_image("Complete.svg", bytes, PixelFormat::RGBA32F, photocraft_doc::StackMode::Mean).unwrap(); + check_mean(source.surface.rgba(1, 1)); + let strict = render(&doc, &smart).unwrap().unwrap(); + check_mean(strict.rgba(1, 1)); + let (reported, warnings) = render_with_warnings(&doc, &smart).unwrap(); + assert_eq!(reported.unwrap(), strict); + assert!(warnings.is_empty()); + assert_eq!(source_box(&doc, &smart), Some([0., 0., 2., 2.])); + } +} diff --git a/crates/engine/src/cmd/smart_svg_cmds.rs b/crates/engine/src/cmd/smart_svg_cmds.rs index ca42123a08..9cd119bc94 100644 --- a/crates/engine/src/cmd/smart_svg_cmds.rs +++ b/crates/engine/src/cmd/smart_svg_cmds.rs @@ -385,6 +385,7 @@ fn update_contents_with_frame_budget(s: &mut Session, p: &Value, native: bool, f replacements.push(replacement); } // Finish every fallible render before committing any document state. + let mut sources = crate::smart_cmds::WarningRenderSources::new(doc); for replacement in &mut replacements { if let Some(preview) = vector_preview.as_ref() { // This exact SVG was fully validated above. Render only a disposable display @@ -402,7 +403,7 @@ fn update_contents_with_frame_budget(s: &mut Session, p: &Value, native: bool, f sm.cache = rendered.cache; } else { let LayerContent::Smart(sm) = &mut replacement.content else { return Err(EngineError::NoLayer(replacement.id)) }; - let (surface, omitted) = crate::smart_cmds::render_with_warnings(doc, sm)?; + let (surface, omitted) = crate::smart_cmds::render_with_warnings_using(sm, &mut sources)?; sm.cache = Some(surface.ok_or_else(|| bad(UPDATE, "SVG contents could not be rendered"))?); for warning in omitted { if !warnings.contains(&warning) { @@ -459,5 +460,7 @@ pub fn specs() -> Vec { ] } +#[cfg(test)] +mod source_cache_tests; #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/smart_svg_cmds/source_cache_tests.rs b/crates/engine/src/cmd/smart_svg_cmds/source_cache_tests.rs new file mode 100644 index 0000000000..43f06e4849 --- /dev/null +++ b/crates/engine/src/cmd/smart_svg_cmds/source_cache_tests.rs @@ -0,0 +1,301 @@ +use super::*; +use crate::smart_cmds::{WARNING_SOURCE_DECODES, WARNING_SOURCE_LIMIT, WarningRenderSources, render_with_warnings_using}; +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_doc::SmartFilter; +use photocraft_geom::Affine; + +fn artwork(width: u32, height: u32) -> String { + let image = photocraft_codecs::Image::from_u8(width, height, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat((width * height) as usize)).unwrap(); + let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let encoded = base64::engine::general_purpose::STANDARD.encode(png); + format!( + r##""## + ) +} + +fn object(svg: &str) -> SmartObject { + SmartObject::new(SmartSource::Embedded { file_name: "Memo.svg".into(), bytes: Arc::new(svg.as_bytes().to_vec()) }, Affine::IDENTITY, None) +} + +fn count() -> usize { + WARNING_SOURCE_DECODES.with(std::cell::Cell::get) +} + +fn reset() { + WARNING_SOURCE_DECODES.with(|count| count.set(0)); +} + +fn assert_update_warnings(result: &Value) { + let warnings = result["warnings"].as_array().unwrap(); + let omitted = "SVG: 1 embedded image was omitted"; + assert_eq!(warnings.iter().filter(|warning| warning.as_str().unwrap().starts_with(omitted)).count(), 1); + assert!(warnings.len() <= 2, "at most one omission and one image-layer information notice: {warnings:?}"); + assert!(warnings.iter().all(|warning| { + let warning = warning.as_str().unwrap(); + warning.starts_with(omitted) || warning == "SVG: embedded images are pixel layers" + })); +} + +fn draw(sources: &mut WarningRenderSources<'_>, sm: &SmartObject) -> photocraft_raster::Surface { + let (surface, warnings) = render_with_warnings_using(sm, sources).unwrap(); + assert_eq!(warnings.len(), 1); + surface.unwrap() +} + +fn shared_session(instances: usize) -> (Session, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width":32,"height":32})).unwrap(); + let original = br#""#; + let placed = crate::file_cmds::place_bytes(&mut s, "Shared.svg", original.to_vec(), None, &json!({"smartObject":true})).unwrap(); + let id = LayerId(placed["layer"].as_u64().unwrap()); + let first = s.active().unwrap().doc.layer(id).unwrap().clone(); + let doc = Arc::make_mut(&mut s.active_mut().unwrap().doc); + for index in 1..instances { + let mut layer = first.duplicate(); + let LayerContent::Smart(sm) = &mut layer.content else { panic!("smart") }; + sm.transform = Affine::translate((index % 4) as f64, (index % 3) as f64); + layer.opacity = 0.5; + doc.layers.push(layer); + } + (s, id) +} + +fn request(s: &mut Session, id: LayerId, svg: &str) -> Value { + let handoff = s.execute(EXPORT, json!({"layer":id.0})).unwrap(); + json!({"document":handoff["document"],"layer":id.0,"contentsId":handoff["contentsId"],"fingerprint":handoff["fingerprint"],"svg":svg}) +} + +#[test] +fn warning_source_profile_context_stays_lazy_for_non_svg_and_missing_sources() { + let doc = Document::new("Raster", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); + let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap(); + let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let sm = SmartObject::new(SmartSource::Embedded { file_name: "Raster.png".into(), bytes: Arc::new(png) }, Affine::IDENTITY, None); + let expected = crate::smart_cmds::render(&doc, &sm).unwrap(); + let mut sources = WarningRenderSources::new(&doc); + assert!(!sources.profile_initialized()); + reset(); + let (surface, warnings) = render_with_warnings_using(&sm, &mut sources).unwrap(); + assert_eq!(surface, expected); + assert!(warnings.is_empty()); + assert!(!sources.profile_initialized(), "a strict non-SVG cache hit needs no SVG color context"); + let missing = SmartObject::new(SmartSource::Linked { path: String::new() }, Affine::IDENTITY, None); + let (surface, warnings) = render_with_warnings_using(&missing, &mut sources).unwrap(); + assert!(surface.is_none()); + assert!(warnings.is_empty()); + assert!(!sources.profile_initialized()); + assert_eq!(count(), 0); + draw(&mut sources, &object(&artwork(4, 4))); + assert!(sources.profile_initialized()); + assert_eq!(count(), 1); +} + +#[test] +fn shared_svg_update_decodes_one_source_for_equal_scale_and_keeps_warning_caches_private() { + let (mut s, id) = shared_session(100); + let before = s.active().unwrap().doc.clone(); + let svg = artwork(8, 8); + let params = request(&mut s, id, &svg); + reset(); + let result = s.execute(UPDATE, params).unwrap(); + assert_eq!(count(), 1, "each placement must reuse the update's source-space render"); + assert_update_warnings(&result); + let doc = &s.active().unwrap().doc; + let instances: Vec<_> = doc.layers.iter().filter(|layer| matches!(&layer.content, LayerContent::Smart(_))).collect(); + assert_eq!(instances.len(), 100); + for layer in instances { + let sm = smart(doc, layer.id).unwrap(); + let previous = before.layer(layer.id).unwrap(); + assert_eq!(layer.opacity, previous.opacity); + assert_eq!(sm.transform, smart(&before, layer.id).unwrap().transform); + assert_eq!(embedded(doc, sm).unwrap().1, svg.as_bytes()); + let x = sm.transform.m[4] as i32; + let y = sm.transform.m[5] as i32; + assert_eq!(sm.cache.as_ref().unwrap().rgba(x + 3, y + 3), [0., 1., 0., 1.]); + } + let sm = smart(doc, id).unwrap(); + assert!(crate::smart_cmds::render(doc, sm).is_err(), "strict global cache must remain unpoisoned"); + let mut stack = sm.clone(); + stack.stack_mode = Some(photocraft_doc::StackMode::Mean); + assert!(crate::smart_cmds::render(doc, &stack).is_err(), "Stack Mode still requires complete artwork"); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + assert!(s.redo()); + assert_eq!(embedded(&s.active().unwrap().doc, smart(&s.active().unwrap().doc, id).unwrap()).unwrap().1, svg.as_bytes()); +} + +#[test] +fn local_svg_sources_separate_scale_and_profile_but_keep_instance_filters_and_placement() { + let mut doc = Document::new("Profile", Size::new(64, 64), ColorMode::Rgb, SampleType::F32); + doc.icc_profile = Some(craft_cms::Builtin::Srgb.profile().to_bytes()); + let mut linear = doc.clone(); + linear.icc_profile = Some(craft_cms::Builtin::LinearSrgb.profile().to_bytes()); + let first = object(&artwork(4, 4)); + let mut moved = first.clone(); + moved.transform = Affine::translate(20., 0.); + moved.smart_filters.push(SmartFilter { + command: "image.adjustments.invert".into(), + params: json!({}), + blend: photocraft_color::BlendMode::Normal, + opacity: 0.5, + visible: true, + }); + let mut sources = WarningRenderSources::new(&doc); + reset(); + let a = draw(&mut sources, &first); + let b = draw(&mut sources, &moved); + assert_eq!(count(), 1); + assert_eq!(a.rgba(3, 3), [0., 1., 0., 1.]); + assert_eq!(b.rgba(3, 3), [0.; 4]); + assert!(b.rgba(23, 3).iter().take(3).all(|value| (*value - 0.5).abs() < 0.01)); + let mut scaled = first.clone(); + scaled.transform = Affine { m: [2., 0., 0., 2., 0., 0.] }; + draw(&mut sources, &scaled); + assert_eq!(count(), 2, "different raster scales require different source renders"); + let corrected = draw(&mut WarningRenderSources::new(&linear), &first); + assert_eq!(count(), 3, "a different document interpretation cannot reuse the earlier source"); + assert!((a.rgba(12, 3)[0] - 0.502).abs() < 0.01); + assert!((corrected.rgba(12, 3)[0] - 0.216).abs() < 0.01); + assert_eq!(draw(&mut sources, &first), a); + assert_eq!(count(), 3); +} + +#[test] +fn local_svg_source_memo_evicts_and_oversize_entries_render_without_retention() { + let mut doc = Document::new("Budget", Size::new(64, 64), ColorMode::Rgb, SampleType::U8); + doc.icc_profile = Some(craft_cms::Builtin::Srgb.profile().to_bytes()); + let first = object(&artwork(4, 4)); + let mut scaled = first.clone(); + scaled.transform = Affine { m: [2., 0., 0., 2., 0., 0.] }; + let tile = photocraft_raster::tile_storage_bytes(Rect::new(0, 0, 32, 32), &PixelFormat::RGBA8) as usize; + for (budget, limit) in [(tile + 4096, 32), (usize::MAX, 1)] { + let mut sources = WarningRenderSources::with_limits(&doc, budget, limit); + reset(); + let expected = draw(&mut sources, &first); + draw(&mut sources, &scaled); + assert_eq!(draw(&mut sources, &first), expected); + assert_eq!(count(), 3, "byte and entry limits both evict the old scale"); + } + let huge_source = artwork(4, 4).replace("", &format!("", " ".repeat(tile + 8192))); + let encoded = object(&huge_source); + let mut sources = WarningRenderSources::with_limits(&doc, tile + 4096, 32); + reset(); + let expected = draw(&mut sources, &encoded); + assert_eq!(draw(&mut sources, &encoded), expected); + assert_eq!(count(), 2, "retained encoded bytes count even for a tiny output"); + let mut disabled = WarningRenderSources::with_limits(&doc, 0, 0); + assert_eq!(draw(&mut disabled, &first), draw(&mut WarningRenderSources::new(&doc), &first)); +} + +#[test] +fn shared_svg_update_render_failure_and_cancelled_authorization_preserve_document_history() { + for cancel in [false, true] { + let (mut s, id) = shared_session(2); + let doc = Arc::make_mut(&mut s.active_mut().unwrap().doc); + let LayerContent::Smart(sm) = &mut doc.layers.last_mut().unwrap().content else { panic!("smart") }; + sm.smart_filters.push(SmartFilter { + command: if cancel { "image.adjustments.invert" } else { "unsupported.persisted.filter" }.into(), + params: json!({}), + blend: photocraft_color::BlendMode::Normal, + opacity: 1., + visible: true, + }); + if cancel { + s.authorize = Some(|command, _| if command == "image.adjustments.invert" { Err(EngineError::Cancelled) } else { Ok(()) }); + } + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.entries(); + let revision = s.active().unwrap().revision; + let params = request(&mut s, id, &artwork(4, 4)); + reset(); + let error = s.execute(UPDATE, params).unwrap_err(); + if cancel { + assert!(matches!(error, EngineError::Cancelled), "expected the authority cancellation, got {error}"); + } else { + assert!(error.to_string().contains("unsupported visible filters"), "{error}"); + } + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.entries(), history); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(count(), if cancel { 0 } else { 1 }); + } +} + +#[test] +fn shared_svg_update_keeps_the_existing_placed_pixel_budget_atomic() { + let (mut s, id) = shared_session(2); + let LayerContent::Smart(sm) = &mut Arc::make_mut(&mut s.active_mut().unwrap().doc).layers.last_mut().unwrap().content else { panic!("smart") }; + sm.transform = Affine { m: [1000., 0., 0., 1000., 0., 0.] }; + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.entries(); + let revision = s.active().unwrap().revision; + let params = request(&mut s, id, &artwork(4, 4)); + reset(); + assert!(s.execute(UPDATE, params).is_err()); + assert_eq!(count(), 0, "placed-frame admission precedes source rendering"); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.active().unwrap().history.entries(), history); + assert_eq!(s.active().unwrap().revision, revision); +} + +#[test] +#[ignore = "24MP embedded PNG / 100 shared instances; run once in release for performance qualification"] +fn shared_svg_update_24mp_source_timing() { + struct MemoLimit(Option); + impl MemoLimit { + fn set(limit: usize) -> Self { + Self(WARNING_SOURCE_LIMIT.with(|current| current.replace(Some(limit)))) + } + } + impl Drop for MemoLimit { + fn drop(&mut self) { + WARNING_SOURCE_LIMIT.with(|current| current.set(self.0)); + } + } + let previous_limit = WARNING_SOURCE_LIMIT.with(std::cell::Cell::get); + // Encode once. Each pass builds the same initial document and handoff outside + // the clock; UPDATE includes its normal import and all instance rendering. + let svg = artwork(6000, 4000); + let mut expected = None; + let mut timings = Vec::new(); + for (label, limit, decodes) in [("optimized-before", 32, 1), ("memo-off", 0, 100), ("optimized-after", 32, 1)] { + let (mut s, id) = shared_session(100); + let params = request(&mut s, id, &svg); + let _restore = MemoLimit::set(limit); + reset(); + let start = std::time::Instant::now(); + let result = s.execute(UPDATE, params).unwrap(); + let elapsed = start.elapsed().as_secs_f64() * 1000.; + assert_eq!(count(), decodes, "{label}"); + assert_update_warnings(&result); + let doc = &s.active().unwrap().doc; + let mut pixels = blake3::Hasher::new(); + let mut sources = blake3::Hasher::new(); + let mut samples = Vec::new(); + for layer in doc.layers.iter().filter(|layer| matches!(&layer.content, LayerContent::Smart(_))) { + let sm = smart(doc, layer.id).unwrap(); + let source = embedded(doc, sm).unwrap().1; + assert_eq!(source, svg.as_bytes()); + sources.update(blake3::hash(source).as_bytes()); + let cache = sm.cache.as_ref().unwrap(); + for value in cache.read_region(doc.bounds()) { + pixels.update(&value.to_bits().to_le_bytes()); + } + let (x, y) = (sm.transform.m[4] as i32, sm.transform.m[5] as i32); + let sample = cache.rgba(x + 3, y + 3); + assert_eq!(sample, [0., 1., 0., 1.]); + samples.push(sample); + } + assert_eq!(samples.len(), 100); + let signature = (*pixels.finalize().as_bytes(), *sources.finalize().as_bytes(), samples, result["warnings"].clone()); + if let Some(expected) = &expected { + assert_eq!(&signature, expected, "pixels, samples, encoded sources and warnings must match: {label}"); + } else { + expected = Some(signature); + } + eprintln!("24MP PNG / 16x16 SVG / 100 shared instances: {label}: {elapsed:.3} ms, {decodes} source renders"); + timings.push(elapsed); + } + eprintln!("optimized median of two: {:.3} ms; memo-off: {:.3} ms", (timings[0] + timings[2]) / 2., timings[1]); + assert_eq!(WARNING_SOURCE_LIMIT.with(std::cell::Cell::get), previous_limit, "test override restored"); +} diff --git a/crates/engine/src/cmd/smart_svg_cmds/tests.rs b/crates/engine/src/cmd/smart_svg_cmds/tests.rs index 5945470a0f..f6ad26ff51 100644 --- a/crates/engine/src/cmd/smart_svg_cmds/tests.rs +++ b/crates/engine/src/cmd/smart_svg_cmds/tests.rs @@ -419,13 +419,24 @@ fn original_vector_formats_save_atomically_and_survive_undo_and_persistence() { /// is accepted with that image left out, as placing the same SVG is. #[test] fn saved_svg_with_an_unreadable_embedded_image_still_updates() { - let (mut s, id) = session(8); - let edited = r#""#; - let params = request(&mut s, id, edited); - let result = s.execute(UPDATE, params).unwrap(); - assert_eq!(result["updated"], true); - assert!(result["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("embedded image was omitted"))); - assert_eq!(source(&s, id), edited.as_bytes()); + for href in ["data:image/bmp,BM", "data:image/png;base64,A"] { + let (mut s, id) = session(8); + let edited = format!( + r#""# + ); + let params = request(&mut s, id, &edited); + let result = s.execute(UPDATE, params).unwrap(); + assert_eq!(result["updated"], true); + let warnings = result["warnings"].as_array().unwrap(); + assert_eq!(warnings.len(), 1, "{href}: {warnings:?}"); + assert!(warnings[0].as_str().unwrap().contains("embedded image was omitted")); + assert_eq!(source(&s, id), edited.as_bytes()); + let doc = &s.active().unwrap().doc; + let sm = smart(doc, id).unwrap(); + assert_eq!(sm.cache.as_ref().unwrap().rgba(18, 11), [0.0, 0.0, 1.0, 1.0]); + assert!(crate::smart_cmds::render(doc, sm).is_err(), "warning-bearing save must not populate strict caches: {href}"); + assert_eq!(source(&s, id), edited.as_bytes(), "strict refusal must leave the unrepaired source intact"); + } } /// updateSvg replaces SVG contents only: it never turns an AI, PDF or EPS source into SVG. diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 6d7332ca03..aafa63c810 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -53,6 +53,12 @@ craft-tiff = { workspace = true } craft-crs = { workspace = true } craft-xml = { workspace = true } thiserror = { workspace = true } +# Match the SVG renderer decoder backends when validating optional images. +zune-core = { workspace = true } +zune-jpeg = { workspace = true } +gif = { workspace = true } +image-webp = { workspace = true } +data-url = { workspace = true } ttf-parser = "0.25.1" serde_json = { workspace = true } blake3 = { version = "1.8", default-features = false, features = ["pure"] } diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 4d94295064..d61d378d70 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -10,7 +10,6 @@ //! stops and direction in the layer's own gradient fill, with a warning that the exact geometry //! is not kept. -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, OnceLock, PoisonError}; use craft_svg::tree::draw::{self, tiny_skia}; @@ -25,6 +24,10 @@ use photocraft_raster::Surface; use crate::{ImportResult, IoError}; +mod data_href_validation; +mod image_integrity; +mod raster_validation; + /// Hard caps on the memory resvg needs to draw a subtree, checked before it draws: craft-svg's /// `tree::draw`, within this crate's peak pixel budget. #[cfg(test)] @@ -377,7 +380,13 @@ fn parse_at_depth(depth: usize, isolated: bool, parse: impl FnOnce(bool /// Supplies bounded parsing options to direct resolver tests without changing their existing interface. #[cfg(test)] fn options(fontdb: Arc, depth_left: usize) -> usvg::Options<'static> { - options_with_isolation(fontdb, depth_left, false, Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(depth_left, MAX_RASTER_PIXELS)))) + options_with_isolation( + fontdb, + depth_left, + false, + Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(depth_left, MAX_RASTER_PIXELS))), + Arc::new(Mutex::new(image_integrity::Integrity::new(MAX_RASTER_PIXELS))), + ) } /// Parse options for an untrusted drawing. `` resolves only `data:` URLs: a file path @@ -390,8 +399,15 @@ fn options_with_isolation( _depth_left: usize, _isolated: bool, image_resolver: Arc, + integrity: Arc>, ) -> usvg::Options<'static> { - usvg::Options { resources_dir: None, image_href_resolver: image_resolver.resolver(), fontdb, font_resolver: font_resolver(), ..usvg::Options::default() } + usvg::Options { + resources_dir: None, + image_href_resolver: image_integrity::wrap(image_resolver.resolver(), integrity), + fontdb, + font_resolver: font_resolver(), + ..usvg::Options::default() + } } /// A parsed drawing. @@ -451,16 +467,20 @@ fn parse_with_image_limit(bytes: &[u8], fonts: fn() -> Arc, resolver: Arc, + integrity: Arc>, } /// Record the first budget or decoding failure seen while usvg resolves images. Resolver @@ -549,16 +570,17 @@ fn parse_image_bounded_with( budget.lock().unwrap_or_else(PoisonError::into_inner).fontless_text = true; } let resolver = Arc::clone(&budget.lock().unwrap_or_else(PoisonError::into_inner).resolver); + let integrity = Arc::clone(&budget.lock().unwrap_or_else(PoisonError::into_inner).integrity); let text = std::str::from_utf8(&xml).map_err(|_| IoError::Svg("the SVG is not valid UTF-8".into()))?; - resolver.check_document(text).map_err(svg_parse_error)?; - let refusals = Arc::new(SvgRefusals::default()); - let mut opt = options_with_isolation(fontdb, xml_left, isolated, Arc::clone(&resolver)); - opt.image_href_resolver = noting_refusals(opt.image_href_resolver, resolver, Arc::clone(&refusals)); let limits = tree_limits(xml_left, MAX_RASTER_PIXELS); - let tree = guarded_parse(|| craft_svg::tree::parse_text(text, &limits, &opt))?; - let tree = tree.map_err(svg_parse_error)?; + let opt = options_with_isolation(fontdb, xml_left, isolated, resolver, integrity); + let tree = guarded_parse(|| { + data_href_validation::with_repaired_xml(text, &limits, |xml| { + usvg::Tree::from_xmltree(xml, &opt).map_err(|error| svg_parse_error(craft_svg::tree::Error::Parse(error.to_string()))) + }) + })??; let mut counter = budget.lock().unwrap_or_else(PoisonError::into_inner); - let usage = counter.resolver.usage(); + let usage = counter.integrity.lock().unwrap_or_else(PoisonError::into_inner).usage(counter.resolver.usage())?; counter.pixels = counter.pixels.saturating_sub(usage.raster_pixels); counter.xml_bytes = counter.xml_bytes.saturating_sub(u64::try_from(usage.embedded_svg_bytes).unwrap_or(u64::MAX)); counter.svg_images = usage.embedded_svg_count as u64; @@ -567,7 +589,7 @@ fn parse_image_bounded_with( // whose XML depth exceeds the allowance left by the outer drawing. 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 usage.svg_resource_limit_images > 0 || (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()); @@ -593,116 +615,6 @@ fn parse_image_bounded_with( }) } -/// Why craft-svg left embedded SVG images out of one bounded parse. Its usage counts every -/// refused SVG image together, but an image past [`MAX_EMBEDDED_SVG_DEPTH`] or the byte budget -/// fails even a non-strict parse, as the bounded path did before craft-svg, while one nested -/// too deeply in XML or that can't be unpacked (gzip inside gzip, a damaged stream, an unknown -/// encoding) only leaves itself out. -#[derive(Default)] -struct SvgRefusals { - /// Embedded SVG images being resolved around the current one. - depth: AtomicUsize, - /// An image was refused for the chain depth or the byte budget. - over_budget: AtomicBool, - /// Bytes craft-svg charged images that couldn't be unpacked: it charges such an image - /// 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, - /// Bytes unpacked again to tell those images apart, at most one byte budget per drawing. - rechecked: AtomicUsize, - /// Source bytes decoded during refusal rechecks, at most one byte budget per drawing. - text_rechecked: AtomicUsize, -} - -/// 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 -/// for size after unreadable images were charged, the data is unpacked once more within the -/// budget less only the drawing's content; past that, or past what may be unpacked again, the -/// drawing is over budget. -fn note_byte_refusal(data: &[u8], used: usize, refusals: &SvgRefusals) { - let budget = usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap_or(usize::MAX); - let left = budget.saturating_sub(used); - let unread = refusals.unread_charges.load(Ordering::Relaxed); - match craft_svg::svgz::text(data, left) { - Ok(text) if text.len() > left => refusals.over_budget.store(true, Ordering::Relaxed), - Ok(_) => {} - 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)); - // Rechecks may inflate or allocate text for a legacy encoding. - 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 }; - // Bound inflation and text-conversion work independently from content size. - let (unpacked, too_large) = match craft_svg::svgz::inflate(data, limit) { - Ok(xml) => { - // Inflation and text conversion have separate work allowances: a fitting - // Latin-1 document must not spend its UTF-8 size against inflation bytes. - // Charge source bytes before decoding, including invalid encodings. The - // supported encodings expand by at most 2x, so conversion work stays bounded - // even for plain children that do not require inflation. - let text_left = budget.saturating_sub(refusals.text_rechecked.load(Ordering::Relaxed)); - let too_large = if xml.len() > text_left { - true - } else { - refusals.text_rechecked.fetch_add(xml.len(), Ordering::Relaxed); - craft_svg::svgz::decode(&xml).is_ok_and(|text| text.len() > content_left) - }; - (if compressed { xml.len() } else { 0 }, too_large) - } - Err(craft_svg::svgz::Error::Nested(len)) => (len, false), - Err(craft_svg::svgz::Error::TooLarge(_)) => (if compressed { limit } else { 0 }, true), - Err(_) => (limit, false), - }; - refusals.rechecked.fetch_add(unpacked, Ordering::Relaxed); - if too_large { - refusals.over_budget.store(true, Ordering::Relaxed); - } else { - refusals.unread_charges.fetch_add(left, Ordering::Relaxed); - } - } - Err(_) => { - refusals.unread_charges.fetch_add(left, Ordering::Relaxed); - } - } -} - -/// `resolve`, also noting in `refusals` why craft-svg is about to refuse each embedded SVG. It -/// repeats craft-svg's first two checks in their order: the chain depth, then unpacking within -/// what the byte budget has left (`text/plain` data is an SVG unless it is a raster craft-svg -/// draws). -fn noting_refusals( - resolve: usvg::ImageHrefResolver<'static>, - resolver: Arc, - refusals: Arc, -) -> usvg::ImageHrefResolver<'static> { - let usvg::ImageHrefResolver { resolve_data, resolve_string } = resolve; - usvg::ImageHrefResolver { - resolve_data: Box::new(move |mime, data, options| { - let raster = matches!( - photocraft_codecs::detect(&data), - Some(photocraft_codecs::Format::Png | photocraft_codecs::Format::Jpeg | photocraft_codecs::Format::Gif | photocraft_codecs::Format::WebP) - ); - if !(mime == "image/svg+xml" || (mime == "text/plain" && !raster)) { - return resolve_data(mime, data, options); - } - // Once over budget the drawing fails whatever follows, so nothing more is unpacked. - if !refusals.over_budget.load(Ordering::Relaxed) { - if refusals.depth.load(Ordering::Relaxed) >= MAX_EMBEDDED_SVG_DEPTH { - refusals.over_budget.store(true, Ordering::Relaxed); - } else { - note_byte_refusal(&data, resolver.usage().embedded_svg_bytes, &refusals); - } - } - refusals.depth.fetch_add(1, Ordering::Relaxed); - let image = resolve_data(mime, data, options); - refusals.depth.fetch_sub(1, Ordering::Relaxed); - image - }), - resolve_string, - } -} - /// Used paint/effect resources can decode an image once per use. Ordinary paths, gradients, /// clipping paths and blur filters without image references do not multiply unrelated photos. fn repeatable_image_resources(tree: &usvg::Tree) -> (bool, bool) { @@ -805,12 +717,17 @@ fn parse_bounded_work_with(bytes: &[u8], max_pixels: u64, strict: bool, fonts: f strict, error: None, resolver: Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(MAX_XML_DEPTH, max_pixels.min(MAX_RASTER_PIXELS)))), + integrity: Arc::new(Mutex::new(image_integrity::Integrity::new(max_pixels))), })); let tree = parse_image_bounded_with(bytes, budget.clone(), MAX_XML_DEPTH, fonts, false)?; 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, image_usage: counter.resolver.usage() }, + parsed: Parsed { + tree, + fontless_text: counter.fontless_text, + image_usage: counter.integrity.lock().unwrap_or_else(PoisonError::into_inner).usage(counter.resolver.usage())?, + }, svg_images: counter.svg_images, svg_chain: counter.svg_chain, decoded, diff --git a/crates/io/src/svg/data_href_validation.rs b/crates/io/src/svg/data_href_validation.rs new file mode 100644 index 0000000000..9fbb12bfb4 --- /dev/null +++ b/crates/io/src/svg/data_href_validation.rs @@ -0,0 +1,415 @@ +//! Repair data-URL failures that usvg drops before invoking its image resolver. +//! This changes only attribute values. Resolver callbacks still decide whether an +//! image is used, so hidden/unused resources do not acquire omission warnings. + +use std::borrow::Cow; +use std::ops::Range; + +use crate::IoError; +use craft_svg::tree::Limits; + +#[cfg(test)] +const SVG_NS: &str = "http://www.w3.org/2000/svg"; +const XLINK_NS: &str = "http://www.w3.org/1999/xlink"; +const INVALID_IMAGE: &str = "data:image/png,%00"; +const IGNORED_DATA: &str = "data:application/octet-stream,%00"; + +struct Patch { + range: Range, + replacement: &'static str, +} + +fn invalid(message: &str) -> IoError { + IoError::Svg(message.into()) +} + +/// Validate the original decoded XML before patching it. The caller must charge +/// its original bytes/work before any shorter result replaces an embedded source. +/// This does not rewrite an XML encoding declaration for a UTF-8 byte transport. +pub(super) fn repair<'a>(text: &'a str, limits: &Limits) -> Result, IoError> { + if !text.contains("href") && !text.starts_with("( + text: &str, + limits: &Limits, + convert: impl FnOnce(&super::usvg::roxmltree::Document<'_>) -> Result, +) -> Result { + let xml = checked_xml(text, limits)?; + match repair_xml(text, limits, &xml)? { + Cow::Borrowed(_) => convert(&xml), + Cow::Owned(repaired) => { + drop(xml); + let xml = checked_xml(&repaired, limits)?; + convert(&xml) + } + } +} + +// These are the same preflight and expanded-reference guards used by the +// shared tree parser, before its public from_xmltree conversion. Do not replace +// this with an unbounded XML parse or feed an unchecked DOM to usvg. +fn checked_xml<'a>(text: &'a str, limits: &Limits) -> Result, IoError> { + #[cfg(test)] + XML_PARSES.with(|count| count.set(count.get().saturating_add(1))); + let xml_limits = craft_svg::preflight::Limits { + bytes: limits.bytes, + depth: limits.depth, + entity_bytes: limits.entity_bytes, + refuse_entity_markup: limits.refuse_entity_markup, + attributes: limits.attributes, + attribute_work: limits.attribute_work, + xml_nodes: limits.xml_nodes, + }; + let xml = craft_svg::preflight::parse_text(text, &xml_limits).map_err(|error| match error { + craft_svg::preflight::Error::TooDeep(_) => invalid("layers are nested too deeply"), + error => IoError::Svg(error.to_string()), + })?; + if craft_svg::tree::height(&xml, limits.tree_depth).map_err(super::svg_parse_error)?.is_none() { + return Err(invalid("layers are nested too deeply")); + } + Ok(xml) +} + +fn repair_xml<'a>(text: &'a str, limits: &Limits, xml: &super::usvg::roxmltree::Document<'a>) -> Result, IoError> { + if !text.contains("href") { + return Ok(Cow::Borrowed(text)); + } + // The expanded attribute values fit source + entity work. Streaming URL + // validation reads them and emits at most that much decoded data, never a Vec. + let mut work = + text.len().checked_add(limits.entity_bytes).and_then(|n| n.checked_mul(2)).ok_or_else(|| invalid("SVG data-URL validation work exceeds its limit"))?; + let max_patches = (limits.bytes / std::mem::size_of::()).min(usize::try_from(limits.xml_nodes).unwrap_or(usize::MAX)); + let mut patches: Vec = Vec::new(); + for node in xml.descendants().filter(|node| node.is_element()) { + if !matches!(node.tag_name().name(), "image" | "feImage") { + continue; + } + // Shared preflight inspects local image names in every namespace and + // checks XLink before plain href. Normalize both representations, even + // when one is inert or unselected. Only actual resolver callbacks count + // omissions, so this does not turn hidden/unused resources into warnings. + for href in node.attributes().filter(|a| a.name() == "href" && matches!(a.namespace(), None | Some(XLINK_NS))) { + let Some(replacement) = malformed_data_url_replacement(href.value(), &mut work)? else { continue }; + let range = verified_value_range(text, node.range(), href.range(), href.range_qname(), href.range_value(), href.name())?; + if patches.len() == patches.capacity() { + if patches.len() >= max_patches { + return Err(invalid("SVG data-URL repair metadata exceeds its limit")); + } + let capacity = patches.capacity().max(8).saturating_mul(2).min(max_patches); + patches.try_reserve_exact(capacity.saturating_sub(patches.len())).map_err(|_| invalid("could not allocate bounded SVG data-URL repairs"))?; + } + patches.push(Patch { range, replacement }); + } + } + if patches.is_empty() { + return Ok(Cow::Borrowed(text)); + } + patches.sort_unstable_by_key(|patch| (patch.range.start, patch.range.end)); + patches.dedup_by_key(|patch| (patch.range.start, patch.range.end)); + let mut end = 0; + let mut length = text.len(); + for patch in &patches { + let range = &patch.range; + if range.start < end { + return Err(invalid("SVG data-URL source ranges overlap")); + } + end = range.end; + length = length + .checked_sub(range.len()) + .and_then(|n| n.checked_add(patch.replacement.len())) + .ok_or_else(|| invalid("SVG data-URL repair size overflows"))?; + } + if length > limits.bytes { + return Err(invalid("repaired SVG exceeds the text byte limit")); + } + let mut result = String::new(); + result.try_reserve_exact(length).map_err(|_| invalid("could not allocate bounded repaired SVG text"))?; + let mut cursor = 0; + for patch in patches { + result.push_str(text.get(cursor..patch.range.start).ok_or_else(|| invalid("invalid SVG data-URL source range"))?); + result.push_str(patch.replacement); + cursor = patch.range.end; + } + result.push_str(text.get(cursor..).ok_or_else(|| invalid("invalid SVG data-URL source range"))?); + Ok(Cow::Owned(result)) +} + +// The pinned MIME parser searches all earlier parameters for each new name. +// Cap even quoted semicolons before invoking it: source-byte work is already +// charged, so at most this constant times the bounded XML work reaches MIME +// parsing. Bodies can remain large without acquiring MIME parameter records. +const MAX_MIME_SEPARATORS: usize = 64; + +fn mime_header_admitted(value: &str) -> bool { + let trimmed = value.trim_start_matches(|ch| ch <= ' '); + let mut bytes = trimmed.bytes(); + for expected in b"data:" { + let Some(actual) = bytes.by_ref().find(|&byte| !matches!(byte, b'\t' | b'\n' | b'\r')) else { return true }; + if !actual.eq_ignore_ascii_case(expected) { + return true; // Not a data URL: preserve external/fragment handling. + } + } + let mut separators = 0; + for byte in bytes { + if matches!(byte, b',' | b'#') { + break; + } + if byte == b';' { + separators += 1; + if separators > MAX_MIME_SEPARATORS { + return false; + } + } + } + true +} + +fn malformed_data_url_replacement(value: &str, work: &mut usize) -> Result, IoError> { + malformed_data_url_replacement_with(value, work, data_url::DataUrl::process) +} + +fn malformed_data_url_replacement_with<'a>( + value: &'a str, + work: &mut usize, + parse: impl FnOnce(&'a str) -> Result, data_url::DataUrlError>, +) -> Result, IoError> { + *work = work.checked_sub(value.len()).ok_or_else(|| invalid("SVG data-URL validation work exceeds its limit"))?; + if !mime_header_admitted(value) { + // Strip parameters before recovering MIME disposition; no original + // parameter list reaches either our parser or shared whole-DOM preflight. + return missing_comma_replacement(value, work).map(Some); + } + let url = match parse(value) { + Ok(url) => url, + Err(data_url::DataUrlError::NoComma) => return missing_comma_replacement(value, work).map(Some), + Err(data_url::DataUrlError::NotADataUrl) => return Ok(None), + }; + let mut exhausted = false; + let decoded = url.decode(|bytes| { + if let Some(left) = work.checked_sub(bytes.len()) { + *work = left; + Ok(()) + } else { + exhausted = true; + Err(()) + } + }); + if exhausted { + return Err(invalid("SVG data-URL validation work exceeds its limit")); + } + Ok(decoded.is_err().then(|| replacement_for_mime(url.mime_type()))) +} + +/// Preflight must see a valid URL, while the resolver must keep its original +/// disposition. Non-image MIME types are ignored even when their body is bad. +fn replacement_for_mime(mime: &data_url::mime::Mime) -> &'static str { + if mime.type_ == "image" || mime.matches("text", "plain") { INVALID_IMAGE } else { IGNORED_DATA } +} + +fn missing_comma_replacement(value: &str, work: &mut usize) -> Result<&'static str, IoError> { + // NoComma does not expose its MIME type. Ask the same parser about a header + // with an empty body rather than guessing MIME defaults, case or parameters. + // Match its URL C0 trimming; fragments and MIME parameters cannot affect + // the image/text-plain essence. Do not allocate parameter bookkeeping for a + // hostile missing-comma header just to recover that disposition. + let normalized = value.trim_matches(|ch| ch <= ' '); + let header = normalized.split_once('#').map_or(normalized, |(header, _)| header); + let essence = header.split_once(';').map_or(header, |(essence, _)| essence); + *work = work.checked_sub(essence.len()).ok_or_else(|| invalid("SVG data-URL validation work exceeds its limit"))?; + let length = essence.len().checked_add(1).ok_or_else(|| invalid("SVG data-URL repair size overflows"))?; + let mut candidate = String::new(); + candidate.try_reserve_exact(length).map_err(|_| invalid("could not allocate bounded SVG data-URL header"))?; + candidate.push_str(essence); + candidate.push(','); + // This candidate has no MIME parameters, including for oversized original + // lists. Its byte scan/allocation is charged above before the linear parse. + if !mime_header_admitted(&candidate) { + return Err(invalid("SVG data-URL MIME header exceeds its limit")); + } + let url = data_url::DataUrl::process(&candidate).map_err(|_| invalid("invalid SVG data-URL header framing"))?; + Ok(replacement_for_mime(url.mime_type())) +} + +/// roxmltree bounds QName and equals-spacing bookkeeping internally. Refuse a +/// projection that does not identify the attribute's actual quoted value, rather +/// than editing a truncated position or a DTD entity declaration by mistake. +fn verified_value_range( + text: &str, + owner: Range, + attribute: Range, + qname: Range, + value: Range, + local_name: &str, +) -> Result, IoError> { + let error = || invalid("SVG data-URL attribute source positions cannot be represented safely"); + if attribute.start < owner.start || attribute.end > owner.end || qname.start != attribute.start || qname.end > value.start { + return Err(error()); + } + let open = value.start.checked_sub(1).ok_or_else(error)?; + if value.end.checked_add(1) != Some(attribute.end) || open < qname.end { + return Err(error()); + } + let name = text.get(qname.clone()).ok_or_else(error)?; + if name.rsplit(':').next() != Some(local_name) { + return Err(error()); + } + let equals = text.get(qname.end..open).ok_or_else(error)?; + if equals.trim_matches([' ', '\t', '\r', '\n']) != "=" { + return Err(error()); + } + let quote = text.get(open..value.start).ok_or_else(error)?; + if !matches!(quote, "'" | "\"") || text.get(value.end..attribute.end) != Some(quote) || text.get(value.clone()).is_none() { + return Err(error()); + } + Ok(value) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn limits() -> Limits { + Limits { bytes: 1 << 20, depth: 32, tree_depth: 32, entity_bytes: 65_536, ..Default::default() } + } + + #[test] + fn malformed_image_urls_are_repaired_in_both_svg_namespaces_and_filter_resources() { + for tag in ["image", "feImage"] { + for text in [ + format!("<{tag} href='data:image/png;base64,A'/>"), + format!("<{tag} href='data:image/png;base64,A'/>"), + format!(""), + ] { + let repaired = repair(&text, &limits()).unwrap(); + assert!(matches!(repaired, Cow::Owned(_))); + assert_eq!(repaired.matches(INVALID_IMAGE).count(), 1); + } + } + } + + #[test] + fn unselected_href_and_foreign_local_image_names_are_normalized_for_shared_preflight() { + for attrs in ["href='data:image/png,%00' x:href='data:image/png;base64,A'", "x:href='data:image/png;base64,A' href='data:image/png,%00'"] { + let text = format!(""); + let repaired = repair(&text, &limits()).unwrap(); + assert!(matches!(repaired, Cow::Owned(_))); + assert_eq!(repaired.matches(INVALID_IMAGE).count(), 2); + assert!(!repaired.contains("base64,A")); + } + let text = format!( + "" + ); + let repaired = repair(&text, &limits()).unwrap(); + assert_eq!(repaired.matches(INVALID_IMAGE).count(), 3); + assert!(repaired.contains("f:href='data:image/png;base64,A'"), "foreign href attributes remain inert and unchanged"); + } + + #[test] + fn both_href_forms_on_hidden_unused_and_foreign_resources_do_not_preflight_as_omissions() { + for tag in ["image", "feImage"] { + let text = format!( + "<{tag} id='unused' href='data:image/png;base64,A' x:href='data:image/png;base64,A'/><{tag} display='none' x:href='data:image/png;base64,A' href='data:image/png;base64,A'/>" + ); + let original = text.clone(); + let repaired = repair(&text, &limits()).unwrap(); + assert_eq!(text, original, "repair never mutates the original source"); + assert_eq!(repaired.matches(INVALID_IMAGE).count(), 6); + let resolver = craft_svg::tree::ImageResolver::new(limits()); + resolver.check_document(&repaired).unwrap(); + let usage = resolver.usage(); + assert_eq!( + (usage.invalid_raster_images, usage.invalid_svg_images), + (0, 0), + "shared whole-document scanning cannot invent omissions before resolution" + ); + assert!(matches!(repair(&repaired, &limits()).unwrap(), Cow::Borrowed(_)), "normalization is idempotent"); + } + } + + #[test] + fn entity_expanded_urls_patch_the_owning_attributes_without_rewriting_the_doctype() { + let text = format!( + "]>" + ); + let repaired = repair(&text, &limits()).unwrap(); + assert!(repaired.contains("")); + assert_eq!(repaired.matches(INVALID_IMAGE).count(), 2); + assert!(!repaired.contains("href='&bad;'")); + assert!(matches!(repair(&repaired, &limits()).unwrap(), Cow::Borrowed(_))); + } + + #[test] + fn valid_data_and_external_urls_are_not_rewritten() { + for value in ["data:image/png;base64,AA==", "data:image/svg+xml,%3Csvg%2F%3E", "file.png", "#local"] { + let text = format!(""); + assert!(matches!(repair(&text, &limits()).unwrap(), Cow::Borrowed(_))); + } + let text = ""; + assert!(repair(text, &limits()).unwrap().contains(INVALID_IMAGE)); + } + + #[test] + fn malformed_non_image_urls_keep_ignored_replacements_even_without_a_comma() { + for value in [ + "data:application/octet-stream;base64,A", + "data:application/octet-stream;base64", + "data:APPLICATION/OCTET-STREAM;BASE64,A", + "data:text/css;base64,A", + "data:audio/ogg;base64,A", + "data:application/octet-stream;base64#fragment,not-the-delimiter", + ] { + let text = format!(""); + let repaired = repair(&text, &limits()).unwrap(); + assert!(repaired.contains(IGNORED_DATA), "{value}: {repaired}"); + assert!(!repaired.contains(INVALID_IMAGE)); + assert!(matches!(repair(&repaired, &limits()).unwrap(), Cow::Borrowed(_))); + let resolver = craft_svg::tree::ImageResolver::new(limits()); + resolver.check_document(&repaired).unwrap(); + assert_eq!(resolver.usage().invalid_raster_images, 0); + } + } + + #[test] + fn image_and_default_plain_mime_failures_remain_disclosed() { + for value in + ["data:IMAGE/PNG;base64,A", "data:image/png;base64", "data:text/plain;base64,A", "data:;base64,A", "data:;base64", "data:not-a-mime;base64"] + { + let text = format!(""); + assert!(repair(&text, &limits()).unwrap().contains(INVALID_IMAGE), "{value}"); + } + let value = "data:application/octet-stream;base64#fragment"; + let mut insufficient = value.len(); + assert!(malformed_data_url_replacement(value, &mut insufficient).is_err(), "the extra MIME-header parse has its own work charge"); + let mut sufficient = value.len() * 2; + assert_eq!(malformed_data_url_replacement(value, &mut sufficient).unwrap(), Some(IGNORED_DATA)); + } + + #[test] + fn unrepresentable_attribute_positions_and_output_growth_fail_safely() { + let text = format!("", " ".repeat(300)); + assert!(matches!(repair(&text, &limits()), Err(IoError::Svg(message)) if message.contains("source positions"))); + let text = ""; + assert!(matches!(repair(text, &Limits { bytes: text.len(), ..limits() }), Err(IoError::Svg(message)) if message.contains("byte limit"))); + } +} + +#[cfg(test)] +#[path = "mime_header_tests.rs"] +mod mime_header_tests; + +#[cfg(test)] +thread_local! { + static XML_PARSES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +#[cfg(test)] +#[path = "xml_reuse_tests.rs"] +mod xml_reuse_tests; diff --git a/crates/io/src/svg/image_integrity.rs b/crates/io/src/svg/image_integrity.rs new file mode 100644 index 0000000000..8c5bd422eb --- /dev/null +++ b/crates/io/src/svg/image_integrity.rs @@ -0,0 +1,297 @@ +//! Image validation state shared by the outer parser and all embedded SVG resolvers. +use std::collections::HashMap; +use std::sync::{Arc, Mutex, PoisonError}; + +use super::{IoError, MAX_BOUNDED_SVG_BYTES, MAX_INFLATED_BYTES, MAX_RASTER_PIXELS, MAX_XML_DEPTH, data_href_validation, raster_validation, tree_limits, usvg}; + +#[cfg(test)] +#[path = "integrity_budget_tests.rs"] +mod integrity_budget_tests; + +struct RasterRecord { + // Retain successful and failed sources: parser-discarded image allocations + // must not recycle an address and bypass the validation-work allowance. + _encoded: Arc>, + result: Result<(), raster_validation::Failure>, +} + +pub(super) struct Integrity { + pixel_limit: u64, + pixels_left: u64, + svg_bytes_left: usize, + // Failed input spends the original allowance without refund. Later + // classification never admits children; it has a separate aggregate 16 MiB + // inflation allowance. Decoded UTF-8 is checked against the genuine content + // room saved before that failure, not against remaining inflation work. + svg_failure_exhausted: bool, + classification_bytes_left: usize, + classification_content_left: usize, + // Upstream's text_rechecked contract: even plain legacy-encoded retries + // allocate/scan decoded text. Charge source bytes before every retry decode. + classification_text_bytes_left: usize, + raster: HashMap, + encoded_left: usize, + invalid_raster: usize, + invalid_svg: usize, + raster_limits: usize, + svg_limits: usize, + svg_resource_limits: usize, + fatal: bool, +} + +impl Integrity { + pub(super) fn new(pixels: u64) -> Self { + Self { + pixel_limit: pixels.min(MAX_RASTER_PIXELS), + pixels_left: pixels.min(MAX_RASTER_PIXELS), + svg_bytes_left: MAX_BOUNDED_SVG_BYTES as usize, + svg_failure_exhausted: false, + classification_bytes_left: MAX_BOUNDED_SVG_BYTES as usize, + classification_content_left: MAX_BOUNDED_SVG_BYTES as usize, + classification_text_bytes_left: MAX_BOUNDED_SVG_BYTES as usize, + raster: HashMap::new(), + encoded_left: (MAX_INFLATED_BYTES + MAX_BOUNDED_SVG_BYTES) as usize, + invalid_raster: 0, + invalid_svg: 0, + raster_limits: 0, + svg_limits: 0, + svg_resource_limits: 0, + fatal: false, + } + } + + pub(super) fn usage(&self, mut usage: craft_svg::tree::ImageUsage) -> Result { + if self.fatal { + return Err(IoError::Svg("embedded image validation metadata exceeds its bounded allowance".into())); + } + // Raster callbacks use the exact rendering backend here, rather than decoding + // once generically in the shared resolver and then again for validation. + usage.raster_pixels = usage.raster_pixels.max(self.pixel_limit.saturating_sub(self.pixels_left)); + usage.invalid_raster_images = usage.invalid_raster_images.saturating_add(self.invalid_raster); + usage.invalid_svg_images = usage.invalid_svg_images.saturating_add(self.invalid_svg); + usage.raster_limit_images = usage.raster_limit_images.saturating_add(self.raster_limits); + usage.svg_limit_images = usage.svg_limit_images.saturating_add(self.svg_limits); + usage.svg_resource_limit_images = usage.svg_resource_limit_images.saturating_add(self.svg_resource_limits); + // Repairing a malformed href can shorten text. Its original expanded UTF-8 + // bytes remain charged, including XML declarations removed for transport. + usage.embedded_svg_bytes = usage.embedded_svg_bytes.max((MAX_BOUNDED_SVG_BYTES as usize).saturating_sub(self.svg_bytes_left)); + Ok(usage) + } + + #[cfg(test)] + pub(super) fn classification_bytes_left(&self) -> usize { + self.classification_bytes_left + } + + /// Classify only, without refund or admission. Gzip retries charge actual + /// inflated bytes; plain input needs no inflation. Latin-1/UTF-16 conversion + /// can expand text, so its content limit is independent of retry work. + fn classify_after_svg_failure(&mut self, data: &[u8]) { + if self.svg_resource_limits != 0 { + self.svg_limits = self.svg_limits.saturating_add(1); + self.svg_resource_limits = self.svg_resource_limits.saturating_add(1); + return; + } + let compressed = data.starts_with(&[0x1f, 0x8b]); + let content_left = self.classification_content_left; + let limit = if compressed { content_left.min(self.classification_bytes_left) } else { content_left }; + if compressed && limit == 0 { + self.svg_limits = self.svg_limits.saturating_add(1); + self.svg_resource_limits = self.svg_resource_limits.saturating_add(1); + return; + } + let resource_refusal = match craft_svg::svgz::inflate(data, limit) { + Ok(bytes) => { + if compressed { + self.classification_bytes_left = self.classification_bytes_left.saturating_sub(bytes.len()); + } + let Some(text_left) = self.classification_text_bytes_left.checked_sub(bytes.len()) else { + self.svg_limits = self.svg_limits.saturating_add(1); + self.svg_resource_limits = self.svg_resource_limits.saturating_add(1); + return; + }; + self.classification_text_bytes_left = text_left; + match craft_svg::svgz::decode(&bytes) { + Ok(text) => text.len() > content_left, + Err(_) => { + self.invalid_svg = self.invalid_svg.saturating_add(1); + return; + } + } + } + Err(craft_svg::svgz::Error::TooLarge(_)) => { + if compressed { + self.classification_bytes_left = self.classification_bytes_left.saturating_sub(limit); + } + true + } + Err(error) => { + // Nested data was fully inflated before refusal. Other failures + // may have consumed the entire attempted inflation allowance. + if compressed { + let charged = match error { + craft_svg::svgz::Error::Nested(bytes) => bytes, + _ => limit, + }; + self.classification_bytes_left = self.classification_bytes_left.saturating_sub(charged); + } + self.invalid_svg = self.invalid_svg.saturating_add(1); + return; + } + }; + self.svg_limits = self.svg_limits.saturating_add(1); + if resource_refusal { + self.svg_resource_limits = self.svg_resource_limits.saturating_add(1); + } + } + + fn raster(&mut self, kind: &usvg::ImageKind) -> bool { + if self.fatal { + return false; + } + let encoded = match kind { + usvg::ImageKind::SVG(_) => return true, + usvg::ImageKind::PNG(data) | usvg::ImageKind::JPEG(data) | usvg::ImageKind::GIF(data) | usvg::ImageKind::WEBP(data) => data, + }; + let key = Arc::as_ptr(encoded).addr(); + let result = if let Some(record) = self.raster.get(&key) { + record.result + } else { + // Bound auxiliary records independently of a hostile count of tiny images. + let Some(left) = self.encoded_left.checked_sub(encoded.len()) else { + self.fatal = true; + return false; + }; + if self.raster.len() >= 100_000 || self.raster.try_reserve(1).is_err() { + self.fatal = true; + return false; + } + self.encoded_left = left; + let result = raster_validation::validate(kind, &mut self.pixels_left); + self.raster.insert(key, RasterRecord { _encoded: Arc::clone(encoded), result }); + result + }; + match result { + Ok(()) => true, + Err(raster_validation::Failure::Invalid) => { + self.invalid_raster = self.invalid_raster.saturating_add(1); + false + } + Err(raster_validation::Failure::Limit) => { + self.raster_limits = self.raster_limits.saturating_add(1); + false + } + } + } +} + +pub(super) fn wrap(base: usvg::ImageHrefResolver<'static>, state: Arc>) -> usvg::ImageHrefResolver<'static> { + usvg::ImageHrefResolver { + resolve_string: base.resolve_string, + resolve_data: Box::new(move |mime, data, options| { + if state.lock().unwrap_or_else(PoisonError::into_inner).fatal { + return None; + } + if let Some(kind) = raster_kind(mime, &data) { + let valid = state.lock().unwrap_or_else(PoisonError::into_inner).raster(&kind); + return valid.then_some(kind); + } + let svg = matches!(mime, "image/svg+xml" | "text/plain"); + if !svg { + // Count failed declared images, while preserving the existing policy: + // non-image media types are ignored before decoding or pixel admission. + if mime.starts_with("image/") { + let mut state = state.lock().unwrap_or_else(PoisonError::into_inner); + state.invalid_raster = state.invalid_raster.saturating_add(1); + } + return None; + } + let data = if svg { + let room = { + let mut state = state.lock().unwrap_or_else(PoisonError::into_inner); + if state.svg_failure_exhausted { + state.classify_after_svg_failure(&data); + return None; + } + state.svg_bytes_left + }; + // Inflate once under the original aggregate allowance, then pass UTF-8 + // text onward. Nested parses retain these exact same wrapped options. + let text = match craft_svg::svgz::text(&data, room) { + Ok(text) if text.len() <= room => text, + error => { + let mut state = state.lock().unwrap_or_else(PoisonError::into_inner); + // Failed inflation/encoding already spent work. Match the shared + // resolver: none of its remaining allowance can be retried. + state.svg_bytes_left = 0; + if matches!(error, Err(craft_svg::svgz::Error::TooLarge(_))) || error.is_ok() { + state.svg_limits = state.svg_limits.saturating_add(1); + state.svg_resource_limits = state.svg_resource_limits.saturating_add(1); + } else { + state.invalid_svg = state.invalid_svg.saturating_add(1); + state.svg_failure_exhausted = true; + state.classification_content_left = room; + } + return None; + } + }; + state.lock().unwrap_or_else(PoisonError::into_inner).svg_bytes_left = room.saturating_sub(text.len()); + let repaired = match data_href_validation::repair(&text, &tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS)) { + Ok(text) => text, + Err(_) => { + let mut state = state.lock().unwrap_or_else(PoisonError::into_inner); + state.invalid_svg = state.invalid_svg.saturating_add(1); + return None; + } + }; + // The declaration was already validated against original UTF-8 text. + // Removing it prevents a Latin-1 declaration from decoding UTF-8 twice. + let normalized = if repaired.strip_prefix("").and_then(|at| repaired.get(at + 2..)).unwrap_or(&repaired) + } else { + &repaired + }; + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(normalized.len()).is_err() { + state.lock().unwrap_or_else(PoisonError::into_inner).fatal = true; + return None; + } + bytes.extend_from_slice(normalized.as_bytes()); + Arc::new(bytes) + } else { + data + }; + // Keep shared SVG nesting/XML accounting. Its nested parsers reuse this + // wrapper, so every raster still follows our one exact, bounded decode. + (base.resolve_data)(mime, data, options) + }), + } +} + +// Preserve the shared resolver's MIME/magic agreement. A forged MIME must not +// borrow a successful validation belonging to a different rendering decoder. +fn raster_kind(mime: &str, data: &Arc>) -> Option { + use photocraft_codecs::Format; + if !matches!(mime, "image/jpg" | "image/jpeg" | "image/png" | "image/gif" | "image/webp" | "text/plain") { + return None; + } + let format = photocraft_codecs::detect(data)?; + let accepted = match mime { + "image/jpg" | "image/jpeg" => format == Format::Jpeg, + "image/png" => format == Format::Png, + "image/gif" => format == Format::Gif, + "image/webp" => format == Format::WebP, + "text/plain" => true, + _ => false, + }; + if !accepted { + return None; + } + Some(match format { + Format::Png => usvg::ImageKind::PNG(Arc::clone(data)), + Format::Jpeg => usvg::ImageKind::JPEG(Arc::clone(data)), + Format::Gif => usvg::ImageKind::GIF(Arc::clone(data)), + Format::WebP => usvg::ImageKind::WEBP(Arc::clone(data)), + _ => return None, + }) +} diff --git a/crates/io/src/svg/integrity_budget_tests.rs b/crates/io/src/svg/integrity_budget_tests.rs new file mode 100644 index 0000000000..44fb71a0c2 --- /dev/null +++ b/crates/io/src/svg/integrity_budget_tests.rs @@ -0,0 +1,259 @@ +use super::*; +use std::io::Write; + +fn wrapped_options(pixels: u64) -> (usvg::Options<'static>, Arc>, Arc) { + let state = Arc::new(Mutex::new(Integrity::new(pixels))); + let resolver = Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(MAX_XML_DEPTH, pixels))); + let options = + super::super::options_with_isolation(Arc::new(usvg::fontdb::Database::new()), MAX_XML_DEPTH, false, Arc::clone(&resolver), Arc::clone(&state)); + (options, state, resolver) +} + +fn png() -> Vec { + let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [17, 83, 149].repeat(4)).unwrap(); + photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap() +} + +#[test] +fn original_nested_xml_bytes_are_not_refunded_when_malformed_hrefs_shrink() { + super::super::on_svg_stack(|| { + let (options, state, resolver) = wrapped_options(MAX_RASTER_PIXELS); + let prefix = ""; + let original_size = 3 << 20; + let source = Arc::new([prefix.as_bytes(), &vec![b'A'; original_size - prefix.len() - suffix.len()], suffix.as_bytes()].concat()); + assert_eq!(source.len(), original_size); + for accepted in 1..=5 { + let kind = (options.image_href_resolver.resolve_data)("image/svg+xml", Arc::clone(&source), &options); + assert!(matches!(kind, Some(usvg::ImageKind::SVG(_))), "source {accepted} fits the original-text allowance"); + drop(kind); + let state = state.lock().unwrap_or_else(PoisonError::into_inner); + assert_eq!(state.svg_bytes_left, MAX_BOUNDED_SVG_BYTES as usize - accepted * original_size); + assert!(!state.svg_failure_exhausted); + assert_eq!(state.classification_bytes_left(), MAX_BOUNDED_SVG_BYTES as usize); + let usage = state.usage(resolver.usage()).unwrap(); + assert_eq!(usage.embedded_svg_bytes, accepted * original_size, "the short replacement cannot refund original XML work"); + } + assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::clone(&source), &options).is_none()); + let state = state.lock().unwrap_or_else(PoisonError::into_inner); + assert_eq!(state.svg_bytes_left, 0); + assert_eq!((state.svg_limits, state.svg_resource_limits), (1, 1)); + assert!(!state.svg_failure_exhausted, "ordinary byte exhaustion cannot enter compatibility classification"); + assert_eq!(state.classification_bytes_left(), MAX_BOUNDED_SVG_BYTES as usize); + assert_eq!(state.usage(resolver.usage()).unwrap().svg_resource_limit_images, 1); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn invalid_utf8_gzip_consumes_remaining_svg_work_before_the_next_child() { + super::super::on_svg_stack(|| { + let (options, state, resolver) = wrapped_options(MAX_RASTER_PIXELS); + let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + encoder.write_all(&[0xff; 4096]).unwrap(); + let invalid = Arc::new(encoder.finish().unwrap()); + assert!((options.image_href_resolver.resolve_data)("image/svg+xml", invalid, &options).is_none()); + { + let state = state.lock().unwrap_or_else(PoisonError::into_inner); + assert_eq!(state.svg_bytes_left, 0, "a failed decode cannot retry the full work allowance"); + assert_eq!(state.invalid_svg, 1); + assert!(state.svg_failure_exhausted); + assert_eq!(state.svg_resource_limits, 0); + assert_eq!(state.classification_bytes_left(), MAX_BOUNDED_SVG_BYTES as usize); + } + let valid = Arc::new(b"".to_vec()); + let valid_size = valid.len(); + assert!((options.image_href_resolver.resolve_data)("image/svg+xml", valid, &options).is_none()); + let state = state.lock().unwrap_or_else(PoisonError::into_inner); + assert_eq!((state.invalid_svg, state.svg_limits, state.svg_resource_limits), (1, 1, 0)); + assert_eq!(state.classification_bytes_left(), MAX_BOUNDED_SVG_BYTES as usize, "plain input does not spend retry inflation work"); + let usage = state.usage(resolver.usage()).unwrap(); + assert_eq!(usage.embedded_svg_bytes, MAX_BOUNDED_SVG_BYTES as usize); + assert_eq!(usage.svg_resource_limit_images, 0, "a later small child is omitted, not a resource error"); + let charged = 2 * MAX_BOUNDED_SVG_BYTES as usize - state.svg_bytes_left - state.classification_bytes_left(); + assert_eq!(charged, MAX_BOUNDED_SVG_BYTES as usize); + assert!(valid_size < MAX_BOUNDED_SVG_BYTES as usize); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn post_failure_classification_is_cumulative_and_never_admits_later_children() { + super::super::on_svg_stack(|| { + let (options, state, resolver) = wrapped_options(MAX_RASTER_PIXELS); + let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + encoder.write_all(&[0xff; 256]).unwrap(); + assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::new(encoder.finish().unwrap()), &options).is_none()); + let text = b""; + let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + encoder.write_all(text).unwrap(); + let valid = Arc::new(encoder.finish().unwrap()); + // Exercise the cumulative inflated-byte boundary with a small injected + // second pool; public tests cover the full 16 MiB allowance. + let classification_limit = text.len() * 2 - 1; + state.lock().unwrap_or_else(PoisonError::into_inner).classification_bytes_left = classification_limit; + assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::clone(&valid), &options).is_none()); + { + let state = state.lock().unwrap_or_else(PoisonError::into_inner); + assert_eq!(state.classification_bytes_left(), text.len() - 1); + assert_eq!((state.svg_limits, state.svg_resource_limits), (1, 0)); + } + assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::clone(&valid), &options).is_none()); + let state = state.lock().unwrap_or_else(PoisonError::into_inner); + assert_eq!(state.classification_bytes_left(), 0); + assert_eq!((state.svg_limits, state.svg_resource_limits), (2, 1)); + assert_eq!(state.svg_bytes_left, 0, "classification never refunds original failed work"); + assert!(state.svg_failure_exhausted); + let charged = 2 * MAX_BOUNDED_SVG_BYTES as usize - state.svg_bytes_left - state.classification_bytes_left(); + assert_eq!(charged, 2 * MAX_BOUNDED_SVG_BYTES as usize, "original content plus aggregate retry inflation allowances remain bounded"); + assert_eq!(resolver.usage().embedded_svg_count, 0, "classified children must never reach the shared parser"); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn retry_inflation_room_and_saved_decoded_content_room_remain_independent() { + super::super::on_svg_stack(|| { + let mut latin1 = b""); + let decoded_len = craft_svg::svgz::decode(&latin1).unwrap().len(); + assert!(latin1.len() < 256 && decoded_len > 256 && decoded_len < 512); + let gzip = |bytes: &[u8]| { + let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + encoder.write_all(bytes).unwrap(); + Arc::new(encoder.finish().unwrap()) + }; + for (content_room, expected_resource) in [(512usize, false), (256, true)] { + let (options, state, resolver) = wrapped_options(MAX_RASTER_PIXELS); + // Model preceding genuine content consumption before an unreadable + // stream burns the rest. Classification must save this exact room. + state.lock().unwrap_or_else(PoisonError::into_inner).svg_bytes_left = content_room; + assert!((options.image_href_resolver.resolve_data)("image/svg+xml", gzip(&[0xff; 4]), &options).is_none()); + { + let mut state = state.lock().unwrap_or_else(PoisonError::into_inner); + assert_eq!(state.classification_content_left, content_room); + assert_eq!(state.svg_bytes_left, 0); + // Enough compressed retry work for the raw Latin-1 bytes, but + // less than their decoded UTF-8 length, just like main's case. + state.classification_bytes_left = latin1.len() + 1; + } + assert!((options.image_href_resolver.resolve_data)("image/svg+xml", gzip(&latin1), &options).is_none()); + let state = state.lock().unwrap_or_else(PoisonError::into_inner); + assert_eq!(state.classification_bytes_left(), 1, "retry work charges inflated bytes, not UTF-8 bytes"); + assert_eq!(state.svg_resource_limits, usize::from(expected_resource)); + assert_eq!(state.svg_bytes_left, 0, "classification never restores original content allowance"); + assert_eq!(resolver.usage().embedded_svg_count, 0, "no classified child is parsed or drawn"); + } + Ok(()) + }) + .unwrap(); +} + +#[test] +fn failed_raster_arcs_are_retained_and_cached_failures_do_not_recharge_work() { + let mut broken = png(); + let idat = broken.windows(4).position(|bytes| bytes == b"IDAT").unwrap(); + broken[idat + 4] ^= 1; + assert_eq!(photocraft_codecs::probe_allocation_size(&broken).unwrap(), (2, 2), "failure must occur after four-pixel admission"); + let encoded = Arc::new(broken); + let key = Arc::as_ptr(&encoded).addr(); + let weak = Arc::downgrade(&encoded); + let kind = usvg::ImageKind::PNG(Arc::clone(&encoded)); + let mut state = Integrity::new(4); + let encoded_before = state.encoded_left; + assert!(!state.raster(&kind)); + assert_eq!(state.pixels_left, 0); + assert_eq!(state.encoded_left, encoded_before - encoded.len()); + assert_eq!(state.raster.get(&key).unwrap().result, Err(raster_validation::Failure::Invalid)); + let charged = state.encoded_left; + assert!(!state.raster(&kind)); + assert_eq!((state.pixels_left, state.encoded_left, state.raster.len(), state.invalid_raster), (0, charged, 1, 2)); + drop(kind); + drop(encoded); + let retained = weak.upgrade().expect("cache must retain failed encoded sources to prevent pointer reuse"); + assert_eq!(Arc::as_ptr(&retained).addr(), key); + assert_eq!(Arc::as_ptr(&state.raster.get(&key).unwrap()._encoded).addr(), key); + let other = Arc::new(png()); + assert_ne!(Arc::as_ptr(&other).addr(), key, "a live failed source's identity cannot be reused"); + assert!(!state.raster(&usvg::ImageKind::PNG(other)), "a distinct source cannot reuse pixels spent by the failed decode"); + assert_eq!(state.raster_limits, 1); +} + +#[test] +fn cached_valid_png_with_exactly_four_pixels_is_not_charged_twice() { + let encoded = Arc::new(png()); + let kind = usvg::ImageKind::PNG(Arc::clone(&encoded)); + let mut state = Integrity::new(4); + let encoded_before = state.encoded_left; + assert!(state.raster(&kind)); + assert_eq!(state.pixels_left, 0); + assert_eq!(state.encoded_left, encoded_before - encoded.len()); + let charged = state.encoded_left; + assert!(state.raster(&kind), "cached validation remains valid after it spent the last four pixels"); + assert_eq!((state.pixels_left, state.encoded_left, state.raster.len()), (0, charged, 1)); + assert_eq!((state.invalid_raster, state.raster_limits), (0, 0)); +} + +#[test] +fn raster_callbacks_own_pixel_charges_and_keep_mime_aliases_separate() { + let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap(); + let png = Arc::new(photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap()); + let shared = craft_svg::tree::ImageResolver::new(tree_limits(MAX_XML_DEPTH, 4)); + let state = Arc::new(Mutex::new(Integrity::new(4))); + let resolver = wrap(shared.resolver(), Arc::clone(&state)); + for _ in 0..2 { + assert!((resolver.resolve_data)("image/png", Arc::clone(&png), &usvg::Options::default()).is_some()); + let usage = state.lock().unwrap().usage(shared.usage()).unwrap(); + assert_eq!(usage.raster_pixels, 4, "a retained alias does not spend decoding work again"); + assert_eq!(usage.invalid_raster_images, 0); + assert_eq!(shared.usage().raster_pixels, 0, "generic decoding must not duplicate exact renderer validation"); + } + assert!((resolver.resolve_data)("image/jpeg", png, &usvg::Options::default()).is_none()); + let usage = state.lock().unwrap().usage(shared.usage()).unwrap(); + assert_eq!(usage.raster_pixels, 4); + assert_eq!(usage.invalid_raster_images, 1, "a mismatched MIME cannot borrow the successful PNG cache entry"); +} + +// Preserve upstream's text_rechecked boundary using the integrated real resolver. +// Plain and gzip retries spend source bytes before decoding, independently of +// inflation work and the drawing's genuine decoded-content capacity. +#[test] +fn plain_legacy_encoding_rechecks_have_a_separate_bounded_work_allowance() { + super::super::on_svg_stack(|| { + let xml = b""; + for compressed in [false, true] { + let (options, state, resolver) = wrapped_options(MAX_RASTER_PIXELS); + let encode = |bytes: &[u8]| { + if compressed { + let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + encoder.write_all(bytes).unwrap(); + encoder.finish().unwrap() + } else { + bytes.to_vec() + } + }; + assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::new(encode(&[0xff])), &options).is_none()); + state.lock().unwrap_or_else(PoisonError::into_inner).classification_text_bytes_left = xml.len(); + assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::new(encode(xml)), &options).is_none()); + { + let state = state.lock().unwrap_or_else(PoisonError::into_inner); + assert_eq!(state.classification_text_bytes_left, 0); + assert_eq!(state.svg_resource_limits, 0, "exactly fitting text recheck is permitted"); + assert_eq!(state.classification_bytes_left, MAX_BOUNDED_SVG_BYTES as usize - usize::from(compressed) * xml.len()); + } + assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::new(encode(xml)), &options).is_none()); + let state = state.lock().unwrap_or_else(PoisonError::into_inner); + assert_eq!(state.classification_text_bytes_left, 0); + assert_eq!(state.svg_resource_limits, 1, "the next source cannot repeat text-conversion work"); + assert_eq!(state.invalid_svg, 1, "the original encoding error stays invalid"); + assert_eq!(state.svg_limits, 2); + assert_eq!(resolver.usage().embedded_svg_count, 0, "rechecked children are never admitted"); + } + Ok(()) + }) + .unwrap(); +} diff --git a/crates/io/src/svg/mime_header_tests.rs b/crates/io/src/svg/mime_header_tests.rs new file mode 100644 index 0000000000..88c27dd79b --- /dev/null +++ b/crates/io/src/svg/mime_header_tests.rs @@ -0,0 +1,119 @@ +use super::*; +use std::fmt::Write; + +fn parameters(count: usize) -> String { + let mut text = String::new(); + for index in 0..count { + write!(&mut text, ";p{index}=x").unwrap(); + } + text +} + +#[test] +fn a_hundred_thousand_unique_mime_parameters_are_refused_before_the_original_parser() { + let params = parameters(100_000); + for (essence, expected) in [ + ("image/png", INVALID_IMAGE), + ("text/plain", INVALID_IMAGE), + ("", INVALID_IMAGE), + ("not-a-mime", INVALID_IMAGE), + ("application/octet-stream", IGNORED_DATA), + ("audio/ogg", IGNORED_DATA), + ] { + for delimiter in [",AA==", "#fragment,AA==", ""] { + let value = format!("data:{essence}{params};base64{delimiter}"); + let mut work = value.len() * 2; + assert!(!mime_header_admitted(&value)); + let result = + malformed_data_url_replacement_with(&value, &mut work, |_| panic!("the original parameter flood must not reach DataUrl::process")).unwrap(); + assert_eq!(result, Some(expected), "{essence} {delimiter}"); + } + } +} + +#[test] +fn mime_parameter_admission_preserves_the_boundary_and_ignores_body_semicolons() { + let accepted = format!("data:image/png{};base64,AA==", parameters(MAX_MIME_SEPARATORS - 1)); + assert!(mime_header_admitted(&accepted)); + let called = std::cell::Cell::new(false); + let mut work = accepted.len() * 2; + assert_eq!( + malformed_data_url_replacement_with(&accepted, &mut work, |value| { + called.set(true); + data_url::DataUrl::process(value) + }) + .unwrap(), + None + ); + assert!(called.get(), "an admitted original URL still reaches the real parser"); + let refused = format!("data:image/png{};base64,AA==", parameters(MAX_MIME_SEPARATORS)); + assert!(!mime_header_admitted(&refused)); + let mut work = refused.len() * 2; + assert_eq!(malformed_data_url_replacement(&refused, &mut work).unwrap(), Some(INVALID_IMAGE)); + + for value in [format!("data:text/plain,{}", ";".repeat(100_000)), format!("external.png?{}", parameters(100_000))] { + assert!(mime_header_admitted(&value), "payloads/external URLs are not MIME parameters"); + let mut work = value.len() * 2; + assert_eq!(malformed_data_url_replacement(&value, &mut work).unwrap(), None); + } + let value = format!(" \td\ta\nt\ra:image/png{};base64,A", parameters(MAX_MIME_SEPARATORS)); + assert!(!mime_header_admitted(&value), "scheme normalization matches the pinned parser"); + let mut work = value.len() * 2; + assert_eq!(malformed_data_url_replacement(&value, &mut work).unwrap(), Some(INVALID_IMAGE)); +} + +#[test] +fn refused_parameter_lists_normalize_both_hrefs_and_foreign_resources_without_preflight_warnings() { + let value = format!("data:image/png{};base64,AA==", parameters(MAX_MIME_SEPARATORS)); + let text = format!( + "" + ); + let limits = Limits { bytes: 1 << 20, ..Default::default() }; + let repaired = repair(&text, &limits).unwrap(); + assert_eq!(repaired.matches(INVALID_IMAGE).count(), 6); + assert!(!repaired.contains(";p0=")); + let resolver = craft_svg::tree::ImageResolver::new(limits); + resolver.check_document(&repaired).unwrap(); + let usage = resolver.usage(); + assert_eq!((usage.invalid_raster_images, usage.invalid_svg_images), (0, 0)); + assert!(matches!(repair(&repaired, &Limits { bytes: 1 << 20, ..Default::default() }).unwrap(), Cow::Borrowed(_))); +} + +#[test] +fn duplicate_and_quoted_parameters_share_the_same_conservative_boundary() { + for (accepted, refused) in [ + (format!("data:image/png{},%00", ";p=x".repeat(MAX_MIME_SEPARATORS)), format!("data:image/png{},%00", ";p=x".repeat(MAX_MIME_SEPARATORS + 1))), + (format!("data:image/png;p=\"{}\",%00", ";".repeat(MAX_MIME_SEPARATORS - 1)), format!("data:image/png;p=\"{}\",%00", ";".repeat(MAX_MIME_SEPARATORS))), + ] { + assert!(mime_header_admitted(&accepted)); + let mut work = accepted.len() * 2; + assert_eq!(malformed_data_url_replacement(&accepted, &mut work).unwrap(), None); + assert!(!mime_header_admitted(&refused)); + let mut work = refused.len() * 2; + assert_eq!(malformed_data_url_replacement(&refused, &mut work).unwrap(), Some(INVALID_IMAGE)); + } + for value in ["external.png", "#local", "datx:image/png;param=x,body"] { + let mut work = value.len() * 2; + assert_eq!(malformed_data_url_replacement(value, &mut work).unwrap(), None); + } + let value = "data:image/png;base64"; + let mut work = value.len() * 2; + assert_eq!(malformed_data_url_replacement(value, &mut work).unwrap(), Some(INVALID_IMAGE)); +} + +#[test] +fn parameter_flood_scans_and_essence_classification_spend_one_shared_work_ledger() { + let value = format!("data:application/octet-stream{};base64,AA==", parameters(MAX_MIME_SEPARATORS)); + let essence_len = "data:application/octet-stream".len(); + let charge = value.len() + essence_len; + let mut work = charge * 2; + for remaining in [charge, 0] { + assert_eq!(malformed_data_url_replacement_with(&value, &mut work, |_| panic!("not admitted")).unwrap(), Some(IGNORED_DATA)); + assert_eq!(work, remaining, "the original header scan and parameter-free fallback each retain their charge"); + } + assert!(malformed_data_url_replacement_with(&value, &mut work, |_| panic!("no work remains")).is_err()); + assert_eq!(work, 0); + let mut not_enough_for_essence = value.len(); + assert!(malformed_data_url_replacement_with(&value, &mut not_enough_for_essence, |_| panic!("not admitted")).is_err()); + assert_eq!(not_enough_for_essence, 0); +} diff --git a/crates/io/src/svg/optional_image_review_tests.rs b/crates/io/src/svg/optional_image_review_tests.rs index d670ec2845..8b792c59f4 100644 --- a/crates/io/src/svg/optional_image_review_tests.rs +++ b/crates/io/src/svg/optional_image_review_tests.rs @@ -1,6 +1,250 @@ use super::*; use std::io::Write; +fn assert_incomplete_image_is_disclosed(text: &str) { + for bytes in [text.as_bytes().to_vec(), gzip(text.as_bytes())] { + let imported = crate::import("damaged.svg", &bytes).unwrap(); + assert_omission_warning(&imported, 1); + assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [1., 0., 0., 1.]); + let bounded = import_svg_bounded_images("damaged.svg", &bytes, MAX_RASTER_PIXELS).unwrap(); + assert_omission_warning(&bounded, 1); + assert!(import_svg_preview_with_work("damaged.svg", &bytes, MAX_RASTER_PIXELS).is_err()); + assert!(import_svg_bounded_images_strict("damaged.svg", &bytes, MAX_RASTER_PIXELS).is_err()); + assert!(rasterize(&bytes, 1.).is_err()); + assert!(rasterize_bounded(&bytes, 1., MAX_RASTER_PIXELS).is_err()); + let (pixels, warnings) = rasterize_bounded_with_warnings(&bytes, 1., MAX_RASTER_PIXELS).unwrap(); + assert_eq!(pixels.get(1, 1), [1., 0., 0., 1.]); + assert_eq!(warnings.len(), 1); + assert!(warnings[0].starts_with("SVG: 1 embedded ")); + assert!(warnings[0].len() < 256); + assert!(!warnings[0].contains("data:")); + // A warning-aware parse cannot make a later strict render accept an omission. + assert!(rasterize_bounded(&bytes, 1., MAX_RASTER_PIXELS).is_err()); + assert!(rasterize_rgba8(&bytes).is_err()); + } +} + +#[test] +fn valid_twelve_bit_jpeg_rejected_by_the_svg_renderer_is_disclosed() { + // ISO/IEC 10918-1 marker syntax: one 8x8, 12-bit gray DCT block. + // Unit quantization, zero DC difference and EOB yield a constant mid-gray. + // This is generated data, not a camera or third-party binary fixture. + fn segment(out: &mut Vec, marker: u8, payload: &[u8]) { + out.extend_from_slice(&[0xff, marker]); + out.extend_from_slice(&u16::try_from(payload.len() + 2).unwrap().to_be_bytes()); + out.extend_from_slice(payload); + } + let mut jpeg = vec![0xff, 0xd8]; + let mut quantization = vec![0]; + quantization.extend_from_slice(&[1; 64]); + segment(&mut jpeg, 0xdb, &quantization); + segment(&mut jpeg, 0xc1, &[12, 0, 8, 0, 8, 1, 1, 0x11, 0]); + let mut tables = Vec::new(); + for class in [0x00, 0x10] { + tables.extend_from_slice(&[class, 1]); + tables.extend_from_slice(&[0; 15]); + tables.push(0); // One one-bit code: DC category zero / AC end-of-block. + } + segment(&mut jpeg, 0xc4, &tables); + segment(&mut jpeg, 0xda, &[1, 1, 0, 0, 63, 0]); + jpeg.extend_from_slice(&[0x3f, 0xff, 0xd9]); // DC=0, EOB=0, then six pad bits. + let decoded = photocraft_codecs::decode(&jpeg).expect("valid extended sequential JPEG"); + assert_eq!(decoded.dimensions(), (8, 8)); + // Match resvg's actual JPEG backend/output policy, rather than the broader + // shared codec which also supports valid 12-bit and arithmetic JPEG files. + let options = zune_core::options::DecoderOptions::default().jpeg_set_out_colorspace(zune_core::colorspace::ColorSpace::RGBA); + let mut renderer_decoder = zune_jpeg::JpegDecoder::new_with_options(std::io::Cursor::new(jpeg.as_slice()), options); + assert!(renderer_decoder.decode().is_err(), "fixture must exercise the actual renderer capability gap"); + for mime in ["image/jpeg", "text/plain"] { + let direct = drawing(&url(mime, &jpeg)); + assert_incomplete_image_is_disclosed(&direct); + for child in [direct.as_bytes().to_vec(), gzip(direct.as_bytes())] { + assert_incomplete_image_is_disclosed(&drawing(&url("image/svg+xml", &child))); + } + } +} + +#[test] +fn corrupt_png_pixels_with_valid_dimensions_are_disclosed_before_rasterization() { + let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap(); + let mut png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let mut at = 8; + loop { + let length = u32::from_be_bytes(png[at..at + 4].try_into().unwrap()) as usize; + if &png[at + 4..at + 8] == b"IDAT" { + assert!(length >= 2); + png[at + 8..at + 10].fill(0); // Invalid zlib header, with an honest chunk CRC. + let checksum = crc32fast::hash(&png[at + 4..at + 8 + length]); + png[at + 8 + length..at + 12 + length].copy_from_slice(&checksum.to_be_bytes()); + break; + } + at += length + 12; + } + assert_eq!(photocraft_codecs::probe_allocation_size(&png).unwrap(), (2, 2)); + assert!(tiny_skia::Pixmap::decode_png(&png).is_err()); + let direct = drawing(&url("image/png", &png)); + assert_incomplete_image_is_disclosed(&direct); + for child in [direct.as_bytes().to_vec(), gzip(direct.as_bytes())] { + assert_incomplete_image_is_disclosed(&drawing(&url("image/svg+xml", &child))); + } +} + +#[test] +fn malformed_data_image_hrefs_are_disclosed_before_the_parser_discards_them() { + let direct = drawing("data:image/png;base64,A"); + assert_incomplete_image_is_disclosed(&direct); + assert_incomplete_image_is_disclosed(&direct.replace("href=", "xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:href=")); + assert_incomplete_image_is_disclosed(&direct.replace("base64,A", "base64,A")); + for child in [direct.as_bytes().to_vec(), gzip(direct.as_bytes())] { + assert_incomplete_image_is_disclosed(&drawing(&url("image/svg+xml", &child))); + } +} + +fn assert_no_omission_or_unexpected_import_warning(imported: &ImportResult) { + assert!(omission_warnings(imported).is_empty(), "{:?}", imported.warnings); + assert!( + imported.warnings.iter().all(|warning| warning == "SVG: embedded images are pixel layers"), + "only the existing pixel-layer information is expected: {:?}", + imported.warnings + ); +} + +fn assert_ignored_data_image_stays_quiet(text: &str) { + for bytes in [text.as_bytes().to_vec(), gzip(text.as_bytes())] { + let imported = crate::import("ignored.svg", &bytes).unwrap(); + assert_no_omission_or_unexpected_import_warning(&imported); + assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [1., 0., 0., 1.]); + let strict = import_svg_bounded_images_strict("ignored.svg", &bytes, MAX_RASTER_PIXELS).unwrap(); + assert_no_omission_or_unexpected_import_warning(&strict); + import_svg_preview_with_work("ignored.svg", &bytes, MAX_RASTER_PIXELS).unwrap(); + let (pixels, warnings) = rasterize_bounded_with_warnings(&bytes, 1., MAX_RASTER_PIXELS).unwrap(); + assert!(warnings.is_empty()); + assert_eq!(pixels.get(1, 1), [1., 0., 0., 1.]); + assert_eq!(rasterize_bounded(&bytes, 1., MAX_RASTER_PIXELS).unwrap().get(1, 1), [1., 0., 0., 1.]); + assert_eq!(rasterize(&bytes, 1.).unwrap().get(1, 1), [1., 0., 0., 1.]); + } +} + +#[test] +fn malformed_non_image_data_hrefs_stay_ignored_in_open_and_strict_rendering() { + for href in [ + "data:application/octet-stream;base64,A", + "data:application/octet-stream;base64", + "data:APPLICATION/OCTET-STREAM;BASE64,A", + "data:text/css;base64,A", + "data:application/octet-stream;base64#fragment,not-the-delimiter", + ] { + let text = drawing(href); + assert_ignored_data_image_stays_quiet(&text); + assert_ignored_data_image_stays_quiet(&text.replace("href=", "xmlns:x='http://www.w3.org/1999/xlink' x:href=")); + for child in [text.as_bytes().to_vec(), gzip(text.as_bytes())] { + assert_ignored_data_image_stays_quiet(&drawing(&url("image/svg+xml", &child))); + } + } +} + +#[test] +fn default_and_explicit_plain_data_failures_keep_image_omission_policy() { + for href in ["data:text/plain;base64,A", "data:;base64,A", "data:;base64", "data:image/png;base64"] { + assert_incomplete_image_is_disclosed(&drawing(href)); + } +} + +#[test] +fn ignored_non_image_repair_preserves_hidden_foreign_and_valid_image_controls() { + for content in [ + "", + "", + "", + ] { + let text = format!("{content}"); + assert_ignored_data_image_stays_quiet(&text); + } + let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap(); + let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let text = format!( + "", + url("image/png", &png) + ); + let imported = crate::import("mixed.svg", text.as_bytes()).unwrap(); + assert_eq!(imported.warnings, vec!["SVG: embedded images are pixel layers"]); + assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [0., 1., 0., 1.]); + let strict = import_svg_bounded_images_strict("mixed.svg", text.as_bytes(), MAX_RASTER_PIXELS).unwrap(); + assert_eq!(strict.warnings, vec!["SVG: embedded images are pixel layers"]); + assert_eq!(rasterize_bounded(text.as_bytes(), 1., MAX_RASTER_PIXELS).unwrap().get(1, 1), [0., 1., 0., 1.]); +} + +#[test] +fn malformed_nested_declarations_are_not_removed_into_valid_images() { + let child = b""; + for bytes in [child.to_vec(), gzip(child)] { + assert_incomplete_image_is_disclosed(&drawing(&url("image/svg+xml", &bytes))); + } +} + +#[test] +fn used_data_images_with_mismatched_image_mime_are_disclosed() { + let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap(); + let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + assert_eq!(photocraft_codecs::decode(&png).unwrap().dimensions(), (2, 2)); + for mime in ["image/jpeg", "image/jpg"] { + let direct = drawing(&url(mime, &png)); + assert_incomplete_image_is_disclosed(&direct); + for child in [direct.as_bytes().to_vec(), gzip(direct.as_bytes())] { + assert_incomplete_image_is_disclosed(&drawing(&url("image/svg+xml", &child))); + } + } +} + +#[test] +fn complete_renderer_raster_formats_and_plain_text_sniffing_stay_usable() { + let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap(); + for (format, mime) in [ + (photocraft_codecs::Format::Png, "image/png"), + (photocraft_codecs::Format::Jpeg, "image/jpeg"), + (photocraft_codecs::Format::Gif, "image/gif"), + (photocraft_codecs::Format::WebP, "image/webp"), + ] { + let encoded = photocraft_codecs::encode(&image, format, &Default::default()).unwrap(); + for mime in [mime, "text/plain"] { + let text = drawing(&url(mime, &encoded)); + let imported = crate::import("complete.svg", text.as_bytes()).unwrap(); + assert!(omission_warnings(&imported).is_empty(), "{format:?}: {:?}", imported.warnings); + let pixel = rasterize_bounded(text.as_bytes(), 1., MAX_RASTER_PIXELS).unwrap().get(1, 1); + assert!(pixel[1] > 0.8 && pixel[0] < 0.2 && pixel[2] < 0.2 && pixel[3] == 1., "{format:?}: {pixel:?}"); + } + } +} + +#[test] +fn unused_hidden_and_unselected_href_failures_do_not_acquire_warnings() { + for content in [ + "", + "", + "", + "", + ] { + let text = format!("{content}"); + for source_text in [text.clone(), drawing(&url("image/svg+xml", text.as_bytes())), drawing(&url("image/svg+xml", &gzip(text.as_bytes())))] { + for bytes in [source_text.as_bytes().to_vec(), gzip(source_text.as_bytes())] { + let imported = crate::import("unused.svg", &bytes).unwrap(); + assert!(omission_warnings(&imported).is_empty(), "{content}: {:?}", imported.warnings); + assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [1., 0., 0., 1.]); + let imported = import_svg_bounded_images("unused.svg", &bytes, MAX_RASTER_PIXELS).unwrap(); + assert!(omission_warnings(&imported).is_empty()); + let (pixels, warnings) = rasterize_bounded_with_warnings(&bytes, 1., MAX_RASTER_PIXELS).unwrap(); + assert!(warnings.is_empty(), "{content}: {warnings:?}"); + assert_eq!(pixels.get(1, 1), [1., 0., 0., 1.]); + assert_eq!(rasterize_bounded(&bytes, 1., MAX_RASTER_PIXELS).unwrap().get(1, 1), [1., 0., 0., 1.]); + assert_eq!(rasterize(&bytes, 1.).unwrap().get(1, 1), [1., 0., 0., 1.]); + rasterize_rgba8(&bytes).unwrap(); + import_svg_preview_with_work("unused.svg", &bytes, MAX_RASTER_PIXELS).unwrap(); + import_svg_bounded_images_strict("unused.svg", &bytes, MAX_RASTER_PIXELS).unwrap(); + } + } + } +} + fn url(mime: &str, bytes: &[u8]) -> String { let mut value = format!("data:{mime},"); for byte in bytes { @@ -215,3 +459,45 @@ fn malformed_data_urls_and_broken_pixel_payloads_are_disclosed_before_rendering( assert!(import_svg_preview_with_work("strict.svg", text.as_bytes(), MAX_RASTER_PIXELS).is_err()); } } + +#[test] +fn excessive_mime_parameters_are_disclosed_only_for_used_image_resources() { + let parameters = (0..65).map(|index| format!(";p{index}=x")).collect::(); + let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap(); + let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + for essence in ["image/png", "text/plain", ""] { + let href = url(&format!("{essence}{parameters}"), &png); + let text = drawing(&href); + assert_incomplete_image_is_disclosed(&text); + for child in [text.as_bytes().to_vec(), gzip(text.as_bytes())] { + assert_incomplete_image_is_disclosed(&drawing(&url("image/svg+xml", &child))); + } + } + let href = format!("data:application/octet-stream{parameters};base64,AA=="); + assert_ignored_data_image_stays_quiet(&drawing(&href)); + let image = url(&format!("image/png{parameters}"), &png); + for content in [ + format!(""), + format!(""), + format!(""), + format!(""), + ] { + let text = format!("{content}"); + assert_ignored_data_image_stays_quiet(&text); + } +} + +#[test] +fn valid_image_at_the_mime_parameter_boundary_keeps_its_pixels() { + let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap(); + let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + // This helper percent-encodes the payload; 64 parameters hit the separator boundary. + let parameters = (0..64).map(|index| format!(";p{index}=x")).collect::(); + let text = drawing(&url(&format!("image/png{parameters}"), &png)); + for bytes in [text.as_bytes().to_vec(), gzip(text.as_bytes())] { + let imported = crate::import("valid.svg", &bytes).unwrap(); + assert_eq!(imported.warnings, vec!["SVG: embedded images are pixel layers"]); + assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [0., 1., 0., 1.]); + assert_eq!(rasterize(&bytes, 1.).unwrap().get(1, 1), [0., 1., 0., 1.]); + } +} diff --git a/crates/io/src/svg/raster_validation.rs b/crates/io/src/svg/raster_validation.rs new file mode 100644 index 0000000000..364b199010 --- /dev/null +++ b/crates/io/src/svg/raster_validation.rs @@ -0,0 +1,135 @@ +//! Validate optional raster images with the same backends used by the SVG renderer. +//! +//! Header probing alone cannot detect damaged pixel data. Admit dimensions and +//! reserve work before decoding: even a failed decode keeps its charge. + +use std::io::Cursor; +use std::num::NonZeroU64; + +use super::{MAX_RASTER_PIXELS, tiny_skia, usvg}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Failure { + Invalid, + Limit, +} + +/// Validate the renderer's first frame without retaining decoded pixels. SVG +/// children use the same wrapped resolver and need no second recursive walk. +pub(super) fn validate(kind: &usvg::ImageKind, pixels_left: &mut u64) -> Result<(), Failure> { + let data = match kind { + usvg::ImageKind::PNG(data) | usvg::ImageKind::JPEG(data) | usvg::ImageKind::GIF(data) | usvg::ImageKind::WEBP(data) => data, + usvg::ImageKind::SVG(_) => return Ok(()), + }; + // The allocation probe includes oversized GIF/WebP frames, not merely their + // canvas. Reserve before asking any rendering decoder to allocate pixels. + let (width, height) = photocraft_codecs::probe_allocation_size(data).map_err(|_| Failure::Invalid)?; + let pixels = area(width, height)?; + if pixels > MAX_RASTER_PIXELS { + return Err(Failure::Limit); + } + *pixels_left = pixels_left.checked_sub(pixels).ok_or(Failure::Limit)?; + match kind { + usvg::ImageKind::PNG(data) => { + let decoded = tiny_skia::Pixmap::decode_png(data).map_err(|_| Failure::Invalid)?; + rgba_bytes(decoded.width(), decoded.height(), pixels)?; + Ok(()) + } + usvg::ImageKind::JPEG(data) => jpeg(data, pixels), + usvg::ImageKind::GIF(data) => gif(data, pixels), + usvg::ImageKind::WEBP(data) => webp(data, pixels), + usvg::ImageKind::SVG(_) => Ok(()), + } +} + +fn area(width: u32, height: u32) -> Result { + if width == 0 || height == 0 { + return Err(Failure::Invalid); + } + u64::from(width).checked_mul(u64::from(height)).ok_or(Failure::Limit) +} + +/// Decoder headers must not request more output than the allocation probe paid for. +fn rgba_bytes(width: u32, height: u32, admitted: u64) -> Result { + let pixels = area(width, height)?; + if pixels > admitted { + return Err(Failure::Limit); + } + usize::try_from(pixels.checked_mul(4).ok_or(Failure::Limit)?).map_err(|_| Failure::Limit) +} + +fn buffer(length: usize) -> Result, Failure> { + let mut output = Vec::new(); + output.try_reserve_exact(length).map_err(|_| Failure::Limit)?; + output.resize(length, 0); + Ok(output) +} + +fn jpeg(data: &[u8], admitted: u64) -> Result<(), Failure> { + use zune_core::colorspace::ColorSpace; + use zune_core::options::DecoderOptions; + + // Preserve the rendering decoder's default limits and RGBA conversion; a + // general photo decoder may accept formats the SVG renderer cannot draw. + let options = DecoderOptions::default().jpeg_set_out_colorspace(ColorSpace::RGBA); + let mut decoder = zune_jpeg::JpegDecoder::new_with_options(Cursor::new(data), options); + decoder.decode_headers().map_err(|_| Failure::Invalid)?; + let info = decoder.info().ok_or(Failure::Invalid)?; + let length = rgba_bytes(u32::from(info.width), u32::from(info.height), admitted)?; + if decoder.output_colorspace() != Some(ColorSpace::RGBA) || decoder.output_buffer_size() != Some(length) { + return Err(Failure::Invalid); + } + let mut output = buffer(length)?; + decoder.decode_into(&mut output).map_err(|_| Failure::Invalid) +} + +fn gif(data: &[u8], admitted: u64) -> Result<(), Failure> { + let bytes = admitted.checked_mul(4).ok_or(Failure::Limit)?; + // Do not loosen the renderer's default 50 MB GIF frame limit. Smaller + // imports also keep their own admitted allocation ceiling during decode. + let limit = NonZeroU64::new(bytes.min(50_000_000)).ok_or(Failure::Invalid)?; + let mut options = gif::DecodeOptions::new(); + options.set_color_output(gif::ColorOutput::RGBA); + options.set_memory_limit(gif::MemoryLimit::Bytes(limit)); + let mut decoder = options.read_info(data).map_err(gif_error)?; + let frame = decoder.read_next_frame().map_err(gif_error)?.ok_or(Failure::Invalid)?; + let expected = rgba_bytes(u32::from(frame.width), u32::from(frame.height), admitted)?; + if frame.buffer.len() != expected { + return Err(Failure::Invalid); + } + Ok(()) +} + +fn gif_error(error: gif::DecodingError) -> Failure { + match error { + gif::DecodingError::MemoryLimit | gif::DecodingError::OutOfMemory => Failure::Limit, + _ => Failure::Invalid, + } +} + +fn webp(data: &[u8], admitted: u64) -> Result<(), Failure> { + let mut decoder = image_webp::WebPDecoder::new(Cursor::new(data)).map_err(webp_error)?; + let (width, height) = decoder.dimensions(); + let rgba = rgba_bytes(width, height, admitted)?; + let channels = if decoder.has_alpha() { 4 } else { 3 }; + let expected = usize::try_from(area(width, height)?.checked_mul(channels).ok_or(Failure::Limit)?).map_err(|_| Failure::Limit)?; + if expected > rgba { + return Err(Failure::Limit); + } + if decoder.output_buffer_size() != Some(expected) { + return Err(Failure::Invalid); + } + // A small valid image can have a compressed chunk larger than its pixels. + // Bound decoder scratch without rejecting that ordinary encoding overhead. + let admitted_bytes = usize::try_from(admitted.checked_mul(4).ok_or(Failure::Limit)?).map_err(|_| Failure::Limit)?; + decoder.set_memory_limit(admitted_bytes.max(data.len())); + let mut output = buffer(expected)?; + decoder.read_image(&mut output).map_err(webp_error) +} + +fn webp_error(error: image_webp::DecodingError) -> Failure { + match error { + image_webp::DecodingError::MemoryLimitExceeded | image_webp::DecodingError::ImageTooLarge => Failure::Limit, + _ => Failure::Invalid, + } +} diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index 0d4dfd1838..93b2735a60 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -41,6 +41,7 @@ fn non_strict_embedded_svg_records_isolation_failure_but_omits_invalid_images() strict: false, error: None, resolver: Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS))), + integrity: Arc::new(Mutex::new(image_integrity::Integrity::new(MAX_RASTER_PIXELS))), })); let invalid = image_svg(&embedded_image("image/svg+xml", b"")); parse_image_bounded_with(invalid.as_bytes(), budget.clone(), MAX_XML_DEPTH, inter_only, false).unwrap(); @@ -1191,10 +1192,35 @@ fn fitting_latin1_retry_keeps_inflation_and_content_budgets_separate() { let decoded = craft_svg::svgz::decode(&latin1).unwrap(); assert!(latin1.len() < budget / 2); assert!(decoded.len() > budget / 2 && decoded.len() < budget); - let refusals = SvgRefusals { unread_charges: AtomicUsize::new(budget), rechecked: AtomicUsize::new(budget / 2), ..SvgRefusals::default() }; - note_byte_refusal(&gzip(&latin1), budget, &refusals); - assert!(!refusals.over_budget.load(Ordering::Relaxed)); - assert_eq!(refusals.rechecked.load(Ordering::Relaxed), budget / 2 + latin1.len()); + let state = Arc::new(Mutex::new(image_integrity::Integrity::new(MAX_RASTER_PIXELS))); + let resolver = Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS))); + let options = options_with_isolation(Arc::new(usvg::fontdb::Database::new()), MAX_XML_DEPTH, false, Arc::clone(&resolver), Arc::clone(&state)); + let valid = gzip(b""); + let damaged = Arc::new(valid[..valid.len() / 2].to_vec()); + assert!((options.image_href_resolver.resolve_data)("image/svg+xml", damaged, &options).is_none()); + assert_eq!(state.lock().unwrap().classification_bytes_left(), budget); + + // Spend half the inflation allowance through an actual compressed retry. + // None of these retries may restore admission after the damaged source. + let mut primer = b""; + primer.resize(budget / 2 - close.len(), b' '); + primer.extend_from_slice(close); + assert_eq!(primer.len(), budget / 2); + assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::new(gzip(&primer)), &options).is_none()); + { + let state = state.lock().unwrap(); + assert_eq!(state.classification_bytes_left(), budget / 2); + assert_eq!(state.usage(resolver.usage()).unwrap().svg_resource_limit_images, 0); + } + assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::new(gzip(&latin1)), &options).is_none()); + let state = state.lock().unwrap(); + let usage = state.usage(resolver.usage()).unwrap(); + assert_eq!(usage.svg_resource_limit_images, 0, "decoded content fits its independent original allowance"); + assert_eq!(usage.svg_limit_images, 2, "both fitting retries remain omitted"); + assert_eq!(usage.invalid_svg_images, 1, "the original corrupt source stays classified as unreadable"); + assert_eq!(usage.embedded_svg_bytes, budget, "retry classification never refunds failed admission work"); + assert_eq!(state.classification_bytes_left(), budget / 2 - latin1.len(), "only inflated Latin-1 bytes consume retry inflation work"); } /// 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 @@ -1213,8 +1239,9 @@ fn images_after_a_damaged_svgz_are_unpacked_again_within_one_budget() { 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. +/// Classification after damaged data has one separate allowance for the entire drawing. +/// Exercise the real wrapped resolver: failed work stays charged and later references cannot +/// acquire another classification allowance after the first oversized source exhausts it. #[test] fn unpacking_images_again_adds_up_to_one_budget_however_many_there_are() { let budget = usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap(); @@ -1222,12 +1249,31 @@ fn unpacking_images_again_adds_up_to_one_budget_however_many_there_are() { 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); + let state = Arc::new(Mutex::new(image_integrity::Integrity::new(MAX_RASTER_PIXELS))); + let resolver = Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS))); + let options = options_with_isolation(Arc::new(usvg::fontdb::Database::new()), MAX_XML_DEPTH, false, Arc::clone(&resolver), Arc::clone(&state)); + let valid = gzip(b""); + let damaged = Arc::new(valid[..valid.len() / 2].to_vec()); + assert!((options.image_href_resolver.resolve_data)("image/svg+xml", damaged, &options).is_none()); + { + let state = state.lock().unwrap(); + let usage = state.usage(resolver.usage()).unwrap(); + assert_eq!(usage.invalid_svg_images, 1, "the actual damaged stream is omitted"); + assert_eq!(usage.embedded_svg_bytes, budget, "failed work retains its original charge"); + assert_eq!(usage.svg_resource_limit_images, 0, "corruption alone is not a resource overrun"); + assert_eq!(state.classification_bytes_left(), budget, "classification has its own single shared allowance"); + } + for index in 0..64 { + // Distinct references must share one classification pool, not acquire one + // pool per source or retry. This tail is never reached before the size cap. + let mut source = huge.clone(); + source.push(index); + assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::new(source), &options).is_none()); + let state = state.lock().unwrap(); + let usage = state.usage(resolver.usage()).unwrap(); + assert!(usage.svg_resource_limit_images > 0, "the body is too large independently of the failed-work charge"); + assert_eq!(state.classification_bytes_left(), 0, "all 64 references share exactly one exhausted allowance"); + assert_eq!(usage.embedded_svg_bytes, budget, "classification must not refund or multiply the original allowance"); } } @@ -1609,17 +1655,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); } - -#[test] -fn plain_legacy_encoding_rechecks_have_a_separate_bounded_work_allowance() { - let budget = usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap(); - let xml = b""; - let refusals = SvgRefusals { unread_charges: AtomicUsize::new(budget), text_rechecked: AtomicUsize::new(budget - xml.len()), ..SvgRefusals::default() }; - note_byte_refusal(xml, budget, &refusals); - assert!(!refusals.over_budget.load(Ordering::Relaxed)); - assert_eq!(refusals.text_rechecked.load(Ordering::Relaxed), budget); - assert_eq!(refusals.rechecked.load(Ordering::Relaxed), 0); - note_byte_refusal(xml, budget, &refusals); - assert!(refusals.over_budget.load(Ordering::Relaxed)); - assert_eq!(refusals.text_rechecked.load(Ordering::Relaxed), budget); -} diff --git a/crates/io/src/svg/xml_reuse_tests.rs b/crates/io/src/svg/xml_reuse_tests.rs new file mode 100644 index 0000000000..44f150cbbd --- /dev/null +++ b/crates/io/src/svg/xml_reuse_tests.rs @@ -0,0 +1,137 @@ +use super::super as svg; +use super::*; +use std::sync::Arc; + +fn empty_fonts() -> Arc { + Arc::new(svg::usvg::fontdb::Database::new()) +} + +fn parse_count(run: impl FnOnce() -> T) -> (T, usize) { + XML_PARSES.with(|count| count.set(0)); + let result = run(); + (result, XML_PARSES.with(|count| count.get())) +} + +#[test] +fn unchanged_xml_is_borrowed_and_converted_with_one_checked_parse() { + let text = ""; + let limits = svg::tree_limits(svg::MAX_XML_DEPTH, svg::MAX_RASTER_PIXELS); + let (result, count) = parse_count(|| { + with_repaired_xml(text, &limits, |xml| { + assert_eq!(xml.input_text().as_ptr(), text.as_ptr(), "unchanged XML retains the caller's source"); + assert_eq!(xml.descendants().filter(|n| n.has_tag_name((SVG_NS, "rect"))).count(), 1); + Ok(()) + }) + }); + result.unwrap(); + assert_eq!(count, 1); + let (parsed, count) = parse_count(|| svg::parse_with(text.as_bytes(), empty_fonts)); + let parsed = parsed.unwrap(); + assert_eq!(count, 1, "the ordinary parser must not parse the checked XML again"); + let pixels = svg::render(&parsed.tree, 1.).unwrap(); + assert_eq!(pixels.pixel(1, 1).unwrap().red(), 255); + let (parsed, count) = parse_count(|| svg::parse_bounded_inner_with(text.as_bytes(), 16, empty_fonts)); + parsed.unwrap(); + assert_eq!(count, 1, "bounded previews use the same checked-DOM path"); +} + +#[test] +fn repaired_xml_is_checked_again_and_keeps_warning_and_strict_contracts() { + let text = ""; + let (parsed, count) = parse_count(|| svg::parse_with(text.as_bytes(), empty_fonts)); + let parsed = parsed.unwrap(); + assert_eq!(count, 2, "repair reparses only the replacement, after checking the original"); + assert_eq!(parsed.image_usage.invalid_raster_images, 1); + assert_eq!(svg::render(&parsed.tree, 1.).unwrap().pixel(2, 2).unwrap().red(), 255); + let (pixels, warnings) = svg::rasterize_bounded_with_warnings(text.as_bytes(), 1., 16).unwrap(); + assert_eq!(pixels.get(2, 2), [1., 0., 0., 1.]); + assert_eq!(warnings.len(), 1); + assert!(svg::rasterize_bounded(text.as_bytes(), 1., 16).is_err()); +} + +#[test] +fn original_xml_guards_run_before_repair_or_conversion() { + let normal = ""; + let entity = "]>"; + let markup = "'>]>&a;"; + let referenced = ""; + for (text, limits) in [ + (normal, Limits { bytes: normal.len() - 1, ..Default::default() }), + (normal, Limits { attributes: 0, ..Default::default() }), + (normal, Limits { xml_nodes: 1, ..Default::default() }), + (entity, Limits { entity_bytes: 1, ..Default::default() }), + (markup, Limits { refuse_entity_markup: true, ..Default::default() }), + (referenced, Limits { tree_depth: 2, ..Default::default() }), + ] { + let mut converted = false; + let result = with_repaired_xml(text, &limits, |_| { + converted = true; + Ok(()) + }); + assert!(result.is_err(), "guard must reject original XML: {text}"); + assert!(!converted, "an unchecked DOM must never reach conversion"); + } + let allowed = Limits { entity_bytes: 1024, ..Default::default() }; + with_repaired_xml(entity, &allowed, |xml| { + assert_eq!(xml.descendants().find(|n| n.has_tag_name("image")).unwrap().attribute("href"), Some(INVALID_IMAGE)); + Ok(()) + }) + .unwrap(); +} + +// Retain the previous public-library sequence solely as a timing control. It +// uses the same resolver/validation implementations, not a copied decoder. +fn prior_parse(text: &str) -> Result { + let limits = svg::tree_limits(svg::MAX_XML_DEPTH, svg::MAX_RASTER_PIXELS); + let resolver = Arc::new(craft_svg::tree::ImageResolver::new(limits)); + resolver.set_document_depth(svg::nesting_depth(text.as_bytes(), svg::MAX_XML_DEPTH)?); + let state = Arc::new(std::sync::Mutex::new(svg::image_integrity::Integrity::new(svg::MAX_RASTER_PIXELS))); + let options = svg::options_with_isolation(empty_fonts(), svg::MAX_XML_DEPTH, false, Arc::clone(&resolver), state); + let repaired = repair(text, &limits)?; + resolver.check_document(&repaired).map_err(svg::svg_parse_error)?; + craft_svg::tree::parse_text(&repaired, &limits, &options).map_err(svg::svg_parse_error) +} + +#[test] +#[ignore = "release-only XML and 24 MP embedded-source timing probe"] +fn xml_reuse_and_24mp_source_timing() { + use std::time::Instant; + let image = photocraft_codecs::Image::from_u8(6000, 4000, photocraft_codecs::ChannelLayout::Rgb, [17, 83, 149].repeat(24_000_000)).unwrap(); + let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + drop(image); + let mut href = String::from("data:image/png,"); + for byte in png { + use std::fmt::Write; + write!(&mut href, "%{byte:02X}").unwrap(); + } + let embedded = format!(""); + let mut xml = format!(""); + for _ in 0..20_000 { + xml.push_str(""); + } + xml.push_str(""); + for (name, text) in [("xml-20000-nodes", xml), ("png-24mp", embedded)] { + let mut expected = None; + for old in [false, true, false] { + let started = Instant::now(); + let tree = if old { prior_parse(&text).unwrap() } else { svg::parse_with(text.as_bytes(), empty_fonts).unwrap().tree }; + let elapsed = started.elapsed(); + let rendered = svg::render(&tree, 1.).unwrap(); + let checksum: u64 = rendered.data().iter().map(|b| u64::from(*b)).sum(); + if let Some(previous) = expected { + assert_eq!(checksum, previous); + } else { + expected = Some(checksum); + } + assert_eq!((rendered.width(), rendered.height()), (16, 16)); + eprintln!("{name} {} parse_ms={:.3} output_checksum={checksum}", if old { "prior" } else { "reuse" }, elapsed.as_secs_f64() * 1000.); + } + } +} + +#[test] +fn checked_xml_conversion_panic_is_an_isolation_failure() { + let limits = svg::tree_limits(svg::MAX_XML_DEPTH, svg::MAX_RASTER_PIXELS); + let result: Result, IoError> = svg::guarded_parse(|| with_repaired_xml("", &limits, |_| panic!("injected XML conversion panic"))); + assert!(matches!(result, Err(IoError::Svg(message)) if message.contains("bounded SVG worker failed"))); +} diff --git a/crates/ui-egui/src/smart_svg_ui.rs b/crates/ui-egui/src/smart_svg_ui.rs index 611e693831..c1314f4ae0 100644 --- a/crates/ui-egui/src/smart_svg_ui.rs +++ b/crates/ui-egui/src/smart_svg_ui.rs @@ -469,7 +469,7 @@ pub(crate) fn poll(app: &mut PhotocraftApp, ctx: &egui::Context) { Ok(result) => { if let Some(fingerprint) = result.get("fingerprint").filter(|v| !v.is_null()) { edit.target.fingerprint = fingerprint.clone(); - crate::notices::io_result_warnings(app, &result, "SVG"); + crate::notices::io_result_warnings(app, &result, if native { "Vector" } else { "SVG" }); } else { report(app, "The SVG update did not return its fingerprint; syncing stopped".into()); continue; diff --git a/crates/ui-egui/src/smart_svg_ui/tests.rs b/crates/ui-egui/src/smart_svg_ui/tests.rs index 5bced96c17..f82ad90e35 100644 --- a/crates/ui-egui/src/smart_svg_ui/tests.rs +++ b/crates/ui-egui/src/smart_svg_ui/tests.rs @@ -770,6 +770,38 @@ fn finished_session_retains_final_save_until_target_is_safe() { assert!(app.smart_svg.editing.is_empty()); } +#[test] +fn external_svg_save_back_reports_omissions_once_and_keeps_silent_updates_quiet() { + for omitted in [false, true] { + let (mut app, saves, _) = fixture(); + open(&mut app); + app.smart_svg.pending.as_mut().unwrap().editor = Editor::Illustrator; + confirm(&mut app).unwrap(); + app.ui.notices.clear(); + let before = app.session.active().unwrap().doc.clone(); + let child = if omitted { "" } else { "" }; + let svg = SVG.replace("red", "blue").replace("", &format!("{child}")); + saves.borrow_mut().push_back(Ok(svg.into_bytes())); + let ctx = egui::Context::default(); + poll(&mut app, &ctx); + assert_ne!(app.session.active().unwrap().doc, before); + assert_eq!(app.smart_svg.editing.len(), 1, "the session keeps the successful new fingerprint"); + if omitted { + assert_eq!(app.ui.notices.len(), 1); + assert!(app.ui.notices[0].title.contains("SVG")); + assert!(app.ui.notices[0].lines.iter().any(|line| line.contains("embedded") && line.contains("omitted"))); + assert!(!app.ui.notices[0].error); + } else { + assert!(app.ui.notices.is_empty(), "{:?}", app.ui.notices); + } + let notices = app.ui.notices.clone(); + poll(&mut app, &ctx); + assert_eq!(app.ui.notices, notices, "polling the same completed save cannot duplicate a warning"); + app.session.execute("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc, before); + } +} + #[test] fn svg_save_back_displays_omitted_image_warning() { let (mut app, saves, _) = fixture(); From e1866168957b3c67ff2a3b1cbd556048e3cfe690 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Tue, 17 Nov 2026 04:09:01 +0800 Subject: [PATCH 02/85] Match worker setup in SVG parse timing controls --- crates/io/src/svg/xml_reuse_tests.rs | 38 ++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/crates/io/src/svg/xml_reuse_tests.rs b/crates/io/src/svg/xml_reuse_tests.rs index 44f150cbbd..59dd9d8083 100644 --- a/crates/io/src/svg/xml_reuse_tests.rs +++ b/crates/io/src/svg/xml_reuse_tests.rs @@ -79,17 +79,32 @@ fn original_xml_guards_run_before_repair_or_conversion() { .unwrap(); } -// Retain the previous public-library sequence solely as a timing control. It -// uses the same resolver/validation implementations, not a copied decoder. -fn prior_parse(text: &str) -> Result { +// Retain the previous public-library sequence solely as a timing control. Its +// outer inflate/depth/font/resolver setup, worker entry and usage snapshot match +// parse_with; only repair + check_document + shared parse_text differ. +fn prior_parse(bytes: &[u8]) -> Result { + let xml = svg::inflate(bytes)?; + let depth = svg::nesting_depth(&xml, svg::MAX_XML_DEPTH)?; + if depth > svg::MAX_XML_DEPTH { + return Err(IoError::Svg(format!("elements are nested more than {} levels deep", svg::MAX_XML_DEPTH))); + } + let has_text = xml.windows(4).any(|w| w == b"text"); + let fontdb = empty_fonts(); + let fontless_text = has_text && fontdb.faces().next().is_none(); + let text = std::str::from_utf8(&xml).map_err(|_| IoError::Svg("the SVG is not valid UTF-8".into()))?; let limits = svg::tree_limits(svg::MAX_XML_DEPTH, svg::MAX_RASTER_PIXELS); let resolver = Arc::new(craft_svg::tree::ImageResolver::new(limits)); - resolver.set_document_depth(svg::nesting_depth(text.as_bytes(), svg::MAX_XML_DEPTH)?); let state = Arc::new(std::sync::Mutex::new(svg::image_integrity::Integrity::new(svg::MAX_RASTER_PIXELS))); - let options = svg::options_with_isolation(empty_fonts(), svg::MAX_XML_DEPTH, false, Arc::clone(&resolver), state); - let repaired = repair(text, &limits)?; - resolver.check_document(&repaired).map_err(svg::svg_parse_error)?; - craft_svg::tree::parse_text(&repaired, &limits, &options).map_err(svg::svg_parse_error) + resolver.set_document_depth(depth); + svg::parse_at_depth(depth, false, |isolated| { + let options = svg::options_with_isolation(fontdb, svg::MAX_XML_DEPTH.saturating_sub(depth), isolated, Arc::clone(&resolver), Arc::clone(&state)); + let repaired = repair(text, &limits)?; + resolver.check_document(&repaired).map_err(svg::svg_parse_error)?; + let tree = svg::guarded_parse(|| craft_svg::tree::parse_text(&repaired, &limits, &options))?.map_err(svg::svg_parse_error)?; + let image_usage = state.lock().unwrap_or_else(std::sync::PoisonError::into_inner).usage(resolver.usage())?; + Ok(svg::Parsed { tree, fontless_text, image_usage }) + }) + .map_err(IoError::from) } #[test] @@ -114,9 +129,12 @@ fn xml_reuse_and_24mp_source_timing() { let mut expected = None; for old in [false, true, false] { let started = Instant::now(); - let tree = if old { prior_parse(&text).unwrap() } else { svg::parse_with(text.as_bytes(), empty_fonts).unwrap().tree }; + let parsed = if old { prior_parse(text.as_bytes()).unwrap() } else { svg::parse_with(text.as_bytes(), empty_fonts).unwrap() }; let elapsed = started.elapsed(); - let rendered = svg::render(&tree, 1.).unwrap(); + assert!(!parsed.fontless_text); + assert_eq!(svg::omitted_image_count(parsed.image_usage), 0); + assert_eq!(parsed.image_usage.raster_pixels, if name == "png-24mp" { 24_000_000 } else { 0 }); + let rendered = svg::render(&parsed.tree, 1.).unwrap(); let checksum: u64 = rendered.data().iter().map(|b| u64::from(*b)).sum(); if let Some(previous) = expected { assert_eq!(checksum, previous); From 53c0a6aecdcfe8fc174c7e6c82d1f41ba5d2e912 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Tue, 17 Nov 2026 06:09:22 +0800 Subject: [PATCH 03/85] Observe XML parse counts on the isolated parser worker --- crates/io/src/svg/xml_reuse_tests.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/io/src/svg/xml_reuse_tests.rs b/crates/io/src/svg/xml_reuse_tests.rs index 59dd9d8083..dbf21c4984 100644 --- a/crates/io/src/svg/xml_reuse_tests.rs +++ b/crates/io/src/svg/xml_reuse_tests.rs @@ -6,10 +6,16 @@ fn empty_fonts() -> Arc { Arc::new(svg::usvg::fontdb::Database::new()) } -fn parse_count(run: impl FnOnce() -> T) -> (T, usize) { - XML_PARSES.with(|count| count.set(0)); - let result = run(); - (result, XML_PARSES.with(|count| count.get())) +fn parse_count(run: impl FnOnce() -> T + Send) -> (T, usize) { + // The public parsers dispatch onto this worker on native targets. Reset and + // read its TLS there too; nested parser entry then reuses the same worker. + // on_svg_stack executes this closure directly on wasm. + svg::on_svg_stack(move || { + XML_PARSES.with(|count| count.set(0)); + let result = run(); + Ok((result, XML_PARSES.with(|count| count.get()))) + }) + .unwrap() } #[test] From 0fba1456043a20ee55af868c88c135073b4fd66d Mon Sep 17 00:00:00 2001 From: Terra854 Date: Tue, 17 Nov 2026 19:04:53 +0800 Subject: [PATCH 04/85] Reuse shared SVG validation and bound source cache work --- Cargo.lock | 146 ++++-- Cargo.toml | 7 +- crates/engine/src/cmd/smart_cmds.rs | 7 +- crates/engine/src/cmd/smart_cmds/rendering.rs | 246 ++++++++--- crates/engine/src/cmd/smart_cmds/source.rs | 13 +- .../src/cmd/smart_cmds/tests/source_work.rs | 205 +++++++++ .../cmd/smart_svg_cmds/source_cache_tests.rs | 7 +- crates/io/Cargo.toml | 9 +- crates/io/src/svg.rs | 110 ++--- crates/io/src/svg/data_href_validation.rs | 415 ------------------ crates/io/src/svg/decoder_edges.rs | 103 +++++ crates/io/src/svg/image_integrity.rs | 297 ------------- crates/io/src/svg/integrity_budget_tests.rs | 259 ----------- crates/io/src/svg/mime_header_tests.rs | 119 ----- .../io/src/svg/optional_image_review_tests.rs | 10 +- crates/io/src/svg/raster_validation.rs | 135 ------ crates/io/src/svg/tests.rs | 195 ++++---- crates/io/src/svg/xml_reuse_tests.rs | 206 ++++----- 18 files changed, 877 insertions(+), 1612 deletions(-) create mode 100644 crates/engine/src/cmd/smart_cmds/tests/source_work.rs delete mode 100644 crates/io/src/svg/data_href_validation.rs create mode 100644 crates/io/src/svg/decoder_edges.rs delete mode 100644 crates/io/src/svg/image_integrity.rs delete mode 100644 crates/io/src/svg/integrity_budget_tests.rs delete mode 100644 crates/io/src/svg/mime_header_tests.rs delete mode 100644 crates/io/src/svg/raster_validation.rs diff --git a/Cargo.lock b/Cargo.lock index b0c651627b..e602c4abf3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1364,7 +1364,7 @@ version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "thiserror 2.0.21", ] @@ -1376,6 +1376,14 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-dds" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a#f32b47a1d4799269b7e4b99bb130161dcb7b312a" +dependencies = [ + "rayon", +] + [[package]] name = "craft-docpath" version = "0.1.0" @@ -1393,12 +1401,12 @@ source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064 dependencies = [ "craft-eps", "craft-idml", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-kra", "craft-ora", "craft-pcraft-bundle", "craft-raw", - "craft-svg", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-zip", "serde", "serde_json", @@ -1456,18 +1464,45 @@ name = "craft-idml" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-zip", "thiserror 2.0.21", ] +[[package]] +name = "craft-image-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a#f32b47a1d4799269b7e4b99bb130161dcb7b312a" +dependencies = [ + "craft-dds", + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a)", + "crc32fast", + "exr", + "flate2", + "half", + "hayro-jpeg2000", + "image", + "image-webp", + "jpeg-encoder", + "png 0.18.1", + "rayon", + "serde_json", + "thiserror 2.0.21", + "tiff", + "zune-core", + "zune-jpeg", + "zune-jpegxl", +] + [[package]] name = "craft-image-codecs" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ "craft-heif", - "craft-jpeg", + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "crc32fast", "exr", @@ -1487,6 +1522,14 @@ dependencies = [ "zune-jpegxl", ] +[[package]] +name = "craft-jpeg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a#f32b47a1d4799269b7e4b99bb130161dcb7b312a" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-jpeg" version = "0.1.0" @@ -1500,7 +1543,7 @@ name = "craft-kra" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-zip", "thiserror 2.0.21", ] @@ -1517,6 +1560,18 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-metadata" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a#f32b47a1d4799269b7e4b99bb130161dcb7b312a" +dependencies = [ + "brotli-decompressor 6.3.1", + "chrono", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a)", + "quick-xml 0.41.0", + "serde", +] + [[package]] name = "craft-metadata" version = "0.1.0" @@ -1534,7 +1589,7 @@ name = "craft-ora" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" dependencies = [ - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-zip", "thiserror 2.0.21", ] @@ -1716,19 +1771,38 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" +source = "git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a#f32b47a1d4799269b7e4b99bb130161dcb7b312a" dependencies = [ - "craft-image-codecs", - "craft-xml", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a)", "data-url", "flate2", + "gif", + "image-webp", "kurbo 0.13.1", + "quick-xml 0.41.0", "resvg 0.48.1", "roxmltree 0.21.2", "thiserror 2.0.21", "usvg 0.48.1", "vectorcraft-geom", "vectorcraft-pathops", + "zune-jpeg", +] + +[[package]] +name = "craft-svg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a" +dependencies = [ + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", + "flate2", + "kurbo 0.13.1", + "roxmltree 0.21.2", + "thiserror 2.0.21", + "vectorcraft-geom", + "vectorcraft-pathops", ] [[package]] @@ -1740,6 +1814,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a#f32b47a1d4799269b7e4b99bb130161dcb7b312a" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-tiff" version = "0.1.0" @@ -1814,6 +1897,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a#f32b47a1d4799269b7e4b99bb130161dcb7b312a" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-xml" version = "0.1.0" @@ -5526,10 +5619,10 @@ dependencies = [ "core-graphics2", "craft-cms", "craft-flags", - "craft-image-codecs", - "craft-svg", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a)", "craft-update", - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "dispatch2", "eframe", "egui", @@ -5594,7 +5687,7 @@ dependencies = [ "clap", "craft-ai-agents", "craft-flags", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eafb50aff3c6b1acc14dff53060157877e3e4fce)", "getrandom 0.3.4", "hmac", @@ -5628,7 +5721,7 @@ dependencies = [ "clap_complete", "clap_mangen", "craft-cms", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eafb50aff3c6b1acc14dff53060157877e3e4fce)", "photocraft-automation", "photocraft-doc", @@ -5691,11 +5784,11 @@ dependencies = [ "craft-affinity", "craft-cms", "craft-file-formats", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-pcraft-format 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3e970577b9bb446967c2003ec8ecaf4f28b0768c)", "craft-print", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eafb50aff3c6b1acc14dff53060157877e3e4fce)", - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "exr", "flate2", "getrandom 0.3.4", @@ -5733,7 +5826,7 @@ version = "0.23.1" dependencies = [ "blake3", "craft-file-formats", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-pcraft-bundle", "craft-pcraft-format 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-zip", @@ -5792,7 +5885,7 @@ dependencies = [ "craft-crs", "craft-docpath", "craft-file-formats", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-kra", "craft-ora", "craft-pdf", @@ -5804,15 +5897,12 @@ dependencies = [ "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5e2bc54a48c9f03e7ce4eca42775ce5cc051f5d6)", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b9c22554ce0fd2caccdb53b417082a2ff2ef178f)", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eafb50aff3c6b1acc14dff53060157877e3e4fce)", - "craft-svg", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a)", "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-xcf", - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "crc32fast", - "data-url", "flate2", - "gif", - "image-webp", "kurbo 0.13.1", "lopdf", "miniz_oxide 0.9.1", @@ -5831,9 +5921,9 @@ dependencies = [ "proptest", "serde_json", "thiserror 2.0.21", + "toml", "ttf-parser", "zune-core", - "zune-jpeg", "zune-jpegxl", ] @@ -5899,7 +5989,7 @@ dependencies = [ name = "photocraft-raw" version = "0.23.1" dependencies = [ - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-raw", "flate2", "image", @@ -5959,7 +6049,7 @@ dependencies = [ "craft-cms", "craft-file-formats", "craft-i18n", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-print", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eafb50aff3c6b1acc14dff53060157877e3e4fce)", "craft-ui", @@ -6015,7 +6105,7 @@ dependencies = [ name = "photocraft-web" version = "0.23.1" dependencies = [ - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eafb50aff3c6b1acc14dff53060157877e3e4fce)", "eframe", "egui", diff --git a/Cargo.toml b/Cargo.toml index 4a5cb02906..a9ac4625b0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,11 +10,6 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -# Match SVG renderer backends for exact optional-image validation. -zune-jpeg = "=0.5.15" -gif = "=0.14.2" -image-webp = "=0.2.4" -data-url = "=0.3.2" craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a", features = ["serde"] } # Feature flags shared with the launcher and the other Craft apps (craft-libs#1118, #1119). craft-flags = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } @@ -67,7 +62,7 @@ craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a", features = ["tree-render", "tree-render-system-fonts"] } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "f32b47a1d4799269b7e4b99bb130161dcb7b312a", features = ["tree-render", "tree-render-system-fonts"] } craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } # Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563. diff --git a/crates/engine/src/cmd/smart_cmds.rs b/crates/engine/src/cmd/smart_cmds.rs index a494f3552e..5afccb2141 100644 --- a/crates/engine/src/cmd/smart_cmds.rs +++ b/crates/engine/src/cmd/smart_cmds.rs @@ -70,7 +70,12 @@ pub fn encode_source(doc: &Document) -> Result> { /// Decodes smart-object contents (a `.pcraft` bundle, PSD/PSB, or any flat image format). pub fn decode_source(file_name: &str, bytes: &[u8]) -> Result { - if photocraft_io::is_svg_input(file_name, bytes) { + decode_source_classified(file_name, bytes, photocraft_io::is_svg_input(file_name, bytes)) +} + +/// Reuse the central format decision made by this render operation. +fn decode_source_classified(file_name: &str, bytes: &[u8], svg: bool) -> Result { + if svg { // This API has no warning channel. Stack/source caches and contents edits must not // turn a partial SVG import into silently complete smart-object contents. return photocraft_io::svg::import_svg_bounded_images_strict(file_name, bytes, 24_000_000) diff --git a/crates/engine/src/cmd/smart_cmds/rendering.rs b/crates/engine/src/cmd/smart_cmds/rendering.rs index eb19efdfff..07e66b46f0 100644 --- a/crates/engine/src/cmd/smart_cmds/rendering.rs +++ b/crates/engine/src/cmd/smart_cmds/rendering.rs @@ -1,26 +1,31 @@ use super::filters::smart; use super::source::{ - SourceImage, cache_get, cache_key, cache_put, convert_svg_source, source_bytes, source_image, source_surface_from_buffer, svg_source_image_in, vector_scale, + SourceImage, cache_get, cache_key, cache_put, convert_svg_source, source_bytes, source_surface_from_buffer, svg_source_image_in, vector_scale, }; use super::{ Affine, Arc, BlendMode, Document, EngineError, Homography, JobCtx, Layer, LayerContent, LayerId, PixelFormat, Rect, Result, SmartFilter, SmartObject, - SmartSource, Stage, StageKey, Surface, Value, affine_homography, decode_source, other, placement, stack_cache, + SmartSource, Stage, StageKey, Surface, Value, affine_homography, other, placement, stack_cache, }; -use std::sync::Mutex; +use std::collections::VecDeque; +use std::sync::{Mutex, Weak}; /// Layer › Smart Objects › Stack Mode: the source's layers (or, when it holds a single group, the -/// group's layers) combined per pixel with `mode`. Cached like [`source_image`], keyed by mode. +/// group's layers) combined per pixel with `mode`. Cached like [`super::source_image`], keyed by mode. pub fn stack_image(file_name: &str, bytes: &[u8], fmt: PixelFormat, mode: photocraft_doc::StackMode) -> Result { + stack_image_classified(file_name, bytes, fmt, mode, None) +} + +fn stack_image_classified(file_name: &str, bytes: &[u8], fmt: PixelFormat, mode: photocraft_doc::StackMode, svg: Option) -> Result { use photocraft_algo::stack::Stat; let mut key = cache_key(bytes, fmt); - // Incomplete warning-aware imports must never share a strict Stack Mode cache. - let svg = photocraft_io::is_svg_input(file_name, bytes); - let domain: &[u8] = if svg { b"stack-svg-complete-v1:" } else { b"stack:" }; - key.0 = *blake3::hash(&[&key.0[..], domain, mode.id().as_bytes()].concat()).as_bytes(); + // A uniform fresh strict domain admits cache hits before any compressed SVG probe. + // Earlier domains could contain incomplete warning-aware SVG imports. + key.0 = *blake3::hash(&[&key.0[..], b"stack-complete-v2:", blake3::hash(file_name.as_bytes()).as_bytes(), mode.id().as_bytes()].concat()).as_bytes(); if let Some(img) = cache_get(&key) { return Ok(img); } - let doc = decode_source(file_name, bytes)?; + let svg = svg.unwrap_or_else(|| svg_input(file_name, bytes)); + let doc = super::decode_source_classified(file_name, bytes, svg)?; let layers: &[Layer] = match doc.layers.as_slice() { [only] if only.is_group() => only.children().unwrap_or_default(), all => all, @@ -67,6 +72,15 @@ pub fn stack_image(file_name: &str, bytes: &[u8], fmt: PixelFormat, mode: photoc Ok(img) } +#[cfg(test)] +thread_local! { static SVG_CLASSIFICATIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; } + +fn svg_input(name: &str, bytes: &[u8]) -> bool { + #[cfg(test)] + SVG_CLASSIFICATIONS.with(|count| count.set(count.get().saturating_add(1))); + photocraft_io::is_svg_input(name, bytes) +} + // ---------- rendering ---------- /// Mix a filter's result with its input, without stacking the same pixel coverage twice. @@ -176,16 +190,24 @@ fn apply_smart_filter(f: &SmartFilter, sm: &SmartObject, cur: &Surface, canvas: if f.blend == BlendMode::Normal && f.opacity >= 1.0 { Ok(out) } else { Ok(blend_surfaces(cur, &out, f.blend, f.opacity.clamp(0.0, 1.0))) } } -/// The source placed in document pixels, before any smart filter. +/// The source placed in document pixels, before any smart filter (uncached test oracle). +#[cfg(test)] pub(super) fn place(name: &str, bytes: &[u8], doc: &Document, sm: &SmartObject) -> Result { - place_with_svg(name, bytes, doc, sm, &mut |bytes, scale| svg_source_image_in(bytes, doc, scale)) + place_with_svg(name, bytes, doc, sm, svg_input(name, bytes), &mut |bytes, scale| svg_source_image_in(bytes, doc, scale)) } -fn place_with_svg(name: &str, bytes: &[u8], doc: &Document, sm: &SmartObject, svg: &mut impl FnMut(&[u8], f64) -> Result) -> Result { +fn place_with_svg( + name: &str, + bytes: &[u8], + doc: &Document, + sm: &SmartObject, + is_svg: bool, + svg: &mut impl FnMut(&[u8], f64) -> Result, +) -> Result { let fmt = doc.pixel_format(); // A vector source is rendered at the placement's scale, and the placement is divided by // that scale so the rendered pixels land where the source units would. - if sm.stack_mode.is_none() && sm.warp.is_none() && photocraft_io::is_svg_input(name, bytes) { + if sm.stack_mode.is_none() && sm.warp.is_none() && is_svg { let k = vector_scale(sm); let img = svg(bytes, k)?; return Ok(match &sm.perspective { @@ -204,10 +226,10 @@ fn place_with_svg(name: &str, bytes: &[u8], doc: &Document, sm: &SmartObject, sv }); } let img = match sm.stack_mode { - Some(mode) if photocraft_io::is_svg_input(name, bytes) => convert_svg_source(stack_image(name, bytes, PixelFormat::RGBA32F, mode)?, doc)?, - None if photocraft_io::is_svg_input(name, bytes) => svg(bytes, 1.0)?, - Some(mode) => stack_image(name, bytes, fmt, mode)?, - None => source_image(name, bytes, fmt)?, + Some(mode) if is_svg => convert_svg_source(stack_image_classified(name, bytes, PixelFormat::RGBA32F, mode, Some(is_svg))?, doc)?, + None if is_svg => svg(bytes, 1.0)?, + Some(mode) => stack_image_classified(name, bytes, fmt, mode, Some(is_svg))?, + None => super::source::source_image_classified(name, bytes, fmt, is_svg)?, }; // The placed stage is unclipped: a large enough placement (an image scaled to fill a huge // frame) would otherwise fill memory before any allocation could fail. @@ -313,9 +335,17 @@ pub(crate) fn source_box(doc: &Document, sm: &SmartObject) -> Option<[f64; 4]> { let bytes = display_source(sm, &bytes); let fmt = doc.pixel_format(); let r = match sm.stack_mode { - None if photocraft_io::is_svg_input(&name, &bytes) => photocraft_io::svg::bounded_canvas_bounds(&bytes, 24_000_000).ok()?, Some(mode) => stack_image(&name, &bytes, fmt, mode).ok()?.bounds, - None => source_image(&name, &bytes, fmt).ok()?.bounds, + None => { + // An existing typed placed stage already proves the source kind; bounds + // still come from the original drawing, not from its transformed pixels. + let (_, svg) = select_stage_domain(doc, sm, &name, &bytes, &[], None); + if svg { + photocraft_io::svg::bounded_canvas_bounds(&bytes, 24_000_000).ok()? + } else { + super::source::source_image_classified(&name, &bytes, fmt, false).ok()?.bounds + } + } }; Some([f64::from(r.x0), f64::from(r.y0), f64::from(r.x1), f64::from(r.y1)]) } @@ -333,20 +363,21 @@ pub(crate) fn render_with_warnings(doc: &Document, sm: &SmartObject) -> Result<( } struct WarningSource { - source: Arc>, - key: (u64, PixelFormat, [u8; 32]), + source: Weak>, + name: [u8; 32], + scale: u64, image: SourceImage, warnings: Vec, bytes: usize, } /// One command's bounded source-space renders. Placement, warp, filters and masks -/// are instance-specific and must never be cached here. Retaining the source Arc -/// makes allocation identity safe without hashing the same encoded SVG per instance. +/// are instance-specific and must never be cached here. Weak identity pins only the +/// allocation header; the borrowed document owns encoded bytes throughout the command. pub(crate) struct WarningRenderSources<'a> { document: &'a Document, - profile_context: Option<([u8; 32], bool)>, - entries: Vec, + srgb: Option, + entries: VecDeque, budget: usize, limit: usize, bytes: usize, @@ -364,7 +395,7 @@ impl<'a> WarningRenderSources<'a> { let limit = WARNING_SOURCE_LIMIT.with(|limit| limit.get().unwrap_or(32)); #[cfg(not(test))] let limit = 32; - Self { document, profile_context: None, entries: Vec::new(), budget: if cfg!(target_arch = "wasm32") { 128 << 20 } else { 384 << 20 }, limit, bytes: 0 } + Self { document, srgb: None, entries: VecDeque::new(), budget: if cfg!(target_arch = "wasm32") { 128 << 20 } else { 384 << 20 }, limit, bytes: 0 } } #[cfg(test)] @@ -374,43 +405,51 @@ impl<'a> WarningRenderSources<'a> { #[cfg(test)] pub(crate) fn profile_initialized(&self) -> bool { - self.profile_context.is_some() + self.srgb.is_some() } - fn image(&mut self, bytes: &Arc>, scale: f64) -> Result<(SourceImage, Vec)> { + fn knows_svg(&self, bytes: &Arc>, name: &[u8; 32]) -> bool { + self.entries.iter().any(|entry| entry.name == *name && std::ptr::eq(entry.source.as_ptr(), Arc::as_ptr(bytes))) + } + + fn image(&mut self, bytes: &Arc>, scale: f64, name: [u8; 32]) -> Result<(SourceImage, Vec)> { let doc = self.document; // Non-SVG and unavailable sources keep their old fast path without // materializing ICC bytes. This immutable document needs the context once. - let (profile_key, srgb) = *self.profile_context.get_or_insert_with(|| { - let profile = crate::color_cmds::document_profile(doc).to_bytes(); - ( - *blake3::hash(&profile).as_bytes(), - doc.mode == photocraft_color::ColorMode::Rgb && profile.as_ref() == craft_cms::Builtin::Srgb.profile().to_bytes().as_ref(), - ) - }); - let key = (scale.to_bits(), doc.pixel_format(), profile_key); - if let Some(index) = self.entries.iter().position(|entry| entry.key == key && Arc::ptr_eq(&entry.source, bytes)) { - let entry = self.entries.remove(index); + let key = scale.to_bits(); + if let Some(index) = + self.entries.iter().position(|entry| entry.scale == key && entry.name == name && std::ptr::eq(entry.source.as_ptr(), Arc::as_ptr(bytes))) + && let Some(entry) = self.entries.remove(index) + { let result = (entry.image.clone(), entry.warnings.clone()); - self.entries.push(entry); + self.entries.push_back(entry); return Ok(result); } + // Only the exact sRGB fast path needs this lazy, immutable document context. + // Pixel format/profile do not belong in each entry's key: the document is borrowed. + let srgb = *self.srgb.get_or_insert_with(|| { + doc.mode == photocraft_color::ColorMode::Rgb + && crate::color_cmds::document_profile(doc).to_bytes().as_ref() == craft_cms::Builtin::Srgb.profile().to_bytes().as_ref() + }); #[cfg(test)] WARNING_SOURCE_DECODES.with(|count| count.set(count.get().saturating_add(1))); let (buf, warnings) = photocraft_io::svg::rasterize_bounded_with_warnings(bytes, scale as f32, 24_000_000) .map_err(|e| other(format!("can't render the SVG smart object: {e}")))?; - // Charge full native tiles and retained encoded bytes, not just logical pixels. + // Charge owned native tiles, entry and warning storage, not borrowed encoded bytes. // This is a soft memo budget: oversize entries retain the existing uncached path. let cost = usize::try_from(photocraft_raster::tile_storage_bytes(buf.rect, &doc.pixel_format())) .unwrap_or(usize::MAX) - .saturating_add(bytes.capacity()) .saturating_add(std::mem::size_of::()) .saturating_add(warnings.capacity().saturating_mul(std::mem::size_of::())) .saturating_add(warnings.iter().fold(0usize, |total, warning| total.saturating_add(warning.capacity()))); let admitted = self.limit != 0 && cost <= self.budget; if admitted { while self.entries.len() >= self.limit || self.bytes > self.budget - cost { - let entry = self.entries.remove(0); + let Some(entry) = self.entries.pop_front() else { + // Recover conservatively if accounting ever outlives an empty queue. + self.bytes = 0; + break; + }; self.bytes = self.bytes.saturating_sub(entry.bytes); } } @@ -423,7 +462,14 @@ impl<'a> WarningRenderSources<'a> { }; if admitted && self.entries.try_reserve(1).is_ok() { self.bytes += cost; // cost was admitted against budget - bytes above. - self.entries.push(WarningSource { source: Arc::clone(bytes), key, image: image.clone(), warnings: warnings.clone(), bytes: cost }); + self.entries.push_back(WarningSource { + source: Arc::downgrade(bytes), + name, + scale: key, + image: image.clone(), + warnings: warnings.clone(), + bytes: cost, + }); } Ok((image, warnings)) } @@ -432,68 +478,122 @@ impl<'a> WarningRenderSources<'a> { /// Reuse only warning-aware source pixels during one shared-content update. pub(crate) fn render_with_warnings_using(sm: &SmartObject, sources: &mut WarningRenderSources<'_>) -> Result<(Option, Vec)> { let doc = sources.document; - let Some((name, bytes)) = source_bytes(&doc.metadata, &sm.source) else { return Ok((None, Vec::new())) }; - if !photocraft_io::is_svg_input(&name, &bytes) || sm.vector_preview.is_some() || sm.stack_mode.is_some() { + if sm.vector_preview.is_some() || sm.stack_mode.is_some() { return render(doc, sm).map(|surface| (surface, Vec::new())); } + let Some((name, bytes)) = source_bytes(&doc.metadata, &sm.source) else { return Ok((None, Vec::new())) }; + // Filename recognition is not constant: the same source Arc may be named + // .svgz in one instance and .af in another, which the central router treats differently. + let name_key = *blake3::hash(name.as_bytes()).as_bytes(); + if !sources.knows_svg(&bytes, &name_key) && !svg_input(&name, &bytes) { + // Keep this exact authorized source snapshot and its decision through strict fallback. + return render_in_with_source(doc, sm, &JobCtx::new(), Some((name, bytes, false))).map(|surface| (surface, Vec::new())); + } if !unapplied_filters(sm).is_empty() { return Err(other("the smart object has unsupported visible filters")); } let mut warnings = Vec::new(); - let placed = place_with_svg(&name, &bytes, doc, sm, &mut |_, scale| { - let (image, omitted) = sources.image(&bytes, scale)?; + let placed = place_with_svg(&name, &bytes, doc, sm, true, &mut |_, scale| { + let (image, omitted) = sources.image(&bytes, scale, name_key)?; warnings.extend(omitted); Ok(image) })?; Ok((Some(apply_smart_filters(&placed, sm, doc.bounds())?), warnings)) } +/// A typed stage domain keeps successful non-SVG and strict SVG results distinguishable +/// without probing a compressed source again. Names remain part of format recognition. +fn stage_domain(base: &StageKey, name: &str, doc: &Document, svg: bool) -> StageKey { + let mut hash = blake3::Hasher::new(); + hash.update(base); + hash.update(if svg { b"strict-svg-stage-v2:" } else { b"non-svg-stage-v2:" }); + hash.update(blake3::hash(name.as_bytes()).as_bytes()); + if svg { + hash.update(&crate::color_cmds::document_profile(doc).to_bytes()); + } + *hash.finalize().as_bytes() +} + +struct CachedStages { + placed_key: StageKey, + keys: Vec, + hit: Option<(usize, Stage)>, +} + +fn stage_candidate(placed_key: StageKey, filters: &[&SmartFilter], mask: Option<&photocraft_doc::LayerMask>) -> CachedStages { + let keys: Vec<_> = filters + .iter() + .scan(placed_key, |key, filter| { + *key = stack_cache::filter_key(key, filter, mask); + Some(*key) + }) + .collect(); + let hit = keys + .iter() + .enumerate() + .rev() + .find_map(|(index, key)| stack_cache::get(key).map(|stage| (index + 1, stage))) + .or_else(|| stack_cache::get(&placed_key).map(|stage| (0, stage))); + CachedStages { placed_key, keys, hit } +} + +fn select_stage_domain(doc: &Document, sm: &SmartObject, name: &str, bytes: &[u8], filters: &[&SmartFilter], known: Option) -> (CachedStages, bool) { + let base = stack_cache::placed_key(bytes, doc.pixel_format(), sm, doc.bounds()); + let ordinary = stage_candidate(stage_domain(&base, name, doc, false), filters, sm.filter_mask.as_ref()); + if known == Some(false) || (known.is_none() && ordinary.hit.is_some()) { + return (ordinary, false); + } + let svg = stage_candidate(stage_domain(&base, name, doc, true), filters, sm.filter_mask.as_ref()); + if known == Some(true) || svg.hit.is_some() { + return (svg, true); + } + if svg_input(name, bytes) { (svg, true) } else { (ordinary, false) } +} + /// [`render`], reporting progress per smart filter to `ctx` and stopping between filters once it /// is cancelled. Gives the same pixels as [`apply_smart_filters`] on the placed source, but /// starts from the deepest stage of the stack already rendered (see [`stack_cache`]). pub(super) fn render_in(doc: &Document, sm: &SmartObject, ctx: &JobCtx) -> Result> { + render_in_with_source(doc, sm, ctx, None) +} + +fn render_in_with_source(doc: &Document, sm: &SmartObject, ctx: &JobCtx, known: Option<(String, Arc>, bool)>) -> Result> { // Stored filters can come from a file or another layer. Check before looking up cached // stages too: a trusted UI render may have populated this process-wide cache earlier. for filter in sm.smart_filters.iter().filter(|f| sm.filters_enabled && f.visible) { crate::jobs::authorize_render_command(&filter.command, &filter.params)?; } - let Some((name, bytes)) = source_bytes(&doc.metadata, &sm.source) else { return Ok(None) }; - let bytes = display_source(sm, &bytes); - let (fmt, canvas) = (doc.pixel_format(), doc.bounds()); - let mut placed_key = stack_cache::placed_key(&bytes, fmt, sm, canvas); - if photocraft_io::is_svg_input(&name, &bytes) { - let mut h = blake3::Hasher::new(); - h.update(&placed_key); - if sm.stack_mode.is_some() { - // Old placed/filter stages may have been computed from omitted SVG data. - h.update(b"stack-svg-complete-v1:"); + let (name, original, kind) = match known { + Some((name, bytes, kind)) => (name, bytes, Some(kind)), + None => { + let Some((name, bytes)) = source_bytes(&doc.metadata, &sm.source) else { return Ok(None) }; + (name, bytes, None) } - h.update(&crate::color_cmds::document_profile(doc).to_bytes()); - placed_key = *h.finalize().as_bytes(); - } + }; + let bytes = display_source(sm, &original); + let canvas = doc.bounds(); + let filters: Vec<&SmartFilter> = sm.smart_filters.iter().filter(|filter| sm.filters_enabled && filter.visible).collect(); + // A changed native preview is a distinct source and cannot reuse the original's classification. + let kind = if Arc::ptr_eq(&bytes, &original) { kind } else { None }; + let (CachedStages { placed_key, keys, hit }, is_svg) = select_stage_domain(doc, sm, &name, &bytes, &filters, kind); + let cached_placement = hit.as_ref().filter(|(done, _)| *done == 0).map(|(_, stage)| stage.clone()); let placed = || -> Result { + if let Some(stage) = &cached_placement { + return Ok(stage.clone()); + } if let Some(stage) = stack_cache::get(&placed_key) { return Ok(stage); } - let surface = place(&name, &bytes, doc, sm)?; + let surface = place_with_svg(&name, &bytes, doc, sm, is_svg, &mut |bytes, scale| svg_source_image_in(bytes, doc, scale))?; // Edge pixels repeat at the canvas ∪ placed-content edge, as for layer filters. let stage = Stage { extent: canvas.union(&surface.content_bounds()), surface }; stack_cache::put(placed_key, &stage); Ok(stage) }; - let filters: Vec<&SmartFilter> = sm.smart_filters.iter().filter(|f| sm.filters_enabled && f.visible).collect(); if filters.is_empty() { return Ok(Some(placed()?.surface)); } - let keys: Vec = filters - .iter() - .scan(placed_key, |key, f| { - *key = stack_cache::filter_key(key, f, sm.filter_mask.as_ref()); - Some(*key) - }) - .collect(); - let deepest = keys.iter().enumerate().rev().find_map(|(i, key)| stack_cache::get(key).map(|stage| (i + 1, stage))); - let (done, mut cur) = match deepest { + let (done, mut cur) = match hit { Some(hit) => hit, None => (0, placed()?), }; @@ -599,3 +699,7 @@ pub(super) fn refresh_or_fail_in(doc: &mut Document, id: LayerId, ctx: &JobCtx) } Err(other("the smart object's contents are unavailable (missing linked file?), so it can't be re-rendered")) } + +#[cfg(test)] +#[path = "tests/source_work.rs"] +mod source_work_tests; diff --git a/crates/engine/src/cmd/smart_cmds/source.rs b/crates/engine/src/cmd/smart_cmds/source.rs index 505be3e0aa..e5bd657097 100644 --- a/crates/engine/src/cmd/smart_cmds/source.rs +++ b/crates/engine/src/cmd/smart_cmds/source.rs @@ -353,12 +353,23 @@ pub(crate) fn vector_scale(sm: &SmartObject) -> f64 { /// The composited source image of `bytes` in pixel format `fmt` (decoded once, then cached). pub fn source_image(file_name: &str, bytes: &[u8], fmt: PixelFormat) -> Result { + source_image_inner(file_name, bytes, fmt, None) +} + +pub(super) fn source_image_classified(file_name: &str, bytes: &[u8], fmt: PixelFormat, svg: bool) -> Result { + source_image_inner(file_name, bytes, fmt, Some(svg)) +} + +fn source_image_inner(file_name: &str, bytes: &[u8], fmt: PixelFormat, svg: Option) -> Result { let key = cache_key(bytes, fmt); if let Some(img) = cache_get(&key) { return Ok(img); } crate::memory_gate::ensure(&format!("render the smart object \u{201c}{file_name}\u{201d}"), crate::memory_gate::smart_render_need(bytes))?; - let doc = decode_source(file_name, bytes)?; + let doc = match svg { + Some(svg) => super::decode_source_classified(file_name, bytes, svg)?, + None => decode_source(file_name, bytes)?, + }; let img = SourceImage { surface: Arc::new(flattened_source(&doc, fmt)?), bounds: doc.bounds() }; cache_put(key, img.clone()); Ok(img) diff --git a/crates/engine/src/cmd/smart_cmds/tests/source_work.rs b/crates/engine/src/cmd/smart_cmds/tests/source_work.rs new file mode 100644 index 0000000000..0fdaeb736c --- /dev/null +++ b/crates/engine/src/cmd/smart_cmds/tests/source_work.rs @@ -0,0 +1,205 @@ +use super::*; +use photocraft_color::{ColorMode, SampleType}; +use photocraft_doc::StackMode; +use photocraft_geom::{ + Size, + warp::{BezierMesh, Warp}, +}; +use std::io::Write; + +fn drawing(label: &str, omitted: bool) -> Vec { + let image = if omitted { r#""# } else { "" }; + format!(r#"{image}"#).into_bytes() +} + +fn gzip(bytes: &[u8]) -> Vec { + let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + encoder.write_all(bytes).unwrap(); + encoder.finish().unwrap() +} + +fn document() -> Document { + Document::new("Source work", Size::new(8, 8), ColorMode::Rgb, SampleType::U8) +} +fn object(name: &str, bytes: Arc>) -> SmartObject { + SmartObject::new(SmartSource::Embedded { file_name: name.into(), bytes }, Affine::IDENTITY, None) +} +fn probes() -> usize { + SVG_CLASSIFICATIONS.with(std::cell::Cell::get) +} +fn reset_probes() { + SVG_CLASSIFICATIONS.with(|value| value.set(0)); +} + +#[test] +fn compressed_stack_hits_skip_format_probe_and_preserve_misnamed_sources() { + for name in ["cached.svgz", "cached.gz", "no-extension", "wrong.dat"] { + let encoded = gzip(&drawing(name, false)); + reset_probes(); + let first = stack_image(name, &encoded, PixelFormat::RGBA32F, StackMode::Mean).unwrap(); + assert_eq!(probes(), 1, "the cold Stack operation classifies once"); + let second = stack_image(name, &encoded, PixelFormat::RGBA32F, StackMode::Mean).unwrap(); + assert!(Arc::ptr_eq(&first.surface, &second.surface)); + assert_eq!(probes(), 1, "a strict Stack cache hit never inflates merely to choose its cache key"); + } +} + +#[test] +fn compressed_render_and_bounds_classify_once_per_operation() { + for kind in ["direct", "warp", "stack"] { + let doc = document(); + let bytes = Arc::new(gzip(&drawing(kind, false))); + let mut sm = object("misnamed.gz", bytes); + if kind == "warp" { + let bounds = [0., 0., 8., 8.]; + sm.warp = Some(Warp::custom(BezierMesh::identity(bounds, 1, 1), bounds)); + } else if kind == "stack" { + sm.stack_mode = Some(StackMode::Mean); + } + reset_probes(); + let rendered = render_in(&doc, &sm, &JobCtx::new()).unwrap().unwrap(); + assert_eq!(rendered.rgba(3, 3), [1., 0., 0., 1.]); + assert_eq!(probes(), 1, "{kind}: classification is shared with placement and decoding"); + reset_probes(); + assert_eq!(render_in(&doc, &sm, &JobCtx::new()).unwrap().unwrap(), rendered); + assert_eq!(probes(), 0, "{kind}: the typed warm stage avoids compressed recognition entirely"); + reset_probes(); + assert_eq!(source_box(&doc, &sm), Some([0., 0., 8., 8.])); + assert_eq!(probes(), usize::from(kind == "stack"), "bounds reuse typed placement kind; a new Stack pixel format classifies once"); + reset_probes(); + assert_eq!(source_box(&doc, &sm), Some([0., 0., 8., 8.])); + assert_eq!(probes(), 0, "warm bounds reuse strict cache domains without recognizing compressed input again"); + } +} + +#[test] +fn warning_memo_hits_skip_compressed_classification_and_keep_warnings_private() { + let doc = document(); + let bytes = Arc::new(gzip(&drawing("warning memo probe", true))); + let sm = object("warning-without-extension", bytes); + let mut memo = WarningRenderSources::new(&doc); + reset_probes(); + WARNING_SOURCE_DECODES.with(|value| value.set(0)); + let (first, warnings) = render_with_warnings_using(&sm, &mut memo).unwrap(); + assert_eq!(warnings.len(), 1); + let (second, repeated) = render_with_warnings_using(&sm, &mut memo).unwrap(); + assert_eq!(first, second); + assert_eq!(warnings, repeated); + assert_eq!(probes(), 1); + assert_eq!(WARNING_SOURCE_DECODES.with(std::cell::Cell::get), 1); + assert!(render(&doc, &sm).is_err(), "warning-aware source pixels never populate strict caches"); +} + +#[test] +fn memo_prices_owned_output_and_does_not_retain_encoded_capacity() { + let doc = document(); + let data = drawing("reserved encoded capacity", false); + let mut reserved = Vec::with_capacity(1 << 20); + reserved.extend_from_slice(&data); + let bytes = Arc::new(reserved); + let weak = Arc::downgrade(&bytes); + let sm = object("reserved.svg", bytes); + let tile = photocraft_raster::tile_storage_bytes(doc.bounds(), &doc.pixel_format()) as usize; + let mut memo = WarningRenderSources::with_limits(&doc, tile + 4096, 32); + WARNING_SOURCE_DECODES.with(|value| value.set(0)); + let first = render_with_warnings_using(&sm, &mut memo).unwrap(); + assert!(first.1.is_empty()); + assert_eq!(memo.entries.len(), 1, "encoded spare capacity is borrowed, not retained memo storage"); + assert!(memo.bytes <= tile + 4096); + assert_eq!(render_with_warnings_using(&sm, &mut memo).unwrap(), first); + assert_eq!(WARNING_SOURCE_DECODES.with(std::cell::Cell::get), 1); + assert_eq!(weak.strong_count(), 1, "only the caller owns its source allocation"); + drop(sm); + assert!(weak.upgrade().is_none(), "the memo must not pin an encoded body after its owner drops it"); +} + +#[test] +fn empty_memo_with_stale_accounting_recovers_without_panicking() { + let doc = document(); + let data = Arc::new(drawing("empty accounting", false)); + let mut memo = WarningRenderSources::new(&doc); + memo.bytes = memo.budget; + let (image, warnings) = memo.image(&data, 1., *blake3::hash(b"empty.svg").as_bytes()).unwrap(); + assert!(warnings.is_empty()); + assert_eq!(image.surface.rgba(3, 3), [1., 0., 0., 1.]); + assert_eq!(memo.entries.len(), 1); + assert!(memo.bytes <= memo.budget); +} + +#[test] +fn central_recognition_keeps_real_raster_bytes_even_with_svg_name() { + let image = photocraft_codecs::Image::from_u8(1, 1, photocraft_codecs::ChannelLayout::Rgb, vec![0, 255, 0]).unwrap(); + let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + assert!(!svg_input("renamed.svg", &png)); + let doc = document(); + let sm = object("renamed.svg", Arc::new(png)); + reset_probes(); + let rendered = render_in(&doc, &sm, &JobCtx::new()).unwrap().unwrap(); + assert_eq!(rendered.rgba(0, 0), [0., 1., 0., 1.]); + assert_eq!(probes(), 1); + reset_probes(); + let (reported, warnings) = render_with_warnings_using(&sm, &mut WarningRenderSources::new(&doc)).unwrap(); + assert_eq!(reported.unwrap(), rendered); + assert!(warnings.is_empty()); + assert_eq!(probes(), 1, "warning-aware non-SVG fallback reuses the same authorized snapshot and classification"); +} + +#[test] +fn warm_typed_stages_keep_profile_name_and_authority_boundaries() { + let mut doc = document(); + let data = String::from_utf8(drawing("typed domains", false)).unwrap().replace("fill=\"red\"", "fill=\"#808080\""); + let bytes = Arc::new(gzip(data.as_bytes())); + let mut sm = object("typed-domains.svgz", bytes.clone()); + sm.smart_filters.push(SmartFilter { + command: "image.adjustments.invert".into(), + params: serde_json::json!({}), + blend: BlendMode::Normal, + opacity: 1., + visible: true, + }); + let first = render_in(&doc, &sm, &JobCtx::new()).unwrap().unwrap(); + reset_probes(); + assert_eq!(render_in(&doc, &sm, &JobCtx::new()).unwrap().unwrap(), first); + assert_eq!(probes(), 0, "filtered warm stages do not sniff compressed text"); + fn deny_invert(command: &str, _: &Value) -> Result<()> { + if command == "image.adjustments.invert" { Err(other("test denies cached invert")) } else { Ok(()) } + } + { + let _scope = crate::jobs::render_authorization_scope(Some(deny_invert)); + assert!(render_in(&doc, &sm, &JobCtx::new()).unwrap_err().to_string().contains("test denies cached invert")); + assert_eq!(probes(), 0, "authority is checked before either cache domain"); + } + doc.icc_profile = Some(craft_cms::Builtin::LinearSrgb.profile().to_bytes()); + reset_probes(); + let linear = render_in(&doc, &sm, &JobCtx::new()).unwrap().unwrap(); + assert_ne!(linear.pixel(3, 3), first.pixel(3, 3), "a profile change cannot reuse sRGB stage pixels"); + assert_eq!(probes(), 1); + reset_probes(); + assert_eq!(render_in(&doc, &sm, &JobCtx::new()).unwrap().unwrap(), linear); + assert_eq!(probes(), 0); + let mut renamed = sm.clone(); + renamed.source = SmartSource::Embedded { file_name: "typed-domains-without-extension".into(), bytes }; + reset_probes(); + assert_eq!(render_in(&doc, &renamed, &JobCtx::new()).unwrap().unwrap(), linear); + assert_eq!(probes(), 1, "filename-dependent recognition uses a distinct typed domain"); +} + +#[test] +fn warning_memo_retains_filename_recognition_for_the_same_encoded_arc() { + let doc = document(); + let bytes = Arc::new(gzip(&drawing("same allocation different format names", false))); + let svg = object("shared.svgz", bytes.clone()); + let renamed = object("shared.af", bytes.clone()); + assert!(!svg_input("shared.af", &bytes)); + let cold = render_with_warnings_using(&renamed, &mut WarningRenderSources::new(&doc)).unwrap_err(); + let mut memo = WarningRenderSources::new(&doc); + let (rendered, warnings) = render_with_warnings_using(&svg, &mut memo).unwrap(); + assert_eq!(rendered.unwrap().rgba(3, 3), [1., 0., 0., 1.]); + assert!(warnings.is_empty()); + assert_eq!(memo.entries.len(), 1); + reset_probes(); + let warm = render_with_warnings_using(&renamed, &mut memo).unwrap_err(); + assert_eq!(warm.to_string(), cold.to_string(), "a warm SVG instance cannot override central filename precedence"); + assert_eq!(probes(), 1, "a different recognition name must be checked even for the exact same source Arc"); + assert_eq!(memo.entries.len(), 1, "a failed alternate route does not enter the SVG memo"); +} diff --git a/crates/engine/src/cmd/smart_svg_cmds/source_cache_tests.rs b/crates/engine/src/cmd/smart_svg_cmds/source_cache_tests.rs index 43f06e4849..99428118e9 100644 --- a/crates/engine/src/cmd/smart_svg_cmds/source_cache_tests.rs +++ b/crates/engine/src/cmd/smart_svg_cmds/source_cache_tests.rs @@ -182,7 +182,12 @@ fn local_svg_source_memo_evicts_and_oversize_entries_render_without_retention() reset(); let expected = draw(&mut sources, &encoded); assert_eq!(draw(&mut sources, &encoded), expected); - assert_eq!(count(), 2, "retained encoded bytes count even for a tiny output"); + assert_eq!(count(), 1, "the immutable document owns encoded bytes; only rendered output belongs to the memo budget"); + let mut output_too_large = WarningRenderSources::with_limits(&doc, tile - 1, 32); + reset(); + let expected = draw(&mut output_too_large, &first); + assert_eq!(draw(&mut output_too_large, &first), expected); + assert_eq!(count(), 2, "oversize rendered output remains an uncached success"); let mut disabled = WarningRenderSources::with_limits(&doc, 0, 0); assert_eq!(draw(&mut disabled, &first), draw(&mut WarningRenderSources::new(&doc), &first)); } diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index a5567d52ce..5a3e221afb 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -54,12 +54,6 @@ craft-tiff = { workspace = true } craft-crs = { workspace = true } craft-xml = { workspace = true } thiserror = { workspace = true } -# Match the SVG renderer decoder backends when validating optional images. -zune-core = { workspace = true } -zune-jpeg = { workspace = true } -gif = { workspace = true } -image-webp = { workspace = true } -data-url = { workspace = true } ttf-parser = "0.25.1" serde_json = { workspace = true } blake3 = { version = "1.8", default-features = false, features = ["pure"] } @@ -75,6 +69,9 @@ craft-pdf = { workspace = true } kurbo = { version = "0.13", optional = true } [dev-dependencies] +# Check selected SVG validator/renderer edges in this consumer lockfile. +# Already resolved; MIT OR Apache-2.0. +toml = "=1.1.6" lopdf = { version = "0.38", default-features = false } miniz_oxide = "0.9" crc32fast = "1.5" diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index d61d378d70..d291de8c75 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -24,9 +24,10 @@ use photocraft_raster::Surface; use crate::{ImportResult, IoError}; -mod data_href_validation; -mod image_integrity; -mod raster_validation; +#[cfg(all(test, not(target_arch = "wasm32")))] +mod decoder_edges; +#[cfg(test)] +mod xml_reuse_tests; /// Hard caps on the memory resvg needs to draw a subtree, checked before it draws: craft-svg's /// `tree::draw`, within this crate's peak pixel budget. @@ -377,37 +378,10 @@ fn parse_at_depth(depth: usize, isolated: bool, parse: impl FnOnce(bool } } -/// Supplies bounded parsing options to direct resolver tests without changing their existing interface. -#[cfg(test)] -fn options(fontdb: Arc, depth_left: usize) -> usvg::Options<'static> { - options_with_isolation( - fontdb, - depth_left, - false, - Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(depth_left, MAX_RASTER_PIXELS))), - Arc::new(Mutex::new(image_integrity::Integrity::new(MAX_RASTER_PIXELS))), - ) -} - -/// Parse options for an untrusted drawing. `` resolves only `data:` URLs: a file path -/// or relative href is never read, so opening an SVG cannot pull local files (`/etc/...`, -/// `~/.ssh/...`) into the document. Embedded SVG images get no `` resolution at all -/// (`usvg` already blanks it for sub-SVGs). An embedded SVG may nest `depth_left` levels: it is -/// parsed on top of the drawing's own recursion, so the two depths share [`MAX_XML_DEPTH`]. -fn options_with_isolation( - fontdb: Arc, - _depth_left: usize, - _isolated: bool, - image_resolver: Arc, - integrity: Arc>, -) -> usvg::Options<'static> { - usvg::Options { - resources_dir: None, - image_href_resolver: image_integrity::wrap(image_resolver.resolver(), integrity), - fontdb, - font_resolver: font_resolver(), - ..usvg::Options::default() - } +/// Font and resource options for untrusted drawings. The shared validated context +/// installs its own bounded data-only image resolver during conversion. +fn parse_options(fontdb: Arc) -> usvg::Options<'static> { + usvg::Options { resources_dir: None, fontdb, font_resolver: font_resolver(), ..usvg::Options::default() } } /// A parsed drawing. @@ -437,10 +411,14 @@ fn tree_limits(depth: usize, raster_pixels: u64) -> craft_svg::tree::Limits { // PhotoCraft's stack guard counts open tags; the shared SVG preflight counts every // element, including a self-closing leaf. Allow that leaf at the same guarded depth. depth: depth.saturating_add(1), - // The shared default is intentionally conservative for general consumers. PhotoCraft - // already guards XML nesting and reference expansion against its 512-level parser - // budget, so pass that same explicit limit through instead of inheriting 256. - tree_depth: depth.saturating_add(1), + // Expanded references consume parser stack even when the source XML is + // shallow. Native parsing owns the larger worker; WASM must keep both + // reference expansion and lexical nesting within its inline allowance. + tree_depth: { + #[cfg(target_arch = "wasm32")] + let depth = depth.min(INLINE_XML_DEPTH); + depth.saturating_add(1) + }, embedded_bytes: usize::try_from(MAX_BOUNDED_SVG_BYTES).unwrap_or(usize::MAX), embedded_depth: MAX_EMBEDDED_SVG_DEPTH, embedded_raster_pixels: raster_pixels.min(MAX_RASTER_PIXELS), @@ -462,25 +440,20 @@ fn parse_with_image_limit(bytes: &[u8], fonts: fn() -> Arc, - resolver: Arc, - integrity: Arc>, + resolver: Arc, } /// Record the first budget or decoding failure seen while usvg resolves images. Resolver @@ -562,25 +534,28 @@ fn parse_image_bounded_with( return Err(IoError::Svg(format!("elements are nested more than {xml_left} levels deep"))); } let shared_depth = MAX_XML_DEPTH.saturating_sub(xml_left).saturating_add(nesting); - budget.lock().unwrap_or_else(PoisonError::into_inner).resolver.set_document_depth(nesting); - parse_at_depth(shared_depth, isolated, |isolated| { + parse_at_depth(shared_depth, isolated, |_isolated| { let has_text = xml.windows(4).any(|w| w == b"text"); let fontdb = if has_text { fonts() } else { Arc::new(usvg::fontdb::Database::new()) }; if has_text && fontdb.faces().next().is_none() { budget.lock().unwrap_or_else(PoisonError::into_inner).fontless_text = true; } let resolver = Arc::clone(&budget.lock().unwrap_or_else(PoisonError::into_inner).resolver); - let integrity = Arc::clone(&budget.lock().unwrap_or_else(PoisonError::into_inner).integrity); let text = std::str::from_utf8(&xml).map_err(|_| IoError::Svg("the SVG is not valid UTF-8".into()))?; - let limits = tree_limits(xml_left, MAX_RASTER_PIXELS); - let opt = options_with_isolation(fontdb, xml_left, isolated, resolver, integrity); + let limits = resolver.limits(); let tree = guarded_parse(|| { - data_href_validation::with_repaired_xml(text, &limits, |xml| { - usvg::Tree::from_xmltree(xml, &opt).map_err(|error| svg_parse_error(craft_svg::tree::Error::Parse(error.to_string()))) - }) + // Private callers may reserve less stack than the context's outer + // policy. Check expanded references too; lexical depth alone misses + // a shallow chain of elements. Public imports use the full + // allowance and keep the single checked-DOM conversion path. + if xml_left < MAX_XML_DEPTH { + craft_svg::tree::preflight(text, &tree_limits(xml_left, limits.embedded_raster_pixels)).map_err(svg_parse_error)?; + } + let checked = craft_svg::tree::preflight(text, &limits).map_err(svg_parse_error)?; + resolver.parse_preflight(checked, parse_options(fontdb)).map_err(svg_parse_error) })??; let mut counter = budget.lock().unwrap_or_else(PoisonError::into_inner); - let usage = counter.integrity.lock().unwrap_or_else(PoisonError::into_inner).usage(counter.resolver.usage())?; + let usage = counter.resolver.usage(); counter.pixels = counter.pixels.saturating_sub(usage.raster_pixels); counter.xml_bytes = counter.xml_bytes.saturating_sub(u64::try_from(usage.embedded_svg_bytes).unwrap_or(u64::MAX)); counter.svg_images = usage.embedded_svg_count as u64; @@ -716,18 +691,13 @@ fn parse_bounded_work_with(bytes: &[u8], max_pixels: u64, strict: bool, fonts: f fontless_text: false, strict, error: None, - resolver: Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(MAX_XML_DEPTH, max_pixels.min(MAX_RASTER_PIXELS)))), - integrity: Arc::new(Mutex::new(image_integrity::Integrity::new(max_pixels))), + resolver: Arc::new(craft_svg::tree::ValidatedImageResolver::new(tree_limits(MAX_XML_DEPTH, max_pixels.min(MAX_RASTER_PIXELS)))), })); let tree = parse_image_bounded_with(bytes, budget.clone(), MAX_XML_DEPTH, fonts, false)?; 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, - image_usage: counter.integrity.lock().unwrap_or_else(PoisonError::into_inner).usage(counter.resolver.usage())?, - }, + parsed: Parsed { tree, fontless_text: counter.fontless_text, image_usage: counter.resolver.usage() }, svg_images: counter.svg_images, svg_chain: counter.svg_chain, decoded, diff --git a/crates/io/src/svg/data_href_validation.rs b/crates/io/src/svg/data_href_validation.rs deleted file mode 100644 index 9fbb12bfb4..0000000000 --- a/crates/io/src/svg/data_href_validation.rs +++ /dev/null @@ -1,415 +0,0 @@ -//! Repair data-URL failures that usvg drops before invoking its image resolver. -//! This changes only attribute values. Resolver callbacks still decide whether an -//! image is used, so hidden/unused resources do not acquire omission warnings. - -use std::borrow::Cow; -use std::ops::Range; - -use crate::IoError; -use craft_svg::tree::Limits; - -#[cfg(test)] -const SVG_NS: &str = "http://www.w3.org/2000/svg"; -const XLINK_NS: &str = "http://www.w3.org/1999/xlink"; -const INVALID_IMAGE: &str = "data:image/png,%00"; -const IGNORED_DATA: &str = "data:application/octet-stream,%00"; - -struct Patch { - range: Range, - replacement: &'static str, -} - -fn invalid(message: &str) -> IoError { - IoError::Svg(message.into()) -} - -/// Validate the original decoded XML before patching it. The caller must charge -/// its original bytes/work before any shorter result replaces an embedded source. -/// This does not rewrite an XML encoding declaration for a UTF-8 byte transport. -pub(super) fn repair<'a>(text: &'a str, limits: &Limits) -> Result, IoError> { - if !text.contains("href") && !text.starts_with("( - text: &str, - limits: &Limits, - convert: impl FnOnce(&super::usvg::roxmltree::Document<'_>) -> Result, -) -> Result { - let xml = checked_xml(text, limits)?; - match repair_xml(text, limits, &xml)? { - Cow::Borrowed(_) => convert(&xml), - Cow::Owned(repaired) => { - drop(xml); - let xml = checked_xml(&repaired, limits)?; - convert(&xml) - } - } -} - -// These are the same preflight and expanded-reference guards used by the -// shared tree parser, before its public from_xmltree conversion. Do not replace -// this with an unbounded XML parse or feed an unchecked DOM to usvg. -fn checked_xml<'a>(text: &'a str, limits: &Limits) -> Result, IoError> { - #[cfg(test)] - XML_PARSES.with(|count| count.set(count.get().saturating_add(1))); - let xml_limits = craft_svg::preflight::Limits { - bytes: limits.bytes, - depth: limits.depth, - entity_bytes: limits.entity_bytes, - refuse_entity_markup: limits.refuse_entity_markup, - attributes: limits.attributes, - attribute_work: limits.attribute_work, - xml_nodes: limits.xml_nodes, - }; - let xml = craft_svg::preflight::parse_text(text, &xml_limits).map_err(|error| match error { - craft_svg::preflight::Error::TooDeep(_) => invalid("layers are nested too deeply"), - error => IoError::Svg(error.to_string()), - })?; - if craft_svg::tree::height(&xml, limits.tree_depth).map_err(super::svg_parse_error)?.is_none() { - return Err(invalid("layers are nested too deeply")); - } - Ok(xml) -} - -fn repair_xml<'a>(text: &'a str, limits: &Limits, xml: &super::usvg::roxmltree::Document<'a>) -> Result, IoError> { - if !text.contains("href") { - return Ok(Cow::Borrowed(text)); - } - // The expanded attribute values fit source + entity work. Streaming URL - // validation reads them and emits at most that much decoded data, never a Vec. - let mut work = - text.len().checked_add(limits.entity_bytes).and_then(|n| n.checked_mul(2)).ok_or_else(|| invalid("SVG data-URL validation work exceeds its limit"))?; - let max_patches = (limits.bytes / std::mem::size_of::()).min(usize::try_from(limits.xml_nodes).unwrap_or(usize::MAX)); - let mut patches: Vec = Vec::new(); - for node in xml.descendants().filter(|node| node.is_element()) { - if !matches!(node.tag_name().name(), "image" | "feImage") { - continue; - } - // Shared preflight inspects local image names in every namespace and - // checks XLink before plain href. Normalize both representations, even - // when one is inert or unselected. Only actual resolver callbacks count - // omissions, so this does not turn hidden/unused resources into warnings. - for href in node.attributes().filter(|a| a.name() == "href" && matches!(a.namespace(), None | Some(XLINK_NS))) { - let Some(replacement) = malformed_data_url_replacement(href.value(), &mut work)? else { continue }; - let range = verified_value_range(text, node.range(), href.range(), href.range_qname(), href.range_value(), href.name())?; - if patches.len() == patches.capacity() { - if patches.len() >= max_patches { - return Err(invalid("SVG data-URL repair metadata exceeds its limit")); - } - let capacity = patches.capacity().max(8).saturating_mul(2).min(max_patches); - patches.try_reserve_exact(capacity.saturating_sub(patches.len())).map_err(|_| invalid("could not allocate bounded SVG data-URL repairs"))?; - } - patches.push(Patch { range, replacement }); - } - } - if patches.is_empty() { - return Ok(Cow::Borrowed(text)); - } - patches.sort_unstable_by_key(|patch| (patch.range.start, patch.range.end)); - patches.dedup_by_key(|patch| (patch.range.start, patch.range.end)); - let mut end = 0; - let mut length = text.len(); - for patch in &patches { - let range = &patch.range; - if range.start < end { - return Err(invalid("SVG data-URL source ranges overlap")); - } - end = range.end; - length = length - .checked_sub(range.len()) - .and_then(|n| n.checked_add(patch.replacement.len())) - .ok_or_else(|| invalid("SVG data-URL repair size overflows"))?; - } - if length > limits.bytes { - return Err(invalid("repaired SVG exceeds the text byte limit")); - } - let mut result = String::new(); - result.try_reserve_exact(length).map_err(|_| invalid("could not allocate bounded repaired SVG text"))?; - let mut cursor = 0; - for patch in patches { - result.push_str(text.get(cursor..patch.range.start).ok_or_else(|| invalid("invalid SVG data-URL source range"))?); - result.push_str(patch.replacement); - cursor = patch.range.end; - } - result.push_str(text.get(cursor..).ok_or_else(|| invalid("invalid SVG data-URL source range"))?); - Ok(Cow::Owned(result)) -} - -// The pinned MIME parser searches all earlier parameters for each new name. -// Cap even quoted semicolons before invoking it: source-byte work is already -// charged, so at most this constant times the bounded XML work reaches MIME -// parsing. Bodies can remain large without acquiring MIME parameter records. -const MAX_MIME_SEPARATORS: usize = 64; - -fn mime_header_admitted(value: &str) -> bool { - let trimmed = value.trim_start_matches(|ch| ch <= ' '); - let mut bytes = trimmed.bytes(); - for expected in b"data:" { - let Some(actual) = bytes.by_ref().find(|&byte| !matches!(byte, b'\t' | b'\n' | b'\r')) else { return true }; - if !actual.eq_ignore_ascii_case(expected) { - return true; // Not a data URL: preserve external/fragment handling. - } - } - let mut separators = 0; - for byte in bytes { - if matches!(byte, b',' | b'#') { - break; - } - if byte == b';' { - separators += 1; - if separators > MAX_MIME_SEPARATORS { - return false; - } - } - } - true -} - -fn malformed_data_url_replacement(value: &str, work: &mut usize) -> Result, IoError> { - malformed_data_url_replacement_with(value, work, data_url::DataUrl::process) -} - -fn malformed_data_url_replacement_with<'a>( - value: &'a str, - work: &mut usize, - parse: impl FnOnce(&'a str) -> Result, data_url::DataUrlError>, -) -> Result, IoError> { - *work = work.checked_sub(value.len()).ok_or_else(|| invalid("SVG data-URL validation work exceeds its limit"))?; - if !mime_header_admitted(value) { - // Strip parameters before recovering MIME disposition; no original - // parameter list reaches either our parser or shared whole-DOM preflight. - return missing_comma_replacement(value, work).map(Some); - } - let url = match parse(value) { - Ok(url) => url, - Err(data_url::DataUrlError::NoComma) => return missing_comma_replacement(value, work).map(Some), - Err(data_url::DataUrlError::NotADataUrl) => return Ok(None), - }; - let mut exhausted = false; - let decoded = url.decode(|bytes| { - if let Some(left) = work.checked_sub(bytes.len()) { - *work = left; - Ok(()) - } else { - exhausted = true; - Err(()) - } - }); - if exhausted { - return Err(invalid("SVG data-URL validation work exceeds its limit")); - } - Ok(decoded.is_err().then(|| replacement_for_mime(url.mime_type()))) -} - -/// Preflight must see a valid URL, while the resolver must keep its original -/// disposition. Non-image MIME types are ignored even when their body is bad. -fn replacement_for_mime(mime: &data_url::mime::Mime) -> &'static str { - if mime.type_ == "image" || mime.matches("text", "plain") { INVALID_IMAGE } else { IGNORED_DATA } -} - -fn missing_comma_replacement(value: &str, work: &mut usize) -> Result<&'static str, IoError> { - // NoComma does not expose its MIME type. Ask the same parser about a header - // with an empty body rather than guessing MIME defaults, case or parameters. - // Match its URL C0 trimming; fragments and MIME parameters cannot affect - // the image/text-plain essence. Do not allocate parameter bookkeeping for a - // hostile missing-comma header just to recover that disposition. - let normalized = value.trim_matches(|ch| ch <= ' '); - let header = normalized.split_once('#').map_or(normalized, |(header, _)| header); - let essence = header.split_once(';').map_or(header, |(essence, _)| essence); - *work = work.checked_sub(essence.len()).ok_or_else(|| invalid("SVG data-URL validation work exceeds its limit"))?; - let length = essence.len().checked_add(1).ok_or_else(|| invalid("SVG data-URL repair size overflows"))?; - let mut candidate = String::new(); - candidate.try_reserve_exact(length).map_err(|_| invalid("could not allocate bounded SVG data-URL header"))?; - candidate.push_str(essence); - candidate.push(','); - // This candidate has no MIME parameters, including for oversized original - // lists. Its byte scan/allocation is charged above before the linear parse. - if !mime_header_admitted(&candidate) { - return Err(invalid("SVG data-URL MIME header exceeds its limit")); - } - let url = data_url::DataUrl::process(&candidate).map_err(|_| invalid("invalid SVG data-URL header framing"))?; - Ok(replacement_for_mime(url.mime_type())) -} - -/// roxmltree bounds QName and equals-spacing bookkeeping internally. Refuse a -/// projection that does not identify the attribute's actual quoted value, rather -/// than editing a truncated position or a DTD entity declaration by mistake. -fn verified_value_range( - text: &str, - owner: Range, - attribute: Range, - qname: Range, - value: Range, - local_name: &str, -) -> Result, IoError> { - let error = || invalid("SVG data-URL attribute source positions cannot be represented safely"); - if attribute.start < owner.start || attribute.end > owner.end || qname.start != attribute.start || qname.end > value.start { - return Err(error()); - } - let open = value.start.checked_sub(1).ok_or_else(error)?; - if value.end.checked_add(1) != Some(attribute.end) || open < qname.end { - return Err(error()); - } - let name = text.get(qname.clone()).ok_or_else(error)?; - if name.rsplit(':').next() != Some(local_name) { - return Err(error()); - } - let equals = text.get(qname.end..open).ok_or_else(error)?; - if equals.trim_matches([' ', '\t', '\r', '\n']) != "=" { - return Err(error()); - } - let quote = text.get(open..value.start).ok_or_else(error)?; - if !matches!(quote, "'" | "\"") || text.get(value.end..attribute.end) != Some(quote) || text.get(value.clone()).is_none() { - return Err(error()); - } - Ok(value) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn limits() -> Limits { - Limits { bytes: 1 << 20, depth: 32, tree_depth: 32, entity_bytes: 65_536, ..Default::default() } - } - - #[test] - fn malformed_image_urls_are_repaired_in_both_svg_namespaces_and_filter_resources() { - for tag in ["image", "feImage"] { - for text in [ - format!("<{tag} href='data:image/png;base64,A'/>"), - format!("<{tag} href='data:image/png;base64,A'/>"), - format!(""), - ] { - let repaired = repair(&text, &limits()).unwrap(); - assert!(matches!(repaired, Cow::Owned(_))); - assert_eq!(repaired.matches(INVALID_IMAGE).count(), 1); - } - } - } - - #[test] - fn unselected_href_and_foreign_local_image_names_are_normalized_for_shared_preflight() { - for attrs in ["href='data:image/png,%00' x:href='data:image/png;base64,A'", "x:href='data:image/png;base64,A' href='data:image/png,%00'"] { - let text = format!(""); - let repaired = repair(&text, &limits()).unwrap(); - assert!(matches!(repaired, Cow::Owned(_))); - assert_eq!(repaired.matches(INVALID_IMAGE).count(), 2); - assert!(!repaired.contains("base64,A")); - } - let text = format!( - "" - ); - let repaired = repair(&text, &limits()).unwrap(); - assert_eq!(repaired.matches(INVALID_IMAGE).count(), 3); - assert!(repaired.contains("f:href='data:image/png;base64,A'"), "foreign href attributes remain inert and unchanged"); - } - - #[test] - fn both_href_forms_on_hidden_unused_and_foreign_resources_do_not_preflight_as_omissions() { - for tag in ["image", "feImage"] { - let text = format!( - "<{tag} id='unused' href='data:image/png;base64,A' x:href='data:image/png;base64,A'/><{tag} display='none' x:href='data:image/png;base64,A' href='data:image/png;base64,A'/>" - ); - let original = text.clone(); - let repaired = repair(&text, &limits()).unwrap(); - assert_eq!(text, original, "repair never mutates the original source"); - assert_eq!(repaired.matches(INVALID_IMAGE).count(), 6); - let resolver = craft_svg::tree::ImageResolver::new(limits()); - resolver.check_document(&repaired).unwrap(); - let usage = resolver.usage(); - assert_eq!( - (usage.invalid_raster_images, usage.invalid_svg_images), - (0, 0), - "shared whole-document scanning cannot invent omissions before resolution" - ); - assert!(matches!(repair(&repaired, &limits()).unwrap(), Cow::Borrowed(_)), "normalization is idempotent"); - } - } - - #[test] - fn entity_expanded_urls_patch_the_owning_attributes_without_rewriting_the_doctype() { - let text = format!( - "]>" - ); - let repaired = repair(&text, &limits()).unwrap(); - assert!(repaired.contains("")); - assert_eq!(repaired.matches(INVALID_IMAGE).count(), 2); - assert!(!repaired.contains("href='&bad;'")); - assert!(matches!(repair(&repaired, &limits()).unwrap(), Cow::Borrowed(_))); - } - - #[test] - fn valid_data_and_external_urls_are_not_rewritten() { - for value in ["data:image/png;base64,AA==", "data:image/svg+xml,%3Csvg%2F%3E", "file.png", "#local"] { - let text = format!(""); - assert!(matches!(repair(&text, &limits()).unwrap(), Cow::Borrowed(_))); - } - let text = ""; - assert!(repair(text, &limits()).unwrap().contains(INVALID_IMAGE)); - } - - #[test] - fn malformed_non_image_urls_keep_ignored_replacements_even_without_a_comma() { - for value in [ - "data:application/octet-stream;base64,A", - "data:application/octet-stream;base64", - "data:APPLICATION/OCTET-STREAM;BASE64,A", - "data:text/css;base64,A", - "data:audio/ogg;base64,A", - "data:application/octet-stream;base64#fragment,not-the-delimiter", - ] { - let text = format!(""); - let repaired = repair(&text, &limits()).unwrap(); - assert!(repaired.contains(IGNORED_DATA), "{value}: {repaired}"); - assert!(!repaired.contains(INVALID_IMAGE)); - assert!(matches!(repair(&repaired, &limits()).unwrap(), Cow::Borrowed(_))); - let resolver = craft_svg::tree::ImageResolver::new(limits()); - resolver.check_document(&repaired).unwrap(); - assert_eq!(resolver.usage().invalid_raster_images, 0); - } - } - - #[test] - fn image_and_default_plain_mime_failures_remain_disclosed() { - for value in - ["data:IMAGE/PNG;base64,A", "data:image/png;base64", "data:text/plain;base64,A", "data:;base64,A", "data:;base64", "data:not-a-mime;base64"] - { - let text = format!(""); - assert!(repair(&text, &limits()).unwrap().contains(INVALID_IMAGE), "{value}"); - } - let value = "data:application/octet-stream;base64#fragment"; - let mut insufficient = value.len(); - assert!(malformed_data_url_replacement(value, &mut insufficient).is_err(), "the extra MIME-header parse has its own work charge"); - let mut sufficient = value.len() * 2; - assert_eq!(malformed_data_url_replacement(value, &mut sufficient).unwrap(), Some(IGNORED_DATA)); - } - - #[test] - fn unrepresentable_attribute_positions_and_output_growth_fail_safely() { - let text = format!("", " ".repeat(300)); - assert!(matches!(repair(&text, &limits()), Err(IoError::Svg(message)) if message.contains("source positions"))); - let text = ""; - assert!(matches!(repair(text, &Limits { bytes: text.len(), ..limits() }), Err(IoError::Svg(message)) if message.contains("byte limit"))); - } -} - -#[cfg(test)] -#[path = "mime_header_tests.rs"] -mod mime_header_tests; - -#[cfg(test)] -thread_local! { - static XML_PARSES: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -#[cfg(test)] -#[path = "xml_reuse_tests.rs"] -mod xml_reuse_tests; diff --git a/crates/io/src/svg/decoder_edges.rs b/crates/io/src/svg/decoder_edges.rs new file mode 100644 index 0000000000..0a12d81eee --- /dev/null +++ b/crates/io/src/svg/decoder_edges.rs @@ -0,0 +1,103 @@ +//! Verify the SVG validator uses the selected renderer backends in this app graph. +//! Resolve the direct IO edge: other pinned craft-svg versions may coexist. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing)] + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct PackageId { + name: String, + version: String, + source: Option, +} +struct Package { + id: PackageId, + dependencies: Vec, +} +pub(crate) struct LockGraph { + packages: Vec, +} +impl LockGraph { + pub(crate) fn parse(text: &str) -> Self { + let lock: toml::Value = text.parse().unwrap(); + let packages = lock + .get("package") + .unwrap() + .as_array() + .unwrap() + .iter() + .map(|package| { + let string = |key| package.get(key).unwrap().as_str().unwrap().to_owned(); + Package { + id: PackageId { name: string("name"), version: string("version"), source: package.get("source").map(|v| v.as_str().unwrap().to_owned()) }, + dependencies: package + .get("dependencies") + .map(|d| d.as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_owned()).collect()) + .unwrap_or_default(), + } + }) + .collect(); + Self { packages } + } + pub(crate) fn workspace_package(&self, name: &str) -> PackageId { + let found: Vec<_> = self.packages.iter().filter(|p| p.id.name == name && p.id.source.is_none()).collect(); + assert_eq!(found.len(), 1, "one exact workspace package required: {name}"); + found[0].id.clone() + } + pub(crate) fn dependency(&self, from: &PackageId, name: &str) -> PackageId { + let package = self.packages.iter().find(|p| &p.id == from).unwrap(); + let edges: Vec<_> = package.dependencies.iter().filter(|edge| edge.split_whitespace().next() == Some(name)).collect(); + assert_eq!(edges.len(), 1, "one {name} dependency edge required from {from:?}"); + let fields: Vec<_> = edges[0].split_whitespace().collect(); + let version = fields.get(1).copied(); + let source = fields.get(2).map(|s| s.trim_start_matches('(').trim_end_matches(')')); + let found: Vec<_> = self + .packages + .iter() + .filter(|p| p.id.name == name && version.is_none_or(|v| p.id.version == v) && source.is_none_or(|s| p.id.source.as_deref() == Some(s))) + .collect(); + assert_eq!(found.len(), 1, "ambiguous or absent resolved edge {} from {from:?}", edges[0]); + found[0].id.clone() + } +} + +pub(crate) fn assert_renderer_edges(graph: &LockGraph, svg: &PackageId) { + let renderer = graph.dependency(svg, "resvg"); + assert_eq!(graph.dependency(svg, "usvg"), graph.dependency(&renderer, "usvg"), "shared and renderer trees must be the same resolved package"); + for codec in ["gif", "image-webp", "zune-jpeg"] { + assert_eq!(graph.dependency(svg, codec), graph.dependency(&renderer, codec), "validator and selected renderer differ for {codec}"); + } +} + +#[test] +fn svg_validator_and_selected_renderer_share_resolved_backend_packages() { + let file = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../Cargo.lock"); + let graph = LockGraph::parse(&std::fs::read_to_string(file).unwrap()); + let svg = graph.dependency(&graph.workspace_package("photocraft-io"), "craft-svg"); + assert_renderer_edges(&graph, &svg); +} + +#[test] +fn dependency_lookup_follows_the_selected_edge_and_rejects_ambiguity() { + let graph = LockGraph::parse( + r#" +[[package]] +name = "consumer" +version = "1" +dependencies = ["codec 1 (registry+one)"] +[[package]] +name = "codec" +version = "1" +source = "registry+one" +[[package]] +name = "codec" +version = "1" +source = "registry+two" +[[package]] +name = "other" +version = "1" +dependencies = ["codec"] +"#, + ); + let selected = graph.dependency(&graph.workspace_package("consumer"), "codec"); + assert_eq!(selected.source.as_deref(), Some("registry+one")); + assert!(std::panic::catch_unwind(|| graph.dependency(&graph.workspace_package("other"), "codec")).is_err()); +} diff --git a/crates/io/src/svg/image_integrity.rs b/crates/io/src/svg/image_integrity.rs deleted file mode 100644 index 8c5bd422eb..0000000000 --- a/crates/io/src/svg/image_integrity.rs +++ /dev/null @@ -1,297 +0,0 @@ -//! Image validation state shared by the outer parser and all embedded SVG resolvers. -use std::collections::HashMap; -use std::sync::{Arc, Mutex, PoisonError}; - -use super::{IoError, MAX_BOUNDED_SVG_BYTES, MAX_INFLATED_BYTES, MAX_RASTER_PIXELS, MAX_XML_DEPTH, data_href_validation, raster_validation, tree_limits, usvg}; - -#[cfg(test)] -#[path = "integrity_budget_tests.rs"] -mod integrity_budget_tests; - -struct RasterRecord { - // Retain successful and failed sources: parser-discarded image allocations - // must not recycle an address and bypass the validation-work allowance. - _encoded: Arc>, - result: Result<(), raster_validation::Failure>, -} - -pub(super) struct Integrity { - pixel_limit: u64, - pixels_left: u64, - svg_bytes_left: usize, - // Failed input spends the original allowance without refund. Later - // classification never admits children; it has a separate aggregate 16 MiB - // inflation allowance. Decoded UTF-8 is checked against the genuine content - // room saved before that failure, not against remaining inflation work. - svg_failure_exhausted: bool, - classification_bytes_left: usize, - classification_content_left: usize, - // Upstream's text_rechecked contract: even plain legacy-encoded retries - // allocate/scan decoded text. Charge source bytes before every retry decode. - classification_text_bytes_left: usize, - raster: HashMap, - encoded_left: usize, - invalid_raster: usize, - invalid_svg: usize, - raster_limits: usize, - svg_limits: usize, - svg_resource_limits: usize, - fatal: bool, -} - -impl Integrity { - pub(super) fn new(pixels: u64) -> Self { - Self { - pixel_limit: pixels.min(MAX_RASTER_PIXELS), - pixels_left: pixels.min(MAX_RASTER_PIXELS), - svg_bytes_left: MAX_BOUNDED_SVG_BYTES as usize, - svg_failure_exhausted: false, - classification_bytes_left: MAX_BOUNDED_SVG_BYTES as usize, - classification_content_left: MAX_BOUNDED_SVG_BYTES as usize, - classification_text_bytes_left: MAX_BOUNDED_SVG_BYTES as usize, - raster: HashMap::new(), - encoded_left: (MAX_INFLATED_BYTES + MAX_BOUNDED_SVG_BYTES) as usize, - invalid_raster: 0, - invalid_svg: 0, - raster_limits: 0, - svg_limits: 0, - svg_resource_limits: 0, - fatal: false, - } - } - - pub(super) fn usage(&self, mut usage: craft_svg::tree::ImageUsage) -> Result { - if self.fatal { - return Err(IoError::Svg("embedded image validation metadata exceeds its bounded allowance".into())); - } - // Raster callbacks use the exact rendering backend here, rather than decoding - // once generically in the shared resolver and then again for validation. - usage.raster_pixels = usage.raster_pixels.max(self.pixel_limit.saturating_sub(self.pixels_left)); - usage.invalid_raster_images = usage.invalid_raster_images.saturating_add(self.invalid_raster); - usage.invalid_svg_images = usage.invalid_svg_images.saturating_add(self.invalid_svg); - usage.raster_limit_images = usage.raster_limit_images.saturating_add(self.raster_limits); - usage.svg_limit_images = usage.svg_limit_images.saturating_add(self.svg_limits); - usage.svg_resource_limit_images = usage.svg_resource_limit_images.saturating_add(self.svg_resource_limits); - // Repairing a malformed href can shorten text. Its original expanded UTF-8 - // bytes remain charged, including XML declarations removed for transport. - usage.embedded_svg_bytes = usage.embedded_svg_bytes.max((MAX_BOUNDED_SVG_BYTES as usize).saturating_sub(self.svg_bytes_left)); - Ok(usage) - } - - #[cfg(test)] - pub(super) fn classification_bytes_left(&self) -> usize { - self.classification_bytes_left - } - - /// Classify only, without refund or admission. Gzip retries charge actual - /// inflated bytes; plain input needs no inflation. Latin-1/UTF-16 conversion - /// can expand text, so its content limit is independent of retry work. - fn classify_after_svg_failure(&mut self, data: &[u8]) { - if self.svg_resource_limits != 0 { - self.svg_limits = self.svg_limits.saturating_add(1); - self.svg_resource_limits = self.svg_resource_limits.saturating_add(1); - return; - } - let compressed = data.starts_with(&[0x1f, 0x8b]); - let content_left = self.classification_content_left; - let limit = if compressed { content_left.min(self.classification_bytes_left) } else { content_left }; - if compressed && limit == 0 { - self.svg_limits = self.svg_limits.saturating_add(1); - self.svg_resource_limits = self.svg_resource_limits.saturating_add(1); - return; - } - let resource_refusal = match craft_svg::svgz::inflate(data, limit) { - Ok(bytes) => { - if compressed { - self.classification_bytes_left = self.classification_bytes_left.saturating_sub(bytes.len()); - } - let Some(text_left) = self.classification_text_bytes_left.checked_sub(bytes.len()) else { - self.svg_limits = self.svg_limits.saturating_add(1); - self.svg_resource_limits = self.svg_resource_limits.saturating_add(1); - return; - }; - self.classification_text_bytes_left = text_left; - match craft_svg::svgz::decode(&bytes) { - Ok(text) => text.len() > content_left, - Err(_) => { - self.invalid_svg = self.invalid_svg.saturating_add(1); - return; - } - } - } - Err(craft_svg::svgz::Error::TooLarge(_)) => { - if compressed { - self.classification_bytes_left = self.classification_bytes_left.saturating_sub(limit); - } - true - } - Err(error) => { - // Nested data was fully inflated before refusal. Other failures - // may have consumed the entire attempted inflation allowance. - if compressed { - let charged = match error { - craft_svg::svgz::Error::Nested(bytes) => bytes, - _ => limit, - }; - self.classification_bytes_left = self.classification_bytes_left.saturating_sub(charged); - } - self.invalid_svg = self.invalid_svg.saturating_add(1); - return; - } - }; - self.svg_limits = self.svg_limits.saturating_add(1); - if resource_refusal { - self.svg_resource_limits = self.svg_resource_limits.saturating_add(1); - } - } - - fn raster(&mut self, kind: &usvg::ImageKind) -> bool { - if self.fatal { - return false; - } - let encoded = match kind { - usvg::ImageKind::SVG(_) => return true, - usvg::ImageKind::PNG(data) | usvg::ImageKind::JPEG(data) | usvg::ImageKind::GIF(data) | usvg::ImageKind::WEBP(data) => data, - }; - let key = Arc::as_ptr(encoded).addr(); - let result = if let Some(record) = self.raster.get(&key) { - record.result - } else { - // Bound auxiliary records independently of a hostile count of tiny images. - let Some(left) = self.encoded_left.checked_sub(encoded.len()) else { - self.fatal = true; - return false; - }; - if self.raster.len() >= 100_000 || self.raster.try_reserve(1).is_err() { - self.fatal = true; - return false; - } - self.encoded_left = left; - let result = raster_validation::validate(kind, &mut self.pixels_left); - self.raster.insert(key, RasterRecord { _encoded: Arc::clone(encoded), result }); - result - }; - match result { - Ok(()) => true, - Err(raster_validation::Failure::Invalid) => { - self.invalid_raster = self.invalid_raster.saturating_add(1); - false - } - Err(raster_validation::Failure::Limit) => { - self.raster_limits = self.raster_limits.saturating_add(1); - false - } - } - } -} - -pub(super) fn wrap(base: usvg::ImageHrefResolver<'static>, state: Arc>) -> usvg::ImageHrefResolver<'static> { - usvg::ImageHrefResolver { - resolve_string: base.resolve_string, - resolve_data: Box::new(move |mime, data, options| { - if state.lock().unwrap_or_else(PoisonError::into_inner).fatal { - return None; - } - if let Some(kind) = raster_kind(mime, &data) { - let valid = state.lock().unwrap_or_else(PoisonError::into_inner).raster(&kind); - return valid.then_some(kind); - } - let svg = matches!(mime, "image/svg+xml" | "text/plain"); - if !svg { - // Count failed declared images, while preserving the existing policy: - // non-image media types are ignored before decoding or pixel admission. - if mime.starts_with("image/") { - let mut state = state.lock().unwrap_or_else(PoisonError::into_inner); - state.invalid_raster = state.invalid_raster.saturating_add(1); - } - return None; - } - let data = if svg { - let room = { - let mut state = state.lock().unwrap_or_else(PoisonError::into_inner); - if state.svg_failure_exhausted { - state.classify_after_svg_failure(&data); - return None; - } - state.svg_bytes_left - }; - // Inflate once under the original aggregate allowance, then pass UTF-8 - // text onward. Nested parses retain these exact same wrapped options. - let text = match craft_svg::svgz::text(&data, room) { - Ok(text) if text.len() <= room => text, - error => { - let mut state = state.lock().unwrap_or_else(PoisonError::into_inner); - // Failed inflation/encoding already spent work. Match the shared - // resolver: none of its remaining allowance can be retried. - state.svg_bytes_left = 0; - if matches!(error, Err(craft_svg::svgz::Error::TooLarge(_))) || error.is_ok() { - state.svg_limits = state.svg_limits.saturating_add(1); - state.svg_resource_limits = state.svg_resource_limits.saturating_add(1); - } else { - state.invalid_svg = state.invalid_svg.saturating_add(1); - state.svg_failure_exhausted = true; - state.classification_content_left = room; - } - return None; - } - }; - state.lock().unwrap_or_else(PoisonError::into_inner).svg_bytes_left = room.saturating_sub(text.len()); - let repaired = match data_href_validation::repair(&text, &tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS)) { - Ok(text) => text, - Err(_) => { - let mut state = state.lock().unwrap_or_else(PoisonError::into_inner); - state.invalid_svg = state.invalid_svg.saturating_add(1); - return None; - } - }; - // The declaration was already validated against original UTF-8 text. - // Removing it prevents a Latin-1 declaration from decoding UTF-8 twice. - let normalized = if repaired.strip_prefix("").and_then(|at| repaired.get(at + 2..)).unwrap_or(&repaired) - } else { - &repaired - }; - let mut bytes = Vec::new(); - if bytes.try_reserve_exact(normalized.len()).is_err() { - state.lock().unwrap_or_else(PoisonError::into_inner).fatal = true; - return None; - } - bytes.extend_from_slice(normalized.as_bytes()); - Arc::new(bytes) - } else { - data - }; - // Keep shared SVG nesting/XML accounting. Its nested parsers reuse this - // wrapper, so every raster still follows our one exact, bounded decode. - (base.resolve_data)(mime, data, options) - }), - } -} - -// Preserve the shared resolver's MIME/magic agreement. A forged MIME must not -// borrow a successful validation belonging to a different rendering decoder. -fn raster_kind(mime: &str, data: &Arc>) -> Option { - use photocraft_codecs::Format; - if !matches!(mime, "image/jpg" | "image/jpeg" | "image/png" | "image/gif" | "image/webp" | "text/plain") { - return None; - } - let format = photocraft_codecs::detect(data)?; - let accepted = match mime { - "image/jpg" | "image/jpeg" => format == Format::Jpeg, - "image/png" => format == Format::Png, - "image/gif" => format == Format::Gif, - "image/webp" => format == Format::WebP, - "text/plain" => true, - _ => false, - }; - if !accepted { - return None; - } - Some(match format { - Format::Png => usvg::ImageKind::PNG(Arc::clone(data)), - Format::Jpeg => usvg::ImageKind::JPEG(Arc::clone(data)), - Format::Gif => usvg::ImageKind::GIF(Arc::clone(data)), - Format::WebP => usvg::ImageKind::WEBP(Arc::clone(data)), - _ => return None, - }) -} diff --git a/crates/io/src/svg/integrity_budget_tests.rs b/crates/io/src/svg/integrity_budget_tests.rs deleted file mode 100644 index 44fb71a0c2..0000000000 --- a/crates/io/src/svg/integrity_budget_tests.rs +++ /dev/null @@ -1,259 +0,0 @@ -use super::*; -use std::io::Write; - -fn wrapped_options(pixels: u64) -> (usvg::Options<'static>, Arc>, Arc) { - let state = Arc::new(Mutex::new(Integrity::new(pixels))); - let resolver = Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(MAX_XML_DEPTH, pixels))); - let options = - super::super::options_with_isolation(Arc::new(usvg::fontdb::Database::new()), MAX_XML_DEPTH, false, Arc::clone(&resolver), Arc::clone(&state)); - (options, state, resolver) -} - -fn png() -> Vec { - let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [17, 83, 149].repeat(4)).unwrap(); - photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap() -} - -#[test] -fn original_nested_xml_bytes_are_not_refunded_when_malformed_hrefs_shrink() { - super::super::on_svg_stack(|| { - let (options, state, resolver) = wrapped_options(MAX_RASTER_PIXELS); - let prefix = ""; - let original_size = 3 << 20; - let source = Arc::new([prefix.as_bytes(), &vec![b'A'; original_size - prefix.len() - suffix.len()], suffix.as_bytes()].concat()); - assert_eq!(source.len(), original_size); - for accepted in 1..=5 { - let kind = (options.image_href_resolver.resolve_data)("image/svg+xml", Arc::clone(&source), &options); - assert!(matches!(kind, Some(usvg::ImageKind::SVG(_))), "source {accepted} fits the original-text allowance"); - drop(kind); - let state = state.lock().unwrap_or_else(PoisonError::into_inner); - assert_eq!(state.svg_bytes_left, MAX_BOUNDED_SVG_BYTES as usize - accepted * original_size); - assert!(!state.svg_failure_exhausted); - assert_eq!(state.classification_bytes_left(), MAX_BOUNDED_SVG_BYTES as usize); - let usage = state.usage(resolver.usage()).unwrap(); - assert_eq!(usage.embedded_svg_bytes, accepted * original_size, "the short replacement cannot refund original XML work"); - } - assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::clone(&source), &options).is_none()); - let state = state.lock().unwrap_or_else(PoisonError::into_inner); - assert_eq!(state.svg_bytes_left, 0); - assert_eq!((state.svg_limits, state.svg_resource_limits), (1, 1)); - assert!(!state.svg_failure_exhausted, "ordinary byte exhaustion cannot enter compatibility classification"); - assert_eq!(state.classification_bytes_left(), MAX_BOUNDED_SVG_BYTES as usize); - assert_eq!(state.usage(resolver.usage()).unwrap().svg_resource_limit_images, 1); - Ok(()) - }) - .unwrap(); -} - -#[test] -fn invalid_utf8_gzip_consumes_remaining_svg_work_before_the_next_child() { - super::super::on_svg_stack(|| { - let (options, state, resolver) = wrapped_options(MAX_RASTER_PIXELS); - let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); - encoder.write_all(&[0xff; 4096]).unwrap(); - let invalid = Arc::new(encoder.finish().unwrap()); - assert!((options.image_href_resolver.resolve_data)("image/svg+xml", invalid, &options).is_none()); - { - let state = state.lock().unwrap_or_else(PoisonError::into_inner); - assert_eq!(state.svg_bytes_left, 0, "a failed decode cannot retry the full work allowance"); - assert_eq!(state.invalid_svg, 1); - assert!(state.svg_failure_exhausted); - assert_eq!(state.svg_resource_limits, 0); - assert_eq!(state.classification_bytes_left(), MAX_BOUNDED_SVG_BYTES as usize); - } - let valid = Arc::new(b"".to_vec()); - let valid_size = valid.len(); - assert!((options.image_href_resolver.resolve_data)("image/svg+xml", valid, &options).is_none()); - let state = state.lock().unwrap_or_else(PoisonError::into_inner); - assert_eq!((state.invalid_svg, state.svg_limits, state.svg_resource_limits), (1, 1, 0)); - assert_eq!(state.classification_bytes_left(), MAX_BOUNDED_SVG_BYTES as usize, "plain input does not spend retry inflation work"); - let usage = state.usage(resolver.usage()).unwrap(); - assert_eq!(usage.embedded_svg_bytes, MAX_BOUNDED_SVG_BYTES as usize); - assert_eq!(usage.svg_resource_limit_images, 0, "a later small child is omitted, not a resource error"); - let charged = 2 * MAX_BOUNDED_SVG_BYTES as usize - state.svg_bytes_left - state.classification_bytes_left(); - assert_eq!(charged, MAX_BOUNDED_SVG_BYTES as usize); - assert!(valid_size < MAX_BOUNDED_SVG_BYTES as usize); - Ok(()) - }) - .unwrap(); -} - -#[test] -fn post_failure_classification_is_cumulative_and_never_admits_later_children() { - super::super::on_svg_stack(|| { - let (options, state, resolver) = wrapped_options(MAX_RASTER_PIXELS); - let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); - encoder.write_all(&[0xff; 256]).unwrap(); - assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::new(encoder.finish().unwrap()), &options).is_none()); - let text = b""; - let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); - encoder.write_all(text).unwrap(); - let valid = Arc::new(encoder.finish().unwrap()); - // Exercise the cumulative inflated-byte boundary with a small injected - // second pool; public tests cover the full 16 MiB allowance. - let classification_limit = text.len() * 2 - 1; - state.lock().unwrap_or_else(PoisonError::into_inner).classification_bytes_left = classification_limit; - assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::clone(&valid), &options).is_none()); - { - let state = state.lock().unwrap_or_else(PoisonError::into_inner); - assert_eq!(state.classification_bytes_left(), text.len() - 1); - assert_eq!((state.svg_limits, state.svg_resource_limits), (1, 0)); - } - assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::clone(&valid), &options).is_none()); - let state = state.lock().unwrap_or_else(PoisonError::into_inner); - assert_eq!(state.classification_bytes_left(), 0); - assert_eq!((state.svg_limits, state.svg_resource_limits), (2, 1)); - assert_eq!(state.svg_bytes_left, 0, "classification never refunds original failed work"); - assert!(state.svg_failure_exhausted); - let charged = 2 * MAX_BOUNDED_SVG_BYTES as usize - state.svg_bytes_left - state.classification_bytes_left(); - assert_eq!(charged, 2 * MAX_BOUNDED_SVG_BYTES as usize, "original content plus aggregate retry inflation allowances remain bounded"); - assert_eq!(resolver.usage().embedded_svg_count, 0, "classified children must never reach the shared parser"); - Ok(()) - }) - .unwrap(); -} - -#[test] -fn retry_inflation_room_and_saved_decoded_content_room_remain_independent() { - super::super::on_svg_stack(|| { - let mut latin1 = b""); - let decoded_len = craft_svg::svgz::decode(&latin1).unwrap().len(); - assert!(latin1.len() < 256 && decoded_len > 256 && decoded_len < 512); - let gzip = |bytes: &[u8]| { - let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); - encoder.write_all(bytes).unwrap(); - Arc::new(encoder.finish().unwrap()) - }; - for (content_room, expected_resource) in [(512usize, false), (256, true)] { - let (options, state, resolver) = wrapped_options(MAX_RASTER_PIXELS); - // Model preceding genuine content consumption before an unreadable - // stream burns the rest. Classification must save this exact room. - state.lock().unwrap_or_else(PoisonError::into_inner).svg_bytes_left = content_room; - assert!((options.image_href_resolver.resolve_data)("image/svg+xml", gzip(&[0xff; 4]), &options).is_none()); - { - let mut state = state.lock().unwrap_or_else(PoisonError::into_inner); - assert_eq!(state.classification_content_left, content_room); - assert_eq!(state.svg_bytes_left, 0); - // Enough compressed retry work for the raw Latin-1 bytes, but - // less than their decoded UTF-8 length, just like main's case. - state.classification_bytes_left = latin1.len() + 1; - } - assert!((options.image_href_resolver.resolve_data)("image/svg+xml", gzip(&latin1), &options).is_none()); - let state = state.lock().unwrap_or_else(PoisonError::into_inner); - assert_eq!(state.classification_bytes_left(), 1, "retry work charges inflated bytes, not UTF-8 bytes"); - assert_eq!(state.svg_resource_limits, usize::from(expected_resource)); - assert_eq!(state.svg_bytes_left, 0, "classification never restores original content allowance"); - assert_eq!(resolver.usage().embedded_svg_count, 0, "no classified child is parsed or drawn"); - } - Ok(()) - }) - .unwrap(); -} - -#[test] -fn failed_raster_arcs_are_retained_and_cached_failures_do_not_recharge_work() { - let mut broken = png(); - let idat = broken.windows(4).position(|bytes| bytes == b"IDAT").unwrap(); - broken[idat + 4] ^= 1; - assert_eq!(photocraft_codecs::probe_allocation_size(&broken).unwrap(), (2, 2), "failure must occur after four-pixel admission"); - let encoded = Arc::new(broken); - let key = Arc::as_ptr(&encoded).addr(); - let weak = Arc::downgrade(&encoded); - let kind = usvg::ImageKind::PNG(Arc::clone(&encoded)); - let mut state = Integrity::new(4); - let encoded_before = state.encoded_left; - assert!(!state.raster(&kind)); - assert_eq!(state.pixels_left, 0); - assert_eq!(state.encoded_left, encoded_before - encoded.len()); - assert_eq!(state.raster.get(&key).unwrap().result, Err(raster_validation::Failure::Invalid)); - let charged = state.encoded_left; - assert!(!state.raster(&kind)); - assert_eq!((state.pixels_left, state.encoded_left, state.raster.len(), state.invalid_raster), (0, charged, 1, 2)); - drop(kind); - drop(encoded); - let retained = weak.upgrade().expect("cache must retain failed encoded sources to prevent pointer reuse"); - assert_eq!(Arc::as_ptr(&retained).addr(), key); - assert_eq!(Arc::as_ptr(&state.raster.get(&key).unwrap()._encoded).addr(), key); - let other = Arc::new(png()); - assert_ne!(Arc::as_ptr(&other).addr(), key, "a live failed source's identity cannot be reused"); - assert!(!state.raster(&usvg::ImageKind::PNG(other)), "a distinct source cannot reuse pixels spent by the failed decode"); - assert_eq!(state.raster_limits, 1); -} - -#[test] -fn cached_valid_png_with_exactly_four_pixels_is_not_charged_twice() { - let encoded = Arc::new(png()); - let kind = usvg::ImageKind::PNG(Arc::clone(&encoded)); - let mut state = Integrity::new(4); - let encoded_before = state.encoded_left; - assert!(state.raster(&kind)); - assert_eq!(state.pixels_left, 0); - assert_eq!(state.encoded_left, encoded_before - encoded.len()); - let charged = state.encoded_left; - assert!(state.raster(&kind), "cached validation remains valid after it spent the last four pixels"); - assert_eq!((state.pixels_left, state.encoded_left, state.raster.len()), (0, charged, 1)); - assert_eq!((state.invalid_raster, state.raster_limits), (0, 0)); -} - -#[test] -fn raster_callbacks_own_pixel_charges_and_keep_mime_aliases_separate() { - let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap(); - let png = Arc::new(photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap()); - let shared = craft_svg::tree::ImageResolver::new(tree_limits(MAX_XML_DEPTH, 4)); - let state = Arc::new(Mutex::new(Integrity::new(4))); - let resolver = wrap(shared.resolver(), Arc::clone(&state)); - for _ in 0..2 { - assert!((resolver.resolve_data)("image/png", Arc::clone(&png), &usvg::Options::default()).is_some()); - let usage = state.lock().unwrap().usage(shared.usage()).unwrap(); - assert_eq!(usage.raster_pixels, 4, "a retained alias does not spend decoding work again"); - assert_eq!(usage.invalid_raster_images, 0); - assert_eq!(shared.usage().raster_pixels, 0, "generic decoding must not duplicate exact renderer validation"); - } - assert!((resolver.resolve_data)("image/jpeg", png, &usvg::Options::default()).is_none()); - let usage = state.lock().unwrap().usage(shared.usage()).unwrap(); - assert_eq!(usage.raster_pixels, 4); - assert_eq!(usage.invalid_raster_images, 1, "a mismatched MIME cannot borrow the successful PNG cache entry"); -} - -// Preserve upstream's text_rechecked boundary using the integrated real resolver. -// Plain and gzip retries spend source bytes before decoding, independently of -// inflation work and the drawing's genuine decoded-content capacity. -#[test] -fn plain_legacy_encoding_rechecks_have_a_separate_bounded_work_allowance() { - super::super::on_svg_stack(|| { - let xml = b""; - for compressed in [false, true] { - let (options, state, resolver) = wrapped_options(MAX_RASTER_PIXELS); - let encode = |bytes: &[u8]| { - if compressed { - let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); - encoder.write_all(bytes).unwrap(); - encoder.finish().unwrap() - } else { - bytes.to_vec() - } - }; - assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::new(encode(&[0xff])), &options).is_none()); - state.lock().unwrap_or_else(PoisonError::into_inner).classification_text_bytes_left = xml.len(); - assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::new(encode(xml)), &options).is_none()); - { - let state = state.lock().unwrap_or_else(PoisonError::into_inner); - assert_eq!(state.classification_text_bytes_left, 0); - assert_eq!(state.svg_resource_limits, 0, "exactly fitting text recheck is permitted"); - assert_eq!(state.classification_bytes_left, MAX_BOUNDED_SVG_BYTES as usize - usize::from(compressed) * xml.len()); - } - assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::new(encode(xml)), &options).is_none()); - let state = state.lock().unwrap_or_else(PoisonError::into_inner); - assert_eq!(state.classification_text_bytes_left, 0); - assert_eq!(state.svg_resource_limits, 1, "the next source cannot repeat text-conversion work"); - assert_eq!(state.invalid_svg, 1, "the original encoding error stays invalid"); - assert_eq!(state.svg_limits, 2); - assert_eq!(resolver.usage().embedded_svg_count, 0, "rechecked children are never admitted"); - } - Ok(()) - }) - .unwrap(); -} diff --git a/crates/io/src/svg/mime_header_tests.rs b/crates/io/src/svg/mime_header_tests.rs deleted file mode 100644 index 88c27dd79b..0000000000 --- a/crates/io/src/svg/mime_header_tests.rs +++ /dev/null @@ -1,119 +0,0 @@ -use super::*; -use std::fmt::Write; - -fn parameters(count: usize) -> String { - let mut text = String::new(); - for index in 0..count { - write!(&mut text, ";p{index}=x").unwrap(); - } - text -} - -#[test] -fn a_hundred_thousand_unique_mime_parameters_are_refused_before_the_original_parser() { - let params = parameters(100_000); - for (essence, expected) in [ - ("image/png", INVALID_IMAGE), - ("text/plain", INVALID_IMAGE), - ("", INVALID_IMAGE), - ("not-a-mime", INVALID_IMAGE), - ("application/octet-stream", IGNORED_DATA), - ("audio/ogg", IGNORED_DATA), - ] { - for delimiter in [",AA==", "#fragment,AA==", ""] { - let value = format!("data:{essence}{params};base64{delimiter}"); - let mut work = value.len() * 2; - assert!(!mime_header_admitted(&value)); - let result = - malformed_data_url_replacement_with(&value, &mut work, |_| panic!("the original parameter flood must not reach DataUrl::process")).unwrap(); - assert_eq!(result, Some(expected), "{essence} {delimiter}"); - } - } -} - -#[test] -fn mime_parameter_admission_preserves_the_boundary_and_ignores_body_semicolons() { - let accepted = format!("data:image/png{};base64,AA==", parameters(MAX_MIME_SEPARATORS - 1)); - assert!(mime_header_admitted(&accepted)); - let called = std::cell::Cell::new(false); - let mut work = accepted.len() * 2; - assert_eq!( - malformed_data_url_replacement_with(&accepted, &mut work, |value| { - called.set(true); - data_url::DataUrl::process(value) - }) - .unwrap(), - None - ); - assert!(called.get(), "an admitted original URL still reaches the real parser"); - let refused = format!("data:image/png{};base64,AA==", parameters(MAX_MIME_SEPARATORS)); - assert!(!mime_header_admitted(&refused)); - let mut work = refused.len() * 2; - assert_eq!(malformed_data_url_replacement(&refused, &mut work).unwrap(), Some(INVALID_IMAGE)); - - for value in [format!("data:text/plain,{}", ";".repeat(100_000)), format!("external.png?{}", parameters(100_000))] { - assert!(mime_header_admitted(&value), "payloads/external URLs are not MIME parameters"); - let mut work = value.len() * 2; - assert_eq!(malformed_data_url_replacement(&value, &mut work).unwrap(), None); - } - let value = format!(" \td\ta\nt\ra:image/png{};base64,A", parameters(MAX_MIME_SEPARATORS)); - assert!(!mime_header_admitted(&value), "scheme normalization matches the pinned parser"); - let mut work = value.len() * 2; - assert_eq!(malformed_data_url_replacement(&value, &mut work).unwrap(), Some(INVALID_IMAGE)); -} - -#[test] -fn refused_parameter_lists_normalize_both_hrefs_and_foreign_resources_without_preflight_warnings() { - let value = format!("data:image/png{};base64,AA==", parameters(MAX_MIME_SEPARATORS)); - let text = format!( - "" - ); - let limits = Limits { bytes: 1 << 20, ..Default::default() }; - let repaired = repair(&text, &limits).unwrap(); - assert_eq!(repaired.matches(INVALID_IMAGE).count(), 6); - assert!(!repaired.contains(";p0=")); - let resolver = craft_svg::tree::ImageResolver::new(limits); - resolver.check_document(&repaired).unwrap(); - let usage = resolver.usage(); - assert_eq!((usage.invalid_raster_images, usage.invalid_svg_images), (0, 0)); - assert!(matches!(repair(&repaired, &Limits { bytes: 1 << 20, ..Default::default() }).unwrap(), Cow::Borrowed(_))); -} - -#[test] -fn duplicate_and_quoted_parameters_share_the_same_conservative_boundary() { - for (accepted, refused) in [ - (format!("data:image/png{},%00", ";p=x".repeat(MAX_MIME_SEPARATORS)), format!("data:image/png{},%00", ";p=x".repeat(MAX_MIME_SEPARATORS + 1))), - (format!("data:image/png;p=\"{}\",%00", ";".repeat(MAX_MIME_SEPARATORS - 1)), format!("data:image/png;p=\"{}\",%00", ";".repeat(MAX_MIME_SEPARATORS))), - ] { - assert!(mime_header_admitted(&accepted)); - let mut work = accepted.len() * 2; - assert_eq!(malformed_data_url_replacement(&accepted, &mut work).unwrap(), None); - assert!(!mime_header_admitted(&refused)); - let mut work = refused.len() * 2; - assert_eq!(malformed_data_url_replacement(&refused, &mut work).unwrap(), Some(INVALID_IMAGE)); - } - for value in ["external.png", "#local", "datx:image/png;param=x,body"] { - let mut work = value.len() * 2; - assert_eq!(malformed_data_url_replacement(value, &mut work).unwrap(), None); - } - let value = "data:image/png;base64"; - let mut work = value.len() * 2; - assert_eq!(malformed_data_url_replacement(value, &mut work).unwrap(), Some(INVALID_IMAGE)); -} - -#[test] -fn parameter_flood_scans_and_essence_classification_spend_one_shared_work_ledger() { - let value = format!("data:application/octet-stream{};base64,AA==", parameters(MAX_MIME_SEPARATORS)); - let essence_len = "data:application/octet-stream".len(); - let charge = value.len() + essence_len; - let mut work = charge * 2; - for remaining in [charge, 0] { - assert_eq!(malformed_data_url_replacement_with(&value, &mut work, |_| panic!("not admitted")).unwrap(), Some(IGNORED_DATA)); - assert_eq!(work, remaining, "the original header scan and parameter-free fallback each retain their charge"); - } - assert!(malformed_data_url_replacement_with(&value, &mut work, |_| panic!("no work remains")).is_err()); - assert_eq!(work, 0); - let mut not_enough_for_essence = value.len(); - assert!(malformed_data_url_replacement_with(&value, &mut not_enough_for_essence, |_| panic!("not admitted")).is_err()); - assert_eq!(not_enough_for_essence, 0); -} diff --git a/crates/io/src/svg/optional_image_review_tests.rs b/crates/io/src/svg/optional_image_review_tests.rs index 8b792c59f4..5cbded4da0 100644 --- a/crates/io/src/svg/optional_image_review_tests.rs +++ b/crates/io/src/svg/optional_image_review_tests.rs @@ -52,9 +52,13 @@ fn valid_twelve_bit_jpeg_rejected_by_the_svg_renderer_is_disclosed() { assert_eq!(decoded.dimensions(), (8, 8)); // Match resvg's actual JPEG backend/output policy, rather than the broader // shared codec which also supports valid 12-bit and arithmetic JPEG files. - let options = zune_core::options::DecoderOptions::default().jpeg_set_out_colorspace(zune_core::colorspace::ColorSpace::RGBA); - let mut renderer_decoder = zune_jpeg::JpegDecoder::new_with_options(std::io::Cursor::new(jpeg.as_slice()), options); - assert!(renderer_decoder.decode().is_err(), "fixture must exercise the actual renderer capability gap"); + let kind = usvg::ImageKind::JPEG(Arc::new(jpeg.clone())); + let mut pixels_left = MAX_RASTER_PIXELS; + assert_eq!( + draw::validate_raster(&kind, MAX_RASTER_PIXELS, &mut pixels_left), + Err(draw::RasterValidationFailure::Invalid), + "fixture must exercise the shared renderer capability gap" + ); for mime in ["image/jpeg", "text/plain"] { let direct = drawing(&url(mime, &jpeg)); assert_incomplete_image_is_disclosed(&direct); diff --git a/crates/io/src/svg/raster_validation.rs b/crates/io/src/svg/raster_validation.rs deleted file mode 100644 index 364b199010..0000000000 --- a/crates/io/src/svg/raster_validation.rs +++ /dev/null @@ -1,135 +0,0 @@ -//! Validate optional raster images with the same backends used by the SVG renderer. -//! -//! Header probing alone cannot detect damaged pixel data. Admit dimensions and -//! reserve work before decoding: even a failed decode keeps its charge. - -use std::io::Cursor; -use std::num::NonZeroU64; - -use super::{MAX_RASTER_PIXELS, tiny_skia, usvg}; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Failure { - Invalid, - Limit, -} - -/// Validate the renderer's first frame without retaining decoded pixels. SVG -/// children use the same wrapped resolver and need no second recursive walk. -pub(super) fn validate(kind: &usvg::ImageKind, pixels_left: &mut u64) -> Result<(), Failure> { - let data = match kind { - usvg::ImageKind::PNG(data) | usvg::ImageKind::JPEG(data) | usvg::ImageKind::GIF(data) | usvg::ImageKind::WEBP(data) => data, - usvg::ImageKind::SVG(_) => return Ok(()), - }; - // The allocation probe includes oversized GIF/WebP frames, not merely their - // canvas. Reserve before asking any rendering decoder to allocate pixels. - let (width, height) = photocraft_codecs::probe_allocation_size(data).map_err(|_| Failure::Invalid)?; - let pixels = area(width, height)?; - if pixels > MAX_RASTER_PIXELS { - return Err(Failure::Limit); - } - *pixels_left = pixels_left.checked_sub(pixels).ok_or(Failure::Limit)?; - match kind { - usvg::ImageKind::PNG(data) => { - let decoded = tiny_skia::Pixmap::decode_png(data).map_err(|_| Failure::Invalid)?; - rgba_bytes(decoded.width(), decoded.height(), pixels)?; - Ok(()) - } - usvg::ImageKind::JPEG(data) => jpeg(data, pixels), - usvg::ImageKind::GIF(data) => gif(data, pixels), - usvg::ImageKind::WEBP(data) => webp(data, pixels), - usvg::ImageKind::SVG(_) => Ok(()), - } -} - -fn area(width: u32, height: u32) -> Result { - if width == 0 || height == 0 { - return Err(Failure::Invalid); - } - u64::from(width).checked_mul(u64::from(height)).ok_or(Failure::Limit) -} - -/// Decoder headers must not request more output than the allocation probe paid for. -fn rgba_bytes(width: u32, height: u32, admitted: u64) -> Result { - let pixels = area(width, height)?; - if pixels > admitted { - return Err(Failure::Limit); - } - usize::try_from(pixels.checked_mul(4).ok_or(Failure::Limit)?).map_err(|_| Failure::Limit) -} - -fn buffer(length: usize) -> Result, Failure> { - let mut output = Vec::new(); - output.try_reserve_exact(length).map_err(|_| Failure::Limit)?; - output.resize(length, 0); - Ok(output) -} - -fn jpeg(data: &[u8], admitted: u64) -> Result<(), Failure> { - use zune_core::colorspace::ColorSpace; - use zune_core::options::DecoderOptions; - - // Preserve the rendering decoder's default limits and RGBA conversion; a - // general photo decoder may accept formats the SVG renderer cannot draw. - let options = DecoderOptions::default().jpeg_set_out_colorspace(ColorSpace::RGBA); - let mut decoder = zune_jpeg::JpegDecoder::new_with_options(Cursor::new(data), options); - decoder.decode_headers().map_err(|_| Failure::Invalid)?; - let info = decoder.info().ok_or(Failure::Invalid)?; - let length = rgba_bytes(u32::from(info.width), u32::from(info.height), admitted)?; - if decoder.output_colorspace() != Some(ColorSpace::RGBA) || decoder.output_buffer_size() != Some(length) { - return Err(Failure::Invalid); - } - let mut output = buffer(length)?; - decoder.decode_into(&mut output).map_err(|_| Failure::Invalid) -} - -fn gif(data: &[u8], admitted: u64) -> Result<(), Failure> { - let bytes = admitted.checked_mul(4).ok_or(Failure::Limit)?; - // Do not loosen the renderer's default 50 MB GIF frame limit. Smaller - // imports also keep their own admitted allocation ceiling during decode. - let limit = NonZeroU64::new(bytes.min(50_000_000)).ok_or(Failure::Invalid)?; - let mut options = gif::DecodeOptions::new(); - options.set_color_output(gif::ColorOutput::RGBA); - options.set_memory_limit(gif::MemoryLimit::Bytes(limit)); - let mut decoder = options.read_info(data).map_err(gif_error)?; - let frame = decoder.read_next_frame().map_err(gif_error)?.ok_or(Failure::Invalid)?; - let expected = rgba_bytes(u32::from(frame.width), u32::from(frame.height), admitted)?; - if frame.buffer.len() != expected { - return Err(Failure::Invalid); - } - Ok(()) -} - -fn gif_error(error: gif::DecodingError) -> Failure { - match error { - gif::DecodingError::MemoryLimit | gif::DecodingError::OutOfMemory => Failure::Limit, - _ => Failure::Invalid, - } -} - -fn webp(data: &[u8], admitted: u64) -> Result<(), Failure> { - let mut decoder = image_webp::WebPDecoder::new(Cursor::new(data)).map_err(webp_error)?; - let (width, height) = decoder.dimensions(); - let rgba = rgba_bytes(width, height, admitted)?; - let channels = if decoder.has_alpha() { 4 } else { 3 }; - let expected = usize::try_from(area(width, height)?.checked_mul(channels).ok_or(Failure::Limit)?).map_err(|_| Failure::Limit)?; - if expected > rgba { - return Err(Failure::Limit); - } - if decoder.output_buffer_size() != Some(expected) { - return Err(Failure::Invalid); - } - // A small valid image can have a compressed chunk larger than its pixels. - // Bound decoder scratch without rejecting that ordinary encoding overhead. - let admitted_bytes = usize::try_from(admitted.checked_mul(4).ok_or(Failure::Limit)?).map_err(|_| Failure::Limit)?; - decoder.set_memory_limit(admitted_bytes.max(data.len())); - let mut output = buffer(expected)?; - decoder.read_image(&mut output).map_err(webp_error) -} - -fn webp_error(error: image_webp::DecodingError) -> Failure { - match error { - image_webp::DecodingError::MemoryLimitExceeded | image_webp::DecodingError::ImageTooLarge => Failure::Limit, - _ => Failure::Invalid, - } -} diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index 93b2735a60..8de48b1a96 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -40,8 +40,7 @@ fn non_strict_embedded_svg_records_isolation_failure_but_omits_invalid_images() fontless_text: false, strict: false, error: None, - resolver: Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS))), - integrity: Arc::new(Mutex::new(image_integrity::Integrity::new(MAX_RASTER_PIXELS))), + resolver: Arc::new(craft_svg::tree::ValidatedImageResolver::new(tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS))), })); let invalid = image_svg(&embedded_image("image/svg+xml", b"")); parse_image_bounded_with(invalid.as_bytes(), budget.clone(), MAX_XML_DEPTH, inter_only, false).unwrap(); @@ -52,6 +51,53 @@ fn non_strict_embedded_svg_records_isolation_failure_but_omits_invalid_images() assert_eq!(budget.lock().unwrap().error.as_deref(), Some(error.to_string().as_str())); } +/// Shallow declarations can expand to a much deeper parser walk through references. +fn reference_chain_svg(links: usize) -> String { + let mut source = String::from(""); + for index in 0..links { + source.push_str(&format!("", index + 1)); + } + source.push_str(&format!("")); + source +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn narrowed_embedded_xml_allowance_also_bounds_expanded_references() { + let source = reference_chain_svg(12); + let xml_left = 5; + assert!(nesting_depth(source.as_bytes(), xml_left).unwrap() <= xml_left, "lexical nesting alone fits"); + assert!(craft_svg::tree::preflight(&source, &tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS)).is_ok()); + assert!(matches!(craft_svg::tree::preflight(&source, &tree_limits(xml_left, MAX_RASTER_PIXELS)), Err(craft_svg::tree::Error::TooDeep(_)))); + let budget = Arc::new(Mutex::new(ImageBudget { + pixels: MAX_RASTER_PIXELS, + xml_bytes: MAX_BOUNDED_SVG_BYTES, + svg_images: 0, + svg_chain: 0, + draw_nodes: 0, + repeatable_raster: false, + repeatable_svg: false, + fontless_text: false, + strict: false, + error: None, + resolver: Arc::new(craft_svg::tree::ValidatedImageResolver::new(tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS))), + })); + let error = parse_image_bounded_with(source.as_bytes(), budget, xml_left, inter_only, false).unwrap_err(); + assert!(error.to_string().contains("nested"), "{error}"); +} + +#[cfg(target_arch = "wasm32")] +#[test] +fn wasm_inline_allowance_bounds_shallow_expanded_references_before_conversion() { + let limits = tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS); + assert_eq!(limits.tree_depth, INLINE_XML_DEPTH + 1); + let shallow = reference_chain_svg(INLINE_XML_DEPTH / 4); + assert!(craft_svg::tree::preflight(&shallow, &limits).is_ok()); + let expanded = reference_chain_svg(INLINE_XML_DEPTH + 2); + assert!(nesting_depth(expanded.as_bytes(), INLINE_XML_DEPTH).unwrap() <= INLINE_XML_DEPTH); + assert!(matches!(craft_svg::tree::preflight(&expanded, &limits), Err(craft_svg::tree::Error::TooDeep(_)))); +} + fn embedded_image(mime: &str, bytes: &[u8]) -> String { let data = bytes.iter().map(|byte| format!("%{byte:02X}")).collect::(); format!("") @@ -852,24 +898,29 @@ fn missing_svg_font_uses_an_available_generic_instead_of_dropping_text() { } #[test] -fn resolve_data_rejects_oversized_and_malformed_embedded_png_and_webp() { - let opt = options(Arc::new(usvg::fontdb::Database::new()), MAX_XML_DEPTH); - let resolve = &opt.image_href_resolver.resolve_data; +fn embedded_png_and_webp_validation_preserves_public_warning_and_strict_contracts() { let img = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, vec![255; 12]).unwrap(); let valid_png = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); - assert!(resolve("image/png", Arc::new(valid_png.clone()), &opt).is_some()); - assert!(resolve("text/plain", Arc::new(valid_png.clone()), &opt).is_some()); - - let mut huge_png = valid_png; - huge_png[16..20].copy_from_slice(&40_000u32.to_be_bytes()); - huge_png[20..24].copy_from_slice(&40_000u32.to_be_bytes()); - assert!(resolve("image/png", Arc::new(huge_png.clone()), &opt).is_none(), "oversized PNG rejected before decode"); - assert!(resolve("text/plain", Arc::new(huge_png), &opt).is_none(), "oversized mime-less PNG rejected before decode"); - - // Malformed WebP header under image/webp or text/plain must be rejected at the probe step. - let bad_webp = b"RIFF\x10\x00\x00\x00WEBPVP8 ".to_vec(); - assert!(resolve("image/webp", Arc::new(bad_webp.clone()), &opt).is_none()); - assert!(resolve("text/plain", Arc::new(bad_webp), &opt).is_none()); + for mime in ["image/png", "text/plain"] { + let svg = image_svg(&embedded_image(mime, &valid_png)); + let output = rasterize_bounded(svg.as_bytes(), 1.0, 64).unwrap(); + assert_eq!((output.rect.width(), output.rect.height()), (1, 1)); + assert_eq!(output.get(0, 0), [1.; 4]); + let mut huge = valid_png.clone(); + huge[16..20].copy_from_slice(&40_000u32.to_be_bytes()); + huge[20..24].copy_from_slice(&40_000u32.to_be_bytes()); + let svg = image_svg(&embedded_image(mime, &huge)); + assert!(parse_bounded(svg.as_bytes(), 64).is_err(), "oversized PNG refused before decode: {mime}"); + assert!(rasterize_bounded(svg.as_bytes(), 1.0, 64).is_err()); + } + for mime in ["image/webp", "text/plain"] { + let svg = image_svg(&embedded_image(mime, b"RIFF\x10\x00\x00\x00WEBPVP8 ")); + let parsed = parse_bounded(svg.as_bytes(), 64).unwrap(); + assert_eq!(omitted_image_count(parsed.image_usage), 1); + assert!(rasterize_bounded(svg.as_bytes(), 1.0, 64).is_err()); + let imported = import_svg_bounded("invalid.webp.svg", svg.as_bytes(), 64).unwrap(); + assert!(imported.warnings.iter().any(|warning| warning.contains("omitted"))); + } } #[test] @@ -885,11 +936,12 @@ fn jpeg_allocation_probe_uses_the_frame_header_and_oversized_jpegs_are_refused() assert_eq!(photocraft_codecs::probe_allocation_size(&jpeg(400, 300)).unwrap(), (300, 400)); assert!(photocraft_codecs::probe_allocation_size(&[0xFF, 0xD8, 0xFF, 0xDA, 0, 2]).is_err()); assert!(photocraft_codecs::probe_allocation_size(&[0xFF, 0xD8]).is_err()); - let opt = options(Arc::new(usvg::fontdb::Database::new()), MAX_XML_DEPTH); - let resolve = &opt.image_href_resolver.resolve_data; - // 1.2 billion pixels would be 4.8 GB of RGBA before resvg scaled anything down. - assert!(resolve("image/jpeg", Arc::new(jpeg(40_000, 30_000)), &opt).is_none()); - assert!(resolve("text/plain", Arc::new(jpeg(40_000, 30_000)), &opt).is_none()); + for mime in ["image/jpeg", "text/plain"] { + // 1.2 billion pixels would require 4.8 GB before scaling. + let svg = image_svg(&embedded_image(mime, &jpeg(40_000, 30_000))); + assert!(parse_bounded(svg.as_bytes(), 64).is_err()); + assert!(rasterize_bounded(svg.as_bytes(), 1.0, 64).is_err()); + } } #[test] @@ -900,17 +952,21 @@ fn resolve_data_rejects_nested_gzip_and_handles_text_plain_svgz() { e.write_all(bytes).unwrap(); e.finish().unwrap() } - let opt = options(Arc::new(usvg::fontdb::Database::new()), MAX_XML_DEPTH); - let resolve = &opt.image_href_resolver.resolve_data; - let svg = b""; + let svg = b""; let once = gz(svg); - assert!(resolve("image/svg+xml", Arc::new(once.clone()), &opt).is_some()); - assert!(resolve("text/plain", Arc::new(once.clone()), &opt).is_some()); - - // Doubly gzip-compressed payload must be rejected rather than decompressed a second time by usvg. let twice = gz(&once); - assert!(resolve("image/svg+xml", Arc::new(twice.clone()), &opt).is_none()); - assert!(resolve("text/plain", Arc::new(twice), &opt).is_none()); + for mime in ["image/svg+xml", "text/plain"] { + let single = image_svg(&embedded_image(mime, &once)); + let output = rasterize_bounded(single.as_bytes(), 1.0, 64).unwrap(); + assert_eq!((output.rect.width(), output.rect.height()), (1, 1)); + assert_eq!(output.get(0, 0), [1., 0., 0., 1.]); + let nested = image_svg(&embedded_image(mime, &twice)); + let parsed = parse_bounded(nested.as_bytes(), 64).unwrap(); + assert_eq!(omitted_image_count(parsed.image_usage), 1); + assert!(rasterize_bounded(nested.as_bytes(), 1.0, 64).is_err()); + let imported = import_svg_bounded("nested.svg", nested.as_bytes(), 64).unwrap(); + assert!(imported.warnings.iter().any(|warning| warning.contains("omitted"))); + } } /// The outer gzip is size-limited by PhotoCraft. Its result must be XML, never another @@ -1192,35 +1248,24 @@ fn fitting_latin1_retry_keeps_inflation_and_content_budgets_separate() { let decoded = craft_svg::svgz::decode(&latin1).unwrap(); assert!(latin1.len() < budget / 2); assert!(decoded.len() > budget / 2 && decoded.len() < budget); - let state = Arc::new(Mutex::new(image_integrity::Integrity::new(MAX_RASTER_PIXELS))); - let resolver = Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS))); - let options = options_with_isolation(Arc::new(usvg::fontdb::Database::new()), MAX_XML_DEPTH, false, Arc::clone(&resolver), Arc::clone(&state)); let valid = gzip(b""); - let damaged = Arc::new(valid[..valid.len() / 2].to_vec()); - assert!((options.image_href_resolver.resolve_data)("image/svg+xml", damaged, &options).is_none()); - assert_eq!(state.lock().unwrap().classification_bytes_left(), budget); - - // Spend half the inflation allowance through an actual compressed retry. - // None of these retries may restore admission after the damaged source. + let damaged = embedded_image("image/svg+xml", &valid[..valid.len() / 2]); let mut primer = b""; primer.resize(budget / 2 - close.len(), b' '); primer.extend_from_slice(close); assert_eq!(primer.len(), budget / 2); - assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::new(gzip(&primer)), &options).is_none()); - { - let state = state.lock().unwrap(); - assert_eq!(state.classification_bytes_left(), budget / 2); - assert_eq!(state.usage(resolver.usage()).unwrap().svg_resource_limit_images, 0); - } - assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::new(gzip(&latin1)), &options).is_none()); - let state = state.lock().unwrap(); - let usage = state.usage(resolver.usage()).unwrap(); - assert_eq!(usage.svg_resource_limit_images, 0, "decoded content fits its independent original allowance"); - assert_eq!(usage.svg_limit_images, 2, "both fitting retries remain omitted"); - assert_eq!(usage.invalid_svg_images, 1, "the original corrupt source stays classified as unreadable"); - assert_eq!(usage.embedded_svg_bytes, budget, "retry classification never refunds failed admission work"); - assert_eq!(state.classification_bytes_left(), budget / 2 - latin1.len(), "only inflated Latin-1 bytes consume retry inflation work"); + let primer = embedded_image("image/svg+xml", &gzip(&primer)); + let fitting = embedded_image("image/svg+xml", &gzip(&latin1)); + let source = image_svg(&format!("{damaged}{primer}{fitting}")); + let parsed = parse_bounded(source.as_bytes(), MAX_RASTER_PIXELS).unwrap(); + assert_eq!(parsed.image_usage.svg_resource_limit_images, 0, "decoded content fits its independent original allowance"); + assert_eq!(parsed.image_usage.svg_limit_images, 2, "both fitting retries remain omitted"); + assert_eq!(parsed.image_usage.invalid_svg_images, 1, "the original corrupt source stays unreadable"); + assert_eq!(parsed.image_usage.embedded_svg_bytes, budget, "retry classification never refunds failed admission work"); + assert!(rasterize_bounded(source.as_bytes(), 1.0, MAX_RASTER_PIXELS).is_err(), "warningless pixels must remain strict"); + let imported = import_svg_bounded("legacy-retry.svg", source.as_bytes(), MAX_RASTER_PIXELS).unwrap(); + assert!(imported.warnings.iter().any(|warning| warning.contains("omitted"))); } /// 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 @@ -1249,31 +1294,23 @@ fn unpacking_images_again_adds_up_to_one_budget_however_many_there_are() { huge.resize(budget * 2, b' '); huge.extend_from_slice(b""); let huge = gzip(&huge); - let state = Arc::new(Mutex::new(image_integrity::Integrity::new(MAX_RASTER_PIXELS))); - let resolver = Arc::new(craft_svg::tree::ImageResolver::new(tree_limits(MAX_XML_DEPTH, MAX_RASTER_PIXELS))); - let options = options_with_isolation(Arc::new(usvg::fontdb::Database::new()), MAX_XML_DEPTH, false, Arc::clone(&resolver), Arc::clone(&state)); let valid = gzip(b""); - let damaged = Arc::new(valid[..valid.len() / 2].to_vec()); - assert!((options.image_href_resolver.resolve_data)("image/svg+xml", damaged, &options).is_none()); - { - let state = state.lock().unwrap(); - let usage = state.usage(resolver.usage()).unwrap(); - assert_eq!(usage.invalid_svg_images, 1, "the actual damaged stream is omitted"); - assert_eq!(usage.embedded_svg_bytes, budget, "failed work retains its original charge"); - assert_eq!(usage.svg_resource_limit_images, 0, "corruption alone is not a resource overrun"); - assert_eq!(state.classification_bytes_left(), budget, "classification has its own single shared allowance"); - } - for index in 0..64 { - // Distinct references must share one classification pool, not acquire one - // pool per source or retry. This tail is never reached before the size cap. - let mut source = huge.clone(); - source.push(index); - assert!((options.image_href_resolver.resolve_data)("image/svg+xml", Arc::new(source), &options).is_none()); - let state = state.lock().unwrap(); - let usage = state.usage(resolver.usage()).unwrap(); - assert!(usage.svg_resource_limit_images > 0, "the body is too large independently of the failed-work charge"); - assert_eq!(state.classification_bytes_left(), 0, "all 64 references share exactly one exhausted allowance"); - assert_eq!(usage.embedded_svg_bytes, budget, "classification must not refund or multiply the original allowance"); + let damaged = embedded_image("image/svg+xml", &valid[..valid.len() / 2]); + let parsed = parse_bounded(image_svg(&damaged).as_bytes(), MAX_RASTER_PIXELS).unwrap(); + assert_eq!(parsed.image_usage.invalid_svg_images, 1); + assert_eq!(parsed.image_usage.embedded_svg_bytes, budget, "failed work retains its original charge"); + assert_eq!(parsed.image_usage.svg_resource_limit_images, 0, "corruption alone is not a resource overrun"); + for count in [1, 64] { + let mut children = damaged.clone(); + for index in 0..count { + let mut source = huge.clone(); + source.push(index); + children.push_str(&embedded_image("image/svg+xml", &source)); + } + let source = image_svg(&children); + let error = parse_bounded(source.as_bytes(), MAX_RASTER_PIXELS).unwrap_err(); + assert!(error.to_string().contains("byte or nesting budget"), "{error}"); + assert!(rasterize_bounded(source.as_bytes(), 1.0, MAX_RASTER_PIXELS).is_err()); } } diff --git a/crates/io/src/svg/xml_reuse_tests.rs b/crates/io/src/svg/xml_reuse_tests.rs index dbf21c4984..fe3985b098 100644 --- a/crates/io/src/svg/xml_reuse_tests.rs +++ b/crates/io/src/svg/xml_reuse_tests.rs @@ -1,58 +1,42 @@ -use super::super as svg; -use super::*; +//! App-visible XML validation, rendering and omission contracts. Detailed repair +//! source projection and parse-count tests live with the shared SVG implementation. +use super as svg; +use super::tiny_skia; +use crate::IoError; +use craft_svg::tree::Limits; use std::sync::Arc; +const SVG_NS: &str = "http://www.w3.org/2000/svg"; +const XLINK_NS: &str = "http://www.w3.org/1999/xlink"; + fn empty_fonts() -> Arc { Arc::new(svg::usvg::fontdb::Database::new()) } -fn parse_count(run: impl FnOnce() -> T + Send) -> (T, usize) { - // The public parsers dispatch onto this worker on native targets. Reset and - // read its TLS there too; nested parser entry then reuses the same worker. - // on_svg_stack executes this closure directly on wasm. - svg::on_svg_stack(move || { - XML_PARSES.with(|count| count.set(0)); - let result = run(); - Ok((result, XML_PARSES.with(|count| count.get()))) - }) - .unwrap() -} - #[test] -fn unchanged_xml_is_borrowed_and_converted_with_one_checked_parse() { +fn unchanged_xml_keeps_ordinary_and_bounded_rendering() { let text = ""; - let limits = svg::tree_limits(svg::MAX_XML_DEPTH, svg::MAX_RASTER_PIXELS); - let (result, count) = parse_count(|| { - with_repaired_xml(text, &limits, |xml| { - assert_eq!(xml.input_text().as_ptr(), text.as_ptr(), "unchanged XML retains the caller's source"); - assert_eq!(xml.descendants().filter(|n| n.has_tag_name((SVG_NS, "rect"))).count(), 1); - Ok(()) - }) - }); - result.unwrap(); - assert_eq!(count, 1); - let (parsed, count) = parse_count(|| svg::parse_with(text.as_bytes(), empty_fonts)); - let parsed = parsed.unwrap(); - assert_eq!(count, 1, "the ordinary parser must not parse the checked XML again"); + let parsed = svg::parse_with(text.as_bytes(), empty_fonts).unwrap(); + assert_eq!(svg::omitted_image_count(parsed.image_usage), 0); let pixels = svg::render(&parsed.tree, 1.).unwrap(); assert_eq!(pixels.pixel(1, 1).unwrap().red(), 255); - let (parsed, count) = parse_count(|| svg::parse_bounded_inner_with(text.as_bytes(), 16, empty_fonts)); - parsed.unwrap(); - assert_eq!(count, 1, "bounded previews use the same checked-DOM path"); + svg::parse_bounded_inner_with(text.as_bytes(), 16, empty_fonts).unwrap(); } #[test] -fn repaired_xml_is_checked_again_and_keeps_warning_and_strict_contracts() { - let text = ""; - let (parsed, count) = parse_count(|| svg::parse_with(text.as_bytes(), empty_fonts)); - let parsed = parsed.unwrap(); - assert_eq!(count, 2, "repair reparses only the replacement, after checking the original"); - assert_eq!(parsed.image_usage.invalid_raster_images, 1); - assert_eq!(svg::render(&parsed.tree, 1.).unwrap().pixel(2, 2).unwrap().red(), 255); - let (pixels, warnings) = svg::rasterize_bounded_with_warnings(text.as_bytes(), 1., 16).unwrap(); - assert_eq!(pixels.get(2, 2), [1., 0., 0., 1.]); - assert_eq!(warnings.len(), 1); - assert!(svg::rasterize_bounded(text.as_bytes(), 1., 16).is_err()); +fn repaired_xml_keeps_warning_and_strict_contracts() { + for text in [ + "", + "]>", + ] { + let parsed = svg::parse_with(text.as_bytes(), empty_fonts).unwrap(); + assert_eq!(parsed.image_usage.invalid_raster_images, 1); + assert_eq!(svg::render(&parsed.tree, 1.).unwrap().pixel(2, 2).unwrap().red(), 255); + let (pixels, warnings) = svg::rasterize_bounded_with_warnings(text.as_bytes(), 1., 16).unwrap(); + assert_eq!(pixels.get(2, 2), [1., 0., 0., 1.]); + assert_eq!(warnings.len(), 1); + assert!(svg::rasterize_bounded(text.as_bytes(), 1., 16).is_err()); + } } #[test] @@ -69,93 +53,73 @@ fn original_xml_guards_run_before_repair_or_conversion() { (markup, Limits { refuse_entity_markup: true, ..Default::default() }), (referenced, Limits { tree_depth: 2, ..Default::default() }), ] { - let mut converted = false; - let result = with_repaired_xml(text, &limits, |_| { - converted = true; - Ok(()) - }); - assert!(result.is_err(), "guard must reject original XML: {text}"); - assert!(!converted, "an unchecked DOM must never reach conversion"); + assert!(craft_svg::tree::preflight(text, &limits).is_err(), "guard must reject original XML before conversion: {text}"); } let allowed = Limits { entity_bytes: 1024, ..Default::default() }; - with_repaired_xml(entity, &allowed, |xml| { - assert_eq!(xml.descendants().find(|n| n.has_tag_name("image")).unwrap().attribute("href"), Some(INVALID_IMAGE)); - Ok(()) - }) - .unwrap(); -} - -// Retain the previous public-library sequence solely as a timing control. Its -// outer inflate/depth/font/resolver setup, worker entry and usage snapshot match -// parse_with; only repair + check_document + shared parse_text differ. -fn prior_parse(bytes: &[u8]) -> Result { - let xml = svg::inflate(bytes)?; - let depth = svg::nesting_depth(&xml, svg::MAX_XML_DEPTH)?; - if depth > svg::MAX_XML_DEPTH { - return Err(IoError::Svg(format!("elements are nested more than {} levels deep", svg::MAX_XML_DEPTH))); - } - let has_text = xml.windows(4).any(|w| w == b"text"); - let fontdb = empty_fonts(); - let fontless_text = has_text && fontdb.faces().next().is_none(); - let text = std::str::from_utf8(&xml).map_err(|_| IoError::Svg("the SVG is not valid UTF-8".into()))?; - let limits = svg::tree_limits(svg::MAX_XML_DEPTH, svg::MAX_RASTER_PIXELS); - let resolver = Arc::new(craft_svg::tree::ImageResolver::new(limits)); - let state = Arc::new(std::sync::Mutex::new(svg::image_integrity::Integrity::new(svg::MAX_RASTER_PIXELS))); - resolver.set_document_depth(depth); - svg::parse_at_depth(depth, false, |isolated| { - let options = svg::options_with_isolation(fontdb, svg::MAX_XML_DEPTH.saturating_sub(depth), isolated, Arc::clone(&resolver), Arc::clone(&state)); - let repaired = repair(text, &limits)?; - resolver.check_document(&repaired).map_err(svg::svg_parse_error)?; - let tree = svg::guarded_parse(|| craft_svg::tree::parse_text(&repaired, &limits, &options))?.map_err(svg::svg_parse_error)?; - let image_usage = state.lock().unwrap_or_else(std::sync::PoisonError::into_inner).usage(resolver.usage())?; - Ok(svg::Parsed { tree, fontless_text, image_usage }) - }) - .map_err(IoError::from) + assert!(craft_svg::tree::preflight(entity, &allowed).is_ok(), "bounded entity expansion remains admitted"); } #[test] -#[ignore = "release-only XML and 24 MP embedded-source timing probe"] -fn xml_reuse_and_24mp_source_timing() { - use std::time::Instant; - let image = photocraft_codecs::Image::from_u8(6000, 4000, photocraft_codecs::ChannelLayout::Rgb, [17, 83, 149].repeat(24_000_000)).unwrap(); - let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); - drop(image); - let mut href = String::from("data:image/png,"); - for byte in png { - use std::fmt::Write; - write!(&mut href, "%{byte:02X}").unwrap(); - } - let embedded = format!(""); - let mut xml = format!(""); - for _ in 0..20_000 { - xml.push_str(""); - } - xml.push_str(""); - for (name, text) in [("xml-20000-nodes", xml), ("png-24mp", embedded)] { - let mut expected = None; - for old in [false, true, false] { - let started = Instant::now(); - let parsed = if old { prior_parse(text.as_bytes()).unwrap() } else { svg::parse_with(text.as_bytes(), empty_fonts).unwrap() }; - let elapsed = started.elapsed(); - assert!(!parsed.fontless_text); - assert_eq!(svg::omitted_image_count(parsed.image_usage), 0); - assert_eq!(parsed.image_usage.raster_pixels, if name == "png-24mp" { 24_000_000 } else { 0 }); - let rendered = svg::render(&parsed.tree, 1.).unwrap(); - let checksum: u64 = rendered.data().iter().map(|b| u64::from(*b)).sum(); - if let Some(previous) = expected { - assert_eq!(checksum, previous); - } else { - expected = Some(checksum); - } - assert_eq!((rendered.width(), rendered.height()), (16, 16)); - eprintln!("{name} {} parse_ms={:.3} output_checksum={checksum}", if old { "prior" } else { "reuse" }, elapsed.as_secs_f64() * 1000.); +fn checked_xml_conversion_panic_is_an_isolation_failure() { + let result: Result<(), IoError> = svg::guarded_parse(|| panic!("injected XML conversion panic")); + assert!(matches!(result, Err(IoError::Svg(message)) if message.contains("bounded SVG worker failed"))); +} + +#[test] +fn long_attribute_spacing_preserves_artwork_and_discloses_only_used_images() { + for spacing in [" ".repeat(300), " \t\n\r".repeat(300)] { + for attribute in ["href", "x:href"] { + let text = format!( + "" + ); + let (pixels, warnings) = svg::rasterize_bounded_with_warnings(text.as_bytes(), 1., 16).unwrap(); + assert_eq!(pixels.get(2, 2), [1., 0., 0., 1.]); + assert_eq!(warnings.len(), 1); + assert!(svg::rasterize_bounded(text.as_bytes(), 1., 16).is_err()); + let hidden = text.replace(", IoError> = svg::guarded_parse(|| with_repaired_xml("", &limits, |_| panic!("injected XML conversion panic"))); - assert!(matches!(result, Err(IoError::Svg(message)) if message.contains("bounded SVG worker failed"))); +fn many_mime_parameters_preserve_valid_pixels_and_invalid_image_omissions() { + let mut image = tiny_skia::Pixmap::new(1, 1).unwrap(); + image.fill(tiny_skia::Color::from_rgba8(0, 255, 0, 255)); + let body = base64(&image.encode_png().unwrap()); + let parameters = ";p=x".repeat(100); + let drawing = |body: &str| { + format!( + "" + ) + }; + let text = drawing(&body); + let (pixels, warnings) = svg::rasterize_bounded_with_warnings(text.as_bytes(), 1., 16).unwrap(); + assert!(warnings.is_empty()); + assert_eq!(pixels.get(0, 0), [0., 1., 0., 1.]); + assert_eq!(pixels.get(2, 2), [1., 0., 0., 1.]); + assert!(svg::rasterize_bounded(text.as_bytes(), 1., 16).is_ok()); + let text = drawing("A"); + let (pixels, warnings) = svg::rasterize_bounded_with_warnings(text.as_bytes(), 1., 16).unwrap(); + assert_eq!(pixels.get(2, 2), [1., 0., 0., 1.]); + assert_eq!(warnings.len(), 1); + assert!(svg::rasterize_bounded(text.as_bytes(), 1., 16).is_err()); +} + +/// Test-only RFC4648 encoding, keeping the real base64 image path covered without +/// adding a dependency for fixture construction. +fn base64(bytes: &[u8]) -> String { + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut result = String::new(); + for chunk in bytes.chunks(3) { + let a = chunk[0]; + let b = chunk.get(1).copied().unwrap_or(0); + let c = chunk.get(2).copied().unwrap_or(0); + result.push(char::from(ALPHABET[usize::from(a >> 2)])); + result.push(char::from(ALPHABET[usize::from((a & 3) << 4 | b >> 4)])); + result.push(if chunk.len() > 1 { char::from(ALPHABET[usize::from((b & 15) << 2 | c >> 6)]) } else { '=' }); + result.push(if chunk.len() > 2 { char::from(ALPHABET[usize::from(c & 63)]) } else { '=' }); + } + result } From 9e0e5f680f2ef70ba84df5d047546168808ac20c Mon Sep 17 00:00:00 2001 From: Terra854 Date: Tue, 17 Nov 2026 19:17:33 +0800 Subject: [PATCH 05/85] Pin the validated shared SVG API and document parser guard --- Cargo.lock | 30 +++++++++++++++--------------- Cargo.toml | 2 +- crates/io/src/svg/decoder_edges.rs | 2 +- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e602c4abf3..d2b97d8bc4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1379,7 +1379,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a#f32b47a1d4799269b7e4b99bb130161dcb7b312a" +source = "git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3#96dd8c4e0996b3d85edf5c98070c261892ac30f3" dependencies = [ "rayon", ] @@ -1472,12 +1472,12 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a#f32b47a1d4799269b7e4b99bb130161dcb7b312a" +source = "git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3#96dd8c4e0996b3d85edf5c98070c261892ac30f3" dependencies = [ "craft-dds", - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a)", + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3)", "crc32fast", "exr", "flate2", @@ -1525,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a#f32b47a1d4799269b7e4b99bb130161dcb7b312a" +source = "git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3#96dd8c4e0996b3d85edf5c98070c261892ac30f3" dependencies = [ "thiserror 2.0.21", ] @@ -1563,11 +1563,11 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a#f32b47a1d4799269b7e4b99bb130161dcb7b312a" +source = "git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3#96dd8c4e0996b3d85edf5c98070c261892ac30f3" dependencies = [ "brotli-decompressor 6.3.1", "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3)", "quick-xml 0.41.0", "serde", ] @@ -1771,10 +1771,10 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a#f32b47a1d4799269b7e4b99bb130161dcb7b312a" +source = "git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3#96dd8c4e0996b3d85edf5c98070c261892ac30f3" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3)", "data-url", "flate2", "gif", @@ -1817,7 +1817,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a#f32b47a1d4799269b7e4b99bb130161dcb7b312a" +source = "git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3#96dd8c4e0996b3d85edf5c98070c261892ac30f3" dependencies = [ "serde", "thiserror 2.0.21", @@ -1900,7 +1900,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a#f32b47a1d4799269b7e4b99bb130161dcb7b312a" +source = "git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3#96dd8c4e0996b3d85edf5c98070c261892ac30f3" dependencies = [ "quick-xml 0.41.0", "serde", @@ -5620,7 +5620,7 @@ dependencies = [ "craft-cms", "craft-flags", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", - "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3)", "craft-update", "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "dispatch2", @@ -5897,7 +5897,7 @@ dependencies = [ "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5e2bc54a48c9f03e7ce4eca42775ce5cc051f5d6)", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b9c22554ce0fd2caccdb53b417082a2ff2ef178f)", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eafb50aff3c6b1acc14dff53060157877e3e4fce)", - "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f32b47a1d4799269b7e4b99bb130161dcb7b312a)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3)", "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-xcf", "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", diff --git a/Cargo.toml b/Cargo.toml index a9ac4625b0..b2b7fa5f90 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -62,7 +62,7 @@ craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "f32b47a1d4799269b7e4b99bb130161dcb7b312a", features = ["tree-render", "tree-render-system-fonts"] } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "96dd8c4e0996b3d85edf5c98070c261892ac30f3", features = ["tree-render", "tree-render-system-fonts"] } craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } # Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563. diff --git a/crates/io/src/svg/decoder_edges.rs b/crates/io/src/svg/decoder_edges.rs index 0a12d81eee..894e25e24f 100644 --- a/crates/io/src/svg/decoder_edges.rs +++ b/crates/io/src/svg/decoder_edges.rs @@ -17,7 +17,7 @@ pub(crate) struct LockGraph { } impl LockGraph { pub(crate) fn parse(text: &str) -> Self { - let lock: toml::Value = text.parse().unwrap(); + let lock: toml::Value = toml::from_str(text).unwrap(); let packages = lock .get("package") .unwrap() From ad075ffc76acd6ef7393285eae6d091bb89c2c80 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Tue, 17 Nov 2026 19:34:40 +0800 Subject: [PATCH 06/85] Cover canonical Git edges and valid SVG MIME headers --- crates/io/src/svg/decoder_edges.rs | 55 ++++++++++++++++++- .../io/src/svg/optional_image_review_tests.rs | 31 ++++++++++- 2 files changed, 82 insertions(+), 4 deletions(-) diff --git a/crates/io/src/svg/decoder_edges.rs b/crates/io/src/svg/decoder_edges.rs index 894e25e24f..ea3d4b5623 100644 --- a/crates/io/src/svg/decoder_edges.rs +++ b/crates/io/src/svg/decoder_edges.rs @@ -15,6 +15,12 @@ struct Package { pub(crate) struct LockGraph { packages: Vec, } +// Cargo dependency edges may omit the resolved Git fragment even though the +// selected package ID always records it. Other source identities stay exact. +fn source_matches(edge: &str, package: Option<&str>) -> bool { + let Some(package) = package else { return false }; + if edge.starts_with("git+") && !edge.contains('#') { package.split_once('#').map_or(package, |(base, _)| base) == edge } else { package == edge } +} impl LockGraph { pub(crate) fn parse(text: &str) -> Self { let lock: toml::Value = toml::from_str(text).unwrap(); @@ -52,7 +58,7 @@ impl LockGraph { let found: Vec<_> = self .packages .iter() - .filter(|p| p.id.name == name && version.is_none_or(|v| p.id.version == v) && source.is_none_or(|s| p.id.source.as_deref() == Some(s))) + .filter(|p| p.id.name == name && version.is_none_or(|v| p.id.version == v) && source.is_none_or(|s| source_matches(s, p.id.source.as_deref()))) .collect(); assert_eq!(found.len(), 1, "ambiguous or absent resolved edge {} from {from:?}", edges[0]); found[0].id.clone() @@ -101,3 +107,50 @@ dependencies = ["codec"] assert_eq!(selected.source.as_deref(), Some("registry+one")); assert!(std::panic::catch_unwind(|| graph.dependency(&graph.workspace_package("other"), "codec")).is_err()); } + +#[test] +fn git_edges_resolve_full_package_ids_and_reject_canonical_ambiguity() { + let fixture = |second: bool| { + let mut text = String::from( + r#" +[[package]] +name = "consumer" +version = "1" +dependencies = ["codec 1 (git+https://example.invalid/codecs?rev=chosen)"] +[[package]] +name = "explicit" +version = "1" +dependencies = ["codec 1 (git+https://example.invalid/codecs?rev=chosen#aaaa)"] +[[package]] +name = "wrong" +version = "1" +dependencies = ["codec 1 (git+https://example.invalid/codecs?rev=chosen#cccc)"] +[[package]] +name = "codec" +version = "1" +source = "git+https://example.invalid/codecs?rev=chosen#aaaa" +"#, + ); + if second { + text.push_str( + r#" +[[package]] +name = "codec" +version = "1" +source = "git+https://example.invalid/codecs?rev=chosen#bbbb" +"#, + ); + } + LockGraph::parse(&text) + }; + let unique = fixture(false); + let selected = unique.dependency(&unique.workspace_package("consumer"), "codec"); + assert_eq!(selected.source.as_deref(), Some("git+https://example.invalid/codecs?rev=chosen#aaaa")); + assert_eq!(selected, unique.dependency(&unique.workspace_package("explicit"), "codec")); + assert!(std::panic::catch_unwind(|| unique.dependency(&unique.workspace_package("wrong"), "codec")).is_err()); + let ambiguous = fixture(true); + assert!(std::panic::catch_unwind(|| ambiguous.dependency(&ambiguous.workspace_package("consumer"), "codec")).is_err()); + assert_eq!(selected, ambiguous.dependency(&ambiguous.workspace_package("explicit"), "codec")); + assert!(!source_matches("registry+one", Some("registry+one#aaaa")), "registry sources remain exact"); + assert!(!source_matches("git+https://example.invalid/codecs?rev=other", selected.source.as_deref()), "requested Git revision remains part of the identity"); +} diff --git a/crates/io/src/svg/optional_image_review_tests.rs b/crates/io/src/svg/optional_image_review_tests.rs index 5cbded4da0..2f09d3c872 100644 --- a/crates/io/src/svg/optional_image_review_tests.rs +++ b/crates/io/src/svg/optional_image_review_tests.rs @@ -465,18 +465,43 @@ fn malformed_data_urls_and_broken_pixel_payloads_are_disclosed_before_rendering( } #[test] -fn excessive_mime_parameters_are_disclosed_only_for_used_image_resources() { +fn excessive_mime_parameters_preserve_valid_images_and_disclose_only_real_failures() { + fn assert_complete_green_image(text: &str) { + for bytes in [text.as_bytes().to_vec(), gzip(text.as_bytes())] { + let imported = crate::import("valid.svg", &bytes).unwrap(); + assert_no_omission_or_unexpected_import_warning(&imported); + assert_eq!(photocraft_compose::flatten(&imported.document).get(1, 1), [0., 1., 0., 1.]); + let strict = import_svg_bounded_images_strict("valid.svg", &bytes, MAX_RASTER_PIXELS).unwrap(); + assert_no_omission_or_unexpected_import_warning(&strict); + assert_eq!(photocraft_compose::flatten(&strict.document).get(1, 1), [0., 1., 0., 1.]); + import_svg_preview_with_work("valid.svg", &bytes, MAX_RASTER_PIXELS).unwrap(); + let (pixels, warnings) = rasterize_bounded_with_warnings(&bytes, 1., MAX_RASTER_PIXELS).unwrap(); + assert!(warnings.is_empty()); + assert_eq!(pixels.get(1, 1), [0., 1., 0., 1.]); + assert_eq!(rasterize_bounded(&bytes, 1., MAX_RASTER_PIXELS).unwrap().get(1, 1), [0., 1., 0., 1.]); + assert_eq!(rasterize(&bytes, 1.).unwrap().get(1, 1), [0., 1., 0., 1.]); + let (width, height, pixels) = rasterize_rgba8(&bytes).unwrap(); + assert_eq!((width, height), (2, 2)); + assert_eq!(pixels, [0, 255, 0, 255].repeat(4)); + } + } let parameters = (0..65).map(|index| format!(";p{index}=x")).collect::(); let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap(); let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); for essence in ["image/png", "text/plain", ""] { let href = url(&format!("{essence}{parameters}"), &png); let text = drawing(&href); - assert_incomplete_image_is_disclosed(&text); + assert_complete_green_image(&text); for child in [text.as_bytes().to_vec(), gzip(text.as_bytes())] { - assert_incomplete_image_is_disclosed(&drawing(&url("image/svg+xml", &child))); + assert_complete_green_image(&drawing(&url("image/svg+xml", &child))); + } + // Header compaction cannot turn a malformed base64 body or a missing + // delimiter into a valid image, including default text/plain MIME. + for href in [format!("data:{essence}{parameters};base64,A"), format!("data:{essence}{parameters};base64")] { + assert_incomplete_image_is_disclosed(&drawing(&href)); } } + assert_incomplete_image_is_disclosed(&drawing(&url(&format!("image/unsupported{parameters}"), &png))); let href = format!("data:application/octet-stream{parameters};base64,AA=="); assert_ignored_data_image_stays_quiet(&drawing(&href)); let image = url(&format!("image/png{parameters}"), &png); From 05e97d9fe9ae9dfb869bdc94639d927aa741888f Mon Sep 17 00:00:00 2001 From: Terra854 Date: Tue, 17 Nov 2026 20:12:43 +0800 Subject: [PATCH 07/85] Preserve accepted SVG depth boundaries through the shared API --- Cargo.lock | 30 +++++++++++++++--------------- Cargo.toml | 2 +- crates/io/tests/it/svg.rs | 6 ++++++ 3 files changed, 22 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d2b97d8bc4..3f42ec6a90 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1379,7 +1379,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3#96dd8c4e0996b3d85edf5c98070c261892ac30f3" +source = "git+https://github.com/storytold/craft-libs?rev=fcafab33d9fedbefb0992d7776db3b6ae8b918f6#fcafab33d9fedbefb0992d7776db3b6ae8b918f6" dependencies = [ "rayon", ] @@ -1472,12 +1472,12 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3#96dd8c4e0996b3d85edf5c98070c261892ac30f3" +source = "git+https://github.com/storytold/craft-libs?rev=fcafab33d9fedbefb0992d7776db3b6ae8b918f6#fcafab33d9fedbefb0992d7776db3b6ae8b918f6" dependencies = [ "craft-dds", - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3)", + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fcafab33d9fedbefb0992d7776db3b6ae8b918f6)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fcafab33d9fedbefb0992d7776db3b6ae8b918f6)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fcafab33d9fedbefb0992d7776db3b6ae8b918f6)", "crc32fast", "exr", "flate2", @@ -1525,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3#96dd8c4e0996b3d85edf5c98070c261892ac30f3" +source = "git+https://github.com/storytold/craft-libs?rev=fcafab33d9fedbefb0992d7776db3b6ae8b918f6#fcafab33d9fedbefb0992d7776db3b6ae8b918f6" dependencies = [ "thiserror 2.0.21", ] @@ -1563,11 +1563,11 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3#96dd8c4e0996b3d85edf5c98070c261892ac30f3" +source = "git+https://github.com/storytold/craft-libs?rev=fcafab33d9fedbefb0992d7776db3b6ae8b918f6#fcafab33d9fedbefb0992d7776db3b6ae8b918f6" dependencies = [ "brotli-decompressor 6.3.1", "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fcafab33d9fedbefb0992d7776db3b6ae8b918f6)", "quick-xml 0.41.0", "serde", ] @@ -1771,10 +1771,10 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3#96dd8c4e0996b3d85edf5c98070c261892ac30f3" +source = "git+https://github.com/storytold/craft-libs?rev=fcafab33d9fedbefb0992d7776db3b6ae8b918f6#fcafab33d9fedbefb0992d7776db3b6ae8b918f6" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fcafab33d9fedbefb0992d7776db3b6ae8b918f6)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fcafab33d9fedbefb0992d7776db3b6ae8b918f6)", "data-url", "flate2", "gif", @@ -1817,7 +1817,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3#96dd8c4e0996b3d85edf5c98070c261892ac30f3" +source = "git+https://github.com/storytold/craft-libs?rev=fcafab33d9fedbefb0992d7776db3b6ae8b918f6#fcafab33d9fedbefb0992d7776db3b6ae8b918f6" dependencies = [ "serde", "thiserror 2.0.21", @@ -1900,7 +1900,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3#96dd8c4e0996b3d85edf5c98070c261892ac30f3" +source = "git+https://github.com/storytold/craft-libs?rev=fcafab33d9fedbefb0992d7776db3b6ae8b918f6#fcafab33d9fedbefb0992d7776db3b6ae8b918f6" dependencies = [ "quick-xml 0.41.0", "serde", @@ -5620,7 +5620,7 @@ dependencies = [ "craft-cms", "craft-flags", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", - "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fcafab33d9fedbefb0992d7776db3b6ae8b918f6)", "craft-update", "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "dispatch2", @@ -5897,7 +5897,7 @@ dependencies = [ "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5e2bc54a48c9f03e7ce4eca42775ce5cc051f5d6)", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b9c22554ce0fd2caccdb53b417082a2ff2ef178f)", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eafb50aff3c6b1acc14dff53060157877e3e4fce)", - "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=96dd8c4e0996b3d85edf5c98070c261892ac30f3)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fcafab33d9fedbefb0992d7776db3b6ae8b918f6)", "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", "craft-xcf", "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a)", diff --git a/Cargo.toml b/Cargo.toml index b2b7fa5f90..9cae72c981 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -62,7 +62,7 @@ craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "96dd8c4e0996b3d85edf5c98070c261892ac30f3", features = ["tree-render", "tree-render-system-fonts"] } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "fcafab33d9fedbefb0992d7776db3b6ae8b918f6", features = ["tree-render", "tree-render-system-fonts"] } craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" } # Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563. diff --git a/crates/io/tests/it/svg.rs b/crates/io/tests/it/svg.rs index e8e8e90a71..baf96f0047 100644 --- a/crates/io/tests/it/svg.rs +++ b/crates/io/tests/it/svg.rs @@ -403,6 +403,12 @@ fn deeply_nested_embedded_svg_is_dropped_not_a_stack_overflow() { // drawing still renders (its rect is black). let r = open(&embed(&base64_data_url("image/svg+xml", nested(svg::MAX_XML_DEPTH - 2).as_bytes()))); assert!(close(px(&r.document, 4, 4), [0.0, 0.0, 0.0, 1.0]), "{:?}", px(&r.document, 4, 4)); + // One more child level fits in isolation, but exceeds the shared + // allowance once the outer drawing's ancestor is included. + let beyond = nested(svg::MAX_XML_DEPTH - 1); + let r = open(&embed(&base64_data_url("image/svg+xml", beyond.as_bytes()))); + assert!(close(px(&r.document, 4, 4), [0.0; 4]), "over-limit child must remain transparent: {:?}", px(&r.document, 4, 4)); + assert!(r.warnings.iter().any(|warning| warning.contains("omitted")), "over-limit child must be disclosed: {:?}", r.warnings); }) .unwrap() .join() From 314ee982a288e5487429f53147d5c4a54cc1ed5c Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 16:10:25 +0000 Subject: [PATCH 08/85] Pin craft-libs next 427c816db: the full colour picker in Photoshop's arrangement --- Cargo.lock | 154 +++++++++++++++++++-------------------- Cargo.toml | 70 +++++++++--------- crates/engine/Cargo.toml | 2 +- 3 files changed, 113 insertions(+), 113 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 29bb8647a1..4ebc72b812 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1365,7 +1365,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-automation", "craft-behavior", @@ -1403,7 +1403,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "crc32fast", "flate2", @@ -1424,7 +1424,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "rustix 1.1.5", ] @@ -1432,7 +1432,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "base64 0.22.1", "craft-ai-agents", @@ -1458,7 +1458,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1474,7 +1474,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-docpath", @@ -1492,7 +1492,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "md-5", "rayon", @@ -1501,7 +1501,7 @@ dependencies = [ [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-cms", @@ -1521,7 +1521,7 @@ dependencies = [ [[package]] name = "craft-crs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-metadata", "craft-xml", @@ -1531,7 +1531,7 @@ dependencies = [ [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "thiserror 2.0.21", ] @@ -1539,7 +1539,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "rayon", ] @@ -1547,7 +1547,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "block2 0.6.2", "craft-atomic", @@ -1570,7 +1570,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "serde", ] @@ -1578,7 +1578,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1597,12 +1597,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" [[package]] name = "craft-file-formats" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-eps", "craft-idml", @@ -1620,7 +1620,7 @@ dependencies = [ [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-atomic", "dirs", @@ -1630,7 +1630,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1645,7 +1645,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1664,7 +1664,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "cap-primitives", "craft-atomic", @@ -1685,12 +1685,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" [[package]] name = "craft-heif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "heic-rs", "rayon", @@ -1699,7 +1699,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1712,7 +1712,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "chrono", "fixed_decimal", @@ -1740,7 +1740,7 @@ dependencies = [ [[package]] name = "craft-idml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-xml", "craft-zip", @@ -1750,7 +1750,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-dds", "craft-heif", @@ -1778,7 +1778,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1796,7 +1796,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "thiserror 2.0.21", ] @@ -1804,7 +1804,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-host", "craft-i18n", @@ -1817,7 +1817,7 @@ dependencies = [ [[package]] name = "craft-kra" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-xml", "craft-zip", @@ -1827,7 +1827,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-i18n", @@ -1841,7 +1841,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-host", @@ -1859,7 +1859,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1871,7 +1871,7 @@ dependencies = [ [[package]] name = "craft-ora" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-xml", "craft-zip", @@ -1881,7 +1881,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-text", @@ -1895,7 +1895,7 @@ dependencies = [ [[package]] name = "craft-pcraft-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "blake3", "craft-atomic", @@ -1908,7 +1908,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "flate2", "serde", @@ -1919,7 +1919,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "bytemuck", "flate2", @@ -1934,7 +1934,7 @@ dependencies = [ [[package]] name = "craft-pdn" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1943,7 +1943,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "async-channel", "async-io", @@ -1969,7 +1969,7 @@ dependencies = [ [[package]] name = "craft-plist" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "thiserror 2.0.21", ] @@ -1977,7 +1977,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-ui", @@ -1995,7 +1995,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "encoding_rs", "flate2", @@ -2006,7 +2006,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "dispatch2", "egui", @@ -2017,7 +2017,7 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "chrono", "craft-crw", @@ -2035,7 +2035,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-host", @@ -2052,7 +2052,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-atomic", "craft-host", @@ -2066,7 +2066,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2085,7 +2085,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-keymap", @@ -2097,7 +2097,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2120,7 +2120,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "bitflags 2.13.2", "ecolor", @@ -2133,7 +2133,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-atomic", "craft-behavior", @@ -2148,7 +2148,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "serde", "thiserror 2.0.21", @@ -2157,7 +2157,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "serde", "thiserror 2.0.21", @@ -2166,7 +2166,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-keymap", @@ -2181,7 +2181,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-ui-canvas", "craft-ui-contract", @@ -2194,7 +2194,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-i18n", @@ -2210,7 +2210,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "accesskit", "craft-behavior", @@ -2244,7 +2244,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2255,7 +2255,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-host", @@ -2273,7 +2273,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-host", @@ -2294,7 +2294,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-host", @@ -2313,7 +2313,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-behavior", "craft-host", @@ -2330,7 +2330,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "chrono", "craft-host", @@ -2359,7 +2359,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "winsafe", ] @@ -2367,7 +2367,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "craft-atomic", "craft-behavior", @@ -2397,7 +2397,7 @@ dependencies = [ [[package]] name = "craft-xcf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2406,7 +2406,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2416,7 +2416,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "flate2", "thiserror 2.0.21", @@ -3879,7 +3879,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "bytemuck", "hayro-interpret", @@ -3909,7 +3909,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3927,7 +3927,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3951,7 +3951,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "flate2", "hayro-ccitt", @@ -5035,7 +5035,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -11094,14 +11094,14 @@ source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1c [[patch.unused]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" [[patch.unused]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" [[patch.unused]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9#a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" +source = "git+https://github.com/storytold/craft-libs?rev=427c816db0ac8c72f3ba052086f642ed1be398fe#427c816db0ac8c72f3ba052086f642ed1be398fe" diff --git a/Cargo.toml b/Cargo.toml index b2ddec2a66..d0e009ee6e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,19 +12,19 @@ rust-version = "1.95" [workspace.dependencies] # The craft framework through its facade (`craft::ui::…`). The egui `[patch]` below must match # `craft::egui_fork::REV` (checked by `cargo xtask ci`). -craft = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } # internal photocraft-geom = { path = "crates/geom" } photocraft-color = { path = "crates/color" } photocraft-raster = { path = "crates/raster" } photocraft-doc = { path = "crates/doc" } photocraft-ops = { path = "crates/ops" } -craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } +craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } photocraft-raw = { path = "crates/raw" } -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } photocraft-compose = { path = "crates/compose" } photocraft-gpu = { path = "crates/gpu" } photocraft-paint = { path = "crates/paint" } @@ -43,33 +43,33 @@ photocraft-ipp = { path = "crates/ipp" } # external # ICC colour management: the shared crate (replaces crates/cms; craft-libs#779). -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } # HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784). -craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9", features = ["raster", "write-raster"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9", features = ["tree-render", "tree-render-system-fonts"] } -craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe", features = ["raster", "write-raster"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe", features = ["tree-render", "tree-render-system-fonts"] } +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } # Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563. -craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } +craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } # Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n # catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at # the commit in `craft-i18n.rev`). Already in the tree through craft. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9", features = ["ui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe", features = ["ui"] } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" @@ -249,14 +249,14 @@ opt-level = 3 # Keep the complete egui family and native event bridge on reviewed fork commits. [patch.crates-io] -krilla = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -hayro = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } emath = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } epaint = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 8825357772..025e93a76c 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -16,7 +16,7 @@ photocraft-geom = { workspace = true } photocraft-color = { workspace = true } craft-cms = { workspace = true } # PCTIP codec from craft-libs#1564; isolated pin until the shared revision is adopted workspace-wide. -craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } +craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "427c816db0ac8c72f3ba052086f642ed1be398fe" } photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-ops = { workspace = true } From 12c9bd6a5fe110878ee393085a62472a1baf36d9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 18:04:42 +0000 Subject: [PATCH 09/85] Image Size test: Width and Height show their values and their unit selects (#15483) --- crates/ui-egui/src/dialogs/sizing/tests.rs | 41 ++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/crates/ui-egui/src/dialogs/sizing/tests.rs b/crates/ui-egui/src/dialogs/sizing/tests.rs index dfbf00aac8..9dbecb6f4f 100644 --- a/crates/ui-egui/src/dialogs/sizing/tests.rs +++ b/crates/ui-egui/src/dialogs/sizing/tests.rs @@ -174,3 +174,44 @@ fn the_image_size_readout_counts_the_flat_image() { assert_eq!(bpp(json!({"width": 4, "height": 4}), &["image.mode.indexedColor"]), 1.0); assert_eq!(bpp(json!({"width": 4, "height": 4}), &["image.mode.grayscale", "image.mode.bitmap"]), 1.0 / 8.0); } + +/// #15483: Image Size on a 1600 x 1000 px document, opened as the menu opens it and drawn in the whole app, shows its +/// Width and Height with their values and the Pixels unit; editing the Width with Constrain on moves the Height. +#[test] +fn image_size_draws_width_and_height_with_values_and_unit() { + use egui::vec2; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).with_max_steps(8).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 1600, "height": 1000, "resolution": 72})).unwrap(); + PhotocraftApp::with_context(cc.egui_ctx.clone(), s, crate::Services::default()) + }); + h.run_steps(4); + open(h.state_mut(), "image.imageSize").expect("a document is open"); + h.run_steps(6); + + let value_of = |h: &Harness<'static, PhotocraftApp>, label: &str| -> Vec { + h.query_all_by_label(label).filter_map(|n| n.accesskit_node().value().map(|v| v.to_string())).collect() + }; + for (label, want) in [("Width", "1600"), ("Height", "1000"), ("Resolution", "72")] { + let shown = value_of(&h, label); + assert!(shown.iter().any(|v| v == want), "{label} shows {want}: {shown:?}"); + } + let pixels = h.query_all_by_label("Pixels").count(); + assert!(pixels >= 2, "the Width and Height unit selects show Pixels ({pixels} nodes)"); + + let width = h.query_all_by_label("Width").find(|n| n.accesskit_node().value().is_some()).expect("the Width field"); + width.click(); + h.run_steps(2); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(2); + h.get_all_by_label("Width").find(|n| n.accesskit_node().value().is_some()).expect("the Width field").type_text("800"); + h.run_steps(2); + h.key_press(egui::Key::Tab); + h.run_steps(4); + assert!(value_of(&h, "Width").iter().any(|v| v == "800"), "Width: {:?}", value_of(&h, "Width")); + assert!(value_of(&h, "Height").iter().any(|v| v == "500"), "Height follows: {:?}", value_of(&h, "Height")); +} From 62d928f97d0026beeb30edc5ecf4f38c38dd431a Mon Sep 17 00:00:00 2001 From: Terra854 Date: Wed, 18 Nov 2026 02:43:00 +0800 Subject: [PATCH 10/85] Assert save-back warning tone with shared notices --- crates/ui-egui/src/smart_svg_ui/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/smart_svg_ui/tests.rs b/crates/ui-egui/src/smart_svg_ui/tests.rs index 3642524cce..fb05c079d2 100644 --- a/crates/ui-egui/src/smart_svg_ui/tests.rs +++ b/crates/ui-egui/src/smart_svg_ui/tests.rs @@ -586,7 +586,7 @@ fn embedded_ai_link_table_handoff_preserves_source_until_saved_and_undo_restores assert_eq!(app.ui.notices.len(), 1); let notice = &app.ui.notices[0]; assert!(notice.title.contains("Vector"), "{notice:?}"); - assert!(!notice.error); + assert_eq!(notice.tone, craft::theme::variant::Tone::Neutral); assert!(notice.lines.iter().any(|line| line.contains("nothing to draw"))); let layer = app.session.active().unwrap().doc.layer(id).unwrap(); assert!( @@ -682,7 +682,7 @@ fn external_svg_save_back_reports_omissions_once_and_keeps_silent_updates_quiet( assert_eq!(app.ui.notices.len(), 1); assert!(app.ui.notices[0].title.contains("SVG")); assert!(app.ui.notices[0].lines.iter().any(|line| line.contains("embedded") && line.contains("omitted"))); - assert!(!app.ui.notices[0].error); + assert_eq!(app.ui.notices[0].tone, craft::theme::variant::Tone::Neutral); } else { assert!(app.ui.notices.is_empty(), "{:?}", app.ui.notices); } From ba146351ed29c95eaffd6b92e7006254f4bfa2a3 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Wed, 18 Nov 2026 03:05:00 +0800 Subject: [PATCH 11/85] Match the SVG parser refusal directly in the guard test --- crates/io/src/svg/xml_reuse_tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/io/src/svg/xml_reuse_tests.rs b/crates/io/src/svg/xml_reuse_tests.rs index 1b53d8c440..e23c8830c1 100644 --- a/crates/io/src/svg/xml_reuse_tests.rs +++ b/crates/io/src/svg/xml_reuse_tests.rs @@ -49,7 +49,9 @@ fn original_xml_guards_run_before_repair_or_conversion() { write!(attributes, " a{index}='x'").unwrap(); } let rejected = format!("{opening}{image}"); - let error = svg::parse_with(rejected.as_bytes(), empty_fonts).err().expect("original attribute limits must apply before URL repair"); + let Err(error) = svg::parse_with(rejected.as_bytes(), empty_fonts) else { + panic!("original attribute limits must apply before URL repair"); + }; assert!(error.to_string().contains("attribute"), "{error}"); let accepted = format!( From e0c855296d0978628ed62c41f4f6ec48f0fa198e Mon Sep 17 00:00:00 2001 From: Terra854 Date: Wed, 18 Nov 2026 03:34:57 +0800 Subject: [PATCH 12/85] Load fonts for text in embedded SVG images --- crates/io/src/svg.rs | 63 ++++++++++++++++++++------------------ crates/io/src/svg/tests.rs | 40 ++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 30 deletions(-) diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index d806c88074..5830316088 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -302,18 +302,25 @@ fn fallback_face(c: char, used: &[usvg::fontdb::ID], db: &usvg::fontdb::Database .map(|f| f.id) } -/// usvg's font choice, with the chosen faces read from memory ([`in_memory`]). -fn font_resolver() -> usvg::FontResolver<'static> { +/// Load the same fonts for top-level and embedded text. usvg requests them only +/// when it shapes text, including text hidden inside an encoded image URL. +fn font_resolver(loaded: &OnceLock>, load: fn() -> Arc) -> usvg::FontResolver<'_> { + let mut resolver = usvg::FontResolver::default(); + let select = resolver.select_font; + resolver.select_font = Box::new(move |font, db| { + if db.faces().next().is_none() { + *db = Arc::clone(loaded.get_or_init(load)); + } + let id = select(font, db)?; + #[cfg(not(target_arch = "wasm32"))] + let id = in_memory(id, db); + Some(id) + }); #[cfg(not(target_arch = "wasm32"))] { - let select = usvg::FontResolver::default_font_selector(); - usvg::FontResolver { - select_font: Box::new(move |font, db| select(font, db).map(|id| in_memory(id, db))), - select_fallback: Box::new(|c, used, db| fallback_face(c, used, db).map(|id| in_memory(id, db))), - } + resolver.select_fallback = Box::new(|c, used, db| fallback_face(c, used, db).map(|id| in_memory(id, db))); } - #[cfg(target_arch = "wasm32")] - usvg::FontResolver::default() + resolver } #[cfg(not(target_arch = "wasm32"))] @@ -383,8 +390,17 @@ fn parse_at_depth(depth: usize, parse: impl FnOnce() -> Result) -> usvg::Options<'static> { - usvg::Options { resources_dir: None, fontdb, font_resolver: font_resolver(), ..usvg::Options::default() } +fn parse_checked_svg( + text: &str, + resolver: &craft_svg::tree::ValidatedImageResolver, + load_fonts: fn() -> Arc, +) -> Result<(usvg::Tree, bool), IoError> { + let checked = craft_svg::tree::preflight(text, &resolver.limits()).map_err(svg_parse_error)?; + let loaded = OnceLock::new(); + let options = usvg::Options { resources_dir: None, font_resolver: font_resolver(&loaded, load_fonts), ..usvg::Options::default() }; + let tree = resolver.parse_preflight(checked, options).map_err(svg_parse_error)?; + let fontless_text = loaded.get().is_some_and(|db| db.faces().next().is_none()); + Ok((tree, fontless_text)) } /// A parsed drawing. @@ -402,8 +418,8 @@ struct Parsed { /// Parses a drawing, `.svgz` included. The XML is inflated and checked here, before the parser /// sees it: deeper nesting than [`MAX_XML_DEPTH`] is an error, not a stack overflow. The font -/// database (and its one-off scan of the system fonts) is only loaded when the drawing may -/// contain text. +/// database (and its one-off scan of the system fonts) is loaded only when the drawing requests +/// a text font. fn parse(bytes: &[u8]) -> Result { parse_with(bytes, fonts) } @@ -440,9 +456,6 @@ fn parse_with_image_limit(bytes: &[u8], fonts: fn() -> Arc MAX_XML_DEPTH { return Err(IoError::Svg(format!("elements are nested more than {MAX_XML_DEPTH} levels deep"))); } - let has_text = xml.windows(4).any(|w| w == b"text"); - let fontdb = if has_text { fonts() } else { Arc::new(usvg::fontdb::Database::new()) }; - let fontless_text = has_text && fontdb.faces().next().is_none(); // Convert the already-bounded-and-decoded text through checked XML, never from_data: // re-checks the gzip magic and would decompress a second time without our size limit if // the inflated content happened to start with a nested gzip stream. @@ -450,10 +463,7 @@ fn parse_with_image_limit(bytes: &[u8], fonts: fn() -> Arc>, fonts return Err(IoError::Svg(format!("elements are nested more than {MAX_XML_DEPTH} levels deep"))); } parse_at_depth(depth, || { - let has_text = xml.windows(4).any(|w| w == b"text"); - let fontdb = if has_text { fonts() } else { Arc::new(usvg::fontdb::Database::new()) }; - if has_text && fontdb.faces().next().is_none() { - budget.lock().unwrap_or_else(PoisonError::into_inner).fontless_text = true; - } let resolver = Arc::clone(&budget.lock().unwrap_or_else(PoisonError::into_inner).resolver); let text = std::str::from_utf8(&xml).map_err(|_| IoError::Svg("the SVG is not valid UTF-8".into()))?; - let limits = resolver.limits(); - let tree = guarded_parse(|| { - let checked = craft_svg::tree::preflight(text, &limits).map_err(svg_parse_error)?; - resolver.parse_preflight(checked, parse_options(fontdb)).map_err(svg_parse_error) - })??; + let (tree, fontless_text) = + guarded_parse(|| parse_checked_svg(text, &resolver, fonts)).inspect_err(|error| image_error(&budget, error.to_string()))??; let mut counter = budget.lock().unwrap_or_else(PoisonError::into_inner); + counter.fontless_text |= fontless_text; let usage = counter.resolver.usage(); counter.pixels = counter.pixels.saturating_sub(usage.raster_pixels); counter.xml_bytes = counter.xml_bytes.saturating_sub(u64::try_from(usage.embedded_svg_bytes).unwrap_or(u64::MAX)); diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index 7541a58db3..96facb2592 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -456,6 +456,46 @@ fn inter_only() -> Arc { Arc::new(db) } +#[test] +fn percent_encoded_svg_child_text_renders_without_outer_text() { + let child = br#"HI"#; + let data = child.iter().map(|byte| format!("%{byte:02X}")).collect::(); + let outer = + format!(r#""#); + assert!(!outer.contains("text"), "the encoded child is the only text source"); + let has_glyph_ink = |pixels: &photocraft_compose::Buffer| pixels.px.iter().any(|pixel| pixel[3] > 0.5); + + let ink = on_svg_stack(|| { + let parsed = parse_with(outer.as_bytes(), inter_only)?; + let imported = import_parsed("child.svg", parsed, MAX_GROUP_DEPTH, None, false)?; + let (parsed, chain) = parse_bounded_inner_with(outer.as_bytes(), MAX_RASTER_PIXELS, inter_only)?; + assert_eq!(chain, 1); + let pixels = rasterize_tree(&complete_raster_tree(parsed)?, 1.0)?; + Ok([has_glyph_ink(&photocraft_compose::flatten(&imported.document)), has_glyph_ink(&pixels)]) + }) + .unwrap(); + assert_eq!(ink, [true, true], "glyph ink through ordinary import and bounded rendering"); +} + +#[test] +fn svg_without_text_does_not_load_fonts() { + fn unexpected_fonts() -> Arc { + panic!("a text-free drawing should never load fonts"); + } + let child = image_svg(r#""#); + let outer = image_svg(&embedded_image("image/svg+xml", child.as_bytes())); + on_svg_stack(|| { + let ordinary = parse_with(outer.as_bytes(), unexpected_fonts)?; + let (bounded, _) = parse_bounded_inner_with(outer.as_bytes(), MAX_RASTER_PIXELS, unexpected_fonts)?; + for parsed in [ordinary, bounded] { + assert!(!parsed.fontless_text); + assert_eq!(rasterize_tree(&parsed.tree, 1.0)?.get(0, 0), [1., 0., 0., 1.]); + } + Ok(()) + }) + .unwrap(); +} + /// Text asking for fonts that aren't installed (`Arial, Helvetica, sans-serif` on a Linux /// without them) is set in an installed font, as a browser does, instead of being dropped. #[test] From e9796f05908c71542245f3ceaf1860bfeda64d92 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 17 Nov 2026 21:30:25 +0100 Subject: [PATCH 13/85] Toolbar: flyouts open to the right, flipped only at the window edge (#12517) The toolbar's tool flyouts, "..." flyout and Edit Toolbar drawer opened toward the canvas, so with the toolbar docked on the right between the dock's columns they opened to the left over the canvas. The reference application opens them to the right there too, over the panels, and flips them only where they would leave the window. They now always prefer the end side; the overlay placement already flips them when that side has no room. --- crates/ui-egui/src/panels/panel_docking.rs | 11 --- crates/ui-egui/src/panels/toolbar.rs | 15 +++- .../src/panels/toolbar_docking_tests.rs | 89 +++++++++++++++++++ 3 files changed, 101 insertions(+), 14 deletions(-) create mode 100644 crates/ui-egui/src/panels/toolbar_docking_tests.rs diff --git a/crates/ui-egui/src/panels/panel_docking.rs b/crates/ui-egui/src/panels/panel_docking.rs index 596f12af47..0911972911 100644 --- a/crates/ui-egui/src/panels/panel_docking.rs +++ b/crates/ui-egui/src/panels/panel_docking.rs @@ -6,7 +6,6 @@ //! The lock is `app.workspaces.set.locked`. use craft::behavior::dock::{Action, DockEdge, DockPlacement, Layout, Node, PanelPlace, PanelState, Permissions, SplitSize, Target}; -use craft::behavior::overlay::Side; use craft::behavior::{DockSide, EditEvent, EditEvents, IconId}; use craft::ui::contract::{Bind, BodyCx, SizeLimits}; use craft::ui::docking::{ @@ -56,16 +55,6 @@ pub(crate) fn is_front(app: &PhotocraftApp, id: &str) -> bool { layout.panel_state(&panel) == PanelState::Front || (layout.opens_in_flyout(&panel) && app.ui.flyout.as_ref() == Some(&panel)) } -/// The side of the Toolbar its flyouts and drawer open on: the side of the canvas. A toolbar in the end dock opens -/// towards the start, any other toward the end. -pub(crate) fn toolbar_opens(app: &PhotocraftApp) -> Side { - let layout = &app.ui.docking.layout; - match layout.place(&TOOLBAR.to_owned()) { - Some(PanelPlace::Dock { path, .. }) if layout.dock_path(DockEdge::End).is_some_and(|end| end == path) => Side::Start, - _ => Side::End, - } -} - /// Shows or hides panel `id` (an id or a label). `Some(true)` opens a hidden panel at its place, and brings a shown /// one to the front, expanding its minimized group; `Some(false)` closes it; `None` shows a panel that is hidden, /// minimized or behind another tab and closes one that is in front. A panel in a column collapsed to icons opens and diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs index acb14c1d00..36c511681a 100644 --- a/crates/ui-egui/src/panels/toolbar.rs +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -14,6 +14,9 @@ use photocraft_engine::prefs::ToolbarCustomization; use super::tool_commands; +#[cfg(test)] +#[path = "toolbar_docking_tests.rs"] +mod toolbar_docking_tests; #[cfg(test)] #[path = "toolbar_tab_reveal_tests.rs"] mod toolbar_tab_reveal_tests; @@ -154,7 +157,13 @@ fn quick_mask_button(app: &PhotocraftApp, ui: &mut egui::Ui) { let _ = FlyoutButton::new(&tools, &0).id_salt("quick-mask").selected(on).show(ui); } -/// The rail over `slots`, its flyouts and drawer opening on `opens`, the side of the canvas. +/// The side of the toolbar its tool flyouts, "…" flyout and Edit Toolbar drawer open on: the end (the right in a +/// left-to-right layout) wherever the toolbar is docked or floats, as in the reference application, which opens them +/// to the right even when the toolbar sits on the right between the dock's columns. The overlay flips them to the +/// other side only when they would leave the window. +const FLYOUTS_OPEN: Side = Side::End; + +/// The rail over `slots`, its flyouts and drawer opening on `opens`. fn rail<'a>(slots: &'a [ToolSlot], current: &'a Tool, remembered: &'a LastUsed, opens: Side, editing: bool) -> ToolRail<'a, Tool> { let rail = ToolRail::new(Label::Empty, slots, current, remembered).opens(opens).edit_toolbar(tl!("Edit Toolbar…").to_string()); // The drawer's open flag is the one source of "editing". @@ -184,7 +193,7 @@ pub(crate) fn measure(app: &mut PhotocraftApp, ui: &egui::Ui, width: f32) -> f32 let slots = tool_commands::slots(&app.session.prefs().toolbar); let remembered = last_used(&slots, &app.ui.group_tools); let current = app.ui.tool; - let (opens, editing) = (crate::panel_docking::toolbar_opens(app), app.ui.toolbar_drawer); + let (opens, editing) = (FLYOUTS_OPEN, app.ui.toolbar_drawer); rail(&slots, ¤t, &remembered, opens, editing).measure_rail(ui, width, |ui, at| footer(app, ui, at)).y } @@ -199,7 +208,7 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let slots = tool_commands::slots(&app.session.prefs().toolbar); let remembered = last_used(&slots, &app.ui.group_tools); let current = app.ui.tool; - let (opens, editing) = (crate::panel_docking::toolbar_opens(app), app.ui.toolbar_drawer); + let (opens, editing) = (FLYOUTS_OPEN, app.ui.toolbar_drawer); let out = rail(&slots, ¤t, &remembered, opens, editing).show_rail(ui, |ui, at| footer(app, ui, at)); if let Some(tool) = out.select { diff --git a/crates/ui-egui/src/panels/toolbar_docking_tests.rs b/crates/ui-egui/src/panels/toolbar_docking_tests.rs new file mode 100644 index 0000000000..156b370b4d --- /dev/null +++ b/crates/ui-egui/src/panels/toolbar_docking_tests.rs @@ -0,0 +1,89 @@ +//! The toolbar as a dock panel (#12517): its tool flyouts open to the right of the button wherever it is docked, and +//! flip to the left only where they would leave the window. + +use super::*; +use crate::panels::registry::TOOLBAR; +use craft::behavior::dock::{Action, DockPlacement, Target}; +use egui::{PointerButton, Pos2, Rect}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +const SIZE: egui::Vec2 = egui::vec2(1200.0, 800.0); + +/// The whole app in a 1200 x 800 window with a small document open. +fn harness() -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(SIZE).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::AppTheme::pro()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).expect("new document"); + app + }); + h.run_steps(4); + h +} + +/// Moves the toolbar's column beside the column holding `anchor`, after it in the dock's column order or before it. +fn dock_toolbar_beside(h: &mut Harness<'static, PhotocraftApp>, anchor: &str, after: bool) { + let action = Action::move_column(TOOLBAR.to_owned(), Target::at(anchor.to_owned(), DockPlacement::column(after))); + crate::panel_docking::apply(h.state_mut(), vec![action]).expect("the toolbar docks beside the column"); + h.run_steps(6); +} + +/// The rect of the innermost node named `label`. +fn rect_of(h: &Harness<'static, PhotocraftApp>, label: &str) -> Option { + h.query_all_by_label(label).last().map(|node| node.rect()) +} + +/// Right-clicks the middle of `rect`, which opens a tool slot's flyout. +fn right_click(h: &mut Harness<'static, PhotocraftApp>, rect: Rect) { + let at: Pos2 = rect.center(); + h.event(egui::Event::PointerMoved(at)); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(4); +} + +/// The Lasso slot's flyout rows, opened from the toolbar: the slot's button and the Polygonal Lasso row. +fn lasso_flyout(h: &mut Harness<'static, PhotocraftApp>) -> (Rect, Rect) { + let button = rect_of(h, "Lasso Tool").expect("the Lasso slot is drawn"); + right_click(h, button); + let row = rect_of(h, "Polygonal Lasso Tool").expect("the Lasso flyout is open"); + (button, row) +} + +/// Docked on the right between the dock's icon column and its panel column, the toolbar still opens its flyouts to the +/// right of the button, over the panels, as the reference application does (they used to open toward the canvas). +#[test] +fn flyouts_open_to_the_right_between_the_end_docks_columns() { + let mut h = harness(); + dock_toolbar_beside(&mut h, "color", true); + let toolbar = crate::panel_docking::probe::group_rect(&h, "toolbar"); + let panels = crate::panel_docking::probe::group_rect(&h, "color").expect("the Color group is drawn"); + let (button, row) = lasso_flyout(&mut h); + assert!(button.right() < panels.left(), "the toolbar sits left of the panel column: {button:?}, {panels:?}, {toolbar:?}"); + assert!(button.center().x > SIZE.x * 0.5, "the toolbar is on the right half of the window: {button:?}"); + assert!(row.left() >= button.right() - 0.5, "the flyout opens to the right of the button: row {row:?}, button {button:?}"); +} + +/// At the right window edge there is no room to the right, so the flyout flips to the left of the button. +#[test] +fn flyouts_flip_left_at_the_right_window_edge() { + let mut h = harness(); + dock_toolbar_beside(&mut h, "color", false); + let (button, row) = lasso_flyout(&mut h); + assert!(button.right() > SIZE.x - 80.0, "the toolbar is at the right window edge: {button:?}"); + assert!(row.right() <= button.left() + 0.5, "the flyout flips to the left of the button: row {row:?}, button {button:?}"); +} + +/// Docked at the left edge (the default), the flyout opens to the right. +#[test] +fn flyouts_open_to_the_right_at_the_left_edge() { + let mut h = harness(); + let (button, row) = lasso_flyout(&mut h); + assert!(button.left() < 80.0, "the toolbar is at the left window edge: {button:?}"); + assert!(row.left() >= button.right() - 0.5, "the flyout opens to the right of the button: row {row:?}, button {button:?}"); +} From ccc82156ce9d8dd9ac89a99618d8e0bac372f84e Mon Sep 17 00:00:00 2001 From: FredApps Date: Tue, 17 Nov 2026 22:37:52 +0100 Subject: [PATCH 14/85] Keep smart source cache hits within decode context --- crates/engine/src/cmd/smart_cmds/placing.rs | 9 ++- crates/engine/src/cmd/smart_cmds/source.rs | 58 +++++++++++++++++-- .../tests/svg_stack_completeness.rs | 2 +- 3 files changed, 59 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/smart_cmds/placing.rs b/crates/engine/src/cmd/smart_cmds/placing.rs index 48cede87e4..f107df8fd3 100644 --- a/crates/engine/src/cmd/smart_cmds/placing.rs +++ b/crates/engine/src/cmd/smart_cmds/placing.rs @@ -1,5 +1,5 @@ use super::rendering::{refresh_or_fail, unapplied_filters}; -use super::source::{SourceImage, buffer_to_surface, cache_key, cache_put, source_bytes}; +use super::source::{SourceImage, buffer_to_surface, cache_put, source_bytes, source_cache_key}; use super::{ Affine, Arc, BlendMode, Document, EngineError, Homography, Layer, LayerContent, LayerId, PLACED_KEYS, Rect, Result, Session, Size, SmartContentsId, SmartObject, SmartSource, Surface, Value, encode_source, json, layer_param, other, source_box, translate_surface, @@ -258,8 +258,11 @@ pub fn layers_to_smart(doc: &Document, name: &str, layers: Vec) -> Result sub.layers.iter_mut().for_each(|l| shift_layer(l, -b.x0, -b.y0)); sub.size = Size::new(b.width(), b.height()); let bytes = encode_source(&sub)?; - // Seed the decode cache with the composite we already have. - cache_put(cache_key(&bytes, fmt), SourceImage { surface: Arc::new(translate_surface(&cache, -b.x0, -b.y0)), bounds: sub.bounds() }); + // The encoded native document is non-SVG; match the classified render/bounds path. + cache_put( + source_cache_key(&sub.name, &bytes, fmt, Some(false)), + SourceImage { surface: Arc::new(translate_surface(&cache, -b.x0, -b.y0)), bounds: sub.bounds() }, + ); let source = SmartSource::Embedded { file_name: sub.name.clone(), bytes: Arc::new(bytes) }; Ok(Layer::new(name, LayerContent::Smart(SmartObject::new(source, Affine::translate(b.x0 as f64, b.y0 as f64), Some(cache))))) diff --git a/crates/engine/src/cmd/smart_cmds/source.rs b/crates/engine/src/cmd/smart_cmds/source.rs index e5bd657097..52b6b5820a 100644 --- a/crates/engine/src/cmd/smart_cmds/source.rs +++ b/crates/engine/src/cmd/smart_cmds/source.rs @@ -70,7 +70,7 @@ pub struct SourceImage { pub bounds: Rect, } -type CacheKey = ([u8; 32], PixelFormat); +pub(super) type CacheKey = ([u8; 32], PixelFormat, Option<[u8; 32]>); struct CacheEntry { key: CacheKey, @@ -100,7 +100,23 @@ fn cache() -> std::sync::MutexGuard<'static, Vec> { } pub(super) fn cache_key(bytes: &[u8], fmt: PixelFormat) -> CacheKey { - (*blake3::hash(bytes).as_bytes(), fmt) + (*blake3::hash(bytes).as_bytes(), fmt, None) +} + +/// Keep automatic recognition and caller-supplied classifications separate. The filename +/// also selects extension-sensitive importers. Neither decision may be bypassed by a hit. +pub(super) fn source_cache_key(file_name: &str, bytes: &[u8], fmt: PixelFormat, svg: Option) -> CacheKey { + let mut key = cache_key(bytes, fmt); + let mut context = blake3::Hasher::new(); + context.update(b"source-decode-context-v1\0"); + context.update(&[match svg { + None => 0, + Some(false) => 1, + Some(true) => 2, + }]); + context.update(file_name.as_bytes()); + key.2 = Some(*context.finalize().as_bytes()); + key } pub(super) fn cache_get(key: &CacheKey) -> Option { @@ -136,7 +152,7 @@ fn cache_put_within(key: CacheKey, image: SourceImage, limit: usize) { /// How many times these contents were decoded at this pixel format (0 = never / evicted). pub fn source_decode_count(bytes: &[u8], fmt: PixelFormat) -> u32 { let key = cache_key(bytes, fmt); - cache().iter().find(|e| e.key == key).map(|e| e.decodes).unwrap_or(0) + cache().iter().filter(|e| e.key.0 == key.0 && e.key.1 == fmt).fold(0u32, |total, e| total.saturating_add(e.decodes)) } /// Bytes held by cached source composites. @@ -291,7 +307,7 @@ pub fn svg_source_image(bytes: &[u8], fmt: PixelFormat, scale: f64) -> Result R h.update(bytes); h.update(&scale.to_bits().to_le_bytes()); h.update(&profile.to_bytes()); - let key = (*h.finalize().as_bytes(), fmt); + let key = (*h.finalize().as_bytes(), fmt, None); if let Some(image) = cache_get(&key) { return Ok(image); } @@ -361,7 +377,7 @@ pub(super) fn source_image_classified(file_name: &str, bytes: &[u8], fmt: PixelF } fn source_image_inner(file_name: &str, bytes: &[u8], fmt: PixelFormat, svg: Option) -> Result { - let key = cache_key(bytes, fmt); + let key = source_cache_key(file_name, bytes, fmt, svg); if let Some(img) = cache_get(&key) { return Ok(img); } @@ -379,6 +395,36 @@ fn source_image_inner(file_name: &str, bytes: &[u8], fmt: PixelFormat, svg: Opti mod tests { use super::*; + #[test] + fn source_cache_keys_preserve_filename_and_classification() { + let bytes = b"source context regression"; + let fmt = PixelFormat::RGBA8; + let keys = [ + source_cache_key("source.png", bytes, fmt, None), + source_cache_key("source.dat", bytes, fmt, None), + source_cache_key("source.png", bytes, fmt, Some(false)), + source_cache_key("source.png", bytes, fmt, Some(true)), + cache_key(bytes, fmt), + ]; + for (i, key) in keys.iter().enumerate() { + for other in &keys[i + 1..] { + assert_ne!(key, other); + } + } + assert_eq!(keys[0], source_cache_key("source.png", bytes, fmt, None)); + assert_ne!(keys[0], source_cache_key("source.png", bytes, PixelFormat::RGBA32F, None)); + } + + #[test] + fn warm_raster_source_cannot_bypass_svg_classification() { + let raster = photocraft_codecs::Image::from_u8(1, 1, photocraft_codecs::ChannelLayout::Rgb, vec![13, 47, 91]).unwrap(); + let png = photocraft_codecs::encode(&raster, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let name = "source-classification-regression.png"; + let first = source_image_classified(name, &png, PixelFormat::RGBA8, false).unwrap(); + assert_eq!(first.bounds, Rect::new(0, 0, 1, 1)); + assert!(source_image_classified(name, &png, PixelFormat::RGBA8, true).is_err(), "a warm raster hit must not skip strict SVG decoding"); + assert!(source_image(name, &png, PixelFormat::RGBA8).is_ok()); + } fn image(side: i32) -> SourceImage { let mut s = Surface::new(PixelFormat::RGBA8); s.fill_rect(Rect::new(0, 0, side, side), &[0.2, 0.4, 0.6, 1.0]); diff --git a/crates/engine/src/cmd/smart_cmds/tests/svg_stack_completeness.rs b/crates/engine/src/cmd/smart_cmds/tests/svg_stack_completeness.rs index 2974992f77..4195593180 100644 --- a/crates/engine/src/cmd/smart_cmds/tests/svg_stack_completeness.rs +++ b/crates/engine/src/cmd/smart_cmds/tests/svg_stack_completeness.rs @@ -16,7 +16,7 @@ fn smart_svg(bytes: Vec) -> SmartObject { SmartObject::new(SmartSource::Embedded { file_name: "Stack completeness.svg".into(), bytes: Arc::new(bytes) }, Affine::IDENTITY, None) } -fn old_stack_key(bytes: &[u8], fmt: PixelFormat, mode: photocraft_doc::StackMode) -> ([u8; 32], PixelFormat) { +fn old_stack_key(bytes: &[u8], fmt: PixelFormat, mode: photocraft_doc::StackMode) -> source::CacheKey { let mut key = source::cache_key(bytes, fmt); key.0 = *blake3::hash(&[&key.0[..], b"stack:", mode.id().as_bytes()].concat()).as_bytes(); key From fbc9f98d1bca1fdaea30a593df4fd75d5c997458 Mon Sep 17 00:00:00 2001 From: NaufalDzz Date: Wed, 18 Nov 2026 00:48:02 +0000 Subject: [PATCH 15/85] Dialogs: titles drop the menu item's ellipsis (#15541) Stroke, New Group, New Group from Layers and New Brush Preset showed the menu label with its trailing ellipsis as the window title. Co-authored-by: OpenBot <335604065+openbotgit[bot]@users.noreply.github.com> --- .../src/dialog_title_ellipsis_tests.rs | 49 +++++++++++++++++++ .../src/dialogs/brush_preset_dialog.rs | 2 +- crates/ui-egui/src/dialogs/new_group_ui.rs | 2 +- crates/ui-egui/src/dialogs/stroke_ui.rs | 2 +- crates/ui-egui/src/lib.rs | 2 + 5 files changed, 54 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/dialog_title_ellipsis_tests.rs diff --git a/crates/ui-egui/src/dialog_title_ellipsis_tests.rs b/crates/ui-egui/src/dialog_title_ellipsis_tests.rs new file mode 100644 index 0000000000..d958214bce --- /dev/null +++ b/crates/ui-egui/src/dialog_title_ellipsis_tests.rs @@ -0,0 +1,49 @@ +//! A dialog's title is its command's name without the menu item's ellipsis (#15541): Edit › Stroke… +//! opens "Stroke", as in Photoshop. Covers the dialogs that name themselves after their menu item. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +use crate::PhotocraftApp; + +/// Opens one dialog. +type Open = fn(&mut PhotocraftApp); + +fn harness() -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1000.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::AppTheme::pro()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app + }); + h.run_steps(6); + h +} + +#[test] +fn dialog_titles_drop_the_menu_ellipsis() { + let cases: [(&str, Open); 4] = [ + ("Stroke", |app| { + crate::stroke_ui::open(app); + }), + ("New Group", |app| { + crate::new_group_ui::open(app, crate::new_group_ui::NEW_GROUP); + }), + ("New Group from Layers", |app| { + crate::new_group_ui::open(app, crate::new_group_ui::FROM_LAYERS); + }), + ("New Brush Preset", |app| { + crate::brush_preset_dialog::open(app, None); + }), + ]; + for (title, open) in cases { + let mut h = harness(); + open(h.state_mut()); + h.run_steps(4); + assert!(h.query_all_by_label(&format!("{title}…")).next().is_none(), "the {title} dialog's title has no ellipsis"); + assert!(h.query_all_by_label(title).next().is_some(), "the dialog is titled {title}"); + } +} diff --git a/crates/ui-egui/src/dialogs/brush_preset_dialog.rs b/crates/ui-egui/src/dialogs/brush_preset_dialog.rs index 30d680888d..fde37ee089 100644 --- a/crates/ui-egui/src/dialogs/brush_preset_dialog.rs +++ b/crates/ui-egui/src/dialogs/brush_preset_dialog.rs @@ -67,7 +67,7 @@ pub fn open(app: &mut PhotocraftApp, brush: Option<&BrushSettings>) -> DialogId // Include Color belongs to the tool settings: only with them, as in Photoshop. Param::new("color", tl!("Include Color"), ParamKind::bool(false)).enabled_when("toolSettings", true), ]; - let mut dialog = ParamDialog::command(KEY, tl!("New Brush Preset…"), rows).values(Bind::bound(fields)).ok_enabled(why.is_none()); + let mut dialog = ParamDialog::command(KEY, tl!("New Brush Preset"), rows).values(Bind::bound(fields)).ok_enabled(why.is_none()); if let Some(why) = why { dialog = dialog.ok_reason(Label::from(why)); } diff --git a/crates/ui-egui/src/dialogs/new_group_ui.rs b/crates/ui-egui/src/dialogs/new_group_ui.rs index 2412592556..af393044ea 100644 --- a/crates/ui-egui/src/dialogs/new_group_ui.rs +++ b/crates/ui-egui/src/dialogs/new_group_ui.rs @@ -33,7 +33,7 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> DialogId { let command = if command == FROM_LAYERS { FROM_LAYERS } else { NEW_GROUP }; let name = app.session.active().map(|st| st.doc.next_layer_name("Group")).unwrap_or_else(|| "Group 1".into()); // The window title, as in Photoshop. - let title = if command == FROM_LAYERS { tl!("New Group from Layers…") } else { tl!("New Group…") }; + let title = if command == FROM_LAYERS { tl!("New Group from Layers") } else { tl!("New Group") }; params::open_param(app, command, DialogFields::new(), Value::Null, move |fields: &mut DialogFields| { let rows = vec![ Param::new("name", tl!("Name:"), ParamKind::text(name.clone())), diff --git a/crates/ui-egui/src/dialogs/stroke_ui.rs b/crates/ui-egui/src/dialogs/stroke_ui.rs index e5a07a6707..2048251e57 100644 --- a/crates/ui-egui/src/dialogs/stroke_ui.rs +++ b/crates/ui-egui/src/dialogs/stroke_ui.rs @@ -43,7 +43,7 @@ pub fn open(app: &mut PhotocraftApp) -> DialogId { } let [r, g, b, _] = app.session.tools.foreground; let rows = rows([r, g, b]); - let title = Label::from(tl!("Stroke…")); + let title = Label::from(tl!("Stroke")); open_param(app, COMMAND, DialogFields::new(), held, move |fields| { ParamDialog::new(COMMAND, title.clone(), Cow::Owned(rows.clone())).values(Bind::bound(fields)).remember(SaveKey::named(REMEMBER)) }) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8b08795cd8..e6c73c7d3c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -799,6 +799,8 @@ mod navigator_gpu_tests; #[cfg(test)] mod color_swatch_tests; +#[cfg(test)] +mod dialog_title_ellipsis_tests; #[cfg(test)] mod profile_open_tests; From 84ee720e61051509bc536e15baafbb79ff506487 Mon Sep 17 00:00:00 2001 From: DingusMcRinkyDinky <127614779+DingusMcRinkyDinky@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:25:34 +0100 Subject: [PATCH 16/85] Free Transform: the layer shows inside its box again While Free Transform is open, the canvas hides the layer being transformed from the document's picture and draws it as the transform preview. Both go into the canvas's picture slot in show order, and the canvas shows its controls (the preview among them) before it prepares the document's picture, so the document, without the layer, painted over the preview: only the layers below showed inside the box. The preview is now painted in place, taken out and handed to the canvas body, which adds it to the picture slot after the document and the channel overlay, as the Levels clipping display already joins it. The layers above the moving pixels go with them; the box, the warp grid and the guides still draw on top. Fixes #15546. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZbgszHyuEuWAzxaamteuU --- crates/ui-egui/src/canvas/document_display.rs | 5 + crates/ui-egui/src/canvas/tools/mod.rs | 4 +- .../ui-egui/src/tools/transform_tool/draw.rs | 30 ++-- .../tests/it/free_transform_preview_canvas.rs | 139 ++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + 5 files changed, 168 insertions(+), 11 deletions(-) create mode 100644 crates/ui-egui/tests/it/free_transform_preview_canvas.rs diff --git a/crates/ui-egui/src/canvas/document_display.rs b/crates/ui-egui/src/canvas/document_display.rs index 768d2b4aec..6bc6a7fd79 100644 --- a/crates/ui-egui/src/canvas/document_display.rs +++ b/crates/ui-egui/src/canvas/document_display.rs @@ -335,6 +335,8 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, // What the controls report for the host's pass. let mut body_shown = tools::BodyShown::default(); let live = canvas_controls(app, ui, body.rect, host, &space, &mut turned, &mut body_shown); + // The Free Transform preview joins the picture slot after the document, which is prepared after the tools. + let transform_picture = std::mem::take(&mut body_shown.transform_picture); // The body can run more than once in a frame; a report from any of its runs counts. if let Some(context) = body_shown.crop.as_mut().and_then(craft::draw::ui::CropShown::take_context) { overlay_context = Some(context); @@ -414,6 +416,8 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, }; display.show_at(ui, body.rect); } + // The moving pixels over the document, which hides the layer they come from, and under the controls. + space.paint_picture(ctx, transform_picture); space.paint_picture(ctx, clipping); // The grid is drawn over the picture. if app.ui.view.shows(app.ui.view.show.pixel_grid) { @@ -528,6 +532,7 @@ fn canvas_controls( let session = if primary { crate::transform_tool::show_in_canvas(app, ui, rect, now) } else { crate::transform_tool::SessionShown::default() }; let session_box_shown = session.shown; reported.transform_snapped = session.snapped; + reported.transform_picture = session.picture; crate::cam_transform::show(app, ui, rect); super::transform_controls::show(app, ui, rect, session_box_shown); crate::move_box::show(app, ui, rect); diff --git a/crates/ui-egui/src/canvas/tools/mod.rs b/crates/ui-egui/src/canvas/tools/mod.rs index 019e289041..8e39edf481 100644 --- a/crates/ui-egui/src/canvas/tools/mod.rs +++ b/crates/ui-egui/src/canvas/tools/mod.rs @@ -477,6 +477,8 @@ pub(crate) struct BodyShown { pub(crate) crop: Option, /// The snap lines of the open Free Transform's box, which its canvas tool hands to the host. pub(crate) transform_snapped: Vec, + /// The open Free Transform's preview, which the body adds to the canvas's picture slot after the document. + pub(crate) transform_picture: Vec, } /// Borrows a family tool as the host's `dyn`. @@ -513,7 +515,7 @@ fn with_rig( let transform_open = app.ui.transform.is_some(); let lends_transform = stand_ins && (!in_gesture || tools.gesture_pick == GesturePick::Transform); let free_transform = if lends_transform { app.ui.transform.take() } else { None }; - let BodyShown { crop: crop_shown, transform_snapped } = shown; + let BodyShown { crop: crop_shown, transform_snapped, .. } = shown; let mut transform = free_transform.as_ref().map(|session| crate::transform_tool::canvas_tool(session, transform_snapped)); // The symmetry session moves into the pass the same way. let symmetry_transform = if stand_ins && fam == Family::Paint { app.ui.symmetry_transform.take() } else { None }; diff --git a/crates/ui-egui/src/tools/transform_tool/draw.rs b/crates/ui-egui/src/tools/transform_tool/draw.rs index 0eab00e4f0..a8723af30e 100644 --- a/crates/ui-egui/src/tools/transform_tool/draw.rs +++ b/crates/ui-egui/src/tools/transform_tool/draw.rs @@ -12,6 +12,7 @@ use craft::imaging::ui::transform_preview::{PreviewDisplay, PreviewMap, Transfor use craft::imaging::ui::warp::{CylinderValues, CylinderWarp, WarpEdit, WarpGrid, WarpMesh}; use craft::ui::canvas::RasterDisplay; use craft::ui::contract::{Bind, Show as _}; +use craft::ui::primitives::PaintSlot; use photocraft_doc::DocId; use photocraft_geom::warp::WarpStyle; @@ -38,11 +39,16 @@ struct Shown { cylinder: Option>, /// A warp control has the pointer button down on it. busy: bool, + /// The preview's shapes, for the canvas's picture slot after the document ([`SessionShown::picture`]). + picture: Vec, } /// Shows the open Free Transform in the canvas body at `rect`, and applies what its controls /// report: the preview (moving pixels, covering layers, path outline), then the box or warp -/// controls. The canvas calls it after the document display and before the tool overlays. +/// controls. The canvas calls it with its controls, before it prepares the document's picture, so +/// the preview's moving pixels come back in [`SessionShown::picture`] for the canvas to add to its +/// picture slot after the document: added here, the document (which hides the moving layer) would +/// paint over them (#15546). /// /// Every control reads the frame's input once for its own pass, so a second pass of a frame /// reports no edit again and this applies only what the pass it ran in reported. @@ -55,7 +61,7 @@ pub fn show_in_canvas(app: &mut PhotocraftApp, ui: &mut egui::Ui, rect: egui::Re let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview) else { return SessionShown::default() }; show_session(app, t, pv, ui, rect) }; - let Shown { edits, snapped, apply, discard, mesh, cylinder, busy } = shown; + let Shown { edits, snapped, apply, discard, mesh, cylinder, busy, picture } = shown; let mut need_warp = false; if let Some(t) = app.ui.transform.as_mut() { for edit in edits.iter().cloned() { @@ -85,13 +91,12 @@ pub fn show_in_canvas(app: &mut PhotocraftApp, ui: &mut egui::Ui, rect: egui::Re if let Some(t) = app.ui.transform.as_mut() { t.session.settle(now, busy); } - SessionShown { shown: true, snapped } + SessionShown { shown: true, snapped, picture } } /// The pass's shows, in paint order. fn show_session(app: &PhotocraftApp, t: &FreeTransform, pv: &OpenPreview, ui: &mut egui::Ui, rect: egui::Rect) -> Shown { - show_preview(app, t, pv, ui, rect); - let mut out = Shown::default(); + let mut out = Shown { picture: show_preview(app, t, pv, ui, rect), ..Shown::default() }; if pv.committing.is_some() { // The moving pixels stay without the box until the commit job lands. return out; @@ -125,14 +130,19 @@ pub struct SessionShown { pub shown: bool, /// The snap lines of the box's drag. pub snapped: Vec, + /// The preview's shapes (the moving pixels, then the layers above them), which the canvas adds to its picture + /// slot after the document's picture. + pub picture: Vec, } /// The moving pixels as the session maps them (warped, skewed or styled), then the layers above /// them, both in the canvas's picture, under the grid, guides and controls. Nothing is shown for the Frame tool's transform. -fn show_preview(app: &PhotocraftApp, t: &FreeTransform, pv: &OpenPreview, ui: &mut egui::Ui, rect: egui::Rect) { +fn show_preview(app: &PhotocraftApp, t: &FreeTransform, pv: &OpenPreview, ui: &mut egui::Ui, rect: egui::Rect) -> Vec { if crate::frame_tool::frame_transform(t) { - return; + return Vec::new(); } + // Painted in place after this mark, then taken out for the picture slot. + let mark = PaintSlot::reserve(ui.painter()); let display = preview_display(app, ui.ctx()); let boxed = t.session.phase() == TransformPhase::Box; // The layers that get the styled preview stay PhotoCraft's: a visible layer with a style. @@ -150,8 +160,7 @@ fn show_preview(app: &PhotocraftApp, t: &FreeTransform, pv: &OpenPreview, ui: &m .opacity(pv.opacity) .nearest(t.session.interpolation() == Interpolation::NearestNeighbor) .clip(canvas) - .dragging(t.session.dragging()) - .picture(); + .dragging(t.session.dragging()); if let Some(display) = display.as_ref() { preview = preview.display(display); } @@ -162,8 +171,9 @@ fn show_preview(app: &PhotocraftApp, t: &FreeTransform, pv: &OpenPreview, ui: &m if let Some(above) = &pv.above && let Some(frame) = above.frame() { - RasterDisplay::new("", above).mapped(frame, 1).picture().show_at(ui, rect); + RasterDisplay::new("", above).mapped(frame, 1).show_at(ui, rect); } + mark.take_after(ui.ctx()) } /// What the box draws for the styled layer at `zoom`, as the framework's styled preview builds it: the composite and its diff --git a/crates/ui-egui/tests/it/free_transform_preview_canvas.rs b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs new file mode 100644 index 0000000000..99681b74e6 --- /dev/null +++ b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs @@ -0,0 +1,139 @@ +//! #15546: while Free Transform is open, the canvas shows the layer being transformed inside its box. +//! +//! The canvas hides that layer from the document's picture and draws it as the transform preview. The preview +//! joins the canvas's picture slot, and the document's picture is prepared after the canvas controls, so a preview +//! added with the controls lay under the document: only the layers below showed inside the box. These tests drive +//! the real app offscreen on wgpu, on the GPU canvas and on the CPU one, start Free Transform on a red layer over a +//! white background, and look at the rendered pixels inside the box, before and during a drag that moves it. +//! Skips when no GPU adapter exists (like `drag_preview_canvas.rs`). + +use craft::behavior::kurbo::Point; +use egui::{Modifiers, PointerButton, Pos2}; +use photocraft_geom::Rect; +use photocraft_ui_egui::PhotocraftApp; +use photocraft_ui_egui::control::{ControlRequest, handle}; +use serde_json::{Value, json}; + +type Harness = egui_kittest::Harness<'static, PhotocraftApp>; + +/// The red square on the layer, in document pixels: x 100..200, y 100..200 of a 400 × 300 document. +fn square() -> Rect { + Rect::new(100, 100, 200, 200) +} + +fn harness(gpu_canvas: bool) -> Option { + let built = std::panic::catch_unwind(|| { + egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 640.0)).with_pixels_per_point(1.0).with_max_steps(64).wgpu().build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); + if gpu_canvas && let Some(rs) = cc.wgpu_render_state.as_ref() { + app.set_wgpu(rs.clone()); + } + app + }) + }); + match built { + Ok(h) => Some(h), + Err(_) => { + eprintln!("skipping: no GPU adapter"); + None + } + } +} + +fn control(h: &mut Harness, method: &str, params: Value) { + let ctx = h.ctx.clone(); + let (req, _rx) = ControlRequest::new(method, params); + handle(h.state_mut(), &ctx, &req); + h.run_steps(3); +} + +/// A white 400 × 300 document at 100 % with a layer holding the red square, active, and the Move tool. +fn setup(h: &mut Harness) { + { + let app = h.state_mut(); + app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).expect("new"); + app.run("layer.new.layer", json!({})).expect("new layer"); + app.session + .edit("paint", |doc, active| { + let id = active.expect("the new layer is active"); + let surface = doc.layer_mut(id).and_then(|l| l.surface_mut()).expect("a raster layer"); + surface.fill_rect(square(), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .expect("paint"); + app.sync_views(); + app.ui.extras.rulers = false; + } + control(h, "ui.set", json!({"tool": "move", "zoom": 1.0, "center": [200, 150]})); + h.run_steps(3); +} + +/// Screen point (egui points, one physical pixel each here) of document point `(x, y)`. +fn screen(h: &Harness, x: f64, y: f64) -> Pos2 { + photocraft_ui_egui::canvas::active_view(h.state()).expect("an active document view").to_screen(Point::new(x, y)) +} + +fn pointer_move(h: &mut Harness, at: Pos2) { + h.event(egui::Event::PointerMoved(at)); + h.step(); +} + +fn button(h: &mut Harness, at: Pos2, pressed: bool) { + h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); +} + +/// The rendered frame's RGB at document point `(x, y)`. +fn rgb_at(h: &mut Harness, x: f64, y: f64) -> [u8; 3] { + let p = screen(h, x, y); + let img = h.render().expect("render"); + let px = img.get_pixel(p.x.floor() as u32, p.y.floor() as u32); + [px[0], px[1], px[2]] +} + +fn is_red(c: [u8; 3]) -> bool { + c[0] > 200 && c[1] < 60 && c[2] < 60 +} + +fn is_white(c: [u8; 3]) -> bool { + c.iter().all(|&v| v > 230) +} + +fn shows_the_layer_inside_the_box(gpu_canvas: bool) { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut h) = harness(gpu_canvas) else { return }; + setup(&mut h); + assert!(is_red(rgb_at(&mut h, 150.5, 150.5)), "the layer shows before the transform"); + + control(&mut h, "ui.menu.invoke", json!({"id": "edit.freeTransform"})); + assert!(h.state().ui.transform.is_some(), "Free Transform is open"); + let inside = rgb_at(&mut h, 150.5, 150.5); + assert!(is_red(inside), "the layer shows inside the box once Free Transform opens, not the background: {inside:?}"); + + // Drag the box 60 px right from its middle and hold: the preview follows the pointer. The samples sit off the + // middle row, where the smart guide of the centred box is drawn. + let (from, to) = (screen(&h, 150.0, 150.0), screen(&h, 210.0, 150.0)); + pointer_move(&mut h, from); + button(&mut h, from, true); + for i in 1..=6 { + pointer_move(&mut h, from + (to - from) * (i as f32 / 6.0)); + } + let moved = rgb_at(&mut h, 230.5, 130.5); + assert!(is_red(moved), "the moved square shows where the drag took it: {moved:?}"); + let vacated = rgb_at(&mut h, 120.5, 130.5); + assert!(is_white(vacated), "the place the square left shows the background: {vacated:?}"); + button(&mut h, to, false); + let released = rgb_at(&mut h, 230.5, 130.5); + assert!(is_red(released), "the moved square still shows after the release: {released:?}"); +} + +#[test] +fn free_transform_shows_the_layer_inside_its_box_on_the_gpu_canvas() { + shows_the_layer_inside_the_box(true); +} + +#[test] +fn free_transform_shows_the_layer_inside_its_box_on_the_cpu_canvas() { + shows_the_layer_inside_the_box(false); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index f2143a01cf..1bb6bc452c 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -19,6 +19,7 @@ mod crop_task_bar; mod display_shadows; mod drag_preview_canvas; mod eraser_reset_defaults; +mod free_transform_preview_canvas; mod full_res_preview; mod gpu_device_loss; mod healing_reset_tip; From 70e03a3b6113f692ab5643ac3265a9fc10a5af05 Mon Sep 17 00:00:00 2001 From: Zaxaerith <189452125+Zaxaerith@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:29:10 +0800 Subject: [PATCH 17/85] fix(xtask): classify craft as a UI dependency (#15467) --- xtask/src/layers.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index 42e18e12a7..cc8e282730 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -98,7 +98,7 @@ fn standalone_exception(from: &str, to: &str) -> bool { /// External crates that constitute a UI toolkit / windowing dependency. /// Entries ending in `*` are prefixes. -pub const UI_CRATES: &[&str] = &["egui", "eframe", "winit", "egui_kittest", "craft-ui", "rfd", "bevy*"]; +pub const UI_CRATES: &[&str] = &["egui", "eframe", "winit", "egui_kittest", "craft-ui", "craft", "rfd", "bevy*"]; /// First layer allowed to use UI crates. pub const UI_MIN_LAYER: u8 = 6; @@ -340,7 +340,7 @@ mod tests { #[test] fn ui_crates_below_l6_flagged() { - for dep in ["egui", "eframe", "winit", "egui_kittest", "craft-ui", "rfd", "bevy_ecs", "bevy"] { + for dep in ["egui", "eframe", "winit", "egui_kittest", "craft-ui", "craft", "rfd", "bevy_ecs", "bevy"] { let v = check(&[c("photocraft-engine", &[(dep, Normal, false)])]); assert!(matches!(v[..], [Violation::UiBelowL6 { layer: 5, .. }]), "{dep}"); } From f5c66274b95be39e2ba5065497a4fa20ec6f37b3 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:10:58 +0100 Subject: [PATCH 18/85] fix(svg): pin merged shared embedded-image validation Advance craft-svg and its seven-source dependency closure to upstream merge7b8c1ec. Preserve registry versions and unrelated shared pins; remove obsolete direct SVG zune-jpeg edge per upstream manifest. Lock candidate reconstructed from reviewed dependency delta; hosted --locked validation pending, no local Cargo run. --- Cargo.lock | 33 ++++++++++++++++----------------- Cargo.toml | 2 +- 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 96aa236a38..382feb16e8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1539,7 +1539,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1aff2841c9ee575eb24f82d578f0e69cef452daa#1aff2841c9ee575eb24f82d578f0e69cef452daa" +source = "git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be#7b8c1eccea0c695a495ab279c9523e6efcc9b8be" dependencies = [ "rayon", ] @@ -1758,12 +1758,12 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1aff2841c9ee575eb24f82d578f0e69cef452daa#1aff2841c9ee575eb24f82d578f0e69cef452daa" +source = "git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be#7b8c1eccea0c695a495ab279c9523e6efcc9b8be" dependencies = [ - "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1aff2841c9ee575eb24f82d578f0e69cef452daa)", - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1aff2841c9ee575eb24f82d578f0e69cef452daa)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1aff2841c9ee575eb24f82d578f0e69cef452daa)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1aff2841c9ee575eb24f82d578f0e69cef452daa)", + "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)", + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)", "crc32fast", "exr", "flate2", @@ -1831,7 +1831,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1aff2841c9ee575eb24f82d578f0e69cef452daa#1aff2841c9ee575eb24f82d578f0e69cef452daa" +source = "git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be#7b8c1eccea0c695a495ab279c9523e6efcc9b8be" dependencies = [ "thiserror 2.0.21", ] @@ -1902,11 +1902,11 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1aff2841c9ee575eb24f82d578f0e69cef452daa#1aff2841c9ee575eb24f82d578f0e69cef452daa" +source = "git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be#7b8c1eccea0c695a495ab279c9523e6efcc9b8be" dependencies = [ "brotli-decompressor 6.3.2", "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1aff2841c9ee575eb24f82d578f0e69cef452daa)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)", "quick-xml 0.41.0", "serde", ] @@ -2121,10 +2121,10 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1aff2841c9ee575eb24f82d578f0e69cef452daa#1aff2841c9ee575eb24f82d578f0e69cef452daa" +source = "git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be#7b8c1eccea0c695a495ab279c9523e6efcc9b8be" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1aff2841c9ee575eb24f82d578f0e69cef452daa)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1aff2841c9ee575eb24f82d578f0e69cef452daa)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)", "data-url", "flate2", "gif", @@ -2137,7 +2137,6 @@ dependencies = [ "usvg 0.48.1", "vectorcraft-geom", "vectorcraft-pathops", - "zune-jpeg", ] [[package]] @@ -2223,7 +2222,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1aff2841c9ee575eb24f82d578f0e69cef452daa#1aff2841c9ee575eb24f82d578f0e69cef452daa" +source = "git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be#7b8c1eccea0c695a495ab279c9523e6efcc9b8be" dependencies = [ "serde", "thiserror 2.0.21", @@ -2490,7 +2489,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1aff2841c9ee575eb24f82d578f0e69cef452daa#1aff2841c9ee575eb24f82d578f0e69cef452daa" +source = "git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be#7b8c1eccea0c695a495ab279c9523e6efcc9b8be" dependencies = [ "quick-xml 0.41.0", "serde", @@ -6347,7 +6346,7 @@ dependencies = [ "craft", "craft-cms", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9)", - "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1aff2841c9ee575eb24f82d578f0e69cef452daa)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)", "craft-update", "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9)", "eframe", @@ -6617,7 +6616,7 @@ dependencies = [ "craft-pdf", "craft-pdn", "craft-psd", - "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1aff2841c9ee575eb24f82d578f0e69cef452daa)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)", "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9)", "craft-xcf", "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9)", diff --git a/Cargo.toml b/Cargo.toml index cd154da031..8713a6052b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -60,7 +60,7 @@ craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986 craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } # The UI framework uses its own shared snapshot. Its SVG sniff and gzip decoder # match this revision. Align all shared pins once both changes reach craft-libs main. -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "1aff2841c9ee575eb24f82d578f0e69cef452daa", features = ["tree-render", "tree-render-system-fonts"] } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "7b8c1eccea0c695a495ab279c9523e6efcc9b8be", features = ["tree-render", "tree-render-system-fonts"] } craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a6b9d9c986f7c4c399632d72d9a4a8c8ea0b86e9" } # Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563. From 5dcb91a891ed51d0837e2dd4e984189c46195887 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:58:04 +0100 Subject: [PATCH 19/85] Control channel: list and cancel every dialog by the id it replies with (#15544) Since the move onto the craft UI framework, four dialogs could not be driven by the id the control channel gave for them: - Keyboard Shortcuts and Menus draws outside the framework's dialog host, so ui.inspect never listed it and ui.dialog.cancel {"dialog": "shortcuts"} failed, leaving every command refused behind its modal. It is now listed under "shortcuts" while open (first: it draws beneath the host's dialogs), and ui.dialog.cancel with that id closes it without saving, as its Cancel does. ui.dialog.set/confirm/apply refuse it with a pointer to edit.keyboardShortcuts params. - Preferences replied "preferences" but is listed under its host id. It now replies with that id, or with the reason it did not open. - Select > Color Range replied {"dialog": {"Ok": id}}: json! serialised the Result. It now replies through dialog_reply like every other dialog, and an open that fails is an error instead of ok with {"Err": ...} inside. - The unsaved-changes prompt was listed under a number with only `choice`. It is listed as "discard" again with the documented command, document, remaining, choices and default, and ui.dialog.confirm/cancel resolve "discard" to it (docs/control-protocol.md, #4920). Tests drive each through the control channel (handle with a ControlRequest). Two existing tests change with the documented ids: the Preferences apply test asserted the old "preferences" reply, and the save-authorization helper fed the listed prompt id to the host lookup. docs/control-protocol.md now says which dialogs have fixed ids and what menu items reply. --- crates/ui-egui/src/control/dialogs.rs | 23 +++- crates/ui-egui/src/control/inspect.rs | 5 + crates/ui-egui/src/control/tests.rs | 109 +++++++++++++++++- crates/ui-egui/src/dialogs/discard_ui.rs | 37 ++++++ crates/ui-egui/src/menus/invoke.rs | 4 +- crates/ui-egui/src/prefs/kys_import.rs | 4 +- crates/ui-egui/src/prefs/prefs_ui/dialogs.rs | 9 +- .../ui-egui/src/prefs/prefs_ui/shortcuts.rs | 23 +++- docs/control-protocol.md | 6 +- 9 files changed, 201 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/control/dialogs.rs b/crates/ui-egui/src/control/dialogs.rs index 3e40a1788a..08eb3f28a3 100644 --- a/crates/ui-egui/src/control/dialogs.rs +++ b/crates/ui-egui/src/control/dialogs.rs @@ -360,9 +360,26 @@ pub(crate) fn method(app: &mut PhotocraftApp, ctx: &egui::Context, req: &Control if !matches!(req.method.as_str(), "ui.dialog.set" | "ui.dialog.confirm" | "ui.dialog.cancel" | "ui.dialog.apply") { return None; } - let id = match dialog_id(host(app), p) { - Ok(id) => id, - Err(e) => return Some(err(e)), + // Keyboard Shortcuts and Menus draws outside the host: Cancel closes it; its changes go through + // `edit.keyboardShortcuts` params (#15544). + if p.get("dialog").and_then(Value::as_str) == Some(crate::prefs_ui::shortcuts::CONTROL_ID) { + return Some(match req.method.as_str() { + "ui.dialog.cancel" if crate::prefs_ui::shortcuts::cancel(app) => ok(Value::Null), + "ui.dialog.cancel" => err("Keyboard Shortcuts and Menus is not open"), + _ => err("Keyboard Shortcuts and Menus takes its changes as `edit.keyboardShortcuts` params; `ui.dialog.cancel` closes it"), + }); + } + // The unsaved-changes prompt is listed as "discard" and answered by that id. + let id = if p.get("dialog").and_then(Value::as_str) == Some(crate::discard_ui::CONTROL_ID) { + match crate::discard_ui::host_id(app) { + Some(id) => id, + None => return Some(err("no unsaved-changes prompt is open")), + } + } else { + match dialog_id(host(app), p) { + Ok(id) => id, + Err(e) => return Some(err(e)), + } }; Some(match req.method.as_str() { "ui.dialog.set" => set(app, ctx, id, p), diff --git a/crates/ui-egui/src/control/inspect.rs b/crates/ui-egui/src/control/inspect.rs index b4ac2a24f6..5c71c68dd7 100644 --- a/crates/ui-egui/src/control/inspect.rs +++ b/crates/ui-egui/src/control/inspect.rs @@ -87,6 +87,11 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { // The framework host's dialogs in their one stack order (top last). let mut dialogs = craft::automation::dialogs::inspect(&app.framework.dialogs); crate::layer_style::describe_params(app, &mut dialogs); + crate::discard_ui::describe(app, &mut dialogs); + // Keyboard Shortcuts and Menus draws beneath the host's dialogs, outside the host (#15544). + if let (Some(shortcuts), Some(list)) = (crate::prefs_ui::shortcuts::inspect(app), dialogs.as_array_mut()) { + list.insert(0, shortcuts); + } // Last frame's task bar rect, unless the bar can't show now (hidden by `ui.set` before the // next draw). let task_bar_rect = app.ui.task_bar_shown.filter(|_| crate::crop_task_bar::eligible(app)); diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index aa8e65df7a..2b6c55355e 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -986,11 +986,11 @@ fn preferences_apply_is_available_over_control_without_closing() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); let ctx = app.ctx().clone(); let r = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "edit.preferences.interface"})); - // The Preferences window is held by the app; control addresses it by the id `ui.inspect` lists - // and the reply names it by its key. + // The Preferences window is held by the app; control addresses it by the id `ui.inspect` lists, + // and the reply names it by that id (#15544). let listed = dialogs(&mut app, &ctx); let window = listed.iter().find(|d| d["key"] == "preferences").expect("the Preferences window is listed"); - assert_eq!(r["result"]["dialog"], window["key"], "{r}"); + assert_eq!(r["result"]["dialog"], window["id"], "{r}"); let id = window["id"].clone(); let mut values = window["fields"]["values"].clone(); values["interface"]["uiScale"] = json!("200"); @@ -1354,7 +1354,8 @@ fn dirty_close_prompted() -> (Box, egui::Context, std::rc::Rc Result<(), String> { let prompt = top_dialog(app, ctx)["id"].clone(); if synthetic { - let id = craft::automation::dialogs::dialog_id(&app.framework.dialogs, &json!({"dialog": prompt})).expect("the prompt is listed"); + assert_eq!(prompt, crate::discard_ui::CONTROL_ID, "the prompt is listed as discard"); + let id = crate::discard_ui::host_id(app).expect("the prompt is open"); app.automation_input = true; let r = crate::dialogs::confirm(app, ctx, id); app.automation_input = false; @@ -2223,3 +2224,103 @@ fn shift_right_menu_choose_rejects_bad_choices_and_sets_the_tool() { shift_right(&mut app, "magicEraser"); assert!(inspect(&app, &ctx)["brushModeMenu"].is_null()); } + +/// A fresh app with a document, as a control client finds it, and the context the control channel runs on. +fn app_with_document() -> (Box, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + let ctx = app.ctx().clone(); + (app, ctx) +} + +/// The id `ui.menu.invoke {id, wait: false}` replied for the dialog it opened. +fn invoked_dialog(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str) -> Value { + let reply = call(app, ctx, "ui.menu.invoke", json!({"id": id, "wait": false})); + assert_eq!(reply["ok"], true, "{id}: {reply}"); + crate::canvas::testing::frame(app); + reply["result"]["dialog"].clone() +} + +/// #15544: Keyboard Shortcuts and Menus is listed under the id its menu items reply with, and +/// `ui.dialog.cancel` with that id closes it, so a control client is never stuck behind it. +#[test] +fn keyboard_shortcuts_is_listed_and_cancelled_by_the_id_invoke_replies() { + for command in ["edit.keyboardShortcuts", "edit.menus"] { + let (mut app, ctx) = app_with_document(); + let id = invoked_dialog(&mut app, &ctx, command); + assert!(id.is_string(), "{command}: the reply names the dialog: {id}"); + let listed = dialogs(&mut app, &ctx); + assert!(listed.iter().any(|d| d["id"] == id), "{command}: {id} is listed in {listed:?}"); + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "select.all"}))["ok"], false, "{command}: the dialog is modal"); + let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id})); + assert_eq!(cancelled["ok"], true, "{command}: {cancelled}"); + assert!(!crate::prefs_ui::shortcuts_open(&app), "{command}: Cancel closed it"); + assert!(dialogs(&mut app, &ctx).is_empty()); + assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id}))["ok"], false, "{command}: nothing left to cancel"); + let next = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "select.all"})); + assert_eq!(next["ok"], true, "{command}: commands run again: {next}"); + } +} + +/// #15544: Preferences replies with the id `ui.inspect` lists it under, and cancelling that id closes it. +#[test] +fn preferences_replies_with_the_id_it_is_listed_under() { + let (mut app, ctx) = app_with_document(); + let id = invoked_dialog(&mut app, &ctx, "edit.preferences.interface"); + let listed = dialogs(&mut app, &ctx); + assert_eq!(listed.len(), 1, "{listed:?}"); + assert_eq!(listed[0]["id"], id, "the reply is the listed id"); + assert_eq!(listed[0]["key"], "preferences"); + let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id})); + assert_eq!(cancelled["ok"], true, "{cancelled}"); + crate::canvas::testing::frame(&mut app); + assert!(dialogs(&mut app, &ctx).is_empty()); + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "select.all"}))["ok"], true); +} + +/// #15544: Select › Color Range… replies with the bare id, as every other dialog does, not a `Result` around it. +#[test] +fn color_range_replies_with_the_bare_dialog_id() { + let (mut app, ctx) = app_with_document(); + let id = invoked_dialog(&mut app, &ctx, "select.colorRange"); + assert!(id.is_string(), "a bare id, not a wrapper: {id}"); + assert_eq!(top_dialog(&mut app, &ctx)["id"], id); + assert_eq!(top_dialog(&mut app, &ctx)["key"], "select.colorRange"); + let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id})); + assert_eq!(cancelled["ok"], true, "{cancelled}"); + assert!(dialogs(&mut app, &ctx).is_empty()); +} + +/// #15544: the unsaved-changes prompt is listed as `"discard"` with the command it holds back, the document it +/// asks about, how many are left and the choices, and `ui.dialog.confirm` / `ui.dialog.cancel` take that id +/// (docs/control-protocol.md). +#[test] +fn the_unsaved_changes_prompt_is_listed_as_discard_and_answered_by_that_id() { + let (mut app, ctx) = app_with_document(); + app.run("layer.new.layer", json!({})).unwrap(); + let prompt = |app: &mut PhotocraftApp| dialogs(app, &ctx).into_iter().find(|d| d["id"] == "discard"); + assert!(prompt(&mut app).is_none()); + // Close the changed document: the prompt is listed; Cancel keeps the document. + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "file.close"}))["ok"], true); + crate::canvas::testing::frame(&mut app); + let listed = prompt(&mut app).unwrap_or_else(|| panic!("listed as discard: {:?}", dialogs(&mut app, &ctx))); + let name = app.session.active().unwrap().doc.name.clone(); + assert_eq!(listed["fields"]["command"], "file.close"); + assert_eq!(listed["fields"]["document"], name.as_str()); + assert_eq!(listed["fields"]["remaining"], 1); + assert_eq!(listed["fields"]["choices"], json!(["save", "dontSave", "cancel"])); + let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"})); + assert_eq!(cancelled["ok"], true, "{cancelled}"); + crate::canvas::testing::frame(&mut app); + assert!(prompt(&mut app).is_none()); + assert_eq!(app.session.documents().len(), 1, "Cancel keeps the document"); + assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"}))["ok"], false, "nothing left to answer"); + // Don't Save by that id closes it. + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "file.close"}))["ok"], true); + crate::canvas::testing::frame(&mut app); + let answered = call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "discard", "choice": "dontSave"})); + assert_eq!(answered["ok"], true, "{answered}"); + crate::canvas::testing::frame(&mut app); + assert!(app.session.documents().is_empty(), "Don't Save closed the document"); +} diff --git a/crates/ui-egui/src/dialogs/discard_ui.rs b/crates/ui-egui/src/dialogs/discard_ui.rs index 8ca632d0c7..f96391a6fb 100644 --- a/crates/ui-egui/src/dialogs/discard_ui.rs +++ b/crates/ui-egui/src/dialogs/discard_ui.rs @@ -418,6 +418,43 @@ pub(crate) fn authorize_save(app: &PhotocraftApp, from_control: bool) -> Result< } } +/// The id the control channel knows the prompt by: `ui.inspect` lists it under this id, and `ui.dialog.confirm` and +/// `ui.dialog.cancel` answer it by it (docs/control-protocol.md, #4920, #15544). +pub const CONTROL_ID: &str = "discard"; + +/// The host's id of the open question, for a control request naming [`CONTROL_ID`]. +pub(crate) fn host_id(app: &PhotocraftApp) -> Option { + app.framework.dialogs.get::().map(craft::ui::dialog::StackDialog::id) +} + +/// Lists the open question in `dialogs` (the host's `ui.inspect` entries) under [`CONTROL_ID`], its fields adding the +/// command it holds back, the document it asks about, how many are left to answer, the choices `ui.dialog.confirm` +/// takes and the default one. +pub(crate) fn describe(app: &PhotocraftApp, dialogs: &mut Value) { + let Some(key) = host_id(app).map(|id| id.value().to_string()) else { return }; + let Some(entry) = dialogs.as_array_mut().and_then(|list| list.iter_mut().find(|d| d["id"] == key.as_str())) else { return }; + entry["id"] = json!(CONTROL_ID); + let Some(p) = app.discard.as_ref() else { return }; + let name = p.docs.first().and_then(|&doc| index_of(app, doc)).and_then(|i| app.session.documents().get(i)).map(|d| d.doc.name.clone()); + let reverts = p.id == "file.revert"; + let choices: &[&str] = match (reverts, p.docs.len() > 1) { + (true, _) => &["dontSave", "cancel"], + (false, false) => &["save", "dontSave", "cancel"], + (false, true) => &["save", "saveAll", "dontSave", "dontSaveAll", "cancel"], + }; + let described = json!({ + "command": p.id, + "document": name, + "remaining": p.docs.len(), + "choices": choices, + "default": if reverts { "dontSave" } else { "save" }, + }); + match entry.get_mut("fields").and_then(Value::as_object_mut) { + Some(fields) => fields.extend(described.as_object().cloned().unwrap_or_default()), + None => entry["fields"] = described, + } +} + /// The command the prompt holds back and its params, for the automation policy to see before a /// control client answers it. pub fn pending_command(app: &PhotocraftApp) -> Option<(String, Value)> { diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index c7e1cf2378..5f442d0bc5 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -523,9 +523,7 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: "select.findLayers" => crate::layer_filter_ui::find::invoke(app, params), // Photoshop's "Select and Mask…" is the engine's select.refineEdge. // Select › Color Range… from the menu: the dialog (with params: the engine directly). - "select.colorRange" if params.as_object().is_none_or(|o| o.is_empty()) => { - Ok(json!({"dialog": crate::color_range_ui::open(app).map(|dialog| dialog.value().to_string())})) - } + "select.colorRange" if params.as_object().is_none_or(|o| o.is_empty()) => crate::color_range_ui::open(app).map(dialog_reply), // Layer › New Fill Layer › Pattern… from the menu: the Pattern Fill dialog (with params: // the engine directly). photocraft_engine::pattern_fill_cmds::CREATE if params.as_object().is_none_or(|o| o.is_empty()) => { diff --git a/crates/ui-egui/src/prefs/kys_import.rs b/crates/ui-egui/src/prefs/kys_import.rs index 8d45d3a61f..bdec2dd9f0 100644 --- a/crates/ui-egui/src/prefs/kys_import.rs +++ b/crates/ui-egui/src/prefs/kys_import.rs @@ -14,7 +14,7 @@ use craft::keymap::import::kys; use craft::menu::shortcuts::{ImportOffer, OfferAnswer, OfferRecord}; use craft::ui::dialog::{DialogResult, StartupStage}; -use serde_json::{Value, json}; +use serde_json::Value; use crate::PhotocraftApp; use crate::prefs_ui::shortcuts::{draft_keymap, import_options, kys_text, profiles_of, queue_import, save_keys}; @@ -28,7 +28,7 @@ pub const IMPORTED_PREF: &str = "photoshopShortcuts"; pub fn open_bytes(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Result { let text = kys_text(name, bytes)?; queue_import(app, text); - Ok(json!({"dialog": "shortcuts"})) + Ok(crate::prefs_ui::shortcuts::control_reply()) } fn remember(app: &mut PhotocraftApp, record: &OfferRecord) { diff --git a/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs b/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs index 1fc4722e94..64a0727d53 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs @@ -41,17 +41,20 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &V } if let Some(section) = id.strip_prefix("edit.preferences.") { open_preferences(app, section); - return Some(Ok(json!({"dialog": "preferences"}))); + // The id `ui.inspect` lists the window under, as every hosted dialog replies (#15544); the status says why it + // did not open. + let opened = app.framework.dialogs.get::().map(|d| json!({"dialog": d.id().value().to_string()})); + return Some(opened.ok_or_else(|| app.ui.status.clone())); } let dialog = |d: Result| Some(d.map(|d| json!({"dialog": d.value().to_string()}))); match id { "edit.keyboardShortcuts" => { super::shortcuts::open(app, 0); - Some(Ok(json!({"dialog": "shortcuts"}))) + Some(Ok(super::shortcuts::control_reply())) } "edit.menus" => { super::shortcuts::open(app, 1); - Some(Ok(json!({"dialog": "shortcuts"}))) + Some(Ok(super::shortcuts::control_reply())) } "edit.toolbar" => { crate::panels::toolbar::open_drawer(app); diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs index 282c69dba3..9f14c5ee74 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs @@ -117,6 +117,27 @@ pub fn shortcuts_open(app: &PhotocraftApp) -> bool { app.prefs_rt.shortcuts.is_some() } +/// The id the control channel knows the dialog by: Edit › Keyboard Shortcuts and Edit › Menus reply with it, +/// `ui.inspect` lists the dialog under it, and `ui.dialog.cancel` closes it. The dialog draws outside the framework's +/// dialog host, which has no id for it (#15544). +pub(crate) const CONTROL_ID: &str = "shortcuts"; + +/// The reply of a command that opened the dialog. +pub(crate) fn control_reply() -> Value { + json!({"dialog": CONTROL_ID}) +} + +/// The dialog as `ui.inspect` lists it among the dialogs while it is open, in the host's entry shape. +pub(crate) fn inspect(app: &PhotocraftApp) -> Option { + shortcuts_open(app).then(|| json!({"id": CONTROL_ID, "key": "edit.keyboardShortcuts", "parent": null, "fields": {}})) +} + +/// Cancel for a control client, as the dialog's Cancel: the session goes and nothing it edited is saved. False with +/// the dialog closed. +pub(crate) fn cancel(app: &mut PhotocraftApp) -> bool { + app.prefs_rt.shortcuts.take().is_some() +} + /// Whether the dialog is recording a chord: the key goes to the recorder and runs nothing, and the /// native menu bar pauses its key equivalents. pub fn recording(app: &PhotocraftApp) -> bool { @@ -213,7 +234,7 @@ fn ask_import(app: &mut PhotocraftApp, state: &mut DialogState) { let picked = app.pick_file_bytes_filtered(&["kys", "psp", "json"], |app, name, bytes| { let text = kys_text(&name, &bytes)?; queue_import(app, text); - Ok(json!({"dialog": "shortcuts"})) + Ok(control_reply()) }); if let Err(e) = picked { state.show_error(e); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 4aed18c1c4..22225621a7 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -126,13 +126,13 @@ The transport is the framework's control server (`craft::automation::server` in - Gradient Overlay color stops use `colorPicker {parent, effect, field: "stops", stop: index}`; the stop must exist. - `ui.dialog.open {kind:"colorPicker", textStyle:{kind:"character"|"paragraph", id:u32}}` opens the shared Color Picker for an explicitly enabled Color attribute in Style Options. It opens the matching style panel/editor after validation; inherited colors must first be enabled through the existing style command. The picker reports its bound document/revision/style under `__textStyleColor` in `ui.inspect`. Changes preview in an isolated document; OK runs the existing style `set` command once, Cancel changes nothing. Document edits/switches or closed/changed Style Options discard the picker. `textStyle` cannot be combined with `parent`, `effect`, `field` or `target`. - - Every dialog is hosted: `ui.inspect`'s `dialogs` lists them in stack order (top last) with a decimal-string `id`, and `ui.dialog.set`, `ui.dialog.confirm`, `ui.dialog.cancel` and `ui.dialog.apply` take that id as `dialog`, or `"top"` for the top one (the shell's workspace and pixel-aspect dialogs and the unsaved-changes prompt are listed like any other; the prompt's `ui.dialog.confirm` takes a `choice`). OK runs the dialog's command and keeps the dialog open if it fails. Camera Raw and the other full-window workspaces are hosted dialogs too: `{ui: …}` requests and `ui.dialog.set` field keys drive them (see Camera Raw below) + - Every dialog is hosted: `ui.inspect`'s `dialogs` lists them in stack order (top last) with a decimal-string `id`, and `ui.dialog.set`, `ui.dialog.confirm`, `ui.dialog.cancel` and `ui.dialog.apply` take that id as `dialog`, or `"top"` for the top one (the shell's workspace and pixel-aspect dialogs are listed like any other). A menu item that opens a dialog replies `{"dialog": ""}` with the id it is listed under. Two dialogs have a fixed id instead: the unsaved-changes prompt is `"discard"` (below), and Keyboard Shortcuts and Menus (Edit › Keyboard Shortcuts, Edit › Menus) is `"shortcuts"`, listed first while it is open (it draws beneath the other dialogs); `ui.dialog.cancel {"dialog": "shortcuts"}` closes it without saving, as its Cancel does, and its changes go through `edit.keyboardShortcuts` params rather than `ui.dialog.set` or `ui.dialog.confirm`, which refuse it; `"top"` never names it. OK runs the dialog's command and keeps the dialog open if it fails. Camera Raw and the other full-window workspaces are hosted dialogs too: `{ui: …}` requests and `ui.dialog.set` field keys drive them (see Camera Raw below) - The unsaved-changes prompt (closing a document, Revert, quitting with unsaved work) is listed in `ui.inspect`'s `dialogs` with the id `"discard"` while it is up: `fields` gives the waiting `command` (`file.close`, `file.exit`…), the `document` it asks about, how many are `remaining`, and its `choices`. `ui.dialog.confirm` takes `{"dialog": "discard", "choice": "save" | "saveAll" | "dontSave" | "dontSaveAll" | "cancel"}` (default `save`; Revert takes `dontSave` or `cancel`) and answers it as the window's buttons do, one document at a time. `saveAll` and `dontSaveAll` tick "Apply to All": they answer for every document still to ask about, and are listed in `choices` only while more than one is left. A document whose save is cancelled or fails is asked about again; `ui.dialog.cancel` with `{"dialog": "discard"}` cancels it. Save of an untitled document opens the save dialog first, so the reply's `fileDialog` is true and the prompt stays open until that is answered. - A save dialog's answer that PhotoCraft changes, by giving a name without an extension the suggested file's or by lowercasing the extension (Preferences › File Handling › Lowercase Extension), opens a replace prompt when a file exists under the changed name: a dialog with `__replaceSaved`, `message`, `detail` and `path` (the file the save would replace). `ui.dialog.confirm` writes the file; `ui.dialog.cancel` ends the save without writing, as Cancel in the save dialog does. The file dialog counts as open until the prompt is answered. A name that differs only in letter case and reaches the same file (Windows and macOS by default) does not open it. - Layer Style (`layerStyle {effect?}` opens on that effect kind): the fields hold the dialog's whole state, so agents read and drive it like a user. `effects` lists every effect instance in the layer's order as `{id, kind, on, params, fx}` (`fx` is the effect snapshot the dialog loaded; OK edits that snapshot with `params`, so anything the dialog doesn't model survives). `selected` picks the page (`blendingOptions` or an instance id), `preview` (default on) gates the live canvas preview, `p:blendingOptions` edits blend mode/opacity/fill opacity, and `patternList` names the usable patterns. OK replaces the layer's effects in one step (`layer.layerStyle.replace`); Cancel discards. "New Style…" saves the pending state via `style.presets.new {effects}`, a swatch click applies a style preset, and Make/Reset Default use `layer.layerStyle.makeDefault` / `layer.layerStyle.defaultFor` - Gradient Overlay exposes `params.method` (`smooth`, `perceptual`, `linear`, `classic`). `custom` denotes an existing curve without a recorded method and preserves it. Choosing a method retains all recorded source colour stops. If no source record exists (including baked PSD imports), choosing a method rebuilds from the two end colours, matching legacy command behaviour; the old curve stays unchanged until that choice. Later endpoint edits rebuild the colour curve using the recorded method. The source stops, smoothness and method survive dialog reopening, undo/redo and native `.pcraft` saves. Saving a style preset through "New Style…" may lose the multi-stop source curve: it passes only params to `style.presets.new`, and `effect_from_params` rebuilds the effect from the default gradient. PSD export continues to write the baked appearance; reopening that PSD shows Custom because editable interpolation metadata is not exported yet. Opacity interpolation and the multi-stop editor are separate work. - Gradient Overlay's `params.offset` is the gradient's centre as a fraction of the layer's bounds (`[x, y]`, `[0, 0]` centred, as the renderer takes it). With the dialog on a Gradient Overlay page, a drag on the image moves it by the pointer's movement over the layer's size, as a drag on a shadow page moves the shadow (#10763). - - Preferences (`ui.menu.invoke {id: "edit.preferences.interface"}`) exposes the sections in its `values` field. Apply (`ui.dialog.apply`) and OK (`ui.dialog.confirm`) on Preferences are refused over control because automation denies whole-preferences updates and filesystem-bearing preference sections. A refused `ui.dialog.apply` returns an error and keeps the dialog open; a refused `ui.dialog.confirm` returns an error but closes and removes the dialog. `ui.dialog.cancel` closes the dialog without saving. Individual safe preferences can instead be changed with `engine.execute` using `prefs.set` (e.g. `{"command": "prefs.set", "params": {"path": "interface.showTooltips", "value": false}}`). Settings marked for the next launch still require a restart. + - Preferences (`ui.menu.invoke {id: "edit.preferences.interface"}`, which replies with the id `ui.inspect` lists the window under, its `key` being `preferences`) exposes the sections in its `values` field. Apply (`ui.dialog.apply`) and OK (`ui.dialog.confirm`) on Preferences are refused over control because automation denies whole-preferences updates and filesystem-bearing preference sections. A refused `ui.dialog.apply` returns an error and keeps the dialog open; a refused `ui.dialog.confirm` returns an error but closes and removes the dialog. `ui.dialog.cancel` closes the dialog without saving. Individual safe preferences can instead be changed with `engine.execute` using `prefs.set` (e.g. `{"command": "prefs.set", "params": {"path": "interface.showTooltips", "value": false}}`). Settings marked for the next launch still require a restart. - Select › Select and Mask… (`ui.menu.invoke {id: "select.selectAndMask"}`, Ctrl+Alt+R) opens Photoshop's workspace; `ui.inspect` reports it as `distort.selectAndMask`. Drive it with `ui.menu.invoke {id: "select.selectAndMask", params: {ui: {…}}}`: `tool` (`quick|refineEdge|brush|object|lasso|polygonalLasso|hand|zoom`), `mode` (`add|subtract`), `size`, `hardness`, `sampleAllLayers`, `hideView` (true shows the image without the view, as holding X does), `stroke: {points: [[x,y],…], alt?}` (a drag with the current tool in document px: Object Selection takes a click or the rectangle's corners, the lassos the polygon), `selectSubject`, `clearSelection`, `invert`, the settings (`view`, `opacity`, `showEdge`, `showOriginal`, `realTimeRefinement`, `highQualityPreview`, `overlayColor`, `indicates`, `radius`, `smartRadius`, `smooth`, `feather`, `contrast`, `shiftEdge`, `decontaminate`, `amount`, `output`, `remember`), `undo`, `redo`, `reset`, `waitPreview`, `commit` (OK: `select.refineEdge` with the workspace's `edits` and `refineStrokes`, one history step) and `cancel`. The reply describes the workspace (`edits`, `strokes`, `selectedProxyPixels`, `previewReady`, …). - Edit › Fill… (`ui.menu.invoke {id: "edit.fill"}`, Shift+F5, Shift+Backspace) opens the Fill dialog; its fields are `edit.fill`'s params (`contents`, `color`, `pattern`, `colorAdaptation`, `mode`, `opacity`, `preserveTransparency`), and OK remembers them in the preferences (`dialogs["edit.fill"]`). - Image › Adjustments › Levels… (`ui.menu.invoke {id: "image.adjustments.levels"}`): `__clipping` (`"shadows"` or `"highlights"`; `null` turns it off) shows Photoshop's clipping display on the canvas instead of the preview, what the black or white Input slider clips. The app sets it while Alt and the mouse button are held on one of those sliders; it never reaches OK. The display shows only for RGB and Grayscale documents whose target is a raster layer's pixels, on the main canvas. Other targets (CMYK or Lab documents, a channel, mask or Quick Mask target, a non-pixel layer, a Smart Filter) accept the value and keep the normal preview. @@ -336,7 +336,7 @@ when it starts); see [Without `--control`](#without---control-preferences--integ | `prefs.set` | `{"path":"cursors.painting","value":"precise"}` or `{"values":{"unitsAndRulers.rulers":"cm","guidesGridAndSlices.gridColor":"#ff8800"}}`. Values are validated (choices, ranges, `#rrggbb` colours, shortcut syntax); a batch applies all or nothing. A section path takes an object and merges it key by key | | `prefs.reset` | `{"path":"performance"}` (a section or key); no path resets everything. An individual `shortcuts.` or `menus.colors.` reset removes the override and returns `null`, including when it is already absent | | `edit.preferences.
` | the section's values; in the app (no params) it opens the Preferences dialog on that section | -| `edit.keyboardShortcuts` | `{"set":{"edit.fill":"Cmd+Shift+F"},"reset":true\|["id",…],"removeConflicts":true,"filter":"blur","list":false,"importKys":"<.kys XML>"}`: returns overrides, matching commands and conflicts. A shortcut moved to another command is removed from its old owner unless `removeConflicts` is false. `""` removes a shortcut, `null` restores the default. The held temporary tools are bindable too: `tools.temporary.hand` (Space; also repositions a selection being drawn), `tools.temporary.zoomIn` (Cmd+Space), `tools.temporary.zoomOut` (Alt+Space; Alt added to a held Zoom In, Cmd+Alt+Space, zooms out too), `tools.temporary.erase` (`` ` ``; with the Brush or Pencil, a stroke started while it is held is in Clear mode, `paint.stroke`/`paint.pencil` `"mode": "clear"`, erasing with that tool's brush); they list with `"hold": true`. ⌘ (Ctrl off the Mac) held alone is the Move tool with the painting, retouching and other non-selection tools, as in Photoshop; it is a modifier, not a binding. `importKys` applies a Photoshop `.kys` set (the file's XML text, at most 4 MiB): rows are matched to commands by our id (`pc-id`, in sets PhotoCraft exported) or else by menu label, a key equal to the default restores it, keys also given in `set` win, and the result gains `import` (`name`, `imported`, `set`, `unknown`, `unreadable`, `alternates`, `toolKeys`, `windows`). A set saved by Photoshop on Windows (no ⌘ or Opt anywhere, Ctrl used) reads Ctrl as the primary modifier, so `Ctrl+L` is the `Cmd+L` default (`windows: true`). Tool keys are matched to tools by `pc-id` or name (a tool's own letter keeps its Shift cycling); `import.tools` lists the keys given. In the app it opens Keyboard Shortcuts and Menus, whose Import Shortcuts… button loads a `.kys` set into the dialog (opening or dropping a `.kys`, or Photoshop's live `Keyboard Shortcuts.psp`, does the same). On a desktop with Photoshop installed, the first launch that has no shortcut overrides yet asks whether to import the newest install's live set (Import / Don't Import; `ui.inspect` shows it as `kysOffer`); the answer is recorded in the preferences as `dialogs.photoshopShortcuts`, so it is asked once. **Sets** (Edit › Keyboard Shortcuts › Set): `useSet` loads a saved set's bindings (`""` or `"PhotoCraft Defaults"`: the defaults) before the call's other changes; then `saveSet` saves the bindings as they end up under a name and uses it, `deleteSet` removes one (the bindings stay), `sets` replaces every saved set (`{"": {"shortcuts": {…}, "alternateShortcuts": {…}}}`, the dialog's OK) and `activeSet` names the set in use without loading it. Names are trimmed, 1–64 characters, at most 64 sets. Every reply has `sets`, `activeSet` (`""` for the defaults), `defaultsName` and `modified` (the bindings differ from the set in use). `exportKys: true` adds `kys`, the bindings of every bindable command and tool as a `.kys` file (Photoshop's macOS key spelling; each row carries our id as `pc-id`, so the file imports back exactly); `summarize: true` (or `{"mac": false}`) adds `html`, Photoshop's Summarize page. A bad parameter anywhere in the call, an export path that can't be written included, changes nothing. **Headless parity:** the shell's commands (View › Zoom In, the panels; `photocraft_engine::shell_commands::SHELL_COMMANDS`) and the tools (`tools.select.`, listed with `"tool": true`) are bindable, listed, imported, exported and checked for conflicts without the UI; tools may share a key (they cycle with Shift, so a shared letter is no conflict), while a command given a tool's key takes it from the tools. Keys the system takes first (Alt+Tab, Alt+F4, Ctrl+Alt+Delete everywhere but the Mac, plus Ctrl+Esc and Ctrl+Shift+Esc on Windows and Ctrl+Alt+F1–F12 on Linux; ⌘Tab, ⌘`, ⌘⌥Esc on the Mac) are refused, and left out of an imported set (`import.reserved`). Files: `importKys: {"path": …}` reads a `.kys`, `exportKys: {"path": …}` and `summarize: {"path": …}` write the file (the reply has `kysPath` / `htmlPath`); automation (MCP) refuses these paths, as it does `actions.save`'s | +| `edit.keyboardShortcuts` | `{"set":{"edit.fill":"Cmd+Shift+F"},"reset":true\|["id",…],"removeConflicts":true,"filter":"blur","list":false,"importKys":"<.kys XML>"}`: returns overrides, matching commands and conflicts. A shortcut moved to another command is removed from its old owner unless `removeConflicts` is false. `""` removes a shortcut, `null` restores the default. The held temporary tools are bindable too: `tools.temporary.hand` (Space; also repositions a selection being drawn), `tools.temporary.zoomIn` (Cmd+Space), `tools.temporary.zoomOut` (Alt+Space; Alt added to a held Zoom In, Cmd+Alt+Space, zooms out too), `tools.temporary.erase` (`` ` ``; with the Brush or Pencil, a stroke started while it is held is in Clear mode, `paint.stroke`/`paint.pencil` `"mode": "clear"`, erasing with that tool's brush); they list with `"hold": true`. ⌘ (Ctrl off the Mac) held alone is the Move tool with the painting, retouching and other non-selection tools, as in Photoshop; it is a modifier, not a binding. `importKys` applies a Photoshop `.kys` set (the file's XML text, at most 4 MiB): rows are matched to commands by our id (`pc-id`, in sets PhotoCraft exported) or else by menu label, a key equal to the default restores it, keys also given in `set` win, and the result gains `import` (`name`, `imported`, `set`, `unknown`, `unreadable`, `alternates`, `toolKeys`, `windows`). A set saved by Photoshop on Windows (no ⌘ or Opt anywhere, Ctrl used) reads Ctrl as the primary modifier, so `Ctrl+L` is the `Cmd+L` default (`windows: true`). Tool keys are matched to tools by `pc-id` or name (a tool's own letter keeps its Shift cycling); `import.tools` lists the keys given. In the app it opens Keyboard Shortcuts and Menus (`ui.menu.invoke` replies `{"dialog": "shortcuts"}`, the id `ui.inspect` lists it under and `ui.dialog.cancel` closes it by), whose Import Shortcuts… button loads a `.kys` set into the dialog (opening or dropping a `.kys`, or Photoshop's live `Keyboard Shortcuts.psp`, does the same). On a desktop with Photoshop installed, the first launch that has no shortcut overrides yet asks whether to import the newest install's live set (Import / Don't Import; `ui.inspect` shows it as `kysOffer`); the answer is recorded in the preferences as `dialogs.photoshopShortcuts`, so it is asked once. **Sets** (Edit › Keyboard Shortcuts › Set): `useSet` loads a saved set's bindings (`""` or `"PhotoCraft Defaults"`: the defaults) before the call's other changes; then `saveSet` saves the bindings as they end up under a name and uses it, `deleteSet` removes one (the bindings stay), `sets` replaces every saved set (`{"": {"shortcuts": {…}, "alternateShortcuts": {…}}}`, the dialog's OK) and `activeSet` names the set in use without loading it. Names are trimmed, 1–64 characters, at most 64 sets. Every reply has `sets`, `activeSet` (`""` for the defaults), `defaultsName` and `modified` (the bindings differ from the set in use). `exportKys: true` adds `kys`, the bindings of every bindable command and tool as a `.kys` file (Photoshop's macOS key spelling; each row carries our id as `pc-id`, so the file imports back exactly); `summarize: true` (or `{"mac": false}`) adds `html`, Photoshop's Summarize page. A bad parameter anywhere in the call, an export path that can't be written included, changes nothing. **Headless parity:** the shell's commands (View › Zoom In, the panels; `photocraft_engine::shell_commands::SHELL_COMMANDS`) and the tools (`tools.select.`, listed with `"tool": true`) are bindable, listed, imported, exported and checked for conflicts without the UI; tools may share a key (they cycle with Shift, so a shared letter is no conflict), while a command given a tool's key takes it from the tools. Keys the system takes first (Alt+Tab, Alt+F4, Ctrl+Alt+Delete everywhere but the Mac, plus Ctrl+Esc and Ctrl+Shift+Esc on Windows and Ctrl+Alt+F1–F12 on Linux; ⌘Tab, ⌘`, ⌘⌥Esc on the Mac) are refused, and left out of an imported set (`import.reserved`). Files: `importKys: {"path": …}` reads a `.kys`, `exportKys: {"path": …}` and `summarize: {"path": …}` write the file (the reply has `kysPath` / `htmlPath`); automation (MCP) refuses these paths, as it does `actions.save`'s | | `edit.menus` / `edit.toolbar` | `{"hide":["edit.fade"],"show":[…],"color":{"edit.fill":"red"},"reset":false}` / `{"hidden":["Sponge"],"order":[…]}` | | `edit.colorSettings` | `{"workingRgb":"display-p3","workingCmyk":"coated-cmyk","workingGray":"sgray","policyRgb":"preserve\|convert\|off",…,"askOnMismatch":true,"intent":"perceptual","bpc":true}`; honoured when opening files (`file.openAs`, the app's File › Open) and by Image › Mode and "working" profile specs. `color.profileMismatch {"action":"preserve\|convert\|discard\|assignWorking"}` answers the mismatch prompt | From ade6b80679109f7456074d85afe0dc2eb6278bb9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 21:19:08 +0100 Subject: [PATCH 20/85] WIP: trim the unclaimed slow tests (#15652) Co-Authored-By: Claude Opus 5.5 From 6f0861cc2344c6116ec21f2af6cd50e5a80c68eb Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 21:25:52 +0100 Subject: [PATCH 21/85] Tests: no GPU canvas, harness or render the ui-egui integration tests do not need (#15652) - batch_export_options: the Batch harness no longer installs the GPU canvas; the dialog is form data and the batch an engine job, so the first canvas refresh only built every compositor pipeline. - canvas_16f: the two 32-bit preview documents share one harness (one device and compositor build, not two). - ui_scale_canvas: UI scales 125% and 200% instead of 100/125/150/200; the canvas branches only on zoom x ppp being below 1, whole or fractional, and 125% and 200% reach every branch the four did. - pattern_preview_canvas: the points of one state are read from one settled render. Co-Authored-By: Claude Opus 5.5 --- .../ui-egui/tests/it/batch_export_options.rs | 6 +-- crates/ui-egui/tests/it/canvas_16f.rs | 52 +++++++++++++------ .../tests/it/pattern_preview_canvas.rs | 25 ++++----- crates/ui-egui/tests/it/ui_scale_canvas.rs | 6 ++- 4 files changed, 56 insertions(+), 33 deletions(-) diff --git a/crates/ui-egui/tests/it/batch_export_options.rs b/crates/ui-egui/tests/it/batch_export_options.rs index 250a852965..0bd1518069 100644 --- a/crates/ui-egui/tests/it/batch_export_options.rs +++ b/crates/ui-egui/tests/it/batch_export_options.rs @@ -24,9 +24,9 @@ fn harness() -> Harness { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); app.session.prefs.edit(|p| p.interface.language = "en".into()); - if let Some(rs) = cc.wgpu_render_state.as_ref() { - app.set_wgpu(rs.clone()); - } + // No `set_wgpu`: the Batch dialog is form data and the batch runs as an engine job, so nothing here reads the + // GPU canvas, whose first refresh would build every compositor pipeline (#15439, #15652). The harness keeps its + // wgpu renderer for `evidence`'s screenshots. app.run("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); app.run("actions.record", json!({"name": "Invert"})).unwrap(); app.run("image.adjustments.invert", json!({})).unwrap(); diff --git a/crates/ui-egui/tests/it/canvas_16f.rs b/crates/ui-egui/tests/it/canvas_16f.rs index 5831e80980..5d160fadea 100644 --- a/crates/ui-egui/tests/it/canvas_16f.rs +++ b/crates/ui-egui/tests/it/canvas_16f.rs @@ -177,9 +177,17 @@ impl Screen { /// Renders the app with `doc` open after `setup` commands (saving the PNG as `name` in the temp /// dir), or None when the GPU can't be used. fn screen(doc: Document, setup: &[(&str, serde_json::Value)], name: &str) -> Option { + screens(vec![(doc, setup, name)]).and_then(|mut shown| shown.pop()) +} + +/// [`screen`] for several documents in one app, opened and rendered in turn: one harness, so one GPU device and one +/// compositor build (#15439) instead of one per document (#15652). Each document's setup commands run while it is +/// the active one; View › 32-bit Preview Options is kept per document. +fn screens(cases: Vec<(Document, &[(&str, serde_json::Value)], &str)>) -> Option> { + let mut cases = cases.into_iter(); + let (doc, setup, name) = cases.next()?; let ok = Arc::new(AtomicBool::new(false)); let ok2 = ok.clone(); - let setup: Vec<(String, serde_json::Value)> = setup.iter().map(|(a, b)| (a.to_string(), b.clone())).collect(); let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { egui_kittest::Harness::builder() .with_size(egui::vec2(1000.0, 700.0)) @@ -205,17 +213,27 @@ fn screen(doc: Document, setup: &[(&str, serde_json::Value)], name: &str) -> Opt eprintln!("skipping: adapter can't render/filter Rgba16Float"); return None; } - // Outside the catch_unwind: a failing setup command fails the test instead of reading as - // "no GPU adapter" (#760). - for (id, p) in setup { - harness.state_mut().run(&id, p).unwrap_or_else(|e| panic!("setup command {id}: {e}")); + let mut shown = Vec::new(); + let mut case = Some((setup, name)); + while let Some((setup, name)) = case.take() { + // Outside the catch_unwind: a failing setup command fails the test instead of reading as + // "no GPU adapter" (#760). + for (id, p) in setup { + harness.state_mut().run(id, p.clone()).unwrap_or_else(|e| panic!("setup command {id}: {e}")); + } + harness.run_steps(6); + let img = harness.render().expect("render"); + let out = std::env::temp_dir().join(name); + let _ = img.save(&out); + eprintln!("screen: {}", out.display()); + shown.push(Screen { w: img.width(), h: img.height(), px: img.into_raw() }); + if let Some((doc, setup, name)) = cases.next() { + harness.state_mut().session.open_document(doc, None); + harness.state_mut().sync_views(); + case = Some((setup, name)); + } } - harness.run_steps(6); - let img = harness.render().expect("render"); - let out = std::env::temp_dir().join(name); - let _ = img.save(&out); - eprintln!("screen: {}", out.display()); - Some(Screen { w: img.width(), h: img.height(), px: img.into_raw() }) + Some(shown) } /// Distinct gray levels along a screen row inside `x0..x1`, and the largest step between @@ -242,20 +260,20 @@ fn thirty_two_bit_preview_exposes_values_above_one() { // A dark 32-bit ramp brightened +4 stops by View › 32-bit Preview Options: with an 8-bit // canvas texture its 0..1/16 range has 16 codes (banding); the float texture keeps it smooth. let doc = gradient(SampleType::F32, 2048, 1024, 0.0, 1.0 / 16.0); - let Some(img) = screen(doc, &[("view.thirtyTwoBitPreviewOptions", json!({"exposure": 4.0, "gamma": 1.0}))], "photocraft-canvas-16f-hdr-ramp.png") else { - return; - }; - let (n, _) = screen_levels(&img, img.h / 2, 150, 600); - assert!(n > 40, "{n} levels: banded"); // Values above 1.0 are brought into range by a negative exposure instead of clipped: 2.0 // at −3 stops shows as sRGB(lin(2.0) / 8) rather than sRGB(lin(1.0) / 8). let mut flat = Document::new("hdr", Size::new(512, 512), ColorMode::Rgb, SampleType::F32); let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::F32, true)); s.fill_rect(Rect::new(0, 0, 512, 512), &[2.0, 2.0, 2.0, 1.0]); flat.layers.push(Layer::new("bright", LayerContent::Raster(s))); - let Some(img) = screen(flat, &[("view.thirtyTwoBitPreviewOptions", json!({"exposure": -3.0, "gamma": 1.0}))], "photocraft-canvas-16f-hdr-flat.png") else { + let brighten = [("view.thirtyTwoBitPreviewOptions", json!({"exposure": 4.0, "gamma": 1.0}))]; + let darken = [("view.thirtyTwoBitPreviewOptions", json!({"exposure": -3.0, "gamma": 1.0}))]; + let Some(shown) = screens(vec![(doc, &brighten, "photocraft-canvas-16f-hdr-ramp.png"), (flat, &darken, "photocraft-canvas-16f-hdr-flat.png")]) else { return; }; + let [ramp, img] = &shown[..] else { panic!("two screens, got {}", shown.len()) }; + let (n, _) = screen_levels(ramp, ramp.h / 2, 150, 600); + assert!(n > 40, "{n} levels: banded"); let got = img.green(img.w * 2 / 5, img.h / 2) as f32; let dec = |v: f32| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }; let enc = |v: f32| if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; diff --git a/crates/ui-egui/tests/it/pattern_preview_canvas.rs b/crates/ui-egui/tests/it/pattern_preview_canvas.rs index edce249219..d7b6e71967 100644 --- a/crates/ui-egui/tests/it/pattern_preview_canvas.rs +++ b/crates/ui-egui/tests/it/pattern_preview_canvas.rs @@ -29,14 +29,17 @@ fn harness() -> Option { } } -/// The colour on screen at document point `at` (which may lie past the document). -fn sample(h: &mut Harness, at: [f32; 2]) -> [u8; 3] { +/// The colours on screen at document points `at` (which may lie past the document), read from one settled frame: +/// the points of one state share a render instead of settling and rendering the same frame again (#15652). +fn samples(h: &mut Harness, at: [[f32; 2]; N]) -> [[u8; 3]; N] { h.run_steps(6); let xf = photocraft_ui_egui::canvas::active_view(h.state()).expect("canvas view"); - let p = xf.to_screen(craft::behavior::kurbo::Point::new(f64::from(at[0]), f64::from(at[1]))); let img = h.render().expect("render"); - let px = img.get_pixel(p.x.round() as u32, p.y.round() as u32); - [px[0], px[1], px[2]] + at.map(|at| { + let p = xf.to_screen(craft::behavior::kurbo::Point::new(f64::from(at[0]), f64::from(at[1]))); + let px = img.get_pixel(p.x.round() as u32, p.y.round() as u32); + [px[0], px[1], px[2]] + }) } /// View › Pattern Preview, as the menu runs it. @@ -77,17 +80,15 @@ fn pattern_preview_repeats_the_document_on_gpu_and_cpu_canvases() { let path = if flip { "CPU" } else { "GPU" }; h.state_mut().ui.view.flip_horizontal = flip; h.state_mut().ui.view.pattern_preview = false; - let off = sample(&mut h, right); + let [off, band] = samples(&mut h, [right, [10.0, 50.0]]); assert!(!near(off, red) && !near(off, blue), "{path}: pasteboard without Pattern Preview, got {off:?}"); - assert!(near(sample(&mut h, [10.0, 50.0]), red), "{path}: the document's own band"); + assert!(near(band, red), "{path}: the document's own band"); toggle(&mut h); assert!(h.state().ui.view.pattern_preview); - let got = sample(&mut h, right); + let [got, under, diag] = samples(&mut h, [right, below, diagonal]); assert!(near(got, red), "{path}: copy to the right shows the left edge, got {got:?}"); - let got = sample(&mut h, below); - assert!(near(got, blue), "{path}: copy below, got {got:?}"); - let got = sample(&mut h, diagonal); - assert!(near(got, blue), "{path}: diagonal copy, got {got:?}"); + assert!(near(under, blue), "{path}: copy below, got {under:?}"); + assert!(near(diag, blue), "{path}: diagonal copy, got {diag:?}"); toggle(&mut h); assert!(!h.state().ui.view.pattern_preview); } diff --git a/crates/ui-egui/tests/it/ui_scale_canvas.rs b/crates/ui-egui/tests/it/ui_scale_canvas.rs index 927413a6cb..c661370ea6 100644 --- a/crates/ui-egui/tests/it/ui_scale_canvas.rs +++ b/crates/ui-egui/tests/it/ui_scale_canvas.rs @@ -86,7 +86,11 @@ fn assert_document_size_is_physical(gpu: bool) { let Some(mut h) = harness(gpu) else { return }; h.run_steps(4); const DOC: u32 = 60; - for ui_scale in ["100", "125", "150", "200"] { + // A fractional and an integer UI scale: the canvas sees the scale only as `pixels_per_point` (device px per doc px + // = zoom x ppp), and its sampling branches on that product being below 1, whole (or 2 and up) or fractional + // (`gpu_canvas::callback::filter_mode`). 125% gives 1.25 and 2.5 at the two zooms, as 150% would; 200% gives 2 and + // 4, covering 100%'s 1 and 2, where a dropped ppp could not show anyway (#15652). + for ui_scale in ["125", "200"] { { let app = h.state_mut(); while app.session.active().is_some() { From 493d2df62ff4adb9cf873436810cf1422e5db28e Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 22:14:12 +0100 Subject: [PATCH 22/85] Tests: trim the loops of the unclaimed slow tests that reach no new code (#15652) Each removed variant takes the same branch as one that stays, or is covered without the app or oracle cost by a named lower-level test; the commit's comments say which for every test. ui-egui: floating-document zoom (10 frames after Enter, not 60), Wide Angle (one depth per mode, alpha kept), Brush panel sections (only those Brush Settings draws; Brushes ignores the section), Camera Raw GPU (8 and 32 bits), enable rules (one app per world, a copied style for Paste only), Content-Aware Move preview (selection just past the coarse budget, smaller canvas). algo/compose/engine/gpu/format: Pixelate (Lab, cell 100, seed 37, tile 1), box blurs (Gaussian 40), Smart Blur (multichannel layouts cover every arm; Low and High), FFT sharpen gate (one depth), panorama batching (budgets at every split instead of a 47-step sweep), bevel and chisel threads (2 and 16), fused tone tiles (256 x 256, the U16 table threshold), live dabs (8 and 32 bits), Camera Raw GPU sizes (1600 x 240 wide case; the proxy-size per-pixel run lives in the clarity test), directory bundle (two modes; zip_cases has the matrix). Co-Authored-By: Claude Opus 5.5 --- crates/algo/src/blur/tests.rs | 3 +- crates/algo/src/blur2/smart_tests.rs | 17 +++--- crates/algo/src/panorama/parallel_tests.rs | 19 +++++-- crates/algo/src/pixelate/tests.rs | 13 +++-- crates/algo/src/sharpen/fft/tests.rs | 14 ++--- crates/compose/src/effects/tests.rs | 6 ++- crates/engine/src/cmd/retouch_cmds/tests.rs | 4 +- crates/engine/src/color_channels/tone.rs | 3 +- crates/format/tests/it/roundtrip.rs | 18 +++---- crates/gpu/tests/it/camera_raw.rs | 15 +++--- crates/ui-egui/src/canvas/cam_preview.rs | 7 ++- crates/ui-egui/src/canvas/tests.rs | 5 +- crates/ui-egui/src/dialogs/camera_raw_gpu.rs | 4 +- crates/ui-egui/src/dialogs/wide_angle_ui.rs | 53 ++++++++++--------- crates/ui-egui/src/menus/enable_rules.rs | 12 +++-- .../ui-egui/src/panels/brush_panel/tests.rs | 9 +++- crates/ui-egui/tests/it/canvas_16f.rs | 5 +- 17 files changed, 121 insertions(+), 86 deletions(-) diff --git a/crates/algo/src/blur/tests.rs b/crates/algo/src/blur/tests.rs index 74cf7ab20c..fd2917cd32 100644 --- a/crates/algo/src/blur/tests.rs +++ b/crates/algo/src/blur/tests.rs @@ -241,8 +241,9 @@ fn layer_box_blurs_match_direct_convolution_at_any_radius() { ]; let params = [ FilterParams::GaussianBlur { radius: 4.5 }, + // 9.3 already reaches past the layer's height with three boxes (edges repeated); a larger radius takes the same + // running sums and only made the direct-convolution oracle slow (#15652). FilterParams::GaussianBlur { radius: 9.3 }, - FilterParams::GaussianBlur { radius: 40.0 }, FilterParams::BoxBlur { radius: 5.0 }, FilterParams::BoxBlur { radius: 70.0 }, ]; diff --git a/crates/algo/src/blur2/smart_tests.rs b/crates/algo/src/blur2/smart_tests.rs index 505764e42e..9114ee8505 100644 --- a/crates/algo/src/blur2/smart_tests.rs +++ b/crates/algo/src/blur2/smart_tests.rs @@ -102,16 +102,10 @@ fn exact(a: &[f32], b: &[f32], what: &str) { #[test] fn offset_fast_path_matches_the_per_channel_oracle() { - let mut layouts: Vec<(ColorMode, usize, bool)> = vec![ - (ColorMode::Rgb, 3, false), - (ColorMode::Rgb, 4, true), - (ColorMode::Grayscale, 1, false), - (ColorMode::Grayscale, 2, true), - (ColorMode::Cmyk, 4, false), - (ColorMode::Cmyk, 5, true), - (ColorMode::Lab, 4, true), - ]; - layouts.extend((1..=MAXC).flat_map(|n| [(ColorMode::Multichannel, n, false), (ColorMode::Multichannel, n, true)])); + // The fast path dispatches on the channel count and alpha (`smart_blur`'s `smart_rows` arms, generic code past + // five); the colour mode reaches it only through the native white and black, which the oracle computes the same + // way. So every count with and without alpha covers every arm, whatever the mode is called (#15652). + let layouts: Vec<(ColorMode, usize, bool)> = (1..=MAXC).flat_map(|n| [(ColorMode::Multichannel, n, false), (ColorMode::Multichannel, n, true)]).collect(); let win = Rect::new(-7, -4, 33, 30); for (mode, n, alpha) in layouts { let src = image(win, n, alpha); @@ -121,7 +115,8 @@ fn offset_fast_path_matches_the_per_channel_oracle() { // The usual tile (the window less the halo), the whole window, and one sticking out of it. let inner = Rect::new(win.x0 + ri, win.y0 + ri, win.x1 - ri, win.y1 - ri); for out in [inner, win, Rect::new(-12, -9, 10, 8), Rect::EMPTY] { - for quality in [BlurQuality::Low, BlurQuality::Medium, BlurQuality::High] { + // Quality only sets the offset stride: Low a coarse one, High every offset at these radii (#15652). + for quality in [BlurQuality::Low, BlurQuality::High] { for sm in [SmartBlurMode::Normal, SmartBlurMode::EdgeOnly, SmartBlurMode::OverlayEdge] { for threshold in [8.0, 60.0] { let what = format!("{mode:?} n={n} alpha={alpha} r={radius} {out:?} {quality:?} {sm:?} t={threshold}"); diff --git a/crates/algo/src/panorama/parallel_tests.rs b/crates/algo/src/panorama/parallel_tests.rs index a8972f32cb..54f6f54edb 100644 --- a/crates/algo/src/panorama/parallel_tests.rs +++ b/crates/algo/src/panorama/parallel_tests.rs @@ -361,18 +361,27 @@ fn multiband_matches_the_serial_code() { assert_eq!(multiband(9, 7, &[], &[], 3).unwrap().0.len(), ref_multiband(9, 7, &[], &[], 3).0.len()); } -/// Batching the bands (#7758) changes when they are built, not the result. Budgets from none -/// (one image per batch) up to everything in steps of a fifth pass through every split of the -/// three images. +/// Batching the bands (#7758) changes when they are built, not the result. The batching adds the +/// next image while the batch's band cost stays within the budget, so its split changes only where +/// the budget crosses the cost of a run of consecutive images: each such sum and one below it, plus +/// none and everything, pass through every split the images can have (#15652; it swept 47 budgets). #[test] fn multiband_batches_match_the_serial_code() { - let budgets: Vec = - std::iter::successors(Some(1024.0f64), |b| Some(b * 1.2)).take_while(|b| *b < 4e6).map(|b| b as usize).chain([0, usize::MAX]).collect(); for (n, &(w, h)) in [(40usize, 30usize), (97, 61), (201, 129)].iter().enumerate() { for ch in [1usize, 3] { let (imgs, wts) = rois(w, h, ch, n as u64 * 17 + ch as u64); for levels in [1usize, 3, 5] { let want = ref_multiband(w, h, &imgs, &wts, levels); + let costs: Vec = imgs.iter().map(|im| blend::band_cost(im, w, h, ch, levels)).collect(); + let mut budgets = vec![0, usize::MAX]; + for start in 0..costs.len() { + for end in start + 1..=costs.len() { + let run: usize = costs[start..end].iter().sum(); + budgets.extend([run.saturating_sub(1), run]); + } + } + budgets.sort_unstable(); + budgets.dedup(); for &budget in &budgets { let got = try_multiband_batched(w, h, &imgs, &wts, levels, budget, None).unwrap(); assert_eq!(bits(&got.0), bits(&want.0), "colours {w}x{h}x{ch} levels {levels} budget {budget}"); diff --git a/crates/algo/src/pixelate/tests.rs b/crates/algo/src/pixelate/tests.rs index f0339e19c9..ac432283a5 100644 --- a/crates/algo/src/pixelate/tests.rs +++ b/crates/algo/src/pixelate/tests.rs @@ -195,15 +195,18 @@ fn facet_scratch_rejects_large_or_incomplete_storage() { #[test] fn cell_filters_match_scalar_models_edges_and_fractional_cells() { let bounds = Rect::new(-19, -13, 32, 29); - for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab, ColorMode::Multichannel] { + // The cell filters see the mode only as a channel count, CMYK's ink direction (`subtractive`) and the native + // background, so Lab adds nothing to RGB; cells of 100 and 300 are both past every `out`, and the seed has no + // branch (0 and u32::MAX keep the wrapping ends) (#15652). + for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Multichannel] { for alpha in [false, true] { let ctx = Ctx { bounds, mode, alpha }; for pattern in 0..5 { for halo in [0, 7] { let src = fixture(bounds.inflate(halo), &ctx, pattern); for out in [bounds, Rect::new(-23, -15, 37, 31), Rect::new(-7, 2, 18, 13)] { - for cell in [2.0, 3.75, 10.0, 100.0, 300.0] { - for seed in [0, 37, u32::MAX] { + for cell in [2.0, 3.75, 10.0, 300.0] { + for seed in [0, u32::MAX] { let got = cells::crystallize(&src, out, &ctx, cell, seed).unwrap(); assert_bits(&got, &crystallize_direct(&src, out, &ctx, cell, seed)); for bg in [[1.0; 4], [0.1, 0.8, 0.4, 0.25]] { @@ -257,7 +260,9 @@ fn cell_filters_tiled_storage_matches_scalar_with_soft_selection() { crate::mix_selection(&mut expected_data, bounds, &selection, &image, ctx.alpha); let mut expected = surface.clone(); expected.write_region(bounds, &expected_data); - for tile in [1, 7, 17, 256] { + // Tile 7 has dense edge tiles, sparse inner ones and a partial last one; 17 makes 1-pixel-wide and + // 2-row tiles. Tile 1 sent every edge pixel through the dense fallback (#15652). + for tile in [7, 17, 256] { let got = apply_tiled(&surface, ¶ms, bounds, bounds, Some(&selection), tile, extent); assert_bits(&got.read_region(bounds), &expected.read_region(bounds)); } diff --git a/crates/algo/src/sharpen/fft/tests.rs b/crates/algo/src/sharpen/fft/tests.rs index e1f7a26ed8..ff5d89dd6f 100644 --- a/crates/algo/src/sharpen/fft/tests.rs +++ b/crates/algo/src/sharpen/fft/tests.rs @@ -113,13 +113,13 @@ fn fft_cancellation_discards_partial_work_and_bounds_scratch() { #[test] fn positive_threshold_dispatch_retains_exact_pixel_decisions() { let area = Rect::new(-3, 2, 253, 258); - for depth in SampleType::ALL { - let s = source(area, PixelFormat::new(ColorMode::Rgb, depth, true)); - let p = FilterParams::UnsharpMask { amount: 500.0, radius: 64.0, threshold: 8.0 }; - let expected = crate::sharpen::tests::apply_reference(&s, &p, area, area, None, Some(area), 256); - let actual = crate::apply_in(&s, &p, area, area, None, area); - assert_eq!(expected.to_interleaved(area), actual.to_interleaved(area)); - } + // The FFT gate has no depth branch; only the positive threshold turns it away here. The exact kernel at every + // depth is `sharpen::tests::exact_tiled_selected_outputs_and_cancellation` (#15652). + let s = source(area, PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); + let p = FilterParams::UnsharpMask { amount: 500.0, radius: 64.0, threshold: 8.0 }; + let expected = crate::sharpen::tests::apply_reference(&s, &p, area, area, None, Some(area), 256); + let actual = crate::apply_in(&s, &p, area, area, None, area); + assert_eq!(expected.to_interleaved(area), actual.to_interleaved(area)); } #[test] diff --git a/crates/compose/src/effects/tests.rs b/crates/compose/src/effects/tests.rs index be4884deb9..d2552a9024 100644 --- a/crates/compose/src/effects/tests.rs +++ b/crates/compose/src/effects/tests.rs @@ -624,7 +624,8 @@ fn chisel_fields_do_not_depend_on_the_threads() { for (k, m) in maps.iter().enumerate() { for reach in [3.0f32, 12.0] { let one = with_threads(1, || (sharp_edges(m), distance_field_of(m, reach))); - for threads in [2, 5, 16] { + // 2 threads give groups of several units with a short last one, 16 one unit a group: the two ways `par_units` splits work (#15652). + for threads in [2, 16] { let many = with_threads(threads, || (sharp_edges(m), distance_field_of(m, reach))); assert_eq!(one.0.slot, many.0.slot, "map {k} sharp slots on {threads} threads"); let edges = |s: &SharpEdges| { @@ -675,7 +676,8 @@ fn bevel_maps_do_not_depend_on_the_threads() { } let run = || bevel_maps(shape, &b, &light, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)).0; let one = with_threads(1, run); - for threads in [2, 5, 16] { + // 2 threads give groups of several units with a short last one, 16 one unit a group: the two ways `par_units` splits work (#15652). + for threads in [2, 16] { let many = with_threads(threads, run); assert_eq!(one.len(), many.len()); for (j, (a, m)) in one.iter().zip(&many).enumerate() { diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index c6918ef1db..5c3c789168 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -2298,7 +2298,9 @@ fn live_dab_strokes_commit_their_pixels_and_they_are_the_commands() { fn live_dab_batches_match_the_accumulating_renderer() { use photocraft_paint::{GrayTile, StrokeRenderer, TipShape}; - for depth in DEPTHS { + // 8 bits (integers, and the measured Smudge mode only 8-bit RGB gets in `dab.rs`) and 32 bits (floats): 16 bits + // differs from 8 only in the raster's shared encode, which the live and the reference renderer both use (#15652). + for depth in [8, 32] { let mut s = session(200, 90, depth, "rgb"); s.execute("layer.new.layer", json!({})).unwrap(); paint_layer(&mut s, |x, y| { diff --git a/crates/engine/src/color_channels/tone.rs b/crates/engine/src/color_channels/tone.rs index c64b1debba..b7db453e09 100644 --- a/crates/engine/src/color_channels/tone.rs +++ b/crates/engine/src/color_channels/tone.rs @@ -267,7 +267,8 @@ mod tests { for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { let fmt = PixelFormat::new(mode, sample, true); let mut source = Surface::with_default(fmt, &vec![0.3; fmt.channels()]); - let bounds = Rect::from_xywh(-128, -128, 512, 256); + // 256 x 256 is exactly the U16 table's area threshold (`use_table`), so the table path still runs (#15652). + let bounds = Rect::from_xywh(-128, -128, 256, 256); let data: Vec<_> = (0..32 * 24 * fmt.channels()) .map(|i| { let v = (i * 37 % 257) as f32 / 256.0; diff --git a/crates/format/tests/it/roundtrip.rs b/crates/format/tests/it/roundtrip.rs index a311a17671..79850cb26a 100644 --- a/crates/format/tests/it/roundtrip.rs +++ b/crates/format/tests/it/roundtrip.rs @@ -382,15 +382,15 @@ zip_cases! { #[test] fn directory_bundle_roundtrip_all_modes() { - for mode in MODES { - for depth in SampleType::ALL { - let doc = rich_doc(mode, depth); - let dir = temp_dir("dir"); - PcraftWriter::new().save_dir(&doc, &dir, &SaveOptions::default()).unwrap(); - assert!(dir.join("manifest.json").is_file()); - assert_eq!(load_path(&dir).unwrap(), doc, "{mode:?} {depth:?}"); - std::fs::remove_dir_all(dir).unwrap(); - } + // The directory bundle runs the zip save's `prepare` and object encoding and differs only in the container, which + // does not depend on mode or depth: every mode x depth is `zip_cases!` above (#15652). + for (mode, depth) in [(ColorMode::Rgb, SampleType::U8), (ColorMode::Lab, SampleType::F32)] { + let doc = rich_doc(mode, depth); + let dir = temp_dir("dir"); + PcraftWriter::new().save_dir(&doc, &dir, &SaveOptions::default()).unwrap(); + assert!(dir.join("manifest.json").is_file()); + assert_eq!(load_path(&dir).unwrap(), doc, "{mode:?} {depth:?}"); + std::fs::remove_dir_all(dir).unwrap(); } } diff --git a/crates/gpu/tests/it/camera_raw.rs b/crates/gpu/tests/it/camera_raw.rs index d57bd31f80..60cf1a2d9e 100644 --- a/crates/gpu/tests/it/camera_raw.rs +++ b/crates/gpu/tests/it/camera_raw.rs @@ -479,19 +479,16 @@ fn shadows_and_highlights_with_per_pixel_stages() { check( "shadows/highlights + per pixel", &[ - all.clone(), + all, // Whites and Blacks measured after the filter, both directions. cr! { shadows: 60.0, whites: 70.0, blacks: -45.0}, cr! { highlights: -60.0, whites: -60.0, blacks: 50.0, exposure: -0.4}, cr! { shadows: 30.0, highlights: -30.0, whites: 40.0, blacks: -30.0, encoding_gamma: 1.8}, ], ); - // At the dialog's proxy size, at one depth: the depth only changes how the input is - // quantized (8 and 16 bits both develop with `float = false`), and every depth already ran - // above at 171×113. The size is what matters here (subsampled pyramid levels). - let Some(mut g) = gpu() else { return }; - let d = compare_at(&mut g, &all, Depth::Sixteen, (858, 572)); - eprintln!("shadows/highlights + per pixel 858x572: max |GPU - CPU| = {d:.2e}"); + // The proxy-size run (a multi-stage Reduce, subsampled pyramid levels) is + // `clarity_texture_and_dehaze_with_shadows_highlights_and_per_pixel_stages`, whose 858×572 case runs these + // shadows/highlights and per-pixel sliders too (#15652). } /// Asserts that each of `sets` moves some pixel of the test image by over 2 %, so a comparison @@ -567,7 +564,9 @@ fn clarity_texture_and_dehaze_with_shadows_highlights_and_per_pixel_stages() { // At the dialog's proxy size (Dehaze and Clarity on a copy subsampled twice), and wider (three // times). One depth per size: the depth only changes how the input is quantized (8 and 16 // bits both develop with `float = false`), and every depth already ran above at 171×113. - for (size, depth) in [((858, 572), Depth::Eight), ((1600, 900), Depth::Float)] { + // Only the long side sets the subsampling (Dehaze factor, Clarity radius, Texture sigma), so the + // wide case is 1600×240: still factor 3 and a two-stage Reduce, at a quarter of the pixels (#15652). + for (size, depth) in [((858, 572), Depth::Eight), ((1600, 240), Depth::Float)] { let d = compare_at(&mut g, &all, depth, size); eprintln!("everything {size:?} {depth:?}: max |GPU - CPU| = {d:.2e}"); } diff --git a/crates/ui-egui/src/canvas/cam_preview.rs b/crates/ui-egui/src/canvas/cam_preview.rs index 6296e31ef0..537a4e58d6 100644 --- a/crates/ui-egui/src/canvas/cam_preview.rs +++ b/crates/ui-egui/src/canvas/cam_preview.rs @@ -319,9 +319,12 @@ mod tests { #[test] fn a_large_selection_shows_a_coarse_result_then_the_exact_one() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + // The selection is just past the engine's full-resolution preview budget (256 x 256 pixels), the one condition + // for the coarse stage; the solve's cost grows with the selection and the canvas, so both stay as small as the + // move to x 250..507 allows (#15652). + app.run("file.new", json!({"width": 520, "height": 280})).unwrap(); app.run("paint.pencil", json!({"points": [[150, 160], [170, 160]], "size": 12, "color": "#0000ff"})).unwrap(); - app.run("select.rect", json!({"x": 10, "y": 10, "width": 300, "height": 300})).unwrap(); + app.run("select.rect", json!({"x": 10, "y": 10, "width": 257, "height": 256})).unwrap(); app.ui.tool = Tool::ContentAwareMove; app.ui.tool_options.cam_transform_on_drop = false; let m = egui::Modifiers::NONE; diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index c8ff36a3ea..c437de30f1 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1057,8 +1057,9 @@ fn a_floating_document_follows_navigator_and_status_bar_zoom() { h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); h.event(egui::Event::Text(typed.into())); h.key_press(egui::Key::Enter); - h.run_steps(2); - h.run_steps(58); + // The harness steps 1/4 s a frame, so 10 frames after Enter are 2.5 s: well past the 150 ms zoom ease, with + // frames after it in which the window could write its view back (60 frames, 15 s, before #15652). + h.run_steps(10); assert!(h.state().ui.window_views.is_empty(), "the window keeps no copy of the view"); assert!( (h.state().ui.views[0].zoom - want).abs() < 1e-3, diff --git a/crates/ui-egui/src/dialogs/camera_raw_gpu.rs b/crates/ui-egui/src/dialogs/camera_raw_gpu.rs index 378fc09db3..884bf49677 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_gpu.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_gpu.rs @@ -275,7 +275,9 @@ mod tests { #[test] fn per_pixel_settings_develop_on_the_gpu_like_the_cpu_and_the_rest_stays_on_the_cpu() { let _gpu = photocraft_testkit::gpu_lock(); - for depth in [8, 16, 32] { + // 8 and 32 bits: the dialog hands the develop only `float` (32-bit or not, `camera_raw_ui/convert.rs`), so 16 + // bits takes 8 bits' path; every depth's develop is the gpu crate's `tests/it/camera_raw.rs` (#15652). + for depth in [8, 32] { let Some(mut app) = gpu_app(depth) else { return }; force_pass(&app); open_raw(&mut app); diff --git a/crates/ui-egui/src/dialogs/wide_angle_ui.rs b/crates/ui-egui/src/dialogs/wide_angle_ui.rs index b7e32e2ece..6de1beedcc 100644 --- a/crates/ui-egui/src/dialogs/wide_angle_ui.rs +++ b/crates/ui-egui/src/dialogs/wide_angle_ui.rs @@ -375,32 +375,33 @@ mod tests { #[test] fn native_component_wide_angle_previews_and_commit_keep_unselected_samples() { - for mode in ["rgb", "cmyk", "lab"] { - for depth in [8, 16, 32] { - for alpha in [true, false] { - let fixture = crate::distort_ui::component_tests::app(mode, depth); - let mut app = if alpha { fixture } else { crate::distort_ui::component_tests::without_alpha(fixture) }; - let ctx = app.ctx().clone(); - open(&mut app, &ctx).unwrap(); - ui(&mut app, json!({"set": {"model": "fisheye", "focalLength": 10.0}})).unwrap(); - ui(&mut app, json!({"add": {"a": [8, 8], "b": [56, 16], "orientation": "horizontal"}})).unwrap(); - let layer = app.wide_angle.as_ref().unwrap().layer; - let source = source_of(&app); - let session = session_of(&app); - let before = source.proxy.as_ref().clone(); - let pf = source.geometry.proxy_rect; - let (preview, _) = - preview_surface(&before, &proxy_params(&session, source.geometry.frame, source.geometry.scale), pf, &source.target, None).unwrap(); - source.state().run(&session).unwrap(); - crate::distort_ui::component_tests::protected(&before, &preview, pf); - assert_ne!(preview.read_region(pf), before.read_region(pf)); - app.run("channel.target", json!({"channel":{"color":1}})).unwrap(); - ui(&mut app, json!({"commit": true})).unwrap(); - take(&mut app, &ctx); - let after = app.session.active().unwrap().doc.layer(layer).unwrap().surface().unwrap(); - crate::distort_ui::component_tests::protected(&before, after, pf); - assert_ne!(after.read_region(pf), before.read_region(pf)); - } + // One depth per mode, each with and without alpha: the preview and commit have no branch on mode or depth, and + // `restrict_surface_impl` is generic over the sample width; alpha decides whether the warped layout differs + // from the original, so it stays a full axis (#15652). + for (mode, depth) in [("rgb", 8), ("cmyk", 16), ("lab", 32)] { + for alpha in [true, false] { + let fixture = crate::distort_ui::component_tests::app(mode, depth); + let mut app = if alpha { fixture } else { crate::distort_ui::component_tests::without_alpha(fixture) }; + let ctx = app.ctx().clone(); + open(&mut app, &ctx).unwrap(); + ui(&mut app, json!({"set": {"model": "fisheye", "focalLength": 10.0}})).unwrap(); + ui(&mut app, json!({"add": {"a": [8, 8], "b": [56, 16], "orientation": "horizontal"}})).unwrap(); + let layer = app.wide_angle.as_ref().unwrap().layer; + let source = source_of(&app); + let session = session_of(&app); + let before = source.proxy.as_ref().clone(); + let pf = source.geometry.proxy_rect; + let (preview, _) = + preview_surface(&before, &proxy_params(&session, source.geometry.frame, source.geometry.scale), pf, &source.target, None).unwrap(); + source.state().run(&session).unwrap(); + crate::distort_ui::component_tests::protected(&before, &preview, pf); + assert_ne!(preview.read_region(pf), before.read_region(pf)); + app.run("channel.target", json!({"channel":{"color":1}})).unwrap(); + ui(&mut app, json!({"commit": true})).unwrap(); + take(&mut app, &ctx); + let after = app.session.active().unwrap().doc.layer(layer).unwrap().surface().unwrap(); + crate::distort_ui::component_tests::protected(&before, after, pf); + assert_ne!(after.read_region(pf), before.read_region(pf)); } } } diff --git a/crates/ui-egui/src/menus/enable_rules.rs b/crates/ui-egui/src/menus/enable_rules.rs index 7ed4e7c211..1219845ad5 100644 --- a/crates/ui-egui/src/menus/enable_rules.rs +++ b/crates/ui-egui/src/menus/enable_rules.rs @@ -434,10 +434,16 @@ mod tests { let mut checked = 0; for sel in selections { for copied in [false, true] { + // `is_enabled` only reads the app, so one app per world answers for every command; each command then + // runs on a world of its own. A copied style is read by Paste Layer Style alone (the engine's + // `style_clipboard`), so the other commands run without it only (#15652). + let app = crate::PhotocraftApp::new(world(sel, copied), crate::Services::default()); for (cmd, must_change) in commands { - let app = crate::PhotocraftApp::new(world(sel, copied), crate::Services::default()); + if copied && cmd != "layer.layerStyle.pasteLayerStyle" { + continue; + } let enabled = crate::menus::is_enabled(&app, cmd); - let mut s = app.session; + let mut s = world(sel, copied); let before = fingerprint(&s); let r = s.execute(cmd, json!({})); let changed = fingerprint(&s) != before; @@ -457,7 +463,7 @@ mod tests { } } } - assert_eq!(checked, selections.len() * 2 * commands.len()); + assert_eq!(checked, selections.len() * (commands.len() + 1)); } /// #13293: on a lone Background, Group from Layers… and Load Selection… are greyed, as in the diff --git a/crates/ui-egui/src/panels/brush_panel/tests.rs b/crates/ui-egui/src/panels/brush_panel/tests.rs index 781a9469cf..6d52d98708 100644 --- a/crates/ui-egui/src/panels/brush_panel/tests.rs +++ b/crates/ui-egui/src/panels/brush_panel/tests.rs @@ -431,8 +431,13 @@ fn editing_the_options_bar_amount_reenables_smoothing() { #[test] fn every_section_draws_without_issuing_commands() { - for (panel, view) in [("brushSettings", None), ("brushes", Some(PresetView::List)), ("brushes", Some(PresetView::Grid))] { - for section in 0..SECTIONS.len() { + // Brush Settings draws the selected section's controls, but only up to `CHECKBOX_ONLY_START`: a later section is + // reset to 0 before drawing (`brush_settings.rs`, tested by `checkbox_only_rows_cannot_restore_an_empty_properties_pane`). + // The Brushes panel does not read the section at all, so one run per view covers it (#15652). + for (panel, view, sections) in + [("brushSettings", None, 0..CHECKBOX_ONLY_START), ("brushes", Some(PresetView::List), 0..1), ("brushes", Some(PresetView::Grid), 0..1)] + { + for section in sections { let mut h = harness(panel, section); if let Some(view) = view { h.state_mut().ui.brushes_panel.view = view; diff --git a/crates/ui-egui/tests/it/canvas_16f.rs b/crates/ui-egui/tests/it/canvas_16f.rs index 5d160fadea..efc331b4f3 100644 --- a/crates/ui-egui/tests/it/canvas_16f.rs +++ b/crates/ui-egui/tests/it/canvas_16f.rs @@ -180,10 +180,13 @@ fn screen(doc: Document, setup: &[(&str, serde_json::Value)], name: &str) -> Opt screens(vec![(doc, setup, name)]).and_then(|mut shown| shown.pop()) } +/// A document to show, the commands that set it up, and the file name of its screenshot. +type ScreenCase<'a> = (Document, &'a [(&'a str, serde_json::Value)], &'a str); + /// [`screen`] for several documents in one app, opened and rendered in turn: one harness, so one GPU device and one /// compositor build (#15439) instead of one per document (#15652). Each document's setup commands run while it is /// the active one; View › 32-bit Preview Options is kept per document. -fn screens(cases: Vec<(Document, &[(&str, serde_json::Value)], &str)>) -> Option> { +fn screens(cases: Vec>) -> Option> { let mut cases = cases.into_iter(); let (doc, setup, name) = cases.next()?; let ok = Arc::new(AtomicBool::new(false)); From 36d05ab93301495cb4b12a49f0d62447304360dc Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 23:26:31 +0100 Subject: [PATCH 23/85] Toolbar: the rail's version no longer keys on the flyout side, which is fixed now Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/region_versions.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/region_versions.rs b/crates/ui-egui/src/panels/region_versions.rs index d99adab582..3ace374c97 100644 --- a/crates/ui-egui/src/panels/region_versions.rs +++ b/crates/ui-egui/src/panels/region_versions.rs @@ -39,13 +39,12 @@ pub(crate) fn panel(app: &PhotocraftApp, id: &str) -> u64 { } /// The version of the Toolbar's rail: the toolbar slots (the preferences revision), the remembered group tools, the -/// Edit Toolbar drawer, the side its flyouts open on, Quick Mask and the screen mode. The active tool and the colours -/// are in every version. +/// Edit Toolbar drawer, Quick Mask and the screen mode. Its flyouts always open on the same side. The active tool and +/// the colours are in every version. pub(crate) fn toolbar(app: &PhotocraftApp) -> u64 { let quick_mask = app.session.active().is_some_and(|st| st.doc.quick_mask.is_some()); - let opens_start = crate::panel_docking::toolbar_opens(app) == craft::behavior::overlay::Side::Start; let screen_mode = format!("{:?}", app.ui.view.screen_mode); - version(app, (app.session.prefs.rev(), &app.ui.group_tools, app.ui.toolbar_drawer, opens_start, quick_mask, screen_mode)) + version(app, (app.session.prefs.rev(), &app.ui.group_tools, app.ui.toolbar_drawer, quick_mask, screen_mode)) } /// What every region may show, joined with `extra`: the commands run (any of them may change anything), the active From ce996788a08554db78d113216718e463540b39e2 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 23:44:32 +0100 Subject: [PATCH 24/85] Control channel: rects keys the unsaved-changes prompt as discard, the id dialogs lists it by Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/control/inspect.rs | 8 +++++++- crates/ui-egui/src/control/tests.rs | 5 +++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/control/inspect.rs b/crates/ui-egui/src/control/inspect.rs index 5c71c68dd7..6b542994c2 100644 --- a/crates/ui-egui/src/control/inspect.rs +++ b/crates/ui-egui/src/control/inspect.rs @@ -60,12 +60,18 @@ fn rects(app: &PhotocraftApp, ctx: &egui::Context) -> Value { } for dialog in app.framework.dialogs.open_dialogs() { if let Some(r) = rect(dialog.id) { - out.insert(dialog.id.value().to_string(), r); + out.insert(dialog_key(app, dialog.id), r); } } Value::Object(out) } +/// The key `rects` stores hosted dialog `id` under: the id `dialogs` lists it by, so the unsaved-changes prompt is +/// [`crate::discard_ui::CONTROL_ID`] there too (#15544), any other dialog its host id. +pub(super) fn dialog_key(app: &PhotocraftApp, id: egui::Id) -> String { + if crate::discard_ui::host_id(app) == Some(id) { crate::discard_ui::CONTROL_ID.to_string() } else { id.value().to_string() } +} + /// The notices posted since the last pass and the toast cards on screen in every window. fn notices(app: &PhotocraftApp, ctx: &egui::Context) -> Value { let mut all: Vec = app.ui.notices.iter().map(|notice| serde_json::to_value(notice).unwrap_or_default()).collect(); diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 2b6c55355e..f265b281f4 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -2310,6 +2310,11 @@ fn the_unsaved_changes_prompt_is_listed_as_discard_and_answered_by_that_id() { assert_eq!(listed["fields"]["document"], name.as_str()); assert_eq!(listed["fields"]["remaining"], 1); assert_eq!(listed["fields"]["choices"], json!(["save", "dontSave", "cancel"])); + // Its rect is keyed by that id too, as `rects` keys every hosted dialog by its `dialogs` id; others keep theirs. + let host = crate::discard_ui::host_id(&app).expect("the prompt is open"); + assert_eq!(super::inspect::dialog_key(&app, host), "discard"); + let other = egui::Id::new("another dialog"); + assert_eq!(super::inspect::dialog_key(&app, other), other.value().to_string()); let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"})); assert_eq!(cancelled["ok"], true, "{cancelled}"); crate::canvas::testing::frame(&mut app); From c79b357811a46f0f94016b9aeb0ffe0c5918e7e9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 00:25:48 +0000 Subject: [PATCH 25/85] Image Size test: read values through the boxed app harness --- crates/ui-egui/src/dialogs/sizing/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/sizing/tests.rs b/crates/ui-egui/src/dialogs/sizing/tests.rs index 150bb86b78..2f93d1890d 100644 --- a/crates/ui-egui/src/dialogs/sizing/tests.rs +++ b/crates/ui-egui/src/dialogs/sizing/tests.rs @@ -193,7 +193,7 @@ fn image_size_draws_width_and_height_with_values_and_unit() { open(h.state_mut(), "image.imageSize").expect("a document is open"); h.run_steps(6); - let value_of = |h: &Harness<'static, PhotocraftApp>, label: &str| -> Vec { + let value_of = |h: &Harness<'_, Box>, label: &str| -> Vec { h.query_all_by_label(label).filter_map(|n| n.accesskit_node().value().map(|v| v.to_string())).collect() }; for (label, want) in [("Width", "1600"), ("Height", "1000"), ("Resolution", "72")] { From 81e95dfc213c4d6244071027dfc04bc5b21113af Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 01:47:43 +0100 Subject: [PATCH 26/85] Integration: craft-libs pin to next 04ba41419b (craft-libs#2242, #15540) Moves every craft-libs pin from 18ffc07519 to the current next head, two commits newer: storytold/craft-libs#2242 (a dialog that opens on a text field selects its text). craft-svg keeps its own rev. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 222 +++++++++++++++++++-------------------- Cargo.toml | 68 ++++++------ crates/engine/Cargo.toml | 2 +- 3 files changed, 146 insertions(+), 146 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a52ea4f9a5..a73a50ae2b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1365,7 +1365,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-automation", "craft-behavior", @@ -1404,7 +1404,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "crc32fast", "flate2", @@ -1425,7 +1425,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "rustix 1.1.5", ] @@ -1433,7 +1433,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "base64 0.22.1", "craft-ai-agents", @@ -1459,7 +1459,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1475,7 +1475,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-docpath", @@ -1493,7 +1493,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "egui", ] @@ -1501,7 +1501,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "md-5", "rayon", @@ -1510,7 +1510,7 @@ dependencies = [ [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-cms", @@ -1530,17 +1530,17 @@ dependencies = [ [[package]] name = "craft-crs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "thiserror 2.0.21", ] [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "thiserror 2.0.21", ] @@ -1548,7 +1548,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "rayon", ] @@ -1564,7 +1564,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "block2 0.6.2", "craft-atomic", @@ -1587,7 +1587,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "serde", ] @@ -1595,7 +1595,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1614,21 +1614,21 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" [[package]] name = "craft-file-formats" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-eps", "craft-idml", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-kra", "craft-ora", "craft-pcraft-bundle", "craft-raw", - "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-zip", "serde", "serde_json", @@ -1637,7 +1637,7 @@ dependencies = [ [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-atomic", "dirs", @@ -1647,7 +1647,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1662,7 +1662,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1681,7 +1681,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "cap-primitives", "craft-atomic", @@ -1702,12 +1702,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" [[package]] name = "craft-heif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "heic-rs", "rayon", @@ -1716,7 +1716,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1729,7 +1729,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "chrono", "fixed_decimal", @@ -1757,9 +1757,9 @@ dependencies = [ [[package]] name = "craft-idml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-zip", "thiserror 2.0.21", ] @@ -1767,13 +1767,13 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-heif", - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "crc32fast", "exr", "flate2", @@ -1822,7 +1822,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1845,7 +1845,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a0455 [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "thiserror 2.0.21", ] @@ -1861,11 +1861,11 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-host", "craft-i18n", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "egui", "serde", "serde_json", @@ -1874,9 +1874,9 @@ dependencies = [ [[package]] name = "craft-kra" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-zip", "thiserror 2.0.21", ] @@ -1884,7 +1884,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-i18n", @@ -1898,7 +1898,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", @@ -1916,11 +1916,11 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "brotli-decompressor 6.3.2", "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "quick-xml 0.41.0", "serde", ] @@ -1940,9 +1940,9 @@ dependencies = [ [[package]] name = "craft-ora" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-zip", "thiserror 2.0.21", ] @@ -1950,7 +1950,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-text", @@ -1964,7 +1964,7 @@ dependencies = [ [[package]] name = "craft-pcraft-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "blake3", "craft-atomic", @@ -1977,7 +1977,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "flate2", "serde", @@ -1988,7 +1988,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "bytemuck", "flate2", @@ -2003,7 +2003,7 @@ dependencies = [ [[package]] name = "craft-pdn" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2012,7 +2012,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "async-channel", "async-io", @@ -2038,7 +2038,7 @@ dependencies = [ [[package]] name = "craft-plist" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "thiserror 2.0.21", ] @@ -2046,7 +2046,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-ui", @@ -2064,7 +2064,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "encoding_rs", "flate2", @@ -2075,7 +2075,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "dispatch2", "egui", @@ -2086,12 +2086,12 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "chrono", "craft-crw", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "jxl-oxide", "miniz_oxide 0.9.1", "rayon", @@ -2104,7 +2104,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", @@ -2121,7 +2121,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-atomic", "craft-host", @@ -2135,9 +2135,9 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "flate2", "kurbo 0.13.1", "quick-xml 0.41.0", @@ -2173,7 +2173,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-keymap", @@ -2185,7 +2185,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2208,7 +2208,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "bitflags 2.13.2", "ecolor", @@ -2221,7 +2221,7 @@ dependencies = [ [[package]] name = "craft-theme-editor" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-theme", @@ -2232,7 +2232,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-atomic", "craft-behavior", @@ -2247,7 +2247,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "serde", "thiserror 2.0.21", @@ -2265,7 +2265,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "serde", "thiserror 2.0.21", @@ -2274,7 +2274,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-keymap", @@ -2289,7 +2289,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2303,7 +2303,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-i18n", @@ -2319,7 +2319,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "accesskit", "craft-behavior", @@ -2331,7 +2331,7 @@ dependencies = [ "craft-platform", "craft-quit", "craft-settings", - "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-theme", "craft-ui-macros", "craft-window", @@ -2353,7 +2353,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2364,7 +2364,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", @@ -2382,7 +2382,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", @@ -2403,13 +2403,13 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", "craft-i18n", "craft-platform", - "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-theme", "craft-ui-macros", "craft-ui-panels", @@ -2422,7 +2422,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-behavior", "craft-host", @@ -2439,7 +2439,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "chrono", "craft-host", @@ -2468,7 +2468,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "winsafe", ] @@ -2476,7 +2476,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "craft-atomic", "craft-behavior", @@ -2506,7 +2506,7 @@ dependencies = [ [[package]] name = "craft-xcf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2515,7 +2515,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2535,7 +2535,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "flate2", "thiserror 2.0.21", @@ -3998,7 +3998,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "bytemuck", "hayro-interpret", @@ -4028,7 +4028,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -4046,7 +4046,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -4070,7 +4070,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "flate2", "hayro-ccitt", @@ -5154,7 +5154,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -6371,10 +6371,10 @@ dependencies = [ "core-graphics2", "craft", "craft-cms", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)", "craft-update", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "eframe", "egui", "egui_kittest", @@ -6418,7 +6418,7 @@ name = "photocraft-algo" version = "0.23.1" dependencies = [ "craft", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "criterion", "photocraft-color", "photocraft-geom", @@ -6438,7 +6438,7 @@ dependencies = [ "cap-std", "clap", "craft", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-psd", "getrandom 0.3.4", "photocraft-color", @@ -6471,7 +6471,7 @@ dependencies = [ "clap_mangen", "craft", "craft-cms", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-psd", "photocraft-automation", "photocraft-doc", @@ -6535,11 +6535,11 @@ dependencies = [ "craft-affinity", "craft-cms", "craft-file-formats", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-pcraft-format", "craft-print", "craft-psd", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "exr", "flate2", "photocraft-algo", @@ -6575,7 +6575,7 @@ name = "photocraft-format" version = "0.23.1" dependencies = [ "blake3", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-pcraft-bundle", "craft-pcraft-format", "craft-zip", @@ -6635,16 +6635,16 @@ dependencies = [ "craft-crs", "craft-docpath", "craft-file-formats", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-kra", "craft-ora", "craft-pdf", "craft-pdn", "craft-psd", "craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7b8c1eccea0c695a495ab279c9523e6efcc9b8be)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-xcf", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "crc32fast", "flate2", "kurbo 0.13.1", @@ -6735,7 +6735,7 @@ dependencies = [ name = "photocraft-raw" version = "0.23.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-raw", "flate2", "image", @@ -6797,7 +6797,7 @@ dependencies = [ "craft", "craft-file-formats", "craft-i18n", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-print", "craft-psd", "eframe", @@ -6846,7 +6846,7 @@ dependencies = [ name = "photocraft-web" version = "0.23.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb)", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee)", "craft-psd", "eframe", "egui", @@ -11216,14 +11216,14 @@ source = "git+https://github.com/storytold/egui.git?rev=e9711ca9b69772f875ae0d1c [[patch.unused]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" [[patch.unused]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" [[patch.unused]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=18ffc07519b15f5ef39e752aa0f405261fec8ebb#18ffc07519b15f5ef39e752aa0f405261fec8ebb" +source = "git+https://github.com/storytold/craft-libs?rev=04ba41419b99967e4d2b990cdfe5d80184be64ee#04ba41419b99967e4d2b990cdfe5d80184be64ee" diff --git a/Cargo.toml b/Cargo.toml index eac941937a..2192a12aff 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,19 +12,19 @@ rust-version = "1.95" [workspace.dependencies] # The craft framework through its facade (`craft::ui::…`). The egui `[patch]` below must match # `craft::egui_fork::REV` (checked by `cargo xtask ci`). -craft = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb", default-features = false } +craft = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee", default-features = false } # internal photocraft-geom = { path = "crates/geom" } photocraft-color = { path = "crates/color" } photocraft-raster = { path = "crates/raster" } photocraft-doc = { path = "crates/doc" } photocraft-ops = { path = "crates/ops" } -craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } +craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } photocraft-raw = { path = "crates/raw" } -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } photocraft-compose = { path = "crates/compose" } photocraft-gpu = { path = "crates/gpu" } photocraft-paint = { path = "crates/paint" } @@ -43,34 +43,34 @@ photocraft-ipp = { path = "crates/ipp" } # external # ICC colour management: the shared crate (replaces crates/cms; craft-libs#779). -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } # HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784). -craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb", features = ["raster", "write-raster"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee", features = ["raster", "write-raster"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } # Keep the shared embedded-image validation API until the framework revision includes it. craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "7b8c1eccea0c695a495ab279c9523e6efcc9b8be", features = ["tree-render", "tree-render-system-fonts"] } -craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } # Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563. -craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } # Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n # catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at # the commit in `craft-i18n.rev`). Already in the tree through craft. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb", features = ["ui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee", features = ["ui"] } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" @@ -322,14 +322,14 @@ opt-level = 3 # Keep the complete egui family and native event bridge on reviewed fork commits. [patch.crates-io] -krilla = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } emath = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } epaint = { git = "https://github.com/storytold/egui.git", rev = "e9711ca9b69772f875ae0d1cef1977ff8c16234d" } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 65220283e8..b28eeb44cd 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -16,7 +16,7 @@ photocraft-geom = { workspace = true } photocraft-color = { workspace = true } craft-cms = { workspace = true } # PCTIP codec from craft-libs#1564; isolated pin until the shared revision is adopted workspace-wide. -craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "18ffc07519b15f5ef39e752aa0f405261fec8ebb" } +craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "04ba41419b99967e4d2b990cdfe5d80184be64ee" } photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-ops = { workspace = true } From 248fd87a6a79510ee17b67e1347d2a1733d374ce Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 01:47:43 +0100 Subject: [PATCH 27/85] Integration: #15504 with #15496: the toolbar's measured height keys on the fixed flyout side #15504 removes panel_docking::toolbar_opens (flyouts always open the same way); #15496's measure cache still read it. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/toolbar.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs index 7690f29d94..f80b73bf9a 100644 --- a/crates/ui-egui/src/panels/toolbar.rs +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -227,7 +227,7 @@ pub(crate) fn measure(app: &mut PhotocraftApp, ui: &egui::Ui, width: f32) -> f32 static LAST: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } let slots = app.toolbar_slots.get(&app.session.prefs); - let (opens, editing) = (crate::panel_docking::toolbar_opens(app), app.ui.toolbar_drawer); + let (opens, editing) = (FLYOUTS_OPEN, app.ui.toolbar_drawer); let env = craft::ui::runtime::env::Env::of(ui); let room = ui.available_size(); let key = MeasureKey { From 73b13c8424d2ac12695d207e47aec45cd3d524e3 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 01:47:43 +0100 Subject: [PATCH 28/85] Integration: #15631: Id::unique in place of the deprecated Id::new in the discard-prompt test Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/control/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index f265b281f4..dc88c6efed 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -2313,7 +2313,7 @@ fn the_unsaved_changes_prompt_is_listed_as_discard_and_answered_by_that_id() { // Its rect is keyed by that id too, as `rects` keys every hosted dialog by its `dialogs` id; others keep theirs. let host = crate::discard_ui::host_id(&app).expect("the prompt is open"); assert_eq!(super::inspect::dialog_key(&app, host), "discard"); - let other = egui::Id::new("another dialog"); + let other = egui::Id::unique("another dialog"); assert_eq!(super::inspect::dialog_key(&app, other), other.value().to_string()); let cancelled = call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"})); assert_eq!(cancelled["ok"], true, "{cancelled}"); From 15321f219e99c74742747c5d9ab85b0f6f67b88f Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 01:47:43 +0100 Subject: [PATCH 29/85] Integration: #15561: the dialog-title test harness holds the boxed app, as build_eframe returns it Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialog_title_ellipsis_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialog_title_ellipsis_tests.rs b/crates/ui-egui/src/dialog_title_ellipsis_tests.rs index d958214bce..014c7dc1c5 100644 --- a/crates/ui-egui/src/dialog_title_ellipsis_tests.rs +++ b/crates/ui-egui/src/dialog_title_ellipsis_tests.rs @@ -10,7 +10,7 @@ use crate::PhotocraftApp; /// Opens one dialog. type Open = fn(&mut PhotocraftApp); -fn harness() -> Harness<'static, PhotocraftApp> { +fn harness() -> Harness<'static, Box> { let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1000.0)).with_max_steps(64).build_eframe(|cc| { PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::AppTheme::pro()); let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); From 56e818059f43cbdaa66bba5cbe8c18bbd1c5e9eb Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 01:47:43 +0100 Subject: [PATCH 30/85] Integration: #15585: the Free Transform preview test harness holds the boxed app Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/tests/it/free_transform_preview_canvas.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/it/free_transform_preview_canvas.rs b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs index 99681b74e6..0b7ff0eb5b 100644 --- a/crates/ui-egui/tests/it/free_transform_preview_canvas.rs +++ b/crates/ui-egui/tests/it/free_transform_preview_canvas.rs @@ -14,7 +14,7 @@ use photocraft_ui_egui::PhotocraftApp; use photocraft_ui_egui::control::{ControlRequest, handle}; use serde_json::{Value, json}; -type Harness = egui_kittest::Harness<'static, PhotocraftApp>; +type Harness = egui_kittest::Harness<'static, Box>; /// The red square on the layer, in document pixels: x 100..200, y 100..200 of a 400 × 300 document. fn square() -> Rect { From eb55919530b2ff523be90c5d9295207b7ccbe552 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 01:47:44 +0100 Subject: [PATCH 31/85] Integration: #15608: craft counts as a UI dependency only with its UI features (#15467) Listing craft by name in UI_CRATES flagged photocraft-algo, -io, -text and -engine, which use the facade's non-UI parts (imaging, fonts, keymap, settings), so cargo xtask layers failed on the workspace. The facade brings the craft UI framework (craft-ui, egui) only through `ui` and the features that turn it on (`ui-*`, `screen-testing`), so the guard now reads each dependency's declared features from cargo metadata and flags craft below L6 only with one of those. Tests: craft with ui, ui-app or screen-testing below L6 fails (normal and dev), the features the workspace uses today pass, L6 may use them all, and metadata parsing keeps the features. Both fail with the feature rule empty. Co-Authored-By: Claude Opus 5.5 --- xtask/src/layers.rs | 67 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 58 insertions(+), 9 deletions(-) diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index cc8e282730..c7ed3f95d9 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -98,7 +98,12 @@ fn standalone_exception(from: &str, to: &str) -> bool { /// External crates that constitute a UI toolkit / windowing dependency. /// Entries ending in `*` are prefixes. -pub const UI_CRATES: &[&str] = &["egui", "eframe", "winit", "egui_kittest", "craft-ui", "craft", "rfd", "bevy*"]; +pub const UI_CRATES: &[&str] = &["egui", "eframe", "winit", "egui_kittest", "craft-ui", "rfd", "bevy*"]; + +/// Facade crates that are a UI toolkit dependency only with some of their features (#15467): `craft` carries the +/// whole craft UI framework behind `ui` (and the features that turn it on), while lower layers use its non-UI parts +/// (imaging, fonts, keymap, settings). Feature names ending in `*` are prefixes. +pub const UI_FEATURES: &[(&str, &[&str])] = &[("craft", &["ui", "ui-*", "screen-testing"])]; /// First layer allowed to use UI crates. pub const UI_MIN_LAYER: u8 = 6; @@ -112,11 +117,17 @@ pub fn classify(pkg: &str) -> Option { TABLE.iter().find(|(n, _)| *n == s).map(|(_, c)| *c) } -fn is_ui_crate(name: &str) -> bool { - UI_CRATES.iter().any(|p| match p.strip_suffix('*') { +fn matches_pattern(name: &str, pattern: &str) -> bool { + match pattern.strip_suffix('*') { Some(prefix) => name.starts_with(prefix), - None => name == *p, - }) + None => name == pattern, + } +} + +/// Whether `dep` brings a UI toolkit: a crate in [`UI_CRATES`], or a [`UI_FEATURES`] facade with one of its UI features. +fn is_ui_dep(dep: &Dep) -> bool { + UI_CRATES.iter().any(|p| matches_pattern(&dep.name, p)) + || UI_FEATURES.iter().any(|(krate, features)| dep.name == *krate && dep.features.iter().any(|f| features.iter().any(|p| matches_pattern(f, p)))) } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -132,6 +143,8 @@ pub struct Dep { pub kind: DepKind, /// `true` if the dependency is a workspace member. pub workspace: bool, + /// The features the dependency is declared with (including the ones inherited from the workspace). + pub features: Vec, } #[derive(Debug, Clone)] @@ -214,7 +227,7 @@ pub fn check(crates: &[Crate]) -> Vec { } } } - } else if layer < UI_MIN_LAYER && is_ui_crate(&d.name) { + } else if layer < UI_MIN_LAYER && is_ui_dep(d) { out.push(Violation::UiBelowL6 { krate: c.name.clone(), dep: d.name.clone(), layer }); } } @@ -240,7 +253,8 @@ pub fn from_metadata(meta: &Value) -> Result, String> { _ => DepKind::Normal, }; let workspace = members.contains(&dname.as_str()) || d["path"].is_string(); - deps.push(Dep { name: dname, kind, workspace }); + let features = d["features"].as_array().into_iter().flatten().filter_map(|f| f.as_str().map(str::to_owned)).collect(); + deps.push(Dep { name: dname, kind, workspace, features }); } out.push(Crate { name, deps }); } @@ -263,7 +277,7 @@ mod tests { use super::*; fn c(name: &str, deps: &[(&str, DepKind, bool)]) -> Crate { - Crate { name: name.into(), deps: deps.iter().map(|(n, k, w)| Dep { name: (*n).into(), kind: *k, workspace: *w }).collect() } + Crate { name: name.into(), deps: deps.iter().map(|(n, k, w)| Dep { name: (*n).into(), kind: *k, workspace: *w, features: Vec::new() }).collect() } } use DepKind::*; @@ -340,7 +354,7 @@ mod tests { #[test] fn ui_crates_below_l6_flagged() { - for dep in ["egui", "eframe", "winit", "egui_kittest", "craft-ui", "craft", "rfd", "bevy_ecs", "bevy"] { + for dep in ["egui", "eframe", "winit", "egui_kittest", "craft-ui", "rfd", "bevy_ecs", "bevy"] { let v = check(&[c("photocraft-engine", &[(dep, Normal, false)])]); assert!(matches!(v[..], [Violation::UiBelowL6 { layer: 5, .. }]), "{dep}"); } @@ -349,6 +363,41 @@ mod tests { assert!(check(&[c("photocraft-platform", &[("winit", Normal, false)])]).is_empty()); } + fn with_features(name: &str, dep: &str, kind: DepKind, features: &[&str]) -> Crate { + let features = features.iter().map(|f| (*f).to_owned()).collect(); + Crate { name: name.into(), deps: vec![Dep { name: dep.into(), kind, workspace: false, features }] } + } + + #[test] + fn craft_facade_with_ui_features_flagged_below_l6() { + // #15467: the facade's UI features bring the whole craft UI framework. + for features in [&["ui"][..], &["imaging", "ui-app"], &["screen-testing"]] { + let v = check(&[with_features("photocraft-engine", "craft", Normal, features)]); + assert!(matches!(&v[..], [Violation::UiBelowL6 { layer: 5, dep, .. }] if dep == "craft"), "{features:?}"); + let v = check(&[with_features("photocraft-text", "craft", Dev, features)]); + assert!(matches!(v[..], [Violation::UiBelowL6 { layer: 2, .. }]), "dev {features:?}"); + } + // Its non-UI parts stay usable below L6 (what text, io and engine use today), and L6 may use it all. + for features in [&[][..], &["imaging"], &["font-catalog", "font-manager"], &["automation", "color-ui", "keymap", "platform", "settings"]] { + assert!(check(&[with_features("photocraft-engine", "craft", Normal, features)]).is_empty(), "{features:?}"); + } + assert!(check(&[with_features("photocraft-ui-egui", "craft", Normal, &["ui", "screen-testing"])]).is_empty()); + // Only the facade is judged by its features. + assert!(check(&[with_features("photocraft-engine", "craft-imaging", Normal, &["ui"])]).is_empty()); + } + + #[test] + fn metadata_reads_dependency_features() { + let meta: Value = serde_json::from_str( + r#"{"packages":[{"name":"photocraft-engine","dependencies":[ + {"name":"craft","kind":null,"features":["keymap","ui"]}]}]}"#, + ) + .unwrap(); + let g = from_metadata(&meta).unwrap(); + assert_eq!(g[0].deps[0].features, ["keymap", "ui"]); + assert!(matches!(check(&g)[..], [Violation::UiBelowL6 { .. }])); + } + #[test] fn unregistered_crate_is_error() { let v = check(&[c("photocraft-mystery", &[])]); From 9be5f352358dc72558189d4a01099eeae96f1a55 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 01:47:44 +0100 Subject: [PATCH 32/85] Integration: regenerate docs/scorecard.md Co-Authored-By: Claude Opus 5.5 --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 3f01a2ece7..e3fb1e1dbb 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -12,7 +12,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 9 of 202 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 6 | 4 | 2 | 664 of 664 menu items live (100.0%) | -| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 25 of 25 crates; panic_hunt present | +| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 24 of 25 crates; panic_hunt present | | [Distribution](#distribution) | 5 | 5 | 1 | | | [Open bugs](#open-bugs) | 31 | 1 | 0 | | @@ -280,7 +280,7 @@ Menu wiring (`docs/parity-checklist.md`): 664 of 664 menu items live (100.0%). T ## Reliability -Never-crash attribute on 25 of 25 crate roots. +Never-crash attribute on 24 of 25 crate roots; missing: `crates/ipp/src/lib.rs`. | Id | Target | Status | Issue | Note | |---|---|---|---|---| From a89a4faa49ed1908c4b7efe483e194c1a9379b33 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 17:09:06 -0800 Subject: [PATCH 33/85] IPP: the re-export crate keeps the never-crash lints #15684 replaced crates/ipp/src/lib.rs with a re-export of craft_ipp and dropped the crate's forbid(unsafe_code) and never-crash deny lines. The scorecard counts that attribute on every crate root, so docs/scorecard.md went stale on main and `scorecard::tests::staleness_check_and_determinism` and the lint job's `scorecard` step fail on every pull request. This puts the two lines back, so the scorecard reads 25 of 25 again and matches the committed docs/scorecard.md. --- crates/ipp/src/lib.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ipp/src/lib.rs b/crates/ipp/src/lib.rs index 0110914d8f..e849c3f791 100644 --- a/crates/ipp/src/lib.rs +++ b/crates/ipp/src/lib.rs @@ -1,3 +1,6 @@ //! Re-exports [`craft_ipp`] for backward compatibility with `photocraft-ipp`. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + pub use craft_ipp::*; From 90d9e35affabbf4aeacb1596590b4996820e683d Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 02:37:11 +0100 Subject: [PATCH 34/85] Integration: #15480: the Image Size test reads Pixels as the unit selects' value The Width and Height unit selects are labelled "Width unit" and "Height unit" and show Pixels as their value, so looking for a node labelled "Pixels" found none (it failed on Linux and Windows CI too). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/sizing/tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/sizing/tests.rs b/crates/ui-egui/src/dialogs/sizing/tests.rs index 2f93d1890d..f3cc2fedf7 100644 --- a/crates/ui-egui/src/dialogs/sizing/tests.rs +++ b/crates/ui-egui/src/dialogs/sizing/tests.rs @@ -200,8 +200,10 @@ fn image_size_draws_width_and_height_with_values_and_unit() { let shown = value_of(&h, label); assert!(shown.iter().any(|v| v == want), "{label} shows {want}: {shown:?}"); } - let pixels = h.query_all_by_label("Pixels").count(); - assert!(pixels >= 2, "the Width and Height unit selects show Pixels ({pixels} nodes)"); + for label in ["Width unit", "Height unit"] { + let shown = value_of(&h, label); + assert!(shown.iter().any(|v| v == "Pixels"), "the {label} select shows Pixels: {shown:?}"); + } let width = h.query_all_by_label("Width").find(|n| n.accesskit_node().value().is_some()).expect("the Width field"); width.click(); From 7abaf8a3270dc5d1aea4d6f58146f3b928e2f1cf Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 01:55:31 +0000 Subject: [PATCH 35/85] Image Size test: read the unit selects' values by their labels --- crates/ui-egui/src/dialogs/sizing/tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/sizing/tests.rs b/crates/ui-egui/src/dialogs/sizing/tests.rs index 2f93d1890d..46d381fd5d 100644 --- a/crates/ui-egui/src/dialogs/sizing/tests.rs +++ b/crates/ui-egui/src/dialogs/sizing/tests.rs @@ -200,8 +200,10 @@ fn image_size_draws_width_and_height_with_values_and_unit() { let shown = value_of(&h, label); assert!(shown.iter().any(|v| v == want), "{label} shows {want}: {shown:?}"); } - let pixels = h.query_all_by_label("Pixels").count(); - assert!(pixels >= 2, "the Width and Height unit selects show Pixels ({pixels} nodes)"); + for unit in ["Width unit", "Height unit"] { + let shown = value_of(&h, unit); + assert!(shown.iter().any(|v| v == "Pixels"), "the {unit} select shows Pixels: {shown:?}"); + } let width = h.query_all_by_label("Width").find(|n| n.accesskit_node().value().is_some()).expect("the Width field"); width.click(); From 0052ec5ce9942dbe4a69b882bdc1d8273bf84b80 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 02:20:03 +0000 Subject: [PATCH 36/85] ci: strip test binaries and build the craft framework at opt-level 0 in test builds --- .github/workflows/ci.yml | 9 +++++++-- Cargo.toml | 26 +++++++++++++------------- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 28e9a01d88..4d8ece1fc4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -164,13 +164,16 @@ jobs: # The tests build with the optional craft-fonts input (crates/text/build.rs), so the # Japanese font tests that skip without it run. Same commit as release.yml. craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795 - # Cargo.toml's dev profile already keeps line tables only. - dev-debug: "" + # CI test binaries carry no debuginfo and no symbols (CARGO_PROFILE_TEST_STRIP below): a + # test build drops from ~19 to ~6.5 GB. A panic still names its file and line; only + # backtrace frames lose names and lines. Local builds keep Cargo.toml's line tables. + dev-debug: "0" cache-version: v2 env: | PHOTOCRAFT_FULL_SWEEP=${{ inputs.full_sweep && '1' || '0' }} PHOTOCRAFT_NO_PRINT=1 LPDEST=photocraft-no-such-printer + CARGO_PROFILE_TEST_STRIP=symbols timeout-minutes: 100 # On main, a `cache warm` leg builds xtask and the tests, as each shard does, and saves the # dependency cache as soon as the build succeeds; the shards then only restore, so a failing @@ -245,6 +248,8 @@ jobs: # The gate sets these; rust-cache hashes CARGO_* and RUST* variables into its key. CARGO_INCREMENTAL: 0 CARGO_NET_RETRY: 10 + CARGO_PROFILE_DEV_DEBUG: "0" + CARGO_PROFILE_TEST_STRIP: symbols steps: - name: Harden runner uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 diff --git a/Cargo.toml b/Cargo.toml index eac941937a..f2e7f0b2c4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -174,27 +174,27 @@ opt-level = 0 # every crate that uses `craft`, photocraft-text included, waits for the whole framework. At 2 the # chain from craft-host to the facade took 38 of the 77 build minutes of the Windows unit leg, and # rustc shares no generic instantiations across crates at 2 (it does at 0 and 1). -# With the whole framework at 0, ten more photocraft-ui-egui tests overflowed their 2 MiB stack on -# Windows, so the runtime every frame passes through (contract, shell, canvas, panels, widgets, -# host) builds at 1, as do the crates with per-frame or per-pixel code (theme, behavior, imaging, -# text, font loading). The panels, tools and services around them build at 0, as in craft-libs. -# `cargo run` and `cargo build` use the dev profile and are unaffected. +# The framework's frames are small enough for this: a nesting level of the pass costs 21-26 KB of +# stack at opt-level 0, and the app's own state is boxed, so the deepest tests stay well inside +# their 2 MiB stack on Windows. Only the crates with per-frame or per-pixel code (theme, +# behavior, imaging, text, font loading) build at 1. `cargo run` and `cargo build` use the dev +# profile and are unaffected. [profile.test.package.craft] -opt-level = 1 +opt-level = 0 [profile.test.package.craft-ui] -opt-level = 1 +opt-level = 0 [profile.test.package.craft-ui-contract] -opt-level = 1 +opt-level = 0 [profile.test.package.craft-ui-shell] -opt-level = 1 +opt-level = 0 [profile.test.package.craft-ui-canvas] -opt-level = 1 +opt-level = 0 [profile.test.package.craft-ui-panels] -opt-level = 1 +opt-level = 0 [profile.test.package.craft-ui-widgets] -opt-level = 1 +opt-level = 0 [profile.test.package.craft-host] -opt-level = 1 +opt-level = 0 [profile.test.package.craft-theme] opt-level = 1 [profile.test.package.craft-behavior] From 22a1e6ce5f6e1dde7c82481518153d648f31f75d Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 05:21:42 +0000 Subject: [PATCH 37/85] test profile: framework runtime back at opt-level 1, engine at opt-level 0 At opt-level 0 the framework runtime made the whole-app UI tests about 60% slower on Linux and 30% on Windows. The framework comes from the CI cache and compiles only when the craft-libs pin moves, so the build saving appeared on few runs while every run paid in test time. The engine is a workspace crate that every test job compiles: at 0 its build is about 20% shorter and its tests 7-8% longer. --- Cargo.toml | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index f2e7f0b2c4..cb8461998c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -169,32 +169,41 @@ debug = "line-tables-only" [profile.test.package.photocraft-ui-egui] opt-level = 0 +# Test builds compile the engine without optimization. Every test job compiles it, and at 0 its +# test build is about 20% shorter on both Linux and Windows, while its tests run 7-8% longer +# (measured against crates the setting doesn't touch). Its pixel-heavy neighbours (algo) stay at +# the dev profile's 1. +[profile.test.package.photocraft-engine] +opt-level = 0 + # Test builds compile the craft UI framework (the `craft` facade and the craft-libs crates behind # it) below the opt-level 2 of `package."*"` above. The workspace unifies the facade's features, so # every crate that uses `craft`, photocraft-text included, waits for the whole framework. At 2 the # chain from craft-host to the facade took 38 of the 77 build minutes of the Windows unit leg, and # rustc shares no generic instantiations across crates at 2 (it does at 0 and 1). -# The framework's frames are small enough for this: a nesting level of the pass costs 21-26 KB of -# stack at opt-level 0, and the app's own state is boxed, so the deepest tests stay well inside -# their 2 MiB stack on Windows. Only the crates with per-frame or per-pixel code (theme, -# behavior, imaging, text, font loading) build at 1. `cargo run` and `cargo build` use the dev -# profile and are unaffected. +# The runtime every frame passes through (contract, shell, canvas, panels, widgets, host) builds at +# 1, as do the crates with per-frame or per-pixel code (theme, behavior, imaging, text, font +# loading). At 0 the whole-app UI tests ran about 60% longer on Linux and 30% longer on Windows, +# measured against crates the setting doesn't touch, while the framework comes from the CI cache +# and compiles only when the craft-libs pin moves (7 of 290 main merges in the week to 19 Nov). +# The panels, tools and services around the runtime build at 0, as in craft-libs. `cargo run` and +# `cargo build` use the dev profile and are unaffected. [profile.test.package.craft] -opt-level = 0 +opt-level = 1 [profile.test.package.craft-ui] -opt-level = 0 +opt-level = 1 [profile.test.package.craft-ui-contract] -opt-level = 0 +opt-level = 1 [profile.test.package.craft-ui-shell] -opt-level = 0 +opt-level = 1 [profile.test.package.craft-ui-canvas] -opt-level = 0 +opt-level = 1 [profile.test.package.craft-ui-panels] -opt-level = 0 +opt-level = 1 [profile.test.package.craft-ui-widgets] -opt-level = 0 +opt-level = 1 [profile.test.package.craft-host] -opt-level = 0 +opt-level = 1 [profile.test.package.craft-theme] opt-level = 1 [profile.test.package.craft-behavior] From ec40c48cc2215b5f4e5ca9e899621eab981b490f Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 03:33:27 +0000 Subject: [PATCH 38/85] ci: build the tests once per OS and run the shards from a nextest archive --- .config/nextest.toml | 6 ++++ .github/workflows/ci.yml | 6 ++-- docs/development.md | 2 +- scripts/ci-gpu-lavapipe.py | 2 +- scripts/ci-test-shard.sh | 38 +++++++++------------- xtask/src/main.rs | 66 ++++++++++++++++++++++++++++++++------ 6 files changed, 85 insertions(+), 35 deletions(-) diff --git a/.config/nextest.toml b/.config/nextest.toml index ce481be0f7..e50593dd52 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -33,6 +33,12 @@ test-group = 'gpu' fail-fast = false slow-timeout = { period = "60s", terminate-after = 10 } failure-output = "immediate-final" +# The gate's shards run the tests from a nextest archive (`cargo xtask ci archive`) and start them +# with the xtask binary the archive carries, so a shard builds nothing. Only one of the two exists. +archive.include = [ + { path = "debug/xtask", relative-to = "target", depth = 0, on-missing = "ignore" }, + { path = "debug/xtask.exe", relative-to = "target", depth = 0, on-missing = "ignore" }, +] # Keep phase timings for the remaining expensive Windows GPU regressions visible. This does # not relax their timeout, isolate failures differently or remove any test cases. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4d8ece1fc4..70c2e6083e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -155,7 +155,7 @@ jobs: gate: if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. - uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + uses: aiongg/craft-common-actions/.github/workflows/gate.yml@trial-build-once with: # egui/winit/rfd. packages: >- @@ -184,6 +184,7 @@ jobs: # missing-translations report (`cargo xtask ci lint`, xtask/src/main.rs), and the CI scripts' # own tests. lint-command: python3 scripts/test-ci-gpu-lavapipe.py && python3 scripts/test-ci-windows-gpu-tests.py && cargo xtask ci lint + archive-command: cargo xtask ci archive test-shards: 4 # The tests and panic_hunt with `--locked --features heif` (TEST_TARGETS in xtask/src/main.rs). shard-command: bash scripts/ci-test-shard.sh --gpu-shard @@ -201,7 +202,7 @@ jobs: needs: platforms if: needs.platforms.outputs.windows == 'true' # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. - uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + uses: aiongg/craft-common-actions/.github/workflows/gate.yml@trial-build-once with: os: '["windows-latest"]' # The all-language UI tests shape real Japanese, Chinese, Korean and Devanagari labels with @@ -231,6 +232,7 @@ jobs: timeout-minutes: 100 warm-command: cargo xtask ci build lint-command: cargo xtask ci clippy + archive-command: cargo xtask ci archive test-shards: 6 shard-command: bash scripts/ci-test-shard.sh diff --git a/docs/development.md b/docs/development.md index 4297bd541b..fe51840cac 100644 --- a/docs/development.md +++ b/docs/development.md @@ -114,7 +114,7 @@ the opted-in test; an unset variable leaves the ordinary behavior tests availabl After review, remove only the two generated PNGs and their owned temporary directory. The same Rust test and variable work on Windows with the native shell's environment-variable syntax. -**GPU tests without a GPU.** Linux CI uses the shared `craft-common-actions` gate with Mesa's Vulkan driver installed. The gate runs the tests in shards (`scripts/ci-test-shard.sh`, which calls `cargo xtask ci tests`). One shard runs the configured `gpu` group alone, through `python3 scripts/ci-gpu-lavapipe.py`, with `WGPU_BACKEND=vulkan` and the lavapipe ICD explicitly selected; the other shards split the remaining tests. The script requires Vulkan parity evidence in that shard's output and rejects authored skips, except the documented software-adapter timing exceptions. xtask reads the group's filter from `.config/nextest.toml`, so no second filter needs maintaining. To run locally on Linux, install `mesa-vulkan-drivers libvulkan1` and run `python3 scripts/ci-gpu-lavapipe.py cargo xtask ci tests --gpu`. Windows uses WARP; this check does not certify Windows skip coverage. +**GPU tests without a GPU.** Linux CI uses the shared `craft-common-actions` gate with Mesa's Vulkan driver installed. The gate builds the tests once into a nextest archive (`cargo xtask ci archive`) and runs them in shards from it (`cargo xtask ci tests`). One shard runs the configured `gpu` group alone, through `python3 scripts/ci-gpu-lavapipe.py`, with `WGPU_BACKEND=vulkan` and the lavapipe ICD explicitly selected; the other shards split the remaining tests. The script requires Vulkan parity evidence in that shard's output and rejects authored skips, except the documented software-adapter timing exceptions. xtask reads the group's filter from `.config/nextest.toml`, so no second filter needs maintaining. To run locally on Linux, install `mesa-vulkan-drivers libvulkan1`, build an archive and run `python3 scripts/ci-gpu-lavapipe.py /target/debug/xtask ci tests --from --gpu` as the gate's shard command in `.github/workflows/ci.yml` does. Windows uses WARP; this check does not certify Windows skip coverage. ## Fonts (craft-fonts) diff --git a/scripts/ci-gpu-lavapipe.py b/scripts/ci-gpu-lavapipe.py index ab3d46d5a7..7ff41e10c7 100644 --- a/scripts/ci-gpu-lavapipe.py +++ b/scripts/ci-gpu-lavapipe.py @@ -2,7 +2,7 @@ """Run a command with wgpu on lavapipe, and fail if a GPU comparison in its output was skipped. The Linux gate runs nextest's `gpu` test group in a shard of its own through this script -(`ci-gpu-lavapipe.py cargo xtask ci tests --gpu`, scripts/ci-test-shard.sh): every wgpu +(`ci-gpu-lavapipe.py ci tests --from --gpu`, .github/workflows/ci.yml): every wgpu device in the run is Vulkan on Mesa's CPU rasterizer, each test's output is shown, and the output is checked here for authored skips and for the parity tests' Vulkan backend line. diff --git a/scripts/ci-test-shard.sh b/scripts/ci-test-shard.sh index c1c380de6f..40afc15146 100755 --- a/scripts/ci-test-shard.sh +++ b/scripts/ci-test-shard.sh @@ -1,41 +1,35 @@ #!/usr/bin/env bash -# One shard of the gate's tests: the gate's `shard-command` (.github/workflows/ci.yml). Each shard -# restores the dependency cache, builds the tests (`cargo xtask ci build` builds the same on main's -# cache warm-up leg) and runs its share with `cargo xtask ci tests`. The gate sets GATE_SHARD (1..N), -# GATE_SHARDS (N) and NEXTEST_PARTITION (hash:GATE_SHARD/GATE_SHARDS). +# One shard of the gate's tests: the gate's `shard-command` (.github/workflows/ci.yml). The gate's +# build job wrote a nextest archive of the tests with `cargo xtask ci archive`, and the archive +# carries that xtask binary (.config/nextest.toml), so the shard extracts it and runs the test steps +# with `xtask ci tests` without building anything. The gate sets NEXTEST_ARCHIVE_FILE, GATE_SHARD, +# GATE_SHARDS and NEXTEST_PARTITION. # -# ci-test-shard.sh each shard runs its hash partition of every test; shard 1 also -# runs the doctests +# ci-test-shard.sh the shard runs its hash partition of every test # ci-test-shard.sh --gpu-shard shard 1 runs nextest's `gpu` group alone on lavapipe, checked by -# scripts/ci-gpu-lavapipe.py; the other shards split the other tests, -# and shard 2 also runs the doctests +# scripts/ci-gpu-lavapipe.py; the other shards split the other tests set -euo pipefail +archive=target/nextest-archive +mkdir -p "$archive" +cargo nextest run --archive-file "$NEXTEST_ARCHIVE_FILE" --workspace-remap . --extract-to "$archive" --extract-overwrite -E 'none()' --no-tests=pass +xtask=("$archive/target/debug/xtask" ci tests --from "$archive") +case "$(uname -s)" in MINGW* | MSYS* | CYGWIN*) xtask=("$archive/target/debug/xtask.exe" ci tests --from "$archive") ;; esac + case "${1:-}" in - "") - cargo xtask ci tests - doctests=1 - ;; + "") exec "${xtask[@]}" ;; --gpu-shard) if [ "$GATE_SHARDS" -lt 2 ]; then echo "::error::--gpu-shard needs at least two shards, got $GATE_SHARDS" exit 1 fi if [ "$GATE_SHARD" = 1 ]; then - # Build first, so only the test run goes through the lavapipe check. - cargo xtask ci build - python3 scripts/ci-gpu-lavapipe.py cargo xtask ci tests --gpu - else - NEXTEST_PARTITION="hash:$((GATE_SHARD - 1))/$((GATE_SHARDS - 1))" cargo xtask ci tests --no-gpu + exec python3 scripts/ci-gpu-lavapipe.py "${xtask[@]}" --gpu fi - doctests=2 + NEXTEST_PARTITION="hash:$((GATE_SHARD - 1))/$((GATE_SHARDS - 1))" exec "${xtask[@]}" --no-gpu ;; *) echo "usage: $0 [--gpu-shard]" >&2 exit 2 ;; esac - -if [ "$GATE_SHARD" = "$doctests" ]; then - cargo xtask ci doctest -fi diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 72abfd43dd..97ae021fd4 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -35,11 +35,13 @@ commands: wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates (one call, plus one per optional web feature) test workspace tests (cargo nextest when installed, else cargo test), then doctests - ci [lint | build | tests [--gpu | --no-gpu] | ] + ci [lint | archive | build | tests [--from ] [--gpu | --no-gpu] | ] the CI gate: fmt --check, egui-fork, clippy -D warnings, layers, panel-commands, scorecard --check, tests (nextest --profile ci), panic_hunt, doctests, wasm and the i18n-report, with --locked --features heif (stops at first failure). The gate splits it over its jobs: `lint` runs the - steps that need no test build; `tests` runs the tests and panic_hunt on the partition in + steps that need no test build; `archive` builds the tests into the nextest archive at + $NEXTEST_ARCHIVE_FILE and runs the doctests; `tests --from ` runs the tests from that archive + extracted to (without --from it builds them); `tests` runs the tests and panic_hunt on the partition in $NEXTEST_PARTITION (`--gpu`: all of nextest's gpu test group, whatever the partition, each test's output shown; `--no-gpu`: every other test); `doctest` runs the doctests; `build` only builds what `tests` @@ -284,6 +286,10 @@ struct CiOptions { build_only: bool, /// The nextest partition the test steps run ($NEXTEST_PARTITION with `ci tests`). partition: Option, + /// `ci archive`: build the tests into this nextest archive instead of running them. + archive: Option, + /// `ci tests --from `: run the tests from a nextest archive extracted to this directory. + from: Option, selection: Selection, /// Workspace packages left out of the test build and the doctests ($PHOTOCRAFT_CI_EXCLUDE). exclude: Vec, @@ -388,7 +394,22 @@ fn nextest_args(o: &CiOptions, panic_hunt: bool, gpu: Option<&str>) -> Vec Result<(), String> { /// warm-up's entry covers each shard's build. fn build_tests(o: &CiOptions) -> Result<(), String> { let mut c = cargo(); - c.args(["test", "--no-run"]).args(test_build_args(&o.exclude)); + match &o.archive { + Some(file) => { + c.args(["nextest", "archive", "--profile", "ci"]).args(test_build_args(&o.exclude)).arg("--archive-file").arg(file); + } + None => { + c.args(["test", "--no-run"]).args(test_build_args(&o.exclude)); + } + } let what = shown(&c); run(c, &what) } @@ -465,18 +493,23 @@ fn ci_exclude() -> Vec { /// The steps `cargo xtask ci ` runs, and how: no argument runs every step; a part (`lint`, /// `build`, `tests`) runs the steps of one gate job; a step's name runs that step. fn ci_from_args(args: &[&str], exclude: Vec) -> Result<(CiPlan, CiOptions), String> { - let mut options = CiOptions { build_only: false, partition: None, selection: Selection::All, exclude }; + let mut options = CiOptions { build_only: false, partition: None, archive: None, from: None, selection: Selection::All, exclude }; let mut what = None; - for &arg in args { + let mut it = args.iter(); + while let Some(&arg) = it.next() { match arg { + "--from" => { + let dir = it.next().ok_or("--from needs the directory the archive was extracted to")?; + options.from = Some(std::path::absolute(dir).map_err(|e| format!("--from {dir}: {e}"))?); + } "--gpu" => options.selection = Selection::Gpu, "--no-gpu" => options.selection = Selection::NoGpu, _ if what.is_none() && !arg.starts_with('-') => what = Some(arg), _ => return Err(format!("ci: unexpected argument `{arg}`")), } } - if options.selection != Selection::All && what != Some("tests") { - return Err("ci: --gpu and --no-gpu go with `ci tests`".into()); + if (options.selection != Selection::All || options.from.is_some()) && what != Some("tests") { + return Err("ci: --from, --gpu and --no-gpu go with `ci tests`".into()); } let parts: &[Part] = match what { None => &[Part::Lint, Part::Test, Part::Doc], @@ -485,6 +518,14 @@ fn ci_from_args(args: &[&str], exclude: Vec) -> Result<(CiPlan, CiOption options.build_only = true; &[Part::Test] } + // The gate's build job: the tests into the archive at $NEXTEST_ARCHIVE_FILE (which also + // carries this xtask, .config/nextest.toml), and the doctests, which need the rlibs. + Some("archive") => { + let file = std::env::var_os("NEXTEST_ARCHIVE_FILE").ok_or("ci archive: set NEXTEST_ARCHIVE_FILE to the archive to write")?; + options.archive = Some(file.into()); + options.build_only = true; + &[Part::Test, Part::Doc] + } Some("tests") => { options.partition = tests_partition(options.selection, std::env::var("NEXTEST_PARTITION").ok()); &[Part::Test] @@ -574,7 +615,14 @@ mod ci_tests { #[test] fn a_shard_builds_what_the_warm_up_builds_and_runs_its_partition() { - let options = CiOptions { build_only: false, partition: Some("hash:2/3".into()), selection: Selection::NoGpu, exclude: vec!["photocraft-web".into()] }; + let options = CiOptions { + build_only: false, + archive: None, + from: None, + partition: Some("hash:2/3".into()), + selection: Selection::NoGpu, + exclude: vec!["photocraft-web".into()], + }; let build = "--workspace --locked --features heif --exclude photocraft-web --lib --bins --tests"; let args = nextest_args(&options, false, Some("package(g)")).join(" "); assert_eq!(args, format!("nextest run --profile ci {build} --partition hash:2/3 -E not (package(g))")); From c353bd027454adb8796cd927c0644fc98921cb45 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 04:47:18 +0000 Subject: [PATCH 39/85] windows_delay_loads: read the exe path at run time, so a run from a nextest archive finds it --- apps/photocraft/tests/windows_delay_loads.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/photocraft/tests/windows_delay_loads.rs b/apps/photocraft/tests/windows_delay_loads.rs index f7b7504ced..a060f05871 100644 --- a/apps/photocraft/tests/windows_delay_loads.rs +++ b/apps/photocraft/tests/windows_delay_loads.rs @@ -10,7 +10,10 @@ const PRINT_ONLY: [&str; 2] = ["windows.data.pdf.dll", "prntvpt.dll"]; /// The built exe names each print-only DLL in its delay-load table, never its import table. #[test] fn print_only_system_dlls_are_delay_loaded() { - let exe = std::fs::read(env!("CARGO_BIN_EXE_photocraft")).unwrap(); + // The run-time variable first: a run from a nextest archive points it at the extracted exe, + // while the compile-time path names the directory the archive was built in. + let path = std::env::var("CARGO_BIN_EXE_photocraft").unwrap_or_else(|_| env!("CARGO_BIN_EXE_photocraft").to_string()); + let exe = std::fs::read(path).unwrap(); let pe = Pe::parse(&exe); let imports = pe.dll_names(1, 20, 12); let delayed = pe.dll_names(13, 32, 4); From 4e949fa450dfe594d2d0f238935f9413104426a0 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 07:57:34 +0100 Subject: [PATCH 40/85] Track engine change signals --- crates/engine/src/lib.rs | 1 + crates/engine/src/prefs/store.rs | 62 +++++++++++++++++++++++++- crates/engine/src/session/documents.rs | 30 +++++++++++++ 3 files changed, 92 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index d75e2a645d..4dbb442134 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -201,6 +201,7 @@ pub(crate) fn active_layer_of(s: &Session) -> std::result::Result<&photocraft_do #[derive(Default)] pub struct Session { docs: Vec, + documents_generation: u64, /// Override Open belongs only to one Batch scratch session, never to caller preferences. pub(crate) batch_open: Option, /// Import diagnostics retained by a Batch scratch that suppresses only profile prompts. diff --git a/crates/engine/src/prefs/store.rs b/crates/engine/src/prefs/store.rs index 07f0d8260f..10194488c8 100644 --- a/crates/engine/src/prefs/store.rs +++ b/crates/engine/src/prefs/store.rs @@ -8,6 +8,8 @@ use super::{Deserialize, Map, Preferences, Serialize, Value}; pub struct PrefsStore { values: Preferences, rev: u64, + catalog_rev: u64, + section_revs: std::collections::BTreeMap, } impl PrefsStore { @@ -16,8 +18,29 @@ impl PrefsStore { } /// Change preferences; bumps the revision. pub fn edit(&mut self, f: impl FnOnce(&mut Preferences) -> R) -> R { + let before = (&self.values.shortcuts, &self.values.alternate_shortcuts, &self.values.toolbar); + let before = (before.0.clone(), before.1.clone(), before.2.clone()); + let sections = self.values.sections.clone(); self.rev += 1; - f(&mut self.values) + let result = f(&mut self.values); + if (&before.0, &before.1, &before.2) != (&self.values.shortcuts, &self.values.alternate_shortcuts, &self.values.toolbar) { + self.catalog_rev = self.catalog_rev.wrapping_add(1); + } + for key in sections.keys().chain(self.values.sections.keys()).collect::>() { + if sections.get(key) != self.values.sections.get(key) { + let revision = self.section_revs.entry(key.clone()).or_default(); + *revision = revision.wrapping_add(1); + } + } + result + } + /// Revision of catalog-affecting preferences. + pub fn catalog_rev(&self) -> u64 { + self.catalog_rev + } + /// Revision of a framework preference section. + pub fn section_rev(&self, key: &str) -> u64 { + self.section_revs.get(key).copied().unwrap_or_default() } pub fn rev(&self) -> u64 { self.rev @@ -131,3 +154,40 @@ fn lay_over( fn object_at<'a>(root: &'a mut Value, path: &[String]) -> Option<&'a mut Map> { path.iter().try_fold(root, |cur, k| cur.get_mut(k.as_str()))?.as_object_mut() } + +#[cfg(test)] +mod revision_tests { + use super::PrefsStore; + use serde_json::json; + + #[test] + fn unrelated_preference_edits_do_not_invalidate_the_catalog() { + let mut prefs = PrefsStore::default(); + let before = prefs.catalog_rev(); + prefs.edit(|p| p.selected_tool = json!("brush")); + assert_eq!(prefs.catalog_rev(), before); + prefs.edit(|p| { + p.shortcuts.insert("example".into(), "A".into()); + }); + assert_eq!(prefs.catalog_rev(), before.wrapping_add(1)); + } + + #[test] + fn section_revisions_change_independently() { + let mut prefs = PrefsStore::default(); + prefs.edit(|p| { + p.sections.insert("one".into(), json!({"value": 1})); + }); + let one = prefs.section_rev("one"); + let two = prefs.section_rev("two"); + prefs.edit(|p| { + p.sections.insert("two".into(), json!({"value": 2})); + }); + assert_eq!(prefs.section_rev("one"), one); + assert_eq!(prefs.section_rev("two"), two.wrapping_add(1)); + prefs.edit(|p| { + p.sections.remove("one"); + }); + assert_eq!(prefs.section_rev("one"), one.wrapping_add(1)); + } +} diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index fc3b1708aa..72ca474fe1 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -24,6 +24,11 @@ impl Session { &self.docs } + /// Changes whenever a document is opened or closed. + pub fn documents_generation(&self) -> u64 { + self.documents_generation + } + pub fn active_index(&self) -> Option { self.active } @@ -182,6 +187,7 @@ impl Session { st.snapshots.clear(); } self.docs.push(st); + self.documents_generation = self.documents_generation.wrapping_add(1); let i = self.docs.len() - 1; self.active = Some(i); self.note_active_change(); @@ -222,6 +228,7 @@ impl Session { self.link_scan = None; } let d = self.docs.remove(index); + self.documents_generation = self.documents_generation.wrapping_add(1); self.open_document_order.retain(|&id| id != d.doc.id); self.active = if self.docs.is_empty() { None @@ -244,3 +251,26 @@ pub(super) fn fix_active(st: &mut DocState) { fix_selection(st); channel_cmds::fix_view(st); } + +#[cfg(test)] +mod document_generation_tests { + use super::Session; + use photocraft_color::SampleType; + use photocraft_doc::{ColorMode, Document}; + use photocraft_geom::Size; + + #[test] + fn document_generation_tracks_open_and_close_but_not_selection() { + let mut session = Session::new(); + let before = session.documents_generation(); + session.add_document(Document::new("test", Size::new(2, 2), ColorMode::Rgb, SampleType::U8), None); + let opened = session.documents_generation(); + assert_eq!(opened, before.wrapping_add(1)); + session.set_active(0); + assert_eq!(session.documents_generation(), opened); + session.close(0); + assert_eq!(session.documents_generation(), opened.wrapping_add(1)); + session.close(0); + assert_eq!(session.documents_generation(), opened.wrapping_add(1)); + } +} From e681044bf52c6fc6840ede6fd3dfc94f330a95bf Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 07:58:27 +0100 Subject: [PATCH 41/85] Reduce slow algorithm test fixtures --- crates/algo/src/inpaint/tests.rs | 4 ++-- crates/algo/src/panorama/parallel_tests.rs | 2 +- crates/algo/src/render.rs | 4 ++++ 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/algo/src/inpaint/tests.rs b/crates/algo/src/inpaint/tests.rs index 747e9c36cd..8db4da3828 100644 --- a/crates/algo/src/inpaint/tests.rs +++ b/crates/algo/src/inpaint/tests.rs @@ -186,10 +186,10 @@ fn a_hole_is_as_thick_as_it_is_through_not_along() { #[test] #[cfg(not(target_arch = "wasm32"))] fn thin_holes_are_filled_the_same_on_any_number_of_threads() { - let (w, h) = (300, 200); + let (w, h) = (150, 100); let img = busy(w, h, 3, 5); // A wavy line 6 px thick across the image. - let hole: Vec = (0..w * h).map(|i| (((i % w) as f32 * 0.05).sin() * 30.0 + 100.0 - (i / w) as f32).abs() < 3.0).collect(); + let hole: Vec = (0..w * h).map(|i| (((i % w) as f32 * 0.05).sin() * 15.0 + 50.0 - (i / w) as f32).abs() < 3.0).collect(); let px = roles(w, h, &hole); let run = |threads: usize| { let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap(); diff --git a/crates/algo/src/panorama/parallel_tests.rs b/crates/algo/src/panorama/parallel_tests.rs index 54f6f54edb..2bfa239fd5 100644 --- a/crates/algo/src/panorama/parallel_tests.rs +++ b/crates/algo/src/panorama/parallel_tests.rs @@ -367,7 +367,7 @@ fn multiband_matches_the_serial_code() { /// none and everything, pass through every split the images can have (#15652; it swept 47 budgets). #[test] fn multiband_batches_match_the_serial_code() { - for (n, &(w, h)) in [(40usize, 30usize), (97, 61), (201, 129)].iter().enumerate() { + for (n, &(w, h)) in [(40usize, 30usize), (97, 61)].iter().enumerate() { for ch in [1usize, 3] { let (imgs, wts) = rois(w, h, ch, n as u64 * 17 + ch as u64); for levels in [1usize, 3, 5] { diff --git a/crates/algo/src/render.rs b/crates/algo/src/render.rs index 6bce0bfa59..4df30a76a1 100644 --- a/crates/algo/src/render.rs +++ b/crates/algo/src/render.rs @@ -273,6 +273,10 @@ mod tests { let fmt = PixelFormat::new(mode, depth, true); for (w, h) in [(512, 512), (900, 240), (2400, 1200)] { for seed in [0, 3, 7, 18916] { + // One seed exercises the large canvas; all seeds still run at both smaller sizes. + if w == 2400 && seed != 0 { + continue; + } let px = render(fmt, w, h, seed, (BLACK, WHITE), None); let v: Vec = px.chunks_exact(fmt.channels()).map(|p| p[0]).collect(); let n = v.len() as f32; From 236bc84a5e7d67aa75976f401df9af5a51e78f35 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:01:25 +0100 Subject: [PATCH 42/85] Give scratch tests a deterministic volume capacity --- crates/automation/tests/it/scratch_save.rs | 1 + crates/compose/tests/it/scratch_retry.rs | 1 + .../engine/tests/global_state/scratch_disk.rs | 1 + .../tests/global_state/scratch_pause.rs | 1 + crates/format/tests/it/scratch_retry.rs | 1 + crates/raster/src/spill.rs | 40 ++++++++++++++++--- crates/raster/tests/it/main.rs | 4 +- crates/ui-egui/src/app.rs | 2 + crates/ui-egui/tests/it/gpu_device_loss.rs | 2 + .../tests/it/gpu_tests/live_stroke_canvas.rs | 2 + .../ui-egui/tests/it/variables_data_sets.rs | 4 ++ 11 files changed, 53 insertions(+), 6 deletions(-) diff --git a/crates/automation/tests/it/scratch_save.rs b/crates/automation/tests/it/scratch_save.rs index 140b916e31..e6f4eaa860 100644 --- a/crates/automation/tests/it/scratch_save.rs +++ b/crates/automation/tests/it/scratch_save.rs @@ -34,6 +34,7 @@ impl BandRenderer for QueuedDiagnosticsRenderer { #[test] fn native_save_refuses_previews_rendered_from_unreadable_scratch() { + photocraft_raster::spill::use_test_volume_space(); let dir = std::env::temp_dir().join(format!("photocraft-automation-scratch-save-{}", std::process::id())); spill::configure(Some(&dir), 1).unwrap(); let mut doc = Document::new("Scratch", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); diff --git a/crates/compose/tests/it/scratch_retry.rs b/crates/compose/tests/it/scratch_retry.rs index 70fdc41225..625bb30e7f 100644 --- a/crates/compose/tests/it/scratch_retry.rs +++ b/crates/compose/tests/it/scratch_retry.rs @@ -8,6 +8,7 @@ use std::io::{Read, Seek, SeekFrom, Write}; #[test] fn failed_effect_build_is_not_reused_after_original_pixels_recover() { + photocraft_raster::spill::use_test_volume_space(); let dir = std::env::temp_dir().join(format!("photocraft-compose-scratch-retry-{}", std::process::id())); spill::configure(Some(&dir), 1).unwrap(); let mut doc = Document::new("Shadow", Size::new(64, 64), ColorMode::Rgb, SampleType::U8); diff --git a/crates/engine/tests/global_state/scratch_disk.rs b/crates/engine/tests/global_state/scratch_disk.rs index 888fa4551c..21122fced2 100644 --- a/crates/engine/tests/global_state/scratch_disk.rs +++ b/crates/engine/tests/global_state/scratch_disk.rs @@ -9,6 +9,7 @@ use std::sync::Arc; #[test] fn scratch_pixels_history_and_failed_save_are_transactional() { + photocraft_raster::spill::use_test_volume_space(); let _scratch = crate::lock(&crate::PROCESS); let dir = std::env::temp_dir().join(format!("photocraft-engine-scratch-{}", std::process::id())); let mut session = Session::new(); diff --git a/crates/engine/tests/global_state/scratch_pause.rs b/crates/engine/tests/global_state/scratch_pause.rs index 309e69fd39..30c81f2903 100644 --- a/crates/engine/tests/global_state/scratch_pause.rs +++ b/crates/engine/tests/global_state/scratch_pause.rs @@ -9,6 +9,7 @@ use serde_json::json; #[test] fn paused_scratch_disk_restores_the_history_limit() { + photocraft_raster::spill::use_test_volume_space(); let _scratch = crate::lock(&crate::PROCESS); let dir = std::env::temp_dir().join(format!("photocraft-engine-scratch-pause-{}", std::process::id())); let mut session = Session::new(); diff --git a/crates/format/tests/it/scratch_retry.rs b/crates/format/tests/it/scratch_retry.rs index 3d8a32f540..ea26de5a88 100644 --- a/crates/format/tests/it/scratch_retry.rs +++ b/crates/format/tests/it/scratch_retry.rs @@ -8,6 +8,7 @@ use std::io::{Read, Seek, SeekFrom, Write}; #[test] fn retry_after_failed_hashing_never_reuses_placeholder_hashes() { + photocraft_raster::spill::use_test_volume_space(); let dir = std::env::temp_dir().join(format!("photocraft-format-scratch-retry-{}", std::process::id())); spill::configure(Some(&dir), 1).unwrap(); let mut doc = Document::new("Retry", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); diff --git a/crates/raster/src/spill.rs b/crates/raster/src/spill.rs index 2fc5707fa7..9b5245dea9 100644 --- a/crates/raster/src/spill.rs +++ b/crates/raster/src/spill.rs @@ -256,6 +256,7 @@ struct Registry { } struct Config { + query_space: fn(&Path) -> Option<(u64, u64)>, dir: Option, /// Opened at configuration time; startup also reaps abandoned Unix files. file: Option>, @@ -341,7 +342,17 @@ static M: Manager = Manager { recovering: AtomicBool::new(false), space_unmeasured: AtomicBool::new(false), registry: Mutex::new(Registry { cells: Vec::new(), hand: 0 }), - config: Mutex::new(Config { dir: None, file: None, last_error: None, budget: 0, paused: None, backoff: RETRY_FIRST, size_cap: None, room: None }), + config: Mutex::new(Config { + query_space: free_space, + dir: None, + file: None, + last_error: None, + budget: 0, + paused: None, + backoff: RETRY_FIRST, + size_cap: None, + room: None, + }), evictions: AtomicU64::new(0), reloads: AtomicU64::new(0), written: AtomicU64::new(0), @@ -609,11 +620,15 @@ impl Manager { /// Record a volume's answer (`None` = it didn't say) and derive the growth limit from it. fn apply_space(c: &mut Config, used: u64, space: Option<(u64, u64)>) { M.space_unmeasured.store(space.is_none(), Ordering::Relaxed); - c.room = space.map(|(available, total)| used.saturating_add(available.saturating_sub(RESERVE_MIN.max(total / 20)))); + c.room = space.map(|(available, total)| growth_limit(used, available, total)); store_limit(c); M.next_space_check.store(used.saturating_add(SPACE_CHECK_EVERY), Ordering::Relaxed); } +fn growth_limit(used: u64, available: u64, total: u64) -> u64 { + used.saturating_add(available.saturating_sub(RESERVE_MIN.max(total / 20))) +} + /// Publish the scratch size the volume and the size limit allow. fn store_limit(c: &Config) { let room = c.room.unwrap_or(u64::MAX); @@ -664,13 +679,13 @@ fn run_query(dir: PathBuf, prepare: bool, done: Arc) { } // Before measuring: writes made during the query come off the free space and must not be // counted again on top of it. Another folder's file says nothing about this one. - let (open, used) = { + let (open, used, query_space) = { let c = M.config(); let current = c.file.as_ref().filter(|_| c.dir.as_deref() == Some(dir.as_path())); - (prepare && current.is_none(), current.map_or(0, |f| f.used())) + (prepare && current.is_none(), current.map_or(0, |f| f.used()), c.query_space) }; let file = open.then(|| std::fs::create_dir_all(&dir).and_then(|()| ScratchFile::create(&dir))); - let space = free_space(&dir); + let space = query_space(&dir); // Forget it first: a caller that joined it can rely on the answer, and a later caller asks anew. QUERIES.lock().unwrap_or_else(PoisonError::into_inner).retain(|q| !Arc::ptr_eq(&q.done, &done)); M.settle(&dir, prepare, file, used, space, &done); @@ -1122,6 +1137,12 @@ pub fn scratch_handle_for_tests() -> Option { M.config().file.as_ref().and_then(|f| f.duplicate_handle().ok()) } +/// Use a volume with ample space for scratch tests. Missing folders still report unknown space. +#[doc(hidden)] +pub fn use_test_volume_space() { + M.config().query_space = |dir| dir.is_dir().then_some((32 << 30, 64 << 30)); +} + /// Runs at the start of every folder query, off every lock: tests stall it to simulate a dead mount. #[doc(hidden)] pub fn set_query_hook_for_tests(hook: Option) { @@ -1156,6 +1177,15 @@ fn log_error(msg: &str) { mod tests { use super::*; + #[test] + fn scratch_growth_preserves_the_larger_of_one_gib_or_five_percent() { + const GIB: u64 = 1 << 30; + let used = 3 * GIB; + assert_eq!(growth_limit(used, 2 * GIB, 10 * GIB), used + GIB); + assert_eq!(growth_limit(used, 7 * GIB, 100 * GIB), used + 2 * GIB); + assert_eq!(growth_limit(used, 3 * GIB, 100 * GIB), used); + } + #[cfg(windows)] #[test] fn free_space_keeps_a_trailing_dot_folder() { diff --git a/crates/raster/tests/it/main.rs b/crates/raster/tests/it/main.rs index cda56fa4c1..9a6b14ffce 100644 --- a/crates/raster/tests/it/main.rs +++ b/crates/raster/tests/it/main.rs @@ -14,5 +14,7 @@ pub(crate) static SCRATCH: Mutex<()> = Mutex::new(()); /// Takes one of the locks above; a failed test that held it does not fail the next. pub(crate) fn lock(lock: &'static Mutex<()>) -> MutexGuard<'static, ()> { - lock.lock().unwrap_or_else(PoisonError::into_inner) + let guard = lock.lock().unwrap_or_else(PoisonError::into_inner); + photocraft_raster::spill::use_test_volume_space(); + guard } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index f65417fd5c..47e02244e3 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -228,6 +228,8 @@ impl PhotocraftApp { #[cfg(all(debug_assertions, not(target_arch = "wasm32")))] live_tokens: theme::live::LiveTokens::from_env(), }; + #[cfg(all(test, not(target_arch = "wasm32")))] + photocraft_raster::spill::use_test_volume_space(); // Saved preferences are in place before the first frame; recovery starts in upkeep. prefs_ui::load(&mut app); // The workspace set reads the loaded preferences (and moves the earlier saves into it). diff --git a/crates/ui-egui/tests/it/gpu_device_loss.rs b/crates/ui-egui/tests/it/gpu_device_loss.rs index a3aa0bdca3..94d0bce1d3 100644 --- a/crates/ui-egui/tests/it/gpu_device_loss.rs +++ b/crates/ui-egui/tests/it/gpu_device_loss.rs @@ -142,6 +142,8 @@ mod gpu_tests { fn app_switches_to_the_cpu_canvas_and_keeps_the_documents() { let _gpu = gpu_lock(); let Some(rs) = render_state() else { return }; + #[cfg(not(target_arch = "wasm32"))] + photocraft_raster::spill::use_test_volume_space(); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); app.set_wgpu(rs); app.run("file.new", json!({"width": 320, "height": 240})).unwrap(); diff --git a/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs b/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs index fba4fef7a9..1556fb0e04 100644 --- a/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs +++ b/crates/ui-egui/tests/it/gpu_tests/live_stroke_canvas.rs @@ -76,6 +76,8 @@ fn harness() -> Option { let built = std::panic::catch_unwind(|| { egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 640.0)).with_pixels_per_point(1.0).with_max_steps(64).wgpu().build_eframe(|cc| { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + #[cfg(not(target_arch = "wasm32"))] + photocraft_raster::spill::use_test_volume_space(); let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); if let Some(rs) = cc.wgpu_render_state.as_ref() { app.set_wgpu(rs.clone()); diff --git a/crates/ui-egui/tests/it/variables_data_sets.rs b/crates/ui-egui/tests/it/variables_data_sets.rs index 3fb254e664..6625378806 100644 --- a/crates/ui-egui/tests/it/variables_data_sets.rs +++ b/crates/ui-egui/tests/it/variables_data_sets.rs @@ -83,6 +83,8 @@ fn pixel_replacement_harness() -> (tempfile::TempDir, H, String) { let png = photocraft_io::export(&source.active().unwrap().doc, "png", &photocraft_io::ExportOptions::default()).unwrap().bytes; std::fs::write(dir.path().join(name), png).unwrap(); } + #[cfg(not(target_arch = "wasm32"))] + photocraft_raster::spill::use_test_volume_space(); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); app.run("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); let layer = app.session.active().unwrap().active_layer.unwrap(); @@ -103,6 +105,8 @@ fn save_draft_and_open_apply_menu(h: &mut H, id: &str) -> String { #[test] fn apply_menu_ok_requires_a_row_but_not_variable_definitions() { for (rows, expected) in [(json!([]), None), (json!([{"name": "Empty", "values": []}]), Some(0))] { + #[cfg(not(target_arch = "wasm32"))] + photocraft_raster::spill::use_test_volume_space(); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); app.run("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); app.run("image.variables.dataSets", json!({"dataSets": rows})).unwrap(); From 3ee723a5259160df3e5136c6e7b7de951455268d Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:01:29 +0100 Subject: [PATCH 43/85] Reduce slow engine test fixtures --- crates/engine/src/cmd/image_cmds/tests.rs | 10 ++++++---- crates/engine/src/cmd/retouch_cmds/tests.rs | 8 +++----- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/image_cmds/tests.rs b/crates/engine/src/cmd/image_cmds/tests.rs index 5acec8b8ba..88da8f65c1 100644 --- a/crates/engine/src/cmd/image_cmds/tests.rs +++ b/crates/engine/src/cmd/image_cmds/tests.rs @@ -798,16 +798,18 @@ fn crop_at_a_small_angle_keeps_the_frame_size_in_every_mode() { #[test] fn turned_crop_deleting_pixels_matches_turning_the_whole_canvas() { use photocraft_color::PixelFormat; - let pixels = || (0..500).flat_map(|y| (0..700).map(move |x| (x, y))); for depth in [8, 16, 32] { for angle in [3.0, -7.5, 33.0, 181.0] { + let (w, h) = if depth == 8 && angle == 33.0 { (700, 500) } else { (140, 100) }; + let scale = w / 140; + let pixels = || (0..h).flat_map(|y| (0..w).map(move |x| (x, y))); let mut sessions = [true, false].map(|delete| { let mut s = Session::new(); - s.execute("file.new", json!({"width": 700, "height": 500, "depth": depth, "background": "white"})).unwrap(); + s.execute("file.new", json!({"width": w, "height": h, "depth": depth, "background": "white"})).unwrap(); s.execute("layer.new.layer", json!({})).unwrap(); s.edit("paint", |doc, active| { let wave = |x: i32, y: i32, k: i32| ((x * 7 + y * 13 + k * 31) % 97) as f32 / 96.0; - let all = Rect::new(0, 0, 700, 500); + let all = Rect::new(0, 0, w, h); let rgba: Vec = pixels().flat_map(|(x, y)| [wave(x, y, 0), wave(x, y, 1), wave(x, y, 2), wave(y, x, 3)]).collect(); let gray: Vec = pixels().map(|(x, y)| wave(y, x, 4)).collect(); let l = doc.layer_mut(active.unwrap()).unwrap(); @@ -824,7 +826,7 @@ fn turned_crop_deleting_pixels_matches_turning_the_whole_canvas() { Ok(()) }) .unwrap(); - let p = json!({"x": 150, "y": 120, "width": 330, "height": 290, "angle": angle, "deleteCroppedPixels": delete}); + let p = json!({"x": 30 * scale, "y": 24 * scale, "width": 66 * scale, "height": 58 * scale, "angle": angle, "deleteCroppedPixels": delete}); s.execute("image.crop", p).unwrap(); s }); diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index 49eaaaa52f..999575cf69 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -1650,10 +1650,11 @@ fn large_move(depth: u64) -> Session { } #[test] -fn content_aware_move_previews_large_selections_coarse_then_exact_at_all_depths() { +fn content_aware_move_previews_large_selections_coarse_then_exact() { use crate::jobs::JobCtx; let p = json!({"offset": [250, 60]}); - for depth in DEPTHS { + // The small move test covers all depths; the preview sequence needs one. + for depth in [8] { let mut s = large_move(depth); let before = s.active().unwrap().revision; let job = content_aware_move_preview(&s, &p).unwrap(); @@ -1684,9 +1685,6 @@ fn content_aware_move_previews_large_selections_coarse_then_exact_at_all_depths( let fine = job.refine().unwrap(); assert!(!fine.is_coarse() && fine.refine().is_none()); assert!(matches!(fine.run(&ctx), Err(EngineError::Cancelled)), "depth {depth}"); - if depth != 8 { - continue; - } // The refined preview is the command's result, bit for bit. let (exact, _) = fine.run(&JobCtx::new()).unwrap(); assert_eq!(s.active().unwrap().revision, before); From cb019d6cc6d294148d4bee4d53a0555c26d65145 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:10:56 +0100 Subject: [PATCH 44/85] Initialize the measurement callback in the isolated spill manager --- crates/raster/src/spill.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/raster/src/spill.rs b/crates/raster/src/spill.rs index 9b5245dea9..9caf545c5e 100644 --- a/crates/raster/src/spill.rs +++ b/crates/raster/src/spill.rs @@ -1359,6 +1359,7 @@ mod tests { space_unmeasured: AtomicBool::new(false), registry: Mutex::new(Registry { cells: Vec::new(), hand: 0 }), config: Mutex::new(Config { + query_space: free_space, dir: Some(base.join("growth")), file: None, last_error: None, From 63ac4be5a2c27af19920a9ff1df2ccfcba32ee3d Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:17:10 +0100 Subject: [PATCH 45/85] Reduce redundant pixelate fixture combinations --- crates/algo/src/pixelate/tests.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/algo/src/pixelate/tests.rs b/crates/algo/src/pixelate/tests.rs index ac432283a5..59a3936e43 100644 --- a/crates/algo/src/pixelate/tests.rs +++ b/crates/algo/src/pixelate/tests.rs @@ -127,9 +127,13 @@ fn halftone_unusual_coordinates_and_params_keep_direct_semantics() { fn tiled_filters_match_scalar_at_all_depths_with_soft_selection() { use crate::{FilterParams, apply_tiled}; let bounds = Rect::new(-17, -9, 26, 24); - for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - for alpha in [false, true] { + // Every mode/depth pair and both alpha values for each mode and depth. + for (mi, mode) in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().enumerate() { + for (di, depth) in [SampleType::U8, SampleType::U16, SampleType::F32].into_iter().enumerate() { + for (ai, alpha) in [false, true].into_iter().enumerate() { + if (mi + di) % 2 != ai { + continue; + } let ctx = Ctx { bounds, mode, alpha }; let src = fixture(bounds, &ctx, 2); let mut surface = Surface::new(PixelFormat::new(mode, depth, alpha)); From 35219ec6a1c2a7b64c754628ee91da4a0f8b2d12 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:27:27 +0100 Subject: [PATCH 46/85] Track surface pixel generations --- crates/raster/src/lib.rs | 40 ++++++++++++++++++++++++++++++++++++-- crates/raster/src/shift.rs | 10 ++++++++-- crates/raster/src/tests.rs | 21 ++++++++++++++++++++ 3 files changed, 67 insertions(+), 4 deletions(-) diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 1c1b74d992..8255122bb8 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -311,6 +311,7 @@ impl PruneCursor { #[derive(Clone, Debug)] pub struct Surface { + generation: u64, format: PixelFormat, default_pixel: Box<[u8]>, tiles: BTreeMap>, @@ -585,7 +586,23 @@ fn decode_tile_row_rgba(fmt: &PixelFormat, t: &[u8], base: usize, dst: &mut [[f3 } } +// Tokens identify a particular pixel state across surfaces and copy-on-write clones. +static NEXT_SURFACE_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +fn fresh_surface_generation() -> u64 { + NEXT_SURFACE_GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + impl Surface { + /// Equal generations identify the same pixel state, including across clones. + pub fn generation(&self) -> u64 { + self.generation + } + + fn note_mutation(&mut self) { + self.generation = fresh_surface_generation(); + } + /// Reads a region into a newly allocated buffer, returning an error instead of aborting if /// the requested pixel buffer cannot be represented or reserved. pub fn try_read_region(&self, r: Rect) -> Result, AllocationError> { @@ -647,7 +664,7 @@ impl Surface { /// Transparent/zero surface. pub fn new(format: PixelFormat) -> Self { - Self { format, default_pixel: vec![0u8; format.bytes_per_pixel()].into_boxed_slice(), tiles: BTreeMap::new() } + Self { generation: fresh_surface_generation(), format, default_pixel: vec![0u8; format.bytes_per_pixel()].into_boxed_slice(), tiles: BTreeMap::new() } } /// Surface whose untouched pixels read as `pixel` (normalised channel values). @@ -687,6 +704,7 @@ impl Surface { /// Mutable access to a tile, allocating it (filled with the default pixel) or un-sharing it. pub fn tile_mut(&mut self, c: TileCoord) -> &mut Tile { + self.note_mutation(); let fmt = self.format; let dp = &self.default_pixel; let arc = self.tiles.entry(c).or_insert_with(|| Arc::new(Tile::filled(&fmt, dp))); @@ -696,6 +714,7 @@ impl Surface { /// Fallible counterpart to [`Surface::tile_mut`]. Pixel storage is reserved before changing /// the surface, and a shared tile is copied only after its replacement has been allocated. pub fn try_tile_mut(&mut self, c: TileCoord) -> Result<&mut Tile, AllocationError> { + self.note_mutation(); if let Some(tile) = self.tiles.get(&c) { drop(tile.try_bytes().map_err(AllocationError::ScratchRead)?); } @@ -723,6 +742,7 @@ impl Surface { /// Writes a region using fallible pixel-tile allocations. Callers that need transactional /// document updates should perform this on their staged document copy and commit on success. pub fn try_write_region(&mut self, r: Rect, data: &[f32]) -> Result<(), AllocationError> { + self.note_mutation(); let n = self.channels(); let sample = self.format.sample; let expected = (r.width() as usize).checked_mul(r.height() as usize).and_then(|v| v.checked_mul(n)).ok_or(AllocationError::SizeOverflow)?; @@ -804,6 +824,7 @@ impl Surface { /// large it is, and across every surface that shares `interner`. Tiles are copy-on-write, so /// editing one splits it off again. Returns the bytes no longer held by this surface alone. pub fn share_uniform_tiles(&mut self, interner: &mut TileInterner) -> usize { + self.note_mutation(); let bpp = self.format.bytes_per_pixel(); let mut saved = 0; for t in self.tiles.values_mut() { @@ -826,6 +847,7 @@ impl Surface { /// Drop tiles that are entirely the default pixel. pub fn prune(&mut self) { + self.note_mutation(); let dp = self.default_pixel.as_ref(); let bpp = dp.len(); self.tiles.retain(|_, t| t.bytes().chunks_exact(bpp).any(|px| px != dp)); @@ -844,6 +866,7 @@ impl Surface { /// before the last visited coordinate is not visited, one inserted after it is (and dropped /// when it holds only the default pixel, which reads the same as an absent tile). pub fn prune_batch(&mut self, cursor: &mut PruneCursor, max: usize) -> bool { + self.note_mutation(); if cursor.done { return true; } @@ -902,6 +925,7 @@ impl Surface { } pub fn write_pixel(&mut self, x: i32, y: i32, px: &[f32]) { + self.note_mutation(); let (c, base) = self.locate(x, y); let n = self.channels(); let sample = self.format.sample; @@ -1099,6 +1123,7 @@ impl Surface { /// section that must not run another Rayon job on its stack. [`Surface::write_region_par`] /// writes the same bytes on all cores. pub fn write_region(&mut self, r: Rect, data: &[f32]) { + self.note_mutation(); let n = self.channels(); let w = r.width() as usize; assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch"); @@ -1114,6 +1139,7 @@ impl Surface { /// queued Rayon job. Callers inside a `OnceLock` initializer or another section that must /// not do that use [`Surface::write_region`]. pub fn write_region_par(&mut self, r: Rect, data: &[f32]) { + self.note_mutation(); let n = self.channels(); let w = r.width() as usize; assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch"); @@ -1130,6 +1156,7 @@ impl Surface { /// pixel), so they can be edited elsewhere, e.g. in parallel: `Arc::unwrap_or_clone` copies a /// tile only if an undo snapshot still shares it. Give them back with [`Surface::put_tiles`]. pub fn take_tiles(&mut self, r: Rect) -> Vec<(TileCoord, Arc)> { + self.note_mutation(); let fmt = self.format; let mut blank: Option> = None; r.tiles() @@ -1143,6 +1170,7 @@ impl Surface { /// Fallible counterpart to [`Surface::take_tiles`]. Reserves the complete result and any /// default tile before removing a tile, so a reservation failure leaves the surface intact. pub fn try_take_tiles(&mut self, r: Rect) -> Result)>, AllocationError> { + self.note_mutation(); // Counted in u64 and checked before narrowing: on 32-bit targets the grid of a sparse // surface's bounds can pass `usize` (and visiting it to count it takes just as long). let count = usize::try_from(r.tile_count()).map_err(|_| AllocationError::SizeOverflow)?; @@ -1162,6 +1190,7 @@ impl Surface { /// Put tiles back (see [`Surface::take_tiles`]); each replaces the tile at its coordinate. pub fn put_tiles(&mut self, tiles: impl IntoIterator)>) { + self.note_mutation(); for (c, t) in tiles { self.tiles.insert(c, t); } @@ -1187,6 +1216,7 @@ impl Surface { /// Fill a rectangle with one pixel value. pub fn fill_rect(&mut self, r: Rect, px: &[f32]) { + self.note_mutation(); let n = self.channels(); let mut enc = vec![0u8; self.format.bytes_per_pixel()]; encode_pixel(&self.format, &px[..n], &mut enc); @@ -1224,6 +1254,7 @@ impl Surface { /// Write interleaved encoded bytes (same format as the surface) into `r`. pub fn write_interleaved(&mut self, r: Rect, bytes: &[u8]) { + self.note_mutation(); let bpp = self.format.bytes_per_pixel(); let w = r.width() as usize; assert_eq!(bytes.len(), w * r.height() as usize * bpp, "interleaved length mismatch"); @@ -1246,6 +1277,7 @@ impl Surface { /// /// This enters Rayon, as [`Surface::write_region_par`] does. pub fn try_write_interleaved(&mut self, r: Rect, bytes: &[u8]) -> Result<(), AllocationError> { + self.note_mutation(); let bpp = self.format.bytes_per_pixel(); let w = r.width() as usize; let expected = w.checked_mul(r.height() as usize).and_then(|v| v.checked_mul(bpp)).ok_or(AllocationError::SizeOverflow)?; @@ -1273,6 +1305,7 @@ impl Surface { where F: Fn(i32, i32, &mut [u8]) + Sync, { + self.note_mutation(); self.try_prepare_rows(r, |tiles, format, default_pixel| fill_tiles(tiles, r, format, default_pixel, &fill, &|| Ok(()))) } @@ -1282,6 +1315,7 @@ impl Surface { where F: Fn(i32, i32, &mut [u8]) + Sync, { + self.note_mutation(); self.try_prepare_rows(r, |tiles, format, default_pixel| { fill_tiles(tiles, r, format, default_pixel, &fill, &|| ctl.check().map_err(RowWriteError::Cancelled)) }) @@ -1347,7 +1381,8 @@ impl Surface { /// `content` must hold every pixel that isn't the default one (`content_bounds`, say): only /// tiles it reaches are kept. pub fn translated(&self, dx: i32, dy: i32, content: Rect) -> Surface { - let mut out = Surface { format: self.format, default_pixel: self.default_pixel.clone(), tiles: BTreeMap::new() }; + let mut out = + Surface { generation: fresh_surface_generation(), format: self.format, default_pixel: self.default_pixel.clone(), tiles: BTreeMap::new() }; let sources = || self.tiles.iter().filter(move |(c, _)| !c.rect().intersect(&content).is_empty()); if dx % TILE_SIZE == 0 && dy % TILE_SIZE == 0 { let (tx, ty) = (dx / TILE_SIZE, dy / TILE_SIZE); @@ -1375,6 +1410,7 @@ impl Surface { /// Applies `f` to every colour sample (not alpha), including the default pixel: a tone-curve /// change such as linearising when a document becomes 32-bit. pub fn map_color(&mut self, f: impl Fn(f32) -> f32) { + self.note_mutation(); let format = self.format; let color = format.mode.color_channels(); let n = format.channels(); diff --git a/crates/raster/src/shift.rs b/crates/raster/src/shift.rs index 6c3a49ffab..c75ebf3401 100644 --- a/crates/raster/src/shift.rs +++ b/crates/raster/src/shift.rs @@ -221,7 +221,8 @@ impl TranslateSteps { let builder = ShiftBuilder::new(&src, dx, dy, content); let tiles: Vec<(TileCoord, Arc)> = if whole_tiles { Vec::new() } else { ShiftBuilder::sources(&src, content).map(|(c, t)| (*c, Arc::clone(t))).collect() }; - let out = Surface { format: src.format, default_pixel: src.default_pixel.clone(), tiles: Default::default() }; + let out = + Surface { generation: super::fresh_surface_generation(), format: src.format, default_pixel: src.default_pixel.clone(), tiles: Default::default() }; Self { sources: tiles.len(), scan: tiles.into_iter(), @@ -274,7 +275,12 @@ impl TranslateSteps { } else { return Some(std::mem::replace( &mut self.out, - Surface { format: self.src.format, default_pixel: self.src.default_pixel.clone(), tiles: Default::default() }, + Surface { + generation: super::fresh_surface_generation(), + format: self.src.format, + default_pixel: self.src.default_pixel.clone(), + tiles: Default::default(), + }, )); } if !more() { diff --git a/crates/raster/src/tests.rs b/crates/raster/src/tests.rs index 6c9427d963..db6a3ca0ff 100644 --- a/crates/raster/src/tests.rs +++ b/crates/raster/src/tests.rs @@ -1341,3 +1341,24 @@ fn benchmark_u16_rgba_reads() { } } } + +#[test] +fn generations_follow_mutations_and_remain_shared_by_unmodified_clones() { + let mut original = Surface::new(PixelFormat::RGBA8); + let initial = original.generation(); + let copy = original.clone(); + assert_eq!(copy.generation(), initial); + let region = Rect::new(0, 0, 1, 1); + let _ = original.read_region(region); + assert_eq!(original.generation(), initial); + original.write_pixel(0, 0, &[1.0, 0.0, 0.0, 1.0]); + assert_ne!(original.generation(), initial); + assert_eq!(copy.generation(), initial); + assert_ne!(original.read_region(region), copy.read_region(region)); + let changed = original.generation(); + original.map_color(|v| v * 0.5); + assert_ne!(original.generation(), changed); + let mapped = original.generation(); + original.prune(); + assert_ne!(original.generation(), mapped); +} From 5e6b4c0945d12fbb4aa2f8605cd2eb30e7ab0b30 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:35:06 +0100 Subject: [PATCH 47/85] Use typed blend modes in Layers menu --- crates/color/src/blend.rs | 61 ++++++++++++++++++++++++ crates/ui-egui/src/panels/layers_tree.rs | 18 +++---- 2 files changed, 71 insertions(+), 8 deletions(-) diff --git a/crates/color/src/blend.rs b/crates/color/src/blend.rs index d6149feafb..196a0dcafd 100644 --- a/crates/color/src/blend.rs +++ b/crates/color/src/blend.rs @@ -47,6 +47,52 @@ pub enum BlendMode { } impl BlendMode { + /// Stable key used by the Layers panel. + pub fn key(self) -> &'static str { + match self { + Self::PassThrough => "passthrough", + Self::Normal => "normal", + Self::Dissolve => "dissolve", + Self::Darken => "darken", + Self::Multiply => "multiply", + Self::ColorBurn => "colorburn", + Self::LinearBurn => "linearburn", + Self::DarkerColor => "darkercolor", + Self::Lighten => "lighten", + Self::Screen => "screen", + Self::ColorDodge => "colordodge", + Self::LinearDodge => "lineardodgeadd", + Self::LighterColor => "lightercolor", + Self::Overlay => "overlay", + Self::SoftLight => "softlight", + Self::HardLight => "hardlight", + Self::VividLight => "vividlight", + Self::LinearLight => "linearlight", + Self::PinLight => "pinlight", + Self::HardMix => "hardmix", + Self::Difference => "difference", + Self::Exclusion => "exclusion", + Self::Subtract => "subtract", + Self::Divide => "divide", + Self::Hue => "hue", + Self::Saturation => "saturation", + Self::Color => "color", + Self::Luminosity => "luminosity", + Self::Reflect => "reflect", + Self::Glow => "glow", + Self::Negation => "negation", + Self::Xor => "xor", + Self::PaintNetColorBurn => "colorburnpaint.net", + Self::PaintNetColorDodge => "colordodgepaint.net", + } + } + + /// Resolve a canonical Layers panel key. + pub fn from_key(key: &str) -> Option { + static MODES: std::sync::OnceLock> = std::sync::OnceLock::new(); + MODES.get_or_init(|| std::iter::once(Self::PassThrough).chain(Self::layer_modes()).map(|mode| (mode.key(), mode)).collect()).get(key).copied() + } + /// Paint.NET modes without an exact Photoshop equivalent. pub const PAINT_NET_MODES: [BlendMode; 6] = [Self::Reflect, Self::Glow, Self::Negation, Self::Xor, Self::PaintNetColorBurn, Self::PaintNetColorDodge]; @@ -623,3 +669,18 @@ pub fn composite_atop(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opa #[cfg(test)] mod tests; + +#[cfg(test)] +mod key_tests { + use super::BlendMode; + + #[test] + fn canonical_keys_match_legacy_panel_names_and_round_trip() { + for mode in std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()) { + let old = mode.label().to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], ""); + assert_eq!(mode.key(), old); + assert_eq!(BlendMode::from_key(&old), Some(mode)); + } + assert_eq!(BlendMode::from_key("no-such-mode"), None); + } +} diff --git a/crates/ui-egui/src/panels/layers_tree.rs b/crates/ui-egui/src/panels/layers_tree.rs index adb8c24cf9..8a9643c3c7 100644 --- a/crates/ui-egui/src/panels/layers_tree.rs +++ b/crates/ui-egui/src/panels/layers_tree.rs @@ -28,7 +28,7 @@ use crate::PhotocraftApp; /// The key the panel and the filter use for a blend mode: its label folded as the engine's /// `blend_from_str` reads it ("normal", "lineardodgeadd"). pub(crate) fn blend_key(m: BlendMode) -> String { - m.label().to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], "") + m.key().to_string() } /// The blend mode a panel key names. @@ -382,13 +382,15 @@ impl LayerTree for PhotoLayers<'_> { } fn blend_modes(&self, group: bool, current: &str) -> Vec> { - let current = blend_of(current).unwrap_or(BlendMode::Normal); - let modes: Vec> = - super::layers::blend_options(group, current).into_iter().map(|(m, _)| super::blend_entry(blend_key(m), m)).collect(); - blend_entries(&modes, |e| { - let label = blend_of(&e.key).map_or(e.key.as_str(), |m| tl!(m.label())); - Label::from(label.to_string()) - }) + let current = BlendMode::from_key(current).or_else(|| blend_of(current)).unwrap_or(BlendMode::Normal); + let modes: Vec> = super::layers::blend_options(group, current).into_iter().map(|(m, _)| super::blend_entry(m, m)).collect(); + blend_entries(&modes, |mode| Label::from(tl!(mode.key.label()).to_string())) + .into_iter() + .map(|entry| match entry.value() { + Some(mode) => Entry::new(mode.key().to_string(), entry.label().clone()), + None => Entry::separator(), + }) + .collect() } fn footer(&self) -> LayersFooterState { From 567b88610abffc52bf83098803c637296d207670 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:36:47 +0100 Subject: [PATCH 48/85] Pair tone target test flags --- crates/engine/tests/it/tone_target_picker.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/engine/tests/it/tone_target_picker.rs b/crates/engine/tests/it/tone_target_picker.rs index 16b4ee9cec..9f34868798 100644 --- a/crates/engine/tests/it/tone_target_picker.rs +++ b/crates/engine/tests/it/tone_target_picker.rs @@ -237,9 +237,13 @@ fn gray_tone_records_do_not_leak_from_rgb_channels() { for (target, panel) in [(json!("mask"), ChannelTarget::LayerMask), (json!({"channel":0}), ChannelTarget::Alpha(0)), (json!("quickMask"), ChannelTarget::Composite)] { - for style in ["levels", "points", "pencil"] { - for sampled in [false, true] { - for explicit in [false, true] { + // Each style sees both flags; all four flag pairs occur across the styles. + for (si, style) in ["levels", "points", "pencil"].into_iter().enumerate() { + for (ai, sampled) in [false, true].into_iter().enumerate() { + for (ei, explicit) in [false, true].into_iter().enumerate() { + if (si + ai) % 2 != ei { + continue; + } let mut clean = session(mode, depth); clean.active_mut().unwrap().channel_view.target = panel; clean From 8b68407a61c7c83f9a2a0481552741a8089ee0b5 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:36:50 +0100 Subject: [PATCH 49/85] Reduce blur and selection test fixtures --- crates/algo/src/blur/tests.rs | 6 +++++- crates/algo/src/gallery/tests.rs | 10 +++++++--- crates/algo/src/segment/workflow_tests.rs | 15 ++++++++------- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/crates/algo/src/blur/tests.rs b/crates/algo/src/blur/tests.rs index fd2917cd32..41018d91ae 100644 --- a/crates/algo/src/blur/tests.rs +++ b/crates/algo/src/blur/tests.rs @@ -255,7 +255,11 @@ fn layer_box_blurs_match_direct_convolution_at_any_radius() { SampleType::U16 => 1.0 / 65535.0, _ => 0.0, } + 2e-5; - for p in ¶ms { + // Each format sees both blur modes; each radius is covered across formats. + for (pi, p) in params.iter().enumerate() { + if pi % 2 != i % 2 { + continue; + } let boxes = box_widths(p).expect("a box-pass blur"); let reach: i32 = boxes.iter().map(|w| (w / 2) as i32).sum(); let area = crate::output_area(p, s.content_bounds(), canvas, None); diff --git a/crates/algo/src/gallery/tests.rs b/crates/algo/src/gallery/tests.rs index e822d7a938..0e1967b89c 100644 --- a/crates/algo/src/gallery/tests.rs +++ b/crates/algo/src/gallery/tests.rs @@ -149,9 +149,13 @@ fn iris_depths_models_selection_tiles_and_cancellation() { let mut selection = Surface::new(PixelFormat::GRAY8); selection.fill_rect(bounds, &[0.4]); selection.fill_rect(Rect::new(3, 19, 35, 44), &[1.0]); - for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] { - for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { - for alpha in [false, true] { + // Cover every mode/sample pair and both alpha values for each mode and sample. + for (mi, mode) in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().enumerate() { + for (si, sample) in [SampleType::U8, SampleType::U16, SampleType::F32].into_iter().enumerate() { + for (ai, alpha) in [false, true].into_iter().enumerate() { + if (mi + si) % 2 != ai { + continue; + } let fmt = PixelFormat::new(mode, sample, alpha); let mut surface = Surface::new(fmt); surface.write_region(bounds, &image(bounds, fmt.channels()).data); diff --git a/crates/algo/src/segment/workflow_tests.rs b/crates/algo/src/segment/workflow_tests.rs index 96c6caeb8f..3ab7d5ea83 100644 --- a/crates/algo/src/segment/workflow_tests.rs +++ b/crates/algo/src/segment/workflow_tests.rs @@ -82,16 +82,16 @@ fn quick_selection_workflow_release_comparison() { #[test] fn quick_selection_preserves_textures_low_contrast_and_thin_features() { - let (w, h) = (360usize, 280usize); + let (w, h) = (180usize, 140usize); let canvas = Rect::new(0, 0, w as i32, h as i32); for kind in 0..6 { let img = RgbImage::from_fn(w, h, |x, y| { let inside = if kind == 2 { - (x as f32 - 180.0).hypot(y as f32 - 140.0) < 72.0 + (x as f32 - 90.0).hypot(y as f32 - 70.0) < 36.0 } else if kind == 3 { - y > 130 && y < 145 + y > 65 && y < 73 } else { - x > 60 && x < 300 && y > 60 && y < 220 + x > 30 && x < 150 && y > 30 && y < 110 }; let t = ((x * 23 + y * 19) % 101) as f32 / 100.0; match kind { @@ -102,7 +102,7 @@ fn quick_selection_preserves_textures_low_contrast_and_thin_features() { [0.4, 0.3 + t * 0.1, 0.2] } } - 1 => [0.4 + x as f32 / 1800.0, 0.3 + y as f32 / 1400.0, t * 0.02], + 1 => [0.4 + x as f32 / 900.0, 0.3 + y as f32 / 700.0, t * 0.02], 4 => [t, ((x * 7 + y * 31) % 79) as f32 / 78.0, 0.4], 5 => [0.4; 3], _ => { @@ -115,8 +115,9 @@ fn quick_selection_preserves_textures_low_contrast_and_thin_features() { } }); let sampler = ImageSampler { img: &img, origin: (0, 0) }; - for (points, brush) in [(vec![(180.0, 140.0)], 12.0), (vec![(90.0, 140.0), (270.0, 140.0)], 40.0), (vec![(1.0, 1.0), (160.0, 130.0)], 64.0)] { - for direct_px in [10_000, 300_000] { + for (points, brush) in [(vec![(90.0, 70.0)], 6.0), (vec![(45.0, 70.0), (135.0, 70.0)], 20.0), (vec![(1.0, 1.0), (80.0, 65.0)], 32.0)] { + // Scale the coarse-cut threshold with the canvas area; the second case stays direct. + for direct_px in [2_500, 300_000] { let tune = quick::Tuning { direct_px, ..quick::Tuning::default() }; let old = quick::quick_select_using::(&sampler, canvas, &points, brush, &tune); let new = quick::quick_select_using::(&sampler, canvas, &points, brush, &tune); From 6b207c5b55e9af7426e26c8e9017b46ce4bed00a Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:41:16 +0100 Subject: [PATCH 50/85] Share built-in brush presets across sessions --- crates/engine/examples/abr_memory.rs | 2 +- crates/engine/src/cmd/brush_cmds.rs | 11 ++++++---- crates/engine/src/cmd/brush_key_cmds.rs | 4 ++-- crates/engine/src/cmd/brush_preset_cmds.rs | 20 +++++++++---------- .../engine/src/cmd/brush_preset_cmds/tests.rs | 12 +++++------ crates/engine/src/cmd/edit_menu_cmds.rs | 4 ++-- .../engine/src/cmd/edit_menu_cmds/presets.rs | 4 ++-- crates/engine/src/cmd/preset_import_cmds.rs | 8 ++++---- crates/engine/src/doc_state.rs | 4 ++-- crates/engine/src/preset_store.rs | 6 +++--- crates/engine/src/preset_store/tests.rs | 16 +++++++-------- crates/engine/src/tests.rs | 13 ++++++++++++ crates/paint/src/presets.rs | 6 ++++++ .../src/dialogs/preset_group_prompt/tests.rs | 4 ++-- .../ui-egui/src/panels/brush_panel/tests.rs | 8 ++++---- crates/ui-egui/src/preset_files_ui.rs | 2 +- 16 files changed, 73 insertions(+), 51 deletions(-) diff --git a/crates/engine/examples/abr_memory.rs b/crates/engine/examples/abr_memory.rs index 9cec8ec1de..71c1460664 100644 --- a/crates/engine/examples/abr_memory.rs +++ b/crates/engine/examples/abr_memory.rs @@ -52,7 +52,7 @@ fn library_tip_bytes(s: &Session) -> (usize, u64, u64) { previews += g.data.len() as u64 * 2; } }; - for p in &s.tools.presets { + for p in s.tools.presets.iter() { let b = &p.brush; for t in [&b.tip, &b.dual_brush.tip] { match t { diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index f17b5b28b4..8b25c1d3c6 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -980,9 +980,9 @@ fn name_param(p: &Value, cmd: &str) -> Result { /// Replace the preset of that name, or append it at the end of the list. fn upsert(s: &mut Session, preset: BrushPreset) { - match s.tools.presets.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&preset.name)) { + match std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().find(|x| x.name.eq_ignore_ascii_case(&preset.name)) { Some(x) => *x = preset, - None => s.tools.presets.push(preset), + None => std::sync::Arc::make_mut(&mut s.tools.presets).push(preset), } s.brush_presets_changed(); } @@ -1010,7 +1010,7 @@ fn presets_delete(s: &mut Session, p: &Value) -> Result { let cmd = "brush.presets.delete"; let name = name_param(p, cmd)?; let before = s.tools.presets.len(); - s.tools.presets.retain(|x| !x.name.eq_ignore_ascii_case(&name)); + std::sync::Arc::make_mut(&mut s.tools.presets).retain(|x| !x.name.eq_ignore_ascii_case(&name)); if s.tools.presets.len() == before { return Err(bad(cmd, format!("no brush preset named `{name}`"))); } @@ -1043,7 +1043,10 @@ fn presets_update(s: &mut Session, p: &Value) -> Result { Some(patch) => merge_brush(&s.tools.brush, patch, cmd)?, None => s.tools.brush.clone(), }; - let pr = s.tools.presets.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)).ok_or_else(|| bad(cmd, format!("no brush preset named `{name}`")))?; + let pr = std::sync::Arc::make_mut(&mut s.tools.presets) + .iter_mut() + .find(|x| x.name.eq_ignore_ascii_case(&name)) + .ok_or_else(|| bad(cmd, format!("no brush preset named `{name}`")))?; pr.brush = brush; pr.builtin = false; let (name, group) = (pr.name.clone(), pr.group.clone()); diff --git a/crates/engine/src/cmd/brush_key_cmds.rs b/crates/engine/src/cmd/brush_key_cmds.rs index 0cb6f93ff0..a76f15b868 100644 --- a/crates/engine/src/cmd/brush_key_cmds.rs +++ b/crates/engine/src/cmd/brush_key_cmds.rs @@ -263,7 +263,7 @@ mod tests { #[test] fn previous_and_next_brush_walk_the_presets_and_wrap() { let mut s = Session::new(); - s.tools.presets = vec![preset("One", "", &[], 11.0), preset("Two", "", &[], 22.0), preset("Three", "", &[], 33.0)]; + s.tools.presets = std::sync::Arc::new(vec![preset("One", "", &[], 11.0), preset("Two", "", &[], 22.0), preset("Three", "", &[], 33.0)]); s.tools.current_preset = None; let picked = |s: &Session| (s.tools.current_preset.clone().unwrap_or_default(), s.tools.brush.size); s.execute("tools.nextBrush", Value::Null).unwrap(); @@ -284,7 +284,7 @@ mod tests { [Some(","), Some("."), Some("Shift+,"), Some("Shift+.")] ); // No presets: an error, and the brush and the current preset stay as they were. - s.tools.presets.clear(); + std::sync::Arc::make_mut(&mut s.tools.presets).clear(); let (brush, current) = (s.tools.brush.clone(), s.tools.current_preset.clone()); for id in ["tools.previousBrush", "tools.nextBrush", "tools.firstBrush", "tools.lastBrush"] { assert!(s.execute(id, Value::Null).is_err(), "{id}"); diff --git a/crates/engine/src/cmd/brush_preset_cmds.rs b/crates/engine/src/cmd/brush_preset_cmds.rs index 6cfe6365c7..34cd2fbb4a 100644 --- a/crates/engine/src/cmd/brush_preset_cmds.rs +++ b/crates/engine/src/cmd/brush_preset_cmds.rs @@ -153,7 +153,7 @@ fn move_preset(s: &mut Session, p: &Value) -> Result { }; let folder = folder_param(p, cmd)?; let group = group_param(p, "group", cmd)?; - let lib = &mut s.tools.presets; + let lib = std::sync::Arc::make_mut(&mut s.tools.presets); let (Some(moving), before_pr) = (lib.get(i), before.and_then(|b| lib.get(b))) else { return Err(bad(cmd, "no such preset")); }; @@ -233,7 +233,7 @@ fn move_folder(s: &mut Session, p: &Value, g: String, f: Vec, cmd: &str) None | Some(Value::Null) => None, Some(v) => Some(v.as_u64().ok_or_else(|| bad(cmd, "`index` must be a non-negative integer"))?), }; - let lib = std::mem::take(&mut s.tools.presets); + let lib = std::mem::take(std::sync::Arc::make_mut(&mut s.tools.presets)); // Where the block sits among the other presets (its place when nothing else is in the parent). let start = lib.iter().position(|x| in_folder(x, &g, &f)).unwrap_or(0); let (block, mut rest): (Vec, Vec) = lib.into_iter().partition(|x| in_folder(x, &g, &f)); @@ -252,7 +252,7 @@ fn move_folder(s: &mut Session, p: &Value, g: String, f: Vec, cmd: &str) let tail = rest.split_off(pos.min(rest.len())); rest.extend(block); rest.extend(tail); - s.tools.presets = rest; + s.tools.presets = std::sync::Arc::new(rest); s.brush_presets_changed(); let at = subfolder_order(&s.tools.presets, &g, parent).iter().position(|x| x == leaf).unwrap_or(0); Ok(json!({ "group": g, "folder": f, "index": at })) @@ -332,7 +332,7 @@ fn move_into(s: &mut Session, p: &Value, g: String, f: Vec, dest: Dest, if deepest > MAX_FOLDER_DEPTH { return Err(bad(cmd, format!("folders can be nested at most {MAX_FOLDER_DEPTH} deep"))); } - let lib = std::mem::take(&mut s.tools.presets); + let lib = std::mem::take(std::sync::Arc::make_mut(&mut s.tools.presets)); let (mut block, mut rest): (Vec, Vec) = lib.into_iter().partition(|x| in_folder(x, &g, &f)); for x in &mut block { let tail = rest_of(x); @@ -352,7 +352,7 @@ fn move_into(s: &mut Session, p: &Value, g: String, f: Vec, dest: Dest, let tail = rest.split_off(pos.unwrap_or(rest.len()).min(rest.len())); rest.extend(block); rest.extend(tail); - s.tools.presets = rest; + s.tools.presets = std::sync::Arc::new(rest); s.brush_presets_changed(); let folder = new_prefix.get(..new_prefix.len().saturating_sub(1)).unwrap_or_default(); let at = match &dest { @@ -382,7 +382,7 @@ fn move_group(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => None, Some(v) => Some(v.as_u64().ok_or_else(|| bad(cmd, "`index` must be a non-negative integer"))?), }; - let lib = std::mem::take(&mut s.tools.presets); + let lib = std::mem::take(std::sync::Arc::make_mut(&mut s.tools.presets)); let (block, mut rest): (Vec, Vec) = lib.into_iter().partition(|x| x.group == g); let order = group_order(&rest); let first = |name: &str, rest: &[BrushPreset]| rest.iter().position(|x| x.group == name).unwrap_or(rest.len()); @@ -394,7 +394,7 @@ fn move_group(s: &mut Session, p: &Value) -> Result { let tail = rest.split_off(pos.min(rest.len())); rest.extend(block); rest.extend(tail); - s.tools.presets = rest; + s.tools.presets = std::sync::Arc::new(rest); s.brush_presets_changed(); let at = group_order(&s.tools.presets).iter().position(|x| *x == g).unwrap_or(0); Ok(json!({ "group": g, "index": at })) @@ -410,7 +410,7 @@ fn rename_group(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, format!("a folder named `{new}` already exists there"))); } let depth = parent.len(); - for x in s.tools.presets.iter_mut().filter(|x| in_folder(x, &g, &f)) { + for x in std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().filter(|x| in_folder(x, &g, &f)) { if let Some(n) = x.folder.get_mut(depth) { n.clone_from(&new); } @@ -426,7 +426,7 @@ fn rename_group(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, format!("a group named `{new}` already exists"))); } if new != g { - for x in s.tools.presets.iter_mut().filter(|x| x.group == g) { + for x in std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().filter(|x| x.group == g) { x.group = new.clone(); x.builtin = false; } @@ -439,7 +439,7 @@ fn delete_group(s: &mut Session, p: &Value) -> Result { let cmd = "brush.presets.deleteGroup"; let (g, f) = target_folder(s, p, cmd)?; let before = s.tools.presets.len(); - s.tools.presets.retain(|x| !in_folder(x, &g, &f)); + std::sync::Arc::make_mut(&mut s.tools.presets).retain(|x| !in_folder(x, &g, &f)); if s.tools.current_preset.as_ref().is_some_and(|c| !s.tools.presets.iter().any(|x| x.name.eq_ignore_ascii_case(c))) { s.tools.current_preset = None; s.tools.brush_changed(); diff --git a/crates/engine/src/cmd/brush_preset_cmds/tests.rs b/crates/engine/src/cmd/brush_preset_cmds/tests.rs index eeed131bc7..5bb2b6698d 100644 --- a/crates/engine/src/cmd/brush_preset_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_preset_cmds/tests.rs @@ -7,7 +7,7 @@ fn names(s: &Session, g: &str) -> Vec { fn with_groups() -> Session { let mut s = Session::new(); for (n, g) in [("A1", "Alpha"), ("A2", "Alpha"), ("A3", "Alpha"), ("B1", "Beta"), ("B2", "Beta")] { - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: n.into(), brush: Default::default(), builtin: false, @@ -119,7 +119,7 @@ fn with_folders() -> Session { let mut s = Session::new(); for (n, f) in [("S0", &[][..]), ("I1", &["Ink"][..]), ("F1", &["Ink", "Fine"][..]), ("I2", &["Ink"][..]), ("D1", &["Dry"][..])] { let folder = f.iter().map(|x| x.to_string()).collect(); - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: n.into(), brush: Default::default(), builtin: false, @@ -226,7 +226,7 @@ fn with_two_groups() -> Session { let mut s = with_folders(); for (n, f) in [("O1", &[][..]), ("B1", &["Box"][..])] { let folder = f.iter().map(|x| x.to_string()).collect(); - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: n.into(), brush: Default::default(), builtin: false, @@ -266,7 +266,7 @@ fn bad_moves_into_folders_fail_without_changes() { let mut s = with_two_groups(); // A chain 31 deep under Set/Deep. let deep: Vec = std::iter::once("Deep".to_string()).chain((0..30).map(|i| format!("d{i}"))).collect(); - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: "Z".into(), brush: Default::default(), builtin: false, @@ -274,7 +274,7 @@ fn bad_moves_into_folders_fail_without_changes() { folder: deep.clone(), captures: Default::default(), }); - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: "Y".into(), brush: Default::default(), builtin: false, @@ -314,7 +314,7 @@ fn bad_moves_into_folders_fail_without_changes() { s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink", "Fine"], "into": {"group": "Set"}})).unwrap(); assert_eq!(folder_of(&s, "F1"), ["Fine"]); // An ungrouped preset's group can't move. - s.tools.presets.push(BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(BrushPreset { name: "U".into(), brush: Default::default(), builtin: false, diff --git a/crates/engine/src/cmd/edit_menu_cmds.rs b/crates/engine/src/cmd/edit_menu_cmds.rs index fab273a9a6..b9f32b9df0 100644 --- a/crates/engine/src/cmd/edit_menu_cmds.rs +++ b/crates/engine/src/cmd/edit_menu_cmds.rs @@ -314,9 +314,9 @@ fn export_import(s: &mut Session, p: &Value) -> Result { // absurd tree). b.folder.retain(|f| !f.trim().is_empty()); b.folder.truncate(crate::brush_preset_cmds::MAX_FOLDER_DEPTH); - match s.tools.presets.iter_mut().find(|x| x.name == b.name) { + match std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().find(|x| x.name == b.name) { Some(x) => *x = b, - None => s.tools.presets.push(b), + None => std::sync::Arc::make_mut(&mut s.tools.presets).push(b), } nb += 1; } diff --git a/crates/engine/src/cmd/edit_menu_cmds/presets.rs b/crates/engine/src/cmd/edit_menu_cmds/presets.rs index abc3a61172..9a73f086db 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/presets.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/presets.rs @@ -114,7 +114,7 @@ pub(super) fn preset_manager(s: &mut Session, p: &Value) -> Result { } "delete" => match kind.as_str() { "brushes" => { - let gone = s.tools.presets.remove(i); + let gone = std::sync::Arc::make_mut(&mut s.tools.presets).remove(i); crate::brush_cmds::forget_deleted_preset(s, &gone.name); } "patterns" => drop(s.patterns.items.remove(i)), @@ -123,7 +123,7 @@ pub(super) fn preset_manager(s: &mut Session, p: &Value) -> Result { "move" => { let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "missing `to`"))? as usize; match kind.as_str() { - "brushes" => crate::move_item(&mut s.tools.presets, i, to), + "brushes" => crate::move_item(std::sync::Arc::make_mut(&mut s.tools.presets), i, to), "patterns" => crate::move_item(&mut s.patterns.items, i, to), _ => crate::move_item(&mut s.edit_state.custom_shapes, i, to), }; diff --git a/crates/engine/src/cmd/preset_import_cmds.rs b/crates/engine/src/cmd/preset_import_cmds.rs index 8b866c3f89..62c786e848 100644 --- a/crates/engine/src/cmd/preset_import_cmds.rs +++ b/crates/engine/src/cmd/preset_import_cmds.rs @@ -155,7 +155,7 @@ fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io // in Photoshop, unless `replace` asks to drop that group's own presets first: the group name // is only the file name, and the library is outside document history (#10640). let group = if p.get("replace").and_then(Value::as_bool).unwrap_or(false) { - s.tools.presets.retain(|x| x.builtin || x.group != group); + std::sync::Arc::make_mut(&mut s.tools.presets).retain(|x| x.builtin || x.group != group); group } else { // One pass over the library, not one per numbered candidate. @@ -168,7 +168,7 @@ fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io preset.group.clone_from(&group); preset.name = taken.unique(&preset.name); names.push(preset.name.clone()); - s.tools.presets.push(preset); + std::sync::Arc::make_mut(&mut s.tools.presets).push(preset); } s.brush_presets_changed(); if p.get("select").and_then(Value::as_bool).unwrap_or(false) @@ -262,7 +262,7 @@ fn import_image(s: &mut Session, p: &Value) -> Result { let (v, w, h) = image_paint(&doc, cmd)?; let (brush, tw, th) = crate::brush_cmds::sampled_brush(cmd, &v, w, h)?; let name = UniqueNames::new(s.tools.presets.iter().map(|x| x.name.as_str())).unique(&name); - s.tools.presets.push(photocraft_paint::BrushPreset { + std::sync::Arc::make_mut(&mut s.tools.presets).push(photocraft_paint::BrushPreset { name: name.clone(), brush: brush.clone(), builtin: false, @@ -541,7 +541,7 @@ mod tests { // The user's own brush moved into the group. let mut own = s.tools.presets.iter().find(|p| p.group == "Kit").unwrap().clone(); own.name = "My Ink".into(); - s.tools.presets.push(own); + std::sync::Arc::make_mut(&mut s.tools.presets).push(own); let r = s.execute("brush.presets.importAbr", json!({"data": data, "group": "Kit"})).unwrap(); assert_eq!(r["group"], "Kit (2)"); let in_group = |s: &Session, g: &str| s.tools.presets.iter().filter(|p| p.group == g).count(); diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 17ac800c97..662d39ecb1 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -183,7 +183,7 @@ pub struct ToolState { pub background: [f32; 4], pub brush: photocraft_paint::BrushSettings, /// Brush presets (built-ins plus user presets; see `brush.presets.*`). - pub presets: Vec, + pub presets: Arc>, /// Bumped whenever `presets` changes ([`Session::brush_presets_changed`]); the preset store /// syncs when it moves. pub presets_rev: u64, @@ -284,7 +284,7 @@ impl Default for ToolState { smoothing: photocraft_paint::brush::Smoothing { amount: 0.1, ..Default::default() }, ..Default::default() }, - presets: photocraft_paint::presets::builtin(), + presets: photocraft_paint::presets::builtin_shared(), presets_rev: 0, mixer: Default::default(), brush_gesture: None, diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs index c654de811f..b44a2abdae 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -1103,7 +1103,7 @@ impl PresetStore { fn builtin_names() -> &'static [String] { static NAMES: std::sync::OnceLock> = std::sync::OnceLock::new(); - NAMES.get_or_init(|| photocraft_paint::presets::builtin().into_iter().map(|p| p.name).collect()) + NAMES.get_or_init(|| photocraft_paint::presets::builtin_shared().iter().map(|p| p.name.clone()).collect()) } impl Session { @@ -1141,7 +1141,7 @@ impl Session { } } } - let lib = &mut self.tools.presets; + let lib = std::sync::Arc::make_mut(&mut self.tools.presets); lib.retain(|p| !(p.builtin && hidden_builtins.iter().any(|h| h.eq_ignore_ascii_case(&p.name)))); for p in presets { match lib.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&p.name)) { @@ -1204,7 +1204,7 @@ impl Session { let rev = self.tools.presets_rev; if let Some(st) = self.preset_store.as_mut() { if st.synced_rev != Some(rev) { - st.sync(&mut self.tools.presets); + st.sync(std::sync::Arc::make_mut(&mut self.tools.presets)); st.synced_rev = Some(rev); if link_stored_tips(st, &mut self.tools.brush) { // An embedded tip became a store reference: what the last-brush diff --git a/crates/engine/src/preset_store/tests.rs b/crates/engine/src/preset_store/tests.rs index 368d74e155..3e601f2601 100644 --- a/crates/engine/src/preset_store/tests.rs +++ b/crates/engine/src/preset_store/tests.rs @@ -119,7 +119,7 @@ fn group_with_sampled_8_and_16_bit_tips_round_trips() { let b = sampled("Sixteen", "Inks", tip16(50, 70, 2)); let mut c = sampled("Shared tip", "Other", tip8(64, 48, 1)); c.brush.size = 9.0; - s.tools.presets.extend([a, b, c]); + std::sync::Arc::make_mut(&mut s.tools.presets).extend([a, b, c]); s.brush_presets_changed(); s.sync_preset_store(); let files = dir.files(); @@ -243,7 +243,7 @@ fn startup_with_many_groups_loads_them_all() { let (mut s, _) = session(&dir); for g in 0..25 { for i in 0..4 { - s.tools.presets.push(sampled(&format!("P{g}-{i}"), &format!("Group {g}"), tip8(16 + i, 16, g))); + std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled(&format!("P{g}-{i}"), &format!("Group {g}"), tip8(16 + i, 16, g))); } } s.brush_presets_changed(); @@ -267,7 +267,7 @@ fn reordering_presets_and_groups_persists() { let (mut s, _) = session(&dir); for (n, g) in [("Ink 1", "Inks"), ("Ink 2", "Inks"), ("Wash", "Washes")] { s.execute("brush.presets.save", json!({"name": n})).unwrap(); - s.tools.presets.iter_mut().find(|p| p.name == n).unwrap().group = g.into(); + std::sync::Arc::make_mut(&mut s.tools.presets).iter_mut().find(|p| p.name == n).unwrap().group = g.into(); } s.brush_presets_changed(); s.sync_preset_store(); @@ -299,8 +299,8 @@ fn reordering_presets_and_groups_persists() { fn corrupt_and_oversized_files_are_skipped_with_a_warning() { let dir = TempDir::new("corrupt"); let (mut s, _) = session(&dir); - s.tools.presets.push(sampled("Good", "Fine", tip8(8, 8, 1))); - s.tools.presets.push(sampled("Lost", "Broken tip", tip16(9, 9, 2))); + std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled("Good", "Fine", tip8(8, 8, 1))); + std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled("Lost", "Broken tip", tip16(9, 9, 2))); s.brush_presets_changed(); s.sync_preset_store(); let be = DirBackend::new(&dir.0); @@ -370,7 +370,7 @@ fn bench_load_500_sampled_presets() { // A mix of 8-bit (most .abr tips) and 16-bit tips, 64..319 px. let side = 64 + (i * 37) % 256; let t = if i % 4 == 0 { tip16(side, side, i) } else { tip8(side, side, i) }; - s.tools.presets.push(sampled(&format!("Brush {i}"), &format!("Set {}", i / 50), t)); + std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled(&format!("Brush {i}"), &format!("Set {}", i / 50), t)); } s.brush_presets_changed(); let t0 = std::time::Instant::now(); @@ -411,7 +411,7 @@ fn library(n: u32, side: u32) -> (Session, MemBackend) { let mut s = Session::new(); s.attach_preset_store(open(Box::new(mem.clone()))); for i in 0..n { - s.tools.presets.push(sampled(&format!("Big {i}"), "Big Set", tip8(side, side, i))); + std::sync::Arc::make_mut(&mut s.tools.presets).push(sampled(&format!("Big {i}"), "Big Set", tip8(side, side, i))); } s.brush_presets_changed(); s.sync_preset_store(); @@ -519,7 +519,7 @@ fn missing_corrupt_or_unknown_tips_fail_when_used_without_panicking() { let k0 = key(&t, "Big 0"); mem.remove(&tip_file(&k0)).unwrap(); t.execute("tools.setBrush", json!({"preset": "Hard Round"})).unwrap(); - let broken = t.tools.presets.iter_mut().find(|p| p.name == "Big 0").unwrap(); + let broken = std::sync::Arc::make_mut(&mut t.tools.presets).iter_mut().find(|p| p.name == "Big 0").unwrap(); broken.captures.color = true; broken.brush.color = [1.0, 0.0, 0.0, 1.0]; t.tools.foreground = [0.0, 0.0, 1.0, 1.0]; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b15add018c..2e6b02aa32 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2063,3 +2063,16 @@ fn the_active_layer_marker_advances_for_a_new_document_and_not_for_a_same_layer_ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); assert!(s.active_layer_changes() > before, "a new active document advances the marker"); } + +#[test] +fn sessions_share_builtin_brushes_until_edited() { + let mut first = Session::new(); + let second = Session::new(); + assert!(std::sync::Arc::ptr_eq(&first.tools.presets, &second.tools.presets)); + let count = second.tools.presets.len(); + first.execute("brush.presets.save", serde_json::json!({"name": "Session-only test brush"})).unwrap(); + assert_eq!(second.tools.presets.len(), count); + assert!(second.tools.presets.iter().all(|preset| preset.name != "Session-only test brush")); + assert!(first.tools.presets.iter().any(|preset| preset.name == "Session-only test brush")); + assert!(!std::sync::Arc::ptr_eq(&first.tools.presets, &second.tools.presets)); +} diff --git a/crates/paint/src/presets.rs b/crates/paint/src/presets.rs index e40902a78f..0107dfdcfe 100644 --- a/crates/paint/src/presets.rs +++ b/crates/paint/src/presets.rs @@ -448,6 +448,12 @@ pub fn builtin() -> Vec { v } +/// The built-in set shared by new sessions until one is edited. +pub fn builtin_shared() -> std::sync::Arc> { + static BUILTIN: std::sync::OnceLock>> = std::sync::OnceLock::new(); + BUILTIN.get_or_init(|| std::sync::Arc::new(builtin())).clone() +} + /// Find a preset by name (case-insensitive). pub fn find<'a>(presets: &'a [BrushPreset], name: &str) -> Option<&'a BrushPreset> { presets.iter().find(|p| p.name.eq_ignore_ascii_case(name)) diff --git a/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs b/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs index 96de48ce66..160238e8a4 100644 --- a/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs +++ b/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs @@ -38,7 +38,7 @@ fn group(app: &PhotocraftApp, kind: Kind, name: &str) -> Value { } fn library(app: &PhotocraftApp) -> Value { - json!({"brushes": app.session.tools.presets, "gradients": app.session.presets.gradients, "selectedBrush": app.session.tools.brush}) + json!({"brushes": app.session.tools.presets.as_ref(), "gradients": app.session.presets.gradients, "selectedBrush": app.session.tools.brush}) } impl Fixture { @@ -74,7 +74,7 @@ impl Fixture { match kind { Kind::Brushes => { assert_eq!(original.as_array().unwrap().len(), 2); - app.session.tools.presets.iter_mut().find(|p| p.group == stem).unwrap().brush.size = 77.0; + std::sync::Arc::make_mut(&mut app.session.tools.presets).iter_mut().find(|p| p.group == stem).unwrap().brush.size = 77.0; } Kind::Gradients => { assert_eq!(original[0]["items"].as_array().unwrap().len(), 2); diff --git a/crates/ui-egui/src/panels/brush_panel/tests.rs b/crates/ui-egui/src/panels/brush_panel/tests.rs index 6d52d98708..57264f5603 100644 --- a/crates/ui-egui/src/panels/brush_panel/tests.rs +++ b/crates/ui-egui/src/panels/brush_panel/tests.rs @@ -487,14 +487,14 @@ fn preset_rows_nest_presets_in_panel_order() { let max = photocraft_engine::brush_preset_cmds::MAX_FOLDER_DEPTH; let deep: Vec<&str> = vec!["d"; max + 5]; let mut app = app(); - app.session.tools.presets = vec![ + app.session.tools.presets = std::sync::Arc::new(vec![ kit("Top", "Kit", &[]), kit("Pen", "Kit", &["Inks"]), kit("Chalk", "Kit", &["Dry"]), kit("Nib", "Kit", &["Inks", "Fine"]), kit("Quill", "Kit", &["Inks"]), kit("Deep", "Kit", &deep), - ]; + ]); let out: Vec = rows_of(app, PresetView::List) .iter() .map(|r| match r.count { @@ -509,7 +509,7 @@ fn preset_rows_nest_presets_in_panel_order() { fn fixture() -> Box { let mut app = app(); - app.session.tools.presets = vec![ + app.session.tools.presets = std::sync::Arc::new(vec![ kit("A1", "Alpha", &[]), kit("A2", "Alpha", &[]), kit("A3", "Alpha", &[]), @@ -518,7 +518,7 @@ fn fixture() -> Box { kit("Kit Pen", "Kit", &["Inks"]), kit("Kit Nib", "Kit", &["Inks", "Fine"]), kit("Kit Chalk", "Kit", &["Dry"]), - ]; + ]); app } diff --git a/crates/ui-egui/src/preset_files_ui.rs b/crates/ui-egui/src/preset_files_ui.rs index 2b84f9de6d..4d7b9cae8b 100644 --- a/crates/ui-egui/src/preset_files_ui.rs +++ b/crates/ui-egui/src/preset_files_ui.rs @@ -211,7 +211,7 @@ mod tests { assert!(prompt(&app).is_none(), "a new group imports without asking"); assert!(app.ui.status.ends_with("brushes from Kit"), "{}", app.ui.status); // The user edits one of its brushes. - let edited = app.session.tools.presets.iter_mut().find(|p| p.group == "Kit").unwrap(); + let edited = std::sync::Arc::make_mut(&mut app.session.tools.presets).iter_mut().find(|p| p.group == "Kit").unwrap(); edited.brush.size = 77.0; let edited = edited.name.clone(); From 878d5fa717f4058e250a688c2b4719d5b2f4adfb Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:52:11 +0100 Subject: [PATCH 51/85] Pair scalar cell filter cases --- crates/algo/src/pixelate/tests.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/algo/src/pixelate/tests.rs b/crates/algo/src/pixelate/tests.rs index 59a3936e43..a97a9d6f88 100644 --- a/crates/algo/src/pixelate/tests.rs +++ b/crates/algo/src/pixelate/tests.rs @@ -202,14 +202,18 @@ fn cell_filters_match_scalar_models_edges_and_fractional_cells() { // The cell filters see the mode only as a channel count, CMYK's ink direction (`subtractive`) and the native // background, so Lab adds nothing to RGB; cells of 100 and 300 are both past every `out`, and the seed has no // branch (0 and u32::MAX keep the wrapping ends) (#15652). - for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Multichannel] { - for alpha in [false, true] { + for (mi, mode) in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Multichannel].into_iter().enumerate() { + for (ai, alpha) in [false, true].into_iter().enumerate() { let ctx = Ctx { bounds, mode, alpha }; for pattern in 0..5 { for halo in [0, 7] { let src = fixture(bounds.inflate(halo), &ctx, pattern); for out in [bounds, Rect::new(-23, -15, 37, 31), Rect::new(-7, 2, 18, 13)] { - for cell in [2.0, 3.75, 10.0, 300.0] { + // Retain every mode/alpha pair and all four cell sizes for each mode. + for (ci, cell) in [2.0, 3.75, 10.0, 300.0].into_iter().enumerate() { + if ci % 2 != (mi + ai) % 2 { + continue; + } for seed in [0, u32::MAX] { let got = cells::crystallize(&src, out, &ctx, cell, seed).unwrap(); assert_bits(&got, &crystallize_direct(&src, out, &ctx, cell, seed)); From b3f4721c29a8743008437c12b32f5426a09ccc75 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:52:12 +0100 Subject: [PATCH 52/85] Reduce bitmap and color move fixtures --- crates/engine/src/cmd/mode_cmds.rs | 7 ++++++- crates/engine/src/cmd/mode_cmds/tests.rs | 8 ++++---- .../cmd/retouch_cmds/content_aware_move_color_tests.rs | 4 ++-- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index fb8b40f152..20b9aede70 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -600,6 +600,11 @@ fn custom_pattern_map(s: &Session, cmd: &str, p: &Value) -> Result<(Vec, us } fn bitmap(s: &mut Session, p: &Value) -> Result { + bitmap_in_bands(s, p, 0) +} + +/// Convert with the requested compositor band height (zero chooses its normal budget). +fn bitmap_in_bands(s: &mut Session, p: &Value, band_rows: i32) -> Result { const CMD: &str = "image.mode.bitmap"; let d = s.active().ok_or(EngineError::NoDocument)?; let input = f64::from(d.doc.resolution_dpi.max(1.0)); @@ -674,7 +679,7 @@ fn bitmap(s: &mut Session, p: &Value) -> Result { let n = fmt.channels(); let mut out = Surface::new(fmt); let (mut gray, mut data) = (Vec::new(), Vec::new()); - let _ = photocraft_compose::render_bands(doc, doc.bounds(), 0, |band| -> std::result::Result<(), std::convert::Infallible> { + let _ = photocraft_compose::render_bands(doc, doc.bounds(), band_rows, |band| -> std::result::Result<(), std::convert::Infallible> { gray.clear(); gray.extend(band.px.iter().map(|q| { // Over white, as the flattened image. diff --git a/crates/engine/src/cmd/mode_cmds/tests.rs b/crates/engine/src/cmd/mode_cmds/tests.rs index 8164ea3aac..c64e38b09b 100644 --- a/crates/engine/src/cmd/mode_cmds/tests.rs +++ b/crates/engine/src/cmd/mode_cmds/tests.rs @@ -860,10 +860,10 @@ fn bitmap_pixels(d: &Document) -> Vec { #[test] fn bitmap_in_bands_matches_one_full_canvas_conversion() { - // #8477: the composite is converted in bands (32768 px wide: 256 rows each, so 300 rows are - // two). Diffusion carries its error across the band edge, and pattern, halftone and custom + // #8477: 300 rows cross a 256-row compositor band. Diffusion carries its error across the + // band edge, and pattern, halftone and custom // pattern stay anchored to the image's rows: the result equals one full-canvas conversion. - let (w, h) = (32_768u32, 300u32); + let (w, h) = (64u32, 300u32); let mut s = session(w, h, 8, "grayscale"); paint(&mut s, |x, y| { let v = ((x % 509) as f32 / 509.0 * 0.6 + (y as f32 / 300.0) * 0.4).fract(); @@ -888,7 +888,7 @@ fn bitmap_in_bands_matches_one_full_canvas_conversion() { if method == "customPattern" { p["pattern"] = json!("Cells"); } - s.execute("image.mode.bitmap", p.clone()).unwrap(); + bitmap_in_bands(&mut s, &p, 256).unwrap(); let want = match method { "halftone" => { let cell = (before.resolution_dpi / 53.0).max(2.0); diff --git a/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs b/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs index 57e99d3898..8375889a98 100644 --- a/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs @@ -43,9 +43,9 @@ fn checker(x: i32, y: i32) -> Option { } } -/// 800×600. Left half grey, right half green, with the 80×80 checker at (100, 100). +/// 640×460. Grey to the left of x=400, green to the right, with an 80×80 checker at (100, 100). fn green_doc() -> Session { - let mut s = session(800, 600); + let mut s = session(640, 460); paint(&mut s, |x, y| { if let Some(v) = checker(x, y) { [v, v, v] From eb67d8f066309da3b7c4b82dc3de9bbeeb5028af Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:54:07 +0100 Subject: [PATCH 53/85] Cover surface tile mutation generations --- crates/raster/src/tests.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/raster/src/tests.rs b/crates/raster/src/tests.rs index db6a3ca0ff..68d9870b0e 100644 --- a/crates/raster/src/tests.rs +++ b/crates/raster/src/tests.rs @@ -1361,4 +1361,10 @@ fn generations_follow_mutations_and_remain_shared_by_unmodified_clones() { let mapped = original.generation(); original.prune(); assert_ne!(original.generation(), mapped); + let before_tile = original.generation(); + let old_copy = original.clone(); + original.tile_mut(TileCoord { tx: 0, ty: 0 }).bytes_mut()[0] ^= 0xff; + assert_ne!(original.generation(), before_tile); + assert_eq!(old_copy.generation(), before_tile); + assert_ne!(original.read_region(region), old_copy.read_region(region)); } From 475dcbcad17006c1a74a78f5e178cb4a7feac7cb Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 08:58:53 +0100 Subject: [PATCH 54/85] Reduce redundant smart blur offsets --- crates/algo/src/blur2/smart_tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/algo/src/blur2/smart_tests.rs b/crates/algo/src/blur2/smart_tests.rs index 9114ee8505..d2db9cb077 100644 --- a/crates/algo/src/blur2/smart_tests.rs +++ b/crates/algo/src/blur2/smart_tests.rs @@ -110,12 +110,14 @@ fn offset_fast_path_matches_the_per_channel_oracle() { for (mode, n, alpha) in layouts { let src = image(win, n, alpha); let ctx = Ctx { bounds: win, mode, alpha }; - for radius in [0.1f32, 1.0, 3.0, 12.0, 17.5] { + // Centre only, unit stride, and a coarse stride for both qualities. At 13 the inner + // rectangle still has pixels, so coarse offsets exercise the fast path too. + for radius in [0.1f32, 3.0, 13.0] { let ri = f32::ceil(radius) as i32; // The usual tile (the window less the halo), the whole window, and one sticking out of it. let inner = Rect::new(win.x0 + ri, win.y0 + ri, win.x1 - ri, win.y1 - ri); for out in [inner, win, Rect::new(-12, -9, 10, 8), Rect::EMPTY] { - // Quality only sets the offset stride: Low a coarse one, High every offset at these radii (#15652). + // Quality selects the offset stride; both paths are compared to the oracle. for quality in [BlurQuality::Low, BlurQuality::High] { for sm in [SmartBlurMode::Normal, SmartBlurMode::EdgeOnly, SmartBlurMode::OverlayEdge] { for threshold in [8.0, 60.0] { From c9746558d7628ce3f3888ec4fe5bbabe527b989a Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 08:06:05 +0000 Subject: [PATCH 55/85] ci: build the tests once per OS, keep compiled workspace crates, balance the shards - Both gate calls build the tests once into a nextest archive (cargo xtask ci archive); the shards run it, and the build job runs the doctests after the upload. - The Linux gate keeps the compiled workspace crates in a rolling cache entry (cache-workspace-crates). A nightly cold build is its safety net; gate-cache-prune keeps the newest entry. test (without heif) restores that entry. - The shards split the tests with nextest's slice partition, which spreads the slow modules: on one main run's times the non-GPU shards go from 728/493/523 s (hash) to about 602/506/625 s. Fixes #15702 --- .github/workflows/ci.yml | 111 ++++++++++++++++++++++++++----------- docs/development.md | 2 +- scripts/ci-gpu-lavapipe.py | 2 +- scripts/ci-test-shard.sh | 15 +++-- xtask/src/main.rs | 12 ++-- 5 files changed, 96 insertions(+), 46 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 70c2e6083e..8a0af37391 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,10 +2,14 @@ name: CI # Quality gates for every push to main and every pull request. The Linux and Windows tests run # through the suite's shared gate workflow in craft-common-actions (`cargo xtask ci`, split over the -# gate's jobs); the test variant and the corpus, web and fuzz jobs are PhotoCraft's own. +# gate's jobs); the test variant and the corpus, web and fuzz jobs are PhotoCraft's own. Every night +# the Linux gate alone runs a cold build: the safety net for the workspace crates it keeps between +# runs (`cache-workspace-crates`), and a fresh start for that cache entry. on: push: branches: [main] + schedule: + - cron: "11 3 * * *" pull_request: # `labeled` so that adding `full-ci` to an open PR starts a run with Windows in it. types: [opened, synchronize, reopened, labeled] @@ -70,7 +74,7 @@ concurrency: jobs: # Git dependencies come from github.com/storytold, and Cargo.lock is complete and up to date. git-sources: - if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' + if: github.event_name != 'schedule' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. uses: storytold/craft-common-actions/.github/workflows/git-sources.yml@main @@ -86,7 +90,7 @@ jobs: # `windows_skip`: the platform-neutral packages whose Windows tests a pull request skips because nothing it # changes reaches them (same script); empty on main and `full-ci`. platforms: - if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' + if: github.event_name != 'schedule' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') timeout-minutes: 10 name: select platforms runs-on: ubuntu-latest @@ -145,17 +149,20 @@ jobs: fi # The Linux gate (craft-common-actions gate.yml). Its `lint` leg runs the checks that need no test - # build; four test shards each build the tests from the restored cache and run their share - # (scripts/ci-test-shard.sh). Shard 1 runs nextest's `gpu` group alone, on lavapipe, and fails on - # a skipped GPU comparison (scripts/ci-gpu-lavapipe.py); shards 2-4 split the other tests, and - # shard 2 runs the doctests. The `gpu` group is ~2400 test-seconds on 4 slots (~12 min with its - # slowest test, ~8 once the five slow UI tests are fixed); the other ~5900 test-seconds over 3 - # shards are ~8 min each, so a fifth shard would not shorten the gate. Its rust-cache entry is - # the one `test (without heif)` restores. + # build. The `build` job builds the tests once into a nextest archive (`cargo xtask ci archive`), + # uploads it and then runs the doctests; four test shards download the archive and run their + # share (scripts/ci-test-shard.sh). Shard 1 runs nextest's `gpu` group alone, on lavapipe, and + # fails on a skipped GPU comparison (scripts/ci-gpu-lavapipe.py); shards 2-4 split the other + # tests. The `gpu` group is ~840 test-seconds on 4 slots (~3.5 min); the other ~6900 + # test-seconds over 3 shards are ~8.5-10.5 min each. + # The build keeps the compiled workspace crates between runs (`cache-workspace-crates`), so a + # pull request rebuilds only the crates its changes reach. Each main run's build job saves a + # rolling entry of its own, which `test (without heif)` restores too; `gate-cache-prune` keeps + # the newest one. gate: if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. - uses: aiongg/craft-common-actions/.github/workflows/gate.yml@trial-build-once + uses: aiongg/craft-common-actions/.github/workflows/gate.yml@ci-build-once-test with: # egui/winit/rfd. packages: >- @@ -175,34 +182,32 @@ jobs: LPDEST=photocraft-no-such-printer CARGO_PROFILE_TEST_STRIP=symbols timeout-minutes: 100 - # On main, a `cache warm` leg builds xtask and the tests, as each shard does, and saves the - # dependency cache as soon as the build succeeds; the shards then only restore, so a failing - # test cannot keep the entry from being saved (craft-common-actions#270). The lint leg keeps - # its own entry. - warm-command: cargo xtask ci build + cache-workspace-crates: true + cold-build: ${{ github.event_name == 'schedule' }} # fmt, egui-fork, clippy, layers, panel-commands, scorecard, the wasm32 check and the # missing-translations report (`cargo xtask ci lint`, xtask/src/main.rs), and the CI scripts' # own tests. lint-command: python3 scripts/test-ci-gpu-lavapipe.py && python3 scripts/test-ci-windows-gpu-tests.py && cargo xtask ci lint archive-command: cargo xtask ci archive + after-archive-command: cargo xtask ci doctest test-shards: 4 # The tests and panic_hunt with `--locked --features heif` (TEST_TARGETS in xtask/src/main.rs). shard-command: bash scripts/ci-test-shard.sh --gpu-shard # The Windows tests and Clippy on the same gate, when `platforms` says the run needs them: a - # `lint` leg runs Clippy, and six shards each build the tests and run their hash partition; - # shard 1 also runs the doctests. Windows runs the tests ~1.75x slower than Linux: ~55 min on - # one runner, ~9 min per shard. A seventh shard would not shorten the slowest one while its - # slowest test alone takes ~9.6 min (the shortcut-dispatch UI test). The browser apps are wasm - # targets, so their native tests are left out; - # pull requests also leave out photocraft-gpu and the platform-neutral packages nothing they change - # reaches (`windows_gpu`, `windows_skip`). The `cache warm` leg (main only) builds what main's - # build job builds. + # `lint` leg runs Clippy, the `build` job builds the tests once into a nextest archive and then + # runs the doctests, and six shards run their slice of the tests from the archive. Windows runs + # the tests ~1.75x slower than Linux: ~55 min on one runner, ~9 min per shard. A seventh shard + # would not shorten the slowest one while its slowest test alone takes ~9.6 min (the + # shortcut-dispatch UI test). The browser apps are wasm targets, so their native tests are left + # out; pull requests also leave out photocraft-gpu and the platform-neutral packages nothing they + # change reaches (`windows_gpu`, `windows_skip`). Windows keeps a dependency-only cache entry: + # its workspace crates would not fit the repository's cache budget beside Linux's. windows: needs: platforms if: needs.platforms.outputs.windows == 'true' # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. - uses: aiongg/craft-common-actions/.github/workflows/gate.yml@trial-build-once + uses: aiongg/craft-common-actions/.github/workflows/gate.yml@ci-build-once-test with: os: '["windows-latest"]' # The all-language UI tests shape real Japanese, Chinese, Korean and Devanagari labels with @@ -230,18 +235,57 @@ jobs: CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS=-Clink-arg=/OPT:NOICF -Clink-arg=/DEBUG:NONE PHOTOCRAFT_CI_EXCLUDE=photocraft-web photocraft-web-boot ${{ needs.platforms.outputs.windows_gpu == 'false' && 'photocraft-gpu' || '' }} ${{ needs.platforms.outputs.windows_skip }} timeout-minutes: 100 - warm-command: cargo xtask ci build lint-command: cargo xtask ci clippy archive-command: cargo xtask ci archive + after-archive-command: cargo xtask ci doctest test-shards: 6 shard-command: bash scripts/ci-test-shard.sh + # The Linux gate's build job saves a rolling cache entry of its own on every main and nightly run + # (`cache-workspace-crates`), about 3.8 GB, and every run restores only the newest. This deletes + # the older ones at once instead of leaving them to the 10 GB budget's eviction, which would + # evict other entries too. + gate-cache-prune: + needs: gate + if: ${{ !cancelled() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + timeout-minutes: 5 + runs-on: ubuntu-24.04 + permissions: + actions: write + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - name: Delete all but the newest rolling entry of each job and runner + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + run: | + set -euo pipefail + # `-rust---crates-----...`, newest first. + gh cache list --repo "$REPO" --limit 100 --sort created_at --order desc --json id,key \ + --jq '.[] | "\(.id) \(.key)"' > "$RUNNER_TEMP/caches" + declare -A kept + while read -r id key; do + [[ "$key" =~ ^.+-rust-[0-9a-f]{64}-(.+-crates-[A-Za-z_]+-[a-z0-9]+)-[0-9]+-[0-9]+- ]] || continue + entry=${BASH_REMATCH[1]} + if [ -n "${kept[$entry]:-}" ]; then + echo "delete $key" + gh cache delete "$id" --repo "$REPO" + else + kept[$entry]=1 + echo "keep $key" + fi + done < "$RUNNER_TEMP/caches" + # The same codecs without the optional decoder: HEIC must stay a clear "not in this build" error - # for distributors who leave it out. Runs beside the gate and restores the gate's dependency - # cache without saving one: the dependencies are the same, and the 10 GB cache budget is tight - # (#2688). + # for distributors who leave it out. Runs beside the gate and restores the gate's newest rolling + # cache entry without saving one: the dependencies are the same, and the 10 GB cache budget is + # tight (#2688). Its sources keep their checkout mtimes, so the workspace crates it builds are + # rebuilt. test-without-heif: - if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' + if: github.event_name != 'schedule' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') timeout-minutes: 60 name: test (without heif) # The gate's runner: its cache entry is keyed on the OS. @@ -279,11 +323,12 @@ jobs: # The gate's own key (the shared action computes it), restore only. The toolchain action # exports CARGO_HOME, which the gate's legs do not have; align-environment leaves it out of - # the key. - - uses: storytold/craft-common-actions/actions/rust-cache@main + # the cache paths. + - uses: aiongg/craft-common-actions/actions/rust-cache@ci-build-once-test with: cache-version: v2 job: gate + cache-workspace-crates: "true" align-environment: "true" - uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32 @@ -294,7 +339,7 @@ jobs: run: cargo nextest run -p photocraft-io --locked --profile ci corpus: - if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' + if: github.event_name != 'schedule' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') timeout-minutes: 30 # Real-file corpus tests (cargo feature `corpus`), on every PR and on main. The corpora are # pinned in xtask/src/corpus_pins.rs and sha256-verified (xtask/*.sha256) after both a cache diff --git a/docs/development.md b/docs/development.md index fe51840cac..bd62ca10e1 100644 --- a/docs/development.md +++ b/docs/development.md @@ -114,7 +114,7 @@ the opted-in test; an unset variable leaves the ordinary behavior tests availabl After review, remove only the two generated PNGs and their owned temporary directory. The same Rust test and variable work on Windows with the native shell's environment-variable syntax. -**GPU tests without a GPU.** Linux CI uses the shared `craft-common-actions` gate with Mesa's Vulkan driver installed. The gate builds the tests once into a nextest archive (`cargo xtask ci archive`) and runs them in shards from it (`cargo xtask ci tests`). One shard runs the configured `gpu` group alone, through `python3 scripts/ci-gpu-lavapipe.py`, with `WGPU_BACKEND=vulkan` and the lavapipe ICD explicitly selected; the other shards split the remaining tests. The script requires Vulkan parity evidence in that shard's output and rejects authored skips, except the documented software-adapter timing exceptions. xtask reads the group's filter from `.config/nextest.toml`, so no second filter needs maintaining. To run locally on Linux, install `mesa-vulkan-drivers libvulkan1`, build an archive and run `python3 scripts/ci-gpu-lavapipe.py /target/debug/xtask ci tests --from --gpu` as the gate's shard command in `.github/workflows/ci.yml` does. Windows uses WARP; this check does not certify Windows skip coverage. +**GPU tests without a GPU.** Linux CI uses the shared `craft-common-actions` gate with Mesa's Vulkan driver installed. The gate builds the tests once into a nextest archive (`cargo xtask ci archive`) and runs them in shards from it (`cargo xtask ci tests`). One shard runs the configured `gpu` group alone, through `python3 scripts/ci-gpu-lavapipe.py`, with `WGPU_BACKEND=vulkan` and the lavapipe ICD explicitly selected; the other shards split the remaining tests. The script requires Vulkan parity evidence in that shard's output and rejects authored skips, except the documented software-adapter timing exceptions. xtask reads the group's filter from `.config/nextest.toml`, so no second filter needs maintaining. To run locally on Linux, install `mesa-vulkan-drivers libvulkan1`, build an archive and run `python3 scripts/ci-gpu-lavapipe.py /target/debug/xtask ci tests --from --gpu` as `scripts/ci-test-shard.sh` does. Windows uses WARP; this check does not certify Windows skip coverage. ## Fonts (craft-fonts) diff --git a/scripts/ci-gpu-lavapipe.py b/scripts/ci-gpu-lavapipe.py index 7ff41e10c7..8d89c1a17f 100644 --- a/scripts/ci-gpu-lavapipe.py +++ b/scripts/ci-gpu-lavapipe.py @@ -2,7 +2,7 @@ """Run a command with wgpu on lavapipe, and fail if a GPU comparison in its output was skipped. The Linux gate runs nextest's `gpu` test group in a shard of its own through this script -(`ci-gpu-lavapipe.py ci tests --from --gpu`, .github/workflows/ci.yml): every wgpu +(`ci-gpu-lavapipe.py ci tests --from --gpu`, scripts/ci-test-shard.sh): every wgpu device in the run is Vulkan on Mesa's CPU rasterizer, each test's output is shown, and the output is checked here for authored skips and for the parity tests' Vulkan backend line. diff --git a/scripts/ci-test-shard.sh b/scripts/ci-test-shard.sh index 40afc15146..298c672b2f 100755 --- a/scripts/ci-test-shard.sh +++ b/scripts/ci-test-shard.sh @@ -2,10 +2,15 @@ # One shard of the gate's tests: the gate's `shard-command` (.github/workflows/ci.yml). The gate's # build job wrote a nextest archive of the tests with `cargo xtask ci archive`, and the archive # carries that xtask binary (.config/nextest.toml), so the shard extracts it and runs the test steps -# with `xtask ci tests` without building anything. The gate sets NEXTEST_ARCHIVE_FILE, GATE_SHARD, -# GATE_SHARDS and NEXTEST_PARTITION. +# with `xtask ci tests` without building anything. The gate sets NEXTEST_ARCHIVE_FILE, GATE_SHARD +# and GATE_SHARDS. # -# ci-test-shard.sh the shard runs its hash partition of every test +# The shards split the tests with nextest's `slice` partition (round-robin over every test of every +# binary). Test times are heavy-tailed and cluster in a few modules: on the times of a main run +# (#15702), a three-way `hash` split of the non-GPU tests ran 728, 493 and 523 s, and `slice` +# would run them in about 602, 506 and 625 s. +# +# ci-test-shard.sh the shard runs its slice of every test # ci-test-shard.sh --gpu-shard shard 1 runs nextest's `gpu` group alone on lavapipe, checked by # scripts/ci-gpu-lavapipe.py; the other shards split the other tests set -euo pipefail @@ -17,7 +22,7 @@ xtask=("$archive/target/debug/xtask" ci tests --from "$archive") case "$(uname -s)" in MINGW* | MSYS* | CYGWIN*) xtask=("$archive/target/debug/xtask.exe" ci tests --from "$archive") ;; esac case "${1:-}" in - "") exec "${xtask[@]}" ;; + "") NEXTEST_PARTITION="slice:$GATE_SHARD/$GATE_SHARDS" exec "${xtask[@]}" ;; --gpu-shard) if [ "$GATE_SHARDS" -lt 2 ]; then echo "::error::--gpu-shard needs at least two shards, got $GATE_SHARDS" @@ -26,7 +31,7 @@ case "${1:-}" in if [ "$GATE_SHARD" = 1 ]; then exec python3 scripts/ci-gpu-lavapipe.py "${xtask[@]}" --gpu fi - NEXTEST_PARTITION="hash:$((GATE_SHARD - 1))/$((GATE_SHARDS - 1))" exec "${xtask[@]}" --no-gpu + NEXTEST_PARTITION="slice:$((GATE_SHARD - 1))/$((GATE_SHARDS - 1))" exec "${xtask[@]}" --no-gpu ;; *) echo "usage: $0 [--gpu-shard]" >&2 diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 97ae021fd4..4fdf22d635 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -40,12 +40,12 @@ commands: tests (nextest --profile ci), panic_hunt, doctests, wasm and the i18n-report, with --locked --features heif (stops at first failure). The gate splits it over its jobs: `lint` runs the steps that need no test build; `archive` builds the tests into the nextest archive at - $NEXTEST_ARCHIVE_FILE and runs the doctests; `tests --from ` runs the tests from that archive + $NEXTEST_ARCHIVE_FILE (the gate's build job, which then runs `doctest`); `tests --from ` runs the tests from that archive extracted to (without --from it builds them); `tests` runs the tests and panic_hunt on the partition in $NEXTEST_PARTITION (`--gpu`: all of nextest's gpu test group, whatever the partition, each test's output shown; `--no-gpu`: every other test); `doctest` runs the doctests; `build` only builds what `tests` - builds (the cache warm-up). $PHOTOCRAFT_CI_EXCLUDE (packages separated by spaces) leaves + builds. $PHOTOCRAFT_CI_EXCLUDE (packages separated by spaces) leaves packages out of the test build and the doctests corpus [--all | --pngsuite | --psd | --psd-tools | --pixls | --atn | --photoshop | --gimp] [--local] [--update-manifest] show where test corpora live and their pins (xtask/src/corpus_pins.rs), or fetch @@ -265,7 +265,7 @@ enum Part { Lint, /// The tests, which the gate splits over its shards (`ci tests`). Test, - /// The doctests, which the gate runs in one shard (`ci doctest`). + /// The doctests, which the gate's build job runs once the archive is uploaded (`ci doctest`). Doc, } @@ -518,13 +518,13 @@ fn ci_from_args(args: &[&str], exclude: Vec) -> Result<(CiPlan, CiOption options.build_only = true; &[Part::Test] } - // The gate's build job: the tests into the archive at $NEXTEST_ARCHIVE_FILE (which also - // carries this xtask, .config/nextest.toml), and the doctests, which need the rlibs. + // The gate's build job: the tests into the archive at $NEXTEST_ARCHIVE_FILE, which also + // carries this xtask (.config/nextest.toml). Some("archive") => { let file = std::env::var_os("NEXTEST_ARCHIVE_FILE").ok_or("ci archive: set NEXTEST_ARCHIVE_FILE to the archive to write")?; options.archive = Some(file.into()); options.build_only = true; - &[Part::Test, Part::Doc] + &[Part::Test] } Some("tests") => { options.partition = tests_partition(options.selection, std::env::var("NEXTEST_PARTITION").ok()); From 17e6b13052a2f262d4d8a795f910d6eeb40c02cc Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:21:52 +0100 Subject: [PATCH 56/85] Reduce preview and pattern boundary fixtures --- crates/engine/src/cmd/mode_cmds/tests.rs | 5 +++- crates/engine/src/cmd/pattern_cmds.rs | 24 ++++++++++++------- crates/engine/src/cmd/retouch_cmds.rs | 4 +++- .../cmd/retouch_cmds/content_aware_move.rs | 8 ++++++- crates/engine/src/cmd/retouch_cmds/tests.rs | 20 ++++++++++------ crates/engine/src/color_channels/tone.rs | 10 +++++--- 6 files changed, 50 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/mode_cmds/tests.rs b/crates/engine/src/cmd/mode_cmds/tests.rs index c64e38b09b..7e49ee5f8f 100644 --- a/crates/engine/src/cmd/mode_cmds/tests.rs +++ b/crates/engine/src/cmd/mode_cmds/tests.rs @@ -866,7 +866,7 @@ fn bitmap_in_bands_matches_one_full_canvas_conversion() { let (w, h) = (64u32, 300u32); let mut s = session(w, h, 8, "grayscale"); paint(&mut s, |x, y| { - let v = ((x % 509) as f32 / 509.0 * 0.6 + (y as f32 / 300.0) * 0.4).fract(); + let v = ((x % 61) as f32 / 61.0 * 0.6 + (y as f32 / 300.0) * 0.4).fract(); [v, v, v, 1.0] }); add_pattern(&mut s, "Cells", 3, 2, &[10, 200, 90, 250, 150, 40]); @@ -902,6 +902,9 @@ fn bitmap_in_bands_matches_one_full_canvas_conversion() { }; // Grayscale stores 0/1 the way `from_rgba` turns the old RGBA output into gray. let want: Vec = want.iter().map(|g| photocraft_raster::from_rgba(&storage_format(ColorMode::Bitmap), [*g, *g, *g, 1.0])[0]).collect(); + if method == "threshold" { + assert!(want.contains(&0.0) && want.contains(&1.0), "the gradient crosses the threshold"); + } let got = bitmap_pixels(doc(&s)); let diff = got.iter().zip(&want).filter(|(a, b)| (**a - **b).abs() > 1e-6).count(); assert_eq!(diff, 0, "{method}: {diff} of {} pixels differ", got.len()); diff --git a/crates/engine/src/cmd/pattern_cmds.rs b/crates/engine/src/cmd/pattern_cmds.rs index d1a93b42d4..c113b69dba 100644 --- a/crates/engine/src/cmd/pattern_cmds.rs +++ b/crates/engine/src/cmd/pattern_cmds.rs @@ -325,6 +325,12 @@ pub fn default_name(s: &Session) -> String { const MAX_DEFINE_EDGE: u32 = 8000; fn define(s: &mut Session, p: &Value) -> Result { + let sample = s.active().ok_or(EngineError::NoDocument)?.doc.pixel_format().sample; + define_with_max_pixels(s, p, photocraft_doc::pattern::max_paint_pixels(sample)) +} + +/// Define a pattern with a bound on its pixel count. +fn define_with_max_pixels(s: &mut Session, p: &Value, max_px: u64) -> Result { let cmd = "edit.definePattern"; let st = s.active().ok_or(EngineError::NoDocument)?; let doc = &st.doc; @@ -345,7 +351,6 @@ fn define(s: &mut Session, p: &Value) -> Result { // A pattern the compositor could not hold would define but paint nothing: 8 bits go to the // edge limit, 16-bit documents to 33,554,432 px in all, float to 16,777,216 (4096 × 4096). let sample = doc.pixel_format().sample; - let max_px = photocraft_doc::pattern::max_paint_pixels(sample); if u64::from(r.width()) * u64::from(r.height()) > max_px { return Err(bad(cmd, format!("patterns in a {}-bit document are limited to {max_px} px in all", sample.bytes() * 8))); } @@ -762,17 +767,20 @@ mod tests { assert!(e.contains("16-bit") && e.contains("33554432"), "{e}"); } - /// A pattern of the largest area Define Pattern accepts at 8 bits is paintable: held at 4 - /// bytes a pixel, 256 MB, as the compositor's cap allows, and it renders. + /// A pattern at the area limit is paintable and renders; production permits 8000×8000 at 8 bits. #[test] - fn an_8000_by_8000_pattern_is_defined_and_paints() { + fn a_pattern_at_the_area_limit_is_defined_and_paints() { let mut s = Session::new(); - s.execute("file.new", json!({"width": 8000, "height": 8000, "depth": 8})).unwrap(); + assert_eq!(photocraft_doc::pattern::max_paint_pixels(SampleType::U8), 8000 * 8000); + assert_eq!(photocraft_doc::pattern::working_bytes_for(8000 * 8000, SampleType::U8), 8000 * 8000 * 4); + let (side, max_px) = (80, 80 * 80); + s.execute("file.new", json!({"width": side, "height": side, "depth": 8})).unwrap(); s.execute("edit.fill", json!({"color": "#336699"})).unwrap(); - s.execute("edit.definePattern", json!({"name": "Largest"})).unwrap(); + assert!(define_with_max_pixels(&mut s, &json!({"name": "Too large"}), max_px - 1).is_err()); + define_with_max_pixels(&mut s, &json!({"name": "Largest"}), max_px).unwrap(); let p = s.patterns.items.iter().find(|p| p.name == "Largest").unwrap(); - assert_eq!((p.width, p.height), (8000, 8000)); - assert!(p.is_paintable() && p.working_bytes() == 256_000_000); + assert_eq!((p.width, p.height), (side, side)); + assert!(p.is_paintable() && p.working_bytes() == max_px * 4); s.execute("file.new", json!({"width": 40, "height": 30, "depth": 8})).unwrap(); s.execute("layer.newFillLayer.pattern", json!({"pattern": "Largest"})).unwrap(); let [r, g, b, a] = pixel(&s, 5, 5); diff --git a/crates/engine/src/cmd/retouch_cmds.rs b/crates/engine/src/cmd/retouch_cmds.rs index 95cbe7ca99..00631c91b3 100644 --- a/crates/engine/src/cmd/retouch_cmds.rs +++ b/crates/engine/src/cmd/retouch_cmds.rs @@ -35,7 +35,9 @@ pub use pattern_stamp::{ }; mod periodic; mod remove; -pub use content_aware_move::{ContentAwarePreview, preview as content_aware_move_preview}; +pub use content_aware_move::{ + ContentAwarePreview, preview as content_aware_move_preview, preview_with_pixel_budget as content_aware_move_preview_with_pixel_budget, +}; pub use patch::preview as patch_preview; fn bad(cmd: &str, msg: impl Into) -> EngineError { diff --git a/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs b/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs index fb1e8a703d..89eca9973a 100644 --- a/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs +++ b/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs @@ -696,12 +696,18 @@ impl ContentAwarePreview { /// Prepare the preview of `paint.contentAwareMove` with params `p` on the active document. Errors /// as the command does (bad params, nothing to move, a selection larger than the command takes). pub fn preview(s: &Session, p: &Value) -> Result { + preview_with_pixel_budget(s, p, PREVIEW_MAX_PIXELS) +} + +/// Prepare a preview with a bound on the number of pixels solved at full resolution. +pub fn preview_with_pixel_budget(s: &Session, p: &Value, max_pixels: u64) -> Result { let captured = crate::channel_cmds::inject_target(s, CMD, p.clone()); let p = &captured; let plan = plan(s, p, PREVIEW_MARGIN)?; let px = |r: Rect| u64::from(r.width()) * u64::from(r.height()); let pixels = px(plan.area).max(px(plan.dest)); - let scale = if pixels > PREVIEW_MAX_PIXELS { (PREVIEW_MAX_PIXELS as f64 / pixels as f64).sqrt() } else { 1.0 }; + let max_pixels = max_pixels.max(1); + let scale = if pixels > max_pixels { (max_pixels as f64 / pixels as f64).sqrt() } else { 1.0 }; let d = s.active().ok_or(EngineError::NoDocument)?; Ok(ContentAwarePreview { colors: crate::color_channels::target(s, p)?, doc: d.doc.clone(), plan, params: p.clone(), scale }) } diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index 999575cf69..c1096a7135 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -1698,15 +1698,21 @@ fn content_aware_move_previews_large_selections_coarse_then_exact() { #[test] fn content_aware_move_coarse_preview_handles_transform_extend_and_limits() { use crate::jobs::JobCtx; - let s = large_move(8); + let mut s = session(128, 64, 8, "rgb"); + paint_layer(&mut s, with_object(20, 26)); + s.execute("select.rect", json!({"x": 16, "y": 22, "width": 20, "height": 20})).unwrap(); let px = |d: &Document, x, y| d.layers[0].surface().unwrap().rgba(x, y); - // Transform On Drop: turned 90° about the selection's centre (210, 160), then moved; the - // object sits at the centre, so it lands at (460, 220) either way. - let (turned, _) = content_aware_move_preview(&s, &json!({"offset": [250, 60], "rotate": 90})).unwrap().run(&JobCtx::new()).unwrap(); - assert!(is_object(px(&turned, 460, 220)) && !is_object(px(&turned, 210, 160))); + // A 400-pixel selection is just over the preview budget. It turns about its centre and moves. + let preview = |p: &Value| content_aware_move::preview_with_pixel_budget(&s, p, 399); + let job = preview(&json!({"offset": [70, 0], "rotate": 90})).unwrap(); + assert!(job.is_coarse()); + let (turned, _) = job.run(&JobCtx::new()).unwrap(); + assert!(is_object(px(&turned, 96, 32)) && !is_object(px(&turned, 26, 32))); // Extend keeps the original. - let (extended, _) = content_aware_move_preview(&s, &json!({"offset": [250, 60], "mode": "extend"})).unwrap().run(&JobCtx::new()).unwrap(); - assert!(is_object(px(&extended, 460, 220)) && is_object(px(&extended, 210, 160))); + let job = preview(&json!({"offset": [70, 0], "mode": "extend"})).unwrap(); + assert!(job.is_coarse()); + let (extended, _) = job.run(&JobCtx::new()).unwrap(); + assert!(is_object(px(&extended, 96, 32)) && is_object(px(&extended, 26, 32))); // Off the canvas, or past the command's own limit, is still an error. assert!(content_aware_move_preview(&s, &json!({"offset": [400, 0]})).is_err()); let mut big = session(5000, 4000, 8, "rgb"); diff --git a/crates/engine/src/color_channels/tone.rs b/crates/engine/src/color_channels/tone.rs index b7db453e09..584e28953c 100644 --- a/crates/engine/src/color_channels/tone.rs +++ b/crates/engine/src/color_channels/tone.rs @@ -263,8 +263,8 @@ mod tests { space: ToneSpace::Lab, }, ]; - for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab] { - for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + for (mi, mode) in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab].into_iter().enumerate() { + for (si, sample) in [SampleType::U8, SampleType::U16, SampleType::F32].into_iter().enumerate() { let fmt = PixelFormat::new(mode, sample, true); let mut source = Surface::with_default(fmt, &vec![0.3; fmt.channels()]); // 256 x 256 is exactly the U16 table's area threshold (`use_table`), so the table path still runs (#15652). @@ -281,7 +281,11 @@ mod tests { let mut holes = Surface::with_default(mask.format(), &[0.63]); holes.fill_rect(Rect::from_xywh(2, 8, 7, 5), &[0.0]); let colors = ColorChannels::from_indices([0, mode.color_channels() - 1], mode.color_channels()).unwrap(); - for selection in [None, Some(&mask), Some(&holes)] { + // Every mode/sample, mode/selection and sample/selection pair remains. + for (ti, selection) in [None, Some(&mask), Some(&holes)].into_iter().enumerate() { + if ti != (mi + si) % 3 { + continue; + } for adjustment in &adjustments { let mut expected = source.clone(); let mut actual = source.clone(); From bd0671f017d7baf964e787b6eea7ddab5b50087e Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:21:52 +0100 Subject: [PATCH 57/85] Exercise relight bands with a smaller budget --- crates/algo/src/relight.rs | 38 +++++++++++++++++++++++--------------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/crates/algo/src/relight.rs b/crates/algo/src/relight.rs index 679c9b7f51..d36454d238 100644 --- a/crates/algo/src/relight.rs +++ b/crates/algo/src/relight.rs @@ -150,6 +150,11 @@ fn read_rgba(src: &Image, ctx: &Ctx, x: i32, y: i32) -> [f32; 4] { /// Relight `out` of `src`. Identity when `intensity` is 0 (or not finite). pub(crate) fn relight(src: &Image, out: Rect, ctx: &Ctx, p: Params) -> Vec { + relight_with_luma_budget(src, out, ctx, p, MAX_LUMA_PIXELS) +} + +/// Relight with a bound on the luma field allocated by each band. +fn relight_with_luma_budget(src: &Image, out: Rect, ctx: &Ctx, p: Params, max_luma_pixels: usize) -> Vec { let n = src.ch; if out.is_empty() || n == 0 { return src.crop(out); @@ -160,14 +165,14 @@ pub(crate) fn relight(src: &Image, out: Rect, ctx: &Ctx, p: Params) -> Vec let sig = sigma(p.softness, ctx.bounds); let step = step_for_sigma(sig); let reach = read_radius(sig); - if let Some(band_h) = luma_band_rows(out, reach) { + if let Some(band_h) = luma_band_rows(out, reach, max_luma_pixels) { return relight_bands(src, out, ctx, p, sig, step, band_h); } relight_rect(src, out, ctx, p, sig, step) } /// Horizontal strip height so the inflated luma field stays within [`MAX_LUMA_PIXELS`]. -fn luma_band_rows(out: Rect, reach: i32) -> Option { +fn luma_band_rows(out: Rect, reach: i32, max_luma_pixels: usize) -> Option { let margin = 2usize.saturating_mul(reach.max(0) as usize); let yw = (out.width() as usize).saturating_add(margin); let yh = (out.height() as usize).saturating_add(margin); @@ -179,10 +184,10 @@ fn luma_band_rows(out: Rect, reach: i32) -> Option { Some(_) => return None, None => usize::MAX, }; - if n <= MAX_LUMA_PIXELS { + if n <= max_luma_pixels { return None; } - let max_yh = (MAX_LUMA_PIXELS / yw).max(1); + let max_yh = (max_luma_pixels / yw).max(1); let inner = max_yh.saturating_sub(margin).max(1).min(i32::MAX as usize) as i32; if inner >= out.height() as i32 { None } else { Some(inner.max(1)) } } @@ -534,10 +539,9 @@ mod tests { } #[test] - fn layers_above_8mp_are_relit() { - // 4096×2048 = 8.39 MP. A single full-frame kernel call inflates past 8 MP of luma, - // which used to return the input unchanged. Force one tile so that path is taken. - let (w, h) = (4096, 2048); + fn layers_above_the_luma_budget_are_relit() { + // A small budget exercises the same banding path as an 8 MP luma field. + let (w, h) = (256, 128); let bounds = Rect::new(0, 0, w, h); let mut s = Surface::new(PixelFormat::RGBA8); let bytes: Vec = (0..h) @@ -550,15 +554,19 @@ mod tests { }) .collect(); s.write_interleaved(bounds, &bytes); - let p = relight_p(180.0, 30.0, 90.0, 12.0, 0.0, 25.0); - let area = output_area(&p, s.content_bounds(), bounds, None); + let p = Params { angle: 180.0, elevation: 30.0, intensity: 90.0, ambient: 12.0, warmth: 0.0, softness: 25.0 }; + let reach = read_radius(sigma(p.softness, bounds)); + assert!(luma_band_rows(bounds, reach, 20_000).is_some()); + let src = Image::read_clamped(&s, bounds.inflate(reach), bounds); + let ctx = Ctx { bounds, mode: ColorMode::Rgb, alpha: true }; let before = s.pixel(w / 2, h / 2); - let out = apply_tiled(&s, &p, area, bounds, None, 8192, None); - let after = out.pixel(w / 2, h / 2); + let out = relight_with_luma_budget(&src, bounds, &ctx, p, 20_000); + let pixel = |x: i32, y: i32| &out[((y * w + x) * 4) as usize..][..4]; + let after = pixel(w / 2, h / 2); assert!(after.iter().all(|c| c.is_finite()), "{after:?}"); - let d = max_diff(&before, &after); - assert!(d > 1e-4, "8 MP+ layer was left unchanged (max diff {d})"); - assert!(max_diff(&s.pixel(8, 8), &out.pixel(8, 8)) > 1e-4); + let d = max_diff(&before, after); + assert!(d > 1e-4, "over-budget layer was left unchanged (max diff {d})"); + assert!(max_diff(&s.pixel(8, 8), pixel(8, 8)) > 1e-4); } #[test] From cb368d32e96aa4ef16993ab99e06e1ec48c134db Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:29:51 +0100 Subject: [PATCH 58/85] Correct pattern budget assertions --- crates/engine/src/cmd/pattern_cmds.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/pattern_cmds.rs b/crates/engine/src/cmd/pattern_cmds.rs index c113b69dba..1271ea0591 100644 --- a/crates/engine/src/cmd/pattern_cmds.rs +++ b/crates/engine/src/cmd/pattern_cmds.rs @@ -771,7 +771,8 @@ mod tests { #[test] fn a_pattern_at_the_area_limit_is_defined_and_paints() { let mut s = Session::new(); - assert_eq!(photocraft_doc::pattern::max_paint_pixels(SampleType::U8), 8000 * 8000); + assert_eq!(MAX_DEFINE_EDGE, 8000); + assert!(photocraft_doc::pattern::max_paint_pixels(SampleType::U8) >= 8000 * 8000); assert_eq!(photocraft_doc::pattern::working_bytes_for(8000 * 8000, SampleType::U8), 8000 * 8000 * 4); let (side, max_px) = (80, 80 * 80); s.execute("file.new", json!({"width": side, "height": side, "depth": 8})).unwrap(); @@ -780,7 +781,8 @@ mod tests { define_with_max_pixels(&mut s, &json!({"name": "Largest"}), max_px).unwrap(); let p = s.patterns.items.iter().find(|p| p.name == "Largest").unwrap(); assert_eq!((p.width, p.height), (side, side)); - assert!(p.is_paintable() && p.working_bytes() == max_px * 4); + // A small pattern uses the expanded float representation, unlike the largest 8-bit one. + assert!(p.is_paintable() && p.working_bytes() == max_px * 16); s.execute("file.new", json!({"width": 40, "height": 30, "depth": 8})).unwrap(); s.execute("layer.newFillLayer.pattern", json!({"pattern": "Largest"})).unwrap(); let [r, g, b, a] = pixel(&s, 5, 5); From 16935087ab25952cca3a74eb18ac4a713ad3aa5e Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:30:24 +0100 Subject: [PATCH 59/85] Fix shared preset mutation and sync --- crates/engine/src/cmd/brush_preset_cmds.rs | 2 +- crates/engine/src/preset_store.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/brush_preset_cmds.rs b/crates/engine/src/cmd/brush_preset_cmds.rs index 34cd2fbb4a..8965d1d658 100644 --- a/crates/engine/src/cmd/brush_preset_cmds.rs +++ b/crates/engine/src/cmd/brush_preset_cmds.rs @@ -120,7 +120,7 @@ pub(crate) fn rename_at(s: &mut Session, i: usize, new: &str, cmd: &str) -> Resu if index_of(&s.tools.presets, new).is_some_and(|j| j != i) { return Err(bad(cmd, format!("a brush preset named `{new}` already exists"))); } - let pr = s.tools.presets.get_mut(i).ok_or_else(|| bad(cmd, "no such preset"))?; + let pr = std::sync::Arc::make_mut(&mut s.tools.presets).get_mut(i).ok_or_else(|| bad(cmd, "no such preset"))?; if pr.name != new { let was_current = s.tools.current_preset.as_ref().is_some_and(|c| c.eq_ignore_ascii_case(&pr.name)); pr.name = new.to_string(); diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs index b44a2abdae..174c99281d 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -1204,7 +1204,7 @@ impl Session { let rev = self.tools.presets_rev; if let Some(st) = self.preset_store.as_mut() { if st.synced_rev != Some(rev) { - st.sync(std::sync::Arc::make_mut(&mut self.tools.presets)); + st.sync(std::sync::Arc::make_mut(&mut self.tools.presets).as_mut_slice()); st.synced_rev = Some(rev); if link_stored_tips(st, &mut self.tools.brush) { // An embedded tip became a store reference: what the last-brush From de5725af2fc532aa42141334cc993dfb2a375664 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:40:39 +0100 Subject: [PATCH 60/85] Use strips for Camera Raw parity tests --- crates/gpu/tests/it/camera_raw.rs | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/crates/gpu/tests/it/camera_raw.rs b/crates/gpu/tests/it/camera_raw.rs index 836c1d42a1..d85a2fac52 100644 --- a/crates/gpu/tests/it/camera_raw.rs +++ b/crates/gpu/tests/it/camera_raw.rs @@ -170,10 +170,6 @@ fn image(w: usize, h: usize, depth: Depth) -> Vec<[f32; 4]> { } /// Develops `p` both ways and returns the largest channel difference. -fn compare(g: &mut Gpu, p: &Case, depth: Depth) -> f32 { - compare_at(g, p, depth, (171, 113)) -} - fn compare_at(g: &mut Gpu, p: &Case, depth: Depth, (w, h): (usize, usize)) -> f32 { compare_image(g, p, depth, &image(w, h, depth), (w, h)) } @@ -207,10 +203,14 @@ fn compare_image(g: &mut Gpu, p: &Case, depth: Depth, src: &[[f32; 4]], (w, h): } fn check(name: &str, sets: &[Case]) { + check_at(name, sets, (171, 113)); +} + +fn check_at(name: &str, sets: &[Case], size: (usize, usize)) { let Some(mut g) = gpu() else { return }; for p in sets { for depth in DEPTHS { - let d = compare(&mut g, p, depth); + let d = compare_at(&mut g, p, depth, size); eprintln!("{name} {depth:?}: max |GPU - CPU| = {d:.2e}"); } } @@ -424,7 +424,8 @@ fn shadows_and_highlights() { cr! { shadows: 35.0, highlights: -45.0, encoding_gamma: 1.8}, ]; assert_moves(&sets); - check("shadows/highlights", &sets); + // The long side preserves the spatial filter scale; 48 rows keep several pyramid levels. + check_at("shadows/highlights", &sets, (171, 48)); } #[test] @@ -476,7 +477,7 @@ fn shadows_and_highlights_with_per_pixel_stages() { vignette_amount: -30.0, grain_amount: 20.0, pixel_scale: 0.2}; - check( + check_at( "shadows/highlights + per pixel", &[ all.clone(), @@ -485,10 +486,11 @@ fn shadows_and_highlights_with_per_pixel_stages() { cr! { highlights: -60.0, whites: -60.0, blacks: 50.0, exposure: -0.4}, cr! { shadows: 30.0, highlights: -30.0, whites: 40.0, blacks: -30.0, encoding_gamma: 1.8}, ], + (171, 48), ); // At the dialog's proxy width, at one depth: the depth only changes how the input is // quantized (8 and 16 bits both develop with `float = false`), and every depth already ran - // above at 171×113. The long side is what matters here (subsampled pyramid levels); the short + // above at 171×48. The long side is what matters here (subsampled pyramid levels); the short // one only needs to keep several levels, so the frame is a strip. let Some(mut g) = gpu() else { return }; let d = compare_at(&mut g, &all, Depth::Sixteen, (858, 120)); @@ -499,9 +501,9 @@ fn shadows_and_highlights_with_per_pixel_stages() { /// with the CPU can't pass trivially. fn assert_moves(sets: &[Case]) { for p in sets { - let src = image(171, 113, Depth::Sixteen); + let src = image(171, 48, Depth::Sixteen); let mut out = src.clone(); - develop(&mut out, 171, 113, p, false); + develop(&mut out, 171, 48, p, false); let moved = out.iter().zip(&src).flat_map(|(a, b)| (0..3).map(move |c| (a[c] - b[c]).abs())).fold(0.0f32, f32::max); assert!(moved > 0.02, "{p:?} moves pixels by at most {moved}"); } @@ -523,7 +525,8 @@ fn clarity_texture_and_dehaze() { cr! { dehaze: -30.0, clarity: -25.0, texture: 60.0, encoding_gamma: 1.8}, ]; assert_moves(&sets); - check("clarity/texture/dehaze", &sets); + // Match the movement check while retaining several pyramid levels. + check_at("clarity/texture/dehaze", &sets, (171, 48)); } #[test] @@ -563,11 +566,11 @@ fn clarity_texture_and_dehaze_with_shadows_highlights_and_per_pixel_stages() { cr! { clarity: 50.0, whites: -50.0, blacks: 45.0, exposure: -0.3}, cr! { texture: -60.0, whites: 30.0, blacks: -60.0}, ]; - check("clarity/texture/dehaze + shadows/highlights + per pixel", &sets); + check_at("clarity/texture/dehaze + shadows/highlights + per pixel", &sets, (171, 48)); let Some(mut g) = gpu() else { return }; // At the dialog's proxy width (Dehaze and Clarity on a copy subsampled twice), and wider (three // times). One depth per size: the depth only changes how the input is quantized (8 and 16 - // bits both develop with `float = false`), and every depth already ran above at 171×113. The + // bits both develop with `float = false`), and every depth already ran above at 171×48. The // long side sets the subsampling; the short one only needs to keep several pyramid levels, so // the frames are strips. for (size, depth) in [((858, 120), Depth::Eight), ((1600, 120), Depth::Float)] { From 83f391c3c9db253e84b39a6f97e8efa810e9781d Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:46:01 +0100 Subject: [PATCH 61/85] Reduce sparse resampling fixture --- crates/algo/src/resample/tests.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/algo/src/resample/tests.rs b/crates/algo/src/resample/tests.rs index f4406da0d2..0f4c9547ac 100644 --- a/crates/algo/src/resample/tests.rs +++ b/crates/algo/src/resample/tests.rs @@ -297,23 +297,23 @@ fn canvas_edges_repeat_instead_of_fading() { } } -/// Two tiles in opposite corners of a 100000 px square: the content bounds are huge but +/// Two tiles in opposite corners of a 20096 px square: the content bounds are huge but /// almost nothing is stored. Shrinking it to one pixel must neither allocate a window /// proportional to the scale (#713) nor read the empty middle. #[test] fn tiny_target_of_a_huge_sparse_source() { let mut s = Surface::new(PixelFormat::RGBA32F); s.fill_rect(Rect::new(0, 0, 256, 256), &[1.0, 1.0, 1.0, 1.0]); - s.fill_rect(Rect::new(99_840, 99_840, 100_096, 100_096), &[1.0, 1.0, 1.0, 1.0]); - let k = 1.0 / 100_096.0; + s.fill_rect(Rect::new(19_840, 19_840, 20_096, 20_096), &[1.0, 1.0, 1.0, 1.0]); + let k = 1.0 / 20_096.0; let o = resize_surface(&s, k, k, Resample::Bicubic); assert_eq!(o.content_bounds(), Rect::new(0, 0, 1, 1)); let p = o.pixel(0, 0); - // Two 256² tiles out of 100096²: nearly transparent, and white where it isn't. + // Two 256² tiles out of 20096²: nearly transparent, and white where it isn't. assert!(p[3] >= 0.0 && p[3] < 1e-3 && p.iter().all(|v| v.is_finite()), "{p:?}"); // Squashed to one row but kept wide: the whole height feeds one band of output rows, // which must not hold a full-height intermediate. - let o = resize_surface(&s, 1000.0 / 100_096.0, k, Resample::Bicubic); + let o = resize_surface(&s, 1000.0 / 20_096.0, k, Resample::Bicubic); let b = o.content_bounds(); assert!(b.height() == 1 && (1000..=1001).contains(&b.width()), "{b:?}"); assert!(o.pixel(0, 0)[3] > 0.0 && o.pixel(500, 0)[3] == 0.0, "{:?} {:?}", o.pixel(0, 0), o.pixel(500, 0)); From b43ffa380f185169056b251861867bf649874b0b Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:48:31 +0100 Subject: [PATCH 62/85] Borrow shared presets as a vector --- crates/ui-egui/src/panels/brush_panel/brushes.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/brush_panel/brushes.rs b/crates/ui-egui/src/panels/brush_panel/brushes.rs index e851181931..f4ae4a302c 100644 --- a/crates/ui-egui/src/panels/brush_panel/brushes.rs +++ b/crates/ui-egui/src/panels/brush_panel/brushes.rs @@ -109,7 +109,7 @@ pub(crate) fn tip_paint(b: &BrushSettings) -> impl Fn(&ContentPainterCx, Rect) + /// The rows of every preset in the engine's panel order (the order `,` and `.` step through): a /// group row before the first preset of each group and each folder, with its count. pub(crate) fn preset_rows(app: &PhotocraftApp, env: &Env, parts: BrushCardParts) -> Vec> { - let presets = &app.session.tools.presets; + let presets = app.session.tools.presets.as_ref(); let mut counts: std::collections::HashMap<(&str, &[String]), usize> = std::collections::HashMap::new(); for p in presets { let path = path_of(p); @@ -204,7 +204,7 @@ pub(crate) fn apply_events(app: &mut PhotocraftApp, events: Vec, rows: &[BrushKey]) -> Option<(&'static str, Value)> { - let presets = &app.session.tools.presets; + let presets = app.session.tools.presets.as_ref(); match event { PresetEvent::Select { key: BrushKey::Preset(name), .. } => Some(("tools.setBrush", json!({ "preset": name }))), // The double click's first click already picked it. From b0c0abee5490cc6be608cbc4fbc197778afa695e Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:56:44 +0100 Subject: [PATCH 63/85] Pair sharpen tile and format cases --- crates/algo/src/sharpen/tests.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/algo/src/sharpen/tests.rs b/crates/algo/src/sharpen/tests.rs index aef62259a3..f491c14f18 100644 --- a/crates/algo/src/sharpen/tests.rs +++ b/crates/algo/src/sharpen/tests.rs @@ -183,13 +183,17 @@ fn exact_tiled_selected_outputs_and_cancellation() { let mut sel = Surface::new(PixelFormat::GRAY8); sel.fill_rect(area, &[0.4]); sel.fill_rect(Rect::new(250, 250, 270, 265), &[1.0]); - for depth in SampleType::ALL { + for (di, depth) in SampleType::ALL.into_iter().enumerate() { let surface = source(bounds, PixelFormat::new(ColorMode::Rgb, depth, true)); - for radius in [0.6, 3.0, 10.0] { + for (ri, radius) in [0.6, 3.0, 10.0].into_iter().enumerate() { let p = crate::FilterParams::UnsharpMask { amount: 150.0, radius, threshold: 8.0 }; for extent in [None, Some(bounds)] { let expected = apply_reference(&surface, &p, area, bounds, Some(&sel), extent, 256); - for tile in [63, 256, 512] { + // Keep every depth/radius, depth/tile and radius/tile pair, with both extents. + for (ti, tile) in [63, 256, 512].into_iter().enumerate() { + if ti != (di + ri) % 3 { + continue; + } let actual = crate::apply_tiled(&surface, &p, area, bounds, Some(&sel), tile, extent); assert_eq!(expected.to_interleaved(bounds), actual.to_interleaved(bounds)); } From 378fda83b0bc9f28a5000949abee59bfcb1d1a93 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 10:02:15 +0100 Subject: [PATCH 64/85] Pair extrude sweep fixture axes --- crates/algo/src/stylize2/tests.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/algo/src/stylize2/tests.rs b/crates/algo/src/stylize2/tests.rs index 4751511e62..17c70df860 100644 --- a/crates/algo/src/stylize2/tests.rs +++ b/crates/algo/src/stylize2/tests.rs @@ -44,8 +44,11 @@ fn swept_blocks_match_the_pixel_search_part(part: u64) { let repeat = !seen.insert((n, alpha, mode == ColorMode::Cmyk)); for kind in 0..5 { let src = image(bounds.inflate(20), n, kind); - for (size, depth) in [(2.0, 0.0), (2.0, 255.0), (3.5, 190.0), (8.0, 64.0), (22.0, 255.0), (255.0, 100.0)] { - for flags in (0..8).filter(|f| !repeat || f & 1 != 0) { + for (si, (size, depth)) in [(2.0, 0.0), (2.0, 255.0), (3.5, 190.0), (8.0, 64.0), (22.0, 255.0), (255.0, 100.0)].into_iter().enumerate() { + // For distinct channel layouts each kind and size sees every flag + // combination. Repeated layouts keep one level-based case per pair. + let first = (kind + si) % 8; + for flags in (0..8).filter(|f| (!repeat || f & 1 != 0) && (*f == first || *f == (first + 3) % 8)) { case += 1; if !sweep.includes(case) { continue; From 52a5293663e66f4df212729cfa3892a1a2ddc8d4 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 10:08:25 +0100 Subject: [PATCH 65/85] Reuse content-aware crop scenes --- .../engine/tests/it/crop_content_aware_layers.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/engine/tests/it/crop_content_aware_layers.rs b/crates/engine/tests/it/crop_content_aware_layers.rs index 24f407ee3a..df7bf506b9 100644 --- a/crates/engine/tests/it/crop_content_aware_layers.rs +++ b/crates/engine/tests/it/crop_content_aware_layers.rs @@ -134,8 +134,8 @@ fn undo_redo(s: &mut Session, before: &Document) { /// Matches the three measured rows: bounds and sample points, at half the measured size. #[test] fn measured_straight_rows_fill_background_and_only_the_active_raster() { + let (mut s, ids) = scene(); for row in 0..3 { - let (mut s, ids) = scene(); let active = if row == 1 { ids.edge } else { ids.quads }; if row == 2 { s.edit("Layer 0", |d, _| { @@ -172,6 +172,8 @@ fn measured_straight_rows_fill_background_and_only_the_active_raster() { unchanged(d, &plain, &untouched); named_one_step(&s, past, "Content-aware Crop"); undo_redo(&mut s, &before); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(doc(&s), &before); } } @@ -179,8 +181,9 @@ fn measured_straight_rows_fill_background_and_only_the_active_raster() { #[test] fn turned_rows_sample_each_target_and_leave_other_layers_at_plain_crop() { let (x, y) = extension_sample(); + let (mut s, ids) = scene(); + let original = doc(&s).clone(); for row in 0..3 { - let (mut s, ids) = scene(); // Uniform donors isolate target selection from the existing turned-fill sampling policy. s.edit("Uniform Quads", |d, _| { let fmt = d.pixel_format(); @@ -213,15 +216,20 @@ fn turned_rows_sample_each_target_and_leave_other_layers_at_plain_crop() { unchanged(d, &plain, &untouched); named_one_step(&s, past, "Content-aware Crop"); undo_redo(&mut s, &before); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(doc(&s), &before); + s.execute("edit.undo", json!({})).unwrap(); // Restore the scene before the uniform edit. + assert_eq!(doc(&s), &original); } } /// Selecting the Background leaves each other layer identical to its plain crop. #[test] fn background_active_is_not_a_second_target() { + let (mut s, ids) = scene(); + let original = doc(&s).clone(); for turned in [false, true] { let (x, y) = extension_sample(); - let (mut s, ids) = scene(); select(&mut s, ids.background); let p = frame(turned); let plain = plain_control(&mut s, &p); @@ -230,6 +238,8 @@ fn background_active_is_not_a_second_target() { pixel(doc(&s), ids.background, x, y, WHITE); unchanged(doc(&s), &plain, &[ids.quads, ids.small, ids.edge, ids.hidden, ids.text]); named_one_step(&s, past, "Content-aware Crop"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(doc(&s), &original); } } From 931ec750c010f821aabca63b374cca90f68fda02 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 10:27:10 +0100 Subject: [PATCH 66/85] Keep color move reference fixture --- .../src/cmd/retouch_cmds/content_aware_move_color_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs b/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs index 8375889a98..57e99d3898 100644 --- a/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs @@ -43,9 +43,9 @@ fn checker(x: i32, y: i32) -> Option { } } -/// 640×460. Grey to the left of x=400, green to the right, with an 80×80 checker at (100, 100). +/// 800×600. Left half grey, right half green, with the 80×80 checker at (100, 100). fn green_doc() -> Session { - let mut s = session(640, 460); + let mut s = session(800, 600); paint(&mut s, |x, y| { if let Some(v) = checker(x, y) { [v, v, v] From 8ff1a1862e53062a3c1f353a78e484dbed728588 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 09:30:58 +0000 Subject: [PATCH 67/85] ci: the cache prune lists main's entries only --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8a0af37391..9cffda4e94 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -264,7 +264,7 @@ jobs: run: | set -euo pipefail # `-rust---crates-----...`, newest first. - gh cache list --repo "$REPO" --limit 100 --sort created_at --order desc --json id,key \ + gh cache list --repo "$REPO" --ref refs/heads/main --limit 100 --sort created_at --order desc --json id,key \ --jq '.[] | "\(.id) \(.key)"' > "$RUNNER_TEMP/caches" declare -A kept while read -r id key; do From a8f95bd16d9917cf658a36f36f3bd0c9564c2ade Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 10:07:19 +0000 Subject: [PATCH 68/85] Document layer index and index-ordered selection (#15704) Document.layers is a LayerTree that builds an id index on first lookup and drops it on any mutable access. Layer lookups and selected_layers use the index instead of walking the document. --- crates/compose/src/cmyk/tests.rs | 3 +- crates/compose/src/stroke_tests.rs | 4 +- crates/compose/src/tests.rs | 10 +- crates/doc/src/layer_tree.rs | 227 ++++++++++++++++++ crates/doc/src/lib.rs | 49 ++-- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/adjust_cmds.rs | 2 +- crates/engine/src/cmd/artboard_cmds.rs | 2 +- crates/engine/src/cmd/background_cmds.rs | 2 +- crates/engine/src/cmd/channel_cmds/spot.rs | 2 +- crates/engine/src/cmd/channel_cmds/tests.rs | 2 +- crates/engine/src/cmd/color_cmds.rs | 2 +- crates/engine/src/cmd/edit_cmds.rs | 2 +- crates/engine/src/cmd/file_cmds/export.rs | 2 +- crates/engine/src/cmd/file_cmds/processing.rs | 8 +- crates/engine/src/cmd/file_cmds/save.rs | 2 +- crates/engine/src/cmd/history_cmds.rs | 6 +- crates/engine/src/cmd/image_cmds.rs | 2 +- .../engine/src/cmd/layer_label_cmds/tests.rs | 2 +- crates/engine/src/cmd/layer_menu_cmds.rs | 4 +- .../engine/src/cmd/layer_menu_cmds/tests.rs | 2 +- crates/engine/src/cmd/layer_xmp_cmds/tests.rs | 2 +- crates/engine/src/cmd/mode_cmds.rs | 2 +- crates/engine/src/cmd/multichannel_cmds.rs | 2 +- crates/engine/src/cmd/ops.rs | 2 +- crates/engine/src/cmd/rasterize_style_cmds.rs | 2 +- crates/engine/src/cmd/sample_cmds.rs | 2 +- crates/engine/src/cmd/smart_cmds/placing.rs | 2 +- crates/engine/src/cmd/smart_cmds/source.rs | 2 +- .../src/cmd/smart_cmds/tests/selection.rs | 14 +- .../cmd/smart_cmds/tests/source_flatten.rs | 4 +- .../src/cmd/smart_cmds/tests/svg_profile.rs | 2 +- crates/engine/src/cmd/smart_cmds/unpack.rs | 2 +- crates/engine/src/cmd/stamp_cmds.rs | 2 +- crates/engine/src/cmd/vector_clipboard.rs | 4 +- crates/engine/src/cmd/web_cmds/tests.rs | 4 +- crates/engine/src/doc_state.rs | 66 ++++- crates/engine/src/inspect.rs | 2 +- crates/engine/src/layer_place.rs | 2 +- crates/engine/src/pixels.rs | 2 +- crates/engine/tests/it/atn_newer_events.rs | 2 +- crates/engine/tests/it/atn_stack_modes.rs | 2 +- .../tests/it/convert_profile_options.rs | 2 +- .../engine/tests/it/export_shape_strokes.rs | 2 +- .../tests/it/image_size_scale_styles.rs | 2 +- crates/format/src/convert.rs | 2 +- crates/format/tests/it/roundtrip.rs | 4 +- crates/gpu/src/plan/tests.rs | 2 +- crates/gpu/src/prefix.rs | 2 +- crates/gpu/tests/it/parity.rs | 10 +- crates/io/src/affinity.rs | 2 +- crates/io/src/exr_parts.rs | 2 +- crates/io/src/flat.rs | 18 +- crates/io/src/kra.rs | 2 +- crates/io/src/ora.rs | 2 +- crates/io/src/ora/tests.rs | 4 +- crates/io/src/pdf/tests.rs | 8 +- crates/io/src/psd_import.rs | 2 +- crates/io/src/psd_import/tests.rs | 4 +- crates/io/src/svg.rs | 2 +- crates/io/src/xcf.rs | 2 +- crates/io/tests/it/artboard_guide_order.rs | 2 +- crates/io/tests/it/comps_artboards.rs | 2 +- crates/io/tests/it/roundtrip.rs | 14 +- crates/ui-egui/examples/interactive_bench.rs | 4 +- .../ui-egui/src/tools/transform_tool/tests.rs | 2 +- crates/ui-egui/tests/support/layout_doc.rs | 2 +- 67 files changed, 432 insertions(+), 129 deletions(-) create mode 100644 crates/doc/src/layer_tree.rs diff --git a/crates/compose/src/cmyk/tests.rs b/crates/compose/src/cmyk/tests.rs index eee79ac0d9..2e8292f8c0 100644 --- a/crates/compose/src/cmyk/tests.rs +++ b/crates/compose/src/cmyk/tests.rs @@ -1704,7 +1704,8 @@ fn normal_onto_nothing_is_exact() { }; let mut d = doc(4, 6); d.layers = - vec![build(&LayerSpec::Group { children: vec![shape, inv], pass_through: false, blend: BlendMode::Normal, opacity: 1.0, fill: 1.0, mask: None })]; + vec![build(&LayerSpec::Group { children: vec![shape, inv], pass_through: false, blend: BlendMode::Normal, opacity: 1.0, fill: 1.0, mask: None })] + .into(); assert_matches_reference(&d); assert_eq!(render1(&d, 0, 0)[..4], [0.0; 4]); } diff --git a/crates/compose/src/stroke_tests.rs b/crates/compose/src/stroke_tests.rs index 3608327628..3800441d1e 100644 --- a/crates/compose/src/stroke_tests.rs +++ b/crates/compose/src/stroke_tests.rs @@ -170,10 +170,10 @@ fn a_stroked_shapes_mask_applies_to_fill_and_stroke_together() { assert!(close4(p, [0.0, 1.0, 0.0, 0.5]), "{p:?}"); // With effects too. l.effects.items = vec![Effect::ColorOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), color: Color::rgb(1.0, 1.0, 1.0) }]; - d.layers = vec![l.clone()]; + d.layers = vec![l.clone()].into(); let p = px(&d, 12, 20); assert!(close4(p, [0.0, 1.0, 0.0, 0.5]), "without clipped layers: {p:?}"); - d.layers = vec![l, clip]; + d.layers = vec![l, clip].into(); let p = px(&d, 12, 20); assert!(close4(p, [0.0, 1.0, 0.0, 0.5]), "{p:?}"); } diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index e281204b00..b7375afa8e 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -404,7 +404,7 @@ fn every_blend_mode_matches_reference_on_opaque_pixels() { let mut top = Layer::raster("t", PixelFormat::RGBA32F); top.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 2, 2), &source); top.blend = mode; - d.layers = vec![bottom, top]; + d.layers = vec![bottom, top].into(); let got = px(&d, 0, 0); // A 32-bit document: Add / Divide don't clip at 1 (Divide gives 0.6 / 0.2 = 3 in red). psblend::HDR.with(|h| h.set(true)); @@ -434,7 +434,7 @@ fn full_coverage_adjustment_keeps_its_result_over_huge_hdr_values() { dither: false, source: None, }; - d.layers = vec![base, Layer::new("look", LayerContent::Adjustment(look))]; + d.layers = vec![base, Layer::new("look", LayerContent::Adjustment(look))].into(); let got = px(&d, 0, 0); for c in &got[..3] { assert!((c - 0.5).abs() < 1e-6, "{v}: {got:?}"); @@ -479,7 +479,7 @@ fn blend_px(depth: SampleType, mode: BlendMode, bottom: [f32; 3], top: [f32; 3]) let mut t = Layer::raster("t", fmt); t.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 1, 1), &photocraft_raster::from_rgba(&fmt, [top[0], top[1], top[2], 1.0])); t.blend = mode; - d.layers = vec![b, t]; + d.layers = vec![b, t].into(); px(&d, 0, 0) } @@ -3294,7 +3294,7 @@ fn exposure_scales_32_bit_samples_as_stored() { let mut d = Document::new("e", Size::new(1, 1), ColorMode::Rgb, depth); let mut l = Layer::raster("px", fmt); l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 1, 1), &[0.2, 0.2, 0.2, 1.0]); - d.layers = vec![l, Layer::new("exp", LayerContent::Adjustment(plus_one_stop.clone()))]; + d.layers = vec![l, Layer::new("exp", LayerContent::Adjustment(plus_one_stop.clone()))].into(); let got = px(&d, 0, 0)[0]; assert!((got - want).abs() < 2e-3, "{depth:?}: {got}"); } @@ -3384,7 +3384,7 @@ fn float_adjustments_preserve_hdr_range() { let mut d = Document::new("HDR", Size::new(1, 1), ColorMode::Rgb, SampleType::F32); let mut l = Layer::raster("pixels", PixelFormat::RGBA32F); l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 1, 1), &[4.0, 2.0, 0.5, 0.75]); - d.layers = vec![l, Layer::new("adjustment", LayerContent::Adjustment(adj.clone()))]; + d.layers = vec![l, Layer::new("adjustment", LayerContent::Adjustment(adj.clone()))].into(); let got = px(&d, 0, 0); for (a, b) in got[..3].iter().zip(want) { assert!((a - b).abs() < 1e-5, "{adj:?}: {got:?} vs {want:?}"); diff --git a/crates/doc/src/layer_tree.rs b/crates/doc/src/layer_tree.rs new file mode 100644 index 0000000000..ce7549738c --- /dev/null +++ b/crates/doc/src/layer_tree.rs @@ -0,0 +1,227 @@ +//! The document's layer stack with a lazily built id index. + +use std::collections::HashMap; +use std::ops::{Deref, DerefMut}; +use std::sync::OnceLock; + +use crate::{Layer, LayerId, LayerPath}; + +/// Where a layer sits in the stack. +#[derive(Clone, Debug)] +struct Entry { + path: LayerPath, + parent: Option, +} + +/// Id to position for every layer, nested ones included. +#[derive(Debug, Default)] +pub struct LayerIndex { + entries: HashMap, + serial: u64, +} + +static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +impl LayerIndex { + fn build(layers: &[Layer]) -> Self { + fn rec(layers: &[Layer], parent: Option, path: &mut LayerPath, out: &mut HashMap) { + for (i, l) in layers.iter().enumerate() { + path.push(i); + out.entry(l.id).or_insert_with(|| Entry { path: path.clone(), parent }); + if let Some(ch) = l.children() { + rec(ch, Some(l.id), path, out); + } + path.pop(); + } + } + let mut entries = HashMap::with_capacity(layers.len()); + rec(layers, None, &mut Vec::new(), &mut entries); + Self { entries, serial: SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } + } + + /// The layer's path from the root. Paths order layers bottom-to-top as the depth-first walk does. + pub fn path(&self, id: LayerId) -> Option<&[usize]> { + self.entries.get(&id).map(|e| e.path.as_slice()) + } + + /// The group holding the layer; `None` at the root or for an unknown id. + pub fn parent(&self, id: LayerId) -> Option { + self.entries.get(&id)?.parent + } + + /// Nesting depth: 0 at the root. + pub fn depth(&self, id: LayerId) -> Option { + self.entries.get(&id).map(|e| e.path.len() - 1) + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// A number unique to this build: it differs between two builds, so equal serials mean the + /// same index (tests count rebuilds with it). + pub fn serial(&self) -> u64 { + self.serial + } +} + +/// The layer stack, bottom-to-top, with an index from layer id to position built on the first +/// lookup. +/// +/// The stack is a public vector that code edits in place, nested groups included, so no mutator +/// method can be the place that drops the index. Every route to a `&mut Layer` or `&mut Vec` +/// goes through `DerefMut`, so the reset lives there: any write drops the index, and the next +/// lookup rebuilds it once. `Clone` starts without an index. +#[derive(Default)] +pub struct LayerTree { + layers: Vec, + index: OnceLock, +} + +impl LayerTree { + /// The id index, built on first use after the last write. + pub fn index(&self) -> &LayerIndex { + self.index.get_or_init(|| LayerIndex::build(&self.layers)) + } +} + +/// `Vec` methods that callers pass `&document` into (`doc.layers.push(make(&doc))`): as methods +/// on the tree the receiver borrow is two-phase, which it is not through `DerefMut`. +impl LayerTree { + pub fn push(&mut self, layer: Layer) { + self.deref_mut().push(layer); + } + + pub fn insert(&mut self, at: usize, layer: Layer) { + self.deref_mut().insert(at, layer); + } +} + +impl Deref for LayerTree { + type Target = Vec; + fn deref(&self) -> &Vec { + &self.layers + } +} + +impl DerefMut for LayerTree { + fn deref_mut(&mut self) -> &mut Vec { + self.index = OnceLock::new(); + &mut self.layers + } +} + +impl Clone for LayerTree { + fn clone(&self) -> Self { + Self { layers: self.layers.clone(), index: OnceLock::new() } + } +} + +impl PartialEq for LayerTree { + fn eq(&self, other: &Self) -> bool { + self.layers == other.layers + } +} + +impl std::fmt::Debug for LayerTree { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.layers.fmt(f) + } +} + +impl From> for LayerTree { + fn from(layers: Vec) -> Self { + Self { layers, index: OnceLock::new() } + } +} + +impl<'a> IntoIterator for &'a LayerTree { + type Item = &'a Layer; + type IntoIter = std::slice::Iter<'a, Layer>; + fn into_iter(self) -> Self::IntoIter { + self.layers.iter() + } +} + +impl<'a> IntoIterator for &'a mut LayerTree { + type Item = &'a mut Layer; + type IntoIter = std::slice::IterMut<'a, Layer>; + fn into_iter(self) -> Self::IntoIter { + self.deref_mut().iter_mut() + } +} + +impl FromIterator for LayerTree { + fn from_iter>(iter: I) -> Self { + iter.into_iter().collect::>().into() + } +} + +impl IntoIterator for LayerTree { + type Item = Layer; + type IntoIter = std::vec::IntoIter; + fn into_iter(self) -> Self::IntoIter { + self.layers.into_iter() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::PixelFormat; + + fn layers(n: usize) -> LayerTree { + (0..n).map(|i| Layer::raster(format!("l{i}"), PixelFormat::RGBA8)).collect() + } + + #[test] + fn index_builds_once_per_edit() { + let mut t = layers(200); + let id = t[150].id; + let first = t.index().serial(); + for _ in 0..100 { + assert_eq!(t.index().path(id), Some(&[150][..])); + } + assert_eq!(t.index().serial(), first, "lookups reuse the index"); + t.push(Layer::raster("new", PixelFormat::RGBA8)); + let second = t.index().serial(); + assert_ne!(second, first, "an edit rebuilds it"); + assert_eq!(t.index().serial(), second); + let _ = &mut t[3]; + assert_ne!(t.index().serial(), second, "any mutable access drops it"); + } + + #[test] + fn clone_after_edit_does_not_reuse_the_index() { + let mut t = layers(5); + let old = t.index().serial(); + let new_id = { + t.insert(0, Layer::raster("below", PixelFormat::RGBA8)); + t[0].id + }; + let c = t.clone(); + assert_ne!(c.index().serial(), old); + assert_eq!(c.index().path(new_id), Some(&[0][..])); + assert_eq!(t.index().path(new_id), Some(&[0][..])); + } + + #[test] + fn nested_edits_reset_and_paths_follow_walk_order() { + let inner = Layer::raster("in", PixelFormat::RGBA8); + let inner_id = inner.id; + let group = Layer::group("g", vec![inner]); + let group_id = group.id; + let mut t: LayerTree = vec![Layer::raster("a", PixelFormat::RGBA8), group].into(); + assert_eq!(t.index().path(inner_id), Some(&[1, 0][..])); + assert_eq!(t.index().parent(inner_id), Some(group_id)); + assert_eq!(t.index().depth(inner_id), Some(1)); + let before = t.index().serial(); + t[1].children_mut().unwrap().insert(0, Layer::raster("x", PixelFormat::RGBA8)); + assert_eq!(t.index().path(inner_id), Some(&[1, 1][..])); + assert_ne!(t.index().serial(), before); + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index d7a87ff756..523bdc16fa 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -16,6 +16,7 @@ pub mod comps; pub mod effects; pub mod frame; pub mod import_conversion; +pub mod layer_tree; pub mod mode; pub mod pattern; pub mod slices; @@ -901,7 +902,7 @@ pub struct Document { pub depth: SampleType, pub icc_profile: Option>>, /// Bottom-to-top. - pub layers: Vec, + pub layers: layer_tree::LayerTree, pub channels: Vec, pub guides: Guides, /// The rulers' zero point in document pixels (`[x, y]`), dragged from the ruler corner. The @@ -1004,7 +1005,7 @@ impl Document { mode, depth, icc_profile: None, - layers: Vec::new(), + layers: Default::default(), channels: Vec::new(), guides: Guides::default(), ruler_origin: [0.0, 0.0], @@ -1161,18 +1162,7 @@ impl Document { } pub fn path_of(&self, id: LayerId) -> Option { - fn rec(layers: &[Layer], id: LayerId, path: &mut LayerPath) -> bool { - for (i, l) in layers.iter().enumerate() { - path.push(i); - if l.id == id || l.children().is_some_and(|ch| rec(ch, id, path)) { - return true; - } - path.pop(); - } - false - } - let mut path = Vec::new(); - rec(&self.layers, id, &mut path).then_some(path) + self.layers.index().path(id).map(<[usize]>::to_vec) } /// The locks in force on the layer at `path`: its own and those of every group around it, @@ -1211,10 +1201,7 @@ impl Document { } pub fn layer(&self, id: LayerId) -> Option<&Layer> { - fn rec(layers: &[Layer], id: LayerId) -> Option<&Layer> { - layers.iter().find_map(|l| if l.id == id { Some(l) } else { l.children().and_then(|ch| rec(ch, id)) }) - } - rec(&self.layers, id) + self.layer_at(self.layers.index().path(id)?) } pub fn layer_mut(&mut self, id: LayerId) -> Option<&mut Layer> { @@ -1394,6 +1381,32 @@ mod tests { assert_eq!(d.unused_link_group(), Some(3)); } + /// Id lookups share one index per document state: 100 lookups on 200 layers build it once, + /// an edit builds it once more, and a clone built after the edit has its own. + #[test] + fn layer_lookups_share_one_index_per_state() { + let mut d = doc(); + for i in 0..199 { + d.layers.push(Layer::raster(format!("l{i}"), PixelFormat::RGBA8)); + } + let ids: Vec = d.layers.iter().map(|l| l.id).collect(); + let first = d.layers.index().serial(); + for i in 0..100 { + let id = ids[i * 2]; + assert_eq!(d.layer(id).unwrap().id, id); + assert_eq!(d.path_of(id), Some(vec![i * 2])); + } + assert_eq!(d.layers.index().serial(), first); + assert!(d.shift(ids[10], 1)); + assert_eq!(d.path_of(ids[10]), Some(vec![11])); + let second = d.layers.index().serial(); + assert_ne!(second, first); + d.layer_mut(ids[3]).unwrap().name = "x".into(); + let copy = d.clone(); + assert_ne!(copy.layers.index().serial(), d.layers.index().serial()); + assert_eq!(copy.layer(ids[3]).unwrap().name, "x"); + } + #[test] fn new_document_has_locked_background() { let d = doc(); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c2d10acae7..3f3ee0c378 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -894,7 +894,7 @@ fn build() -> Vec { bg.locks.position = true; *crate::pixels_mut(&mut bg)? = photocraft_compose::flatten_to_surface(doc, fmt, Some([1.0, 1.0, 1.0])); *active = Some(bg.id); - doc.layers = vec![bg]; + doc.layers = vec![bg].into(); Ok(()) })?; Ok(Value::Null) diff --git a/crates/engine/src/cmd/adjust_cmds.rs b/crates/engine/src/cmd/adjust_cmds.rs index 6c97430d50..f7dd8925bd 100644 --- a/crates/engine/src/cmd/adjust_cmds.rs +++ b/crates/engine/src/cmd/adjust_cmds.rs @@ -652,7 +652,7 @@ fn hdr_toning(s: &mut Session, p: &Value) -> Result { bg.locks.position = true; crate::pixels_mut(&mut bg)?.write_region(doc.bounds(), &data); *active = Some(bg.id); - doc.layers = vec![bg]; + doc.layers = vec![bg].into(); doc.selection = None; Ok(()) })?; diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 55966ce97a..af62d62696 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -643,7 +643,7 @@ pub fn artboard_document(doc: &Document, id: LayerId) -> Result let mut one = doc.clone(); one.name = l.name.clone(); one.size = Size::new(r.width(), r.height()); - one.layers = vec![group]; + one.layers = vec![group].into(); one.channels.clear(); one.selection = None; one.quick_mask = None; diff --git a/crates/engine/src/cmd/background_cmds.rs b/crates/engine/src/cmd/background_cmds.rs index 0c067b3842..f5d2ffbf3d 100644 --- a/crates/engine/src/cmd/background_cmds.rs +++ b/crates/engine/src/cmd/background_cmds.rs @@ -69,7 +69,7 @@ fn background_from_layer(s: &mut Session, p: &Value) -> Result { only.clipped = false; let visible = l.visible; let fmt = doc.pixel_format(); - let rest = std::mem::replace(&mut doc.layers, vec![only]); + let rest = std::mem::replace(&mut doc.layers, vec![only].into()); let pixels = photocraft_compose::flatten_to_surface(doc, fmt, Some([bg[0], bg[1], bg[2]])); doc.layers = rest; let mut out = Layer::raster("Background", fmt); diff --git a/crates/engine/src/cmd/channel_cmds/spot.rs b/crates/engine/src/cmd/channel_cmds/spot.rs index 74b227d8d4..23ae600c79 100644 --- a/crates/engine/src/cmd/channel_cmds/spot.rs +++ b/crates/engine/src/cmd/channel_cmds/spot.rs @@ -43,7 +43,7 @@ pub(super) fn merge_spot(s: &mut Session, p: &Value) -> Result { sf.prune(); } let id = bg.id; - doc.layers = vec![bg]; + doc.layers = vec![bg].into(); doc.channels.remove(i); *active = Some(id); Ok(()) diff --git a/crates/engine/src/cmd/channel_cmds/tests.rs b/crates/engine/src/cmd/channel_cmds/tests.rs index f198fccde6..65ee637059 100644 --- a/crates/engine/src/cmd/channel_cmds/tests.rs +++ b/crates/engine/src/cmd/channel_cmds/tests.rs @@ -1259,7 +1259,7 @@ fn split_refuses_an_image_with_more_than_one_layer() { assert_eq!(s.execute("channel.split", json!({})).unwrap()["documents"].as_array().unwrap().len(), 3); // A lone group is a layer the split would lose. let mut s = session(); - std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).layers = vec![Layer::group("Group 1", vec![])]; + std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).layers = vec![Layer::group("Group 1", vec![])].into(); assert!(!s.is_enabled("channel.split")); assert!(s.execute("channel.split", json!({})).is_err()); assert_eq!(s.documents().len(), 1); diff --git a/crates/engine/src/cmd/color_cmds.rs b/crates/engine/src/cmd/color_cmds.rs index 96fe367ea4..ce069c131c 100644 --- a/crates/engine/src/cmd/color_cmds.rs +++ b/crates/engine/src/cmd/color_cmds.rs @@ -1116,7 +1116,7 @@ fn flatten_for_profile(doc: &mut Document, active: &mut Option Result { out.push(l); } } - doc.layers = out; + doc.layers = out.into(); *active = Some(mid); Ok(()) })?; diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index b1cdbe0f62..abb4425033 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -77,7 +77,7 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& let mut only = l.clone(); only.visible = true; only.clipped = false; - one.layers = vec![only]; + one.layers = vec![only].into(); if trim { let mut bounds = Rect::EMPTY; let _ = photocraft_compose::render_bands(&one, one.bounds(), 0, |band| -> std::result::Result<(), ()> { diff --git a/crates/engine/src/cmd/file_cmds/processing.rs b/crates/engine/src/cmd/file_cmds/processing.rs index 5e0d6b2ddb..5438a52a73 100644 --- a/crates/engine/src/cmd/file_cmds/processing.rs +++ b/crates/engine/src/cmd/file_cmds/processing.rs @@ -304,9 +304,9 @@ pub(super) fn load_files_into_stack(s: &mut Session, p: &Value) -> Result // "Create Smart Object after Loading Layers": the layers go inside one smart object, ready // for Layer › Smart Objects › Stack Mode. Like Photoshop, they sit at the top level of the // contents, with no wrapper group. - let layers = std::mem::take(&mut stack.layers); + let layers = std::mem::take(&mut *stack.layers); let smart = crate::smart_cmds::layers_to_smart(&stack, &smart_name, layers)?; - stack.layers = vec![smart]; + stack.layers = vec![smart].into(); } let i = s.add_document(stack, None); if align { @@ -314,10 +314,10 @@ pub(super) fn load_files_into_stack(s: &mut Session, p: &Value) -> Result s.execute("edit.autoAlignLayers", json!({"projection": "auto"}))?; if smart { s.edit("Convert to Smart Object", |doc, active| { - let layers = std::mem::take(&mut doc.layers); + let layers = std::mem::take(&mut *doc.layers); let smart = crate::smart_cmds::layers_to_smart(doc, &smart_name, layers)?; *active = Some(smart.id); - doc.layers = vec![smart]; + doc.layers = vec![smart].into(); Ok(()) })?; if let Some(st) = s.active_mut() { diff --git a/crates/engine/src/cmd/file_cmds/save.rs b/crates/engine/src/cmd/file_cmds/save.rs index eba2b9502d..4b8eef165f 100644 --- a/crates/engine/src/cmd/file_cmds/save.rs +++ b/crates/engine/src/cmd/file_cmds/save.rs @@ -312,7 +312,7 @@ pub(super) fn save_a_copy(s: &mut Session, p: &Value) -> Result { // "Layers" unchecked in Save a Copy: write the flattened image. let fmt = doc.pixel_format(); let px = flattened_checked(&doc, fmt, "file.saveACopy")?; - doc.layers = vec![Layer::new("Background", LayerContent::Raster(px))]; + doc.layers = vec![Layer::new("Background", LayerContent::Raster(px))].into(); } let warnings = save_doc(&doc, &path, SaveOpts::from_params(s, p, "file.saveACopy")?)?; Ok(json!({"path": path, "warnings": warnings})) diff --git a/crates/engine/src/cmd/history_cmds.rs b/crates/engine/src/cmd/history_cmds.rs index 2717465db5..30d8528545 100644 --- a/crates/engine/src/cmd/history_cmds.rs +++ b/crates/engine/src/cmd/history_cmds.rs @@ -145,7 +145,7 @@ fn new_snapshot(s: &mut Session, p: &Value) -> Result { let one_layer = |doc: &Document, layer: Layer| { let mut doc = doc.clone(); let id = layer.id; - doc.layers = vec![layer]; + doc.layers = vec![layer].into(); (Arc::new(doc), LayerTarget { active: Some(id), selected: vec![id] }) }; let (doc, layers) = match from { @@ -525,7 +525,7 @@ mod tests { assert_eq!(st.memory_bytes(), base + flat); // Room for the document's tiles and four fill tiles. let cur = tile_bytes(&st.doc); - let fill = tile_bytes(&Document { layers: st.doc.layers[1..].to_vec(), ..(*st.doc).clone() }); + let fill = tile_bytes(&Document { layers: st.doc.layers[1..].to_vec().into(), ..(*st.doc).clone() }); assert!(flat <= fill, "the flattened tile is no bigger than a fill's"); let budget = cur + 4 * fill; for s in [&mut with, &mut without] { @@ -549,7 +549,7 @@ mod tests { s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); let st = s.active().unwrap(); // The snapshot's green layer tile, now only in it and the last state. - let shared = tile_bytes(&Document { layers: st.snapshots.last().unwrap().doc.layers[1..].to_vec(), ..(*st.doc).clone() }); + let shared = tile_bytes(&Document { layers: st.snapshots.last().unwrap().doc.layers[1..].to_vec().into(), ..(*st.doc).clone() }); let all = st.history.unique_bytes(&st.doc); let r = s.execute("edit.purge.histories", json!({})).unwrap(); assert_eq!(r["bytes"], json!(all - shared), "the green tile stays with the snapshot"); diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index 571f4754ac..55b45e9707 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -1213,7 +1213,7 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { let mut merged = Layer::new(if has_background { "Background" } else { "Layer 1" }, LayerContent::Raster(surf)); merged.locks.transparency = has_background; merged.locks.position = has_background; - doc.layers = vec![merged]; + doc.layers = vec![merged].into(); // A merged-only copy has no original layers for saved comps to restore. // Don't carry dangling comp state into a single-layer flattened document. doc.layer_comps.clear(); diff --git a/crates/engine/src/cmd/layer_label_cmds/tests.rs b/crates/engine/src/cmd/layer_label_cmds/tests.rs index 3288c5aebf..b7cb432286 100644 --- a/crates/engine/src/cmd/layer_label_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_label_cmds/tests.rs @@ -21,7 +21,7 @@ fn fixture(depth: u8) -> (Session, [LayerId; 4]) { let outer_id = outer.id; let other = Layer::raster("Other", doc.pixel_format()); let other_id = other.id; - doc.layers = vec![outer, other]; + doc.layers = vec![outer, other].into(); Ok([outer_id, inner_id, leaf_id, other_id]) }) .unwrap(); diff --git a/crates/engine/src/cmd/layer_menu_cmds.rs b/crates/engine/src/cmd/layer_menu_cmds.rs index 944b6755c6..252c41930f 100644 --- a/crates/engine/src/cmd/layer_menu_cmds.rs +++ b/crates/engine/src/cmd/layer_menu_cmds.rs @@ -876,7 +876,7 @@ fn create_layer(s: &mut Session, p: &Value) -> Result { let mut tmp = Document::new("fx", doc.size, doc.mode, doc.depth); tmp.global_light = light; tmp.patterns = doc.patterns.clone(); - tmp.layers = vec![alone]; + tmp.layers = vec![alone].into(); let buf = photocraft_compose::render(&tmp, area); let mut surf = Surface::new(fmt); let data: Vec = buf.px.iter().flat_map(|q| photocraft_raster::from_rgba(&fmt, *q)).collect(); @@ -952,7 +952,7 @@ pub fn layer_document(doc: &Document, id: LayerId) -> Result { alone.blend = if alone.is_group() { BlendMode::PassThrough } else { BlendMode::Normal }; alone.clipped = false; let mut tmp = doc.clone(); - tmp.layers = vec![alone]; + tmp.layers = vec![alone].into(); tmp.selection = None; let area = doc.bounds(); let buf = photocraft_compose::render(&tmp, area); diff --git a/crates/engine/src/cmd/layer_menu_cmds/tests.rs b/crates/engine/src/cmd/layer_menu_cmds/tests.rs index 0dcd7c2333..8efe428398 100644 --- a/crates/engine/src/cmd/layer_menu_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_menu_cmds/tests.rs @@ -548,7 +548,7 @@ fn stack_modes_render_from_the_nested_layers() { let g = Layer::new("stack", LayerContent::Group(photocraft_doc::Group { children: kids, expanded: true, artboard: None, frame_stroke: None })); let smart = crate::smart_cmds::layer_to_smart(doc, &g)?; let id = smart.id; - doc.layers = vec![smart]; + doc.layers = vec![smart].into(); *active = Some(id); Ok(()) }) diff --git a/crates/engine/src/cmd/layer_xmp_cmds/tests.rs b/crates/engine/src/cmd/layer_xmp_cmds/tests.rs index 5fb67ad13c..cacad97308 100644 --- a/crates/engine/src/cmd/layer_xmp_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_xmp_cmds/tests.rs @@ -11,7 +11,7 @@ fn fixture(depth: u8) -> (Session, LayerId, LayerId) { let a = Layer::raster("A", doc.pixel_format()); let b = Layer::group("B", vec![Layer::raster("Child", doc.pixel_format())]); let ids = (a.id, b.id); - doc.layers = vec![a, b]; + doc.layers = vec![a, b].into(); Ok(ids) }) .unwrap(); diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index fb8b40f152..45d47f0ca1 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -241,7 +241,7 @@ fn single_layer_surface(doc: &mut Document, active: &mut Option, mode: *surf = pixels; } *active = Some(l.id); - doc.layers = vec![l]; + doc.layers = vec![l].into(); for ch in doc.channels.iter_mut() { let f = PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false); ch.surface = ch.surface.convert(PixelFormat { alpha: ch.surface.format().alpha, ..f }); diff --git a/crates/engine/src/cmd/multichannel_cmds.rs b/crates/engine/src/cmd/multichannel_cmds.rs index 91570fc245..77846d17c5 100644 --- a/crates/engine/src/cmd/multichannel_cmds.rs +++ b/crates/engine/src/cmd/multichannel_cmds.rs @@ -246,7 +246,7 @@ pub(crate) fn convert_from(s: &mut Session, mode: ColorMode, _p: &Value) -> Resu bg.locks.transparency = true; bg.locks.position = true; *active = Some(bg.id); - doc.layers = vec![bg]; + doc.layers = vec![bg].into(); doc.channels = others; Ok(if reinterpret { "channels" } else { "appearance" }) })?; diff --git a/crates/engine/src/cmd/ops.rs b/crates/engine/src/cmd/ops.rs index 5a7373f843..7073b45184 100644 --- a/crates/engine/src/cmd/ops.rs +++ b/crates/engine/src/cmd/ops.rs @@ -246,7 +246,7 @@ pub(super) fn merge_group(s: &mut Session, id: LayerId) -> Result { solo.blend = photocraft_doc::BlendMode::Normal; solo.clipped = false; let mut tmp = doc.clone(); - tmp.layers = vec![solo]; + tmp.layers = vec![solo].into(); let mut merged = Layer::new(group.name.clone(), LayerContent::Raster(pixels::composite_layers_uncropped(&tmp, fmt))); merged.id = group.id; merged.opacity = group.opacity; diff --git a/crates/engine/src/cmd/rasterize_style_cmds.rs b/crates/engine/src/cmd/rasterize_style_cmds.rs index 5c8210852b..5ef5c9860c 100644 --- a/crates/engine/src/cmd/rasterize_style_cmds.rs +++ b/crates/engine/src/cmd/rasterize_style_cmds.rs @@ -64,7 +64,7 @@ fn bake_one(s: &mut Session, id: LayerId, key: &str) -> Result { if !area.is_empty() { // Render the layer on its own with the document's settings (mode, depth, global // light, patterns), then put the real stack back. - let stack = std::mem::replace(&mut doc.layers, vec![alone]); + let stack = std::mem::replace(&mut doc.layers, vec![alone].into()); let buf = photocraft_compose::render(doc, area); doc.layers = stack; let n = fmt.channels(); diff --git a/crates/engine/src/cmd/sample_cmds.rs b/crates/engine/src/cmd/sample_cmds.rs index 5baa7f14f2..5b676eb575 100644 --- a/crates/engine/src/cmd/sample_cmds.rs +++ b/crates/engine/src/cmd/sample_cmds.rs @@ -158,7 +158,7 @@ fn sampled_document(doc: &Document, active: Option, which: SampleLayers layer.fill_opacity = 1.0; layer.blend = photocraft_color::BlendMode::Normal; let mut solo = doc.clone(); - solo.layers = vec![layer]; + solo.layers = vec![layer].into(); return Some(Cow::Owned(solo)); } _ => {} diff --git a/crates/engine/src/cmd/smart_cmds/placing.rs b/crates/engine/src/cmd/smart_cmds/placing.rs index f107df8fd3..fa0f9cf459 100644 --- a/crates/engine/src/cmd/smart_cmds/placing.rs +++ b/crates/engine/src/cmd/smart_cmds/placing.rs @@ -236,7 +236,7 @@ pub fn layers_to_smart(doc: &Document, name: &str, layers: Vec) -> Result } let has_fx = layers.iter().any(|l| any_layer(l, &|x| x.effects.enabled && !x.effects.items.is_empty())); let region = layers.iter().map(|l| subtree_bounds(l, canvas)).fold(canvas, |a, b| a.union(&b)).inflate(if has_fx { 256 } else { 0 }); - sub.layers = layers; + sub.layers = layers.into(); let buf = photocraft_compose::render(&sub, region); let w = region.width() as usize; diff --git a/crates/engine/src/cmd/smart_cmds/source.rs b/crates/engine/src/cmd/smart_cmds/source.rs index 52b6b5820a..3a4d65e0a4 100644 --- a/crates/engine/src/cmd/smart_cmds/source.rs +++ b/crates/engine/src/cmd/smart_cmds/source.rs @@ -285,7 +285,7 @@ fn convert_source(src: &Document, fmt: PixelFormat, raster: impl FnOnce(PixelFor } let mut doc = Document::new(src.name.clone(), src.size, src.mode, src.depth); doc.icc_profile = src.icc_profile.clone(); - doc.layers = vec![Layer::new("source", LayerContent::Raster(raster(src.pixel_format())))]; + doc.layers = vec![Layer::new("source", LayerContent::Raster(raster(src.pixel_format())))].into(); if gray { let gray_profile = crate::color_cmds::working_profile(ColorMode::Grayscale); crate::color_cmds::convert_document(&mut doc, &gray_profile, craft_cms::Intent::RelativeColorimetric, true)?; diff --git a/crates/engine/src/cmd/smart_cmds/tests/selection.rs b/crates/engine/src/cmd/smart_cmds/tests/selection.rs index a4f94029fa..793499f6f4 100644 --- a/crates/engine/src/cmd/smart_cmds/tests/selection.rs +++ b/crates/engine/src/cmd/smart_cmds/tests/selection.rs @@ -45,7 +45,7 @@ fn selected_pixels_become_one_editable_smart_object_in_every_mode_and_depth() { let mut hidden = pixel(&doc, "Hidden", Rect::new(50, 40, 58, 44), [0.2, 0.9, 0.3, 1.0]); hidden.visible = false; let ids = [a.id, b.id, hidden.id]; - doc.layers = vec![a, b, hidden]; + doc.layers = vec![a, b, hidden].into(); let mut selection = Surface::new(PixelFormat::GRAY8); selection.fill_rect(Rect::new(0, 0, 12, 12), &[0.5]); doc.selection = Some(selection); @@ -99,7 +99,7 @@ fn selected_group_and_descendant_are_embedded_once() { let group_id = group.id; let b = pixel(&doc, "Outside", Rect::new(16, 0, 32, 16), [0.0, 0.0, 1.0, 1.0]); let b_id = b.id; - doc.layers = vec![group, b]; + doc.layers = vec![group, b].into(); let mut s = selected_session(doc, &[group_id, a_id, b_id]); convert(&mut s); assert_eq!(s.active().unwrap().doc.layers.len(), 1); @@ -120,7 +120,7 @@ fn mixed_parent_selection_keeps_unselected_siblings_and_uses_the_top_selected_pa let lower = Layer::group("Lower parent", vec![a, keep_a.clone()]); let upper = Layer::group("Upper parent", vec![b, keep_b.clone()]); let (lower_id, upper_id) = (lower.id, upper.id); - doc.layers = vec![lower, upper]; + doc.layers = vec![lower, upper].into(); let original = doc.clone(); let mut s = selected_session(doc, &[b_id, a_id]); let before = flat(&s); @@ -144,7 +144,7 @@ fn explicit_layer_converts_only_that_layer_despite_multi_selection() { let a = pixel(&doc, "A", Rect::new(0, 0, 8, 8), [1.0, 0.0, 0.0, 1.0]); let b = pixel(&doc, "B", Rect::new(8, 0, 16, 8), [0.0, 0.0, 1.0, 1.0]); let (a_id, b_id) = (a.id, b.id); - doc.layers = vec![a, b.clone()]; + doc.layers = vec![a, b.clone()].into(); let mut s = selected_session(doc, &[a_id, b_id]); s.execute("layer.smartObjects.convertToSmartObject", json!({"layer": a_id.0})).unwrap(); assert_eq!(s.active().unwrap().doc.layers.len(), 2); @@ -160,7 +160,7 @@ fn combined_contents_survive_native_and_psd_save_open() { let a = pixel(&doc, "Bottom", Rect::new(-2, 4, 20, 20), [1.0, 0.0, 0.0, 1.0]); let b = pixel(&doc, "Top", Rect::new(10, 8, 24, 24), [0.0, 0.0, 1.0, 1.0]); let ids = [a.id, b.id]; - doc.layers = vec![a, b]; + doc.layers = vec![a, b].into(); let mut s = selected_session(doc, &ids); let id = LayerId(convert(&mut s)); let original = s.active().unwrap().doc.clone(); @@ -189,7 +189,7 @@ fn selected_ancestor_in_another_parent_cannot_remove_the_new_smart_object() { let lower = Layer::group("Selected parent", vec![a]); let upper = Layer::group("Unselected parent", vec![b, keep]); let (lower_id, upper_id) = (lower.id, upper.id); - doc.layers = vec![lower, upper]; + doc.layers = vec![lower, upper].into(); let mut s = selected_session(doc, &[lower_id, a_id, b_id]); let so = LayerId(convert(&mut s)); let outer = &s.active().unwrap().doc; @@ -210,7 +210,7 @@ fn an_all_hidden_selection_is_rejected_without_changing_document_selection_or_hi a.visible = false; b.visible = false; let ids = [a.id, b.id]; - doc.layers = vec![a, b]; + doc.layers = vec![a, b].into(); let original = doc.clone(); let mut s = selected_session(doc, &ids); let err = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap_err(); diff --git a/crates/engine/src/cmd/smart_cmds/tests/source_flatten.rs b/crates/engine/src/cmd/smart_cmds/tests/source_flatten.rs index 6d3f3a9e23..e97e3d32d0 100644 --- a/crates/engine/src/cmd/smart_cmds/tests/source_flatten.rs +++ b/crates/engine/src/cmd/smart_cmds/tests/source_flatten.rs @@ -4,7 +4,7 @@ use crate::cmd::smart_cmds::source::{flattened_source, source_surface_from_buffe /// A source document of `mode`/`depth` with a textured, partly transparent block on a layer. fn source(mode: ColorMode, depth: SampleType) -> Document { let mut doc = Document::new("source", Size::new(W as u32, H as u32), mode, depth); - doc.layers = vec![Layer::new("block", LayerContent::Raster(block(&doc.pixel_format(), Rect::new(4, 3, 50, 40))))]; + doc.layers = vec![Layer::new("block", LayerContent::Raster(block(&doc.pixel_format(), Rect::new(4, 3, 50, 40))))].into(); doc } @@ -127,7 +127,7 @@ fn effects_across_block_edges_match() { let mut mask = LayerMask::reveal_all(); mask.surface.fill_rect(Rect::new(0, 240, width as i32, 270), &[0.3]); base.mask = Some(mask); - doc.layers = vec![base]; + doc.layers = vec![base].into(); same(&format!("blocks {width} {depth:?}"), &doc, fmt); } } diff --git a/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs b/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs index 0a5c635d97..6a824011ef 100644 --- a/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs +++ b/crates/engine/src/cmd/smart_cmds/tests/svg_profile.rs @@ -173,7 +173,7 @@ fn svg_smart_render_cache_tracks_destination_profile_and_transform() { assert!(warnings.is_empty()); assert_eq!(reported.unwrap(), warped, "warning-bearing warp parity"); assert!((warped.pixel(10, 8)[0] - corrected.pixel(3, 3)[0]).abs() < 0.01, "warp must keep corrected colours"); - linear.layers = vec![Layer::new("Saved SVG", LayerContent::Smart(smart.clone()))]; + linear.layers = vec![Layer::new("Saved SVG", LayerContent::Smart(smart.clone()))].into(); let saved = encode_source(&linear).unwrap(); let reopened = decode_source("saved.pcraft", &saved).unwrap(); let LayerContent::Smart(restored) = &reopened.layers[0].content else { panic!("smart object lost on save") }; diff --git a/crates/engine/src/cmd/smart_cmds/unpack.rs b/crates/engine/src/cmd/smart_cmds/unpack.rs index a7d1eb9030..d821e1fedd 100644 --- a/crates/engine/src/cmd/smart_cmds/unpack.rs +++ b/crates/engine/src/cmd/smart_cmds/unpack.rs @@ -33,7 +33,7 @@ fn contents(s: &Session, doc: &Document, sm: &SmartObject, intent: Intent, bpc: crate::image_cmds::convert_layers_depth(&mut src.layers, doc.depth); } let background_id = src.background().map(|l| l.id); - let mut layers = std::mem::take(&mut src.layers); + let mut layers = std::mem::take(&mut *src.layers); for l in &mut layers { if Some(l.id) == background_id { l.name = "Layer 0".into(); diff --git a/crates/engine/src/cmd/stamp_cmds.rs b/crates/engine/src/cmd/stamp_cmds.rs index 1f96831f7e..06785cd53a 100644 --- a/crates/engine/src/cmd/stamp_cmds.rs +++ b/crates/engine/src/cmd/stamp_cmds.rs @@ -130,7 +130,7 @@ fn stamp_down(s: &mut Session, p: &Value) -> Result { let mut tmp = doc.clone(); let mut base = lower.clone(); base.visible = true; - tmp.layers = vec![base, upper]; + tmp.layers = vec![base, upper].into(); let fmt = doc.pixel_format(); let fmt = if lower.locks.transparency { fmt } else { PixelFormat::new(fmt.mode, fmt.sample, true) }; let surf = photocraft_compose::flatten_to_surface(&tmp, fmt, None); diff --git a/crates/engine/src/cmd/vector_clipboard.rs b/crates/engine/src/cmd/vector_clipboard.rs index 0ad426d3b4..fde0d7763b 100644 --- a/crates/engine/src/cmd/vector_clipboard.rs +++ b/crates/engine/src/cmd/vector_clipboard.rs @@ -217,11 +217,11 @@ pub(super) fn paste(s: &mut Session, p: &Value, mode: Mode) -> Result { copies.layers = if mode == Mode::Shape { let layer = shape(&copies)?; shape_budget(layer, &destination, dx, dy)?; - vec![layer.duplicate()] + vec![layer.duplicate()].into() } else { let image = crate::smart_cmds::svg_source_image(&bytes, PixelFormat::new(ColorMode::Rgb, SampleType::F32, true), 1.0)?; copies.depth = SampleType::F32; - vec![Layer::new("Pasted SVG", LayerContent::Raster((*image.surface).clone()))] + vec![Layer::new("Pasted SVG", LayerContent::Raster((*image.surface).clone()))].into() }; crate::layer_copy_cmds::adapt_copies(s, &mut copies, &destination)?; crate::layer_copy_cmds::translate_copies(&mut copies, &destination, dx, dy); diff --git a/crates/engine/src/cmd/web_cmds/tests.rs b/crates/engine/src/cmd/web_cmds/tests.rs index bc1d154e07..ee4abbd846 100644 --- a/crates/engine/src/cmd/web_cmds/tests.rs +++ b/crates/engine/src/cmd/web_cmds/tests.rs @@ -881,7 +881,7 @@ fn image_assets_keep_full_artboards() { let board = photocraft_doc::Artboard { rect: Rect::new(4, 6, 44, 36), background: photocraft_doc::ArtboardBackground::Transparent, preset: String::new() }; let group = photocraft_doc::Group { children: vec![logo], expanded: true, artboard: Some(board), frame_stroke: None }; - doc.layers = vec![Layer::new("board.png", LayerContent::Group(group))]; + doc.layers = vec![Layer::new("board.png", LayerContent::Group(group))].into(); Ok(()) }) .unwrap(); @@ -920,7 +920,7 @@ fn image_assets_refuse_empty_artboards() { }; let empty = photocraft_doc::Group { children: vec![], expanded: true, artboard: Some(board(0)), frame_stroke: None }; let off = photocraft_doc::Group { children: vec![outside], expanded: true, artboard: Some(board(24)), frame_stroke: None }; - doc.layers = vec![Layer::new("empty.png", LayerContent::Group(empty)), Layer::new("off.png", LayerContent::Group(off))]; + doc.layers = vec![Layer::new("empty.png", LayerContent::Group(empty)), Layer::new("off.png", LayerContent::Group(off))].into(); Ok(()) }) .unwrap(); diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 17ac800c97..7dcacd3561 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -322,9 +322,71 @@ pub struct CopiedStyle { pub const PRECHECKED: &[&str] = &["layer.new.layer", "layer.new.group", "layer.new.groupFromLayers", "layer.new.layerFromBackground"]; /// The selected layers of `doc` whose active layer is `active` and whose selection set is `selected`, in bottom-to-top -/// order ([`DocState::selected_layers`]), for a reader that holds the document without its editing state. +/// order ([`DocState::selected_layers`]), taken from the document's layer index rather than a walk, for a reader that holds the document without its editing state. pub fn selected_in(doc: &Document, active: Option, selected: &[LayerId]) -> Vec { let Some(active) = active else { return Vec::new() }; let set: &[LayerId] = if selected.contains(&active) { selected } else { std::slice::from_ref(&active) }; - doc.walk().into_iter().map(|(_, _, l)| l.id).filter(|id| set.contains(id)).collect() + // Paths from the document's layer index order layers as the walk does (depth-first, bottom-to-top). + let index = doc.layers.index(); + let mut ids: Vec = set.iter().copied().filter(|id| index.path(*id).is_some()).collect(); + ids.sort_unstable_by(|a, b| index.path(*a).cmp(&index.path(*b))); + ids.dedup(); + ids +} + +#[cfg(test)] +mod selected_tests { + use super::selected_in; + use photocraft_doc::{ColorMode, Document, Layer, LayerId, PixelFormat, SampleType, Size}; + + fn raster(name: &str) -> Layer { + Layer::raster(name, PixelFormat::RGBA8) + } + + /// The answer before the layer index: filter the depth-first walk by the selection set. + fn by_walk(doc: &Document, active: Option, selected: &[LayerId]) -> Vec { + let Some(active) = active else { return Vec::new() }; + let set: &[LayerId] = if selected.contains(&active) { selected } else { std::slice::from_ref(&active) }; + doc.walk().into_iter().map(|(_, _, l)| l.id).filter(|id| set.contains(id)).collect() + } + + /// `a`, group `g` (`b`, group `h` (`c`), `d`), `e`: nested groups mixed with root layers. + fn mixed() -> (Document, Vec) { + let mut doc = Document::new("t", Size::new(4, 4), ColorMode::Rgb, SampleType::U8); + let (a, b, c, d, e) = (raster("a"), raster("b"), raster("c"), raster("d"), raster("e")); + let h = Layer::group("h", vec![c.clone()]); + let g = Layer::group("g", vec![b.clone(), h.clone(), d.clone()]); + let ids = [&a, &g, &b, &h, &c, &d, &e].map(|l| l.id).to_vec(); + doc.layers = vec![a, g, e].into(); + (doc, ids) + } + + #[test] + fn selection_order_matches_the_walk_through_edits() { + let (mut doc, ids) = mixed(); + let stale = LayerId::fresh(); + let sets: Vec> = + vec![vec![ids[6], ids[4], ids[0]], vec![ids[5], ids[2], ids[1], ids[3]], vec![ids[4], ids[4], ids[0], stale], vec![ids[0]], vec![]]; + let check = |doc: &Document| { + let first = doc.layers.index().serial(); + for set in &sets { + for active in [None, Some(ids[0]), Some(ids[4]), Some(ids[6]), Some(stale)] { + assert_eq!(selected_in(doc, active, set), by_walk(doc, active, set)); + } + } + assert_eq!(doc.layers.index().serial(), first, "no rebuild while the document is unchanged"); + }; + check(&doc); + // Reorder: move `e` to the bottom, then a layer inside a group. + doc.shift(ids[6], -2); + check(&doc); + doc.shift(ids[5], -1); + check(&doc); + // Add and delete. + doc.insert_above(Some(ids[4]), raster("new")); + check(&doc); + doc.remove(ids[3]); + check(&doc); + assert_eq!(selected_in(&doc, Some(ids[0]), &[ids[0], ids[3], ids[4]]), vec![ids[0]], "deleted layers are skipped"); + } } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 722e8b5c6d..1c6643f083 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -344,7 +344,7 @@ mod tests { roots.push(Layer::group("Outer", vec![group])); session .edit("Mask fixtures", |doc, _| { - doc.layers = roots; + doc.layers = roots.into(); Ok(()) }) .unwrap(); diff --git a/crates/engine/src/layer_place.rs b/crates/engine/src/layer_place.rs index 53d8f836b8..6e0589f123 100644 --- a/crates/engine/src/layer_place.rs +++ b/crates/engine/src/layer_place.rs @@ -64,7 +64,7 @@ pub fn insertion_point(doc: &Document, anchor: Option, layer: &Layer, p pub fn insert_new(doc: &mut Document, anchor: Option, mut layer: Layer, place: Place) -> LayerId { let id = layer.id; let (parent, index) = insertion_point(doc, anchor, &layer, place); - let sib = if parent.is_empty() { Some(&mut doc.layers) } else { doc.layer_at_mut(&parent).and_then(Layer::children_mut) }; + let sib = if parent.is_empty() { Some(&mut *doc.layers) } else { doc.layer_at_mut(&parent).and_then(Layer::children_mut) }; if let Some(sib) = sib { let mut index = index.min(sib.len()); if layer.artboard().is_some() { diff --git a/crates/engine/src/pixels.rs b/crates/engine/src/pixels.rs index bb5f6924a5..ae27445174 100644 --- a/crates/engine/src/pixels.rs +++ b/crates/engine/src/pixels.rs @@ -558,7 +558,7 @@ pub fn merge_down(doc: &Document, lower: &Layer, upper: &Layer) -> Layer { let mut tmp = Document::new("merge", doc.size, format.mode, format.sample); // The pair is read (and a CMYK one separated again) through the document's own profile. tmp.icc_profile = doc.icc_profile.clone(); - tmp.layers = stack; + tmp.layers = stack.into(); // A Background stays canvas-sized; any other layer keeps the pixels outside the canvas (#5067). let s = if doc.is_background(lower.id) { composite_layers(&tmp, format, None) } else { composite_layers_uncropped(&tmp, format) }; let mut merged = Layer::new(lower.name.clone(), LayerContent::Raster(s)); diff --git a/crates/engine/tests/it/atn_newer_events.rs b/crates/engine/tests/it/atn_newer_events.rs index 77ecad13ef..16440ba1bf 100644 --- a/crates/engine/tests/it/atn_newer_events.rs +++ b/crates/engine/tests/it/atn_newer_events.rs @@ -468,7 +468,7 @@ fn artboard_fixture() -> Session { } let group = Layer::group("Group", vec![child]); let id = group.id; - doc.layers = vec![group]; + doc.layers = vec![group].into(); s.restore_layer_selection(Some(id), &[id], Some(id)).unwrap(); s } diff --git a/crates/engine/tests/it/atn_stack_modes.rs b/crates/engine/tests/it/atn_stack_modes.rs index d70fe99a41..1085f83cba 100644 --- a/crates/engine/tests/it/atn_stack_modes.rs +++ b/crates/engine/tests/it/atn_stack_modes.rs @@ -134,7 +134,7 @@ fn stack(depth: u32) -> Session { let group = Layer::new("Stack", LayerContent::Group(Group { children, expanded: true, artboard: None, frame_stroke: None })); let smart = photocraft_engine::smart_cmds::layer_to_smart(doc, &group)?; *active = Some(smart.id); - doc.layers = vec![smart]; + doc.layers = vec![smart].into(); Ok(()) }) .unwrap(); diff --git a/crates/engine/tests/it/convert_profile_options.rs b/crates/engine/tests/it/convert_profile_options.rs index ad28e2d2d5..b7cc909e1f 100644 --- a/crates/engine/tests/it/convert_profile_options.rs +++ b/crates/engine/tests/it/convert_profile_options.rs @@ -196,7 +196,7 @@ fn smart_scene(children: Vec) -> Session { doc.icc_profile = Some(Builtin::Srgb.profile().to_bytes()); let ordinary = Layer::raster("Ordinary", PixelFormat::RGBA32F); let active = ordinary.id; - doc.layers = vec![Layer::group("Outer", vec![Layer::group("Inner", children)]), ordinary]; + doc.layers = vec![Layer::group("Outer", vec![Layer::group("Inner", children)]), ordinary].into(); from_document(doc, Some(active)) } diff --git a/crates/engine/tests/it/export_shape_strokes.rs b/crates/engine/tests/it/export_shape_strokes.rs index 0875f4bfc0..a9c23d47e3 100644 --- a/crates/engine/tests/it/export_shape_strokes.rs +++ b/crates/engine/tests/it/export_shape_strokes.rs @@ -66,7 +66,7 @@ fn image_size_scales_strokes_once_and_undo_restores_them() { fn grouped_strokes_scale_up_and_unchanged_size_is_a_noop() { let (mut s, id) = shape_session(8); s.edit("Group", |doc, _| { - let children = std::mem::take(&mut doc.layers); + let children = std::mem::take(&mut *doc.layers); doc.layers.push(photocraft_doc::Layer::group("Outer", vec![photocraft_doc::Layer::group("Inner", children)])); Ok(()) }) diff --git a/crates/engine/tests/it/image_size_scale_styles.rs b/crates/engine/tests/it/image_size_scale_styles.rs index 4ae6cbabd2..5bde492676 100644 --- a/crates/engine/tests/it/image_size_scale_styles.rs +++ b/crates/engine/tests/it/image_size_scale_styles.rs @@ -28,7 +28,7 @@ fn styled_shape(depth: u32) -> (Session, LayerId) { ..Default::default() }; doc.layer_mut(id).unwrap().effects = effects.clone(); - let children = std::mem::take(&mut doc.layers); + let children = std::mem::take(&mut *doc.layers); let mut outer = Layer::group("Outer", vec![Layer::group("Inner", children)]); outer.effects = effects; doc.layers.push(outer); diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs index cc255ab818..cd76c4c542 100644 --- a/crates/format/src/convert.rs +++ b/crates/format/src/convert.rs @@ -698,7 +698,7 @@ impl Loader<'_> { mode: m.mode, depth: m.depth, icc_profile: self.opt_blob(&m.icc_profile)?, - layers, + layers: layers.into(), channels, guides: m.guides.clone(), ruler_origin: m.ruler_origin, diff --git a/crates/format/tests/it/roundtrip.rs b/crates/format/tests/it/roundtrip.rs index 79850cb26a..3e9f340c1e 100644 --- a/crates/format/tests/it/roundtrip.rs +++ b/crates/format/tests/it/roundtrip.rs @@ -461,11 +461,11 @@ fn group_depth(layers: &[Layer]) -> usize { /// [`rich_doc`] with its layers wrapped in groups until they are nested `levels` deep. fn nested_doc(levels: usize, depth: SampleType) -> Document { let mut doc = rich_doc(ColorMode::Rgb, depth); - let mut layers = std::mem::take(&mut doc.layers); + let mut layers = std::mem::take(&mut *doc.layers); for i in group_depth(&layers)..levels { layers = vec![Layer::group(format!("Level {i}"), layers)]; } - doc.layers = layers; + doc.layers = layers.into(); assert_eq!(group_depth(&doc.layers), levels); doc } diff --git a/crates/gpu/src/plan/tests.rs b/crates/gpu/src/plan/tests.rs index c563fb289f..39b0f64e6a 100644 --- a/crates/gpu/src/plan/tests.rs +++ b/crates/gpu/src/plan/tests.rs @@ -12,7 +12,7 @@ fn nested_pass_through_groups_with_clipped_layers_are_not_planned_exponentially( layers = vec![group, clipped]; } let mut doc = Document::new("nest", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); - doc.layers = layers; + doc.layers = layers.into(); let started = std::time::Instant::now(); let Err(error) = plan(&doc) else { panic!("2^30 plannings must be refused") }; assert!(error.0.contains("too many nested layers"), "{}", error.0); diff --git a/crates/gpu/src/prefix.rs b/crates/gpu/src/prefix.rs index 31406c6449..6c45acb096 100644 --- a/crates/gpu/src/prefix.rs +++ b/crates/gpu/src/prefix.rs @@ -114,7 +114,7 @@ impl Prefix { // Keeping every non-layer field makes new document inputs invalidate automatically. // Tile data is Arc-shared; shared Tile equality does not scan its pixel bytes. let mut context = doc.clone(); - let layers = std::mem::take(&mut context.layers); + let layers = std::mem::take(&mut *context.layers); let same_context = self.context.as_ref() == Some(&context); // The lowest root layer this render changes since the last one (a layer added or removed // at the top changes from there on). diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index 46154fb3f5..e12030fe52 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -78,7 +78,7 @@ fn hdr_adjustments_preserve_range_and_cpu_parity() { let mut d = Document::new("HDR adjustments", Size::new(3, 1), ColorMode::Rgb, SampleType::F32); let mut layer = Layer::raster("pixels", PixelFormat::RGBA32F); layer.surface_mut().unwrap().write_region(Rect::new(0, 0, 3, 1), &[4.0, 2.0, 0.5, 1.0, -0.1, 3.0, 0.25, 0.75, 0.0, 0.0, 0.0, 1.0]); - d.layers = vec![layer, Layer::new("adjustment", LayerContent::Adjustment(adj.clone()))]; + d.layers = vec![layer, Layer::new("adjustment", LayerContent::Adjustment(adj.clone()))].into(); let cpu = photocraft_compose::flatten(&d); assert!(cpu.px[0][0] > 1.0, "HDR reference unexpectedly clipped: {adj:?}"); check(&mut g, &d, &format!("HDR {adj:?}")); @@ -1011,7 +1011,7 @@ fn hard_stop_fill_fallback_respects_caches_and_visibility() { assert_gradient_fallback(&d); let mut clipped = Layer::new("clipped", LayerContent::Fill(fill)); clipped.clipped = true; - d.layers = vec![Layer::new("base", LayerContent::Fill(Fill::Solid(Color::WHITE))), clipped]; + d.layers = vec![Layer::new("base", LayerContent::Fill(Fill::Solid(Color::WHITE))), clipped].into(); assert_gradient_fallback(&d); d.layers.push(Layer::new("cover", LayerContent::Fill(Fill::Solid(Color::WHITE)))); assert!(photocraft_gpu::plan(&d).is_ok(), "occluded gradients are not sampled"); @@ -3040,7 +3040,7 @@ fn lab_documents_mix_in_lab() { a.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 2, 1), &photocraft_raster::from_rgba(&fmt, [0.0, 0.0, 1.0, 1.0])); let mut b = Layer::raster("b", fmt); b.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 2, 1), &photocraft_raster::from_rgba(&fmt, [1.0, 1.0, 0.0, 0.5])); - d.layers = vec![a, b]; + d.layers = vec![a, b].into(); let p = photocraft_compose::flatten(&d).px[0]; assert!((p[0] - 0.5).abs() > 0.05 || (p[2] - 0.5).abs() > 0.05, "{p:?}"); } @@ -3545,7 +3545,7 @@ fn integration_adjustment_fill_opacity_masks_and_hdr_match_cpu() { &[coverage], ); layer.mask = Some(mask); - d.layers = vec![base, layer]; + d.layers = vec![base, layer].into(); check(&mut g, &d, &format!("combined {mode:?} fill={fill} opacity={opacity} mask={coverage} clipped={clipped}")); } } @@ -3565,7 +3565,7 @@ fn integration_adjustment_fill_opacity_masks_and_hdr_match_cpu() { dither: false, source: None, }; - d.layers = vec![base, Layer::new("lookup", LayerContent::Adjustment(look))]; + d.layers = vec![base, Layer::new("lookup", LayerContent::Adjustment(look))].into(); check(&mut g, &d, "HDR full coverage with bounded result"); } diff --git a/crates/io/src/affinity.rs b/crates/io/src/affinity.rs index 8e925bf8b4..f4625caf71 100644 --- a/crates/io/src/affinity.rs +++ b/crates/io/src/affinity.rs @@ -201,7 +201,7 @@ impl Builder<'_> { l.locks.position = true; layers.insert(0, l); } - self.doc.layers = layers; + self.doc.layers = layers.into(); Ok(()) } diff --git a/crates/io/src/exr_parts.rs b/crates/io/src/exr_parts.rs index 7ebac8eae2..4b815787d8 100644 --- a/crates/io/src/exr_parts.rs +++ b/crates/io/src/exr_parts.rs @@ -270,7 +270,7 @@ pub fn import(name: &str, bytes: &[u8], sel: &Selection) -> Result) -> Result) -> Result 0.0 && xres < 1.0e6 { diff --git a/crates/io/src/ora/tests.rs b/crates/io/src/ora/tests.rs index e4f5868717..e073b01908 100644 --- a/crates/io/src/ora/tests.rs +++ b/crates/io/src/ora/tests.rs @@ -42,7 +42,7 @@ fn doc(depth: SampleType) -> Document { through_child.blend = BlendMode::LinearLight; through_child.locks.all = true; let through = Layer::group("Pass <&> \"through\"", vec![through_child]); - d.layers = vec![base, off, hidden, group, through]; + d.layers = vec![base, off, hidden, group, through].into(); d } @@ -93,7 +93,7 @@ fn float_documents_save_as_16_bit() { let mut d = doc(SampleType::U16); d.depth = SampleType::F32; let fmt = PixelFormat::RGBA32F; - d.layers = vec![block("Float", fmt, 0, 0, 10, 10, 9)]; + d.layers = vec![block("Float", fmt, 0, 0, 10, 10, 9)].into(); let (back, warnings, _) = round_trip(&d); assert!(warnings.iter().any(|w| w.contains("16-bit")), "{warnings:?}"); assert_eq!(back.depth, SampleType::U16); diff --git a/crates/io/src/pdf/tests.rs b/crates/io/src/pdf/tests.rs index 3dd6322c88..b3844d993e 100644 --- a/crates/io/src/pdf/tests.rs +++ b/crates/io/src/pdf/tests.rs @@ -28,7 +28,7 @@ fn doc(mode: ColorMode) -> Document { let fmt = PixelFormat::new(mode, SampleType::F32, true); let bg = paper(mode); let mut d = Document::new("t.pdf", Size { width: 4, height: 2 }, mode, SampleType::F32); - d.layers = vec![Layer::new("Paper", LayerContent::Raster(solid(fmt, 0, 0, 4, 2, &bg)))]; + d.layers = vec![Layer::new("Paper", LayerContent::Raster(solid(fmt, 0, 0, 4, 2, &bg)))].into(); d } @@ -187,7 +187,7 @@ fn the_page_measures_at_the_document_resolution() { let mut d = doc(ColorMode::Rgb); d.size = Size { width: 300, height: 150 }; let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); - d.layers = vec![Layer::new("Paper", LayerContent::Raster(solid(fmt, 0, 0, 300, 150, &[1.0, 1.0, 1.0, 1.0])))]; + d.layers = vec![Layer::new("Paper", LayerContent::Raster(solid(fmt, 0, 0, 300, 150, &[1.0, 1.0, 1.0, 1.0])))].into(); d.resolution_dpi = 300.0; let out = export(&d, true, &Interrupt::NONE).unwrap(); assert!(has(&out.bytes, "/MediaBox [0 0 72.00 36.00]"), "300 px at 300 dpi is one inch"); @@ -495,7 +495,7 @@ fn unicode_text_over_a_photo_extracts_through_a_pdf_reader() { d.size = Size { width: 128, height: 48 }; let fmt = d.pixel_format(); // Synthetic photo-like backdrop; no personal image or third-party asset. - d.layers = vec![Layer::new("Photo", LayerContent::Raster(solid(fmt, 0, 0, 128, 48, &[0.2, 0.4, 0.6, 1.0])))]; + d.layers = vec![Layer::new("Photo", LayerContent::Raster(solid(fmt, 0, 0, 128, 48, &[0.2, 0.4, 0.6, 1.0])))].into(); let text = "café Ω 😀"; d.layers.push(Layer::new( "Text", @@ -599,7 +599,7 @@ fn a_text_layer_refused_at_emission_keeps_the_upper_vectors_and_stays_raster() { let mut d = doc(ColorMode::Rgb); d.size = Size { width: 128, height: 48 }; let fmt = d.pixel_format(); - d.layers = vec![Layer::new("Paper", LayerContent::Raster(solid(fmt, 0, 0, 128, 48, &[1.0, 1.0, 1.0, 1.0])))]; + d.layers = vec![Layer::new("Paper", LayerContent::Raster(solid(fmt, 0, 0, 128, 48, &[1.0, 1.0, 1.0, 1.0])))].into(); // A box too short for its paragraph: the layout hides the overflow, so `prepare` accepts // the layer (its checks only see placed clusters) while emission refuses it, because the // hidden, unpainted source text would otherwise show up in the selection plane. diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 7884cef7c2..706802ee26 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -1451,7 +1451,7 @@ fn import_layered(import: DecodedImport<'_>, doc: &mut Document, cx: &mut Ctx<'_ let cc = fmt.mode.color_channels(); let tree = file.layer_tree_max_depth(photocraft_doc::MAX_GROUP_DEPTH); let space = photocraft_compose::cmyk_space(doc); - doc.layers = photocraft_color::convert::with_cmyk_space(space.as_ref(), || cx.build(&tree, 0)); + doc.layers = photocraft_color::convert::with_cmyk_space(space.as_ref(), || cx.build(&tree, 0)).into(); mark_background(file, &mut doc.layers); if let Some(Ok(craft_psd::resources::ResourceData::LayerGroupInfo(groups))) = file.resources.iter().find(|r| r.id == ids::LAYER_GROUP_INFO).and_then(craft_psd::resources::ImageResource::parsed) diff --git a/crates/io/src/psd_import/tests.rs b/crates/io/src/psd_import/tests.rs index 2cef2ad229..8a0825c881 100644 --- a/crates/io/src/psd_import/tests.rs +++ b/crates/io/src/psd_import/tests.rs @@ -319,7 +319,7 @@ fn as_earlier_photocraft_resaved(doc: &Document, stale_ids: &[u32], kept: usize) fn a_spot_added_behind_a_kept_alpha_identifiers_resource_keeps_its_ink() { let transparent = |names: &[&str]| { let mut doc = channels_document(SampleType::U8); - doc.layers = vec![Layer::raster("Layer 1", doc.pixel_format())]; + doc.layers = vec![Layer::raster("Layer 1", doc.pixel_format())].into(); doc.channels.retain(|c| names.contains(&c.name.as_str())); doc }; @@ -350,7 +350,7 @@ fn a_spot_added_behind_a_kept_alpha_identifiers_resource_keeps_its_ink() { #[test] fn a_complete_alpha_identifiers_resource_keeps_photoshop_polarity() { let mut doc = channels_document(SampleType::U8); - doc.layers = vec![Layer::raster("Layer 1", doc.pixel_format())]; + doc.layers = vec![Layer::raster("Layer 1", doc.pixel_format())].into(); let bytes = as_earlier_photocraft_resaved(&doc, &[0, 3, 4, 5], 3); let file = PsdFile::from_bytes(&bytes).unwrap(); assert!(file.merged_has_alpha()); diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 5830316088..2905cca741 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -1047,7 +1047,7 @@ fn import_parsed_with_limits( } } } else { - doc.layers = conv.convert_children(tree.root().children(), 0, 0, tree.root().abs_transform()); + doc.layers = conv.convert_children(tree.root().children(), 0, 0, tree.root().abs_transform()).into(); } if doc.layers.is_empty() && !conv.noted.contains(&"raster-panic") { conv.warnings.push("SVG: nothing to draw (an empty drawing)".to_string()); diff --git a/crates/io/src/xcf.rs b/crates/io/src/xcf.rs index 9ae250ee11..2f9706d43d 100644 --- a/crates/io/src/xcf.rs +++ b/crates/io/src/xcf.rs @@ -297,7 +297,7 @@ pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result 0.0 && *x < 1.0e6) { diff --git a/crates/io/tests/it/artboard_guide_order.rs b/crates/io/tests/it/artboard_guide_order.rs index 514c7e0b56..de53f9d407 100644 --- a/crates/io/tests/it/artboard_guide_order.rs +++ b/crates/io/tests/it/artboard_guide_order.rs @@ -33,7 +33,7 @@ fn doc_with_board(rect: Rect) -> Document { if let LayerContent::Group(g) = &mut g1.content { g.artboard = Some(Artboard { rect, background: ArtboardBackground::White, preset: String::new() }); } - d.layers = vec![g1]; + d.layers = vec![g1].into(); d.guides = Guides { horizontal: vec![90.0], vertical: vec![20.0], ..Default::default() }; d } diff --git a/crates/io/tests/it/comps_artboards.rs b/crates/io/tests/it/comps_artboards.rs index 3476560d1c..27500a9d55 100644 --- a/crates/io/tests/it/comps_artboards.rs +++ b/crates/io/tests/it/comps_artboards.rs @@ -134,7 +134,7 @@ fn synthetic(depth: SampleType) -> Document { g.artboard = Some(Artboard { rect: Rect::new(40, 0, 80, 40), background: ArtboardBackground::Custom(Color::rgb(0.0, 1.0, 0.0)), preset: String::new() }); } - d.layers = vec![g1, g2]; + d.layers = vec![g1, g2].into(); let states = capture_states(&d); d.layer_comps.push(LayerComp { id: 11, diff --git a/crates/io/tests/it/roundtrip.rs b/crates/io/tests/it/roundtrip.rs index 6402329d9d..af72cd1e1c 100644 --- a/crates/io/tests/it/roundtrip.rs +++ b/crates/io/tests/it/roundtrip.rs @@ -417,7 +417,7 @@ fn link_groups_and_effects_reference_round_trip() { let mut inner = Layer::raster("inner", fmt); inner.link_group = Some(3); let g = Layer::group("g", vec![inner]); - d.layers = vec![a, b, g]; + d.layers = vec![a, b, g].into(); let back = roundtrip(&d); assert_eq!(back.layers[0].link_group, Some(7)); assert_eq!(back.layers[1].link_group, Some(7)); @@ -459,7 +459,7 @@ fn channel_restrictions_round_trip_as_brst() { a.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]); a.excluded_channels = 0b110; let b = Layer::raster("b", d.pixel_format()); - d.layers = vec![a, b]; + d.layers = vec![a, b].into(); let f = document_to_psd(&d).unwrap(); let rec = f.layers().iter().find(|r| r.name() == "a").unwrap(); assert_eq!(rec.block(b"brst").unwrap().data, vec![0, 0, 0, 1, 0, 0, 0, 2]); @@ -497,7 +497,7 @@ fn advanced_blending_round_trips_as_tagged_blocks() { g.advanced.knockout = Knockout::Shallow; g.fill_opacity = 128.0 / 255.0; let b = Layer::raster("b", d.pixel_format()); - d.layers = vec![a, b, g]; + d.layers = vec![a, b, g].into(); let f = document_to_psd(&d).unwrap(); let rec = |name: &str| f.layers().iter().find(|r| r.name() == name).unwrap().clone(); let ra = rec("a"); @@ -539,7 +539,7 @@ fn blend_if_round_trips_as_blending_ranges() { let mut g = Layer::group("g", vec![Layer::raster("c", d.pixel_format())]); g.blend_if.set(1, [BlendRange { black: [1, 2], white: [3, 4] }, BlendRange::FULL]); let b = Layer::raster("b", d.pixel_format()); - d.layers = vec![a, b, g]; + d.layers = vec![a, b, g].into(); let f = document_to_psd(&d).unwrap(); let rec = f.layers().iter().find(|r| r.name() == "a").unwrap(); let full = [0u8, 0, 255, 255, 0, 0, 255, 255]; @@ -630,7 +630,7 @@ fn frame_children_keep_their_links() { let b = Layer::raster("b", fmt); let mut outside = Layer::raster("outside", fmt); outside.link_group = Some(5); - d.layers = vec![framed(vec![a, b], Some(photocraft_doc::ShapeStroke::default())), outside]; + d.layers = vec![framed(vec![a, b], Some(photocraft_doc::ShapeStroke::default())), outside].into(); let back = roundtrip(&d); let LayerContent::Group(g) = &back.layers[0].content else { panic!("frame is not a group") }; let names: Vec<_> = g.children.iter().map(|l| (l.name.as_str(), l.link_group)).collect(); @@ -645,7 +645,7 @@ fn frame_stroke_exports_its_pixels() { let mut d = Document::new("s", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); let fmt = d.pixel_format(); let stroke = photocraft_doc::ShapeStroke { width: 2.0, ..Default::default() }; - d.layers = vec![framed(vec![Layer::raster("a", fmt)], Some(stroke))]; + d.layers = vec![framed(vec![Layer::raster("a", fmt)], Some(stroke))].into(); let r = export(&d, "x.psd", &ExportOptions::default()).unwrap(); let f = PsdFile::from_bytes(&r.bytes).unwrap(); let rec = f.layers().iter().find(|r| r.name() == "Frame Stroke").expect("stroke record"); @@ -659,7 +659,7 @@ fn an_invalidated_frame_stays_removed_after_psd_roundtrip() { for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { let mut doc = Document::new("frame", Size::new(8, 8), ColorMode::Rgb, depth); - doc.layers = vec![framed(vec![Layer::raster("image", doc.pixel_format())], None)]; + doc.layers = vec![framed(vec![Layer::raster("image", doc.pixel_format())], None)].into(); let mut imported = roundtrip(&doc); let frame = &mut imported.layers[0]; assert!(frame.frame.is_some(), "{depth:?}: the frame must first survive import"); diff --git a/crates/ui-egui/examples/interactive_bench.rs b/crates/ui-egui/examples/interactive_bench.rs index d4c555df47..090aad88b4 100644 --- a/crates/ui-egui/examples/interactive_bench.rs +++ b/crates/ui-egui/examples/interactive_bench.rs @@ -294,7 +294,7 @@ fn clipped_document(w: u32, h: u32, styled: bool) -> (Document, LayerId) { } above.clipped = true; above.opacity = 0.6; - doc.layers = vec![base, below, target, above]; + doc.layers = vec![base, below, target, above].into(); (doc, id) } @@ -746,7 +746,7 @@ mod reporting_tests { if let Some(s) = photo.surface_mut() { s.fill_rect(doc.bounds(), &[0.4, 0.5, 0.6, 1.0]); } - doc.layers = vec![photo]; + doc.layers = vec![photo].into(); let psd = photocraft_io::export(&doc, "x.psd", &Default::default()).expect("export psd").bytes; let no_free_memory = photocraft_io::memory::MemorySnapshot { available_ram: Some(0), swap_free: None, commit_headroom: None }; photocraft_io::memory::with_mock_memory(no_free_memory, || { diff --git a/crates/ui-egui/src/tools/transform_tool/tests.rs b/crates/ui-egui/src/tools/transform_tool/tests.rs index e73a495756..cdaaf74c93 100644 --- a/crates/ui-egui/src/tools/transform_tool/tests.rs +++ b/crates/ui-egui/src/tools/transform_tool/tests.rs @@ -1251,7 +1251,7 @@ fn artboard_preview_app(background: photocraft_doc::ArtboardBackground) -> (Box< ab.background = background; g.artboard = Some(ab); } - doc.layers = vec![board]; + doc.layers = vec![board].into(); (app, board_id, red_id) } diff --git a/crates/ui-egui/tests/support/layout_doc.rs b/crates/ui-egui/tests/support/layout_doc.rs index a36acfc604..249f22e18d 100644 --- a/crates/ui-egui/tests/support/layout_doc.rs +++ b/crates/ui-egui/tests/support/layout_doc.rs @@ -344,7 +344,7 @@ pub fn build(spec: Spec) -> (Document, Handles) { let lv = t(levels); let background = doc.layers.remove(0); assert!(doc.layers.is_empty(), "unassembled layers: {:?}", doc.layers.iter().map(|l| &l.name).collect::>()); - doc.layers = vec![background, gallery, products, hero, header, footer, lv]; + doc.layers = vec![background, gallery, products, hero, header, footer, lv].into(); handles.closed_group = hero_id; (doc, handles) } From 0d2ed110e8b4580dc5c4f25c8e88d42010682065 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 12:53:45 +0100 Subject: [PATCH 69/85] Keep transient surface generations out of content diagnostics --- crates/raster/src/lib.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 8255122bb8..8bb7d13a77 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -309,7 +309,7 @@ impl PruneCursor { } } -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct Surface { generation: u64, format: PixelFormat, @@ -317,6 +317,14 @@ pub struct Surface { tiles: BTreeMap>, } +impl std::fmt::Debug for Surface { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // The generation identifies an edit history. Independently opened copies of the same + // document should retain the same content representation. + f.debug_struct("Surface").field("format", &self.format).field("default_pixel", &self.default_pixel).field("tiles", &self.tiles).finish() + } +} + /// Use stack storage when it fits, otherwise reuse a dynamically sized sample buffer. fn sample_buffer<'a>(channels: usize, stack: &'a mut [f32], heap: &'a mut Vec) -> &'a mut [f32] { if let Some(samples) = stack.get_mut(..channels) { From b1368133d11748af832419d6834216cad120a1c1 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 13:05:19 +0100 Subject: [PATCH 70/85] Advance the surface generation once per serial write --- crates/raster/src/lib.rs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 8bb7d13a77..9ccf9e67e7 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -713,6 +713,11 @@ impl Surface { /// Mutable access to a tile, allocating it (filled with the default pixel) or un-sharing it. pub fn tile_mut(&mut self, c: TileCoord) -> &mut Tile { self.note_mutation(); + self.tile_for_write(c) + } + + // Region writers already advanced the generation before entering their tile loop. + fn tile_for_write(&mut self, c: TileCoord) -> &mut Tile { let fmt = self.format; let dp = &self.default_pixel; let arc = self.tiles.entry(c).or_insert_with(|| Arc::new(Tile::filled(&fmt, dp))); @@ -723,6 +728,10 @@ impl Surface { /// the surface, and a shared tile is copied only after its replacement has been allocated. pub fn try_tile_mut(&mut self, c: TileCoord) -> Result<&mut Tile, AllocationError> { self.note_mutation(); + self.try_tile_for_write(c) + } + + fn try_tile_for_write(&mut self, c: TileCoord) -> Result<&mut Tile, AllocationError> { if let Some(tile) = self.tiles.get(&c) { drop(tile.try_bytes().map_err(AllocationError::ScratchRead)?); } @@ -759,7 +768,7 @@ impl Surface { } for tc in r.tiles() { let tr = tc.rect().intersect(&r); - let t = self.try_tile_mut(tc)?; + let t = self.try_tile_for_write(tc)?; let mut target = t.bytes_mut(); let span = tr.width() as usize * n; for y in tr.y0..tr.y1 { @@ -933,7 +942,6 @@ impl Surface { } pub fn write_pixel(&mut self, x: i32, y: i32, px: &[f32]) { - self.note_mutation(); let (c, base) = self.locate(x, y); let n = self.channels(); let sample = self.format.sample; @@ -1137,7 +1145,7 @@ impl Surface { assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch"); let sample = self.format.sample; for tc in r.tiles() { - write_tile(self.tile_mut(tc), tc, r, data, w, n, sample); + write_tile(self.tile_for_write(tc), tc, r, data, w, n, sample); } } @@ -1240,7 +1248,7 @@ impl Surface { self.tiles.insert(tc, t.clone()); continue; } - let mut t = self.tile_mut(tc).bytes_mut(); + let mut t = self.tile_for_write(tc).bytes_mut(); for y in tr.y0..tr.y1 { let ly = (y - tc.ty * TILE_SIZE) as usize; let lx0 = (tr.x0 - tc.tx * TILE_SIZE) as usize; @@ -1268,7 +1276,7 @@ impl Surface { assert_eq!(bytes.len(), w * r.height() as usize * bpp, "interleaved length mismatch"); for tc in r.tiles() { let tr = tc.rect().intersect(&r); - let mut t = self.tile_mut(tc).bytes_mut(); + let mut t = self.tile_for_write(tc).bytes_mut(); let span = tr.width() as usize * bpp; for y in tr.y0..tr.y1 { let src = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * bpp; From 19641af17110694e4280afcc8d97df35ff6e8db2 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 13:06:09 +0100 Subject: [PATCH 71/85] Cache legacy blend mode parsing --- crates/color/src/blend.rs | 36 +++++++++++++++++++ crates/engine/src/cmd.rs | 8 ++--- crates/engine/src/cmd/adjust_params.rs | 2 +- crates/engine/src/cmd/atn_cmds/steps_make.rs | 2 +- crates/engine/src/cmd/atn_cmds/tables.rs | 2 +- crates/engine/src/cmd/brush_cmds.rs | 2 +- crates/engine/src/cmd/channel_cmds/refs.rs | 2 +- crates/engine/src/cmd/edit_menu_cmds.rs | 2 +- crates/engine/src/cmd/edit_menu_cmds/fade.rs | 4 +-- crates/engine/src/cmd/extra_cmds.rs | 2 +- crates/engine/src/cmd/fill_cmds.rs | 4 +-- crates/engine/src/cmd/gradient_fill_cmds.rs | 4 +-- crates/engine/src/cmd/layer_menu_cmds.rs | 2 +- crates/engine/src/cmd/layer_params.rs | 8 +---- crates/engine/src/cmd/paint_cmds.rs | 6 ++-- crates/engine/src/cmd/retouch_cmds.rs | 2 +- crates/engine/src/cmd/retouch_cmds/clone.rs | 4 +-- crates/engine/src/cmd/retouch_cmds/dab.rs | 6 ++-- crates/engine/src/cmd/smart_cmds.rs | 2 +- crates/engine/src/cmd/smart_cmds/filters.rs | 6 ++-- crates/engine/src/cmd/vector_cmds.rs | 2 +- crates/engine/src/cmd/vector_cmds/paths.rs | 4 +-- crates/engine/src/group_options.rs | 4 +-- crates/engine/src/layer_style.rs | 8 ++--- crates/engine/src/new_layer.rs | 2 +- crates/engine/src/presets/styles.rs | 2 +- crates/ui-egui/src/control/dialogs.rs | 8 ++--- crates/ui-egui/src/control/dispatch.rs | 2 +- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/dialogs/blend_options.rs | 12 +++---- .../src/dialogs/fade_mode_list_tests.rs | 7 ++-- crates/ui-egui/src/dialogs/fade_modes.rs | 3 +- crates/ui-egui/src/dialogs/fill_ui.rs | 3 +- .../ui-egui/src/dialogs/new_group_ui/tests.rs | 2 +- crates/ui-egui/src/dialogs/new_layer_ui.rs | 5 ++- .../src/dialogs/smart_filter_dialog.rs | 5 ++- .../src/dialogs/smart_filter_dialog/tests.rs | 2 +- crates/ui-egui/src/dialogs/tests.rs | 5 +-- crates/ui-egui/src/panels/blend_rows_tests.rs | 3 +- crates/ui-egui/src/panels/layer_filter_ui.rs | 4 +-- .../src/panels/layer_filter_ui/tests.rs | 4 +-- crates/ui-egui/src/panels/layers_tree.rs | 12 ++----- 42 files changed, 108 insertions(+), 99 deletions(-) diff --git a/crates/color/src/blend.rs b/crates/color/src/blend.rs index 196a0dcafd..7b26f06a4f 100644 --- a/crates/color/src/blend.rs +++ b/crates/color/src/blend.rs @@ -46,6 +46,23 @@ pub enum BlendMode { PaintNetColorDodge, } +/// Parse legacy command names and labels, retaining their case and punctuation tolerance. +pub fn parse_blend(s: &str) -> Option { + fn normalize(value: &str) -> String { + value.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], "") + } + static ALIASES: std::sync::OnceLock> = std::sync::OnceLock::new(); + let aliases = ALIASES.get_or_init(|| { + let mut aliases = std::collections::HashMap::new(); + for mode in std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()) { + aliases.entry(normalize(mode.label())).or_insert(mode); + aliases.entry(normalize(&format!("{mode:?}"))).or_insert(mode); + } + aliases + }); + aliases.get(&normalize(s)).copied() +} + impl BlendMode { /// Stable key used by the Layers panel. pub fn key(self) -> &'static str { @@ -674,6 +691,25 @@ mod tests; mod key_tests { use super::BlendMode; + #[test] + fn parser_preserves_legacy_names_and_normalization() { + let normalize = |s: &str| s.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], ""); + let legacy = |s: &str| { + let wanted = normalize(s); + std::iter::once(BlendMode::PassThrough) + .chain(BlendMode::layer_modes()) + .find(|mode| normalize(mode.label()) == wanted || normalize(&format!("{mode:?}")) == wanted) + }; + for mode in std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()) { + for name in [mode.label().to_owned(), format!("{mode:?}"), mode.label().to_ascii_uppercase().replace(' ', "_-")] { + assert_eq!(super::parse_blend(&name), legacy(&name), "{name}"); + } + } + for name in ["", "not a mode", "color.burn", "é"] { + assert_eq!(super::parse_blend(name), legacy(name), "{name}"); + } + } + #[test] fn canonical_keys_match_legacy_panel_names_and_round_trip() { for mode in std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()) { diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c2d10acae7..809fd05d96 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -1,6 +1,6 @@ //! The command registry. Ids follow Photoshop's menu structure (see the parity checklist). -use photocraft_color::{BlendMode, Color, ColorMode, SampleType}; +use photocraft_color::{Color, ColorMode, SampleType}; use photocraft_doc::{Adjustment, Document, Fill, Layer, LayerContent, LayerId, LayerMask, Size}; use photocraft_geom::{Rect, TILE_SIZE}; use photocraft_raster::Surface; @@ -189,13 +189,13 @@ use adjust_params::{adjust_mode, destructive_adjust, doc_mode, new_adjustment}; pub use adjust_params::{adjustment_from_params, adjustment_kind}; pub(crate) use enabled::{always, check_all_unlocked, check_pixels_unlocked, has_paintable, is_mask_target, paint_surface}; use enabled::{can_redo, can_undo, has_doc, has_layer, has_pixel_or_channel, has_selection}; -pub use layer_params::blend_from_str; pub(crate) use layer_params::{NEW_LAYER_PATH, explicit_layer, layer_listing, layer_panel_option, layer_param, mask_at_depth, mask_new_layer, selection_mask}; pub(crate) use layer_references::{recorded_drop, recorded_layer}; use ops::{arrange, merge_group, move_mask, set_mask, set_mask_and_deselect}; pub(crate) use ops::{layer_copy, translate_layer, translate_layer_wrapped}; use params::{bad, set_clipped}; pub(crate) use params::{check_f32_values, cmyk_param, color_param, int, int_i32, parse_hex, u32_id, u32_id_param}; +pub use photocraft_color::blend::parse_blend; pub fn command_specs() -> &'static [CommandSpec] { ®istry().specs @@ -726,7 +726,7 @@ fn build() -> Vec { // The Background has no opacity, fill or blend mode: like Photoshop, setting // one that changes its look turns it into a normal layer ("Layer 0") first. let num = |k: &str| p.get(k).and_then(Value::as_f64).is_some_and(|v| v < 1.0); - let blends = p.get("blend").and_then(Value::as_str).and_then(blend_from_str).is_some_and(|b| b != photocraft_color::BlendMode::Normal); + let blends = p.get("blend").and_then(Value::as_str).and_then(parse_blend).is_some_and(|b| b != photocraft_color::BlendMode::Normal); for &id in &ids { if num("opacity") || num("fill") || blends { crate::extra_cmds::background_to_layer(doc, id); @@ -745,7 +745,7 @@ fn build() -> Vec { l.fill_opacity = v; } if let Some(v) = p.get("blend").and_then(Value::as_str) { - let b = blend_from_str(v).ok_or_else(|| bad("layer.setProps", format!("unknown blend mode `{v}`")))?; + let b = parse_blend(v).ok_or_else(|| bad("layer.setProps", format!("unknown blend mode `{v}`")))?; // Pass Through is a group's mode only, as in Photoshop. if b == photocraft_color::BlendMode::PassThrough && !l.is_group() { return Err(bad("layer.setProps", format!("Pass Through applies to groups only; layer {} isn't one", l.id.0))); diff --git a/crates/engine/src/cmd/adjust_params.rs b/crates/engine/src/cmd/adjust_params.rs index 416016c8d3..fa078383e2 100644 --- a/crates/engine/src/cmd/adjust_params.rs +++ b/crates/engine/src/cmd/adjust_params.rs @@ -24,7 +24,7 @@ pub(super) fn new_adjustment(s: &mut Session, adj: Adjustment, p: &Value, cmd: & None | Some(Value::Null) => BlendMode::Normal, Some(v) => { let m = v.as_str().ok_or_else(|| bad("`mode` must be a blend mode name".into()))?; - crate::commands::blend_from_str(m).filter(|b| *b != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown layer blend mode `{m}`")))? + crate::commands::parse_blend(m).filter(|b| *b != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown layer blend mode `{m}`")))? } }; let clip = match p.get("clipToPrevious") { diff --git a/crates/engine/src/cmd/atn_cmds/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs index 0e16f09c8f..995a7120e5 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_make.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -892,7 +892,7 @@ fn adjustment_layer_to(id: &str, p: &Value) -> Option { None | Some(Value::Null) => None, Some(v) => { let label = v.as_str()?; - if crate::commands::blend_from_str(label)? == photocraft_doc::BlendMode::PassThrough { + if crate::commands::parse_blend(label)? == photocraft_doc::BlendMode::PassThrough { return None; } Some(blend_ps(label)?) diff --git a/crates/engine/src/cmd/atn_cmds/tables.rs b/crates/engine/src/cmd/atn_cmds/tables.rs index 0a6a07abee..6751291997 100644 --- a/crates/engine/src/cmd/atn_cmds/tables.rs +++ b/crates/engine/src/cmd/atn_cmds/tables.rs @@ -56,7 +56,7 @@ pub(super) fn blend_label(ps: &str) -> Option<&'static str> { } pub(super) fn blend_ps(label: &str) -> Option<&'static str> { - crate::commands::blend_from_str(label).and_then(|m| BLEND_MODES.iter().find(|(_, v)| crate::commands::blend_from_str(v) == Some(m))).map(|(k, _)| *k) + crate::commands::parse_blend(label).and_then(|m| BLEND_MODES.iter().find(|(_, v)| crate::commands::parse_blend(v) == Some(m))).map(|(k, _)| *k) } /// Photoshop ↔ PhotoCraft value tables; Photoshop codes compare without their space padding. diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index f17b5b28b4..afd521e942 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -448,7 +448,7 @@ fn with_blend_mode(mut b: BrushSettings, p: &Value) -> BrushSettings { } else if p.get("mode").and_then(Value::as_str).is_some_and(|m| m.eq_ignore_ascii_case("behind")) { b.mode = photocraft_color::BlendMode::Normal; b.behind = true; - } else if let Some(m) = p.get("mode").and_then(Value::as_str).and_then(crate::commands::blend_from_str) { + } else if let Some(m) = p.get("mode").and_then(Value::as_str).and_then(crate::commands::parse_blend) { b.mode = m; b.behind = false; } diff --git a/crates/engine/src/cmd/channel_cmds/refs.rs b/crates/engine/src/cmd/channel_cmds/refs.rs index 39a56e1928..eace867c12 100644 --- a/crates/engine/src/cmd/channel_cmds/refs.rs +++ b/crates/engine/src/cmd/channel_cmds/refs.rs @@ -314,7 +314,7 @@ impl Blending { match name.to_ascii_lowercase().as_str() { "add" => Ok(Blending::Add { scale, offset }), "subtract" => Ok(Blending::Subtract { scale, offset }), - other => match crate::commands::blend_from_str(other) { + other => match crate::commands::parse_blend(other) { Some(m) if m.is_separable() && !matches!(m, BlendMode::Dissolve | BlendMode::PassThrough) => Ok(Blending::Mode(m)), _ => Err(format!("unsupported blending `{other}`")), }, diff --git a/crates/engine/src/cmd/edit_menu_cmds.rs b/crates/engine/src/cmd/edit_menu_cmds.rs index fab273a9a6..a78e39e49b 100644 --- a/crates/engine/src/cmd/edit_menu_cmds.rs +++ b/crates/engine/src/cmd/edit_menu_cmds.rs @@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use crate::channel_cmds::Target; -use crate::commands::{CommandSpec, blend_from_str, int, layer_param}; +use crate::commands::{CommandSpec, int, layer_param, parse_blend}; use crate::{EngineError, Result, Session}; // ------------------------------------------------------------------ state diff --git a/crates/engine/src/cmd/edit_menu_cmds/fade.rs b/crates/engine/src/cmd/edit_menu_cmds/fade.rs index e8c797b212..59f15057e3 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/fade.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/fade.rs @@ -1,5 +1,5 @@ use super::{ - BlendMode, Document, EngineError, FadeSource, FadeTarget, Rect, Result, Session, Surface, Value, bad, blend_from_str, f32_or, from_rgba_into, json, str_or, + BlendMode, Document, EngineError, FadeSource, FadeTarget, Rect, Result, Session, Surface, Value, bad, f32_or, from_rgba_into, json, parse_blend, str_or, surface_of, surface_of_mut, to_rgba, }; @@ -103,7 +103,7 @@ fn fade_job(s: &Session, p: &Value) -> Result { let cmd = "edit.fade"; let src = s.edit_state.fade.clone().ok_or_else(|| bad(cmd, "nothing to fade"))?; let opacity = f32_or(p, "opacity", 100.0).clamp(0.0, 100.0) / 100.0; - let mode = blend_from_str(str_or(p, "mode", "normal")).ok_or_else(|| bad(cmd, "unknown blend mode"))?; + let mode = parse_blend(str_or(p, "mode", "normal")).ok_or_else(|| bad(cmd, "unknown blend mode"))?; let st = s.active().ok_or(EngineError::NoDocument)?; let prev = before_state(st, &src).ok_or_else(|| bad(cmd, "no previous state"))?; let before = surface_of(&prev, src.target).cloned().ok_or_else(|| EngineError::Other("the layer or channel did not exist before this step".into()))?; diff --git a/crates/engine/src/cmd/extra_cmds.rs b/crates/engine/src/cmd/extra_cmds.rs index 505048f6ae..7e09659db9 100644 --- a/crates/engine/src/cmd/extra_cmds.rs +++ b/crates/engine/src/cmd/extra_cmds.rs @@ -147,7 +147,7 @@ fn stroke(s: &mut Session, p: &Value) -> Result { let picked = s.tools.picked_cmyk([color[0], color[1], color[2]]); let mode = match p.get("mode") { None | Some(Value::Null) => photocraft_color::BlendMode::Normal, - Some(Value::String(m)) => crate::commands::blend_from_str(m) + Some(Value::String(m)) => crate::commands::parse_blend(m) .filter(|m| *m != photocraft_color::BlendMode::PassThrough) .ok_or_else(|| EngineError::BadParams { cmd: "edit.stroke".into(), msg: format!("unknown blend mode `{m}`") })?, Some(v) => return Err(EngineError::BadParams { cmd: "edit.stroke".into(), msg: format!("mode must be a blend mode name, not {v}") }), diff --git a/crates/engine/src/cmd/fill_cmds.rs b/crates/engine/src/cmd/fill_cmds.rs index 988a5b4aad..2d16adb077 100644 --- a/crates/engine/src/cmd/fill_cmds.rs +++ b/crates/engine/src/cmd/fill_cmds.rs @@ -11,7 +11,7 @@ use photocraft_geom::{Rect, TILE_SIZE}; use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use serde_json::{Value, json}; -use crate::commands::{blend_from_str, color_param, layer_param}; +use crate::commands::{color_param, layer_param, parse_blend}; use crate::{EngineError, Result, Session}; const CMD: &str = "edit.fill"; @@ -66,7 +66,7 @@ fn contents(p: &Value) -> Result<&str> { fn mode(p: &Value) -> Result { match p.get("mode") { None | Some(Value::Null) => Ok(BlendMode::Normal), - Some(Value::String(m)) => blend_from_str(m).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown blend mode `{m}`"))), + Some(Value::String(m)) => parse_blend(m).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown blend mode `{m}`"))), Some(v) => Err(bad(format!("`mode` must be a blend mode name, not {v}"))), } } diff --git a/crates/engine/src/cmd/gradient_fill_cmds.rs b/crates/engine/src/cmd/gradient_fill_cmds.rs index 39a61de8f4..7a4e036409 100644 --- a/crates/engine/src/cmd/gradient_fill_cmds.rs +++ b/crates/engine/src/cmd/gradient_fill_cmds.rs @@ -17,7 +17,7 @@ use photocraft_doc::{Document, Fill, GradientStyle, Layer, LayerContent, LayerId use photocraft_geom::Rect; use serde_json::{Value, json}; -use crate::commands::{CommandSpec, blend_from_str, check_pixels_unlocked, layer_param}; +use crate::commands::{CommandSpec, check_pixels_unlocked, layer_param, parse_blend}; use crate::presets::gradients::{GradientPreset, transparency_param}; use crate::{EngineError, Result, Session}; @@ -300,7 +300,7 @@ pub fn new_layer(s: &Session, doc: &Document, p: &Value) -> Result { let opacity = num(p, "opacity").unwrap_or(100.0).clamp(0.0, 100.0) / 100.0; let blend = match p.get("mode").and_then(Value::as_str) { None | Some("") => photocraft_color::BlendMode::Normal, - Some(m) => blend_from_str(m).ok_or_else(|| bad(CMD, format!("unknown blend mode `{m}`")))?, + Some(m) => parse_blend(m).ok_or_else(|| bad(CMD, format!("unknown blend mode `{m}`")))?, }; let canvas = doc.bounds(); if canvas.is_empty() { diff --git a/crates/engine/src/cmd/layer_menu_cmds.rs b/crates/engine/src/cmd/layer_menu_cmds.rs index 944b6755c6..448b047067 100644 --- a/crates/engine/src/cmd/layer_menu_cmds.rs +++ b/crates/engine/src/cmd/layer_menu_cmds.rs @@ -525,7 +525,7 @@ fn blending_options(s: &mut Session, p: &Value) -> Result { const CMD: &str = "layer.layerStyle.blendingOptions"; let id = layer_param(s, p)?; let blend = match p.get("blend").and_then(Value::as_str) { - Some(b) => Some(crate::commands::blend_from_str(b).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?), + Some(b) => Some(crate::commands::parse_blend(b).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?), None => None, }; let opacity = p.get("opacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0)); diff --git a/crates/engine/src/cmd/layer_params.rs b/crates/engine/src/cmd/layer_params.rs index 82726f8369..1f15afea2e 100644 --- a/crates/engine/src/cmd/layer_params.rs +++ b/crates/engine/src/cmd/layer_params.rs @@ -1,5 +1,5 @@ use super::params::bad; -use super::{BlendMode, Document, EngineError, Layer, LayerId, LayerMask, Result, SampleType, Session, Value}; +use super::{Document, EngineError, Layer, LayerId, LayerMask, Result, SampleType, Session, Value}; /// The layer a command's `"layer"` param names: an id, or a name (the topmost layer of that /// name, as Photoshop's "select layer by name" action step finds it, so a loaded action replays @@ -72,12 +72,6 @@ pub(crate) fn layer_param(s: &Session, p: &Value) -> Result { } } -pub fn blend_from_str(s: &str) -> Option { - let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], ""); - let want = norm(s); - std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()).find(|m| norm(m.label()) == want || norm(&format!("{m:?}")) == want) -} - /// The active selection as the mask of a layer being created, or None without a selection. /// Photoshop masks a new adjustment or fill layer with the selection, so the adjustment acts on /// the selected area only (#1250). [`mask_new_layer`] then drops the selection (#8801). diff --git a/crates/engine/src/cmd/paint_cmds.rs b/crates/engine/src/cmd/paint_cmds.rs index e4e0c2265a..ffe6720b56 100644 --- a/crates/engine/src/cmd/paint_cmds.rs +++ b/crates/engine/src/cmd/paint_cmds.rs @@ -3,7 +3,7 @@ use photocraft_algo::paint::{FillMode, GradientShape, bucket_fill_inks, bucket_fill_region_inks, paint_gradient}; use serde_json::{Value, json}; -use crate::commands::{CommandSpec, blend_from_str}; +use crate::commands::{CommandSpec, parse_blend}; use crate::presets::gradients; use crate::{EngineError, Result, Session}; @@ -47,7 +47,7 @@ fn fill_mode(p: &Value) -> Result { match p.get("mode") { None | Some(Value::Null) => Ok(FillMode::Blend(photocraft_color::BlendMode::Normal)), Some(Value::String(m)) if m.eq_ignore_ascii_case("clear") => Ok(FillMode::Clear), - Some(Value::String(m)) => blend_from_str(m) + Some(Value::String(m)) => parse_blend(m) .filter(|m| *m != photocraft_color::BlendMode::PassThrough) .map(FillMode::Blend) .ok_or_else(|| bad(format!("unknown blend mode `{m}`"))), @@ -186,7 +186,7 @@ fn gradient(s: &mut Session, p: &Value) -> Result { }; let reverse = b(p, "reverse", false); let opacity = opacity(p, "paint.gradient")?; - let blend = p.get("mode").and_then(Value::as_str).and_then(blend_from_str).unwrap_or(photocraft_color::BlendMode::Normal); + let blend = p.get("mode").and_then(Value::as_str).and_then(parse_blend).unwrap_or(photocraft_color::BlendMode::Normal); let dither = b(p, "dither", true); // Photoshop dithers gradients by default (reduces banding). let layer = if p.get("layer").is_some() { Some(crate::commands::layer_param(s, p)?) } else { s.active().and_then(|st| st.active_layer) }; s.edit("Gradient", |doc, _| { diff --git a/crates/engine/src/cmd/retouch_cmds.rs b/crates/engine/src/cmd/retouch_cmds.rs index 95cbe7ca99..868a5428ba 100644 --- a/crates/engine/src/cmd/retouch_cmds.rs +++ b/crates/engine/src/cmd/retouch_cmds.rs @@ -22,7 +22,7 @@ use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use rayon::prelude::*; use serde_json::{Value, json}; -use crate::commands::{CommandSpec, blend_from_str}; +use crate::commands::{CommandSpec, parse_blend}; use crate::{EngineError, Result, Session}; mod art_history; diff --git a/crates/engine/src/cmd/retouch_cmds/clone.rs b/crates/engine/src/cmd/retouch_cmds/clone.rs index ada043ade4..59c39ab183 100644 --- a/crates/engine/src/cmd/retouch_cmds/clone.rs +++ b/crates/engine/src/cmd/retouch_cmds/clone.rs @@ -3,7 +3,7 @@ use super::heal::history_source; use super::sampling::{SampleLayers, sample_layers}; use super::{ BlendMode, BrushSettings, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, SampleType, Session, Stroke, StrokePoint, Surface, Value, - alpha_index, apply_coverage, bad, blend_from_str, coverage, damage_json, flag, has_pixel_layer, json, parse_brush, pattern_stamp, periodic, point, + alpha_index, apply_coverage, bad, coverage, damage_json, flag, has_pixel_layer, json, parse_blend, parse_brush, pattern_stamp, periodic, point, reject_huge_stroke, run_stroke, to_rgba, }; @@ -212,7 +212,7 @@ pub(super) fn clone_result(dmg: Rect, off: (i32, i32), aligned: bool, p: &Value, pub(super) fn blend_param(p: &Value, cmd: &str) -> Result { match p.get("mode").and_then(Value::as_str) { None => Ok(BlendMode::Normal), - Some(m) => blend_from_str(m).ok_or_else(|| bad(cmd, format!("unknown blend mode `{m}`"))), + Some(m) => parse_blend(m).ok_or_else(|| bad(cmd, format!("unknown blend mode `{m}`"))), } } diff --git a/crates/engine/src/cmd/retouch_cmds/dab.rs b/crates/engine/src/cmd/retouch_cmds/dab.rs index 564df7512d..7c17ecf9e5 100644 --- a/crates/engine/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine/src/cmd/retouch_cmds/dab.rs @@ -1,8 +1,8 @@ use super::sampling::{AllLayers, sample_all_layers}; use super::{ BlendMode, BrushSettings, Document, EngineError, Footprint, IndexedParallelIterator, LayerId, ParallelIterator, ParallelSliceMut, PixelFormat, Rect, - Region, Result, Session, Smudge, Stroke, StrokePoint, Surface, ToneRange, Value, alpha_index, apply_dab_stroke, bad, blend_from_str, damage_json, - dodge_burn, flag, from_rgba_into, has_pixel_layer, json, local_blur, local_sharpen, num, parse_brush, run_stroke, sponge, string, to_rgba, + Region, Result, Session, Smudge, Stroke, StrokePoint, Surface, ToneRange, Value, alpha_index, apply_dab_stroke, bad, damage_json, dodge_burn, flag, + from_rgba_into, has_pixel_layer, json, local_blur, local_sharpen, num, parse_blend, parse_brush, run_stroke, sponge, string, to_rgba, }; // --------------------------------------------------------------------------------------------- @@ -206,7 +206,7 @@ pub(super) enum DabTool { fn smudge_mode(p: &Value, cmd: &str) -> Result { use BlendMode::{Color, Darken, Hue, Lighten, Luminosity, Normal, Saturation}; let Some(v) = p.get("mode") else { return Ok(Normal) }; - let named = v.as_str().and_then(blend_from_str).filter(|m| matches!(m, Normal | Darken | Lighten | Hue | Saturation | Color | Luminosity)); + let named = v.as_str().and_then(parse_blend).filter(|m| matches!(m, Normal | Darken | Lighten | Hue | Saturation | Color | Luminosity)); named.ok_or_else(|| { let given = v.as_str().map_or_else(|| v.to_string(), str::to_owned); bad(cmd, format!("unknown mode `{given}` (normal|darken|lighten|hue|saturation|color|luminosity)")) diff --git a/crates/engine/src/cmd/smart_cmds.rs b/crates/engine/src/cmd/smart_cmds.rs index ada909f54b..ffb172cf88 100644 --- a/crates/engine/src/cmd/smart_cmds.rs +++ b/crates/engine/src/cmd/smart_cmds.rs @@ -34,7 +34,7 @@ use photocraft_raster::Surface; use serde_json::{Value, json}; use stack_cache::{Stage, StageKey}; -use crate::commands::{CommandSpec, blend_from_str, layer_param}; +use crate::commands::{CommandSpec, layer_param, parse_blend}; use crate::jobs::JobCtx; use crate::{EngineError, Result, Session}; diff --git a/crates/engine/src/cmd/smart_cmds/filters.rs b/crates/engine/src/cmd/smart_cmds/filters.rs index c37c17a6f2..46a5ccba39 100644 --- a/crates/engine/src/cmd/smart_cmds/filters.rs +++ b/crates/engine/src/cmd/smart_cmds/filters.rs @@ -1,8 +1,8 @@ use super::rendering::{refresh_or_fail, refresh_or_fail_in}; use super::source::source_bytes; use super::{ - BlendMode, Document, EngineError, Layer, LayerContent, LayerId, LayerMask, Result, Session, SmartObject, Surface, Value, bad, blend_from_str, json, - layer_param, other, + BlendMode, Document, EngineError, Layer, LayerContent, LayerId, LayerMask, Result, Session, SmartObject, Surface, Value, bad, json, layer_param, other, + parse_blend, }; pub(super) fn smart(doc: &Document, id: LayerId) -> Result<&SmartObject> { @@ -241,7 +241,7 @@ pub(super) fn set_filter_params(s: &mut Session, p: &Value) -> Result { pub(super) fn blending_options(s: &mut Session, p: &Value) -> Result { const CMD: &str = "layer.smartFilter.blendingOptions"; let blend = match p.get("blend").and_then(Value::as_str) { - Some(b) => Some(blend_from_str(b).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?), + Some(b) => Some(parse_blend(b).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?), None => None, }; let opacity = p.get("opacity").and_then(Value::as_f64).map(|o| if o > 1.0 { o / 100.0 } else { o } as f32); diff --git a/crates/engine/src/cmd/vector_cmds.rs b/crates/engine/src/cmd/vector_cmds.rs index 9c91142e26..aa9e9a33ce 100644 --- a/crates/engine/src/cmd/vector_cmds.rs +++ b/crates/engine/src/cmd/vector_cmds.rs @@ -26,7 +26,7 @@ use photocraft_geom::{Affine, Point, Rect}; use photocraft_vector as vector; use serde_json::{Value, json}; -use crate::commands::{CommandSpec, blend_from_str}; +use crate::commands::{CommandSpec, parse_blend}; use crate::{EngineError, Result, Session}; /// Keys PSD uses for a shape layer's vector data; dropped when a shape is rasterized. diff --git a/crates/engine/src/cmd/vector_cmds/paths.rs b/crates/engine/src/cmd/vector_cmds/paths.rs index df8d922b45..5fdda419f9 100644 --- a/crates/engine/src/cmd/vector_cmds/paths.rs +++ b/crates/engine/src/cmd/vector_cmds/paths.rs @@ -2,7 +2,7 @@ use super::params::{color, f64p, layer_id, op_from, parse_path, path_json}; use super::shape::{map_path, map_shape, transform_shape, with_shape}; use super::{ Affine, BlendMode, ClippingPath, Color, Document, EngineError, LayerContent, LayerId, NamedPath, Path, Rect, Result, SelectionMode, Session, Value, bad, - blend_from_str, json, sel, vector, + json, parse_blend, sel, vector, }; // --------------------------------------------------------------------------- @@ -444,7 +444,7 @@ pub(super) fn path_fill(s: &mut Session, p: &Value) -> Result { let rgb = c.to_rgb(); let src = [rgb[0], rgb[1], rgb[2], c.alpha]; let opacity = (f64p(p, "opacity").unwrap_or(100.0) / 100.0).clamp(0.0, 1.0) as f32; - let mode = p.get("mode").and_then(Value::as_str).and_then(blend_from_str).unwrap_or(BlendMode::Normal); + let mode = p.get("mode").and_then(Value::as_str).and_then(parse_blend).unwrap_or(BlendMode::Normal); let feather = f64p(p, "feather").unwrap_or(0.0) as f32; let aa = p.get("antiAlias").and_then(Value::as_bool).unwrap_or(true); let id = layer_id(s, p)?; diff --git a/crates/engine/src/group_options.rs b/crates/engine/src/group_options.rs index dd2ddee02f..a2a50f027b 100644 --- a/crates/engine/src/group_options.rs +++ b/crates/engine/src/group_options.rs @@ -37,9 +37,7 @@ impl GroupOptions { let blend = match get("mode") { None => None, Some(v) => Some( - v.as_str() - .and_then(crate::commands::blend_from_str) - .ok_or_else(|| bad("`mode` must be a blend mode such as \"passThrough\" or \"multiply\""))?, + v.as_str().and_then(crate::commands::parse_blend).ok_or_else(|| bad("`mode` must be a blend mode such as \"passThrough\" or \"multiply\""))?, ), }; let opacity = match get("opacity") { diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs index 9f7c2c7873..6a4e683fa7 100644 --- a/crates/engine/src/layer_style.rs +++ b/crates/engine/src/layer_style.rs @@ -9,7 +9,7 @@ use photocraft_doc::{ }; use serde_json::{Value, json}; -use crate::commands::{CommandSpec, blend_from_str}; +use crate::commands::{CommandSpec, parse_blend}; use crate::presets::{always, bad}; use crate::{EngineError, Result, Session}; @@ -714,7 +714,7 @@ fn overlay_common(c: &mut FxCommon, p: &Value) { if let Some(x) = b_of(p, "enabled") { c.enabled = x; } - if let Some(x) = p.get("blend").and_then(Value::as_str).and_then(blend_from_str) { + if let Some(x) = p.get("blend").and_then(Value::as_str).and_then(parse_blend) { c.blend = x; } if let Some(x) = f_of(p, "opacity") { @@ -883,10 +883,10 @@ fn overlay_bevel(bv: &mut Bevel, p: &Value) { } overlay_contour(p, "glossContour", &mut bv.gloss_contour); overlay_bool(p, "glossAntiAlias", &mut bv.gloss_anti_alias); - if let Some(blend) = p.get("highlightBlend").and_then(Value::as_str).and_then(blend_from_str) { + if let Some(blend) = p.get("highlightBlend").and_then(Value::as_str).and_then(parse_blend) { bv.highlight.blend = blend; } - if let Some(blend) = p.get("shadowBlend").and_then(Value::as_str).and_then(blend_from_str) { + if let Some(blend) = p.get("shadowBlend").and_then(Value::as_str).and_then(parse_blend) { bv.shadow.blend = blend; } overlay_color(p, "highlightColor", &mut bv.highlight_color); diff --git a/crates/engine/src/new_layer.rs b/crates/engine/src/new_layer.rs index b102907ccc..ed05e24c8e 100644 --- a/crates/engine/src/new_layer.rs +++ b/crates/engine/src/new_layer.rs @@ -74,7 +74,7 @@ pub(crate) fn parse(p: &Value) -> Result { None | Some(Value::Null) => BlendMode::Normal, Some(v) => { let name = v.as_str().ok_or_else(|| bad("`mode` must be a blend mode name"))?; - crate::commands::blend_from_str(name).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown layer blend mode `{name}`")))? + crate::commands::parse_blend(name).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown layer blend mode `{name}`")))? } }; let opacity = match p.get("opacity") { diff --git a/crates/engine/src/presets/styles.rs b/crates/engine/src/presets/styles.rs index cac8fb158a..241cea036f 100644 --- a/crates/engine/src/presets/styles.rs +++ b/crates/engine/src/presets/styles.rs @@ -280,7 +280,7 @@ fn new_preset(s: &mut Session, p: &Value) -> Result { } } }, - blend: p.get("blend").and_then(Value::as_str).and_then(crate::commands::blend_from_str).or_else(|| with_blend.then_some(l.blend)), + blend: p.get("blend").and_then(Value::as_str).and_then(crate::commands::parse_blend).or_else(|| with_blend.then_some(l.blend)), fill_opacity: p.get("fillOpacity").and_then(Value::as_f64).map(|v| (v / 100.0).clamp(0.0, 1.0) as f32).or_else(|| with_blend.then_some(l.fill_opacity)), opacity: p.get("opacity").and_then(Value::as_f64).map(|v| (v / 100.0).clamp(0.0, 1.0) as f32).or_else(|| with_blend.then_some(l.opacity)), }; diff --git a/crates/ui-egui/src/control/dialogs.rs b/crates/ui-egui/src/control/dialogs.rs index 3e40a1788a..f7423d0441 100644 --- a/crates/ui-egui/src/control/dialogs.rs +++ b/crates/ui-egui/src/control/dialogs.rs @@ -199,14 +199,10 @@ fn dont_save_all(_: &Value, _: &Value) -> Vec<(String, Value)> { vec![pair("applyToAll", json!(true)), pair("choice", json!("dontSave"))] } -/// A blend label such as "Multiply" to the Blend row's id; a string `blend_from_str` refuses passes through so the +/// A blend label such as "Multiply" to the Blend row's id; a string `parse_blend` refuses passes through so the /// row refuses it. fn blend_id(value: &Value) -> Value { - value - .as_str() - .and_then(photocraft_engine::commands::blend_from_str) - .map(|mode| json!(crate::panels::layers_tree::blend_key(mode).to_string())) - .unwrap_or_else(|| value.clone()) + value.as_str().and_then(photocraft_engine::commands::parse_blend).map(|mode| json!(mode.key().to_string())).unwrap_or_else(|| value.clone()) } // PLAN: the framework field ids `mode` (Fill, Stroke) and `blend` (Smart Filter) are assumed (dialogs-w22 by request). diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index ea4a202f17..52f5bb000c 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -615,7 +615,7 @@ fn marquee_params(app: &PhotocraftApp, p: &Value) -> std::result::Result<(Option fn gradient_blend_param(p: &Value) -> std::result::Result, String> { let Some(value) = p.get("gradientBlendMode") else { return Ok(None) }; let Some(name) = value.as_str() else { return Err("gradientBlendMode must be a blend mode name".into()) }; - photocraft_engine::commands::blend_from_str(name) + photocraft_engine::commands::parse_blend(name) .filter(|m| photocraft_color::BlendMode::LAYER_MODES.contains(m)) .map(Some) .ok_or_else(|| format!("unknown gradient blend mode `{name}`")) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4b7963e120..30b71c92b4 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -660,7 +660,7 @@ fn convert_blend_mode(key: &str, value: &mut Value) { } let Some(mode) = value.get_mut("mode") else { return }; if let Some(blend) = mode.as_str().and_then(crate::panels::layers_tree::blend_of) { - *mode = Value::String(crate::panels::layers_tree::blend_key(blend)); + *mode = Value::String(blend.key().to_string()); } } diff --git a/crates/ui-egui/src/dialogs/blend_options.rs b/crates/ui-egui/src/dialogs/blend_options.rs index c0a99dce95..6d48c6ec82 100644 --- a/crates/ui-egui/src/dialogs/blend_options.rs +++ b/crates/ui-egui/src/dialogs/blend_options.rs @@ -6,18 +6,18 @@ use craft::ui::runtime::env::Label; use photocraft_color::BlendMode; use serde_json::{Map, Value, json}; -use crate::panels::layers_tree::blend_key; - /// A blend-mode row `key` over the Layers panel's mode list (`group` adds Pass Through), opening on `current`. pub(crate) fn blend_param(key: &str, label: impl Into