Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Sketch text: Arabic and Hebrew are ordered right to left and joined (#8237) (#8324)

Logan Nightd67c8e62314c
diff --git a/Cargo.lock b/Cargo.lock
index ebb93b624b..90c1a614a6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4404,11 +4404,13 @@ dependencies = [
name = "solidcraft-sketch"
version = "0.25.1"
dependencies = [
+ "harfrust",
"serde",
"serde_json",
"solidcraft-geom",
"thiserror 2.0.21",
"ttf-parser",
+ "unicode-bidi",
]
[[package]]
diff --git a/crates/sketch/Cargo.toml b/crates/sketch/Cargo.toml
index eba000b5a4..ba238d5a25 100644
--- a/crates/sketch/Cargo.toml
+++ b/crates/sketch/Cargo.toml
@@ -17,10 +17,12 @@ name = "solve_profile"
required-features = ["solver-profiling"]
[dependencies]
+harfrust = "0.12"
solidcraft-geom = { workspace = true }
serde = { workspace = true }
thiserror = { workspace = true }
ttf-parser = { workspace = true }
+unicode-bidi = "0.3"
[dev-dependencies]
serde_json = { workspace = true }
diff --git a/crates/sketch/src/font_tests.rs b/crates/sketch/src/font_tests.rs
index b8f21b6bbc..fc1c1ac466 100644
--- a/crates/sketch/src/font_tests.rs
+++ b/crates/sketch/src/font_tests.rs
@@ -454,3 +454,68 @@ fn installed_families_are_listed_by_name_once_without_the_built_in_one() {
}
assert!(crate::families_in(&[folder.0.join("missing")]).is_empty());
}
+
+/// The left and right ends of a text's outline, from every point its curves give (the same points move with the text,
+/// so a letter's ends in a word are its ends alone, moved along).
+fn reach(geometry: &[LinkGeom]) -> (f64, f64) {
+ let xs: Vec<f64> = geometry
+ .iter()
+ .flat_map(|g| match g {
+ LinkGeom::Line(a, b) => vec![a.x, b.x],
+ LinkGeom::Conic { a, apex, b, .. } => vec![a.x, apex.x, b.x],
+ LinkGeom::Spline { pts, .. } => pts.iter().map(|p| p.x).collect(),
+ _ => Vec::new(),
+ })
+ .collect();
+ (xs.iter().copied().fold(f64::INFINITY, f64::min), xs.iter().copied().fold(f64::NEG_INFINITY, f64::max))
+}
+
+/// Checks a right-to-left word set in `font` at 10 mm: the letters stand from right to left in reading order, so the
+/// first letter is the line's right end and the last one its left end, and the line is as wide as its letters side by
+/// side.
+fn check_right_to_left(font: Option<&str>, word: &str) {
+ let data = font_data(font).unwrap();
+ let m = TextMetrics::new(&data, &TextStyle::default()).unwrap();
+ let draw = |text: &str| text_geometry_in(font, text, Vec2::ZERO, 10.0, 0.0).unwrap();
+ let (first, last) = (word.chars().next().unwrap().to_string(), word.chars().next_back().unwrap().to_string());
+ let (width, first_width) = (m.line_width(word, 10.0).unwrap(), m.line_width(&first, 10.0).unwrap());
+ let (left, right) = reach(&draw(word));
+ // The first letter's right end, moved to where it stands at the right end of the line; the last letter at the start.
+ assert!((right - (width - first_width + reach(&draw(&first)).1)).abs() < 1e-6, "right end {right}");
+ assert!((left - reach(&draw(&last)).0).abs() < 1e-6, "left end {left}");
+}
+
+#[test]
+fn hebrew_reads_right_to_left_in_the_built_in_font() {
+ // Shalom in reading order: shin first, final mem last.
+ check_right_to_left(None, "\u{5E9}\u{5DC}\u{5D5}\u{5DD}");
+ // A left-to-right word before it keeps its place; the Hebrew after it still ends at the line's right end.
+ let font = font_data(None).unwrap();
+ let m = TextMetrics::new(&font, &TextStyle::default()).unwrap();
+ let line = "ab \u{5E9}\u{5DC}\u{5D5}\u{5DD}";
+ let (_, right) = reach(&text_geometry_in(None, line, Vec2::ZERO, 10.0, 0.0).unwrap());
+ let shin = reach(&text_geometry_in(None, "\u{5E9}", Vec2::ZERO, 10.0, 0.0).unwrap()).1;
+ let shin_width = m.line_width("\u{5E9}", 10.0).unwrap();
+ assert!((right - (m.line_width(line, 10.0).unwrap() - shin_width + shin)).abs() < 1e-6);
+ let (left, _) = reach(&text_geometry_in(None, line, Vec2::ZERO, 10.0, 0.0).unwrap());
+ assert!((left - reach(&text_geometry_in(None, "a", Vec2::ZERO, 10.0, 0.0).unwrap()).0).abs() < 1e-6, "a stays first");
+ // Text without right-to-left characters keeps its width.
+ assert!(m.line_width("ab", 10.0).unwrap() > 0.0);
+ // A line break inside the line ends a paragraph of the bidirectional algorithm; the text after it still counts.
+ let after = "\u{5D1}\u{5D1}\u{5D1}\u{5D1}";
+ assert!(m.line_width(&format!("\u{5D0}\n{after}"), 10.0).unwrap() > m.line_width(after, 10.0).unwrap());
+}
+
+#[test]
+fn arabic_letters_join_in_an_arabic_font() {
+ // An installed Arabic font; a machine without one has nothing to check.
+ let Ok(font) = font_data(Some("Noto Naskh Arabic")) else { return };
+ let m = TextMetrics::new(&font, &TextStyle::default()).unwrap();
+ // "Algeria" in reading order. Set one letter at a time every letter takes its isolated form and width.
+ let word = "\u{627}\u{644}\u{62C}\u{632}\u{627}\u{626}\u{631}";
+ let isolated: f64 = word.chars().map(|c| m.line_width(&c.to_string(), 10.0).unwrap()).sum();
+ let joined = m.line_width(word, 10.0).unwrap();
+ assert!(joined > 0.0 && joined < isolated, "joined {joined} isolated {isolated}");
+ // Its first letter, an alef, never joins to the one after it: it stands at the line's right end.
+ check_right_to_left(Some("Noto Naskh Arabic"), word);
+}
diff --git a/crates/sketch/src/text.rs b/crates/sketch/src/text.rs
index b04a24027e..74ff72594a 100644
--- a/crates/sketch/src/text.rs
+++ b/crates/sketch/src/text.rs
@@ -5,7 +5,9 @@
//!
//! 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. [`TextMetrics`] measures
-//! text by the rule that draws it.
+//! text by the rule that draws it. A line with right-to-left characters (Arabic, Hebrew…) is ordered by the
+//! Unicode bidirectional algorithm and shaped with the font's own rules, so letters join and marks sit where the font
+//! puts them; every other line is set glyph by glyph, as it always was.
use serde::{Deserialize, Serialize};
use solidcraft_geom::{Ring, Vec2};
@@ -194,6 +196,20 @@ pub struct TextMetrics<'a> {
fallback: Option<ttf_parser::GlyphId>,
letter_spacing: f64,
line_spacing: f64,
+ /// The font's bytes and face index, for shaping a right-to-left line.
+ bytes: &'a [u8],
+ index: u32,
+ /// What shaping needs from the font, read the first time a right-to-left line asks (None: the font cannot be shaped).
+ shaper: std::cell::OnceCell<Option<harfrust::ShaperData>>,
+}
+
+/// One glyph of a laid-out line: where its origin is along the line, its advance and how far it is raised (marks),
+/// in millimetres.
+struct Glyph {
+ id: ttf_parser::GlyphId,
+ x: f64,
+ advance: f64,
+ rise: f64,
}
impl<'a> TextMetrics<'a> {
@@ -210,6 +226,9 @@ impl<'a> TextMetrics<'a> {
fallback: face.glyph_index('?'),
letter_spacing: style.letter_spacing,
line_spacing: style.line_spacing,
+ bytes: font.bytes(),
+ index: font.index,
+ shaper: std::cell::OnceCell::new(),
face,
})
}
@@ -232,7 +251,7 @@ impl<'a> TextMetrics<'a> {
/// 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<f64> {
let k = self.scale(height)?;
- Ok(self.glyphs(line, k).last().map(|(_, x, advance)| x + advance).unwrap_or(0.0))
+ Ok(self.laid_out(line, k).1)
}
/// The characters of one line the font has no glyph for, in order and each time they come: those its character map
@@ -255,6 +274,68 @@ impl<'a> TextMetrics<'a> {
Some((gid, x, advance))
})
}
+
+ /// The glyphs of one line in the order they stand along it, left to right, and the line's width. A line with
+ /// right-to-left characters is shaped (see [`Self::shaped`]); any other is laid out by [`Self::glyphs`].
+ fn laid_out(&self, line: &str, k: f64) -> (Vec<Glyph>, f64) {
+ if let Some(shaped) = self.shaped(line, k) {
+ return shaped;
+ }
+ let glyphs: Vec<Glyph> = self.glyphs(line, k).map(|(id, x, advance)| Glyph { id, x, advance, rise: 0.0 }).collect();
+ let width = glyphs.last().map(|g| g.x + g.advance).unwrap_or(0.0);
+ (glyphs, width)
+ }
+
+ /// A line with right-to-left characters, set the way the script needs it: the Unicode bidirectional algorithm puts
+ /// its runs in display order, each run is shaped by the font's own rules in its own direction (joined letters,
+ /// ligatures, marks attached to their letters), and the glyphs come out left to right. None for a line without
+ /// right-to-left characters, or when the font cannot be shaped. Kerning stays off, as in the other lines, and the
+ /// letter spacing goes after each glyph that has an advance, not after a mark. A character the font lacks is its
+ /// missing-glyph box here. Brackets are not mirrored.
+ fn shaped(&self, line: &str, k: f64) -> Option<(Vec<Glyph>, f64)> {
+ use harfrust::{Direction, Feature, ShapeOptions, Tag, UnicodeBuffer};
+ // Nothing below U+0590 is written right to left.
+ if line.chars().all(|c| u32::from(c) < 0x0590) {
+ return None;
+ }
+ let info = unicode_bidi::BidiInfo::new(line, None);
+ if !info.has_rtl() {
+ return None;
+ }
+ let font = harfrust::FontRef::from_index(self.bytes, self.index).ok()?;
+ let data = self.shaper.get_or_init(|| Some(harfrust::ShaperData::new(&font))).as_ref()?;
+ let shaper = data.shaper(&font).build();
+ let kerning_off = [Feature::new(Tag::new(b"kern"), 0, ..)];
+ let (mut out, mut pen, mut gap) = (Vec::new(), 0.0f64, 0.0f64);
+ // A line break in the line ends a paragraph of the algorithm; the paragraphs follow one another.
+ let runs = info.paragraphs.iter().flat_map(|paragraph| {
+ let (levels, runs) = info.visual_runs(paragraph, paragraph.range.clone());
+ runs.into_iter().map(move |run| (levels.get(run.start).is_some_and(|l| l.is_rtl()), run))
+ });
+ for (rtl, run) in runs {
+ let mut buffer = UnicodeBuffer::new();
+ buffer.push_str(line.get(run.clone())?);
+ buffer.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight });
+ buffer.guess_segment_properties();
+ let shaped = shaper.shape(buffer, ShapeOptions::new().features(&kerning_off));
+ for (glyph, place) in shaped.glyph_infos().iter().zip(shaped.glyph_positions()) {
+ let advance = f64::from(place.x_advance) * k;
+ out.push(Glyph {
+ id: ttf_parser::GlyphId(u16::try_from(glyph.glyph_id).ok()?),
+ x: pen + f64::from(place.x_offset) * k,
+ advance,
+ rise: f64::from(place.y_offset) * k,
+ });
+ pen += advance;
+ gap = 0.0;
+ if advance != 0.0 {
+ pen += self.letter_spacing;
+ gap = self.letter_spacing;
+ }
+ }
+ }
+ Some((out, pen - gap))
+ }
}
/// Outline geometry of `text` in the built-in font (see [`text_geometry_in`]).
@@ -305,7 +386,7 @@ pub fn text_geometry_styled(
TextAlign::Center => -metrics.line_width(line, height)? / 2.0,
TextAlign::Right => -metrics.line_width(line, height)?,
};
- for (gid, x, advance) in metrics.glyphs(line, k) {
+ for Glyph { id: gid, x, advance, rise } in metrics.laid_out(line, k).0 {
// The glyph's frame: its origin on the baseline and the way the baseline runs.
let (origin, dir) = match &along {
None => {
@@ -320,7 +401,7 @@ pub fn text_geometry_styled(
let up = Vec2::new(-dir.y, dir.x);
let map = Box::new(move |gx: f32, gy: f32| {
let (gx, gy) = (f64::from(gx) * k, f64::from(gy) * k);
- origin + dir * (gx + gy * shear) + up * gy
+ origin + dir * (gx + gy * shear) + up * (gy + rise)
});
let mut ob = Outline { out: Vec::new(), start: origin, cur: origin, map };
let _ = metrics.face.outline_glyph(gid, &mut ob);