diff --git a/crates/sketch/src/font_tests.rs b/crates/sketch/src/font_tests.rs index 11a45fa3c..8de9066d2 100644 --- a/crates/sketch/src/font_tests.rs +++ b/crates/sketch/src/font_tests.rs @@ -293,6 +293,33 @@ fn a_text_that_the_font_makes_too_large_is_refused() { std::fs::write(&path, font).unwrap(); assert_eq!(text_geometry_in(Some(&path), &"H".repeat(66), Vec2::ZERO, 5.0, 0.0).unwrap().len(), 66 * 300); assert!(matches!(text_geometry_in(Some(&path), &"H".repeat(67), Vec2::ZERO, 5.0, 0.0), Err(SketchError::TooLarge))); + // Too large to draw, not to measure: 67 times one H. + let font = font_data(Some(&path)).unwrap(); + let m = TextMetrics::new(&font, &TextStyle::default()).unwrap(); + let (one, all) = (m.line_width("H", 5.0).unwrap(), m.line_width(&"H".repeat(67), 5.0).unwrap()); + assert!(one > 0.0 && (all - 67.0 * one).abs() < 1e-12 * all, "{one} {all}"); +} + +#[test] +fn a_font_file_is_measured_by_its_own_tables() { + let folder = Folder::new("metrics"); + let font = font_data(Some(&folder.font())).unwrap(); + let m = TextMetrics::new(&font, &TextStyle::default()).unwrap(); + // Its H is 700 units tall, so at 7 mm a unit is 0.01 mm; ascender 800, descender -200 and no line gap put lines + // 10 mm apart; H, I and O advance 700, 200 and 900 units. + assert!((m.scale(7.0).unwrap() - 0.01).abs() < 1e-15); + assert!((m.line_pitch(7.0).unwrap() - 10.0).abs() < 1e-12); + assert!((m.line_width("HIO", 7.0).unwrap() - 18.0).abs() < 1e-12); + // It has neither an x nor a `?`: an x is left out, taking no room and drawing nothing, but it is named. + assert_eq!(m.line_width("HxI", 7.0).unwrap(), m.line_width("HI", 7.0).unwrap()); + assert_eq!(m.missing("xHx"), ['x', 'x']); + let draw = |text: &str| text_geometry_in(Some(&folder.font()), text, Vec2::ZERO, 7.0, 0.0).unwrap(); + assert_eq!(draw("HxI"), draw("HI")); + assert!(draw("xx").is_empty() && m.line_width("xx", 7.0).unwrap() == 0.0); + // A face the file does not have (it is no collection) is an error. + let mut elsewhere = font.clone(); + elsewhere.index = 1; + assert!(TextMetrics::new(&elsewhere, &TextStyle::default()).is_err()); } #[test] diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rs index 66ee6b015..c009dbf57 100644 --- a/crates/sketch/src/lib.rs +++ b/crates/sketch/src/lib.rs @@ -69,7 +69,7 @@ pub use solver::{ Analysis, CONSISTENT, DrivingValues, Hold, MAX_COMPONENT_VARS, SolveReport, SolveStatus, constraint_residual, determined_by, measure_dimension, move_line_towards, move_point_towards, solve, solve_after_edit, solve_after_value_edit, solve_holding, solve_with, }; -pub use text::{MAX_TEXT_CHARS, TextAlign, TextStyle, text_geometry, text_geometry_in, text_geometry_styled}; +pub use text::{MAX_TEXT_CHARS, TextAlign, TextMetrics, TextStyle, text_geometry, text_geometry_in, text_geometry_styled}; pub use thin::{MAX_THIN_SEGMENTS, thin_wall_regions}; pub use wire::{MAX_FIT_POINTS, MAX_WIRE_POINTS, Wire, WireSpace, fit_polyline}; diff --git a/crates/sketch/src/text.rs b/crates/sketch/src/text.rs index 5e218294e..7327fb680 100644 --- a/crates/sketch/src/text.rs +++ b/crates/sketch/src/text.rs @@ -4,12 +4,13 @@ //! holes of A, B, 8…) are loops inside its outline; profile detection makes them holes. //! //! The default font is embedded (Liberation Sans, SIL OFL 1.1; see `assets/fonts/liberation-sans/OFL.txt` and -//! ATTRIBUTION.md); [`crate::fonts`] finds others by file path or installed family name. +//! ATTRIBUTION.md); [`crate::fonts`] finds others by file path or installed family name. [`TextMetrics`] measures +//! text by the rule that draws it. use serde::{Deserialize, Serialize}; use solidcraft_geom::{Ring, Vec2}; -use crate::fonts::font_data_styled; +use crate::fonts::{FontData, font_data_styled}; use crate::link::{LinkGeom, LinkKind, LinkSource, MAX_LINK_ENTITIES}; use crate::model::{Result, Sketch, SketchError}; @@ -160,6 +161,99 @@ const SLANT_DEG: f64 = 12.0; const MAX_LETTER_SPACING: f64 = 1e5; const LINE_SPACING_RANGE: (f64, f64) = (0.05, 100.0); +/// A capital height (mm) text can be set at: finite, above a micrometre and below a kilometre. +fn check_height(height: f64) -> Result<()> { + if height.is_finite() && height > 1e-6 && height < 1e6 { Ok(()) } else { Err(SketchError::Invalid("text height must be positive".into())) } +} + +/// A style's spacing: a finite letter spacing of at most [`MAX_LETTER_SPACING`] either way, and a line spacing in +/// [`LINE_SPACING_RANGE`]. +fn check_spacing(style: &TextStyle) -> Result<()> { + if !(style.letter_spacing.is_finite() && style.letter_spacing.abs() <= MAX_LETTER_SPACING) { + return Err(SketchError::Invalid("the letter spacing must be a finite length".into())); + } + if !(style.line_spacing.is_finite() && (LINE_SPACING_RANGE.0..=LINE_SPACING_RANGE.1).contains(&style.line_spacing)) { + return Err(SketchError::Invalid(format!( + "the line spacing must be between {} and {} times the font's", + LINE_SPACING_RANGE.0, LINE_SPACING_RANGE.1 + ))); + } + Ok(()) +} + +/// How a font sets text in a style, read once from its face: the scale for a capital height, the distance between +/// lines, the width of a line and the characters the font has no glyph for. Sketch text is laid out with it, so a +/// line measures what it draws. Kerning stays off, as in sketch text. +pub struct TextMetrics<'a> { + face: ttf_parser::Face<'a>, + /// The capital height, in font units. + cap: f64, + /// The distance between baselines in font units: ascender to descender, plus the line gap (none when not positive). + pitch: f64, + /// What a character the font lacks is set as: its `?`, when it has one. + fallback: Option, + letter_spacing: f64, + line_spacing: f64, +} + +impl<'a> TextMetrics<'a> { + /// The face of `font` set in `style`: its letter and line spacing (its bold and italic chose the face). + pub fn new(font: &'a FontData, style: &TextStyle) -> Result> { + check_spacing(style)?; + let face = ttf_parser::Face::parse(font.bytes(), font.index).map_err(|e| SketchError::Invalid(format!("font: {e}")))?; + Ok(TextMetrics { + cap: cap_height(&face), + pitch: f64::from(face.ascender()) - f64::from(face.descender()) + f64::from(face.line_gap()), + fallback: face.glyph_index('?'), + letter_spacing: style.letter_spacing, + line_spacing: style.line_spacing, + face, + }) + } + + /// Millimetres per font unit at a capital height of `height` mm. + pub fn scale(&self, height: f64) -> Result { + check_height(height)?; + Ok(height / self.cap) + } + + /// The distance between baselines (mm) at a capital height of `height` mm: the font's own (one and a half heights + /// when it gives none) times the line spacing. + pub fn line_pitch(&self, height: f64) -> Result { + let k = self.scale(height)?; + let own = if self.pitch > 0.0 { self.pitch * k } else { height * 1.5 }; + Ok(own * self.line_spacing) + } + + /// The width (mm) of one line at a capital height of `height` mm, as it is drawn: from its first glyph's origin to + /// the end of its last glyph's advance. A line break in it is a character like any other. + pub fn line_width(&self, line: &str, height: f64) -> Result { + let k = self.scale(height)?; + Ok(self.glyphs(line, k).last().map(|(_, x, advance)| x + advance).unwrap_or(0.0)) + } + + /// The characters of one line the font has no glyph for, in order and each time they come: those its character map + /// lacks (set as its `?`, or left out when it has none) and those it sends to its missing-glyph box (`.notdef`, drawn + /// as it is). + pub fn missing(&self, line: &str) -> Vec { + line.chars().filter(|ch| self.face.glyph_index(*ch).is_none_or(|g| g.0 == 0)).collect() + } + + /// The one rule that lays out a line, at `k` mm per font unit: each glyph, where its origin is along the line and + /// its advance. No kerning; a character the font lacks is set as its `?` (left out when it has none either); the + /// letter spacing goes between glyphs, not after the last. + fn glyphs(&self, line: &str, k: f64) -> impl Iterator { + let mut pen = 0.0f64; + line.chars().filter_map(move |ch| { + let gid = self.face.glyph_index(ch).or(self.fallback)?; + let advance = f64::from(self.face.glyph_hor_advance(gid).unwrap_or(0)) * k; + let x = pen; + pen += advance + self.letter_spacing; + Some((gid, x, advance)) + }) + } +} + /// Outline geometry of `text` in the built-in font (see [`text_geometry_in`]). pub fn text_geometry(text: &str, at: Vec2, height: f64, angle: f64) -> Result> { text_geometry_in(None, text, at, height, angle) @@ -187,52 +281,28 @@ pub fn text_geometry_styled( if text.chars().count() > MAX_TEXT_CHARS { return Err(SketchError::TooLarge); } - if !(height.is_finite() && height > 1e-6 && height < 1e6 && angle.is_finite() && at.is_finite()) { - return Err(SketchError::Invalid("text height must be positive".into())); - } - if !(style.letter_spacing.is_finite() && style.letter_spacing.abs() <= MAX_LETTER_SPACING) { - return Err(SketchError::Invalid("the letter spacing must be a finite length".into())); - } - if !(style.line_spacing.is_finite() && (LINE_SPACING_RANGE.0..=LINE_SPACING_RANGE.1).contains(&style.line_spacing)) { - return Err(SketchError::Invalid(format!( - "the line spacing must be between {} and {} times the font's", - LINE_SPACING_RANGE.0, LINE_SPACING_RANGE.1 - ))); + // The numbers first: finding an installed font can mean reading its folders. + check_height(height)?; + if !(angle.is_finite() && at.is_finite()) { + return Err(SketchError::Invalid("the text's place and angle must be finite".into())); } + check_spacing(style)?; let (data, slant) = font_data_styled(font, style.bold, style.italic)?; - let face = ttf_parser::Face::parse(data.bytes(), data.index).map_err(|e| SketchError::Invalid(format!("font: {e}")))?; - let k = height / cap_height(&face); - let line_gap = f64::from(face.ascender()) - f64::from(face.descender()) + f64::from(face.line_gap()); - let line_gap = if line_gap > 0.0 { line_gap * k } else { height * 1.5 } * style.line_spacing; + let metrics = TextMetrics::new(&data, style)?; + let (k, pitch) = (metrics.scale(height)?, metrics.line_pitch(height)?); let shear = if slant { SLANT_DEG.to_radians().tan() } else { 0.0 }; - // Each line's glyphs (glyph, where its origin is along the line, its advance) and width. - let lines: Vec<(Vec<(ttf_parser::GlyphId, f64, f64)>, f64)> = text - .split('\n') - .map(|line| { - let mut pen = 0.0f64; - let mut glyphs = Vec::new(); - for ch in line.chars() { - let Some(gid) = face.glyph_index(ch).or_else(|| face.glyph_index('?')) else { continue }; - let advance = f64::from(face.glyph_hor_advance(gid).unwrap_or(0)) * k; - glyphs.push((gid, pen, advance)); - pen += advance + style.letter_spacing; - } - let width = glyphs.last().map(|(_, x, advance)| x + advance).unwrap_or(0.0); - (glyphs, width) - }) - .collect(); let along = path.map(|pts| Path::new(pts, style.reverse)).transpose()?; let anchor = along.as_ref().map(|p| p.anchor(style.align)).unwrap_or(0.0); let (sin, cos) = angle.sin_cos(); let mut out = Vec::new(); - for (row, (glyphs, width)) in lines.iter().enumerate() { - let base_y = -(row as f64) * line_gap; + for (row, line) in text.split('\n').enumerate() { + let base_y = -(row as f64) * pitch; let start = match style.align { TextAlign::Left => 0.0, - TextAlign::Center => -width / 2.0, - TextAlign::Right => -width, + TextAlign::Center => -metrics.line_width(line, height)? / 2.0, + TextAlign::Right => -metrics.line_width(line, height)?, }; - for &(gid, x, advance) in glyphs { + for (gid, x, advance) in metrics.glyphs(line, k) { // The glyph's frame: its origin on the baseline and the way the baseline runs. let (origin, dir) = match &along { None => { @@ -250,7 +320,7 @@ pub fn text_geometry_styled( origin + dir * (gx + gy * shear) + up * gy }); let mut ob = Outline { out: Vec::new(), start: origin, cur: origin, map }; - let _ = face.outline_glyph(gid, &mut ob); + let _ = metrics.face.outline_glyph(gid, &mut ob); out.extend(ob.out); // A font can give a glyph any number of points: stop where the link would be refused anyway. if out.len() > MAX_LINK_ENTITIES { diff --git a/crates/sketch/src/text_style_tests.rs b/crates/sketch/src/text_style_tests.rs index e4dc2d259..14b9431dd 100644 --- a/crates/sketch/src/text_style_tests.rs +++ b/crates/sketch/src/text_style_tests.rs @@ -1,10 +1,10 @@ //! Text styles: alignment, letter and line spacing, a made-up italic, a bold the font lacks, and -//! text that follows a curve of its sketch. +//! text that follows a curve of its sketch; and text measured (`TextMetrics`) by the rule that draws it. use solidcraft_geom::Vec2; use super::*; -use crate::{CurveKind, Sketch}; +use crate::{CurveKind, Sketch, font_data}; fn v(x: f64, y: f64) -> Vec2 { Vec2::new(x, y) @@ -187,6 +187,45 @@ fn a_style_is_saved_only_when_it_is_not_plain_and_reads_back() { assert_eq!(serde_json::from_value::(old).unwrap(), plain); } +/// What pins an outline exactly: how many pieces it has, its first and last point, and the sum of all its points. +fn pin(g: &[LinkGeom]) -> (usize, Vec2, Vec2, Vec2) { + let pts = points(g); + let sum = pts.iter().fold(Vec2::ZERO, |s, p| s + *p); + (g.len(), pts.first().copied().unwrap_or_default(), pts.last().copied().unwrap_or_default(), sum) +} + +#[test] +fn the_outlines_of_styled_texts_stay_exactly_as_they_were() { + // Pinned before `TextMetrics` took over the layout (#4813): curves and a descender; spacing, a blank line, a made-up + // italic and an angle; a path; glyphs the font lacks (`?`, and U+FFFF, which its character map sends to `.notdef`); + // line breaks at both ends. + let arc: Vec = (0..=90).map(|i| v(40.0 * f64::from(i).to_radians().cos(), 40.0 * f64::from(i).to_radians().sin())).collect(); + let spaced = TextStyle { italic: true, align: TextAlign::Center, letter_spacing: 0.75, line_spacing: 1.5, ..TextStyle::default() }; + let on_arc = TextStyle { align: TextAlign::Right, path: Some("arc".into()), ..TextStyle::default() }; + let missing = TextStyle { align: TextAlign::Right, letter_spacing: -0.5, ..TextStyle::default() }; + let cases: [(&str, Vec2, f64, f64, &TextStyle, Option<&[Vec2]>); 5] = [ + ("Hg", v(5.0, -3.0), 10.0, 0.0, &TextStyle::default(), None), + ("Ab\n\nC", v(1.0, 2.0), 7.0, 0.3, &spaced, None), + ("Hi", Vec2::ZERO, 5.0, 0.0, &on_arc, Some(&arc)), + ("x\u{5b57}y\u{ffff}", v(-2.0, 0.5), 4.0, -1.0, &missing, None), + ("\nH\n", Vec2::ZERO, 3.5, 0.0, &TextStyle::default(), None), + ]; + let pins: Vec<_> = cases + .iter() + .map(|(text, at, height, angle, style, path)| pin(&text_geometry_styled(None, text, *at, *height, *angle, style, *path).unwrap())) + .collect(); + assert_eq!( + pins, + [ + (45, v(12.955997161107167, -3.0), v(21.330731014904188, 0.8396025550035482), v(2070.968772178849, 45.508161816891416)), + (58, v(0.235951166654778, 1.7636519993743809), v(11.036554267036463, -25.010425523555526), v(777.6105726380807, -898.3264755185471)), + (20, v(39.918286168688034, 2.884686538489657), v(39.984307910534746, 1.1283251324010486), v(1709.968158829435, 122.02595165962421)), + (66, v(-7.205346806960301, 8.606847326667703), v(-0.7406630833657615, 5.5426375007981274), v(-709.3625374614094, 1175.3199400202661)), + (12, v(2.784599006387509, -5.849893541518807), v(2.784599006387509, -5.849893541518807), v(44.11639460610361, -97.83108587650818)), + ] + ); +} + #[test] fn on_a_closed_curve_left_alignment_starts_at_the_top() { let r = 30.0; @@ -195,3 +234,154 @@ fn on_a_closed_curve_left_alignment_starts_at_the_top() { // It runs clockwise from the top: to the right of it, coming down. assert!(lo.x > -1.0 && hi.x > 10.0 && hi.y > r, "{lo:?} {hi:?}"); } + +/// The built-in font, Liberation Sans, as its own tables give it: 2048 units per em, a capital height of 1409 units, +/// ascender 1854, descender -434 and line gap 67 (2355 units from baseline to baseline); `0` and `?` advance 1139 +/// units, `H` 1479, `A` and `V` 1366. At a capital height of 1409 mm a unit is a millimetre. +const CAP: f64 = 1409.0; + +#[test] +fn text_is_measured_by_the_fonts_own_tables() { + let font = font_data(None).unwrap(); + let m = TextMetrics::new(&font, &TextStyle::default()).unwrap(); + assert_eq!((m.scale(CAP).unwrap(), m.line_pitch(CAP).unwrap()), (1.0, 2355.0)); + assert_eq!((m.line_width("0", CAP).unwrap(), m.line_width("H0", CAP).unwrap()), (1139.0, 1479.0 + 1139.0)); + assert_eq!(m.line_width("", CAP).unwrap(), 0.0); + // No kerning: the font's own pair for A and V (152 units closer) is not used, in measured or drawn text. + assert_eq!(m.line_width("AV", CAP).unwrap(), 2.0 * 1366.0); + // At 3.5 mm, a parts list's text: 5.850 mm between lines, 2.829 mm a digit. + assert!((m.line_pitch(3.5).unwrap() - 5.850).abs() < 5e-4 && (m.line_width("0", 3.5).unwrap() - 2.829).abs() < 5e-4); +} + +#[test] +fn letter_spacing_goes_between_letters_only_and_line_spacing_scales_the_pitch() { + let font = font_data(None).unwrap(); + let spaced = TextMetrics::new(&font, &TextStyle { letter_spacing: 2.5, line_spacing: 1.5, ..TextStyle::default() }).unwrap(); + // One letter has no gap, three have two. + assert_eq!(spaced.line_width("0", CAP).unwrap(), 1139.0); + assert_eq!(spaced.line_width("000", CAP).unwrap(), 3.0 * 1139.0 + 2.0 * 2.5); + assert_eq!(spaced.line_pitch(CAP).unwrap(), 1.5 * 2355.0); + // Closer than the letters are wide, each starts left of the one before and the line measures less than nothing. + let tight = TextMetrics::new(&font, &TextStyle { letter_spacing: -2000.0, ..TextStyle::default() }).unwrap(); + assert_eq!(tight.line_width("000", CAP).unwrap(), 3.0 * 1139.0 - 2.0 * 2000.0); +} + +#[test] +fn the_characters_a_font_lacks_are_named_in_order_each_time() { + let font = font_data(None).unwrap(); + let m = TextMetrics::new(&font, &TextStyle::default()).unwrap(); + // It has no 字, tab or emoji; its character map sends U+FFFF to its missing-glyph box. + assert_eq!(m.missing("a\u{5b57}b\t\u{5b57}\u{ffff}\u{1f600}c"), ['\u{5b57}', '\t', '\u{5b57}', '\u{ffff}', '\u{1f600}']); + assert!(m.missing("").is_empty() && m.missing("Hello, w\u{f6}rld \u{20ac} 0?").is_empty()); + // Only characters it lacks: each is set, drawn and measured as `?`, which is why they are named. + assert_eq!(m.line_width("\u{5b57}\u{5b57}", CAP).unwrap(), 2.0 * 1139.0); + assert_eq!(styled("\u{5b57}", &TextStyle::default(), None), styled("?", &TextStyle::default(), None)); + // The box is drawn and measured as it is (1536 units), as before. + assert_eq!(m.line_width("\u{ffff}", CAP).unwrap(), 1536.0); +} + +#[test] +fn a_line_too_long_to_draw_is_still_measured() { + // A hundred times the characters a text may have, in one pass. + let font = font_data(None).unwrap(); + let m = TextMetrics::new(&font, &TextStyle::default()).unwrap(); + let long = "0".repeat(100 * MAX_TEXT_CHARS); + assert!(matches!(text_geometry(&long, Vec2::ZERO, 1.0, 0.0), Err(SketchError::TooLarge))); + assert_eq!(m.line_width(&long, CAP).unwrap(), 100_000.0 * 1139.0); + assert!(m.missing(&long).is_empty()); +} + +#[test] +fn line_breaks_at_the_ends_are_empty_lines() { + let font = font_data(None).unwrap(); + let m = TextMetrics::new(&font, &TextStyle::default()).unwrap(); + // Three lines: the H stands on the second baseline, one measured pitch below the first. + assert_eq!(extent(&styled("\nH\n", &TextStyle::default(), None)).0.y, -m.line_pitch(10.0).unwrap()); + assert!(styled("\n", &TextStyle::default(), None).is_empty()); +} + +#[test] +fn sizes_and_spacings_a_text_refuses_are_refused_by_its_measure() { + let font = font_data(None).unwrap(); + let m = TextMetrics::new(&font, &TextStyle::default()).unwrap(); + // A capital height above a micrometre and below a kilometre. + for h in [0.0, -1.0, 1e-6, 1e6, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert!(m.scale(h).is_err() && m.line_pitch(h).is_err() && m.line_width("H", h).is_err(), "{h}"); + assert!(text_geometry("H", Vec2::ZERO, h, 0.0).is_err(), "{h}"); + } + for h in [2e-6, 999_999.0] { + let width = m.line_width(&"W".repeat(MAX_TEXT_CHARS), h).unwrap(); + assert!(width.is_finite() && width > 0.0 && m.line_pitch(h).unwrap().is_finite(), "{h}"); + } + // The spacing a text accepts, at its bounds and just past them. + for (letter_spacing, line_spacing, ok) in [ + (MAX_LETTER_SPACING, LINE_SPACING_RANGE.0, true), + (-MAX_LETTER_SPACING, LINE_SPACING_RANGE.1, true), + (MAX_LETTER_SPACING * (1.0 + 1e-12), 1.0, false), + (f64::NAN, 1.0, false), + (0.0, LINE_SPACING_RANGE.0 * (1.0 - 1e-12), false), + (0.0, LINE_SPACING_RANGE.1 * (1.0 + 1e-12), false), + (0.0, f64::INFINITY, false), + ] { + let style = TextStyle { letter_spacing, line_spacing, ..TextStyle::default() }; + assert_eq!(TextMetrics::new(&font, &style).is_ok(), ok, "{style:?}"); + assert_eq!(text_geometry_styled(None, "H", Vec2::ZERO, 10.0, 0.0, &style, None).is_ok(), ok, "{style:?}"); + } +} + +#[test] +fn a_line_measures_what_it_draws() { + // Right-aligned, a line ends at the anchor: its outline is the left-aligned one moved back by its measured width + // (centred, by half of it). The next line stands one measured pitch below. + for style in [TextStyle::default(), TextStyle { italic: true, letter_spacing: -0.4, line_spacing: 1.3, ..TextStyle::default() }] { + let (font, _) = font_data_styled(None, style.bold, style.italic).unwrap(); + let m = TextMetrics::new(&font, &style).unwrap(); + for line in ["Hg", "W i d e ", "x\u{5b57}y\u{ffff}?", "0"] { + let width = m.line_width(line, 10.0).unwrap(); + let left = points(&styled(line, &style, None)); + for (align, by) in [(TextAlign::Center, -width / 2.0), (TextAlign::Right, -width)] { + let moved = points(&styled(line, &TextStyle { align, ..style.clone() }, None)); + let same = moved.len() == left.len() && left.iter().zip(&moved).all(|(p, q)| (*p + v(by, 0.0)).dist(*q) < 1e-9); + assert!(same, "{line:?} {align:?} {style:?}"); + } + } + let two = points(&styled("Hg\nHg", &style, None)); + let (first, second) = two.split_at(two.len() / 2); + let pitch = m.line_pitch(10.0).unwrap(); + assert!(first.iter().zip(second).all(|(p, q)| (*p - v(0.0, pitch)).dist(*q) < 1e-9), "{style:?}"); + } +} + +#[test] +fn hostile_lines_are_measured_as_they_are_drawn_or_refused_alike() { + // Characters the font has and lacks (字, a tab, U+FFFF, an emoji, NUL, a carriage return), a lone combining accent, + // sizes and spacings at and past their bounds: never a panic, the measure refuses what the text refuses, and what + // it measures is what is drawn. + let chars = ['H', 'g', ' ', '?', '\u{e9}', '\u{301}', '\u{5b57}', '\t', '\u{ffff}', '\u{1f600}', '\0', '\r']; + let lacks = ['\u{5b57}', '\t', '\u{ffff}', '\u{1f600}', '\0', '\r']; + let heights = [0.0, -1.0, 1e-6, 2e-6, 0.5, 10.0, 999_999.0, 1e6, f64::NAN, f64::INFINITY]; + let letter = [0.0, -0.5, 3.0, -1e5, 1e5, 1.5e5, f64::NAN]; + let lines = [1.0, 0.05, 100.0, 0.04, 101.0, f64::INFINITY]; + let mut rnd = crate::tests::Lcg(4813); + let mut pick = |n: usize| ((rnd.next() * n as f64) as usize).min(n - 1); + let font = font_data(None).unwrap(); + for _ in 0..1000 { + let line: String = (0..pick(10)).map(|_| chars[pick(chars.len())]).collect(); + let height = heights[pick(heights.len())]; + let style = TextStyle { letter_spacing: letter[pick(letter.len())], line_spacing: lines[pick(lines.len())], ..TextStyle::default() }; + let measured = TextMetrics::new(&font, &style).and_then(|m| Ok((m.line_width(&line, height)?, m.line_pitch(height)?, m.missing(&line)))); + let right_aligned = TextStyle { align: TextAlign::Right, ..style.clone() }; + let drawn = [&style, &right_aligned].map(|s| text_geometry_styled(None, &line, Vec2::ZERO, height, 0.0, s, None)); + let (Ok((width, pitch, missing)), [Ok(left), Ok(right)]) = (&measured, &drawn) else { + assert!(measured.is_err() && drawn.iter().all(|d| d.is_err()), "{line:?} {height} {style:?}"); + continue; + }; + assert!(width.is_finite() && pitch.is_finite() && *pitch > 0.0, "{line:?} {height} {style:?}"); + assert_eq!(*missing, line.chars().filter(|c| lacks.contains(c)).collect::>()); + let (left, right, tol) = (points(left), points(right), 1e-12 * (1.0 + width.abs() + 2.0 * height)); + assert!( + left.len() == right.len() && left.iter().zip(&right).all(|(p, q)| (*p - v(*width, 0.0)).dist(*q) <= tol), + "{line:?} {height} {style:?}" + ); + } +}