diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index b710c7d4b..27e8fdba0 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -24,6 +24,9 @@ Sources: https://pronom.nationalarchives.gov.uk/fmt/467.xml, https://pronom.nationalarchives.gov.uk/fmt/466.xml and https://pronom.nationalarchives.gov.uk/fmt/465.xml +- **G**: the Windows GDI reference pages for the BMP file header and the bitmap info header, + https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapfileheader and + https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapinfoheader - **S**: own inspection of the bytes of public sample files, checked against the picture each file carries of its drawing where it has one (versions 2 and 4 to 25; files of versions 1 and 3 carry none). The files come from: @@ -50,7 +53,7 @@ Sources: was read for the order of fields that the notes do not spell out (the table entries, the rendering attributes and the curve body); no code was copied from it -Status: `public-spec` (K, KF, KR, Z, F or PR), `sample` (S), `public-notes` (a layout CN marks +Status: `public-spec` (K, KF, KR, Z, F, PR or G), `sample` (S), `public-notes` (a layout CN marks confirmed that no CX file shows), `unconfirmed` (a point no source states and no sample file shows; listed so it can be checked against a file, with what the reader does when it is wrong). @@ -88,6 +91,8 @@ file is committed. | R24 | ZIP: the end of central directory record (signature `PK\5\6`, 22 bytes and a comment of up to 65,535 bytes) gives the member count and where the central directory lies; each central directory entry (46 bytes, then name, extra field and comment) gives the flags, method, CRC-32, sizes and its local header; a local header is 30 bytes, then its name and extra field, then the member's bytes. Flag bit 0 marks an encrypted member; method 0 is stored and 8 deflated; 0xFFFF and 0xFFFFFFFF mark ZIP64 fields, and a ZIP64 locator (`PK\6\7`, 20 bytes) precedes the end record of a ZIP64 archive; disk numbers other than 0 mark an archive split across files | Z 4.3.7, 4.3.12, 4.3.15, 4.3.16, 4.4.1.4, 4.4.4, 4.4.5, 4.4.7, 4.4.8, 4.4.13 | public-spec | | R25 | Versions 14 and 15 save a ZIP package whose member `content/riffData.cdr` is the RIFF file | KR README L33, `cdr-unpk` L30 | public-spec | | R26 | From version 16 the package's member `content/root.dat` is the RIFF file; `content/dataFileList.dat` names the data streams, one per line, members of `content/data/`; a redirect's stream number counts lines from 0 | KR README L34, L40, `cdr-unpk` L34-L66; K L173-L180 | public-spec | +| R75 | `DISP`, a chunk of the RIFF form itself, holds the picture of the drawing: 4 bytes, then a bitmap info header (its own length u32, width, height, planes u16, bit count u16, compression u32, image size, two resolutions, the colors used u32, the important colors), then the color table or color masks and the pixels, to the end of the chunk. A BMP file is that bitmap after a 14-byte file header: `BM`, the file length u32, 4 reserved bytes of 0 and the offset of the pixels u32. The color table holds the colors used, or 2^bit count colors when that is 0 at 8 bits or fewer; compression 3 after a 40-byte header puts three u32 masks before the pixels. Uncompressed pixels (compression 0 or 3) are one row for each line of the height, each the width times the bit count rounded up to whole 32-bit words | K L231, L280-L306; G (both pages); S: every RIFF file of versions 4 to 13 in TP, UC, LT, NR, DM and TDF (469 files) has one `DISP`, starting with the bytes `08 00 00 00` and a 40-byte header of 1, 4 or 8 bits, compression 0 and a positive height, whose color table and rows fill the rest of the chunk; the files of version 3 (TP, 9) have none | public-spec (the 4 bytes and where the chunk lies: sample; other header lengths and bit counts: unconfirmed, as no sample has one, and a wrong guess gives a picture that fails to decode) | +| R76 | The package holds the picture of the drawing as `metadata/thumbnails/thumbnail.bmp`, a BMP file, in versions 14 to 16, and as `previews/thumbnail.png`, a PNG file, from version 17; each page's picture is beside it (`page1.bmp`, `page1.png` ...) | S: every package of versions 14 to 16 (62) and of 17 to 25 (231) in LT, TP and TDF | sample | | R27 | In a package of version 16 on, a chunk outside a compressed list whose size is 16 (in `root.dat` or in a redirected list's body) is a redirect record: stream u32, length u32, offset u32 and a reserved u32; its body is `length` bytes at `offset` of the stream; stream `0xFFFFFFFF` holds the body (at most 8 bytes) in the record after the length; a redirected list's body starts with its form type | K L144-L193 | public-spec | | R28 | Templates have the form type `CDT` and a letter of their own; the `vrsn` chunk names the version. The reader takes any letter `A` to `Z` there | none: no sample template | unconfirmed (a template is read as a drawing of the version its `vrsn` chunk names, and one without that chunk is refused) | | R29 | Rectangle coordinates from version 15: width and height as f64 coordinate units, scale x and y (f64, repeating the transform's scale), the scale-with flag (u8) and 7 bytes, then the four radii as f64, 16 bytes apart (a corner type byte and 15 bytes after the first), in the order of R15. With the flag clear each radius is a share of half the shorter side; with it set the radii are multiplied by 254000 coordinate units, which makes them inches | K L674-L752; S: LT `square_blackfill_nooutline_roundedcorners_cdr.cdr` of `testset/15` to `testset/25` (flag clear, a share of 0.25) | public-spec (radius share with the flag clear: sample; that the scale is not applied: unconfirmed, as every sample has a scale of 1, and a wrong guess changes only the corners' size) | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index dd66bdccc..bde0489ab 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -57,6 +57,15 @@ reports version 1 for the marker `e` and version 2 for the other two. A RIFF fil a version before 3 is refused, and so is the version 4 template form type `CDST`, which reads as not a `.cdr` drawing. +## Previews + +`preview` returns the picture a `.cdr` file keeps of its drawing without reading the drawing (rows +R75 and R76). In versions 4 to 13 the picture is the `DISP` chunk, returned as a BMP file. In versions +14 to 16 it is the package member `metadata/thumbnails/thumbnail.bmp`, and from version 17 on it +is `previews/thumbnail.png`. The package's drawing stream is not read, so a package that holds +both members gives the PNG. Files of versions 1 to 3 keep no picture. The bytes are returned still +encoded, so the caller decodes them within its own image limits. + ## `.cmx` files `read_cmx` reads `.cmx` exchange files with 32-bit coordinates (rows R53 to R63) into the same diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs index 64cdae512..8c96e7f4f 100644 --- a/crates/cdr/src/lib.rs +++ b/crates/cdr/src/lib.rs @@ -3,7 +3,8 @@ //! packages of versions 14 on with their data streams, then pages, layers, guidelines, groups, //! curves, rectangles, ellipses, arcs and polygons with uniform fills and outlines. It also reads //! `.cmx` exchange files with 32-bit coordinates ([`read_cmx`]): their pages, layers, groups and -//! curves with uniform fills and outlines. +//! curves with uniform fills and outlines. [`preview`] gives the picture a `.cdr` file keeps of its +//! drawing, without reading the drawing. //! //! Every record layout the reader relies on is listed in `PROVENANCE.md` with its public source //! and status; code cites the row ids (R1 ...). Reading is bounded by [`Limits`], never recurses and does not @@ -22,6 +23,7 @@ mod layout; mod limits; pub mod model; mod package; +mod preview; mod records; mod riff; mod styles; @@ -34,6 +36,7 @@ mod zip; pub use limits::Limits; pub use model::{Drawing, Warning}; +pub use preview::{Preview, PreviewFormat, preview}; /// Does `bytes` look like a `.cdr` drawing: a RIFF file, a ZIP package holding one, or a `WL` file /// of version 1 or 2 whose header offsets fit the file? diff --git a/crates/cdr/src/package.rs b/crates/cdr/src/package.rs index c46fa31e3..6d7fd7e1e 100644 --- a/crates/cdr/src/package.rs +++ b/crates/cdr/src/package.rs @@ -18,7 +18,12 @@ const DATA_DIR: &[u8] = b"content/data/"; /// Is `bytes` a ZIP archive with a `.cdr` drawing's root stream? pub(crate) fn is_package(bytes: &[u8]) -> bool { - zip::is_zip(bytes) && Archive::open(bytes, Limits::default().members).is_ok_and(|a| a.find(RIFF_DATA).or_else(|| a.find(ROOT)).is_some()) + zip::is_zip(bytes) && Archive::open(bytes, Limits::default().members).is_ok_and(|a| holds_drawing(&a)) +} + +/// Does the archive `zip` hold a `.cdr` drawing's root stream? +pub(crate) fn holds_drawing(zip: &Archive) -> bool { + zip.find(RIFF_DATA).or_else(|| zip.find(ROOT)).is_some() } /// The RIFF stream of the package `bytes`, and its data streams when it has them (16 on). diff --git a/crates/cdr/src/preview.rs b/crates/cdr/src/preview.rs new file mode 100644 index 000000000..fbac0e54c --- /dev/null +++ b/crates/cdr/src/preview.rs @@ -0,0 +1,352 @@ +//! The picture a drawing keeps of itself: the `DISP` chunk of a RIFF file (R75), or the thumbnail +//! member of a package (R76). Reading it walks only the RIFF form's own chunks, or reads one +//! package member, so it does not depend on the drawing's records. + +use std::borrow::Cow; + +use crate::bytes::Rd; +use crate::zip::{self, Archive}; +use crate::{Error, Limits, package, riff, wl}; + +const DISP: [u8; 4] = *b"DISP"; +/// The bytes of a `DISP` body before its bitmap info header (R75). +const DISP_LEAD: usize = 4; +/// The shortest bitmap info header, and the one whose color masks follow it (R75). +const INFO_LEN: usize = 40; +/// The compression values of uncompressed pixels, and of pixels that three color masks describe +/// (R75). +const RGB: u32 = 0; +const BITFIELDS: u32 = 3; +/// A BMP file header: `BM`, the file length, 4 reserved bytes and where the pixels start (R75). +const FILE_HEADER_LEN: usize = 14; +/// The package members that hold the drawing's picture (R76), in the order they are looked for. +const PNG_THUMBNAIL: &[u8] = b"previews/thumbnail.png"; +const BMP_THUMBNAIL: &[u8] = b"metadata/thumbnails/thumbnail.bmp"; +const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n"; +const BMP_SIGNATURE: &[u8] = b"BM"; + +/// How a [`Preview`]'s bytes are encoded. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PreviewFormat { + /// A BMP file. + Bmp, + /// A PNG file. + Png, +} + +/// The picture a drawing keeps of itself, still encoded: the caller decodes it within its own +/// image limits. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Preview<'a> { + pub format: PreviewFormat, + pub bytes: Cow<'a, [u8]>, +} + +/// The picture the drawing `bytes` keeps of itself, within `limits`, without reading the drawing: +/// a version 4 to 13 file's `DISP` chunk as a BMP file, or a package's thumbnail member: +/// `previews/thumbnail.png` when the package has one (versions 17 on), else +/// `metadata/thumbnails/thumbnail.bmp` (versions 14 to 16). The package's drawing stream is not +/// read, so the member is chosen by its name, not by the drawing's version. `None` when the file +/// keeps no picture, as versions 1 to 3 do. A package member is read within the member and inflate +/// limits, and its CRC-32 is checked. +pub fn preview(bytes: &[u8], limits: Limits) -> Result>, Error> { + if bytes.len() > limits.input { + return Err(Error::Limit("input size")); + } + if zip::is_zip(bytes) { + return thumbnail(bytes, limits); + } + if riff::is_cdr_riff(bytes) { + return disp(bytes, limits); + } + if wl::is_wl(bytes) { + return Ok(None); + } + Err(Error::NotCdr) +} + +/// A package's thumbnail member (R76). +fn thumbnail(bytes: &[u8], limits: Limits) -> Result>, Error> { + let zip = Archive::open(bytes, limits.members)?; + if !package::holds_drawing(&zip) { + return Err(Error::NotCdr); + } + for (name, format, signature) in [(PNG_THUMBNAIL, PreviewFormat::Png, PNG_SIGNATURE), (BMP_THUMBNAIL, PreviewFormat::Bmp, BMP_SIGNATURE)] { + if let Some(i) = zip.find(name) { + let bytes = zip.read(i, limits.member, limits.inflated)?; + if !bytes.starts_with(signature) { + return Err(Error::Damaged("preview")); + } + return Ok(Some(Preview { format, bytes })); + } + } + Ok(None) +} + +/// The `DISP` chunk among the RIFF form's own chunks, as a BMP file (R75). A file cut short is +/// walked to its end. +fn disp(bytes: &[u8], limits: Limits) -> Result>, Error> { + let declared = Rd::at(bytes, 4).u32().ok_or(Error::NotCdr)? as usize; + let end = declared.checked_add(8).filter(|e| (12..=bytes.len()).contains(e)).unwrap_or(bytes.len()); + let mut at: usize = 12; + let mut chunks = 0; + while at.checked_add(8).is_some_and(|h| h <= end) { + chunks += 1; + if chunks > limits.chunks { + return Err(Error::Limit("chunk count")); + } + let mut r = Rd::at(bytes, at); + let (id, len) = (r.fourcc(), r.u32().map(|n| n as usize)); + let (Some(id), Some(len)) = (id, len) else { break }; + let body = at + 8; + if id == DISP { + let data = body.checked_add(len).filter(|e| *e <= end).and_then(|e| bytes.get(body..e)).ok_or(Error::Damaged("preview"))?; + return Ok(Some(Preview { format: PreviewFormat::Bmp, bytes: Cow::Owned(bmp(data)?) })); + } + // Chunks are padded to an even length. + at = body.saturating_add(len).saturating_add(len & 1); + } + Ok(None) +} + +/// The bitmap of a `DISP` body as a BMP file: a file header before its info header, color masks or +/// table and pixels (R75). +fn bmp(disp: &[u8]) -> Result, Error> { + let damaged = || Error::Damaged("preview"); + let dib = disp.get(DISP_LEAD..).ok_or_else(damaged)?; + let mut r = Rd::new(dib); + let info = r.u32().ok_or_else(damaged)? as usize; + let (width, height) = (r.i32().ok_or_else(damaged)?, r.i32().ok_or_else(damaged)?); + // The planes, then the bit count and compression; the image size and resolution, then the + // colors used. + r.skip(2).ok_or_else(damaged)?; + let bits = r.u16().ok_or_else(damaged)?; + let compression = r.u32().ok_or_else(damaged)?; + r.skip(12).ok_or_else(damaged)?; + let used = r.u32().ok_or_else(damaged)? as usize; + if info < INFO_LEN || info > dib.len() { + return Err(damaged()); + } + // A table of 2^bits colors when the header names none for 8 bits or fewer. + let colors = if bits <= 8 && used == 0 { 1usize << bits } else { used }; + let masks = if info == INFO_LEN && compression == BITFIELDS { 12 } else { 0 }; + let pixels = colors.checked_mul(4).and_then(|t| (FILE_HEADER_LEN + info + masks).checked_add(t)).ok_or_else(damaged)?; + let total = FILE_HEADER_LEN + dib.len(); + if pixels > total { + return Err(damaged()); + } + // Uncompressed pixels are rows of whole 32-bit words, as many as the height says (R75). + if matches!(compression, RGB | BITFIELDS) { + let width = usize::try_from(width).ok().filter(|w| *w > 0).ok_or_else(damaged)?; + if !matches!(bits, 1 | 4 | 8 | 16 | 24 | 32) || height == 0 { + return Err(damaged()); + } + let stride = width.checked_mul(usize::from(bits)).map(|b| b.div_ceil(32) * 4); + let rows = stride.and_then(|s| s.checked_mul(height.unsigned_abs() as usize)); + if rows.and_then(|n| pixels.checked_add(n)).is_none_or(|e| e > total) { + return Err(damaged()); + } + } + let (total32, pixels32) = (u32::try_from(total).map_err(|_| damaged())?, u32::try_from(pixels).map_err(|_| damaged())?); + let mut out = Vec::with_capacity(total); + out.extend(BMP_SIGNATURE); + out.extend(total32.to_le_bytes()); + out.extend([0; 4]); + out.extend(pixels32.to_le_bytes()); + out.extend(dib); + Ok(out) +} + +#[cfg(test)] +mod tests { + use proptest::prelude::*; + + use super::*; + use crate::synth::{self, Member, chunk}; + + /// A `DISP` body: the lead bytes, a 40-byte info header for `bits` per pixel and `used` + /// colors, the color table and `rows` rows of `width` pixels. + fn disp_body(width: u32, rows: u32, bits: u16, used: u32) -> Vec { + let mut b = 8u32.to_le_bytes().to_vec(); + b.extend(40u32.to_le_bytes()); + b.extend(width.to_le_bytes()); + b.extend(rows.to_le_bytes()); + b.extend(1u16.to_le_bytes()); + b.extend(bits.to_le_bytes()); + b.extend([0; 16]); + b.extend(used.to_le_bytes()); + b.extend([0; 4]); + let colors = if bits <= 8 && used == 0 { 1 << bits } else { used }; + b.extend((0..colors * 4).map(|i| i as u8)); + let stride = (width * u32::from(bits)).div_ceil(32) * 4; + b.extend((0..stride * rows).map(|i| (i * 7) as u8)); + b + } + + fn with_disp(version: u16, body: Vec) -> Vec { + let mut content = vec![chunk(b"vrsn", version.to_le_bytes().to_vec()), chunk(b"DISP", body)]; + content.extend(synth::sample_content(version)); + synth::riff(version, &content) + } + + fn png() -> Vec { + [PNG_SIGNATURE, b"rest of the picture"].concat() + } + + fn package16(extra: &[Member]) -> Vec { + let mut body = vec![chunk(b"vrsn", 1700u16.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(1700)); + synth::package16(1700, &body, true, extra) + } + + fn member(name: &str, data: Vec, deflate: bool) -> Member { + Member { name: name.into(), data, deflate } + } + + #[test] + fn a_riff_files_disp_chunk_is_a_bmp_file_around_its_bitmap() { + for (bits, used) in [(8, 256), (8, 0), (4, 0), (4, 16), (1, 2)] { + let body = disp_body(9, 5, bits, used); + let file = with_disp(1100, body.clone()); + let p = preview(&file, Limits::default()).unwrap().unwrap(); + assert_eq!(p.format, PreviewFormat::Bmp); + let b = &p.bytes; + assert!(b.starts_with(b"BM")); + assert_eq!(&b[FILE_HEADER_LEN..], &body[DISP_LEAD..], "the bitmap follows the file header unchanged"); + assert_eq!(u32::from_le_bytes(b[2..6].try_into().unwrap()) as usize, b.len()); + // The pixels start after the info header and the whole color table. + let colors = if used == 0 { 1 << bits } else { used } as usize; + assert_eq!(u32::from_le_bytes(b[10..14].try_into().unwrap()) as usize, FILE_HEADER_LEN + 40 + colors * 4, "{bits} bits, {used} colors"); + } + } + + #[test] + fn a_file_without_a_picture_has_no_preview() { + assert_eq!(preview(&synth::sample(300, false), Limits::default()), Ok(None)); + assert_eq!(preview(&synth::sample(1100, true), Limits::default()), Ok(None)); + assert_eq!(preview(&synth::wl_sample(b'e'), Limits::default()), Ok(None)); + assert_eq!(preview(&package16(&[]), Limits::default()), Ok(None)); + assert_eq!(preview(&synth::package14(synth::sample(1500, true), true), Limits::default()), Ok(None)); + } + + #[test] + fn a_package_gives_its_thumbnail_member() { + let bmp = with_disp(1100, disp_body(3, 2, 8, 0)); + let bmp = preview(&bmp, Limits::default()).unwrap().unwrap().bytes.into_owned(); + let v15 = synth::zip( + &[member("content/riffData.cdr", synth::sample(1500, true), true), member("metadata/thumbnails/thumbnail.bmp", bmp.clone(), true)], + b"", + ); + assert_eq!(preview(&v15, Limits::default()), Ok(Some(Preview { format: PreviewFormat::Bmp, bytes: Cow::Owned(bmp) }))); + // A stored member is lent, not copied. + let v16 = package16(&[member("previews/page1.png", vec![1; 10], false), member("previews/thumbnail.png", png(), false)]); + let p = preview(&v16, Limits::default()).unwrap().unwrap(); + assert_eq!(p.format, PreviewFormat::Png); + assert!(matches!(p.bytes, Cow::Borrowed(b) if b == png().as_slice())); + } + + #[test] + fn a_thumbnail_that_is_not_its_format_is_damage() { + let v16 = package16(&[member("previews/thumbnail.png", b"BM not a PNG".to_vec(), false)]); + assert_eq!(preview(&v16, Limits::default()), Err(Error::Damaged("preview"))); + let v15 = synth::zip( + &[member("content/riffData.cdr", synth::sample(1500, false), false), member("metadata/thumbnails/thumbnail.bmp", png(), false)], + b"", + ); + assert_eq!(preview(&v15, Limits::default()), Err(Error::Damaged("preview"))); + } + + #[test] + fn a_disp_chunk_too_short_for_its_bitmap_is_damage() { + let body = disp_body(4, 4, 8, 0); + // Cut inside the info header, inside the color table, and before the lead bytes end. + for cut in [DISP_LEAD + 20, DISP_LEAD + 40 + 100, 2] { + let file = with_disp(1100, body[..cut].to_vec()); + assert_eq!(preview(&file, Limits::default()), Err(Error::Damaged("preview")), "cut at {cut}"); + } + // An info header longer than the chunk, or shorter than 40 bytes. + for info in [u32::MAX, 12] { + let mut b = body.clone(); + b[DISP_LEAD..DISP_LEAD + 4].copy_from_slice(&info.to_le_bytes()); + assert_eq!(preview(&with_disp(1100, b), Limits::default()), Err(Error::Damaged("preview")), "info {info}"); + } + // A color count past the chunk. + let mut b = body.clone(); + b[DISP_LEAD + 32..DISP_LEAD + 36].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(preview(&with_disp(1100, b), Limits::default()), Err(Error::Damaged("preview"))); + // Pixel rows cut short, and a width or bit count that gives no rows. + let rows = with_disp(1100, body[..body.len() - 1].to_vec()); + assert_eq!(preview(&rows, Limits::default()), Err(Error::Damaged("preview"))); + for (at, v) in [(4, 0u32.to_le_bytes().to_vec()), (14, 2u16.to_le_bytes().to_vec())] { + let mut b = body.clone(); + b[DISP_LEAD + at..DISP_LEAD + at + v.len()].copy_from_slice(&v); + assert_eq!(preview(&with_disp(1100, b), Limits::default()), Err(Error::Damaged("preview")), "field at {at}"); + } + // A chunk that runs past the end of the RIFF form, though not past the file. + let mut past = with_disp(1100, body.clone()); + let at = past.windows(4).position(|w| w == b"DISP").unwrap(); + let form_len = (at + 8 + body.len() - 1 - 8) as u32; + past[4..8].copy_from_slice(&form_len.to_le_bytes()); + assert_eq!(preview(&past, Limits::default()), Err(Error::Damaged("preview"))); + // A chunk whose length runs past the file. + let mut file = with_disp(1100, body); + let at = file.windows(4).position(|w| w == b"DISP").unwrap(); + file[at + 4..at + 8].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(preview(&file, Limits::default()), Err(Error::Damaged("preview"))); + } + + #[test] + fn color_masks_after_a_40_byte_header_come_before_the_pixels() { + let plain = disp_body(2, 2, 16, 0); + let mut body = plain[..DISP_LEAD + 40].to_vec(); + body[DISP_LEAD + 16..DISP_LEAD + 20].copy_from_slice(&BITFIELDS.to_le_bytes()); + body.extend([0x00, 0xF8, 0, 0, 0xE0, 0x07, 0, 0, 0x1F, 0, 0, 0]); + body.extend(&plain[DISP_LEAD + 40..]); + let pixels_at = |file: Vec| { + let p = preview(&file, Limits::default()).unwrap().unwrap(); + u32::from_le_bytes(p.bytes[10..14].try_into().unwrap()) as usize + }; + assert_eq!(pixels_at(with_disp(1100, body)), FILE_HEADER_LEN + 40 + 12); + // Without the masks the pixels start right after the header. + assert_eq!(pixels_at(with_disp(1100, plain)), FILE_HEADER_LEN + 40); + } + + #[test] + fn the_limits_hold() { + let file = with_disp(1100, disp_body(4, 4, 8, 0)); + assert_eq!(preview(&file, Limits { input: file.len() - 1, ..Limits::default() }), Err(Error::Limit("input size"))); + // The `DISP` chunk is the second chunk. + assert_eq!(preview(&file, Limits { chunks: 1, ..Limits::default() }), Err(Error::Limit("chunk count"))); + assert!(preview(&file, Limits { chunks: 2, ..Limits::default() }).unwrap().is_some()); + let big = vec![7; 4000]; + let v16 = package16(&[member("previews/thumbnail.png", [PNG_SIGNATURE, &big].concat(), true)]); + assert_eq!(preview(&v16, Limits { member: 4000, ..Limits::default() }), Err(Error::Limit("package member size"))); + assert_eq!(preview(&v16, Limits { inflated: 4000, ..Limits::default() }), Err(Error::Limit("inflated size"))); + } + + #[test] + fn other_files_are_not_drawings() { + assert_eq!(preview(b"not a drawing", Limits::default()), Err(Error::NotCdr)); + let zip = synth::zip(&[member("previews/thumbnail.png", png(), false)], b""); + assert_eq!(preview(&zip, Limits::default()), Err(Error::NotCdr)); + } + + proptest! { + #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] + + #[test] + fn never_panics_on_mutated_files(package: bool, cut in any::(), edits in prop::collection::vec((any::(), any::()), 1..24)) { + let mut b = if package { + package16(&[member("previews/thumbnail.png", png(), false)]) + } else { + with_disp(900, disp_body(5, 3, 4, 0)) + }; + let n = b.len(); + for (at, v) in edits { + b[at % n] = v; + } + let _ = preview(&b, Limits::default()); + let _ = preview(&b[..cut % (n + 1)], Limits::default()); + } + } +}