mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-30 18:27:00 +01:00
Merge branch 'main' into fix/screen-objc2-core-graphics
This commit is contained in:
27 files changed
+1651
-56
No files matched your search
@@ -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"]
|
||||
|
||||
|
||||
@@ -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 }
|
||||
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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] {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
//! 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, nested groups, text characters,
|
||||
//! font and size, and page dimensions. Coordinates are
|
||||
//! millimetres from the page's top-left corner, y down, as the file stores them. Layers
|
||||
//! and cut settings are not read.
|
||||
//!
|
||||
@@ -16,7 +18,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 +71,26 @@ 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>,
|
||||
/// When the outline is a letter of a text object: an index into [`Imported::texts`].
|
||||
pub text: Option<usize>,
|
||||
}
|
||||
|
||||
/// A text object as typed: its characters, font and size, and where it starts. Its letters
|
||||
/// are also read as outlines (shapes whose [`Shape::text`] points here).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Text {
|
||||
pub text: String,
|
||||
/// The font family's name, when its record was found.
|
||||
pub font: Option<String>,
|
||||
/// The font size in millimetres (25.4 for 72 pt).
|
||||
pub size_mm: f64,
|
||||
/// The text's origin in page millimetres.
|
||||
pub x_mm: f64,
|
||||
pub y_mm: f64,
|
||||
}
|
||||
|
||||
/// A document's shapes in file order, plus notes about what was skipped.
|
||||
@@ -79,6 +100,10 @@ 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>>,
|
||||
/// Text objects in file order.
|
||||
pub texts: Vec<Text>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
@@ -120,6 +145,8 @@ 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 text_starts = Vec::new();
|
||||
let mut points_total = 0usize;
|
||||
let mut cursor = root.start;
|
||||
// An object's style record comes before its outline: search from the last outline.
|
||||
@@ -142,13 +169,218 @@ 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,
|
||||
text: None,
|
||||
});
|
||||
starts.push((at, path.end));
|
||||
text_starts.push((style_from, at));
|
||||
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()
|
||||
}
|
||||
};
|
||||
let records = glyph_records(body, &root)?;
|
||||
let (texts, owners) = build_texts(body, &records);
|
||||
for (shape, &(from, at)) in shapes.iter_mut().zip(&text_starts) {
|
||||
// The letter's record comes just before its outline.
|
||||
shape.text =
|
||||
records.partition_point(|r| r.at < at).checked_sub(1).filter(|&i| records[i].at >= from && records[i].code != 0).and_then(|i| owners[i]);
|
||||
}
|
||||
Ok(Imported { version, page_mm: page_size(body, &root), shapes, group_parents, texts, warnings })
|
||||
}
|
||||
|
||||
/// The most glyph records read from one document.
|
||||
const MAX_GLYPHS: usize = 1_000_000;
|
||||
|
||||
/// One record of a text object: a u32 code (0 for the text object itself, else a letter's
|
||||
/// Unicode scalar), then a 2 × 3 transform as six f32 (size, 0, x, 0, size, y), after the
|
||||
/// marker bytes `01 00 00 00 01` and 16 zero bytes. Found by saving "Hello", "Hellp" and "A B" in
|
||||
/// Silhouette Studio 5.0.556 and comparing the bytes; a space has a record but no outline.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
struct GlyphRecord {
|
||||
at: usize,
|
||||
code: u32,
|
||||
size_mm: f32,
|
||||
x_mm: f32,
|
||||
y_mm: f32,
|
||||
}
|
||||
|
||||
fn glyph_records(d: &[u8], root: &Block) -> Result<Vec<GlyphRecord>, Error> {
|
||||
const LEAD: [u8; 21] = [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
|
||||
let mut out = Vec::new();
|
||||
let end = root.end.min(d.len());
|
||||
let mut at = root.start + LEAD.len();
|
||||
while at + 28 <= end {
|
||||
if d.get(at - LEAD.len()..at) == Some(LEAD.as_slice())
|
||||
&& let (Some(code), Some(size), Some(zero), Some(x), Some(zero2), Some(size2), Some(y)) =
|
||||
(u32_at(d, at), f32_at(d, at + 4), f32_at(d, at + 8), f32_at(d, at + 12), f32_at(d, at + 16), f32_at(d, at + 20), f32_at(d, at + 24))
|
||||
{
|
||||
let limit = MAX_COORD_MM;
|
||||
let plausible = (0.01..=1000.0).contains(&size)
|
||||
&& size2 == size
|
||||
&& zero == 0.0
|
||||
&& zero2 == 0.0
|
||||
&& x.is_finite()
|
||||
&& y.is_finite()
|
||||
&& x.abs() <= limit
|
||||
&& y.abs() <= limit
|
||||
&& (code == 0 || char::from_u32(code).is_some_and(|c| !c.is_control() || matches!(c, '\n' | '\r' | '\t')));
|
||||
if plausible {
|
||||
if out.len() == MAX_GLYPHS {
|
||||
return Err(Error::Malformed("more than the supported number of glyph records".to_string()));
|
||||
}
|
||||
out.push(GlyphRecord { at, code, size_mm: size, x_mm: x, y_mm: y });
|
||||
at += 28;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Text objects from their records: each object's record (code 0) starts one, its letters
|
||||
/// follow. Returns the texts and, per record, the text it belongs to.
|
||||
fn build_texts(d: &[u8], records: &[GlyphRecord]) -> (Vec<Text>, Vec<Option<usize>>) {
|
||||
let mut texts: Vec<Text> = Vec::new();
|
||||
let mut owners = Vec::with_capacity(records.len());
|
||||
for r in records {
|
||||
if r.code == 0 {
|
||||
texts.push(Text {
|
||||
text: String::new(),
|
||||
font: font_name_before(d, r.at),
|
||||
size_mm: f64::from(r.size_mm),
|
||||
x_mm: f64::from(r.x_mm),
|
||||
y_mm: f64::from(r.y_mm),
|
||||
});
|
||||
owners.push(texts.len().checked_sub(1));
|
||||
continue;
|
||||
}
|
||||
let owner = texts.len().checked_sub(1);
|
||||
if let (Some(i), Some(c)) = (owner, char::from_u32(r.code))
|
||||
&& let Some(text) = texts.get_mut(i)
|
||||
{
|
||||
text.text.push(c);
|
||||
}
|
||||
owners.push(owner);
|
||||
}
|
||||
(texts, owners)
|
||||
}
|
||||
|
||||
/// The nearest length-prefixed name (1–64 printable bytes) ending within 160 bytes before
|
||||
/// `at`: a text object's font family ("Arial"), stored just ahead of its record.
|
||||
fn font_name_before(d: &[u8], at: usize) -> Option<String> {
|
||||
let from = at.saturating_sub(160);
|
||||
(from..at.saturating_sub(5)).rev().find_map(|p| {
|
||||
let n = usize::try_from(u32_at(d, p)?).ok()?;
|
||||
if !(1..=64).contains(&n) {
|
||||
return None;
|
||||
}
|
||||
let name = d.get(p + 4..p + 4 + n)?;
|
||||
(p + 4 + n <= at && name.iter().all(|b| (0x20..0x7f).contains(b)) && name.iter().any(u8::is_ascii_alphabetic))
|
||||
.then(|| String::from_utf8_lossy(name).into_owned())
|
||||
})
|
||||
}
|
||||
|
||||
/// The most groups read from one document.
|
||||
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 +592,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 +676,74 @@ 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)]);
|
||||
}
|
||||
|
||||
fn glyph(code: u32, size: f32, x: f32, y: f32) -> Vec<u8> {
|
||||
let mut out = vec![1, 0, 0, 0, 1];
|
||||
out.extend_from_slice(&[0; 16]);
|
||||
out.extend_from_slice(&code.to_le_bytes());
|
||||
for v in [size, 0.0, x, 0.0, size, y] {
|
||||
out.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_objects_are_read_from_their_letter_records() {
|
||||
let mut payload = 5u32.to_le_bytes().to_vec();
|
||||
payload.extend_from_slice(b"Arial");
|
||||
payload.extend_from_slice(&[0; 8]);
|
||||
payload.extend(glyph(0, 25.4, 67.9, 91.5));
|
||||
for (c, x) in [('A', 67.9), (' ', 83.5), ('B', 90.5)] {
|
||||
payload.extend(glyph(c as u32, 25.4, x, 91.5));
|
||||
}
|
||||
// A record whose two sizes differ is not a letter.
|
||||
let mut bad = glyph('C' as u32, 25.4, 1.0, 1.0);
|
||||
bad[41..45].copy_from_slice(&3.0f32.to_le_bytes());
|
||||
payload.extend(bad);
|
||||
let mut d = b"silhouette04;".to_vec();
|
||||
d.extend(block(&payload));
|
||||
let root = super::block(&d, MAGIC_LEN).unwrap();
|
||||
let records = glyph_records(&d, &root).unwrap();
|
||||
assert_eq!(records.len(), 4);
|
||||
let (texts, owners) = build_texts(&d, &records);
|
||||
assert_eq!(texts.len(), 1);
|
||||
assert_eq!(texts[0].text, "A B");
|
||||
assert_eq!(texts[0].font.as_deref(), Some("Arial"));
|
||||
assert!((texts[0].size_mm - 25.4).abs() < 1e-4 && (texts[0].x_mm - 67.9).abs() < 1e-4);
|
||||
assert_eq!(owners, [Some(0); 4]);
|
||||
}
|
||||
|
||||
/// The tail of a style record as `.studio3` files store it: the cap and join names, then
|
||||
/// the fill flag and, with a fill, R, G, B, A as f32.
|
||||
fn style_tail(fill: Option<[f32; 4]>) -> Vec<u8> {
|
||||
@@ -543,7 +844,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
@@ -18,16 +18,7 @@ pub fn place_label(ui: &Ui, id: Id, size: ControlSize, column: &LabelColumn, flo
|
||||
/// Stores the distance from the top of the control of `size` of the row `id` to its first baseline, for the next
|
||||
/// pass's `place_label`, and for the first appearance of later rows with a control of `size`.
|
||||
pub fn record_control_baseline(ui: &Ui, id: Id, size: ControlSize, baseline: f32) {
|
||||
record_baseline(ui.ctx(), id, Some(size), baseline);
|
||||
}
|
||||
|
||||
/// `record_control_baseline` for the control of the row `id`; `size`: the control's size, when the row's label step
|
||||
/// knows it.
|
||||
pub(crate) fn record_baseline(ctx: &egui::Context, id: Id, size: Option<ControlSize>, baseline: f32) {
|
||||
layout_memory::record(ctx, sub(id, "baseline"), Vec2::new(0.0, baseline));
|
||||
if let Some(size) = size {
|
||||
layout_memory::note_typical(ctx, baseline_kind(size), Vec2::new(0.0, baseline));
|
||||
}
|
||||
layout_memory::record_control_baseline(ui.ctx(), id, Some(size), baseline);
|
||||
}
|
||||
|
||||
/// The first baseline of the control of `size` of the row `id`, from its top, as `record_control_baseline` stored it
|
||||
@@ -39,13 +30,8 @@ pub fn control_baseline(ctx: &egui::Context, id: Id, size: ControlSize, label: V
|
||||
.map(|size| size.y)
|
||||
.or_else(|| layout_memory::read(ctx, sub(id, "centre")).map(|size| size.y + label_baseline - label.y / 2.0));
|
||||
own.or_else(|| {
|
||||
let typical = layout_memory::typical(ctx, baseline_kind(size))?;
|
||||
let typical = layout_memory::typical(ctx, layout_memory::control_baseline_kind(size))?;
|
||||
layout_memory::assume(ctx, sub(id, "baseline"), typical);
|
||||
Some(typical.y)
|
||||
})
|
||||
}
|
||||
|
||||
/// The key the baselines of the controls of `size` are noted under.
|
||||
fn baseline_kind(size: ControlSize) -> Id {
|
||||
crate::runtime::memory::unique(("label control baseline", size))
|
||||
}
|
||||
@@ -14,7 +14,6 @@ pub use column_group::ambient_width;
|
||||
#[doc(hidden)]
|
||||
pub use column_group::report_beyond;
|
||||
pub(crate) use column_group::{Columns, GLYPHS, LABELS, Reached, ambient_room, note_beside};
|
||||
pub(crate) use label::record_baseline;
|
||||
pub use label::{control_baseline, place_label, record_control_baseline};
|
||||
pub use slot::measure_slot;
|
||||
|
||||
|
||||
@@ -707,7 +707,7 @@ pub(crate) fn finish(ctx: &Context, container: Id, merged: Option<Merged>) {
|
||||
crate::runtime::focus::request(ctx, only.inner_stop.unwrap_or(crate::runtime::focus::FocusTarget::Id(only.id)));
|
||||
}
|
||||
if let Some(baseline) = scope.baseline {
|
||||
crate::layout::record_baseline(ctx, scope.container, scope.control_size, baseline - scope.control_top);
|
||||
layout_memory::record_control_baseline(ctx, scope.container, scope.control_size, baseline - scope.control_top);
|
||||
}
|
||||
if let (None, Some(centre)) = (scope.baseline, scope.centre) {
|
||||
layout_memory::record(ctx, sub(scope.container, "centre"), Vec2::new(0.0, centre - scope.control_top));
|
||||
|
||||
@@ -528,6 +528,21 @@ pub(crate) fn note_typical(ctx: &Context, kind: Id, size: Vec2) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Stores `baseline`, the distance from the top of the control of the labeled row `row` to its first baseline, for the
|
||||
/// next pass's label placement. With the control's `size`, it also notes the baseline for the first appearance of
|
||||
/// later rows with a control of that size ([`control_baseline_kind`]).
|
||||
pub(crate) fn record_control_baseline(ctx: &Context, row: Id, size: Option<craft_theme::ControlSize>, baseline: f32) {
|
||||
record(ctx, crate::runtime::memory::sub(row, "baseline"), Vec2::new(0.0, baseline));
|
||||
if let Some(size) = size {
|
||||
note_typical(ctx, control_baseline_kind(size), Vec2::new(0.0, baseline));
|
||||
}
|
||||
}
|
||||
|
||||
/// The key the baselines of the controls of `size` are noted under ([`typical`]).
|
||||
pub(crate) fn control_baseline_kind(size: craft_theme::ControlSize) -> Id {
|
||||
crate::runtime::memory::unique(("label control baseline", size))
|
||||
}
|
||||
|
||||
/// This pass placed the block `id` by `size`, which it took from elsewhere (a block of the same kind, [`typical`]),
|
||||
/// where the entry under `id` holds no size yet: [`record`] compares the real size with `size`, as it compares a size
|
||||
/// from the last pass, so a first appearance that measures what the placement assumed asks no discard pass. It
|
||||
|
||||
@@ -361,7 +361,11 @@ pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 's
|
||||
drops: Vec<PresetDrop<'a, K>>,
|
||||
/// The host's payloads a preset drag carries beside its `ListDrag<K>`.
|
||||
payloads: Vec<DragPayload>,
|
||||
/// The version of what the host's closures read ([`host_version`](Self::host_version)).
|
||||
/// The version of everything the host's closures read: the tip painter (`tip`), the row menu's rows (`row_items`),
|
||||
/// the drop rules (`takes_drop`) and the payload maps (`drag_payload`). The host gives a new version whenever one
|
||||
/// of them would answer differently. While the version holds and nothing reaches the presets, their view repaints
|
||||
/// its last run; without a version a browser with any of those closures runs its view in every pass.
|
||||
#[prop]
|
||||
host_version: Option<u64>,
|
||||
/// The search field is its scope's default stop (`Initial::Default`): a picker's popover opens with the focus in
|
||||
/// it, so typing filters the presets.
|
||||
@@ -442,15 +446,6 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> PresetBrowser
|
||||
self
|
||||
}
|
||||
|
||||
/// The version of everything the host's closures read: the tip painter (`tip`), the row menu's rows (`row_items`),
|
||||
/// the drop rules (`takes_drop`) and the payload maps (`drag_payload`). The host gives a new version whenever one
|
||||
/// of them would answer differently. While the version holds and nothing reaches the presets, their view repaints
|
||||
/// its last run; without a version a browser with any of those closures runs its view in every pass.
|
||||
pub fn host_version(mut self, version: u64) -> Self {
|
||||
self.host_version = Some(version);
|
||||
self
|
||||
}
|
||||
|
||||
/// The id of the browser's list, the `ListDrag::list` of its drags: a footer action accepts only drags from its own
|
||||
/// browser.
|
||||
pub fn list_id(browser: Id) -> Id {
|
||||
|
||||
Reference in new issue
Block a user