From 23317d328450a14a47c8773883c05a1b72e48472 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 10:17:23 -0800 Subject: [PATCH 1/2] craft-metafile: report what the reader leaves out A caller could only tell from skipped_records that part of a file was not read. Picture now also reports: - truncated: the parse stopped at a limit that ends it (items, bytes kept, SAVEDC depth, clip paths), in the file or in an EMF+ metafile image drawn in it. - dropped_images: images that were not read: bitmaps past a size, byte or decode limit or not decodable, EMF+ metafile images that do not parse or are nested too deep, and pattern or texture brushes whose bitmap was not read. An image with no pixels, or drawn from a source rectangle that selects none, is not counted. - ignored_clips: SELECTCLIPPATH with RGN_OR, RGN_XOR or RGN_DIFF, EMF+ clips combined with XOR, exclude or complement, EMF+ unions drawn as the rectangle around both areas, and EMF+ clip paths and regions whose area stands in for the one the file gives, when the clip that results can differ from the one the file asks for. - unplayed_raster_ops: bitmaps drawn as plain copies because their raster operation is not SRCCOPY, SRCAND, SRCPAINT or SRCINVERT, and operations without a source other than PATCOPY, BLACKNESS and WHITENESS. Behavior changes: - An EMF+ metafile image adds its own counts, skipped_records included, once, the first time it is drawn. A nested picture without a size still draws nothing, and its counts are kept. - A raster operation that takes no source no longer draws the record's bitmap. PATCOPY, BLACKNESS and WHITENESS fill the destination in STRETCHDIBITS and STRETCHDIB, as they already did in BITBLT, STRETCHBLT, DIBBITBLT and DIBSTRETCHBLT. Other such operations (DSTINVERT, PATINVERT) are left out and counted. --- crates/metafile/README.md | 20 +- crates/metafile/src/canvas.rs | 70 ++++++- crates/metafile/src/dib.rs | 57 +++++ crates/metafile/src/emf.rs | 41 +++- crates/metafile/src/emfplus.rs | 311 +++++++++++++++++++++++----- crates/metafile/src/geom.rs | 27 +++ crates/metafile/src/lib.rs | 45 +++- crates/metafile/src/tests.rs | 22 +- crates/metafile/src/tests/limits.rs | 81 +++++++- crates/metafile/src/tests/model.rs | 263 ++++++++++++++++++++++- crates/metafile/src/wmf.rs | 42 +++- 11 files changed, 887 insertions(+), 92 deletions(-) diff --git a/crates/metafile/README.md b/crates/metafile/README.md index 77dd7233c..4e246de51 100644 --- a/crates/metafile/README.md +++ b/crates/metafile/README.md @@ -33,7 +33,19 @@ Every item carries the clip it was drawn under: `region` (the GDI clip region as `Arc`). An item shows inside its region and inside each of its clip paths. `Picture::skipped_records` counts records of a type the reader does not play, so a caller can say -that part of a file was not read. +that part of a file was not read. The other fields report what the reader left out or drew +differently: + +| Field | Reports | +|---|---| +| `truncated` | The parse stopped at a limit that ends it (items, bytes kept, `SAVEDC` depth, clip paths), in the file or in an EMF+ metafile image drawn in it. | +| `dropped_images` | Images that were not read: bitmaps past a size, byte or decode limit or not decodable, EMF+ metafile images that do not parse or are nested too deep, and pattern or texture brushes whose bitmap was not read (counted when the brush is created). An image with no pixels, or drawn from a source rectangle that selects none, is not counted. | +| `ignored_clips` | Clip changes not applied as the file asks: `SELECTCLIPPATH` with `RGN_OR`, `RGN_XOR` or `RGN_DIFF`, EMF+ clips combined with XOR, exclude or complement, EMF+ unions drawn as the rectangle around both areas, and EMF+ clips whose area stands in for the one the file gives (a path that is not one convex figure, drawn as its rectangle, or a region built with XOR, exclude or complement). A change that cannot alter the clip is not counted: an area whose figures all lie on a line (except in an EMF+ complement of a clip that encloses some area, which would empty it), `RGN_OR` on a clip that is still the whole surface, and a union whose rectangle is no larger than the union. | +| `unplayed_raster_ops` | Raster operations not played: bitmaps drawn as plain copies because their operation is not one of `SRCCOPY`, `SRCAND`, `SRCPAINT` and `SRCINVERT`, and operations without a source (such as `DSTINVERT` or `PATINVERT`) that are left out. | + +An EMF+ metafile image adds its own counts, `skipped_records` included, once, the first time it is +drawn. A metafile image that the byte limit refuses is counted in `dropped_images`, and its own +counts are not added. ### Why this model @@ -153,6 +165,12 @@ it never panics and never allocates from an unchecked count. Each limit has a te | Writers: dashes cut from one stroke | 100,000 | The stroke is written solid. | | Writers: segments from one curve | about 4,096 | The tolerance is raised. | +A limit that stops the parse sets `Picture::truncated`, and a bitmap, metafile image or pattern +brush whose pixels were not read is counted in `Picture::dropped_images`. These are not reported: +the limits that cut a path, a string, a clip region, a pen style or an EMF+ point list or gradient +short, items left out by the clipping and masking limits, and an EMF+ continued object whose pieces +never complete. + The tests parse every prefix of sample files, files with each byte replaced, and random bytes. ## What stays in the apps diff --git a/crates/metafile/src/canvas.rs b/crates/metafile/src/canvas.rs index 217d27495..67cc43f0f 100644 --- a/crates/metafile/src/canvas.rs +++ b/crates/metafile/src/canvas.rs @@ -391,6 +391,14 @@ pub(crate) struct Canvas { fig_start: P, /// Records of a type the readers do not know. pub skipped: u32, + /// Bitmaps a record asks to draw whose pixels were not read (see [`crate::Picture::dropped_images`]). + pub dropped_images: u32, + /// Clip changes not applied as the file asks (see [`crate::Picture::ignored_clips`]). + pub ignored_clips: u32, + /// Raster operations not played (see [`crate::Picture::unplayed_raster_ops`]). + pub unplayed_raster_ops: u32, + /// A nested picture drawn on this canvas stopped at a limit. + pub truncated_inside: bool, } impl Canvas { @@ -426,6 +434,10 @@ impl Canvas { arc_clockwise: false, fig_start: (0.0, 0.0), skipped: 0, + dropped_images: 0, + ignored_clips: 0, + unplayed_raster_ops: 0, + truncated_inside: false, } } @@ -772,12 +784,25 @@ impl Canvas { /// SELECTCLIPPATH: the bracketed path becomes part of the clip and the bracket is emptied. /// RGN_AND clips to it inside the current clip; RGN_COPY replaces the clip with it. The modes - /// that add to or cut from the clip (RGN_OR, RGN_XOR, RGN_DIFF) leave the clip as it was. The - /// path uses the current fill mode. One clip path more than [`MAX_CLIP_PATHS`] stops the parse. + /// that add to or cut from the clip (RGN_OR, RGN_XOR, RGN_DIFF) leave the clip as it was, and a + /// path they would have used is counted in `ignored_clips`. The path uses the current fill + /// mode. One clip path more than [`MAX_CLIP_PATHS`] stops the parse. pub fn select_clip_path(&mut self, mode: u32) { let ops = std::mem::take(&mut self.path); self.in_path = false; if !matches!(mode, clip::RGN_AND | clip::RGN_COPY) { + // A path that encloses no area adds nothing to the clip and cuts nothing from it under + // these modes, and adding to a clip that is still the whole surface leaves it the whole + // surface. + let unclipped = self.clip.is_none() && self.clip_paths.is_empty(); + let changes = match mode { + clip::RGN_OR => !unclipped, + clip::RGN_XOR | clip::RGN_DIFF => true, + _ => false, + }; + if changes && crate::geom::encloses_area(&ops) { + self.ignore_clip(); + } return; } if mode == clip::RGN_COPY { @@ -1189,17 +1214,30 @@ impl Canvas { } /// Fills a logical rectangle `[x, y, w, h]` for a source-less raster operation. PATCOPY uses the - /// brush (when solid); the others fill black or white. Other operations are not handled here. + /// brush (when solid); the others fill black or white. Other operations are not drawn; one that + /// takes no source (such as DSTINVERT) is counted in `unplayed_raster_ops`. pub fn fill_rop(&mut self, [x, y, w, h]: [f64; 4], rop: u32) { let rect = [x, y, x + w, y + h]; match rop { PATCOPY => self.fill_brush_rect(rect), BLACKNESS => self.fill_rect_with(rect, [0, 0, 0, 255]), WHITENESS => self.fill_rect_with(rect, [255, 255, 255, 255]), + _ if !crate::dib::uses_source(rop) => self.unplayed_rop(), _ => {} } } + /// Counts a raster operation the canvas does not play (see [`crate::Picture::unplayed_raster_ops`]). + pub fn unplayed_rop(&mut self) { + self.unplayed_raster_ops = self.unplayed_raster_ops.saturating_add(1); + } + + /// Counts a clip change the canvas does not apply as the file asks (see + /// [`crate::Picture::ignored_clips`]). + pub fn ignore_clip(&mut self) { + self.ignored_clips = self.ignored_clips.saturating_add(1); + } + /// Draws `text` (one `dx` advance per character, or none) with the current font, colours and /// alignment. The reference point is `at`, or the current position under TA_UPDATECP (which /// then moves past the string). `rect` (logical `[l, t, r, b]`) is filled with the background @@ -1299,6 +1337,32 @@ impl Canvas { let dev = if xf[1] == 0.0 && xf[2] == 0.0 { dev } else { [x0, y0, x1 - x0, y1 - y0] }; self.push(Raw::Bitmap { rect: dev, xf, img, region: RawClip::default() }); } + + /// Draws a bitmap that a record asked to combine with raster operation `rop` (already applied by + /// `dib::prepare`). A kept bitmap whose operation is drawn as a plain copy is counted in + /// `unplayed_raster_ops`. + pub fn bitmap_rop(&mut self, rect: [f64; 4], img: Rgba, rop: u32) { + let before = self.items.len(); + self.bitmap(rect, img); + if self.items.len() > before && crate::dib::copies_for(rop) { + self.unplayed_rop(); + } + } + + /// Counts a bitmap a record asked to draw that the reader could not keep (see + /// [`crate::Picture::dropped_images`]). + pub fn drop_image(&mut self) { + self.dropped_images = self.dropped_images.saturating_add(1); + } + + /// Adds what a nested picture left out to this canvas's counts. + pub fn add_losses(&mut self, pic: &crate::Picture) { + self.dropped_images = self.dropped_images.saturating_add(pic.dropped_images); + self.ignored_clips = self.ignored_clips.saturating_add(pic.ignored_clips); + self.unplayed_raster_ops = self.unplayed_raster_ops.saturating_add(pic.unplayed_raster_ops); + self.skipped = self.skipped.saturating_add(pic.skipped_records); + self.truncated_inside |= pic.truncated; + } } /// An 8×8 GDI hatch tile (HS_HORIZONTAL through HS_DIAGCROSS). None for an unknown GDI style. diff --git a/crates/metafile/src/dib.rs b/crates/metafile/src/dib.rs index 787f20eb6..04aa4a068 100644 --- a/crates/metafile/src/dib.rs +++ b/crates/metafile/src/dib.rs @@ -13,6 +13,7 @@ const BI_PNG: u32 = 5; const CORE_HEADER: usize = 12; /// Most palette entries a DIB can carry (the colour table never exceeds 2^8). const MAX_PALETTE: usize = 256; +const ROP_SRCCOPY: u32 = 0x00CC_0020; const ROP_SRCAND: u32 = 0x0088_00C6; const ROP_SRCPAINT: u32 = 0x00EE_0086; const ROP_SRCINVERT: u32 = 0x0066_0046; @@ -107,6 +108,17 @@ fn compression(info: Bytes) -> Option { (info.u32(0)? >= 40).then(|| info.u32(16)).flatten().filter(|c| matches!(*c, BI_JPEG | BI_PNG)) } +/// The width and height a JPEG or PNG file's header gives, without decoding any pixel. Unlike +/// [`decode_compressed`] it takes any side, with the same cap on what the decoder allocates. +pub(crate) fn compressed_size(bytes: &[u8]) -> Option<(usize, usize)> { + let mut r = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; + let mut limits = image::Limits::default(); + limits.max_alloc = Some((MAX_PIXELS * 4) as u64); + r.limits(limits); + let (w, h) = r.into_dimensions().ok()?; + Some((w as usize, h as usize)) +} + /// Decodes a JPEG or PNG file (the bits of a BI_JPEG or BI_PNG DIB, an EMF+ image) to top-down /// RGBA. The size comes from the file's header first, so an image over the side or pixel cap is /// refused before any pixel is decoded, and the decoder's own allocations are capped too. @@ -193,6 +205,51 @@ pub(crate) fn decode_clip(info: Bytes, bits: Bytes, keep_alpha: bool, src: [i64; Some((Rgba { w: ow, h: oh, px }, out)) } +/// The width, height and row order (true for bottom-up) a DIB's header gives, whatever its depth or +/// compression. A BI_JPEG or BI_PNG bitmap is measured by the image file in `bits`, as +/// [`decode_clip`] crops it, counted from the top. None when the header is not readable. +fn header_size(info: Bytes, bits: Option) -> Option<(usize, usize, bool)> { + match info.u32(0)? { + n if n as usize == CORE_HEADER => info.u16(4).zip(info.u16(6)).map(|(w, h)| (usize::from(w), usize::from(h), true)), + _ if compression(info).is_some() => bits.and_then(|b| compressed_size(b.0)).map(|(w, h)| (w, h, false)), + n if n >= 40 => info.i32(4).zip(info.i32(8)).and_then(|(w, h)| Some((usize::try_from(w).ok()?, h.unsigned_abs() as usize, h > 0))), + _ => None, + } +} + +/// True when the header of `info` is readable and the source rectangle `src` (as [`decode_clip`] +/// takes it) covers none of the bitmap's pixels, or the bitmap has none: such a bitmap draws nothing, +/// so it is not counted as left out. The size comes from [`header_size`], so a bitmap the decoder +/// does not read is measured too. +pub(crate) fn crop_misses(info: Bytes, bits: Option, src: [i64; 4]) -> bool { + header_size(info, bits).is_some_and(|(w, h, bottom_up)| w == 0 || h == 0 || clip_rect(w, h, bottom_up, src, [0.0, 0.0, 1.0, 1.0]).is_none()) +} + +/// True when a DIB's header is readable and gives it no pixels. +pub(crate) fn has_no_pixels(info: Bytes, bits: Option) -> bool { + header_size(info, bits).is_some_and(|(w, h, _)| w == 0 || h == 0) +} + +/// True when a `w` x `h` top-down image has no pixels, or the source rectangle `src` (as +/// [`clip_blit`] takes it) covers none of them. +pub(crate) fn src_misses(w: usize, h: usize, src: [i64; 4]) -> bool { + w == 0 || h == 0 || clip_rect(w, h, false, src, [0.0, 0.0, 1.0, 1.0]).is_none() +} + +/// Whether a ternary raster operation reads the source bitmap. Its index byte (bits 16 to 23) is the +/// operation's truth table over pattern, source and destination bits; the source does not matter +/// when the table is the same with the source bit set and clear. +pub(crate) fn uses_source(rop: u32) -> bool { + let table = (rop >> 16) & 0xFF; + ((table >> 2) ^ table) & 0x33 != 0 +} + +/// Whether a bitmap drawn with raster operation `rop` is drawn as a plain copy without being one: +/// [`prepare`] plays SRCCOPY, SRCAND, SRCPAINT and SRCINVERT, and copies the source for every other. +pub(crate) fn copies_for(rop: u32) -> bool { + !matches!(rop, ROP_SRCCOPY | ROP_SRCAND | ROP_SRCPAINT | ROP_SRCINVERT) +} + /// Decodes a whole DIB (rows top-down); see [`decode_clip`]. pub(crate) fn decode(info: Bytes, bits: Bytes, keep_alpha: bool) -> Option { decode_clip(info, bits, keep_alpha, [0, 0, 0, 0], [0.0, 0.0, 1.0, 1.0]).map(|(img, _)| img) diff --git a/crates/metafile/src/emf.rs b/crates/metafile/src/emf.rs index 81a8dd7fe..39aff6d05 100644 --- a/crates/metafile/src/emf.rs +++ b/crates/metafile/src/emf.rs @@ -357,14 +357,21 @@ fn create_brush(cv: &mut Canvas, r: Bytes) -> Option<()> { /// EMR_CREATEDIBPATTERNBRUSHPT (94) and EMR_CREATEMONOBRUSH (93): handle, colour usage, then the /// bitmap info and bits as offset/size pairs. A mono brush (or one whose palette holds indices, /// DIB_PAL_COLORS) takes the text and background colours. An undecodable bitmap leaves the slot -/// empty. +/// empty, as does a tile past the side cap; either is counted as a dropped image unless it has no +/// pixels. fn create_dib_brush(cv: &mut Canvas, r: Bytes, mono: bool) -> Option<()> { let slot = r.u32(8)? as usize; let usage = r.u32(12)?; let (bo, bl) = (r.u32(16)? as usize, r.u32(20)? as usize); let (po, pl) = (r.u32(24)? as usize, r.u32(28)? as usize); - let img = dib::decode(Bytes(r.slice(bo, bl)?), Bytes(r.slice(po, pl)?), false)?; - let b = Brush::pattern(img, mono || usage == 1)?; + let (info, bits) = (r.slice(bo, bl).map(Bytes), r.slice(po, pl).map(Bytes)); + let brush = info.zip(bits).and_then(|(info, bits)| dib::decode(info, bits, false)).and_then(|img| Brush::pattern(img, mono || usage == 1)); + let Some(b) = brush else { + if !info.is_some_and(|i| dib::has_no_pixels(i, bits)) { + cv.drop_image(); + } + return None; + }; cv.add_object(Some(slot), Obj::Brush(b)); Some(()) } @@ -500,17 +507,35 @@ fn set_dibits(cv: &mut Canvas, r: Bytes) -> Option<()> { /// Decodes the bitmap at `at` = (offset of the bmi offset/length pair, offset of the bits pair), both /// inside the record, and stretches the source rectangle `src` into `dst`. Both are `[x, y, w, h]`; a -/// non-positive source size means the whole bitmap. `blend` decides how it combines. +/// non-positive source size means the whole bitmap. `blend` decides how it combines. A record with +/// pixel bits whose bitmap cannot be read, or is past a limit, is counted as a dropped image. A raster +/// operation that takes no source fills the destination instead (see [`Canvas::fill_rop`]), with or +/// without bits. fn blit(cv: &mut Canvas, r: Bytes, dst: [f64; 4], src: [f64; 4], at: (usize, usize), blend: Blend) -> Option<()> { + if let Blend::Rop(rop) = blend + && !dib::uses_source(rop) + { + cv.fill_rop(dst, rop); + return Some(()); + } let (bo, bl) = (r.u32(at.0)? as usize, r.u32(at.0 + 4)? as usize); let (po, pl) = (r.u32(at.1)? as usize, r.u32(at.1 + 4)? as usize); if pl == 0 { return None; } - let info = Bytes(r.slice(bo, bl)?); - let pixels = Bytes(r.slice(po, pl)?); - let (mut img, dst) = dib::decode_clip(info, pixels, blend.per_pixel(), src.map(|v| v as i64), dst)?; + let src = src.map(|v| v as i64); + let (info, bits) = (r.slice(bo, bl).map(Bytes), r.slice(po, pl).map(Bytes)); + let decoded = info.zip(bits).and_then(|(info, pixels)| dib::decode_clip(info, pixels, blend.per_pixel(), src, dst)); + let Some((mut img, dst)) = decoded else { + if !info.is_some_and(|i| dib::crop_misses(i, bits, src)) { + cv.drop_image(); + } + return None; + }; dib::prepare(&mut img, blend); - cv.bitmap(dst, img); + match blend { + Blend::Rop(rop) => cv.bitmap_rop(dst, img, rop), + Blend::Alpha { .. } => cv.bitmap(dst, img), + } Some(()) } diff --git a/crates/metafile/src/emfplus.rs b/crates/metafile/src/emfplus.rs index af406aa30..32786bc5f 100644 --- a/crates/metafile/src/emfplus.rs +++ b/crates/metafile/src/emfplus.rs @@ -195,10 +195,17 @@ enum Obj { }, Path(Vec), Image(Arc), + /// An image object that could not be read or kept (past a limit, or in a form the reader does + /// not decode): drawing it counts a dropped image. The size of a bitmap, when its header gives one. + LostImage(Option<(usize, usize)>), + /// A texture brush whose image was not read or kept. It is counted as a dropped image when it is + /// stored, and the slot is left empty. + LostBrush, Font(FontObj), Format(Format), - /// A region's bounding rectangle `[l, t, r, b]` in world units; None is infinite. - Region(Area), + /// A region's bounding rectangle `[l, t, r, b]` in world units; None is infinite. The flag is set + /// when the area differs from the region the file describes (see [`region_node`]). + Region(Area, bool), } /// An object arriving in several records: its id, type, total size and the bytes so far. @@ -227,6 +234,10 @@ pub(crate) struct Plus { /// Convex device clip polygon; None is unclipped. clip: Area, objects: Vec>, + /// Whether the metafile image in each object slot has added its counts to the canvas. + reported: Vec, + /// Texture brushes not kept since the canvas last took the count. + lost_brushes: u32, object_bytes: usize, stack: Vec, partial: Option, @@ -244,6 +255,8 @@ impl Plus { page: 1.0, clip: None, objects: vec![None; MAX_OBJECTS], + reported: vec![false; MAX_OBJECTS], + lost_brushes: 0, object_bytes: 0, stack: Vec::new(), partial: None, @@ -302,7 +315,13 @@ impl Plus { return Some(()); } let done = match typ { - 0x4008 => self.object(flags, r, cv.used().saturating_add(self.clip_bytes())), + 0x4008 => { + let done = self.object(flags, r, cv.used().saturating_add(self.clip_bytes())); + for _ in 0..std::mem::take(&mut self.lost_brushes) { + cv.drop_image(); + } + done + } 0x4009 | 0x4013 | 0x401A..=0x401C | 0x4036 => self.record_image_text_region(cv, typ, flags, r), 0x4025..=0x4035 => self.record_state(cv, typ, flags, r), 0x4010..=0x4012 | 0x4016..=0x4019 => self.record_curve(cv, typ, flags, r), @@ -463,7 +482,7 @@ impl Plus { // FillRegion: the region's area (as the clip reads it). 0x4013 => { let fill = self.brush_of(flags, r.u32(0)?)?; - let Some(Some(Obj::Region(Some(area)))) = self.objects.get(id).cloned() else { return None }; + let Some(Some(Obj::Region(Some(area), _))) = self.objects.get(id).cloned() else { return None }; if area.len() < 3 { return None; } @@ -471,14 +490,14 @@ impl Plus { Some(()) } 0x401A => { - let img = self.image(id)?; let dst = *rects(r, 24, 1, compressed)?.first()?; + let img = self.image(cv, id, r)?; self.draw_image(cv, &img, r, [dst[0], dst[1], dst[2] - dst[0], dst[3] - dst[1]]) } 0x401B => { - let img = self.image(id)?; let pts = points(r, 28, 3, compressed)?; let (p0, p1, p2) = (*pts.first()?, *pts.get(1)?, *pts.get(2)?); + let img = self.image(cv, id, r)?; // The destination parallelogram's top-left, top-right and bottom-left corners; a // sheared or rotated one is drawn into its bounding rectangle's axes. let dst = [p0.0, p0.1, p1.0 - p0.0 + (p2.0 - p0.0), p2.1 - p0.1 + (p1.1 - p0.1)]; @@ -523,16 +542,17 @@ impl Plus { 0x4032 => { let [x, y, w, h] = floats::<4>(r, 0)?; let area = map_area(Some(rect_poly([x, y, x + w, y + h])), mul(self.xf(), cv.device_affine())); - self.combine(flags, area) + self.combine(cv, flags, area, false) } 0x4033 => { - let area = map_area(Some(area_of_ops(&self.path(id)?)), mul(self.xf(), cv.device_affine())); - self.combine(flags, area) + let (area, inexact) = area_of_ops(&self.path(id)?); + let area = map_area(Some(area), mul(self.xf(), cv.device_affine())); + self.combine(cv, flags, area, inexact) } 0x4034 => { - let Some(Some(Obj::Region(reg))) = self.objects.get(id).cloned() else { return None }; + let Some(Some(Obj::Region(reg, inexact))) = self.objects.get(id).cloned() else { return None }; let area = map_area(reg, mul(self.xf(), cv.device_affine())); - self.combine(flags, area) + self.combine(cv, flags, area, inexact) } 0x4035 => { let [dx, dy] = floats::<2>(r, 0)?; @@ -571,14 +591,42 @@ impl Plus { /// Combines a new clip area with the current one under the record's combine mode: replace, /// intersect and union (as the rectangle around both). XOR, exclude and complement leave the - /// clip as it was. - fn combine(&mut self, flags: u16, new: Area) -> Option<()> { - self.clip = match (flags >> 8) & 0xF { - 0 => new, - 1 => area_intersect(self.clip.take(), new), - 2 => area_union(self.clip.take(), new), - _ => self.clip.take(), + /// clip as it was. `inexact` says the new area already differs from what the file asks (see + /// [`region_node`]). The change is counted in the canvas's `ignored_clips` when the clip it + /// leaves can differ from what the file asks: an inexact area that replaces, cuts or widens the + /// clip, an intersection that ran out of work, a union whose rectangle is larger than the + /// union, an XOR, exclude or complement with an area that encloses some, and a complement of a + /// clip that encloses some. + fn combine(&mut self, cv: &mut Canvas, flags: u16, new: Area, inexact: bool) -> Option<()> { + let (clip, ignored) = match (flags >> 8) & 0xF { + 0 => (new, inexact), + 1 => { + let stand_in = intersect_inexact(&self.clip, false, &new, inexact); + let (out, cut_short) = area_intersect(self.clip.take(), new); + (out, stand_in || cut_short) + } + 2 => { + let ignored = union_inexact(&self.clip, false, &new, inexact) || union_grows(&self.clip, &new); + (area_union(self.clip.take(), new), ignored) + } + // XOR changes the clip unless the new area is empty, exclude unless either is empty; + // complement replaces the clip with the part of the new area outside it, which differs + // from the clip unless both are empty. + mode @ 3..=5 => { + let new_area = inexact || encloses(&new); + let changes = match mode { + 3 => new_area, + 4 => new_area && encloses(&self.clip), + _ => new_area || encloses(&self.clip), + }; + (self.clip.take(), changes) + } + _ => (self.clip.take(), false), }; + if ignored { + cv.ignore_clip(); + } + self.clip = clip; Some(()) } @@ -626,11 +674,25 @@ impl Plus { if let Some(old) = slot.take() { self.object_bytes = self.object_bytes.saturating_sub(Self::obj_cost(&old)); } + if let Some(r) = self.reported.get_mut(id) { + *r = false; + } if let Some(new_obj) = obj { let cost = Self::obj_cost(&new_obj); - if self.object_bytes.saturating_add(cost).saturating_add(canvas_used) <= crate::MAX_BYTES { + if matches!(new_obj, Obj::LostBrush) { + self.lost_brushes = self.lost_brushes.saturating_add(1); + } else if self.object_bytes.saturating_add(cost).saturating_add(canvas_used) <= crate::MAX_BYTES { self.object_bytes += cost; *slot = Some(new_obj); + } else if let Obj::Image(img) = &new_obj { + // A metafile image refused here has its own counts dropped with it. + let size = match img.as_ref() { + ImageData::Bitmap(b) => Some((b.w, b.h)), + ImageData::Meta(_) => None, + }; + *slot = Some(Obj::LostImage(size)); + } else if let Obj::Brush(Fill::Texture { .. }) = new_obj { + self.lost_brushes = self.lost_brushes.saturating_add(1); } } } @@ -661,9 +723,27 @@ impl Plus { } } - fn image(&self, id: usize) -> Option> { + /// The image object `id` for the draw record `r`. A lost one gives None and is counted as a + /// dropped image, unless the record's source rectangle selects none of its pixels. A metafile + /// image adds what it left out to the canvas's counts the first time it is drawn. + fn image(&mut self, cv: &mut Canvas, id: usize, r: Bytes) -> Option> { match self.objects.get(id)? { - Some(Obj::Image(img)) => Some(img.clone()), + Some(Obj::Image(img)) => { + if let (ImageData::Meta(pic), Some(reported)) = (img.as_ref(), self.reported.get_mut(id)) + && !*reported + { + cv.add_losses(pic); + *reported = true; + } + Some(img.clone()) + } + Some(Obj::LostImage(size)) => { + let misses = size.zip(source_px(r)).is_some_and(|((w, h), src)| crate::dib::src_misses(w, h, src)); + if !misses { + cv.drop_image(); + } + None + } _ => None, } } @@ -685,13 +765,15 @@ impl Plus { let img = match img { ImageData::Bitmap(b) => b, ImageData::Meta(pic) => { - self.painter().picture(cv, dst, pic); + // A nested picture without a size draws nothing; [`Self::image`] still reports what + // it left out. + if pic.width > 0.0 && pic.height > 0.0 { + self.painter().picture(cv, dst, pic); + } return Some(()); } }; - let [sx, sy, sw, sh] = floats::<4>(r, 8)?; - let src = if r.u32(4)? == 2 { [sx, sy, sw, sh].map(|v| v.round().clamp(-1.0e9, 1.0e9) as i64) } else { [0; 4] }; - let (part, dst) = crate::dib::clip_blit(img, src, dst)?; + let (part, dst) = crate::dib::clip_blit(img, source_px(r)?, dst)?; self.painter().image(cv, dst, part); Some(()) } @@ -994,11 +1076,11 @@ fn matrix(r: Bytes, off: usize) -> Option { fn parse_object(kind: u16, r: Bytes) -> Option { match kind { - 1 => brush(r, 0).map(Obj::Brush), + 1 => brush(r, 0).map(Obj::Brush).or_else(|| lost_texture(r).then_some(Obj::LostBrush)), 2 => pen(r), 3 => path(r).map(Obj::Path), 4 => region(r), - 5 => image(r).map(|i| Obj::Image(Arc::new(i))), + 5 => Some(image(r).map_or_else(|| Obj::LostImage(bitmap_size(r)), |i| Obj::Image(Arc::new(i)))), 6 => font(r), 7 => Some(Obj::Format(Format { flags: r.u32(4)?, align: r.u32(12)?, line_align: r.u32(16)? })), _ => None, @@ -1143,11 +1225,13 @@ fn path(r: Bytes) -> Option> { /// rectangle). fn region(r: Bytes) -> Option { let mut work = 0; - region_node(r, 8, 0, &mut work).map(|(a, _)| Obj::Region(a)) + region_node(r, 8, 0, &mut work).map(|(a, _, inexact)| Obj::Region(a, inexact)) } -/// One region node at `off`: its area and its length in bytes. -fn region_node(r: Bytes, off: usize, depth: usize, work: &mut usize) -> Option<(Area, usize)> { +/// One region node at `off`: its area, its length in bytes, and whether the area differs from the +/// node's (a path that is not one convex figure, an intersection that ran out of work, a union +/// drawn larger, or an XOR, exclude or complement node). +fn region_node(r: Bytes, off: usize, depth: usize, work: &mut usize) -> Option<(Area, usize, bool)> { *work = work.checked_add(1)?; if depth > MAX_REGION_DEPTH || *work > MAX_REGION_WORK { return None; @@ -1155,7 +1239,7 @@ fn region_node(r: Bytes, off: usize, depth: usize, work: &mut usize) -> Option<( match r.u32(off)? { 0x1000_0000 => { let [x, y, w, h] = floats::<4>(r, off + 4)?; - Some((Some(rect_poly([x.min(x + w), y.min(y + h), x.max(x + w), y.max(y + h)])), 20)) + Some((Some(rect_poly([x.min(x + w), y.min(y + h), x.max(x + w), y.max(y + h)])), 20, false)) } 0x1000_0001 => { let size = r.u32(off + 4)? as usize; @@ -1168,53 +1252,114 @@ fn region_node(r: Bytes, off: usize, depth: usize, work: &mut usize) -> Option<( if *work > MAX_REGION_WORK { return None; } - let area = area_of_ops(&path(data)?); - Some((Some(area), 8usize.checked_add(size)?)) + let (area, inexact) = area_of_ops(&path(data)?); + Some((Some(area), 8usize.checked_add(size)?, inexact)) } - 0x1000_0002 => Some((Some(Vec::new()), 4)), - 0x1000_0003 => Some((None, 4)), + 0x1000_0002 => Some((Some(Vec::new()), 4, false)), + 0x1000_0003 => Some((None, 4, false)), mode @ 0..=5 => { - let (a, la) = region_node(r, off + 4, depth + 1, work)?; - let (b, lb) = region_node(r, off.checked_add(4 + la)?, depth + 1, work)?; - let out = match mode { - 0 => b, - 1 => area_intersect(a, b), - 2 => area_union(a, b), - // XOR, exclude, complement: the left area bounds the result closely enough. - _ => a, + let (a, la, ia) = region_node(r, off + 4, depth + 1, work)?; + let (b, lb, ib) = region_node(r, off.checked_add(4 + la)?, depth + 1, work)?; + let (out, inexact) = match mode { + 0 => (b, ib), + 1 => { + let stand_in = intersect_inexact(&a, ia, &b, ib); + let (out, cut_short) = area_intersect(a, b); + (out, stand_in || cut_short) + } + 2 => { + let inexact = union_inexact(&a, ia, &b, ib) || union_grows(&a, &b); + (area_union(a, b), inexact) + } + // XOR, exclude, complement: the left area bounds the result closely enough. It is the + // result when the right area is empty under XOR, when either is empty under exclude, + // and when both are empty under complement (the right area outside the left). + _ => { + let (ea, eb) = (!ia && !encloses(&a), !ib && !encloses(&b)); + let exact = match mode { + 3 => !ia && eb, + 4 => (!ia && eb) || ea, + _ => ea && eb, + }; + (a, !exact) + } }; - Some((out, (4 + la).checked_add(lb)?)) + Some((out, (4 + la).checked_add(lb)?, inexact)) } _ => None, } } /// The area a path encloses: its outline when that is one convex figure, else the rectangle -/// around it. -fn area_of_ops(ops: &[Op]) -> Vec

