From fb927525f668e79e09a54ec5a5ae1a84a321dbb9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 16:18:29 -0800 Subject: [PATCH] Metafile import: a LOGFONT average character width becomes Horizontal Scale Follows #7608. EMF and WMF type ignored the font's average character width, and a positive font height was read as a fixed 0.85 of the cell. Both changes are to how the importer reads a LOGFONT's size fields. - When the face gives an average width (OS/2 xAvgCharWidth), a font's average character width becomes Horizontal Scale: the face's average width at the type size is stretched or narrowed to the font's width, also when the size is held at its 5000 pt limit. A negative width is read as its absolute value, and the width is ignored when the height is 0. - A positive height is the character cell. The em is the cell times unitsPerEm divided by the face's usWinAscent plus usWinDescent (its ascent plus descent when it has no OS/2 table). Type with a positive height in existing files changes size. - A font the system lacks is measured in the face VectorCraft draws it in. - FontFace gets win_cell_height and average_char_width. LOGFONT: https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-logfontw MS-EMF 2.2.13 LogFont: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-emf/1cd7cb7a-1a7c-48d2-b4a4-c218f9d12100 --- crates/metafile/src/import/picture.rs | 31 ++++++- crates/metafile/src/tests/import.rs | 118 ++++++++++++++++++++++++++ crates/text/src/fontdb/face.rs | 15 ++++ docs/mcp.md | 8 ++ docs/target-app-parity.md | 1 + 5 files changed, 169 insertions(+), 4 deletions(-) diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 03a2e5628e..2b1ae87380 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -537,10 +537,7 @@ impl Mapper { let shape = if k > 1e-12 && k.is_finite() && linear.determinant().abs() > 1e-24 { Affine::scale(1.0 / k) * linear } else { Affine::IDENTITY }; let f = &t.font; let h = f64::from(f.height); - // A negative height is the em; a positive one the cell (the em and the internal leading). - let em = if h < 0.0 { -h } else { h * 0.85 }; - let size = if em > 0.0 && (em * k).is_finite() { (em * k).clamp(0.5, 5000.0) } else { 12.0 }; - let mut style = CharStyle { size, fill: color(t.color), stroke: Paint::None, ..CharStyle::default() }; + let mut style = CharStyle { fill: color(t.color), stroke: Paint::None, ..CharStyle::default() }; if !f.family.trim().is_empty() { style.font_family = f.family.trim().to_string(); } @@ -551,6 +548,32 @@ impl Mapper { (false, false) => "Regular", } .into(); + // The face layout draws the type in (the fallback face for a font that isn't installed). + let face = vectorcraft_text::FontDb::global().style_face(&style); + // A negative height is the em. A positive height is the character cell, and the em is + // the cell times unitsPerEm divided by the face's OS/2 usWinAscent plus usWinDescent + // (its own ascent plus descent when it has no OS/2 table). + let cell_em = face.as_ref().and_then(|face| { + let (a, d) = face.vertical_metrics(); + Some(face.units_per_em() / face.win_cell_height().unwrap_or(a + d)).filter(|r| r.is_finite() && *r > 0.0) + }); + let em = if h < 0.0 { -h } else { h * cell_em.unwrap_or(0.85) }; + let sized = em > 0.0 && (em * k).is_finite(); + let size = if sized { (em * k).clamp(0.5, 5000.0) } else { 12.0 }; + style.size = size; + // An average character width, negative or positive, becomes Horizontal Scale: the face's + // own average width (OS/2 xAvgCharWidth) at the type size is stretched or narrowed to it, + // also when the size was held to its range. A width is ignored when the height is 0. + let width = f64::from(f.width).abs(); + if width > 0.0 + && sized + && let Some(avg) = face.as_ref().and_then(|face| Some(face.average_char_width()? / face.units_per_em())) + { + let h_scale = width * k / (avg * size) * 100.0; + if h_scale.is_finite() { + style.h_scale = h_scale.clamp(1.0, 10000.0); + } + } style.underline = f.underline; style.strikethrough = f.strike; // Where the baseline is below the reference point. diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index d8f4e8cce0..b456f03c3a 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -677,6 +677,124 @@ fn text_keeps_a_stretch_across() { assert!((a - 2.0).abs() < 1e-6 && b.abs() < 1e-6 && c.abs() < 1e-6 && (d - 1.0).abs() < 1e-6, "{:?}", t.xf); } +/// Source Sans 3 Regular's own values, read from its table directory: unitsPerEm (`head`), +/// xAvgCharWidth and usWinAscent + usWinDescent (`OS/2`), in font units. +fn source_sans_metrics() -> (f64, f64, f64) { + let font: &[u8] = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"); + let u16_at = |at: usize| u16::from_be_bytes([font[at], font[at + 1]]); + let table = |tag: &[u8; 4]| { + let at = (0..usize::from(u16_at(4))).map(|i| 12 + 16 * i).find(|at| &font[*at..*at + 4] == tag).unwrap(); + u32::from_be_bytes([font[at + 8], font[at + 9], font[at + 10], font[at + 11]]) as usize + }; + let (head, os2) = (table(b"head"), table(b"OS/2")); + let avg = f64::from(i16::from_be_bytes([font[os2 + 2], font[os2 + 3]])); + (f64::from(u16_at(head + 18)), avg, f64::from(u16_at(os2 + 74)) + f64::from(u16_at(os2 + 76))) +} + +/// The style of "Hi" drawn in an EMF in Source Sans 3 with a LOGFONT of `height` and `width` +/// (hundredths of a millimeter). +fn emf_font_style(height: i32, width: i32) -> vectorcraft_doc::CharStyle { + emf_font_style_in("Source Sans 3", height, width) +} + +/// [`emf_font_style`] with the LOGFONT naming `family`. +fn emf_font_style_in(family: &str, height: i32, width: i32) -> vectorcraft_doc::CharStyle { + let mut text = vec![0; 16]; + text.extend(le(&[1, 0, 0])); + text.extend(le(&[1000, 1500, 2, 76, 0, 0, 0, 0, 0, 0])); + text.extend("Hi".encode_utf16().flat_map(u16::to_le_bytes)); + let mut font = le(&[2, height, width, 0, 0, 400]); + font.extend([0u8; 8]); + font.extend(family.encode_utf16().chain(std::iter::repeat_n(0, 32 - family.encode_utf16().count())).flat_map(u16::to_le_bytes)); + let records = vec![(82, font), (37, le(&[2])), (84, text)]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + let t = all(&back.document) + .into_iter() + .find_map(|n| match n.kind { + NodeKind::Text(t) => Some(t), + _ => None, + }) + .unwrap(); + t.runs[0].style.clone() +} + +#[test] +fn a_font_width_becomes_horizontal_scale() { + let (upem, avg, _) = source_sans_metrics(); + let mm = 72.0 / 25.4; + // A 10 mm em and an average character width of 6 mm: the face's average width, avg/upem of + // the em, is scaled to 6 mm. + let want = 6.0 / (avg / upem * 10.0) * 100.0; + for width in [600, -600] { + let st = emf_font_style(-1000, width); + assert_eq!(st.font_family, "Source Sans 3"); + assert!((st.size - 10.0 * mm).abs() < 1e-9, "{}", st.size); + assert!((st.h_scale - want).abs() < 1e-9, "width {width}: {} for {want}", st.h_scale); + } + assert_eq!(emf_font_style(-1000, 0).h_scale, 100.0); + // A 4 m em is set at the largest type size, 5000 pt, and a 2.4 m average width keeps its + // width at that size. + let st = emf_font_style(-400_000, 240_000); + assert_eq!(st.size, 5000.0); + let want = 2400.0 * mm / (avg / upem * 5000.0) * 100.0; + assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale); + // With a height of 0 the type is set at the default size and the width is ignored. + assert_eq!(emf_font_style(0, 600).h_scale, 100.0); +} + +#[test] +fn a_positive_font_height_is_the_character_cell() { + let (upem, avg, cell) = source_sans_metrics(); + let mm = 72.0 / 25.4; + // A 10 mm cell: the em is the cell times unitsPerEm divided by the face's usWinAscent plus + // usWinDescent, and a 6 mm average width is measured against that em. + let em = 10.0 * upem / cell; + let st = emf_font_style(1000, 600); + assert!((st.size - em * mm).abs() < 1e-9, "{} for {}", st.size, em * mm); + let want = 6.0 / (avg / upem * em) * 100.0; + assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale); +} + +#[test] +fn a_font_the_system_lacks_is_measured_in_the_face_that_draws_it() { + // A family no system has keeps its name, and layout draws it in Source Sans 3: the cell and + // the average width are measured in that face. + let (upem, avg, cell) = source_sans_metrics(); + let mm = 72.0 / 25.4; + let st = emf_font_style_in("Missing Family 7183", 1000, 600); + assert_eq!(st.font_family, "Missing Family 7183"); + let em = 10.0 * upem / cell; + assert!((st.size - em * mm).abs() < 1e-9, "{} for {}", st.size, em * mm); + let want = 6.0 / (avg / upem * em) * 100.0; + assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale); +} + +#[test] +fn wmf_font_width_becomes_horizontal_scale() { + let (upem, avg, _) = source_sans_metrics(); + // CREATEFONTINDIRECT: a 0.1 inch em (144 units) with an average width of 72 units, then + // SELECTOBJECT and TEXTOUT "Hi" at (720, 360). + let mut font = le16(&[-144, 72, 0, 0, 400]); + font.extend([0u8; 8]); + font.extend(b"Source Sans 3".iter().copied().chain(std::iter::repeat_n(0, 19))); + let mut text = le16(&[2]); + text.extend(b"Hi"); + text.extend(le16(&[360, 720])); + let records = vec![(0x02FB, font), (0x012D, le16(&[0])), (0x0521, text)]; + let back = import(&hand_wmf(1440, 1440, &records)).unwrap(); + let t = all(&back.document) + .into_iter() + .find_map(|n| match n.kind { + NodeKind::Text(t) => Some(t), + _ => None, + }) + .unwrap(); + let st = &t.runs[0].style; + assert!((st.size - 7.2).abs() < 1e-9, "{}", st.size); + let want = 72.0 / (avg / upem * 144.0) * 100.0; + assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale); +} + #[test] fn a_clip_whose_box_holds_the_picture_still_clips() { // A diamond around the middle of the picture, whose box holds the whole frame but which cuts diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index c856525dfc..0e96e48008 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -368,6 +368,21 @@ impl FontFace { pub fn line_gap(&self) -> f64 { self.skrifa().map_or(0.0, |f| f64::from(f.metrics(Size::unscaled(), self.location()).leading)).max(0.0) } + /// The height of the face's character cell on Windows (the OS/2 table's `usWinAscent` plus + /// `usWinDescent`), in font units; `None` when the font has no OS/2 table or both are 0. + pub fn win_cell_height(&self) -> Option { + use skrifa::raw::TableProvider; + let o = self.skrifa()?.os2().ok()?; + let h = f64::from(o.us_win_ascent()) + f64::from(o.us_win_descent()); + (h > 0.0).then_some(h) + } + /// The average width of the face's characters (the OS/2 table's `xAvgCharWidth`), in font + /// units; `None` when the font has no OS/2 table or gives no positive width. + pub fn average_char_width(&self) -> Option { + use skrifa::raw::TableProvider; + let w = f64::from(self.skrifa()?.os2().ok()?.x_avg_char_width()); + (w > 0.0).then_some(w) + } /// Every mapped character and its glyph id, sorted by code point (the Glyphs panel). pub fn chars(&self) -> Vec<(char, u32)> { self.mapped_chars().to_vec() diff --git a/docs/mcp.md b/docs/mcp.md index bee07110e6..3fa5c6d9c0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8724,6 +8724,14 @@ pattern brushes fill with their average color. Records VectorCraft doesn't read pastes `image/emf` from the system clipboard ahead of text and bitmaps when the platform's clipboard service offers it (the Windows desktop service doesn't read metafiles yet). +The type size comes from the font's height. A negative height is the em. A positive height is the character cell, and +the em is the cell times the face's units per em divided by its OS/2 `usWinAscent` plus `usWinDescent` (its ascent +plus descent when it has no OS/2 table). When the face gives an average width (OS/2 `xAvgCharWidth`), a font's average +character width, negative or positive, becomes Horizontal Scale: the face's average width at the type size is +stretched or narrowed to the font's width. VectorCraft's own rules are that a negative width is read as its absolute +value and that the width is ignored when the height is 0. For a font the system doesn't have, both values are measured +in the face VectorCraft draws the type in. + ```json {"name":"export","arguments":{"path":"/tmp/logo.emf"}} {"name":"run_command","arguments":{"command":"document.export","params":{"format":"wmf","useArtboards":true,"path":"/tmp/icons.wmf"}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f506da06e1..28aa0613c0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1982,6 +1982,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - HEIC and HEIF images open and place from `.heic` and `.heif`, as the [supported file formats](https://helpx.adobe.com/illustrator/kb/supported-file-formats-illustrator.html) list High Efficiency Image under both Open and Place (and [Fix HEIF file import errors on Windows](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/fix-heif-file-import-errors-on-windows.html) covers both ways of bringing HEIF files in): HEVC-coded single pictures and grids of tiles, 8 to 10 bits, with an alpha image, decoded by heic-rs in the engine's default `heif` feature. The container's rotation, mirror and crop are applied. Without an `nclx` box, the HEVC stream's video signal type gives the samples' matrix and range. An RGB ICC profile, or Display P3 with the sRGB curve named by an `nclx` box or, without a color box, by the stream, is converted to sRGB; the EXIF resolution tags size the image, or 72 ppi. Image sequences, other codings and grids of cropped tiles are refused with a message, and so is every HEIF file in a build without the feature. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_heifread.rs`). - HP-GL/2 plot files (`.plt`, `.hpgl`, `.hgl`, `.hpg`, or a name no other format reads when the file starts with plotter instructions) open and place as paths on one layer, the artboard round the art: each line drawn with the pen down is a stroked path in its pen's color and width, line types become dash patterns, circles, arcs, wedges and Bézier curves are curves, filled and edged rectangles, wedges and polygons (polygon mode) are filled or stroked paths, and encoded polylines, scaling points, user units and rotation are read. Labels, symbol mode's symbols, raster images and hatching aren't drawn and are listed in the warnings (`crates/cad/src/hpgl/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - PICT pictures (`.pct`, `.pic`, and `.pict` as VectorCraft's own name) open and place, as [the help page](https://helpx.adobe.com/archive/illustrator/illustrator-cs5-5-troubleshooting.pdf) lists Macintosh PICT under both opening and placing: versions 1 and 2, with or without the file's 512 bytes of application data, read by the opcodes of Apple's [Opcodes in Pictures](https://dev.os9.ca/techpubs/mac/QuickDraw/QuickDraw-461.html). Lines, rectangles, rounded rectangles, ovals, arcs, polygons and regions become paths in their pen and pattern colors, text becomes point type in the font the picture names, bitmaps, pixel maps and QuickTime JPEG images become images, and the clip region clips what follows it; File › Place places the picture as one group clipped to its frame. Inverted shapes, other transfer modes and other QuickTime formats come back as warnings, and a picture cut short keeps what came before it (`crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs`). + - EMF and WMF type takes its size from the font's height, where a negative height is the em and a positive height is the character cell, and a font's average character width becomes Horizontal Scale against the face's own average width (OS/2 `xAvgCharWidth`) when the face gives one, as [LOGFONT](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-logfontw) and [MS-EMF 2.2.13](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-emf/1cd7cb7a-1a7c-48d2-b4a4-c218f9d12100) describe the two fields. VectorCraft's own rules are that the cell is the face's `usWinAscent` plus `usWinDescent` (its ascent plus descent without an OS/2 table), that a negative width is read as its absolute value, and that the width is ignored when the height is 0 (`a_font_width_becomes_horizontal_scale`, `a_positive_font_height_is_the_character_cell`, `a_font_the_system_lacks_is_measured_in_the_face_that_draws_it`, `wmf_font_width_becomes_horizontal_scale`). - EMF and WMF files are read by the shared `craft-metafile` reader and open, place and paste as editable paths, clipping groups, images and point type: an EMF drawn with EMF+ records (on their own, or beside plain records) is read from them instead of opening empty, and hatched and pattern brushes fill with their average color (`crates/metafile/src/tests/import.rs`). - Export As › HP-GL (`document.export {format: "hpgl"}`) writes a `.plt` plot of an artboard, each artboard or the art for pen plotters and cutters: each visible path once along its line in plotter units from the artboard's bottom-left corner or center, a pen per color or a pen table, curves flattened to a tolerance, type as outlines, clipping masks and the artboard's edges applied, and HP-GL or HP-GL/2 (pen colors and encoded polylines); plots read back by the HP-GL reader give the same lines (`crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - HP-GL export's `insideFirst` cuts each pen's paths inside before outside: a path is drawn only after the pen's paths that lie inside it (a letter's counter, a part's holes, rings within rings), touching outlines counted as inside and crossing ones not, in paint order or nearest first with `sortPaths`, within the plot's work budget; these order rules are VectorCraft's own (`crates/cad/src/hpgl/write/nest.rs`, `crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`).