Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/sketch/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ pub use model::{
pub use nurbs::Nurbs;
pub use offset::OffsetChain;
pub use offset_topology::{OffsetCreated, OffsetRole, OffsetRoleFlags, OffsetRoleKind, OffsetTopology};
pub use paper_text::{paper_fallback_notes, paper_font_note, paper_text, paper_text_in, paper_text_now};
pub use paper_text::{PaperLines, paper_fallback_notes, paper_font_note, paper_lines, paper_lines_in, paper_text, paper_text_in, paper_text_now};
pub use pattern::{PatternAlignment, PatternInstance, SketchPattern, SketchPatternKind};
pub use periodic::periodic_beziers;
pub use profiles::{
Expand Down
151 changes: 127 additions & 24 deletions crates/sketch/src/paper_text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,10 @@
//! - The browser has no font folders: there the web covers Arabic, Chinese, Japanese and Korean, a
//! font each ([`fallback`]). Text is refused with [`SketchError::FontPending`], whichever way it's
//! asked for, until each font it asked the web app for has come or failed.
//! - Lines break at `\n`, a line pitch apart, and are aligned as sketch text's are. A line with
//! right-to-left characters is a run per direction, shaped. Every run of a line starts where the
//! line does, its glyphs placed along the whole line.
//! - Lines break at `\n` (and between words, to a width: [`paper_lines`]), a line pitch apart,
//! and are aligned as sketch text's are. A line with right-to-left characters is a run per
//! direction, shaped. Every run of a line starts where the line does, its glyphs placed along the
//! whole line. A text is measured once ([`PaperLines`]) and set from what was measured.

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::{Path, PathBuf};
Expand Down Expand Up @@ -117,17 +118,96 @@ fn set_text(
style: &TextStyle,
wait: bool,
) -> Result<Option<(Vec<TextRun>, Vec<Font>)>> {
measure(dirs, text, family, language, height, None, style, wait)?.set(at, angle)
}

/// A text measured for paper: the lines it is set in, each with its width (mm), and the distance
/// between their baselines, with its runs and fonts, so [`PaperLines::set`] only places them.
#[derive(Clone)]
pub struct PaperLines {
/// Each line's text and its width (mm), top to bottom.
pub lines: Vec<(String, f64)>,
/// The distance between two lines' baselines (mm).
pub pitch: f64,
/// Each run with its line's start along and down from the first line's (mm, before turning).
runs: Vec<((f64, f64), TextRun)>,
/// Each font once, in order of id, holding the glyphs its runs place.
fonts: Vec<Font>,
}

impl std::fmt::Debug for PaperLines {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PaperLines").field("lines", &self.lines).field("pitch", &self.pitch).finish_non_exhaustive()
}
}

impl PaperLines {
/// The lines on paper, the first line's baseline starting at `at` (sheet mm) and turned `angle`
/// radians about it, each aligned on it as the style said: their runs, and the fonts they use
/// (each once, in order of id, holding the glyphs its runs place); None when they set no glyph
/// (empty lines only).
pub fn set(&self, at: Vec2, angle: f64) -> Result<Option<(Vec<TextRun>, Vec<Font>)>> {
if !(angle.is_finite() && at.is_finite()) {
return Err(SketchError::Invalid("the text's place and angle must be finite".into()));
}
if self.runs.is_empty() {
return Ok(None);
}
let (sin, cos) = angle.sin_cos();
let place = |((along, down), run): &((f64, f64), TextRun)| TextRun {
origin: at + Vec2::new(along * cos + down * sin, along * sin - down * cos),
angle,
..run.clone()
};
Ok(Some((self.runs.iter().map(place).collect(), self.fonts.clone())))
}
}

/// `text` measured for paper in the font `family` (None or empty: the built-in font, as
/// [`paper_text`] chooses), in the drawing's `language`, at a capital height of `height` mm, set in
/// `style` (which follows no path on paper): broken at each line break, and with `wrap` (a width,
/// mm) also between words, each line holding as many of its words as fit. Words are the text
/// between spaces, put back one space apart on a wrapped line. A word is never cut, so a line of
/// one word may be wider than `wrap`. Fonts to fall back to are searched for here.
pub fn paper_lines(text: &str, family: Option<&str>, language: &str, height: f64, wrap: Option<f64>, style: &TextStyle) -> Result<PaperLines> {
paper_lines_in(&font_dirs(), text, family, language, height, wrap, style)
}

/// [`paper_lines`] with the fonts installed in `dirs`.
pub fn paper_lines_in(
dirs: &[PathBuf],
text: &str,
family: Option<&str>,
language: &str,
height: f64,
wrap: Option<f64>,
style: &TextStyle,
) -> Result<PaperLines> {
measure(dirs, text, family, language, height, wrap, style, true)
}

#[allow(clippy::too_many_arguments)]
fn measure(
dirs: &[PathBuf],
text: &str,
family: Option<&str>,
language: &str,
height: f64,
wrap: Option<f64>,
style: &TextStyle,
wait: bool,
) -> Result<PaperLines> {
if text.chars().count() > MAX_TEXT_CHARS {
return Err(SketchError::TooLarge);
}
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)?;
if style.path.is_some() {
return Err(SketchError::Invalid("text on paper follows no path".into()));
}
if wrap.is_some_and(|w| !w.is_finite()) {
return Err(SketchError::Invalid("a width to wrap text to must be finite".into()));
}
let (data, font, family) = paper_face(dirs, family, style.bold, style.italic)?;
let metrics = TextMetrics::new(&data, style)?;
let (k, pitch) = (metrics.scale(height)?, metrics.line_pitch(height)?);
Expand All @@ -141,30 +221,52 @@ fn set_text(
// Every font takes the same em size.
let own_em = f64::from(records[0].units_per_em);
let scales: Vec<f64> = records.iter().map(|font| k * own_em / f64::from(font.units_per_em)).collect();
let (sin, cos) = angle.sin_cos();
let lean = SLANT_DEG.to_radians().tan();
let mut placed: Vec<(usize, TextRun)> = Vec::new();
for (row, line) in text.split('\n').enumerate() {
let laid = if metrics.missing(line).is_empty() {
metrics.laid_out(line, k)
let lay = |line: &str| {
if metrics.missing(line).is_empty() {
Ok(metrics.laid_out(line, k))
} else {
mixed_line(line, &faces, &found, &scales, language, &family, dirs.is_empty())?
mixed_line(line, &faces, &found, &scales, language, &family, dirs.is_empty())
}
};
let mut laid: Vec<(String, LaidLine)> = Vec::new();
for paragraph in text.split('\n') {
let Some(wrap) = wrap else {
laid.push((paragraph.to_string(), lay(paragraph)?));
continue;
};
let mut words = paragraph.split(' ').filter(|w| !w.is_empty());
let Some(first) = words.next() else {
laid.push((String::new(), lay("")?));
continue;
};
let mut line = (first.to_string(), lay(first)?);
for word in words {
let longer = format!("{} {word}", line.0);
let wider = lay(&longer)?;
if wider.width <= wrap {
line = (longer, wider);
} else {
laid.push(std::mem::replace(&mut line, (word.to_string(), lay(word)?)));
}
}
laid.push(line);
}
let lean = SLANT_DEG.to_radians().tan();
let mut placed: Vec<(usize, (f64, f64), TextRun)> = Vec::new();
for (row, (line, laid)) in laid.iter().enumerate() {
// The line's start: along the baseline by its alignment, then down a pitch a row.
let (along, down) = (style.align.start(laid.width), row as f64 * pitch);
let origin = at + Vec2::new(along * cos + down * sin, along * sin - down * cos);
let start = (style.align.start(laid.width), row as f64 * pitch);
for run in laid.runs.iter().filter(|run| !run.glyphs.is_empty()) {
let (glyphs, text, clusters) = run_records(&laid, run, line)?;
let (glyphs, text, clusters) = run_records(laid, run, line)?;
let record = records.get(run.face).ok_or_else(|| SketchError::Invalid("a run in a font it wasn't given".into()))?;
let slant = if style.italic && !record.metrics.flags.italic { lean } else { 0.0 };
let run_record = TextRun { font: record.id, scale: scales[run.face], origin, angle, slant, glyphs, text, clusters, rtl: run.rtl };
placed.push((run.face, run_record));
// Placed by `PaperLines::set`.
let origin = Vec2::new(0.0, 0.0);
let run_record = TextRun { font: record.id, scale: scales[run.face], origin, angle: 0.0, slant, glyphs, text, clusters, rtl: run.rtl };
placed.push((run.face, start, run_record));
}
}
if placed.is_empty() {
return Ok(None);
}
for (face, run) in &placed {
for (face, _, run) in &placed {
let (record, metrics) = (&mut records[*face], faces[*face]);
for g in &run.glyphs {
let id = ttf_parser::GlyphId(g.id);
Expand All @@ -176,8 +278,9 @@ fn set_text(
for record in records.into_iter().filter(|record| !record.glyphs.is_empty()) {
fonts.entry(record.id).or_insert(record);
}
let runs = placed.into_iter().map(|(_, run)| run).collect();
Ok(Some((runs, fonts.into_values().collect())))
let lines = laid.iter().map(|(line, laid)| (line.clone(), laid.width)).collect();
let runs = placed.into_iter().map(|(_, start, run)| (start, run)).collect();
Ok(PaperLines { lines, pitch, runs, fonts: fonts.into_values().collect() })
}

/// The fonts `lacking` falls back to, each with its record, and the font (by its place among
Expand Down
120 changes: 120 additions & 0 deletions crates/sketch/src/paper_text_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -922,6 +922,126 @@ fn hostile_numbers_and_sizes_are_refused() {
assert!(paper_text("A", None, "", AT, 5.0, 0.0, &TextStyle { letter_spacing: f64::NAN, ..TextStyle::default() }).is_err());
}

/// The marks dimensions and tolerances write that the built-in font has are set as its own glyphs,
/// never its missing-glyph box: Ø ° ± ′ ″ × ≤ ≥ (#4890 B3b).
#[test]
fn dimension_marks_are_the_built_in_fonts_own_glyphs() {
let (runs, font) = set("\u{d8}12 30\u{b0} \u{b1}0.1 5\u{2032} 7\u{2033} 2\u{d7} \u{2264} \u{2265}", &TextStyle::default());
assert!(runs.iter().flat_map(|r| &r.glyphs).all(|g| g.id != 0), "{runs:?}");
scene(&runs, &font).validate().unwrap();
}

fn texts(lines: &PaperLines) -> Vec<&str> {
lines.lines.iter().map(|(l, _)| l.as_str()).collect()
}

/// A text measured before it is set: broken at each line break, and given a width between words,
/// each line as many words as fit, a word never cut; set as measured (#4890 B3b).
#[test]
fn lines_wrap_between_words_to_a_width_and_never_cut_one() {
let plain = TextStyle::default();
let lines = |text: &str, wrap| paper_lines(text, None, "", 5.0, wrap, &plain).unwrap();
let text = "Bracket for the left hand side";
let wrapped = lines(text, Some(40.0));
assert!(wrapped.lines.len() > 1, "{wrapped:?}");
for (i, (line, w)) in wrapped.lines.iter().enumerate() {
assert_eq!(*w, width(line), "{line}");
assert!(*w <= 40.0, "{line}: {w}");
// Each line holds as many words as fit: the next line's first word would take it past the width.
if let Some((next, _)) = wrapped.lines.get(i + 1) {
let first = next.split(' ').next().unwrap();
assert!(width(&format!("{line} {first}")) > 40.0, "{line} | {first}");
}
}
assert_eq!(texts(&wrapped).join(" "), text);
assert_eq!(wrapped.pitch, TextMetrics::new(&font_data(None).unwrap(), &plain).unwrap().line_pitch(5.0).unwrap());
// Set as measured: the runs `paper_text` sets for the same lines joined by breaks.
let joined = texts(&wrapped).join("\n");
assert_eq!(wrapped.set(AT, 0.3).unwrap(), paper_text(&joined, None, "", AT, 5.0, 0.3, &plain).unwrap());
// A line exactly the width fits; a hair less and its last word moves down.
let two = width("Bracket for");
assert_eq!(texts(&lines("Bracket for", Some(two))), ["Bracket for"]);
assert_eq!(texts(&lines("Bracket for", Some(two - 1e-9))), ["Bracket", "for"]);
// A word wider than the width is a line of its own, whole.
let long = lines("a Bracketforthelefthandside b", Some(20.0));
assert_eq!(texts(&long), ["a", "Bracketforthelefthandside", "b"]);
assert!(long.lines[1].1 > 20.0);
// Line breaks always break; spaces between words become one; without a width only the breaks do.
assert_eq!(texts(&lines("A B\n\nC", Some(1000.0))), ["A B", "", "C"]);
assert_eq!(lines("A B\nC", None).lines, vec![("A B".to_string(), width("A B")), ("C".to_string(), width("C"))]);
// No width to speak of: every word on its own line.
for wrap in [0.0, -5.0] {
assert_eq!(texts(&lines("A B C", Some(wrap))), ["A", "B", "C"], "{wrap}");
}
}

/// A wrapped line with words the text's font lacks measures them in the font they fall back to, so
/// it is set as it was measured (#4890 B3b).
#[test]
fn a_wrapped_line_measures_its_fallback_words_in_their_font() {
let plain = TextStyle::default();
let text = "Plate \u{4e2d}\u{6587}\u{4e2d}\u{6587} for \u{4e2d}\u{6587} left side";
let wrapped = paper_lines_in(&repo_fonts(), text, None, "ja", 5.0, Some(25.0), &plain).unwrap();
assert!(wrapped.lines.len() > 1, "{wrapped:?}");
assert_eq!(texts(&wrapped).join(" "), text);
for (line, w) in &wrapped.lines {
let alone = paper_lines_in(&repo_fonts(), line, None, "ja", 5.0, None, &plain).unwrap();
assert_eq!(alone.lines, [(line.clone(), *w)], "{line}");
assert!(*w <= 25.0 || !line.contains(' '), "{line}: {w}");
}
let joined = texts(&wrapped).join("\n");
let measured = mixed(wrapped.set(AT, 0.0).unwrap().unwrap());
assert_eq!(measured, mixed(paper_text_in(&repo_fonts(), &joined, None, "ja", AT, 5.0, 0.0, &plain).unwrap().unwrap()));
}

/// Measuring refuses what setting would, and a width that isn't a number (#4890 B3b).
#[test]
fn measuring_refuses_what_setting_would() {
let plain = TextStyle::default();
for wrap in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
assert!(paper_lines("A", None, "", 5.0, Some(wrap), &plain).is_err(), "{wrap}");
}
assert!(paper_lines("A", None, "", f64::NAN, None, &plain).is_err());
assert!(matches!(paper_lines(&"A ".repeat(MAX_TEXT_CHARS), None, "", 5.0, Some(10.0), &plain), Err(SketchError::TooLarge)));
assert!(paper_lines_in(&repo_fonts(), "A \u{e000}", None, "", 5.0, Some(40.0), &plain).unwrap_err().to_string().contains("no glyph for"));
assert!(paper_lines("A", None, "", 5.0, None, &TextStyle { bold: true, ..plain.clone() }).is_err());
assert!(paper_lines("A", None, "", 5.0, None, &plain).unwrap().set(AT, f64::NAN).is_err());
assert_eq!(paper_lines("\n", None, "", 5.0, Some(10.0), &plain).unwrap().set(AT, 0.0).unwrap(), None);
}

/// Random lines of words in each font, wrapped to random widths: set as measured into runs a scene
/// takes, or refused by name, never a panic (#4890 B3b).
#[test]
fn fuzz_wrapped_lines_are_set_as_measured() {
let chars: Vec<char> = "Ab9 . \n\u{5e9}\u{5dc}\u{5b8}\u{301}\u{30c6}\u{4e2d}\u{d55c}\t".chars().collect();
let mut seed = 0x51ed_270b_27c1_9f3du64;
let mut next = |n: usize| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % n as u64) as usize
};
let plain = TextStyle::default();
for _ in 0..200 {
let text: String = (0..next(32)).map(|_| chars[next(chars.len())]).collect();
let wrap = [None, Some(-5.0), Some(0.0), Some(3.0), Some(12.0), Some(40.0)][next(6)];
match paper_lines_in(&repo_fonts(), &text, None, ["", "ja"][next(2)], 3.5, wrap, &plain) {
Ok(lines) => {
let words = |t: &str| t.split([' ', '\n']).filter(|w| !w.is_empty()).map(str::to_string).collect::<Vec<_>>();
assert_eq!(words(&texts(&lines).join("\n")), words(&text), "{text:?} {wrap:?}");
match lines.set(AT, 0.5).unwrap() {
Some(set) => {
mixed(set);
}
None => assert!(lines.lines.iter().all(|(l, _)| l.is_empty()), "{text:?}"),
}
}
Err(SketchError::Invalid(why)) => assert!(why.contains("no glyph for"), "{text:?}: {why}"),
Err(e) => panic!("{text:?}: {e}"),
}
}
}

/// Random lines of Latin, Hebrew with its points, digits, spaces and breaks, in random styles:
/// each is set into runs the scene accepts, or refused, never a panic.
#[test]
Expand Down