From aaa7230822a2ea11ff93cd069c095b6c30f2de6e Mon Sep 17 00:00:00 2001 From: Hamza Date: Fri, 13 Nov 2026 15:12:42 +0500 Subject: [PATCH 1/3] craft-metafile: WMF scale and offset mapping records META_SCALEVIEWPORTEXT, META_SCALEWINDOWEXT, META_OFFSETVIEWPORTORG and META_OFFSETWINDOWORG were skipped, so a WMF that draws sub-pictures into parts of its frame (each halving the viewport between SaveDC and RestoreDC) stretched the first one over the whole frame and drew the next outside it (storytold/deckcraft#2069). --- crates/metafile/README.md | 4 +- crates/metafile/src/canvas.rs | 10 ++++- crates/metafile/src/tests.rs | 73 +++++++++++++++++++++++++++++++++++ crates/metafile/src/wmf.rs | 9 +++++ 4 files changed, 92 insertions(+), 4 deletions(-) diff --git a/crates/metafile/README.md b/crates/metafile/README.md index ba255c36d..77dd7233c 100644 --- a/crates/metafile/README.md +++ b/crates/metafile/README.md @@ -53,14 +53,14 @@ decoder is where the size, pixel and work limits have to be enforced. | Group | Records | |---|---| | Headers | Placeable header, memory and disk metafile headers. | -| Mapping | `SETMAPMODE`, `SETWINDOWORG`, `SETWINDOWEXT`, `SETVIEWPORTORG`, `SETVIEWPORTEXT`, all map modes (text, metric, isotropic, anisotropic). A placeable file is played into its box the way Office plays it. | +| Mapping | `SETMAPMODE`, `SETWINDOWORG`, `SETWINDOWEXT`, `SETVIEWPORTORG`, `SETVIEWPORTEXT`, `OFFSETWINDOWORG`, `OFFSETVIEWPORTORG`, `SCALEWINDOWEXT`, `SCALEVIEWPORTEXT`, all map modes (text, metric, isotropic, anisotropic). A placeable file is played into its box the way Office plays it. | | State | `SAVEDC`, `RESTOREDC`, `SETPOLYFILLMODE`, `SETROP2`, `SETBKMODE`, `SETBKCOLOR`, `SETTEXTCOLOR`, `SETTEXTALIGN`. | | Objects | `CREATEPENINDIRECT` (style, cap and join bits), `CREATEBRUSHINDIRECT` (solid, null, hatched), `DIBCREATEPATTERNBRUSH`, `CREATEFONTINDIRECT`, `SELECTOBJECT`, `DELETEOBJECT`, stock objects. `CREATEPALETTE`, `CREATEPATTERNBRUSH` and `CREATEREGION` take their handle slot. | | Drawing | `MOVETO`, `LINETO`, `POLYLINE`, `POLYGON`, `POLYPOLYGON`, `RECTANGLE`, `ROUNDRECT`, `ELLIPSE`, `ARC`, `PIE`, `CHORD`, `PATBLT`. | | Bitmaps | `STRETCHDIB`, `DIBSTRETCHBLT`, `DIBBITBLT` (with or without a source). | | Text | `EXTTEXTOUT` (rectangle, opaque, clipped, dx), `TEXTOUT`, decoded in the selected font's character set: code pages 1250 to 1258 and 874, Shift_JIS, UHC, GBK and Big5 (a double-byte character takes the advances of both its bytes), and the symbol character set (also the Symbol font under `DEFAULT_CHARSET`), whose codes stay in the private-use area at U+F000. Face names are read in the font's code page. Johab pairs are blanks. | | Clipping | `INTERSECTCLIPRECT`, `EXCLUDECLIPRECT`. | -| Not read | `OFFSETWINDOWORG`, `OFFSETVIEWPORTORG`, `SCALEWINDOWEXT`, `SCALEVIEWPORTEXT`, flood fills, `SETPIXEL`, region records (`FILLREGION`, `FRAMEREGION`, `PAINTREGION`, `INVERTREGION`, `SELECTCLIPREGION`, `OFFSETCLIPRGN`), the device-dependent `BITBLT`, `STRETCHBLT` and `SETDIBTODEV`. They are counted in `skipped_records`. | +| Not read | Flood fills, `SETPIXEL`, region records (`FILLREGION`, `FRAMEREGION`, `PAINTREGION`, `INVERTREGION`, `SELECTCLIPREGION`, `OFFSETCLIPRGN`), the device-dependent `BITBLT`, `STRETCHBLT` and `SETDIBTODEV`. They are counted in `skipped_records`. | ### EMF (MS-EMF) diff --git a/crates/metafile/src/canvas.rs b/crates/metafile/src/canvas.rs index 51159bdf3..217d27495 100644 --- a/crates/metafile/src/canvas.rs +++ b/crates/metafile/src/canvas.rs @@ -822,8 +822,14 @@ impl Canvas { if self.arc_clockwise { (e, s) } else { (s, e) } } - /// SCALEVIEWPORTEXTEX and SCALEWINDOWEXTEX: the extent times `num / den` on each axis. A zero - /// denominator leaves the extent alone. + /// OFFSETWINDOWORG and OFFSETVIEWPORTORG (WMF): the window or viewport origin moved by `d`. + pub fn offset_org(&mut self, window: bool, d: P) { + let o = if window { &mut self.map.wo } else { &mut self.map.vo }; + *o = (o.0 + d.0, o.1 + d.1); + } + + /// SCALEVIEWPORTEXTEX and SCALEWINDOWEXTEX (and WMF's SCALEVIEWPORTEXT and SCALEWINDOWEXT): the + /// extent times `num / den` on each axis. A zero denominator leaves the extent alone. pub fn scale_ext(&mut self, window: bool, x: (f64, f64), y: (f64, f64)) { if x.1 == 0.0 || y.1 == 0.0 { return; diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index 1a2a30fc6..262146780 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -2654,3 +2654,76 @@ fn canvas_budget_counts_bytes_held_elsewhere() { assert!(cv.full()); assert!(cv.items.is_empty()); } + +/// The box through a path's segment ends (an ellipse's four cubics end on its box). +fn end_extent(item: &Item) -> (f32, f32, f32, f32) { + let (segs, ..) = path_segs(item); + let (xs, ys): (Vec, Vec) = segs + .iter() + .filter_map(|s| match s { + Seg::Move(x, y) | Seg::Line(x, y) | Seg::Cubic(.., x, y) => Some((*x, *y)), + Seg::Close => None, + }) + .unzip(); + let lo = |v: &[f32]| v.iter().copied().fold(f32::MAX, f32::min); + let hi = |v: &[f32]| v.iter().copied().fold(f32::MIN, f32::max); + (lo(&xs), lo(&ys), hi(&xs), hi(&ys)) +} + +/// Two sub-pictures drawn into halves of the frame, as charts pasted from older Office versions +/// are stored (deckcraft#2069): each saves the DC, halves the viewport with SCALEVIEWPORTEXT, sets +/// its own 400 x 400 window (the second shifted 400 to the left, so it lands in the right half), +/// draws a circle and restores the DC. The left circle stays in the left half and the right one +/// lands in the right half of the 800 x 400 frame. +#[test] +fn wmf_scale_viewport_ext_draws_sub_pictures_into_parts_of_the_frame() { + let sub = |org_x: i32| { + vec![ + wrec(0x001E, &[]), + wrec(0x0103, &h16(8)), + // yDenom, yNum, xDenom, xNum: x * 1/2, y * 1/1. + wrec(0x0412, &cat(vec![h16(1), h16(1), h16(2), h16(1)])), + wrec(0x020B, &cat(vec![h16(0), h16(org_x)])), + wrec(0x020C, &cat(vec![h16(400), h16(400)])), + wrec(0x0418, &cat(vec![h16(380), h16(380), h16(20), h16(20)])), + wrec(0x0127, &h16(-1)), + ] + }; + let mut recs = vec![wrec(0x020B, &cat(vec![h16(0), h16(0)])), wrec(0x020C, &cat(vec![h16(400), h16(800)]))]; + recs.extend(sub(0)); + recs.extend(sub(-400)); + let p = parse(&wmf(&recs, None)).unwrap(); + assert_eq!((p.width, p.height), (800.0, 400.0)); + assert_eq!((p.items.len(), p.skipped_records), (2, 0), "both circles, and every record played"); + for (item, want) in p.items.iter().zip([(20.0, 20.0, 380.0, 380.0), (420.0, 20.0, 780.0, 380.0)]) { + let got = end_extent(item); + assert!(close(got.0, want.0) && close(got.1, want.1) && close(got.2, want.2) && close(got.3, want.3), "{got:?}, want {want:?}"); + } +} + +/// SCALEWINDOWEXT scales the window extent, and OFFSETWINDOWORG and OFFSETVIEWPORTORG move the +/// window and viewport origins by their offsets, on top of what the SET records gave them. The +/// 100 x 100 window of a plain WMF is the frame, and the records after it place a rectangle in it. +#[test] +fn wmf_scale_window_ext_and_offset_origins_change_the_mapping() { + let rect = || wrec(0x041B, &cat(vec![h16(20), h16(20), h16(10), h16(10)])); + let base = || vec![wrec(0x0103, &h16(8)), wrec(0x020B, &cat(vec![h16(0), h16(0)])), wrec(0x020C, &cat(vec![h16(100), h16(100)]))]; + let extent = |extra: Vec>| { + let mut recs = base(); + recs.extend(extra); + recs.push(rect()); + rect_extent(&parse(&wmf(&recs, None)).unwrap().items[0]) + }; + // The window doubled (x * 2/1, y * 4/2): the rectangle shows at half size. + let got = extent(vec![wrec(0x0410, &cat(vec![h16(2), h16(4), h16(1), h16(2)]))]); + assert!(close(got.0, 5.0) && close(got.1, 5.0) && close(got.2, 10.0) && close(got.3, 10.0), "scaled window: {got:?}"); + // The window origin moved by (5, 10): the rectangle moves the other way. + let got = extent(vec![wrec(0x020F, &cat(vec![h16(10), h16(5)]))]); + assert!(close(got.0, 5.0) && close(got.1, 0.0) && close(got.2, 15.0) && close(got.3, 10.0), "window origin: {got:?}"); + // The viewport origin moved by (30, -5): the rectangle moves with it. + let got = extent(vec![wrec(0x0211, &cat(vec![h16(-5), h16(30)]))]); + assert!(close(got.0, 40.0) && close(got.1, 5.0) && close(got.2, 50.0) && close(got.3, 15.0), "viewport origin: {got:?}"); + // A zero denominator leaves the extent alone. + let got = extent(vec![wrec(0x0412, &cat(vec![h16(0), h16(1), h16(0), h16(1)]))]); + assert!(close(got.0, 10.0) && close(got.1, 10.0) && close(got.2, 20.0) && close(got.3, 20.0), "zero denominator: {got:?}"); +} diff --git a/crates/metafile/src/wmf.rs b/crates/metafile/src/wmf.rs index 9f9db3508..a4c408fd1 100644 --- a/crates/metafile/src/wmf.rs +++ b/crates/metafile/src/wmf.rs @@ -105,6 +105,15 @@ fn record(cv: &mut Canvas, func: u16, r: Bytes) { 0x020C => xy16(r, 6).map(|p| cv.set_window_ext(p)), 0x020D => xy16(r, 6).map(|p| cv.set_viewport_org(p)), 0x020E => xy16(r, 6).map(|p| cv.set_viewport_ext(p)), + // OFFSETWINDOWORG and OFFSETVIEWPORTORG: yOffset, xOffset, added to the origin. + 0x020F | 0x0211 => xy16(r, 6).map(|d| cv.offset_org(func == 0x020F, d)), + // SCALEWINDOWEXT and SCALEVIEWPORTEXT: yDenom, yNum, xDenom, xNum ([MS-WMF] 2.3.5). A + // sub-picture drawn into part of the frame halves the viewport this way (deckcraft#2069). + 0x0410 | 0x0412 => (|| { + let [y_den, y_num, x_den, x_num] = [r.i16(6)?, r.i16(8)?, r.i16(10)?, r.i16(12)?].map(f64::from); + cv.scale_ext(func == 0x0410, (x_num, x_den), (y_num, y_den)); + Some(()) + })(), 0x001E => { cv.save_dc(); Some(()) From 7585d2df79324a6b35b137a3183f7b7780a67ea7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 23:50:34 -0500 Subject: [PATCH 2/3] fix(metafile): retain WMF player target across viewport scaling --- crates/metafile/src/tests.rs | 17 +++++++++++++++++ crates/metafile/src/wmf.rs | 15 ++++++++------- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index 262146780..5befb8818 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -2727,3 +2727,20 @@ fn wmf_scale_window_ext_and_offset_origins_change_the_mapping() { let got = extent(vec![wrec(0x0412, &cat(vec![h16(0), h16(1), h16(0), h16(1)]))]); assert!(close(got.0, 10.0) && close(got.1, 10.0) && close(got.2, 20.0) && close(got.3, 20.0), "zero denominator: {got:?}"); } + +#[test] +fn wmf_viewport_scaling_does_not_resize_the_player_frame() { + for numerator in [1, 4] { + let recs = [ + wrec(0x0103, &h16(8)), + wrec(0x020C, &cat(vec![h16(100), h16(100)])), + wrec(0x041B, &cat(vec![h16(100), h16(100), h16(0), h16(0)])), + // Change the mapping after drawing, without a matching RESTOREDC. + wrec(0x0412, &cat(vec![h16(1), h16(1), h16(2), h16(numerator)])), + ]; + let p = parse(&wmf(&recs, None)).unwrap(); + assert_eq!((p.width, p.height), (100.0, 100.0)); + assert_eq!(p.skipped_records, 0); + assert_eq!(rect_extent(&p.items[0]), (0.0, 0.0, 100.0, 100.0)); + } +} diff --git a/crates/metafile/src/wmf.rs b/crates/metafile/src/wmf.rs index a4c408fd1..3900de482 100644 --- a/crates/metafile/src/wmf.rs +++ b/crates/metafile/src/wmf.rs @@ -50,7 +50,8 @@ pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> { cv.set_clip_surface([0.0, 0.0, size.0, size.1]); cv.pattern_px = PT_PER_PX; } - let mut player_viewport = bounds.is_some(); + // Keep the player target independent of subsequent mapping changes. + let mut player_target = bounds.map(|(_, size)| size); let mut parsed = 0usize; while !cv.full() { let (Some(words), Some(func)) = (input.u32(pos), pos.checked_add(4).and_then(|o| input.u16(o))) else { break }; @@ -60,10 +61,11 @@ pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> { break; } record(&mut cv, func, Bytes(rec)); - if func == 0x020C && cv.window_set && !player_viewport && !cv.viewport_set { + if func == 0x020C && cv.window_set && player_target.is_none() && !cv.viewport_set { let we = cv.map.window_ext(); - cv.play_into(None, (we.0.abs(), we.1.abs())); - player_viewport = true; + let target = (we.0.abs(), we.1.abs()); + cv.play_into(None, target); + player_target = Some(target); } parsed += 1; let Some(next) = pos.checked_add(len) else { break }; @@ -82,9 +84,8 @@ pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> { let rect = [a.0.min(b.0), a.1.min(b.1), (b.0 - a.0).abs(), (b.1 - a.1).abs()]; (rect[2] > 0.0 && rect[3] > 0.0).then_some(Frame { rect, size: Some(size) }) } - None if player_viewport && !cv.viewport_set && cv.map.uses_extents() => { - let ve = cv.map.viewport_ext(); - Some(Frame { rect: [0.0, 0.0, ve.0, ve.1], size: None }) + None if !cv.viewport_set && cv.map.uses_extents() && player_target.is_some() => { + player_target.map(|(w, h)| Frame { rect: [0.0, 0.0, w, h], size: None }) } None if cv.window_set => Some(Frame { rect: cv.map.window_rect(), size: None }), None => None, From 8644532ed7c7ffbf7b51a3c52ef583cfe0320a3b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 00:05:09 -0500 Subject: [PATCH 3/3] fix(metafile): preserve viewport scaling before inferred target --- crates/metafile/src/tests.rs | 14 ++++++++++++++ crates/metafile/src/wmf.rs | 5 ++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index 5befb8818..661f319d6 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -2744,3 +2744,17 @@ fn wmf_viewport_scaling_does_not_resize_the_player_frame() { assert_eq!(rect_extent(&p.items[0]), (0.0, 0.0, 100.0, 100.0)); } } + +#[test] +fn wmf_viewport_scaling_before_first_window_is_retained() { + let recs = [ + wrec(0x0103, &h16(8)), + wrec(0x0412, &cat(vec![h16(1), h16(1), h16(2), h16(1)])), + wrec(0x020C, &cat(vec![h16(100), h16(100)])), + wrec(0x041B, &cat(vec![h16(100), h16(100), h16(0), h16(0)])), + ]; + let p = parse(&wmf(&recs, None)).unwrap(); + assert_eq!((p.width, p.height), (100.0, 100.0)); + assert_eq!(p.skipped_records, 0); + assert_eq!(rect_extent(&p.items[0]), (0.0, 0.0, 50.0, 100.0)); +} diff --git a/crates/metafile/src/wmf.rs b/crates/metafile/src/wmf.rs index 3900de482..c93f823c6 100644 --- a/crates/metafile/src/wmf.rs +++ b/crates/metafile/src/wmf.rs @@ -64,7 +64,10 @@ pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> { if func == 0x020C && cv.window_set && player_target.is_none() && !cv.viewport_set { let we = cv.map.window_ext(); let target = (we.0.abs(), we.1.abs()); - cv.play_into(None, target); + // Before an explicit viewport, its default (1, 1) retains any + // SCALEVIEWPORTEXT factors already applied by the file. + let scale = cv.map.viewport_ext(); + cv.play_into(None, (target.0 * scale.0, target.1 * scale.1)); player_target = Some(target); } parsed += 1;