From 9dcc6913d8bb5c1ae1f7f1008e04c98ec3b15dd7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 02:32:34 -0800 Subject: [PATCH 1/6] Metafile import: text in the opaque background mode fills its character cells A metafile playback starts in the opaque background mode with a white background color, and text drawn in that mode fills its character cells with the background color before the glyphs. EMF and WMF import now adds one filled rectangle of the background color behind each line of such text, before the type, from the font's OS/2 usWinAscent above the baseline to its usWinDescent below it, as far as the line's advances reach (NULs and negative advances included). Files that never set the background mode now import with a background behind their text. Top and bottom aligned text now has the top or the bottom of that cell at the reference point instead of 0.8 and 0.2 of the em. A single line without advances is aligned as long as its glyphs' advances, trailing spaces included. NULs after a line break move the start of that line, and underlined or struck through blanks draw their bars. Face::win_ascent_descent gives the OS/2 usWinAscent and usWinDescent separately, at a variable font's instance. --- crates/metafile/src/import/picture.rs | 270 ++++++++++++++++++++++---- crates/metafile/src/tests/import.rs | 190 +++++++++++++++++- crates/text/src/fontdb/face.rs | 10 +- crates/text/src/tests.rs | 7 +- docs/mcp.md | 8 +- 5 files changed, 434 insertions(+), 51 deletions(-) diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 125126790c..5f596e2389 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -16,7 +16,13 @@ //! range reaches, or a tab) are point type of their own, and an underline or strikethrough is carried across the space between. //! It is also carried on to the end of the last character's advance. Type on more than one line //! is placed a line at a time: each line is aligned by its own advances and split as a single -//! line is. +//! line is. NULs at the start, or after a line break, move the start of their line. A +//! character cell runs from the font's OS/2 usWinAscent above the baseline to its usWinDescent +//! below it, and top or bottom aligned text has the top or the bottom of its cells at the +//! reference point. One line without advances is aligned as long as its glyphs' advances, +//! trailing spaces included. Text drawn in the opaque background mode (the mode a playback +//! starts in) has one rectangle of the background color behind the character cells of each +//! line, as far as its advances reach. //! - Clip regions and clip paths become clipping groups around what they clip; a rectangle around //! the whole picture clips nothing and is left out. //! @@ -539,24 +545,44 @@ impl Mapper { fn text(&mut self, t: &craft_metafile::Text, chain: Vec>) { // The characters without NULs, and each one's advance (text units) when the file gives // one for every character: a NUL's advance goes to the character before it, or moves the - // start when the string begins with one. + // start when the string, or a line after a line break, begins with one. let advances = t.dx.len() == t.text.chars().count() && t.dx.iter().all(|d| d.is_finite()); - let (mut s, mut dx, mut lead) = (String::new(), Vec::new(), 0.0f64); + let (mut s, mut dx) = (String::new(), Vec::new()); + // How far before and after its start each character's advances (its own and the NULs' + // after it) reach (text units): an advance may be negative. And before each character, + // the advance of the NULs that move its line's start, with how far they reach. + let (mut reach, mut leads) = (Vec::new(), Vec::new()); + let mut lead = Lead::default(); + let breaks = |c: char| matches!(c, '\n' | '\r' | '\u{b}' | '\u{c}' | '\u{85}' | '\u{2028}' | '\u{2029}'); for (c, d) in t.text.chars().zip(t.dx.iter().map(|d| f64::from(*d)).chain(std::iter::repeat(0.0))) { if c != '\0' { s.push(c); dx.push(d); - } else if let Some(last) = dx.last_mut() { + reach.push((d.min(0.0), d.max(0.0))); + leads.push(std::mem::take(&mut lead)); + } else if let (Some(last), Some(r), false) = (dx.last_mut(), reach.last_mut(), s.chars().next_back().is_none_or(breaks)) { *last += d; + *r = (r.0.min(*last), r.1.max(*last)); } else { - lead += d; + lead.by += d; + lead.reach = (lead.reach.0.min(lead.by), lead.reach.1.max(lead.by)); } } if !advances { dx.clear(); - lead = 0.0; + reach.clear(); + leads.clear(); + lead = Lead::default(); } - if s.trim().is_empty() || t.color[3] == 0 { + // The leading NULs of the first line, or of a string of NULs alone. + let first = leads.first().copied().unwrap_or(lead); + // Type that draws nothing still fills its character cells on an opaque background. Blanks + // draw when they are underlined or struck through. + let background = t.background.filter(|c| c[3] > 0); + let shows = (!s.trim().is_empty() || t.font.underline || t.font.strike) && t.color[3] > 0; + // A string of NULs only fills the cells across its advances. + let nuls = s.is_empty() && first.reach.0 < first.reach.1 && background.is_some(); + if (s.is_empty() && !nuls) || !(shows || background.is_some()) { return; } // Text space → document without the move: its vertical scale gives the type size, and what @@ -613,11 +639,26 @@ impl Mapper { if !dx.is_empty() { style.kerning = Some(0.0); } - // Where the baseline is below the reference point. + // The character cell above and below the baseline (points): the face's OS/2 usWinAscent + // and usWinDescent at the type size (its own ascent and descent when it has no OS/2 + // table), as tall as a positive height asks. + let cell = face + .as_ref() + .map(|face| { + let (a, d) = face.win_ascent_descent().unwrap_or_else(|| face.vertical_metrics()); + (a / face.units_per_em() * size, d / face.units_per_em() * size) + }) + .filter(|(a, d)| a.is_finite() && d.is_finite() && *a >= 0.0 && *d >= 0.0 && a + d > 0.0) + .unwrap_or_else(|| { + let c = if h > 0.0 { size / 0.85 } else { size }; + (0.8 * c, 0.2 * c) + }); + // Where the baseline is below the reference point: the top or the bottom of the cell is at + // the reference point. let drop = match t.v_align { VAlign::Baseline => 0.0, - VAlign::Bottom => -0.2 * size, - VAlign::Top => 0.8 * size, + VAlign::Bottom => -cell.1, + VAlign::Top => cell.0, }; let origin = self.xf * Point::new(t.transform[4], t.transform[5]); let base = Affine::translate(origin.to_vec2()) * shape; @@ -633,19 +674,56 @@ impl Mapper { }; let whole = point(&s); let opacity = f32::from(t.color[3]) / 255.0; + let line = Line { + base, + drop, + align: &t.h_align, + decorated: f.underline || f.strike, + shows, + color: t.color, + opacity, + background, + cell, + point: &point, + }; + // The backgrounds of every line and piece, and the type added after them so that none of + // them covers it. + let mut out = TextOut::default(); if dx.is_empty() { let mut text = whole; - text.xf = base * Affine::translate((0.0, drop)); - text.cached_bounds = Some(vectorcraft_text::layout(db, &text).bounds); - let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text))); - n.opacity = opacity; - self.push(chain, n); - return; + let laid = vectorcraft_text::layout(db, &text); + // One line is as long as its advances, its trailing blanks included, where the + // alignment puts a line that long. + let along = laid + .glyphs + .iter() + .fold((f64::INFINITY, 0.0), |(from, width), g| (from.min(g.origin.x.min(g.origin.x + g.advance)), width + g.advance)); + let one = laid.lines.len() == 1 && along.0.is_finite() && along.1.is_finite(); + let shift = if one { aligned(0.0, along.1, &t.h_align) - along.0 } else { 0.0 }; + text.xf = base * Affine::translate((if shift.is_finite() { shift } else { 0.0 }, drop)); + text.cached_bounds = Some(laid.bounds); + // The cells of one line run across its advances, those of more than one across each + // line's glyphs. NULs alone span their advances, where the alignment puts them. + let cells = if nuls { + let start = aligned(first.by * k, 0.0, &t.h_align) - first.by * k; + cell_rect(start + first.reach.0 * k, start + first.reach.1 * k, 0.0, cell) + } else if one { + cell_rect(along.0, along.0 + along.1, laid.glyphs.first().map_or(0.0, |g| g.origin.y), cell) + } else { + cells(&laid, &s, cell, &t.h_align) + }; + out.backs.extend(self.background(&line, cells, text.xf)); + if shows { + let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text))); + n.opacity = opacity; + out.texts.push(n); + } + return self.add_text(&chain, out); } // Text units grow by `k` along the baseline in the text object's own space. let dx: Vec = dx.iter().map(|d| d * k).collect(); + let reach: Vec<(f64, f64)> = reach.iter().map(|(lo, hi)| (lo * k, hi * k)).collect(); let chars: Vec = s.chars().collect(); - let line = Line { base, drop, align: &t.h_align, decorated: f.underline || f.strike, color: t.color, opacity, point: &point, chain: &chain }; // Type on more than one line is placed a line at a time, each line aligned by its own // advances (layout leaves the tracking after a line's last character out of the width it // aligns, and each line ends with its own) and its underline carried on to its own end. @@ -655,25 +733,68 @@ impl Mapper { // a search. let starts: Vec = s.char_indices().map(|(at, _)| at).collect(); let count = |to: usize| starts.partition_point(|at| *at < to); - let first = laid.lines.first().map_or(0.0, |l| l.baseline); - for (n, l) in laid.lines.iter().enumerate() { + let top = laid.lines.first().map_or(0.0, |l| l.baseline); + for l in &laid.lines { let (from, to) = (count(l.start), count(l.end)); - let (Some(cs), Some(dx)) = (chars.get(from..to), dx.get(from..to)) else { continue }; - // A leading NUL's advance comes before the first line only. - let lead = if n == 0 { lead * k } else { 0.0 }; - let down = l.baseline - first; - self.line(&line, cs, dx, lead, if down.is_finite() { down } else { 0.0 }); + let (Some(cs), Some(dx), Some(reach)) = (chars.get(from..to), dx.get(from..to), reach.get(from..to)) else { continue }; + // The NULs before the line's first character, at the start or after a line break. + let lead = leads.get(from).copied().unwrap_or_default().scaled(k); + let down = l.baseline - top; + self.line(&line, cs, Advances { dx, reach, lead }, if down.is_finite() { down } else { 0.0 }, &mut out); } } else { - self.line(&line, &chars, &dx, lead * k, 0.0); + self.line(&line, &chars, Advances { dx: &dx, reach: &reach, lead: first.scaled(k) }, 0.0, &mut out); + } + self.add_text(&chain, out); + } + + /// Adds a text record's backgrounds and then its type, leaving out backgrounds when there is + /// no room for both. + fn add_text(&mut self, chain: &[Arc], out: TextOut) { + let TextOut { mut backs, texts } = out; + let keep = MAX_NODES.saturating_sub(self.out.len()).saturating_sub(texts.len()); + if backs.len() > keep { + backs.truncate(keep); + self.warn(TOO_MANY); + } + for n in backs.into_iter().chain(texts) { + self.push(chain.to_vec(), n); } } - /// One line of text with advances `dx` (points along the baseline) for its characters `chars`, - /// `down` below the first line's baseline: in pieces, each a text object of its own, a new - /// piece after each cluster that tracking can't space by its advance. - fn line(&mut self, line: &Line, chars: &[char], dx: &[f64], lead: f64, down: f64) { - if chars.is_empty() || (chars.iter().all(|c| c.is_whitespace()) && !line.decorated) { + /// Character cells `cells`, placed by `xf`, filled with the line's background when it has one. + fn background(&self, line: &Line, mut cells: BezPath, xf: Affine) -> Option { + let bg = line.background?; + if cells.elements().is_empty() { + return None; + } + cells.apply_affine(xf); + self.path_node(cells, Some(bg), None, false) + } + + /// One line of text with advances `adv` (points along the baseline) for its characters + /// `chars`, `down` below the first line's baseline: in pieces, each a text object of its own, + /// a new piece after each cluster that tracking can't space by its advance. + fn line(&mut self, line: &Line, chars: &[char], adv: Advances, down: f64, out: &mut TextOut) { + let Advances { dx, reach, lead } = adv; + if chars.is_empty() { + return; + } + // The line's cells, one rectangle behind every piece, run as far each way as its + // advances reach (an advance may be negative), from where the leading NULs' advances + // start, which the alignment puts where it puts a line as long as its advances. + let start = aligned(lead.by, dx.iter().sum(), line.align); + let (mut lo, mut hi, mut pos) = (lead.reach.0 - lead.by, lead.reach.1 - lead.by, 0.0f64); + for (d, r) in dx.iter().zip(reach) { + (lo, hi) = (lo.min(pos + r.0), hi.max(pos + r.1)); + pos += d; + } + let xf = line.base * Affine::translate((0.0, line.drop + down)); + out.backs.extend(self.background(line, cell_rect(start + lo, start + hi, 0.0, line.cell), xf)); + let blank = |cs: &[char]| cs.iter().all(|c| c.is_whitespace()); + // A piece's type draws when it shows: blanks only when underlined or struck through. + let draws = |cs: &[char]| line.shows && (!blank(cs) || line.decorated); + if !draws(chars) { return; } let db = vectorcraft_text::FontDb::global(); @@ -684,13 +805,13 @@ impl Mapper { // Along the baseline (the text object's own space), where the next piece starts from the // reference point: the line as long as its advances (a leading NUL's included), where the // alignment puts it. - let mut at = aligned(lead, dx.iter().sum(), line.align); + let mut at = start; let last = pieces.len().saturating_sub(1); for (i, (from, to)) in pieces.into_iter().enumerate() { - let piece: String = chars.get(from..to).unwrap_or_default().iter().collect(); + let cs = chars.get(from..to).unwrap_or_default(); + let piece: String = cs.iter().collect(); let dx = dx.get(from..to).unwrap_or_default(); - // Blanks of their own draw nothing unless they are underlined or struck through. - if piece.trim().is_empty() && !line.decorated { + if !draws(cs) { at += dx.iter().sum::(); continue; } @@ -715,12 +836,12 @@ impl Mapper { let gap = if (split && i < last) || (i == last && line.decorated) { gaps(&laid, db, &text, x0 + span) } else { BezPath::new() }; let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text.clone()))); n.opacity = line.opacity; - self.push(line.chain.to_vec(), n); + out.texts.push(n); if !gap.elements().is_empty() { let mut gap = gap; gap.apply_affine(text.xf); if let Some(n) = self.path_node(gap, Some(line.color), None, false) { - self.push(line.chain.to_vec(), n); + out.texts.push(n); } } } @@ -785,16 +906,89 @@ fn aligned(lead: f64, span: f64, align: &HAlign) -> f64 { /// What every piece of a text record's lines shares: the text space (`base`, with the baseline /// `drop` below the reference point), the alignment, whether the type is underlined or struck -/// through, its color and opacity, a point type object of a string in its style, and its clips. +/// through, whether the type shows, its color and opacity, its background and the character cell +/// above and below the baseline (points), and a point type object of a string in its style. struct Line<'a> { base: Affine, drop: f64, align: &'a HAlign, decorated: bool, + shows: bool, color: [u8; 4], opacity: f32, + background: Option<[u8; 4]>, + cell: (f64, f64), point: &'a dyn Fn(&str) -> TextObject, - chain: &'a [Arc], +} + +/// What a text record draws: the backgrounds behind its character cells, and its type (with the +/// bars that carry an underline or strikethrough on), added after them. +#[derive(Default)] +struct TextOut { + backs: Vec, + texts: Vec, +} + +/// One line's advances (points along the baseline): each character's own, how far before and +/// after its start the advances from it to the next character reach, and the leading NULs'. +struct Advances<'a> { + dx: &'a [f64], + reach: &'a [(f64, f64)], + lead: Lead, +} + +/// The NULs that move a line's start: their advance, and how far before and after the line's +/// start they reach. +#[derive(Clone, Copy, Default)] +struct Lead { + by: f64, + reach: (f64, f64), +} + +impl Lead { + /// The same NULs with their advances grown by `k`. + fn scaled(self, k: f64) -> Lead { + Lead { by: self.by * k, reach: (self.reach.0 * k, self.reach.1 * k) } + } +} + +/// The character cell from `x0` to `x1` along a baseline at `y`, `cell.0` above and `cell.1` +/// below it (points); empty when it has no area. +fn cell_rect(x0: f64, x1: f64, y: f64, cell: (f64, f64)) -> BezPath { + let r = Rect::new(x0, y - cell.0, x1, y + cell.1).abs(); + if r.width() > 0.0 && r.height() > 0.0 && r.is_finite() { shapes::rectangle(r).to_bezpath() } else { BezPath::new() } +} + +/// The character cells of `laid` (the type `s` laid out on more than one line), `cell.0` above +/// and `cell.1` below each baseline (points), as one rectangle a line: across the line as layout +/// places it (its trailing blanks are left out of the width layout aligns), or for a line of +/// blanks alone as wide as their advances, where `align` puts a line that long. +fn cells(laid: &vectorcraft_text::TextLayout, s: &str, cell: (f64, f64), align: &HAlign) -> BezPath { + // Each line's baseline, the sum of its glyphs' advances and whether they are all blanks. + // Glyphs come line by line. + let mut lines: Vec<(usize, f64, f64, bool)> = Vec::new(); + for g in &laid.glyphs { + let blank = s.get(g.byte..).and_then(|r| r.chars().next()).is_none_or(char::is_whitespace); + match lines.last_mut() { + Some((line, _, width, all)) if *line == g.line => { + *width += g.advance; + *all &= blank; + } + _ => lines.push((g.line, g.origin.y, g.advance, blank)), + } + } + let mut bp = BezPath::new(); + for (line, y, width, blank) in lines { + let (x0, x1) = match laid.lines.get(line) { + Some(l) if !blank => (l.x0, l.x1), + _ => { + let x0 = aligned(0.0, width, align); + (x0, x0 + width) + } + }; + bp.extend(cell_rect(x0, x1, y, cell)); + } + bp } /// The most times [`advanced`] lays the type out again to correct its tracking. diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 01883c740b..64f826b16a 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -274,7 +274,9 @@ fn hand_built_emf_plays_like_gdi() { let lines = &children[1]; assert_eq!(lines.appearance.items.len(), 1); assert!(near(lines.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 5.0 * mm, 5.0 * mm), 0.01)); - let NodeKind::Text(t) = &children[2].kind else { panic!("text") }; + // The background mode starts opaque: the text's cells are filled white behind it. + assert_eq!(fill_rgb(&children[2]), Some([255, 255, 255])); + let NodeKind::Text(t) = &children[3].kind else { panic!("text") }; assert_eq!(t.plain_text(), "Hi"); let st = &t.runs[0].style; assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Arial", "Bold")); @@ -884,6 +886,38 @@ fn wmf_font_width_becomes_horizontal_scale() { assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale); } +#[test] +fn wmf_text_fills_its_cells_in_the_opaque_background_mode() { + // CREATEFONTINDIRECT and SELECTOBJECT: a 0.1 inch em; SETBKCOLOR green; SETBKMODE `mode` + // (none when 0); TEXTOUT "Hi" at (720, 360), top aligned. + let backgrounds = |mode: i16| { + let mut font = le16(&[-144, 0, 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 mut records = vec![(0x02FB, font), (0x012D, le16(&[0])), (0x0201, 0x0000_ff00u32.to_le_bytes().to_vec())]; + if mode != 0 { + records.push((0x0102, le16(&[mode, 0]))); + } + records.push((0x0521, text)); + paths(&import(&hand_wmf(1440, 1440, &records)).unwrap().document) + }; + let mm = 72.0 / 25.4; + // A file that never sets the mode, and one that sets OPAQUE: one green rectangle whose top + // is at the reference point and whose left edge is at the start of the text. + for mode in [0, 2] { + let p = backgrounds(mode); + assert_eq!(p.len(), 1, "{mode}"); + assert_eq!(fill_rgb(&p[0]), Some([0, 255, 0]), "{mode}"); + let b = p[0].geometric_bounds().unwrap(); + assert!((b.x0 - 12.7 * mm).abs() < 0.01 && (b.y0 - 6.35 * mm).abs() < 0.01 && b.x1 > b.x0 && b.y1 > b.y0, "{mode}: {b:?}"); + } + // TRANSPARENT: no background. + assert!(backgrounds(1).is_empty()); +} + #[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 @@ -1001,7 +1035,8 @@ fn clipped_text_is_clipped_to_its_rectangle() { let mut font = le(&[2, -1000, 0, 0, 0, 400]); font.extend([0, 1, 1, 0, 0, 0, 0, 0]); font.extend("Arial".encode_utf16().chain(std::iter::repeat_n(0, 27)).flat_map(u16::to_le_bytes)); - let mut records = vec![(82, font), (37, le(&[2])), (84, text)]; + // SETBKMODE TRANSPARENT: no background behind the text. + let mut records = vec![(18, le(&[1])), (82, font), (37, le(&[2])), (84, text)]; let back = import(&hand_emf(5000, 3000, &records)).unwrap(); let layer = back.document.layers[0].children().unwrap(); assert_eq!(layer.len(), 1); @@ -1030,6 +1065,142 @@ fn clipped_text_is_clipped_to_its_rectangle() { assert!(matches!(children[1].kind, NodeKind::Text(_))); } +/// The layer of an EMF that sets the background color green, the background mode `mode` (none +/// when 0) and the text alignment `align`, then draws `s` at (`x`, 1500) in `font` with the +/// advances `dx`. +fn on_background(mode: i32, align: i32, x: i32, font: Vec, s: &str, dx: &[i32]) -> Vec> { + let mut records = vec![(25, le(&[0x0000_ff00])), (22, le(&[align])), (82, font), (37, le(&[2])), (84, text_out(x, s, dx))]; + if mode > 0 { + records.insert(0, (18, le(&[mode]))); + } + import(&hand_emf(5000, 3000, &records)).unwrap().document.layers[0].children().unwrap().clone() +} + +#[test] +fn opaque_backgrounds_fill_behind_the_character_cells() { + let mm = 72.0 / 25.4; + let aligned = on_background; + // TA_BASELINE: the baseline at (10, 15) mm. + let drawn = |mode: i32, font: Vec, s: &str, dx: &[i32]| aligned(mode, 24, 1000, font, s, dx); + let opaque = |font: Vec, s: &str, dx: &[i32]| drawn(2, font, s, dx); + // "Hi" with advances of 20 and 10 mm in a 10 mm em: the cells run across the advances, from + // the face's usWinAscent above the baseline to its usWinDescent below it, behind the type. + let layer = opaque(arial(), "Hi", &[2000, 1000]); + assert_eq!(layer.len(), 2); + assert_eq!(fill_rgb(&layer[0]), Some([0, 255, 0])); + let NodeKind::Text(t) = &layer[1].kind else { panic!("text") }; + let face = vectorcraft_text::FontDb::global().style_face(&t.runs[0].style).unwrap(); + let (a, d) = face.win_ascent_descent().unwrap(); + let em = face.units_per_em(); + let b = layer[0].geometric_bounds().unwrap(); + assert!(near(b, Rect::new(10.0 * mm, (15.0 - 10.0 * a / em) * mm, 40.0 * mm, (15.0 + 10.0 * d / em) * mm), 0.01), "{b:?}"); + // TA_TOP and TA_BOTTOM put the top and the bottom of the cell at the reference point: the + // baseline is usWinAscent below it, or usWinDescent above it. + for (align, top) in [(0, 15.0), (8, 15.0 - 10.0 * (a + d) / em)] { + let layer = aligned(2, align, 1000, arial(), "Hi", &[2000, 1000]); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.y0 - top * mm).abs() < 0.01 && (b.height() - 10.0 * (a + d) / em * mm).abs() < 0.01, "{align}: {b:?}"); + let NodeKind::Text(t) = &layer[1].kind else { panic!("text") }; + let baseline = (t.xf * vectorcraft_geom::Point::ZERO).y; + assert!((baseline - (top + 10.0 * a / em) * mm).abs() < 0.01, "{align}: {baseline}"); + } + // A leading NUL's advance is filled too: right aligned at 50 mm, "\0Hi" fills from 10 mm. + let b = aligned(2, 26, 5000, arial(), "\0Hi", &[1000, 2000, 1000])[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 50.0 * mm).abs() < 0.01, "{b:?}"); + // A positive height is the cell: 10 mm from top to bottom. + let mut font = le(&[2, 1000, 0, 0, 0, 400]); + font.extend([0; 8]); + font.extend("Arial".encode_utf16().chain(std::iter::repeat_n(0, 27)).flat_map(u16::to_le_bytes)); + let b = opaque(font, "Hi", &[2000, 1000])[0].geometric_bounds().unwrap(); + assert!((b.height() - 10.0 * mm).abs() < 0.01, "{b:?}"); + // Without advances the cells run across the glyphs' own advances. + let layer = opaque(arial(), "Hi", &[]); + let NodeKind::Text(t) = &layer[1].kind else { panic!("text") }; + let (xs, end) = glyph_xs(t); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.x0 - xs[0]).abs() < 0.01 && (b.x1 - end).abs() < 0.01, "{b:?} {xs:?} {end}"); + // Type split where an advance is further than tracking reaches: one background across the + // whole line's advances comes before both pieces of type. + let layer = opaque(arial(), "Hiy", &[12000, 500, 1000]); + let kinds: Vec = layer.iter().map(|n| matches!(n.kind, NodeKind::Text(_))).collect(); + assert_eq!(kinds, [false, true, true]); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 145.0 * mm).abs() < 0.01, "{b:?}"); + // A NUL after a line break moves the start of the line it begins, as it moves the first + // line's: "\0B" on a line of its own is placed and filled as the same record alone. + // Where the last text object's first glyph starts, and the left edges of the backgrounds. + let placed = |layer: &[std::sync::Arc]| { + let last = layer.iter().rev().find_map(|n| match &n.kind { + NodeKind::Text(t) => Some(glyph_xs(t).0[0]), + _ => None, + }); + let backs: Vec = + layer.iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).filter_map(|n| n.geometric_bounds()).map(|b| b.x0).collect(); + (last.unwrap(), backs) + }; + let (b_alone, _) = placed(&opaque(arial(), "\0B", &[2000, 1000])); + let (b_together, backs) = placed(&opaque(arial(), "A\n\0B", &[1000, 0, 2000, 1000])); + assert!((b_alone - 30.0 * mm).abs() < 0.01 && (b_together - b_alone).abs() < 0.01, "{b_alone} {b_together}"); + assert!(backs.len() == 2 && backs.iter().all(|x| (x - 10.0 * mm).abs() < 0.01), "{backs:?}"); +} + +#[test] +fn opaque_backgrounds_reach_as_far_as_the_advances() { + let mm = 72.0 / 25.4; + let aligned = on_background; + // TA_BASELINE: the baseline at (10, 15) mm. + let drawn = |mode: i32, font: Vec, s: &str, dx: &[i32]| aligned(mode, 24, 1000, font, s, dx); + let opaque = |font: Vec, s: &str, dx: &[i32]| drawn(2, font, s, dx); + // Two lines: a rectangle behind each, not one block over the space between them. + let layer = opaque(arial(), "Hi\nHi", &[]); + let NodeKind::Path { path, .. } = &layer[0].kind else { panic!("a path") }; + let rects = path.to_bezpath().elements().iter().filter(|e| matches!(e, vectorcraft_geom::PathEl::MoveTo(_))).count(); + assert_eq!(rects, 2); + // Without advances, a line is aligned as long as its advances, trailing spaces included, and + // its cells run across them: right aligned at 40 mm, "Hi " and its cells end there. + let layer = aligned(2, 26, 4000, arial(), "Hi ", &[]); + let NodeKind::Text(t) = &layer[1].kind else { panic!("text") }; + let (xs, end) = glyph_xs(t); + let b = layer[0].geometric_bounds().unwrap(); + assert!(xs.len() == 3 && (end - 40.0 * mm).abs() < 0.01, "{xs:?} {end}"); + assert!((b.x0 - xs[0]).abs() < 0.01 && (b.x1 - end).abs() < 0.01, "{b:?} {xs:?} {end}"); + // On more than one line, each line is aligned without its trailing spaces, and so are its + // cells: right aligned at 40 mm, neither passes it. + let b = aligned(2, 26, 4000, arial(), "Hi \nHi", &[])[0].geometric_bounds().unwrap(); + assert!((b.x1 - 40.0 * mm).abs() < 0.01, "{b:?}"); + // NULs whose advances go forward and back again still fill as far as they reach. + let layer = opaque(arial(), "\0\0", &[1000, -1000]); + assert_eq!(layer.len(), 1); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 20.0 * mm).abs() < 0.01, "{b:?}"); + let b = opaque(arial(), "H\0i", &[3000, -2000, 1000])[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 40.0 * mm).abs() < 0.01, "{b:?}"); + // An advance that goes back: the cells reach as far as the advances go, here to 30 mm. + let b = opaque(arial(), "Hi", &[2000, -1000])[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 30.0 * mm).abs() < 0.01, "{b:?}"); + // NULs alone fill across their advances. + let layer = opaque(arial(), "\0", &[2000]); + assert_eq!(layer.len(), 1); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 30.0 * mm).abs() < 0.01, "{b:?}"); + // Blanks on an opaque background still fill their cells, from the reference point on; on a + // transparent one nothing is left. + let layer = opaque(arial(), " \t", &[]); + assert_eq!(layer.len(), 1); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && b.x1 > 10.0 * mm, "{b:?}"); + assert!(drawn(1, arial(), " \t", &[]).is_empty()); + // Underlined blanks draw their underline, on a transparent background too. + for mode in [1, 2] { + let layer = drawn(mode, font_of("Arial", true), " ", &[]); + assert!(layer.iter().any(|n| matches!(&n.kind, NodeKind::Text(t) if t.runs[0].style.underline)), "{mode}"); + } + // A file that never sets the mode draws in the opaque mode a playback starts in. + let layer = drawn(0, arial(), "Hi", &[]); + assert_eq!(fill_rgb(&layer[0]), Some([0, 255, 0])); + assert!(drawn(1, arial(), "Hi", &[]).iter().all(|n| matches!(n.kind, NodeKind::Text(_)))); +} + /// The first text object of `d`. fn first_text(d: &Document) -> TextObject { all(d) @@ -1195,8 +1366,8 @@ fn multiline_text_with_advances_aligns_each_line() { } assert!(drops.iter().all(|d| (d - drops[0]).abs() < 0.01), "{drops:?}"); // Underlined and left aligned, each line's underline ends with its own advances: no bar runs on - // past either line. - let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hi\nHi", &[2000, 1000, 0, 2000, 1000]))]; + // past either line (on a transparent background, SETBKMODE). + let records = vec![(18, le(&[1])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hi\nHi", &[2000, 1000, 0, 2000, 1000]))]; let back = import(&hand_emf(5000, 3000, &records)).unwrap(); assert!(all(&back.document).iter().all(|n| !matches!(n.kind, NodeKind::Path { .. }))); for (align, x, second) in [(6, 2500, [15.0, 30.0]), (2, 4000, [20.0, 35.0])] { @@ -1254,8 +1425,9 @@ fn wmf_text_is_spaced_by_its_advances() { fn split_type_keeps_its_underline_and_right_to_left_order() { let mm = 72.0 / 25.4; // Underlined "Hiy" with an advance further than tracking reaches after the "H": the bar runs on - // from the end of the "H"'s underline to where "iy" starts, at 130 mm. - let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))]; + // from the end of the "H"'s underline to where "iy" starts, at 130 mm. The background is + // transparent (SETBKMODE) throughout. + let records = vec![(18, le(&[1])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))]; let back = import(&hand_emf(20000, 3000, &records)).unwrap(); assert_eq!(texts_at(&back.document), vec![("H".to_string(), vec![10.0]), ("iy".to_string(), vec![130.0, 135.0])]); let bars: Vec = @@ -1265,7 +1437,7 @@ fn split_type_keeps_its_underline_and_right_to_left_order() { assert!(b.x0 > 10.0 * mm && b.x0 < 130.0 * mm && (b.x1 - 130.0 * mm).abs() < 0.01 && b.height() < 2.0 * mm, "{b:?}"); // The "H" and the "i" before the split are tracked apart and draw a bar each: only the bar that // ends the piece runs on, from the end of the "i" to 130 mm. - let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[1000, 12000, 1000]))]; + let records = vec![(18, le(&[1])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[1000, 12000, 1000]))]; let back = import(&hand_emf(20000, 3000, &records)).unwrap(); assert_eq!(texts_at(&back.document), vec![("Hi".to_string(), vec![10.0, 20.0]), ("y".to_string(), vec![140.0])]); let gaps: Vec = all(&back.document).into_iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).collect(); @@ -1276,12 +1448,12 @@ fn split_type_keeps_its_underline_and_right_to_left_order() { let b = gaps[0].geometric_bounds().unwrap(); assert!(b.x0 > 20.0 * mm && (b.x1 - 140.0 * mm).abs() < 0.01, "{b:?}"); // Without an underline, nothing but the type. - let records = vec![(82, arial()), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))]; + let records = vec![(18, le(&[1])), (82, arial()), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))]; let back = import(&hand_emf(20000, 3000, &records)).unwrap(); assert!(all(&back.document).iter().all(|n| !matches!(n.kind, NodeKind::Path { .. }))); // A last advance further than tracking reaches, right aligned at 140 mm: the "H" and the "i" // start at 10 and 20 mm, and the underline runs on from the "i" to 140 mm. - let records = vec![(22, le(&[2])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(14000, "Hi", &[1000, 12000]))]; + let records = vec![(18, le(&[1])), (22, le(&[2])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(14000, "Hi", &[1000, 12000]))]; let back = import(&hand_emf(20000, 3000, &records)).unwrap(); assert_eq!(texts_at(&back.document), vec![("Hi".to_string(), vec![10.0, 20.0])]); let bars: Vec = diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index 5c21fbb4f1..d6e114a33f 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -372,6 +372,12 @@ impl FontFace { /// `usWinDescent`, at the face's location in a variable font), in font units; `None` when the /// font has no OS/2 table or the sum isn't positive. pub fn win_cell_height(&self) -> Option { + self.win_ascent_descent().map(|(a, d)| a + d) + } + /// The face's character cell on Windows above and below the baseline (the OS/2 table's + /// `usWinAscent` and `usWinDescent`, at the face's location in a variable font), in font + /// units; `None` when the font has no OS/2 table or the sum isn't positive. + pub fn win_ascent_descent(&self) -> Option<(f64, f64)> { use skrifa::raw::TableProvider; let f = self.skrifa()?; let o = f.os2().ok()?; @@ -380,8 +386,8 @@ impl FontFace { let varied = |tag: &[u8; 4]| { f.mvar().ok().and_then(|m| m.metric_delta(skrifa::Tag::new(tag), self.location().coords()).ok()).map_or(0.0, |d| d.to_f64()) }; - let h = f64::from(o.us_win_ascent()) + varied(b"hcla") + f64::from(o.us_win_descent()) + varied(b"hcld"); - (h > 0.0 && h.is_finite()).then_some(h) + let (a, d) = (f64::from(o.us_win_ascent()) + varied(b"hcla"), f64::from(o.us_win_descent()) + varied(b"hcld")); + (a + d > 0.0 && (a + d).is_finite()).then_some((a, d)) } /// 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. diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 38a8d97f69..94709cbb23 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -875,7 +875,8 @@ fn on_path_align_takes_a_variable_font_instances_em_box() { } /// A variable font's instance takes its Windows character cell from the `usWinAscent` and -/// `usWinDescent` its `MVAR` table varies: 200 units taller in Bold. +/// `usWinDescent` its `MVAR` table varies: 200 units taller in Bold, 120 above the baseline and +/// 80 below it. #[test] fn win_cell_height_takes_a_variable_font_instances_mvar() { use crate::test_fonts::{PATH_ALIGN_VARIABLE_FAMILY, path_align_font}; @@ -885,6 +886,10 @@ fn win_cell_height_takes_a_variable_font_instances_mvar() { let cell = |font_style: &str| db.style_face(&st(font_style)).and_then(|f| f.win_cell_height()).unwrap(); let (regular, bold) = (cell("Regular"), cell("Bold")); assert!((bold - regular - 200.0).abs() < 1e-6, "Regular {regular}, Bold {bold}"); + let split = |font_style: &str| db.style_face(&st(font_style)).and_then(|f| f.win_ascent_descent()).unwrap(); + let ((ra, rd), (ba, bd)) = (split("Regular"), split("Bold")); + assert!((ba - ra - 120.0).abs() < 1e-6 && (bd - rd - 80.0).abs() < 1e-6, "Regular {ra}/{rd}, Bold {ba}/{bd}"); + assert!((ra + rd - regular).abs() < 1e-6); } /// In vertical type, Align to Path moves the glyphs half an em, with their horizontal scale and not diff --git a/docs/mcp.md b/docs/mcp.md index 79f6183e79..95bce038ca 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9875,7 +9875,13 @@ images and point type in the font the file names. Type keeps the file's characte kerning off. On a single left to right line, an advance that tracking can't give (wider than its range, or a tab) starts a new point type object at the position the advance gives, and an underline or strikethrough is filled across the space between and on to the end of the last character's advance. Type on more than one line is placed a line at a time: each line is aligned by its own advances and -split as a single line is. An EMF that +split as a single line is. NULs at the start of the text, or after a line break, move the start of their line by their +advances. Blanks that are underlined or struck through draw their bars. A character cell runs from the font's OS/2 +`usWinAscent` above the baseline to its `usWinDescent` below it: top and bottom aligned text has the top or the +bottom of its cells at the reference point. A single line without character advances is aligned as long as its +glyphs' advances, trailing spaces included. Text drawn in the opaque background mode, which a file is in until it +sets the mode to transparent, gets one filled rectangle of the background color behind the character cells of each +line, as far as its advances reach (NULs' included), placed before the type. An EMF that draws with EMF+ records is read from them. Hatched and pattern brushes fill with their average color. Records VectorCraft doesn't read are skipped with one warning. A file, or a metafile image inside it, cut short by one of the reader's limits adds one warning without a count. Each of these adds one warning, with a count: images and pattern brushes whose bitmap can't be read, which are left From 8993be043f90bbcce70c5916e72318ec00828fba Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:42:41 -0800 Subject: [PATCH 2/6] Metafile import: keep the opaque text background to its own change This takes three behavior changes out of the branch, so that it holds the opaque background and the character cell it fills: - A single line without advances is aligned as before, without its trailing spaces. Its cells run across its glyphs' advances from where its type starts; blanks alone, which draw no type, are filled where the alignment puts them. - NULs after a line break add their advance to the character before them, as before. - Blanks that are underlined or struck through draw nothing, as before. A string of NULs alone in an underlined font now fills its cells and adds no empty type object. docs/mcp.md no longer describes the three, and docs/target-app-parity.md lists the background and the cell. The first commit's body names FontFace::win_ascent_descent as Face::win_ascent_descent. A device context starts with a background color that is typically white; the first commit states white as the playback default. --- crates/metafile/src/import/picture.rs | 56 +++++++++++++-------------- crates/metafile/src/tests/import.rs | 30 +++----------- docs/mcp.md | 6 +-- docs/target-app-parity.md | 1 + 4 files changed, 35 insertions(+), 58 deletions(-) diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 5f596e2389..29e40ed984 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -16,13 +16,11 @@ //! range reaches, or a tab) are point type of their own, and an underline or strikethrough is carried across the space between. //! It is also carried on to the end of the last character's advance. Type on more than one line //! is placed a line at a time: each line is aligned by its own advances and split as a single -//! line is. NULs at the start, or after a line break, move the start of their line. A -//! character cell runs from the font's OS/2 usWinAscent above the baseline to its usWinDescent -//! below it, and top or bottom aligned text has the top or the bottom of its cells at the -//! reference point. One line without advances is aligned as long as its glyphs' advances, -//! trailing spaces included. Text drawn in the opaque background mode (the mode a playback -//! starts in) has one rectangle of the background color behind the character cells of each -//! line, as far as its advances reach. +//! line is. A character cell runs from the font's OS/2 usWinAscent above the baseline to its +//! usWinDescent below it, and top or bottom aligned text has the top or the bottom of its cells +//! at the reference point. Text drawn in the opaque background mode (the mode a playback starts +//! in) has one rectangle of the background color behind the character cells of each line, as +//! far as its advances reach. //! - Clip regions and clip paths become clipping groups around what they clip; a rectangle around //! the whole picture clips nothing and is left out. //! @@ -545,22 +543,20 @@ impl Mapper { fn text(&mut self, t: &craft_metafile::Text, chain: Vec>) { // The characters without NULs, and each one's advance (text units) when the file gives // one for every character: a NUL's advance goes to the character before it, or moves the - // start when the string, or a line after a line break, begins with one. + // start when the string begins with one. let advances = t.dx.len() == t.text.chars().count() && t.dx.iter().all(|d| d.is_finite()); let (mut s, mut dx) = (String::new(), Vec::new()); // How far before and after its start each character's advances (its own and the NULs' - // after it) reach (text units): an advance may be negative. And before each character, - // the advance of the NULs that move its line's start, with how far they reach. - let (mut reach, mut leads) = (Vec::new(), Vec::new()); + // after it) reach (text units): an advance may be negative. And the advance of the NULs + // that move the start, with how far they reach. + let mut reach = Vec::new(); let mut lead = Lead::default(); - let breaks = |c: char| matches!(c, '\n' | '\r' | '\u{b}' | '\u{c}' | '\u{85}' | '\u{2028}' | '\u{2029}'); for (c, d) in t.text.chars().zip(t.dx.iter().map(|d| f64::from(*d)).chain(std::iter::repeat(0.0))) { if c != '\0' { s.push(c); dx.push(d); reach.push((d.min(0.0), d.max(0.0))); - leads.push(std::mem::take(&mut lead)); - } else if let (Some(last), Some(r), false) = (dx.last_mut(), reach.last_mut(), s.chars().next_back().is_none_or(breaks)) { + } else if let (Some(last), Some(r)) = (dx.last_mut(), reach.last_mut()) { *last += d; *r = (r.0.min(*last), r.1.max(*last)); } else { @@ -571,15 +567,13 @@ impl Mapper { if !advances { dx.clear(); reach.clear(); - leads.clear(); lead = Lead::default(); } - // The leading NULs of the first line, or of a string of NULs alone. - let first = leads.first().copied().unwrap_or(lead); - // Type that draws nothing still fills its character cells on an opaque background. Blanks - // draw when they are underlined or struck through. + // The leading NULs, of the text or of a string of NULs alone. + let first = lead; + // Type that draws nothing still fills its character cells on an opaque background. let background = t.background.filter(|c| c[3] > 0); - let shows = (!s.trim().is_empty() || t.font.underline || t.font.strike) && t.color[3] > 0; + let shows = !s.trim().is_empty() && t.color[3] > 0; // A string of NULs only fills the cells across its advances. let nuls = s.is_empty() && first.reach.0 < first.reach.1 && background.is_some(); if (s.is_empty() && !nuls) || !(shows || background.is_some()) { @@ -692,23 +686,25 @@ impl Mapper { if dx.is_empty() { let mut text = whole; let laid = vectorcraft_text::layout(db, &text); - // One line is as long as its advances, its trailing blanks included, where the - // alignment puts a line that long. + // Where one line's glyphs start, and the sum of their advances, its trailing blanks + // included. let along = laid .glyphs .iter() .fold((f64::INFINITY, 0.0), |(from, width), g| (from.min(g.origin.x.min(g.origin.x + g.advance)), width + g.advance)); let one = laid.lines.len() == 1 && along.0.is_finite() && along.1.is_finite(); - let shift = if one { aligned(0.0, along.1, &t.h_align) - along.0 } else { 0.0 }; - text.xf = base * Affine::translate((if shift.is_finite() { shift } else { 0.0 }, drop)); + text.xf = base * Affine::translate((0.0, drop)); text.cached_bounds = Some(laid.bounds); - // The cells of one line run across its advances, those of more than one across each - // line's glyphs. NULs alone span their advances, where the alignment puts them. + // The cells of one line run across its advances, from where its type starts, or for + // blanks alone, which draw no type, where the alignment puts a line that long. Those + // of more than one line run across each line's glyphs. NULs alone span their + // advances, where the alignment puts them. let cells = if nuls { let start = aligned(first.by * k, 0.0, &t.h_align) - first.by * k; cell_rect(start + first.reach.0 * k, start + first.reach.1 * k, 0.0, cell) } else if one { - cell_rect(along.0, along.0 + along.1, laid.glyphs.first().map_or(0.0, |g| g.origin.y), cell) + let x0 = if shows { along.0 } else { aligned(0.0, along.1, &t.h_align) }; + cell_rect(x0, x0 + along.1, laid.glyphs.first().map_or(0.0, |g| g.origin.y), cell) } else { cells(&laid, &s, cell, &t.h_align) }; @@ -734,11 +730,11 @@ impl Mapper { let starts: Vec = s.char_indices().map(|(at, _)| at).collect(); let count = |to: usize| starts.partition_point(|at| *at < to); let top = laid.lines.first().map_or(0.0, |l| l.baseline); - for l in &laid.lines { + for (n, l) in laid.lines.iter().enumerate() { let (from, to) = (count(l.start), count(l.end)); let (Some(cs), Some(dx), Some(reach)) = (chars.get(from..to), dx.get(from..to), reach.get(from..to)) else { continue }; - // The NULs before the line's first character, at the start or after a line break. - let lead = leads.get(from).copied().unwrap_or_default().scaled(k); + // A leading NUL's advance comes before the first line only. + let lead = if n == 0 { first.scaled(k) } else { Lead::default() }; let down = l.baseline - top; self.line(&line, cs, Advances { dx, reach, lead }, if down.is_finite() { down } else { 0.0 }, &mut out); } diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 64f826b16a..aebed8a859 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -1126,22 +1126,6 @@ fn opaque_backgrounds_fill_behind_the_character_cells() { assert_eq!(kinds, [false, true, true]); let b = layer[0].geometric_bounds().unwrap(); assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 145.0 * mm).abs() < 0.01, "{b:?}"); - // A NUL after a line break moves the start of the line it begins, as it moves the first - // line's: "\0B" on a line of its own is placed and filled as the same record alone. - // Where the last text object's first glyph starts, and the left edges of the backgrounds. - let placed = |layer: &[std::sync::Arc]| { - let last = layer.iter().rev().find_map(|n| match &n.kind { - NodeKind::Text(t) => Some(glyph_xs(t).0[0]), - _ => None, - }); - let backs: Vec = - layer.iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).filter_map(|n| n.geometric_bounds()).map(|b| b.x0).collect(); - (last.unwrap(), backs) - }; - let (b_alone, _) = placed(&opaque(arial(), "\0B", &[2000, 1000])); - let (b_together, backs) = placed(&opaque(arial(), "A\n\0B", &[1000, 0, 2000, 1000])); - assert!((b_alone - 30.0 * mm).abs() < 0.01 && (b_together - b_alone).abs() < 0.01, "{b_alone} {b_together}"); - assert!(backs.len() == 2 && backs.iter().all(|x| (x - 10.0 * mm).abs() < 0.01), "{backs:?}"); } #[test] @@ -1156,13 +1140,13 @@ fn opaque_backgrounds_reach_as_far_as_the_advances() { let NodeKind::Path { path, .. } = &layer[0].kind else { panic!("a path") }; let rects = path.to_bezpath().elements().iter().filter(|e| matches!(e, vectorcraft_geom::PathEl::MoveTo(_))).count(); assert_eq!(rects, 2); - // Without advances, a line is aligned as long as its advances, trailing spaces included, and - // its cells run across them: right aligned at 40 mm, "Hi " and its cells end there. + // Without advances, one line's cells run across its glyphs' advances, trailing spaces + // included: right aligned, they run from the "H" to the end of the space after the "i". let layer = aligned(2, 26, 4000, arial(), "Hi ", &[]); let NodeKind::Text(t) = &layer[1].kind else { panic!("text") }; let (xs, end) = glyph_xs(t); let b = layer[0].geometric_bounds().unwrap(); - assert!(xs.len() == 3 && (end - 40.0 * mm).abs() < 0.01, "{xs:?} {end}"); + assert!(xs.len() == 3, "{xs:?} {end}"); assert!((b.x0 - xs[0]).abs() < 0.01 && (b.x1 - end).abs() < 0.01, "{b:?} {xs:?} {end}"); // On more than one line, each line is aligned without its trailing spaces, and so are its // cells: right aligned at 40 mm, neither passes it. @@ -1190,11 +1174,9 @@ fn opaque_backgrounds_reach_as_far_as_the_advances() { let b = layer[0].geometric_bounds().unwrap(); assert!((b.x0 - 10.0 * mm).abs() < 0.01 && b.x1 > 10.0 * mm, "{b:?}"); assert!(drawn(1, arial(), " \t", &[]).is_empty()); - // Underlined blanks draw their underline, on a transparent background too. - for mode in [1, 2] { - let layer = drawn(mode, font_of("Arial", true), " ", &[]); - assert!(layer.iter().any(|n| matches!(&n.kind, NodeKind::Text(t) if t.runs[0].style.underline)), "{mode}"); - } + // NULs alone in an underlined font fill their cells and add no type. + let layer = opaque(font_of("Arial", true), "\0", &[2000]); + assert!(layer.len() == 1 && matches!(layer[0].kind, NodeKind::Path { .. }), "{layer:?}"); // A file that never sets the mode draws in the opaque mode a playback starts in. let layer = drawn(0, arial(), "Hi", &[]); assert_eq!(fill_rgb(&layer[0]), Some([0, 255, 0])); diff --git a/docs/mcp.md b/docs/mcp.md index 95bce038ca..20c3c80722 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9875,11 +9875,9 @@ images and point type in the font the file names. Type keeps the file's characte kerning off. On a single left to right line, an advance that tracking can't give (wider than its range, or a tab) starts a new point type object at the position the advance gives, and an underline or strikethrough is filled across the space between and on to the end of the last character's advance. Type on more than one line is placed a line at a time: each line is aligned by its own advances and -split as a single line is. NULs at the start of the text, or after a line break, move the start of their line by their -advances. Blanks that are underlined or struck through draw their bars. A character cell runs from the font's OS/2 +split as a single line is. A character cell runs from the font's OS/2 `usWinAscent` above the baseline to its `usWinDescent` below it: top and bottom aligned text has the top or the -bottom of its cells at the reference point. A single line without character advances is aligned as long as its -glyphs' advances, trailing spaces included. Text drawn in the opaque background mode, which a file is in until it +bottom of its cells at the reference point. Text drawn in the opaque background mode, which a file is in until it sets the mode to transparent, gets one filled rectangle of the background color behind the character cells of each line, as far as its advances reach (NULs' included), placed before the type. An EMF that draws with EMF+ records is read from them. Hatched and pattern brushes fill with their average color. Records VectorCraft doesn't read are skipped with one warning. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f4c76fcbbd..24bb533a8d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2271,6 +2271,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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` at a variable font's instance (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`). - EMF, WMF and EMF+ text keeps the character advances the file gives (ExtTextOut's `lpDx`, DrawDriverString positions) as tracking, with pair kerning off; on a single left to right line, an advance that tracking can't give (wider than its range, or a tab) starts a new point type object where the advance puts it, with an underline or strikethrough filled across the space between and on to the end of the last character's advance; type on more than one line is placed a line at a time, each line aligned by its own advances and split as a single line is (`text_is_spaced_by_its_advances`, `multiline_text_with_advances_aligns_each_line`, `wmf_text_is_spaced_by_its_advances`, `emf_plus_driver_strings_keep_their_positions`, `split_type_keeps_its_underline_and_right_to_left_order`). + - EMF and WMF text drawn in the opaque background mode, which a playback starts in ([MS-EMF 2.1.4 BackgroundMode](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-emf/2f57054c-2b69-4303-a6f8-5aacd401f759), [SetBkMode](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-setbkmode)), gets one rectangle of the background color behind each line's character cells, placed before the type; transparent text gets none. A character cell runs from the font's OS/2 `usWinAscent` above the baseline to its `usWinDescent` below it, and top or bottom aligned text puts the top or the bottom of the cell at the reference point (`opaque_backgrounds_fill_behind_the_character_cells`, `opaque_backgrounds_reach_as_far_as_the_advances`, `wmf_text_fills_its_cells_in_the_opaque_background_mode`). - EMF and WMF import warns about what the reader leaves out or does not play as the file asks: a file, or a metafile image inside it, cut short by one of the reader's limits (items, bytes kept, saved states, clip paths), with one warning without a count, and, with counts, images and pattern brushes that are not read, clips that are not applied, and raster operations other than a plain copy (`a_file_cut_short_by_another_limit_says_so`, `images_the_reader_does_not_read_are_counted`, `clips_that_are_not_applied_are_counted`, `raster_operations_that_are_not_played_are_counted`, `a_wmf_reports_unread_pattern_brushes_and_raster_operations`). - 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`). From 8dd0824b3f4789a9bde7d817e9d8655ad3fab7b8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:49:23 -0800 Subject: [PATCH 3/6] Metafile import: opaque backgrounds cover trailing spaces and NUL-only lines On more than one line without advances, each line's background now runs across its glyphs' advances, trailing spaces included, as a single line's does; layout leaves the trailing spaces out of the width it aligns. A first line that holds only NULs fills its cells across their advances instead of drawing nothing. --- crates/metafile/src/import/picture.rs | 30 ++++++++++++++------------- crates/metafile/src/tests/import.rs | 14 ++++++++++--- 2 files changed, 27 insertions(+), 17 deletions(-) diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 29e40ed984..ce9d3a902b 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -773,12 +773,10 @@ impl Mapper { /// a new piece after each cluster that tracking can't space by its advance. fn line(&mut self, line: &Line, chars: &[char], adv: Advances, down: f64, out: &mut TextOut) { let Advances { dx, reach, lead } = adv; - if chars.is_empty() { - return; - } // The line's cells, one rectangle behind every piece, run as far each way as its // advances reach (an advance may be negative), from where the leading NULs' advances - // start, which the alignment puts where it puts a line as long as its advances. + // start, which the alignment puts where it puts a line as long as its advances. A line + // of leading NULs alone fills the cells across their advances. let start = aligned(lead.by, dx.iter().sum(), line.align); let (mut lo, mut hi, mut pos) = (lead.reach.0 - lead.by, lead.reach.1 - lead.by, 0.0f64); for (d, r) in dx.iter().zip(reach) { @@ -790,7 +788,7 @@ impl Mapper { let blank = |cs: &[char]| cs.iter().all(|c| c.is_whitespace()); // A piece's type draws when it shows: blanks only when underlined or struck through. let draws = |cs: &[char]| line.shows && (!blank(cs) || line.decorated); - if !draws(chars) { + if chars.is_empty() || !draws(chars) { return; } let db = vectorcraft_text::FontDb::global(); @@ -957,26 +955,30 @@ fn cell_rect(x0: f64, x1: f64, y: f64, cell: (f64, f64)) -> BezPath { /// The character cells of `laid` (the type `s` laid out on more than one line), `cell.0` above /// and `cell.1` below each baseline (points), as one rectangle a line: across the line as layout -/// places it (its trailing blanks are left out of the width layout aligns), or for a line of -/// blanks alone as wide as their advances, where `align` puts a line that long. +/// places it and across its glyphs' advances, its trailing blanks included (layout leaves them +/// out of the width it aligns), or for a line of blanks alone as wide as their advances, where +/// `align` puts a line that long. fn cells(laid: &vectorcraft_text::TextLayout, s: &str, cell: (f64, f64), align: &HAlign) -> BezPath { - // Each line's baseline, the sum of its glyphs' advances and whether they are all blanks. - // Glyphs come line by line. - let mut lines: Vec<(usize, f64, f64, bool)> = Vec::new(); + // Each line's baseline, the sum of its glyphs' advances, how far before and after the + // reference point they reach, and whether they are all blanks. Glyphs come line by line. + type Row = (usize, f64, f64, (f64, f64), bool); + let mut lines: Vec = Vec::new(); for g in &laid.glyphs { let blank = s.get(g.byte..).and_then(|r| r.chars().next()).is_none_or(char::is_whitespace); + let (from, to) = (g.origin.x.min(g.origin.x + g.advance), g.origin.x.max(g.origin.x + g.advance)); match lines.last_mut() { - Some((line, _, width, all)) if *line == g.line => { + Some((line, _, width, reach, all)) if *line == g.line => { *width += g.advance; + *reach = (reach.0.min(from), reach.1.max(to)); *all &= blank; } - _ => lines.push((g.line, g.origin.y, g.advance, blank)), + _ => lines.push((g.line, g.origin.y, g.advance, (from, to), blank)), } } let mut bp = BezPath::new(); - for (line, y, width, blank) in lines { + for (line, y, width, reach, blank) in lines { let (x0, x1) = match laid.lines.get(line) { - Some(l) if !blank => (l.x0, l.x1), + Some(l) if !blank => (l.x0.min(reach.0), l.x1.max(reach.1)), _ => { let x0 = aligned(0.0, width, align); (x0, x0 + width) diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index aebed8a859..f7937614d4 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -1148,10 +1148,18 @@ fn opaque_backgrounds_reach_as_far_as_the_advances() { let b = layer[0].geometric_bounds().unwrap(); assert!(xs.len() == 3, "{xs:?} {end}"); assert!((b.x0 - xs[0]).abs() < 0.01 && (b.x1 - end).abs() < 0.01, "{b:?} {xs:?} {end}"); - // On more than one line, each line is aligned without its trailing spaces, and so are its - // cells: right aligned at 40 mm, neither passes it. + // Layout aligns a line without its trailing spaces: right aligned at 40 mm, the space after + // the "i" runs on past it. On more than one line, the cells also run across the trailing + // spaces, as far as on one line. + assert!(end > 41.0 * mm, "{end}"); let b = aligned(2, 26, 4000, arial(), "Hi \nHi", &[])[0].geometric_bounds().unwrap(); - assert!((b.x1 - 40.0 * mm).abs() < 0.01, "{b:?}"); + assert!((b.x1 - end).abs() < 0.01, "{b:?} {end}"); + // Leading NULs on a line of their own fill their cells across their advances, before the + // next line: from 10 to 30 mm. + let layer = opaque(arial(), "\0\nA", &[2000, 0, 1000]); + let first = layer[0].geometric_bounds().unwrap(); + assert!((first.x0 - 10.0 * mm).abs() < 0.01 && (first.x1 - 30.0 * mm).abs() < 0.01, "{first:?}"); + assert!(matches!(layer[1].kind, NodeKind::Path { .. }) && matches!(layer[2].kind, NodeKind::Text(_)), "{layer:?}"); // NULs whose advances go forward and back again still fill as far as they reach. let layer = opaque(arial(), "\0\0", &[1000, -1000]); assert_eq!(layer.len(), 1); From 14318099c29ff5f546cfbea9b6b23b671b45015a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:54:13 -0800 Subject: [PATCH 4/6] Metafile import: an underlined blank line's background follows its bar On more than one line without advances, a line of blanks whose underline or strikethrough draws now has its background across its glyphs, where the bar is drawn, instead of where the alignment puts a line that long. Text without a background no longer measures or builds the cells. --- crates/metafile/src/import/picture.rs | 66 +++++++++++++++------------ crates/metafile/src/tests/import.rs | 24 ++++++++++ 2 files changed, 60 insertions(+), 30 deletions(-) diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index ce9d3a902b..226ad0380e 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -686,29 +686,31 @@ impl Mapper { if dx.is_empty() { let mut text = whole; let laid = vectorcraft_text::layout(db, &text); - // Where one line's glyphs start, and the sum of their advances, its trailing blanks - // included. - let along = laid - .glyphs - .iter() - .fold((f64::INFINITY, 0.0), |(from, width), g| (from.min(g.origin.x.min(g.origin.x + g.advance)), width + g.advance)); - let one = laid.lines.len() == 1 && along.0.is_finite() && along.1.is_finite(); text.xf = base * Affine::translate((0.0, drop)); text.cached_bounds = Some(laid.bounds); - // The cells of one line run across its advances, from where its type starts, or for - // blanks alone, which draw no type, where the alignment puts a line that long. Those - // of more than one line run across each line's glyphs. NULs alone span their - // advances, where the alignment puts them. - let cells = if nuls { - let start = aligned(first.by * k, 0.0, &t.h_align) - first.by * k; - cell_rect(start + first.reach.0 * k, start + first.reach.1 * k, 0.0, cell) - } else if one { - let x0 = if shows { along.0 } else { aligned(0.0, along.1, &t.h_align) }; - cell_rect(x0, x0 + along.1, laid.glyphs.first().map_or(0.0, |g| g.origin.y), cell) - } else { - cells(&laid, &s, cell, &t.h_align) - }; - out.backs.extend(self.background(&line, cells, text.xf)); + if background.is_some() { + // Where one line's glyphs start, and the sum of their advances, its trailing + // blanks included. + let along = laid + .glyphs + .iter() + .fold((f64::INFINITY, 0.0), |(from, width), g| (from.min(g.origin.x.min(g.origin.x + g.advance)), width + g.advance)); + let one = laid.lines.len() == 1 && along.0.is_finite() && along.1.is_finite(); + // The cells of one line run across its advances, from where its type starts, or + // for blanks alone, which draw no type, where the alignment puts a line that long. + // Those of more than one line run across each line's glyphs. NULs alone span + // their advances, where the alignment puts them. + let cells = if nuls { + let start = aligned(first.by * k, 0.0, &t.h_align) - first.by * k; + cell_rect(start + first.reach.0 * k, start + first.reach.1 * k, 0.0, cell) + } else if one { + let x0 = if shows { along.0 } else { aligned(0.0, along.1, &t.h_align) }; + cell_rect(x0, x0 + along.1, laid.glyphs.first().map_or(0.0, |g| g.origin.y), cell) + } else { + cells(&laid, &s, cell, &t.h_align, shows && line.decorated) + }; + out.backs.extend(self.background(&line, cells, text.xf)); + } if shows { let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text))); n.opacity = opacity; @@ -778,13 +780,15 @@ impl Mapper { // start, which the alignment puts where it puts a line as long as its advances. A line // of leading NULs alone fills the cells across their advances. let start = aligned(lead.by, dx.iter().sum(), line.align); - let (mut lo, mut hi, mut pos) = (lead.reach.0 - lead.by, lead.reach.1 - lead.by, 0.0f64); - for (d, r) in dx.iter().zip(reach) { - (lo, hi) = (lo.min(pos + r.0), hi.max(pos + r.1)); - pos += d; + if line.background.is_some() { + let (mut lo, mut hi, mut pos) = (lead.reach.0 - lead.by, lead.reach.1 - lead.by, 0.0f64); + for (d, r) in dx.iter().zip(reach) { + (lo, hi) = (lo.min(pos + r.0), hi.max(pos + r.1)); + pos += d; + } + let xf = line.base * Affine::translate((0.0, line.drop + down)); + out.backs.extend(self.background(line, cell_rect(start + lo, start + hi, 0.0, line.cell), xf)); } - let xf = line.base * Affine::translate((0.0, line.drop + down)); - out.backs.extend(self.background(line, cell_rect(start + lo, start + hi, 0.0, line.cell), xf)); let blank = |cs: &[char]| cs.iter().all(|c| c.is_whitespace()); // A piece's type draws when it shows: blanks only when underlined or struck through. let draws = |cs: &[char]| line.shows && (!blank(cs) || line.decorated); @@ -956,9 +960,10 @@ fn cell_rect(x0: f64, x1: f64, y: f64, cell: (f64, f64)) -> BezPath { /// The character cells of `laid` (the type `s` laid out on more than one line), `cell.0` above /// and `cell.1` below each baseline (points), as one rectangle a line: across the line as layout /// places it and across its glyphs' advances, its trailing blanks included (layout leaves them -/// out of the width it aligns), or for a line of blanks alone as wide as their advances, where -/// `align` puts a line that long. -fn cells(laid: &vectorcraft_text::TextLayout, s: &str, cell: (f64, f64), align: &HAlign) -> BezPath { +/// out of the width it aligns). A line of blanks alone runs across its glyphs' advances when +/// the type draws its underline or strikethrough (`decorated`), and otherwise as wide as their +/// advances, where `align` puts a line that long. +fn cells(laid: &vectorcraft_text::TextLayout, s: &str, cell: (f64, f64), align: &HAlign, decorated: bool) -> BezPath { // Each line's baseline, the sum of its glyphs' advances, how far before and after the // reference point they reach, and whether they are all blanks. Glyphs come line by line. type Row = (usize, f64, f64, (f64, f64), bool); @@ -979,6 +984,7 @@ fn cells(laid: &vectorcraft_text::TextLayout, s: &str, cell: (f64, f64), align: for (line, y, width, reach, blank) in lines { let (x0, x1) = match laid.lines.get(line) { Some(l) if !blank => (l.x0.min(reach.0), l.x1.max(reach.1)), + _ if decorated => reach, _ => { let x0 = aligned(0.0, width, align); (x0, x0 + width) diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index f7937614d4..217b962dbe 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -1160,6 +1160,30 @@ fn opaque_backgrounds_reach_as_far_as_the_advances() { let first = layer[0].geometric_bounds().unwrap(); assert!((first.x0 - 10.0 * mm).abs() < 0.01 && (first.x1 - 30.0 * mm).abs() < 0.01, "{first:?}"); assert!(matches!(layer[1].kind, NodeKind::Path { .. }) && matches!(layer[2].kind, NodeKind::Text(_)), "{layer:?}"); + // An underlined line of blanks between two others draws its bar across its glyphs, and its + // cells run across the same glyphs. + let layer = opaque(font_of("Arial", true), "A\n \nB", &[]); + let (NodeKind::Path { path, .. }, NodeKind::Text(t)) = (&layer[0].kind, &layer[1].kind) else { panic!("a path and type") }; + let mut rects: Vec<(f64, f64, f64)> = Vec::new(); + for el in path.to_bezpath().elements() { + let p = match el { + vectorcraft_geom::PathEl::MoveTo(p) => { + rects.push((p.x, p.x, p.y)); + *p + } + vectorcraft_geom::PathEl::LineTo(p) => *p, + _ => continue, + }; + if let Some(r) = rects.last_mut() { + *r = (r.0.min(p.x), r.1.max(p.x), r.2.min(p.y)); + } + } + rects.sort_by(|a, b| a.2.total_cmp(&b.2)); + let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let spaces: Vec<(f64, f64)> = + laid.glyphs.iter().filter(|g| g.line == 1).map(|g| ((t.xf * g.origin).x, (t.xf * g.origin).x + g.advance)).collect(); + let (from, to) = spaces.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), (x0, x1)| (a.min(*x0), b.max(*x1))); + assert!(rects.len() == 3 && (rects[1].0 - from).abs() < 0.01 && (rects[1].1 - to).abs() < 0.01, "{rects:?} {spaces:?}"); // NULs whose advances go forward and back again still fill as far as they reach. let layer = opaque(arial(), "\0\0", &[1000, -1000]); assert_eq!(layer.len(), 1); From 5b25517dc12cb07a5f5d82472739a82870088178 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:59:19 -0800 Subject: [PATCH 5/6] Metafile import: one line's background reaches its furthest glyph edge A single line without advances now has its background from the nearest to the furthest edge its glyphs' advances reach, as a line of several does, instead of from the nearest edge on by the sum of the advances. --- crates/metafile/src/import/picture.rs | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 226ad0380e..1cfb3038cd 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -689,23 +689,28 @@ impl Mapper { text.xf = base * Affine::translate((0.0, drop)); text.cached_bounds = Some(laid.bounds); if background.is_some() { - // Where one line's glyphs start, and the sum of their advances, its trailing - // blanks included. - let along = laid - .glyphs - .iter() - .fold((f64::INFINITY, 0.0), |(from, width), g| (from.min(g.origin.x.min(g.origin.x + g.advance)), width + g.advance)); - let one = laid.lines.len() == 1 && along.0.is_finite() && along.1.is_finite(); - // The cells of one line run across its advances, from where its type starts, or - // for blanks alone, which draw no type, where the alignment puts a line that long. + // How far one line's glyphs reach each way, and the sum of their advances, its + // trailing blanks included. + let along = laid.glyphs.iter().fold((f64::INFINITY, f64::NEG_INFINITY, 0.0), |(from, to, width), g| { + let (a, b) = (g.origin.x, g.origin.x + g.advance); + (from.min(a.min(b)), to.max(a.max(b)), width + g.advance) + }); + let one = laid.lines.len() == 1 && along.0.is_finite() && along.1.is_finite() && along.2.is_finite(); + // The cells of one line run as far as its glyphs' advances reach, or for blanks + // alone, which draw no type, where the alignment puts a line that long. // Those of more than one line run across each line's glyphs. NULs alone span // their advances, where the alignment puts them. let cells = if nuls { let start = aligned(first.by * k, 0.0, &t.h_align) - first.by * k; cell_rect(start + first.reach.0 * k, start + first.reach.1 * k, 0.0, cell) } else if one { - let x0 = if shows { along.0 } else { aligned(0.0, along.1, &t.h_align) }; - cell_rect(x0, x0 + along.1, laid.glyphs.first().map_or(0.0, |g| g.origin.y), cell) + let (x0, x1) = if shows { + (along.0, along.1) + } else { + let x0 = aligned(0.0, along.2, &t.h_align); + (x0, x0 + along.2) + }; + cell_rect(x0, x1, laid.glyphs.first().map_or(0.0, |g| g.origin.y), cell) } else { cells(&laid, &s, cell, &t.h_align, shows && line.decorated) }; From abcb2a40b7adb7f8adc0b6ae742d296864b1ef21 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 23:36:30 +0700 Subject: [PATCH 6/6] xtask: pdf-deps expects the craft-libs pin main moved to in #8703 --- xtask/src/pdf_deps.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index e0877302a9..0b9653830a 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b"; +const REV: &str = "50b0ee7bf811e363b5f238382b5c77318cf33e46"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV),