Skip to content

The headless browser for AI agents and web scraping

fix(render): apply word spacing to text layout and paint

Peder Berganbf10c461caf6
diff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rs
index ec446dd1..376a43d5 100644
--- a/crates/obscura-render/src/dom.rs
+++ b/crates/obscura-render/src/dom.rs
@@ -14,6 +14,11 @@ use taffy::prelude::*;
use crate::{to_taffy_style, Rect};
+pub(crate) fn word_spacing_advance(text: &str, spacing: f32) -> f32 {
+ if spacing == 0.0 { return 0.0; }
+ text.chars().filter(|c| matches!(c, ' ' | '\u{00a0}')).count() as f32 * spacing
+}
+
/// Text width for layout. With the `paint` feature this is exact (real glyph
/// metrics from the embedded font, shared with rasterization). Without it
/// (layout-only builds, e.g. for `getBoundingClientRect`), fall back to a
@@ -28,9 +33,11 @@ fn text_width(
is_bold: bool,
family: Option<&str>,
letter_spacing: f32,
+ word_spacing: f32,
) -> f32 {
crate::paint::measure_text(text, size, is_bold, family)
+ text.chars().filter(|c| !c.is_control()).count() as f32 * letter_spacing
+ + word_spacing_advance(text, word_spacing)
}
#[cfg(not(feature = "paint"))]
@@ -40,6 +47,7 @@ fn text_width(
is_bold: bool,
_family: Option<&str>,
letter_spacing: f32,
+ word_spacing: f32,
) -> f32 {
const AVG_CHAR_WIDTH_EM: f32 = 0.55;
let chars = text.chars().filter(|c| !c.is_control()).count() as f32;
@@ -49,6 +57,7 @@ fn text_width(
} else {
glyph_width
}) + chars * letter_spacing
+ + word_spacing_advance(text, word_spacing)
}
#[derive(Default)]
@@ -4802,6 +4811,7 @@ fn layout_dom_once(
font_optical_sizing: crate::FontOpticalSizing,
font_variation_settings: Vec<crate::FontVariationSetting>,
letter_spacing: f32,
+ word_spacing: f32,
letter_spacing_non_normal: bool,
container_type: crate::ContainerType,
container_names: Vec<String>,
@@ -4854,6 +4864,7 @@ fn layout_dom_once(
font_optical_sizing: crate::FontOpticalSizing::Auto,
font_variation_settings: Vec::new(),
letter_spacing: 0.0,
+ word_spacing: 0.0,
letter_spacing_non_normal: false,
container_type: crate::ContainerType::Normal,
container_names: Vec::new(),
@@ -4963,6 +4974,9 @@ fn layout_dom_once(
if let Some(spacing) = style.letter_spacing {
inh.letter_spacing = spacing;
}
+ if let Some(spacing) = style.word_spacing {
+ inh.word_spacing = spacing;
+ }
if let Some(non_normal) = style.letter_spacing_non_normal {
inh.letter_spacing_non_normal = non_normal;
}
@@ -5178,6 +5192,16 @@ fn layout_dom_once(
Some(spacing) if spacing.is_finite() => inh.letter_spacing = spacing,
_ => style.letter_spacing = Some(inh.letter_spacing),
}
+ if let Some(raw) = style.word_spacing_raw {
+ style.word_spacing = match raw.resolve(em_px, root_fs, vw, vh) {
+ crate::Dimension::Px(pixels) if pixels.is_finite() => Some(pixels),
+ _ => None,
+ };
+ }
+ match style.word_spacing {
+ Some(spacing) if spacing.is_finite() => inh.word_spacing = spacing,
+ _ => style.word_spacing = Some(inh.word_spacing),
+ }
match style.letter_spacing_non_normal {
Some(non_normal) => inh.letter_spacing_non_normal = non_normal,
None => style.letter_spacing_non_normal = Some(inh.letter_spacing_non_normal),
@@ -5557,6 +5581,7 @@ fn layout_dom_once(
// now-final computed style.
let host_color = style.color;
let host_font_size = style.font_size.unwrap_or(parent_fs);
+ let host_word_spacing = style.word_spacing.unwrap_or(0.0);
let host_letter_spacing = style.letter_spacing.unwrap_or(0.0);
let host_letter_spacing_non_normal =
style.letter_spacing_non_normal.unwrap_or(false);
@@ -5672,6 +5697,14 @@ fn layout_dom_once(
} else if pseudo.letter_spacing.is_none() {
pseudo.letter_spacing = Some(host_letter_spacing);
}
+ if let Some(raw) = pseudo.word_spacing_raw {
+ pseudo.word_spacing = match raw.resolve(pseudo_em, root_fs, vw, vh) {
+ crate::Dimension::Px(pixels) if pixels.is_finite() => Some(pixels),
+ _ => None,
+ };
+ } else if pseudo.word_spacing.is_none() {
+ pseudo.word_spacing = Some(host_word_spacing);
+ }
if pseudo.letter_spacing_non_normal.is_none() {
pseudo.letter_spacing_non_normal = Some(host_letter_spacing_non_normal);
}
@@ -5936,6 +5969,7 @@ fn layout_dom_once(
bold,
style.font_family.as_deref(),
style.letter_spacing.unwrap_or(0.0),
+ style.word_spacing.unwrap_or(0.0),
);
content_width += intrinsic_content
.map(|content| content.atomic_width)
@@ -6006,6 +6040,7 @@ fn layout_dom_once(
bold,
style.font_family.as_deref(),
style.letter_spacing.unwrap_or(0.0),
+ style.word_spacing.unwrap_or(0.0),
)
})
.fold(0.0f32, f32::max);
@@ -9789,6 +9824,7 @@ fn build_text_words(
let mut line_height = fsize * 1.2;
let mut transform = crate::TextTransform::None;
let mut letter_spacing = 0.0;
+ let mut word_spacing = 0.0;
if let Some(parent_id) = rendered_parent(tree, id) {
if let Some(p_style) = styles.get(&parent_id) {
fsize = p_style.font_size.unwrap_or(16.0);
@@ -9797,6 +9833,7 @@ fn build_text_words(
line_height = crate::inline::used_line_height(p_style);
transform = p_style.text_transform.unwrap_or(crate::TextTransform::None);
letter_spacing = p_style.letter_spacing.unwrap_or(0.0);
+ word_spacing = p_style.word_spacing.unwrap_or(0.0);
}
}
if let Some(style) = rendered_parent(tree, id).and_then(|parent| styles.get(&parent)) {
@@ -9823,6 +9860,7 @@ fn build_text_words(
is_bold,
family,
letter_spacing,
+ word_spacing,
taffy_tree,
words,
)
@@ -9926,13 +9964,14 @@ fn build_word_leaves(
is_bold: bool,
family: Option<&str>,
letter_spacing: f32,
+ word_spacing: f32,
taffy_tree: &mut TaffyTree<usize>,
words: &mut HashMap<taffy::NodeId, (NodeId, String)>,
) -> Vec<taffy::NodeId> {
tokenize_with_spaces(text)
.into_iter()
.filter_map(|token| {
- let width = text_width(&token, fsize, is_bold, family, letter_spacing);
+ let width = text_width(&token, fsize, is_bold, family, letter_spacing, word_spacing);
// A pure-whitespace token is HTML source formatting or a bare
// inter-element space; it keeps its (small) width so adjacent
// inline content stays visually separated, but contributes no
@@ -9987,6 +10026,7 @@ fn build_pseudo_content(
is_bold,
style.font_family.as_deref(),
style.letter_spacing.unwrap_or(0.0),
+ style.word_spacing.unwrap_or(0.0),
taffy_tree,
words,
)
diff --git a/crates/obscura-render/src/inline.rs b/crates/obscura-render/src/inline.rs
index 150b434e..d0d4d29a 100644
--- a/crates/obscura-render/src/inline.rs
+++ b/crates/obscura-render/src/inline.rs
@@ -1228,6 +1228,7 @@ impl TextEngine {
font_size: context.font_size,
line_height: context.line_height,
letter_spacing: context.letter_spacing,
+ word_spacing: context.word_spacing,
letter_spacing_non_normal: context.letter_spacing_non_normal,
weight: context.weight,
optical_sizing: context.optical_sizing,
@@ -1846,6 +1847,7 @@ struct SpanAttrs {
font_size: f32,
line_height: f32,
letter_spacing: f32,
+ word_spacing: f32,
letter_spacing_non_normal: bool,
weight: u16,
optical_sizing: crate::FontOpticalSizing,
@@ -1909,6 +1911,9 @@ impl SpanAttrs {
if self.synthetic_italic {
a = a.cache_key_flags(CacheKeyFlags::FAKE_ITALIC);
}
+ if self.word_spacing.is_finite() && self.word_spacing != 0.0 {
+ a = a.word_spacing(self.word_spacing / self.font_size.max(1.0));
+ }
if self.letter_spacing.is_finite() && self.letter_spacing != 0.0 {
a = a.letter_spacing(self.letter_spacing / self.font_size.max(1.0));
}
@@ -1966,6 +1971,7 @@ struct SpanCtx {
font_size: f32,
line_height: f32,
letter_spacing: f32,
+ word_spacing: f32,
letter_spacing_non_normal: bool,
color: [u8; 4],
weight: u16,
@@ -2109,6 +2115,7 @@ fn base_span_ctx(base: &LayoutStyle, font: ResolvedFont, collector: &mut Collect
font_size: base.font_size.unwrap_or(16.0),
line_height,
letter_spacing: base.letter_spacing.unwrap_or(0.0),
+ word_spacing: base.word_spacing.unwrap_or(0.0),
letter_spacing_non_normal: base.letter_spacing_non_normal.unwrap_or(false),
color: base.color.unwrap_or([0, 0, 0, 255]),
weight: crate::style::used_font_weight(base),
@@ -2164,6 +2171,7 @@ fn collect_node_spans(
font_size: ctx.font_size,
line_height: ctx.line_height,
letter_spacing: ctx.letter_spacing,
+ word_spacing: ctx.word_spacing,
letter_spacing_non_normal: ctx.letter_spacing_non_normal,
weight: ctx.weight,
optical_sizing: ctx.optical_sizing,
@@ -2196,6 +2204,7 @@ fn collect_node_spans(
font_size: ctx.font_size,
line_height: ctx.line_height,
letter_spacing: ctx.letter_spacing,
+ word_spacing: ctx.word_spacing,
letter_spacing_non_normal: ctx.letter_spacing_non_normal,
weight: ctx.weight,
optical_sizing: ctx.optical_sizing,
@@ -2266,6 +2275,9 @@ fn collect_node_spans(
letter_spacing: style
.and_then(|style| style.letter_spacing)
.unwrap_or(ctx.letter_spacing),
+ word_spacing: style
+ .and_then(|style| style.word_spacing)
+ .unwrap_or(ctx.word_spacing),
letter_spacing_non_normal: style
.and_then(|style| style.letter_spacing_non_normal)
.unwrap_or(ctx.letter_spacing_non_normal),
@@ -4118,6 +4130,7 @@ mod tests {
font_size: 16.0,
line_height: 18.0,
letter_spacing: 0.0,
+ word_spacing: 0.0,
letter_spacing_non_normal: false,
weight: 400,
optical_sizing: crate::FontOpticalSizing::Auto,
@@ -4198,6 +4211,7 @@ mod tests {
font_size: 20.0,
line_height: 24.0,
letter_spacing: 2.0,
+ word_spacing: 0.0,
letter_spacing_non_normal: true,
weight: 400,
optical_sizing: crate::FontOpticalSizing::Auto,
diff --git a/crates/obscura-render/src/lib.rs b/crates/obscura-render/src/lib.rs
index e8416020..11ae12f9 100644
--- a/crates/obscura-render/src/lib.rs
+++ b/crates/obscura-render/src/lib.rs
@@ -1239,6 +1239,10 @@ pub struct LayoutStyle {
/// Keeping this provenance distinguishes an explicit zero from the
/// `normal` initial value while resolving the inherited property.
pub letter_spacing_non_normal: Option<bool>,
+ /// Additional advance per word separator, resolved to CSS pixels before inheritance.
+ pub word_spacing: Option<f32>,
+ /// Relative length retained until the element's font size is resolved.
+ pub word_spacing_raw: Option<Dimension>,
/// Specified CSS font weight during cascade (`1..1000`, `bolder`, or
/// `lighter`), normalized to its numeric computed value by the inheritance
/// pass before layout and shaping.
diff --git a/crates/obscura-render/src/paint.rs b/crates/obscura-render/src/paint.rs
index 35dd15dd..5cb3f6ac 100644
--- a/crates/obscura-render/src/paint.rs
+++ b/crates/obscura-render/src/paint.rs
@@ -4488,6 +4488,7 @@ fn paint_laid_dom_scrolled(
false,
None,
0.0,
+ 0.0,
clip,
element_clip_mask,
raster_scale,
@@ -4621,6 +4622,7 @@ fn paint_laid_dom_scrolled(
false,
style.font_family.as_deref(),
style.letter_spacing.unwrap_or(0.0),
+ style.word_spacing.unwrap_or(0.0),
clip,
element_clip_mask,
raster_scale,
@@ -4660,6 +4662,7 @@ fn paint_laid_dom_scrolled(
is_bold,
style.font_family.as_deref(),
style.letter_spacing.unwrap_or(0.0),
+ style.word_spacing.unwrap_or(0.0),
clip,
element_clip_mask,
raster_scale,
@@ -4686,6 +4689,7 @@ fn paint_laid_dom_scrolled(
crate::style::used_font_weight(style) >= 600,
style.font_family.as_deref(),
style.letter_spacing.unwrap_or(0.0),
+ style.word_spacing.unwrap_or(0.0),
Some(visible_rect),
element_clip_mask,
raster_scale,
@@ -4760,6 +4764,7 @@ fn paint_laid_dom_scrolled(
false,
style.font_family.as_deref(),
style.letter_spacing.unwrap_or(0.0),
+ style.word_spacing.unwrap_or(0.0),
clip,
element_clip_mask,
raster_scale,
@@ -4794,6 +4799,7 @@ fn paint_laid_dom_scrolled(
false,
style.font_family.as_deref(),
style.letter_spacing.unwrap_or(0.0),
+ style.word_spacing.unwrap_or(0.0),
clip,
element_clip_mask,
raster_scale,
@@ -6790,6 +6796,7 @@ fn paint_text_node(
is_bold,
style.font_family.as_deref(),
style.letter_spacing.unwrap_or(0.0),
+ style.word_spacing.unwrap_or(0.0),
clip,
clip_mask.as_ref(),
raster_scale,
@@ -6875,6 +6882,7 @@ fn draw_text(
is_bold: bool,
family: Option<&str>,
letter_spacing: f32,
+ word_spacing: f32,
clip: Option<crate::Rect>,
clip_mask: Option<&tiny_skia::Mask>,
raster_scale: f32,
@@ -6981,11 +6989,13 @@ fn draw_text(
// each word is its own independently-positioned box.
caret.x += scaled_font.h_advance(id)
+ if is_bold { raster_scale } else { 0.0 }
- + letter_spacing * raster_scale;
+ + letter_spacing * raster_scale
+ + if matches!(c, ' ' | '\u{00a0}') { word_spacing * raster_scale } else { 0.0 };
} else {
caret.x += scaled_font.h_advance(id)
+ if is_bold { raster_scale } else { 0.0 }
- + letter_spacing * raster_scale;
+ + letter_spacing * raster_scale
+ + if matches!(c, ' ' | '\u{00a0}') { word_spacing * raster_scale } else { 0.0 };
}
}
}
diff --git a/crates/obscura-render/src/style.rs b/crates/obscura-render/src/style.rs
index 8b12a273..43d7c37d 100644
--- a/crates/obscura-render/src/style.rs
+++ b/crates/obscura-render/src/style.rs
@@ -1164,6 +1164,7 @@ fn apply_value(style: &mut LayoutStyle, name: &str, value: &str) {
apply_font_size(style, value);
}
"letter-spacing" => apply_letter_spacing(style, value),
+ "word-spacing" => apply_word_spacing(style, value),
"font" => apply_font_shorthand(style, value),
"font-weight" => {
let lower = value.trim().to_ascii_lowercase();
@@ -2062,6 +2063,7 @@ pub fn supports_declaration(name: &str, value: &str) -> bool {
| "color-scheme"
| "font-size"
| "letter-spacing"
+ | "word-spacing"
| "font"
| "font-weight"
| "font-family"
@@ -2904,6 +2906,7 @@ fn supports_conservative_known_value(name: &str, value: &str) -> bool {
};
match name {
"width" | "inline-size" => lower == "fit-content" || dimension(value, true),
+ "word-spacing" => lower == "normal" || parse_word_spacing_length(value).is_some(),
"height" | "block-size" | "min-width" | "min-inline-size" | "min-height"
| "min-block-size" | "max-width" | "max-inline-size" | "max-height" | "max-block-size"
| "flex-basis" => dimension(value, true),
@@ -6978,6 +6981,50 @@ fn apply_font_size(style: &mut LayoutStyle, value: &str) {
}
}
+fn apply_word_spacing(style: &mut LayoutStyle, value: &str) {
+ let value = value.trim();
+ let lower = value.to_ascii_lowercase();
+ if matches!(lower.as_str(), "inherit" | "unset" | "revert" | "revert-layer") {
+ style.word_spacing = None;
+ style.word_spacing_raw = None;
+ return;
+ }
+ if matches!(lower.as_str(), "normal" | "initial") {
+ style.word_spacing = Some(0.0);
+ style.word_spacing_raw = None;
+ return;
+ }
+ // Invalid declarations must not replace an earlier cascade winner.
+ match parse_word_spacing_length(value) {
+ Some(crate::Dimension::Px(pixels)) => {
+ style.word_spacing = Some(pixels);
+ style.word_spacing_raw = None;
+ }
+ Some(relative) => {
+ style.word_spacing = None;
+ style.word_spacing_raw = Some(relative);
+ }
+ None => {}
+ }
+}
+
+fn parse_word_spacing_length(value: &str) -> Option<crate::Dimension> {
+ let mut input = cssparser::ParserInput::new(value);
+ let mut parser = cssparser::Parser::new(&mut input);
+ let length = match parser.next().ok()? {
+ cssparser::Token::Number { value, .. } if *value == 0.0 => crate::Dimension::Px(0.0),
+ cssparser::Token::Dimension { value, unit, .. } if value.is_finite() => {
+ dimension_value(&format!("{value}{unit}"))
+ }
+ _ => return None,
+ };
+ if !parser.is_exhausted() { return None; }
+ match length.resolve(16.0, 16.0, 1.0, 1.0) {
+ crate::Dimension::Px(pixels) if pixels.is_finite() => Some(length),
+ _ => None,
+ }
+}
+
fn apply_letter_spacing(style: &mut LayoutStyle, value: &str) {
let value = value.trim();
let lower = value.to_ascii_lowercase();
diff --git a/crates/obscura-render/tests/layout_test.rs b/crates/obscura-render/tests/layout_test.rs
index ad3b12c1..37f68487 100644
--- a/crates/obscura-render/tests/layout_test.rs
+++ b/crates/obscura-render/tests/layout_test.rs
@@ -7,6 +7,146 @@ use obscura_dom::tree_sink::parse_html;
use obscura_render::{layout_dom, layout_dom_with_images};
use std::collections::HashMap;
+#[test]
+fn word_spacing_changes_intrinsic_width() {
+ let tree = parse_html(r#"<style>
+ span { display:inline-block; font:40px/60px monospace; white-space:nowrap }
+ #spaced { word-spacing:30px }
+ </style><span id="normal">A B C</span><span id="spaced">A B C</span>"#);
+ let layout = layout_dom(&tree, (600.0, 200.0));
+ let width = |id| layout.rects[&tree.get_element_by_id(id).unwrap()].width;
+ assert!((width("spaced") - width("normal") - 60.0).abs() < 0.1);
+}
+
+#[test]
+fn word_spacing_rejects_invalid_and_unsupported_lengths() {
+ for value in ["bogus", "30", "10%", "3 px", "min(30px,bogus)", "calc(30px) bogus",
+ "calc(30)", "calc(2px * 3px)", "min(1px,max(2px,bogus))", "1px 2px", "1e99px"]
+ {
+ let tree = parse_html(&format!("<div id='copy' style='word-spacing:3px;word-spacing:{value}'>A B</div>"));
+ let layout = layout_dom(&tree, (400.0, 200.0));
+ assert_eq!(layout.styles[&tree.get_element_by_id("copy").unwrap()].word_spacing, Some(3.0), "{value}");
+ assert!(!obscura_render::style::supports_declaration("word-spacing", value), "{value}");
+ }
+ for value in ["normal", "0", "-3px", ".75em", "2rem"] {
+ assert!(obscura_render::style::supports_declaration("word-spacing", value), "{value}");
+ }
+}
+
+#[test]
+fn word_spacing_resolves_before_inheritance_and_preserves_cascade() {
+ let tree = parse_html(r#"<style>
+ section { font-size:20px; word-spacing:1.5em }
+ span { display:inline-block; font-size:40px; white-space:nowrap }
+ #normal { word-spacing:normal }
+ #inherit { word-spacing:3px; word-spacing:inherit }
+ #unset { word-spacing:3px; word-spacing:unset }
+ #invalid { word-spacing:3px; word-spacing:bogus; word-spacing:calc(bogus) }
+ #negative { word-spacing:-.25em }
+ #revert { word-spacing:3px; word-spacing:revert }
+ </style><section>
+ <span id="inherited">A B C</span><span id="normal">A B C</span>
+ <span id="inherit">A B C</span><span id="unset">A B C</span>
+ <span id="invalid">A B C</span><span id="negative">A B C</span>
+ <span id="revert">A B C</span></section>"#);
+ let layout = layout_dom(&tree, (1800.0, 300.0));
+ let width = |id| layout.rects[&tree.get_element_by_id(id).unwrap()].width;
+ for (id, spacing) in [("inherited", 30.0), ("normal", 0.0), ("inherit", 30.0),
+ ("unset", 30.0), ("invalid", 3.0), ("negative", -10.0), ("revert", 30.0)]
+ {
+ assert_eq!(layout.styles[&tree.get_element_by_id(id).unwrap()].word_spacing, Some(spacing), "{id}");
+ assert!((width(id) - width("normal") - 2.0 * spacing).abs() <= 1.0, "{id}");
+ }
+}
+
+#[cfg(feature = "paint")]
+#[test]
+fn word_spacing_changes_wrapping_and_native_control_widths() {
+ let tree = parse_html(r#"<style>
+ div { width:140px; font:40px/60px monospace }
+ .spaced { word-spacing:30px }
+ button, select { font:40px/60px monospace }
+ </style><div id="normal">A B C</div><div id="spaced" class="spaced">A B C</div>
+ <button id="button">A B C</button><button id="button-spaced" class="spaced">A B C</button>
+ <select id="select"><option>A B C</option></select>
+ <select id="select-spaced" class="spaced"><option>A B C</option></select>"#);
+ let layout = layout_dom(&tree, (1000.0, 500.0));
+ let rect = |id| layout.rects[&tree.get_element_by_id(id).unwrap()];
+ assert_eq!(rect("normal").height, 60.0);
+ assert_eq!(rect("spaced").height, 120.0);
+ for (normal, spaced) in [("button", "button-spaced"), ("select", "select-spaced")] {
+ assert!((rect(spaced).width - rect(normal).width - 60.0).abs() <= 1.0,
+ "{normal}: {:?} -> {:?}", rect(normal), rect(spaced));
+ }
+}
+
+#[cfg(feature = "paint")]
+#[test]
+fn word_spacing_handles_whitespace_nested_spans_and_generated_content() {
+ for (content, extra_css, delta) in [
+ (" A B C ", "", 60.0),
+ ("A&nbsp;B&nbsp;C", "", 60.0),
+ ("A B", "white-space:pre", 60.0),
+ ("A\tB", "white-space:pre", 0.0),
+ ("A B C", "letter-spacing:2px", 60.0),
+ ("A<span> B</span> C", "", 60.0),
+ ("אב גד", "direction:rtl", 30.0),
+ ] {
+ let tree = parse_html(&format!(r#"<style>
+ div {{ display:inline-block; font:40px/60px monospace; white-space:nowrap; {extra_css} }}
+ #spaced {{ word-spacing:30px }}
+ </style><div id="normal">{content}</div><div id="spaced">{content}</div>"#));
+ let layout = layout_dom(&tree, (1000.0, 300.0));
+ let width = |id| layout.rects[&tree.get_element_by_id(id).unwrap()].width;
+ assert!((width("spaced") - width("normal") - delta).abs() <= 1.0, "{content:?}, {extra_css}");
+ }
+ let tree = parse_html(r#"<style>
+ div { display:inline-block; font:40px/60px monospace; white-space:nowrap }
+ #spaced { word-spacing:30px }
+ div::before { content:'A B C'; font-size:20px }
+ div::after { content:'A B C'; word-spacing:normal }
+ </style><div id="normal"></div><div id="spaced"></div>"#);
+ let layout = layout_dom(&tree, (1000.0, 300.0));
+ let id = tree.get_element_by_id("spaced").unwrap();
+ assert_eq!(layout.styles[&id].before_pseudo.as_ref().unwrap().word_spacing, Some(30.0));
+ assert_eq!(layout.styles[&id].after_pseudo.as_ref().unwrap().word_spacing, Some(0.0));
+ let normal = layout.rects[&tree.get_element_by_id("normal").unwrap()].width;
+ assert!((layout.rects[&id].width - normal - 60.0).abs() <= 1.0);
+}
+
+#[cfg(feature = "paint")]
+#[test]
+fn word_spacing_moves_painted_glyphs() {
+ let tree = parse_html(r#"<style>
+ body { margin:0; background:white; color:black }
+ div { height:80px; font:40px/60px monospace; white-space:nowrap }
+ #spaced { word-spacing:30px }
+ </style><div>A B C</div><div id="spaced">A B C</div>"#);
+ let png = obscura_render::screenshot_png(&tree, (400.0, 180.0), None).unwrap();
+ let pixmap = tiny_skia::Pixmap::decode_png(&png).unwrap();
+ let starts = |top: usize| {
+ let mut result = Vec::new();
+ let mut previous = false;
+ for x in 0..400 {
+ let ink = (top..top + 70).any(|y| {
+ let pixel = pixmap.pixels()[y * 400 + x];
+ pixel.red() < 128 && pixel.green() < 128 && pixel.blue() < 128
+ });
+ if ink && !previous { result.push(x as i32); }
+ previous = ink;
+ }
+ result
+ };
+ let normal = starts(0);
+ let spaced = starts(80);
+ assert_eq!(normal.len(), 3, "normal glyph columns: {normal:?}");
+ assert_eq!(spaced.len(), 3, "spaced glyph columns: {spaced:?}");
+ for i in 0..3 {
+ assert!((spaced[i] - normal[i] - i as i32 * 30).abs() <= 1,
+ "painted positions: {normal:?} -> {spaced:?}");
+ }
+}
+
const HN_HTML: &str = r##"
<table border="0" cellpadding="0" cellspacing="0" width="85%" bgcolor="#f6f6ef">
<tr>
diff --git a/crates/obscura-render/tests/word_spacing_shaping.rs b/crates/obscura-render/tests/word_spacing_shaping.rs
new file mode 100644
index 00000000..9b40f708
--- /dev/null
+++ b/crates/obscura-render/tests/word_spacing_shaping.rs
@@ -0,0 +1,55 @@
+#![cfg(feature = "paint")]
+
+use cosmic_text::{Attrs, AttrsList, AttrsOwned, Family, FontSystem, ShapeLine, Shaping};
+
+fn font_system() -> FontSystem {
+ let mut db = cosmic_text::fontdb::Database::new();
+ db.load_font_data(include_bytes!("../assets/liberation-mono.ttf").to_vec());
+ FontSystem::new_with_locale_and_db("en-US".into(), db)
+}
+
+fn advances(fonts: &mut FontSystem, text: &str, attrs: &AttrsList, shaping: Shaping) -> Vec<f32> {
+ ShapeLine::new(fonts, text, attrs, shaping, 8).spans.iter()
+ .flat_map(|span| &span.words).flat_map(|word| &word.glyphs)
+ .map(|glyph| glyph.x_advance).collect()
+}
+
+#[test]
+fn word_spacing_uses_separator_attributes_and_cache_identity() {
+ let mut fonts = font_system();
+ let base = Attrs::new().family(Family::Name("Liberation Mono"));
+ for shaping in [Shaping::Basic, Shaping::Advanced] {
+ let normal = advances(&mut fonts, "A B C", &AttrsList::new(&base), shaping);
+ for spacing in [0.75, -0.25, -1.0, 0.0, 0.75] {
+ let spaced = base.clone().word_spacing(spacing);
+ let owned = AttrsOwned::new(&spaced);
+ assert_eq!(owned.as_attrs(), spaced);
+ let mut attrs = AttrsList::new(&base);
+ attrs.add_span(1..2, &owned.as_attrs());
+ attrs.add_span(3..4, &base.clone().word_spacing(spacing * 2.0));
+ let actual = advances(&mut fonts, "A B C", &attrs, shaping);
+ assert_eq!(actual.len(), normal.len());
+ for (i, (actual, normal)) in actual.iter().zip(&normal).enumerate() {
+ let extra = match i { 1 => spacing, 3 => spacing * 2.0, _ => 0.0 };
+ assert!((actual - normal - extra).abs() < 0.00001, "glyph {i}: {actual} vs {normal}");
+ }
+ }
+ }
+}
+
+#[test]
+fn word_spacing_preserves_tabs_and_non_separator_glyphs() {
+ let mut fonts = font_system();
+ let base = Attrs::new().family(Family::Name("Liberation Mono"));
+ for shaping in [Shaping::Basic, Shaping::Advanced] {
+ for (text, separators) in [("A\u{a0}B", 1), ("A\tB", 0), ("A\u{2003}B", 0),
+ ("A B", 2), ("office", 0)]
+ {
+ let normal = advances(&mut fonts, text, &AttrsList::new(&base), shaping);
+ let spaced = advances(&mut fonts, text, &AttrsList::new(&base.clone().word_spacing(0.75)), shaping);
+ assert_eq!(normal.len(), spaced.len(), "{text:?}");
+ let delta = spaced.iter().sum::<f32>() - normal.iter().sum::<f32>();
+ assert!((delta - separators as f32 * 0.75).abs() < 0.00001, "{text:?}: {delta}");
+ }
+ }
+}
diff --git a/render-repros/check.py b/render-repros/check.py
index a21f4ed8..c0bc8d89 100755
--- a/render-repros/check.py
+++ b/render-repros/check.py
@@ -25,6 +25,24 @@ from scipy.ndimage import (
)
+def word_spacing_checks(array):
+ """Compare ink positions within one engine, allowing rasterization differences."""
+ rows = []
+ for top in (20, 100, 180, 260, 340):
+ ink = np.any(np.all(array[top : top + 70, :400] < 128, axis=2), axis=0)
+ starts = np.flatnonzero(ink & ~np.r_[False, ink[:-1]]).tolist()
+ rows.append(starts)
+ results = []
+ for index, spacing in enumerate((0, 30, 30, 0, -10)):
+ passed = len(rows[0]) == len(rows[index]) == 3
+ if passed:
+ passed = all(abs(rows[index][glyph] - rows[0][glyph] - glyph * spacing) <= 1
+ for glyph in range(3))
+ results.append({"name": f"word spacing row {index}", "passed": passed,
+ "glyph_starts": rows[index], "spacing": spacing})
+ return results
+
+
def rgb(value):
value = value.removeprefix("#")
return tuple(int(value[i : i + 2], 16) for i in (0, 2, 4))
@@ -205,6 +223,11 @@ def main():
"behavior": {"obscura": [], "chromium": []},
}
for engine, array in (("obscura", ours), ("chromium", chromium)):
+ if name == "word-spacing":
+ for check in word_spacing_checks(array):
+ fixture["behavior"][engine].append(check)
+ if not check["passed"]:
+ failures.append(f"{name} {engine}: {check}")
for check in checks.get(name, []):
expected_count = check.get("count", 1)
matches = []
diff --git a/render-repros/word-spacing.html b/render-repros/word-spacing.html
new file mode 100644
index 00000000..2afd9b26
--- /dev/null
+++ b/render-repros/word-spacing.html
@@ -0,0 +1,20 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>Word spacing advances measured and painted text</title>
+<style>
+@font-face {
+ font-family: "Liberation Mono";
+ src: url("../crates/obscura-render/assets/liberation-mono.ttf");
+}
+body { margin:20px; color:black; background:white }
+.row { height:80px; font:40px/60px "Liberation Mono", monospace; white-space:nowrap }
+.positive { word-spacing:30px }
+.relative { word-spacing:.75em }
+.negative { word-spacing:-10px }
+.normal { word-spacing:normal }
+</style>
+<div class="row">A B C</div>
+<div class="row positive">A B C</div>
+<div class="row relative"><span>A B C</span></div>
+<div class="row positive"><span class="normal">A B C</span></div>
+<div class="row negative">A B C</div>
diff --git a/vendor/cosmic-text/src/attrs.rs b/vendor/cosmic-text/src/attrs.rs
index 3b0ea465..154ff9e4 100644
--- a/vendor/cosmic-text/src/attrs.rs
+++ b/vendor/cosmic-text/src/attrs.rs
@@ -392,6 +392,8 @@ pub struct Attrs<'a> {
pub metrics_opt: Option<CacheMetrics>,
/// Letter spacing (tracking) in EM
pub letter_spacing_opt: Option<LetterSpacing>,
+ /// Additional word-separator advance in EM.
+ pub word_spacing_opt: Option<LetterSpacing>,
pub font_features: FontFeatures,
pub font_variations: FontVariations,
/// Optional browser-grade line-breaking policy for this text span.
@@ -417,6 +419,7 @@ impl<'a> Attrs<'a> {
cache_key_flags: CacheKeyFlags::empty(),
metrics_opt: None,
letter_spacing_opt: None,
+ word_spacing_opt: None,
font_features: FontFeatures::new(),
font_variations: FontVariations::new(),
css_line_break: None,
@@ -498,6 +501,13 @@ impl<'a> Attrs<'a> {
self
}
+ /// Set additional word-separator advance in EM.
+ pub fn word_spacing(mut self, word_spacing: f32) -> Self {
+ self.word_spacing_opt = Some(LetterSpacing(word_spacing));
+ self
+ }
+
+
/// Set [`FontFeatures`]
pub fn font_features(mut self, font_features: FontFeatures) -> Self {
self.font_features = font_features;
@@ -581,6 +591,8 @@ pub struct AttrsOwned {
pub metrics_opt: Option<CacheMetrics>,
/// Letter spacing (tracking) in EM
pub letter_spacing_opt: Option<LetterSpacing>,
+ /// Additional word-separator advance in EM.
+ pub word_spacing_opt: Option<LetterSpacing>,
pub font_features: FontFeatures,
pub font_variations: FontVariations,
pub css_line_break: Option<CssLineBreak>,
@@ -602,6 +614,7 @@ impl AttrsOwned {
cache_key_flags: attrs.cache_key_flags,
metrics_opt: attrs.metrics_opt,
letter_spacing_opt: attrs.letter_spacing_opt,
+ word_spacing_opt: attrs.word_spacing_opt,
font_features: attrs.font_features.clone(),
font_variations: attrs.font_variations.clone(),
css_line_break: attrs.css_line_break,
@@ -623,6 +636,7 @@ impl AttrsOwned {
cache_key_flags: self.cache_key_flags,
metrics_opt: self.metrics_opt,
letter_spacing_opt: self.letter_spacing_opt,
+ word_spacing_opt: self.word_spacing_opt,
font_features: self.font_features.clone(),
font_variations: self.font_variations.clone(),
css_line_break: self.css_line_break,
diff --git a/vendor/cosmic-text/src/shape.rs b/vendor/cosmic-text/src/shape.rs
index 0799edab..f3e1a61a 100644
--- a/vendor/cosmic-text/src/shape.rs
+++ b/vendor/cosmic-text/src/shape.rs
@@ -272,7 +272,16 @@ fn shape_fallback(
}
_ => 0.0,
};
- let x_advance = pos.x_advance as f32 / font_scale + letter_spacing;
+ let word_spacing = attrs.word_spacing_opt.map_or(0.0, |spacing| {
+ let cluster_end = glyph_infos.get(glyph_index + 1)
+ .map_or(true, |next| next.cluster != info.cluster);
+ if cluster_end && matches!(line[start_glyph..].chars().next(), Some(' ' | '\u{00a0}')) {
+ spacing.0
+ } else {
+ 0.0
+ }
+ });
+ let x_advance = pos.x_advance as f32 / font_scale + letter_spacing + word_spacing;
let y_advance = pos.y_advance as f32 / font_scale;
let x_offset = pos.x_offset as f32 / font_scale;
let y_offset = pos.y_offset as f32 / font_scale;
@@ -590,7 +599,11 @@ fn shape_skip(
.char_indices()
.map(|(chr_idx, codepoint)| {
let glyph_id = charmap.map(codepoint);
- let x_advance = glyph_metrics.advance_width(glyph_id)
+ let word_attrs = attrs_list.get_span(start_run + chr_idx);
+ let word_spacing = if matches!(codepoint, ' ' | '\u{00a0}') {
+ word_attrs.word_spacing_opt.map_or(0.0, |spacing| spacing.0)
+ } else { 0.0 };
+ let x_advance = word_spacing + glyph_metrics.advance_width(glyph_id)
+ attrs.letter_spacing_opt.map_or(0.0, |spacing| spacing.0);
let attrs = attrs_list.get_span(start_run + chr_idx);