Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(fonts): share full descriptor capabilities with layout selection

ldm0e24bd4a69071
diff --git a/Cargo.lock b/Cargo.lock
index 8713e659b..1f6485a1f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3042,6 +3042,7 @@ dependencies = [
"brotlic",
"euclid",
"kurbo",
+ "moli-css-parse",
"moli-image",
"moli-system-fonts",
"moli-trace",
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/font_face_matching.py b/moli-cdp-smoke/moli_cdp_smoke/groups/font_face_matching.py
index 1954ff4a5..b19d52adf 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/groups/font_face_matching.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/font_face_matching.py
@@ -19,6 +19,38 @@ FONT_MATCHING_PROBE = r"""async ({narrowData, wideData}) => {
document.fonts.add(face);
return face;
};
+ const descriptorRanges = [];
+ for (const [property, range, single, request, changed] of [
+ ['weight','100 900','400','700','100'],
+ ['stretch','75% 125%','100%','expanded','75%'],
+ ['style','oblique 10deg 30deg','oblique 20deg','oblique 30deg','oblique 10deg'],
+ ['weight','calc(100 + 200) calc(800 + 100)','700','800','100'],
+ ['stretch','calc(50% + 25%) calc(100% + 25%)','100%','expanded','75%'],
+ ['style','oblique calc(5deg + 5deg) calc(15deg + 15deg)','oblique 20deg','oblique 30deg','oblique 10deg'],
+ ['weight','900 100','400','700','100'],
+ ['stretch','125% 75%','100%','expanded','75%'],
+ ['style','oblique 30deg 10deg','oblique 20deg','oblique 30deg','oblique 10deg'],
+ ]) {
+ const family = 'GeometryRange' + descriptorRanges.length;
+ const good = new FontFace(family, bytes(wideData), {[property]:range});
+ const other = new FontFace(family, bytes(narrowData), {[property]:single});
+ document.fonts.add(good); document.fonts.add(other);
+ const matches = await document.fonts.load(`${request} 40px ${family}`, 'AAAA');
+ const target = document.createElement('span');
+ target.textContent = 'AAAA'; target.style.cssText = `display:inline-block;font:${request} 40px ${family}`;
+ document.body.append(target);
+ const result = [matches.length, matches[0] === good, target.getBoundingClientRect().width];
+ good[property] = changed;
+ result.push(target.getBoundingClientRect().width);
+ // Use a fresh family to distinguish stale selection from descriptor parsing.
+ const freshFamily = family + 'Fresh';
+ const replacement = new FontFace(freshFamily, bytes(wideData), {[property]: good[property]});
+ const freshOther = new FontFace(freshFamily, bytes(narrowData), {[property]: single});
+ document.fonts.add(replacement); document.fonts.add(freshOther);
+ target.style.fontFamily = freshFamily;
+ result.push(target.getBoundingClientRect().width);
+ descriptorRanges.push(result);
+ }
const range = bad('ReviewRange', {unicodeRange: 'U+0041'});
const text = {
checks: ['B', ''].map(text => document.fonts.check('16px ReviewRange', text)),
@@ -122,12 +154,13 @@ FONT_MATCHING_PROBE = r"""async ({narrowData, wideData}) => {
const owners = [widths()];
document.fonts.delete(narrow); document.fonts.add(narrow); owners.push(widths());
child.fonts.delete(wide); child.fonts.add(wide); owners.push(widths());
- return {text, properties, calculations, capabilityBeforeRange, descriptorWrites, scalars, familyOrder,
+ return {descriptorRanges, text, properties, calculations, capabilityBeforeRange, descriptorWrites, scalars, familyOrder,
order, cssVsManual, lateCss, owners};
}"""
EXPECTED_FONT_MATCHING = {
+ "descriptorRanges": [[1, True, 160, 80, 80] for _ in range(9)],
"text": {"checks": [True, True], "loads": [[], []], "status": "unloaded", "included": False},
"properties": [
[True, ["ReviewWeight"], "unloaded", False],
@@ -166,10 +199,13 @@ async def run_font_matching_contract(browser: Any, fixture: str, results: list[d
await page.goto(f"{fixture}/plain", wait_until="load", timeout=10_000)
observed = await page.evaluate(FONT_MATCHING_PROBE, font_matching_payload())
expected = EXPECTED_FONT_MATCHING
- # The pinned CI Chromium build reports true immediately after the
- # weight setter. Moli and Chromium 147 keep the strict false result.
+ # Chromium 145.0.7632.6 retains stale selection metadata after a
+ # descriptor write, in both check() and layout. A fresh equivalent family
+ # must still select correctly. Moli and Chromium 147 use the updated
+ # descriptor immediately; keep those assertions strict.
if not is_moli_browser() and browser.version == "145.0.7632.6":
- expected = {**expected, "descriptorWrites": [True, True, True, False]}
+ expected = {**expected, "descriptorWrites": [True, True, True, False],
+ "descriptorRanges": [[1, True, 160, 160, 80] for _ in range(9)]}
assert_equal(observed, expected, "FontFaceSet matching and per-document selection order")
record_contract(
results,
diff --git a/moli-css-parse/src/font_selection.rs b/moli-css-parse/src/font_selection.rs
new file mode 100644
index 000000000..47aa359f3
--- /dev/null
+++ b/moli-css-parse/src/font_selection.rs
@@ -0,0 +1,306 @@
+use std::cmp::Ordering;
+
+use crate::{CssNumericContext, CssNumericKind, UnitlessAngle};
+
+fn components(mut value: &str) -> Vec<&str> {
+ let mut values = Vec::new();
+ while !value.trim_start().is_empty() {
+ value = value.trim_start();
+ let word_end = value.find(char::is_whitespace).unwrap_or(value.len());
+ let len = if value.find('(').is_some_and(|index| index < word_end) {
+ crate::balanced_function_len(value).unwrap_or(value.len())
+ } else {
+ word_end
+ };
+ values.push(&value[..len]);
+ value = &value[len..];
+ }
+ values
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct FontSelectionRange {
+ pub min: f32,
+ pub max: f32,
+}
+
+impl FontSelectionRange {
+ pub fn new(first: f32, second: f32) -> Self {
+ Self {
+ min: first.min(second),
+ max: first.max(second),
+ }
+ }
+
+ fn parse(value: &str, parse: impl Fn(&str) -> Option<f32>, initial: f32) -> Self {
+ let mut values = components(value).into_iter();
+ let min = values.next().and_then(&parse).unwrap_or(initial);
+ let max = values.next().and_then(parse).unwrap_or(min);
+ Self::new(min, max)
+ }
+
+ fn contains(self, value: f32) -> bool {
+ self.min <= value && value <= self.max
+ }
+
+ fn width_rank(self, requested: f32) -> (u8, f32) {
+ if self.contains(requested) {
+ (0, 0.0)
+ } else if requested <= 100.0 {
+ if self.max < requested {
+ (1, requested - self.max)
+ } else {
+ (2, self.min - requested)
+ }
+ } else if self.min > requested {
+ (1, self.min - requested)
+ } else {
+ (2, requested - self.max)
+ }
+ }
+
+ fn weight_rank(self, requested: f32) -> (u8, f32) {
+ if self.contains(requested) {
+ return (0, 0.0);
+ }
+ if (400.0..=500.0).contains(&requested) {
+ if self.min > requested && self.min <= 500.0 {
+ (1, self.min - requested)
+ } else if self.max < requested {
+ (2, requested - self.max)
+ } else {
+ (3, self.min - 500.0)
+ }
+ } else if requested < 400.0 {
+ if self.max < requested {
+ (1, requested - self.max)
+ } else {
+ (2, self.min - requested)
+ }
+ } else if self.min > requested {
+ (1, self.min - requested)
+ } else {
+ (2, requested - self.max)
+ }
+ }
+
+ fn style_rank(self, requested: f32) -> (u8, f32) {
+ if self.contains(requested) {
+ return (0, 0.0);
+ }
+ // Match Blink's slope search: italic and the default oblique slope are
+ // 14deg, with asymmetric fallback on either side of zero and +/-14deg.
+ if requested >= 14.0 {
+ if self.min > requested {
+ (1, self.min - requested)
+ } else {
+ (2, requested - self.max)
+ }
+ } else if requested >= 0.0 {
+ if self.max >= 0.0 && self.max < requested {
+ (1, requested - self.max)
+ } else if self.min > requested {
+ (2, self.min)
+ } else {
+ (3, -self.max)
+ }
+ } else if requested > -14.0 {
+ if self.min > requested && self.min <= 0.0 {
+ (1, self.min - requested)
+ } else if self.max < requested {
+ (2, -self.max)
+ } else {
+ (3, self.min)
+ }
+ } else if self.max < requested {
+ (1, requested - self.max)
+ } else {
+ (2, self.min - requested)
+ }
+ }
+}
+
+/// Font capabilities are selected before testing unicode-range, and do not
+/// depend on whether the source has been loaded or contains a particular glyph.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct FontSelectionCapabilities {
+ pub width: FontSelectionRange,
+ pub slope: FontSelectionRange,
+ pub weight: FontSelectionRange,
+}
+
+impl FontSelectionCapabilities {
+ pub fn new(weight: &str, stretch: &str, style: &str) -> Self {
+ let angles = components(style);
+ let angle = |value: &str| {
+ crate::resolve_css_numeric(
+ value,
+ CssNumericKind::Angle(UnitlessAngle::ZeroOnly),
+ CssNumericContext::default(),
+ )
+ .and_then(|value| value.angle_degrees())
+ .map(|value| (value as f32).clamp(-90.0, 90.0))
+ };
+ let min = match angles.first().copied() {
+ Some("italic") => 14.0,
+ Some("oblique") => angles.get(1).and_then(|value| angle(value)).unwrap_or(14.0),
+ _ => 0.0,
+ };
+ let max = angles.get(2).and_then(|value| angle(value)).unwrap_or(min);
+ let weight_value = |value: &str| match value {
+ // FontFaceSet resolves relative weights against initial normal.
+ "bolder" => Some(700.0),
+ "lighter" => Some(100.0),
+ _ => crate::resolve_css_number(value, None)
+ .map(|value| (value as f32).clamp(1.0, 1000.0))
+ .or(match value {
+ "normal" => Some(400.0),
+ "bold" => Some(700.0),
+ _ => None,
+ }),
+ };
+ let width_value = |value: &str| {
+ match value {
+ "ultra-condensed" => Some(50.0),
+ "extra-condensed" => Some(62.5),
+ "condensed" => Some(75.0),
+ "semi-condensed" => Some(87.5),
+ "normal" => Some(100.0),
+ "semi-expanded" => Some(112.5),
+ "expanded" => Some(125.0),
+ "extra-expanded" => Some(150.0),
+ "ultra-expanded" => Some(200.0),
+ _ => None,
+ }
+ .or_else(|| {
+ crate::resolve_css_numeric(
+ value,
+ CssNumericKind::Percentage,
+ CssNumericContext::default(),
+ )
+ .and_then(|value| value.percentage())
+ .map(|value| value as f32)
+ })
+ };
+ Self {
+ width: FontSelectionRange::parse(stretch, width_value, 100.0),
+ slope: FontSelectionRange::new(min, max),
+ weight: FontSelectionRange::parse(weight, weight_value, 400.0),
+ }
+ }
+
+ /// Capabilities from a single font or one computed style request.
+ pub fn single(weight: f32, width: f32, slope: f32) -> Self {
+ Self {
+ weight: FontSelectionRange::new(weight, weight),
+ width: FontSelectionRange::new(width, width),
+ slope: FontSelectionRange::new(slope, slope),
+ }
+ }
+
+ pub fn compare(self, other: Self, requested: Self) -> Ordering {
+ let first = [
+ self.width.width_rank(requested.width.min),
+ self.slope.style_rank(requested.slope.min),
+ self.weight.weight_rank(requested.weight.min),
+ ];
+ let second = [
+ other.width.width_rank(requested.width.min),
+ other.slope.style_rank(requested.slope.min),
+ other.weight.weight_rank(requested.weight.min),
+ ];
+ for (first, second) in first.into_iter().zip(second) {
+ let ordering = first
+ .0
+ .cmp(&second.0)
+ .then_with(|| first.1.total_cmp(&second.1));
+ if ordering != Ordering::Equal {
+ return ordering;
+ }
+ }
+ Ordering::Equal
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn weight_search_prefers_500_then_lower_weights_before_600_for_normal() {
+ let face = |weight| FontSelectionCapabilities::new(weight, "normal", "normal");
+ assert_eq!(
+ face("500").compare(face("300"), face("400")),
+ Ordering::Less
+ );
+ assert_eq!(
+ face("300").compare(face("600"), face("400")),
+ Ordering::Less
+ );
+ assert_eq!(
+ face("400").compare(face("500"), face("450")),
+ Ordering::Greater
+ );
+ assert_eq!(
+ face("600").compare(face("400"), face("550")),
+ Ordering::Less
+ );
+ }
+
+ #[test]
+ fn descriptor_ranges_and_width_then_style_then_weight_control_matching() {
+ let query = FontSelectionCapabilities::new("700", "normal", "oblique 20deg");
+ assert_eq!(
+ FontSelectionCapabilities::new("100 900", "normal", "oblique 10deg 30deg").compare(
+ FontSelectionCapabilities::new("700", "normal", "normal"),
+ query
+ ),
+ Ordering::Less
+ );
+ assert_eq!(
+ FontSelectionCapabilities::new("400", "normal", "normal").compare(
+ FontSelectionCapabilities::new("700", "condensed", "oblique 20deg"),
+ query
+ ),
+ Ordering::Less
+ );
+ let narrow = FontSelectionCapabilities::new("400", "75%", "normal");
+ let wide = FontSelectionCapabilities::new("400", "125%", "normal");
+ assert_eq!(
+ narrow.compare(
+ wide,
+ FontSelectionCapabilities::new("400", "normal", "normal")
+ ),
+ Ordering::Less
+ );
+ assert_eq!(
+ narrow.compare(
+ wide,
+ FontSelectionCapabilities::new("400", "110%", "normal")
+ ),
+ Ordering::Greater
+ );
+ }
+
+ #[test]
+ fn calculation_components_keep_whitespace_and_descriptor_range_boundaries() {
+ let ranged = FontSelectionCapabilities::new(
+ "calc(100 + 200) calc(800 - 100)",
+ "calc(50% + 25%) calc(100% + 25%)",
+ "oblique calc(5deg + 5deg) calc(15deg + 15deg)",
+ );
+ let requested = FontSelectionCapabilities::new(
+ "calc(400 + 100)",
+ "normal",
+ "oblique calc(10deg + 10deg)",
+ );
+ assert_eq!(
+ ranged.compare(
+ FontSelectionCapabilities::new("400", "normal", "normal"),
+ requested
+ ),
+ Ordering::Less,
+ "ranged={ranged:?}, requested={requested:?}"
+ );
+ }
+}
diff --git a/moli-css-parse/src/lib.rs b/moli-css-parse/src/lib.rs
index 7e7e1785d..627f64258 100644
--- a/moli-css-parse/src/lib.rs
+++ b/moli-css-parse/src/lib.rs
@@ -7,6 +7,7 @@ mod color;
mod declaration;
mod font_face;
mod font_palette;
+mod font_selection;
mod math;
mod root_margin;
mod stylo_stylesheet;
@@ -27,6 +28,7 @@ pub use font_face::{
pub use font_palette::{
CssFontPaletteValuesProperty, parse_font_palette_values_property_with_stylo,
};
+pub use font_selection::{FontSelectionCapabilities, FontSelectionRange};
pub use math::{
ContainerQueryLengthContext, CssNumericContext, CssNumericKind, CssNumericValue, UnitlessAngle,
UnitlessLength, balanced_function_len, css_number_value_is_supported,
diff --git a/moli-layout/Cargo.toml b/moli-layout/Cargo.toml
index 908986004..1f4045682 100644
--- a/moli-layout/Cargo.toml
+++ b/moli-layout/Cargo.toml
@@ -8,6 +8,7 @@ license.workspace = true
brotlic = "0.8.2"
euclid = "=0.22.14"
kurbo = "=0.13.1"
+moli-css-parse = { path = "../moli-css-parse" }
moli-image = { path = "../moli-image" }
moli-system-fonts = { path = "../moli-system-fonts" }
moli-trace = { path = "../moli-trace" }
diff --git a/moli-layout/src/text.rs b/moli-layout/src/text.rs
index 46c82b358..9809cb06f 100644
--- a/moli-layout/src/text.rs
+++ b/moli-layout/src/text.rs
@@ -11,6 +11,7 @@ use std::{
sync::Arc,
};
+use moli_css_parse::{FontSelectionCapabilities as WebFontCapabilities, FontSelectionRange};
use moli_system_fonts::SystemFontFamilyResolver;
use parley::{
FontContext, FontFamily, FontFamilyName, LayoutContext, TextStyle,
@@ -53,16 +54,23 @@ const MAX_FONT_FAMILY_RESOLUTION_PLANS: usize = 1024;
const MAX_CHARACTER_RESOLUTIONS_PER_PLAN: usize = 4096;
const MAX_INLINE_FONT_METRICS_CACHE_ENTRIES: usize = 1024;
-#[derive(Clone, Copy, Debug, PartialEq)]
-struct WebFontCapabilities {
- width: FontWidth,
- style: FontStyle,
- weight: FontWeight,
+fn font_selection_capabilities(attributes: Attributes) -> WebFontCapabilities {
+ let slope = match attributes.style {
+ FontStyle::Normal => 0.0,
+ FontStyle::Italic => 14.0,
+ FontStyle::Oblique(angle) => angle.unwrap_or(14.0),
+ };
+ WebFontCapabilities::single(
+ attributes.weight.value(),
+ attributes.width.percentage(),
+ slope,
+ )
}
#[derive(Clone, Debug)]
struct SegmentedWebFontFace {
internal_family_name: String,
+ source_order: usize,
unicode_ranges: Vec<WebFontUnicodeRange>,
}
@@ -79,7 +87,6 @@ impl SegmentedWebFontFace {
#[derive(Clone, Debug)]
struct SegmentedWebFontCapabilityGroup {
capabilities: WebFontCapabilities,
- selector_font_identities: Vec<(u64, u32)>,
faces: Vec<SegmentedWebFontFace>,
}
@@ -269,39 +276,33 @@ impl ParleyDocumentServices {
continue;
}
- let selected_identity = {
- let FontContext {
- collection,
- source_cache,
- } = &mut self.font_context;
- let mut query = collection.query(source_cache);
- query.set_families([QueryFamily::Named(name)]);
- query.set_attributes(attributes);
- let mut identity = None;
- query.matches_with(|font| {
- identity = Some((font.blob.id(), font.index));
- QueryStatus::Stop
- });
- identity
- };
- let Some(selected_identity) = selected_identity else {
- resolved.push(family);
- continue;
- };
- let Some(group) = self.web_font_families[&family_key]
- .groups
+ let groups = &self.web_font_families[&family_key].groups;
+ let requested = font_selection_capabilities(attributes);
+ let Some(best) = groups
.iter()
- .find(|group| group.selector_font_identities.contains(&selected_identity))
+ .min_by(|first, second| first.capabilities.compare(second.capabilities, requested))
else {
resolved.push(family);
continue;
};
+ // Overlapping ranges can tie even when their endpoints differ.
+ // Keep all best matches in this Document's FontFaceSet order.
+ let mut faces = groups
+ .iter()
+ .filter(|group| {
+ group
+ .capabilities
+ .compare(best.capabilities, requested)
+ .is_eq()
+ })
+ .flat_map(|group| &group.faces)
+ .collect::<Vec<_>>();
+ faces.sort_by_key(|face| face.source_order);
let default_uses_latin_metrics =
- character.is_none() && group.faces.iter().any(|face| face.contains('x'));
+ character.is_none() && faces.iter().any(|face| face.contains('x'));
resolved.extend(
- group
- .faces
- .iter()
+ faces
+ .into_iter()
.rev()
.filter(|face| match character {
Some(character) => face.contains(character),
@@ -518,6 +519,7 @@ pub struct WebFontFace {
weight: Option<f32>,
stretch: Option<f32>,
style: Option<WebFontStyle>,
+ capabilities: Option<WebFontCapabilities>,
unicode_ranges: Vec<WebFontUnicodeRange>,
}
@@ -528,22 +530,53 @@ impl WebFontFace {
weight: None,
stretch: None,
style: None,
+ capabilities: None,
unicode_ranges: Vec::new(),
}
}
pub fn with_weight(mut self, weight: f32) -> Self {
self.weight = Some(weight);
+ if let Some(capabilities) = &mut self.capabilities {
+ capabilities.weight = FontSelectionRange::new(weight, weight);
+ }
self
}
pub fn with_stretch(mut self, percentage: f32) -> Self {
self.stretch = Some(percentage);
+ if let Some(capabilities) = &mut self.capabilities {
+ capabilities.width = FontSelectionRange::new(percentage, percentage);
+ }
self
}
pub fn with_style(mut self, style: WebFontStyle) -> Self {
self.style = Some(style);
+ if let Some(capabilities) = &mut self.capabilities {
+ let slope = match style {
+ WebFontStyle::Normal => 0.0,
+ WebFontStyle::Italic => 14.0,
+ WebFontStyle::Oblique(angle) => angle.unwrap_or(14.0),
+ };
+ capabilities.slope = FontSelectionRange::new(slope, slope);
+ }
+ self
+ }
+
+ /// Retains full computed CSS capabilities for selection before shaping.
+ /// Fontique's scalar overrides describe the physical internal family;
+ /// they must not reduce a CSS range to one point for family selection.
+ pub fn with_css_descriptors(mut self, weight: &str, stretch: &str, style: &str) -> Self {
+ let capabilities = WebFontCapabilities::new(weight, stretch, style);
+ self.weight = Some(capabilities.weight.min);
+ self.stretch = Some(capabilities.width.min);
+ self.style = Some(match style.split_ascii_whitespace().next() {
+ Some("italic") => WebFontStyle::Italic,
+ Some("oblique") => WebFontStyle::Oblique(Some(capabilities.slope.min)),
+ _ => WebFontStyle::Normal,
+ });
+ self.capabilities = Some(capabilities);
self
}
@@ -1020,11 +1053,13 @@ fn build_parley_services(
.or_default();
for (_, fonts) in selector_fonts {
for selector_font in fonts {
- let capabilities = WebFontCapabilities {
- width: selector_font.width(),
- style: selector_font.style(),
- weight: selector_font.weight(),
- };
+ let capabilities = font.face.capabilities.unwrap_or_else(|| {
+ font_selection_capabilities(Attributes::new(
+ selector_font.width(),
+ selector_font.style(),
+ selector_font.weight(),
+ ))
+ });
let group_index = family
.groups
.iter()
@@ -1033,15 +1068,11 @@ fn build_parley_services(
let index = family.groups.len();
family.groups.push(SegmentedWebFontCapabilityGroup {
capabilities,
- selector_font_identities: Vec::new(),
faces: Vec::new(),
});
index
});
let group = &mut family.groups[group_index];
- group
- .selector_font_identities
- .push((blob.id(), selector_font.index()));
if !group
.faces
.iter()
@@ -1049,6 +1080,7 @@ fn build_parley_services(
{
group.faces.push(SegmentedWebFontFace {
internal_family_name: internal_family_name.clone(),
+ source_order,
unicode_ranges: font.face.unicode_ranges.clone(),
});
}
diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/query/selection.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/query/selection.rs
index d95f05207..875c0c632 100644
--- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/query/selection.rs
+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/query/selection.rs
@@ -1,265 +1 @@
-use std::cmp::Ordering;
-
-use crate::css_resource_urls::{parse_font_stretch_lower_bound, parse_font_weight_lower_bound};
-use moli_css_parse::{CssNumericContext, CssNumericKind, UnitlessAngle};
-
-fn components(mut value: &str) -> Vec<&str> {
- let mut values = Vec::new();
- while !value.trim_start().is_empty() {
- value = value.trim_start();
- let word_end = value.find(char::is_whitespace).unwrap_or(value.len());
- let len = if value.find('(').is_some_and(|index| index < word_end) {
- moli_css_parse::balanced_function_len(value).unwrap_or(value.len())
- } else {
- word_end
- };
- values.push(&value[..len]);
- value = &value[len..];
- }
- values
-}
-
-#[derive(Clone, Copy, Debug)]
-struct Range {
- min: f32,
- max: f32,
-}
-
-impl Range {
- fn new(first: f32, second: f32) -> Self {
- Self {
- min: first.min(second),
- max: first.max(second),
- }
- }
-
- fn parse(value: &str, parse: impl Fn(&str) -> Option<f32>, initial: f32) -> Self {
- let mut values = components(value).into_iter();
- let min = values.next().and_then(&parse).unwrap_or(initial);
- let max = values.next().and_then(parse).unwrap_or(min);
- Self::new(min, max)
- }
-
- fn contains(self, value: f32) -> bool {
- self.min <= value && value <= self.max
- }
-
- fn width_rank(self, requested: f32) -> (u8, f32) {
- if self.contains(requested) {
- (0, 0.0)
- } else if requested <= 100.0 {
- if self.max < requested {
- (1, requested - self.max)
- } else {
- (2, self.min - requested)
- }
- } else if self.min > requested {
- (1, self.min - requested)
- } else {
- (2, requested - self.max)
- }
- }
-
- fn weight_rank(self, requested: f32) -> (u8, f32) {
- if self.contains(requested) {
- return (0, 0.0);
- }
- if (400.0..=500.0).contains(&requested) {
- if self.min > requested && self.min <= 500.0 {
- (1, self.min - requested)
- } else if self.max < requested {
- (2, requested - self.max)
- } else {
- (3, self.min - 500.0)
- }
- } else if requested < 400.0 {
- if self.max < requested {
- (1, requested - self.max)
- } else {
- (2, self.min - requested)
- }
- } else if self.min > requested {
- (1, self.min - requested)
- } else {
- (2, requested - self.max)
- }
- }
-
- fn style_rank(self, requested: f32) -> (u8, f32) {
- if self.contains(requested) {
- return (0, 0.0);
- }
- // Match Blink's slope search: italic and the default oblique slope are
- // 14deg, with asymmetric fallback on either side of zero and +/-14deg.
- if requested >= 14.0 {
- if self.min > requested {
- (1, self.min - requested)
- } else {
- (2, requested - self.max)
- }
- } else if requested >= 0.0 {
- if self.max >= 0.0 && self.max < requested {
- (1, requested - self.max)
- } else if self.min > requested {
- (2, self.min)
- } else {
- (3, -self.max)
- }
- } else if requested > -14.0 {
- if self.min > requested && self.min <= 0.0 {
- (1, self.min - requested)
- } else if self.max < requested {
- (2, -self.max)
- } else {
- (3, self.min)
- }
- } else if self.max < requested {
- (1, requested - self.max)
- } else {
- (2, self.min - requested)
- }
- }
-}
-
-/// Font capabilities are selected before testing unicode-range, and do not
-/// depend on whether the source has been loaded or contains a particular glyph.
-#[derive(Clone, Copy, Debug)]
-pub(super) struct Selection {
- width: Range,
- slope: Range,
- weight: Range,
-}
-
-impl Selection {
- pub(super) fn new(weight: &str, stretch: &str, style: &str) -> Self {
- let angles = components(style);
- let angle = |value: &str| {
- moli_css_parse::resolve_css_numeric(
- value,
- CssNumericKind::Angle(UnitlessAngle::ZeroOnly),
- CssNumericContext::default(),
- )
- .and_then(|value| value.angle_degrees())
- .map(|value| (value as f32).clamp(-90.0, 90.0))
- };
- let min = match angles.first().copied() {
- Some("italic") => 14.0,
- Some("oblique") => angles.get(1).and_then(|value| angle(value)).unwrap_or(14.0),
- _ => 0.0,
- };
- let max = angles.get(2).and_then(|value| angle(value)).unwrap_or(min);
- let weight_value = |value: &str| match value {
- // FontFaceSet resolves relative weights against initial normal.
- "bolder" => Some(700.0),
- "lighter" => Some(100.0),
- _ => moli_css_parse::resolve_css_number(value, None)
- .map(|value| (value as f32).clamp(1.0, 1000.0))
- .or_else(|| parse_font_weight_lower_bound(value)),
- };
- let width_value = |value: &str| {
- parse_font_stretch_lower_bound(value).or_else(|| {
- moli_css_parse::resolve_css_numeric(
- value,
- CssNumericKind::Percentage,
- CssNumericContext::default(),
- )
- .and_then(|value| value.percentage())
- .map(|value| value as f32)
- })
- };
- Self {
- width: Range::parse(stretch, width_value, 100.0),
- slope: Range::new(min, max),
- weight: Range::parse(weight, weight_value, 400.0),
- }
- }
-
- pub(super) fn compare(self, other: Self, requested: Self) -> Ordering {
- let first = [
- self.width.width_rank(requested.width.min),
- self.slope.style_rank(requested.slope.min),
- self.weight.weight_rank(requested.weight.min),
- ];
- let second = [
- other.width.width_rank(requested.width.min),
- other.slope.style_rank(requested.slope.min),
- other.weight.weight_rank(requested.weight.min),
- ];
- for (first, second) in first.into_iter().zip(second) {
- let ordering = first
- .0
- .cmp(&second.0)
- .then_with(|| first.1.total_cmp(&second.1));
- if ordering != Ordering::Equal {
- return ordering;
- }
- }
- Ordering::Equal
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn weight_search_prefers_500_then_lower_weights_before_600_for_normal() {
- let face = |weight| Selection::new(weight, "normal", "normal");
- assert_eq!(
- face("500").compare(face("300"), face("400")),
- Ordering::Less
- );
- assert_eq!(
- face("300").compare(face("600"), face("400")),
- Ordering::Less
- );
- assert_eq!(
- face("400").compare(face("500"), face("450")),
- Ordering::Greater
- );
- assert_eq!(
- face("600").compare(face("400"), face("550")),
- Ordering::Less
- );
- }
-
- #[test]
- fn descriptor_ranges_and_width_then_style_then_weight_control_matching() {
- let query = Selection::new("700", "normal", "oblique 20deg");
- assert_eq!(
- Selection::new("100 900", "normal", "oblique 10deg 30deg")
- .compare(Selection::new("700", "normal", "normal"), query),
- Ordering::Less
- );
- assert_eq!(
- Selection::new("400", "normal", "normal")
- .compare(Selection::new("700", "condensed", "oblique 20deg"), query),
- Ordering::Less
- );
- let narrow = Selection::new("400", "75%", "normal");
- let wide = Selection::new("400", "125%", "normal");
- assert_eq!(
- narrow.compare(wide, Selection::new("400", "normal", "normal")),
- Ordering::Less
- );
- assert_eq!(
- narrow.compare(wide, Selection::new("400", "110%", "normal")),
- Ordering::Greater
- );
- }
-
- #[test]
- fn calculation_components_keep_whitespace_and_descriptor_range_boundaries() {
- let ranged = Selection::new(
- "calc(100 + 200) calc(800 - 100)",
- "calc(50% + 25%) calc(100% + 25%)",
- "oblique calc(5deg + 5deg) calc(15deg + 15deg)",
- );
- let requested = Selection::new("calc(400 + 100)", "normal", "oblique calc(10deg + 10deg)");
- assert_eq!(
- ranged.compare(Selection::new("400", "normal", "normal"), requested),
- Ordering::Less,
- "ranged={ranged:?}, requested={requested:?}"
- );
- }
-}
+pub(super) use moli_css_parse::FontSelectionCapabilities as Selection;
diff --git a/moli-renderer-v8/src/css_resource_urls.rs b/moli-renderer-v8/src/css_resource_urls.rs
index 72d467158..1fee945a0 100644
--- a/moli-renderer-v8/src/css_resource_urls.rs
+++ b/moli-renderer-v8/src/css_resource_urls.rs
@@ -4,7 +4,7 @@ use moli_css_parse::{
DeclarationParseOptions, parse_declaration_list, parse_font_face_rule_view_with_stylo,
parse_font_faces, parse_stylesheet_rule_snapshots_with_stylo,
};
-use moli_layout::{WebFontFace, WebFontStyle, WebFontUnicodeRange};
+use moli_layout::{WebFontFace, WebFontUnicodeRange};
use url::Url;
use crate::protocol_types::OptionalResourceFetchMask;
@@ -245,9 +245,9 @@ fn collect_font_face_rule_css(rules: &[moli_css_parse::CssRuleSnapshot], output:
struct ParsedWebFontFace {
family: String,
source: String,
- weight: Option<f32>,
- stretch: Option<f32>,
- style: Option<WebFontStyle>,
+ weight: String,
+ stretch: String,
+ style: String,
unicode_ranges: Vec<WebFontUnicodeRange>,
}
@@ -257,17 +257,9 @@ impl ParsedWebFontFace {
}
fn into_face(self) -> WebFontFace {
- let mut face = WebFontFace::new(self.family);
- if let Some(weight) = self.weight {
- face = face.with_weight(weight);
- }
- if let Some(stretch) = self.stretch {
- face = face.with_stretch(stretch);
- }
- if let Some(style) = self.style {
- face = face.with_style(style);
- }
- face.with_unicode_ranges(self.unicode_ranges)
+ WebFontFace::new(self.family)
+ .with_css_descriptors(&self.weight, &self.stretch, &self.style)
+ .with_unicode_ranges(self.unicode_ranges)
}
}
@@ -292,9 +284,9 @@ fn parsed_web_font_face(css_text: &str) -> Option<ParsedWebFontFace> {
Some(ParsedWebFontFace {
family: parsed.family,
source: parsed.source,
- weight: descriptor("font-weight").and_then(parse_font_weight_lower_bound),
- stretch: descriptor("font-stretch").and_then(parse_font_stretch_lower_bound),
- style: descriptor("font-style").and_then(parse_font_style_lower_bound),
+ weight: descriptor("font-weight").unwrap_or("normal").to_owned(),
+ stretch: descriptor("font-stretch").unwrap_or("normal").to_owned(),
+ style: descriptor("font-style").unwrap_or("normal").to_owned(),
unicode_ranges: descriptor("unicode-range")
.and_then(parse_font_unicode_ranges)
.unwrap_or_default(),
@@ -312,61 +304,6 @@ pub(crate) fn parse_font_unicode_ranges(value: &str) -> Option<Vec<WebFontUnicod
.ok()
}
-pub(crate) fn parse_font_weight_lower_bound(value: &str) -> Option<f32> {
- match value
- .split_ascii_whitespace()
- .next()?
- .to_ascii_lowercase()
- .as_str()
- {
- "normal" => Some(400.0),
- "bold" => Some(700.0),
- value => value
- .parse::<f32>()
- .ok()
- .filter(|value| (1.0..=1000.0).contains(value)),
- }
-}
-
-pub(crate) fn parse_font_stretch_lower_bound(value: &str) -> Option<f32> {
- let value = value.split_ascii_whitespace().next()?.to_ascii_lowercase();
- let percentage = match value.as_str() {
- "ultra-condensed" => 50.0,
- "extra-condensed" => 62.5,
- "condensed" => 75.0,
- "semi-condensed" => 87.5,
- "normal" => 100.0,
- "semi-expanded" => 112.5,
- "expanded" => 125.0,
- "extra-expanded" => 150.0,
- "ultra-expanded" => 200.0,
- value => value.strip_suffix('%')?.parse::<f32>().ok()?,
- };
- (percentage > 0.0 && percentage.is_finite()).then_some(percentage)
-}
-
-pub(crate) fn parse_font_style_lower_bound(value: &str) -> Option<WebFontStyle> {
- let mut values = value.split_ascii_whitespace();
- match values.next()?.to_ascii_lowercase().as_str() {
- "normal" => Some(WebFontStyle::Normal),
- "italic" => Some(WebFontStyle::Italic),
- "oblique" => Some(WebFontStyle::Oblique(
- values.next().and_then(parse_css_angle_degrees),
- )),
- _ => None,
- }
-}
-
-fn parse_css_angle_degrees(value: &str) -> Option<f32> {
- let value = value.to_ascii_lowercase();
- let parse = |suffix: &str| value.strip_suffix(suffix)?.parse::<f32>().ok();
- parse("deg")
- .or_else(|| parse("grad").map(|value| value * 0.9))
- .or_else(|| parse("rad").map(f32::to_degrees))
- .or_else(|| parse("turn").map(|value| value * 360.0))
- .filter(|value| value.is_finite())
-}
-
pub(crate) use moli_css_parse::legacy_variations_font_format;
fn resolve_font_source_url(raw_url: &str, base_url: &Url) -> Option<Url> {
@@ -381,6 +318,7 @@ fn resolve_font_source_url(raw_url: &str, base_url: &Url) -> Option<Url> {
#[cfg(test)]
mod tests {
use super::*;
+ use moli_layout::WebFontStyle;
fn base_url() -> Url {
Url::parse("https://example.test/assets/app.css").expect("base URL should parse")
diff --git a/moli-renderer-v8/src/font_loading.rs b/moli-renderer-v8/src/font_loading.rs
index 3a0b525e6..31810fe0b 100644
--- a/moli-renderer-v8/src/font_loading.rs
+++ b/moli-renderer-v8/src/font_loading.rs
@@ -21,17 +21,11 @@ pub(crate) fn script_font_descriptor(
style: &str,
unicode_range: &str,
) -> WebFontFace {
- use crate::css_resource_urls::{
- parse_font_stretch_lower_bound, parse_font_style_lower_bound, parse_font_unicode_ranges,
- parse_font_weight_lower_bound,
- };
WebFontFace::new(moli_css_parse::unquote_css_string(family))
- .with_weight(parse_font_weight_lower_bound(weight).unwrap_or(400.0))
- .with_stretch(parse_font_stretch_lower_bound(stretch).unwrap_or(100.0))
- .with_style(
- parse_font_style_lower_bound(style).unwrap_or(moli_layout::WebFontStyle::Normal),
+ .with_css_descriptors(weight, stretch, style)
+ .with_unicode_ranges(
+ crate::css_resource_urls::parse_font_unicode_ranges(unicode_range).unwrap_or_default(),
)
- .with_unicode_ranges(parse_font_unicode_ranges(unicode_range).unwrap_or_default())
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/fonts.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/fonts.rs
index 09403e848..4e1cd41b8 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/fonts.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/fonts.rs
@@ -2,6 +2,7 @@ use super::*;
use base64::Engine;
use std::time::Duration;
+mod descriptor_ranges;
mod matching;
mod ownership;
mod readiness;
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/descriptor_ranges.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/descriptor_ranges.rs
new file mode 100644
index 000000000..e876ad0a3
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/descriptor_ranges.rs
@@ -0,0 +1,108 @@
+use super::selection_order::{order_font_data, order_vm};
+
+#[test]
+fn font_face_descriptor_ranges_select_the_same_face_for_queries_and_layout() {
+ let (narrow, wide) = order_font_data();
+ for (property, range, other, request, changed) in [
+ ("weight", "100 900", "400", "700", "100"),
+ ("stretch", "75% 125%", "100%", "expanded", "75%"),
+ (
+ "style",
+ "oblique 10deg 30deg",
+ "oblique 20deg",
+ "oblique 30deg",
+ "oblique 10deg",
+ ),
+ (
+ "weight",
+ "calc(100 + 200) calc(800 + 100)",
+ "700",
+ "800",
+ "100",
+ ),
+ (
+ "stretch",
+ "calc(50% + 25%) calc(100% + 25%)",
+ "100%",
+ "expanded",
+ "75%",
+ ),
+ (
+ "style",
+ "oblique calc(5deg + 5deg) calc(15deg + 15deg)",
+ "oblique 20deg",
+ "oblique 30deg",
+ "oblique 10deg",
+ ),
+ ("weight", "900 100", "400", "700", "100"),
+ ("stretch", "125% 75%", "100%", "expanded", "75%"),
+ (
+ "style",
+ "oblique 30deg 10deg",
+ "oblique 20deg",
+ "oblique 30deg",
+ "oblique 10deg",
+ ),
+ ] {
+ let mut vm = order_vm();
+ vm.eval(&format!(
+ r#"
+ const bytes=data=>Uint8Array.from(atob(data),c=>c.charCodeAt(0));
+ globalThis.good=new FontFace('OrderFace',bytes('{wide}'),{{{property}:'{range}'}});
+ globalThis.other=new FontFace('OrderFace',bytes('{narrow}'),{{{property}:'{other}'}});
+ document.fonts.add(good);document.fonts.add(other);
+ probe.style.font='{request} 40px OrderFace';
+ globalThis.selected=[];
+ document.fonts.load('{request} 40px OrderFace','AAAA').then(
+ faces=>selected.push(faces.length,faces[0]===good));
+ "#
+ ))
+ .unwrap();
+ assert_eq!(
+ vm.eval("JSON.stringify(selected)").unwrap(),
+ "[1,true]",
+ "{property}: {range}"
+ );
+ assert_eq!(
+ vm.eval("String(probe.getBoundingClientRect().width)")
+ .unwrap(),
+ "160",
+ "{property}: {range}"
+ );
+ vm.eval(&format!("good.{property}='{changed}'")).unwrap();
+ assert_eq!(
+ vm.eval("String(probe.getBoundingClientRect().width)")
+ .unwrap(),
+ "80",
+ "{property}: descriptor mutation"
+ );
+ }
+}
+
+#[test]
+fn font_face_overlapping_capability_ranges_follow_font_set_order() {
+ let (narrow, wide) = order_font_data();
+ let mut vm = order_vm();
+ vm.eval(&format!(
+ r#"
+ const bytes=data=>Uint8Array.from(atob(data),c=>c.charCodeAt(0));
+ globalThis.wide=new FontFace('OrderFace',bytes('{wide}'),{{weight:'100 900'}});
+ globalThis.narrow=new FontFace('OrderFace',bytes('{narrow}'),{{weight:'500 800'}});
+ document.fonts.add(wide);document.fonts.add(narrow);
+ probe.style.font='700 40px OrderFace';
+ "#
+ ))
+ .unwrap();
+ assert_eq!(
+ vm.eval("String(probe.getBoundingClientRect().width)")
+ .unwrap(),
+ "80"
+ );
+ vm.eval("document.fonts.delete(wide);document.fonts.add(wide)")
+ .unwrap();
+ assert_eq!(
+ vm.eval("String(probe.getBoundingClientRect().width)")
+ .unwrap(),
+ "160"
+ );
+}
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/selection_order.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/selection_order.rs
index ac96cf1c2..fbd5cc674 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/selection_order.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/selection_order.rs
@@ -1,6 +1,6 @@
use super::*;
-fn order_font_data() -> (String, String) {
+pub(super) fn order_font_data() -> (String, String) {
let encode = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes);
(
encode(include_bytes!(concat!(
@@ -14,7 +14,7 @@ fn order_font_data() -> (String, String) {
)
}
-fn order_vm() -> StandaloneScriptVmHarness {
+pub(super) fn order_vm() -> StandaloneScriptVmHarness {
let mut vm = new_parsed_test_vm(
"https://font-selection-order.test/",
"<!doctype html><html><head></head><body><span id='probe' style='display:inline-block;font:40px OrderFace'>AAAA</span><iframe id='frame'></iframe></body></html>",