Merge main into fix/raster3d-opacity-below-one

This commit is contained in:
dotCooCoo committed 2026-11-29 17:29:30 -08:00
commit 8063b87352
27 files changed
+1788 -41

No files matched your search

+1
View File
@@ -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"]
+1
View File
@@ -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();
+98 -10
View File
@@ -36,6 +36,9 @@ pub struct OutputPath {
pub data_kind: Option<String>,
/// 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<String, Error> {
.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<Vec<u8>, 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<Vec<&OutputPath>> {
/// Encode a neutral list of laid-out pages with vector paths as PDF.
pub fn write_pdf_pages(pages: &[PdfPage]) -> Result<Vec<u8>, 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<Vec<u8>, 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<Vec<u8>, 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::*;
+4 -3
View File
@@ -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 }
+6 -2
View File
@@ -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 = "<commit>", default-features = false, features = ["webp"] }
+40 -1
View File
@@ -248,6 +248,23 @@ fn read_le24(bytes: &[u8], at: usize) -> Option<u32> {
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::<Entry>() 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::<tiff::encoder::colortype::RGB8>(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());
}
}
+3
View File
@@ -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<Vec<u8>, 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))
}
@@ -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<usize>, limits: &Limits) -> Result<Image, CodecError> {
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<usize>, limits: &Limits) -> Result<Self, CodecError> {
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<Prep
})
}
#[cfg(test)]
#[cfg(all(test, feature = "tiff"))]
mod tests {
use super::*;
use crate::{EncodeOptions, ExtraSample, Format};
@@ -539,6 +539,9 @@ fn check_extra_planes(img: &Image) -> Result<(), CodecError> {
}
pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Vec<u8>, 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.
+1
View File
@@ -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,
+3 -2
View File
@@ -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::<tiff::encoder::colortype::RGB8>(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));
@@ -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<u8> {
use tiff::encoder::{TiffEncoder, colortype};
use tiff::tags::Tag;
@@ -272,6 +273,7 @@ fn tiff(ifds: &[(u32, SampleType)]) -> Vec<u8> {
}
#[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);
@@ -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,
+1
View File
@@ -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] {
+1
View File
@@ -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();
+11
View File
@@ -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;
@@ -264,6 +264,7 @@ fn tiny_tiff(extra: &[(u16, u16, u32, u32)]) -> Vec<u8> {
}
#[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));
+4 -2
View File
@@ -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();
+10 -3
View File
@@ -91,6 +91,7 @@ fn png_with_exif(png: &[u8], exif: &[u8]) -> Vec<u8> {
out
}
#[cfg(feature = "tiff")]
fn tiff_with_orientation(data: &[u8], w: u32, h: u32, o: u16) -> Vec<u8> {
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,
+2
View File
@@ -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();
+4 -6
View File
@@ -160,6 +160,7 @@ fn hdr_values_survive_float_formats() {
let vals: Vec<f32> = (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:?}");
}
@@ -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:?}"),
}
}
}
+151 -8
View File
@@ -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<usize>,
}
/// 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<Shape>,
/// One entry per group, outermost first: the group holding it, if any.
pub group_parents: Vec<Option<usize>>,
pub warnings: Vec<String>,
}
@@ -120,6 +126,7 @@ pub fn import(bytes: &[u8]) -> Result<Imported, Error> {
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<Imported, Error> {
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<Vec<(usize, usize)>> {
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<Option<usize>>,
members: Vec<Option<usize>>,
}
/// 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<GroupMemberships> {
let mut parents = Vec::with_capacity(spans.len());
let mut stack: Vec<usize> = 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<f32> {
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<u8> {
@@ -543,7 +686,7 @@ mod tests {
/// then the cut-action record (`01 L`, name "cut").
fn style(rgb: [u8; 3]) -> Vec<u8> {
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]);
File diff suppressed because it is too large. Load diff
+35 -1
View File
@@ -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")?;
}
+115 -2
View File
@@ -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<f64>,
/// 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<str>,
/// 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<std::sync::Arc<str>>,
}
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::<Vec<_>>();
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<Document, DocError> {
#[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);
@@ -369,6 +369,75 @@ pub struct ShapeProduction {
pub hidden_contours: Vec<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub group: Option<Box<SourceGroup>>,
/// 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<f64>,
/// 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<Box<FillPattern>>,
/// 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<Box<FillGradient>>,
}
/// 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<str>,
/// 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<f64> = 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 {