{ +/// around it. The flag is set when the rectangle stands in for a path that encloses some area. +fn area_of_ops(ops: &[Op]) -> (Vec

, bool) { let subs = flatten(ops); if let [(pts, _)] = subs.as_slice() && let Some(c) = convex(pts) { - return c; + return (c, false); } - ops_bbox(ops).map(rect_poly).unwrap_or_default() + (ops_bbox(ops).map(rect_poly).unwrap_or_default(), crate::geom::encloses_area(ops)) } -fn area_intersect(a: Area, b: Area) -> Area { +/// Two areas' intersection, and whether it ran out of work and kept the first area instead. +fn area_intersect(a: Area, b: Area) -> (Area, bool) { match (a, b) { - (None, x) | (x, None) => x, + (None, x) | (x, None) => (x, false), (Some(a), Some(b)) if a.len() >= 3 && b.len() >= 3 => { // Out of work: keep the area so far rather than call the region empty. match clip_polygon_within(&a, &b, &mut { MAX_AREA_CLIP_WORK }) { - Some(p) => Some(convex(&p).unwrap_or_default()), - None => Some(a), + Some(p) => (Some(convex(&p).unwrap_or_default()), false), + None => (Some(a), true), } } - _ => Some(Vec::new()), + _ => (Some(Vec::new()), false), } } +/// Whether an area encloses nothing. +fn is_empty(pts: &[P]) -> bool { + pts.len() < 3 || poly_area(pts) <= 0.0 +} + +/// Whether an area (None: unlimited) encloses some. +fn encloses(a: &Area) -> bool { + a.as_ref().is_none_or(|pts| !is_empty(pts)) +} + +/// Whether the intersection of two areas, each flagged when it stands in for the file's, can differ +/// from the file's: a stand-in does not matter when the other area is exact and empty. +fn intersect_inexact(a: &Area, ia: bool, b: &Area, ib: bool) -> bool { + (ia && (ib || encloses(b))) || (ib && (ia || encloses(a))) +} + +/// Whether the union of two areas, each flagged when it stands in for the file's, can differ from +/// the file's: a stand-in does not matter when the other area is exact and unlimited. +fn union_inexact(a: &Area, ia: bool, b: &Area, ib: bool) -> bool { + (ia && (ib || b.is_some())) || (ib && (ia || a.is_some())) +} + +/// Whether the rectangle [`area_union`] draws for two areas is larger than their union. +fn union_grows(a: &Area, b: &Area) -> bool { + let (Some(a), Some(b)) = (a, b) else { return false }; + if a.len() < 3 || b.len() < 3 { + return false; + } + let all: Vec

= a.iter().chain(b).copied().collect(); + let Some([l, t, r, bottom]) = pts_bbox(&all) else { return false }; + // Out of work: the overlap is unknown, so the rectangle may be larger. + let Some(overlap) = clip_polygon_within(a, b, &mut { MAX_AREA_CLIP_WORK }) else { return true }; + let union = poly_area(a) + poly_area(b) - poly_area(&overlap); + let rect = (r - l) * (bottom - t); + rect > union + 1e-9 * rect +} + +/// The area a polygon encloses, whatever its orientation. +fn poly_area(pts: &[P]) -> f64 { + let twice: f64 = pts.iter().zip(pts.iter().cycle().skip(1)).map(|(a, b)| a.0 * b.1 - b.0 * a.1).sum(); + (twice / 2.0).abs() +} + fn area_union(a: Area, b: Area) -> Area { match (a, b) { (Some(a), Some(b)) => { @@ -1313,7 +1458,41 @@ fn metafile(r: Bytes) -> Option { NESTING.with(|n| n.set(depth + 1)); let pic = crate::parse_nested(data).ok(); NESTING.with(|n| n.set(depth)); - pic.filter(|p| p.width > 0.0 && p.height > 0.0) + pic +} + +/// The size in pixels of a bitmap image object, read from its header (a compressed one's from the +/// image file's header) even when its pixels are not, so a draw whose source rectangle selects none +/// of them, or of a bitmap without pixels, is not counted as lost. +fn bitmap_size(r: Bytes) -> Option<(usize, usize)> { + if r.u32(4)? != 1 { + return None; + } + if r.u32(24)? == 1 { + crate::dib::compressed_size(r.tail(28)?.0) + } else { + Some((usize::try_from(r.i32(8)?).ok()?, usize::try_from(r.i32(12)?).ok()?)) + } +} + +/// Whether a brush object that did not parse is a texture brush (type 2) with an image to draw: its +/// image is a metafile, is not readable, or is a bitmap whose header gives it pixels. +fn lost_texture(r: Bytes) -> bool { + if r.u32(4) != Some(2) { + return false; + } + let image = r.tail(8).and_then(|d| { + let off = if d.u32(0)? & 0x2 != 0 { 32 } else { 8 }; + d.tail(off) + }); + !image.and_then(bitmap_size).is_some_and(|(w, h)| w == 0 || h == 0) +} + +/// The source rectangle of DrawImage or DrawImagePoints in pixels; all zeros (the whole image) when +/// it is given in another unit. +fn source_px(r: Bytes) -> Option<[i64; 4]> { + let [sx, sy, sw, sh] = floats::<4>(r, 8)?; + Some(if r.u32(4)? == 2 { [sx, sy, sw, sh].map(|v| v.round().clamp(-1.0e9, 1.0e9) as i64) } else { [0; 4] }) } /// Bytes the items of a nested picture own: path segments, dashes, clip rectangles, pixels and @@ -1641,6 +1820,30 @@ mod cost_tests { assert!(plus.objects[0].is_some()); } + #[test] + fn an_image_or_texture_past_the_byte_budget_is_counted() { + let (mut plus, mut cv) = (Plus::new(), Canvas::new()); + let img = || Rgba { w: 4, h: 4, px: vec![0; 64] }; + plus.store(0, Some(Obj::Image(Arc::new(ImageData::Bitmap(img())))), crate::MAX_BYTES); + assert!(matches!(plus.objects[0], Some(Obj::LostImage(Some((4, 4)))))); + // DrawImage data: image attributes, source unit (pixels), source rectangle, destination. + let draw = |sx: f32| { + let floats = [sx, 0.0, 1.0, 1.0, 0.0, 0.0, 9.0, 9.0].map(f32::to_le_bytes).concat(); + [0u32.to_le_bytes().to_vec(), 2u32.to_le_bytes().to_vec(), floats].concat() + }; + assert!(plus.image(&mut cv, 0, Bytes(&draw(10.0))).is_none()); + assert_eq!(cv.dropped_images, 0, "a source rectangle beside the pixels draws nothing"); + assert!(plus.image(&mut cv, 0, Bytes(&draw(0.0))).is_none()); + assert_eq!(cv.dropped_images, 1); + let texture = Fill::Texture { img: Arc::new(img()), wrap: 0, xf: IDENTITY }; + plus.store(1, Some(Obj::Brush(texture.clone())), crate::MAX_BYTES); + assert!(plus.objects[1].is_none()); + assert_eq!(plus.lost_brushes, 1); + plus.store(1, Some(Obj::Brush(texture)), 0); + assert!(plus.objects[1].is_some()); + assert_eq!(plus.lost_brushes, 1); + } + #[test] fn pieces_of_a_continued_object_count_against_the_shared_budget() { let (mut plus, mut cv) = (Plus::new(), Canvas::new()); diff --git a/crates/metafile/src/geom.rs b/crates/metafile/src/geom.rs index 0c2b772cf..d69a7da40 100644 --- a/crates/metafile/src/geom.rs +++ b/crates/metafile/src/geom.rs @@ -13,6 +13,33 @@ pub(crate) enum Op { Z, } +/// Whether a path can enclose some area: one of its figures has points (curve control points +/// included) that do not all lie on one line. +pub(crate) fn encloses_area(ops: &[Op]) -> bool { + // The figure's first point and its first point elsewhere. + let (mut first, mut second): (Option

, Option

) = (None, None); + for op in ops { + let pts = match *op { + Op::M(p) => { + (first, second) = (None, None); + [Some(p), None, None] + } + Op::L(p) => [Some(p), None, None], + Op::C(a, b, c) => [Some(a), Some(b), Some(c)], + Op::Z => [None; 3], + }; + for c in pts.into_iter().flatten() { + match (first, second) { + (None, _) => first = Some(c), + (Some(a), None) if c != a => second = Some(c), + (Some(a), Some(b)) if ((b.0 - a.0) * (c.1 - a.1) - (b.1 - a.1) * (c.0 - a.0)).abs() > 0.0 => return true, + _ => {} + } + } + } + false +} + pub(crate) fn rect(l: f64, t: f64, r: f64, b: f64) -> Vec { vec![Op::M((l, t)), Op::L((r, t)), Op::L((r, b)), Op::L((l, b)), Op::Z] } diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 2aa739fc6..6a2338a78 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -14,7 +14,8 @@ //! bounds-checked and every count is capped; hostile input yields a shorter picture or an [`Error`], //! never a panic. Records follow MS-WMF, MS-EMF and MS-EMFPLUS; the README lists the records read //! and the limits. Records of a type the reader does not know are counted in -//! [`Picture::skipped_records`]. +//! [`Picture::skipped_records`]; a parse stopped at a limit, images left out, clips not applied and +//! raster operations not played are reported in the other `Picture` fields. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] @@ -69,8 +70,38 @@ pub struct Picture { pub height: f32, pub items: Vec, /// Records of a type the reader does not know (neither drawn nor known to change nothing that - /// is kept). A caller can tell its user that part of the file was not read. + /// is kept). A caller can tell its user that part of the file was not read. An EMF+ metafile + /// image adds the records skipped inside it once, the first time it is drawn. pub skipped_records: u32, + /// The parse stopped at one of the reader's limits (items, bytes kept, `SAVEDC` depth, clip + /// paths; see the README) before the end of the file, or a metafile image drawn inside it did: + /// the picture holds what came before. The limits that cut one path, string, region or dash + /// pattern short do not set it. + pub truncated: bool, + /// Images the file asks to draw that the reader did not read: bitmaps past a size, byte or decode + /// limit or in a form the reader cannot decode, EMF+ metafile images that do not parse or are + /// nested deeper than 3 levels, and pattern or texture brushes whose bitmap was not read (counted + /// when the brush is created). An image whose source rectangle selects none of its pixels, or that + /// has no pixels, draws nothing and is not counted. Bitmaps left out while clipping to an EMF+ + /// clip (see the README's limits) are not counted here. + pub dropped_images: u32, + /// Clip changes the reader does not apply as the file asks: GDI clip paths selected with + /// `RGN_OR`, `RGN_XOR` or `RGN_DIFF` and EMF+ clips combined with XOR, exclude or complement, + /// which leave the clip as it was; EMF+ unions, drawn as the rectangle around both areas; and + /// EMF+ clips whose area stands in for the one the file gives (a path that is not one convex + /// figure, drawn as its rectangle, or a region built with XOR, exclude or complement). + /// Drawing after them may show more or less than the file asks. A change that cannot alter the + /// clip is not counted: an area whose figures all lie on a line (except in an EMF+ complement of + /// a clip that encloses some area, which would empty it), a GDI `RGN_OR` on a clip that is still + /// the whole surface, and an EMF+ union whose rectangle is no larger than the union. The reader + /// does not work out whether a GDI path changes a clip that is already set, so such a path is + /// counted. + pub ignored_clips: u32, + /// Raster operations the reader does not play: bitmaps drawn as plain copies of their source + /// because their operation is not `SRCCOPY`, `SRCAND`, `SRCPAINT` or `SRCINVERT`, and operations + /// that take no source bitmap (such as `DSTINVERT` or `PATINVERT`) and are left out. `PATCOPY`, + /// `BLACKNESS` and `WHITENESS` are played. + pub unplayed_raster_ops: u32, } /// How the ends of an open stroke and of its dashes are drawn (`PS_ENDCAP_*`). @@ -228,10 +259,10 @@ pub(crate) fn parse_nested(bytes: &[u8]) -> Result { } else { return Err(Error::NotMetafile); }; - let skipped = cv.skipped; - let mut pic = build(cv.items, frame); - pic.skipped_records = skipped; - Ok(pic) + let (skipped, truncated) = (cv.skipped, cv.full() || cv.truncated_inside); + let (dropped_images, ignored_clips, unplayed_raster_ops) = (cv.dropped_images, cv.ignored_clips, cv.unplayed_raster_ops); + let pic = build(cv.items, frame); + Ok(Picture { skipped_records: skipped, truncated, dropped_images, ignored_clips, unplayed_raster_ops, ..pic }) } /// True when the bytes start like a WMF (placeable or plain header) or an EMF. @@ -367,7 +398,7 @@ fn build(raw: Vec, frame: Option) -> Picture { } }); let items = items.collect(); - Picture { width: f(size.0).unwrap_or(0.0), height: f(size.1).unwrap_or(0.0), items, skipped_records: 0 } + Picture { width: f(size.0).unwrap_or(0.0), height: f(size.1).unwrap_or(0.0), items, ..Picture::default() } } /// An item's clip in picture units: the region rectangles and the clip paths. diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index 661f319d6..fa1cbb33a 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -299,6 +299,9 @@ fn item_cap_stops_the_parse_and_keeps_the_rest() { let recs: Vec> = (0..MAX_ITEMS + 10).map(|_| rect.clone()).collect(); let p = parse(&wmf(&recs, None)).unwrap(); assert_eq!(p.items.len(), MAX_ITEMS); + assert!(p.truncated); + let p = parse(&wmf(&recs[..MAX_ITEMS], None)).unwrap(); + assert_eq!((p.items.len(), p.truncated), (MAX_ITEMS, false), "exactly the cap is not past it"); } #[test] @@ -906,7 +909,7 @@ fn place_fits_the_frame_scales_strokes_and_drops_far_paths() { clips: Vec::new(), }, ], - skipped_records: 0, + ..Default::default() }; let placed = pic.place(kurbo::Rect::new(0.0, 0.0, 200.0, 100.0), [0.0; 4]); assert_eq!(placed.len(), 1); @@ -931,7 +934,7 @@ fn a_huge_pen_is_held_to_what_covers_the_frame() { region: None, clips: Vec::new(), }], - skipped_records: 0, + ..Default::default() }; match pic.place(kurbo::Rect::new(0.0, 0.0, 200.0, 100.0), [0.0; 4]).first() { Some(crate::PlacedItem::Path { stroke, .. }) => stroke.map(|s| s.1), @@ -950,7 +953,7 @@ fn a_huge_pen_is_held_to_what_covers_the_frame() { fn crop_window_keeps_a_sliver_and_stays_finite() { let [x, y, w, h] = crate::crop_window([0.0, 0.51771, 0.0, 0.45485]); assert!(x == 0.0 && w == 1.0 && (y - 0.51771).abs() < 1e-6 && (h - 0.02744).abs() < 1e-5, "{y} {h}"); - let pic = crate::Picture { width: 100.0, height: 1000.0, items: Vec::new(), skipped_records: 0 }; + let pic = crate::Picture { width: 100.0, height: 1000.0, items: Vec::new(), ..Default::default() }; let tf = pic.fit(kurbo::Rect::new(0.0, 0.0, 100.0, 27.44), [0.0, 0.51771, 0.0, 0.45485]).unwrap(); // The kept band of the source (517.71..545.15) is the frame (0..27.44). let top = tf * kurbo::Point::new(0.0, 517.71); @@ -979,7 +982,7 @@ fn crop_window_with_negative_sides_pads_the_source() { let [x, _, w, _] = crate::crop_window([f32::MIN, 0.0, -1e9, 0.0]); assert!(x == -100.0 && w == 201.0, "{x} {w}"); // The source sits in the middle half of the frame. - let pic = crate::Picture { width: 100.0, height: 50.0, items: Vec::new(), skipped_records: 0 }; + let pic = crate::Picture { width: 100.0, height: 50.0, items: Vec::new(), ..Default::default() }; let tf = pic.fit(kurbo::Rect::new(0.0, 0.0, 100.0, 100.0), [0.0, -0.5, 0.0, -0.5]).unwrap(); let (top, bottom) = (tf * kurbo::Point::new(0.0, 0.0), tf * kurbo::Point::new(100.0, 50.0)); assert!((top.y - 25.0).abs() < 1e-9 && (bottom.y - 75.0).abs() < 1e-9 && (bottom.x - 100.0).abs() < 1e-9, "{top:?} {bottom:?}"); @@ -1012,7 +1015,7 @@ fn the_narrowest_crop_on_the_largest_frame_keeps_its_content() { clips: Vec::new(), }, ], - skipped_records: 0, + ..Default::default() }; let frame = kurbo::Rect::new(1584.0, 1584.0, 5584.0, 5584.0); // The last sliver, the first sliver, and sides that overlap. @@ -1039,7 +1042,7 @@ fn place_counts_the_items_own_clip_region_before_keeping_it() { let region = || Some(vec![[0.0, 0.0, 50.0, 25.0], [10.0, 10.0, 20.0, 20.0]]); let frame = kurbo::Rect::new(0.0, 0.0, 100.0, 50.0); let placed = |second: Item| { - let pic = crate::Picture { width: 100.0, height: 50.0, items: vec![path(segs.clone(), None), second], skipped_records: 0 }; + let pic = crate::Picture { width: 100.0, height: 50.0, items: vec![path(segs.clone(), None), second], ..Default::default() }; pic.place(frame, [0.0; 4]).len() }; let small = vec![Seg::Move(0.0, 0.0), Seg::Line(1.0, 1.0)]; @@ -1070,7 +1073,7 @@ fn place_expands_a_clip_region_once_for_the_items_that_share_it() { region: Some(region.clone()), clips: Vec::new(), }; - let pic = crate::Picture { width: 100.0, height: 50.0, items: (0..2000).map(|_| item()).collect(), skipped_records: 0 }; + let pic = crate::Picture { width: 100.0, height: 50.0, items: (0..2000).map(|_| item()).collect(), ..Default::default() }; let placed = pic.place(kurbo::Rect::new(0.0, 0.0, 100.0, 50.0), [0.0; 4]); assert_eq!(placed.len(), 2000); let regions: Vec<_> = placed @@ -1096,7 +1099,7 @@ fn place_keeps_only_finite_bounded_bitmaps_with_area() { bitmap([0.0, 0.0, f32::INFINITY, 10.0]), bitmap([10.0, 5.0, 10.0, 10.0]), ], - skipped_records: 0, + ..Default::default() }; let placed = pic.place(kurbo::Rect::new(0.0, 0.0, 200.0, 100.0), [0.0; 4]); assert_eq!(placed.len(), 1); @@ -1249,7 +1252,7 @@ fn take_pixels_returns_only_drawable_bitmaps() { clips: Vec::new(), }; assert_eq!(path.take_pixels(), None); - let pic = |width: f32, height: f32| crate::Picture { width, height, items: Vec::new(), skipped_records: 0 }; + let pic = |width: f32, height: f32| crate::Picture { width, height, items: Vec::new(), ..Default::default() }; assert!(pic(1.0, 2.0).has_size()); assert!(!pic(0.0, 2.0).has_size() && !pic(f32::NAN, 2.0).has_size() && !pic(1.0, f32::INFINITY).has_size()); } @@ -1908,6 +1911,7 @@ fn pattern_brush_pixels_count_against_the_byte_budget() { recs.push(wrec(0x041B, &cat(vec![h16(9), h16(9), h16(0), h16(0)]))); let p = wmf200(&recs); assert!(p.items.is_empty(), "the parse stopped at the budget: {:?}", p.items.len()); + assert!(p.truncated); } fn item_region(item: &Item) -> Option<&[[f32; 4]]> { diff --git a/crates/metafile/src/tests/limits.rs b/crates/metafile/src/tests/limits.rs index 16f995d9e..821ee52d6 100644 --- a/crates/metafile/src/tests/limits.rs +++ b/crates/metafile/src/tests/limits.rs @@ -60,7 +60,7 @@ fn placing_stops_at_the_element_cap() { region: None, clips: Vec::new(), }; - let pic = crate::Picture { width: 10.0, height: 10.0, items: (0..8).map(|_| path()).collect(), skipped_records: 0 }; + let pic = crate::Picture { width: 10.0, height: 10.0, items: (0..8).map(|_| path()).collect(), ..Default::default() }; let placed = pic.place(kurbo::Rect::new(0.0, 0.0, 10.0, 10.0), [0.0; 4]); // Five paths of 100,001 elements reach the 500,000 cap; the rest are left out. assert_eq!(placed.len(), 5); @@ -102,6 +102,85 @@ fn metafiles_nest_only_so_deep() { assert_eq!(nested(emfplus::MAX_NESTING + 1), 0, "the innermost picture is not read"); } +#[test] +fn emfplus_images_that_are_not_read_are_counted() { + let square = || emf(&[erec(43, &cat(vec![e32(0), e32(0), e32(10), e32(10)]))], [0; 4], [0; 4]); + let nested = |levels: usize| { + let mut file = square(); + for _ in 0..levels { + file = wrap(file); + } + parse(&file).unwrap() + }; + assert_eq!(nested(emfplus::MAX_NESTING).dropped_images, 0); + assert_eq!(nested(emfplus::MAX_NESTING + 1).dropped_images, 1, "the picture past the nesting cap"); + // A bitmap image object whose pixels run past the record. + let obj = cat(vec![h32(0xDBC0_1002), h32(1), h32(4), h32(4), h32(16), h32(0x0026_200A), h32(0), vec![1, 2, 3]]); + let file = emf(&[plus_comment(&[plus_header(false), prec(0x4008, 0x0500 | 2, &obj), draw_image(2, [0.0, 0.0, 40.0, 20.0])])], [0; 4], [0; 4]); + assert_eq!(parse(&file).unwrap().dropped_images, 1); + // The same object drawn from a source rectangle beside its 4 x 4 pixels selects none of them. + let beside = prec(0x401A, 2, &cat(vec![h32(0), h32(2), f32s(&[50.0, 0.0, 1.0, 1.0]), f32s(&[0.0, 0.0, 40.0, 20.0])])); + let file = emf(&[plus_comment(&[plus_header(false), prec(0x4008, 0x0500 | 2, &obj), beside])], [0; 4], [0; 4]); + assert_eq!(parse(&file).unwrap().dropped_images, 0); + // What a nested picture leaves out is reported by the file that draws it. + let inner = emf(&[stretch_bad_png(), erec(43, &cat(vec![e32(0), e32(0), e32(10), e32(10)]))], [0; 4], [0; 4]); + assert_eq!(parse(&inner).unwrap().dropped_images, 1); + assert_eq!(parse(&wrap(inner)).unwrap().dropped_images, 1); +} + +#[test] +fn a_metafile_image_adds_its_counts_once_per_object() { + // A square and one record of a type the reader does not know. + let inner = emf(&[erec(43, &cat(vec![e32(0), e32(0), e32(10), e32(10)])), erec(200, &[0; 8])], [0; 4], [0; 4]); + let obj = cat(vec![h32(0xDBC0_1002), h32(2), h32(3), h32(inner.len() as u32), inner]); + let draw = || draw_image(3, [0.0, 0.0, 40.0, 20.0]); + let store = || prec(0x4008, 0x0500 | 3, &obj); + let skipped = |recs: Vec>| { + let mut all = vec![plus_header(false)]; + all.extend(recs); + let p = parse(&emf(&[plus_comment(&all)], [0; 4], [0; 4])).unwrap(); + (p.items.len(), p.skipped_records) + }; + assert_eq!(skipped(vec![store()]), (0, 0), "an image that is never drawn"); + let cut = prec(0x401A, 3, &cat(vec![h32(0), h32(2), f32s(&[0.0, 0.0, 2.0, 2.0])])); + assert_eq!(skipped(vec![store(), cut]), (0, 0), "a draw record without its destination"); + assert_eq!(skipped(vec![store(), draw()]), (1, 1)); + assert_eq!(skipped(vec![store(), draw(), draw(), draw()]), (3, 1), "drawn three times, counted once"); + assert_eq!(skipped(vec![store(), draw(), store(), draw()]), (2, 2), "stored again, counted again"); +} + +#[test] +fn a_nested_picture_stopped_at_a_limit_truncates_the_file_that_draws_it() { + // The square comes first, so the inner picture has a size and is drawn. + let inner = |saves: usize| { + let mut recs = vec![erec(43, &cat(vec![e32(0), e32(0), e32(10), e32(10)]))]; + recs.extend(vec![erec(33, &[]); saves]); + emf(&recs, [0; 4], [0; 4]) + }; + assert!(!parse(&wrap(inner(crate::MAX_STACK))).unwrap().truncated); + assert!(parse(&inner(crate::MAX_STACK + 1)).unwrap().truncated); + let p = parse(&wrap(inner(crate::MAX_STACK + 1))).unwrap(); + assert!(p.truncated && !p.items.is_empty()); + // An inner picture that stops before it draws anything has no size and draws nothing, and still + // reports that it stopped. + let empty = emf(&vec![erec(33, &[]); crate::MAX_STACK + 1], [0; 4], [0; 4]); + let p = parse(&wrap(empty)).unwrap(); + assert!(p.truncated && p.items.is_empty()); +} + +/// EMR_STRETCHDIBITS of a 1 x 1 BI_PNG bitmap whose bits are no image. +fn stretch_bad_png() -> Vec { + let bits = [1u8, 2, 3, 4]; + let mut info = info_header(1, 1, 32, bits.len() as u32); + info[16..20].copy_from_slice(&5u32.to_le_bytes()); + let mut payload = vec![0u8; 16]; + let fields = [0, 0, 0, 0, 1, 1, 80, 40, 120, bits.len() as i32, 0, 0x00CC_0020, 10, 10]; + payload.extend(cat(fields.iter().map(|v| e32(*v)).collect())); + payload.extend(info); + payload.extend(bits); + erec(81, &payload) +} + #[test] fn emfplus_object_ids_past_the_table_are_ignored() { let draw = |id: u16| { diff --git a/crates/metafile/src/tests/model.rs b/crates/metafile/src/tests/model.rs index ab6f87ce5..73186cb4c 100644 --- a/crates/metafile/src/tests/model.rs +++ b/crates/metafile/src/tests/model.rs @@ -400,6 +400,267 @@ fn a_compressed_dib_over_the_side_cap_is_refused_before_decoding() { assert!(parse_emf(&[stretch_dibits(crate::MAX_BITMAP_SIDE as i32 + 1, 1, 5, &wide)]).items.is_empty()); } +#[test] +fn bitmaps_that_are_not_read_are_counted() { + let dropped = |recs: &[Vec]| { + let p = parse_emf(recs); + (p.items.len(), p.dropped_images) + }; + assert_eq!(dropped(&[stretch_dibits(3, 1, 5, &png(3, 1, [1, 2, 3, 255]))]), (1, 0), "a bitmap that is drawn"); + assert_eq!(dropped(&[stretch_dibits(3, 1, 5, &[1, 2, 3, 4])]), (0, 1), "bits that are no image"); + let wide = png(crate::MAX_BITMAP_SIDE + 1, 1, [0; 4]); + assert_eq!(dropped(&[stretch_dibits(crate::MAX_BITMAP_SIDE as i32 + 1, 1, 5, &wide)]), (0, 1), "a side past the cap"); + // A source rectangle beside the bitmap selects none of its pixels: nothing to draw, nothing lost. + let mut beside = stretch_dibits(1, 1, 0, &[1, 2, 3, 255]); + beside[32..36].copy_from_slice(&50i32.to_le_bytes()); + assert_eq!(dropped(&[beside.clone()]), (0, 0)); + // The same for a compression the decoder does not read (BI_RLE8), and counted when it is inside. + beside[80 + 16..80 + 20].copy_from_slice(&1u32.to_le_bytes()); + assert_eq!(dropped(&[beside.clone()]), (0, 0)); + beside[32..36].copy_from_slice(&0i32.to_le_bytes()); + assert_eq!(dropped(&[beside]), (0, 1)); + // A BI_PNG header that says 10 x 1 over a 1 x 1 PNG: the PNG is what is cropped. + let mut png_dib = stretch_dibits(10, 1, 5, &png(1, 1, [1, 2, 3, 255])); + png_dib[32..36].copy_from_slice(&5i32.to_le_bytes()); + png_dib[40..44].copy_from_slice(&1i32.to_le_bytes()); + assert_eq!(dropped(&[png_dib]), (0, 0)); + // A STRETCHDIBITS without bits is not a bitmap. + assert_eq!(dropped(&[stretch_dibits(1, 1, 0, &[])]), (0, 0)); + // WMF: a DIB of a depth the core header does not have. + let core16 = cat(vec![h32(12), h16(2), h16(2), h16(1), h16(16)]); + let p = parse(&stretch_dib(core16)).unwrap(); + assert_eq!((p.items.len(), p.dropped_images), (0, 1)); + let p = parse(&stretch_dib(dib24_bottom_up())).unwrap(); + assert_eq!((p.items.len(), p.dropped_images), (1, 0)); + // WMF: BI_RLE8, which the decoder does not read, from beside the bitmap and from inside it. + let mut file = stretch_dib(dib24_bottom_up()); + // The 18-byte WMF header, then the record: the DIB starts 28 bytes in, after the source x at 18. + let at = 18 + 28; + assert_eq!(file[at..at + 4], 40u32.to_le_bytes()); + file[at + 16..at + 20].copy_from_slice(&1u32.to_le_bytes()); + let x_src = at - 10; + file[x_src..x_src + 2].copy_from_slice(&50i16.to_le_bytes()); + assert_eq!(parse(&file).unwrap().dropped_images, 0); + file[x_src..x_src + 2].copy_from_slice(&0i16.to_le_bytes()); + assert_eq!(parse(&file).unwrap().dropped_images, 1); + // A header that gives the bitmap no pixels draws nothing. + assert_eq!(dropped(&[stretch_dibits(0, 1, 0, &[1, 2, 3, 4])]), (0, 0)); + let empty = cat(vec![h32(12), h16(0), h16(2), h16(1), h16(16)]); + assert_eq!(parse(&stretch_dib(empty)).unwrap().dropped_images, 0); +} + +/// EMR_CREATEDIBPATTERNBRUSHPT in slot 1 with the DIB `info` and `bits`. +fn dib_pattern_brush(info: &[u8], bits: &[u8]) -> Vec { + let fields = [1, 0, 32, info.len() as u32, 32 + info.len() as u32, bits.len() as u32]; + erec(94, &cat(vec![fields.iter().flat_map(|v| v.to_le_bytes()).collect(), info.to_vec(), bits.to_vec()])) +} + +#[test] +fn pattern_and_texture_brushes_that_are_not_read_are_counted() { + let dib = dib24_bottom_up(); + let (info, bits) = dib.split_at(40); + assert_eq!(parse_emf(&[dib_pattern_brush(info, bits)]).dropped_images, 0); + // BI_RLE8, which the decoder does not read. + let mut rle = info_header(2, 2, 8, 4); + rle[16..20].copy_from_slice(&1u32.to_le_bytes()); + assert_eq!(parse_emf(&[dib_pattern_brush(&rle, &[0; 4])]).dropped_images, 1); + // A tile past the side cap. + let wide = info_header(crate::canvas::MAX_TILE_SIDE as i32 + 1, 1, 24, 0); + let wide_bits = vec![0u8; (crate::canvas::MAX_TILE_SIDE + 1) * 3 + 4]; + assert_eq!(parse_emf(&[dib_pattern_brush(&wide, &wide_bits)]).dropped_images, 1); + // A header with no pixels. + assert_eq!(parse_emf(&[dib_pattern_brush(&info_header(0, 2, 24, 0), &[0; 4])]).dropped_images, 0); + // WMF DIBCREATEPATTERNBRUSH. + let wmf_brush = |dib: Vec| parse(&wmf(&[wrec(0x0142, &cat(vec![h16(5), h16(0), dib]))], None)).unwrap().dropped_images; + assert_eq!(wmf_brush(dib24_bottom_up()), 0); + assert_eq!(wmf_brush(cat(vec![rle.clone(), vec![0; 4]])), 1); + assert_eq!(wmf_brush(info_header(0, 2, 24, 0)), 0); + // An EMF+ texture brush whose bitmap runs past the record, one with no pixels, and one that is read. + let texture = |image: Vec| { + let brush = cat(vec![h32(0xDBC0_1002), h32(2), h32(0), h32(0), image]); + emf(&[plus_comment(&[plus_header(false), prec(0x4008, 0x0100 | 5, &brush)])], [0; 4], [0; 4]) + }; + let short = cat(vec![h32(0xDBC0_1002), h32(1), h32(4), h32(4), h32(16), h32(0x0026_200A), h32(0), vec![1, 2, 3]]); + assert_eq!(parse(&texture(short)).unwrap().dropped_images, 1); + let none = cat(vec![h32(0xDBC0_1002), h32(1), h32(0), h32(4), h32(16), h32(0x0026_200A), h32(0)]); + assert_eq!(parse(&texture(none)).unwrap().dropped_images, 0); + assert_eq!(parse(&texture(bitmap_2x2())).unwrap().dropped_images, 0); +} + +#[test] +fn an_emfplus_image_refused_by_a_limit_is_counted_unless_the_crop_misses_it() { + // A PNG one pixel wider than the compressed-side cap: its header is read, its pixels are not. + let side = crate::dib::MAX_COMPRESSED_SIDE; + let wide = png(side + 1, 1, [0; 4]); + let obj = cat(vec![h32(0xDBC0_1002), h32(1), h32(0), h32(0), h32(0), h32(0), h32(1), wide]); + let drawn = |sx: f32| { + let draw = prec(0x401A, 2, &cat(vec![h32(0), h32(2), f32s(&[sx, 0.0, 1.0, 1.0]), f32s(&[0.0, 0.0, 40.0, 20.0])])); + let p = parse(&emf(&[plus_comment(&[plus_header(false), prec(0x4008, 0x0500 | 2, &obj), draw])], [0; 4], [0; 4])).unwrap(); + (p.items.len(), p.dropped_images) + }; + assert_eq!(drawn(0.0), (0, 1)); + assert_eq!(drawn(side as f32 + 10.0), (0, 0), "a source rectangle past the right edge"); +} + +#[test] +fn raster_operations_that_are_not_played_are_counted() { + let copied = |rop: u32| { + let mut rec = stretch_dibits(1, 1, 0, &[10, 20, 30, 255]); + rec[68..72].copy_from_slice(&rop.to_le_bytes()); + let p = parse_emf(&[rec]); + (p.items.len(), p.unplayed_raster_ops) + }; + // SRCCOPY, SRCAND, SRCPAINT and SRCINVERT are played. + for rop in [0x00CC_0020, 0x0088_00C6, 0x00EE_0086, 0x0066_0046] { + assert_eq!(copied(rop), (1, 0), "{rop:#x}"); + } + // NOTSRCCOPY and MERGEPAINT are drawn as the source. + assert_eq!(copied(0x0033_0008), (1, 1)); + assert_eq!(copied(0x00BB_0226), (1, 1)); + // A bitmap that is clipped away is not drawn, so nothing is copied. + let mut rec = stretch_dibits(1, 1, 0, &[10, 20, 30, 255]); + rec[68..72].copy_from_slice(&0x0033_0008u32.to_le_bytes()); + let recs = [erec(59, &[]), erec(60, &[]), erec(67, &h32(1)), rec]; + assert_eq!(parse_emf(&recs).unplayed_raster_ops, 0); + // WMF STRETCHDIB with NOTSRCCOPY. + let mut file = stretch_dib(dib24_bottom_up()); + let at = file.windows(4).position(|w| w == 0x00CC_0020u32.to_le_bytes()).unwrap(); + file[at..at + 4].copy_from_slice(&0x0033_0008u32.to_le_bytes()); + assert_eq!(parse(&file).unwrap().unplayed_raster_ops, 1); + // Operations without a source: BLACKNESS is played; DSTINVERT and PATINVERT are left out. + let bitblt = |rop: u32| { + let mut payload = vec![0u8; 92]; + payload[16..32].copy_from_slice(&cat(vec![e32(0), e32(0), e32(10), e32(10)])); + payload[32..36].copy_from_slice(&rop.to_le_bytes()); + let p = parse_emf(&[erec(76, &payload)]); + (p.items.len(), p.unplayed_raster_ops) + }; + assert_eq!(bitblt(0x0000_0042), (1, 0)); + assert_eq!(bitblt(0x0055_0009), (0, 1)); + assert_eq!(bitblt(0x005A_0049), (0, 1)); + assert_eq!(bitblt(0x00CC_0020), (0, 0), "a copy without a bitmap draws nothing and leaves nothing out"); + // STRETCHDIBITS with an operation without a source fills the destination, with or without bits. + assert_eq!(copied(0x0000_0042), (1, 0), "BLACKNESS with bits"); + assert_eq!(copied(0x0055_0009), (0, 1), "DSTINVERT with bits"); + let mut bare = stretch_dibits(1, 1, 0, &[]); + bare[68..72].copy_from_slice(&0x00FF_0062u32.to_le_bytes()); + assert_eq!(parse_emf(&[bare]).items.len(), 1, "WHITENESS without bits"); + // WMF STRETCHDIB with BLACKNESS fills instead of drawing the bitmap. + let mut file = stretch_dib(dib24_bottom_up()); + let at = file.windows(4).position(|w| w == 0x00CC_0020u32.to_le_bytes()).unwrap(); + file[at..at + 4].copy_from_slice(&0x0000_0042u32.to_le_bytes()); + let p = parse(&file).unwrap(); + assert!(matches!(p.items.as_slice(), [Item::Path { fill: Some([0, 0, 0, 255]), .. }]), "{:?}", p.items); + let patblt = |rop: u32| { + let p = parse(&wmf(&[wrec(0x061D, &cat(vec![h32(rop), h16(10), h16(10), h16(0), h16(0)]))], None)).unwrap(); + (p.items.len(), p.unplayed_raster_ops) + }; + assert_eq!(patblt(0x00FF_0062), (1, 0)); + assert_eq!(patblt(0x0055_0009), (0, 1)); + assert!(!crate::dib::uses_source(0x00F0_0021) && crate::dib::uses_source(0x00CC_0020) && crate::dib::uses_source(0x00BB_0226)); +} + +#[test] +fn clips_that_are_not_applied_are_counted() { + let ignored = |recs: Vec>| parse_emf(&recs).ignored_clips; + let after = |mode: u32| { + let mut recs = clip_to_rect(0, 0, 10, 10, mode); + recs.push(rect(0, 0, 100, 100)); + recs + }; + assert_eq!(ignored(after(1)), 0, "RGN_AND is applied"); + assert_eq!(ignored(after(5)), 0, "RGN_COPY is applied"); + assert_eq!(ignored(after(3)), 1, "RGN_XOR"); + assert_eq!(ignored(after(4)), 1, "RGN_DIFF"); + assert_eq!(ignored(after(2)), 0, "RGN_OR on the whole surface leaves the whole surface"); + assert_eq!(ignored(after(0)), 0, "an invalid mode selects nothing"); + let mut recs = clip_to_rect(0, 0, 50, 50, 1); + recs.extend(after(2)); + assert_eq!(ignored(recs), 1, "RGN_OR on a clip path is counted, whether or not it widens it"); + let recs = vec![erec(59, &[]), erec(60, &[]), erec(67, &h32(4)), rect(0, 0, 100, 100)]; + assert_eq!(ignored(recs), 0, "an empty path cuts nothing"); + let line = vec![erec(59, &[]), move_to(0, 0), line_to(50, 50), move_to(60, 0), erec(60, &[]), erec(67, &h32(3)), rect(0, 0, 100, 100)]; + assert_eq!(ignored(line), 0, "a path on one line encloses nothing"); +} + +#[test] +fn emfplus_clips_that_are_not_applied_are_counted() { + // The combine mode is in bits 8 to 11 of the flags. + let plus = |recs: Vec>| { + let mut all = vec![plus_header(false)]; + all.extend(recs); + parse(&emf(&[plus_comment(&all)], [0; 4], [0; 4])).unwrap().ignored_clips + }; + let clip = |mode: u16, r: [f32; 4]| prec(0x4032, mode << 8, &f32s(&r)); + for mode in 3..=5 { + assert_eq!(plus(vec![clip(0, [0.0, 0.0, 50.0, 50.0]), clip(mode, [10.0, 10.0, 10.0, 10.0])]), 1, "mode {mode}"); + assert_eq!(plus(vec![clip(mode, [10.0, 10.0, 0.0, 10.0])]), u32::from(mode == 5), "mode {mode} with no area"); + let empty_on_clip = vec![clip(0, [0.0, 0.0, 50.0, 50.0]), clip(mode, [10.0, 10.0, 0.0, 10.0])]; + assert_eq!(plus(empty_on_clip), u32::from(mode == 5), "mode {mode} with no area on a clip"); + } + assert_eq!(plus(vec![clip(0, [0.0, 0.0, 50.0, 50.0]), clip(2, [10.0, 10.0, 10.0, 10.0])]), 0, "a union inside the clip"); + assert_eq!(plus(vec![clip(0, [0.0, 0.0, 50.0, 50.0]), clip(2, [60.0, 60.0, 10.0, 10.0])]), 1, "a union apart from it"); + assert_eq!(plus(vec![clip(2, [60.0, 60.0, 10.0, 10.0])]), 0, "a union with no clip set"); + assert_eq!(plus(vec![clip(0, [0.0, 0.0, 10.0, 10.0]), clip(2, [10.0, 0.0, 10.0, 10.0])]), 0, "a union that is its rectangle"); + // A region whose area is a stand-in: an XOR node, unless its right area is empty. + let node = |r: [f32; 4]| cat(vec![h32(0x1000_0000), f32s(&r)]); + let region = |mode: u32, right: Vec| { + let obj = cat(vec![h32(0xDBC0_1002), h32(2), h32(mode), node([0.0, 0.0, 30.0, 30.0]), right]); + vec![prec(0x4008, 0x0400 | 6, &obj), prec(0x4034, 6, &[])] + }; + assert_eq!(plus(region(3, node([10.0, 10.0, 90.0, 90.0]))), 1, "an XOR region"); + assert_eq!(plus(region(3, h32(0x1000_0002))), 0, "XOR with an empty region"); + let empty_pair = cat(vec![h32(0xDBC0_1002), h32(3), h32(5), h32(0x1000_0002), h32(0x1000_0002)]); + assert_eq!(plus(vec![prec(0x4008, 0x0400 | 6, &empty_pair), prec(0x4034, 6, &[])]), 0, "the complement of two empty regions"); + let cut_empty = vec![clip(0, [0.0, 0.0, 0.0, 10.0]), clip(4, [0.0, 0.0, 10.0, 10.0])]; + assert_eq!(plus(cut_empty), 0, "an exclude from an empty clip"); + assert_eq!(plus(region(1, node([10.0, 10.0, 90.0, 90.0]))), 0, "an intersection"); + assert_eq!(plus(region(2, node([30.0, 0.0, 30.0, 30.0]))), 0, "a union that is its rectangle"); + assert_eq!(plus(region(2, node([40.0, 40.0, 30.0, 30.0]))), 1, "a union drawn as a larger rectangle"); + // A clip path that is not one convex figure is drawn as its rectangle. + let path = |pts: &[f32], types: Vec| { + let obj = cat(vec![h32(0xDBC0_1002), h32(types.len() as u32), h32(0), f32s(pts), types]); + vec![prec(0x4008, 0x0300 | 9, &obj), prec(0x4033, 9, &[])] + }; + assert_eq!(plus(path(&[0.0, 50.0, 50.0, 0.0, 100.0, 50.0, 50.0, 100.0], vec![0, 1, 1, 0x81])), 0, "a convex path"); + let l_shape = [0.0, 0.0, 20.0, 0.0, 20.0, 10.0, 10.0, 10.0, 10.0, 20.0, 0.0, 20.0]; + assert_eq!(plus(path(&l_shape, vec![0, 1, 1, 1, 1, 0x81])), 1, "an L shape"); + // A stand-in that cannot show: intersected with an empty clip, or added to an unlimited one. + let combined = |mode: u16, first: Vec>| { + let mut recs = first; + recs.extend(path(&l_shape, vec![0, 1, 1, 1, 1, 0x81])); + let last = recs.len() - 1; + recs[last] = prec(0x4033, (mode << 8) | 9, &[]); + plus(recs) + }; + assert_eq!(combined(1, vec![clip(0, [0.0, 0.0, 0.0, 10.0])]), 0, "an L shape inside an empty clip"); + assert_eq!(combined(2, Vec::new()), 0, "an L shape added to no clip"); + assert_eq!(combined(1, Vec::new()), 1, "an L shape inside no clip"); + let inf = h32(0x1000_0003); + let xor = cat(vec![h32(3), node([0.0, 0.0, 30.0, 30.0]), node([10.0, 10.0, 90.0, 90.0])]); + let obj = cat(vec![h32(0xDBC0_1002), h32(4), h32(2), xor, inf]); + assert_eq!(plus(vec![prec(0x4008, 0x0400 | 6, &obj), prec(0x4034, 6, &[])]), 0, "an XOR region added to an unlimited one"); + assert_eq!(plus(vec![clip(1, [0.0, 0.0, 50.0, 50.0]), clip(0, [1.0, 1.0, 5.0, 5.0])]), 0, "intersect and replace are applied"); +} + +#[test] +fn a_parse_stopped_at_a_limit_is_truncated() { + assert!(!parse_emf(&[rect(0, 0, 10, 10)]).truncated); + // SAVEDC past the stack depth. + let mut recs = vec![erec(33, &[]); crate::MAX_STACK + 1]; + recs.push(rect(0, 0, 10, 10)); + let p = parse_emf(&recs); + assert!(p.truncated && p.items.is_empty()); + let recs = vec![erec(33, &[]); crate::MAX_STACK]; + assert!(!parse_emf(&recs).truncated, "a full stack is not past it"); + // One clip path past the nesting cap. + let mut recs = Vec::new(); + for _ in 0..=MAX_CLIP_PATHS { + recs.extend(clip_to_rect(0, 0, 100, 100, 1)); + } + assert!(parse_emf(&recs).truncated); +} + #[test] fn placed_paths_carry_their_line_style_and_shared_clips() { let mut recs = clip_to_rect(0, 0, 50, 50, 1); @@ -429,7 +690,7 @@ fn an_item_under_a_clip_far_off_the_page_is_left_out() { region: None, clips, }; - let pic = crate::Picture { width: 10.0, height: 10.0, items: vec![bitmap(vec![clip]), bitmap(Vec::new())], skipped_records: 0 }; + let pic = crate::Picture { width: 10.0, height: 10.0, items: vec![bitmap(vec![clip]), bitmap(Vec::new())], ..Default::default() }; let placed = pic.place(kurbo::Rect::new(0.0, 0.0, 10.0, 10.0), [0.0; 4]); assert_eq!(placed.len(), 1); } diff --git a/crates/metafile/src/wmf.rs b/crates/metafile/src/wmf.rs index c93f823c6..62af9c74b 100644 --- a/crates/metafile/src/wmf.rs +++ b/crates/metafile/src/wmf.rs @@ -156,8 +156,17 @@ fn record(cv: &mut Canvas, func: u16, r: Bytes) { Some(()) } 0x0142 => { - // A pattern the reader cannot decode still takes its handle slot. - let b = dib_pattern_brush(r).map_or(Obj::Other, Obj::Brush); + // A pattern the reader cannot decode still takes its handle slot, and is counted as a + // dropped image unless it has no pixels. + let b = dib_pattern_brush(r).map_or_else( + || { + if !pattern_has_no_pixels(r) { + cv.drop_image(); + } + Obj::Other + }, + Obj::Brush, + ); cv.add_object(None, b); Some(()) } @@ -241,6 +250,12 @@ fn dib_pattern_brush(r: Bytes) -> Option { Brush::pattern(img, usage == 1) } +/// Whether the DIB of a DIBCREATEPATTERNBRUSH record has a readable header that gives it no pixels. +fn pattern_has_no_pixels(r: Bytes) -> bool { + let Some(dib) = r.tail(10) else { return false }; + dib::has_no_pixels(dib, dib::info_len(dib).and_then(|n| dib.tail(n))) +} + /// Font object (MS-WMF 2.2.1.2): height, width, escapement, orientation, weight (i16 each), italic, /// underline, strike-out and charset bytes, three precision/quality bytes, pitch and family, then the /// face name (up to 32 bytes, NUL-terminated, in the font's character set). @@ -393,13 +408,24 @@ fn dib_stretchblt(cv: &mut Canvas, r: Bytes) -> Option<()> { /// A DIB at `at`, stretched from source rectangle `src` into `dst` (both in logical units, pixels for `src`). /// The raster operation `rop` decides how the pixels combine (see [`dib::prepare`]). +/// A DIB that cannot be read, or is past a limit, is counted as a dropped image. A raster operation +/// that takes no source fills the destination instead (see [`Canvas::fill_rop`]). fn dib_blit(cv: &mut Canvas, r: Bytes, at: usize, rop: u32, dst: [f64; 4], src: [f64; 4]) -> Option<()> { - let dib = r.tail(at)?; - let n = dib::info_len(dib)?; - let info = dib.slice(0, n)?; - let bits = dib.tail(n)?; - let (mut img, dst) = dib::decode_clip(Bytes(info), bits, false, src.map(|v| v as i64), dst)?; + if !dib::uses_source(rop) { + cv.fill_rop(dst, rop); + return Some(()); + } + let dib = r.tail(at).filter(|d| !d.0.is_empty())?; + let src = src.map(|v| v as i64); + let info = dib::info_len(dib).and_then(|n| Some((Bytes(dib.slice(0, n)?), dib.tail(n)?))); + let decoded = info.and_then(|(info, bits)| dib::decode_clip(info, bits, false, src, dst)); + let Some((mut img, dst)) = decoded else { + if !dib::crop_misses(dib, info.map(|(_, bits)| bits), src) { + cv.drop_image(); + } + return None; + }; dib::prepare(&mut img, dib::Blend::Rop(rop)); - cv.bitmap(dst, img); + cv.bitmap_rop(dst, img, rop); Some(()) } From 227ea620b1388a8e7ac62fcb3b2051af2fc152e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 12:05:10 -0800 Subject: [PATCH 2/2] craft-metafile: count refused bitmaps and lost pen textures, empty line clips - A bitmap that the item or byte limit refuses is counted in dropped_images once, however many pieces a clip cuts it into. - An EMF+ pen whose texture brush was not read is counted in dropped_images, as a lost texture brush object is. - An EMF+ clip path or region path whose figures all lie on a line encloses no area, so it gives an empty area instead of its bounding rectangle. --- crates/metafile/README.md | 2 +- crates/metafile/src/canvas.rs | 5 +++++ crates/metafile/src/emfplus.rs | 16 ++++++++++++---- crates/metafile/src/lib.rs | 8 ++++---- crates/metafile/src/tests.rs | 28 ++++++++++++++++++++++++++++ crates/metafile/src/tests/model.rs | 30 ++++++++++++++++++++++++++++++ 6 files changed, 80 insertions(+), 9 deletions(-) diff --git a/crates/metafile/README.md b/crates/metafile/README.md index 4e246de51..226c956ad 100644 --- a/crates/metafile/README.md +++ b/crates/metafile/README.md @@ -39,7 +39,7 @@ differently: | Field | Reports | |---|---| | `truncated` | The parse stopped at a limit that ends it (items, bytes kept, `SAVEDC` depth, clip paths), in the file or in an EMF+ metafile image drawn in it. | -| `dropped_images` | Images that were not read: bitmaps past a size, byte or decode limit or not decodable, EMF+ metafile images that do not parse or are nested too deep, and pattern or texture brushes whose bitmap was not read (counted when the brush is created). An image with no pixels, or drawn from a source rectangle that selects none, is not counted. | +| `dropped_images` | Images that were not read: bitmaps past a size, item, byte or decode limit or not decodable, EMF+ metafile images that do not parse or are nested too deep, and pattern or texture brushes whose bitmap was not read, a pen's brush included (counted when the brush or pen is created). An image with no pixels, or drawn from a source rectangle that selects none, is not counted. | | `ignored_clips` | Clip changes not applied as the file asks: `SELECTCLIPPATH` with `RGN_OR`, `RGN_XOR` or `RGN_DIFF`, EMF+ clips combined with XOR, exclude or complement, EMF+ unions drawn as the rectangle around both areas, and EMF+ clips whose area stands in for the one the file gives (a path that is not one convex figure, drawn as its rectangle, or a region built with XOR, exclude or complement). A change that cannot alter the clip is not counted: an area whose figures all lie on a line (except in an EMF+ complement of a clip that encloses some area, which would empty it), `RGN_OR` on a clip that is still the whole surface, and a union whose rectangle is no larger than the union. | | `unplayed_raster_ops` | Raster operations not played: bitmaps drawn as plain copies because their operation is not one of `SRCCOPY`, `SRCAND`, `SRCPAINT` and `SRCINVERT`, and operations without a source (such as `DSTINVERT` or `PATINVERT`) that are left out. | diff --git a/crates/metafile/src/canvas.rs b/crates/metafile/src/canvas.rs index 67cc43f0f..916e8ac9a 100644 --- a/crates/metafile/src/canvas.rs +++ b/crates/metafile/src/canvas.rs @@ -1335,7 +1335,12 @@ impl Canvas { let (x0, x1) = (xs.iter().copied().fold(f64::INFINITY, f64::min), xs.iter().copied().fold(f64::NEG_INFINITY, f64::max)); let (y0, y1) = (ys.iter().copied().fold(f64::INFINITY, f64::min), ys.iter().copied().fold(f64::NEG_INFINITY, f64::max)); let dev = if xf[1] == 0.0 && xf[2] == 0.0 { dev } else { [x0, y0, x1 - x0, y1 - y0] }; + let was_full = self.full; self.push(Raw::Bitmap { rect: dev, xf, img, region: RawClip::default() }); + // A bitmap the item or byte limit refuses is counted once, however many pieces a clip cuts it into. + if self.full && !was_full { + self.drop_image(); + } } /// Draws a bitmap that a record asked to combine with raster operation `rop` (already applied by diff --git a/crates/metafile/src/emfplus.rs b/crates/metafile/src/emfplus.rs index 32786bc5f..505149371 100644 --- a/crates/metafile/src/emfplus.rs +++ b/crates/metafile/src/emfplus.rs @@ -1181,7 +1181,11 @@ fn pen(r: Bytes) -> Option { off += 4 + (r.u32(off)? as usize).min(1 << 20); } } - let color = brush(r, off)?.color(); + // A pen whose texture brush was not read is counted like a lost brush object. + let Some(fill) = brush(r, off) else { + return lost_texture(r.tail(off)?).then_some(Obj::LostBrush); + }; + let color = fill.color(); Some(Obj::Pen { color, width: if width.is_finite() { width.clamp(0.0, 1.0e5) } else { 0.0 } }) } @@ -1290,16 +1294,20 @@ fn region_node(r: Bytes, off: usize, depth: usize, work: &mut usize) -> Option<( } } -/// The area a path encloses: its outline when that is one convex figure, else the rectangle -/// around it. The flag is set when the rectangle stands in for a path that encloses some area. +/// The area a path encloses: its outline when that is one convex figure, none when its figures all +/// lie on a line, else the rectangle around it. The flag is set when the rectangle stands in for +/// the path. fn area_of_ops(ops: &[Op]) -> (Vec

