diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 125126790c..1cfb3038cd 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -16,7 +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. +//! 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. //! @@ -541,22 +545,38 @@ impl Mapper { // one for every character: a NUL's advance goes to the character before it, or moves the // 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, 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 the advance of the NULs + // that move the start, with how far they reach. + let mut reach = Vec::new(); + let mut lead = Lead::default(); 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))); + } 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 { - 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(); + lead = Lead::default(); } - if s.trim().is_empty() || t.color[3] == 0 { + // 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.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 +633,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 +668,65 @@ 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; + let laid = vectorcraft_text::layout(db, &text); 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; + text.cached_bounds = Some(laid.bounds); + if background.is_some() { + // 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, 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) + }; + 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 +736,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); + let top = laid.lines.first().map_or(0.0, |l| l.baseline); for (n, l) in laid.lines.iter().enumerate() { let (from, to) = (count(l.start), count(l.end)); - let (Some(cs), Some(dx)) = (chars.get(from..to), dx.get(from..to)) else { continue }; + let (Some(cs), Some(dx), Some(reach)) = (chars.get(from..to), dx.get(from..to), reach.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 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); } } 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; + // 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. A line + // of leading NULs alone fills the cells across their advances. + let start = aligned(lead.by, dx.iter().sum(), line.align); + 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 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 chars.is_empty() || !draws(chars) { return; } let db = vectorcraft_text::FontDb::global(); @@ -684,13 +808,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 +839,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 +909,95 @@ 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 and across its glyphs' advances, its trailing blanks included (layout leaves them +/// 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); + 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, 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, (from, to), blank)), + } + } + let mut bp = BezPath::new(); + 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) + } + }; + 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..217b962dbe 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,156 @@ 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:?}"); +} + +#[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, 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, "{xs:?} {end}"); + assert!((b.x0 - xs[0]).abs() < 0.01 && (b.x1 - end).abs() < 0.01, "{b:?} {xs:?} {end}"); + // 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 - 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:?}"); + // 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); + 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()); + // 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])); + 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 +1380,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 +1439,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 +1451,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 +1462,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 725ba6be20..5fc676b778 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10032,7 +10032,11 @@ 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. 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. 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0add221a0d..a8e5bf9537 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2293,6 +2293,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`).