diff --git a/Cargo.lock b/Cargo.lock index c319ea1631..ea03712224 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3051,6 +3051,8 @@ version = "0.1.0" name = "craft-i18n" version = "0.1.0" dependencies = [ + "brotli 9.1.1", + "brotli-decompressor 6.3.1", "chrono", "fixed_decimal", "icu_calendar", diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index ebba43bc8e..7ac49505b0 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -608,6 +608,7 @@ 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-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"] diff --git a/crates/file-import/src/lib.rs b/crates/file-import/src/lib.rs index 62ad8ad404..e42060210d 100644 --- a/crates/file-import/src/lib.rs +++ b/crates/file-import/src/lib.rs @@ -445,6 +445,7 @@ mod format_tests { height_mm: 50.0, view_box: [0.0, 0.0, 50.0, 50.0], paths: vec![crate::write::PdfPath { path: square, color_rgb: [255, 0, 0], stroke_width_mm: None }], + images: vec![], }]) .unwrap(); let image = render_pdf_page(&pdf, 0, 72.0, Limits::default()).unwrap(); diff --git a/crates/file-import/src/write.rs b/crates/file-import/src/write.rs index 4d9168cb4c..20b60be995 100644 --- a/crates/file-import/src/write.rs +++ b/crates/file-import/src/write.rs @@ -36,6 +36,9 @@ pub struct OutputPath { pub data_kind: Option, /// Close each open contour for formats that require closed cutting operations. pub close_open_contours: bool, + /// The colour the path is filled with in SVG and PDF output (even-odd, as drawn); `None` + /// leaves it unfilled. Cutter and DXF writers ignore it. + pub fill_rgb: Option<[u8; 3]>, } /// A placed raster picture: straight RGBA pixels, row by row from the top, and the box it @@ -171,11 +174,15 @@ fn write_svg(scene: &OutputScene) -> Result { .iter() .map(|path| { let color = path.color_rgb; + let fill = path.fill_rgb.map_or_else(|| "none".to_string(), |[r, g, b]| format!("#{r:02x}{g:02x}{b:02x}")); let mut attributes = vec![ - craft_svg::write::Attribute::text("fill", "none"), + craft_svg::write::Attribute::text("fill", fill), craft_svg::write::Attribute::text("stroke", format!("#{:02x}{:02x}{:02x}", color[0], color[1], color[2])), craft_svg::write::Attribute::text("stroke-width", format_float(path.stroke_width_mm / view_scale)), ]; + if path.fill_rgb.is_some() { + attributes.push(craft_svg::write::Attribute::text("fill-rule", "evenodd")); + } if let Some(class) = &path.class { attributes.push(craft_svg::write::Attribute::text("class", class.clone())); } @@ -211,15 +218,20 @@ fn write_pdf(scene: &OutputScene) -> Result, Error> { .enumerate() .filter(|(_, layer)| layer.visible) .flat_map(|(layer_index, _)| paths_by_layer[layer_index].iter().copied()) - .map(|path| PdfPath { path: path.path.clone(), color_rgb: path.color_rgb, stroke_width_mm: Some(path.stroke_width_mm) }) + // A filled path paints its fill, then its line over it. + .flat_map(|path| { + let fill = path.fill_rgb.map(|rgb| PdfPath { path: path.path.clone(), color_rgb: rgb, stroke_width_mm: None }); + fill.into_iter().chain(std::iter::once(PdfPath { + path: path.path.clone(), + color_rgb: path.color_rgb, + stroke_width_mm: Some(path.stroke_width_mm), + })) + }) .collect(); - write_pdf_pages(&[PdfPage { - width_mm: scene.width_mm, - height_mm: scene.height_mm, - view_box: scene.view_box, - paths, - images: scene.images.clone(), - }]) + write_pdf_pages_with_rule( + &[PdfPage { width_mm: scene.width_mm, height_mm: scene.height_mm, view_box: scene.view_box, paths, images: scene.images.clone() }], + craft_pdf::write::backend::paint::FillRule::EvenOdd, + ) } /// Group the neutral paths once so writing does not rescan all paths for every layer. @@ -235,6 +247,11 @@ fn paths_by_layer(scene: &OutputScene) -> Vec> { /// Encode a neutral list of laid-out pages with vector paths as PDF. pub fn write_pdf_pages(pages: &[PdfPage]) -> Result, Error> { + write_pdf_pages_with_rule(pages, craft_pdf::write::backend::paint::FillRule::NonZero) +} + +// Scene fills are explicitly even-odd. Keep the existing standalone PDF page API's nonzero rule. +fn write_pdf_pages_with_rule(pages: &[PdfPage], fill_rule: craft_pdf::write::backend::paint::FillRule) -> Result, Error> { use craft_pdf::write::{Metadata, Writer, backend}; const PT_PER_MM: f64 = 72.0 / 25.4; craft_pdf::write::guard(|| { @@ -352,7 +369,7 @@ pub fn write_pdf_pages(pages: &[PdfPage]) -> Result, Error> { } None => { surface.set_stroke(None); - surface.set_fill(Some(backend::paint::Fill { paint: color.into(), ..Default::default() })); + surface.set_fill(Some(backend::paint::Fill { paint: color.into(), rule: fill_rule, ..Default::default() })); } } surface.draw_path(&path); @@ -513,6 +530,77 @@ fn format_float(value: f64) -> String { value.to_string() } +#[cfg(test)] +mod fill_tests { + use super::*; + + fn scene(fill_rgb: Option<[u8; 3]>) -> OutputScene { + let mut square = BezPath::new(); + square.move_to((10.0, 10.0)); + square.line_to((30.0, 10.0)); + square.line_to((30.0, 30.0)); + square.line_to((10.0, 30.0)); + square.close_path(); + OutputScene { + width_mm: 50.0, + height_mm: 50.0, + view_box: [0.0, 0.0, 50.0, 50.0], + layers: vec![OutputLayer { name: "cut".into(), dxf_name: "CUT".into(), visible: true, dxf_color_index: 1, class: None, data_kind: None }], + paths: vec![OutputPath { + path: square, + layer: 0, + color_rgb: [255, 0, 0], + stroke_width_mm: 0.25, + class: None, + data_kind: None, + close_open_contours: false, + fill_rgb, + }], + images: Vec::new(), + } + } + + #[test] + fn a_filled_path_is_filled_in_svg_and_pdf() { + let svg = write_svg(&scene(Some([0x12, 0x34, 0x56]))).unwrap(); + assert!(svg.contains("fill=\"#123456\""), "{svg}"); + assert!(write_svg(&scene(None)).unwrap().contains("fill=\"none\"")); + let filled = write_pdf(&scene(Some([0x12, 0x34, 0x56]))).unwrap(); + let plain = write_pdf(&scene(None)).unwrap(); + assert!(filled.len() > plain.len(), "a fill is drawn as well as the line"); + } + + #[test] + fn same_direction_nested_contours_preserve_the_hole() { + let mut scene = scene(Some([255, 0, 0])); + let path = &mut scene.paths[0].path; + path.move_to((15.0, 15.0)); + path.line_to((25.0, 15.0)); + path.line_to((25.0, 25.0)); + path.line_to((15.0, 25.0)); + path.close_path(); + assert!(write_svg(&scene).unwrap().contains("fill-rule=\"evenodd\"")); + let sample = |pdf: &[u8], x_mm: f64, y_mm: f64| { + let image = crate::render_pdf_page(pdf, 0, 72.0, crate::Limits::default()).unwrap(); + let (x, y) = ((x_mm / 25.4 * 72.0) as u32, (y_mm / 25.4 * 72.0) as u32); + let i = ((y * image.width + x) * 4) as usize; + [image.rgba[i], image.rgba[i + 1], image.rgba[i + 2]] + }; + let pdf = write_pdf(&scene).unwrap(); + assert_eq!(sample(&pdf, 12.0, 12.0), [255, 0, 0]); + assert_eq!(sample(&pdf, 20.0, 20.0), [255, 255, 255]); + let standalone = write_pdf_pages(&[PdfPage { + width_mm: scene.width_mm, + height_mm: scene.height_mm, + view_box: scene.view_box, + paths: vec![PdfPath { path: scene.paths[0].path.clone(), color_rgb: [255, 0, 0], stroke_width_mm: None }], + images: Vec::new(), + }]) + .unwrap(); + assert_eq!(sample(&standalone, 20.0, 20.0), [255, 0, 0], "standalone PDF API retains nonzero fill"); + } +} + #[cfg(test)] mod image_tests { use super::*; diff --git a/crates/i18n/Cargo.toml b/crates/i18n/Cargo.toml index 4328b8fe75..19867fdf61 100644 --- a/crates/i18n/Cargo.toml +++ b/crates/i18n/Cargo.toml @@ -21,7 +21,7 @@ icu_datetime = { version = "~2.3", default-features = false, features = ["serde" icu_time = { version = "~2.3", default-features = false } icu_provider = { version = "~2.3", default-features = false, features = ["sync"] } icu_provider_adapters = { version = "~2.3", default-features = false } -icu_provider_blob = { version = "~2.3", default-features = false } +icu_provider_blob = { version = "~2.3", default-features = false, features = ["alloc"] } writeable = "0.6" log = "0.4" sys-locale = "0.3" @@ -34,10 +34,17 @@ icu_collator = { version = "~2.3.1", default-features = false, features = ["serd unicode-bidi = "0.3" [target.'cfg(target_arch = "wasm32")'.dependencies] +brotli-decompressor = { version = "6", default-features = false, features = ["std"] } sys-locale = { version = "0.3", features = ["js"] } # The browser's `Date` supplies the local offset. chrono = { workspace = true, features = ["clock", "wasmbind"] } +[build-dependencies] +brotli = { version = "9", default-features = false, features = ["std"] } + +[dev-dependencies] +brotli-decompressor = { version = "6", default-features = false, features = ["std"] } + # The regional format (Region::system); safe registry reads, MIT OR Apache-2.0. [target.'cfg(windows)'.dependencies] windows-registry = "0.6" diff --git a/crates/i18n/README.md b/crates/i18n/README.md index 544f715505..33dba40156 100644 --- a/crates/i18n/README.md +++ b/crates/i18n/README.md @@ -123,11 +123,13 @@ The app keeps its `tl!` macro, its language setting (`"auto"` → `I18N.system_l (`1.234 Dateien`, `١٬٢٣٤ ملفًا`); for names written into documents or files (`Copy 1234`), use `trn_plain`, which writes `0`–`9` without grouping or isolate marks. - **CLDR data:** decimal symbols, digits and plural rules (`data/numbers.postcard`, about 10 KB), - percent patterns (`data/locales.rs`) and date data (`data/dates.postcard`, about 340 KB) cover + percent patterns (`data/locales.rs`) and date data (`data/dates.postcard`, about 430 KB) cover every CLDR locale; `data/generate.sh` rebuilds all three from CLDR 48.2.1. The ICU4X crates are - pinned to one minor version (`~2.3`), the one the data is generated for. The ICU4X code and the - number data add about 90 KB to a stripped release build and 80 KB to wasm; the date data is - extra. + pinned to one minor version (`~2.3`), the one the data is generated for. Native builds embed the + static provider blobs. Browser builds embed lossless Brotli copies and restore each provider + once on first use, preserving every locale and rule. The build writes packed copies only to + `OUT_DIR`; the checked-in source data and its generation commands are unchanged. Tests compare + every decoded byte with the source blobs and load the result as an owned ICU provider. - **Dates:** `DateFormat` (`I18n::dates`, `set_dates`, `reset_dates`, as `I18n::format` is for numbers) writes dates and times for the region's time locale and clock in the `Short`, `Medium`, `Long` and `Full` lengths, month and weekday names (`NameLength`), the first day of the week and @@ -165,4 +167,5 @@ The app keeps its `tl!` macro, its language setting (`"auto"` → `I18N.system_l - **Sorting** (`Collator`, feature `collate`): ICU4X collation for the locales craft-i18n ships, Persian and Hindi, with digits compared by value (`Layer 2` before `Layer 10`) and `-u-co-pinyin` / `-u-co-stroke` for Chinese. The data (754 KB) is regenerated by `data/generate-collation.sh`; - the feature adds about 1 MB to a release binary or wasm module (320 KB gzipped). + native builds embed it directly, while browser builds use the same lossless packing as the + number and date providers. diff --git a/crates/i18n/build.rs b/crates/i18n/build.rs new file mode 100644 index 0000000000..f2be878371 --- /dev/null +++ b/crates/i18n/build.rs @@ -0,0 +1,39 @@ +//! Pack the existing locale data losslessly for browser builds; native providers stay static. + +use std::io::Write as _; +use std::path::PathBuf; + +fn main() { + if let Err(error) = pack() { + println!("cargo::error=packing locale data: {error}"); + } +} + +fn pack() -> Result<(), Box> { + let out = PathBuf::from(std::env::var_os("OUT_DIR").ok_or("OUT_DIR is missing")?); + let mut declarations = String::new(); + for name in ["numbers", "dates", "collation"] { + let input = format!("data/{name}.postcard"); + println!("cargo::rerun-if-changed={input}"); + let bytes = std::fs::read(&input)?; + if bytes.is_empty() || bytes.len() > 2 * 1024 * 1024 { + return Err(format!("{input} is outside the browser locale-data size budget").into()); + } + let mut compressed = Vec::new(); + { + let mut encoder = brotli::CompressorWriter::new(&mut compressed, 4096, 11, 22); + encoder.write_all(&bytes)?; + } + std::fs::write(out.join(format!("{name}.br")), compressed)?; + if name == "collation" { + declarations.push_str("#[cfg(any(test, feature = \"collate\"))]\n"); + } + declarations.push_str(&format!( + "const {}: (&[u8], usize) = (include_bytes!(concat!(env!(\"OUT_DIR\"), \"/{name}.br\")), {});\n", + name.to_ascii_uppercase(), + bytes.len() + )); + } + std::fs::write(out.join("locale_blobs.rs"), declarations)?; + Ok(()) +} diff --git a/crates/i18n/src/blob.rs b/crates/i18n/src/blob.rs new file mode 100644 index 0000000000..6d644c6d8b --- /dev/null +++ b/crates/i18n/src/blob.rs @@ -0,0 +1,82 @@ +//! Preserve every locale byte while avoiding raw provider blobs in browser binaries. + +use icu_provider::DataError; +use icu_provider_blob::BlobDataProvider; + +#[cfg(any(test, target_arch = "wasm32"))] +include!(concat!(env!("OUT_DIR"), "/locale_blobs.rs")); + +pub(crate) fn numbers() -> Result { + #[cfg(target_arch = "wasm32")] + { + owned(NUMBERS) + } + #[cfg(not(target_arch = "wasm32"))] + BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/numbers.postcard")) +} + +pub(crate) fn dates() -> Result { + #[cfg(target_arch = "wasm32")] + { + owned(DATES) + } + #[cfg(not(target_arch = "wasm32"))] + BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/dates.postcard")) +} + +#[cfg(feature = "collate")] +pub(crate) fn collation() -> Result { + #[cfg(target_arch = "wasm32")] + { + owned(COLLATION) + } + #[cfg(not(target_arch = "wasm32"))] + BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/collation.postcard")) +} + +#[cfg(target_arch = "wasm32")] +fn owned((bytes, len): (&[u8], usize)) -> Result { + let bytes = unpack(bytes, len).ok_or_else(|| DataError::custom("Invalid compressed locale data"))?; + BlobDataProvider::try_new_from_blob(bytes.into_boxed_slice()) +} + +#[cfg(any(test, target_arch = "wasm32"))] +fn unpack(bytes: &[u8], len: usize) -> Option> { + use std::io::Read as _; + // Generated blobs are currently below 1 MiB. Bound allocation and decoding even for corrupt metadata. + if len == 0 || len > 2 * 1024 * 1024 { + return None; + } + let mut decoded = Vec::new(); + decoded.try_reserve_exact(len).ok()?; + brotli_decompressor::Decompressor::new(bytes, 4096).take(len as u64 + 1).read_to_end(&mut decoded).ok()?; + (decoded.len() == len).then_some(decoded) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn packed_catalogs_preserve_every_locale_byte_and_load_as_owned_providers() { + for (packed, original) in [ + (NUMBERS, include_bytes!("../data/numbers.postcard").as_slice()), + (DATES, include_bytes!("../data/dates.postcard").as_slice()), + (COLLATION, include_bytes!("../data/collation.postcard").as_slice()), + ] { + let decoded = unpack(packed.0, packed.1).unwrap(); + assert_eq!(decoded, original); + assert!(packed.0.len() < original.len()); + BlobDataProvider::try_new_from_blob(decoded.into_boxed_slice()).unwrap(); + } + } + + #[test] + fn corrupt_or_wrong_sized_catalogs_are_unavailable() { + assert!(unpack(b"not compressed locale data", NUMBERS.1).is_none()); + assert!(unpack(&NUMBERS.0[..NUMBERS.0.len() / 2], NUMBERS.1).is_none()); + for len in [0, NUMBERS.1 - 1, NUMBERS.1 + 1, usize::MAX] { + assert!(unpack(NUMBERS.0, len).is_none()); + } + } +} diff --git a/crates/i18n/src/collate.rs b/crates/i18n/src/collate.rs index 76d7893565..9c2750371f 100644 --- a/crates/i18n/src/collate.rs +++ b/crates/i18n/src/collate.rs @@ -34,9 +34,9 @@ impl Collator { let mut prefs: CollatorPreferences = Locale::try_from_str(&bcp47(locale)).unwrap_or(Locale::UNKNOWN).into(); prefs.numeric_ordering = Some(CollationNumericOrdering::True); let options = CollatorOptions::default(); - let collator = Data::new().ok().and_then(|data| { - icu_collator::Collator::try_new_unstable(&data, prefs, options) - .or_else(|_| icu_collator::Collator::try_new_unstable(&data, CollatorPreferences::default(), options)) + let collator = Data::shared().as_ref().ok().and_then(|data| { + icu_collator::Collator::try_new_unstable(data, prefs, options) + .or_else(|_| icu_collator::Collator::try_new_unstable(data, CollatorPreferences::default(), options)) .ok() }); Collator(collator) @@ -83,8 +83,13 @@ fn bcp47(locale: &str) -> String { struct Data(LocaleFallbackProvider); impl Data { + fn shared() -> &'static Result { + static DATA: std::sync::OnceLock> = std::sync::OnceLock::new(); + DATA.get_or_init(Self::new) + } + fn new() -> Result { - let blob = BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/collation.postcard"))?; + let blob = crate::blob::collation()?; Ok(Data(LocaleFallbackProvider::new(blob, LocaleFallbacker::new().static_to_owned()))) } } diff --git a/crates/i18n/src/lib.rs b/crates/i18n/src/lib.rs index ea51b6d728..363083bbb7 100644 --- a/crates/i18n/src/lib.rs +++ b/crates/i18n/src/lib.rs @@ -38,6 +38,8 @@ pub use bidi::{file_name, isolate, ltr, path, strip_isolates}; pub use message::MessageMatch; use message::{KEPT_VALUE, MAX_MESSAGE_LEN, MESSAGE_DEPTH, Template, insert_template, sort_templates}; +mod blob; + /// The CLDR number, plural and date data for every CLDR locale, from `data/generate.sh`. mod data { use std::sync::OnceLock; @@ -53,7 +55,7 @@ mod data { static PROVIDER: OnceLock>> = OnceLock::new(); PROVIDER .get_or_init(|| { - let blob = BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/numbers.postcard")).ok()?; + let blob = crate::blob::numbers().ok()?; Some(LocaleFallbackProvider::new(blob, LocaleFallbacker::new().static_to_owned())) }) .as_ref() @@ -65,7 +67,7 @@ mod data { static PROVIDER: OnceLock>> = OnceLock::new(); PROVIDER .get_or_init(|| { - let blob = BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/dates.postcard")).ok()?; + let blob = crate::blob::dates().ok()?; Some(LocaleFallbackProvider::new(blob, LocaleFallbacker::new().static_to_owned())) }) .as_ref() diff --git a/crates/image-codecs/Cargo.toml b/crates/image-codecs/Cargo.toml index 8cb1b3b07e..5b9317cfaf 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 } @@ -85,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 6905563be8..76ce8a6c64 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,13 +89,16 @@ 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. +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..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. @@ -257,6 +274,9 @@ 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") { + 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) { return Err(CodecError::malformed(format, "JPEG input exceeds the allocation budget")); @@ -322,8 +342,27 @@ 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:?}"); } } + + #[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/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..d9178a7d97 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. @@ -356,12 +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, - 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:?}"); } 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..c5730d583c --- /dev/null +++ b/crates/image-codecs/tests/it/tiff_feature.rs @@ -0,0 +1,31 @@ +//! 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)); + 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(), + 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:?}"), + } + } +} diff --git a/crates/silhouette-studio/src/lib.rs b/crates/silhouette-studio/src/lib.rs index 7216d5bf42..5237ce172e 100644 --- a/crates/silhouette-studio/src/lib.rs +++ b/crates/silhouette-studio/src/lib.rs @@ -1,8 +1,9 @@ //! 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 +//! 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. //! @@ -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; @@ -67,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. @@ -79,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, } @@ -120,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. @@ -142,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 @@ -360,7 +470,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]); } } @@ -443,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 { @@ -543,7 +686,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()); + } +} diff --git a/crates/stencilcraft-document/src/canvas.rs b/crates/stencilcraft-document/src/canvas.rs index 615ff2da82..c4e5880de8 100644 --- a/crates/stencilcraft-document/src/canvas.rs +++ b/crates/stencilcraft-document/src/canvas.rs @@ -12,6 +12,10 @@ use crate::{Board, DocError, Document, Shape}; pub const MAX_PAGES: usize = 100; /// Most ruler guides a document may hold. pub const MAX_GUIDES: usize = 1000; +/// Widest line weight a shape may have, millimetres. +pub const MAX_STROKE_MM: f64 = 100.0; +/// Widest text wrap width, millimetres (a 10 m roll). +pub const MAX_WRAP_MM: f64 = 10_000.0; /// Most groups a document may hold. pub const MAX_GROUPS: usize = 100_000; /// Deepest group nesting accepted. @@ -162,11 +166,14 @@ pub struct Grid { pub subdivisions: u32, #[serde(default)] pub visible: bool, + /// Isometric lines (at 30° and 150°, plus verticals) instead of a square grid. + #[serde(default, skip_serializing_if = "crate::is_false")] + pub isometric: bool, } impl Default for Grid { fn default() -> Self { - Self { spacing_mm: 10.0, subdivisions: 1, visible: false } + Self { spacing_mm: 10.0, subdivisions: 1, visible: false, isometric: false } } } @@ -291,6 +298,30 @@ fn check_setup(setup: &PageSetup, what: &str) -> Result<(), DocError> { check_color(setup.color.as_deref(), what) } +/// How deep a Combine's or Flatten's stored members may nest. +const MAX_MEMBER_DEPTH: usize = 64; + +/// A shape's line width and text wrap width are in range, and so are those of the shapes a +/// Combine or Flatten keeps inside it. +fn check_widths(shape: &crate::Shape, depth: usize) -> Result<(), DocError> { + let bad = |message: String| Err(DocError::Model(message)); + if depth > MAX_MEMBER_DEPTH { + return bad(format!("shape {}: grouped members nest deeper than {MAX_MEMBER_DEPTH}", shape.id)); + } + if shape.production.stroke_width_mm.is_some_and(|w| !(w.is_finite() && (0.0..=MAX_STROKE_MM).contains(&w))) { + return bad(format!("shape {}: line width must be 0-{MAX_STROKE_MM} mm", shape.id)); + } + if shape.text.as_ref().and_then(|t| t.wrap_width_mm).is_some_and(|w| !(w.is_finite() && w > 0.0 && w <= MAX_WRAP_MM)) { + return bad(format!("shape {}: text wrap width must be above 0 and at most {MAX_WRAP_MM} mm", shape.id)); + } + if let Some(group) = &shape.production.group { + for member in &group.members { + check_widths(member, depth + 1)?; + } + } + Ok(()) +} + impl Document { /// Pages, guides, grid, snapping, colours, metadata and groups: finite, within caps, /// and groups form a forest (unknown shape members are allowed: they are pruned). @@ -319,6 +350,9 @@ impl Document { if !(0.0..=1000.0).contains(&self.snap.tolerance_mm) { return bad("snap: tolerance must be 0-1000 mm".to_string()); } + for shape in &self.shapes { + check_widths(shape, 0)?; + } for layer in &self.layers { check_name(&layer.name, "layer name")?; } diff --git a/crates/stencilcraft-document/src/lib.rs b/crates/stencilcraft-document/src/lib.rs index d47f8b620d..c8064c4afb 100644 --- a/crates/stencilcraft-document/src/lib.rs +++ b/crates/stencilcraft-document/src/lib.rs @@ -16,7 +16,8 @@ use serde::{Deserialize, Serialize}; pub mod production; pub use metadata::{LibraryIndex, LibraryTrashEntry, MAX_RECENT_FILES, RecentFiles}; pub use production::{ - CombineOp, GroupKind, Operation, OperationKind, OperationSettings, Process, SendAssign, ShapeProduction, SourceGroup, Strategy, Tab, + CombineOp, FillGradient, FillPattern, GroupKind, MAX_PATTERN_DATA, Operation, OperationKind, OperationSettings, PATTERN_TILE_MM, Process, + SendAssign, ShapeProduction, SourceGroup, Strategy, Tab, }; /// Native format identity and supported version, defined by the shared wire-format crate. @@ -132,7 +133,7 @@ pub enum Tip { Wide, } -fn is_false(value: &bool) -> bool { +pub(crate) fn is_false(value: &bool) -> bool { !*value } @@ -173,6 +174,13 @@ pub struct TextSpec { /// the shape since its text was laid out. #[serde(default = "identity", skip_serializing_if = "is_identity")] pub transform: [f64; 6], + /// Area text: lines wrap at this width in millimetres (Silhouette Studio's wrap bar). + /// `None` is point text, which breaks only at newlines. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wrap_width_mm: Option, + /// An underline under every line, part of the cut outline. + #[serde(default, skip_serializing_if = "is_false")] + pub underline: bool, } /// A font by family and style, optionally from a font file. @@ -289,6 +297,10 @@ pub struct RasterImage { pub width_px: u32, pub height_px: u32, pub png_base64: std::sync::Arc, + /// The pixels as placed, before any erase or clean-up, so a restore brush can bring them + /// back. Absent when the image was never edited (and in older files). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub original_png_base64: Option>, } impl RasterImage { @@ -302,6 +314,9 @@ impl RasterImage { if self.png_base64.len() > MAX_IMAGE_DATA { return Err(DocError::Model(format!("image {}: pixel data exceeds the 128 MiB limit", self.id))); } + if self.original_png_base64.as_ref().is_some_and(|o| o.len() > MAX_IMAGE_DATA) { + return Err(DocError::Model(format!("image {}: original pixel data exceeds the 128 MiB limit", self.id))); + } Ok(()) } } @@ -548,6 +563,18 @@ impl Document { return Err(DocError::Model(format!("a document holds at most {MAX_IMAGES} images"))); } self.images.iter().try_for_each(RasterImage::validate)?; + let mut fills = self.shapes.iter().collect::>(); + while let Some(shape) = fills.pop() { + if let Some(pattern) = &shape.production.fill_pattern { + pattern.validate()?; + } + if let Some(gradient) = &shape.production.fill_gradient { + gradient.validate()?; + } + if let Some(group) = &shape.production.group { + fills.extend(&group.members); + } + } let mut ids = std::collections::BTreeSet::new(); for shape in &self.shapes { if !ids.insert(shape.id) { @@ -690,6 +717,50 @@ pub fn load_from(path: &str) -> Result { #[cfg(test)] mod tests { use super::*; + + #[test] + fn pattern_fills_round_trip_and_bad_ones_are_refused() { + let mut doc = Document::default(); + let mut square = BezPath::new(); + square.move_to((0.0, 0.0)); + square.line_to((10.0, 0.0)); + square.line_to((10.0, 10.0)); + square.close_path(); + let id = doc.push_shape(0, square).unwrap().id; + let pattern = FillPattern { png_base64: "iVBORw0KGgo=".into(), tile_mm: 25.0, angle_deg: 15.0 }; + doc.get_shape_mut(id).unwrap().production.fill_pattern = Some(Box::new(pattern.clone())); + let back = Document::load_json(&doc.save_json().unwrap()).unwrap(); + assert_eq!(back.get_shape(id).unwrap().production.fill_pattern.as_deref(), Some(&pattern)); + for bad in [ + FillPattern { tile_mm: f64::NAN, ..pattern.clone() }, + FillPattern { tile_mm: 0.0, ..pattern.clone() }, + FillPattern { angle_deg: f64::INFINITY, ..pattern.clone() }, + FillPattern { png_base64: "".into(), ..pattern.clone() }, + ] { + doc.get_shape_mut(id).unwrap().production.fill_pattern = Some(Box::new(bad)); + assert!(doc.validate().is_err()); + } + doc.get_shape_mut(id).unwrap().production.fill_pattern = None; + let gradient = FillGradient { from: "#ff0000".into(), to: "#0000ff".into(), angle_deg: 90.0 }; + doc.get_shape_mut(id).unwrap().production.fill_gradient = Some(Box::new(gradient.clone())); + let back = Document::load_json(&doc.save_json().unwrap()).unwrap(); + assert_eq!(back.get_shape(id).unwrap().production.fill_gradient.as_deref(), Some(&gradient)); + let mut nested = doc.clone(); + let mut member = nested.get_shape(id).unwrap().clone(); + member.production.fill_pattern = Some(Box::new(pattern.clone())); + let path = member.path.clone(); + nested.get_shape_mut(id).unwrap().production.group = + Some(Box::new(SourceGroup { kind: GroupKind::Combine(CombineOp::Unite), members: vec![member], path })); + assert_eq!(Document::load_json(&nested.save_json().unwrap()).unwrap(), nested); + for bad in [ + FillGradient { from: "red".into(), ..gradient.clone() }, + FillGradient { to: "#12345g".into(), ..gradient.clone() }, + FillGradient { angle_deg: f64::NAN, ..gradient.clone() }, + ] { + doc.get_shape_mut(id).unwrap().production.fill_gradient = Some(Box::new(bad)); + assert!(doc.validate().is_err()); + } + } use crate::geom::Point; fn rect_path(x: f64, y: f64, w: f64, h: f64) -> BezPath { @@ -761,6 +832,8 @@ mod tests { flow: TextFlow::Curve { diameter_mm: 50.0 }, letters: vec![LetterOffset { index: 1, dx_mm: 1.0, ..LetterOffset::default() }], transform: IDENTITY_TRANSFORM, + wrap_width_mm: Some(80.0), + underline: true, })); let back = Document::load_json(&doc.save_json().unwrap()).unwrap(); assert_eq!(doc, back); @@ -804,6 +877,45 @@ mod tests { )); } + #[test] + fn parity_fields_round_trip_stay_out_of_plain_files_and_are_checked() { + let mut doc = sample(); + let plain = doc.save_json().unwrap(); + for key in ["stroke_width_mm", "isometric", "wrap_width_mm", "underline", "original_png_base64"] { + assert!(!plain.contains(key), "a plain document saves as before: {key}"); + } + doc.shapes[0].production.stroke_width_mm = Some(0.5); + doc.grid.isometric = true; + doc.push_image(RasterImage { + id: 0, + name: "photo".to_string(), + x_mm: 0.0, + y_mm: 0.0, + width_mm: 10.0, + height_mm: 5.0, + width_px: 2, + height_px: 1, + png_base64: "AAAA".into(), + original_png_base64: Some("BBBB".into()), + }) + .unwrap(); + let back = Document::load_json(&doc.save_json().unwrap()).unwrap(); + assert_eq!(back, doc); + // Out-of-range values are refused, not saved. + let mut bad = doc.clone(); + bad.shapes[0].production.stroke_width_mm = Some(f64::NAN); + assert!(bad.validate().is_err()); + bad.shapes[0].production.stroke_width_mm = Some(-1.0); + assert!(bad.validate().is_err()); + // A bad width inside a Combine's kept members is caught too. + let mut nested = doc.clone(); + let mut member = nested.shapes[0].clone(); + member.production.stroke_width_mm = Some(-1.0); + nested.shapes[0].production.group = + Some(Box::new(SourceGroup { kind: GroupKind::Combine(CombineOp::Unite), members: vec![member], path: nested.shapes[0].path.clone() })); + assert!(nested.validate().is_err()); + } + #[test] fn images_round_trip_and_share_the_id_counter() { let mut doc = canvas_sample(); @@ -818,6 +930,7 @@ mod tests { width_px: 2, height_px: 1, png_base64: "AAAA".into(), + original_png_base64: None, }) .unwrap(); assert_eq!(id, 3); diff --git a/crates/stencilcraft-document/src/production.rs b/crates/stencilcraft-document/src/production.rs index 5f7df27811..69abeb489e 100644 --- a/crates/stencilcraft-document/src/production.rs +++ b/crates/stencilcraft-document/src/production.rs @@ -369,6 +369,75 @@ pub struct ShapeProduction { pub hidden_contours: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub group: Option>, + /// Line weight in millimetres (Silhouette Studio's line width): how thick the line draws + /// and prints, and the width Outline Stroke outlines at. `None` is a hairline. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stroke_width_mm: Option, + /// A picture repeated inside the shape instead of a plain fill (Silhouette's pattern + /// fill). Printed and shown; the cut follows the path as always. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fill_pattern: Option>, + /// A two-colour linear gradient instead of a plain fill (Silhouette's gradient fill). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fill_gradient: Option>, +} + +/// A gradient fill: `from` blends into `to` across the shape along `angle_deg` (0 runs left +/// to right, 90 bottom to top). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FillGradient { + /// Canonical `#rrggbb` colours at the start and end. + pub from: String, + pub to: String, + #[serde(default)] + pub angle_deg: f64, +} + +impl FillGradient { + /// Both colours are `#rrggbb` and the angle is finite. + pub fn validate(&self) -> Result<(), crate::DocError> { + let hex = |c: &str| c.len() == 7 && c.starts_with('#') && c.get(1..).is_some_and(|d| d.bytes().all(|b| b.is_ascii_hexdigit())); + if !hex(&self.from) || !hex(&self.to) { + return Err(crate::DocError::Model("gradient fill: colours must be #rrggbb".to_string())); + } + if !self.angle_deg.is_finite() { + return Err(crate::DocError::Model("gradient fill: angle must be a number".to_string())); + } + Ok(()) + } +} + +/// A pattern fill: a picture tiled across the shape. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FillPattern { + /// The tile's pixels as base64 PNG, like placed images. + pub png_base64: std::sync::Arc, + /// Width of one tile in millimetres (its height follows the picture's aspect). + pub tile_mm: f64, + /// Rotation of the tiling in degrees. + #[serde(default)] + pub angle_deg: f64, +} + +/// The smallest and largest pattern tile, in millimetres. +pub const PATTERN_TILE_MM: std::ops::RangeInclusive = 0.5..=2000.0; +/// The most pixel data one pattern holds (base64 bytes). +pub const MAX_PATTERN_DATA: usize = 16 * 1024 * 1024; + +impl FillPattern { + /// Tile size and angle are finite and in range, and the data within [`MAX_PATTERN_DATA`]. + pub fn validate(&self) -> Result<(), crate::DocError> { + if !(self.tile_mm.is_finite() && PATTERN_TILE_MM.contains(&self.tile_mm)) { + return Err(crate::DocError::Model("pattern fill: tile size must be 0.5 to 2000 mm".to_string())); + } + if !self.angle_deg.is_finite() { + return Err(crate::DocError::Model("pattern fill: angle must be a number".to_string())); + } + if self.png_base64.is_empty() || self.png_base64.len() > MAX_PATTERN_DATA { + return Err(crate::DocError::Model("pattern fill: pixel data must be 1 byte to 16 MiB".to_string())); + } + Ok(()) + } } impl ShapeProduction {