diff --git a/Cargo.lock b/Cargo.lock
index 161611f0..559e35b5 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.toml
index f38f1bcf..486e5316 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.png
index cc011384..1bece6b3 100644
Binary files a/e2e/snapshots/captions/1.5s.png and b/e2e/snapshots/captions/1.5s.png differ
diff --git a/e2e/snapshots/captions/5.2s.png b/e2e/snapshots/captions/5.2s.png
index bd5b28b5..e406d3b8 100644
Binary files a/e2e/snapshots/captions/5.2s.png and b/e2e/snapshots/captions/5.2s.png differ
diff --git a/e2e/snapshots/captions/7s.png b/e2e/snapshots/captions/7s.png
index 05f022d6..9fba8eb8 100644
Binary files a/e2e/snapshots/captions/7s.png and b/e2e/snapshots/captions/7s.png differ
diff --git a/e2e/snapshots/text-width/0.5s.png b/e2e/snapshots/text-width/0.5s.png
new file mode 100644
index 00000000..133f1fd5
Binary files /dev/null and b/e2e/snapshots/text-width/0.5s.png differ
diff --git a/examples/text-width/Cargo.toml b/examples/text-width/Cargo.toml
new file mode 100644
index 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 = true
diff --git a/examples/text-width/media/NotoSansArabic-subset.ttf b/examples/text-width/media/NotoSansArabic-subset.ttf
new file mode 100644
index 00000000..c374a56c
Binary files /dev/null and b/examples/text-width/media/NotoSansArabic-subset.ttf differ
diff --git a/examples/text-width/media/SofiaSansSemiCondensed-VariableFont_wght.ttf b/examples/text-width/media/SofiaSansSemiCondensed-VariableFont_wght.ttf
new file mode 100644
index 00000000..59ba155e
Binary files /dev/null and b/examples/text-width/media/SofiaSansSemiCondensed-VariableFont_wght.ttf differ
diff --git a/examples/text-width/src/lib.rs b/examples/text-width/src/lib.rs
new file mode 100644
index 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!(
+
+ {text}
+ )
+}
+
+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::>();
+ 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!(
+
+ )
+ }
+}
diff --git a/examples/text-width/src/main.rs b/examples/text-width/src/main.rs
new file mode 100644
index 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.rs
index fe16f6d6..024ab610 100644
--- a/fframes-editor-controller/src/wasm_editor.rs
+++ b/fframes-editor-controller/src/wasm_editor.rs
@@ -402,6 +402,8 @@ impl + 'static> WasmEditor 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.rs
index 50fe7727..212f8a87 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,
pub data: HashMap>,
+ /// 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>,
}
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 + 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 {
+ fframes::measure_text_width(&self.fontdb, font, text)
+ }
+
fn add_font(&mut self, _filename: String, _font_data: Arc + 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.rs
index 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 + '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 {
+ None
+ }
}
diff --git a/fframes/src/renderer/renderer_font_source.rs b/fframes/src/renderer/renderer_font_source.rs
index 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 {
+ crate::measure_text_width(&self.fontdb, font, text)
+ }
+
fn add_font(&mut self, _filename: String, font_data: Arc + 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:: {
+ 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.rs
index 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 {
+ 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 {
+ 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="{}">{}"#,
+ escape(font.family),
+ font.size,
+ font.weight,
+ font.stretch,
+ escape(text),
+ );
+ let svg = format!(
+ r#"