, bool) { + if !crate::geom::encloses_area(ops) { + return (Vec::new(), false); + } let subs = flatten(ops); if let [(pts, _)] = subs.as_slice() && let Some(c) = convex(pts) { return (c, false); } - (ops_bbox(ops).map(rect_poly).unwrap_or_default(), crate::geom::encloses_area(ops)) + (ops_bbox(ops).map(rect_poly).unwrap_or_default(), true) } /// Two areas' intersection, and whether it ran out of work and kept the first area instead. diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 6a2338a78..26a406d31 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -78,10 +78,10 @@ pub struct Picture { /// the picture holds what came before. The limits that cut one path, string, region or dash /// pattern short do not set it. pub truncated: bool, - /// Images the file asks to draw that the reader did not read: bitmaps past a size, byte or decode - /// limit or in a form the reader cannot decode, EMF+ metafile images that do not parse or are - /// nested deeper than 3 levels, and pattern or texture brushes whose bitmap was not read (counted - /// when the brush is created). An image whose source rectangle selects none of its pixels, or that + /// Images the file asks to draw that the reader did not read: bitmaps past a size, item, byte or + /// decode limit or in a form the reader cannot decode, EMF+ metafile images that do not parse or + /// are nested deeper than 3 levels, and pattern or texture brushes whose bitmap was not read, a + /// pen's brush included (counted when the brush or pen is created). An image whose source rectangle selects none of its pixels, or that /// has no pixels, draws nothing and is not counted. Bitmaps left out while clipping to an EMF+ /// clip (see the README's limits) are not counted here. pub dropped_images: u32, diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index fa1cbb33a..9f929108b 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -486,6 +486,34 @@ fn canvas_stops_at_the_byte_budget() { assert_eq!(cv.items.len(), 2); } +#[test] +fn a_bitmap_the_byte_budget_refuses_is_counted_once() { + let img = || Rgba { w: 4, h: 4, px: vec![0u8; 64] }; + let diamond = || Some(vec![(2.0, 0.0), (4.0, 2.0), (2.0, 4.0), (0.0, 2.0)]); + let mut cv = Canvas::new(); + cv.set_clip(diamond()); + cv.bitmap([0.0, 0.0, 4.0, 4.0], img()); + assert!(!cv.full() && !cv.items.is_empty() && cv.dropped_images == 0, "a bitmap that is kept"); + // The clip cuts the bitmap into pieces, and none of them fits: one image is counted. + let mut cv = Canvas::new(); + cv.hold(MAX_BYTES - 1); + cv.set_clip(diamond()); + cv.bitmap([0.0, 0.0, 4.0, 4.0], img()); + assert!(cv.full() && cv.items.is_empty()); + assert_eq!(cv.dropped_images, 1); + // A clip that leaves none of the bitmap refuses nothing. + let mut cv = Canvas::new(); + cv.hold(MAX_BYTES - 1); + cv.set_clip(Some(vec![(100.0, 100.0), (110.0, 100.0), (110.0, 110.0)])); + cv.bitmap([0.0, 0.0, 4.0, 4.0], img()); + assert!(!cv.full() && cv.dropped_images == 0); + // A bitmap drawn with a raster operation is counted the same way. + let mut cv = Canvas::new(); + cv.hold(MAX_BYTES - 1); + cv.bitmap_rop([0.0, 0.0, 4.0, 4.0], img(), 0x00CC_0020); + assert!(cv.full() && cv.dropped_images == 1 && cv.unplayed_raster_ops == 0); +} + #[test] fn oversized_dib_header_size_is_rejected_without_overflow() { let mut info = info_header(2, 2, 24, 16); diff --git a/crates/metafile/src/tests/model.rs b/crates/metafile/src/tests/model.rs index 73186cb4c..5053606c4 100644 --- a/crates/metafile/src/tests/model.rs +++ b/crates/metafile/src/tests/model.rs @@ -485,6 +485,17 @@ fn pattern_and_texture_brushes_that_are_not_read_are_counted() { let none = cat(vec![h32(0xDBC0_1002), h32(1), h32(0), h32(4), h32(16), h32(0x0026_200A), h32(0)]); assert_eq!(parse(&texture(none)).unwrap().dropped_images, 0); assert_eq!(parse(&texture(bitmap_2x2())).unwrap().dropped_images, 0); + // A pen whose brush is such a texture brush. + let pen = |image: Vec| { + let brush = cat(vec![h32(0xDBC0_1002), h32(2), h32(0), h32(0), image]); + let pen = cat(vec![h32(0xDBC0_1002), h32(0), h32(0), h32(0), f32s(&[1.0]), brush]); + emf(&[plus_comment(&[plus_header(false), prec(0x4008, 0x0200 | 5, &pen)])], [0; 4], [0; 4]) + }; + let short = cat(vec![h32(0xDBC0_1002), h32(1), h32(4), h32(4), h32(16), h32(0x0026_200A), h32(0), vec![1, 2, 3]]); + assert_eq!(parse(&pen(short)).unwrap().dropped_images, 1); + let none = cat(vec![h32(0xDBC0_1002), h32(1), h32(0), h32(4), h32(16), h32(0x0026_200A), h32(0)]); + assert_eq!(parse(&pen(none)).unwrap().dropped_images, 0); + assert_eq!(parse(&pen(bitmap_2x2())).unwrap().dropped_images, 0); } #[test] @@ -643,6 +654,25 @@ fn emfplus_clips_that_are_not_applied_are_counted() { assert_eq!(plus(vec![clip(1, [0.0, 0.0, 50.0, 50.0]), clip(0, [1.0, 1.0, 5.0, 5.0])]), 0, "intersect and replace are applied"); } +#[test] +fn an_emfplus_clip_on_a_diagonal_line_encloses_nothing() { + let fill = prec(0x400A, 0x8000, &cat(vec![h32(0xFF00_0000), h32(1), f32s(&[0.0, 0.0, 100.0, 100.0])])); + let drawn = |clip: Vec>| { + let mut all = vec![plus_header(false)]; + all.extend(clip); + all.push(fill.clone()); + let p = parse(&emf(&[plus_comment(&all)], [0; 4], [0; 4])).unwrap(); + (p.items.len(), p.ignored_clips) + }; + let line = cat(vec![h32(0xDBC0_1002), h32(2), h32(0), f32s(&[0.0, 0.0, 10.0, 10.0]), vec![0, 1]]); + // SetClipPath with the line replaces the clip with nothing. + assert_eq!(drawn(vec![prec(0x4008, 0x0300 | 9, &line), prec(0x4033, 9, &[])]), (0, 0)); + // A region whose one node is the line. + let node = cat(vec![h32(0x1000_0001), h32(line.len() as u32), line]); + let region = cat(vec![h32(0xDBC0_1002), h32(1), node]); + assert_eq!(drawn(vec![prec(0x4008, 0x0400 | 6, ®ion), prec(0x4034, 6, &[])]), (0, 0)); +} + #[test] fn a_parse_stopped_at_a_limit_is_truncated() { assert!(!parse_emf(&[rect(0, 0, 10, 10)]).truncated);