programmatic video rendering framework that is actually fast
Revert "fix(text): measure shaped text width instead of summing rounded advances" (#269)
Dmitriy Kovalenko633abaac933e
diff --git a/Cargo.lock b/Cargo.lockindex 008a2910..d3424005 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4064,14 +4064,6 @@ dependencies = ["fframes_skia_renderer",]-[[package]]-name = "text-width-example"-version = "1.4.1"-dependencies = [- "fframes",- "fframes_skia_renderer",-]-[[package]]name = "thingbuf"version = "0.1.6"diff --git a/Cargo.toml b/Cargo.tomlindex 34b5ffde..e6370eac 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -45,7 +45,6 @@ members = ["examples/neon-triangle","examples/neon-triangle/editor/editor-bridge","examples/arm",- "examples/text-width",# maybe clean this up?# "fframes-lyon-renderer",diff --git a/e2e/snapshots/captions/1.5s.png b/e2e/snapshots/captions/1.5s.pngindex 1bece6b3..cc011384 100644Binary files a/e2e/snapshots/captions/1.5s.png and b/e2e/snapshots/captions/1.5s.png differdiff --git a/e2e/snapshots/captions/5.2s.png b/e2e/snapshots/captions/5.2s.pngindex e406d3b8..bd5b28b5 100644Binary files a/e2e/snapshots/captions/5.2s.png and b/e2e/snapshots/captions/5.2s.png differdiff --git a/e2e/snapshots/captions/7s.png b/e2e/snapshots/captions/7s.pngindex 9fba8eb8..05f022d6 100644Binary files a/e2e/snapshots/captions/7s.png and b/e2e/snapshots/captions/7s.png differdiff --git a/e2e/snapshots/text-width/0.5s.png b/e2e/snapshots/text-width/0.5s.pngdeleted file mode 100644index 133f1fd5..00000000Binary files a/e2e/snapshots/text-width/0.5s.png and /dev/null differdiff --git a/examples/text-width/Cargo.toml b/examples/text-width/Cargo.tomldeleted file mode 100644index a38f27ce..00000000--- a/examples/text-width/Cargo.toml+++ /dev/null@@ -1,24 +0,0 @@-[package]-name = "text-width-example"-version = "1.4.1"-edition = "2024"-publish = false--[dependencies]-fframes = { workspace = true, features = ["cli", "compile-time-svgtree"] }--[features]-default = ["skia"]-skia = ["dep:fframes_skia_renderer"]--[target.'cfg(target_os = "macos")'.dependencies]-fframes_skia_renderer = { workspace = true, optional = true, features = ["cli", "metal"] }--[target.'cfg(not(any(target_os = "macos", target_arch = "wasm32")))'.dependencies]-fframes_skia_renderer = { workspace = true, optional = true, features = ["cli", "vulkan"] }--[target.'cfg(not(any(windows, target_arch = "wasm32")))'.dependencies]-fframes = { workspace = true, features = ["h264", "libav-agree-gpl", "build-portable"] }--[lints]-workspace = truediff --git a/examples/text-width/media/NotoSansArabic-subset.ttf b/examples/text-width/media/NotoSansArabic-subset.ttfdeleted file mode 100644index c374a56c..00000000Binary files a/examples/text-width/media/NotoSansArabic-subset.ttf and /dev/null differdiff --git a/examples/text-width/media/SofiaSansSemiCondensed-VariableFont_wght.ttf b/examples/text-width/media/SofiaSansSemiCondensed-VariableFont_wght.ttfdeleted file mode 100644index 59ba155e..00000000Binary files a/examples/text-width/media/SofiaSansSemiCondensed-VariableFont_wght.ttf and /dev/null differdiff --git a/examples/text-width/src/lib.rs b/examples/text-width/src/lib.rsdeleted file mode 100644index e0a2239f..00000000--- a/examples/text-width/src/lib.rs+++ /dev/null@@ -1,117 +0,0 @@-//! Boxes sized by `text_width`, a box filled by `text_fit` and a paragraph wrapped by-//! `text_break_lines`: each box should hug its glyphs, and no wrapped line should cross the-//! paragraph's right edge. The right column covers a variable font at two weights and Arabic-//! laid out with a fallback font inside Latin text.-use fframes::{- AudioMap, BreakLinesOpts, Duration, FFramesContext, FontQuery, Frame, Svgr, TextAlign,- TextOverflow, Video, include_media_dir, svgr,-};--include_media_dir!(pub struct InterMedia, "examples/arm/media");-mod own {- // Sofia Sans Semi Condensed (variable weight) and Noto Sans Arabic cut down to "سلام".- fframes::include_media_dir!(pub struct TextWidthMedia, "examples/text-width/media");-}-pub use own::TextWidthMedia;--const INTER: &str = "Inter 18pt";-const SOFIA: &str = "Sofia Sans Semi Condensed";-const PARAGRAPH_WIDTH: usize = 760;-const FIT_WIDTH: usize = 550;--pub struct TextWidthVideo;--fn font(family: &str, size: usize, weight: u16) -> FontQuery<'_> {- FontQuery {- family,- size,- weight,- ..Default::default()- }-}--fn measured<'a>(- frame: &mut Frame,- ctx: &FFramesContext<'a, '_>,- font: FontQuery<'a>,- text: &'a str,- (x, y): (f64, f64),-) -> Svgr<'a> {- let width = frame.text_width(ctx, font, text).unwrap_or(0);- let size = font.size as f64;- svgr!(<g>- <rect x={x} y={y - size * 0.8} width={width} height={size} fill="#1f3a5f" />- <text x={x} y={y} font-family={font.family} font-weight={font.weight} font-size={size} fill="#f4f7fb">{text}</text>- </g>)-}--impl Video for TextWidthVideo {- const FPS: usize = 30;- const WIDTH: usize = 1920;- const HEIGHT: usize = 1080;-- fn duration(&self) -> Duration<'_> {- Duration::Seconds(1.0)- }-- fn audio(&self) -> AudioMap<'_> {- AudioMap::none()- }-- fn render_frame<'a>(&'a self, mut frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {- let rows = [- (font(INTER, 100, 800), "AVAVAVAV WAVE", (120.0, 260.0)),- (- font(INTER, 46, 800),- "δεν είναι ανατολική ρωμαϊκή αυτοκρατορία",- (120.0, 420.0),- ),- (- font(INTER, 46, 800),- "The Byzantine Greeks call Eastern Rome",- (120.0, 520.0),- ),- (font(SOFIA, 64, 100), "Hamburgefonts WAVE", (1040.0, 660.0)),- (font(SOFIA, 64, 900), "Hamburgefonts WAVE", (1040.0, 760.0)),- (font(INTER, 64, 800), "AV سلام WAVE", (1040.0, 860.0)),- ]- .into_iter()- .map(|(font, text, at)| measured(&mut frame, ctx, font, text, at))- .collect::<Vec<_>>();- let fitted = frame- .text_fit(- ctx,- font(INTER, 64, 800),- "Eastern Rome, Byzantium",- FIT_WIDTH,- TextOverflow::Ellipsis,- )- .unwrap_or_default()- .into_owned();- let paragraph = frame.text_break_lines(- ctx,- "Η Ανατολική Ρωμαϊκή Αυτοκρατορία ονομάστηκε αργότερα Βυζάντιο. Later historians named the Eastern Roman Empire Byzantium.",- BreakLinesOpts {- font: font(INTER, 40, 800),- width: PARAGRAPH_WIDTH,- line_height: 1.25,- x: 120,- y: 660,- align: TextAlign::Left,- fill: "#f4f7fb",- ..Default::default()- },- );- svgr!(- <svg xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 1920 1080">- <rect width="1920" height="1080" fill="#0c1423" />- <text x="120" y="120" font-family={INTER} font-weight="800" font-size="40" fill="#91a3b9">"text_width, text_fit and text_break_lines"</text>- {rows}- <rect x="1040" y="209" width={FIT_WIDTH} height="64" fill="none" stroke="#e76f51" stroke-width="2" />- <text x="1040" y="260" font-family={INTER} font-weight="800" font-size="64" fill="#f4f7fb">{fitted}</text>- <path d={format!("M {} 600 V 1000", 120 + PARAGRAPH_WIDTH)} stroke="#e76f51" stroke-width="2" />- {paragraph}- </svg>- )- }-}diff --git a/examples/text-width/src/main.rs b/examples/text-width/src/main.rsdeleted file mode 100644index 307ce131..00000000--- a/examples/text-width/src/main.rs+++ /dev/null@@ -1,25 +0,0 @@-use fframes::{CombinedMediaProvider, MediaProvider, RenderOptions, cli};-use std::process::ExitCode;-use text_width_example::{InterMedia, TextWidthMedia, TextWidthVideo};--fn main() -> ExitCode {- let (inter, own) = match (InterMedia::new(), TextWidthMedia::new()) {- (Ok(inter), Ok(own)) => (inter, own),- (Err(error), _) | (_, Err(error)) => {- eprintln!("{error}");- return ExitCode::FAILURE;- }- };- let media = CombinedMediaProvider::from([&inter as &dyn MediaProvider, &own]);- let video = TextWidthVideo;- let runner = cli::new(- &video,- RenderOptions {- media: Some(&media),- ..Default::default()- },- );- #[cfg(feature = "skia")]- let runner = runner.renderers(fframes_skia_renderer::cli::SkiaRenderers::default());- runner.run()-}diff --git a/fframes-editor-controller/src/wasm_editor.rs b/fframes-editor-controller/src/wasm_editor.rsindex 024ab610..fe16f6d6 100644--- a/fframes-editor-controller/src/wasm_editor.rs+++ b/fframes-editor-controller/src/wasm_editor.rs@@ -402,8 +402,6 @@ impl<TVideo: Video, TMedia: StaticMediaProvider<'static> + 'static> WasmEditor<Tpub fn ingest_font(&self, slice: &[u8]) -> JsValue {let mut fonts = self.fonts.lock().unwrap();let face_info = fonts.insert_font(slice.to_vec().into(), None);- // Cache keys name the font, not its bytes, so a replaced font would keep old widths.- self.break_lines_cache.clear();serde_wasm_bindgen::to_value(&face_info).unwrap()}diff --git a/fframes-editor-controller/src/wasm_font_source.rs b/fframes-editor-controller/src/wasm_font_source.rsindex 8bd05536..f6f58e87 100644--- a/fframes-editor-controller/src/wasm_font_source.rs+++ b/fframes-editor-controller/src/wasm_font_source.rs@@ -47,10 +47,6 @@ impl StaticFontFace {pub struct WasmFontSource {pub static_fonts: Vec<StaticFontFace>,pub data: HashMap<FaceInfo, Cow<'static, [u8]>>,- /// The same fonts for measuring text the way the native renderer lays it out.- pub fontdb: fframes::usvgr::fontdb::Database,- /// Faces each font added to `fontdb`, replaced when the font is inserted again.- face_ids: HashMap<FaceInfo, Vec<fframes::usvgr::fontdb::ID>>,}impl WasmFontSource {@@ -58,8 +54,6 @@ impl WasmFontSource {Self {static_fonts: vec![],data: HashMap::new(),- fontdb: fframes::usvgr::fontdb::Database::new(),- face_ids: HashMap::new(),}}@@ -87,18 +81,6 @@ impl WasmFontSource {})}- // Static fonts are shared with fontdb, not copied.- let shared: Arc<dyn AsRef<[u8]> + Send + Sync> = match &data {- Cow::Borrowed(bytes) => Arc::new(*bytes),- Cow::Owned(bytes) => Arc::new(bytes.clone()),- };- for id in self.face_ids.remove(&face_info).into_iter().flatten() {- self.fontdb.remove_face(id);- }- let ids = self- .fontdb- .load_font_source(fframes::usvgr::fontdb::Source::Binary(shared));- self.face_ids.insert(face_info.clone(), ids.to_vec());self.data.insert(face_info.clone(), data);Some(face_info)}@@ -155,10 +137,6 @@ impl<'a> fframes::FontSource<'a> for WasmFontSource {}))}- fn measure_text(&self, font: &fframes::FontQuery, text: &str) -> Option<f32> {- fframes::measure_text_width(&self.fontdb, font, text)- }-fn add_font(&mut self, _filename: String, _font_data: Arc<dyn AsRef<[u8]> + Sync + Send>) {unimplemented!("Adding fonts for wasm font source must be done through WasmFontSource::insert_font api"diff --git a/fframes/src/font_data.rs b/fframes/src/font_data.rsindex dd5250b1..ec38fb3a 100644--- a/fframes/src/font_data.rs+++ b/fframes/src/font_data.rs@@ -100,10 +100,4 @@ pub trait FontSource<'a>: Sync + Send + std::fmt::Debug {font_style: FontStyle,font_stretch: FontStretch,) -> Option<Box<dyn FontFace<'a> + 'a>>;-- /// Width of `text` in pixels as the renderer lays it out, see- /// [`crate::measure_text_width`]. `None` falls back to per-character advances.- fn measure_text(&self, _font: &crate::FontQuery, _text: &str) -> Option<f32> {- None- }}diff --git a/fframes/src/renderer/renderer_font_source.rs b/fframes/src/renderer/renderer_font_source.rsindex cacfcee2..b4edf930 100644--- a/fframes/src/renderer/renderer_font_source.rs+++ b/fframes/src/renderer/renderer_font_source.rs@@ -97,157 +97,8 @@ impl<'a> crate::FontSource<'a> for RendererFontSource {}))}- fn measure_text(&self, font: &crate::FontQuery, text: &str) -> Option<f32> {- crate::measure_text_width(&self.fontdb, font, text)- }-fn add_font(&mut self, _filename: String, font_data: Arc<dyn AsRef<[u8]> + Sync + Send>) {self.fontdb.load_font_source(fontdb::Source::Binary(font_data.clone()));}}--#[cfg(test)]-mod tests {- use super::*;- use crate::text::{text_fit_impl, text_wrap_impl};- use crate::{BreakLinesOpts, FontQuery, FontSource, TextOverflow};-- const INTER: &[u8] = include_bytes!("../../../examples/arm/media/Inter_18pt-ExtraBold.ttf");- const SOFIA: &[u8] = include_bytes!(- "../../../examples/teej-podcast/dynamic_media/SofiaSansSemiCondensed-VariableFont_wght.ttf"- );- // Noto Sans Arabic (OFL) cut down to the glyphs of "سلام".- const ARABIC: &[u8] =- include_bytes!("../../../examples/text-width/media/NotoSansArabic-subset.ttf");-- fn fonts(files: &[&[u8]]) -> RendererFontSource {- let mut fontdb = fontdb::Database::new();- for data in files {- fontdb.load_font_data(data.to_vec());- }- RendererFontSource { fontdb }- }-- fn font(family: &str, size: usize, weight: u16) -> FontQuery<'_> {- FontQuery {- family,- size,- weight,- ..Default::default()- }- }-- fn assert_near(actual: f32, expected: f32) {- assert!(- (actual - expected).abs() < 0.5,- "measured {actual}, expected {expected}"- );- }-- #[test]- fn text_fit_keeps_kerned_text_that_fits() {- let fonts = fonts(&[INTER]);- let text = "AVAVAVAV";- assert_near(- fonts- .measure_text(&font("Inter 18pt", 100, 800), text)- .unwrap(),- 546.0,- );- let fitted = text_fit_impl(- font("Inter 18pt", 100, 800),- text,- 550,- TextOverflow::Ellipsis,- &fonts,- );- assert_eq!(fitted.as_deref(), Some(text));- }-- #[test]- fn text_fit_truncates_text_wider_than_its_box() {- let fonts = fonts(&[INTER]);- let query = font("Inter 18pt", 46, 800);- let text = "The Byzantine Greeks call Eastern Rome";- assert!(fonts.measure_text(&query, text).unwrap() > 885.0);- let fitted = text_fit_impl(query, text, 885, TextOverflow::Ellipsis, &fonts).unwrap();- assert!(fitted.ends_with('…'), "{fitted}");- assert!(fonts.measure_text(&query, &fitted).unwrap() <= 885.0);- }-- #[test]- fn wrapped_lines_are_measured_joined() {- let fonts = fonts(&[INTER]);- let query = font("Inter 18pt", 16, 800);- let wrapped = text_wrap_impl(- 0,- "a a a a a a a a a a",- &fonts,- BreakLinesOpts::<usize, usize> {- font: query,- width: 117,- ..Default::default()- },- )- .unwrap();- assert!(wrapped.lines.len() > 1);- for line in &wrapped.lines {- let rendered = fonts.measure_text(&query, &line.words.join(" ")).unwrap();- assert!(rendered <= 117.0, "{:?} renders {rendered} px", line.words);- assert_eq!(line.width, rendered.round() as usize);- }- }-- #[test]- fn measuring_follows_the_weight_axis() {- let fonts = fonts(&[SOFIA]);- let family = "Sofia Sans Semi Condensed";- assert_near(- fonts- .measure_text(&font(family, 40, 100), "Hamburgefonts")- .unwrap(),- 247.9,- );- assert_near(- fonts- .measure_text(&font(family, 40, 900), "Hamburgefonts")- .unwrap(),- 266.5,- );- }-- #[test]- fn missing_glyphs_are_measured_in_the_fallback_font() {- let fonts = fonts(&[INTER, ARABIC]);- let fallback = fonts- .measure_text(&font("Inter 18pt", 40, 800), "سلام")- .unwrap();- let direct = fonts- .measure_text(&font("Noto Sans Arabic", 40, 400), "سلام")- .unwrap();- assert_near(fallback, direct);- }-- #[test]- fn marks_do_not_widen_text() {- let fonts = fonts(&[ARABIC]);- let arabic = font("Noto Sans Arabic", 40, 400);- assert_near(- fonts.measure_text(&arabic, "اَ").unwrap(),- fonts.measure_text(&arabic, "ا").unwrap(),- );- }-- #[test]- fn mixed_direction_text_is_measured_per_run() {- let fonts = fonts(&[INTER, ARABIC]);- let query = font("Inter 18pt", 40, 800);- let latin = fonts.measure_text(&query, "AV ").unwrap();- let arabic = fonts.measure_text(&query, "سلام").unwrap();- assert_near(- fonts.measure_text(&query, "AV سلام").unwrap(),- latin + arabic,- );- }-}diff --git a/fframes/src/text.rs b/fframes/src/text.rsindex 21c9a58a..8f609cec 100644--- a/fframes/src/text.rs+++ b/fframes/src/text.rs@@ -192,9 +192,6 @@ where}}-/// Widths are tiny and a frame often measures every word.-const TEXT_WIDTH_CACHE_MIN: usize = 1024;-/// This is only fframes cache for text related processing, the actual/// glyph aliasing, text outlining happens in the rendering backend and/// can have its own cache@@ -213,19 +210,13 @@ impl TextCache {NonZeroUsize::new(size).unwrap(),))),text_width_cache: Rc::new(RefCell::new(LruCache::new(- NonZeroUsize::new(size.max(TEXT_WIDTH_CACHE_MIN)).unwrap(),+ NonZeroUsize::new(size).unwrap(),))),})} else {None}}-- /// Forgets every measured width and wrapped text, for when a font changes.- pub fn clear(&self) {- self.breaks_cache.borrow_mut().clear();- self.text_width_cache.borrow_mut().clear();- }}#[derive(Debug, Clone)]@@ -345,80 +336,18 @@ fn char_width(}}-/// Width of `text` in pixels as usvgr lays it out when rendering: shaped per bidi run, with-/// fallback fonts and the variation axes the renderer applies. The text is laid out twice, from-/// its start and from its end at `x = 0`: every glyph moves by exactly the advance width between-/// the two, so glyph offsets such as mark positioning cancel out.-pub fn measure_text_width(- fontdb: &usvgr::fontdb::Database,- font: &FontQuery,- text: &str,-) -> Option<f32> {- fn escape(value: &str) -> String {- value- .replace('&', "&")- .replace('<', "<")- .replace('>', ">")- .replace('"', """)- }- fn texts<'t>(group: &'t usvgr::Group, found: &mut Vec<&'t usvgr::Text>) {- for node in group.children() {- match node {- usvgr::Node::Text(text) => found.push(text),- usvgr::Node::Group(group) => texts(group, found),- _ => {}- }- }- }- fn first_glyph_x(text: &usvgr::Text) -> Option<f32> {- let glyph = text.layouted().first()?.positioned_glyphs.first()?;- Some(glyph.transform().tx)- }-- if text.is_empty() {- return Some(0.0);- }- let style = match font.style {- FontStyle::Normal => "normal",- FontStyle::Italic => "italic",- FontStyle::Oblique => "oblique",- };- let text = format!(- r#"xml:space="preserve" font-family="{}" font-size="{}" font-weight="{}" font-style="{style}" font-stretch="{}">{}</text>"#,- escape(font.family),- font.size,- font.weight,- font.stretch,- escape(text),- );- let svg = format!(- r#"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"><text text-anchor="start" {text}<text text-anchor="end" {text}</svg>"#- );- let tree = usvgr::Tree::from_str(&svg, &usvgr::Options::default(), fontdb).ok()?;- let mut found = Vec::with_capacity(2);- texts(tree.root(), &mut found);- let [from_start, from_end] = found[..] else {- return None;- };- Some(first_glyph_x(from_start)? - first_glyph_x(from_end)?)-}--/// The renderer's width when the font source can lay text out, per-character advances-/// otherwise.-fn text_width_px(+fn calc_text_width(text: &str,- font: &FontQuery,- font_source: &dyn FontSource,font_face: &dyn FontFace,+ font_size: usize,font_variant: FontVariant,-) -> f32 {+) -> usize {match text {- "" | "\n" | "\r" => 0.0,- text => font_source.measure_text(font, text).unwrap_or_else(|| {- text.chars()- .map(|char| char_width(char, font_face, font.size, font_variant))- .sum::<usize>() as f32- }),+ "" | "\n" | "\r" => 0,+ text => text+ .chars()+ .map(|char| char_width(char, font_face, font_size, font_variant))+ .sum(),}}@@ -438,51 +367,32 @@ pub(crate) fn text_fit_impl<'a>(font_query.stretch,)?;let font_variant = font_face.font_variant(font_query.size)?;- let max_width = max_width as f32;- let width = |text: &str| {- text_width_px(- text,- &font_query,- font_source,- font_face.as_ref(),- font_variant,- )- };+ let width =+ |text: &str| calc_text_width(text, font_face.as_ref(), font_query.size, font_variant);++ let marker = overflow.marker();+ let marker_width = width(marker);++ // One pass over the glyphs: `fits_end` is the end of the longest prefix+ // that leaves room for the marker, `total` the width of the whole text.+ let mut total = 0;+ let mut fits_end = 0;+ for (index, char) in value.char_indices() {+ total += char_width(char, font_face.as_ref(), font_query.size, font_variant);+ if total + marker_width <= max_width {+ fits_end = index + char.len_utf8();+ }+ }- if width(value) <= max_width {+ if total <= max_width {return Some(Cow::Borrowed(value));}- let marker = overflow.marker();- if width(marker) > max_width {+ if marker_width > max_width {// Not even the marker fits.return Some(Cow::Borrowed(""));}- // The kept prefix and the marker are measured together, as they render. Binary search over- // the number of kept characters: measuring is a layout, so each probe counts.- let ends: Vec<usize> = value- .char_indices()- .map(|(i, c)| i + c.len_utf8())- .collect();- let fits = |end: usize| {- let kept = &value[..end];- if marker.is_empty() {- width(kept) <= max_width- } else {- width(&format!("{}{marker}", kept.trim_end())) <= max_width- }- };- let (mut low, mut high) = (0, ends.len());- while low < high {- let mid = (low + high).div_ceil(2);- if fits(ends[mid - 1]) {- low = mid;- } else {- high = mid - 1;- }- }-- let kept = &value[..low.checked_sub(1).map_or(0, |i| ends[i])];+ let kept = &value[..fits_end];if marker.is_empty() {return Some(Cow::Borrowed(kept));}@@ -505,16 +415,12 @@ pub(crate) fn text_get_width_impl<'a>()?;let font_variant = font_face.font_variant(font_query.size)?;- Some(- text_width_px(- text,- &font_query,- font_source,- font_face.as_ref(),- font_variant,- )- .round() as usize,- )+ Some(calc_text_width(+ text,+ font_face.as_ref(),+ font_query.size,+ font_variant,+ ))}pub(crate) fn text_wrap_impl<@@ -546,41 +452,46 @@ pub(crate) fn text_wrap_impl<};let font_variant = font_face.font_variant(font.size)?;- let max_width = width as f32;- let measure =- |text: &str| text_width_px(text, &font, font_source, font_face.as_ref(), font_variant);+ let space_width = match font_variant {+ crate::FontVariant::Monospaced(mono_width) => mono_width,+ crate::FontVariant::Variable => font_face.resolve_char_width(font.size, ' ')?,+ };- // Lines are measured joined, as they render, so spaces and kerning across words count.- let mut structure: Vec<(Vec<String>, f32)> = vec![(vec![], 0.0)];+ let mut structure: Vec<(Vec<String>, usize)> = vec![(vec![], 0usize)];let line_height_in_px = line_height * font.size as f32;for line in value.split('\n') {let mut is_first_word_in_line = true;for word in line.split_whitespace() {+ let word_width = calc_text_width(word, font_face.as_ref(), font.size, font_variant);let (last_line, last_line_width) = structure.last_mut()?;- let joined = if last_line.is_empty() {- word.to_owned()++ // The first word of a line is never preceded by a space.+ let separator_width = if *last_line_width == 0 {+ 0} else {- format!("{} {word}", last_line.join(" "))+ space_width};- let joined_width = measure(&joined);- if joined_width > max_width && !last_line.is_empty() {- structure.push((vec![word.to_owned()], measure(word)));+ if *last_line_width + separator_width + word_width > width && !last_line.is_empty() {+ structure.push((vec![word.to_owned()], word_width));} else {- *last_line_width = joined_width;+ *last_line_width += separator_width + word_width;last_line.push(word.to_owned());}is_first_word_in_line = false;}if !is_first_word_in_line {- structure.push((vec![], 0.0));+ structure.push((vec![], 0usize));}}- if structure.last().is_some_and(|(words, _)| words.is_empty()) {+ if let Some((last_words, last_width)) = structure.last()+ && last_words.is_empty()+ && *last_width == 0+ {structure.pop();}@@ -588,7 +499,6 @@ pub(crate) fn text_wrap_impl<.into_iter().enumerate().map(|(index, (words, line_width))| {- let line_width = line_width.round() as usize;let dx = match align {TextAlign::Left => 0,TextAlign::Center => width.saturating_sub(line_width) / 2,@@ -637,17 +547,17 @@ pub fn estimate_text_width<'a>(font_stretch,} = options;- text_get_width_impl(- FontQuery {- family: font_family,- size: font_size,- weight: font_weight,- style: font_style,- stretch: font_stretch,- },+ let font_face =+ ctx.font_source?+ .resolve_font(font_family, font_weight, font_style, font_stretch)?;++ let font_variant = font_face.font_variant(font_size)?;+ Some(calc_text_width(text,- ctx.font_source?,- )+ font_face.as_ref(),+ font_size,+ font_variant,+ ))}#[cfg(test)]diff --git a/scripts/e2e.mjs b/scripts/e2e.mjsindex 6067e9a5..937410a0 100644--- a/scripts/e2e.mjs+++ b/scripts/e2e.mjs@@ -63,8 +63,6 @@ const allExamples = [{ dir: "podcast", pkg: "podcast-example", bin: "podcast_example_bin", frames: "10s,40s" },{ dir: "shaders", pkg: "shaders-example", bin: "shaders_example_bin", frames: "2s,6s", skia: true },{ dir: "signal-lab", pkg: "signal-lab", bin: "signal-lab", frames: "ProductScene@3s,DataScene@3s,SystemScene@3s" },- // Boxes sized by text_width and a paragraph wrapped by text_break_lines, in Greek and kerned Latin.- { dir: "text-width", pkg: "text-width-example", bin: "text-width-example", frames: "0.5s" },{ dir: "teej-podcast", pkg: "teej_podcast_example", bin: "teej_podcast_example_bin", frames: "10s,2:00" },{ dir: "tiktok", pkg: "tiktok-example", bin: "tiktok_example_bin", frames: "10s,30s" },];