From 9c022d3cdc40143c3bb292a29c36556cc0c44fad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 13:52:37 -0800 Subject: [PATCH 1/9] design-lint: clear the layer/import and props/hand-setter findings on main craft-design-lint's mapped_crates_have_no_findings test failed on main with two findings: - crates/ui-contract/src/runtime/access/scope.rs:710, layer/import: the label scope (layer 2) called crate::layout::record_baseline, which lives in layout::label (layer 4). The call came in with afd18d148. Recording a control's baseline and the key the baselines of a control size are noted under now live in runtime::layout_memory as record_control_baseline and control_baseline_kind. The label scope and layout::label both call them, and the behavior is unchanged. - crates/ui-patterns/src/patterns/presets/browser.rs:449, props/hand-setter: PresetBrowser::host_version, added in 16f896280, only stored its argument. The field is now a #[prop], and #[derive(Props)] writes the same setter with the same documentation. --- crates/ui-contract/src/layout/label.rs | 18 ++---------------- crates/ui-contract/src/layout/mod.rs | 1 - crates/ui-contract/src/runtime/access/scope.rs | 2 +- .../ui-contract/src/runtime/layout_memory.rs | 15 +++++++++++++++ .../src/patterns/presets/browser.rs | 15 +++++---------- 5 files changed, 23 insertions(+), 28 deletions(-) diff --git a/crates/ui-contract/src/layout/label.rs b/crates/ui-contract/src/layout/label.rs index 94dfd9e2d0..115472679b 100644 --- a/crates/ui-contract/src/layout/label.rs +++ b/crates/ui-contract/src/layout/label.rs @@ -18,16 +18,7 @@ pub fn place_label(ui: &Ui, id: Id, size: ControlSize, column: &LabelColumn, flo /// Stores the distance from the top of the control of `size` of the row `id` to its first baseline, for the next /// pass's `place_label`, and for the first appearance of later rows with a control of `size`. pub fn record_control_baseline(ui: &Ui, id: Id, size: ControlSize, baseline: f32) { - record_baseline(ui.ctx(), id, Some(size), baseline); -} - -/// `record_control_baseline` for the control of the row `id`; `size`: the control's size, when the row's label step -/// knows it. -pub(crate) fn record_baseline(ctx: &egui::Context, id: Id, size: Option, baseline: f32) { - layout_memory::record(ctx, sub(id, "baseline"), Vec2::new(0.0, baseline)); - if let Some(size) = size { - layout_memory::note_typical(ctx, baseline_kind(size), Vec2::new(0.0, baseline)); - } + layout_memory::record_control_baseline(ui.ctx(), id, Some(size), baseline); } /// The first baseline of the control of `size` of the row `id`, from its top, as `record_control_baseline` stored it @@ -39,13 +30,8 @@ pub fn control_baseline(ctx: &egui::Context, id: Id, size: ControlSize, label: V .map(|size| size.y) .or_else(|| layout_memory::read(ctx, sub(id, "centre")).map(|size| size.y + label_baseline - label.y / 2.0)); own.or_else(|| { - let typical = layout_memory::typical(ctx, baseline_kind(size))?; + let typical = layout_memory::typical(ctx, layout_memory::control_baseline_kind(size))?; layout_memory::assume(ctx, sub(id, "baseline"), typical); Some(typical.y) }) } - -/// The key the baselines of the controls of `size` are noted under. -fn baseline_kind(size: ControlSize) -> Id { - crate::runtime::memory::unique(("label control baseline", size)) -} diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 7912e0af94..56f35ae858 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -14,7 +14,6 @@ pub use column_group::ambient_width; #[doc(hidden)] pub use column_group::report_beyond; pub(crate) use column_group::{Columns, GLYPHS, LABELS, Reached, ambient_room, note_beside}; -pub(crate) use label::record_baseline; pub use label::{control_baseline, place_label, record_control_baseline}; pub use slot::measure_slot; diff --git a/crates/ui-contract/src/runtime/access/scope.rs b/crates/ui-contract/src/runtime/access/scope.rs index 8e798bbed5..8a8785c050 100644 --- a/crates/ui-contract/src/runtime/access/scope.rs +++ b/crates/ui-contract/src/runtime/access/scope.rs @@ -707,7 +707,7 @@ pub(crate) fn finish(ctx: &Context, container: Id, merged: Option) { crate::runtime::focus::request(ctx, only.inner_stop.unwrap_or(crate::runtime::focus::FocusTarget::Id(only.id))); } if let Some(baseline) = scope.baseline { - crate::layout::record_baseline(ctx, scope.container, scope.control_size, baseline - scope.control_top); + layout_memory::record_control_baseline(ctx, scope.container, scope.control_size, baseline - scope.control_top); } if let (None, Some(centre)) = (scope.baseline, scope.centre) { layout_memory::record(ctx, sub(scope.container, "centre"), Vec2::new(0.0, centre - scope.control_top)); diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 6021e1279a..d9c17e1578 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -528,6 +528,21 @@ pub(crate) fn note_typical(ctx: &Context, kind: Id, size: Vec2) { }); } +/// Stores `baseline`, the distance from the top of the control of the labeled row `row` to its first baseline, for the +/// next pass's label placement. With the control's `size`, it also notes the baseline for the first appearance of +/// later rows with a control of that size ([`control_baseline_kind`]). +pub(crate) fn record_control_baseline(ctx: &Context, row: Id, size: Option, baseline: f32) { + record(ctx, crate::runtime::memory::sub(row, "baseline"), Vec2::new(0.0, baseline)); + if let Some(size) = size { + note_typical(ctx, control_baseline_kind(size), Vec2::new(0.0, baseline)); + } +} + +/// The key the baselines of the controls of `size` are noted under ([`typical`]). +pub(crate) fn control_baseline_kind(size: craft_theme::ControlSize) -> Id { + crate::runtime::memory::unique(("label control baseline", size)) +} + /// This pass placed the block `id` by `size`, which it took from elsewhere (a block of the same kind, [`typical`]), /// where the entry under `id` holds no size yet: [`record`] compares the real size with `size`, as it compares a size /// from the last pass, so a first appearance that measures what the placement assumed asks no discard pass. It diff --git a/crates/ui-patterns/src/patterns/presets/browser.rs b/crates/ui-patterns/src/patterns/presets/browser.rs index 92754f95e2..af50959ada 100644 --- a/crates/ui-patterns/src/patterns/presets/browser.rs +++ b/crates/ui-patterns/src/patterns/presets/browser.rs @@ -361,7 +361,11 @@ pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 's drops: Vec>, /// The host's payloads a preset drag carries beside its `ListDrag`. payloads: Vec, - /// The version of what the host's closures read ([`host_version`](Self::host_version)). + /// The version of everything the host's closures read: the tip painter (`tip`), the row menu's rows (`row_items`), + /// the drop rules (`takes_drop`) and the payload maps (`drag_payload`). The host gives a new version whenever one + /// of them would answer differently. While the version holds and nothing reaches the presets, their view repaints + /// its last run; without a version a browser with any of those closures runs its view in every pass. + #[prop] host_version: Option, /// The search field is its scope's default stop (`Initial::Default`): a picker's popover opens with the focus in /// it, so typing filters the presets. @@ -442,15 +446,6 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> PresetBrowser self } - /// The version of everything the host's closures read: the tip painter (`tip`), the row menu's rows (`row_items`), - /// the drop rules (`takes_drop`) and the payload maps (`drag_payload`). The host gives a new version whenever one - /// of them would answer differently. While the version holds and nothing reaches the presets, their view repaints - /// its last run; without a version a browser with any of those closures runs its view in every pass. - pub fn host_version(mut self, version: u64) -> Self { - self.host_version = Some(version); - self - } - /// The id of the browser's list, the `ListDrag::list` of its drags: a footer action accepts only drags from its own /// browser. pub fn list_id(browser: Id) -> Id { From 379a2b30e7d1053e40f20a67cab4cbbf18ce4fc6 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 29 Nov 2026 23:23:14 +0100 Subject: [PATCH 2/9] Make TIFF pixel codecs optional while retaining metadata readers --- crates/craft/Cargo.toml | 1 + crates/image-codecs/Cargo.toml | 5 ++-- crates/image-codecs/README.md | 6 ++-- crates/image-codecs/src/codecs/tiff.rs | 3 ++ crates/image-codecs/src/codecs/tiff/decode.rs | 8 ++++- crates/image-codecs/src/codecs/tiff/encode.rs | 3 ++ crates/image-codecs/src/format.rs | 1 + crates/image-codecs/src/tiff_probe.rs | 5 ++-- .../image-codecs/tests/it/decode_warnings.rs | 10 +++++++ crates/image-codecs/tests/it/detect_caps.rs | 1 + crates/image-codecs/tests/it/fidelity.rs | 1 + crates/image-codecs/tests/it/limits.rs | 1 + crates/image-codecs/tests/it/main.rs | 11 +++++++ crates/image-codecs/tests/it/malformed.rs | 1 + crates/image-codecs/tests/it/metadata.rs | 6 ++-- crates/image-codecs/tests/it/orientation.rs | 13 ++++++-- crates/image-codecs/tests/it/png_jpeg.rs | 2 ++ crates/image-codecs/tests/it/roundtrip.rs | 4 +++ crates/image-codecs/tests/it/tiff_feature.rs | 30 +++++++++++++++++++ 19 files changed, 100 insertions(+), 12 deletions(-) create mode 100644 crates/image-codecs/tests/it/tiff_feature.rs diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index ebba43bc8e..21904d2acd 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -607,6 +607,7 @@ image-codecs-pnm = ["image-codecs", "craft-image-codecs/pnm"] image-codecs-sgi = ["image-codecs", "craft-image-codecs/sgi"] image-codecs-sunraster = ["image-codecs", "craft-image-codecs/sunraster"] image-codecs-tga = ["image-codecs", "craft-image-codecs/tga"] +image-codecs-tiff = ["image-codecs", "craft-image-codecs/tiff"] image-codecs-threads = ["image-codecs", "craft-image-codecs/threads"] image-codecs-webp = ["image-codecs", "craft-image-codecs/webp"] image-codecs-xpm = ["image-codecs", "craft-image-codecs/xpm"] diff --git a/crates/image-codecs/Cargo.toml b/crates/image-codecs/Cargo.toml index 8cb1b3b07e..5a05552fb6 100644 --- a/crates/image-codecs/Cargo.toml +++ b/crates/image-codecs/Cargo.toml @@ -15,7 +15,7 @@ corpus = [] # Every codec below is on by default; a build that never reads or writes a format can turn # `default-features` off and list the ones it needs. A format left out is still detected, and # reading or writing it returns `CodecError::Unsupported` naming the feature. -default = ["dds", "dicom", "dpx", "exr", "fits", "iff", "jp2", "jpegls", "jxl-encode", "pnm", "tga", "webp", "xpm"] +default = ["dds", "dicom", "dpx", "exr", "fits", "iff", "jp2", "jpegls", "jxl-encode", "pnm", "tga", "tiff", "webp", "xpm"] dds = [] dicom = [] # DPX and Cineon. @@ -29,6 +29,7 @@ jpegls = [] jxl-encode = ["dep:zune-jpegxl"] pnm = [] tga = ["image/tga"] +tiff = ["image/tiff"] webp = ["dep:image-webp"] xpm = [] # Opt in to threaded AVIF encoding without enabling AVIF (or assembly) by itself. @@ -53,7 +54,7 @@ jp2 = ["dep:hayro-jpeg2000"] craft-dds = { workspace = true } crc32fast = "1.5" thiserror = { workspace = true } -image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tiff", "gif", "bmp", "ico", "qoi", "hdr"] } +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "bmp", "ico", "qoi", "hdr"] } png = "0.18" tiff = { version = "0.11", default-features = false, features = ["deflate", "fax", "jpeg", "lzw"] } exr = { version = "1.73", default-features = false, optional = true } diff --git a/crates/image-codecs/README.md b/crates/image-codecs/README.md index 6905563be8..6ef02d6f97 100644 --- a/crates/image-codecs/README.md +++ b/crates/image-codecs/README.md @@ -69,7 +69,8 @@ craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "< Each codec below sits behind a Cargo feature that is on by default, preserving the default read and write capabilities shown in the matrix. A build that never handles some formats turns `default-features` -off and lists the ones it needs; the codecs left out, and their dependencies, are not compiled in. +off and lists the ones it needs; unused codec backends are removed from optimized builds. +TIFF metadata readers and EXIF writing remain available without TIFF pixel support. For a minimal build, depend directly on `craft-image-codecs` with `default-features = false`. The `craft` facade's generated codec selectors are additive: its base `image-codecs` feature @@ -88,10 +89,11 @@ retains the default codec set for existing facade consumers. | `jxl-encode` | JPEG XL export (the `zune-jpegxl` dependency); decode is the separate `jxl` feature | | `pnm` | Netpbm | | `tga` | TGA (the `image` crate's TGA decoder) | +| `tiff` | TIFF and BigTIFF pixel decoding and encoding | | `webp` | WebP, with the VP8 encoder (the `image-webp` dependency) | | `xpm` | XPM | -PNG, JPEG, TIFF, GIF, BMP, ICO, QOI, Radiance HDR and PCX are always built. A format left +PNG, JPEG, GIF, BMP, ICO, QOI, Radiance HDR and PCX are always built. A format left out is still detected; reading or writing it returns `CodecError::Unsupported` naming the feature, and its `caps` say it can be neither read nor written. The functions specific to a left-out format (`exr_info`, `decode_webp_frames`, `webp_encoding`, `xpm_named_color_rgb`...) are not compiled in. diff --git a/crates/image-codecs/src/codecs/tiff.rs b/crates/image-codecs/src/codecs/tiff.rs index dc537d2fd9..ffd73bfe48 100644 --- a/crates/image-codecs/src/codecs/tiff.rs +++ b/crates/image-codecs/src/codecs/tiff.rs @@ -259,6 +259,9 @@ use PhotometricInterpretation as PI; /// Encode plain classic RGBA16 TIFF for callers that need the legacy file layout. pub fn encode_plain_rgba16(width: u32, height: u32, samples: &[u16]) -> Result, CodecError> { + if !cfg!(feature = "tiff") { + return Err(CodecError::feature_missing(F, "tiff")); + } craft_tiff::plain::encode_rgba16(width, height, samples).map_err(|error| CodecError::encode(F, error)) } diff --git a/crates/image-codecs/src/codecs/tiff/decode.rs b/crates/image-codecs/src/codecs/tiff/decode.rs index dcccadde66..26639812a0 100644 --- a/crates/image-codecs/src/codecs/tiff/decode.rs +++ b/crates/image-codecs/src/codecs/tiff/decode.rs @@ -28,6 +28,9 @@ pub(crate) fn probe(bytes: &[u8], limits: &Limits) -> Result<(u32, u32, u16), Co /// carries the page's metadata, a [`DecodeWarning::MorePages`] when the file holds more /// full-resolution pages, and a [`DecodeWarning::Truncated`] when image data is cut off. pub(crate) fn decode_page(bytes: &[u8], page: Option, limits: &Limits) -> Result { + if !cfg!(feature = "tiff") { + return Err(CodecError::feature_missing(F, "tiff")); + } let (file, dir, more) = open_page(bytes, page)?; let mut img = decode_ifd(&file, &dir, limits)?; let extra_samples = std::mem::take(&mut img.meta.extra_samples); @@ -107,6 +110,9 @@ impl<'a> TiffBands<'a> { /// against `limits`; on 64-bit targets its `max_alloc` bounds each group of bands, not the /// whole image. pub fn open(bytes: &'a [u8], page: Option, limits: &Limits) -> Result { + if !cfg!(feature = "tiff") { + return Err(CodecError::feature_missing(F, "tiff")); + } let (file, dir, more) = open_page(bytes, page)?; // On 32-bit targets the whole image must still fit `max_alloc`, as it did before: the // document holding it shares the same small address space (wasm32: 4 GiB). @@ -911,7 +917,7 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result Result<(), CodecError> { } pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result, CodecError> { + if !cfg!(feature = "tiff") { + return Err(CodecError::feature_missing(F, "tiff")); + } // Check the source planes before `converted`, which brings them to the plan's sample type // with the image but deliberately leaves a wrong-sized plane alone: past that point a bad // plane would be reinterpreted in the new width rather than rejected. diff --git a/crates/image-codecs/src/format.rs b/crates/image-codecs/src/format.rs index 31a1f4817f..61d4a0690d 100644 --- a/crates/image-codecs/src/format.rs +++ b/crates/image-codecs/src/format.rs @@ -292,6 +292,7 @@ pub(crate) fn missing_feature(format: Format) -> Option<&'static str> { Format::Sgi => ("sgi", cfg!(feature = "sgi")), Format::SunRaster => ("sunraster", cfg!(feature = "sunraster")), Format::Tga => ("tga", cfg!(feature = "tga")), + Format::Tiff => ("tiff", cfg!(feature = "tiff")), Format::WebP => ("webp", cfg!(feature = "webp")), Format::Xpm => ("xpm", cfg!(feature = "xpm")), _ => return None, diff --git a/crates/image-codecs/src/tiff_probe.rs b/crates/image-codecs/src/tiff_probe.rs index 1c6889c215..779eb180b5 100644 --- a/crates/image-codecs/src/tiff_probe.rs +++ b/crates/image-codecs/src/tiff_probe.rs @@ -89,8 +89,9 @@ mod tests { use super::*; #[test] fn reads_first_directory_and_enforces_limits_and_bounds() { - let image = crate::Image::from_u8(2, 3, crate::ChannelLayout::Rgb, vec![42; 18]).unwrap(); - let bytes = crate::encode(&image, crate::Format::Tiff, &crate::EncodeOptions::default()).unwrap(); + let mut out = std::io::Cursor::new(Vec::new()); + tiff::encoder::TiffEncoder::new(&mut out).unwrap().write_image::(2, 3, &[42; 18]).unwrap(); + let bytes = out.into_inner(); assert_eq!(header(&bytes, 6).unwrap(), (2, 3, 1)); let info = decode_info(&bytes, 6).unwrap(); assert_eq!((info.width, info.height, info.bit_depth), (2, 3, 8)); diff --git a/crates/image-codecs/tests/it/decode_warnings.rs b/crates/image-codecs/tests/it/decode_warnings.rs index c3fd986992..6207a57dcc 100644 --- a/crates/image-codecs/tests/it/decode_warnings.rs +++ b/crates/image-codecs/tests/it/decode_warnings.rs @@ -244,6 +244,7 @@ fn animated_webp_warns_and_keeps_the_first_frame() { } /// A TIFF with one IFD per entry: `(NewSubfileType, sample type)`. +#[cfg(feature = "tiff")] fn tiff(ifds: &[(u32, SampleType)]) -> Vec { use tiff::encoder::{TiffEncoder, colortype}; use tiff::tags::Tag; @@ -272,6 +273,7 @@ fn tiff(ifds: &[(u32, SampleType)]) -> Vec { } #[test] +#[cfg(feature = "tiff")] fn multi_page_tiff_warns_and_keeps_the_first_page() { for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { let one = decode(&tiff(&[(0, sample)])).unwrap(); @@ -286,6 +288,7 @@ fn multi_page_tiff_warns_and_keeps_the_first_page() { } #[test] +#[cfg(feature = "tiff")] fn tiff_thumbnails_and_masks_are_not_pages() { let u8 = SampleType::U8; // A reduced-resolution copy (bit 0) or a transparency mask (bit 2) is part of the page. @@ -354,12 +357,19 @@ fn additional_images_probe_uses_container_structure_without_decoding_pixels() { (animated_webp(&frames[..1]), false), #[cfg(feature = "webp")] (animated_webp(&frames), true), + #[cfg(feature = "tiff")] (tiff(&[(0, SampleType::U8)]), false), + #[cfg(feature = "tiff")] (tiff(&[(0, SampleType::U8), (2, SampleType::U8)]), true), + #[cfg(feature = "tiff")] (tiff(&[(0, SampleType::U8), (1, SampleType::U8)]), false), + #[cfg(feature = "tiff")] (tiff(&[(4, SampleType::U8)]), false), + #[cfg(feature = "tiff")] (tiff(&[(0, SampleType::U8), (4, SampleType::U8)]), true), + #[cfg(feature = "tiff")] (tiff(&[(4, SampleType::U8), (0, SampleType::U8)]), true), + #[cfg(feature = "tiff")] (tiff(&[(0, SampleType::U8), (1, SampleType::U8), (4, SampleType::U8)]), true), ] { assert_eq!(has_unretained_source_data(&bytes).unwrap(), multiple); diff --git a/crates/image-codecs/tests/it/detect_caps.rs b/crates/image-codecs/tests/it/detect_caps.rs index fbef5693c3..60cbfc1f31 100644 --- a/crates/image-codecs/tests/it/detect_caps.rs +++ b/crates/image-codecs/tests/it/detect_caps.rs @@ -48,6 +48,7 @@ fn feature_config_default_build_formats_all_symmetric() { let expected = [ Format::Png, Format::Jpeg, + #[cfg(feature = "tiff")] Format::Tiff, #[cfg(feature = "webp")] Format::WebP, diff --git a/crates/image-codecs/tests/it/fidelity.rs b/crates/image-codecs/tests/it/fidelity.rs index 50297e974e..63f453bf20 100644 --- a/crates/image-codecs/tests/it/fidelity.rs +++ b/crates/image-codecs/tests/it/fidelity.rs @@ -18,6 +18,7 @@ fn png_u16_rgba_is_clean() { assert!(warns(&test_image(ChannelLayout::Rgba, SampleType::U16), Format::Png).is_empty()); } #[test] +#[cfg(feature = "tiff")] fn tiff_is_clean_for_all_integer_and_f32_layouts() { for l in ChannelLayout::ALL { for s in [SampleType::U8, SampleType::U16, SampleType::F32, SampleType::F16] { diff --git a/crates/image-codecs/tests/it/limits.rs b/crates/image-codecs/tests/it/limits.rs index 668fcb7bb9..92b56c93c2 100644 --- a/crates/image-codecs/tests/it/limits.rs +++ b/crates/image-codecs/tests/it/limits.rs @@ -462,6 +462,7 @@ fn jpeg_bomb_header_rejected() { } #[test] +#[cfg(feature = "tiff")] fn tiff_bomb_header_rejected() { // Minimal little-endian TIFF claiming 1_000_000 x 1_000_000 8-bit gray. let mut b = b"II*\0\x08\0\0\0".to_vec(); diff --git a/crates/image-codecs/tests/it/main.rs b/crates/image-codecs/tests/it/main.rs index 1ec03bec54..0864ea6877 100644 --- a/crates/image-codecs/tests/it/main.rs +++ b/crates/image-codecs/tests/it/main.rs @@ -1,6 +1,7 @@ //! The crate's integration tests, linked into one test binary. mod bmp_resolution; +#[cfg(feature = "tiff")] mod camera_raw; mod common; #[cfg(feature = "dds")] @@ -43,14 +44,24 @@ mod roundtrip; mod source_settings; #[cfg(feature = "tga")] mod tga; +#[cfg(feature = "tiff")] mod tiff_bands; +#[cfg(feature = "tiff")] mod tiff_bench; +#[cfg(feature = "tiff")] mod tiff_exif; +mod tiff_feature; +#[cfg(feature = "tiff")] mod tiff_lab; +#[cfg(feature = "tiff")] mod tiff_pages; +#[cfg(feature = "tiff")] mod tiff_photoshop; +#[cfg(feature = "tiff")] mod tiff_pyramid; +#[cfg(feature = "tiff")] mod tiff_regressions; +#[cfg(feature = "tiff")] mod tiff_ycbcr; #[cfg(feature = "webp")] mod webp_frames; diff --git a/crates/image-codecs/tests/it/malformed.rs b/crates/image-codecs/tests/it/malformed.rs index 85b4995608..0c9b570c64 100644 --- a/crates/image-codecs/tests/it/malformed.rs +++ b/crates/image-codecs/tests/it/malformed.rs @@ -264,6 +264,7 @@ fn tiny_tiff(extra: &[(u16, u16, u32, u32)]) -> Vec { } #[test] +#[cfg(feature = "tiff")] fn tiff_fixture_decodes() { let img = decode_as_with(Format::Tiff, &tiny_tiff(&[]), &tight()).unwrap(); assert_eq!((img.width(), img.height()), (1, 1)); diff --git a/crates/image-codecs/tests/it/metadata.rs b/crates/image-codecs/tests/it/metadata.rs index 4abd89713c..c44a9afd80 100644 --- a/crates/image-codecs/tests/it/metadata.rs +++ b/crates/image-codecs/tests/it/metadata.rs @@ -126,7 +126,7 @@ fn hdr_metadata() { #[test] fn metadata_on_16bit_png_and_tiff() { - for f in [Format::Png, Format::Tiff] { + for f in [Format::Png, Format::Tiff].into_iter().filter(|f| caps(*f).write) { let mut img = test_image(ChannelLayout::Rgba, SampleType::U16); img.icc = Some(sample_icc(512)); img.meta.dpi = Some((72.0, 72.0)); @@ -138,7 +138,7 @@ fn metadata_on_16bit_png_and_tiff() { #[test] fn icc_on_cmyk_tiff_and_jpeg() { - for f in [Format::Tiff, Format::Jpeg] { + for f in [Format::Tiff, Format::Jpeg].into_iter().filter(|f| caps(*f).write) { let img = test_image(ChannelLayout::Cmyk, SampleType::U8).with_icc(Some(sample_icc(900))); let back = decode(&encode(&img, f, &EncodeOptions::default()).unwrap()).unwrap(); assert_eq!(back.layout(), ChannelLayout::Cmyk, "{f:?}"); @@ -220,6 +220,7 @@ fn embed_flags_disable_metadata() { for f in [ Format::Png, Format::Jpeg, + #[cfg(feature = "tiff")] Format::Tiff, #[cfg(feature = "webp")] Format::WebP, @@ -288,6 +289,7 @@ fn jpeg_dpi_in_jfif() { } #[test] +#[cfg(feature = "tiff")] fn tiff_icc_readable_by_oracle() { let img = test_image(ChannelLayout::Rgb, SampleType::U16).with_icc(Some(sample_icc(1234))); let bytes = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap(); diff --git a/crates/image-codecs/tests/it/orientation.rs b/crates/image-codecs/tests/it/orientation.rs index 1112e2c0d4..41168416e1 100644 --- a/crates/image-codecs/tests/it/orientation.rs +++ b/crates/image-codecs/tests/it/orientation.rs @@ -91,6 +91,7 @@ fn png_with_exif(png: &[u8], exif: &[u8]) -> Vec { out } +#[cfg(feature = "tiff")] fn tiff_with_orientation(data: &[u8], w: u32, h: u32, o: u16) -> Vec { use tiff::encoder::{TiffEncoder, colortype::Gray8}; let mut cursor = std::io::Cursor::new(Vec::new()); @@ -305,6 +306,7 @@ fn extra_samples_turn_with_the_image() { } #[test] +#[cfg(feature = "tiff")] fn tiff_opens_upright_for_every_orientation() { let (w, h) = (4, 7); let up = exact_scene(w, h); @@ -396,6 +398,7 @@ fn export_writes_orientation_1_and_keeps_pixels() { Format::Jpeg, #[cfg(feature = "webp")] Format::WebP, + #[cfg(feature = "tiff")] Format::Tiff, ] { let bytes = encode(&stale, format, &EncodeOptions { jpeg_quality: 100, ..Default::default() }).unwrap(); @@ -633,9 +636,12 @@ fn limits_apply_to_the_upright_size() { let flipped = decode_with(&jpeg_with_exif(&jpeg, &exif(3, false, false)), &opts).unwrap(); assert_eq!(flipped.dimensions(), (32, 16)); // The same holds for a TIFF, whose orientation lives in its own IFD0. - let tiff = tiff_with_orientation(&[7; 32 * 16], 32, 16, 8); - assert!(matches!(decode_with(&tiff, &opts), Err(CodecError::LimitExceeded(_)))); - assert_eq!(decode_with(&tiff, &DecodeOptions::default()).unwrap().dimensions(), (16, 32)); + #[cfg(feature = "tiff")] + { + let tiff = tiff_with_orientation(&[7; 32 * 16], 32, 16, 8); + assert!(matches!(decode_with(&tiff, &opts), Err(CodecError::LimitExceeded(_)))); + assert_eq!(decode_with(&tiff, &DecodeOptions::default()).unwrap().dimensions(), (16, 32)); + } } #[test] @@ -673,6 +679,7 @@ fn feature_config_probe_size_matches_decode() { let probed = [ Format::Png, Format::Jpeg, + #[cfg(feature = "tiff")] Format::Tiff, #[cfg(feature = "webp")] Format::WebP, diff --git a/crates/image-codecs/tests/it/png_jpeg.rs b/crates/image-codecs/tests/it/png_jpeg.rs index cad8f33e9a..7d7a89ed9e 100644 --- a/crates/image-codecs/tests/it/png_jpeg.rs +++ b/crates/image-codecs/tests/it/png_jpeg.rs @@ -229,6 +229,7 @@ fn png_output_matches_oracle_all_layouts() { } #[test] +#[cfg(feature = "tiff")] fn tiff_output_matches_oracle() { for l in [ChannelLayout::Gray, ChannelLayout::Rgb, ChannelLayout::Rgba] { for s in [SampleType::U8, SampleType::U16] { @@ -241,6 +242,7 @@ fn tiff_output_matches_oracle() { } #[test] +#[cfg(feature = "tiff")] fn tiff_f32_output_matches_oracle() { let img = test_image(ChannelLayout::Rgba, SampleType::F32); let b = encode(&img, Format::Tiff, &EncodeOptions { tiff_compression: TiffCompression::None, ..Default::default() }).unwrap(); diff --git a/crates/image-codecs/tests/it/roundtrip.rs b/crates/image-codecs/tests/it/roundtrip.rs index 76cdd2ff54..fa79ebd778 100644 --- a/crates/image-codecs/tests/it/roundtrip.rs +++ b/crates/image-codecs/tests/it/roundtrip.rs @@ -160,6 +160,7 @@ fn hdr_values_survive_float_formats() { let vals: Vec = (0..16 * 8 * 3).map(|i| (i as f32 - 40.0) * 0.37).collect(); let img = Image::from_f32(16, 8, ChannelLayout::Rgb, &vals).unwrap(); let formats = [ + #[cfg(feature = "tiff")] Format::Tiff, #[cfg(feature = "exr")] Format::OpenExr, @@ -200,6 +201,7 @@ fn f16_exr_is_bit_exact() { } #[test] +#[cfg(feature = "tiff")] fn tiff_all_compressions_lossless() { for layout in ChannelLayout::ALL { for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { @@ -222,6 +224,7 @@ fn tiff_all_compressions_lossless() { } #[test] +#[cfg(feature = "tiff")] fn compressed_tiff_does_not_keep_the_uncompressed_reservation() { // The encoder reserves the uncompressed size up front for an uncompressed file (#6607). A // smooth image compresses to a fraction of it, and no returned file holds much spare room. @@ -358,6 +361,7 @@ fn larger_image_png_tiff_exact() { let img = synth(513, 257, ChannelLayout::Rgba, SampleType::U16, 99, 1.0); for f in [ Format::Png, + #[cfg(feature = "tiff")] Format::Tiff, #[cfg(feature = "pnm")] Format::Pnm, diff --git a/crates/image-codecs/tests/it/tiff_feature.rs b/crates/image-codecs/tests/it/tiff_feature.rs new file mode 100644 index 0000000000..9abd0525f5 --- /dev/null +++ b/crates/image-codecs/tests/it/tiff_feature.rs @@ -0,0 +1,30 @@ +//! Original synthetic fixture: one RGBA pixel, written by the independent TIFF structure crate. +#[cfg(not(feature = "tiff"))] +use craft_image_codecs::*; + +#[cfg(not(feature = "tiff"))] +#[test] +fn omitted_tiff_pixels_are_refused_but_metadata_remains_readable() { + let bytes = craft_tiff::plain::encode_rgba16(1, 1, &[1, 2, 3, u16::MAX]).unwrap(); + assert_eq!(detect(&bytes), Some(Format::Tiff)); + assert!(!caps(Format::Tiff).read && !caps(Format::Tiff).write); + assert!(tiff_info(&bytes).is_ok()); + assert_eq!(tiff_probe::header(&bytes, 1).unwrap(), (1, 1, 1)); + let image = Image::from_u8(1, 1, ChannelLayout::Rgba, vec![1, 2, 3, 255]).unwrap(); + let errors = [ + decode(&bytes).err(), + decode_tiff_page(&bytes, 0, &DecodeOptions::default()).err(), + TiffBands::open(&bytes, None, &Limits::default()).err(), + encode(&image, Format::Tiff, &EncodeOptions::default()).err(), + encode_tiff_plain_rgba16(1, 1, &[1, 2, 3, u16::MAX]).err(), + ]; + for error in errors { + match error.unwrap() { + CodecError::Unsupported { format, reason } => { + assert_eq!(format, Format::Tiff); + assert!(reason.contains("tiff feature"), "{reason}"); + } + other => panic!("expected a named feature error, got {other:?}"), + } + } +} From d3dbcca7c52baafee6dcf392ffb752342c151f38 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 29 Nov 2026 23:37:04 +0100 Subject: [PATCH 3/9] Keep the generated TIFF selector in facade order --- crates/craft/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 21904d2acd..7ac49505b0 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -607,8 +607,8 @@ image-codecs-pnm = ["image-codecs", "craft-image-codecs/pnm"] image-codecs-sgi = ["image-codecs", "craft-image-codecs/sgi"] image-codecs-sunraster = ["image-codecs", "craft-image-codecs/sunraster"] image-codecs-tga = ["image-codecs", "craft-image-codecs/tga"] -image-codecs-tiff = ["image-codecs", "craft-image-codecs/tiff"] image-codecs-threads = ["image-codecs", "craft-image-codecs/threads"] +image-codecs-tiff = ["image-codecs", "craft-image-codecs/tiff"] image-codecs-webp = ["image-codecs", "craft-image-codecs/webp"] image-codecs-xpm = ["image-codecs", "craft-image-codecs/xpm"] From 31f92f097f2ea4ebce1ae3b1aa7a1dfc6eaee56b Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 29 Nov 2026 23:39:35 +0100 Subject: [PATCH 4/9] Exercise enabled large-image codecs in minimal builds --- crates/image-codecs/tests/it/roundtrip.rs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/crates/image-codecs/tests/it/roundtrip.rs b/crates/image-codecs/tests/it/roundtrip.rs index fa79ebd778..d9178a7d97 100644 --- a/crates/image-codecs/tests/it/roundtrip.rs +++ b/crates/image-codecs/tests/it/roundtrip.rs @@ -359,13 +359,7 @@ fn feature_config_empty_image_rejected() { #[test] fn larger_image_png_tiff_exact() { let img = synth(513, 257, ChannelLayout::Rgba, SampleType::U16, 99, 1.0); - for f in [ - Format::Png, - #[cfg(feature = "tiff")] - Format::Tiff, - #[cfg(feature = "pnm")] - Format::Pnm, - ] { + for f in [Format::Png, Format::Tiff, Format::Pnm].into_iter().filter(|f| caps(*f).read && caps(*f).write) { let back = decode(&encode(&img, f, &EncodeOptions::default()).unwrap()).unwrap(); assert_eq!(back.data(), img.data(), "{f:?}"); } From a9151cb51ffd381ca523d564733c6575773d6ecb Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 29 Nov 2026 23:52:51 +0100 Subject: [PATCH 5/9] Preserve bounded TIFF metadata probing without pixel support --- crates/image-codecs/Cargo.toml | 2 +- crates/image-codecs/README.md | 2 ++ crates/image-codecs/src/allocation.rs | 21 +++++++++++++++++++- crates/image-codecs/tests/it/tiff_feature.rs | 16 +++++++++++++++ 4 files changed, 39 insertions(+), 2 deletions(-) diff --git a/crates/image-codecs/Cargo.toml b/crates/image-codecs/Cargo.toml index 5a05552fb6..5b9317cfaf 100644 --- a/crates/image-codecs/Cargo.toml +++ b/crates/image-codecs/Cargo.toml @@ -86,7 +86,7 @@ exr = { version = "1.73", default-features = false, features = ["rayon"], option [dev-dependencies] proptest = { workspace = true } -image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tiff"] } +image = { version = "0.25", default-features = false, features = ["png", "jpeg"] } sha2 = { version = "0.10", default-features = false, features = ["std"] } craft-media-testkit = { workspace = true } diff --git a/crates/image-codecs/README.md b/crates/image-codecs/README.md index 6ef02d6f97..76ce8a6c64 100644 --- a/crates/image-codecs/README.md +++ b/crates/image-codecs/README.md @@ -97,6 +97,8 @@ PNG, JPEG, GIF, BMP, ICO, QOI, Radiance HDR and PCX are always built. A format l out is still detected; reading or writing it returns `CodecError::Unsupported` naming the feature, and its `caps` say it can be neither read nor written. The functions specific to a left-out format (`exr_info`, `decode_webp_frames`, `webp_encoding`, `xpm_named_color_rgb`...) are not compiled in. +TIFF is an exception: its metadata APIs and public pixel API types remain available; pixel +entry points return the named unsupported-feature error when `tiff` is disabled. ```toml craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "", default-features = false, features = ["webp"] } diff --git a/crates/image-codecs/src/allocation.rs b/crates/image-codecs/src/allocation.rs index df9afd93f7..7c653ae195 100644 --- a/crates/image-codecs/src/allocation.rs +++ b/crates/image-codecs/src/allocation.rs @@ -257,6 +257,21 @@ pub fn probe_stored_size(bytes: &[u8], limits: &crate::Limits) -> Result<(u32, u if !matches!(format, Format::Png | Format::Jpeg | Format::Bmp | Format::Tiff) { return Err(CodecError::unsupported(format, "stored-size probe is not available for this format")); } + if format == Format::Tiff && !cfg!(feature = "tiff") { + // Header inspection remains available without the optional pixel backend. + use crate::codecs::tiff_ifd::{Entry, File, TAG_HEIGHT, TAG_WIDTH}; + let malformed = || CodecError::malformed(format, "invalid first TIFF directory"); + let file = File::parse(bytes).ok_or_else(malformed)?; + let entries = file.entry_count(file.first_ifd).ok_or_else(malformed)?; + if entries.saturating_mul(std::mem::size_of::() as u64) > limits.max_alloc { + return Err(CodecError::LimitExceeded("TIFF directory exceeds max_alloc".into())); + } + let directory = file.ifd(file.first_ifd).ok_or_else(malformed)?; + let side = |tag| file.tag_uint(&directory, tag).and_then(|v| u32::try_from(v).ok()).ok_or_else(malformed); + let (width, height) = (side(TAG_WIDTH)?, side(TAG_HEIGHT)?); + limits.check_size(width, height)?; + return Ok((width, height)); + } // The JPEG header reader owns a copy of its input before applying image limits. if format == Format::Jpeg && u64::try_from(bytes.len()).map_or(true, |len| len > limits.max_alloc) { return Err(CodecError::malformed(format, "JPEG input exceeds the allocation budget")); @@ -322,7 +337,11 @@ mod stored_size_tests { let limits = crate::Limits::new(100, 100, 10_000, 1 << 20); for format in [image::ImageFormat::Png, image::ImageFormat::Jpeg, image::ImageFormat::Bmp, image::ImageFormat::Tiff] { let mut out = Cursor::new(Vec::new()); - image::write_buffer_with_format(&mut out, &[10; 18], 3, 2, image::ExtendedColorType::Rgb8, format).unwrap(); + if format == image::ImageFormat::Tiff { + tiff::encoder::TiffEncoder::new(&mut out).unwrap().write_image::(3, 2, &[10; 18]).unwrap(); + } else { + image::write_buffer_with_format(&mut out, &[10; 18], 3, 2, image::ExtendedColorType::Rgb8, format).unwrap(); + } assert_eq!(probe_stored_size(&out.into_inner(), &limits).unwrap(), (3, 2), "{format:?}"); } } diff --git a/crates/image-codecs/tests/it/tiff_feature.rs b/crates/image-codecs/tests/it/tiff_feature.rs index 9abd0525f5..0967daf35a 100644 --- a/crates/image-codecs/tests/it/tiff_feature.rs +++ b/crates/image-codecs/tests/it/tiff_feature.rs @@ -28,3 +28,19 @@ fn omitted_tiff_pixels_are_refused_but_metadata_remains_readable() { } } } + +#[cfg(not(feature = "tiff"))] +#[test] +fn tiff_header_probe_keeps_dimensions_and_allocation_bounded_without_pixels() { + let bytes = craft_tiff::plain::encode_rgba16(2, 3, &[0; 24]).unwrap(); + assert_eq!(probe_stored_size(&bytes, &Limits::default()).unwrap(), (2, 3)); + for limits in [ + Limits { max_width: 1, ..Limits::default() }, + Limits { max_height: 2, ..Limits::default() }, + Limits { max_pixels: 5, ..Limits::default() }, + Limits { max_alloc: 1, ..Limits::default() }, + ] { + assert!(matches!(probe_stored_size(&bytes, &limits), Err(CodecError::LimitExceeded(_)))); + } + assert!(probe_stored_size(&bytes[..8], &Limits::default()).is_err()); +} From eec1a82b58a45dfb682325f7619e063d8e3e113b Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 00:00:24 +0100 Subject: [PATCH 6/9] Exercise metadata-only TIFF bounds in every feature configuration --- crates/image-codecs/src/allocation.rs | 46 ++++++++++++++------ crates/image-codecs/tests/it/tiff_feature.rs | 17 +------- 2 files changed, 34 insertions(+), 29 deletions(-) diff --git a/crates/image-codecs/src/allocation.rs b/crates/image-codecs/src/allocation.rs index 7c653ae195..f50cb6d903 100644 --- a/crates/image-codecs/src/allocation.rs +++ b/crates/image-codecs/src/allocation.rs @@ -248,6 +248,23 @@ fn read_le24(bytes: &[u8], at: usize) -> Option { Some(u32::from_le_bytes([b[0], b[1], b[2], 0])) } +fn tiff_stored_size(bytes: &[u8], limits: &crate::Limits) -> Result<(u32, u32), CodecError> { + let format = Format::Tiff; + // Header inspection remains available without the optional pixel backend. + use crate::codecs::tiff_ifd::{Entry, File, TAG_HEIGHT, TAG_WIDTH}; + let malformed = || CodecError::malformed(format, "invalid first TIFF directory"); + let file = File::parse(bytes).ok_or_else(malformed)?; + let entries = file.entry_count(file.first_ifd).ok_or_else(malformed)?; + if entries.saturating_mul(std::mem::size_of::() as u64) > limits.max_alloc { + return Err(CodecError::LimitExceeded("TIFF directory exceeds max_alloc".into())); + } + let directory = file.ifd(file.first_ifd).ok_or_else(malformed)?; + let side = |tag| file.tag_uint(&directory, tag).and_then(|v| u32::try_from(v).ok()).ok_or_else(malformed); + let (width, height) = (side(TAG_WIDTH)?, side(TAG_HEIGHT)?); + limits.check_size(width, height)?; + Ok((width, height)) +} + /// Probe the stored dimensions of the first PNG, JPEG, BMP or TIFF image, without decoding /// pixels or applying orientation. TIFF uses the first directory even if it is a thumbnail. /// The caller's limits bound both the header decoder and the declared output dimensions. @@ -258,19 +275,7 @@ pub fn probe_stored_size(bytes: &[u8], limits: &crate::Limits) -> Result<(u32, u return Err(CodecError::unsupported(format, "stored-size probe is not available for this format")); } if format == Format::Tiff && !cfg!(feature = "tiff") { - // Header inspection remains available without the optional pixel backend. - use crate::codecs::tiff_ifd::{Entry, File, TAG_HEIGHT, TAG_WIDTH}; - let malformed = || CodecError::malformed(format, "invalid first TIFF directory"); - let file = File::parse(bytes).ok_or_else(malformed)?; - let entries = file.entry_count(file.first_ifd).ok_or_else(malformed)?; - if entries.saturating_mul(std::mem::size_of::() as u64) > limits.max_alloc { - return Err(CodecError::LimitExceeded("TIFF directory exceeds max_alloc".into())); - } - let directory = file.ifd(file.first_ifd).ok_or_else(malformed)?; - let side = |tag| file.tag_uint(&directory, tag).and_then(|v| u32::try_from(v).ok()).ok_or_else(malformed); - let (width, height) = (side(TAG_WIDTH)?, side(TAG_HEIGHT)?); - limits.check_size(width, height)?; - return Ok((width, height)); + return tiff_stored_size(bytes, limits); } // The JPEG header reader owns a copy of its input before applying image limits. if format == Format::Jpeg && u64::try_from(bytes.len()).map_or(true, |len| len > limits.max_alloc) { @@ -345,4 +350,19 @@ mod stored_size_tests { assert_eq!(probe_stored_size(&out.into_inner(), &limits).unwrap(), (3, 2), "{format:?}"); } } + + #[test] + fn tiff_header_probe_keeps_dimensions_and_allocation_bounded_without_pixels() { + let bytes = craft_tiff::plain::encode_rgba16(2, 3, &[0; 24]).unwrap(); + assert_eq!(tiff_stored_size(&bytes, &crate::Limits::default()).unwrap(), (2, 3)); + for limits in [ + crate::Limits { max_width: 1, ..crate::Limits::default() }, + crate::Limits { max_height: 2, ..crate::Limits::default() }, + crate::Limits { max_pixels: 5, ..crate::Limits::default() }, + crate::Limits { max_alloc: 1, ..crate::Limits::default() }, + ] { + assert!(matches!(tiff_stored_size(&bytes, &limits), Err(CodecError::LimitExceeded(_)))); + } + assert!(tiff_stored_size(&bytes[..8], &crate::Limits::default()).is_err()); + } } diff --git a/crates/image-codecs/tests/it/tiff_feature.rs b/crates/image-codecs/tests/it/tiff_feature.rs index 0967daf35a..c5730d583c 100644 --- a/crates/image-codecs/tests/it/tiff_feature.rs +++ b/crates/image-codecs/tests/it/tiff_feature.rs @@ -10,6 +10,7 @@ fn omitted_tiff_pixels_are_refused_but_metadata_remains_readable() { assert!(!caps(Format::Tiff).read && !caps(Format::Tiff).write); assert!(tiff_info(&bytes).is_ok()); assert_eq!(tiff_probe::header(&bytes, 1).unwrap(), (1, 1, 1)); + assert_eq!(probe_stored_size(&bytes, &Limits::default()).unwrap(), (1, 1)); let image = Image::from_u8(1, 1, ChannelLayout::Rgba, vec![1, 2, 3, 255]).unwrap(); let errors = [ decode(&bytes).err(), @@ -28,19 +29,3 @@ fn omitted_tiff_pixels_are_refused_but_metadata_remains_readable() { } } } - -#[cfg(not(feature = "tiff"))] -#[test] -fn tiff_header_probe_keeps_dimensions_and_allocation_bounded_without_pixels() { - let bytes = craft_tiff::plain::encode_rgba16(2, 3, &[0; 24]).unwrap(); - assert_eq!(probe_stored_size(&bytes, &Limits::default()).unwrap(), (2, 3)); - for limits in [ - Limits { max_width: 1, ..Limits::default() }, - Limits { max_height: 2, ..Limits::default() }, - Limits { max_pixels: 5, ..Limits::default() }, - Limits { max_alloc: 1, ..Limits::default() }, - ] { - assert!(matches!(probe_stored_size(&bytes, &limits), Err(CodecError::LimitExceeded(_)))); - } - assert!(probe_stored_size(&bytes[..8], &Limits::default()).is_err()); -} From c4d0e6278e018b342f99f3c4b1c0ba1c506c9f9f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 19:53:09 -0500 Subject: [PATCH 7/9] silhouette-studio: .studio3 and .studio (V2) writers; read line colours as RGB (#3745) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * silhouette-studio: .studio3 writer (pages, polygons with line colour, width, fill); read line colours as RGB * silhouette-studio writer: Bézier handles and compound contours * silhouette-studio: .studio (V2) writer --- crates/silhouette-studio/src/lib.rs | 10 +- crates/silhouette-studio/src/write.rs | 1175 +++++++++++++++++++++++++ 2 files changed, 1182 insertions(+), 3 deletions(-) create mode 100644 crates/silhouette-studio/src/write.rs diff --git a/crates/silhouette-studio/src/lib.rs b/crates/silhouette-studio/src/lib.rs index 7216d5bf42..ddbcecabf6 100644 --- a/crates/silhouette-studio/src/lib.rs +++ b/crates/silhouette-studio/src/lib.rs @@ -1,5 +1,6 @@ //! Reader for Silhouette Studio documents: `.studio` (header `silhouette04;`) and -//! `.studio3` (header `silhouette05;`). +//! `.studio3` (header `silhouette05;`), and writers for `.studio3` ([`write()`]) and `.studio` ([`write_v2`]) for pages and +//! shapes of straight and Bézier contours with line colour, width and fill. //! //! It reads every object's outline (open and closed paths, lines and Bézier curves, compound //! paths, text as outlines), each outline's line and fill colours and the page size. Coordinates are @@ -16,7 +17,9 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +mod write; use kurbo::{BezPath, Point, Vec2}; +pub use write::{MAX_WRITE_POINTS, MAX_WRITE_SHAPES, WriteContour, WriteDocument, WriteNode, WriteShape, write, write_v2}; /// Largest file read (store designs and saved samples are far smaller). pub const MAX_FILE_BYTES: usize = 64 * 1024 * 1024; @@ -360,7 +363,8 @@ fn line_color_before(d: &[u8], from: usize, to: usize) -> Option<[u8; 3]> { let v = f32_at(d, record - 24 + 4 * i)?; (v.is_finite() && (0.0..=1.0).contains(&v)).then(|| (v * 255.0).round() as u8) }; - if let (Some(b), Some(g), Some(r)) = (channel(0), channel(1), channel(2)) { + // R, G, B, A: a red line saved in Silhouette Studio 5.0.556 stores 1, 0, 0, 1 here. + if let (Some(r), Some(g), Some(b)) = (channel(0), channel(1), channel(2)) { found = Some([r, g, b]); } } @@ -543,7 +547,7 @@ mod tests { /// then the cut-action record (`01 L`, name "cut"). fn style(rgb: [u8; 3]) -> Vec { let mut out = vec![1]; - for c in [rgb[2], rgb[1], rgb[0], 255] { + for c in [rgb[0], rgb[1], rgb[2], 255] { out.extend_from_slice(&(f32::from(c) / 255.0).to_le_bytes()); } out.extend_from_slice(&[0; 8]); diff --git a/crates/silhouette-studio/src/write.rs b/crates/silhouette-studio/src/write.rs new file mode 100644 index 0000000000..c8b5ce0353 --- /dev/null +++ b/crates/silhouette-studio/src/write.rs @@ -0,0 +1,1175 @@ +//! Writer for Silhouette Studio `.studio3` documents (header `silhouette05;`). +//! +//! It writes a page and shapes made of one or more contours of straight and Bézier segments, +//! with line colour, line width and fill. +//! Every byte is generated from the field layout learned by saving documents in Silhouette +//! Studio 5.0.556 that differ in one thing and comparing them; nothing is copied from +//! Silhouette's files, and every record was checked by opening written files in Silhouette. +//! +//! Only section 0 (the objects) is written: Silhouette Studio opens a document whose other +//! twelve sections are absent. + +use crate::{Error, MAX_FILE_BYTES}; + +/// A document to write: the page size and the shapes, in millimetres from the page's +/// top-left corner, y down. +#[derive(Debug, Clone, PartialEq)] +pub struct WriteDocument { + pub page_mm: (f64, f64), + pub shapes: Vec, +} + +/// One shape: its contours (a compound path has several) and its look. +#[derive(Debug, Clone, PartialEq)] +pub struct WriteShape { + pub contours: Vec, + /// Line colour (R, G, B); `None` is Silhouette's default red cut line. + pub line_rgb: Option<[u8; 3]>, + /// Fill colour; `None` is no fill. + pub fill_rgb: Option<[u8; 3]>, + /// Line width in millimetres (0 is a hairline). + pub width_mm: f64, +} + +/// One contour: its nodes in order, and whether it closes back to the first. +#[derive(Debug, Clone, PartialEq)] +pub struct WriteContour { + pub nodes: Vec, + pub closed: bool, +} + +/// A node and its Bézier handles, as offsets from the node in millimetres: `incoming` shapes +/// the segment arriving here, `outgoing` the one leaving. `None` is a straight segment end. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct WriteNode { + pub x: f64, + pub y: f64, + pub incoming: Option<(f64, f64)>, + pub outgoing: Option<(f64, f64)>, +} + +impl WriteNode { + /// A corner node with no handles. + pub fn corner(x: f64, y: f64) -> Self { + Self { x, y, incoming: None, outgoing: None } + } +} + +impl WriteContour { + /// The contours of `path` (page millimetres, y down) as nodes with handles. Quadratic + /// segments become their exact cubics; a closing segment that ends on the first node + /// gives that node its incoming handle. + pub fn from_path(path: &kurbo::BezPath) -> Vec { + use kurbo::PathEl; + let mut out: Vec = Vec::new(); + let mut current: Option = None; + let mut last = kurbo::Point::ZERO; + let push_curve = |c: &mut WriteContour, from: kurbo::Point, c1: kurbo::Point, c2: kurbo::Point, to: kurbo::Point| { + if let Some(prev) = c.nodes.last_mut() { + prev.outgoing = Some((c1.x - from.x, c1.y - from.y)); + } + c.nodes.push(WriteNode { x: to.x, y: to.y, incoming: Some((c2.x - to.x, c2.y - to.y)), outgoing: None }); + }; + for el in path.elements() { + match *el { + PathEl::MoveTo(p) => { + out.extend(current.take()); + current = Some(WriteContour { nodes: vec![WriteNode::corner(p.x, p.y)], closed: false }); + last = p; + } + PathEl::LineTo(p) => { + if let Some(c) = current.as_mut() { + c.nodes.push(WriteNode::corner(p.x, p.y)); + } + last = p; + } + PathEl::QuadTo(q, p) => { + if let Some(c) = current.as_mut() { + let c1 = last + (q - last) * (2.0 / 3.0); + let c2 = p + (q - p) * (2.0 / 3.0); + push_curve(c, last, c1, c2, p); + } + last = p; + } + PathEl::CurveTo(c1, c2, p) => { + if let Some(c) = current.as_mut() { + push_curve(c, last, c1, c2, p); + } + last = p; + } + PathEl::ClosePath => { + if let Some(mut c) = current.take() { + c.closed = true; + // A last node on top of the first is the same node: fold it in. + if c.nodes.len() > 2 + && let (Some(first), Some(end)) = (c.nodes.first().copied(), c.nodes.last().copied()) + && (first.x - end.x).hypot(first.y - end.y) < 1e-9 + { + c.nodes.pop(); + if let Some(first) = c.nodes.first_mut() { + first.incoming = end.incoming; + } + } + if let Some(first) = c.nodes.first() { + last = kurbo::Point::new(first.x, first.y); + } + out.push(c); + } + } + } + } + out.extend(current); + out.retain(|c| c.nodes.len() >= 2); + out + } +} + +/// The most shapes one written document holds. +pub const MAX_WRITE_SHAPES: usize = 100_000; +/// The most points one written document holds. +pub const MAX_WRITE_POINTS: usize = 1_000_000; +/// The largest page side, in millimetres. +pub const MAX_PAGE_MM: f64 = 10_000.0; + +/// The Silhouette mat the page sits on: 12 × 12 in, its outer edge 20 × 40 mm larger. +const MAT_MM: f64 = 304.8; +/// Silhouette's 10 mm as it stores it (f32 bits 0x411FFFEB, 9.99998). +const TEN_MM: f32 = f32::from_bits(0x411F_FFEB); +/// The constant at 0x3E8 of every file saved here. +const HEADER_MAGIC: u32 = 0x1DCD_672C; + +/// Write `doc` as a `.studio3` file. Page sides must be finite and 1–10,000 mm; +/// points must be finite and within ±10,000 mm. Excess shapes, points or bytes are errors. +pub fn write(doc: &WriteDocument) -> Result, Error> { + write_as(doc, false) +} + +/// Write `doc` as a `.studio` (Studio V2, header `silhouette04;`) file, the legacy format +/// Silhouette Studio's Save As offers as "Silhouette Studio V2". It is the `.studio3` objects +/// section without the 1024-byte header, with a shorter page record, no layer objects and the +/// V2 tool defaults. Same checks as [`write()`]. +pub fn write_v2(doc: &WriteDocument) -> Result, Error> { + write_as(doc, true) +} + +fn write_as(doc: &WriteDocument, v2: bool) -> Result, Error> { + let (pw, ph) = doc.page_mm; + let page_ok = |v: f64| v.is_finite() && (1.0..=MAX_PAGE_MM).contains(&v); + if !(page_ok(pw) && page_ok(ph)) { + return Err(Error::Malformed(format!("page {pw} × {ph} mm is outside 1–{MAX_PAGE_MM} mm"))); + } + if doc.shapes.len() > MAX_WRITE_SHAPES { + return Err(Error::Malformed(format!("more than {MAX_WRITE_SHAPES} shapes"))); + } + let mut total = 0usize; + for shape in &doc.shapes { + if shape.contours.is_empty() { + return Err(Error::Malformed("a shape needs a contour".to_string())); + } + for contour in &shape.contours { + let n = contour.nodes.len(); + total = total.saturating_add(n); + if n < 2 || total > MAX_WRITE_POINTS { + return Err(Error::Malformed(format!("a contour needs 2 nodes, and a document at most {MAX_WRITE_POINTS}"))); + } + let ok = |v: f64| v.is_finite() && v.abs() <= MAX_PAGE_MM; + let handle_ok = |h: Option<(f64, f64)>| h.is_none_or(|(x, y)| ok(x) && ok(y)); + if !contour.nodes.iter().all(|n| ok(n.x) && ok(n.y) && handle_ok(n.incoming) && handle_ok(n.outgoing)) { + return Err(Error::Malformed("a node is not a finite page coordinate".to_string())); + } + } + if !(shape.width_mm.is_finite() && (0.0..=100.0).contains(&shape.width_mm)) { + return Err(Error::Malformed("line width must be 0 to 100 mm".to_string())); + } + } + let magic: &[u8] = if v2 { b"silhouette04;" } else { b"silhouette05;" }; + let limit = MAX_FILE_BYTES - if v2 { 0 } else { 0x400 }; + // Account for exactly the same record framing as the serializer, without + // allocating the output until we know it fits the reader's size limit. + let mut count = W::counting(limit); + count.raw(magic); + root(&mut count, doc, v2); + let section_len = count.checked_len()?; + let mut w = W::writing(limit, section_len); + w.raw(magic); + root(&mut w, doc, v2); + w.checked_len()?; + let section = w.bytes.unwrap_or_default(); + if v2 { + return Ok(section); + } + let mut out = vec![0u8; 0x400]; + out[..13].copy_from_slice(b"silhouette05;"); + out[0x10..0x18].copy_from_slice(&(section.len() as u64).to_le_bytes()); + out[0x3E8..0x3EC].copy_from_slice(&HEADER_MAGIC.to_le_bytes()); + out[0x3F0..0x3F8].copy_from_slice(&300_000_000u64.to_le_bytes()); + out[0x3F8..0x400].copy_from_slice(&300_000_000u64.to_le_bytes()); + out.extend_from_slice(§ion); + Ok(out) +} + +/// A little-endian byte builder with Silhouette's record framing. +/// A bounded byte builder. Counting and writing share the same encoding logic. +struct W { + bytes: Option>, + len: usize, + limit: usize, + failed: bool, +} + +impl W { + fn counting(limit: usize) -> Self { + Self { bytes: None, len: 0, limit, failed: false } + } + fn writing(limit: usize, capacity: usize) -> Self { + Self { bytes: Some(Vec::with_capacity(capacity)), ..Self::counting(limit) } + } + fn checked_len(&self) -> Result { + if self.failed { Err(Error::TooLarge) } else { Ok(self.len) } + } + fn advance(&mut self, n: usize) -> bool { + if self.failed { + return false; + } + match self.len.checked_add(n) { + Some(len) if len <= self.limit => { + self.len = len; + true + } + _ => { + self.failed = true; + false + } + } + } + fn raw(&mut self, b: &[u8]) { + if self.advance(b.len()) + && let Some(bytes) = &mut self.bytes + { + bytes.extend_from_slice(b); + } + } + fn u8(&mut self, v: u8) { + self.raw(&[v]); + } + fn zeros(&mut self, n: usize) { + if self.advance(n) + && let Some(bytes) = &mut self.bytes + { + bytes.resize(self.len, 0); + } + } + fn u32(&mut self, v: u32) { + self.raw(&v.to_le_bytes()); + } + /// An f32, rounded from `v` as Silhouette's own conversions are. + fn f32(&mut self, v: f64) { + self.raw(&(v as f32).to_le_bytes()); + } + fn f32s(&mut self, v: &[f64]) { + v.iter().for_each(|&x| self.f32(x)); + } + fn rgba(&mut self, c: [f64; 4]) { + self.f32s(&c); + } + /// A length-prefixed string. + fn s(&mut self, t: &str) { + let Ok(len) = u32::try_from(t.len()) else { + self.failed = true; + return; + }; + self.u32(len); + self.raw(t.as_bytes()); + } + /// A record: marker 0x01, a u32 length counting itself, the payload. + fn rec(&mut self, f: impl FnOnce(&mut W)) { + self.u8(1); + self.sized(f); + } + /// A record with its own marker byte. + fn tagged(&mut self, tag: u8, f: impl FnOnce(&mut W)) { + self.u8(tag); + self.sized(f); + } + /// A payload prefixed by a u32 length counting itself. + fn sized(&mut self, f: impl FnOnce(&mut W)) { + if self.failed { + return; + } + let at = self.len; + self.u32(0); + f(self); + if self.failed { + return; + } + let Ok(len) = u32::try_from(self.len - at) else { + self.failed = true; + return; + }; + if let Some(bytes) = &mut self.bytes { + bytes[at..at + 4].copy_from_slice(&len.to_le_bytes()); + } + } +} + +fn rgb(c: [u8; 3]) -> [f64; 4] { + [f64::from(c[0]) / 255.0, f64::from(c[1]) / 255.0, f64::from(c[2]) / 255.0, 1.0] +} + +fn root(w: &mut W, doc: &WriteDocument, v2: bool) { + w.rec(|w| { + default_line_style(w); + page(w, doc.page_mm, v2); + view(w); + document(w); + objects(w, &doc.shapes, v2); + offset_setting(w); + cut_layers(w, v2); + group_all(w); + default_layer(w); + flags(w); + trailer(w); + }); +} + +fn default_line_style(w: &mut W) { + w.rec(|w| { + w.f32(25.4); + w.u32(4); + w.u32(1); + w.zeros(2); + w.s("square"); + w.rgba([0.5, 0.5, 0.5, 1.0]); + w.rgba([0.5, 0.5, 0.5, 1.0]); + }); +} + +fn page(w: &mut W, (width, height): (f64, f64), v2: bool) { + // The page centred on the 12 × 12 in mat; a custom size has no preset name. + let (x, y) = ((MAT_MM - width) / 2.0, (MAT_MM - height) / 2.0); + w.rec(|w| { + w.u32(0); + w.u8(0); + w.f32s(&[15.875; 4]); + w.u32(1); + w.u32(1); + w.f32s(&[20.0, 0.5, 2.0, width, height, 1.0, 1.0]); + w.zeros(12); + w.f32s(&[x, y]); + w.u32(0); + w.rec(|w| { + w.s("12x12"); + w.f32s(&[324.8, 344.8, 10.0, 20.0]); + w.u32(0); + w.u8(1); + w.f32(10.0); + w.rgba([159.0 / 255.0, 161.0 / 255.0, 163.0 / 255.0, 1.0]); + w.zeros(8); + w.s("12x12"); + }); + w.rec(|w| { + w.u8(0); + w.f32(20.0); + }); + w.rec(|w| { + w.u8(1); + w.f32(20.0); + }); + w.raw(&[0, 0, 1, 0, 0, 0]); + (0..4).for_each(|_| w.f32(f64::from(TEN_MM))); + w.u32(0); + // A V2 page record ends here. + if v2 { + return; + } + // A page the size of the mat is Silhouette's 12 × 12 preset; others are custom. + let preset = (width as f32 == MAT_MM as f32 && height as f32 == MAT_MM as f32).then_some("constant:12x12"); + w.s(preset.unwrap_or("")); + w.rec(|w| { + w.u8(0); + w.u32(3); + w.u8(0); + w.u32(1); + w.f32s(&[20.0, 0.5, 100.0]); + w.u32(0); + w.f32(f64::from(TEN_MM)); + w.f32(f64::from(TEN_MM)); + // The cut area: the page less 10 mm, computed in f32 as Silhouette does. + w.f32(f64::from(width as f32) - f64::from(TEN_MM)); + w.f32(f64::from(height as f32) - f64::from(TEN_MM)); + w.s("media"); + for vals in [[25.4, 25.4, 271.6, 184.6], [25.4; 4], [15.875; 4], [25.4, 25.4, 246.2, 159.2]] { + w.u32(21); + w.u8(0); + w.f32s(&vals); + } + w.u32(1); + w.zeros(16); + w.zeros(3); + w.u8(1); + w.u8(0); + }); + w.zeros(8); + w.rec(|w| { + w.f32(322.0); + w.zeros(8); + w.f32s(&[-61.0, -40.0]); + w.u32(0); + }); + w.u32(0); + w.raw(&[0, 0, 1]); + w.rec(|w| { + w.zeros(16); + w.u8(0); + }); + w.rec(|w| { + w.u32(1); + w.u32(1); + w.f32s(&[40.0, 80.0]); + w.u32(13); + w.zeros(8); + w.u8(0); + }); + w.s("auto"); + w.rec(|w| { + w.u8(1); + w.u8(1); + w.u32(u32::MAX); + }); + w.u8(1); + w.rgba([1.0; 4]); + }); +} + +fn view(w: &mut W) { + w.rec(|w| { + w.f32s(&[0.0, 0.0, 1.0]); + w.zeros(12); + w.rec(|w| { + w.f32(1.0); + w.u32(3); + w.u32(0); + w.f32(1.0); + w.zeros(16); + }); + w.u32(2); + w.u32(0); + }); +} + +fn document(w: &mut W) { + w.rec(|w| { + w.zeros(5); + w.rec(|w| { + w.s("Print Paper"); + w.s("(Light)"); + w.s("PrintPaperLight"); + w.s("Standard light-weight printer or copy paper."); + w.u32(0); + w.raw(&[1, 0, 0]); + w.u32(10); + w.u32(10); + w.u8(0); + w.s("adjustable"); + w.f32(0.1); + w.u32(0); + }); + w.zeros(3); + w.u32(1); + w.zeros(2); + w.s("default"); + w.s("Untitled-1"); + w.zeros(2); + w.f32(3.175); + w.zeros(9); + w.u32(2); + w.f32(10.0); + w.u8(1); + w.zeros(7); + w.f32s(&[1.0, -1.0, -1.0, 4.0, 0.5, 5.0]); + w.raw(&[0, 1, 1]); + w.s("edge"); + w.u32(0); + w.u8(1); + w.s("cameo5"); + w.u8(1); + w.s("cameo5"); + w.s("auto"); + w.s("auto"); + }); +} + +/// A 32-hex-digit id for object `n`, distinct per object and stable across runs. +fn uid(n: u32) -> String { + format!("{:08x}{:08x}{:08x}{:08x}", 0x5c4a_f700u32 ^ n, n.wrapping_mul(0x9E37_79B9), 0x0c0f_fee0, n) +} + +fn objects(w: &mut W, shapes: &[WriteShape], v2: bool) { + w.rec(|w| { + if shapes.is_empty() { + w.u32(u32::MAX); + return; + } + // Count minus one, then (V3) the layers around the shapes, as Silhouette saves them; + // V2 has no layer objects. + if v2 { + w.u32(shapes.len() as u32 - 1); + } else { + w.u32(shapes.len() as u32 + 1); + layer(w, "Layer 1", 1, 0xA7D0, 1); + } + for (i, shape) in shapes.iter().enumerate() { + polygon(w, shape, 0xA800 + i as u32, 100 + i as u32); + } + if !v2 { + layer(w, "Layer 0", 0, 0xA7D5, 2); + } + }); +} + +/// The style record of an object: line colour, line width, the cut style (with its own +/// colour), corner, position and caps, then the fill. +fn style(w: &mut W, line: [f64; 4], width_mm: f64, cut: [f64; 4], fill: Option<[f64; 4]>) { + w.u8(0); + w.u8(1); + w.rgba(line); + w.u32(0); + w.f32(width_mm); + w.rec(|w| { + w.s("cut"); + w.s("Cut"); + w.s("0"); + w.rgba(cut); + w.zeros(2); + }); + w.u8(0); + w.s("rounded"); + w.u8(1); + w.s("rounded"); + match fill { + Some(c) => { + w.u8(1); + w.rgba(c); + } + None => w.u8(0), + } + paint_defaults(w); + layer_ref(w); +} + +/// After the fill: gradient and pattern defaults (identity transforms). +fn paint_defaults(w: &mut W) { + w.zeros(10); + w.raw(&[1, 0, 8, 0, 4]); + w.f32s(&[1.0, 1.0]); + w.u32(0); + w.raw(&[0, 1, 0, 1]); + w.f32s(&[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); + w.raw(&[0, 1]); + w.f32s(&[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]); + w.zeros(3); +} + +/// The reference to the document's Default Layer. +fn layer_ref(w: &mut W) { + w.rec(|w| w.u32(u32::MAX)); + w.s("Default Layer"); + w.rgba([149.0 / 255.0, 163.0 / 255.0, 169.0 / 255.0, 1.0]); + w.f32s(&[0.5, 1.5748, 1.143]); + w.zeros(16); + w.f32(1.0); + w.zeros(12); + w.u32(1); + w.zeros(9); + w.f32(1.0); + w.u32(u32::MAX); + w.zeros(9); + w.f32s(&[76.2, 1.0]); + w.zeros(8); +} + +fn inner_tail(w: &mut W) { + w.u32(0); + w.u32(50); + w.zeros(28); + w.u32(256); + w.zeros(9); + w.u32(256); + w.u32(256); + w.zeros(14); +} + +/// A handle: absent (`00`) or an offset from its node (`01`, f32 dx, dy). +fn handle(w: &mut W, h: Option<(f64, f64)>) { + match h { + Some((dx, dy)) => { + w.u8(1); + w.f32s(&[dx, dy]); + } + None => w.u8(0), + } +} + +/// The exact bounds of a shape's outline (curves included). +fn bounds(shape: &WriteShape) -> kurbo::Rect { + use kurbo::Shape as _; + let mut path = kurbo::BezPath::new(); + for c in &shape.contours { + let mut nodes = c.nodes.iter(); + let Some(first) = nodes.next() else { continue }; + path.move_to((first.x, first.y)); + let mut prev = *first; + let segment = |path: &mut kurbo::BezPath, a: WriteNode, b: WriteNode| { + if a.outgoing.is_none() && b.incoming.is_none() { + path.line_to((b.x, b.y)); + } else { + let (ox, oy) = a.outgoing.unwrap_or((0.0, 0.0)); + let (ix, iy) = b.incoming.unwrap_or((0.0, 0.0)); + path.curve_to((a.x + ox, a.y + oy), (b.x + ix, b.y + iy), (b.x, b.y)); + } + }; + for &n in nodes { + segment(&mut path, prev, n); + prev = n; + } + if c.closed { + segment(&mut path, prev, *first); + } + } + path.bounding_box() +} + +fn polygon(w: &mut W, shape: &WriteShape, ident: u32, id_seed: u32) { + let b = bounds(shape); + let (x0, y0, x1, y1) = (b.x0, b.y0, b.x1, b.y1); + // The visible line colour is the style's first colour; the cut style keeps its own. + let line = shape.line_rgb.map_or([1.0, 0.0, 0.0, 1.0], rgb); + let fill = shape.fill_rgb.map(rgb); + w.rec(|w| { + w.u8(0); + w.rec(|w| { + // The polygon's style, in a record marked 0x02. + w.tagged(2, |w| { + w.u8(0); + w.rec(|w| style(w, line, shape.width_mm, [1.0, 0.6, 0.6, 1.0], fill)); + inner_tail(w); + }); + // The outline in the object's own coordinates (identity transform): the contour + // count minus one, then per contour its closed flag, node count minus one and + // nodes (position, handles, then 0, smooth flag, 0). + w.rec(|w| { + w.u32(shape.contours.len() as u32 - 1); + for c in &shape.contours { + w.rec(|w| { + w.u8(u8::from(c.closed)); + w.u32(c.nodes.len() as u32 - 1); + for n in &c.nodes { + w.rec(|w| { + w.f32s(&[n.x, n.y]); + handle(w, n.incoming); + handle(w, n.outgoing); + let smooth = n.incoming.is_some() && n.outgoing.is_some(); + w.raw(&[0, u8::from(smooth), 0]); + }); + } + }); + } + }); + }); + // Transform (identity), the selection frame, the fill mode. + w.f32s(&[1.0, 0.0, 0.0, 0.0, 1.0, 0.0]); + w.zeros(8); + w.f32s(&[1.0, (x0 + x1) / 2.0, (y0 + y1) / 2.0, (x1 - x0) / 2.0]); + w.zeros(8); + w.f32((y1 - y0) / 2.0); + w.u32(if fill.is_some() { 2 } else { 1 }); + w.u8(0); + // The page-coordinate outline the reader reads. + w.rec(|w| { + w.u32(shape.contours.len() as u32 - 1); + for c in &shape.contours { + w.sized(|w| { + w.u8(u8::from(c.closed)); + w.u32(c.nodes.len() as u32 - 1); + for n in &c.nodes { + w.f32s(&[n.x, n.y]); + handle(w, n.incoming); + handle(w, n.outgoing); + } + }); + } + }); + w.u8(1); + w.u32(ident); + w.u32(0); + w.rec(|w| w.zeros(8)); + w.s("Polygon"); + w.u32(0); + w.s(&uid(id_seed)); + w.u32(0); + w.u32(8); + w.u32(0); + w.u32(u32::MAX); + w.u32(0); + w.u32(0); + }); +} + +fn layer(w: &mut W, name: &str, index: u32, ident: u32, id_seed: u32) { + w.rec(|w| { + w.u8(0); + w.rec(|w| { + w.tagged(0x24, |w| { + w.u8(0); + w.rec(|w| style(w, [1.0, 0.0, 0.0, 1.0], 0.0, [1.0, 0.6, 0.6, 1.0], None)); + inner_tail(w); + }); + w.zeros(2); + w.u32(1); + w.u32(51); + w.u32(0x4F9E_8211); + w.s(&uid(id_seed + 1000)); + w.u8(0); + w.u32(0x4394_2839); + w.raw(&[1, 1]); + }); + w.f32s(&[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0]); + w.u32(2); + w.u8(0); + w.rec(|w| w.u32(u32::MAX)); + w.u8(1); + w.u32(ident); + w.u32(0); + w.rec(|w| w.zeros(8)); + w.s(name); + w.u32(index); + w.s(&uid(id_seed)); + w.zeros(12); + w.u32(u32::MAX); + w.zeros(8); + }); +} + +fn offset_setting(w: &mut W) { + w.rec(|w| { + w.zeros(2); + w.s("off"); + w.u32(0); + w.sized(|w| { + w.u8(0); + w.f32s(&[10.0; 4]); + }); + w.u8(0); + }); +} + +const PATTERN: &str = "222222222222222222222222222222A"; +const MATERIAL_ID: &str = "5bdfacf526573b1fd749d97a05328dbb"; + +/// A cut layer's tool settings: V2 stores 98 and the action `unknown` where V3 has 100 and +/// `no_action`. +fn tool_block(w: &mut W, v2: bool) { + w.s("no_tool"); + tool_tail(w, v2); +} + +fn tool_tail(w: &mut W, v2: bool) { + w.u32(if v2 { 98 } else { 100 }); + w.s(MATERIAL_ID); + w.s(PATTERN); + w.s("auto"); + w.s(if v2 { "unknown" } else { "no_action" }); +} + +fn cut_layers(w: &mut W, v2: bool) { + const LAYERS: [(&str, bool, bool, bool); 10] = [ + ("cnon", false, false, false), + ("ccut", true, false, false), + ("cced", true, true, false), + ("cper", true, false, false), + ("cped", true, true, false), + ("ccu2", true, false, true), + ("cce2", true, true, true), + ("cpf2", true, false, true), + ("cpe2", true, true, true), + ("weed", true, false, false), + ]; + w.rec(|w| { + w.u32(4); + w.u8(0); + w.u32(LAYERS.len() as u32 - 1); + for (key, used, edge, tool2) in LAYERS { + w.s(&format!("layer_@{key}:")); + w.sized(|w| { + w.s(&format!("@{key}:")); + w.s(PATTERN); + w.raw(&[u8::from(used), 0, u8::from(edge), u8::from(tool2), 0, 0, 0]); + tool_block(w, v2); + w.raw(&[u8::from(tool2), 0, 0, 0]); + w.raw(b"studio4.3extension1_dghyujnbvf"); + w.u8(1); + tool_tail(w, v2); + w.raw(&[u8::from(tool2), 0, 0, 0]); + }); + } + w.u32(1); + w.u8(0); + }); +} + +fn group_all(w: &mut W) { + const IDS: [u32; 6] = [1, 2, 3, 5, 6, 7]; + w.rec(|w| { + w.u32(IDS.len() as u32); + w.sized(|w| { + w.u32(4); + w.u32(0); + w.s("@all :"); + }); + for id in IDS { + w.sized(|w| { + w.u32(id); + w.u32(u32::MAX); + }); + } + }); +} + +fn default_layer(w: &mut W) { + let doc_id = uid(0); + // The tail is built apart: its first 272 bytes close the inner record, the rest follow it. + let mut tail = W::writing(MAX_FILE_BYTES, 1024); + default_layer_tail(&mut tail, &doc_id); + let bytes = tail.bytes.unwrap_or_default(); + let (inside, outside) = bytes.split_at(bytes.len().min(272)); + w.rec(|w| { + w.u8(0); + w.rec(|w| { + w.tagged(0x25, |w| { + w.u8(0); + w.rec(|w| style(w, [167.0 / 255.0, 202.0 / 255.0, 1.0, 1.0], 0.5, [1.0, 0.6, 0.6, 1.0], None)); + inner_tail(w); + }); + w.raw(inside); + }); + w.raw(outside); + }); +} + +fn flags(w: &mut W) { + w.rec(|w| { + w.u32(1); + w.u32(10); + w.u32(1); + w.u8(0); + w.u32(1); + w.zeros(2); + }); +} + +fn preset(w: &mut W, group: &str, n: &str, id: &str, colour: [f64; 4]) { + w.sized(|w| { + w.s(group); + w.s(n); + w.s(id); + w.rgba(colour); + w.rgba(colour); + w.u32(0); + w.s(&format!("offsetter.{group}.layer_name.{n}")); + }); +} + +fn trailer(w: &mut W) { + const RED: [f64; 4] = [0.963, 0.0, 0.0, 1.0]; + const BLUE: [f64; 4] = [0.04, 0.424, 1.0, 1.0]; + w.rec(|_| {}); + w.rec(|w| w.zeros(2)); + w.rec(|w| { + for (group, ids, counts) in [ + ("score", ["92cd7ee5a6fd92e0d8da0a20336d1f86", "2f470615bdc4231752d96cc2e14d6fd1"], [2, 2, 2]), + ("template", ["57286a9eb74364ccb766fe3f4902d1aa", "2f470615bdc4231752d96cc2e14d6fd1"], [1, 2, 2]), + ] { + w.sized(|w| { + w.s(group); + preset(w, group, "1", ids[0], RED); + preset(w, group, "2", ids[1], BLUE); + w.f32(0.3); + counts.iter().for_each(|&c| w.u32(c)); + w.u32(1); + w.u8(0); + }); + } + }); + w.rec(|w| w.zeros(8)); + w.zeros(5); + w.f32(1.27); + w.rec(|w| w.u8(0)); + w.rec(|w| { + w.f32(1.5); + w.raw(&[1, 1, 1]); + }); + w.rec(|w| { + w.u8(0); + w.u32(1); + w.raw(&[0, 0, 1]); + w.f32(20.0); + w.u32(1); + }); +} + +/// The Default Layer after its style: its frame, matrices and the document id. +fn default_layer_tail(w: &mut W, doc_id: &str) { + // (The record before ends with the first two of these four zero bytes.) + w.zeros(2); + w.rec(|w| { + w.u32(4); + w.u32(28); + w.u32(0); + w.u32(0); + w.f32(50.0); + w.f32(50.0); + w.u32(2); + w.u32(1); + }); + w.rec(|w| { + w.u32(4); + w.rec(|w| { + w.u32(3); + w.rec(|w| { + w.u32(0); + w.u32(0); + w.u32(0); + w.f32(1.0); + }); + w.rec(|w| { + w.u32(0); + w.f32(1.0); + w.f32(1.0); + w.f32(1.0); + }); + w.rec(|w| { + w.f32(1.0); + w.f32(1.0); + w.f32(1.0); + w.u32(0); + }); + w.rec(|w| { + w.f32(1.0); + w.u32(0); + w.u32(0); + w.u32(0); + }); + }); + w.rec(|w| { + w.u32(0); + w.rec(|w| { + w.u32(0); + w.u32(0); + w.u32(0); + w.f32(1.0); + w.f32(1.0); + w.f32(1.0); + w.f32(1.0); + w.u32(0); + w.u8(1); + }); + }); + }); + w.rec(|w| { + w.u32(0); + w.u32(0); + w.u32(0); + w.u32(0); + w.u8(0); + }); + w.u8(1); + w.u8(0); + w.rec(|w| { + w.u8(0); + w.f32(25.0); + w.u8(1); + w.u8(1); + w.u8(0); + }); + w.rec(|w| { + w.u32(4); + }); + w.u32(1); + w.u32(0); + w.u32(1); + w.u32(0); + w.rec(|w| { + w.u32(0); + w.u32(0); + w.u32(0); + w.u32(0); + w.u8(0); + }); + w.f32(1.0); + w.u32(0); + w.u32(0); + w.u32(0); + w.f32(1.0); + w.u32(0); + w.u32(0); + w.u32(0); + w.f32(1.0); + w.f32(0.5); + w.f32(0.5); + w.f32(0.5); + w.u32(0); + w.u32(0); + w.f32(0.5); + w.u32(2); + w.u8(0); + w.rec(|w| { + w.u32(0xffffffff); + }); + w.rec(|w| { + w.u32(0); + w.rec(|w| { + w.u32(0); + w.u32(0); + }); + w.u32(0); + w.u32(0); + w.s(doc_id); + w.u32(0); + w.u8(0); + w.u8(0); + }); + w.u32(0); + w.u8(0); + w.u8(0); + w.u32(0xffffffff); + w.u32(0); + w.u32(0); +} + +#[cfg(test)] +mod tests { + use super::*; + use kurbo::Shape as _; + + fn shape(points: &[(f64, f64)], closed: bool, line: Option<[u8; 3]>) -> WriteShape { + let nodes = points.iter().map(|&(x, y)| WriteNode::corner(x, y)).collect(); + WriteShape { contours: vec![WriteContour { nodes, closed }], line_rgb: line, fill_rgb: None, width_mm: 0.0 } + } + + #[test] + fn written_documents_read_back_with_their_page_shapes_and_colours() { + let doc = WriteDocument { + page_mm: (150.0, 120.0), + shapes: vec![ + shape(&[(25.0, 45.0), (25.0, 105.0), (125.0, 105.0), (125.0, 45.0)], true, None), + shape(&[(30.0, 110.0), (80.0, 115.0), (130.0, 110.0)], false, Some([0, 90, 200])), + WriteShape { + fill_rgb: Some([250, 200, 40]), + width_mm: 0.5, + ..shape(&[(60.0, 10.0), (90.0, 35.0), (30.0, 35.0)], true, Some([200, 0, 0])) + }, + ], + }; + let bytes = write(&doc).unwrap(); + assert_eq!(bytes.get(..13), Some(b"silhouette05;".as_slice())); + let back = crate::import(&bytes).unwrap(); + assert_eq!(back.version, crate::Version::V3); + assert_eq!(back.page_mm, Some((150.0, 120.0))); + assert_eq!(back.shapes.len(), 3); + let b = back.shapes[0].path.bounding_box(); + assert!((b.x0 - 25.0).abs() < 1e-4 && (b.y1 - 105.0).abs() < 1e-4, "{b:?}"); + let closes = |i: usize| back.shapes[i].path.elements().iter().any(|e| matches!(e, kurbo::PathEl::ClosePath)); + assert!(closes(0) && !closes(1) && closes(2)); + let lines: Vec<_> = back.shapes.iter().map(|s| s.line_color).collect(); + assert_eq!(lines, [Some([255, 0, 0]), Some([0, 90, 200]), Some([200, 0, 0])]); + } + + #[test] + fn curves_and_compound_paths_round_trip() { + let mut path = kurbo::BezPath::from_svg("M10 50 C10 20 90 20 90 50 C90 80 10 80 10 50 Z M40 45 L60 45 L50 60 Z").unwrap(); + path.apply_affine(kurbo::Affine::IDENTITY); + let contours = WriteContour::from_path(&path); + assert_eq!(contours.len(), 2); + assert_eq!(contours[0].nodes.len(), 2, "the closing curve folds into the first node"); + assert!(contours[0].nodes[0].incoming.is_some() && contours[0].nodes[0].outgoing.is_some()); + let doc = WriteDocument { page_mm: (100.0, 100.0), shapes: vec![WriteShape { contours, line_rgb: None, fill_rgb: None, width_mm: 0.0 }] }; + let back = crate::import(&write(&doc).unwrap()).unwrap(); + assert_eq!(back.shapes.len(), 1, "one compound shape"); + let b = back.shapes[0].path.bounding_box(); + // The ellipse-like curve reaches y = 27.5 at its top, beyond its nodes at y = 50. + assert!((b.y0 - 27.5).abs() < 0.01 && (b.x0 - 10.0).abs() < 1e-4, "{b:?}"); + let curves = back.shapes[0].path.elements().iter().filter(|e| matches!(e, kurbo::PathEl::CurveTo(..))).count(); + assert_eq!(curves, 2); + } + + #[test] + fn studio_v2_documents_read_back() { + let doc = + WriteDocument { page_mm: (120.0, 90.0), shapes: vec![shape(&[(10.0, 10.0), (60.0, 10.0), (60.0, 40.0)], true, Some([0, 90, 200]))] }; + let bytes = write_v2(&doc).unwrap(); + assert_eq!(bytes.get(..13), Some(b"silhouette04;".as_slice())); + let back = crate::import(&bytes).unwrap(); + assert_eq!(back.version, crate::Version::V2); + assert_eq!(back.page_mm, Some((120.0, 90.0))); + assert_eq!(back.shapes.len(), 1); + assert_eq!(back.shapes[0].line_color, Some([0, 90, 200])); + assert!(write_v2(&WriteDocument { page_mm: (0.0, 1.0), shapes: Vec::new() }).is_err()); + } + + #[test] + fn an_empty_document_has_the_layout_silhouette_reads() { + let bytes = write(&WriteDocument { page_mm: (304.8, 304.8), shapes: Vec::new() }).unwrap(); + let section = u64::from_le_bytes(bytes[0x10..0x18].try_into().unwrap()) as usize; + assert_eq!(bytes.len(), 0x400 + section, "only section 0"); + assert_eq!(&bytes[0x3E8..0x3EC], &HEADER_MAGIC.to_le_bytes()); + let back = crate::import(&bytes).unwrap(); + assert!(back.shapes.is_empty()); + assert_eq!(back.page_mm, Some((304.8, 304.8))); + } + + #[test] + fn supported_page_range_round_trips() { + for writer in [write, write_v2] { + let mut doc = WriteDocument { page_mm: (1.0, 1.0), shapes: Vec::new() }; + let bytes = writer(&doc).unwrap(); + assert_eq!(crate::import(&bytes).unwrap().page_mm, Some((1.0, 1.0))); + doc.page_mm.0 = 0.5; + assert!(writer(&doc).is_err()); + } + } + + #[test] + fn record_counter_matches_serialized_document_size() { + let doc = WriteDocument { page_mm: (30.0, 20.0), shapes: Vec::new() }; + let mut count = W::counting(MAX_FILE_BYTES); + count.raw(b"silhouette04;"); + root(&mut count, &doc, true); + let size = count.checked_len().unwrap(); + assert_eq!(write_v2(&doc).unwrap().len(), size); + let mut small_budget = W::counting(size - 1); + small_budget.raw(b"silhouette04;"); + root(&mut small_budget, &doc, true); + assert_eq!(small_budget.checked_len(), Err(Error::TooLarge)); + assert!(small_budget.bytes.is_none()); + } + + #[test] + fn hostile_documents_are_errors_not_crashes() { + let ok = shape(&[(0.0, 0.0), (1.0, 1.0)], false, None); + for doc in [ + WriteDocument { page_mm: (f64::NAN, 10.0), shapes: Vec::new() }, + WriteDocument { page_mm: (0.0, 10.0), shapes: Vec::new() }, + WriteDocument { page_mm: (1e9, 10.0), shapes: Vec::new() }, + WriteDocument { page_mm: (10.0, 10.0), shapes: vec![shape(&[(0.0, 0.0)], false, None)] }, + WriteDocument { + page_mm: (10.0, 10.0), + shapes: vec![WriteShape { contours: Vec::new(), ..shape(&[(0.0, 0.0), (1.0, 1.0)], false, None) }], + }, + WriteDocument { page_mm: (10.0, 10.0), shapes: vec![shape(&[(0.0, f64::INFINITY), (1.0, 1.0)], false, None)] }, + WriteDocument { page_mm: (10.0, 10.0), shapes: vec![WriteShape { width_mm: -1.0, ..ok.clone() }] }, + ] { + assert!(write(&doc).is_err(), "{doc:?}"); + } + assert!(write(&WriteDocument { page_mm: (10.0, 10.0), shapes: vec![ok] }).is_ok()); + } +} From f8ee722798af750ce83571c0a52783f9f681d5c9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 19:53:47 -0500 Subject: [PATCH 8/9] silhouette-studio: read which group each object belongs to (#3671) * silhouette-studio: read which group each object belongs to * Restore main fill colour reader during Studio merge * Name the resolved group membership structure --- crates/silhouette-studio/src/lib.rs | 149 +++++++++++++++++++++++++++- 1 file changed, 144 insertions(+), 5 deletions(-) diff --git a/crates/silhouette-studio/src/lib.rs b/crates/silhouette-studio/src/lib.rs index ddbcecabf6..5237ce172e 100644 --- a/crates/silhouette-studio/src/lib.rs +++ b/crates/silhouette-studio/src/lib.rs @@ -3,7 +3,7 @@ //! shapes of straight and Bézier contours with line colour, width and fill. //! //! It reads every object's outline (open and closed paths, lines and Bézier curves, compound -//! paths, text as outlines), each outline's line and fill colours and the page size. Coordinates are +//! paths, text as outlines), each outline's line and fill colours, the groups objects belong to and the page size. Coordinates are //! millimetres from the page's top-left corner, y down, as the file stores them. Layers //! and cut settings are not read. //! @@ -70,9 +70,10 @@ pub struct Shape { pub path: BezPath, /// The object's line colour (R, G, B), when its style record was found. pub line_color: Option<[u8; 3]>, - /// The object's fill colour (R, G, B); `None` when it has no fill or the style record was - /// not found. + /// The object's fill colour (R, G, B), if the style record contains it. pub fill_color: Option<[u8; 3]>, + /// The innermost group holding the object: an index into [`Imported::group_parents`]. + pub group: Option, } /// A document's shapes in file order, plus notes about what was skipped. @@ -82,6 +83,8 @@ pub struct Imported { /// Page width and height in millimetres; `None` when the page record is not as expected. pub page_mm: Option<(f64, f64)>, pub shapes: Vec, + /// One entry per group, outermost first: the group holding it, if any. + pub group_parents: Vec>, pub warnings: Vec, } @@ -123,6 +126,7 @@ pub fn import(bytes: &[u8]) -> Result { let mut warnings = Vec::new(); let root = block(body, MAGIC_LEN).ok_or_else(|| bad("root record is truncated"))?; let mut shapes = Vec::new(); + let mut starts = Vec::new(); let mut points_total = 0usize; let mut cursor = root.start; // An object's style record comes before its outline: search from the last outline. @@ -145,13 +149,116 @@ pub fn import(bytes: &[u8]) -> Result { warnings.push(format!("skipped a path at byte {at}: coordinates out of range")); continue; } - shapes.push(Shape { path: bez, line_color: line_color_before(body, style_from, at), fill_color: fill_color_before(body, style_from, at) }); + shapes.push(Shape { + path: bez, + line_color: line_color_before(body, style_from, at), + fill_color: fill_color_before(body, style_from, at), + group: None, + }); + starts.push((at, path.end)); style_from = path.end; } if budget.get() == 0 { return Err(bad("too much data that only looks like outlines")); } - Ok(Imported { version, page_mm: page_size(body, &root), shapes, warnings }) + let spans = group_spans(body, &root); + let group_parents = match spans.and_then(|spans| group_memberships(&spans, &starts)) { + Some(GroupMemberships { parents, members }) => { + for (shape, group) in shapes.iter_mut().zip(members) { + shape.group = group; + } + parents + } + None => { + warnings.push("group records could not be read consistently; outlines retained".to_string()); + Vec::new() + } + }; + Ok(Imported { version, page_mm: page_size(body, &root), shapes, group_parents, warnings }) +} + +/// The most groups read from one document. +const MAX_GROUPS: usize = 100_000; +/// How many bytes the group search may look back over in all. +const GROUP_SEARCH_BUDGET: usize = 64 * 1024 * 1024; + +/// Group objects as byte spans, outermost first. A group's record (marker `0x01`, a u32 length +/// counting itself) holds its members' records and ends shortly after its type name, +/// length-prefixed "Group". Found by saving the same two rectangles ungrouped and grouped in +/// Silhouette Studio 5.0.556 and comparing the bytes. +fn group_spans(d: &[u8], root: &Block) -> Option> { + const NAME: &[u8] = b"\x05\x00\x00\x00Group"; + let window = d.get(root.start..root.end).unwrap_or_default(); + let mut spans = Vec::new(); + let mut budget = GROUP_SEARCH_BUDGET; + let mut offset = 0; + while let Some(rel) = window.get(offset..).and_then(|w| w.windows(NAME.len()).position(|w| w == NAME)) { + let name = root.start + offset + rel; + offset += rel + 1; + if spans.len() >= MAX_GROUPS || budget == 0 { + return None; + } + // The nearest record start before the name whose record ends just after it. + let mut start = name; + while start > root.start && budget > 0 { + start -= 1; + budget -= 1; + if let Some(b) = block(d, start) + && b.end >= name + NAME.len() + && b.end <= name.saturating_add(512) + && b.end <= root.end + { + spans.push((start, b.end)); + break; + } + } + } + if budget == 0 { + return None; + } + spans.sort_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1))); + spans.dedup(); + Some(spans) +} + +struct GroupMemberships { + parents: Vec>, + members: Vec>, +} + +/// Resolve laminar group records and sorted outline intervals by a forward sweep. +/// Crossing group intervals are not a tree; don't infer metadata from them. +fn group_memberships(spans: &[(usize, usize)], outlines: &[(usize, usize)]) -> Option { + let mut parents = Vec::with_capacity(spans.len()); + let mut stack: Vec = Vec::new(); + for (i, &(start, end)) in spans.iter().enumerate() { + while stack.last().is_some_and(|&j| spans[j].1 <= start) { + stack.pop(); + } + if stack.last().is_some_and(|&j| spans[j].1 < end) { + return None; + } + parents.push(stack.last().copied()); + stack.push(i); + } + + stack.clear(); + let mut next = 0usize; + let mut members = Vec::with_capacity(outlines.len()); + for &(start, end) in outlines { + while let Some(&(group_start, _)) = spans.get(next).filter(|s| s.0 <= start) { + while stack.last().is_some_and(|&j| spans[j].1 <= group_start) { + stack.pop(); + } + stack.push(next); + next += 1; + } + while stack.last().is_some_and(|&j| spans[j].1 < end) { + stack.pop(); + } + members.push(stack.last().copied()); + } + Some(GroupMemberships { parents, members }) } /// `.studio3`: the header is a table of little-endian u64 section lengths; the @@ -447,6 +554,38 @@ fn f32_at(d: &[u8], at: usize) -> Option { mod tests { use super::*; + #[test] + fn groups_are_the_records_named_group_that_hold_outlines() { + // Root payload: a group record (a member outline, then its "Group" name) and an + // outline outside it. + let square: &[(f32, f32)] = &[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 0.0)]; + let mut inner = path_record(&[(true, square)]); + inner.extend_from_slice(&5u32.to_le_bytes()); + inner.extend_from_slice(b"Group"); + let group = block(&inner); + let mut root_payload = group.clone(); + root_payload.extend(path_record(&[(true, square)])); + let mut d = b"silhouette04;".to_vec(); + d.extend(block(&root_payload)); + let root = super::block(&d, MAGIC_LEN).unwrap(); + let spans = group_spans(&d, &root).unwrap(); + assert_eq!(spans.len(), 1); + let (s, e) = spans[0]; + assert_eq!(e - s, group.len()); + let GroupMemberships { parents, members } = group_memberships(&spans, &[(s + 6, s + 7), (e + 1, e + 2)]).unwrap(); + assert_eq!(parents, vec![None], "a group is not its own parent"); + assert_eq!(members, vec![Some(0), None]); + } + + #[test] + fn nested_groups_keep_innermost_members_and_outer_parent() { + let spans = [(10, 100), (15, 35), (50, 90), (60, 80), (120, 140)]; + let outlines = [(12, 14), (20, 30), (40, 45), (65, 70), (110, 115), (125, 130)]; + let GroupMemberships { parents, members } = group_memberships(&spans, &outlines).unwrap(); + assert_eq!(parents, vec![None, Some(0), Some(0), Some(2), None]); + assert_eq!(members, vec![Some(0), Some(1), Some(0), Some(3), None, Some(4)]); + } + /// The tail of a style record as `.studio3` files store it: the cap and join names, then /// the fill flag and, with a fill, R, G, B, A as f32. fn style_tail(fill: Option<[f32; 4]>) -> Vec { From f9371995bc583827e4c7c48a3c83f605d0db7fc8 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 20:54:20 -0500 Subject: [PATCH 9/9] silhouette-studio: read text objects (characters, font, size, origin) (#3673) * silhouette-studio: read text objects (characters, font, size, origin) * Restore main fill colour reader during Studio merge --- crates/silhouette-studio/src/lib.rs | 162 +++++++++++++++++++++++++++- 1 file changed, 160 insertions(+), 2 deletions(-) diff --git a/crates/silhouette-studio/src/lib.rs b/crates/silhouette-studio/src/lib.rs index 5237ce172e..a616fae9b1 100644 --- a/crates/silhouette-studio/src/lib.rs +++ b/crates/silhouette-studio/src/lib.rs @@ -3,7 +3,8 @@ //! shapes of straight and Bézier contours with line colour, width and fill. //! //! It reads every object's outline (open and closed paths, lines and Bézier curves, compound -//! paths, text as outlines), each outline's line and fill colours, the groups objects belong to and the page size. Coordinates are +//! paths, text as outlines), each outline's line and fill colours, nested groups, text characters, +//! font and size, and page dimensions. Coordinates are //! millimetres from the page's top-left corner, y down, as the file stores them. Layers //! and cut settings are not read. //! @@ -74,6 +75,22 @@ pub struct Shape { pub fill_color: Option<[u8; 3]>, /// The innermost group holding the object: an index into [`Imported::group_parents`]. pub group: Option, + /// When the outline is a letter of a text object: an index into [`Imported::texts`]. + pub text: Option, +} + +/// A text object as typed: its characters, font and size, and where it starts. Its letters +/// are also read as outlines (shapes whose [`Shape::text`] points here). +#[derive(Debug, Clone, PartialEq)] +pub struct Text { + pub text: String, + /// The font family's name, when its record was found. + pub font: Option, + /// The font size in millimetres (25.4 for 72 pt). + pub size_mm: f64, + /// The text's origin in page millimetres. + pub x_mm: f64, + pub y_mm: f64, } /// A document's shapes in file order, plus notes about what was skipped. @@ -85,6 +102,8 @@ pub struct Imported { pub shapes: Vec, /// One entry per group, outermost first: the group holding it, if any. pub group_parents: Vec>, + /// Text objects in file order. + pub texts: Vec, pub warnings: Vec, } @@ -127,6 +146,7 @@ pub fn import(bytes: &[u8]) -> Result { let root = block(body, MAGIC_LEN).ok_or_else(|| bad("root record is truncated"))?; let mut shapes = Vec::new(); let mut starts = Vec::new(); + let mut text_starts = Vec::new(); let mut points_total = 0usize; let mut cursor = root.start; // An object's style record comes before its outline: search from the last outline. @@ -154,8 +174,10 @@ pub fn import(bytes: &[u8]) -> Result { line_color: line_color_before(body, style_from, at), fill_color: fill_color_before(body, style_from, at), group: None, + text: None, }); starts.push((at, path.end)); + text_starts.push((style_from, at)); style_from = path.end; } if budget.get() == 0 { @@ -174,7 +196,107 @@ pub fn import(bytes: &[u8]) -> Result { Vec::new() } }; - Ok(Imported { version, page_mm: page_size(body, &root), shapes, group_parents, warnings }) + let records = glyph_records(body, &root)?; + let (texts, owners) = build_texts(body, &records); + for (shape, &(from, at)) in shapes.iter_mut().zip(&text_starts) { + // The letter's record comes just before its outline. + shape.text = + records.partition_point(|r| r.at < at).checked_sub(1).filter(|&i| records[i].at >= from && records[i].code != 0).and_then(|i| owners[i]); + } + Ok(Imported { version, page_mm: page_size(body, &root), shapes, group_parents, texts, warnings }) +} + +/// The most glyph records read from one document. +const MAX_GLYPHS: usize = 1_000_000; + +/// One record of a text object: a u32 code (0 for the text object itself, else a letter's +/// Unicode scalar), then a 2 × 3 transform as six f32 (size, 0, x, 0, size, y), after the +/// marker bytes `01 00 00 00 01` and 16 zero bytes. Found by saving "Hello", "Hellp" and "A B" in +/// Silhouette Studio 5.0.556 and comparing the bytes; a space has a record but no outline. +#[derive(Debug, Clone, Copy, PartialEq)] +struct GlyphRecord { + at: usize, + code: u32, + size_mm: f32, + x_mm: f32, + y_mm: f32, +} + +fn glyph_records(d: &[u8], root: &Block) -> Result, Error> { + const LEAD: [u8; 21] = [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + let mut out = Vec::new(); + let end = root.end.min(d.len()); + let mut at = root.start + LEAD.len(); + while at + 28 <= end { + if d.get(at - LEAD.len()..at) == Some(LEAD.as_slice()) + && let (Some(code), Some(size), Some(zero), Some(x), Some(zero2), Some(size2), Some(y)) = + (u32_at(d, at), f32_at(d, at + 4), f32_at(d, at + 8), f32_at(d, at + 12), f32_at(d, at + 16), f32_at(d, at + 20), f32_at(d, at + 24)) + { + let limit = MAX_COORD_MM; + let plausible = (0.01..=1000.0).contains(&size) + && size2 == size + && zero == 0.0 + && zero2 == 0.0 + && x.is_finite() + && y.is_finite() + && x.abs() <= limit + && y.abs() <= limit + && (code == 0 || char::from_u32(code).is_some_and(|c| !c.is_control() || matches!(c, '\n' | '\r' | '\t'))); + if plausible { + if out.len() == MAX_GLYPHS { + return Err(Error::Malformed("more than the supported number of glyph records".to_string())); + } + out.push(GlyphRecord { at, code, size_mm: size, x_mm: x, y_mm: y }); + at += 28; + continue; + } + } + at += 1; + } + Ok(out) +} + +/// Text objects from their records: each object's record (code 0) starts one, its letters +/// follow. Returns the texts and, per record, the text it belongs to. +fn build_texts(d: &[u8], records: &[GlyphRecord]) -> (Vec, Vec>) { + let mut texts: Vec = Vec::new(); + let mut owners = Vec::with_capacity(records.len()); + for r in records { + if r.code == 0 { + texts.push(Text { + text: String::new(), + font: font_name_before(d, r.at), + size_mm: f64::from(r.size_mm), + x_mm: f64::from(r.x_mm), + y_mm: f64::from(r.y_mm), + }); + owners.push(texts.len().checked_sub(1)); + continue; + } + let owner = texts.len().checked_sub(1); + if let (Some(i), Some(c)) = (owner, char::from_u32(r.code)) + && let Some(text) = texts.get_mut(i) + { + text.text.push(c); + } + owners.push(owner); + } + (texts, owners) +} + +/// The nearest length-prefixed name (1–64 printable bytes) ending within 160 bytes before +/// `at`: a text object's font family ("Arial"), stored just ahead of its record. +fn font_name_before(d: &[u8], at: usize) -> Option { + let from = at.saturating_sub(160); + (from..at.saturating_sub(5)).rev().find_map(|p| { + let n = usize::try_from(u32_at(d, p)?).ok()?; + if !(1..=64).contains(&n) { + return None; + } + let name = d.get(p + 4..p + 4 + n)?; + (p + 4 + n <= at && name.iter().all(|b| (0x20..0x7f).contains(b)) && name.iter().any(u8::is_ascii_alphabetic)) + .then(|| String::from_utf8_lossy(name).into_owned()) + }) } /// The most groups read from one document. @@ -586,6 +708,42 @@ mod tests { assert_eq!(members, vec![Some(0), Some(1), Some(0), Some(3), None, Some(4)]); } + fn glyph(code: u32, size: f32, x: f32, y: f32) -> Vec { + let mut out = vec![1, 0, 0, 0, 1]; + out.extend_from_slice(&[0; 16]); + out.extend_from_slice(&code.to_le_bytes()); + for v in [size, 0.0, x, 0.0, size, y] { + out.extend_from_slice(&v.to_le_bytes()); + } + out + } + + #[test] + fn text_objects_are_read_from_their_letter_records() { + let mut payload = 5u32.to_le_bytes().to_vec(); + payload.extend_from_slice(b"Arial"); + payload.extend_from_slice(&[0; 8]); + payload.extend(glyph(0, 25.4, 67.9, 91.5)); + for (c, x) in [('A', 67.9), (' ', 83.5), ('B', 90.5)] { + payload.extend(glyph(c as u32, 25.4, x, 91.5)); + } + // A record whose two sizes differ is not a letter. + let mut bad = glyph('C' as u32, 25.4, 1.0, 1.0); + bad[41..45].copy_from_slice(&3.0f32.to_le_bytes()); + payload.extend(bad); + let mut d = b"silhouette04;".to_vec(); + d.extend(block(&payload)); + let root = super::block(&d, MAGIC_LEN).unwrap(); + let records = glyph_records(&d, &root).unwrap(); + assert_eq!(records.len(), 4); + let (texts, owners) = build_texts(&d, &records); + assert_eq!(texts.len(), 1); + assert_eq!(texts[0].text, "A B"); + assert_eq!(texts[0].font.as_deref(), Some("Arial")); + assert!((texts[0].size_mm - 25.4).abs() < 1e-4 && (texts[0].x_mm - 67.9).abs() < 1e-4); + assert_eq!(owners, [Some(0); 4]); + } + /// The tail of a style record as `.studio3` files store it: the cap and join names, then /// the fill flag and, with a fill, R, G, B, A as f32. fn style_tail(fill: Option<[f32; 4]>) -> Vec {