programmatic video rendering framework that is actually fast
fix(text): measure shaped text width instead of summing rounded advances (#256)
Silouan Wright21a502dd9c80
diff --git a/Cargo.lock b/Cargo.lockindex d3424005..008a2910 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4064,6 +4064,14 @@ 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 e6370eac..34b5ffde 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -45,6 +45,7 @@ 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 cc011384..1bece6b3 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 bd5b28b5..e406d3b8 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 05f022d6..9fba8eb8 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.pngnew file mode 100644index 00000000..133f1fd5Binary files /dev/null and b/e2e/snapshots/text-width/0.5s.png differdiff --git a/examples/text-width/Cargo.toml b/examples/text-width/Cargo.tomlnew file mode 100644index 00000000..a38f27ce--- /dev/null+++ b/examples/text-width/Cargo.toml@@ -0,0 +1,24 @@+[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.ttfnew file mode 100644index 00000000..c374a56cBinary files /dev/null and b/examples/text-width/media/NotoSansArabic-subset.ttf differdiff --git a/examples/text-width/media/SofiaSansSemiCondensed-VariableFont_wght.ttf b/examples/text-width/media/SofiaSansSemiCondensed-VariableFont_wght.ttfnew file mode 100644index 00000000..59ba155eBinary files /dev/null and b/examples/text-width/media/SofiaSansSemiCondensed-VariableFont_wght.ttf differdiff --git a/examples/text-width/src/lib.rs b/examples/text-width/src/lib.rsnew file mode 100644index 00000000..e0a2239f--- /dev/null+++ b/examples/text-width/src/lib.rs@@ -0,0 +1,117 @@+//! 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.rsnew file mode 100644index 00000000..307ce131--- /dev/null+++ b/examples/text-width/src/main.rs@@ -0,0 +1,25 @@+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 fe16f6d6..024ab610 100644--- a/fframes-editor-controller/src/wasm_editor.rs+++ b/fframes-editor-controller/src/wasm_editor.rs@@ -402,6 +402,8 @@ 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 f6f58e87..8bd05536 100644--- a/fframes-editor-controller/src/wasm_font_source.rs+++ b/fframes-editor-controller/src/wasm_font_source.rs@@ -47,6 +47,10 @@ 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 {@@ -54,6 +58,8 @@ impl WasmFontSource {Self {static_fonts: vec![],data: HashMap::new(),+ fontdb: fframes::usvgr::fontdb::Database::new(),+ face_ids: HashMap::new(),}}@@ -81,6 +87,18 @@ 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)}@@ -137,6 +155,10 @@ 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 ec38fb3a..dd5250b1 100644--- a/fframes/src/font_data.rs+++ b/fframes/src/font_data.rs@@ -100,4 +100,10 @@ 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 b4edf930..cacfcee2 100644--- a/fframes/src/renderer/renderer_font_source.rs+++ b/fframes/src/renderer/renderer_font_source.rs@@ -97,8 +97,157 @@ 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 8f609cec..21c9a58a 100644--- a/fframes/src/text.rs+++ b/fframes/src/text.rs@@ -192,6 +192,9 @@ 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@@ -210,13 +213,19 @@ impl TextCache {NonZeroUsize::new(size).unwrap(),))),text_width_cache: Rc::new(RefCell::new(LruCache::new(- NonZeroUsize::new(size).unwrap(),+ NonZeroUsize::new(size.max(TEXT_WIDTH_CACHE_MIN)).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)]@@ -336,18 +345,80 @@ fn char_width(}}-fn calc_text_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(text: &str,+ font: &FontQuery,+ font_source: &dyn FontSource,font_face: &dyn FontFace,- font_size: usize,font_variant: FontVariant,-) -> usize {+) -> f32 {match text {- "" | "\n" | "\r" => 0,- text => text- .chars()- .map(|char| char_width(char, font_face, font_size, font_variant))- .sum(),+ "" | "\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+ }),}}@@ -367,32 +438,51 @@ pub(crate) fn text_fit_impl<'a>(font_query.stretch,)?;let font_variant = font_face.font_variant(font_query.size)?;- 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();- }- }+ 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,+ )+ };- if total <= max_width {+ if width(value) <= max_width {return Some(Cow::Borrowed(value));}- if marker_width > max_width {+ let marker = overflow.marker();+ if width(marker) > max_width {// Not even the marker fits.return Some(Cow::Borrowed(""));}- let kept = &value[..fits_end];+ // 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])];if marker.is_empty() {return Some(Cow::Borrowed(kept));}@@ -415,12 +505,16 @@ pub(crate) fn text_get_width_impl<'a>()?;let font_variant = font_face.font_variant(font_query.size)?;- Some(calc_text_width(- text,- font_face.as_ref(),- font_query.size,- font_variant,- ))+ Some(+ text_width_px(+ text,+ &font_query,+ font_source,+ font_face.as_ref(),+ font_variant,+ )+ .round() as usize,+ )}pub(crate) fn text_wrap_impl<@@ -452,46 +546,41 @@ pub(crate) fn text_wrap_impl<};let font_variant = font_face.font_variant(font.size)?;- let space_width = match font_variant {- crate::FontVariant::Monospaced(mono_width) => mono_width,- crate::FontVariant::Variable => font_face.resolve_char_width(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 mut structure: Vec<(Vec<String>, usize)> = vec![(vec![], 0usize)];+ // 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 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()?;-- // The first word of a line is never preceded by a space.- let separator_width = if *last_line_width == 0 {- 0+ let joined = if last_line.is_empty() {+ word.to_owned()} else {- space_width+ format!("{} {word}", last_line.join(" "))};+ let joined_width = measure(&joined);- if *last_line_width + separator_width + word_width > width && !last_line.is_empty() {- structure.push((vec![word.to_owned()], word_width));+ if joined_width > max_width && !last_line.is_empty() {+ structure.push((vec![word.to_owned()], measure(word)));} else {- *last_line_width += separator_width + word_width;+ *last_line_width = joined_width;last_line.push(word.to_owned());}is_first_word_in_line = false;}if !is_first_word_in_line {- structure.push((vec![], 0usize));+ structure.push((vec![], 0.0));}}- if let Some((last_words, last_width)) = structure.last()- && last_words.is_empty()- && *last_width == 0- {+ if structure.last().is_some_and(|(words, _)| words.is_empty()) {structure.pop();}@@ -499,6 +588,7 @@ 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,@@ -547,17 +637,17 @@ pub fn estimate_text_width<'a>(font_stretch,} = options;- 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_get_width_impl(+ FontQuery {+ family: font_family,+ size: font_size,+ weight: font_weight,+ style: font_style,+ stretch: font_stretch,+ },text,- font_face.as_ref(),- font_size,- font_variant,- ))+ ctx.font_source?,+ )}#[cfg(test)]diff --git a/scripts/e2e.mjs b/scripts/e2e.mjsindex 937410a0..6067e9a5 100644--- a/scripts/e2e.mjs+++ b/scripts/e2e.mjs@@ -63,6 +63,8 @@ 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" },];