diff --git a/Cargo.lock b/Cargo.lock index 5a89245b0d..d077d28f18 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7128,6 +7128,7 @@ dependencies = [ "cfb", "chardetng", "chrono", + "craft-metafile", "craft-rtf", "encoding_rs", "getrandom 0.3.4", @@ -7143,7 +7144,6 @@ dependencies = [ "wordcraft-doc", "wordcraft-docx", "wordcraft-geom", - "wordcraft-metafile", "zeroize", "zip 3.0.0", ] @@ -7160,6 +7160,7 @@ dependencies = [ name = "wordcraft-layout" version = "0.18.1" dependencies = [ + "craft-metafile", "craft-proof", "image", "js-sys", @@ -7173,7 +7174,6 @@ dependencies = [ "wordcraft-doc", "wordcraft-fonts", "wordcraft-geom", - "wordcraft-metafile", ] [[package]] @@ -7188,19 +7188,12 @@ dependencies = [ "wordcraft-render", ] -[[package]] -name = "wordcraft-metafile" -version = "0.18.1" -dependencies = [ - "kurbo", - "thiserror 2.0.21", -] - [[package]] name = "wordcraft-pdf" version = "0.18.1" dependencies = [ "chrono", + "craft-metafile", "craft-pdf", "hayro-cmap", "hayro-interpret", @@ -7214,13 +7207,13 @@ dependencies = [ "wordcraft-fonts", "wordcraft-geom", "wordcraft-layout", - "wordcraft-metafile", ] [[package]] name = "wordcraft-render" version = "0.18.1" dependencies = [ + "craft-metafile", "image", "log", "vello_cpu", @@ -7228,7 +7221,6 @@ dependencies = [ "wordcraft-fonts", "wordcraft-geom", "wordcraft-layout", - "wordcraft-metafile", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 1ff4830208..6c4c1fc586 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,7 +36,6 @@ wordcraft-mcp = { path = "crates/mcp" } wordcraft-zotero = { path = "crates/zotero" } wordcraft-control-key = { path = "crates/control-key" } wordcraft-ui-egui = { path = "crates/ui-egui" } -wordcraft-metafile = { path = "crates/metafile" } # foundation kurbo = { version = "0.13", features = ["serde"] } @@ -74,6 +73,8 @@ craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "9dcb craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "9dcbd90c7d16e1a668b3afa057e940e2db328b93", version = "=0.1.0" } craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "9dcbd90c7d16e1a668b3afa057e940e2db328b93", version = "=0.1.0", features = ["doc"] } craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "9dcbd90c7d16e1a668b3afa057e940e2db328b93", version = "=0.1.0" } +# WMF, EMF and EMF+ reader. +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "9dcbd90c7d16e1a668b3afa057e940e2db328b93", version = "=0.1.0" } quick-xml = "0.41" zip = { version = "3", default-features = false, features = ["deflate"] } # zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates. diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 995a4eb630..08c6abdeb8 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -13,7 +13,7 @@ wordcraft-doc = { workspace = true } wordcraft-docx = { workspace = true } craft-rtf = { workspace = true } wordcraft-geom = { workspace = true, features = ["image"] } -wordcraft-metafile = { workspace = true } +craft-metafile = { workspace = true } base64 = { workspace = true } image = { workspace = true } quick-xml = { workspace = true } diff --git a/crates/formats/src/odt/body/drawing.rs b/crates/formats/src/odt/body/drawing.rs index 3e5065b5f0..e8b8daa6b4 100644 --- a/crates/formats/src/odt/body/drawing.rs +++ b/crates/formats/src/odt/body/drawing.rs @@ -402,7 +402,7 @@ impl Body<'_> { /// Whether WordCraft can show these bytes as a picture (see the function below). pub(in crate::odt) fn readable_picture(data: &[u8]) -> bool { - wordcraft_metafile::is_metafile(data) || model::sniff_image(data).is_some() + craft_metafile::is_metafile(data) || model::sniff_image(data).is_some() } /// A picture from a package's bytes: a raster image, or a Windows metafile (WMF, EMF: LibreOffice @@ -411,7 +411,7 @@ pub(in crate::odt) fn picture(data: Vec, w: Option, h: Option, alt // What the frame states, if it could be a size (far past any page, kept from overflowing). let stated = |v: Option| v.filter(|v| v.is_finite() && *v > 0.0).map(|v| v.min(1e6)); let (w, h) = (stated(w), stated(h)); - let mut img = if wordcraft_metafile::is_metafile(&data) { + let mut img = if craft_metafile::is_metafile(&data) { // An EMF starts with its header record, type 1. let ext = if data.get(..4) == Some(&[1, 0, 0, 0]) { "emf" } else { "wmf" }; // Its own size, when the frame gives none: a placeable WMF's or an EMF's frame, points. @@ -450,7 +450,7 @@ fn fit_to(img: &mut model::Img, room: Option) { /// A picture's height for each point of its width, by its own size, before anything caps it (1 /// when it doesn't say). fn height_per_width(data: &[u8]) -> f32 { - let own = if wordcraft_metafile::is_metafile(data) { metafile_size(data) } else { model::image_px(data).map(|(w, h)| (w as f32, h as f32)) }; + let own = if craft_metafile::is_metafile(data) { metafile_size(data) } else { model::image_px(data).map(|(w, h)| (w as f32, h as f32)) }; own.filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0).map_or(1.0, |(w, h)| h / w) } diff --git a/crates/layout/Cargo.toml b/crates/layout/Cargo.toml index 21762d5039..7cf71a1bf3 100644 --- a/crates/layout/Cargo.toml +++ b/crates/layout/Cargo.toml @@ -13,7 +13,7 @@ wordcraft-geom = { workspace = true, features = ["image"] } wordcraft-doc = { workspace = true } wordcraft-fonts = { workspace = true } wordcraft-proof = { workspace = true } -wordcraft-metafile = { workspace = true } +craft-metafile = { workspace = true } kurbo = { workspace = true } unicode-bidi = { workspace = true } unicode-linebreak = { workspace = true } diff --git a/crates/layout/src/contour.rs b/crates/layout/src/contour.rs index 9b92cb6e82..9f5d90b56b 100644 --- a/crates/layout/src/contour.rs +++ b/crates/layout/src/contour.rs @@ -307,7 +307,7 @@ fn decode_alpha(bytes: &[u8], decoded: &mut u64) -> Result, OverBu fn alpha_in_crop(img: &Alpha, crop: [f32; 4]) -> Option> { let (iw, ih) = (img.w, img.h); // The part the renderers draw (#1899): a sliver keeps its partly covered pixels. - let [cl, ct, vw, vh] = wordcraft_metafile::crop_window(crop); + let [cl, ct, vw, vh] = crate::crop_window(crop); let (fw, fh) = (f64::from(iw), f64::from(ih)); let x0 = ((fw * cl) as u32).min(iw); let y0 = ((fh * ct) as u32).min(ih); diff --git a/crates/layout/src/lib.rs b/crates/layout/src/lib.rs index 86e2664285..edc60026cd 100644 --- a/crates/layout/src/lib.rs +++ b/crates/layout/src/lib.rs @@ -58,6 +58,7 @@ mod ctx; mod floats; mod flow; mod headers; +mod metafile; mod missing; mod notes; mod page; @@ -84,7 +85,10 @@ use headers::MAX_HEADER_ITEMS; #[cfg(test)] use headers::placed_cost; use headers::placed_cost_by; -pub use missing::{MAX_MISSING_GLYPHS, MissingGlyphs, metafile_text_run, missing_watermark_glyphs, watermark_run}; +pub use metafile::{MAX_METAFILE_DASHES, crop_sides, crop_window, metafile_average_color, metafile_dashes, metafile_miter_limit}; +pub use missing::{ + MAX_MISSING_GLYPHS, MetafileTextLayout, MissingGlyphs, metafile_text_layout, metafile_text_run, missing_watermark_glyphs, watermark_run, +}; pub use notes::DECOR_STORY; pub(crate) use notes::NOTE_SEP_W; use notes::{MAX_NOTE_PASSES, footnote_pages}; diff --git a/crates/layout/src/metafile.rs b/crates/layout/src/metafile.rs new file mode 100644 index 0000000000..a562550e88 --- /dev/null +++ b/crates/layout/src/metafile.rs @@ -0,0 +1,75 @@ +//! Drawing rules the page renderer and the PDF export share for metafile pictures and picture +//! crops, so the two outputs draw the same file the same way. + +/// Most dashes and gaps one metafile stroke is split into. A path that a pen's pattern would split +/// into more draws solid. +pub const MAX_METAFILE_DASHES: f64 = 100_000.0; + +/// The crop sides a picture is drawn with: each side of `crop` (left, top, right, bottom fractions +/// of the source) at least 0. A negative side draws as no crop, not as padding around the source. +pub fn crop_sides(crop: [f32; 4]) -> [f32; 4] { + crop.map(|v| if v.is_finite() { v.max(0.0) } else { 0.0 }) +} + +/// The part of a picture's source that `crop` keeps, as fractions of the source: [left, top, +/// width, height] (`craft_metafile::crop_window` of [`crop_sides`]). +pub fn crop_window(crop: [f32; 4]) -> [f64; 4] { + craft_metafile::crop_window(crop_sides(crop)) +} + +/// The miter limit a metafile pen is drawn with: its own when it is finite and at least 1, +/// otherwise 10. +pub fn metafile_miter_limit(limit: f32) -> f32 { + if limit.is_finite() && limit >= 1.0 { limit } else { 10.0 } +} + +/// The dash lengths (page points) a metafile pen draws a path `length` points long with, or None +/// for a solid line. `dash` is the placed pen's pattern (`craft_metafile::LineStyle::dash`, page +/// points) and `pixel` is one output pixel in points. +/// +/// A cosmetic pen (`cosmetic`: width 0) has its pattern scaled so that its shortest dash or gap is +/// one pixel, at any zoom. A pattern with a negative or non-finite length draws solid, and so does +/// one whose period is shorter than a pixel or that would split the path into more than +/// [`MAX_METAFILE_DASHES`] dashes and gaps. +pub fn metafile_dashes(dash: &[f32], cosmetic: bool, pixel: f64, length: f64) -> Option> { + if dash.is_empty() || !pixel.is_finite() || pixel <= 0.0 { + return None; + } + let mut out: Vec = dash.iter().map(|d| f64::from(*d)).collect(); + if !out.iter().all(|d| d.is_finite() && *d >= 0.0) { + return None; + } + if cosmetic { + let shortest = out.iter().copied().filter(|d| *d > 0.0).fold(f64::INFINITY, f64::min); + if !shortest.is_finite() { + return None; + } + let k = pixel / shortest; + out.iter_mut().for_each(|d| *d *= k); + } + let period: f64 = out.iter().sum(); + if !period.is_finite() || period < pixel { + return None; + } + // Each length of the pattern starts a new dash or gap. + let pieces = out.len() as f64 * if length.is_finite() { length.max(0.0) / period } else { f64::INFINITY }; + (pieces <= MAX_METAFILE_DASHES).then_some(out) +} + +/// The alpha-weighted average color of straight RGBA pixels (transparent when there are none): a +/// metafile pattern fill whose tile is too small to show is filled with it. +pub fn metafile_average_color(px: &[u8]) -> [u8; 4] { + let (mut r, mut g, mut b, mut a, mut n) = (0u64, 0u64, 0u64, 0u64, 0u64); + for p in px.as_chunks::<4>().0 { + let w = u64::from(p[3]); + r += u64::from(p[0]) * w; + g += u64::from(p[1]) * w; + b += u64::from(p[2]) * w; + a += w; + n += 1; + } + if a == 0 || n == 0 { + return [0; 4]; + } + [(r / a) as u8, (g / a) as u8, (b / a) as u8, (a / n) as u8] +} diff --git a/crates/layout/src/missing.rs b/crates/layout/src/missing.rs index 6ea5c3bc20..8425362685 100644 --- a/crates/layout/src/missing.rs +++ b/crates/layout/src/missing.rs @@ -151,12 +151,100 @@ pub fn watermark_run(wm: &wordcraft_doc::Watermark, max_chars: usize) -> Option< /// in the face its font name resolves to (no fallback face), so a character that face lacks shapes /// to glyph id 0. Strict export checks these same glyphs, so the check and the exporters can't /// drift. -pub fn metafile_text_run(t: &wordcraft_metafile::Text) -> (wordcraft_fonts::FaceRef, Vec) { - let face = wordcraft_fonts::word::resolve(&t.font, t.bold, t.italic).face; +pub fn metafile_text_run(t: &craft_metafile::Text) -> (wordcraft_fonts::FaceRef, Vec) { + let family = t.font.family.trim(); + let family = if family.is_empty() { METAFILE_DEFAULT_FONT } else { family }; + let face = wordcraft_fonts::word::resolve(family, t.font.weight >= 600, t.font.italic).face; let shaped = wordcraft_fonts::shape(&face, &t.text, &[], |c| c); (face, shaped) } +/// The face a metafile font with no face name is drawn in. +const METAFILE_DEFAULT_FONT: &str = "Arial"; +/// The cell height (text units) of a metafile font whose height is 0, the file's default size. +const METAFILE_DEFAULT_HEIGHT: f64 = 16.0; + +/// A metafile text run laid out with a font's metrics: the em size (text units), the baseline's y +/// and each glyph's (x, y), alignment included, in the run's text space (see +/// `craft_metafile::Text::transform`). +pub struct MetafileTextLayout { + pub em: f64, + pub baseline: f64, + pub glyphs: Vec<(f64, f64)>, + /// The rectangle of the character cells (x0, y0, x1, y1): from the leftmost to the rightmost + /// pen position of the run, the font's ascent above the baseline and its descent below. An + /// opaque background fills it. + pub cell: [f64; 4], +} + +/// Lays out the shaped glyphs of `t`, given as (cluster byte offset, x advance, x offset, y offset) +/// in font units of a font with `upem` units per em, `ascent` above and `descent` below the +/// baseline. The font height is the em size when negative and the cell height (ascent plus +/// descent) when positive. The per-character advances `dx` place each cluster when there is one +/// per character. None when the size is not finite and positive. +pub fn metafile_text_layout( + t: &craft_metafile::Text, + upem: f64, + ascent: f64, + descent: f64, + glyphs: &[(usize, f64, f64, f64)], +) -> Option { + let upem = if upem.is_finite() && upem > 0.0 { upem } else { 1000.0 }; + let height = if t.font.height == 0.0 { METAFILE_DEFAULT_HEIGHT } else { f64::from(t.font.height) }; + let cell = ascent + descent; + let em = if height > 0.0 && cell.is_finite() && cell > 0.0 { height * upem / cell } else { height.abs() }; + if !em.is_finite() || em <= 0.0 { + return None; + } + let k = em / upem; + let starts: Vec = t.text.char_indices().map(|(i, _)| i).collect(); + let dx = (t.dx.len() == starts.len() && !starts.is_empty()).then(|| { + let mut cum = Vec::with_capacity(t.dx.len() + 1); + let mut x = 0.0; + cum.push(x); + for d in &t.dx { + x += f64::from(*d); + cum.push(x); + } + cum + }); + let mut out = Vec::with_capacity(glyphs.len()); + let (mut pen, mut cluster_pen, mut last) = (0.0, 0.0, None); + // The leftmost and rightmost pen positions: advances can move backward. + let (mut lo, mut hi) = (0.0f64, 0.0f64); + for &(cluster, adv, xo, yo) in glyphs { + let ci = starts.partition_point(|&b| b <= cluster).saturating_sub(1); + if last != Some(ci) { + cluster_pen = pen; + last = Some(ci); + } + let x = match &dx { + Some(cum) => cum.get(ci).copied().unwrap_or(0.0) + pen - cluster_pen, + None => pen, + }; + out.push((x + xo * k, -yo * k)); + pen += adv * k; + (lo, hi) = (lo.min(pen), hi.max(pen)); + } + if let Some(cum) = &dx { + (lo, hi) = cum.iter().fold((0.0f64, 0.0f64), |(l, h), x| (l.min(*x), h.max(*x))); + } + let width = dx.as_ref().and_then(|c| c.last().copied()).unwrap_or(pen); + let hoff = match t.h_align { + craft_metafile::HAlign::Left => 0.0, + craft_metafile::HAlign::Center => -width / 2.0, + craft_metafile::HAlign::Right => -width, + }; + let baseline = match t.v_align { + craft_metafile::VAlign::Top => ascent * k, + craft_metafile::VAlign::Baseline => 0.0, + craft_metafile::VAlign::Bottom => -descent * k, + }; + let glyphs = out.into_iter().map(|(x, y)| (x + hoff, y + baseline)).collect(); + let cell = [hoff + lo, baseline - ascent * k, hoff + hi, baseline + descent * k]; + Some(MetafileTextLayout { em, baseline, glyphs, cell }) +} + /// The characters of the watermark that draw as an empty box (glyph id 0), counted as /// [`DocLayout::missing_glyphs`] counts them; sorted by code point. The watermark is on every /// page, so it counts once. @@ -265,19 +353,19 @@ impl Found { /// The text runs of a metafile picture that the exporters draw (a run whose layout fails is not). fn meta_runs(bytes: &[u8]) -> Vec { - if !wordcraft_metafile::is_metafile(bytes) { + if !craft_metafile::is_metafile(bytes) { return Vec::new(); } - let Ok(pic) = wordcraft_metafile::parse(bytes) else { return Vec::new() }; + let Ok(pic) = craft_metafile::parse(bytes) else { return Vec::new() }; if !pic.has_size() { return Vec::new(); } let mut out = Vec::new(); for item in &pic.items { - let wordcraft_metafile::Item::Text(t) = item else { continue }; + let craft_metafile::Item::Text(t) = item else { continue }; let (face, shaped) = metafile_text_run(t); let glyphs: Vec<_> = shaped.iter().map(|g| (g.cluster, f64::from(g.x_advance), f64::from(g.x_offset), f64::from(g.y_offset))).collect(); - if t.layout(face.upem, face.ascent, face.descent, &glyphs).is_none() { + if metafile_text_layout(t, face.upem, face.ascent, face.descent, &glyphs).is_none() { continue; } let ranges = cluster_ranges(&t.text, &shaped); diff --git a/crates/layout/src/strict.rs b/crates/layout/src/strict.rs index c9dcfec389..e089f711cd 100644 --- a/crates/layout/src/strict.rs +++ b/crates/layout/src/strict.rs @@ -40,7 +40,7 @@ impl StrictOutput { /// decodes within the decode budget. The same decision `wordcraft-pdf` and `wordcraft-render` /// take, so a picture that fails here is drawn as a grey box (or not at all) by that output. pub fn media_check(bytes: &[u8], output: StrictOutput) -> Result<(), DrawFailure> { - if wordcraft_metafile::is_metafile(bytes) && wordcraft_metafile::parse(bytes).is_ok_and(|p| p.has_size()) { + if craft_metafile::is_metafile(bytes) && craft_metafile::parse(bytes).is_ok_and(|p| p.has_size()) { return Ok(()); } wordcraft_geom::picture::check_for_drawing(bytes, output.max_picture_side()) diff --git a/crates/layout/src/tests/missing_glyphs.rs b/crates/layout/src/tests/missing_glyphs.rs index 1a9444f346..e105797f8b 100644 --- a/crates/layout/src/tests/missing_glyphs.rs +++ b/crates/layout/src/tests/missing_glyphs.rs @@ -242,3 +242,62 @@ fn an_equation_run_names_each_glyphs_characters() { assert!(found.iter().any(|(t, g, _)| (t.contains('\u{1D44E}') || t == "ab") && *g == 2), "{found:?}"); assert!(found.iter().all(|(_, g, r)| g == r), "{found:?}"); } + +/// A metafile text run with the given font height and advances, left-aligned at the baseline. +fn meta_text(height: f32, dx: Vec) -> craft_metafile::Text { + craft_metafile::Text { + transform: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], + text: "ab".into(), + dx, + font: craft_metafile::Font { family: "Arial".into(), height, ..Default::default() }, + color: [0, 0, 0, 255], + background: Some([255, 255, 255, 255]), + h_align: craft_metafile::HAlign::Left, + v_align: craft_metafile::VAlign::Baseline, + clip: None, + region: None, + clips: Vec::new(), + } +} + +/// A metafile font height of 0 is the file's default size: a 16-unit cell. A negative height is +/// the em size, and a positive one the cell (ascent plus descent, 1200 units of a 1000-unit em +/// here). +#[test] +fn metafile_text_heights() { + let glyphs = [(0, 500.0, 0.0, 0.0), (1, 500.0, 0.0, 0.0)]; + let em = |h| crate::metafile_text_layout(&meta_text(h, Vec::new()), 1000.0, 900.0, 300.0, &glyphs).map(|l| l.em); + let near = |a: Option, b: f64| a.is_some_and(|a| (a - b).abs() < 1e-9); + assert!(near(em(0.0), 16.0 * 1000.0 / 1200.0), "{:?}", em(0.0)); + assert!(near(em(-10.0), 10.0), "{:?}", em(-10.0)); + assert!(near(em(24.0), 20.0), "a positive height is the cell: {:?}", em(24.0)); +} + +/// A cosmetic pen's dashes become whole output pixels (the shortest one pixel), a period under a +/// pixel draws solid, and so does a pattern that would split the path into too many pieces. +#[test] +fn metafile_dashes_follow_the_output_pixel() { + let cosmetic = crate::metafile_dashes(&[0.75, 0.25], true, 0.5, 100.0).unwrap_or_default(); + assert!(cosmetic.len() == 2 && (cosmetic[0] - 1.5).abs() < 1e-6 && (cosmetic[1] - 0.5).abs() < 1e-6, "{cosmetic:?}"); + assert_eq!(crate::metafile_dashes(&[3.0, 1.0], false, 0.5, 100.0), Some(vec![3.0, 1.0])); + assert_eq!(crate::metafile_dashes(&[0.2, 0.2], false, 0.5, 100.0), None, "a period under a pixel"); + assert_eq!(crate::metafile_dashes(&[1.0, 1.0], false, 0.5, 1e6), None, "a million pieces"); + assert_eq!(crate::metafile_dashes(&[1.0, -1.0], false, 0.5, 100.0), None, "a negative length"); + assert_eq!(crate::metafile_dashes(&[0.0, 0.0], true, 0.5, 100.0), None, "no length at all"); +} + +/// A negative crop side is no crop; the others stay as they are. +#[test] +fn negative_crop_sides_are_no_crop() { + assert_eq!(crate::crop_sides([-0.5, 0.25, f32::NAN, 1.5]), [0.0, 0.25, 0.0, 1.5]); + assert_eq!(crate::crop_window([-0.5, 0.0, 0.0, 0.0]), [0.0, 0.0, 1.0, 1.0]); +} + +/// The opaque background of a run whose advances move backward covers every pen position, not +/// only the run's total advance. +#[test] +fn metafile_text_cell_spans_backward_advances() { + let glyphs = [(0, 500.0, 0.0, 0.0), (1, 500.0, 0.0, 0.0)]; + let lay = crate::metafile_text_layout(&meta_text(-10.0, vec![50.0, -40.0]), 1000.0, 800.0, 200.0, &glyphs).expect("a layout"); + assert_eq!(lay.cell, [0.0, -8.0, 50.0, 2.0]); +} diff --git a/crates/metafile/Cargo.toml b/crates/metafile/Cargo.toml deleted file mode 100644 index 55e76c98ce..0000000000 --- a/crates/metafile/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "wordcraft-metafile" -version.workspace = true -edition.workspace = true -license.workspace = true -description = "WordCraft metafiles: parses Windows WMF and EMF records into a neutral vector model (paths and bitmaps)" - -[lints] -workspace = true - -[dependencies] -kurbo = { workspace = true } -thiserror = { workspace = true } diff --git a/crates/metafile/src/bytes.rs b/crates/metafile/src/bytes.rs deleted file mode 100644 index 5584d6dff8..0000000000 --- a/crates/metafile/src/bytes.rs +++ /dev/null @@ -1,59 +0,0 @@ -//! Bounds-checked little-endian access to hostile input. Every read returns `None` past the end, so -//! a truncated or lying size field stops the parse instead of panicking. - -#[derive(Clone, Copy)] -pub(crate) struct Bytes<'a>(pub(crate) &'a [u8]); - -impl<'a> Bytes<'a> { - pub fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { - self.0.get(off..off.checked_add(len)?) - } - - pub fn tail(&self, off: usize) -> Option> { - self.0.get(off..).map(Bytes) - } - - fn arr(&self, off: usize) -> Option<[u8; N]> { - self.slice(off, N)?.try_into().ok() - } - - pub fn u16(&self, off: usize) -> Option { - Some(u16::from_le_bytes(self.arr(off)?)) - } - - pub fn i16(&self, off: usize) -> Option { - Some(i16::from_le_bytes(self.arr(off)?)) - } - - pub fn u32(&self, off: usize) -> Option { - Some(u32::from_le_bytes(self.arr(off)?)) - } - - pub fn i32(&self, off: usize) -> Option { - Some(i32::from_le_bytes(self.arr(off)?)) - } - - pub fn f32(&self, off: usize) -> Option { - Some(f32::from_le_bytes(self.arr(off)?)) - } - - /// `n` consecutive (x, y) pairs of 16- or 32-bit signed integers starting at `off`. - pub fn points(&self, off: usize, n: usize, wide: bool) -> Option> { - let sz = if wide { 8 } else { 4 }; - let raw = self.slice(off, n.checked_mul(sz)?)?; - let mut out = Vec::with_capacity(n); - for c in raw.chunks_exact(sz) { - let p = if wide { - let x = i32::from_le_bytes(c.get(0..4)?.try_into().ok()?); - let y = i32::from_le_bytes(c.get(4..8)?.try_into().ok()?); - (f64::from(x), f64::from(y)) - } else { - let x = i16::from_le_bytes(c.get(0..2)?.try_into().ok()?); - let y = i16::from_le_bytes(c.get(2..4)?.try_into().ok()?); - (f64::from(x), f64::from(y)) - }; - out.push(p); - } - Some(out) - } -} diff --git a/crates/metafile/src/canvas.rs b/crates/metafile/src/canvas.rs deleted file mode 100644 index bb6ecd3167..0000000000 --- a/crates/metafile/src/canvas.rs +++ /dev/null @@ -1,812 +0,0 @@ -//! Drawing state shared by the WMF and EMF readers: window/viewport mapping and the EMF world -//! transform, pen and brush selection through an object table, the DC save stack and path brackets. -//! Output is device-space items; `lib.rs` maps them into the picture frame. - -use crate::dib::Rgba; -use crate::geom::{Op, P}; -use crate::{MAX_BYTES, MAX_ITEMS, MAX_OBJECTS, MAX_PATH_OPS, MAX_STACK}; - -pub(crate) const MM_TEXT: u32 = 1; -const MM_ISOTROPIC: u32 = 7; -const MM_ANISOTROPIC: u32 = 8; -const STOCK: u32 = 0x8000_0000; -pub(crate) const PS_NULL: u32 = 5; -/// Pen style bits; the rest of the style word holds end-cap, join and type flags. -pub(crate) const PS_STYLE_MASK: u32 = 0x0F; -const BS_SOLID: u32 = 0; -pub(crate) const BS_NULL: u32 = 1; -const WINDING: u32 = 2; -/// SETROP2 mix mode that leaves the destination alone: outlines and fills draw nothing. -const R2_NOP: u32 = 11; -const PATCOPY: u32 = 0x00F0_0021; -const BLACKNESS: u32 = 0x0000_0042; -const WHITENESS: u32 = 0x00FF_0062; -/// SETTEXTALIGN: draw at and update the current point. -const TA_UPDATECP: u32 = 1; -/// Font height (cell height, logical units) of the default font, used for a height of 0. -const DEFAULT_FONT_HEIGHT: f64 = 16.0; -/// Face used when a font names none. -const DEFAULT_FONT_FACE: &str = "Arial"; -/// Device pixels per millimetre assumed for WMF (96 dpi), and for EMF files without a device size. -const DEFAULT_PX_PER_MM: f64 = 96.0 / 25.4; - -/// Affine transform `[m11, m12, m21, m22, dx, dy]` in EMF XFORM order: `x' = x·m11 + y·m21 + dx`. -pub(crate) type Xform = [f64; 6]; -const IDENTITY: Xform = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; - -/// `a` then `b` in EMF row-vector convention: the matrix product `a × b`. -pub(crate) fn mul(a: Xform, b: Xform) -> Xform { - [ - a[0] * b[0] + a[1] * b[2], - a[0] * b[1] + a[1] * b[3], - a[2] * b[0] + a[3] * b[2], - a[2] * b[1] + a[3] * b[3], - a[4] * b[0] + a[5] * b[2] + b[4], - a[4] * b[1] + a[5] * b[3] + b[5], - ] -} - -#[derive(Clone, Copy, PartialEq, Debug)] -pub(crate) struct Pen { - pub style: u32, - /// Logical width; 0 means a cosmetic one-pixel hairline. - pub width: f64, - pub color: [u8; 4], -} - -#[derive(Clone, Copy, PartialEq, Debug)] -pub(crate) struct Brush { - pub style: u32, - pub color: [u8; 4], -} - -/// A logical font (EMF LogFont): height in logical units (negative = character height, positive = -/// cell height, 0 = default), escapement in tenths of a degree, face name as UTF-16 (NUL-padded). -#[derive(Clone, Copy, PartialEq, Debug)] -pub(crate) struct Font { - pub height: i32, - pub escapement: i32, - pub weight: i32, - pub italic: bool, - pub face: [u16; 32], -} - -#[derive(Clone, Copy, Debug)] -pub(crate) enum Obj { - Pen(Pen), - Brush(Brush), - Font(Font), - /// Palettes, pattern brushes and regions: they take a table slot but draw nothing. - Other, -} - -/// Converts a COLORREF (0x00BBGGRR) to opaque RGBA. -pub(crate) fn colorref(c: u32) -> [u8; 4] { - [(c & 0xFF) as u8, ((c >> 8) & 0xFF) as u8, ((c >> 16) & 0xFF) as u8, 255] -} - -/// Millimetres per logical unit of the metric map modes (LOMETRIC, HIMETRIC, LOENGLISH, HIENGLISH, TWIPS). -fn metric_mm(mode: u32) -> Option { - match mode { - 2 => Some(0.1), - 3 => Some(0.01), - 4 => Some(25.4 / 100.0), - 5 => Some(25.4 / 1000.0), - 6 => Some(25.4 / 1440.0), - _ => None, - } -} - -#[derive(Clone, Copy)] -pub(crate) struct Mapping { - wo: P, - we: P, - vo: P, - ve: P, - mode: u32, - world: Xform, - /// Device pixels per millimetre on each axis (EMF: from szlDevice and szlMillimeters). - px_mm: P, -} - -impl Mapping { - fn identity() -> Self { - Mapping { - wo: (0.0, 0.0), - we: (1.0, 1.0), - vo: (0.0, 0.0), - ve: (1.0, 1.0), - mode: MM_TEXT, - world: IDENTITY, - px_mm: (DEFAULT_PX_PER_MM, DEFAULT_PX_PER_MM), - } - } - - /// Logical point to device point: world transform, then window to viewport. - pub fn device(&self, p: P) -> P { - let w = self.world; - let (x, y) = (p.0 * w[0] + p.1 * w[2] + w[4], p.0 * w[1] + p.1 * w[3] + w[5]); - let (sx, sy) = self.ratios(); - ((x - self.wo.0) * sx + self.vo.0, (y - self.wo.1) * sy + self.vo.1) - } - - /// Window-to-viewport scale per axis. MM_TEXT fixes the scale at 1; the metric modes use a fixed - /// scale with y up; MM_ISOTROPIC uses one scale on both axes (the smaller magnitude, each axis's - /// sign kept); anisotropic and unknown modes use the extents as given. - fn ratios(&self) -> (f64, f64) { - if self.mode == MM_TEXT { - return (1.0, 1.0); - } - if let Some(mm) = metric_mm(self.mode) { - return (mm * self.px_mm.0, -mm * self.px_mm.1); - } - let (rx, ry) = (ratio(self.ve.0, self.we.0), ratio(self.ve.1, self.we.1)); - if self.mode == MM_ISOTROPIC { - let s = rx.abs().min(ry.abs()); - return (if rx < 0.0 { -s } else { s }, if ry < 0.0 { -s } else { s }); - } - (rx, ry) - } - - /// Approximate device length per logical length, for pen widths. - fn scale(&self) -> f64 { - let w = self.world; - let det = (w[0] * w[3] - w[1] * w[2]).abs().sqrt(); - let (sx, sy) = self.ratios(); - det * (sx.abs() + sy.abs()) / 2.0 - } - - /// True when the window-to-viewport extents set the scale (the isotropic and anisotropic modes). - pub fn uses_extents(&self) -> bool { - matches!(self.mode, MM_ISOTROPIC | MM_ANISOTROPIC) - } - - pub fn window_ext(&self) -> P { - self.we - } - - pub fn viewport_ext(&self) -> P { - self.ve - } - - /// The window in device units as `[x, y, w, h]` with positive extents, used as the picture frame - /// of a plain WMF. - pub fn window_rect(&self) -> [f64; 4] { - let a = self.device(self.wo); - let b = self.device((self.wo.0 + self.we.0, self.wo.1 + self.we.1)); - [a.0.min(b.0), a.1.min(b.1), (b.0 - a.0).abs(), (b.1 - a.1).abs()] - } -} - -fn ratio(num: f64, den: f64) -> f64 { - if den == 0.0 { 1.0 } else { num / den } -} - -/// Output of drawing, in device units. Path points are already mapped; `lib.rs` normalises them. -pub(crate) enum Raw { - Path { ops: Vec, fill: Option<[u8; 4]>, stroke: Option<([u8; 4], f64)>, even_odd: bool }, - Bitmap { rect: [f64; 4], img: Rgba }, - Text(RawText), -} - -/// A text run in device units: the reference point, the font height along the text's up direction, -/// the baseline angle (radians, clockwise in y-down space) and per-character advances. -pub(crate) struct RawText { - pub text: String, - pub origin: P, - pub size: f64, - pub cell: bool, - pub angle: f64, - pub dx: Vec, - pub font: String, - pub bold: bool, - pub italic: bool, - pub color: [u8; 4], - pub align: u32, -} - -#[derive(Clone)] -struct Saved { - map: Mapping, - pen: Pen, - brush: Brush, - even_odd: bool, - nop: bool, - font: Option, - text_color: [u8; 4], - text_align: u32, -} - -pub(crate) struct Canvas { - pub items: Vec, - pub map: Mapping, - /// True once SETWINDOWEXT was seen, so a plain WMF has a frame to use. - pub window_set: bool, - /// True once the file set the viewport extent itself (not the player, see [`Canvas::play_into`]). - pub viewport_set: bool, - saved: Vec, - /// Bytes held by the items so far (path ops and pixels), capped at [`MAX_BYTES`]. - used: usize, - objects: Vec>, - /// Indices below `objects.len()` that hold no object, so the WMF handle table finds its lowest - /// free slot without scanning. - free: std::collections::BTreeSet, - /// Table slots examined by `add_object(None, ..)`; the tests assert it stays constant per call. - #[cfg(test)] - pub slot_probes: usize, - pen: Pen, - brush: Brush, - even_odd: bool, - /// The mix mode is R2_NOP: shapes draw nothing. - nop: bool, - /// The selected font; None is the default font. - font: Option, - text_color: [u8; 4], - /// SETTEXTALIGN flags (TA_*). - text_align: u32, - pos: P, - in_path: bool, - path: Vec, - full: bool, -} - -impl Canvas { - pub fn new() -> Self { - Canvas { - items: Vec::new(), - map: Mapping::identity(), - window_set: false, - viewport_set: false, - saved: Vec::new(), - used: 0, - objects: Vec::new(), - free: std::collections::BTreeSet::new(), - #[cfg(test)] - slot_probes: 0, - pen: Pen { style: 0, width: 0.0, color: [0, 0, 0, 255] }, - brush: Brush { style: BS_SOLID, color: [255, 255, 255, 255] }, - even_odd: true, - nop: false, - font: None, - text_color: [0, 0, 0, 255], - text_align: 0, - pos: (0.0, 0.0), - in_path: false, - path: Vec::new(), - full: false, - } - } - - /// True once the item cap is hit; the readers stop there and keep what they have. - pub fn full(&self) -> bool { - self.full - } - - fn push(&mut self, raw: Raw) { - let cost = match &raw { - // What is held, capacity and all. - Raw::Path { ops, .. } => ops.capacity().saturating_mul(std::mem::size_of::()), - Raw::Bitmap { img, .. } => img.px.capacity(), - Raw::Text(t) => { - t.text.capacity().saturating_add(t.font.capacity()).saturating_add(t.dx.capacity().saturating_mul(std::mem::size_of::())) - } - }; - if self.items.len() >= MAX_ITEMS || self.used.saturating_add(cost) > MAX_BYTES { - self.full = true; - } else { - self.used += cost; - self.items.push(raw); - } - } - - pub fn set_window_org(&mut self, p: P) { - self.map.wo = p; - } - - pub fn set_window_ext(&mut self, e: P) { - self.map.we = e; - self.window_set = true; - } - - pub fn set_viewport_org(&mut self, p: P) { - self.map.vo = p; - } - - pub fn set_viewport_ext(&mut self, e: P) { - self.map.ve = e; - self.viewport_set = true; - } - - /// Sets up the mapping the way a player does before it plays a WMF into a target: anisotropic, - /// `window` (`[x, y, w, h]` in logical units) onto a viewport of `size` at the origin. The file's - /// own window records then replace the window; the viewport stays unless the file sets one. - /// Without a window (a plain WMF) only the viewport extent is set: the map mode and viewport - /// origin stay the file's. - pub fn play_into(&mut self, window: Option<[f64; 4]>, size: P) { - if let Some([x, y, w, h]) = window { - self.map.mode = MM_ANISOTROPIC; - self.map.wo = (x, y); - self.map.we = (w, h); - self.map.vo = (0.0, 0.0); - } - self.map.ve = size; - } - - pub fn set_map_mode(&mut self, mode: u32) { - self.map.mode = mode; - } - - /// Device pixels per millimetre (x, y) for the metric map modes. Ignored unless both are positive. - pub fn set_device_mm(&mut self, px_mm: P) { - if px_mm.0.is_finite() && px_mm.1.is_finite() && px_mm.0 > 0.0 && px_mm.1 > 0.0 { - self.map.px_mm = px_mm; - } - } - - pub fn set_polyfill(&mut self, mode: u32) { - self.even_odd = mode != WINDING; - } - - /// SETROP2: only R2_NOP changes what is drawn (nothing); the other mix modes draw as copy. - pub fn set_rop2(&mut self, mode: u32) { - self.nop = mode == R2_NOP; - } - - /// EMF SETWORLDTRANSFORM (`mode` 4) and MODIFYWORLDTRANSFORM (1 identity, 2 left, 3 right, 4 set). - /// An unknown mode leaves the world transform as it was. - pub fn modify_world(&mut self, x: Xform, mode: u32) { - match mode { - 1 => self.map.world = IDENTITY, - 2 => self.map.world = mul(x, self.map.world), - 3 => self.map.world = mul(self.map.world, x), - 4 => self.map.world = x, - _ => {} - } - } - - /// Pushes the drawing state. Past [`MAX_STACK`] levels the parse stops, since later restores - /// could no longer match the file. - pub fn save_dc(&mut self) { - if self.saved.len() < MAX_STACK { - self.saved.push(Saved { - map: self.map, - pen: self.pen, - brush: self.brush, - even_odd: self.even_odd, - nop: self.nop, - font: self.font, - text_color: self.text_color, - text_align: self.text_align, - }); - } else { - self.full = true; - } - } - - /// Negative `n` pops `-n` levels; positive `n` restores absolute level `n`. - pub fn restore_dc(&mut self, n: i32) { - let idx = if n < 0 { self.saved.len().checked_sub(n.unsigned_abs() as usize) } else { (n as usize).checked_sub(1) }; - let Some(idx) = idx else { return }; - let Some(s) = self.saved.get(idx).cloned() else { return }; - self.saved.truncate(idx); - self.map = s.map; - self.pen = s.pen; - self.brush = s.brush; - self.even_odd = s.even_odd; - self.nop = s.nop; - self.font = s.font; - self.text_color = s.text_color; - self.text_align = s.text_align; - } - - /// Stores an object in `slot` (EMF index), or in the lowest free slot (WMF handle table). - pub fn add_object(&mut self, slot: Option, obj: Obj) { - match slot { - Some(i) if i < MAX_OBJECTS => { - // Growing the table leaves the slots between the old end and `i` free. - self.free.extend(self.objects.len()..i); - if self.objects.len() <= i { - self.objects.resize(i + 1, None); - } - self.free.remove(&i); - if let Some(s) = self.objects.get_mut(i) { - *s = Some(obj); - } - } - Some(_) => {} - None => match self.free.pop_first() { - Some(i) => { - #[cfg(test)] - { - self.slot_probes += 1; - } - if let Some(s) = self.objects.get_mut(i) { - *s = Some(obj); - } - } - None if self.objects.len() < MAX_OBJECTS => self.objects.push(Some(obj)), - None => {} - }, - } - } - - pub fn delete_object(&mut self, i: u32) { - let i = i as usize; - if let Some(s) = self.objects.get_mut(i) { - *s = None; - self.free.insert(i); - } - } - - /// Selects an object by index; indices with the high bit set are stock objects. - pub fn select(&mut self, i: u32) { - if i & STOCK != 0 { - return self.select_stock(i & !STOCK); - } - match self.objects.get(i as usize).copied().flatten() { - Some(Obj::Pen(p)) => self.pen = p, - Some(Obj::Brush(b)) => self.brush = b, - Some(Obj::Font(f)) => self.font = Some(f), - Some(Obj::Other) | None => {} - } - } - - fn select_stock(&mut self, i: u32) { - let white = [255, 255, 255, 255]; - let black = [0, 0, 0, 255]; - let gray = |v: u8| Brush { style: BS_SOLID, color: [v, v, v, 255] }; - match i { - 0 | 18 => self.brush = Brush { style: BS_SOLID, color: white }, - 1 => self.brush = gray(192), - 2 => self.brush = gray(128), - 3 => self.brush = gray(64), - 4 => self.brush = Brush { style: BS_SOLID, color: black }, - 5 => self.brush = Brush { style: BS_NULL, color: black }, - 6 => self.pen = Pen { style: 0, width: 0.0, color: white }, - 7 | 19 => self.pen = Pen { style: 0, width: 0.0, color: black }, - 8 => self.pen = Pen { style: PS_NULL, width: 0.0, color: black }, - // The stock fonts (OEM, ANSI, system, device default...): the default font. - 10..=17 => self.font = None, - _ => {} - } - } - - fn map_op(&self, op: Op) -> Op { - match op { - Op::M(p) => Op::M(self.map.device(p)), - Op::L(p) => Op::L(self.map.device(p)), - Op::C(a, b, c) => Op::C(self.map.device(a), self.map.device(b), self.map.device(c)), - Op::Z => Op::Z, - } - } - - fn fill_color(&self) -> Option<[u8; 4]> { - (self.brush.style == BS_SOLID).then_some(self.brush.color) - } - - fn stroke_pen(&self) -> Option<([u8; 4], f64)> { - if (self.pen.style & PS_STYLE_MASK) == PS_NULL { - return None; - } - // A cosmetic pen (width 0) stays 0: the renderers draw that as a hairline. - let w = if self.pen.width == 0.0 { 0.0 } else { self.pen.width.abs() * self.map.scale() }; - Some((self.pen.color, w)) - } - - fn push_path_ops(&mut self, ops: impl IntoIterator) { - for op in ops { - if self.path.len() >= MAX_PATH_OPS { - return; - } - self.path.push(op); - } - } - - /// Draws logical-space ops with the current pen (`stroke`) and brush (`fill`), or appends them to - /// the open path bracket, where fill and stroke wait for FILLPATH/STROKEPATH. - pub fn shape(&mut self, mut dev: Vec, fill: bool, stroke: bool) { - // Maps in place: the caller's vector becomes the device-space path, no second copy. - for op in &mut dev { - *op = self.map_op(*op); - } - if self.in_path { - return self.push_path_ops(dev); - } - if self.nop { - return; - } - let fill = if fill { self.fill_color() } else { None }; - let stroke = if stroke { self.stroke_pen() } else { None }; - if (fill.is_none() && stroke.is_none()) || dev.len() < 2 { - return; - } - let even_odd = self.even_odd; - self.push(Raw::Path { ops: dev, fill, stroke, even_odd }); - } - - pub fn move_to(&mut self, p: P) { - if self.in_path { - self.push_path_ops([Op::M(self.map.device(p))]); - } - self.pos = p; - } - - /// LINETO from the current point, then moves the current point to `p`. - pub fn line_to(&mut self, p: P) { - self.line_chain(&[p], false, true); - } - - /// Lines from the current point through `pts` (POLYLINETO), or a polyline from the current point. - pub fn line_chain(&mut self, pts: &[P], fill: bool, stroke: bool) { - // Inside an open bracket the path already ends at the current point, so no MoveTo is needed. - let mut ops = if self.in_path && !self.path.is_empty() { Vec::new() } else { vec![Op::M(self.pos)] }; - ops.extend(pts.iter().map(|p| Op::L(*p))); - if let Some(last) = pts.last() { - self.pos = *last; - } - self.shape(ops, fill, stroke); - } - - /// POLYBEZIER: cubic segments that start a new figure at `from`. The current point is unchanged. - pub fn bezier(&mut self, from: P, pts: &[P]) { - let mut ops = vec![Op::M(from)]; - ops.extend(cubics(pts)); - self.shape(ops, false, true); - } - - /// POLYBEZIERTO: cubic segments from the current point through groups of three control or end - /// points; the current point moves to the last point. Inside an open bracket the path already - /// ends at the current point, so no MoveTo is needed. - pub fn bezier_to(&mut self, pts: &[P]) { - let mut ops = if self.in_path && !self.path.is_empty() { Vec::new() } else { vec![Op::M(self.pos)] }; - ops.extend(cubics(pts)); - if let Some(last) = pts.last() { - self.pos = *last; - } - self.shape(ops, false, true); - } - - pub fn poly(&mut self, pts: &[P], close: bool, fill: bool, stroke: bool) { - let Some(first) = pts.first() else { return }; - let mut ops = vec![Op::M(*first)]; - ops.extend(pts.iter().skip(1).map(|p| Op::L(*p))); - if close { - ops.push(Op::Z); - } - self.shape(ops, fill, stroke); - } - - pub fn begin_path(&mut self) { - self.in_path = true; - self.path.clear(); - } - - pub fn end_path(&mut self) { - self.in_path = false; - } - - pub fn close_figure(&mut self) { - if self.in_path { - self.push_path_ops([Op::Z]); - } - } - - /// FILLPATH, STROKEPATH and STROKEANDFILLPATH: paints the bracketed path and empties it. - pub fn paint_path(&mut self, fill: bool, stroke: bool) { - let ops = std::mem::take(&mut self.path); - if self.nop { - return; - } - let fill = if fill { self.fill_color() } else { None }; - let stroke = if stroke { self.stroke_pen() } else { None }; - if ops.len() < 2 || (fill.is_none() && stroke.is_none()) { - return; - } - let even_odd = self.even_odd; - self.push(Raw::Path { ops, fill, stroke, even_odd }); - } - - /// Fills a logical rectangle `[l, t, r, b]` with the current brush (nothing when it is not solid). - pub fn fill_brush_rect(&mut self, rect: [f64; 4]) { - if let Some(color) = self.fill_color() { - self.fill_rect_with(rect, color); - } - } - - /// Fills a logical rectangle `[l, t, r, b]` with a solid colour (ROP fills such as BLACKNESS). - pub fn fill_rect_with(&mut self, [l, t, r, b]: [f64; 4], color: [u8; 4]) { - let dev: Vec = crate::geom::rect(l, t, r, b).iter().map(|o| self.map_op(*o)).collect(); - self.push(Raw::Path { ops: dev, fill: Some(color), stroke: None, even_odd: true }); - } - - /// Whether a raster operation draws without a source bitmap (PATCOPY, BLACKNESS, WHITENESS). - pub fn sourceless(rop: u32) -> bool { - matches!(rop, PATCOPY | BLACKNESS | WHITENESS) - } - - /// 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. - 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]), - _ => {} - } - } - - pub fn set_text_color(&mut self, c: [u8; 4]) { - self.text_color = c; - } - - pub fn set_text_align(&mut self, a: u32) { - self.text_align = a; - } - - /// Draws `text` at the logical point `at` (the current point with TA_UPDATECP) with the selected - /// font, text colour and alignment. `dx` holds per-character logical advances (empty for the - /// font's own); with TA_UPDATECP the current point moves past them. - pub fn text(&mut self, at: P, text: String, dx: &[f64]) { - if text.is_empty() || self.in_path { - return; - } - let font = self.font.unwrap_or(Font { height: 0, escapement: 0, weight: 400, italic: false, face: [0; 32] }); - let at = if self.text_align & TA_UPDATECP != 0 { self.pos } else { at }; - if self.text_align & TA_UPDATECP != 0 { - self.pos = (at.0 + dx.iter().sum::(), at.1); - } - let height = if font.height == 0 { DEFAULT_FONT_HEIGHT } else { f64::from(font.height) }; - let origin = self.map.device(at); - let len = |v: P| { - let d = self.map.device((at.0 + v.0, at.1 + v.1)); - (d.0 - origin.0).hypot(d.1 - origin.1) - }; - let base = self.map.device((at.0 + 1.0, at.1)); - let escapement = f64::from(font.escapement) / 10.0; - let angle = (base.1 - origin.1).atan2(base.0 - origin.0) - escapement.to_radians(); - let size = len((0.0, height.abs())); - let dx = dx.iter().map(|d| len((*d, 0.0)).copysign(*d)).collect(); - let name = String::from_utf16_lossy(&font.face); - let name = name.trim_end_matches('\0').trim(); - let raw = RawText { - text, - origin, - size, - cell: height > 0.0, - angle: if angle.is_finite() { angle } else { 0.0 }, - dx, - font: if name.is_empty() { DEFAULT_FONT_FACE.to_string() } else { name.to_string() }, - bold: font.weight >= 600, - italic: font.italic, - color: self.text_color, - align: self.text_align, - }; - if raw.origin.0.is_finite() && raw.origin.1.is_finite() && raw.size.is_finite() && raw.size > 0.0 { - self.push(Raw::Text(raw)); - } - } - - /// A bitmap stretched into a logical rectangle `[x, y, w, h]`. A negative extent mirrors the - /// bitmap, as the mapping does. - pub fn bitmap(&mut self, rect: [f64; 4], mut img: Rgba) { - let [x, y, w, h] = rect; - let a = self.map.device((x, y)); - let b = self.map.device((x + w, y + h)); - crate::dib::flip(&mut img, a.0 > b.0, a.1 > b.1); - let dev = [a.0.min(b.0), a.1.min(b.1), (b.0 - a.0).abs(), (b.1 - a.1).abs()]; - self.push(Raw::Bitmap { rect: dev, img }); - } -} - -/// Cubic segments from groups of three points (control, control, end). A trailing partial group is -/// dropped. -fn cubics(pts: &[P]) -> Vec { - let mut ops = Vec::with_capacity(pts.len() / 3); - let mut it = pts.iter().copied(); - while let (Some(a), Some(b), Some(e)) = (it.next(), it.next(), it.next()) { - ops.push(Op::C(a, b, e)); - } - ops -} - -#[cfg(test)] -mod object_table_tests { - use super::*; - - fn pen(id: u32) -> Obj { - Obj::Pen(Pen { style: 0, width: 0.0, color: [id as u8, (id >> 8) as u8, 0, 255] }) - } - - fn id_of(o: &Option) -> Option { - match o { - Some(Obj::Pen(p)) => Some(u32::from(p.color[0]) | u32::from(p.color[1]) << 8), - _ => None, - } - } - - /// The table as it was before the free-slot set: a scan from index 0 for every handle-table create. - struct Naive(Vec>); - - impl Naive { - fn add(&mut self, slot: Option, id: u32) { - match slot { - Some(i) if i < MAX_OBJECTS => { - if self.0.len() <= i { - self.0.resize(i + 1, None); - } - self.0[i] = Some(id); - } - Some(_) => {} - None => match self.0.iter().position(Option::is_none) { - Some(i) => self.0[i] = Some(id), - None if self.0.len() < MAX_OBJECTS => self.0.push(Some(id)), - None => {} - }, - } - } - - fn delete(&mut self, i: u32) { - if let Some(s) = self.0.get_mut(i as usize) { - *s = None; - } - } - } - - #[test] - fn handle_table_picks_the_same_slots_as_the_first_free_scan() { - let mut seed = 0x9E37_79B9_7F4A_7C15u64; - let mut rnd = move |n: u64| { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - seed % n - }; - for round in 0..20 { - // Small tables exercise reuse; some rounds also run past the cap and use explicit EMF slots. - let span = if round % 2 == 0 { 12 } else { MAX_OBJECTS as u64 + 50 }; - let (mut cv, mut naive) = (Canvas::new(), Naive(Vec::new())); - for id in 0..20_000u32 { - match rnd(10) { - 0..=4 => { - cv.add_object(None, pen(id)); - naive.add(None, id); - } - 5 | 6 if round >= 10 => { - let slot = rnd(span + 20) as usize; - cv.add_object(Some(slot), pen(id)); - naive.add(Some(slot), id); - } - _ => { - let i = rnd(span + 5) as u32; - cv.delete_object(i); - naive.delete(i); - } - } - if id % 500 == 0 || id == 19_999 { - let got: Vec> = cv.objects.iter().map(id_of).collect(); - assert_eq!(got, naive.0, "round {round}, step {id}"); - } - } - } - } - - #[test] - fn creating_into_a_full_table_does_not_scan_it() { - let mut cv = Canvas::new(); - for i in 0..MAX_OBJECTS as u32 { - cv.add_object(None, pen(i)); - } - assert_eq!(cv.objects.len(), MAX_OBJECTS); - let before = cv.slot_probes; - for i in 0..10_000 { - cv.add_object(None, pen(i)); - } - // A scan from index 0 would examine 4096 slots per create; the free set examines none. - assert_eq!(cv.slot_probes, before); - cv.delete_object(7); - cv.add_object(None, pen(99)); - assert_eq!(cv.slot_probes, before + 1); - assert_eq!(cv.objects.get(7).map(id_of), Some(Some(99))); - } -} diff --git a/crates/metafile/src/dib.rs b/crates/metafile/src/dib.rs deleted file mode 100644 index 15be8aa3c0..0000000000 --- a/crates/metafile/src/dib.rs +++ /dev/null @@ -1,719 +0,0 @@ -//! Device-independent bitmaps. BITMAPINFOHEADER DIBs at 1/4/8/16/24/32 bpp with BI_RGB or BI_BITFIELDS -//! decode to RGBA8 rows, top-down. Compressed (RLE, JPEG, PNG) and V4/V5-only features are not decoded. - -use crate::{MAX_BITMAP_SIDE, MAX_PIXELS, bytes::Bytes}; - -const BI_RGB: u32 = 0; -const BI_BITFIELDS: u32 = 3; -/// Most palette entries a DIB can carry (the colour table never exceeds 2^8). -const MAX_PALETTE: usize = 256; -const ROP_SRCAND: u32 = 0x0088_00C6; -const ROP_SRCPAINT: u32 = 0x00EE_0086; -const ROP_SRCINVERT: u32 = 0x0066_0046; - -/// A decoded picture, rows top-down. -pub(crate) struct Rgba { - pub w: usize, - pub h: usize, - pub px: Vec, -} - -/// How a decoded bitmap combines with the destination. -#[derive(Clone, Copy)] -pub(crate) enum Blend { - /// A raster operation (BITBLT, STRETCHDIB and friends). - Rop(u32), - /// EMR_ALPHABLEND: a constant alpha (0..=255), times the per-pixel alpha when `per_pixel` is set - /// (AC_SRC_ALPHA: the source colours are premultiplied by it). - Alpha { constant: u8, per_pixel: bool }, -} - -impl Blend { - /// Whether the decoder must keep the 32-bit alpha byte of each pixel. - pub fn per_pixel(self) -> bool { - matches!(self, Blend::Alpha { per_pixel: true, .. }) - } -} - -struct Header { - w: usize, - h: usize, - top_down: bool, - bpp: usize, - masks: [u32; 3], - pal_off: usize, - pal_n: usize, -} - -impl Header { - fn read(info: Bytes) -> Option
{ - let size = info.u32(0)? as usize; - let w = info.i32(4)?; - let h = info.i32(8)?; - let bpp = info.u16(14)? as usize; - let comp = info.u32(16)?; - let clr_used = info.u32(32)? as usize; - if size < 40 || w <= 0 || h == 0 || !matches!(bpp, 1 | 4 | 8 | 16 | 24 | 32) || !matches!(comp, BI_RGB | BI_BITFIELDS) { - return None; - } - let masks = if comp == BI_BITFIELDS { - [info.u32(40)?, info.u32(44)?, info.u32(48)?] - } else if bpp == 16 { - [0x7C00, 0x03E0, 0x001F] - } else { - [0xFF_0000, 0xFF00, 0xFF] - }; - let masks_len = if comp == BI_BITFIELDS && size == 40 { 12 } else { 0 }; - let pal_off = size.checked_add(masks_len)?; - // Indexed formats take 2^bpp entries when clrUsed is 0. Deeper formats carry only the - // entries clrUsed names (WMF DIBs can have them), still capped. - let pal_n = match (bpp <= 8, clr_used) { - (true, 0) => 1usize << bpp, - (true, n) => n.min(1usize << bpp), - (false, n) => n.min(MAX_PALETTE), - }; - Some(Header { w: w as usize, h: h.unsigned_abs() as usize, top_down: h < 0, bpp, masks, pal_off, pal_n }) - } -} - -/// Byte length of the info part (header, masks, palette) of a DIB, so the pixel bits follow it. -pub(crate) fn info_len(dib: Bytes) -> Option { - let h = Header::read(dib)?; - h.pal_off.checked_add(h.pal_n.checked_mul(4)?) -} - -/// Decodes the part of a DIB that the source rectangle `src` = `[x, y, w, h]` selects and returns it -/// (top-down) with the part of the destination `dst` that it fills; see [`clip_rect`] for the -/// coordinates. `info` is the info part (header plus masks and palette) and `bits` the pixel bits. The -/// 32-bit alpha byte is kept only when `keep_alpha` is set (per-pixel alpha blends); otherwise pixels -/// are opaque. Only the clipped rows and columns are decoded, so the work and the memory follow the -/// crop, not the whole bitmap; the whole bitmap is still validated (size cap, palette, bits length). -/// None as well when the clipped width or height is over [`MAX_BITMAP_SIDE`], which no renderer draws. -pub(crate) fn decode_clip(info: Bytes, bits: Bytes, keep_alpha: bool, src: [i64; 4], dst: [f64; 4]) -> Option<(Rgba, [f64; 4])> { - let hd = Header::read(info)?; - let pixels = hd.w.checked_mul(hd.h)?; - if pixels == 0 || pixels > MAX_PIXELS { - return None; - } - let stride = hd.w.checked_mul(hd.bpp)?.checked_add(31)? / 32 * 4; - let data = bits.slice(0, stride.checked_mul(hd.h)?)?; - let pal = info.slice(hd.pal_off, hd.pal_n * 4)?; - let (clip, out) = clip_rect(hd.w, hd.h, !hd.top_down, src, dst)?; - // The renderers draw no bitmap with a side over the cap (`Item::take_pixels`); decoding one - // would only fill the parse's memory budget with pixels nobody draws. - let cap = MAX_BITMAP_SIDE as usize; - if clip.x1 - clip.x0 > cap || clip.r1 - clip.r0 > cap { - return None; - } - let (ow, oh) = (clip.x1 - clip.x0, clip.r1 - clip.r0); - let mut px = vec![0u8; ow.checked_mul(oh)?.checked_mul(4)?]; - #[cfg(test)] - DECODED.with(|d| d.set(d.get() + ow * oh)); - // The depth, palette and masks are the same for every pixel: pick the row decoder once. - let kind = RowKind::new(&hd, pal, keep_alpha); - for (y, line) in (clip.r0..clip.r1).zip(px.chunks_exact_mut(ow * 4)) { - let src_row = if hd.top_down { y } else { hd.h - 1 - y }; - let row = data.get(src_row * stride..(src_row + 1) * stride)?; - kind.decode_row(row, clip.x0..clip.x1, line.as_chunks_mut::<4>().0)?; - } - Some((Rgba { w: ow, h: oh, px }, out)) -} - -#[cfg(test)] -thread_local! { - /// Pixels asked of the decoder on this thread, so the tests can check that the work follows the crop. - static DECODED: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// One channel of a masked 16/32 bpp pixel, with the shift and scale worked out once per bitmap. -/// Channels of up to 8 bits (every common 16 bpp layout) go through a table of their values, so a -/// pixel costs no division. -#[derive(Clone)] -struct Channel { - mask: u32, - shift: u32, - max: u64, - table: [u8; 256], -} - -impl Channel { - fn new(mask: u32) -> Channel { - let shift = if mask == 0 { 0 } else { mask.trailing_zeros() }; - let max = u64::from(mask >> shift); - let mut table = [0u8; 256]; - if mask != 0 && max <= 255 { - for (val, t) in table.iter_mut().enumerate().take(max as usize + 1) { - *t = ((val as u64 * 255 + max / 2) / max) as u8; - } - } - Channel { mask, shift, max, table } - } - - /// The channel of `v` scaled to 8 bits; 0 when the mask is empty. - fn get(&self, v: u32) -> u8 { - if self.mask == 0 { - return 0; - } - let val = u64::from((v & self.mask) >> self.shift); - if self.max <= 255 { - return self.table[usize::from(val as u8)]; - } - ((val * 255 + self.max / 2) / self.max) as u8 - } -} - -/// How the pixels of one DIB turn into RGBA, decided once from its header. -enum RowKind { - /// 1, 4 or 8 bpp: `bpp` bits per index into a table of every possible index. - Indexed { bpp: usize, table: Box<[[u8; 4]; 256]> }, - /// 24 bpp: BGR triples. - Bgr24, - /// 32 bpp with the default masks: BGRA quads, alpha kept or forced opaque. - Bgra32 { keep_alpha: bool }, - /// 16 bpp, or 32 bpp with other masks. - Masked { bpp: usize, ch: Box<[Channel; 3]>, keep_alpha: bool }, -} - -impl RowKind { - fn new(hd: &Header, pal: &[u8], keep_alpha: bool) -> RowKind { - match hd.bpp { - 1 | 4 | 8 => { - // An index past the palette reads as black, as in `palette`. - let mut table = Box::new([[0u8, 0, 0, 255]; 256]); - for (i, t) in table.iter_mut().enumerate().take(1 << hd.bpp) { - let [r, g, b] = palette(pal, i); - *t = [r, g, b, 255]; - } - RowKind::Indexed { bpp: hd.bpp, table } - } - 24 => RowKind::Bgr24, - 32 if hd.masks == [0xFF_0000, 0xFF00, 0xFF] => RowKind::Bgra32 { keep_alpha }, - _ => RowKind::Masked { bpp: hd.bpp, ch: Box::new(hd.masks.map(Channel::new)), keep_alpha }, - } - } - - /// Decodes the columns `cols` of one source row `row` (all of its bytes) into `out`. `None` when - /// the row is shorter than the columns need. - fn decode_row(&self, row: &[u8], cols: std::ops::Range, out: &mut [[u8; 4]]) -> Option<()> { - match self { - RowKind::Indexed { bpp: 8, table } => { - for (d, s) in out.iter_mut().zip(row.get(cols)?) { - *d = table[usize::from(*s)]; - } - } - RowKind::Indexed { bpp: 4, table } => { - for (d, x) in out.iter_mut().zip(cols) { - let b = *row.get(x / 2)?; - *d = table[usize::from(if x.is_multiple_of(2) { b >> 4 } else { b & 0x0F })]; - } - } - RowKind::Indexed { table, .. } => { - for (d, x) in out.iter_mut().zip(cols) { - let b = *row.get(x / 8)?; - *d = table[usize::from((b >> (7 - x % 8)) & 1)]; - } - } - RowKind::Bgr24 => { - let src = row.get(cols.start.checked_mul(3)?..cols.end.checked_mul(3)?)?; - for (d, s) in out.iter_mut().zip(src.as_chunks::<3>().0) { - *d = [s[2], s[1], s[0], 255]; - } - } - RowKind::Bgra32 { keep_alpha } => { - let src = row.get(cols.start.checked_mul(4)?..cols.end.checked_mul(4)?)?; - for (d, s) in out.iter_mut().zip(src.as_chunks::<4>().0) { - *d = [s[2], s[1], s[0], if *keep_alpha { s[3] } else { 255 }]; - } - } - RowKind::Masked { bpp: 16, ch, .. } => { - let [r, g, b] = &**ch; - let src = row.get(cols.start.checked_mul(2)?..cols.end.checked_mul(2)?)?; - for (d, s) in out.iter_mut().zip(src.as_chunks::<2>().0) { - let v = u32::from(u16::from_le_bytes(*s)); - *d = [r.get(v), g.get(v), b.get(v), 255]; - } - } - RowKind::Masked { ch, keep_alpha, .. } => { - let [r, g, b] = &**ch; - let src = row.get(cols.start.checked_mul(4)?..cols.end.checked_mul(4)?)?; - for (d, s) in out.iter_mut().zip(src.as_chunks::<4>().0) { - let v = u32::from_le_bytes(*s); - *d = [r.get(v), g.get(v), b.get(v), if *keep_alpha { (v >> 24) as u8 } else { 255 }]; - } - } - } - Some(()) - } -} - -/// Palette entries are BGRX quads; an index past the table reads as black rather than failing the image. -fn palette(pal: &[u8], i: usize) -> [u8; 3] { - pal.get(i * 4..i * 4 + 4).and_then(|c| <[u8; 4]>::try_from(c).ok()).map_or([0, 0, 0], |c| [c[2], c[1], c[0]]) -} - -/// The columns `x0..x1` and top-down rows `r0..r1` of a bitmap that a clipped source rectangle covers. -struct Clip { - x0: usize, - x1: usize, - r0: usize, - r1: usize, -} - -/// Clips a source rectangle `src` = `[x, y, w, h]` to a `w` x `h` bitmap and returns the covered pixels -/// with the part of the destination `dst` that they fill. `src` is in DIB pixel coordinates (`y` counted -/// from the DIB's origin, so bottom-up images count from the bottom); a non-positive source size means the -/// whole bitmap. Clipping shrinks the destination by the same ratio and shifts it by the clipped-off part, -/// so the rest of the image keeps its place. A negative destination extent is kept (the caller mirrors). -/// `None` when nothing of the bitmap is covered. -fn clip_rect(w: usize, h: usize, bottom_up: bool, src: [i64; 4], dst: [f64; 4]) -> Option<(Clip, [f64; 4])> { - let (iw, ih) = (w as i64, h as i64); - let [sx, sy, sw, sh] = if src[2] > 0 && src[3] > 0 { src } else { [0, 0, iw, ih] }; - // The request's top row in top-down order. - let top = if bottom_up { ih.saturating_sub(sy).saturating_sub(sh) } else { sy }; - let (x0, x1) = (sx.max(0), sx.saturating_add(sw).min(iw)); - let (r0, r1) = (top.max(0), top.saturating_add(sh).min(ih)); - if x1 <= x0 || r1 <= r0 { - return None; - } - let (kx, ky) = (dst[2] / sw as f64, dst[3] / sh as f64); - let out = [dst[0] + (x0 - sx) as f64 * kx, dst[1] + (r0 - top) as f64 * ky, (x1 - x0) as f64 * kx, (r1 - r0) as f64 * ky]; - Some((Clip { x0: x0 as usize, x1: x1 as usize, r0: r0 as usize, r1: r1 as usize }, out)) -} - -/// Applies a blend to decoded pixels before they are drawn. The picture has no destination pixels, so -/// raster operations are drawn as they look over white paper: SRCAND (destination AND source) leaves -/// white source pixels out and draws the rest; SRCPAINT and SRCINVERT leave black ones out. Other -/// operations draw the source as copied. Constant alpha scales every pixel's alpha, after a -/// per-pixel (premultiplied) source is made straight. -pub(crate) fn prepare(img: &mut Rgba, blend: Blend) { - match blend { - Blend::Rop(ROP_SRCAND) => clear_where(img, [255, 255, 255]), - Blend::Rop(ROP_SRCPAINT | ROP_SRCINVERT) => clear_where(img, [0, 0, 0]), - Blend::Rop(_) => {} - Blend::Alpha { constant, per_pixel } => { - for p in img.px.as_chunks_mut::<4>().0 { - if per_pixel { - unpremultiply(p); - } - p[3] = (u16::from(p[3]) * u16::from(constant) / 255) as u8; - } - } - } -} - -/// Makes the pixels of colour `rgb` transparent: where a raster operation keeps the destination. -fn clear_where(img: &mut Rgba, rgb: [u8; 3]) { - for p in img.px.as_chunks_mut::<4>().0 { - if p[..3] == rgb { - p[3] = 0; - } - } -} - -/// AC_SRC_ALPHA sources are premultiplied; the model holds straight RGBA, so divide the colour by the -/// alpha (rounded, capped at 255). A transparent pixel keeps its colour bytes. -fn unpremultiply(p: &mut [u8; 4]) { - let a = u32::from(p[3]); - if a == 0 || a == 255 { - return; - } - for c in &mut p[..3] { - *c = ((u32::from(*c) * 255 + a / 2) / a).min(255) as u8; - } -} - -/// Mirrors a decoded image left-right and/or top-bottom. Rows come from the buffer as chunks, so a -/// short buffer flips only the rows it has. -pub(crate) fn flip(img: &mut Rgba, horizontal: bool, vertical: bool) { - let (w, h) = (img.w, img.h); - if w == 0 || h == 0 { - return; - } - let row = w * 4; - if horizontal { - for line in img.px.chunks_exact_mut(row) { - for x in 0..w / 2 { - for c in 0..4 { - line.swap(x * 4 + c, (w - 1 - x) * 4 + c); - } - } - } - } - if vertical { - // Rows the buffer actually holds: a short buffer flips only those. - let n = h.min(img.px.len() / row); - for y in 0..n / 2 { - swap_rows(&mut img.px, y * row, (n - 1 - y) * row, row); - } - } -} - -/// Swaps the `len` bytes at `a` with those at `b` (`a < b`); does nothing when either is out of range. -fn swap_rows(px: &mut [u8], a: usize, b: usize, len: usize) { - let Some((head, tail)) = px.split_at_mut_checked(b) else { return }; - if let (Some(top), Some(bottom)) = (head.get_mut(a..a.saturating_add(len)), tail.get_mut(..len)) { - top.swap_with_slice(bottom); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The pipeline before `decode_clip`: decode the whole bitmap, then copy the clipped part out. - fn decode_whole(info: Bytes, bits: Bytes, keep_alpha: bool) -> Option { - let hd = Header::read(info)?; - let pixels = hd.w.checked_mul(hd.h)?; - if pixels == 0 || pixels > MAX_PIXELS { - return None; - } - let stride = hd.w.checked_mul(hd.bpp)?.checked_add(31)? / 32 * 4; - let data = bits.slice(0, stride.checked_mul(hd.h)?)?; - let pal = info.slice(hd.pal_off, hd.pal_n * 4)?; - let mut px = vec![0u8; pixels * 4]; - for y in 0..hd.h { - let src_row = if hd.top_down { y } else { hd.h - 1 - y }; - let row = src_row * stride; - for x in 0..hd.w { - let p = pixel(data, row, x, &hd, pal, keep_alpha)?; - let o = (y * hd.w + x) * 4; - px.get_mut(o..o + 4)?.copy_from_slice(&p); - } - } - Some(Rgba { w: hd.w, h: hd.h, px }) - } - - fn clip_blit_whole(img: &Rgba, bottom_up: bool, src: [i64; 4], dst: [f64; 4]) -> Option<(Rgba, [f64; 4])> { - let (iw, ih) = (img.w as i64, img.h as i64); - let [sx, sy, sw, sh] = if src[2] > 0 && src[3] > 0 { src } else { [0, 0, iw, ih] }; - let top = if bottom_up { ih.saturating_sub(sy).saturating_sub(sh) } else { sy }; - let (x0, x1) = (sx.max(0), sx.saturating_add(sw).min(iw)); - let (r0, r1) = (top.max(0), top.saturating_add(sh).min(ih)); - if x1 <= x0 || r1 <= r0 { - return None; - } - let (kx, ky) = (dst[2] / sw as f64, dst[3] / sh as f64); - let out = [dst[0] + (x0 - sx) as f64 * kx, dst[1] + (r0 - top) as f64 * ky, (x1 - x0) as f64 * kx, (r1 - r0) as f64 * ky]; - let (x0, x1, r0, r1) = (x0 as usize, x1 as usize, r0 as usize, r1 as usize); - let (ow, oh) = (x1 - x0, r1 - r0); - let mut px = Vec::with_capacity(ow * oh * 4); - for row in r0..r1 { - let s = (row * img.w + x0) * 4; - px.extend_from_slice(img.px.get(s..s + ow * 4)?); - } - Some((Rgba { w: ow, h: oh, px }, out)) - } - - /// A BITMAPINFOHEADER DIB with a palette for indexed depths; returns (info, bits). - fn make_dib(w: usize, h: i32, bpp: usize, seed: &mut u64) -> (Vec, Vec) { - let mut rnd = || { - *seed ^= *seed << 13; - *seed ^= *seed >> 7; - *seed ^= *seed << 17; - *seed - }; - let mut info = Vec::new(); - info.extend(40u32.to_le_bytes()); - info.extend((w as i32).to_le_bytes()); - info.extend(h.to_le_bytes()); - info.extend(1u16.to_le_bytes()); - info.extend((bpp as u16).to_le_bytes()); - info.extend([0u8; 24]); - if bpp <= 8 { - for _ in 0..(1usize << bpp) * 4 { - info.push(rnd() as u8); - } - } - let stride = (w * bpp).div_ceil(32) * 4; - let bits = (0..stride * h.unsigned_abs() as usize).map(|_| rnd() as u8).collect(); - (info, bits) - } - - /// The per-pixel decoder `decode_clip` used before the depth was chosen once per bitmap. Kept as - /// the reference the fast decoder must match byte for byte. - fn pixel(data: &[u8], row: usize, x: usize, hd: &Header, pal: &[u8], keep_alpha: bool) -> Option<[u8; 4]> { - DECODED.with(|d| d.set(d.get() + 1)); - let [m_r, m_g, m_b] = hd.masks; - let [r, g, b] = match hd.bpp { - 1 => { - let b = *data.get(row + x / 8)?; - palette(pal, usize::from((b >> (7 - x % 8)) & 1)) - } - 4 => { - let b = *data.get(row + x / 2)?; - palette(pal, usize::from(if x.is_multiple_of(2) { b >> 4 } else { b & 0x0F })) - } - 8 => palette(pal, usize::from(*data.get(row + x)?)), - 24 => { - let [b, g, r] = data.get(row + x * 3..row + x * 3 + 3)?.try_into().ok()?; - [r, g, b] - } - 16 => { - let o = row + x * 2; - let v = u32::from(u16::from_le_bytes(data.get(o..o + 2)?.try_into().ok()?)); - [field(v, m_r), field(v, m_g), field(v, m_b)] - } - _ => { - let o = row + x * 4; - let v = u32::from_le_bytes(data.get(o..o + 4)?.try_into().ok()?); - let a = if keep_alpha { (v >> 24) as u8 } else { 255 }; - return Some([field(v, m_r), field(v, m_g), field(v, m_b), a]); - } - }; - Some([r, g, b, 255]) - } - - /// Extracts one channel from a masked pixel value and scales it to 8 bits. - fn field(v: u32, mask: u32) -> u8 { - if mask == 0 { - return 0; - } - let shift = mask.trailing_zeros(); - let max = u64::from(mask >> shift); - let val = u64::from((v & mask) >> shift); - ((val * 255 + max / 2) / max) as u8 - } - - /// `decode_clip` as it was: the same clip, then `pixel` for every output pixel. - fn decode_clip_reference(info: Bytes, bits: Bytes, keep_alpha: bool, src: [i64; 4], dst: [f64; 4]) -> Option<(Rgba, [f64; 4])> { - let hd = Header::read(info)?; - let pixels = hd.w.checked_mul(hd.h)?; - if pixels == 0 || pixels > MAX_PIXELS { - return None; - } - let stride = hd.w.checked_mul(hd.bpp)?.checked_add(31)? / 32 * 4; - let data = bits.slice(0, stride.checked_mul(hd.h)?)?; - let pal = info.slice(hd.pal_off, hd.pal_n * 4)?; - let (clip, out) = clip_rect(hd.w, hd.h, !hd.top_down, src, dst)?; - let (ow, oh) = (clip.x1 - clip.x0, clip.r1 - clip.r0); - let mut px = vec![0u8; ow.checked_mul(oh)?.checked_mul(4)?]; - for (y, line) in (clip.r0..clip.r1).zip(px.chunks_exact_mut(ow * 4)) { - let src_row = if hd.top_down { y } else { hd.h - 1 - y }; - let row = src_row * stride; - for (x, dst_px) in (clip.x0..clip.x1).zip(line.as_chunks_mut::<4>().0) { - *dst_px = pixel(data, row, x, &hd, pal, keep_alpha)?; - } - } - Some((Rgba { w: ow, h: oh, px }, out)) - } - - /// A DIB with chosen header fields: `masks` makes it BI_BITFIELDS (inline after a 40 byte - /// header, or inside a larger header), `clr_used` limits the palette, and the palette, when the - /// depth is indexed, has `pal_entries` entries (fewer than the depth names reads as black). - fn make_dib_with( - w: usize, - h: i32, - bpp: usize, - masks: Option<([u32; 3], usize)>, - clr_used: u32, - pal_entries: usize, - seed: &mut u64, - ) -> (Vec, Vec) { - let mut rnd = || { - *seed ^= *seed << 13; - *seed ^= *seed >> 7; - *seed ^= *seed << 17; - *seed - }; - let size = masks.map_or(40, |(_, s)| s); - let mut info = Vec::new(); - info.extend((size as u32).to_le_bytes()); - info.extend((w as i32).to_le_bytes()); - info.extend(h.to_le_bytes()); - info.extend(1u16.to_le_bytes()); - info.extend((bpp as u16).to_le_bytes()); - info.extend(if masks.is_some() { 3u32 } else { 0 }.to_le_bytes()); - info.extend([0u8; 12]); - info.extend(clr_used.to_le_bytes()); - info.extend([0u8; 4]); - info.resize(size.max(40), 0); - if let Some((m, _)) = masks { - for (i, v) in m.iter().enumerate() { - let at = 40 + i * 4; - if size == 40 { - info.extend(v.to_le_bytes()); - } else if let Some(dst) = info.get_mut(at..at + 4) { - dst.copy_from_slice(&v.to_le_bytes()); - } - } - } - for _ in 0..pal_entries * 4 { - info.push(rnd() as u8); - } - let stride = (w * bpp).div_ceil(32) * 4; - let bits = (0..stride * h.unsigned_abs() as usize).map(|_| rnd() as u8).collect(); - (info, bits) - } - - fn assert_same(info: &[u8], bits: &[u8], what: &str) { - for keep_alpha in [false, true] { - for src in [[0, 0, 0, 0], [3, 1, 20, 3], [-4, -4, 100, 100], [36, 4, 5, 5], [1, 0, 1, 5], [8, 2, 17, 2], [0, 3, 37, 1]] { - let dst = [1.0, 2.0, 30.0, 40.0]; - let old = decode_clip_reference(Bytes(info), Bytes(bits), keep_alpha, src, dst); - let new = decode_clip(Bytes(info), Bytes(bits), keep_alpha, src, dst); - match (old, new) { - (None, None) => {} - (Some((a, ad)), Some((b, bd))) => { - assert_eq!((a.w, a.h, &a.px), (b.w, b.h, &b.px), "{what} alpha={keep_alpha} {src:?}"); - assert_eq!(ad.map(f64::to_bits), bd.map(f64::to_bits), "{what} alpha={keep_alpha} {src:?}"); - } - _ => panic!("old and new disagree on None: {what} alpha={keep_alpha} {src:?}"), - } - } - } - } - - #[test] - fn decode_clip_matches_the_per_pixel_reference_at_every_depth_palette_and_mask() { - let mut seed = 0x9E37_79B9_7F4A_7C15u64; - // Widths that leave padding bits in the row, so a row's last byte is only partly used. - for w in [1, 9, 37] { - for h in [6, -6] { - for bpp in [1usize, 4, 8] { - let n = 1usize << bpp; - // Full palette, clrUsed shorter than the depth (the rest reads black), a - // palette cut short of what clrUsed names, and none at all. - for (clr_used, entries) in [(0, n), (3, 3), (n as u32 + 50, n), (0, 1), (0, 0)] { - let (info, bits) = make_dib_with(w, h, bpp, None, clr_used, entries, &mut seed); - assert_same(&info, &bits, &format!("{bpp} bpp w={w} h={h} clrUsed={clr_used} palette={entries}")); - } - } - let (info, bits) = make_dib_with(w, h, 24, None, 0, 0, &mut seed); - assert_same(&info, &bits, &format!("24 bpp w={w} h={h}")); - // A colour table on a deep DIB is carried but unused. - let (info, bits) = make_dib_with(w, h, 24, None, 5, 5, &mut seed); - assert_same(&info, &bits, &format!("24 bpp with palette w={w} h={h}")); - // Masks on depths that ignore them still move the palette and the bits. - for bpp in [1usize, 8, 24] { - let n = if bpp == 24 { 0 } else { 1 << bpp }; - let (info, bits) = make_dib_with(w, h, bpp, Some(([0xF800, 0x07E0, 0x001F], 40)), 0, n, &mut seed); - assert_same(&info, &bits, &format!("{bpp} bpp with masks w={w} h={h}")); - } - let masks16: [Option<[u32; 3]>; 5] = [ - None, - Some([0xF800, 0x07E0, 0x001F]), - Some([0x7C00, 0x03E0, 0x001F]), - Some([0x0F00, 0x00F0, 0x000F]), - Some([0xF800, 0x0000, 0x001F]), - ]; - let masks32: [Option<[u32; 3]>; 6] = [ - None, - Some([0xFF_0000, 0xFF00, 0xFF]), - Some([0xFF, 0xFF00, 0xFF_0000]), - Some([0x3FF0_0000, 0x000F_FC00, 0x0000_03FF]), - Some([0xFFFF_FFFF, 0x0000_FF00, 0]), - Some([0x00FF_FF00, 0x00FF_FF00, 0x0000_00FF]), - ]; - for (bpp, sets) in [(16usize, masks16.as_slice()), (32, masks32.as_slice())] { - for m in sets { - // 40: the masks follow the header; 56 and 108: they are inside it. - for hsize in [40usize, 56, 108] { - let inline = m.map(|m| (m, hsize)); - let (info, bits) = make_dib_with(w, h, bpp, inline, 0, 0, &mut seed); - assert_same(&info, &bits, &format!("{bpp} bpp masks={m:x?} header={hsize} w={w} h={h}")); - } - } - } - } - } - } - - /// Timing of the per-pixel reference against `decode_clip` on a 40 MP bitmap: - /// `cargo test -p wordcraft-metafile --release -- --ignored --nocapture dib_decode_speed`. - #[test] - #[ignore = "timing only"] - fn dib_decode_speed() { - let mut seed = 6u64; - for bpp in [1usize, 4, 8, 16, 24, 32] { - let (info, bits) = make_dib(8000, -5000, bpp, &mut seed); - for round in 0..4 { - let t = std::time::Instant::now(); - let a = decode_clip_reference(Bytes(&info), Bytes(&bits), false, [0, 0, 8000, 5000], [0.0, 0.0, 1.0, 1.0]).map(|x| x.0.px); - let slow = t.elapsed().as_secs_f64() * 1e3; - let t = std::time::Instant::now(); - let b = decode_clip(Bytes(&info), Bytes(&bits), false, [0, 0, 8000, 5000], [0.0, 0.0, 1.0, 1.0]).map(|x| x.0.px); - let fast = t.elapsed().as_secs_f64() * 1e3; - assert!(a == b); - eprintln!("{bpp:2} bpp round {round}: reference {slow:4.0} ms, decode_clip {fast:4.0} ms"); - } - } - } - - #[test] - fn decode_clip_matches_decode_then_clip_blit() { - let mut seed = 0x2545_F491_4F6C_DD1Du64; - let mut cases = 0; - for bpp in [1, 4, 8, 16, 24, 32] { - for h in [5, -5, 1, -1] { - let w = 7; - let (info, bits) = make_dib(w, h, bpp, &mut seed); - for keep_alpha in [false, true] { - // Source x/y from outside the bitmap on both sides; sizes include zero and negative. - for sx in [-9, -2, 0, 3, 6, 8, 20] { - for sy in [-9, -2, 0, 2, 4, 5, 20] { - for (sw, sh) in [(0, 0), (-3, 4), (4, -2), (1, 1), (3, 2), (7, 5), (30, 30), (2, 9)] { - let src = [sx, sy, sw, sh]; - let dst = [10.0, 20.0, 70.0, 50.0]; - let old = decode_whole(Bytes(&info), Bytes(&bits), keep_alpha).and_then(|img| clip_blit_whole(&img, h > 0, src, dst)); - let new = decode_clip(Bytes(&info), Bytes(&bits), keep_alpha, src, dst); - match (old, new) { - (None, None) => {} - (Some((a, ad)), Some((b, bd))) => { - assert_eq!((a.w, a.h, &a.px), (b.w, b.h, &b.px), "{bpp} bpp h={h} {src:?}"); - assert_eq!(ad.map(f64::to_bits), bd.map(f64::to_bits), "{bpp} bpp h={h} {src:?}"); - } - _ => panic!("old and new disagree on None: {bpp} bpp h={h} {src:?}"), - } - cases += 1; - } - } - } - } - } - } - assert!(cases > 10_000); - } - - #[test] - fn decode_clip_rejects_what_decode_rejected() { - let mut seed = 7; - let (info, bits) = make_dib(7, 5, 24, &mut seed); - let short = &bits[..bits.len() - 1]; - // A short bits buffer fails the whole image even when the crop lies in the rows that exist. - assert!(decode_clip(Bytes(&info), Bytes(short), false, [0, 0, 1, 1], [0.0, 0.0, 1.0, 1.0]).is_none()); - assert!(decode_whole(Bytes(&info), Bytes(short), false).is_none()); - } - - #[test] - fn decode_clip_decodes_only_the_cropped_pixels() { - let mut seed = 99; - let (info, bits) = make_dib(400, -300, 24, &mut seed); - DECODED.with(|d| d.set(0)); - let (img, _) = decode_clip(Bytes(&info), Bytes(&bits), false, [10, 20, 8, 4], [0.0, 0.0, 8.0, 4.0]).unwrap(); - assert_eq!((img.w, img.h), (8, 4)); - assert_eq!(DECODED.with(|d| d.get()), 8 * 4); - // The whole-bitmap path decodes all 400 x 300. - DECODED.with(|d| d.set(0)); - decode_whole(Bytes(&info), Bytes(&bits), false).unwrap(); - assert_eq!(DECODED.with(|d| d.get()), 400 * 300); - } - - #[test] - fn decode_clip_refuses_a_side_no_renderer_draws() { - let cap = MAX_BITMAP_SIDE as usize; - let mut seed = 11; - // 1 bpp, one row longer than the cap: 5 KB of bits, 120 KB of RGBA. - let (info, bits) = make_dib(cap + 1, 1, 1, &mut seed); - assert!(decode_clip(Bytes(&info), Bytes(&bits), false, [0, 0, 0, 0], [0.0, 0.0, 1.0, 1.0]).is_none()); - // The same for the height. - let (info, bits) = make_dib(1, cap as i32 + 1, 1, &mut seed); - assert!(decode_clip(Bytes(&info), Bytes(&bits), false, [0, 0, 0, 0], [0.0, 0.0, 1.0, 1.0]).is_none()); - // A crop of the wide bitmap within the cap still decodes, and so does the cap itself. - let (info, bits) = make_dib(cap + 1, 1, 1, &mut seed); - let (img, _) = decode_clip(Bytes(&info), Bytes(&bits), false, [10, 0, 100, 1], [0.0, 0.0, 1.0, 1.0]).unwrap(); - assert_eq!((img.w, img.h), (100, 1)); - let (info, bits) = make_dib(cap, 1, 1, &mut seed); - let (img, _) = decode_clip(Bytes(&info), Bytes(&bits), false, [0, 0, 0, 0], [0.0, 0.0, 1.0, 1.0]).unwrap(); - assert_eq!((img.w, img.h), (cap, 1)); - } -} diff --git a/crates/metafile/src/emf.rs b/crates/metafile/src/emf.rs deleted file mode 100644 index 195faa2a83..0000000000 --- a/crates/metafile/src/emf.rs +++ /dev/null @@ -1,370 +0,0 @@ -//! EMF reader (MS-EMF). Records are (type, size in bytes) followed by a payload; offsets inside a -//! record (bitmap info and bits) are relative to the record start, so each handler reads the record slice. - -use crate::bytes::Bytes; -use crate::canvas::{BS_NULL, Brush, Canvas, Font, Obj, PS_NULL, PS_STYLE_MASK, Pen, Xform, colorref}; -use crate::dib::{self, Blend}; -use crate::geom::{self, ArcKind, P}; -use crate::{Error, Frame, MAX_PATH_OPS}; - -const EMF_SIGNATURE: u32 = 0x464D_4520; -/// Hundredths of a millimetre to points. -const HMM_TO_PT: f64 = 72.0 / 2540.0; -/// SRCCOPY, the plain copy of a bitmap. -const SRCCOPY: u32 = 0x00CC_0020; -/// LogPenEx pen type bits; PS_COSMETIC pens are one device pixel wide. -const PS_TYPE_MASK: u32 = 0x000F_0000; -const PS_COSMETIC: u32 = 0; -/// EXTTEXTOUT options: the string holds glyph indices, and the dx array holds (x, y) pairs. -const ETO_GLYPH_INDEX: u32 = 0x10; -const ETO_PDY: u32 = 0x2000; - -pub(crate) fn is_emf(b: Bytes) -> bool { - b.u32(0) == Some(1) && b.u32(40) == Some(EMF_SIGNATURE) -} - -/// The picture frame: `rclFrame` (0.01 mm) mapped to device units through `szlDevice` and -/// `szlMillimeters`, sized in points. Without a usable frame, the device bounds stand in (1 unit = 1 point). -pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> { - if !is_emf(input) { - return Err(Error::BadHeader); - } - let hsize = input.u32(4).ok_or(Error::BadHeader)? as usize; - let bounds = rect32(input, 8).ok_or(Error::BadHeader)?; - let [l, t, r, b] = bounds; - let frame = frame_from_header(input).or_else(|| (r > l && b > t).then_some(Frame { rect: [l, t, r - l, b - t], size: None })); - let mut cv = Canvas::new(); - if let Some(px_mm) = device_px_per_mm(input) { - cv.set_device_mm(px_mm); - } - let mut parsed = 0usize; - let mut pos = hsize.max(88); - while !cv.full() { - let (Some(typ), Some(size)) = (input.u32(pos), pos.checked_add(4).and_then(|o| input.u32(o))) else { break }; - let size = size as usize; - if size < 8 || !size.is_multiple_of(4) { - break; - } - let Some(rec) = input.slice(pos, size) else { break }; - if typ == 14 { - break; - } - record(&mut cv, typ, Bytes(rec)); - parsed += 1; - let Some(next) = pos.checked_add(size) else { break }; - pos = next; - } - if parsed == 0 { - return Err(Error::NoRecords); - } - Ok((cv, frame)) -} - -/// Device pixels per millimetre on each axis, from `szlDevice` (72) and `szlMillimeters` (80). -fn device_px_per_mm(input: Bytes) -> Option<(f64, f64)> { - let (dw, dh) = (input.i32(72)?, input.i32(76)?); - let (mw, mh) = (input.i32(80)?, input.i32(84)?); - (dw > 0 && dh > 0 && mw > 0 && mh > 0).then(|| (f64::from(dw) / f64::from(mw), f64::from(dh) / f64::from(mh))) -} - -/// The frame from `rclFrame` (offset 24), `szlDevice` (72) and `szlMillimeters` (80) in the header. -pub(crate) fn frame_from_header(input: Bytes) -> Option { - let [fl, ft, fr, fb] = rect32(input, 24)?; - if fr <= fl || fb <= ft { - return None; - } - // Device units per hundredth of a millimetre. - let (px_mm_x, px_mm_y) = device_px_per_mm(input)?; - let (sx, sy) = (px_mm_x / 100.0, px_mm_y / 100.0); - let rect = [fl * sx, ft * sy, (fr - fl) * sx, (fb - ft) * sy]; - Some(Frame { rect, size: Some(((fr - fl) * HMM_TO_PT, (fb - ft) * HMM_TO_PT)) }) -} - -fn record(cv: &mut Canvas, typ: u32, r: Bytes) { - if cv.full() { - return; - } - let _ = match typ { - 9 => xy32(r, 8).map(|p| cv.set_window_ext(p)), - 10 => xy32(r, 8).map(|p| cv.set_window_org(p)), - 11 => xy32(r, 8).map(|p| cv.set_viewport_ext(p)), - 12 => xy32(r, 8).map(|p| cv.set_viewport_org(p)), - 17 => r.u32(8).map(|m| cv.set_map_mode(m)), - 19 => r.u32(8).map(|m| cv.set_polyfill(m)), - 20 => r.u32(8).map(|m| cv.set_rop2(m)), - 33 => { - cv.save_dc(); - Some(()) - } - 34 => r.i32(8).map(|n| cv.restore_dc(n)), - 35 => xform(r, 8).map(|x| cv.modify_world(x, 4)), - 36 => xform(r, 8).zip(r.u32(32)).map(|(x, m)| cv.modify_world(x, m)), - 37 => r.u32(8).map(|i| cv.select(i)), - 38 => create_pen(cv, r), - 95 => create_ext_pen(cv, r), - 39 => create_brush(cv, r), - 82 => create_font(cv, r), - 22 => r.u32(8).map(|a| cv.set_text_align(a)), - 24 => r.u32(8).map(|c| cv.set_text_color(colorref(c))), - 84 => ext_text_out_w(cv, r), - 40 => r.u32(8).map(|i| cv.delete_object(i)), - 27 => xy32(r, 8).map(|p| cv.move_to(p)), - 54 => xy32(r, 8).map(|p| cv.line_to(p)), - 42 => rect32(r, 8).map(|[l, t, rr, b]| cv.shape(geom::ellipse(l, t, rr, b), true, true)), - 43 => rect32(r, 8).map(|[l, t, rr, b]| cv.shape(geom::rect(l, t, rr, b), true, true)), - 44 => { - let (cw, ch) = (r.i32(24), r.i32(28)); - let (Some(cw), Some(ch)) = (cw, ch) else { return }; - rect32(r, 8).map(|[l, t, rr, b]| { - cv.shape(geom::round_rect(l, t, rr, b, f64::from(cw), f64::from(ch)), true, true); - }) - } - 45..=47 => arc32(r).map(|(bounds, s, e)| { - let kind = match typ { - 45 => ArcKind::Arc, - 46 => ArcKind::Chord, - _ => ArcKind::Pie, - }; - let [l, t, rr, b] = bounds; - cv.shape(geom::arc_shape(l, t, rr, b, s, e, kind), kind != ArcKind::Arc, true); - }), - 4 | 87 => counted(r, typ == 4).map(|pts| cv.poly(&pts, false, false, true)), - 3 | 86 => counted(r, typ == 3).map(|pts| cv.poly(&pts, true, true, true)), - 6 | 89 => counted(r, typ == 6).map(|pts| cv.line_chain(&pts, false, true)), - // POLYBEZIER starts its own figure at the first point and leaves the current point alone; - // POLYBEZIERTO continues from the current point. - 2 | 85 => counted(r, typ == 2).and_then(|pts| { - let from = *pts.first()?; - cv.bezier(from, pts.get(1..)?); - Some(()) - }), - 5 | 88 => counted(r, typ == 5).map(|pts| cv.bezier_to(&pts)), - 7 | 90 => poly_groups(r, typ == 7).map(|(counts, pts)| cv.shape(geom::subpaths(&pts, &counts, false), false, true)), - 8 | 91 => poly_groups(r, typ == 8).map(|(counts, pts)| cv.shape(geom::subpaths(&pts, &counts, true), true, true)), - 59 => { - cv.begin_path(); - Some(()) - } - 60 => { - cv.end_path(); - Some(()) - } - 61 => { - cv.close_figure(); - Some(()) - } - 62 => { - cv.paint_path(true, false); - Some(()) - } - 63 => { - cv.paint_path(true, true); - Some(()) - } - 64 => { - cv.paint_path(false, true); - Some(()) - } - 76 | 77 => bitblt(cv, r, typ == 77), - 80 => set_dibits(cv, r), - 81 => stretch_dibits(cv, r), - 114 => alphablend(cv, r), - _ => Some(()), - }; -} - -/// Two little-endian i32 values at `off`, as a point. -fn xy32(r: Bytes, off: usize) -> Option

{ - Some((f64::from(r.i32(off)?), f64::from(r.i32(off + 4)?))) -} - -/// RECTL (left, top, right, bottom) as i32 values widened to f64. -fn rect32(r: Bytes, off: usize) -> Option<[f64; 4]> { - Some([f64::from(r.i32(off)?), f64::from(r.i32(off + 4)?), f64::from(r.i32(off + 8)?), f64::from(r.i32(off + 12)?)]) -} - -/// An i32 field as f64; 0 past the end. -fn i32s(r: Bytes, off: usize) -> f64 { - r.i32(off).map_or(0.0, f64::from) -} - -/// XFORM: six f32 values in M11, M12, M21, M22, Dx, Dy order. -fn xform(r: Bytes, off: usize) -> Option { - let mut x = [0.0f64; 6]; - for (i, v) in x.iter_mut().enumerate() { - *v = f64::from(r.f32(off + i * 4)?); - } - Some(x) -} - -/// ARC, CHORD, PIE: bounds at 8, start point at 24, end point at 32. -fn arc32(r: Bytes) -> Option<([f64; 4], P, P)> { - Some((rect32(r, 8)?, xy32(r, 24)?, xy32(r, 32)?)) -} - -/// A point count from a record, rejected when it exceeds the path budget (before any allocation). -fn budget(n: u32) -> Option { - let n = n as usize; - (n <= MAX_PATH_OPS).then_some(n) -} - -/// Point count at 24, then the points (32-bit or 16-bit) at 28. -fn counted(r: Bytes, wide: bool) -> Option> { - let n = budget(r.u32(24)?)?; - r.tail(28)?.points(0, n, wide) -} - -/// Subpath count at 24, total point count at 28, per-subpath counts at 32, then the points. -fn poly_groups(r: Bytes, wide: bool) -> Option<(Vec, Vec

)> { - let n = budget(r.u32(24)?)?; - // The record must hold the n counts before anything is allocated for them. - let raw = r.slice(32, n.checked_mul(4)?)?; - let counts: Vec = raw.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c) as usize).collect(); - let total = counts.iter().try_fold(0usize, |a, c| a.checked_add(*c))?; - let total = budget(u32::try_from(total).ok()?)?; - let pts = r.tail(n.checked_mul(4)?.checked_add(32)?)?.points(0, total, wide)?; - Some((counts, pts)) -} - -/// EMR_CREATEPEN: handle, LogPen (style, width x/y, colour). -fn create_pen(cv: &mut Canvas, r: Bytes) -> Option<()> { - let slot = r.u32(8)? as usize; - let style = r.u32(12)?; - let width = r.i32(16)?; - let color = r.u32(24)?; - cv.add_object(Some(slot), Obj::Pen(Pen { style, width: f64::from(width), color: colorref(color) })); - Some(()) -} - -/// EMR_EXTCREATEPEN: handle, bitmap offsets (unused), LogPenEx (style, width, brush style, colour). -/// A cosmetic pen's width is in device pixels (always 1), so it is a hairline; a BS_NULL brush draws -/// no line at all. -fn create_ext_pen(cv: &mut Canvas, r: Bytes) -> Option<()> { - let slot = r.u32(8)? as usize; - let (style, width, brush, color) = (r.u32(28)?, r.u32(32)?, r.u32(36)?, r.u32(40)?); - let width = if style & PS_TYPE_MASK == PS_COSMETIC { 0.0 } else { f64::from(width) }; - let style = if brush == BS_NULL { PS_NULL } else { style & PS_STYLE_MASK }; - cv.add_object(Some(slot), Obj::Pen(Pen { style, width, color: colorref(color) })); - Some(()) -} - -/// EMR_CREATEBRUSHINDIRECT: handle, LogBrush32 (style, colour, hatch). -fn create_brush(cv: &mut Canvas, r: Bytes) -> Option<()> { - let slot = r.u32(8)? as usize; - let style = r.u32(12)?; - let color = r.u32(16)?; - cv.add_object(Some(slot), Obj::Brush(Brush { style, color: colorref(color) })); - Some(()) -} - -/// EMR_EXTCREATEFONTINDIRECTW: handle, then a LogFont (height, width, escapement, orientation, weight, -/// italic, ..., face name of 32 UTF-16 units at 40). -fn create_font(cv: &mut Canvas, r: Bytes) -> Option<()> { - let slot = r.u32(8)? as usize; - let mut face = [0u16; 32]; - for (i, u) in face.iter_mut().enumerate() { - *u = r.u16(40 + i * 2).unwrap_or(0); - } - let font = Font { height: r.i32(12)?, escapement: r.i32(20)?, weight: r.i32(28)?, italic: *r.0.get(32)? != 0, face }; - cv.add_object(Some(slot), Obj::Font(font)); - Some(()) -} - -/// EMR_EXTTEXTOUTW: an EmrText at 36 with the reference point, the character count at 44, the string -/// offset at 48, the options at 52 and the dx array offset at 72 (offsets from the record start). -/// Glyph-index strings are skipped: they cannot be mapped back to characters. -fn ext_text_out_w(cv: &mut Canvas, r: Bytes) -> Option<()> { - let at = xy32(r, 36)?; - let n = r.u32(44)? as usize; - let (off, options, off_dx) = (r.u32(48)? as usize, r.u32(52)?, r.u32(72)? as usize); - if options & ETO_GLYPH_INDEX != 0 || n == 0 { - return None; - } - let units: Vec = r.slice(off, n.checked_mul(2)?)?.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); - // dx has one entry per UTF-16 unit (two with ETO_PDY); a character takes the sum of its units. - let step = if options & ETO_PDY != 0 { 8 } else { 4 }; - let raw_dx: Vec = match r.slice(off_dx, n.checked_mul(step)?) { - Some(b) if off_dx != 0 => b.chunks_exact(step).filter_map(|c| Some(f64::from(i32::from_le_bytes(c.get(..4)?.try_into().ok()?)))).collect(), - _ => Vec::new(), - }; - let mut text = String::new(); - let mut dx = Vec::new(); - let mut i = 0; - for ch in char::decode_utf16(units.iter().copied()) { - let c = ch.unwrap_or(char::REPLACEMENT_CHARACTER); - // A replacement stands for one unpaired unit. - let w = if c == char::REPLACEMENT_CHARACTER { 1 } else { c.len_utf16() }; - if !raw_dx.is_empty() { - dx.push(raw_dx.get(i..i + w).map_or(0.0, |s| s.iter().sum())); - } - i += w; - text.push(c); - } - let text = text.trim_end_matches('\0').to_string(); - dx.truncate(text.chars().count()); - cv.text(at, text, &dx); - Some(()) -} - -/// BITBLT (76) and STRETCHBLT (77): dest at 24..40, rop at 40, source x/y at 44, bmi at 84, bits at -/// 92; STRETCHBLT adds the source w/h at 100. A source-less rop fills the destination instead. -fn bitblt(cv: &mut Canvas, r: Bytes, stretch: bool) -> Option<()> { - let dst = [i32s(r, 24), i32s(r, 28), i32s(r, 32), i32s(r, 36)]; - let rop = r.u32(40)?; - if Canvas::sourceless(rop) { - cv.fill_rop(dst, rop); - return Some(()); - } - let (sw, sh) = if stretch { (i32s(r, 100), i32s(r, 104)) } else { (dst[2], dst[3]) }; - let src = [i32s(r, 44), i32s(r, 48), sw, sh]; - blit(cv, r, dst, src, (84, 92), Blend::Rop(rop)) -} - -/// ALPHABLEND: laid out like STRETCHBLT, with a BLENDFUNCTION at 40. Constant alpha at 42 applies to -/// every pixel; AlphaFormat at 43 with AC_SRC_ALPHA (1) also uses the per-pixel alpha. -fn alphablend(cv: &mut Canvas, r: Bytes) -> Option<()> { - let dst = [i32s(r, 24), i32s(r, 28), i32s(r, 32), i32s(r, 36)]; - let constant = *r.0.get(42)?; - let per_pixel = (*r.0.get(43)? & 0x01) != 0; - let src = [i32s(r, 44), i32s(r, 48), i32s(r, 100), i32s(r, 104)]; - blit(cv, r, dst, src, (84, 92), Blend::Alpha { constant, per_pixel }) -} - -/// STRETCHDIBITS: dest x/y at 24, src x/y/w/h at 32..48, bmi offset/size at 48, bits at 56, rop at 68, -/// dest w/h at 72. -fn stretch_dibits(cv: &mut Canvas, r: Bytes) -> Option<()> { - let dst = [i32s(r, 24), i32s(r, 28), i32s(r, 72), i32s(r, 76)]; - let src = [i32s(r, 32), i32s(r, 36), i32s(r, 40), i32s(r, 44)]; - let rop = r.u32(68)?; - blit(cv, r, dst, src, (48, 56), Blend::Rop(rop)) -} - -/// SETDIBITSTODEVICE (MS-EMF 2.3.1.5): dest x/y at 24, src x/y at 32, size (cxSrc, cySrc) at 40, bmi -/// at 48, bits at 56, start scan at 68. The image keeps its own size; the bits begin at scan line -/// `iStartScan`, so the source y counts from there. -fn set_dibits(cv: &mut Canvas, r: Bytes) -> Option<()> { - let (cx, cy) = (i32s(r, 40), i32s(r, 44)); - if cx <= 0.0 || cy <= 0.0 { - return None; - } - let dst = [i32s(r, 24), i32s(r, 28), cx, cy]; - let src = [i32s(r, 32), i32s(r, 36) - f64::from(r.u32(68)?), cx, cy]; - blit(cv, r, dst, src, (48, 56), Blend::Rop(SRCCOPY)) -} - -/// 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. -fn blit(cv: &mut Canvas, r: Bytes, dst: [f64; 4], src: [f64; 4], at: (usize, usize), blend: Blend) -> Option<()> { - 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)?; - dib::prepare(&mut img, blend); - cv.bitmap(dst, img); - Some(()) -} diff --git a/crates/metafile/src/geom.rs b/crates/metafile/src/geom.rs deleted file mode 100644 index 0c2b772cf1..0000000000 --- a/crates/metafile/src/geom.rs +++ /dev/null @@ -1,128 +0,0 @@ -//! Path operations in `f64` and the shape builders that turn WMF/EMF rectangles, ellipses and arcs -//! into cubic Béziers (the classic 4/3·tan(Δ/4) approximation, at most 90° per piece). - -use std::f64::consts::{FRAC_PI_2, PI, TAU}; - -pub(crate) type P = (f64, f64); - -#[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) enum Op { - M(P), - L(P), - C(P, P, P), - Z, -} - -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] -} - -/// Corner radii are half the EMF/WMF corner ellipse size, clamped so the corners never overlap. -pub(crate) fn round_rect(l: f64, t: f64, r: f64, b: f64, ew: f64, eh: f64) -> Vec { - // Reversed corners (right < left, bottom < top) describe the same rectangle. - let (l, r) = (l.min(r), l.max(r)); - let (t, b) = (t.min(b), t.max(b)); - let rx = (ew / 2.0).abs().min((r - l) / 2.0); - let ry = (eh / 2.0).abs().min((b - t) / 2.0); - let mut ops = vec![Op::M((l + rx, t)), Op::L((r - rx, t))]; - ops.extend(arc(r - rx, t + ry, rx, ry, -FRAC_PI_2, FRAC_PI_2)); - ops.push(Op::L((r, b - ry))); - ops.extend(arc(r - rx, b - ry, rx, ry, 0.0, FRAC_PI_2)); - ops.push(Op::L((l + rx, b))); - ops.extend(arc(l + rx, b - ry, rx, ry, FRAC_PI_2, FRAC_PI_2)); - ops.push(Op::L((l, t + ry))); - ops.extend(arc(l + rx, t + ry, rx, ry, PI, FRAC_PI_2)); - ops.push(Op::Z); - ops -} - -pub(crate) fn ellipse(l: f64, t: f64, r: f64, b: f64) -> Vec { - let (cx, cy, rx, ry) = center(l, t, r, b); - let mut ops = vec![Op::M((cx + rx, cy))]; - ops.extend(arc(cx, cy, rx, ry, 0.0, TAU)); - ops.push(Op::Z); - ops -} - -/// Which closed or open shape an ARC/CHORD/PIE record draws. -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum ArcKind { - Arc, - Chord, - Pie, -} - -/// ARC, CHORD and PIE: the arc runs counter-clockwise on screen from the start point to the end point. -pub(crate) fn arc_shape(l: f64, t: f64, r: f64, b: f64, s: P, e: P, kind: ArcKind) -> Vec { - let (cx, cy, rx, ry) = center(l, t, r, b); - let ang = |p: P| ((p.1 - cy) / ry.max(f64::MIN_POSITIVE)).atan2((p.0 - cx) / rx.max(f64::MIN_POSITIVE)); - let (a0, a1) = (ang(s), ang(e)); - let mut d = (a0 - a1).rem_euclid(TAU); - if d < 1e-12 { - d = TAU; - } - let sweep = -d; - let start = (cx + rx * a0.cos(), cy + ry * a0.sin()); - let mut ops = if kind == ArcKind::Pie { vec![Op::M((cx, cy)), Op::L(start)] } else { vec![Op::M(start)] }; - ops.extend(arc(cx, cy, rx, ry, a0, sweep)); - match kind { - ArcKind::Arc => {} - ArcKind::Chord => ops.push(Op::Z), - ArcKind::Pie => ops.extend([Op::L((cx, cy)), Op::Z]), - } - ops -} - -fn center(l: f64, t: f64, r: f64, b: f64) -> (f64, f64, f64, f64) { - ((l + r) / 2.0, (t + b) / 2.0, (r - l).abs() / 2.0, (b - t).abs() / 2.0) -} - -/// Cubic pieces along an ellipse from parameter `a0` over signed `sweep` radians. The current point -/// must already be at `(cx + rx cos a0, cy + ry sin a0)`. -fn arc(cx: f64, cy: f64, rx: f64, ry: f64, a0: f64, sweep: f64) -> Vec { - let n = ((sweep.abs() / FRAC_PI_2).ceil() as usize).clamp(1, 8); - let step = sweep / n as f64; - let k = 4.0 / 3.0 * (step / 4.0).tan(); - let pt = |t: f64| (cx + rx * t.cos(), cy + ry * t.sin()); - let mut ops = Vec::with_capacity(n); - for i in 0..n { - let t0 = a0 + step * i as f64; - let t1 = t0 + step; - let (p0, p3) = (pt(t0), pt(t1)); - let c1 = (p0.0 - k * rx * t0.sin(), p0.1 + k * ry * t0.cos()); - let c2 = (p3.0 + k * rx * t1.sin(), p3.1 - k * ry * t1.cos()); - ops.push(Op::C(c1, c2, p3)); - } - ops -} - -/// Consecutive subpaths: `counts[i]` points each, taken in order from `pts`. Counts that run past the -/// point list are cut short rather than failing the whole record. -pub(crate) fn subpaths(pts: &[P], counts: &[usize], close: bool) -> Vec { - // The exact size first: empty groups add no ops, so a long count list of zeros (file data) - // mustn't reserve room the canvas budget never sees. - let (mut n, mut at) = (0usize, 0usize); - for &c in counts { - let end = at.saturating_add(c).min(pts.len()); - if end > at { - n = n.saturating_add(end - at + usize::from(close)); - } - at = end; - } - let mut ops = Vec::with_capacity(n); - let mut at = 0usize; - for &c in counts { - let end = at.saturating_add(c).min(pts.len()); - let Some((first, rest)) = pts.get(at..end).and_then(<[_]>::split_first) else { - at = end; - continue; - }; - ops.push(Op::M(*first)); - ops.extend(rest.iter().map(|p| Op::L(*p))); - if close { - ops.push(Op::Z); - } - at = end; - } - ops -} diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs deleted file mode 100644 index 2797002e5f..0000000000 --- a/crates/metafile/src/lib.rs +++ /dev/null @@ -1,284 +0,0 @@ -//! WordCraft metafiles: reads Windows Metafiles (WMF) and Enhanced Metafiles (EMF) into a neutral -//! vector model of filled and stroked paths, RGBA bitmaps and text runs, in a picture frame with y down. -//! -//! The reader is pure Rust over byte slices (no file system), so it builds for wasm. Every read is -//! bounds-checked and every count is capped; hostile input yields a shorter picture or an [`Error`], -//! never a panic. -//! -//! Records follow MS-WMF and MS-EMF. Records outside the supported set are skipped silently. -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -#![forbid(unsafe_code)] - -mod bytes; -mod canvas; -mod dib; -mod emf; -mod geom; -mod place; -mod size; -mod wmf; - -#[cfg(test)] -mod tests; - -use bytes::Bytes; -use canvas::{Raw, RawText}; -use geom::{Op, P}; -pub use place::{MAX_BITMAP_SIDE, PlacedItem, TextLayout, crop_window}; -pub use size::size; - -/// Items kept from one file. Past the cap the parse stops and keeps what it has. -pub(crate) const MAX_ITEMS: usize = 200_000; -/// Object table slots (WMF handles, EMF object indices). -pub(crate) const MAX_OBJECTS: usize = 4096; -/// Largest bitmap in pixels (about 40 megapixels, 160 MB of RGBA). -pub(crate) const MAX_PIXELS: usize = 40_000_000; -/// DC save-stack depth. -pub(crate) const MAX_STACK: usize = 1024; -/// Points in one open path bracket. -pub(crate) const MAX_PATH_OPS: usize = 2_000_000; -/// Bytes of path ops and pixels kept from one file (about 256 MB). -pub(crate) const MAX_BYTES: usize = 256 * 1024 * 1024; - -/// A parsed metafile. Items use coordinates in `0..width` and `0..height`, y down. -#[derive(Debug, Clone, PartialEq)] -pub struct Picture { - /// Size of the drawing in its own units: points for placeable WMF and EMF (from the frame), device - /// or logical units otherwise. - pub width: f32, - pub height: f32, - pub items: Vec, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum Item { - /// A filled and/or stroked path, in picture coordinates. - Path { - segs: Vec, - fill: Option<[u8; 4]>, - /// Colour and width in picture units. - stroke: Option<([u8; 4], f32)>, - even_odd: bool, - }, - /// A bitmap stretched into `rect` = `[x, y, w, h]` (picture units), RGBA8 rows top-down. - Bitmap { rect: [f32; 4], width: u32, height: u32, rgba: Vec }, - /// A run of text; the renderers shape it with the named font (see [`Text::layout`]). - Text(Text), -} - -/// A text run, in picture units. -#[derive(Debug, Clone, PartialEq)] -pub struct Text { - pub text: String, - /// The reference point that `halign` and `valign` refer to. - pub x: f32, - pub y: f32, - /// Font height: the em size, or the cell height (ascent + descent) when `cell` is set. - pub size: f32, - pub cell: bool, - pub font: String, - pub bold: bool, - pub italic: bool, - pub color: [u8; 4], - /// Baseline direction in radians, clockwise from +x (y down). - pub angle: f32, - pub halign: HAlign, - pub valign: VAlign, - /// Advance of each character along the baseline; empty when the font's own advances apply. - pub dx: Vec, -} - -/// Where the reference point sits along the run. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum HAlign { - Left, - Center, - Right, -} - -/// Where the reference point sits across the run. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum VAlign { - Top, - Baseline, - Bottom, -} - -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum Seg { - Move(f32, f32), - Line(f32, f32), - Cubic(f32, f32, f32, f32, f32, f32), - Close, -} - -#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)] -pub enum Error { - #[error("not a WMF or EMF file")] - NotMetafile, - #[error("metafile header is truncated or invalid")] - BadHeader, - #[error("metafile has no readable records")] - NoRecords, -} - -/// The picture frame in device units (`rect` = `[x, y, w, h]`) and, when the file states one, its -/// size in picture units. -pub(crate) struct Frame { - pub rect: [f64; 4], - pub size: Option<(f64, f64)>, -} - -/// Parses a WMF (placeable or plain) or EMF file. -pub fn parse(bytes: &[u8]) -> Result { - let b = Bytes(bytes); - let (cv, frame) = if emf::is_emf(b) { - emf::parse(b)? - } else if wmf::is_wmf(b) { - wmf::parse(b)? - } else { - return Err(Error::NotMetafile); - }; - Ok(build(cv.items, frame)) -} - -/// True when the bytes start like a WMF (placeable or plain header) or an EMF. -pub fn is_metafile(bytes: &[u8]) -> bool { - let b = Bytes(bytes); - emf::is_emf(b) || wmf::is_wmf(b) -} - -/// Maps device-space output into the picture frame. Without a usable frame the frame is the bounding -/// box of the drawing, so the origin is still the top-left of what was drawn. -fn build(raw: Vec, frame: Option) -> Picture { - let frame = frame.filter(|f| f.rect.iter().all(|v| v.is_finite()) && f.rect[2] > 0.0 && f.rect[3] > 0.0); - let (rect, size) = match frame { - Some(f) => (f.rect, f.size.unwrap_or((f.rect[2], f.rect[3]))), - None => match bbox(&raw) { - Some([x0, y0, x1, y1]) => ([x0, y0, x1 - x0, y1 - y0], (x1 - x0, y1 - y0)), - None => return Picture { width: 0.0, height: 0.0, items: Vec::new() }, - }, - }; - let sx = if rect[2] > 0.0 { size.0 / rect[2] } else { 1.0 }; - let sy = if rect[3] > 0.0 { size.1 / rect[3] } else { 1.0 }; - let tf = move |p: P| ((p.0 - rect[0]) * sx, (p.1 - rect[1]) * sy); - let stroke_scale = (sx + sy) / 2.0; - // No stroke is wider than the picture's diagonal: anything wider is a mapping artefact. - let diag = size.0.hypot(size.1); - let items = raw.into_iter().filter_map(|r| match r { - Raw::Path { ops, fill, stroke, even_odd } => { - let segs = ops.iter().map(|op| seg(op, tf)).collect::>>()?; - if segs.len() < 2 { - return None; - } - let stroke = stroke.and_then(|(c, w)| Some((c, f((w * stroke_scale).min(diag))?))); - Some(Item::Path { segs, fill, stroke, even_odd }) - } - Raw::Bitmap { rect: r, img } => { - let (x, y) = tf((r[0], r[1])); - let rect = [f(x)?, f(y)?, f(r[2] * sx)?, f(r[3] * sy)?]; - Some(Item::Bitmap { rect, width: img.w as u32, height: img.h as u32, rgba: img.px }) - } - Raw::Text(t) => text_item(t, tf, sx, sy), - }); - let items = items.collect(); - Picture { width: f(size.0).unwrap_or(0.0), height: f(size.1).unwrap_or(0.0), items } -} - -/// A device-space text run mapped into the picture: the reference point through `tf`, lengths by the -/// frame scale. TA_* flags become the alignment. -fn text_item(t: RawText, tf: impl Fn(P) -> P, sx: f64, sy: f64) -> Option { - let (x, y) = tf(t.origin); - let halign = match t.align & 6 { - 2 => HAlign::Right, - 6 => HAlign::Center, - _ => HAlign::Left, - }; - let valign = match t.align & 24 { - 8 => VAlign::Bottom, - 24 => VAlign::Baseline, - _ => VAlign::Top, - }; - let dx = t.dx.iter().map(|d| f(d * sx.abs())).collect::>>()?; - let size = f(t.size * sy.abs()).filter(|s| *s > 0.0)?; - Some(Item::Text(Text { - text: t.text, - x: f(x)?, - y: f(y)?, - size, - cell: t.cell, - font: t.font, - bold: t.bold, - italic: t.italic, - color: t.color, - angle: f(t.angle).unwrap_or(0.0), - halign, - valign, - dx, - })) -} - -fn f(v: f64) -> Option { - let v = v as f32; - v.is_finite().then_some(v) -} - -fn seg(op: &Op, tf: impl Fn(P) -> P) -> Option { - let pt = |p: P| { - let (x, y) = tf(p); - Some((f(x)?, f(y)?)) - }; - Some(match *op { - Op::M(p) => { - let (x, y) = pt(p)?; - Seg::Move(x, y) - } - Op::L(p) => { - let (x, y) = pt(p)?; - Seg::Line(x, y) - } - Op::C(a, b, c) => { - let (x1, y1) = pt(a)?; - let (x2, y2) = pt(b)?; - let (x3, y3) = pt(c)?; - Seg::Cubic(x1, y1, x2, y2, x3, y3) - } - Op::Z => Seg::Close, - }) -} - -/// Bounding box `[x0, y0, x1, y1]` over the finite points of the output. -fn bbox(raw: &[Raw]) -> Option<[f64; 4]> { - let mut b: Option<[f64; 4]> = None; - let mut grow = |p: P| { - if p.0.is_finite() && p.1.is_finite() { - b = Some(match b { - None => [p.0, p.1, p.0, p.1], - Some([x0, y0, x1, y1]) => [x0.min(p.0), y0.min(p.1), x1.max(p.0), y1.max(p.1)], - }); - } - }; - for r in raw { - match r { - Raw::Path { ops, .. } => { - for op in ops { - match *op { - Op::M(p) | Op::L(p) => grow(p), - Op::C(a, c, d) => { - grow(a); - grow(c); - grow(d); - } - Op::Z => {} - } - } - } - Raw::Bitmap { rect, .. } => { - grow((rect[0], rect[1])); - grow((rect[0] + rect[2], rect[1] + rect[3])); - } - Raw::Text(t) => grow(t.origin), - } - } - b -} diff --git a/crates/metafile/src/place.rs b/crates/metafile/src/place.rs deleted file mode 100644 index 5a160c4edb..0000000000 --- a/crates/metafile/src/place.rs +++ /dev/null @@ -1,217 +0,0 @@ -//! Placing a picture on a target (a page or a device): the fitted transform, paths as kurbo paths in -//! target units and bitmaps as target rectangles. The rasteriser and the PDF writer only paint the result. - -use kurbo::{Affine, BezPath, Rect, Shape}; - -use crate::{HAlign, Item, Picture, Seg, Text, VAlign}; - -/// Largest bitmap side the renderers draw: within the PDF image limit and the rasteriser's 16-bit sides. -pub const MAX_BITMAP_SIDE: u32 = 30_000; -/// Placed coordinates past this (target units) are far off any page; such items are left out. -const MAX_COORD: f64 = 1e6; -/// Smallest placed bitmap side (target units), so the stretch onto it is never singular. -const MIN_BITMAP_SIDE: f64 = 1e-6; -/// The least of a source axis a crop keeps (0.5%). Files crop pictures to slivers (a header bar -/// that is 2.7% of a page-sized metafile, #1899). Layout makes a picture's frame at most 4000 pt -/// a side, so the whole source then spans at most 800,000 pt: what it covers stays inside -/// `MAX_COORD` and is never left out as far off the page. -const MIN_VISIBLE: f64 = 0.005; - -/// The part of a picture's source that `crop` (left, top, right, bottom fractions of the source) -/// keeps, as fractions of the source: [left, top, width, height], bitmap or metafile alike. Each -/// side is taken as 0–1 (junk as 0). When the two sides of an axis leave less than 0.5% of it, -/// the left (top) side stands and 0.5% shows. -pub fn crop_window(crop: [f32; 4]) -> [f64; 4] { - let [l, t, r, b] = crop.map(|v| if v.is_finite() { f64::from(v.clamp(0.0, 1.0)) } else { 0.0 }); - let axis = |lo: f64, hi: f64| { - let lo = lo.min(1.0 - MIN_VISIBLE); - (lo, (1.0 - lo - hi).max(MIN_VISIBLE)) - }; - let ((x, w), (y, h)) = (axis(l, r), axis(t, b)); - [x, y, w, h] -} - -/// One item of a placed picture, in target units. -pub enum PlacedItem { - /// A filled and/or stroked path. The stroke width is in target units; 0 is a cosmetic hairline that - /// the renderer draws at its minimum width. - Path { path: BezPath, fill: Option<[u8; 4]>, stroke: Option<([u8; 4], f64)>, even_odd: bool }, - /// `Picture::items[index]`, a bitmap, stretched into `rect`. - Bitmap { index: usize, rect: Rect }, - /// `Picture::items[index]`, a text run. `tf` maps the run's own space (picture units, the - /// reference point at the origin, the baseline along +x, y down) to the target. - Text { index: usize, tf: Affine }, -} - -/// A text run laid out with a font's metrics: the em size (in the run's own units, see -/// [`PlacedItem::Text`]), the baseline's y and each glyph's (x, y), alignment included. -pub struct TextLayout { - pub em: f64, - pub baseline: f64, - pub glyphs: Vec<(f64, f64)>, -} - -impl Text { - /// Lays out shaped glyphs, given as (cluster byte offset, x advance, x offset, y offset) in font - /// units of a font with `upem` units per em, `ascent` above and `descent` below the baseline. - /// The per-character advances `dx` place each cluster when there is one per character. - pub fn layout(&self, upem: f64, ascent: f64, descent: f64, glyphs: &[(usize, f64, f64, f64)]) -> Option { - let upem = if upem.is_finite() && upem > 0.0 { upem } else { 1000.0 }; - let cell = ascent + descent; - let size = f64::from(self.size); - let em = if self.cell && cell.is_finite() && cell > 0.0 { size * upem / cell } else { size }; - if !em.is_finite() || em <= 0.0 { - return None; - } - let k = em / upem; - let starts: Vec = self.text.char_indices().map(|(i, _)| i).collect(); - let dx = (self.dx.len() == starts.len() && !starts.is_empty()).then(|| { - let mut cum = Vec::with_capacity(self.dx.len() + 1); - let mut x = 0.0; - cum.push(x); - for d in &self.dx { - x += f64::from(*d); - cum.push(x); - } - cum - }); - let mut out = Vec::with_capacity(glyphs.len()); - let (mut pen, mut cluster_pen, mut last) = (0.0, 0.0, None); - for &(cluster, adv, xo, yo) in glyphs { - let ci = starts.partition_point(|&b| b <= cluster).saturating_sub(1); - if last != Some(ci) { - cluster_pen = pen; - last = Some(ci); - } - let x = match &dx { - Some(cum) => cum.get(ci).copied().unwrap_or(0.0) + pen - cluster_pen, - None => pen, - }; - out.push((x + xo * k, -yo * k)); - pen += adv * k; - } - let width = dx.as_ref().and_then(|c| c.last().copied()).unwrap_or(pen); - let hoff = match self.halign { - HAlign::Left => 0.0, - HAlign::Center => -width / 2.0, - HAlign::Right => -width, - }; - let baseline = match self.valign { - VAlign::Top => ascent * k, - VAlign::Baseline => 0.0, - VAlign::Bottom => -descent * k, - }; - let glyphs = out.into_iter().map(|(x, y)| (x + hoff, y + baseline)).collect(); - Some(TextLayout { em, baseline, glyphs }) - } -} - -impl Picture { - /// Whether the picture has a finite, positive size, so it can be fitted into a frame. - pub fn has_size(&self) -> bool { - self.width.is_finite() && self.height.is_finite() && self.width > 0.0 && self.height > 0.0 - } - - /// The transform that fits the picture into `r` with the crop fractions `crop` (left, top, right, - /// bottom) removed first: the visible part fills `r`. None for a degenerate size. - pub fn fit(&self, r: Rect, crop: [f32; 4]) -> Option { - let [cl, ct, vw, vh] = crop_window(crop); - let (w, h) = (f64::from(self.width), f64::from(self.height)); - let sx = r.width() / (w * vw); - let sy = r.height() / (h * vh); - (sx.is_finite() && sy.is_finite() && sx > 0.0 && sy > 0.0) - .then(|| Affine::translate((r.x0 - cl * w * sx, r.y0 - ct * h * sy)) * Affine::scale_non_uniform(sx, sy)) - } - - /// The items placed into `r` with `crop` applied. Items that are not finite or reach past ±1e6 - /// target units are left out (they are far off any page), as are bitmaps with no area. Stroke - /// widths are scaled to target units (along the mean axis scale, so a non-uniform fit keeps - /// strokes even). - pub fn place(&self, r: Rect, crop: [f32; 4]) -> Vec { - let Some(tf) = self.fit(r, crop) else { return Vec::new() }; - let c = tf.as_coeffs(); - let k = (c[0].abs() + c[3].abs()) / 2.0; - let mut out = Vec::with_capacity(self.items.len()); - for (index, item) in self.items.iter().enumerate() { - match item { - Item::Path { segs, fill, stroke, even_odd } => { - let path = tf * bez(segs); - if in_range(path.bounding_box()) { - let stroke = stroke.map(|(c, w)| (c, f64::from(w) * k)); - out.push(PlacedItem::Path { path, fill: *fill, stroke, even_odd: *even_odd }); - } - } - Item::Bitmap { rect: [x, y, w, h], .. } => { - let (x0, y0) = (f64::from(*x), f64::from(*y)); - let rect = tf.transform_rect_bbox(Rect::new(x0, y0, x0 + f64::from(*w), y0 + f64::from(*h))); - if in_range(rect) && rect.width() > MIN_BITMAP_SIDE && rect.height() > MIN_BITMAP_SIDE { - out.push(PlacedItem::Bitmap { index, rect }); - } - } - Item::Text(t) => { - let (x, y) = (f64::from(t.x), f64::from(t.y)); - let at = tf * kurbo::Point::new(x, y); - if in_range(Rect::new(at.x, at.y, at.x, at.y)) { - let tf = tf * Affine::translate((x, y)) * Affine::rotate(f64::from(t.angle)); - out.push(PlacedItem::Text { index, tf }); - } - } - } - } - out - } -} - -impl Item { - /// Takes a bitmap's pixels out of the item (its geometry stays) and returns them as (width, height, - /// RGBA) when a renderer can draw them: both sides in 1..=[`MAX_BITMAP_SIDE`] and exactly that many - /// pixels. None for paths and for bitmaps that cannot be drawn. - pub fn take_pixels(&mut self) -> Option<(u32, u32, Vec)> { - let Item::Bitmap { width, height, rgba, .. } = self else { return None }; - let (w, h, px) = (*width, *height, std::mem::take(rgba)); - let sides = (1..=MAX_BITMAP_SIDE).contains(&w) && (1..=MAX_BITMAP_SIDE).contains(&h); - (sides && px.len() == (w as usize).saturating_mul(h as usize).saturating_mul(4)).then_some((w, h, px)) - } -} - -/// Segments as a kurbo path. A segment after a close opens a new subpath at the last start point. -fn bez(segs: &[Seg]) -> BezPath { - let mut p = BezPath::new(); - let mut start = (0.0, 0.0); - let mut open = false; - for s in segs { - match *s { - Seg::Move(x, y) => { - start = (f64::from(x), f64::from(y)); - p.move_to(start); - open = true; - } - Seg::Line(x, y) => { - if !open { - p.move_to(start); - } - p.line_to((f64::from(x), f64::from(y))); - open = true; - } - Seg::Cubic(a, b, c, d, e, f) => { - if !open { - p.move_to(start); - } - p.curve_to((f64::from(a), f64::from(b)), (f64::from(c), f64::from(d)), (f64::from(e), f64::from(f))); - open = true; - } - Seg::Close => { - if open { - p.close_path(); - } - open = false; - } - } - } - p -} - -/// Whether a placed box is finite and within ±[`MAX_COORD`]. -fn in_range(b: Rect) -> bool { - [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() < MAX_COORD) -} diff --git a/crates/metafile/src/size.rs b/crates/metafile/src/size.rs deleted file mode 100644 index 8766b99626..0000000000 --- a/crates/metafile/src/size.rs +++ /dev/null @@ -1,98 +0,0 @@ -//! The size of a metafile picture without playing its records. - -use crate::bytes::Bytes; -use crate::{Error, emf, f, parse, wmf}; - -/// A placeable WMF header is 22 bytes, followed by the 9-word standard header. -const PLACEABLE_KEY: u32 = 0x9AC6_CDD7; -const PLACEABLE_LEN: usize = 22; -const DEFAULT_INCH: f64 = 1440.0; - -/// The size of a WMF or EMF picture in points (device or logical units when the file states no -/// size), the same as `parse(bytes)` would put in the picture's `width` and `height`, or the error -/// `parse` would give. -/// -/// An EMF and a placeable WMF carry their frame in the header, so the size is read from there -/// without decoding a bitmap or building a path. Any other file (a plain WMF, an EMF without a -/// usable frame) takes the full parse. -pub fn size(bytes: &[u8]) -> Result<(f32, f32), Error> { - if let Some(size) = header_size(Bytes(bytes)) { - return Ok(size); - } - let pic = parse(bytes)?; - Ok((pic.width, pic.height)) -} - -/// The size when the header decides it and the file has a first record (otherwise `parse` fails -/// with `NoRecords`, so the header alone is not enough). None sends the caller to the full parse. -pub(crate) fn header_size(b: Bytes) -> Option<(f32, f32)> { - if emf::is_emf(b) { - return emf_size(b); - } - if wmf::is_wmf(b) && b.u32(0) == Some(PLACEABLE_KEY) { - return placeable_wmf_size(b); - } - None -} - -/// `rclFrame` mapped to points. The frame must pass the checks `build` applies to it. -fn emf_size(b: Bytes) -> Option<(f32, f32)> { - let hsize = b.u32(4)? as usize; - b.slice(8, 16)?; - let frame = emf::frame_from_header(b)?; - if !frame.rect.iter().all(|v| v.is_finite()) || frame.rect[2] <= 0.0 || frame.rect[3] <= 0.0 { - return None; - } - // The records start after the header; the parse needs one that is not the end record. - let pos = hsize.max(88); - let (typ, len) = (b.u32(pos)?, b.u32(pos.checked_add(4)?)? as usize); - if len < 8 || !len.is_multiple_of(4) || b.slice(pos, len).is_none() || typ == 14 { - return None; - } - let (w, h) = frame.size?; - Some((f(w).unwrap_or(0.0), f(h).unwrap_or(0.0))) -} - -/// The placeable header's size in points, for a file whose records leave the target mapping alone -/// (see [`sets_the_mapping`]); the full parse decides the others. -fn placeable_wmf_size(b: Bytes) -> Option<(f32, f32)> { - let [l, t, r, bt] = [6, 8, 10, 12].map(|o| b.i16(o).map(f64::from)); - let (l, t, r, bt) = (l?, t?, r?, bt?); - let inch = b.u16(14).filter(|v| *v > 0).map_or(DEFAULT_INCH, f64::from); - let (w, h) = (r - l, bt - t); - if w <= 0.0 || h <= 0.0 { - return None; - } - let hsize = b.u16(PLACEABLE_LEN + 2)? as usize; - if hsize < 9 { - return None; - } - let pos = PLACEABLE_LEN.checked_add(hsize.checked_mul(2)?)?; - let (words, func) = (b.u32(pos)? as usize, b.u16(pos.checked_add(4)?)?); - let len = words.checked_mul(2).filter(|l| *l >= 6)?; - if func == 0 || b.slice(pos, len).is_none() { - return None; - } - if sets_the_mapping(b, pos) { - return None; - } - Some((f(w * 72.0 / inch)?, f(h * 72.0 / inch)?)) -} - -/// Whether a record from `pos` on is SetMapMode (0x0103) or SetViewportExt (0x020E). Those can change -/// the frame the full parse ends with (a zero-size viewport leaves none), so the header size is not -/// enough. The records are only walked, not played, with the same stops as `wmf::parse`. -fn sets_the_mapping(b: Bytes, mut pos: usize) -> bool { - while let (Some(words), Some(func)) = (b.u32(pos), pos.checked_add(4).and_then(|o| b.u16(o))) { - let Some(len) = (words as usize).checked_mul(2).filter(|l| *l >= 6) else { return false }; - if func == 0 || b.slice(pos, len).is_none() { - return false; - } - if matches!(func, 0x0103 | 0x020E) { - return true; - } - let Some(next) = pos.checked_add(len) else { return false }; - pos = next; - } - false -} diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs deleted file mode 100644 index b006b90428..0000000000 --- a/crates/metafile/src/tests.rs +++ /dev/null @@ -1,1187 +0,0 @@ -//! Hand-built WMF and EMF buffers: each test writes the records it needs and checks the parsed model. - -use crate::canvas::Canvas; -use crate::dib::Rgba; -use crate::{Error, Item, MAX_BYTES, MAX_ITEMS, Seg, is_metafile, parse}; - -fn h16(v: i32) -> Vec { - (v as i16).to_le_bytes().to_vec() -} - -fn h32(v: u32) -> Vec { - v.to_le_bytes().to_vec() -} - -fn e32(v: i32) -> Vec { - v.to_le_bytes().to_vec() -} - -fn cat(parts: Vec>) -> Vec { - parts.concat() -} - -/// One WMF record: size in words, function, parameters (padded to a word boundary). -fn wrec(func: u16, params: &[u8]) -> Vec { - let mut p = params.to_vec(); - if !p.len().is_multiple_of(2) { - p.push(0); - } - let words = ((6 + p.len()) / 2) as u32; - let mut v = words.to_le_bytes().to_vec(); - v.extend(func.to_le_bytes()); - v.extend(p); - v -} - -/// A WMF file: optional placeable header (bbox left, top, right, bottom in logical units, 1440 per inch), -/// the standard header, the records and an end-of-file record. -fn wmf(records: &[Vec], placeable: Option<[i32; 4]>) -> Vec { - let body: Vec = records.concat(); - let eof = wrec(0, &[]); - let mut f = Vec::new(); - if let Some(bb) = placeable { - f.extend(0x9AC6_CDD7u32.to_le_bytes()); - f.extend(0u16.to_le_bytes()); - for v in bb { - f.extend((v as i16).to_le_bytes()); - } - f.extend(1440u16.to_le_bytes()); - f.extend(0u32.to_le_bytes()); - f.extend(0u16.to_le_bytes()); - } - let total = (f.len() + 18 + body.len() + eof.len()) / 2; - f.extend(1u16.to_le_bytes()); - f.extend(9u16.to_le_bytes()); - f.extend(0x300u16.to_le_bytes()); - f.extend((total as u32).to_le_bytes()); - f.extend(16u16.to_le_bytes()); - f.extend(0u32.to_le_bytes()); - f.extend(0u16.to_le_bytes()); - f.extend(body); - f.extend(eof); - f -} - -/// One EMF record: type, size in bytes (payload padded to 4), payload. -fn erec(typ: u32, payload: &[u8]) -> Vec { - let mut p = payload.to_vec(); - while !p.len().is_multiple_of(4) { - p.push(0); - } - let mut v = typ.to_le_bytes().to_vec(); - v.extend(((8 + p.len()) as u32).to_le_bytes()); - v.extend(p); - v -} - -/// An EMF file with an 88-byte header (bounds and frame in 0.01 mm), the records and an EOF record. -fn emf(records: &[Vec], bounds: [i32; 4], frame: [i32; 4]) -> Vec { - let body: Vec = records.concat(); - let eof = erec(14, &[0; 12]); - let total = 88 + body.len() + eof.len(); - let mut h = vec![0u8; 88]; - h[0..4].copy_from_slice(&1u32.to_le_bytes()); - h[4..8].copy_from_slice(&88u32.to_le_bytes()); - h[8..24].copy_from_slice(&bounds.iter().flat_map(|v| v.to_le_bytes()).collect::>()); - h[24..40].copy_from_slice(&frame.iter().flat_map(|v| v.to_le_bytes()).collect::>()); - h[40..44].copy_from_slice(&0x464D_4520u32.to_le_bytes()); - h[44..48].copy_from_slice(&0x0001_0000u32.to_le_bytes()); - h[48..52].copy_from_slice(&(total as u32).to_le_bytes()); - h[52..56].copy_from_slice(&((records.len() + 1) as u32).to_le_bytes()); - h[56..58].copy_from_slice(&1u16.to_le_bytes()); - // 1000 x 500 device pixels for 250 x 125 mm: 0.04 device units per hundredth of a millimetre. - h[72..76].copy_from_slice(&1000i32.to_le_bytes()); - h[76..80].copy_from_slice(&500i32.to_le_bytes()); - h[80..84].copy_from_slice(&250i32.to_le_bytes()); - h[84..88].copy_from_slice(&125i32.to_le_bytes()); - let mut out = h; - out.extend(body); - out.extend(eof); - out -} - -/// A BITMAPINFOHEADER (40 bytes). -fn info_header(w: i32, h: i32, bpp: u16, size_image: u32) -> Vec { - cat(vec![h32(40), e32(w), e32(h), h16(1), h16(i32::from(bpp)), h32(0), h32(size_image), e32(0), e32(0), h32(0), h32(0)]) -} - -/// A 2x2 24-bit bottom-up DIB. File rows are stored bottom first: the bottom image row is blue, green; -/// the top row is red, white. Rows are padded to 4 bytes (8 bytes per row). -fn dib24_bottom_up() -> Vec { - let mut v = info_header(2, 2, 24, 16); - v.extend([255, 0, 0, 0, 255, 0, 0, 0]); - v.extend([0, 0, 255, 255, 255, 255, 0, 0]); - v -} - -/// Top-down RGBA of [`dib24_bottom_up`]: top-left red, top-right white, bottom-left blue, bottom-right green. -const DIB24_RGBA: [u8; 16] = [255, 0, 0, 255, 255, 255, 255, 255, 0, 0, 255, 255, 0, 255, 0, 255]; - -fn path_segs(item: &Item) -> (&Vec, Option<[u8; 4]>, Option<([u8; 4], f32)>, bool) { - match item { - Item::Path { segs, fill, stroke, even_odd } => (segs, *fill, *stroke, *even_odd), - Item::Bitmap { .. } | Item::Text(_) => panic!("expected a path"), - } -} - -fn close(a: f32, b: f32) -> bool { - (a - b).abs() < 1e-3 -} - -#[test] -fn wmf_rectangle_with_solid_brush() { - let recs = [ - wrec(0x02FC, &cat(vec![h16(0), h32(0x0000_00FF), h16(0)])), - wrec(0x012D, &h16(0)), - wrec(0x041B, &cat(vec![h16(70), h16(110), h16(20), h16(10)])), - ]; - let p = parse(&wmf(&recs, None)).unwrap(); - assert_eq!((p.width, p.height), (100.0, 50.0)); - assert_eq!(p.items.len(), 1); - let (segs, fill, stroke, even_odd) = path_segs(&p.items[0]); - assert_eq!(segs, &vec![Seg::Move(0.0, 0.0), Seg::Line(100.0, 0.0), Seg::Line(100.0, 50.0), Seg::Line(0.0, 50.0), Seg::Close]); - assert_eq!(fill, Some([255, 0, 0, 255])); - assert_eq!(stroke, Some(([0, 0, 0, 255], 0.0))); - assert!(even_odd); -} - -#[test] -fn wmf_polyline_with_pen() { - let recs = [ - wrec(0x02FA, &cat(vec![h16(0), h16(4), h16(0), h32(0x0000_FF00)])), - wrec(0x012D, &h16(0)), - wrec(0x0325, &cat(vec![h16(3), h16(0), h16(0), h16(50), h16(0), h16(50), h16(40)])), - ]; - let p = parse(&wmf(&recs, None)).unwrap(); - assert_eq!((p.width, p.height), (50.0, 40.0)); - let (segs, fill, stroke, _) = path_segs(&p.items[0]); - assert_eq!(segs, &vec![Seg::Move(0.0, 0.0), Seg::Line(50.0, 0.0), Seg::Line(50.0, 40.0)]); - assert_eq!(fill, None); - assert_eq!(stroke, Some(([0, 255, 0, 255], 4.0))); -} - -#[test] -fn wmf_polygon_fill_rule_follows_polyfillmode() { - let square = cat(vec![h16(4), h16(0), h16(0), h16(10), h16(0), h16(10), h16(10), h16(0), h16(10)]); - let winding = [wrec(0x0106, &h16(2)), wrec(0x0324, &square)]; - let p = parse(&wmf(&winding, None)).unwrap(); - assert!(!path_segs(&p.items[0]).3, "WINDING fills use the nonzero rule"); - let alternate = [wrec(0x0324, &square)]; - let p = parse(&wmf(&alternate, None)).unwrap(); - let (segs, fill, _, even_odd) = path_segs(&p.items[0]); - assert!(even_odd, "default ALTERNATE is even-odd"); - assert_eq!(fill, Some([255, 255, 255, 255])); - assert_eq!(segs.last(), Some(&Seg::Close)); -} - -#[test] -fn wmf_stretchdib_flips_bottom_up_rows() { - let params = cat(vec![h32(0x00CC_0020), h16(0), h16(2), h16(2), h16(0), h16(0), h16(10), h16(20), h16(0), h16(0), dib24_bottom_up()]); - let p = parse(&wmf(&[wrec(0x0F43, ¶ms)], None)).unwrap(); - assert_eq!((p.width, p.height), (20.0, 10.0)); - let Item::Bitmap { rect, width, height, rgba } = &p.items[0] else { panic!("expected a bitmap") }; - assert_eq!(rect, &[0.0, 0.0, 20.0, 10.0]); - assert_eq!((*width, *height), (2, 2)); - assert_eq!(rgba.as_slice(), DIB24_RGBA); -} - -#[test] -fn wmf_mapping_window_and_viewport() { - let recs = [ - wrec(0x0103, &h16(8)), - wrec(0x020B, &cat(vec![h16(100), h16(100)])), - wrec(0x020C, &cat(vec![h16(50), h16(50)])), - wrec(0x020E, &cat(vec![h16(100), h16(100)])), - wrec(0x0214, &cat(vec![h16(100), h16(100)])), - wrec(0x0213, &cat(vec![h16(150), h16(150)])), - ]; - let p = parse(&wmf(&recs, None)).unwrap(); - assert_eq!((p.width, p.height), (100.0, 100.0)); - let (segs, fill, stroke, _) = path_segs(&p.items[0]); - assert_eq!(segs, &vec![Seg::Move(0.0, 0.0), Seg::Line(100.0, 100.0)]); - assert_eq!(fill, None); - assert_eq!(stroke, Some(([0, 0, 0, 255], 0.0))); -} - -#[test] -fn wmf_placeable_header_sets_frame_in_points() { - let p = parse(&wmf(&[wrec(0x041B, &cat(vec![h16(1440), h16(2880), h16(0), h16(0)]))], Some([0, 0, 2880, 1440]))).unwrap(); - assert_eq!((p.width, p.height), (144.0, 72.0)); -} - -#[test] -fn emf_stretchdibits_flips_and_fits_frame() { - let mut payload = vec![0u8; 16]; - payload.extend(cat(vec![ - e32(0), - e32(0), - e32(0), - e32(0), - e32(2), - e32(2), - e32(80), - e32(40), - e32(120), - e32(16), - e32(0), - e32(0x00CC_0020), - e32(100), - e32(50), - ])); - payload.extend(info_header(2, 2, 24, 16)); - payload.extend(dib24_bottom_up().get(40..).unwrap_or_default()); - let rec = erec(81, &payload); - // A 25 x 12.5 mm frame is 70.87 x 35.43 points; the bitmap fills the whole frame. - let file = emf(&[rec], [0, 0, 100, 50], [0, 0, 2500, 1250]); - let p = parse(&file).unwrap(); - let (w, h) = (2500.0 * 72.0 / 2540.0, 1250.0 * 72.0 / 2540.0); - assert!(close(p.width, w as f32) && close(p.height, h as f32)); - let Item::Bitmap { rect, width, height, rgba } = &p.items[0] else { panic!("expected a bitmap") }; - assert!(rect.iter().zip([0.0, 0.0, w, h]).all(|(a, b)| close(*a, b as f32))); - assert_eq!((*width, *height), (2, 2)); - assert_eq!(rgba.as_slice(), DIB24_RGBA); -} - -#[test] -fn emf_world_transform_scales_geometry() { - let xf = cat([2.0f32, 0.0, 0.0, 2.0, 0.0, 0.0].iter().map(|v| v.to_le_bytes().to_vec()).collect()); - let recs = [erec(35, &xf), erec(27, &cat(vec![e32(0), e32(0)])), erec(54, &cat(vec![e32(10), e32(5)]))]; - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - assert_eq!((p.width, p.height), (20.0, 10.0)); - let (segs, fill, stroke, _) = path_segs(&p.items[0]); - assert_eq!(segs, &vec![Seg::Move(0.0, 0.0), Seg::Line(20.0, 10.0)]); - assert_eq!(fill, None); - assert_eq!(stroke, Some(([0, 0, 0, 255], 0.0))); -} - -#[test] -fn emf_ellipse_is_four_cubics_back_to_start() { - let rect = cat(vec![e32(0), e32(0), e32(40), e32(20)]); - let p = parse(&emf(&[erec(42, &rect)], [0; 4], [0; 4])).unwrap(); - let (segs, fill, _, _) = path_segs(&p.items[0]); - assert_eq!(segs.len(), 6); - assert_eq!(segs[0], Seg::Move(40.0, 10.0)); - assert!(matches!(segs[4], Seg::Cubic(_, _, _, _, x, y) if close(x, 40.0) && close(y, 10.0))); - assert_eq!(segs[5], Seg::Close); - assert_eq!(fill, Some([255, 255, 255, 255])); -} - -#[test] -fn emf_path_bracket_strokeandfill_uses_stock_black_brush() { - let bounds = vec![0u8; 16]; - let recs = [ - erec(59, &[]), - erec(27, &cat(vec![e32(0), e32(0)])), - erec(54, &cat(vec![e32(10), e32(0)])), - erec(54, &cat(vec![e32(10), e32(10)])), - erec(61, &[]), - erec(60, &[]), - erec(37, &h32(0x8000_0004)), - erec(63, &bounds), - ]; - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - assert_eq!(p.items.len(), 1); - let (segs, fill, stroke, _) = path_segs(&p.items[0]); - assert_eq!(segs, &vec![Seg::Move(0.0, 0.0), Seg::Line(10.0, 0.0), Seg::Line(10.0, 10.0), Seg::Close]); - assert_eq!(fill, Some([0, 0, 0, 255])); - assert_eq!(stroke, Some(([0, 0, 0, 255], 0.0))); -} - -#[test] -fn item_cap_stops_the_parse_and_keeps_the_rest() { - let rect = wrec(0x041B, &cat(vec![h16(10), h16(10), h16(0), h16(0)])); - 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); -} - -#[test] -fn detection_and_garbage() { - let w = wmf(&[wrec(0x041B, &cat(vec![h16(1), h16(1), h16(0), h16(0)]))], None); - let e = emf(&[erec(42, &cat(vec![e32(0), e32(0), e32(4), e32(4)]))], [0; 4], [0; 4]); - assert!(is_metafile(&w)); - assert!(is_metafile(&e)); - assert!(!is_metafile(b"hello world, not a metafile")); - assert_eq!(parse(b"hello world, not a metafile").unwrap_err(), Error::NotMetafile); - assert!(parse(&[]).is_err()); -} - -/// Fixed-seed LCG (Knuth's constants): the fuzz inputs are reproducible. -struct Lcg(u64); - -impl Lcg { - fn rnd(&mut self) -> u32 { - self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); - (self.0 >> 33) as u32 - } -} - -#[test] -fn truncated_random_and_mutated_inputs_never_panic() { - let rect = wrec(0x041B, &cat(vec![h16(10), h16(10), h16(0), h16(0)])); - let wfile = wmf( - &[ - wrec(0x02FC, &cat(vec![h16(0), h32(0xFF), h16(0)])), - wrec(0x012D, &h16(0)), - rect, - wrec(0x0325, &cat(vec![h16(2), h16(0), h16(0), h16(5), h16(5)])), - ], - Some([0, 0, 20, 10]), - ); - let mut dib_rec = cat(vec![h32(0x00CC_0020), h16(0), h16(2), h16(2), h16(0), h16(0), h16(10), h16(20), h16(0), h16(0)]); - dib_rec.extend(dib24_bottom_up()); - let mut payload = vec![0u8; 16]; - payload.extend(cat(vec![e32(0), e32(0), e32(0), e32(0), e32(2), e32(2), e32(80), e32(40), e32(120), e32(16), e32(0), e32(0), e32(20), e32(10)])); - payload.extend(info_header(2, 2, 24, 16)); - payload.extend(dib24_bottom_up().get(40..).unwrap_or_default()); - let efile = emf( - &[ - erec(59, &[]), - erec(27, &cat(vec![e32(0), e32(0)])), - erec(54, &cat(vec![e32(9), e32(9)])), - erec(61, &[]), - erec(60, &[]), - erec(63, &[0; 16]), - erec(81, &payload), - erec(86, &cat(vec![h32(4), h16(0), h16(0), h16(9), h16(9), h16(0), h16(9)])), - ], - [0, 0, 20, 10], - [0, 0, 2540, 1270], - ); - for file in [&wfile, &efile] { - for n in 0..=file.len() { - let prefix = &file[..n]; - let _ = parse(prefix); - let _ = is_metafile(prefix); - } - } - let mut rng = Lcg(0x2545_F491_4F6C_DD1D); - for _ in 0..3000 { - let len = (rng.rnd() % 400) as usize; - let buf: Vec = (0..len).map(|_| rng.rnd() as u8).collect(); - let _ = parse(&buf); - } - for i in 0..1500usize { - let mut buf = if i.is_multiple_of(2) { efile.clone() } else { wfile.clone() }; - for _ in 0..8 { - let at = rng.rnd() as usize % buf.len(); - buf[at] = rng.rnd() as u8; - } - let _ = parse(&buf); - } - for i in 0..500usize { - let mut buf = if i.is_multiple_of(2) { efile.clone() } else { wfile.clone() }; - let at = rng.rnd() as usize % buf.len(); - buf[at..].iter_mut().for_each(|b| *b = 0xFF); - let _ = parse(&buf); - } -} - -#[test] -fn wmf_stock_null_brush_by_16_bit_handle_has_no_fill() { - // SELECTOBJECT with 0x8005 is the NULL_BRUSH stock object (0x8000 | 5), so the rectangle is outline only. - let recs = [wrec(0x012D, &h16(0x8005u16 as i32)), wrec(0x041B, &cat(vec![h16(70), h16(110), h16(20), h16(10)]))]; - let p = parse(&wmf(&recs, None)).unwrap(); - let (_, fill, stroke, _) = path_segs(&p.items[0]); - assert_eq!(fill, None); - assert_eq!(stroke, Some(([0, 0, 0, 255], 0.0))); -} - -#[test] -fn emf_frame_comes_from_rclframe_not_device_bounds() { - // Bounds cover only the left half of the 25 x 12.5 mm frame (device units are 0.04 per 0.01 mm), so a - // rectangle from x = 0 to 50 px ends at half the picture width. - let rec = erec(43, &cat(vec![e32(0), e32(0), e32(50), e32(25)])); - let p = parse(&emf(&[rec], [0, 0, 50, 25], [0, 0, 2500, 1250])).unwrap(); - let w = 2500.0 * 72.0 / 2540.0; - assert!(close(p.width, w as f32) && close(p.height, (1250.0 * 72.0 / 2540.0) as f32)); - let (segs, ..) = path_segs(&p.items[0]); - assert!(matches!(segs[1], Seg::Line(x, _) if close(x, (w / 2.0) as f32)), "{segs:?}"); -} - -#[test] -fn emf_bounds_stand_in_when_the_frame_is_empty() { - let rec = erec(43, &cat(vec![e32(0), e32(0), e32(50), e32(25)])); - let p = parse(&emf(&[rec], [0, 0, 50, 25], [0; 4])).unwrap(); - assert_eq!((p.width, p.height), (50.0, 25.0)); -} - -#[test] -fn wmf_placeable_bounds_go_through_the_window_mapping() { - // Logical bounds 200 x 100 at 1440 per inch are 10 x 5 points; the window is 2:1 onto the viewport, so - // the frame is 100 x 50 device units and the rectangle fills it. - let recs = [ - wrec(0x0103, &h16(8)), - wrec(0x020C, &cat(vec![h16(100), h16(200)])), - wrec(0x020E, &cat(vec![h16(50), h16(100)])), - wrec(0x041B, &cat(vec![h16(100), h16(200), h16(0), h16(0)])), - ]; - let p = parse(&wmf(&recs, Some([0, 0, 200, 100]))).unwrap(); - assert_eq!((p.width, p.height), (10.0, 5.0)); - let (segs, ..) = path_segs(&p.items[0]); - assert!(segs.iter().any(|s| matches!(s, Seg::Line(x, y) if close(*x, 10.0) && close(*y, 5.0))), "{segs:?}"); -} - -#[test] -fn wmf_stretchdib_clipped_source_keeps_its_place() { - // Source x from -1 for 2 columns: only column 0 is in the bitmap, so it fills the right half of the - // destination and the picture keeps the original 20-unit width scale. - let params = cat(vec![h32(0x00CC_0020), h16(0), h16(2), h16(2), h16(0), h16(-1), h16(10), h16(20), h16(0), h16(0), dib24_bottom_up()]); - let p = parse(&wmf(&[wrec(0x0F43, ¶ms)], Some([0, 0, 20, 10]))).unwrap(); - let Item::Bitmap { rect, width, height, rgba } = &p.items[0] else { panic!("expected a bitmap") }; - // Placeable units are points: 20 units at 1440 per inch are 1 point, so the right column is 0.5 pt wide. - assert_eq!(rect, &[0.5, 0.0, 0.5, 0.5]); - assert_eq!((*width, *height), (1, 2)); - assert_eq!(rgba.as_slice(), [255, 0, 0, 255, 0, 0, 255, 255]); -} - -#[test] -fn wmf_negative_destination_width_mirrors_the_bitmap() { - let params = cat(vec![h32(0x00CC_0020), h16(0), h16(2), h16(2), h16(0), h16(0), h16(10), h16(-20), h16(0), h16(0), dib24_bottom_up()]); - // Frame from the placeable bounds (-20, 0)-(0, 10): the mirrored bitmap fills it. - let p = parse(&wmf(&[wrec(0x0F43, ¶ms)], Some([-20, 0, 0, 10]))).unwrap(); - let Item::Bitmap { rect, rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - assert_eq!(rect, &[0.0, 0.0, 1.0, 0.5]); - assert_eq!(&rgba[..8], [255, 255, 255, 255, 255, 0, 0, 255]); -} - -#[test] -fn emf_blackness_bitblt_fills_black_without_a_source() { - let mut payload = vec![0u8; 16]; - payload.extend(cat(vec![e32(10), e32(20), e32(30), e32(40), e32(0x0000_0042)])); - let p = parse(&emf(&[erec(76, &payload)], [0; 4], [0; 4])).unwrap(); - let (segs, fill, stroke, _) = path_segs(&p.items[0]); - assert_eq!(fill, Some([0, 0, 0, 255])); - assert_eq!(stroke, None); - assert_eq!(segs.len(), 5); -} - -#[test] -fn emf_savedc_past_the_stack_cap_stops_the_parse() { - let mut recs: Vec> = (0..=crate::MAX_STACK).map(|_| erec(33, &[])).collect(); - recs.push(erec(43, &cat(vec![e32(0), e32(0), e32(10), e32(10)]))); - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - assert!(p.items.is_empty(), "records after the cap must not be drawn"); -} - -#[test] -fn canvas_stops_at_the_byte_budget() { - // Two 128 MB bitmaps fit the budget; the third would exceed it and stops the canvas. - let mut cv = Canvas::new(); - let big = || Rgba { w: 1, h: 1, px: vec![0u8; MAX_BYTES / 2] }; - cv.bitmap([0.0, 0.0, 1.0, 1.0], big()); - cv.bitmap([0.0, 0.0, 1.0, 1.0], big()); - assert!(!cv.full()); - cv.bitmap([0.0, 0.0, 1.0, 1.0], big()); - assert!(cv.full()); - assert_eq!(cv.items.len(), 2); -} - -#[test] -fn oversized_dib_header_size_is_rejected_without_overflow() { - let mut info = info_header(2, 2, 24, 16); - info[0..4].copy_from_slice(&0xFFFF_FFF0u32.to_le_bytes()); - let params = cat(vec![h32(0x00CC_0020), h16(0), h16(2), h16(2), h16(0), h16(0), h16(10), h16(20), h16(0), h16(0), info]); - let p = parse(&wmf(&[wrec(0x0F43, ¶ms)], None)).unwrap(); - assert!(p.items.is_empty()); -} - -/// An EMF record of `len` bytes (header included) with u32 fields and byte blobs written at absolute -/// record offsets, so each test places a field where the spec puts it. -fn erec_at(typ: u32, len: usize, fields: &[(usize, u32)], blobs: &[(usize, &[u8])]) -> Vec { - let mut v = vec![0u8; len]; - v[0..4].copy_from_slice(&typ.to_le_bytes()); - v[4..8].copy_from_slice(&(len as u32).to_le_bytes()); - for (off, val) in fields { - v[*off..*off + 4].copy_from_slice(&val.to_le_bytes()); - } - for (off, b) in blobs { - v[*off..*off + b.len()].copy_from_slice(b); - } - v -} - -/// A BITBLT-style record (BITBLT, STRETCHBLT, ALPHABLEND layout) with its DIB at 112: the bmi and bits -/// offsets and lengths go at 84 and 92. `fields` and `blobs` add the other fields. -fn dib_rec(typ: u32, fields: &[(usize, u32)], blobs: &[(usize, &[u8])], info: &[u8], bits: &[u8]) -> Vec { - let at = 112; - let bits_at = at + info.len(); - let mut f = fields.to_vec(); - f.extend([(84, at as u32), (88, info.len() as u32), (92, bits_at as u32), (96, bits.len() as u32)]); - let mut b: Vec<(usize, &[u8])> = blobs.to_vec(); - b.extend([(at, info), (bits_at, bits)]); - erec_at(typ, bits_at + bits.len(), &f, &b) -} - -/// BITBLT (76) with destination `dst` = [x, y, w, h] and a 40-byte header DIB. -fn bitblt_rec(rop: u32, dst: [u32; 4], info: &[u8], bits: &[u8]) -> Vec { - let fields = [(24, dst[0]), (28, dst[1]), (32, dst[2]), (36, dst[3]), (40, rop)]; - dib_rec(76, &fields, &[], info, bits) -} - -#[test] -fn wmf_font_takes_an_object_slot_so_handles_line_up() { - // The font is handle 0, so the pen created after it is handle 1. - let recs = [ - wrec(0x02FB, &[0u8; 18]), - wrec(0x02FA, &cat(vec![h16(0), h16(4), h16(0), h32(0x0000_FF00)])), - wrec(0x012D, &h16(1)), - wrec(0x0325, &cat(vec![h16(2), h16(0), h16(0), h16(50), h16(0), h16(50)])), - ]; - let p = parse(&wmf(&recs, None)).unwrap(); - let (_, _, stroke, _) = path_segs(&p.items[0]); - assert_eq!(stroke, Some(([0, 255, 0, 255], 4.0))); -} - -#[test] -fn emf_polybezierto16_continues_the_open_path() { - // BEGINPATH, MOVETO a, LINETO b, POLYBEZIERTO16, CLOSEFIGURE, FILLPATH: one closed figure from a. - let mut bezier = vec![0u8; 16]; - bezier.extend(cat(vec![e32(3), h16(10), h16(10), h16(20), h16(10), h16(20), h16(0)])); - let recs = [ - erec(59, &[]), - erec(27, &cat(vec![e32(0), e32(0)])), - erec(54, &cat(vec![e32(10), e32(0)])), - erec(88, &bezier), - erec(61, &[]), - erec(62, &[0; 16]), - ]; - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - assert_eq!(p.items.len(), 1); - let (segs, fill, _, _) = path_segs(&p.items[0]); - assert_eq!(segs, &vec![Seg::Move(0.0, 0.0), Seg::Line(10.0, 0.0), Seg::Cubic(10.0, 10.0, 20.0, 10.0, 20.0, 0.0), Seg::Close]); - assert_eq!(fill, Some([255, 255, 255, 255])); -} - -#[test] -fn emf_polybezier_starts_its_own_figure_and_keeps_the_current_point() { - // POLYBEZIER (2) starts at its first point; the LINETO after it still starts at the MOVETO point. - let mut bezier = vec![0u8; 16]; - bezier.extend(cat(vec![e32(4), e32(0), e32(0), e32(5), e32(5), e32(10), e32(5), e32(10), e32(0)])); - let recs = [erec(27, &cat(vec![e32(3), e32(3)])), erec(2, &bezier), erec(54, &cat(vec![e32(50), e32(50)]))]; - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - assert_eq!(p.items.len(), 2); - let (segs, ..) = path_segs(&p.items[0]); - assert_eq!(segs[0], Seg::Move(0.0, 0.0)); - let (segs, ..) = path_segs(&p.items[1]); - assert_eq!(segs, &vec![Seg::Move(3.0, 3.0), Seg::Line(50.0, 50.0)]); -} - -#[test] -fn hairline_pen_stays_zero_under_an_anisotropic_window() { - // Window 2000 x 2000 onto a 1 x 1 viewport: a cosmetic pen must not become one device unit wide. - let recs = [ - wrec(0x0103, &h16(8)), - wrec(0x020C, &cat(vec![h16(2000), h16(2000)])), - wrec(0x020E, &cat(vec![h16(1), h16(1)])), - wrec(0x0214, &cat(vec![h16(0), h16(0)])), - wrec(0x0213, &cat(vec![h16(2000), h16(2000)])), - ]; - let p = parse(&wmf(&recs, None)).unwrap(); - assert_eq!((p.width, p.height), (1.0, 1.0)); - let (segs, _, stroke, _) = path_segs(&p.items[0]); - assert_eq!(segs.last(), Some(&Seg::Line(1.0, 1.0))); - assert_eq!(stroke, Some(([0, 0, 0, 255], 0.0))); -} - -#[test] -fn null_pen_is_recognised_under_extra_style_bits() { - // Pen style 0x105: PS_NULL (5) with a flag above the style nibble still draws no outline. - let pen = erec_at(38, 28, &[(8, 0), (12, 0x105), (16, 1), (24, 0)], &[]); - let recs = [pen, erec(37, &h32(0)), erec(43, &cat(vec![e32(0), e32(0), e32(10), e32(10)]))]; - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - let (_, fill, stroke, _) = path_segs(&p.items[0]); - assert_eq!(fill, Some([255, 255, 255, 255])); - assert_eq!(stroke, None); -} - -#[test] -fn metric_map_mode_flips_y_and_scales_to_device_pixels_emf() { - // LOMETRIC is 0.1 mm per unit; the header maps 4 device pixels to 1 mm. Points go y-up, so the - // drawing lies below its origin and the picture frame moves up to its top. - let recs = [erec(17, &h32(2)), erec(27, &cat(vec![e32(0), e32(0)])), erec(54, &cat(vec![e32(100), e32(50)]))]; - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - let (segs, ..) = path_segs(&p.items[0]); - assert!(close_seg(&segs[0], Seg::Move(0.0, 20.0)) && close_seg(&segs[1], Seg::Line(40.0, 0.0)), "{segs:?}"); -} - -#[test] -fn metric_map_mode_uses_96_dpi_for_wmf() { - let recs = [wrec(0x0103, &h16(2)), wrec(0x0214, &cat(vec![h16(0), h16(0)])), wrec(0x0213, &cat(vec![h16(50), h16(100)]))]; - let p = parse(&wmf(&recs, None)).unwrap(); - let px_mm = 96.0 / 25.4; - let (segs, ..) = path_segs(&p.items[0]); - let (x, y) = (100.0 * 0.1 * px_mm, 50.0 * 0.1 * px_mm); - assert!(close_seg(&segs[0], Seg::Move(0.0, y as f32)) && close_seg(&segs[1], Seg::Line(x as f32, 0.0)), "{segs:?}"); -} - -/// Segment equality within [`close`] tolerance. -fn close_seg(a: &Seg, b: Seg) -> bool { - match (*a, b) { - (Seg::Move(x, y), Seg::Move(u, v)) | (Seg::Line(x, y), Seg::Line(u, v)) => close(x, u) && close(y, v), - _ => false, - } -} - -#[test] -fn isotropic_mode_uses_one_scale_and_keeps_axis_signs() { - // Window 100 x 50; viewport 400 x -100: the scale is min(4, 2) = 2 on both axes, y flipped. - let recs = [ - wrec(0x0103, &h16(7)), - wrec(0x020C, &cat(vec![h16(50), h16(100)])), - wrec(0x020E, &cat(vec![h16(-100), h16(400)])), - wrec(0x0214, &cat(vec![h16(0), h16(0)])), - wrec(0x0213, &cat(vec![h16(25), h16(50)])), - ]; - let p = parse(&wmf(&recs, None)).unwrap(); - let (segs, ..) = path_segs(&p.items[0]); - assert!(close_seg(&segs[0], Seg::Move(0.0, 100.0)) && close_seg(&segs[1], Seg::Line(100.0, 50.0)), "{segs:?}"); -} - -#[test] -fn modify_world_with_an_unknown_mode_keeps_the_transform() { - let scale2 = cat([2.0f32, 0.0, 0.0, 2.0, 0.0, 0.0].iter().map(|v| v.to_le_bytes().to_vec()).collect()); - let identity = cat([1.0f32, 0.0, 0.0, 1.0, 0.0, 0.0].iter().map(|v| v.to_le_bytes().to_vec()).collect()); - let recs = - [erec(35, &scale2), erec(36, &cat(vec![identity, h32(99)])), erec(27, &cat(vec![e32(0), e32(0)])), erec(54, &cat(vec![e32(10), e32(5)]))]; - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - let (segs, ..) = path_segs(&p.items[0]); - assert_eq!(segs, &vec![Seg::Move(0.0, 0.0), Seg::Line(20.0, 10.0)]); -} - -#[test] -fn round_rect_accepts_reversed_corners() { - let normal = crate::geom::round_rect(0.0, 0.0, 10.0, 20.0, 4.0, 4.0); - assert_eq!(crate::geom::round_rect(10.0, 20.0, 0.0, 0.0, 4.0, 4.0), normal); - assert_eq!(crate::geom::round_rect(10.0, 0.0, 0.0, 20.0, 4.0, 4.0), normal); -} - -#[test] -fn stroke_width_is_clamped_to_the_picture_diagonal() { - // A 1440-unit placeable picture is 72 points square (diagonal 101.8); a 5000-unit pen would be 250. - let recs = [ - wrec(0x02FA, &cat(vec![h16(0), h16(5000), h16(0), h32(0)])), - wrec(0x012D, &h16(0)), - wrec(0x041B, &cat(vec![h16(1440), h16(1440), h16(0), h16(0)])), - ]; - let p = parse(&wmf(&recs, Some([0, 0, 1440, 1440]))).unwrap(); - assert_eq!((p.width, p.height), (72.0, 72.0)); - let (_, _, stroke, _) = path_segs(&p.items[0]); - assert!(close(stroke.unwrap_or(([0; 4], 0.0)).1, 72.0 * 2.0f32.sqrt()), "{stroke:?}"); -} - -/// A WMF rectangle from (0, 0) to (1, 1), so a picture's frame starts at the origin. -fn origin_rect() -> Vec { - wrec(0x041B, &cat(vec![h16(1), h16(1), h16(0), h16(0)])) -} - -#[test] -fn wmf_dibbitblt_without_a_dib_is_a_pattern_fill() { - // The 12-word form: rop(4), ySrc, xSrc, reserved, height, width, yDest, xDest; PATCOPY fills with the brush. - let params = cat(vec![h32(0x00F0_0021), h16(0), h16(0), h16(0), h16(10), h16(20), h16(5), h16(7)]); - let p = parse(&wmf(&[origin_rect(), wrec(0x0940, ¶ms)], None)).unwrap(); - let (segs, fill, _, _) = path_segs(&p.items[1]); - assert_eq!(fill, Some([255, 255, 255, 255])); - assert_eq!(segs, &vec![Seg::Move(7.0, 5.0), Seg::Line(27.0, 5.0), Seg::Line(27.0, 15.0), Seg::Line(7.0, 15.0), Seg::Close]); -} - -#[test] -fn wmf_dibstretchblt_without_a_dib_is_a_rop_fill() { - // The 14-word form: rop(4), srcH, srcW, ySrc, xSrc, reserved, destH, destW, yDest, xDest; BLACKNESS fills black. - let params = cat(vec![h32(0x0000_0042), h16(2), h16(2), h16(0), h16(0), h16(0), h16(10), h16(20), h16(5), h16(7)]); - let p = parse(&wmf(&[origin_rect(), wrec(0x0B41, ¶ms)], None)).unwrap(); - let (segs, fill, stroke, _) = path_segs(&p.items[1]); - assert_eq!((fill, stroke), (Some([0, 0, 0, 255]), None)); - assert_eq!(segs, &vec![Seg::Move(7.0, 5.0), Seg::Line(27.0, 5.0), Seg::Line(27.0, 15.0), Seg::Line(7.0, 15.0), Seg::Close]); -} - -#[test] -fn wmf_dibstretchblt_stretches_the_dib_into_its_destination() { - // rop(4), srcH, srcW, ySrc, xSrc, destH, destW, yDest, xDest, then the DIB (no reserved word). - let mut params = cat(vec![h32(0x00CC_0020), h16(2), h16(2), h16(0), h16(0), h16(10), h16(20), h16(6), h16(5)]); - params.extend(dib24_bottom_up()); - let p = parse(&wmf(&[origin_rect(), wrec(0x0B41, ¶ms)], None)).unwrap(); - let Item::Bitmap { rect, rgba, .. } = &p.items[1] else { panic!("expected a bitmap") }; - assert_eq!(rect, &[5.0, 6.0, 20.0, 10.0]); - assert_eq!(rgba.as_slice(), DIB24_RGBA); -} - -#[test] -fn wmf_negative_destination_height_mirrors_the_rows() { - let params = cat(vec![h32(0x00CC_0020), h16(0), h16(2), h16(2), h16(0), h16(0), h16(-10), h16(20), h16(0), h16(0), dib24_bottom_up()]); - let p = parse(&wmf(&[wrec(0x0F43, ¶ms)], None)).unwrap(); - let Item::Bitmap { rect, rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - assert_eq!(rect, &[0.0, 0.0, 20.0, 10.0]); - // Blue, green on top; red, white below. - assert_eq!(rgba.as_slice(), [0, 0, 255, 255, 0, 255, 0, 255, 255, 0, 0, 255, 255, 255, 255, 255]); -} - -#[test] -fn wmf_dibbitblt_copies_the_dib_at_its_destination() { - // The rectangle fixes the picture origin at (0, 0); the DIB lands at x = 5, y = 6. - let mut params = cat(vec![h32(0x00CC_0020), h16(0), h16(0), h16(2), h16(2), h16(6), h16(5)]); - params.extend(dib24_bottom_up()); - let recs = [wrec(0x041B, &cat(vec![h16(10), h16(10), h16(0), h16(0)])), wrec(0x0940, ¶ms)]; - let p = parse(&wmf(&recs, None)).unwrap(); - let Item::Bitmap { rect, width, height, rgba } = &p.items[1] else { panic!("expected a bitmap") }; - assert_eq!(rect, &[5.0, 6.0, 2.0, 2.0]); - assert_eq!((*width, *height), (2, 2)); - assert_eq!(rgba.as_slice(), DIB24_RGBA); -} - -#[test] -fn emf_setdibitstodevice_draws_the_image_at_its_own_size() { - let dib = dib24_bottom_up(); - let (info, bits) = (&dib[..40], &dib[40..]); - // Destination x/y at 24, src x/y at 32, size at 40, bmi at 48 (offset, length), bits at 56, scan start - // 68 and scan count 72. - let fields = [(24, 10), (28, 20), (40, 2), (44, 2), (48, 112), (52, 40), (56, 152), (60, 16), (72, 2)]; - let rec = erec_at(80, 168, &fields, &[(112, info), (152, bits)]); - let p = parse(&emf(&[rec], [0; 4], [0; 4])).unwrap(); - let Item::Bitmap { rect, rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - assert_eq!(rect, &[0.0, 0.0, 2.0, 2.0]); - assert_eq!(rgba.as_slice(), DIB24_RGBA); -} - -#[test] -fn emf_setdibitstodevice_source_counts_from_the_start_scan() { - // ySrc 1 with the bits starting at scan 1 is source row 0 of the bits: the bottom row (blue, green), - // drawn cxSrc x cySrc = 2 x 1 at the destination. - let dib = dib24_bottom_up(); - let (info, bits) = (&dib[..40], &dib[40..]); - let fields = [(24, 10), (28, 20), (36, 1), (40, 2), (44, 1), (48, 112), (52, 40), (56, 152), (60, 16), (68, 1), (72, 2)]; - let rec = erec_at(80, 168, &fields, &[(112, info), (152, bits)]); - let r = erec(43, &cat(vec![e32(0), e32(0), e32(1), e32(1)])); - let p = parse(&emf(&[r, rec], [0; 4], [0; 4])).unwrap(); - let Item::Bitmap { rect, rgba, .. } = &p.items[1] else { panic!("expected a bitmap") }; - assert_eq!(rect, &[10.0, 20.0, 2.0, 1.0]); - assert_eq!(rgba.as_slice(), [0, 0, 255, 255, 0, 255, 0, 255]); -} - -#[test] -fn emf_alphablend_uses_constant_and_per_pixel_alpha() { - // Constant alpha 128 (BLENDFUNCTION bytes at 40: op, flags, constant, format) over a 24-bit DIB. - let blend = [0u8, 0, 128, 0]; - let dib = dib24_bottom_up(); - let rec = dib_rec(114, &[(24, 0), (28, 0), (32, 2), (36, 2), (44, 0), (48, 0), (100, 2), (104, 2)], &[(40, &blend[..])], &dib[..40], &dib[40..]); - let p = parse(&emf(&[rec], [0; 4], [0; 4])).unwrap(); - let Item::Bitmap { rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - let alpha: Vec = rgba.as_chunks::<4>().0.iter().map(|px| px[3]).collect(); - assert_eq!(alpha, vec![128; 4]); - // Per-pixel alpha (AC_SRC_ALPHA) over a 32-bit premultiplied DIB: BGRA 0, 0, 128, 128 is straight red at - // half alpha, and the constant 128 halves the alpha again. - let one_px = |constant: u8, bgra: [u8; 4]| { - let blend = [0u8, 0, constant, 1]; - let info = info_header(1, 1, 32, 4); - let rec = dib_rec(114, &[(24, 0), (28, 0), (32, 1), (36, 1), (44, 0), (48, 0), (100, 1), (104, 1)], &[(40, &blend[..])], &info, &bgra); - let p = parse(&emf(&[rec], [0; 4], [0; 4])).unwrap(); - let Item::Bitmap { rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - rgba.clone() - }; - assert_eq!(one_px(255, [0, 0, 128, 128]), [255, 0, 0, 128]); - assert_eq!(one_px(128, [0, 0, 128, 128]), [255, 0, 0, 64]); - assert_eq!(one_px(255, [10, 20, 64, 128]), [128, 40, 20, 128], "rounded to the nearest value"); -} - -#[test] -fn emf_srcand_mask_draws_all_but_its_white_pixels() { - // SRCAND over white paper is the source itself; white keeps the destination, so it is transparent. - let dib = dib24_bottom_up(); - let rec = bitblt_rec(0x0088_00C6, [0, 0, 2, 2], &dib[..40], &dib[40..]); - let p = parse(&emf(&[rec], [0; 4], [0; 4])).unwrap(); - let Item::Bitmap { rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - assert_eq!(rgba.as_slice(), [255, 0, 0, 255, 255, 255, 255, 0, 0, 0, 255, 255, 0, 255, 0, 255]); -} - -#[test] -fn emf_srcpaint_makes_black_pixels_transparent() { - // A 2 x 1 DIB: black, then red. SRCPAINT leaves black transparent; SRCCOPY keeps it opaque. - let info = info_header(2, 1, 24, 8); - let bits = [0u8, 0, 0, 0, 0, 255, 0, 0]; - let p = parse(&emf(&[bitblt_rec(0x00EE_0086, [0, 0, 2, 1], &info, &bits)], [0; 4], [0; 4])).unwrap(); - let Item::Bitmap { rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - assert_eq!(rgba.as_slice(), [0, 0, 0, 0, 255, 0, 0, 255]); - let p = parse(&emf(&[bitblt_rec(0x00CC_0020, [0, 0, 2, 1], &info, &bits)], [0; 4], [0; 4])).unwrap(); - let Item::Bitmap { rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - assert_eq!(rgba.as_slice(), [0, 0, 0, 255, 255, 0, 0, 255]); -} - -#[test] -fn wmf_dib_palette_entries_are_skipped_before_the_bits() { - // A 24-bit DIB with biClrUsed = 2 carries two RGBQUADs (8 bytes) before its pixel bits. - let mut info = info_header(2, 2, 24, 16); - info[32..36].copy_from_slice(&2u32.to_le_bytes()); - let mut dib = info; - dib.extend([9u8; 8]); - dib.extend(&dib24_bottom_up()[40..]); - let params = cat(vec![h32(0x00CC_0020), h16(0), h16(2), h16(2), h16(0), h16(0), h16(10), h16(20), h16(0), h16(0), dib]); - let p = parse(&wmf(&[wrec(0x0F43, ¶ms)], None)).unwrap(); - let Item::Bitmap { rgba, .. } = &p.items[0] else { panic!("expected a bitmap") }; - assert_eq!(rgba.as_slice(), DIB24_RGBA); -} - -#[test] -fn emf_point_counts_past_the_budget_are_rejected() { - // A count of 4 billion points in a record that cannot hold them: nothing is drawn and nothing is allocated. - let mut poly = vec![0u8; 16]; - poly.extend(cat(vec![h32(u32::MAX), h32(0), h32(0)])); - let mut groups = vec![0u8; 16]; - groups.extend(cat(vec![h32(u32::MAX), h32(u32::MAX), h32(1)])); - let p = parse(&emf(&[erec(4, &poly), erec(7, &groups)], [0; 4], [0; 4])).unwrap(); - assert!(p.items.is_empty()); -} - -#[test] -fn emf_polypolygon_counts_must_fit_the_record() { - // A polygon count within the point budget in a record too short to hold the counts draws nothing. - let mut short = vec![0u8; 16]; - short.extend(cat(vec![h32(crate::MAX_PATH_OPS as u32), h32(3), h32(3)])); - // POLYPOLYGON16: two triangles of three points each. - let mut two = vec![0u8; 16]; - two.extend(cat(vec![h32(2), h32(6), h32(3), h32(3)])); - two.extend(cat([0, 0, 10, 0, 0, 10, 20, 0, 30, 0, 20, 10].iter().map(|v| h16(*v)).collect())); - let p = parse(&emf(&[erec(91, &short), erec(91, &two)], [0; 4], [0; 4])).unwrap(); - assert_eq!(p.items.len(), 1); - let (segs, ..) = path_segs(&p.items[0]); - assert_eq!(segs.iter().filter(|s| matches!(s, Seg::Move(..))).count(), 2, "{segs:?}"); -} - -/// EMR_EXTCREATEPEN into slot 1 with LogPenEx style, width and brush style, then a selected rectangle. -fn ext_pen_rect(style: u32, width: u32, brush: u32) -> Option<([u8; 4], f32)> { - let pen = erec_at(95, 52, &[(8, 1), (28, style), (32, width), (36, brush), (40, 0x0000_FF00)], &[]); - let recs = [pen, erec(37, &h32(1)), erec(43, &cat(vec![e32(0), e32(0), e32(10), e32(10)]))]; - let p = parse(&emf(&recs, [0; 4], [0; 4])).unwrap(); - path_segs(&p.items[0]).2 -} - -#[test] -fn emf_ext_pen_cosmetic_is_a_hairline_and_null_brush_draws_nothing() { - // PS_COSMETIC widths are device pixels: a hairline, not one logical unit. - assert_eq!(ext_pen_rect(0, 1, 0), Some(([0, 255, 0, 255], 0.0))); - // PS_GEOMETRIC (0x10000) keeps its logical width. - assert_eq!(ext_pen_rect(0x0001_0000, 4, 0), Some(([0, 255, 0, 255], 4.0))); - // A BS_NULL brush draws no line. - assert_eq!(ext_pen_rect(0x0001_0000, 4, 1), None); -} - -#[test] -fn flip_tolerates_a_short_pixel_buffer() { - let mut img = Rgba { w: 2, h: 2, px: vec![1u8; 7] }; - crate::dib::flip(&mut img, true, true); - assert_eq!(img.px.len(), 7); - // Three rows held of four: only the rows present swap (0 with 2). - let mut img = Rgba { w: 1, h: 4, px: (0u8..12).collect() }; - crate::dib::flip(&mut img, false, true); - assert_eq!(img.px, [8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3]); -} - -#[test] -fn place_fits_the_frame_scales_strokes_and_drops_far_paths() { - let pic = crate::Picture { - width: 100.0, - height: 50.0, - items: vec![ - Item::Path { segs: vec![Seg::Move(0.0, 0.0), Seg::Line(10.0, 10.0)], fill: None, stroke: Some(([0, 0, 0, 255], 4.0)), even_odd: true }, - Item::Path { segs: vec![Seg::Move(0.0, 0.0), Seg::Line(2e6, 0.0)], fill: None, stroke: None, even_odd: true }, - ], - }; - let placed = pic.place(kurbo::Rect::new(0.0, 0.0, 200.0, 100.0), [0.0; 4]); - assert_eq!(placed.len(), 1); - let crate::PlacedItem::Path { stroke, .. } = &placed[0] else { panic!("expected a path") }; - assert_eq!(stroke.map(|s| s.1), Some(8.0)); -} - -/// #1899: a crop keeps what the file says down to a sliver (a header's bar is 2.7% of a page-sized -/// metafile), and junk sides give a finite part of the source with some area. -#[test] -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() }; - 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); - let bottom = tf * kurbo::Point::new(0.0, 545.15); - assert!(top.y.abs() < 1e-3 && (bottom.y - 27.44).abs() < 1e-3, "{top:?} {bottom:?}"); - for c in [[f32::NAN, f32::INFINITY, -1.0, 2.0], [0.9; 4], [1.0, 1.0, 0.0, 0.0], [f32::MAX, f32::MIN, f32::NEG_INFINITY, 0.5]] { - let [x, y, w, h] = crate::crop_window(c); - assert!([x, y, w, h].iter().all(|v| v.is_finite()) && w > 0.0 && h > 0.0 && x + w <= 1.0 + 1e-9 && y + h <= 1.0 + 1e-9, "{c:?}"); - } -} - -/// The narrowest crop on the largest frame layout makes (4000 pt, far down a 22-inch page) still -/// places the source's content: none of it is left out as far off the page. -#[test] -fn the_narrowest_crop_on_the_largest_frame_keeps_its_content() { - let pic = crate::Picture { - width: 100.0, - height: 100.0, - items: vec![ - Item::Bitmap { rect: [0.0, 0.0, 100.0, 100.0], width: 1, height: 1, rgba: vec![255; 4] }, - Item::Path { segs: vec![Seg::Move(0.0, 0.0), Seg::Line(100.0, 100.0)], fill: None, stroke: Some(([0, 0, 0, 255], 1.0)), even_odd: false }, - ], - }; - let frame = kurbo::Rect::new(1584.0, 1584.0, 5584.0, 5584.0); - // The last sliver, the first sliver, and sides that overlap. - for crop in [[1.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 1.0], [0.9999, 0.6, 0.5, 0.9999]] { - assert_eq!(pic.place(frame, crop).len(), 2, "{crop:?}"); - } -} - -#[test] -fn place_keeps_only_finite_bounded_bitmaps_with_area() { - let bitmap = |rect: [f32; 4]| Item::Bitmap { rect, width: 1, height: 1, rgba: vec![0; 4] }; - let pic = crate::Picture { - width: 100.0, - height: 50.0, - items: vec![ - bitmap([f32::NAN, 0.0, 10.0, 10.0]), - bitmap([0.0, 0.0, 0.0, 10.0]), - bitmap([0.0, 0.0, 2e6, 10.0]), - bitmap([0.0, 0.0, f32::INFINITY, 10.0]), - bitmap([10.0, 5.0, 10.0, 10.0]), - ], - }; - let placed = pic.place(kurbo::Rect::new(0.0, 0.0, 200.0, 100.0), [0.0; 4]); - assert_eq!(placed.len(), 1); - let crate::PlacedItem::Bitmap { index, rect } = &placed[0] else { panic!("expected a bitmap") }; - assert_eq!((*index, *rect), (4, kurbo::Rect::new(20.0, 10.0, 40.0, 30.0))); -} - -/// `size` against the full parse: same numbers or same error, and whether the header decided it. -fn assert_size_matches_parse(file: &[u8], from_header: bool, what: &str) { - let full = parse(file).map(|p| (p.width, p.height)); - assert_eq!(crate::size(file), full, "{what}"); - assert_eq!(crate::size::header_size(crate::bytes::Bytes(file)).is_some(), from_header, "{what}: header path"); - if let Some(s) = crate::size::header_size(crate::bytes::Bytes(file)) { - assert_eq!(Ok(s), full, "{what}: header size"); - } -} - -#[test] -fn size_from_the_header_equals_the_full_parse() { - let rect = || erec(43, &cat(vec![e32(0), e32(0), e32(50), e32(25)])); - let emfs = [ - ("emf with a frame", emf(&[rect()], [0, 0, 50, 25], [0, 0, 2500, 1250]), true), - ("emf with a large frame", emf(&[rect()], [0, 0, 50, 25], [-90_000, 0, 900_000, 1_250_000]), true), - ("emf with an empty frame", emf(&[rect()], [0, 0, 50, 25], [0; 4]), false), - ("emf with no records", emf(&[], [0, 0, 50, 25], [0, 0, 2500, 1250]), false), - ("emf with no frame and no bounds", emf(&[rect()], [0; 4], [0; 4]), false), - ]; - for (what, file, header) in &emfs { - assert_size_matches_parse(file, *header, what); - } - let draw = [wrec(0x041B, &cat(vec![h16(1440), h16(2880), h16(0), h16(0)]))]; - let wmfs = [ - ("placeable wmf", wmf(&draw, Some([0, 0, 2880, 1440])), true), - ( - "placeable wmf with a window mapping", - wmf( - &[wrec(0x0103, &h16(8)), wrec(0x020C, &cat(vec![h16(100), h16(200)])), wrec(0x020E, &cat(vec![h16(50), h16(100)])), draw[0].clone()], - Some([0, 0, 200, 100]), - ), - false, - ), - ( - "placeable wmf with a zero viewport", - wmf(&[wrec(0x0103, &h16(8)), wrec(0x020E, &cat(vec![h16(0), h16(0)])), draw[0].clone()], Some([0, 0, 200, 100])), - false, - ), - ("placeable wmf with a window only", wmf(&[wrec(0x020C, &cat(vec![h16(100), h16(200)])), draw[0].clone()], Some([0, 0, 200, 100])), true), - ("placeable wmf with an empty box", wmf(&draw, Some([0, 0, 0, 0])), false), - ("placeable wmf with no records", wmf(&[], Some([0, 0, 2880, 1440])), false), - ("plain wmf", wmf(&draw, None), false), - ]; - for (what, file, header) in &wmfs { - assert_size_matches_parse(file, *header, what); - } - assert_size_matches_parse(b"not a metafile at all", false, "garbage"); - assert_size_matches_parse(&[], false, "empty"); -} - -#[test] -fn size_of_a_truncated_or_mutated_file_equals_the_full_parse() { - let rect = erec(43, &cat(vec![e32(0), e32(0), e32(50), e32(25)])); - let draw = wrec(0x041B, &cat(vec![h16(1440), h16(2880), h16(0), h16(0)])); - let files = [emf(&[rect], [0, 0, 50, 25], [0, 0, 2500, 1250]), wmf(&[draw], Some([0, 0, 2880, 1440]))]; - let mut seed = 0x1234_5678_9ABC_DEF0u64; - for file in &files { - for len in 0..=file.len() { - let cut = &file[..len]; - assert_eq!(crate::size(cut), parse(cut).map(|p| (p.width, p.height)), "cut at {len}"); - } - for _ in 0..3000 { - let mut m = file.clone(); - for _ in 0..3 { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - let at = (seed % m.len() as u64) as usize; - m[at] = (seed >> 32) as u8; - } - let full = parse(&m).map(|p| (p.width, p.height)); - let fast = crate::size(&m); - assert_eq!(fast, full, "{m:?}"); - } - } -} - -/// Time of the full parse against the header-only size for an EMF with one 8000 x 5000, 1 bpp bitmap -/// (5 MB, decodes to 160 MB): `cargo test -p wordcraft-metafile --release -- --ignored --nocapture size_speed`. -#[test] -#[ignore = "timing only"] -fn size_speed() { - let (w, h) = (8000i32, 5000i32); - let mut payload = vec![0u8; 16]; - payload.extend(cat(vec![ - e32(0), - e32(0), - e32(0), - e32(0), - e32(w), - e32(h), - e32(80), - e32(48), - e32(128), - h32((w / 8 * h) as u32), - e32(0), - e32(0x00CC_0020), - e32(100), - e32(50), - ])); - payload.extend(info_header(w, h, 1, 0)); - payload.extend([0, 0, 0, 0, 255, 255, 255, 0]); - payload.extend((0..(w / 8 * h) as usize).map(|i| (i * 31) as u8)); - let file = emf(&[erec(81, &payload)], [0, 0, 100, 50], [0, 0, 2500, 1250]); - for round in 0..4 { - let t = std::time::Instant::now(); - let full = parse(&file).map(|p| (p.width, p.height)); - let full_ms = t.elapsed().as_secs_f64() * 1e3; - let t = std::time::Instant::now(); - let fast = crate::size(&file); - let fast_ms = t.elapsed().as_secs_f64() * 1e6; - assert_eq!(full, fast); - eprintln!("round {round}: parse {full_ms:.1} ms, size {fast_ms:.1} us"); - } -} - -#[test] -fn take_pixels_returns_only_drawable_bitmaps() { - let mut ok = Item::Bitmap { rect: [0.0; 4], width: 2, height: 1, rgba: vec![7; 8] }; - assert_eq!(ok.take_pixels(), Some((2, 1, vec![7; 8]))); - assert!(matches!(&ok, Item::Bitmap { rgba, .. } if rgba.is_empty()), "the pixels move out"); - let mut short = Item::Bitmap { rect: [0.0; 4], width: 2, height: 2, rgba: vec![0; 8] }; - assert_eq!(short.take_pixels(), None); - let side = crate::MAX_BITMAP_SIDE + 1; - let mut wide = Item::Bitmap { rect: [0.0; 4], width: side, height: 1, rgba: vec![0; side as usize * 4] }; - assert_eq!(wide.take_pixels(), None); - let mut path = Item::Path { segs: Vec::new(), fill: None, stroke: None, even_odd: false }; - assert_eq!(path.take_pixels(), None); - let pic = |width: f32, height: f32| crate::Picture { width, height, items: Vec::new() }; - 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()); -} - -/// The rectangle a WMF RECTANGLE record covers, from its path's corners. -fn rect_extent(item: &Item) -> (f32, f32, f32, f32) { - let (segs, ..) = path_segs(item); - let pts: Vec<(f32, f32)> = segs - .iter() - .filter_map(|s| match s { - Seg::Move(x, y) | Seg::Line(x, y) => Some((*x, *y)), - _ => None, - }) - .collect(); - let (xs, ys): (Vec, Vec) = pts.into_iter().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)) -} - -#[test] -fn plain_anisotropic_wmf_without_a_viewport_fills_its_window() { - // Anisotropic, window 200 x 100, no viewport (a logo strip saved without a placeable header): the - // window is the target, not a 1 x 1 viewport that squeezes the picture to a point. - let recs = [ - wrec(0x0103, &h16(8)), - wrec(0x020B, &cat(vec![h16(0), h16(0)])), - wrec(0x020C, &cat(vec![h16(100), h16(200)])), - wrec(0x041B, &cat(vec![h16(100), h16(200), h16(0), h16(0)])), - ]; - let p = parse(&wmf(&recs, None)).unwrap(); - assert_eq!((p.width, p.height), (200.0, 100.0)); - let (x0, y0, x1, y1) = rect_extent(&p.items[0]); - assert!(close(x0, 0.0) && close(y0, 0.0) && close(x1, 200.0) && close(y1, 100.0), "{x0} {y0} {x1} {y1}"); -} - -#[test] -fn placeable_wmf_window_records_replace_the_bounds() { - // The placeable bounds say 1440 square (72 points); the file then draws in a window centred on the - // origin, as a coat of arms saved by a drawing program does. The window maps onto the 72-point - // target, so the drawing fills it instead of being blown up around the bounds. - let recs = [ - wrec(0x020C, &cat(vec![h16(2000), h16(2000)])), - wrec(0x020B, &cat(vec![h16(-1000), h16(-1000)])), - wrec(0x041B, &cat(vec![h16(1000), h16(1000), h16(-1000), h16(-1000)])), - ]; - let p = parse(&wmf(&recs, Some([238, 539, 1678, 1979]))).unwrap(); - assert_eq!((p.width, p.height), (72.0, 72.0)); - let (x0, y0, x1, y1) = rect_extent(&p.items[0]); - assert!(close(x0, 0.0) && close(y0, 0.0) && close(x1, 72.0) && close(y1, 72.0), "{x0} {y0} {x1} {y1}"); -} - -#[test] -fn placeable_wmf_keeps_its_target_when_the_window_changes_shape() { - // Bounds 600 x 300 (30 x 15 points), then a portrait window 100 x 200 for a bitmap-sized drawing: - // the drawing still fills the target (Word stretches it to the picture's box). - let recs = [wrec(0x0103, &h16(8)), wrec(0x020C, &cat(vec![h16(200), h16(100)])), wrec(0x041B, &cat(vec![h16(200), h16(100), h16(0), h16(0)]))]; - let p = parse(&wmf(&recs, Some([0, 0, 600, 300]))).unwrap(); - assert_eq!((p.width, p.height), (30.0, 15.0)); - let (x0, y0, x1, y1) = rect_extent(&p.items[0]); - assert!(close(x0, 0.0) && close(y0, 0.0) && close(x1, 30.0) && close(y1, 15.0), "{x0} {y0} {x1} {y1}"); -} - -#[test] -fn rop2_nop_draws_nothing_until_the_mode_changes() { - // A coat of arms that first draws its bounding rectangle with the R2_NOP mix mode (no output), - // then its shapes with R2_COPYPEN. Restoring a saved state brings R2_NOP back. - let rect = |n: i32| wrec(0x041B, &cat(vec![h16(n), h16(n), h16(0), h16(0)])); - let recs = [wrec(0x0104, &h16(11)), rect(100), wrec(0x001E, &[]), wrec(0x0104, &h16(13)), rect(50), wrec(0x0127, &h16(-1)), rect(20)]; - let p = parse(&wmf(&recs, Some([0, 0, 100, 100]))).unwrap(); - assert_eq!(p.items.len(), 1, "{:?}", p.items); - let (_, _, x1, y1) = rect_extent(&p.items[0]); - // 50 of 100 units in a 5-point picture. - assert!(close(x1, 2.5) && close(y1, 2.5), "{x1} {y1}"); -} - -#[test] -fn plain_wmf_target_comes_from_a_window_that_was_read() { - // A window record too short to read, then the real one: the target is the real window, not the - // 1 x 1 default the short record left in place. A viewport origin set before it is kept. - let recs = [ - wrec(0x0103, &h16(8)), - wrec(0x020D, &cat(vec![h16(0), h16(0)])), - wrec(0x020C, &[]), - wrec(0x020C, &cat(vec![h16(100), h16(200)])), - wrec(0x041B, &cat(vec![h16(100), h16(200), h16(0), h16(0)])), - ]; - let p = parse(&wmf(&recs, None)).unwrap(); - assert_eq!((p.width, p.height), (200.0, 100.0)); - let (x0, y0, x1, y1) = rect_extent(&p.items[0]); - assert!(close(x0, 0.0) && close(y0, 0.0) && close(x1, 200.0) && close(y1, 100.0), "{x0} {y0} {x1} {y1}"); -} - -/// A poly-polygon's group counts are file data: a long list of empty groups adds no ops, so it -/// mustn't reserve room for them either (the canvas charges what a path holds, capacity included). -#[test] -fn empty_poly_groups_reserve_nothing() { - let pts = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)]; - let mut counts = vec![0usize; 100_000]; - counts.push(3); - let ops = crate::geom::subpaths(&pts, &counts, true); - assert_eq!(ops.len(), 4, "M L L Z"); - assert!(ops.capacity() <= 8, "capacity {}", ops.capacity()); - // Counts past the points are cut short, and the size still matches. - let ops = crate::geom::subpaths(&pts, &[2, 5, 4], false); - assert_eq!((ops.len(), ops.capacity()), (3, 3)); -} diff --git a/crates/metafile/src/wmf.rs b/crates/metafile/src/wmf.rs deleted file mode 100644 index 54c14271f7..0000000000 --- a/crates/metafile/src/wmf.rs +++ /dev/null @@ -1,272 +0,0 @@ -//! WMF reader (MS-WMF). A file is an optional 22-byte placeable header, a 9-word standard header, then -//! records of (size in 16-bit words, function, parameters). Parameters are read at byte 6 of each record. - -use crate::bytes::Bytes; -use crate::canvas::{Brush, Canvas, Obj, Pen, colorref}; -use crate::dib; -use crate::geom::{self, ArcKind, P}; -use crate::{Error, Frame, MAX_PATH_OPS}; - -const PLACEABLE_KEY: u32 = 0x9AC6_CDD7; -const DEFAULT_INCH: f64 = 1440.0; - -pub(crate) fn is_wmf(b: Bytes) -> bool { - if b.u32(0) == Some(PLACEABLE_KEY) { - return true; - } - matches!(b.u16(0), Some(1 | 2)) && b.u16(2) == Some(9) && matches!(b.u16(4), Some(0x100 | 0x300)) -} - -/// Reads all records. Returns the drawing state and the picture frame, or an error when no record -/// could be read at all. -pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> { - let placeable = input.u32(0) == Some(PLACEABLE_KEY); - // Placeable bounds: logical corners (left, top, right, bottom) and their size in points. - let (hdr, bounds) = if placeable { - let [l, t, r, b] = [6, 8, 10, 12].map(|o| input.i16(o).map(f64::from)); - let (Some(l), Some(t), Some(r), Some(b)) = (l, t, r, b) else { return Err(Error::BadHeader) }; - let inch = input.u16(14).filter(|v| *v > 0).map_or(DEFAULT_INCH, f64::from); - let (w, h) = (r - l, b - t); - let bounds = (w > 0.0 && h > 0.0).then_some(([l, t, r, b], (w * 72.0 / inch, h * 72.0 / inch))); - (22, bounds) - } else { - (0, None) - }; - let hsize = input.u16(hdr + 2).ok_or(Error::BadHeader)? as usize; - if hsize < 9 { - return Err(Error::BadHeader); - } - let mut pos = hdr.checked_add(hsize.checked_mul(2).ok_or(Error::BadHeader)?).ok_or(Error::BadHeader)?; - // Played into a target like Word does: the placeable bounds are the first window, the target (the - // picture size) the viewport. A plain WMF's target is its first window. - let mut cv = Canvas::new(); - if let Some((c, size)) = bounds { - cv.play_into(Some([c[0], c[1], c[2] - c[0], c[3] - c[1]]), size); - } - let mut player_viewport = bounds.is_some(); - 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 }; - let Some(len) = (words as usize).checked_mul(2).filter(|l| *l >= 6) else { break }; - let Some(rec) = input.slice(pos, len) else { break }; - if func == 0 { - break; - } - record(&mut cv, func, Bytes(rec)); - if func == 0x020C && cv.window_set && !player_viewport && !cv.viewport_set { - let we = cv.map.window_ext(); - cv.play_into(None, (we.0.abs(), we.1.abs())); - player_viewport = true; - } - parsed += 1; - let Some(next) = pos.checked_add(len) else { break }; - pos = next; - } - if parsed == 0 { - return Err(Error::NoRecords); - } - let frame = match bounds { - // Played into its target: the frame is the target. - Some((_, size)) if !cv.viewport_set && cv.map.uses_extents() => Some(Frame { rect: [0.0, 0.0, size.0, size.1], size: Some(size) }), - // The file set its own viewport, so the drawing is in its device units and the logical bounds - // go through the final mapping. - Some((c, size)) => { - let (a, b) = (cv.map.device((c[0], c[1])), cv.map.device((c[2], c[3]))); - 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.window_set => Some(Frame { rect: cv.map.window_rect(), size: None }), - None => None, - }; - Ok((cv, frame)) -} - -fn record(cv: &mut Canvas, func: u16, r: Bytes) { - if cv.full() { - return; - } - let _ = match func { - 0x0103 => r.u16(6).map(|m| cv.set_map_mode(u32::from(m))), - 0x0106 => r.u16(6).map(|m| cv.set_polyfill(u32::from(m))), - 0x0104 => r.u16(6).map(|m| cv.set_rop2(u32::from(m))), - // Y is stored before X in these records. - 0x020B => xy16(r, 6).map(|p| cv.set_window_org(p)), - 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)), - 0x001E => { - cv.save_dc(); - Some(()) - } - 0x0127 => r.i16(6).map(|n| cv.restore_dc(i32::from(n))), - 0x0214 => xy16(r, 6).map(|p| cv.move_to(p)), - 0x0213 => xy16(r, 6).map(|p| cv.line_to(p)), - 0x0325 => counted_points(r).map(|pts| cv.poly(&pts, false, false, true)), - 0x0324 => counted_points(r).map(|pts| cv.poly(&pts, true, true, true)), - 0x0538 => polypolygon(r).map(|ops| cv.shape(ops, true, true)), - 0x041B => rect16(r, 6).map(|[l, t, rr, b]| cv.shape(geom::rect(l, t, rr, b), true, true)), - 0x061C => { - let [ew, eh] = [r.i16(8), r.i16(6)]; - let (Some(ew), Some(eh)) = (ew, eh) else { return }; - rect16(r, 10).map(|[l, t, rr, b]| { - cv.shape(geom::round_rect(l, t, rr, b, f64::from(ew), f64::from(eh)), true, true); - }) - } - 0x0418 => rect16(r, 6).map(|[l, t, rr, b]| cv.shape(geom::ellipse(l, t, rr, b), true, true)), - 0x0817 | 0x081A | 0x0830 => arc16(r).map(|(bounds, s, e)| { - let kind = match func { - 0x0817 => ArcKind::Arc, - 0x081A => ArcKind::Pie, - _ => ArcKind::Chord, - }; - let [l, t, rr, b] = bounds; - cv.shape(geom::arc_shape(l, t, rr, b, s, e, kind), kind != ArcKind::Arc, true); - }), - 0x02FA => create_pen(cv, r), - 0x02FC => create_brush(cv, r), - // Fonts, palettes, pattern brushes and regions take a handle slot too, so later SELECTOBJECT - // handles count them; selecting one draws nothing. - 0x02FB | 0x00F7 | 0x01F9 | 0x0142 | 0x06FF => { - cv.add_object(None, Obj::Other); - Some(()) - } - 0x012D => r.u16(6).map(|h| cv.select(wmf_handle(h))), - 0x01F0 => r.u16(6).map(|h| cv.delete_object(u32::from(h))), - // STRETCHDIB: rop(4) usage(2) srcH srcW ySrc xSrc destH destW yDest xDest, then the DIB. - 0x0F43 => { - let rop = r.u32(6).unwrap_or(0); - dib_blit(cv, r, 28, rop, [i16s(r, 26), i16s(r, 24), i16s(r, 22), i16s(r, 20)], [i16s(r, 18), i16s(r, 16), i16s(r, 14), i16s(r, 12)]) - } - 0x0B41 => dib_stretchblt(cv, r), - 0x0940 => dib_bitblt(cv, r), - _ => Some(()), - }; -} - -/// A 16-bit WMF handle as a canvas object index: stock objects are `0x8000 | index`, which the -/// canvas reads with the 32-bit stock flag. -fn wmf_handle(h: u16) -> u32 { - let h = u32::from(h); - if h & 0x8000 != 0 { (h & 0x7FFF) | 0x8000_0000 } else { h } -} - -/// An i16 field as f64; 0 past the end. -fn i16s(r: Bytes, off: usize) -> f64 { - r.i16(off).map_or(0.0, f64::from) -} - -/// CREATEPENINDIRECT: style, width (x, y), colour. Only the width's x component is used. -fn create_pen(cv: &mut Canvas, r: Bytes) -> Option<()> { - let style = r.u16(6)?; - let width = r.i16(8)?; - let color = r.u32(12)?; - cv.add_object(None, Obj::Pen(Pen { style: u32::from(style), width: f64::from(width), color: colorref(color) })); - Some(()) -} - -/// CREATEBRUSHINDIRECT: style, colour, hatch (hatch is not drawn). -fn create_brush(cv: &mut Canvas, r: Bytes) -> Option<()> { - let style = r.u16(6)?; - let color = r.u32(8)?; - cv.add_object(None, Obj::Brush(Brush { style: u32::from(style), color: colorref(color) })); - Some(()) -} - -/// (x, y) from a Y-then-X pair stored at `off`. -fn xy16(r: Bytes, off: usize) -> Option

{ - Some((f64::from(r.i16(off + 2)?), f64::from(r.i16(off)?))) -} - -/// Rectangle stored as bottom, right, top, left (the order MS-WMF uses for RECTANGLE and ELLIPSE). -fn rect16(r: Bytes, off: usize) -> Option<[f64; 4]> { - let (b, rr, t, l) = (r.i16(off)?, r.i16(off + 2)?, r.i16(off + 4)?, r.i16(off + 6)?); - Some([f64::from(l), f64::from(t), f64::from(rr), f64::from(b)]) -} - -/// ARC, PIE and CHORD: end Y, end X, start Y, start X, then the bounding rectangle (bottom, right, top, left). -fn arc16(r: Bytes) -> Option<([f64; 4], P, P)> { - let end = xy16(r, 6)?; - let start = xy16(r, 10)?; - let bounds = rect16(r, 14)?; - Some((bounds, start, end)) -} - -/// A count of 16-bit points, then the points (POLYLINE, POLYGON). -fn counted_points(r: Bytes) -> Option> { - let n = r.u16(6)? as usize; - r.tail(8)?.points(0, n, false) -} - -/// POLYPOLYGON: polygon count, one 16-bit point count per polygon, then all points. -fn polypolygon(r: Bytes) -> Option> { - let n = r.u16(6)? as usize; - let mut counts = Vec::with_capacity(n); - for i in 0..n { - counts.push(r.u16(i.checked_mul(2)?.checked_add(8)?)? as usize); - } - let total = counts.iter().try_fold(0usize, |a, c| a.checked_add(*c))?; - if total > MAX_PATH_OPS { - return None; - } - let pts = r.tail(n.checked_mul(2)?.checked_add(8)?)?.points(0, total, false)?; - Some(geom::subpaths(&pts, &counts, true)) -} - -/// Whether a DIBBITBLT or DIBSTRETCHBLT record carries a bitmap: without one it is exactly -/// `(function >> 8) + 3` words long (MS-WMF 2.3.1.2, 2.3.1.3). -fn has_bitmap(func: u16, r: Bytes) -> bool { - r.0.len() / 2 > usize::from(func >> 8) + 3 -} - -/// META_DIBBITBLT: rop(4), ySrc, xSrc, then height, width, yDest, xDest and the DIB at 22. The -/// bitmap-less form has a reserved word before the height, so its fields sit 2 bytes later; it, or -/// a source-less raster operation, fills the destination. -fn dib_bitblt(cv: &mut Canvas, r: Bytes) -> Option<()> { - let rop = r.u32(6)?; - if !has_bitmap(0x0940, r) { - cv.fill_rop([i16s(r, 22), i16s(r, 20), i16s(r, 18), i16s(r, 16)], rop); - return Some(()); - } - let dst = [i16s(r, 20), i16s(r, 18), i16s(r, 16), i16s(r, 14)]; - if Canvas::sourceless(rop) { - cv.fill_rop(dst, rop); - return Some(()); - } - let src = [i16s(r, 12), i16s(r, 10), dst[2], dst[3]]; - dib_blit(cv, r, 22, rop, dst, src) -} - -/// META_DIBSTRETCHBLT: rop(4), srcH, srcW, ySrc, xSrc, then destH, destW, yDest, xDest and the DIB at -/// 26. The bitmap-less form has a reserved word after xSrc, so the destination sits 2 bytes later; -/// it, or a source-less raster operation, fills the destination. -fn dib_stretchblt(cv: &mut Canvas, r: Bytes) -> Option<()> { - let rop = r.u32(6)?; - if !has_bitmap(0x0B41, r) { - cv.fill_rop([i16s(r, 26), i16s(r, 24), i16s(r, 22), i16s(r, 20)], rop); - return Some(()); - } - let dst = [i16s(r, 24), i16s(r, 22), i16s(r, 20), i16s(r, 18)]; - if Canvas::sourceless(rop) { - cv.fill_rop(dst, rop); - return Some(()); - } - let src = [i16s(r, 16), i16s(r, 14), i16s(r, 12), i16s(r, 10)]; - dib_blit(cv, r, 26, rop, dst, src) -} - -/// 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`]). -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)?; - dib::prepare(&mut img, dib::Blend::Rop(rop)); - cv.bitmap(dst, img); - Some(()) -} diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index 01006d4f63..80c33d85b4 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -13,7 +13,7 @@ wordcraft-doc = { workspace = true } wordcraft-geom = { workspace = true, features = ["image"] } wordcraft-fonts = { workspace = true } wordcraft-layout = { workspace = true } -wordcraft-metafile = { workspace = true } +craft-metafile = { workspace = true } craft-pdf = { workspace = true } kurbo = { workspace = true } image = { workspace = true } diff --git a/crates/pdf/src/exporter.rs b/crates/pdf/src/exporter.rs index 77fe80c348..48cfecf374 100644 --- a/crates/pdf/src/exporter.rs +++ b/crates/pdf/src/exporter.rs @@ -90,7 +90,7 @@ impl Exporter<'_> { fn vector(&mut self, key: &str) -> Option> { let doc = self.doc; let bytes = doc.media.get(key)?; - if !wordcraft_metafile::is_metafile(bytes) { + if !craft_metafile::is_metafile(bytes) { return None; } if let Some(v) = self.vectors.get(key) { diff --git a/crates/pdf/src/exporter/draw.rs b/crates/pdf/src/exporter/draw.rs index 5ad2f16a36..7ae7c511bf 100644 --- a/crates/pdf/src/exporter/draw.rs +++ b/crates/pdf/src/exporter/draw.rs @@ -324,7 +324,7 @@ impl Exporter<'_> { s.set_fill(None); return; }; - let [cl, ct, vis_w, vis_h] = wordcraft_metafile::crop_window(*crop).map(|v| v as f32); + let [cl, ct, vis_w, vis_h] = wordcraft_layout::crop_window(*crop).map(|v| v as f32); let (fw, fh) = (rect.w / vis_w, rect.h / vis_h); let Some(size) = Size::from_wh(fw.max(0.01), fh.max(0.01)) else { return }; let fade = alpha < 0.999; diff --git a/crates/pdf/src/exporter/text.rs b/crates/pdf/src/exporter/text.rs index d1eeeb74b3..e0038570a0 100644 --- a/crates/pdf/src/exporter/text.rs +++ b/crates/pdf/src/exporter/text.rs @@ -1,6 +1,6 @@ use super::{ - Exporter, FaceRef, Fill, FillRule, KrillaGlyph, Point, Rgb, Stroke, Surface, Transform, baseline, cluster_ends, fill, glyph_id, glyph_outlines, - left_to_right, norm, ok, paint_of, rgb, split_clusters, visual_order, + Exporter, FaceRef, Fill, FillRule, KrillaGlyph, Point, Rect, Rgb, Stroke, Surface, Transform, baseline, cluster_ends, fill, glyph_id, + glyph_outlines, left_to_right, norm, ok, paint_of, rect_path, rgb, split_clusters, visual_order, }; /// How a run of glyphs is painted: its colour, opacity and synthetic bold and italic. @@ -181,11 +181,11 @@ impl Exporter<'_> { } /// Draws a metafile text run as PDF text (outlines when the font cannot be embedded). `tf` maps - /// the run's own space (see [`PlacedItem::Text`]) to the page. - pub(crate) fn vector_text(&mut self, s: &mut Surface, t: &wordcraft_metafile::Text, tf: kurbo::Affine) { + /// its text space (`craft_metafile::Text::transform`) to the page. + pub(crate) fn vector_text(&mut self, s: &mut Surface, t: &craft_metafile::Text, tf: kurbo::Affine) { let (face, shaped) = wordcraft_layout::metafile_text_run(t); let glyphs: Vec<_> = shaped.iter().map(|g| (g.cluster, f64::from(g.x_advance), f64::from(g.x_offset), f64::from(g.y_offset))).collect(); - let Some(lay) = t.layout(face.upem, face.ascent, face.descent, &glyphs) else { return }; + let Some(lay) = wordcraft_layout::metafile_text_layout(t, face.upem, face.ascent, face.descent, &glyphs) else { return }; let font = self.font(&face); if font.is_none() && !self.outlined.contains(&face.id()) { return; @@ -198,6 +198,15 @@ impl Exporter<'_> { let (paint, opacity) = paint_of(t.color); s.push_transform(&Transform::from_row(c[0], c[1], c[2], c[3], c[4], c[5])); s.set_stroke(None); + // An opaque background mode fills the character cells first. + if let Some(bg) = t.background { + let [x0, y0, x1, y1] = lay.cell.map(|v| v as f32); + if let Some(cell) = rect_path(&Rect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }) { + let (paint, opacity) = paint_of(bg); + s.set_fill(Some(Fill { paint: paint.into(), opacity, rule: FillRule::NonZero })); + s.draw_path(&cell); + } + } s.set_fill(Some(Fill { paint: paint.into(), opacity, rule: FillRule::NonZero })); match font { Some(font) => { diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index de43694a7f..e4454f0694 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -28,6 +28,7 @@ use std::collections::{HashMap, HashSet}; use std::num::NonZeroU16; use std::sync::Arc; +use craft_metafile::{Picture, PlacedItem}; use craft_pdf::write::{self, Metadata, WriteError, Writer, backend as krilla}; use krilla::annotation::{Annotation, LinkAnnotation, Target}; use krilla::color::rgb; @@ -52,7 +53,6 @@ use wordcraft_layout::display::Paint; use wordcraft_layout::display::{Draw, ItemDisplay, Stroke as LineStyle}; use wordcraft_layout::para::{ClKind, LineEnd}; use wordcraft_layout::{DocLayout, LayoutCache, NumeralMode, Page, Placed, layout}; -use wordcraft_metafile::{Picture, PlacedItem}; mod export; mod exporter; diff --git a/crates/pdf/src/picture.rs b/crates/pdf/src/picture.rs index 66b9938a0b..59c2f15d6a 100644 --- a/crates/pdf/src/picture.rs +++ b/crates/pdf/src/picture.rs @@ -1,28 +1,51 @@ use super::exporter::Exporter; use super::paint::{append_path, norm}; use super::{ - Arc, Fill, FillRule, Image, LineCap, LineJoin, NormalizedF32, Path, PathBuilder, Picture, PlacedItem, Rect, Size, Stroke, Surface, Transform, rgb, + Arc, Fill, FillRule, Image, LineCap, LineJoin, NormalizedF32, Path, PathBuilder, Picture, PlacedItem, Rect, Size, Stroke, StrokeDash, Surface, + Transform, krilla, rgb, }; +use craft_metafile::Item; +use kurbo::Shape as _; use wordcraft_doc::picfx::PicFx; /// Largest picture side we embed (pixels). const MAX_IMAGE_SIDE: u32 = 30_000; -/// A metafile picture, parsed once. The geometry comes placed by the metafile crate; the bitmaps are -/// embedded images, one per picture item (None for paths and undecodable bitmaps). +/// A metafile picture, parsed once. The geometry comes placed by the metafile crate; the bitmaps and +/// pattern tiles are embedded images, one per picture item (None for paths, text and undecodable +/// bitmaps). Fills that share a tile share its image. `averages` holds each pattern fill's tile +/// average color (transparent for other items), computed once a tile. pub(crate) struct Vector { pic: Picture, images: Vec>, + averages: Vec<[u8; 4]>, } -/// Parses a metafile and embeds its bitmaps. None when the picture has no usable size. +/// Parses a metafile and embeds its bitmaps and pattern tiles. None when the picture has no usable +/// size. pub(crate) fn build_vector(bytes: &[u8]) -> Option { - let mut pic = wordcraft_metafile::parse(bytes).ok()?; + let mut pic = craft_metafile::parse(bytes).ok()?; if !pic.has_size() { return None; } - let images = pic.items.iter_mut().map(|it| it.take_pixels().map(|(w, h, px)| Image::from_rgba8(px, w, h))).collect(); - Some(Vector { pic, images }) + let mut tiles: std::collections::HashMap, [u8; 4])> = std::collections::HashMap::new(); + let (images, averages) = pic + .items + .iter_mut() + .map(|it| match it { + Item::Pattern { tile, .. } => tiles + .entry(Arc::as_ptr(tile) as usize) + .or_insert_with(|| { + let n = (tile.width as usize).saturating_mul(tile.height as usize).saturating_mul(4); + let img = (tile.width > 0 && tile.height > 0 && tile.rgba.len() == n) + .then(|| Image::from_rgba8(tile.rgba.clone(), tile.width, tile.height)); + (img, wordcraft_layout::metafile_average_color(&tile.rgba)) + }) + .clone(), + _ => (it.take_pixels().map(|(w, h, px)| Image::from_rgba8(px, w, h)), [0; 4]), + }) + .unzip(); + Some(Vector { pic, images, averages }) } /// A straight RGBA colour as a krilla colour and opacity. @@ -36,9 +59,10 @@ pub(crate) fn paint_of(c: [u8; 4]) -> (rgb::Color, NormalizedF32) { const HAIRLINE: f64 = 0.25; /// Draws a metafile picture into the clip (the picture frame): paths are filled and stroked in page -/// space (strokes keep their width under non-uniform scaling), bitmaps stretched, all faded by `alpha`. -/// Every path sets its fill and stroke, so none carries over; strokes have round caps and joins. Text -/// runs are drawn as text. +/// space (strokes keep their width under non-uniform scaling), bitmaps stretched (or turned by their +/// transform), pattern fills tiled, each item inside its clip region and clip paths, all faded by +/// `alpha`. Every path sets its fill and stroke, so none carries over; strokes take the pen's caps, +/// joins and dashes. Text runs are drawn as text. pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r: &Rect, crop: &[f32; 4], clip: &Path, alpha: f32) { let target = kurbo::Rect::new(f64::from(r.x), f64::from(r.y), f64::from(r.x + r.w), f64::from(r.y + r.h)); let fade = alpha < 0.999; @@ -46,9 +70,9 @@ pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r: s.push_opacity(norm(alpha)); } s.push_clip_path(clip, &FillRule::NonZero); - for it in v.pic.place(target, *crop) { + for it in v.pic.place(target, wordcraft_layout::crop_sides(*crop)) { match it { - PlacedItem::Path { path, fill, stroke, even_odd } => { + PlacedItem::Path { path, fill, stroke, line, even_odd, region, clips } => { let Some(p) = path_from(&path) else { continue }; let fill = fill.map(|c| { let (paint, opacity) = paint_of(c); @@ -57,30 +81,63 @@ pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r: }); let stroke = stroke.map(|(c, w)| { let (paint, opacity) = paint_of(c); - Stroke { - paint: paint.into(), - width: w.max(HAIRLINE) as f32, - opacity, - line_cap: LineCap::Round, - line_join: LineJoin::Round, - ..Default::default() - } + pen(paint.into(), opacity, w, &line, &path) }); + let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue }; s.set_fill(fill); s.set_stroke(stroke); s.draw_path(&p); + pop_clips(s, n); } - PlacedItem::Bitmap { index, rect } => { + PlacedItem::Bitmap { index, rect, transform, region, clips } => { let Some(Some(img)) = v.images.get(index) else { continue }; - let Some(size) = Size::from_wh(rect.width() as f32, rect.height() as f32) else { continue }; - s.push_transform(&Transform::from_translate(rect.x0 as f32, rect.y0 as f32)); + let c = transform.as_coeffs(); + // Upright and not mirrored: the bitmap fills `rect`. + let upright = c[1] == 0.0 && c[2] == 0.0 && c[0] > 0.0 && c[3] > 0.0; + let (tf, size) = if upright { + (Transform::from_translate(rect.x0 as f32, rect.y0 as f32), Size::from_wh(rect.width() as f32, rect.height() as f32)) + } else { + // A turned, skewed or mirrored bitmap: `transform` maps the unit square onto its place. + let c = c.map(|v| v as f32); + (Transform::from_row(c[0], c[1], c[2], c[3], c[4], c[5]), Size::from_wh(1.0, 1.0)) + }; + let Some(size) = size else { continue }; + let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue }; + s.push_transform(&tf); s.draw_image(img.clone(), size); s.pop(); + pop_clips(s, n); } - PlacedItem::Text { index, tf } => { - if let Some(wordcraft_metafile::Item::Text(t)) = v.pic.items.get(index) { - ex.vector_text(s, t, tf); + PlacedItem::Pattern { index, path, even_odd, tile, region, clips } => { + let Some(p) = path_from(&path) else { continue }; + let Some(craft_metafile::Item::Pattern { tile: t, .. }) = v.pic.items.get(index) else { continue }; + let rule = if even_odd { FillRule::EvenOdd } else { FillRule::NonZero }; + let paint = match v.images.get(index) { + Some(Some(img)) => tile_pattern(s, img, t.width, t.height, tile).map(|p| (p.into(), norm(1.0))), + _ => None, + }; + let (paint, opacity) = paint.unwrap_or_else(|| { + let (c, o) = paint_of(v.averages.get(index).copied().unwrap_or([0; 4])); + (c.into(), o) + }); + let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue }; + s.set_fill(Some(Fill { paint, opacity, rule })); + s.set_stroke(None); + s.draw_path(&p); + pop_clips(s, n); + } + PlacedItem::Text { index, transform, clip, region, clips } => { + let Some(craft_metafile::Item::Text(t)) = v.pic.items.get(index) else { continue }; + let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue }; + let text_clip = clip.and_then(|c| path_from(&c.to_path(0.1))); + if let Some(c) = &text_clip { + s.push_clip_path(c, &FillRule::NonZero); } + ex.vector_text(s, t, transform); + if text_clip.is_some() { + s.pop(); + } + pop_clips(s, n); } } } @@ -92,6 +149,69 @@ pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r: } } +/// Pushes a metafile item's clip region and clip paths; pop them with [`pop_clips`] and the count +/// returned. None (nothing pushed) when a clip has no area to draw in. +fn push_clips(s: &mut Surface, region: Option<&kurbo::BezPath>, clips: &[Arc]) -> Option { + let mut paths = Vec::with_capacity(clips.len() + 1); + if let Some(region) = region { + paths.push((path_from(region)?, FillRule::NonZero)); + } + for c in clips { + paths.push((path_from(&c.path)?, if c.even_odd { FillRule::EvenOdd } else { FillRule::NonZero })); + } + for (p, rule) in &paths { + s.push_clip_path(p, rule); + } + Some(paths.len()) +} + +fn pop_clips(s: &mut Surface, n: usize) { + for _ in 0..n { + s.pop(); + } +} + +/// A metafile pen for `path`: `width` (points, at least [`HAIRLINE`]), the pen's caps, joins, +/// miter limit and dashes (`wordcraft_layout::metafile_dashes`, with the hairline as the pixel). +fn pen(paint: krilla::paint::Paint, opacity: NormalizedF32, width: f64, line: &craft_metafile::LineStyle, path: &kurbo::BezPath) -> Stroke { + let line_cap = match line.cap { + craft_metafile::Cap::Round => LineCap::Round, + craft_metafile::Cap::Square => LineCap::Square, + craft_metafile::Cap::Flat => LineCap::Butt, + }; + let line_join = match line.join { + craft_metafile::Join::Round => LineJoin::Round, + craft_metafile::Join::Bevel => LineJoin::Bevel, + craft_metafile::Join::Miter => LineJoin::Miter, + }; + let dash = if line.dash.is_empty() { None } else { wordcraft_layout::metafile_dashes(&line.dash, width == 0.0, HAIRLINE, path.perimeter(1.0)) }; + Stroke { + paint, + width: width.max(HAIRLINE) as f32, + miter_limit: wordcraft_layout::metafile_miter_limit(line.miter_limit), + line_cap, + line_join, + opacity, + dash: dash.map(|d| StrokeDash { array: d.iter().map(|v| *v as f32).collect(), offset: 0.0 }), + } +} + +/// A tiling pattern of `img` (`w` × `h` pixels); `tile` maps tile pixels to page space. None when +/// the mapping is not finite. +fn tile_pattern(s: &mut Surface, img: &Image, w: u32, h: u32, tile: kurbo::Affine) -> Option { + let c = tile.as_coeffs().map(|v| v as f32); + if !c.iter().all(|v| v.is_finite()) { + return None; + } + let size = Size::from_wh(w as f32, h as f32)?; + let mut sb = s.stream_builder(); + let mut ps = sb.surface(); + ps.draw_image(img.clone(), size); + ps.finish(); + let stream = sb.finish(); + Some(krilla::paint::Pattern { stream, transform: Transform::from_row(c[0], c[1], c[2], c[3], c[4], c[5]), width: w as f32, height: h as f32 }) +} + /// A kurbo path as a krilla path (None when empty). fn path_from(b: &kurbo::BezPath) -> Option { let mut pb = PathBuilder::new(); diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index d767b7b644..490eafb1b2 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -1306,6 +1306,117 @@ fn emf_rec(typ: u32, fields: &[i32]) -> Vec { v } +/// The PDF of a document holding one 70 pt metafile picture, uncompressed. +fn metafile_pdf(emf: Vec) -> String { + String::from_utf8_lossy(&metafile_pdf_bytes(emf)).into_owned() +} + +fn metafile_pdf_bytes(emf: Vec) -> Vec { + let mut d = Document::new(); + let media = d.add_media(emf, "emf"); + let mut p = Paragraph::with_text("Figure: ", CharProps::default()); + let n = p.len(); + p.insert_object( + n, + InlineObject::Image { + media, + w: 70.0, + h: 70.0, + alt: String::new(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }, + &CharProps::default(), + ) + .unwrap(); + d.body = vec![para_block(p)]; + export(&d, &PdfOptions { compress: false, tagged: false, ..Default::default() }).unwrap() +} + +/// #6636: an EMF+ only file whose EmfPlusDrawImage draws a 32bppPARGB bitmap: the bitmap is +/// embedded as an image. +#[test] +fn emf_plus_only_bitmap_is_embedded() { + let plus_rec = |typ: u16, flags: u16, data: &[u8]| { + let mut v = typ.to_le_bytes().to_vec(); + v.extend(flags.to_le_bytes()); + v.extend(((12 + data.len()) as u32).to_le_bytes()); + v.extend((data.len() as u32).to_le_bytes()); + v.extend(data); + v + }; + let le32 = |vals: &[i32]| -> Vec { vals.iter().flat_map(|v| v.to_le_bytes()).collect() }; + let header = plus_rec(0x4001, 0, &le32(&[0xDBC0_1002_u32 as i32, 1, 96, 96])); + let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, 2, 2, 8, 0x000E_200B, 0]); + image.extend([0u8, 0, 255, 255].repeat(4)); + let object = plus_rec(0x4008, 0x0500, &image); + let mut draw = le32(&[-1, 2]); + draw.extend([0.0f32, 0.0, 2.0, 2.0, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes())); + let draw = plus_rec(0x401A, 0, &draw); + let mut comment = 0x2B46_4D45u32.to_le_bytes().to_vec(); + comment.extend([header, object, draw, plus_rec(0x4002, 0, &[])].concat()); + let mut rec = 70u32.to_le_bytes().to_vec(); + rec.extend(((12 + comment.len()) as u32).to_le_bytes()); + rec.extend((comment.len() as u32).to_le_bytes()); + rec.extend(comment); + let bytes = metafile_pdf_bytes(emf_file(&[rec, emf_rec(14, &[0; 3])])); + let images = pdf_images(&bytes); + assert!(images.iter().any(|(w, h, ..)| (*w, *h) == (2, 2)), "the 2 × 2 bitmap is embedded"); + assert!(!String::from_utf8_lossy(&bytes).contains("0.8156"), "the gray placeholder box is not drawn"); +} + +/// A dotted cosmetic pen (CREATEPEN, PS_DOT, width 0) draws hairline dots: its dashes and gaps are +/// the hairline's width, not the file's device units scaled to the frame (0.7 pt here). +#[test] +fn metafile_cosmetic_dotted_pen_draws_hairline_dots() { + let recs = [emf_rec(38, &[1, 2, 0, 0, 0]), emf_rec(37, &[1]), emf_rec(27, &[0, 50]), emf_rec(54, &[100, 50]), emf_rec(14, &[0; 3])]; + let raw = metafile_pdf(emf_file(&recs)); + assert!(raw.contains("[0.25 0.25]0 d"), "the dots are hairline-sized"); +} + +/// A geometric PS_USERSTYLE pen whose dashes and gaps are far below the hairline draws its line +/// solid: no dash array is written. +#[test] +fn metafile_sub_pixel_dashes_draw_solid() { + let mut emf = emf_file(&[]); + // 10,000 device pixels over 250 mm: a device unit is 0.025 mm. The picture is 1000 units wide. + let le32 = |vals: &[i32]| -> Vec { vals.iter().flat_map(|v| v.to_le_bytes()).collect() }; + emf[8..24].copy_from_slice(&le32(&[0, 0, 1000, 1000])); + emf[72..80].copy_from_slice(&le32(&[10_000, 10_000])); + let pen = emf_rec(95, &[1, 0, 0, 0, 0, 0x0001_0207, 80, 0, 0, 0, 2, 1, 1]); + let recs = [pen, emf_rec(37, &[1]), emf_rec(27, &[0, 500]), emf_rec(54, &[1000, 500]), emf_rec(14, &[0; 3])]; + emf.extend(recs.concat()); + let raw = metafile_pdf(emf); + assert!(raw.contains(" w ") && !raw.contains("]0 d"), "a stroke with no dash array"); +} + +/// A clip region (INTERSECTCLIPRECT) adds a clip around the rectangle it clips. +#[test] +fn metafile_clip_region_is_a_clip() { + let clips = |raw: &str| raw.matches("\nW\nn").count() + raw.matches("\nW*\nn").count(); + let draw = |clip: bool| { + let mut recs = vec![emf_rec(39, &[1, 0, 0x0000_00FF, 0]), emf_rec(37, &[1])]; + if clip { + recs.push(emf_rec(30, &[0, 0, 50, 100])); + } + recs.extend([emf_rec(43, &[0, 0, 100, 100]), emf_rec(14, &[0; 3])]); + metafile_pdf(emf_file(&recs)) + }; + let (with, without) = (clips(&draw(true)), clips(&draw(false))); + assert!(without > 0 && with == without + 1, "one clip more with the region: {with} and {without}"); +} + +/// A hatched brush (CREATEBRUSHINDIRECT, BS_HATCHED) fills through a tiling pattern, not with a +/// solid color. +#[test] +fn metafile_hatch_brush_is_a_tiling_pattern() { + let recs = [emf_rec(39, &[1, 2, 0x0000_00FF, 1]), emf_rec(37, &[1]), emf_rec(43, &[0, 0, 100, 100]), emf_rec(14, &[0; 3])]; + let raw = metafile_pdf(emf_file(&recs)); + assert!(raw.contains("/PatternType 1"), "the hatch is a tiling pattern"); +} + #[test] fn metafile_strokes_use_round_caps_and_joins() { // A 4-unit black pen (handle 1) outlines a rectangle, so the stroke is drawn with round caps and joins. @@ -1426,6 +1537,17 @@ fn emf_text_records(text: &str) -> Vec> { vec![font, emf_rec(37, &[1]), emf_rec(24, &[0]), out] } +/// With the opaque background mode (the default) and a red background color (SETBKCOLOR), a text +/// run's character cells are filled red behind the text. +#[test] +fn metafile_text_fills_its_opaque_background() { + let mut recs = vec![emf_rec(25, &[0x0000_00FF])]; + recs.extend(emf_text_records("Hi")); + recs.push(emf_rec(14, &[0; 3])); + let raw = metafile_pdf(emf_file(&recs)); + assert!(raw.contains("1 0 0 rg"), "the character cells are filled red"); +} + /// #1764: the text of an EMF picture (EXTTEXTOUTW) is drawn, so it is in the PDF's text layer. #[test] fn metafile_text_records_are_drawn_as_text() { diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 99aa12093b..0224baed65 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -13,7 +13,7 @@ wordcraft-geom = { workspace = true, features = ["image"] } wordcraft-doc = { workspace = true } wordcraft-fonts = { workspace = true } wordcraft-layout = { workspace = true } -wordcraft-metafile = { workspace = true } +craft-metafile = { workspace = true } vello_cpu = { workspace = true } image = { workspace = true } log = { workspace = true } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 8e57e07713..f4befb2459 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4,6 +4,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex, Weak}; +use craft_metafile::{Item, Picture, PlacedItem, Seg}; use vello_cpu::kurbo::{self, Affine, BezPath, Shape}; use vello_cpu::peniko; use vello_cpu::{Pixmap, RenderContext, Resources}; @@ -14,7 +15,6 @@ use wordcraft_fonts::FontDb; use wordcraft_layout::Page; use wordcraft_layout::display::Paint; use wordcraft_layout::display::{DisplayOptions, Draw, Stroke, page_layers}; -use wordcraft_metafile::{Item, Picture, PlacedItem, Seg}; mod media; @@ -858,7 +858,7 @@ fn draw_image(ctx: &mut RenderContext, fr: &Frame, it: &Draw) { return; }; let (pw, ph) = (pm.width().max(1) as f64, pm.height().max(1) as f64); - let [cl, ct, vis_w, vis_h] = wordcraft_metafile::crop_window(*crop); + let [cl, ct, vis_w, vis_h] = wordcraft_layout::crop_window(*crop); let sx = r.width() / (pw * vis_w); let sy = r.height() / (ph * vis_h); ctx.set_transform(view); diff --git a/crates/render/src/media.rs b/crates/render/src/media.rs index 2dbf1faf88..73c484e0ae 100644 --- a/crates/render/src/media.rs +++ b/crates/render/src/media.rs @@ -126,11 +126,11 @@ pub fn image_size(bytes: &[u8]) -> Option<(u32, u32)> { /// extension it is stored under (`"wmf"` or `"emf"`), or None for anything else (#802). Very large /// frames are scaled down to 22 inches on the longer side, keeping the shape. pub fn metafile_size(bytes: &[u8]) -> Option<(f32, f32, &'static str)> { - if !wordcraft_metafile::is_metafile(bytes) { + if !craft_metafile::is_metafile(bytes) { return None; } // The frame comes from the header where the file has one, so no bitmap is decoded for it. - let (w, h) = wordcraft_metafile::size(bytes).ok()?; + let (w, h) = craft_metafile::size(bytes).ok()?; if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { return None; } @@ -140,28 +140,50 @@ pub fn metafile_size(bytes: &[u8]) -> Option<(f32, f32, &'static str)> { Some((w * k, h * k, ext)) } -/// A metafile (WMF/EMF) picture, parsed once. The geometry comes placed by the metafile crate; the -/// bitmaps are pixmaps, one per picture item (None for paths and undecodable bitmaps). +/// A metafile (WMF/EMF/EMF+) picture, parsed once. The geometry comes placed by the metafile crate; +/// the bitmaps and pattern tiles are pixmaps, one per picture item (None for paths, text and +/// undecodable bitmaps). Fills that share a tile share its pixmap. `averages` holds each pattern +/// fill's tile average color (transparent for other items), computed once a tile. pub(crate) struct Vector { pic: Picture, pixmaps: Vec>>, + averages: Vec<[u8; 4]>, } impl Vector { - /// Approximate memory held: pixels and path segments. - fn bytes(&self) -> usize { - let px: usize = self.pixmaps.iter().flatten().map(|p| p.width() as usize * p.height() as usize * 4).sum(); - let segs: usize = self - .pic - .items - .iter() - .map(|it| match it { - Item::Path { segs, .. } => segs.len() * std::mem::size_of::(), - Item::Bitmap { .. } => 0, - Item::Text(t) => t.text.len() + t.dx.len() * 4, - }) - .sum(); - px + segs + /// Approximate memory held: pixmaps, the pattern tiles' own pixels, path segments, dash + /// patterns, clip regions, clip lists, clip paths and text, each shared allocation once. + pub(crate) fn bytes(&self) -> usize { + let mut seen = std::collections::HashSet::new(); + let mut total = self.averages.len() * 4; + for p in self.pixmaps.iter().flatten() { + if seen.insert(Arc::as_ptr(p) as usize) { + total = total.saturating_add(p.width() as usize * p.height() as usize * 4); + } + } + let seg = std::mem::size_of::(); + for it in &self.pic.items { + let (own, region, clips) = match it { + Item::Path { segs, line, region, clips, .. } => ((segs.len() * seg).saturating_add(line.dash.len() * 4), region, clips), + Item::Pattern { segs, tile, region, clips, .. } => { + let tile_bytes = if seen.insert(Arc::as_ptr(tile) as usize) { tile.rgba.len() } else { 0 }; + ((segs.len() * seg).saturating_add(tile_bytes), region, clips) + } + Item::Bitmap { region, clips, .. } => (0, region, clips), + Item::Text(t) => (t.text.len() + t.dx.len() * 4, &t.region, &t.clips), + }; + // Each item holds its own copy of the clip region's rectangles and its own list of the + // clip paths it shares. + let region = region.as_ref().map_or(0, |r| r.len() * std::mem::size_of::<[f32; 4]>()); + let list = clips.len() * std::mem::size_of::>(); + total = total.saturating_add(own).saturating_add(region).saturating_add(list); + for c in clips { + if seen.insert(Arc::as_ptr(c) as usize) { + total = total.saturating_add(c.segs.len() * seg); + } + } + } + total } } @@ -169,7 +191,7 @@ impl Vector { /// the caller falls back to the raster path (and the grey box). pub(crate) fn vector_for(doc: &Document, key: &str) -> Option> { let bytes = doc.media.get(key)?; - if !wordcraft_metafile::is_metafile(bytes) { + if !craft_metafile::is_metafile(bytes) { return None; } if let Some(v) = lock(vectors()).get(key, bytes) { @@ -184,25 +206,45 @@ pub(crate) fn vector_for(doc: &Document, key: &str) -> Option> { v } -/// Parses a metafile and decodes its bitmaps. None when the picture has no usable size. -fn build_vector(bytes: &[u8]) -> Option { - let mut pic = wordcraft_metafile::parse(bytes).ok()?; +/// Parses a metafile and decodes its bitmaps and pattern tiles. None when the picture has no +/// usable size. +pub(crate) fn build_vector(bytes: &[u8]) -> Option { + let mut pic = craft_metafile::parse(bytes).ok()?; if !pic.has_size() { return None; } - // The pixels move into the pixmaps; the picture keeps only the geometry. - let pixmaps = pic.items.iter_mut().map(|it| it.take_pixels().and_then(|(w, h, px)| premul_pixmap(w, h, &px)).map(Arc::new)).collect(); - Some(Vector { pic, pixmaps }) + // The pixels move into the pixmaps; the picture keeps only the geometry. A tile shared by + // several fills is converted and averaged once. + let mut tiles: HashMap>, [u8; 4])> = HashMap::new(); + let (pixmaps, averages) = pic + .items + .iter_mut() + .map(|it| match it { + Item::Pattern { tile, .. } => tiles + .entry(Arc::as_ptr(tile) as usize) + .or_insert_with(|| { + (premul_pixmap(tile.width, tile.height, &tile.rgba).map(Arc::new), wordcraft_layout::metafile_average_color(&tile.rgba)) + }) + .clone(), + _ => (it.take_pixels().and_then(|(w, h, px)| premul_pixmap(w, h, &px)).map(Arc::new), [0; 4]), + }) + .unzip(); + Some(Vector { pic, pixmaps, averages }) } fn rgba_color(c: [u8; 4]) -> peniko::Color { peniko::Color::from_rgba8(c[0], c[1], c[2], c[3]) } +/// Pattern tiles smaller than this (device pixels on both sides) are drawn as the tile's average +/// color: a sub-pixel pattern would only alias. +const MIN_TILE_PX: f64 = 1.5; + /// Draws a metafile picture into `r` (page points): fills and strokes in page space (so strokes keep -/// their width under non-uniform scaling), bitmaps stretched, all clipped to `r` and faded by `alpha`. -/// Strokes have round caps and joins, as GDI draws them, and are at least one device pixel wide, so -/// cosmetic (width 0) pens show as hairlines at any zoom. +/// their width under non-uniform scaling), bitmaps stretched (or turned by their transform), +/// pattern fills tiled, each item inside its clip region and clip paths, all clipped to `r` and +/// faded by `alpha`. Strokes take the pen's caps, joins and dashes and are at least one device +/// pixel wide, so cosmetic (width 0) pens show as hairlines at any zoom. pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect, crop: &[f32; 4], alpha: f32, view: Affine) { ctx.set_transform(view); let alpha = if alpha.is_finite() { alpha.clamp(0.0, 1.0) } else { 1.0 }; @@ -212,9 +254,9 @@ pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect, } ctx.push_clip_layer(&r.to_path(0.1)); let pixel = device_pixel(view); - for it in v.pic.place(*r, *crop) { + for it in v.pic.place(*r, wordcraft_layout::crop_sides(*crop)) { match it { - PlacedItem::Path { path, fill, stroke, even_odd } => { + PlacedItem::Path { path, fill, stroke, line, even_odd, region, clips } => clipped(ctx, region.as_deref(), &clips, |ctx| { if let Some(f) = fill { ctx.set_paint(rgba_color(f)); ctx.set_fill_rule(if even_odd { peniko::Fill::EvenOdd } else { peniko::Fill::NonZero }); @@ -222,25 +264,71 @@ pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect, } if let Some((s, w)) = stroke { ctx.set_paint(rgba_color(s)); - ctx.set_stroke(kurbo::Stroke::new(w.max(pixel)).with_caps(kurbo::Cap::Round).with_join(kurbo::Join::Round)); + ctx.set_stroke(pen(w, pixel, &line, &path)); ctx.stroke_path(&path); } - } - PlacedItem::Bitmap { index, rect } => { - let Some(Some(pm)) = v.pixmaps.get(index) else { continue }; + }), + PlacedItem::Bitmap { index, rect, transform, region, clips } => clipped(ctx, region.as_deref(), &clips, |ctx| { + let Some(Some(pm)) = v.pixmaps.get(index) else { return }; let (pw, ph) = (pm.width().max(1) as f64, pm.height().max(1) as f64); ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm.clone()), sampler: peniko::ImageSampler::default().with_quality(peniko::ImageQuality::Medium), }); - ctx.set_paint_transform(Affine::translate((rect.x0, rect.y0)) * Affine::scale_non_uniform(rect.width() / pw, rect.height() / ph)); - ctx.fill_rect(&rect); - ctx.reset_paint_transform(); - } - PlacedItem::Text { index, tf } => { - if let Some(Item::Text(t)) = v.pic.items.get(index) { - draw_vector_text(ctx, t, view * tf); + let c = transform.as_coeffs(); + // Upright and not mirrored: the bitmap fills `rect`. + if c[1] == 0.0 && c[2] == 0.0 && c[0] > 0.0 && c[3] > 0.0 { + ctx.set_paint_transform(Affine::translate((rect.x0, rect.y0)) * Affine::scale_non_uniform(rect.width() / pw, rect.height() / ph)); + ctx.fill_rect(&rect); + } else { + // A turned, skewed or mirrored bitmap: `transform` maps the unit square onto its place. + ctx.set_paint_transform(transform * Affine::scale_non_uniform(1.0 / pw, 1.0 / ph)); + ctx.fill_path(&(transform * kurbo::Rect::new(0.0, 0.0, 1.0, 1.0).to_path(0.1))); } + ctx.reset_paint_transform(); + }), + PlacedItem::Pattern { index, path, even_odd, tile, region, clips } => clipped(ctx, region.as_deref(), &clips, |ctx| { + let Some(Item::Pattern { tile: t, .. }) = v.pic.items.get(index) else { return }; + ctx.set_fill_rule(if even_odd { peniko::Fill::EvenOdd } else { peniko::Fill::NonZero }); + // `tile` maps one tile pixel to page points: the tile's sides are its columns and + // its rows under that, in device pixels. The tile is drawn when either side is at + // least `MIN_TILE_PX`. + let c = (view * tile).as_coeffs(); + let across = c[0].hypot(c[1]) * f64::from(t.width); + let down = c[2].hypot(c[3]) * f64::from(t.height); + match v.pixmaps.get(index) { + Some(Some(pm)) if across.max(down) >= MIN_TILE_PX => { + ctx.set_paint(vello_cpu::Image { + image: vello_cpu::ImageSource::Pixmap(pm.clone()), + sampler: peniko::ImageSampler { + x_extend: peniko::Extend::Repeat, + y_extend: peniko::Extend::Repeat, + quality: peniko::ImageQuality::Low, + alpha: 1.0, + }, + }); + ctx.set_paint_transform(tile); + ctx.fill_path(&path); + ctx.reset_paint_transform(); + } + _ => { + ctx.set_paint(rgba_color(v.averages.get(index).copied().unwrap_or([0; 4]))); + ctx.fill_path(&path); + } + } + }), + PlacedItem::Text { index, transform, clip, region, clips } => { + clipped(ctx, region.as_deref(), &clips, |ctx| { + let Some(Item::Text(t)) = v.pic.items.get(index) else { return }; + if let Some(c) = clip { + ctx.push_clip_layer(&c.to_path(0.1)); + } + draw_vector_text(ctx, t, view * transform); + ctx.set_transform(view); + if clip.is_some() { + ctx.pop_layer(); + } + }); ctx.set_transform(view); } } @@ -252,15 +340,76 @@ pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect, } } -/// Draws a metafile text run: `tf` maps the run's own space (see [`PlacedItem::Text`]) to the device. -fn draw_vector_text(ctx: &mut RenderContext, t: &wordcraft_metafile::Text, tf: Affine) { +/// Draws `draw` inside a metafile item's clip region and every one of its clip paths (page +/// points, under the current transform). No region is the default clip. +fn clipped( + ctx: &mut RenderContext, + region: Option<&kurbo::BezPath>, + clips: &[Arc], + draw: impl FnOnce(&mut RenderContext), +) { + if let Some(region) = region { + ctx.set_fill_rule(peniko::Fill::NonZero); + ctx.push_clip_layer(region); + } + for c in clips { + ctx.set_fill_rule(if c.even_odd { peniko::Fill::EvenOdd } else { peniko::Fill::NonZero }); + ctx.push_clip_layer(&c.path); + } + ctx.set_fill_rule(peniko::Fill::NonZero); + draw(ctx); + for _ in 0..clips.len() + usize::from(region.is_some()) { + ctx.pop_layer(); + } +} + +/// A metafile pen for `path` as a stroke `width` wide (page points, at least one device `pixel`): +/// its caps, joins, miter limit and dashes (`wordcraft_layout::metafile_dashes`). +fn pen(width: f64, pixel: f64, line: &craft_metafile::LineStyle, path: &kurbo::BezPath) -> kurbo::Stroke { + let cap = match line.cap { + craft_metafile::Cap::Round => kurbo::Cap::Round, + craft_metafile::Cap::Square => kurbo::Cap::Square, + craft_metafile::Cap::Flat => kurbo::Cap::Butt, + }; + let join = match line.join { + craft_metafile::Join::Round => kurbo::Join::Round, + craft_metafile::Join::Bevel => kurbo::Join::Bevel, + craft_metafile::Join::Miter => kurbo::Join::Miter, + }; + let stroke = kurbo::Stroke::new(width.max(pixel)) + .with_caps(cap) + .with_join(join) + .with_miter_limit(f64::from(wordcraft_layout::metafile_miter_limit(line.miter_limit))); + if line.dash.is_empty() { + return stroke; + } + match wordcraft_layout::metafile_dashes(&line.dash, width == 0.0, pixel, path.perimeter(1.0)) { + Some(dash) => stroke.with_dashes(0.0, dash), + None => stroke, + } +} + +/// Draws a metafile text run: `tf` maps its text space (`craft_metafile::Text::transform`) to the +/// device. +fn draw_vector_text(ctx: &mut RenderContext, t: &craft_metafile::Text, tf: Affine) { let (face, shaped) = wordcraft_layout::metafile_text_run(t); let glyphs: Vec<_> = shaped.iter().map(|g| (g.cluster, f64::from(g.x_advance), f64::from(g.x_offset), f64::from(g.y_offset))).collect(); - let Some(lay) = t.layout(face.upem, face.ascent, face.descent, &glyphs) else { return }; + let Some(lay) = wordcraft_layout::metafile_text_layout(t, face.upem, face.ascent, face.descent, &glyphs) else { return }; let k = lay.em / face.upem.max(1.0); + let canvas = kurbo::Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height())); + // An opaque background mode fills the character cells first. + if let Some(bg) = t.background { + let [x0, y0, x1, y1] = lay.cell; + let cell = tf * kurbo::Rect::new(x0, y0, x1, y1).to_path(0.1); + let b = cell.bounding_box(); + if x1 > x0 && [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_GLYPH_PIXELS * 16.0) && b.overlaps(canvas) { + ctx.set_transform(Affine::IDENTITY); + ctx.set_paint(rgba_color(bg)); + ctx.fill_path(&cell); + } + } ctx.set_paint(rgba_color(t.color)); let db = FontDb::global(); - let canvas = kurbo::Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height())); let mut oversized = 0usize; for (g, (x, y)) in shaped.iter().zip(&lay.glyphs) { let o = db.outline(&face, g.gid); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index c18f75790d..9e11f56461 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1037,6 +1037,237 @@ fn metafile_picture_is_drawn_as_vectors() { assert!(left[..3].iter().all(|c| *c > 200), "left half should be paper, not the grey box: {left:?}"); } +/// #6636: an EMF+ only file (no plain EMF drawing records) whose EmfPlusDrawImage draws a +/// 32bppPARGB bitmap over the right half: the bitmap's pixels are drawn. +#[test] +fn emf_plus_only_bitmap_is_drawn() { + // EmfPlusObject 0, an image (type 5): a 2 × 1 bitmap in PixelFormat32bppPARGB, opaque red + // and then red at half opacity (premultiplied BGRA 0, 0, 128, 128). + let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, 2, 1, 8, 0x000E_200B, 0]); + image.extend([0u8, 0, 255, 255, 0, 0, 128, 128]); + let object = plus_rec(0x4008, 0x0500, &image); + // EmfPlusDrawImage of image 0: the whole bitmap (pixel units) into x 50..100, y 0..100. + let mut draw = le32(&[-1, 2]); + draw.extend([0.0f32, 0.0, 2.0, 1.0, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes())); + let emf = emf_plus_file(&[object, plus_rec(0x401A, 0, &draw)]); + + let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0); + let at = |fx: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * 0.5) as u32); + let (opaque, half, left) = (at(0.6), at(0.9), at(0.25)); + assert!(is_red(opaque), "the bitmap's opaque red is drawn on the right half: {opaque:?}"); + // Premultiplied half-opacity red over white paper is (255, 127, 127); read as straight + // color it would be about (191, 127, 127). + assert!(half[0] > 235 && (110..145).contains(&half[1]) && (110..145).contains(&half[2]), "half-opacity red: {half:?}"); + assert!(is_paper(left), "left half should be paper: {left:?}"); +} + +/// An EMF+ record for [`emf_plus_file`]: type, flags and data. +fn plus_rec(typ: u16, flags: u16, data: &[u8]) -> Vec { + let mut v = typ.to_le_bytes().to_vec(); + v.extend(flags.to_le_bytes()); + v.extend(((12 + data.len()) as u32).to_le_bytes()); + v.extend((data.len() as u32).to_le_bytes()); + v.extend(data); + v +} + +/// An EMF+ only file with the frame of [`red_right_half_emf`]: an EmfPlusHeader (96 dpi), then +/// `records`, then EmfPlusEndOfFile, in one comment record. +fn emf_plus_file(records: &[Vec]) -> Vec { + let mut comment = 0x2B46_4D45u32.to_le_bytes().to_vec(); + comment.extend(plus_rec(0x4001, 0, &le32(&[0xDBC0_1002_u32 as i32, 1, 96, 96]))); + comment.extend(records.concat()); + comment.extend(plus_rec(0x4002, 0, &[])); + let mut payload = (comment.len() as u32).to_le_bytes().to_vec(); + payload.extend(comment); + let mut emf = red_right_half_emf()[..88].to_vec(); + emf.extend([emf_rec(70, &payload), emf_rec(14, &[0; 12])].concat()); + emf +} + +/// Renders a document holding one 70 pt metafile picture with `crop` at `scale`: the page and the +/// picture's frame (points). +fn emf_on_page(emf: Vec, crop: [f32; 4], scale: f32) -> (Rendered, wordcraft_geom::Rect) { + emf_on_page_sized(emf, (70.0, 70.0), crop, scale) +} + +/// [`emf_on_page`] with the picture `size` (points). +fn emf_on_page_sized(emf: Vec, size: (f32, f32), crop: [f32; 4], scale: f32) -> (Rendered, wordcraft_geom::Rect) { + let mut d = Document::new(); + let media = d.add_media(emf, "emf"); + let mut p = wordcraft_doc::Paragraph::new(); + let obj = wordcraft_doc::para::InlineObject::Image { + media, + w: size.0, + h: size.1, + alt: String::new(), + float: Default::default(), + crop, + fx: Default::default(), + ole: None, + }; + p.insert_object(0, obj, &Default::default()).unwrap(); + d.body = vec![wordcraft_doc::para_block(p)]; + let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default()); + let opts = RenderOptions::default(); + let rect = page_display(&d, &l.pages[0], &opts.display) + .iter() + .find_map(|i| match i { + Draw::Image { rect, .. } => Some(*rect), + _ => None, + }) + .expect("a picture on the page"); + (render_page(&d, &l.pages[0], scale, &opts), rect) +} + +/// Whether a pixel is close to pure red. +fn is_red(p: [u8; 4]) -> bool { + p[0] > 200 && p[1] < 60 && p[2] < 60 +} + +/// Whether a pixel is paper. +fn is_paper(p: [u8; 4]) -> bool { + p[..3].iter().all(|c| *c > 200) +} + +/// A clip region (INTERSECTCLIPRECT to the left half) keeps a red rectangle over the whole +/// picture to that half; once RESTOREDC drops it, a second rectangle across the bottom shows on +/// both halves. +#[test] +fn metafile_clip_region_clips_and_ends() { + let mut emf = red_right_half_emf()[..88].to_vec(); + let brush = emf_rec(39, &le32(&[1, 0, 0x0000_00FF, 0])); + let recs = [ + brush, + emf_rec(37, &le32(&[1])), + emf_rec(33, &[]), + emf_rec(30, &le32(&[0, 0, 50, 100])), + emf_rec(43, &le32(&[0, 0, 100, 60])), + emf_rec(34, &le32(&[-1])), + emf_rec(43, &le32(&[0, 80, 100, 100])), + emf_rec(14, &[0; 12]), + ]; + emf.extend(recs.concat()); + let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0); + let at = |fx: f32, fy: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * fy) as u32); + assert!(is_red(at(0.25, 0.3)), "inside the clip: {:?}", at(0.25, 0.3)); + assert!(is_paper(at(0.75, 0.3)), "outside the clip: {:?}", at(0.75, 0.3)); + assert!(is_red(at(0.75, 0.9)), "after the clip is restored away: {:?}", at(0.75, 0.9)); +} + +/// The vector cache counts each item's copy of the clip region: 100 rectangles drawn inside a +/// clip region hold 100 copies of its rectangle more than without it. +#[test] +fn metafile_cache_counts_clip_regions() { + let bytes = |clip: bool| { + let mut emf = red_right_half_emf()[..88].to_vec(); + if clip { + emf.extend(emf_rec(30, &le32(&[0, 0, 50, 100]))); + } + for i in 0..100 { + emf.extend(emf_rec(43, &le32(&[i % 50, 0, i % 50 + 10, 10]))); + } + emf.extend(emf_rec(14, &[0; 12])); + media::build_vector(&emf).map(|v| v.bytes()) + }; + let (with, without) = (bytes(true).expect("a picture"), bytes(false).expect("a picture")); + assert!(with >= without + 100 * 16, "{with} and {without}"); +} + +/// A hatch tile squeezed to well under a pixel tall but several pixels wide (the picture is 70 pt +/// wide and 2 pt tall) keeps its vertical lines: the row crosses red lines and the background +/// between them, not one blended color. +#[test] +fn metafile_narrow_hatch_tile_keeps_its_lines() { + let mut emf = red_right_half_emf()[..88].to_vec(); + let brush = emf_rec(39, &le32(&[1, 2, 0x0000_00FF, 1])); + // The stock NULL_PEN leaves the rectangle without an outline. + let no_pen = emf_rec(37, &le32(&[0x8000_0008_u32 as i32])); + emf.extend([brush, emf_rec(37, &le32(&[1])), no_pen, emf_rec(43, &le32(&[0, 0, 100, 100])), emf_rec(14, &[0; 12])].concat()); + let (img, rect) = emf_on_page_sized(emf, (70.0, 2.0), [0.0; 4], 1.0); + let y = (rect.y + rect.h / 2.0) as u32; + let row: Vec = ((rect.x + 2.0) as u32..(rect.x + rect.w - 2.0) as u32).map(|x| img.pixel(x, y)[1]).collect(); + assert!(row.iter().any(|g| *g < 160) && row.iter().any(|g| *g > 240), "red lines and background: {row:?}"); +} + +/// A clip path (a rectangle path over the left half, SELECTCLIPPATH with RGN_COPY) keeps a red +/// rectangle over the whole picture to that half. +#[test] +fn metafile_clip_path_clips() { + let mut emf = red_right_half_emf()[..88].to_vec(); + let brush = emf_rec(39, &le32(&[1, 0, 0x0000_00FF, 0])); + let recs = [ + brush, + emf_rec(37, &le32(&[1])), + emf_rec(59, &[]), + emf_rec(43, &le32(&[0, 0, 50, 100])), + emf_rec(60, &[]), + emf_rec(67, &le32(&[5])), + emf_rec(43, &le32(&[0, 0, 100, 100])), + emf_rec(14, &[0; 12]), + ]; + emf.extend(recs.concat()); + let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0); + let at = |fx: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * 0.5) as u32); + assert!(is_red(at(0.25)), "inside the clip path: {:?}", at(0.25)); + assert!(is_paper(at(0.75)), "outside the clip path: {:?}", at(0.75)); +} + +/// A bitmap under a world transform that turns it a quarter turn clockwise about the picture's +/// center (EmfPlusSetWorldTransform): its left pixel (red) is drawn at the top and its right pixel +/// (blue) at the bottom. +#[test] +fn emf_plus_turned_bitmap_is_drawn_turned() { + let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, 2, 1, 8, 0x000E_200B, 0]); + // BGRA: red, then blue. + image.extend([0u8, 0, 255, 255, 255, 0, 0, 255]); + let turn = plus_rec(0x402A, 0, &[0.0f32, 1.0, -1.0, 0.0, 100.0, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let mut draw = le32(&[-1, 2]); + draw.extend([0.0f32, 0.0, 2.0, 1.0, 25.0, 25.0, 50.0, 50.0].iter().flat_map(|v| v.to_le_bytes())); + let emf = emf_plus_file(&[plus_rec(0x4008, 0x0500, &image), turn, plus_rec(0x401A, 0, &draw)]); + let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0); + let at = |fx: f32, fy: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * fy) as u32); + let (top_right, bottom_left) = (at(0.65, 0.37), at(0.35, 0.62)); + assert!(is_red(top_right), "red at the top: {top_right:?}"); + assert!(bottom_left[2] > 200 && bottom_left[0] < 60, "blue at the bottom: {bottom_left:?}"); +} + +/// A geometric PS_USERSTYLE pen whose dashes and gaps are far below a pixel draws its line solid +/// instead of splitting it into dashes too small to see. +#[test] +fn metafile_sub_pixel_dashes_draw_solid() { + let mut emf = red_right_half_emf()[..88].to_vec(); + // 10,000 device pixels over 250 mm: a device unit is 0.025 mm. The picture is 1000 units wide. + emf[8..24].copy_from_slice(&le32(&[0, 0, 1000, 1000])); + emf[72..80].copy_from_slice(&le32(&[10_000, 10_000])); + // EXTCREATEPEN 1: PS_GEOMETRIC | PS_ENDCAP_FLAT | PS_USERSTYLE, 80 units wide, black, two + // entries of 1 unit. + let pen = emf_rec(95, &le32(&[1, 0, 0, 0, 0, 0x0001_0207, 80, 0, 0, 0, 2, 1, 1])); + let recs = [pen, emf_rec(37, &le32(&[1])), emf_rec(27, &le32(&[0, 500])), emf_rec(54, &le32(&[1000, 500])), emf_rec(14, &[0; 12])]; + emf.extend(recs.concat()); + let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0); + let y = (rect.y + rect.h * 0.5) as u32; + let (x0, x1) = ((rect.x + 5.0) as u32, (rect.x + rect.w - 5.0) as u32); + let dark = (x0..x1).filter(|&x| img.pixel(x, y)[..3].iter().all(|c| *c < 60)).count(); + assert_eq!(dark, (x1 - x0) as usize, "the line is solid black"); +} + +/// A hatched brush (CREATEBRUSHINDIRECT, BS_HATCHED, HS_VERTICAL) fills with its red lines over +/// the background, not with a solid red. +#[test] +fn metafile_hatch_brush_draws_its_lines() { + let mut emf = red_right_half_emf()[..88].to_vec(); + let brush = emf_rec(39, &le32(&[1, 2, 0x0000_00FF, 1])); + emf.extend([brush, emf_rec(37, &le32(&[1])), emf_rec(43, &le32(&[0, 0, 100, 100])), emf_rec(14, &[0; 12])].concat()); + let scale = 4.0; + let (img, rect) = emf_on_page(emf, [0.0; 4], scale); + let y = ((rect.y + rect.h / 2.0) * scale) as u32; + let (x0, x1) = (((rect.x + 2.0) * scale) as u32, ((rect.x + rect.w - 2.0) * scale) as u32); + let red = (x0..x1).filter(|&x| img.pixel(x, y)[1] < 128).count(); + let n = (x1 - x0) as usize; + assert!(red > 0 && red < n * 3 / 4, "the row crosses red lines and the background between them: {red} of {n} red"); +} + /// #1899: a crop that keeps a sliver of the picture (3% here; a header's bar can be 2.7% of a /// page-sized metafile) stretches that sliver over the frame, as the file says, for vector and /// bitmap pictures alike. Both pictures are paper on the left half and red on the right. @@ -1082,6 +1313,45 @@ fn a_crop_keeping_a_sliver_fills_the_frame_with_it() { } } +/// A negative crop side draws as no crop on that side, for vector and bitmap pictures alike: a +/// left side of -0.5 does not pad the source, so the frame at 55% shows the source at 55% (red). +#[test] +fn a_negative_crop_side_draws_uncropped() { + let mut png = Vec::new(); + image::RgbaImage::from_fn(100, 100, |x, _| image::Rgba(if x >= 50 { [255, 0, 0, 255] } else { [255; 4] })) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + for (bytes, ext) in [(red_right_half_emf(), "emf"), (png, "png")] { + let mut d = Document::new(); + let media = d.add_media(bytes, ext); + let mut p = wordcraft_doc::Paragraph::new(); + let obj = wordcraft_doc::para::InlineObject::Image { + media, + w: 70.0, + h: 70.0, + alt: String::new(), + float: Default::default(), + crop: [-0.5, 0.0, 0.0, 0.0], + fx: Default::default(), + ole: None, + }; + p.insert_object(0, obj, &Default::default()).unwrap(); + d.body = vec![wordcraft_doc::para_block(p)]; + let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default()); + let opts = RenderOptions::default(); + let rect = page_display(&d, &l.pages[0], &opts.display) + .iter() + .find_map(|i| match i { + Draw::Image { rect, .. } => Some(*rect), + _ => None, + }) + .expect("a picture on the page"); + let img = render_page(&d, &l.pages[0], 1.0, &opts); + let px = img.pixel((rect.x + rect.w * 0.55) as u32, (rect.y + rect.h * 0.5) as u32); + assert!(is_red(px), "{ext}: {px:?}"); + } +} + #[test] fn cosmetic_metafile_pen_is_one_device_pixel_wide() { // MOVETO (0, 50), LINETO (100, 50) with the default cosmetic black pen: a hairline across the middle. @@ -1166,6 +1436,29 @@ fn metafile_text_records_are_painted() { assert!(dark > 50, "the text is painted inside the picture: {dark} dark pixels"); } +/// With the opaque background mode (the default) and a red background color (SETBKCOLOR), a text +/// run's character cells are filled red behind the black text. +#[test] +fn metafile_text_fills_its_opaque_background() { + let mut font = emf_rec(82, &le32(&[1, -20, 0, 0, 0, 400, 0, 0])); + let mut name: Vec = "Arial".encode_utf16().flat_map(|u| u.to_le_bytes()).collect(); + name.resize(64, 0); + font.extend(name); + font[4..8].copy_from_slice(&104u32.to_le_bytes()); + let mut text = emf_rec(84, &le32(&[0, 0, 100, 100, 1, 0, 0, 5, 40, 4, 76, 0, 0, 0, 0, 0, 0])); + text.extend("WWWW".encode_utf16().flat_map(|u| u.to_le_bytes())); + text[4..8].copy_from_slice(&84u32.to_le_bytes()); + let mut emf = red_right_half_emf()[..88].to_vec(); + let bk = emf_rec(25, &le32(&[0x0000_00FF])); + emf.extend([bk, font, emf_rec(37, &le32(&[1])), emf_rec(24, &le32(&[0])), text, emf_rec(14, &[0; 12])].concat()); + let scale = 2.0; + let (img, rect) = emf_on_page(emf, [0.0; 4], scale); + let (x0, y0) = ((rect.x * scale) as u32, (rect.y * scale) as u32); + let (x1, y1) = (((rect.x + rect.w) * scale) as u32, ((rect.y + rect.h) * scale) as u32); + let red = (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).filter(|&(x, y)| is_red(img.pixel(x, y))).count(); + assert!(red > 50, "the character cells are filled red: {red} red pixels"); +} + /// An EMF text run whose anchor sits inside the picture but whose font is billions of units /// tall: each glyph's curves would span billions of device pixels, which the rasteriser /// subdivides for ever. Glyphs that big (or off the raster) are left out; the page renders. diff --git a/docs/architecture.md b/docs/architecture.md index e22d36a891..20362b09a2 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -21,7 +21,7 @@ crate name links to its source tree. | L0 | [`geom`](../crates/geom/src) | 1,271 | Units (points, twips, EMU, inches, cm), rectangles and measurement parsing | | L1 | [`doc`](../crates/doc/src) | 23,719 | Document model: stories, paragraphs, runs, tables, sections, styles, numbering, fields, notes, comments, revisions and equations; edit primitives and bidi | | L1 | [`fonts`](../crates/fonts/src) | 7,088 | Font database, metrics, outlines, HarfRust shaping, Word font substitution and OpenType MATH | -| L1 | [`metafile`](../crates/metafile/src) | 3,614 | Shared Windows Metafile parsing and drawing primitives used by format readers and renderers | +| L1 (external) | [`craft-metafile`](https://github.com/storytold/craft-libs/tree/main/crates/metafile) | — | WMF, EMF and EMF+ reader shared with the other Craft apps: paths, pattern fills, bitmaps and text with their clips, placed into a picture frame for the renderers | | L1 (external) | [`craft-proof`](https://github.com/storytold/craft-libs/tree/main/crates/proof) (package alias `wordcraft-proof`) | — | Proofing moved to craft-libs (CP1, 2026-11): fifteen spelling dictionaries: English (US, GB, CA), Polish, Portuguese, Italian, Croatian, Turkish, Russian, Czech, Indonesian and Spanish (Spain, Mexico, Latin America, Uruguay); language modules provide spelling, suggestions and grammar, while Bulgarian and German have hyphenation only. Its word lists and patterns are craft-i18n's `language-data/`, embedded from `CRAFT_I18N_DIR` at the commit in `craft-i18n.rev` (CI and releases set `CRAFT_I18N_REQUIRED=1`); without them English spelling falls back to an installed Hunspell English or craft-proof's built-in Moby list, and pattern hyphenation is off (Bulgarian, Turkish and Russian hyphenate by rule) | | L2 | [`docbin`](../crates/docbin/src) | 8,815 | Word 97–2003 `.doc` reader (FIB, piece table, FKPs, SPRMs, stylesheet, lists, tables, notes, pictures) over a CFB container | | L2 | [`docx`](../crates/docx/src) | 37,376 | OOXML WordprocessingML reader/writer (Transitional and Strict), OMML, custom properties and preserved VBA parts | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 818f30e3d2..cd66695b33 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -93,7 +93,7 @@ Weights are the share of a Word user's file traffic (estimate). Read/write: ✅ | Encrypted/password-protected `.doc` (XOR/RC4) | <1% | R | 🟡 | — | ~60% | 1–2 | `crates/docbin/src/tests/encrypted.rs` | XOR obfuscation, RC4 and RC4 CryptoAPI open with a password (`docbin` `crypt.rs`, #1079). An AES header (`fAES`) is refused with a clear message: [MS-OFFCRYPTO] defines AES only for encrypted packages, which open through the `.docx` reader (gap 9) | | `.md` Markdown | — | (no) | ✅ | ✅ | — | — | `crates/formats/src/tests.rs` | Beyond Word | | `.tex` LaTeX | — | — | ✅ | ✅ | — | — | `crates/formats/src/tests.rs` | Beyond Word (#11), incl. math | -| Pictures for Insert › Picture, drag-and-drop and paste | — | R | ✅ | — | — | — | `insert_picture_takes_a_windows_metafile` (engine), `paste_picture.rs` | PNG, JPEG, GIF, WebP, BMP, and Windows Metafile `.wmf` / Enhanced Metafile `.emf` at their own frame size (#802), drawn by `crates/metafile`. Not yet: SVG, TIFF, ICO, HEIC | +| Pictures for Insert › Picture, drag-and-drop and paste | — | R | ✅ | — | — | — | `insert_picture_takes_a_windows_metafile` (engine), `paste_picture.rs` | PNG, JPEG, GIF, WebP, BMP, and Windows Metafile `.wmf` / Enhanced Metafile `.emf`, EMF+ records included (#6636), at their own frame size (#802), drawn with craft-libs' `craft-metafile`. Not yet: SVG, TIFF, ICO, HEIC | | `.png` page images | — | (Save as picture, Mac) | — | ✅ | — | — | `io_ext.rs` | | | `.json` document model | — | — | ✅ | ✅ | — | — | engine tests | For agents. A table cell's span is any number in the file; Insert Column and Merge Cells count it as at most 63 columns, as the `.docx` reader does (#3637) | diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index ed4f7eab98..31b694ee2d 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -37,7 +37,6 @@ pub const TABLE: &[(&str, Class)] = &[ ("control-key", Class::Standalone), ("doc", Class::Layer(1)), ("fonts", Class::Layer(1)), - ("metafile", Class::Layer(1)), ("layout", Class::Layer(2)), ("docx", Class::Layer(2)), ("docbin", Class::Layer(2)),