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 native FontFace loading across CSS and JS

ldm0c7130a3059c8
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/font_face.py b/moli-cdp-smoke/moli_cdp_smoke/groups/font_face.py
index b14006825..35f6f43f8 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/groups/font_face.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/font_face.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import base64
from typing import Any
-from ..assertions import SmokeError, assert_equal, record_contract
+from ..assertions import assert_equal, record_contract
from ..config import REPO_ROOT
@@ -103,11 +103,11 @@ async def run_font_face_payload_group(
"error",
"malformed FontFace BufferSource is synchronously invalid",
)
- if observed.get("invalidInitial", [None, None])[1] not in {"unloaded", "error"}:
- raise SmokeError(
- "malformed data-URL FontFace has an invalid initial status: "
- f"{observed.get('invalidInitial')!r}"
- )
+ assert_equal(
+ observed.get("invalidInitial", [None, None])[1],
+ "unloaded",
+ "data-URL FontFace remains unloaded until load is requested",
+ )
assert_equal(
observed.get("invalidSamePromise"),
[True, True, True],
@@ -128,11 +128,11 @@ async def run_font_face_payload_group(
"loaded",
"valid offset BufferSource is parsed synchronously",
)
- if observed.get("validInitial", [None])[0] not in {"unloaded", "loaded"}:
- raise SmokeError(
- "valid data-URL FontFace has an invalid initial status: "
- f"{observed.get('validInitial')!r}"
- )
+ assert_equal(
+ observed.get("validInitial", [None])[0],
+ "unloaded",
+ "valid data-URL FontFace remains unloaded until load is requested",
+ )
assert_equal(
observed.get("validSamePromise"),
[True, True],
diff --git a/moli-core/tests/fixtures/runtime/chrome_fontfaceset_events_subset.html b/moli-core/tests/fixtures/runtime/chrome_fontfaceset_events_subset.html
index 4350f7687..05cc7dab8 100644
--- a/moli-core/tests/fixtures/runtime/chrome_fontfaceset_events_subset.html
+++ b/moli-core/tests/fixtures/runtime/chrome_fontfaceset_events_subset.html
@@ -2,6 +2,9 @@
<html>
<body data-order="" data-count="" data-ready-status="">
<script>
+ // Real project-generated font: moli-layout/tests/fixtures/moli-ahem.woff2.
+ const FONT_FIXTURE_SOURCE = "url(data:font/woff2;base64,d09GMgABAAAAAAKMAAoAAAAAEewAAAI9AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAARAqSGIlCATYCJAOBRguBRgAEIAWDDweHZhsaDBEVjE2QrxO4OaB11Uo4KkNFQmQIgNrHOq+V6mgnvY2fvSQ/uF+9N7PdNFuXpclV2mkpdFaAC3aRoEdFB3L8iVa3NRGchB7CA+kvmysBs3ExDyF+2La9iSrRM8x/YMEH4+YNnI6ADDhw44HnsPGNf2vg8Vh2oEcLbcza3qYp3gsXSOBToI2cQC+UhHthpAFIuk0EVfwGmbm3vt4jtOf5c3NBuwr0P4kB5kvBCdDgYzQftZAtCfcwRbHKu3S8ycdHAOfu8OUAmLjP+bEQEov+i78AFoAP+AEAxAAAAbQvPfKjw6g3kr+bmM88bAz4CAIItbXF3xu9/n2qfwCnW7usCnIKG0p4i7hd9+SA9QzCt8+eB2LUsMiFeojjkCtwessPXvTy47FKi+3KLnHVsltY375HzLDkOf6NhCkpi4iVsmpyVHYpuS67Fdw/4GE+R/a2N2xwfWXnu79JZ8nsauts62iP3v/+6UJH9FXrZ8WIPds2mEHrVuyYtGLNiW0L8jSL6zWd2nTMNs9acejIxsou80QHe+KtWi8h8LdYBGgJlS666aGXPvoZYJAhhhlhlDHGmbAhTCjjQiptrAMfhFGcpFlelFXdtF0/jNO8rNt+nNf9vB8AQjCCYjhBUjTDcrwgSrKiarphWrbjcb2+/jc6gLBCmFDGhVTaWBf+NANEmFDGhVTaWBf+tABEmFDGhVTaWBf+tAJEmFDGhVTaWBf+tAFEmFDGhVTaWBf+tANEmFDGhVTa2PClCtb3AQAAAA==)";
+ document.fonts.add(new FontFace('FixtureFace', FONT_FIXTURE_SOURCE));
const body = document.body;
const events = [];
@@ -10,7 +13,7 @@
document.fonts.onloadingerror = (event) => events.push(event.type);
document.fonts
- .load('10px sans-serif')
+ .load('10px FixtureFace')
.then(() => document.fonts.ready)
.then(() => {
body.setAttribute('data-order', events.join(','));
diff --git a/moli-core/tests/fixtures/runtime/document_fonts_events.html b/moli-core/tests/fixtures/runtime/document_fonts_events.html
index b7a7b4e3f..2b38954f9 100644
--- a/moli-core/tests/fixtures/runtime/document_fonts_events.html
+++ b/moli-core/tests/fixtures/runtime/document_fonts_events.html
@@ -2,6 +2,9 @@
<html>
<body data-loading-a="" data-loading-b="" data-loadingdone="">
<script>
+ // Real project-generated font: moli-layout/tests/fixtures/moli-ahem.woff2.
+ const FONT_FIXTURE_SOURCE = "url(data:font/woff2;base64,d09GMgABAAAAAAKMAAoAAAAAEewAAAI9AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAARAqSGIlCATYCJAOBRguBRgAEIAWDDweHZhsaDBEVjE2QrxO4OaB11Uo4KkNFQmQIgNrHOq+V6mgnvY2fvSQ/uF+9N7PdNFuXpclV2mkpdFaAC3aRoEdFB3L8iVa3NRGchB7CA+kvmysBs3ExDyF+2La9iSrRM8x/YMEH4+YNnI6ADDhw44HnsPGNf2vg8Vh2oEcLbcza3qYp3gsXSOBToI2cQC+UhHthpAFIuk0EVfwGmbm3vt4jtOf5c3NBuwr0P4kB5kvBCdDgYzQftZAtCfcwRbHKu3S8ycdHAOfu8OUAmLjP+bEQEov+i78AFoAP+AEAxAAAAbQvPfKjw6g3kr+bmM88bAz4CAIItbXF3xu9/n2qfwCnW7usCnIKG0p4i7hd9+SA9QzCt8+eB2LUsMiFeojjkCtwessPXvTy47FKi+3KLnHVsltY375HzLDkOf6NhCkpi4iVsmpyVHYpuS67Fdw/4GE+R/a2N2xwfWXnu79JZ8nsauts62iP3v/+6UJH9FXrZ8WIPds2mEHrVuyYtGLNiW0L8jSL6zWd2nTMNs9acejIxsou80QHe+KtWi8h8LdYBGgJlS666aGXPvoZYJAhhhlhlDHGmbAhTCjjQiptrAMfhFGcpFlelFXdtF0/jNO8rNt+nNf9vB8AQjCCYjhBUjTDcrwgSrKiarphWrbjcb2+/jc6gLBCmFDGhVTaWBf+NANEmFDGhVTaWBf+tABEmFDGhVTaWBf+tAJEmFDGhVTaWBf+tAFEmFDGhVTaWBf+tANEmFDGhVTa2PClCtb3AQAAAA==)";
+ document.fonts.add(new FontFace('Roboto', FONT_FIXTURE_SOURCE));
let loadingA = 0;
let loadingB = 0;
let loadingDone = 0;
@@ -22,11 +25,11 @@
document.fonts.addEventListener('loading', onLoadingB);
document.fonts.addEventListener('loadingdone', onLoadingDone);
document.fonts.removeEventListener('loading', onLoadingA);
- document.fonts.load('italic bold 16px Roboto');
-
- document.body.setAttribute('data-loading-a', String(loadingA));
- document.body.setAttribute('data-loading-b', String(loadingB));
- document.body.setAttribute('data-loadingdone', String(loadingDone));
+ document.fonts.load('italic bold 16px Roboto').then(() => document.fonts.ready).then(() => {
+ document.body.setAttribute('data-loading-a', String(loadingA));
+ document.body.setAttribute('data-loading-b', String(loadingB));
+ document.body.setAttribute('data-loadingdone', String(loadingDone));
+ });
</script>
</body>
</html>
diff --git a/moli-core/tests/fixtures/runtime/local_event_target_callback_exception.html b/moli-core/tests/fixtures/runtime/local_event_target_callback_exception.html
index 91ba69495..b365c92d6 100644
--- a/moli-core/tests/fixtures/runtime/local_event_target_callback_exception.html
+++ b/moli-core/tests/fixtures/runtime/local_event_target_callback_exception.html
@@ -12,6 +12,9 @@
data-simple-error=""
>
<script>
+ // Real project-generated font: moli-layout/tests/fixtures/moli-ahem.woff2.
+ const FONT_FIXTURE_SOURCE = "url(data:font/woff2;base64,d09GMgABAAAAAAKMAAoAAAAAEewAAAI9AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAARAqSGIlCATYCJAOBRguBRgAEIAWDDweHZhsaDBEVjE2QrxO4OaB11Uo4KkNFQmQIgNrHOq+V6mgnvY2fvSQ/uF+9N7PdNFuXpclV2mkpdFaAC3aRoEdFB3L8iVa3NRGchB7CA+kvmysBs3ExDyF+2La9iSrRM8x/YMEH4+YNnI6ADDhw44HnsPGNf2vg8Vh2oEcLbcza3qYp3gsXSOBToI2cQC+UhHthpAFIuk0EVfwGmbm3vt4jtOf5c3NBuwr0P4kB5kvBCdDgYzQftZAtCfcwRbHKu3S8ycdHAOfu8OUAmLjP+bEQEov+i78AFoAP+AEAxAAAAbQvPfKjw6g3kr+bmM88bAz4CAIItbXF3xu9/n2qfwCnW7usCnIKG0p4i7hd9+SA9QzCt8+eB2LUsMiFeojjkCtwessPXvTy47FKi+3KLnHVsltY375HzLDkOf6NhCkpi4iVsmpyVHYpuS67Fdw/4GE+R/a2N2xwfWXnu79JZ8nsauts62iP3v/+6UJH9FXrZ8WIPds2mEHrVuyYtGLNiW0L8jSL6zWd2nTMNs9acejIxsou80QHe+KtWi8h8LdYBGgJlS666aGXPvoZYJAhhhlhlDHGmbAhTCjjQiptrAMfhFGcpFlelFXdtF0/jNO8rNt+nNf9vB8AQjCCYjhBUjTDcrwgSrKiarphWrbjcb2+/jc6gLBCmFDGhVTaWBf+NANEmFDGhVTaWBf+tABEmFDGhVTaWBf+tAJEmFDGhVTaWBf+tAFEmFDGhVTaWBf+tANEmFDGhVTa2PClCtb3AQAAAA==)";
+ document.fonts.add(new FontFace('Roboto', FONT_FIXTURE_SOURCE));
const body = document.body;
const fontOrder = [];
diff --git a/moli-core/tests/fixtures/runtime/servo_fontfaceset_load_ready.html b/moli-core/tests/fixtures/runtime/servo_fontfaceset_load_ready.html
index 82d100148..eb6e5c42e 100644
--- a/moli-core/tests/fixtures/runtime/servo_fontfaceset_load_ready.html
+++ b/moli-core/tests/fixtures/runtime/servo_fontfaceset_load_ready.html
@@ -9,6 +9,9 @@
data-css-wide-keyword-prefixed=""
>
<script>
+ // Real project-generated font: moli-layout/tests/fixtures/moli-ahem.woff2.
+ const FONT_FIXTURE_SOURCE = "url(data:font/woff2;base64,d09GMgABAAAAAAKMAAoAAAAAEewAAAI9AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAARAqSGIlCATYCJAOBRguBRgAEIAWDDweHZhsaDBEVjE2QrxO4OaB11Uo4KkNFQmQIgNrHOq+V6mgnvY2fvSQ/uF+9N7PdNFuXpclV2mkpdFaAC3aRoEdFB3L8iVa3NRGchB7CA+kvmysBs3ExDyF+2La9iSrRM8x/YMEH4+YNnI6ADDhw44HnsPGNf2vg8Vh2oEcLbcza3qYp3gsXSOBToI2cQC+UhHthpAFIuk0EVfwGmbm3vt4jtOf5c3NBuwr0P4kB5kvBCdDgYzQftZAtCfcwRbHKu3S8ycdHAOfu8OUAmLjP+bEQEov+i78AFoAP+AEAxAAAAbQvPfKjw6g3kr+bmM88bAz4CAIItbXF3xu9/n2qfwCnW7usCnIKG0p4i7hd9+SA9QzCt8+eB2LUsMiFeojjkCtwessPXvTy47FKi+3KLnHVsltY375HzLDkOf6NhCkpi4iVsmpyVHYpuS67Fdw/4GE+R/a2N2xwfWXnu79JZ8nsauts62iP3v/+6UJH9FXrZ8WIPds2mEHrVuyYtGLNiW0L8jSL6zWd2nTMNs9acejIxsou80QHe+KtWi8h8LdYBGgJlS666aGXPvoZYJAhhhlhlDHGmbAhTCjjQiptrAMfhFGcpFlelFXdtF0/jNO8rNt+nNf9vB8AQjCCYjhBUjTDcrwgSrKiarphWrbjcb2+/jc6gLBCmFDGhVTaWBf+NANEmFDGhVTaWBf+tABEmFDGhVTaWBf+tAJEmFDGhVTaWBf+tAFEmFDGhVTaWBf+tANEmFDGhVTa2PClCtb3AQAAAA==)";
+ document.fonts.add(new FontFace('FixtureFace', FONT_FIXTURE_SOURCE));
window.fontFixtureDone = (async () => {
const body = document.body;
const ready1 = document.fonts.ready;
diff --git a/moli-csp/src/checks.rs b/moli-csp/src/checks.rs
index 72539dbb0..053886c24 100644
--- a/moli-csp/src/checks.rs
+++ b/moli-csp/src/checks.rs
@@ -1329,6 +1329,7 @@ impl ContentSecurityPolicyResourceKind {
Self::DocumentImage => IMG_SRC,
Self::DocumentManifest => MANIFEST_SRC,
Self::DocumentMedia => MEDIA_SRC,
+ Self::DocumentFont => "font-src",
Self::DocumentScriptElement | Self::WorkerDynamicModuleImport => SCRIPT_SRC_ELEM,
Self::DocumentStyleElement => STYLE_SRC_ELEM,
Self::SharedWorkerScript | Self::WorkerStaticModuleImport => WORKER_SRC,
@@ -1344,6 +1345,7 @@ impl ContentSecurityPolicyResourceKind {
Self::DocumentImage => &[IMG_SRC, DEFAULT_SRC],
Self::DocumentManifest => &[MANIFEST_SRC, DEFAULT_SRC],
Self::DocumentMedia => &[MEDIA_SRC, DEFAULT_SRC],
+ Self::DocumentFont => &["font-src", DEFAULT_SRC],
Self::DocumentScriptElement => &[SCRIPT_SRC_ELEM, SCRIPT_SRC, DEFAULT_SRC],
Self::DocumentStyleElement => &[STYLE_SRC_ELEM, STYLE_SRC, DEFAULT_SRC],
Self::SharedWorkerScript => &[WORKER_SRC, CHILD_SRC, SCRIPT_SRC, DEFAULT_SRC],
diff --git a/moli-csp/src/types.rs b/moli-csp/src/types.rs
index 4cca81cd5..a094a5388 100644
--- a/moli-csp/src/types.rs
+++ b/moli-csp/src/types.rs
@@ -7,6 +7,7 @@ pub enum ContentSecurityPolicyResourceKind {
DocumentImage,
DocumentManifest,
DocumentMedia,
+ DocumentFont,
DocumentScriptElement,
DocumentStyleElement,
SharedWorkerScript,
diff --git a/moli-css-parse/src/font_face.rs b/moli-css-parse/src/font_face.rs
index c8cb8cde3..e94599c8f 100644
--- a/moli-css-parse/src/font_face.rs
+++ b/moli-css-parse/src/font_face.rs
@@ -4,6 +4,131 @@ use crate::unquote_css_string;
pub use style::moli_font_face::{CssFontFace, normalize_font_face_src, parse_font_faces};
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum CssFontSource {
+ Local(String),
+ Url(String),
+}
+
+/// Parse through Stylo first; the token walk only extracts validated sources.
+pub fn parse_font_face_sources(source: &str) -> Option<Vec<CssFontSource>> {
+ let normalized = normalize_font_face_src(source)?;
+ let mut parser = Parser::new(&normalized);
+ parser
+ .parse_comma_separated(|parser| {
+ let name = parser.expect_function()?.clone();
+ let source = parser.parse_nested_block(|nested| {
+ if name.eq_ignore_ascii_case("local") {
+ let mut parts = Vec::new();
+ while !nested.is_exhausted() {
+ parts.push(nested.expect_ident_or_string()?.to_string());
+ }
+ Ok(CssFontSource::Local(parts.join(" ")))
+ } else if name.eq_ignore_ascii_case("url") {
+ Ok(CssFontSource::Url(nested.expect_string()?.to_string()))
+ } else {
+ Err(cssparser::ParseError::custom(()))
+ }
+ })?;
+ let mut supported = true;
+ while !parser.is_exhausted() {
+ let kind = parser.expect_function()?.clone();
+ parser.parse_nested_block(|nested| {
+ let mut values = Vec::new();
+ while !nested.is_exhausted() {
+ if nested.try_parse(|p| p.expect_comma()).is_ok() {
+ continue;
+ }
+ values.push(nested.expect_ident_or_string()?.to_ascii_lowercase());
+ }
+ supported &= kind.eq_ignore_ascii_case("format")
+ && !values.is_empty()
+ && values.iter().all(|v| {
+ matches!(
+ legacy_variations_font_format(v).unwrap_or(v),
+ "woff"
+ | "woff2"
+ | "truetype"
+ | "ttf"
+ | "opentype"
+ | "otf"
+ | "collection"
+ )
+ });
+ Ok::<_, cssparser::ParseError<()>>(())
+ })?;
+ }
+ Ok(supported.then_some(source))
+ })
+ .ok()
+ .map(|sources| sources.into_iter().flatten().collect())
+}
+
+/// Maps a legacy variable font format hint to its container format.
+pub fn legacy_variations_font_format(format: &str) -> Option<&str> {
+ format
+ .strip_suffix("-variations")
+ .filter(|format| matches!(*format, "woff" | "woff2" | "truetype" | "opentype"))
+}
+
+#[derive(Clone, Debug)]
+pub struct CssFontShorthand {
+ pub family_css: String,
+ pub families: Vec<String>,
+ pub size: String,
+ pub style: String,
+ pub weight: String,
+ pub stretch: String,
+}
+
+/// Shares the CSS font grammar with style declarations, including quoted
+/// multi-word families and fallback lists. No guessed last-whitespace token.
+pub fn parse_font_shorthand(value: &str) -> Option<CssFontShorthand> {
+ use style::{
+ properties::{PropertyId, parse_property_declaration_list},
+ stylesheets::CssRuleType,
+ };
+ use style_traits::CssStringWriter;
+ if crate::escape_top_level_semicolons(value) != value
+ || crate::split_important_priority(value).1
+ {
+ return None;
+ }
+ crate::stylo_stylesheet::with_descriptor_declaration_context(CssRuleType::Style, |context| {
+ let text = format!("font: {value}");
+ let block = parse_property_declaration_list(context, &mut Parser::new(&text), &[]);
+ let property = |name: &str| -> Option<String> {
+ let mut out = CssStringWriter::new();
+ block
+ .property_value_to_css(&PropertyId::parse(name, context).ok()?, &mut out)
+ .ok()?;
+ (!out.is_empty()).then(|| out.to_string())
+ };
+ let family_css = property("font-family")?;
+ let size = property("font-size")?;
+ if is_css_wide_keyword(&size) || size.contains("var(") {
+ return None;
+ }
+ let families = Parser::new(&family_css)
+ .parse_comma_separated(|p| {
+ let mut parts = Vec::new();
+ while !p.is_exhausted() {
+ parts.push(p.expect_ident_or_string()?.to_string());
+ }
+ Ok::<_, cssparser::ParseError<()>>(parts.join(" "))
+ })
+ .ok()?;
+ Some(CssFontShorthand {
+ family_css,
+ families,
+ size,
+ style: property("font-style")?,
+ weight: property("font-weight")?,
+ stretch: property("font-stretch")?,
+ })
+ })
+}
+
pub fn font_load_query_contains_css_wide_keyword(query: &str) -> bool {
let input = query;
let mut input = Parser::new(input);
@@ -77,6 +202,62 @@ fn is_css_wide_keyword(value: &str) -> bool {
#[cfg(test)]
mod tests {
+ #[test]
+ fn font_sources_preserve_local_names_and_supported_url_fallback_order() {
+ use super::*;
+ assert_eq!(
+ parse_font_face_sources(
+ "local(Missing Font), url(bad) format('unsupported'), url(good.woff2) format('woff2')"
+ ),
+ Some(vec![
+ CssFontSource::Local("Missing Font".into()),
+ CssFontSource::Url("good.woff2".into())
+ ])
+ );
+ assert!(parse_font_face_sources("not a source").is_none());
+ }
+
+ #[test]
+ fn font_sources_accept_legacy_variable_formats_and_keep_unknown_fallbacks() {
+ use super::*;
+ for format in [
+ "woff-variations",
+ "woff2-variations",
+ "truetype-variations",
+ "opentype-variations",
+ ] {
+ assert_eq!(
+ parse_font_face_sources(&format!("url(variable) format('{format}')")),
+ Some(vec![CssFontSource::Url("variable".into())]),
+ );
+ }
+ assert_eq!(
+ parse_font_face_sources(
+ "url(unknown) format('svg-variations'), url(empty) format(), url(fallback) format('woff2')"
+ ),
+ Some(vec![CssFontSource::Url("fallback".into())]),
+ );
+ }
+
+ #[test]
+ fn font_shorthand_uses_stylo_validation_and_keeps_all_families() {
+ let font =
+ super::parse_font_shorthand("italic bold 10.5px/1.2 \"A B\", Another Face, serif")
+ .unwrap();
+ assert_eq!(font.families, ["A B", "Another Face", "serif"]);
+ assert_eq!(font.size, "10.5px");
+ assert_eq!(font.style, "italic");
+ for invalid in [
+ "",
+ "12px",
+ "not a font",
+ "inherit",
+ "12px serif; color:red",
+ "12px serif !important",
+ ] {
+ assert!(super::parse_font_shorthand(invalid).is_none(), "{invalid}");
+ }
+ }
use super::{
font_load_query_contains_css_wide_keyword, font_load_query_family,
font_load_query_is_valid, normalize_font_face_src, parse_font_faces,
diff --git a/moli-css-parse/src/lib.rs b/moli-css-parse/src/lib.rs
index bb8f20711..7e7e1785d 100644
--- a/moli-css-parse/src/lib.rs
+++ b/moli-css-parse/src/lib.rs
@@ -20,8 +20,9 @@ pub use color::{
};
pub use declaration::{CssDeclaration, DeclarationParseOptions, parse_declaration_list};
pub use font_face::{
- CssFontFace, font_load_query_contains_css_wide_keyword, font_load_query_family,
- font_load_query_is_valid, normalize_font_face_src, parse_font_faces,
+ CssFontFace, CssFontShorthand, CssFontSource, font_load_query_contains_css_wide_keyword,
+ font_load_query_family, font_load_query_is_valid, legacy_variations_font_format,
+ normalize_font_face_src, parse_font_face_sources, parse_font_faces, parse_font_shorthand,
};
pub use font_palette::{
CssFontPaletteValuesProperty, parse_font_palette_values_property_with_stylo,
diff --git a/moli-css-parse/src/stylo_stylesheet.rs b/moli-css-parse/src/stylo_stylesheet.rs
index 5a4fedfe4..8d9cd5660 100644
--- a/moli-css-parse/src/stylo_stylesheet.rs
+++ b/moli-css-parse/src/stylo_stylesheet.rs
@@ -234,7 +234,7 @@ fn declaration_block_css_text(block: &PropertyDeclarationBlock) -> String {
css_text.trim_end().to_owned()
}
-fn with_descriptor_declaration_context<R>(
+pub(crate) fn with_descriptor_declaration_context<R>(
rule_type: CssRuleType,
f: impl FnOnce(&ParserContext) -> Option<R>,
) -> Option<R> {
diff --git a/moli-layout/src/lib.rs b/moli-layout/src/lib.rs
index 8af72d291..ee05ac764 100644
--- a/moli-layout/src/lib.rs
+++ b/moli-layout/src/lib.rs
@@ -102,7 +102,7 @@ pub use style::{
LayoutPosition, ResolvedLayoutStyle,
};
pub use text::{
- DocumentLayoutServices, SystemFontPolicy, WebFontFace, WebFontRegistration,
+ DocumentLayoutServices, FontFaceData, SystemFontPolicy, WebFontFace, WebFontRegistration,
WebFontRegistrationError, WebFontRegistrationOutcome, WebFontStyle, WebFontUnicodeRange,
validate_web_font_bytes,
};
diff --git a/moli-layout/src/text.rs b/moli-layout/src/text.rs
index b2bf6e50c..bc2825ce5 100644
--- a/moli-layout/src/text.rs
+++ b/moli-layout/src/text.rs
@@ -23,6 +23,9 @@ use thiserror::Error;
use crate::stylo_to_parley::TextBrush;
+mod font_source;
+pub use font_source::FontFaceData;
+
pub(crate) struct ParleyDocumentServices {
pub(crate) font_context: FontContext,
pub(crate) layout_context: LayoutContext<TextBrush>,
@@ -700,6 +703,7 @@ pub struct DocumentLayoutServices {
// FontContext and LayoutContext are both large. Keep them off the stack so
// embedding this sidecar in ScriptVm does not inflate every VM frame.
parley: Option<Box<ParleyDocumentServices>>,
+ local_font_sources: Option<Box<font_source::LocalFontSources>>,
system_font_policy: SystemFontPolicy,
web_fonts: BTreeMap<String, RegisteredWebFont>,
pub(crate) text_layout_passes: u64,
@@ -716,6 +720,7 @@ impl DocumentLayoutServices {
pub const fn new() -> Self {
Self {
parley: None,
+ local_font_sources: None,
system_font_policy: SystemFontPolicy::Enabled,
web_fonts: BTreeMap::new(),
text_layout_passes: 0,
@@ -726,6 +731,7 @@ impl DocumentLayoutServices {
pub const fn with_system_font_policy(system_font_policy: SystemFontPolicy) -> Self {
Self {
parley: None,
+ local_font_sources: None,
system_font_policy,
web_fonts: BTreeMap::new(),
text_layout_passes: 0,
@@ -838,6 +844,7 @@ impl DocumentLayoutServices {
.collect();
let mut temporary = Self {
parley: None,
+ local_font_sources: None,
system_font_policy: self.system_font_policy,
web_fonts,
text_layout_passes: 0,
@@ -849,6 +856,18 @@ impl DocumentLayoutServices {
result
}
+ /// Resolves a CSS local() source by its actual full or PostScript name.
+ /// This never substitutes a generic font or a document web-font alias.
+ pub fn local_font_source(&mut self, name: &str) -> Option<FontFaceData> {
+ self.local_font_sources
+ .get_or_insert_with(|| {
+ Box::new(font_source::LocalFontSources::new(
+ self.system_font_policy.is_enabled(),
+ ))
+ })
+ .find(name)
+ }
+
pub(crate) fn parley_mut(&mut self) -> &mut ParleyDocumentServices {
if self.parley.is_none() {
self.parley = Some(Box::new(build_parley_services(
diff --git a/moli-layout/src/text/font_source.rs b/moli-layout/src/text/font_source.rs
new file mode 100644
index 000000000..6ed9647e8
--- /dev/null
+++ b/moli-layout/src/text/font_source.rs
@@ -0,0 +1,250 @@
+//! FontFace sources are actual font data, not successful CSS fallback queries.
+
+use std::collections::BTreeMap;
+
+use parley::fontique::{FontInfo, SourceCache};
+use read_fonts::{FontRef, TableProvider, types::NameId};
+
+use super::*;
+
+/// One decoded, validated SFNT face, ready for document registration.
+#[derive(Clone, Debug)]
+pub struct FontFaceData {
+ pub(super) bytes: Arc<[u8]>,
+}
+
+impl FontFaceData {
+ pub fn from_bytes(bytes: &[u8]) -> Result<Self, WebFontRegistrationError> {
+ let bytes = decode_web_font_bytes(bytes)?;
+ Self::from_index(bytes, 0)
+ }
+
+ fn from_index(bytes: Arc<[u8]>, index: u32) -> Result<Self, WebFontRegistrationError> {
+ let font = FontRef::from_index(&bytes, index)
+ .map_err(|_| WebFontRegistrationError::UnsupportedPayload)?;
+ let bytes = if font.ttc_index().is_some() {
+ standalone_face(&font).ok_or(WebFontRegistrationError::UnsupportedPayload)?
+ } else {
+ bytes
+ };
+ validate_registered_font(&WebFontFace::new("FontFace validation"), bytes.clone())?;
+ Ok(Self { bytes })
+ }
+
+ pub fn bytes(&self) -> &[u8] {
+ &self.bytes
+ }
+}
+
+// Fontique registers every member of a collection. Extract the selected local
+// face first so a CSS alias cannot accidentally refer to another TTC member.
+fn standalone_face(font: &FontRef<'_>) -> Option<Arc<[u8]>> {
+ let directory = font.table_directory();
+ let mut records = directory.table_records().to_vec();
+ records.retain(|record| record.tag() != read_fonts::types::Tag::new(b"DSIG"));
+ records.sort_by_key(|record| record.tag());
+ let count = u16::try_from(records.len()).ok()?;
+ if count == 0 || count > 4095 {
+ return None;
+ }
+ let selector = count.ilog2() as u16;
+ let search_range = (1_u16 << selector) * 16;
+ let mut bytes = Vec::new();
+ bytes.extend_from_slice(&directory.sfnt_version().to_be_bytes());
+ for value in [count, search_range, selector, count * 16 - search_range] {
+ bytes.extend_from_slice(&value.to_be_bytes());
+ }
+ bytes.resize(12 + records.len() * 16, 0);
+ let mut head_offset = None;
+ for (index, record) in records.iter().enumerate() {
+ let data = font.table_data(record.tag())?;
+ let data = data.as_bytes();
+ let offset = bytes.len();
+ bytes.extend_from_slice(data);
+ bytes.resize(bytes.len().next_multiple_of(4), 0);
+ if record.tag() == read_fonts::types::Tag::new(b"head") {
+ if data.len() < 12 {
+ return None;
+ }
+ bytes[offset + 8..offset + 12].fill(0);
+ head_offset = Some(offset);
+ }
+ let checksum = sfnt_checksum(&bytes[offset..]);
+ let entry = 12 + index * 16;
+ bytes[entry..entry + 4].copy_from_slice(&record.tag().to_be_bytes());
+ bytes[entry + 4..entry + 8].copy_from_slice(&checksum.to_be_bytes());
+ bytes[entry + 8..entry + 12].copy_from_slice(&u32::try_from(offset).ok()?.to_be_bytes());
+ bytes[entry + 12..entry + 16].copy_from_slice(&record.length().to_be_bytes());
+ }
+ let head = head_offset?;
+ let adjustment = 0xb1b0_afba_u32.wrapping_sub(sfnt_checksum(&bytes));
+ bytes[head + 8..head + 12].copy_from_slice(&adjustment.to_be_bytes());
+ Some(Arc::from(bytes))
+}
+
+fn sfnt_checksum(bytes: &[u8]) -> u32 {
+ bytes.chunks_exact(4).fold(0_u32, |sum, word| {
+ sum.wrapping_add(u32::from_be_bytes(
+ word.try_into().expect("four-byte chunk"),
+ ))
+ })
+}
+
+/// The platform-only collection is separate from document web fonts. A CSS
+/// alias, generic fallback, or previously downloaded font is not a local font.
+pub(super) struct LocalFontSources {
+ collection: Collection,
+ cache: SourceCache,
+ names: Option<BTreeMap<String, FontInfo>>,
+}
+
+impl LocalFontSources {
+ pub(super) fn new(system_fonts: bool) -> Self {
+ Self {
+ collection: Collection::new(CollectionOptions {
+ shared: false,
+ system_fonts,
+ }),
+ cache: SourceCache::default(),
+ names: None,
+ }
+ }
+
+ pub(super) fn find(&mut self, name: &str) -> Option<FontFaceData> {
+ if self.names.is_none() {
+ let mut names = BTreeMap::new();
+ let families = self
+ .collection
+ .family_names()
+ .map(str::to_owned)
+ .collect::<Vec<_>>();
+ for family in families {
+ let Some(family) = self.collection.family_by_name(&family) else {
+ continue;
+ };
+ for info in family.fonts() {
+ let Some(data) = info.load(Some(&mut self.cache)) else {
+ continue;
+ };
+ let Ok(font) = FontRef::from_index(data.as_ref(), info.index()) else {
+ continue;
+ };
+ let Ok(table) = font.name() else {
+ continue;
+ };
+ for record in table.name_record() {
+ if !matches!(
+ record.name_id(),
+ NameId::FULL_NAME | NameId::POSTSCRIPT_NAME
+ ) {
+ continue;
+ }
+ let Ok(name) = record.string(table.string_data()) else {
+ continue;
+ };
+ let name = name.to_string().to_lowercase();
+ if !name.is_empty() {
+ names.entry(name).or_insert_with(|| info.clone());
+ }
+ }
+ }
+ }
+ self.names = Some(names);
+ }
+ let info = self.names.as_ref()?.get(&name.to_lowercase())?;
+ let data = info.load(Some(&mut self.cache))?;
+ FontFaceData::from_index(Arc::from(data.as_ref()), info.index()).ok()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const FONT: &[u8] = include_bytes!("../../tests/fixtures/moli-ahem.ttf");
+
+ #[test]
+ fn font_face_data_rejects_headers_without_font_tables() {
+ for bytes in [
+ &b"\x00\x01\x00\x00"[..],
+ &b"OTTO"[..],
+ &b"wOFF"[..],
+ &b"wOF2"[..],
+ &[0; 32][..],
+ ] {
+ assert!(FontFaceData::from_bytes(bytes).is_err());
+ }
+ assert!(FontFaceData::from_bytes(FONT).is_ok());
+ assert!(
+ FontFaceData::from_bytes(include_bytes!("../../tests/fixtures/moli-ahem.woff")).is_ok()
+ );
+ assert!(
+ FontFaceData::from_bytes(include_bytes!("../../tests/fixtures/moli-ahem.woff2"))
+ .is_ok()
+ );
+ }
+
+ #[test]
+ fn local_font_lookup_uses_full_and_postscript_names_not_css_aliases() {
+ let mut sources = LocalFontSources::new(false);
+ sources.collection.register_fonts(
+ Blob::new(Arc::new(FONT.to_vec())),
+ Some(FontInfoOverride {
+ family_name: Some("NotTheFontName"),
+ ..Default::default()
+ }),
+ );
+ let font = FontRef::new(FONT).unwrap();
+ let table = font.name().unwrap();
+ let mut checked = 0;
+ for record in table.name_record() {
+ if matches!(
+ record.name_id(),
+ NameId::FULL_NAME | NameId::POSTSCRIPT_NAME
+ ) {
+ let name = record.string(table.string_data()).unwrap().to_string();
+ assert!(sources.find(&name).is_some(), "{name}");
+ assert!(sources.find(&name.to_lowercase()).is_some(), "{name}");
+ checked += 1;
+ }
+ }
+ assert!(checked > 0);
+ assert!(sources.find("NotTheFontName").is_none());
+ assert!(sources.find("serif").is_none());
+ assert!(sources.find("MoliDefinitelyNotAFont").is_none());
+ }
+
+ #[test]
+ fn local_collection_selection_extracts_only_the_requested_face() {
+ let fonts = [
+ FONT,
+ &include_bytes!("../../tests/fixtures/moli-cjk.ttf")[..],
+ ];
+ let mut collection = b"ttcf\x00\x01\x00\x00\x00\x00\x00\x02".to_vec();
+ collection.resize(20, 0);
+ for (index, bytes) in fonts.iter().enumerate() {
+ let offset = collection.len();
+ collection[12 + index * 4..16 + index * 4]
+ .copy_from_slice(&(offset as u32).to_be_bytes());
+ collection.extend_from_slice(bytes);
+ let font = FontRef::new(bytes).unwrap();
+ for (table, record) in font.table_directory().table_records().iter().enumerate() {
+ let position = offset + 12 + table * 16 + 8;
+ collection[position..position + 4]
+ .copy_from_slice(&(record.offset() + offset as u32).to_be_bytes());
+ }
+ collection.resize(collection.len().next_multiple_of(4), 0);
+ }
+ for (index, original) in fonts.iter().enumerate() {
+ let selected =
+ FontFaceData::from_index(Arc::from(collection.as_slice()), index as u32).unwrap();
+ let font = FontRef::new(selected.bytes()).unwrap();
+ assert!(font.ttc_index().is_none());
+ assert_eq!(
+ font.maxp().unwrap().num_glyphs(),
+ FontRef::new(original).unwrap().maxp().unwrap().num_glyphs()
+ );
+ assert_eq!(sfnt_checksum(selected.bytes()), 0xb1b0_afba);
+ }
+ }
+}
diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs
index 9060f8627..cf59d977b 100644
--- a/moli-renderer-v8/src/context_bootstrap.rs
+++ b/moli-renderer-v8/src/context_bootstrap.rs
@@ -15,6 +15,9 @@ mod chrome_runtime;
mod constructors;
mod crypto;
mod css_fontface_runtime;
+pub(crate) use css_fontface_runtime::{
+ bind_stylesheet_font_face, finish_font_face_url_load, publish_font_face_load_changes,
+};
mod css_runtime;
pub(crate) mod css_stylesheet_runtime;
mod dom_rect;
diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime.rs
index a97f39043..7c6412b16 100644
--- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime.rs
+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime.rs
@@ -36,7 +36,9 @@ const FONT_FACE_SET_READY_SLOT: &str = "__moliFontFaceSetReady";
mod events;
mod font_face;
mod font_face_set;
+mod loading;
mod query;
+mod state;
mod storage;
pub(in crate::context_bootstrap) use events::{
@@ -52,6 +54,9 @@ pub(super) use font_face_set::{
font_face_set_has_callback, font_face_set_keys_callback, font_face_set_load_callback,
font_face_set_values_callback,
};
+pub(crate) use loading::{
+ bind_stylesheet_font_face, finish_font_face_url_load, publish_font_face_load_changes,
+};
pub(super) use storage::install_font_face_set_template_accessors;
pub(crate) use storage::new_font_face_set;
pub(crate) use storage::rebuild_font_face_set_faces;
diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/events.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/events.rs
index cd539ddd7..60effcc6b 100644
--- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/events.rs
+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/events.rs
@@ -1,7 +1,4 @@
-use super::storage::{
- font_face_set_owner_snapshot, is_font_face_value, replace_font_face_set_ready_promise,
- set_font_face_set_status,
-};
+use super::storage::{font_face_set_owner_snapshot, is_font_face_value, set_font_face_set_status};
use super::*;
use crate::context_bootstrap::events::initialize_event_object;
use crate::util::{
@@ -265,6 +262,35 @@ pub(super) fn dispatch_font_face_set_event<'s>(
dispatch_simple_event_target_event(scope, object, event_type, event)
}
+const READY_RESOLVER: &str = "__moliFontFaceSetReadyResolver";
+const LOADED_FACES: &str = "__moliFontFaceSetLoadedFaces";
+const FAILED_FACES: &str = "__moliFontFaceSetFailedFaces";
+
+pub(super) fn font_face_loading_started<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ face: v8::Local<'s, v8::Object>,
+) {
+ for owner in font_face_set_owner_snapshot(scope, face) {
+ if super::loading::string_slot(scope, owner, FONT_FACE_SET_STATUS_SLOT) == "loading" {
+ continue;
+ }
+ set_font_face_set_status(scope, owner, "loading");
+ let resolver = v8::PromiseResolver::new(scope).expect("FontFaceSet ready resolver");
+ set_private_value(scope, owner, READY_RESOLVER, resolver.into());
+ set_private_value(
+ scope,
+ owner,
+ FONT_FACE_SET_READY_SLOT,
+ resolver.get_promise(scope).into(),
+ );
+ for slot in [LOADED_FACES, FAILED_FACES] {
+ let array = v8::Array::new(scope, 0);
+ set_private_value(scope, owner, slot, array.into());
+ }
+ let _ = dispatch_font_face_set_event(scope, owner, "loading", None);
+ }
+}
+
pub(super) fn notify_font_face_set_owners_of_load<'s>(
scope: &mut v8::PinScope<'s, '_>,
face: v8::Local<'s, v8::Object>,
@@ -286,20 +312,56 @@ pub(super) fn notify_font_face_set_owners_of_load<'s>(
if owners.is_empty() {
return;
}
- let loaded_faces = v8::Array::new(scope, 1);
- let _ = loaded_faces.set_index(scope, 0, face.into());
- let completion_event_type = if font_face_load_failed(scope, face) {
- "loadingerror"
+ let slot = if font_face_load_failed(scope, face) {
+ FAILED_FACES
} else {
- "loadingdone"
+ LOADED_FACES
};
for owner in owners {
- set_font_face_set_status(scope, owner, "loading");
- replace_font_face_set_ready_promise(scope, owner);
- let _ = dispatch_font_face_set_event(scope, owner, "loading", None);
- set_font_face_set_status(scope, owner, "loaded");
- let _ =
- dispatch_font_face_set_event(scope, owner, completion_event_type, Some(loaded_faces));
+ if let Some(array) = get_private_value(scope, owner, slot)
+ .and_then(|v| v8::Local::<v8::Array>::try_from(v).ok())
+ {
+ let _ = array.set_index(scope, array.length(), face.into());
+ }
+ finish_font_set_if_idle(scope, owner);
+ }
+}
+
+pub(super) fn finish_font_set_if_idle<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ owner: v8::Local<'s, v8::Object>,
+) {
+ if super::loading::string_slot(scope, owner, FONT_FACE_SET_STATUS_SLOT) != "loading" {
+ return;
+ }
+ let pending = super::storage::font_face_set_faces_array(scope, owner).is_some_and(|faces| {
+ (0..faces.length()).any(|index| {
+ faces
+ .get_index(scope, index)
+ .and_then(|v| v8::Local::<v8::Object>::try_from(v).ok())
+ .is_some_and(|face| {
+ super::loading::status(scope, face)
+ == crate::font_loading::FontFaceStatus::Loading
+ })
+ })
+ });
+ if pending {
+ return;
+ }
+ set_font_face_set_status(scope, owner, "loaded");
+ if let Some(resolver) = super::loading::resolver_from_slot(scope, owner, READY_RESOLVER) {
+ let _ = resolver.resolve(scope, owner.into());
+ }
+ for (slot, event) in [
+ (LOADED_FACES, "loadingdone"),
+ (FAILED_FACES, "loadingerror"),
+ ] {
+ if let Some(array) = get_private_value(scope, owner, slot)
+ .and_then(|v| v8::Local::<v8::Array>::try_from(v).ok())
+ && (event == "loadingdone" || array.length() > 0)
+ {
+ let _ = dispatch_font_face_set_event(scope, owner, event, Some(array));
+ }
}
}
@@ -307,7 +369,5 @@ fn font_face_load_failed<'s>(
scope: &mut v8::PinScope<'s, '_>,
face: v8::Local<'s, v8::Object>,
) -> bool {
- get_private_value(scope, face, FONT_FACE_STATUS_SLOT)
- .and_then(|value| v8::Local::<v8::String>::try_from(value).ok())
- .is_some_and(|status| status.to_rust_string_lossy(scope) == "error")
+ super::loading::status(scope, face) == crate::font_loading::FontFaceStatus::Error
}
diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs
index e65d0a3ad..80cf5bb7d 100644
--- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs
+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs
@@ -4,9 +4,7 @@ use crate::{
util::{callback_data_index_value, callback_data_item, get_private_value, set_private_value},
webidl,
};
-use data_url::DataUrl;
use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};
-use url::Url;
mod descriptors;
use descriptors::{FONT_FACE_WRITABLE_ATTRIBUTES, parse_font_face_descriptors};
@@ -42,8 +40,6 @@ struct FontFaceObjectDeclaration<'s> {
line_gap_override: String,
#[webapi(slot = FONT_FACE_SIZE_ADJUST_SLOT)]
size_adjust: String,
- #[webapi(slot = FONT_FACE_STATUS_SLOT)]
- status: &'static str,
#[webapi(slot = FONT_FACE_LOADED_SLOT)]
loaded: Option<v8::Local<'s, v8::Promise>>,
#[webapi(slot = FONT_FACE_SET_OWNERS_SLOT, constructor_default = Vec::new())]
@@ -238,6 +234,13 @@ fn font_face_readonly_attribute_getter_callback<'s>(
rv.set_undefined();
return;
};
+ if slot == FONT_FACE_STATUS_SLOT {
+ let status = super::loading::status(scope, args.this());
+ if let Some(value) = v8_string(scope, status.as_str()) {
+ rv.set(value.into());
+ }
+ return;
+ }
let value = font_face_slot_value(scope, args.this(), slot)
.unwrap_or_else(|| v8::undefined(scope).into());
rv.set(value);
@@ -273,6 +276,7 @@ fn font_face_attribute_setter_callback<'s>(
value
};
set_font_face_slot_value(scope, args.this(), descriptor.slot, value.into());
+ super::loading::update_descriptor(scope, args.this());
rv.set_undefined();
}
@@ -307,78 +311,34 @@ pub(in crate::context_bootstrap) fn font_face_constructor_callback<'s>(
size_adjust,
] = descriptors;
let this = args.this();
- let (source, status, loaded) = if invalid_descriptors {
- let source = match parsed.source {
- FontFaceConstructorSource::Css(source) => source,
- FontFaceConstructorSource::Binary(_) => String::new(),
- };
- let loaded = super::query::make_rejected_dom_exception_promise(
- scope,
- "SyntaxError",
- "Invalid FontFace descriptor.",
- );
- (source, "error", Some(loaded))
- } else {
- match parsed.source {
- FontFaceConstructorSource::Css(source)
- if moli_css_parse::normalize_font_face_src(&source).is_none() =>
- {
- let loaded = super::query::make_rejected_dom_exception_promise(
- scope,
- "SyntaxError",
- "Invalid FontFace source descriptor.",
- );
- (source, "error", Some(loaded))
- }
- FontFaceConstructorSource::Css(source)
- if font_face_data_url_bytes(&source).is_some_and(|bytes| {
- bytes
- .as_deref()
- .is_none_or(|bytes| moli_layout::validate_web_font_bytes(bytes).is_err())
- }) =>
- {
- let loaded = super::query::make_rejected_dom_exception_promise(
- scope,
- "NetworkError",
- "The FontFace data URL does not contain a valid font.",
- );
- (source, "error", Some(loaded))
- }
- FontFaceConstructorSource::Css(source) => {
- let loaded = resolved_promise(scope, this.into());
- (source, "loaded", loaded)
- }
- FontFaceConstructorSource::Binary(value) => {
- // Retain the native buffer during union conversion. Descriptor
- // getters may mutate or detach it before the operation copies it.
- let bytes = match webidl::convert::<webidl::BufferSource>(
+ let (source, sources, binary) = match parsed.source {
+ FontFaceConstructorSource::Css(source) => {
+ let sources = moli_css_parse::parse_font_face_sources(&source);
+ (source, sources, None)
+ }
+ FontFaceConstructorSource::Binary(value) => {
+ // Preserve main's conversion order: descriptor getters may detach
+ // the retained buffer, and invalid descriptors reject before copying.
+ let bytes = if invalid_descriptors {
+ None
+ } else {
+ match webidl::convert::<webidl::BufferSource>(
scope,
value,
webidl::Context::argument("FontFace", 2),
) {
- Ok(bytes) => bytes.into_bytes(),
+ Ok(bytes) => Some(bytes.into_bytes()),
Err(error) => {
webidl::throw_error(scope, &error);
return;
}
- };
- if moli_layout::validate_web_font_bytes(&bytes).is_ok() {
- let backing = v8::ArrayBuffer::new_backing_store_from_vec(bytes).make_shared();
- let data = v8::ArrayBuffer::with_backing_store(scope, &backing);
- set_private_value(scope, this, "__moliFontFaceData", data.into());
- let loaded = resolved_promise(scope, this.into());
- (String::new(), "loaded", loaded)
- } else {
- let loaded = super::query::make_rejected_dom_exception_promise(
- scope,
- "SyntaxError",
- "Invalid font data in ArrayBuffer.",
- );
- (String::new(), "error", Some(loaded))
}
- }
+ };
+ (String::new(), Some(Vec::new()), bytes)
}
};
+ let resolver = v8::PromiseResolver::new(scope).expect("FontFace loaded resolver");
+ let loaded = Some(resolver.get_promise(scope));
FontFaceObjectDeclaration::new(
parsed.family,
source,
@@ -394,27 +354,25 @@ pub(in crate::context_bootstrap) fn font_face_constructor_callback<'s>(
descent_override,
line_gap_override,
size_adjust,
- status,
loaded,
)
.initialize(scope, this)
.expect("FontFace declaration should initialize object");
- rv.set(this.into());
-}
-
-fn font_face_data_url_bytes(source: &str) -> Option<Option<Vec<u8>>> {
- let normalized = moli_css_parse::normalize_font_face_src(source)?;
- let base_url = Url::parse("about:blank").expect("static FontFace base URL should parse");
- let request_url = crate::css_resource_urls::preferred_font_source_url(&normalized, &base_url)?;
- if request_url.scheme() != "data" {
- return None;
+ let valid_sources = sources.is_some();
+ let resource = super::loading::new_resource(scope, this, sources.unwrap_or_default());
+ if invalid_descriptors {
+ resource
+ .borrow_mut()
+ .fail("SyntaxError", "Invalid FontFace descriptor.");
+ } else if !valid_sources {
+ resource
+ .borrow_mut()
+ .fail("SyntaxError", "Invalid FontFace source.");
+ } else if let Some(bytes) = binary {
+ resource.borrow_mut().initialize_binary(&bytes);
}
- Some(
- DataUrl::process(request_url.as_str())
- .ok()
- .and_then(|data_url| data_url.decode_to_vec().ok())
- .map(|(bytes, _)| bytes),
- )
+ super::loading::initialize_resolver(scope, this, resolver, resource);
+ rv.set(this.into());
}
fn font_face_constructor_source_arg<'s>(
@@ -457,13 +415,7 @@ pub(in crate::context_bootstrap) fn font_face_load_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
- let this = args.this();
- super::events::notify_font_face_set_owners_of_load(scope, this);
- if let Some(loaded) = font_face_slot_value(scope, this, FONT_FACE_LOADED_SLOT) {
- rv.set(loaded);
- return;
- }
- match resolved_promise(scope, this.into()) {
+ match super::loading::load_font(scope, args.this()) {
Some(promise) => rv.set(v8::Local::<v8::Value>::from(promise)),
None => rv.set(v8::undefined(scope).into()),
}
diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face_set.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face_set.rs
index 55cfe9a0b..1b602d0a9 100644
--- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face_set.rs
+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face_set.rs
@@ -1,12 +1,7 @@
-use super::events::dispatch_font_face_set_event;
-use super::query::{
- font_face_set_matching_faces_array, font_load_query_is_valid,
- make_rejected_dom_exception_promise,
-};
+use super::query::{font_face_set_matching_faces_array, make_rejected_dom_exception_promise};
use super::storage::{
array_contains_value, font_face_set_faces_array, font_face_set_manual_faces_array,
- is_font_face_value, rebuild_font_face_set_faces, replace_font_face_set_ready_promise,
- set_font_face_set_slot_value, set_font_face_set_status,
+ is_font_face_value, rebuild_font_face_set_faces, set_font_face_set_slot_value,
};
use super::*;
diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face_set/loading.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face_set/loading.rs
index a1fa7ab8e..853b2834d 100644
--- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face_set/loading.rs
+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face_set/loading.rs
@@ -29,16 +29,24 @@ pub(in crate::context_bootstrap) fn font_face_set_check_callback<'s>(
return;
};
let _ = &parsed.text;
- if !font_load_query_is_valid(&parsed.font) {
- let error = new_dom_exception_value(
+ let Some(faces) = font_face_set_matching_faces_array(scope, args.this(), &parsed.font) else {
+ webidl::throw_dom_exception(
scope,
- "The provided font shorthand is invalid.",
"SyntaxError",
+ "The provided font shorthand is invalid.",
);
- scope.throw_exception(error);
return;
- }
- rv.set(v8::Boolean::new(scope, true).into());
+ };
+ let loaded = (0..faces.length()).all(|index| {
+ faces
+ .get_index(scope, index)
+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ .is_some_and(|face| {
+ super::super::loading::status(scope, face)
+ == crate::font_loading::FontFaceStatus::Loaded
+ })
+ });
+ rv.set(v8::Boolean::new(scope, loaded).into());
}
pub(in crate::context_bootstrap) fn font_face_set_load_callback<'s>(
@@ -52,7 +60,7 @@ pub(in crate::context_bootstrap) fn font_face_set_load_callback<'s>(
return;
};
let _ = &parsed.text;
- if !font_load_query_is_valid(&parsed.font) {
+ let Some(matching_faces) = font_face_set_matching_faces_array(scope, this, &parsed.font) else {
rv.set(
make_rejected_dom_exception_promise(
scope,
@@ -62,17 +70,6 @@ pub(in crate::context_bootstrap) fn font_face_set_load_callback<'s>(
.into(),
);
return;
- }
- let matching_faces = font_face_set_matching_faces_array(scope, this, &parsed.font)
- .unwrap_or_else(|| v8::Array::new(scope, 0));
- set_font_face_set_status(scope, this, "loading");
- let _ = dispatch_font_face_set_event(scope, this, "loading", None);
- replace_font_face_set_ready_promise(scope, this);
- set_font_face_set_status(scope, this, "loaded");
- let _ = dispatch_font_face_set_event(scope, this, "loadingdone", Some(matching_faces));
- let faces_value = matching_faces.into();
- match resolved_promise(scope, faces_value) {
- Some(promise) => rv.set(v8::Local::<v8::Value>::from(promise)),
- None => rv.set(v8::undefined(scope).into()),
- }
+ };
+ rv.set(super::super::loading::load_matching_faces(scope, matching_faces).into());
}
diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/loading.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/loading.rs
new file mode 100644
index 000000000..e7ec6f393
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/loading.rs
@@ -0,0 +1,320 @@
+use std::sync::atomic::{AtomicU64, Ordering};
+
+use super::*;
+use crate::font_loading::{FontFaceLoad, FontFaceResource, FontFaceStatus};
+use crate::util::{get_private_value, set_private_value};
+
+const RESOLVER: &str = "__moliFontFaceResolver";
+const OWNER_DOCUMENT: &str = "__moliFontFaceSetOwnerDocument";
+static NEXT_REGISTRATION: AtomicU64 = AtomicU64::new(1);
+const QUERY_RESOLVER: &str = "__moliFontQueryResolver";
+const QUERY_FACES: &str = "__moliFontQueryFaces";
+const QUERY_REMAINING: &str = "__moliFontQueryRemaining";
+
+pub(super) fn load_matching_faces<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ faces: v8::Local<'s, v8::Array>,
+) -> v8::Local<'s, v8::Promise> {
+ let resolver = v8::PromiseResolver::new(scope).expect("FontFaceSet.load resolver");
+ let promise = resolver.get_promise(scope);
+ if faces.length() == 0 {
+ let _ = resolver.resolve(scope, faces.into());
+ return promise;
+ }
+ let state = v8::Object::new(scope);
+ set_private_value(scope, state, QUERY_RESOLVER, resolver.into());
+ set_private_value(scope, state, QUERY_FACES, faces.into());
+ set_private_value(
+ scope,
+ state,
+ QUERY_REMAINING,
+ v8::Integer::new_from_unsigned(scope, faces.length()).into(),
+ );
+ let fulfilled = v8::Function::builder(query_face_loaded)
+ .data(state.into())
+ .build(scope)
+ .expect("font loaded callback");
+ let rejected = v8::Function::builder(query_face_failed)
+ .data(state.into())
+ .build(scope)
+ .expect("font failed callback");
+ for index in 0..faces.length() {
+ let face = faces
+ .get_index(scope, index)
+ .and_then(|v| v8::Local::<v8::Object>::try_from(v).ok())
+ .expect("matched FontFace");
+ if let Some(loaded) = load_font(scope, face) {
+ let _ = loaded.then2(scope, fulfilled, rejected);
+ }
+ }
+ promise
+}
+
+fn query_face_loaded<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ _rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ let state = v8::Local::<v8::Object>::try_from(args.data()).expect("font query state");
+ let remaining = get_private_value(scope, state, QUERY_REMAINING)
+ .and_then(|v| v.uint32_value(scope))
+ .unwrap_or(0);
+ if remaining == 0 {
+ return;
+ }
+ set_private_value(
+ scope,
+ state,
+ QUERY_REMAINING,
+ v8::Integer::new_from_unsigned(scope, remaining - 1).into(),
+ );
+ if remaining == 1 {
+ let resolver =
+ resolver_from_slot(scope, state, QUERY_RESOLVER).expect("font query resolver");
+ let faces = get_private_value(scope, state, QUERY_FACES).expect("font query faces");
+ let _ = resolver.resolve(scope, faces);
+ }
+}
+
+fn query_face_failed<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ _rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ let state = v8::Local::<v8::Object>::try_from(args.data()).expect("font query state");
+ set_private_value(
+ scope,
+ state,
+ QUERY_REMAINING,
+ v8::Integer::new(scope, 0).into(),
+ );
+ let resolver = resolver_from_slot(scope, state, QUERY_RESOLVER).expect("font query resolver");
+ let _ = resolver.reject(scope, args.get(0));
+}
+
+pub(super) fn resolver_from_slot<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+ slot: &'static str,
+) -> Option<v8::Local<'s, v8::PromiseResolver>> {
+ let value = get_private_value(scope, object, slot)?;
+ // SAFETY: these private slots are populated only by PromiseResolver::new
+ // above (and FontFaceSet.ready). They are never writable by page code.
+ Some(unsafe { v8::Local::<v8::PromiseResolver>::cast_unchecked(value) })
+}
+
+pub(super) fn string_slot<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ face: v8::Local<'s, v8::Object>,
+ slot: &str,
+) -> String {
+ get_private_value(scope, face, slot)
+ .and_then(|v| v8::Local::<v8::String>::try_from(v).ok())
+ .map(|v| v.to_rust_string_lossy(scope))
+ .unwrap_or_default()
+}
+
+pub(super) fn status<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ face: v8::Local<'s, v8::Object>,
+) -> FontFaceStatus {
+ super::state::get(scope, face)
+ .expect("FontFace has native state")
+ .borrow()
+ .status()
+}
+
+pub(super) fn new_resource<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ face: v8::Local<'s, v8::Object>,
+ sources: Vec<moli_css_parse::CssFontSource>,
+) -> FontFaceLoad {
+ let id = NEXT_REGISTRATION.fetch_add(1, Ordering::Relaxed);
+ FontFaceResource::new(
+ format!("js-font-face-{id}"),
+ descriptor(scope, face),
+ sources,
+ false,
+ )
+}
+
+fn descriptor<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ face: v8::Local<'s, v8::Object>,
+) -> moli_layout::WebFontFace {
+ crate::font_loading::script_font_descriptor(
+ &string_slot(scope, face, FONT_FACE_FAMILY_SLOT),
+ &string_slot(scope, face, FONT_FACE_WEIGHT_SLOT),
+ &string_slot(scope, face, FONT_FACE_STRETCH_SLOT),
+ &string_slot(scope, face, FONT_FACE_STYLE_SLOT),
+ )
+}
+
+pub(super) fn update_descriptor<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ face: v8::Local<'s, v8::Object>,
+) {
+ let load = super::state::get(scope, face).expect("FontFace has native state");
+ load.borrow_mut().set_descriptor(descriptor(scope, face));
+ sync_owners(scope, face);
+}
+
+pub(super) fn initialize_resolver<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ face: v8::Local<'s, v8::Object>,
+ resolver: v8::Local<'s, v8::PromiseResolver>,
+ resource: FontFaceLoad,
+) {
+ set_private_value(scope, face, RESOLVER, resolver.into());
+ super::state::initialize(scope, face, resource);
+ publish_state(scope, face);
+}
+
+/// Only the observer layer creates JS errors, settles promises and dispatches
+/// events. Native CSS completions update the same resource without touching V8.
+fn publish_state<'s>(scope: &mut v8::PinScope<'s, '_>, face: v8::Local<'s, v8::Object>) {
+ let Some((previous, load)) = super::state::take_change(scope, face) else {
+ return;
+ };
+ let (current, started, error) = {
+ let load = load.borrow();
+ (load.status(), load.was_started(), load.error())
+ };
+ if previous == FontFaceStatus::Unloaded && started {
+ super::events::font_face_loading_started(scope, face);
+ }
+ match current {
+ FontFaceStatus::Loaded => {
+ sync_owners(scope, face);
+ if let Some(resolver) = resolver_from_slot(scope, face, RESOLVER) {
+ let _ = resolver.resolve(scope, face.into());
+ }
+ }
+ FontFaceStatus::Error => {
+ if let Some(resolver) = resolver_from_slot(scope, face, RESOLVER) {
+ let error = error.expect("native failed font has an error");
+ let exception = new_dom_exception_value(scope, error.message, error.name);
+ let _ = resolver.reject(scope, exception);
+ }
+ }
+ FontFaceStatus::Unloaded | FontFaceStatus::Loading => return,
+ }
+ if started {
+ super::events::notify_font_face_set_owners_of_load(scope, face);
+ }
+}
+
+pub(crate) fn publish_font_face_load_changes(scope: &mut v8::PinScope<'_, '_>) {
+ for face in super::state::changed_wrappers(scope) {
+ if let Some(context) = face.get_creation_context(scope) {
+ let scope = &mut v8::ContextScope::new(scope, context);
+ publish_state(scope, face);
+ }
+ }
+}
+
+pub(crate) fn bind_stylesheet_font_face<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ face: v8::Local<'s, v8::Object>,
+ load: FontFaceLoad,
+) -> bool {
+ if !super::state::bind(scope, face, load) {
+ return false;
+ }
+ publish_state(scope, face);
+ true
+}
+
+pub(super) fn load_font<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ face: v8::Local<'s, v8::Object>,
+) -> Option<v8::Local<'s, v8::Promise>> {
+ let promise = get_private_value(scope, face, FONT_FACE_LOADED_SLOT)
+ .and_then(|v| v8::Local::<v8::Promise>::try_from(v).ok())?;
+ let load = super::state::get(scope, face)?;
+ let context = face.get_creation_context(scope)?;
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let start = load.borrow_mut().begin();
+ publish_state(scope, face);
+ if start {
+ advance_sources(scope, face, &load);
+ }
+ Some(promise)
+}
+
+fn advance_sources<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ face: v8::Local<'s, v8::Object>,
+ load: &FontFaceLoad,
+) {
+ loop {
+ let url = with_font_services(scope, |services| load.borrow_mut().next_url(services));
+ let Some(url) = url else {
+ break;
+ };
+ match crate::network_host::start_font_face_fetch(scope, face, &url) {
+ Ok(crate::network_host::FontFaceFetchStart::Pending) => return,
+ Ok(crate::network_host::FontFaceFetchStart::Local(bytes)) => {
+ let _ = load.borrow_mut().accept_response(Some(&bytes));
+ }
+ Err(_) => {}
+ }
+ }
+ publish_font_face_load_changes(scope);
+}
+
+pub(crate) fn finish_font_face_url_load<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ face: v8::Local<'s, v8::Object>,
+ bytes: Option<&[u8]>,
+) {
+ let Some(context) = face.get_creation_context(scope) else {
+ return;
+ };
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let load = super::state::get(scope, face).expect("pending font retains native state");
+ let _ = load.borrow_mut().accept_response(bytes);
+ advance_sources(scope, face, &load);
+}
+
+pub(super) fn sync_owners<'s>(scope: &mut v8::PinScope<'s, '_>, face: v8::Local<'s, v8::Object>) {
+ for owner in super::storage::font_face_set_owner_snapshot(scope, face) {
+ sync_registration(scope, owner, face, true);
+ }
+}
+
+pub(super) fn sync_registration<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ owner: v8::Local<'s, v8::Object>,
+ face: v8::Local<'s, v8::Object>,
+ present: bool,
+) {
+ let Some(document) = get_private_value(scope, owner, OWNER_DOCUMENT)
+ .and_then(|value| crate::native_bridge::callback_value_dom_handle(scope, value))
+ else {
+ return;
+ };
+ let Some(load) = super::state::get(scope, face) else {
+ return;
+ };
+ let Some(context) = owner.get_creation_context(scope) else {
+ return;
+ };
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let Some(host_ptr) = crate::util::context_host_ptr_from_global_bridge(scope) else {
+ return;
+ };
+ // SAFETY: this is the owner document's live bridge; the native font service
+ // does not invoke V8 or page code while borrowed.
+ let host = unsafe { &*host_ptr };
+ host.with_font_services(document, |services| {
+ let load = load.borrow();
+ if present {
+ if let Err(error) = load.register(services) {
+ tracing::warn!(%error, "failed to register FontFace");
+ }
+ } else {
+ load.unregister(services);
+ }
+ });
+}
diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/query.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/query.rs
index f359f9840..dc71988d6 100644
--- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/query.rs
+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/query.rs
@@ -2,19 +2,16 @@ use super::storage::font_face_set_faces_array;
use super::*;
use crate::util::serialize_v8_iter_array;
-pub(super) fn font_load_query_is_valid(query: &str) -> bool {
- moli_css_parse::font_load_query_is_valid(query)
-}
-
-fn font_face_matches_query(
- scope: &mut v8::PinScope<'_, '_>,
- face: v8::Local<'_, v8::Object>,
- query: &str,
+fn font_face_matches_query<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ face: v8::Local<'s, v8::Object>,
+ families: &[String],
) -> bool {
- let Some(query_family) = moli_css_parse::font_load_query_family(query) else {
- return false;
- };
- object_string_property(scope, face, "family").is_some_and(|family| family == query_family)
+ let family = super::loading::string_slot(scope, face, FONT_FACE_FAMILY_SLOT);
+ let family = moli_css_parse::unquote_css_string(&family);
+ families
+ .iter()
+ .any(|query| query.eq_ignore_ascii_case(&family))
}
pub(super) fn font_face_set_matching_faces_array<'s>(
@@ -22,6 +19,14 @@ pub(super) fn font_face_set_matching_faces_array<'s>(
object: v8::Local<'s, v8::Object>,
query: &str,
) -> Option<v8::Local<'s, v8::Array>> {
+ if !moli_css_parse::font_load_query_is_valid(query) {
+ return None;
+ }
+ // System font shorthands are valid queries, but Stylo's Servo configuration
+ // does not expose their platform families for matching authored faces.
+ let families = moli_css_parse::parse_font_shorthand(query)
+ .map(|query| query.families)
+ .unwrap_or_default();
let faces = font_face_set_faces_array(scope, object)?;
let mut matching = Vec::new();
for index in 0..faces.length() {
@@ -31,7 +36,7 @@ pub(super) fn font_face_set_matching_faces_array<'s>(
let Ok(face_object) = v8::Local::<v8::Object>::try_from(face) else {
continue;
};
- if !font_face_matches_query(scope, face_object, query) {
+ if !font_face_matches_query(scope, face_object, &families) {
continue;
}
matching.push(face);
diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/state.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/state.rs
new file mode 100644
index 000000000..2e5eef1a5
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/state.rs
@@ -0,0 +1,193 @@
+//! Weak JS observers of native font resources. No font bytes or load progress
+//! live in JS slots; collecting a wrapper releases only that observer.
+
+use std::{cell::RefCell, collections::HashMap, rc::Rc};
+
+use crate::{
+ font_loading::{FontFaceLoad, FontFaceStatus},
+ util::{get_private_value, set_private_value},
+};
+
+const STATE_SLOT: &str = "__moliFontFaceState";
+type Store = Rc<RefCell<Observers>>;
+
+#[derive(Default)]
+struct Observers {
+ next_id: u64,
+ entries: HashMap<u64, Observer>,
+}
+
+struct Observer {
+ wrapper: v8::Weak<v8::Object>,
+ load: FontFaceLoad,
+ published: FontFaceStatus,
+}
+
+pub(super) fn initialize<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ face: v8::Local<'s, v8::Object>,
+ load: FontFaceLoad,
+) {
+ let store = if let Some(store) = scope.get_slot::<Store>() {
+ store.clone()
+ } else {
+ let store = Store::default();
+ scope.set_slot(store.clone());
+ store
+ };
+ let id = {
+ let mut store = store.borrow_mut();
+ store.next_id = store
+ .next_id
+ .checked_add(1)
+ .expect("FontFace observer identity exhausted");
+ store.next_id
+ };
+ let weak_store = Rc::downgrade(&store);
+ let wrapper = v8::Weak::with_finalizer(
+ scope,
+ face,
+ Box::new(move |_| {
+ if let Some(store) = weak_store.upgrade() {
+ store.borrow_mut().entries.remove(&id);
+ }
+ }),
+ );
+ store.borrow_mut().entries.insert(
+ id,
+ Observer {
+ wrapper,
+ load,
+ published: FontFaceStatus::Unloaded,
+ },
+ );
+ set_private_value(
+ scope,
+ face,
+ STATE_SLOT,
+ v8::BigInt::new_from_u64(scope, id).into(),
+ );
+}
+
+fn id<'s>(scope: &mut v8::PinScope<'s, '_>, face: v8::Local<'s, v8::Object>) -> Option<u64> {
+ get_private_value(scope, face, STATE_SLOT)
+ .and_then(|value| v8::Local::<v8::BigInt>::try_from(value).ok())
+ .map(|value| value.u64_value().0)
+}
+
+pub(super) fn get<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ face: v8::Local<'s, v8::Object>,
+) -> Option<FontFaceLoad> {
+ let id = id(scope, face)?;
+ Some(
+ scope
+ .get_slot::<Store>()?
+ .borrow()
+ .entries
+ .get(&id)?
+ .load
+ .clone(),
+ )
+}
+
+pub(super) fn bind<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ face: v8::Local<'s, v8::Object>,
+ load: FontFaceLoad,
+) -> bool {
+ let Some(id) = id(scope, face) else {
+ return false;
+ };
+ let store = scope
+ .get_slot::<Store>()
+ .expect("FontFace observers installed");
+ let mut store = store.borrow_mut();
+ let observer = store.entries.get_mut(&id).expect("live FontFace observer");
+ if !Rc::ptr_eq(&observer.load, &load) {
+ observer.load = load;
+ observer.published = FontFaceStatus::Unloaded;
+ }
+ true
+}
+
+pub(super) fn take_change<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ face: v8::Local<'s, v8::Object>,
+) -> Option<(FontFaceStatus, FontFaceLoad)> {
+ let id = id(scope, face)?;
+ let mut store = scope.get_slot::<Store>()?.borrow_mut();
+ let observer = store.entries.get_mut(&id)?;
+ let current = observer.load.borrow().status();
+ if current == observer.published {
+ return None;
+ }
+ let previous = std::mem::replace(&mut observer.published, current);
+ Some((previous, observer.load.clone()))
+}
+
+pub(super) fn changed_wrappers<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+) -> Vec<v8::Local<'s, v8::Object>> {
+ let Some(store) = scope.get_slot::<Store>() else {
+ return Vec::new();
+ };
+ store
+ .borrow()
+ .entries
+ .values()
+ .filter(|observer| observer.published != observer.load.borrow().status())
+ .filter_map(|observer| observer.wrapper.to_local(scope))
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::font_loading::FontFaceResource;
+
+ #[test]
+ fn font_face_observer_gc_preserves_css_owned_state_but_releases_js_only_state() {
+ // The platform is process-global: do not let this small isolate install
+ // V8's default platform before renderer tests need Moli's task routing.
+ crate::ensure_v8_for_test();
+ let mut isolate = v8::Isolate::new(Default::default());
+ let css_load = FontFaceResource::new(
+ "css".into(),
+ moli_layout::WebFontFace::new("CSS"),
+ Vec::new(),
+ true,
+ );
+ let js_load = {
+ let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));
+ let scope = &mut scope.init();
+ let context = v8::Context::new(scope, Default::default());
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let css_face = v8::Object::new(scope);
+ initialize(scope, css_face, css_load.clone());
+ let js_face = v8::Object::new(scope);
+ initialize(
+ scope,
+ js_face,
+ FontFaceResource::new(
+ "js".into(),
+ moli_layout::WebFontFace::new("JS"),
+ Vec::new(),
+ false,
+ ),
+ );
+ Rc::downgrade(&get(scope, js_face).unwrap())
+ };
+ isolate.low_memory_notification();
+ assert!(
+ isolate
+ .get_slot::<Store>()
+ .unwrap()
+ .borrow()
+ .entries
+ .is_empty()
+ );
+ assert!(js_load.upgrade().is_none());
+ assert_eq!(Rc::strong_count(&css_load), 1);
+ }
+}
diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/storage.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/storage.rs
index ab5e7029c..eb61d36a3 100644
--- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/storage.rs
+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/storage.rs
@@ -270,6 +270,7 @@ pub(crate) fn rebuild_font_face_set_faces<'s>(
sync_font_face_set_owners(scope, object, previous, combined);
set_font_face_set_slot_value(scope, object, FONT_FACE_SET_FACES_SLOT, combined.into());
sync_font_face_set_size(scope, object);
+ super::events::finish_font_set_if_idle(scope, object);
}
pub(super) fn font_face_set_owner_snapshot<'s>(
@@ -303,6 +304,9 @@ fn sync_font_face_set_owners<'s>(
continue;
};
if !array_contains_value(scope, current, face) {
+ if let Ok(face) = v8::Local::<v8::Object>::try_from(face) {
+ super::loading::sync_registration(scope, owner, face, false);
+ }
remove_font_face_set_owner(scope, face, owner);
}
}
@@ -312,6 +316,14 @@ fn sync_font_face_set_owners<'s>(
};
if !array_contains_value(scope, previous, face) {
add_font_face_set_owner(scope, face, owner);
+ if let Ok(face) = v8::Local::<v8::Object>::try_from(face) {
+ super::loading::sync_registration(scope, owner, face, true);
+ if super::loading::status(scope, face)
+ == crate::font_loading::FontFaceStatus::Loading
+ {
+ super::events::font_face_loading_started(scope, face);
+ }
+ }
}
}
}
diff --git a/moli-renderer-v8/src/context_bootstrap/shared.rs b/moli-renderer-v8/src/context_bootstrap/shared.rs
index f692be7ad..b28ddbb82 100644
--- a/moli-renderer-v8/src/context_bootstrap/shared.rs
+++ b/moli-renderer-v8/src/context_bootstrap/shared.rs
@@ -3,6 +3,7 @@ mod clone;
mod console;
mod definition;
mod dom;
+mod fonts;
mod object;
mod slots;
mod text_codecs;
@@ -25,6 +26,7 @@ pub(crate) use console::{
};
pub(in crate::context_bootstrap) use definition::*;
pub(in crate::context_bootstrap) use dom::*;
+pub(in crate::context_bootstrap) use fonts::with_font_services;
pub(in crate::context_bootstrap) use moli_browser_profile::{
DEFAULT_CONNECTION_DOWNLINK, DEFAULT_CONNECTION_DOWNLINK_MAX,
DEFAULT_CONNECTION_EFFECTIVE_TYPE, DEFAULT_CONNECTION_RTT, DEFAULT_CONNECTION_SAVE_DATA,
diff --git a/moli-renderer-v8/src/context_bootstrap/shared/fonts.rs b/moli-renderer-v8/src/context_bootstrap/shared/fonts.rs
new file mode 100644
index 000000000..296789a68
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/shared/fonts.rs
@@ -0,0 +1,32 @@
+use std::cell::RefCell;
+
+use moli_layout::DocumentLayoutServices;
+
+/// Workers have no DOM layout sidecar. Keep their font collection scoped to
+/// the realm instead; a FontFace and its OffscreenCanvas share this service.
+type RealmFontServices = RefCell<DocumentLayoutServices>;
+
+pub(in crate::context_bootstrap) fn with_font_services<T>(
+ scope: &mut v8::PinScope<'_, '_>,
+ consume: impl FnOnce(&mut DocumentLayoutServices) -> T,
+) -> T {
+ if let Some(host_ptr) = crate::util::context_host_ptr_from_global_bridge(scope) {
+ // SAFETY: the bridge belongs to this live ScriptVm. No V8/author calls
+ // occur while the document's Rust-only font service is borrowed.
+ let host = unsafe { &*host_ptr };
+ let child =
+ crate::context_bootstrap::child_browsing_context_handle_for_current_realm_scope(scope);
+ let document = child
+ .and_then(|handle| host.child_browsing_context_document_handle(handle))
+ .unwrap_or_else(|| host.document_handle());
+ return host.with_font_services(document, consume);
+ }
+ let context = scope.get_current_context();
+ let services = context.get_slot::<RealmFontServices>().unwrap_or_else(|| {
+ context.set_slot(RefCell::new(DocumentLayoutServices::new()).into());
+ context
+ .get_slot::<RealmFontServices>()
+ .expect("initialized realm font service")
+ });
+ consume(&mut services.borrow_mut())
+}
diff --git a/moli-renderer-v8/src/css_resource_urls.rs b/moli-renderer-v8/src/css_resource_urls.rs
index c9da9b378..a5d23766d 100644
--- a/moli-renderer-v8/src/css_resource_urls.rs
+++ b/moli-renderer-v8/src/css_resource_urls.rs
@@ -1,10 +1,10 @@
-use cssparser::{Parser, Token, UnicodeRange};
+use cssparser::{Parser, UnicodeRange};
use moli_crypto::sha256_hex;
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, WebFontRegistration, WebFontStyle, WebFontUnicodeRange};
+use moli_layout::{WebFontFace, WebFontStyle, WebFontUnicodeRange};
use url::Url;
use crate::protocol_types::OptionalResourceFetchMask;
@@ -35,7 +35,7 @@ impl StylesheetLoadBlockingResource {
Self::new(request_url, StylesheetLoadBlockingResourceKind::Image)
}
- fn font(request_url: Url, web_font: StylesheetWebFont) -> Self {
+ pub(crate) fn font(request_url: Url, web_font: StylesheetWebFont) -> Self {
Self {
request_url,
kind: StylesheetLoadBlockingResourceKind::Font,
@@ -47,6 +47,11 @@ impl StylesheetLoadBlockingResource {
&self.request_url
}
+ pub(crate) fn with_request_url(mut self, url: Url) -> Self {
+ self.request_url = url;
+ self
+ }
+
pub(crate) fn into_parts(self) -> (Url, Option<StylesheetWebFont>) {
(self.request_url, self.web_font)
}
@@ -74,6 +79,7 @@ impl StylesheetLoadBlockingResource {
pub(crate) struct StylesheetWebFont {
slot: String,
face: WebFontFace,
+ sources: Vec<moli_css_parse::CssFontSource>,
request_id: Option<u64>,
}
@@ -87,9 +93,8 @@ impl StylesheetWebFont {
self.request_id
}
- pub(crate) fn registration(&self, bytes: Vec<u8>) -> WebFontRegistration {
- WebFontRegistration::new(self.slot.clone(), self.face.clone(), bytes)
- .with_stylesheet_scope()
+ pub(crate) fn sources(&self) -> &[moli_css_parse::CssFontSource] {
+ &self.sources
}
pub(crate) fn slot(&self) -> &str {
@@ -164,12 +169,17 @@ pub(crate) fn stylesheet_web_font_resource(
base_url: &Url,
) -> Option<StylesheetLoadBlockingResource> {
let descriptor = parsed_web_font_face(css_text)?;
- let request_url = preferred_font_source_url(descriptor.source(), base_url)?;
- Some(stylesheet_web_font_resource_with_descriptor(
- css_text,
- request_url,
- descriptor,
- ))
+ let sources = moli_css_parse::parse_font_face_sources(descriptor.source())?
+ .into_iter()
+ .filter_map(|source| match source {
+ moli_css_parse::CssFontSource::Local(name) => {
+ Some(moli_css_parse::CssFontSource::Local(name))
+ }
+ moli_css_parse::CssFontSource::Url(url) => resolve_font_source_url(&url, base_url)
+ .map(|url| moli_css_parse::CssFontSource::Url(url.to_string())),
+ })
+ .collect();
+ stylesheet_web_font_resource_with_resolved_sources(css_text, sources)
}
/// Projects a native Stylo `@font-face` rule using the URL already resolved
@@ -178,18 +188,20 @@ pub(crate) fn stylesheet_web_font_resource(
/// Imported rules retain their imported stylesheet's URL context inside
/// `SpecifiedUrl`. Callers must use this entry point instead of resolving the
/// serialized, relative `src` value against the root stylesheet again.
-pub(crate) fn stylesheet_web_font_resource_with_resolved_url(
+pub(crate) fn stylesheet_web_font_resource_with_resolved_sources(
css_text: &str,
- request_url: Url,
+ sources: Vec<moli_css_parse::CssFontSource>,
) -> Option<StylesheetLoadBlockingResource> {
- if !matches!(request_url.scheme(), "http" | "https" | "data" | "blob") {
- return None;
- }
+ let request_url = sources.iter().find_map(|source| match source {
+ moli_css_parse::CssFontSource::Url(url) => Url::parse(url).ok(),
+ moli_css_parse::CssFontSource::Local(_) => None,
+ })?;
let descriptor = parsed_web_font_face(css_text)?;
Some(stylesheet_web_font_resource_with_descriptor(
css_text,
request_url,
descriptor,
+ sources,
))
}
@@ -197,6 +209,7 @@ fn stylesheet_web_font_resource_with_descriptor(
css_text: &str,
request_url: Url,
descriptor: ParsedWebFontFace,
+ sources: Vec<moli_css_parse::CssFontSource>,
) -> StylesheetLoadBlockingResource {
// The slot describes a declaration, not a layout generation. Two
// projections of the same parsed rule (the import response and the later
@@ -213,6 +226,7 @@ fn stylesheet_web_font_resource_with_descriptor(
StylesheetWebFont {
slot,
face: descriptor.into_face(),
+ sources,
request_id: None,
},
)
@@ -298,7 +312,7 @@ fn parse_font_unicode_ranges(value: &str) -> Option<Vec<WebFontUnicodeRange>> {
.ok()
}
-fn parse_font_weight_lower_bound(value: &str) -> Option<f32> {
+pub(crate) fn parse_font_weight_lower_bound(value: &str) -> Option<f32> {
match value
.split_ascii_whitespace()
.next()?
@@ -314,7 +328,7 @@ fn parse_font_weight_lower_bound(value: &str) -> Option<f32> {
}
}
-fn parse_font_stretch_lower_bound(value: &str) -> Option<f32> {
+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,
@@ -331,7 +345,7 @@ fn parse_font_stretch_lower_bound(value: &str) -> Option<f32> {
(percentage > 0.0 && percentage.is_finite()).then_some(percentage)
}
-fn parse_font_style_lower_bound(value: &str) -> Option<WebFontStyle> {
+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),
@@ -353,89 +367,7 @@ fn parse_css_angle_degrees(value: &str) -> Option<f32> {
.filter(|value| value.is_finite())
}
-pub(crate) fn preferred_font_source_url(source: &str, base_url: &Url) -> Option<Url> {
- let input = source;
- let mut input = Parser::new(input);
- let mut candidate_url: Option<String> = None;
- let mut candidate_format_is_supported = true;
- while let Ok(token) = input.next_including_whitespace_and_comments().cloned() {
- match token {
- Token::Comma => {
- if candidate_format_is_supported && let Some(url) = candidate_url.take() {
- return resolve_font_source_url(&url, base_url);
- }
- candidate_url = None;
- candidate_format_is_supported = true;
- }
- Token::UnquotedUrl(raw_url) => candidate_url = Some(raw_url.to_string()),
- Token::Function(name) if name.eq_ignore_ascii_case("url") => {
- let _ = input.parse_nested_block(|input| {
- candidate_url = css_url_function_value(input);
- Ok::<(), cssparser::ParseError<()>>(())
- });
- }
- Token::Function(name) if name.eq_ignore_ascii_case("format") => {
- let _ = input.parse_nested_block(|input| {
- candidate_format_is_supported = font_format_function_is_supported(input);
- Ok::<(), cssparser::ParseError<()>>(())
- });
- }
- Token::Function(_) | Token::ParenthesisBlock | Token::SquareBracketBlock => {
- let _ = input.parse_nested_block(|input| {
- skip_css_block(input);
- Ok::<(), cssparser::ParseError<()>>(())
- });
- }
- _ => {}
- }
- }
- candidate_url
- .filter(|_| candidate_format_is_supported)
- .and_then(|url| resolve_font_source_url(&url, base_url))
-}
-
-fn css_url_function_value<'i>(input: &mut Parser<'i>) -> Option<String> {
- while let Ok(token) = input.next_including_whitespace_and_comments().cloned() {
- match token {
- Token::WhiteSpace(_) | Token::Comment(_) => {}
- Token::QuotedString(value) | Token::UnquotedUrl(value) => {
- return Some(value.to_string());
- }
- _ => return None,
- }
- }
- None
-}
-
-fn font_format_function_is_supported<'i>(input: &mut Parser<'i>) -> bool {
- let mut saw_format = false;
- while let Ok(token) = input.next_including_whitespace_and_comments().cloned() {
- let value = match token {
- Token::WhiteSpace(_) | Token::Comment(_) | Token::Comma => continue,
- Token::Ident(value) | Token::QuotedString(value) => value.to_ascii_lowercase(),
- _ => return false,
- };
- saw_format = true;
- // Chrome still accepts the pre-`tech()` variable font hints, and font
- // packages such as Fontsource emit `woff2-variations` for every face.
- let value = legacy_variations_font_format(&value).unwrap_or(&value);
- if !matches!(
- value,
- "woff" | "woff2" | "truetype" | "opentype" | "ttf" | "otf" | "collection"
- ) {
- return false;
- }
- }
- saw_format
-}
-
-/// Maps a legacy variable font format hint such as `woff2-variations` to the
-/// container format it names.
-pub(crate) fn legacy_variations_font_format(format: &str) -> Option<&str> {
- format
- .strip_suffix("-variations")
- .filter(|format| matches!(*format, "woff" | "woff2" | "truetype" | "opentype"))
-}
+pub(crate) use moli_css_parse::legacy_variations_font_format;
fn resolve_font_source_url(raw_url: &str, base_url: &Url) -> Option<Url> {
let raw_url = raw_url.trim();
@@ -446,23 +378,6 @@ fn resolve_font_source_url(raw_url: &str, base_url: &Url) -> Option<Url> {
matches!(url.scheme(), "http" | "https" | "data" | "blob").then_some(url)
}
-fn skip_css_block<'i>(input: &mut Parser<'i>) {
- while let Ok(token) = input.next_including_whitespace_and_comments().cloned() {
- match token {
- Token::Function(_)
- | Token::ParenthesisBlock
- | Token::SquareBracketBlock
- | Token::CurlyBracketBlock => {
- let _ = input.parse_nested_block(|input| {
- skip_css_block(input);
- Ok::<(), cssparser::ParseError<()>>(())
- });
- }
- _ => {}
- }
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -582,9 +497,14 @@ mod tests {
let response_projection = stylesheet_web_font_resource(css_text, &imported_base)
.expect("the import response should project its font");
- let native_projection =
- stylesheet_web_font_resource_with_resolved_url(css_text, resolved.clone())
- .expect("the retained native rule should project its resolved font");
+ let native_projection = stylesheet_web_font_resource_with_resolved_sources(
+ css_text,
+ vec![
+ moli_css_parse::CssFontSource::Local("Imported".to_owned()),
+ moli_css_parse::CssFontSource::Url(resolved.to_string()),
+ ],
+ )
+ .expect("the retained native rule should project its resolved font");
assert_eq!(response_projection.request_url(), &resolved);
assert_eq!(native_projection.request_url(), &resolved);
@@ -610,10 +530,16 @@ mod tests {
let css_text = "@font-face { font-family: Shared; src: url(./fonts/shared.woff2); }";
let first_url = Url::parse("https://example.test/first/fonts/shared.woff2").unwrap();
let second_url = Url::parse("https://example.test/second/fonts/shared.woff2").unwrap();
- let first = stylesheet_web_font_resource_with_resolved_url(css_text, first_url)
- .expect("first native resource");
- let second = stylesheet_web_font_resource_with_resolved_url(css_text, second_url)
- .expect("second native resource");
+ let first = stylesheet_web_font_resource_with_resolved_sources(
+ css_text,
+ vec![moli_css_parse::CssFontSource::Url(first_url.to_string())],
+ )
+ .expect("first native resource");
+ let second = stylesheet_web_font_resource_with_resolved_sources(
+ css_text,
+ vec![moli_css_parse::CssFontSource::Url(second_url.to_string())],
+ )
+ .expect("second native resource");
assert_ne!(
first.web_font().expect("first font").slot(),
diff --git a/moli-renderer-v8/src/document_runtime/security_policy.rs b/moli-renderer-v8/src/document_runtime/security_policy.rs
index 43f94b02b..26fe57dd8 100644
--- a/moli-renderer-v8/src/document_runtime/security_policy.rs
+++ b/moli-renderer-v8/src/document_runtime/security_policy.rs
@@ -88,6 +88,28 @@ pub(crate) struct DocumentConnectPolicySnapshot {
}
impl DocumentConnectPolicySnapshot {
+ pub(crate) fn font_violation(
+ &self,
+ document_url: &Url,
+ request_url: &Url,
+ disposition: ContentSecurityPolicyDisposition,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+ ) -> Option<DocumentContentSecurityPolicyViolation> {
+ let policies = match disposition {
+ ContentSecurityPolicyDisposition::Enforce => &self.enforce_policies,
+ ContentSecurityPolicyDisposition::Report => &self.report_only_policies,
+ };
+ document_url_policy_violation(
+ policies,
+ &self.reporting_endpoints,
+ document_url,
+ request_url,
+ ContentSecurityPolicyResourceKind::DocumentFont,
+ redirect_status,
+ disposition,
+ )
+ }
+
pub(crate) fn from_policy_container(policy: &DocumentPolicyContainer) -> Self {
let mut enforce_policies = policy.response_content_security_policies.clone();
enforce_policies.extend(policy.document_content_security_policies.iter().cloned());
diff --git a/moli-renderer-v8/src/font_loading.rs b/moli-renderer-v8/src/font_loading.rs
new file mode 100644
index 000000000..a4c35e4fe
--- /dev/null
+++ b/moli-renderer-v8/src/font_loading.rs
@@ -0,0 +1,201 @@
+//! Native FontFace loading shared by CSS resources and JS wrappers.
+//!
+//! This layer owns source fallback, decoded bytes and registration. It does not
+//! own V8 handles, promises, network tasks or document lifetimes: callers retain
+//! the existing resource owner's request identity and publish changes to JS.
+
+use std::{cell::RefCell, rc::Rc};
+
+use moli_css_parse::CssFontSource;
+use moli_layout::{
+ DocumentLayoutServices, FontFaceData, WebFontFace, WebFontRegistration,
+ WebFontRegistrationError, WebFontRegistrationOutcome,
+};
+
+pub(crate) type FontFaceLoad = Rc<RefCell<FontFaceResource>>;
+
+pub(crate) fn script_font_descriptor(
+ family: &str,
+ weight: &str,
+ stretch: &str,
+ style: &str,
+) -> WebFontFace {
+ use crate::css_resource_urls::{
+ parse_font_stretch_lower_bound, parse_font_style_lower_bound, 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),
+ )
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(crate) enum FontFaceStatus {
+ Unloaded,
+ Loading,
+ Loaded,
+ Error,
+}
+
+impl FontFaceStatus {
+ pub(crate) const fn as_str(self) -> &'static str {
+ match self {
+ Self::Unloaded => "unloaded",
+ Self::Loading => "loading",
+ Self::Loaded => "loaded",
+ Self::Error => "error",
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct FontFaceError {
+ pub(crate) name: &'static str,
+ pub(crate) message: &'static str,
+}
+
+#[derive(Debug)]
+enum LoadState {
+ Unloaded,
+ Loading,
+ Loaded(FontFaceData),
+ Error(FontFaceError),
+}
+
+#[derive(Debug)]
+pub(crate) struct FontFaceResource {
+ slot: String,
+ descriptor: WebFontFace,
+ stylesheet: bool,
+ sources: std::vec::IntoIter<CssFontSource>,
+ state: LoadState,
+ started: bool,
+}
+
+impl FontFaceResource {
+ pub(crate) fn new(
+ slot: String,
+ descriptor: WebFontFace,
+ sources: Vec<CssFontSource>,
+ stylesheet: bool,
+ ) -> FontFaceLoad {
+ Rc::new(RefCell::new(Self {
+ slot,
+ descriptor,
+ stylesheet,
+ sources: sources.into_iter(),
+ state: LoadState::Unloaded,
+ started: false,
+ }))
+ }
+
+ pub(crate) fn slot(&self) -> &str {
+ &self.slot
+ }
+
+ pub(crate) fn set_descriptor(&mut self, descriptor: WebFontFace) {
+ self.descriptor = descriptor.with_unicode_ranges(self.descriptor.unicode_ranges().to_vec());
+ }
+
+ pub(crate) fn status(&self) -> FontFaceStatus {
+ match self.state {
+ LoadState::Unloaded => FontFaceStatus::Unloaded,
+ LoadState::Loading => FontFaceStatus::Loading,
+ LoadState::Loaded(_) => FontFaceStatus::Loaded,
+ LoadState::Error(_) => FontFaceStatus::Error,
+ }
+ }
+
+ pub(crate) fn error(&self) -> Option<FontFaceError> {
+ match self.state {
+ LoadState::Error(error) => Some(error),
+ _ => None,
+ }
+ }
+
+ pub(crate) fn was_started(&self) -> bool {
+ self.started
+ }
+
+ pub(crate) fn fail(&mut self, name: &'static str, message: &'static str) {
+ self.state = LoadState::Error(FontFaceError { name, message });
+ }
+
+ pub(crate) fn initialize_binary(&mut self, bytes: &[u8]) {
+ match FontFaceData::from_bytes(bytes) {
+ Ok(data) => self.state = LoadState::Loaded(data),
+ Err(_) => self.fail("SyntaxError", "Invalid font data in ArrayBuffer."),
+ }
+ }
+
+ /// Only one consumer may initiate loading, even when CSS and JS both ask.
+ pub(crate) fn begin(&mut self) -> bool {
+ if self.status() != FontFaceStatus::Unloaded {
+ return false;
+ }
+ self.state = LoadState::Loading;
+ self.started = true;
+ true
+ }
+
+ /// Advance after starting or after a failed URL. Local lookup and source
+ /// exhaustion are terminal here; only actual URL requests leave this layer.
+ pub(crate) fn next_url(&mut self, services: &mut DocumentLayoutServices) -> Option<String> {
+ if self.status() != FontFaceStatus::Loading {
+ return None;
+ }
+ for source in self.sources.by_ref() {
+ match source {
+ CssFontSource::Local(name) => {
+ if let Some(data) = services.local_font_source(&name) {
+ self.state = LoadState::Loaded(data);
+ return None;
+ }
+ }
+ CssFontSource::Url(url) => return Some(url),
+ }
+ }
+ self.fail(
+ "NetworkError",
+ "A network error occurred while loading the font.",
+ );
+ None
+ }
+
+ /// A bad response leaves the resource loading so its source list can fall
+ /// back. Stale/canceled document requests must be rejected by the owner
+ /// before this method is called.
+ pub(crate) fn accept_response(
+ &mut self,
+ bytes: Option<&[u8]>,
+ ) -> Result<(), WebFontRegistrationError> {
+ if let Some(bytes) = bytes {
+ self.state = LoadState::Loaded(FontFaceData::from_bytes(bytes)?);
+ }
+ Ok(())
+ }
+
+ pub(crate) fn register(
+ &self,
+ services: &mut DocumentLayoutServices,
+ ) -> Result<Option<WebFontRegistrationOutcome>, WebFontRegistrationError> {
+ let LoadState::Loaded(data) = &self.state else {
+ return Ok(None);
+ };
+ let mut registration = WebFontRegistration::new(
+ self.slot.clone(),
+ self.descriptor.clone(),
+ data.bytes().to_vec(),
+ );
+ if self.stylesheet {
+ registration = registration.with_stylesheet_scope();
+ }
+ services.register_web_font(registration).map(Some)
+ }
+
+ pub(crate) fn unregister(&self, services: &mut DocumentLayoutServices) {
+ services.remove_web_font(&self.slot);
+ }
+}
diff --git a/moli-renderer-v8/src/lib.rs b/moli-renderer-v8/src/lib.rs
index 74d2843ca..534ca67ef 100644
--- a/moli-renderer-v8/src/lib.rs
+++ b/moli-renderer-v8/src/lib.rs
@@ -59,6 +59,7 @@ mod dom_parser;
mod dynamic_script_owner;
mod event_listener_args;
mod exception_reporting;
+mod font_loading;
mod frame_owner_model;
mod host;
mod host_bindings;
diff --git a/moli-renderer-v8/src/live_stylesheet/mod.rs b/moli-renderer-v8/src/live_stylesheet/mod.rs
index faf92edac..e9ce4d9d7 100644
--- a/moli-renderer-v8/src/live_stylesheet/mod.rs
+++ b/moli-renderer-v8/src/live_stylesheet/mod.rs
@@ -1728,6 +1728,9 @@ impl LiveStylesheet {
rule_identity: identity,
rule_fingerprint: native_rule.rule_fingerprint.clone(),
descriptor: native_rule.descriptor.clone(),
+ resource: crate::css_resource_urls::stylesheet_web_font_resource_with_resolved_sources(
+ &native_rule.rule_fingerprint, native_rule.sources.clone(),
+ ),
});
if native_projection
.effective_rule_addresses
diff --git a/moli-renderer-v8/src/native_bridge/context_host/layout.rs b/moli-renderer-v8/src/native_bridge/context_host/layout.rs
index 5824064f3..cf36f39bf 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/layout.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/layout.rs
@@ -303,6 +303,20 @@ impl JsContextHost {
Ok(())
}
+ /// FontFace and Canvas use the document's font service without requesting a
+ /// layout pass or changing the frozen synchronous DOM geometry snapshot.
+ pub(crate) fn with_font_services<T>(
+ &self,
+ document: DomHandle,
+ consume: impl FnOnce(&mut moli_layout::DocumentLayoutServices) -> T,
+ ) -> T {
+ self.document_layout_state
+ .borrow_mut()
+ .with_services_for_document(document, self.document_handle(), |services, _| {
+ consume(services)
+ })
+ }
+
pub(crate) fn build_layout_pass_for_document(
&self,
document: DomHandle,
@@ -677,6 +691,16 @@ impl JsContextHost {
.retire_embedded_document_fonts(document);
}
+ pub(crate) fn observe_document_font_face(
+ &self,
+ document: DomHandle,
+ font: &crate::css_resource_urls::StylesheetWebFont,
+ ) -> crate::font_loading::FontFaceLoad {
+ self.document_layout_state
+ .borrow_mut()
+ .observe_font(document, self.document_handle(), font)
+ }
+
#[cfg(test)]
pub(crate) fn document_web_font_counts_for_test(&self) -> (usize, usize, usize) {
self.document_layout_state.borrow().web_font_counts()
diff --git a/moli-renderer-v8/src/native_bridge/context_host/layout_state.rs b/moli-renderer-v8/src/native_bridge/context_host/layout_state.rs
index 1022192d4..0456b4bd7 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/layout_state.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/layout_state.rs
@@ -330,11 +330,29 @@ impl DocumentLayoutState {
main_document: DomHandle,
resource: StylesheetLoadBlockingResource,
) -> Option<StylesheetLoadBlockingResource> {
+ // Ready faces are revisited by read-only font projections.
self.with_web_fonts_for_document(document, main_document, |fonts, services| {
fonts.admit(resource, services)
})
}
+ pub(super) fn observe_font(
+ &mut self,
+ document: DomHandle,
+ main_document: DomHandle,
+ font: &crate::css_resource_urls::StylesheetWebFont,
+ ) -> crate::font_loading::FontFaceLoad {
+ let fonts = if document == main_document {
+ &mut self.web_fonts
+ } else {
+ self.embedded_web_fonts
+ .get_or_insert_with(Default::default)
+ .entry(document)
+ .or_default()
+ };
+ fonts.observe(font)
+ }
+
pub(super) fn complete(
&mut self,
document: DomHandle,
diff --git a/moli-renderer-v8/src/native_bridge/context_host/resource_loading.rs b/moli-renderer-v8/src/native_bridge/context_host/resource_loading.rs
index f5ea94294..65eacdc59 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/resource_loading.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/resource_loading.rs
@@ -1257,6 +1257,50 @@ impl JsContextHost {
Some(internal_id)
}
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) fn record_async_font_face_fetch(
+ &mut self,
+ context: v8::Global<v8::Context>,
+ face: v8::Global<v8::Object>,
+ owner: OwnerDispatchScope,
+ cancel_handle: moli_fetch::FetchCancelHandle,
+ network_partition_key: Option<String>,
+ policy_context: crate::types::SubresourcePolicyContext,
+ mut info: PendingSubresourceFetchInfo,
+ ) -> u64 {
+ self.assign_pending_subresource_fetch_identity(&mut info);
+ let internal_id = info.internal_id;
+ let (load, request_origin) = self.require_document_resource_load_for_dispatch_scope(
+ owner,
+ info.resource_type,
+ ResourceLoadDisposition::Ordinary,
+ Some(cancel_handle),
+ );
+ self.record_pending_subresource_request_started_with_initiator(
+ &info,
+ SubresourceRequestInitiatorType::Script,
+ load.disposition(),
+ );
+ self.pending_subresource_fetches.insert(
+ internal_id,
+ PendingSubresourceFetchState {
+ info,
+ load,
+ execution_context: PendingSubresourceExecutionContext::adapter(owner, context),
+ credentials_mode: moli_fetch::RequestCredentialsMode::SameOrigin,
+ request_mode: moli_fetch::RequestMode::Cors,
+ network_partition_key,
+ policy_context,
+ continuation: PendingSubresourceContinuation::FontFace(face),
+ request_origin,
+ redirect_headers: None,
+ deferred_request_started: false,
+ },
+ );
+ self.note_subresource_activity();
+ internal_id
+ }
+
pub(crate) fn record_async_subresource_beacon(
&mut self,
execution_context: super::WindowExecutionContextIdentity,
diff --git a/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs b/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs
index 4008f91ef..640718297 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs
@@ -3,9 +3,10 @@ use crate::content_security_policy::ContentSecurityPolicy;
use super::{JsContextHost, OwnerDispatchScope};
use crate::{
content_security_policy::{
- ContentSecurityPolicyNonUrlKind, ContentSecurityPolicyRedirectStatus,
- ContentSecurityPolicyReportingEndpoints, ContentSecurityPolicyScriptElementRequest,
- ContentSecurityPolicyViolationEventFields, TrustedTypesForScriptRequirements,
+ ContentSecurityPolicyDisposition, ContentSecurityPolicyNonUrlKind,
+ ContentSecurityPolicyRedirectStatus, ContentSecurityPolicyReportingEndpoints,
+ ContentSecurityPolicyScriptElementRequest, ContentSecurityPolicyViolationEventFields,
+ TrustedTypesForScriptRequirements,
},
context_bootstrap::CHILD_BROWSING_CONTEXT_HANDLE_SLOT,
document_runtime::{
@@ -569,6 +570,35 @@ impl JsContextHost {
OwnerDispatchScope::Top
}
+ pub(crate) fn font_request_allowed_by_csp(
+ &mut self,
+ scope: &mut v8::PinScope<'_, '_>,
+ owner: OwnerDispatchScope,
+ document_url: &url::Url,
+ request_url: &url::Url,
+ redirect_status: ContentSecurityPolicyRedirectStatus,
+ ) -> bool {
+ let Some(policy) = self.document_connect_policy_snapshot_for_owner(owner) else {
+ return false;
+ };
+ let mut allowed = true;
+ for disposition in [
+ ContentSecurityPolicyDisposition::Report,
+ ContentSecurityPolicyDisposition::Enforce,
+ ] {
+ if let Some(violation) =
+ policy.font_violation(document_url, request_url, disposition, redirect_status)
+ {
+ let host_ptr = self as *mut Self;
+ self.dispatch_content_security_policy_violation_event_for_owner_best_effort(
+ scope, host_ptr, owner, &violation,
+ );
+ allowed &= disposition != ContentSecurityPolicyDisposition::Enforce;
+ }
+ }
+ allowed
+ }
+
pub(crate) fn check_document_connect_csp_for_owner<'s>(
&mut self,
scope: &mut v8::PinScope<'s, '_>,
diff --git a/moli-renderer-v8/src/native_bridge/document/css_state/font_faces.rs b/moli-renderer-v8/src/native_bridge/document/css_state/font_faces.rs
index 44b97db6c..1912d88df 100644
--- a/moli-renderer-v8/src/native_bridge/document/css_state/font_faces.rs
+++ b/moli-renderer-v8/src/native_bridge/document/css_state/font_faces.rs
@@ -77,6 +77,7 @@ fn construct_font_face_from_parts<'s>(
scope: &mut v8::PinScope<'s, '_>,
family: &str,
source: &str,
+ rule_css: Option<&str>,
) -> Option<v8::Local<'s, v8::Value>> {
let ctor =
crate::context_bootstrap::exposed_interfaces::ensure_intrinsic_interface_constructor(
@@ -85,7 +86,37 @@ fn construct_font_face_from_parts<'s>(
.ok()?;
let family = v8_string(scope, family)?;
let source = v8_string(scope, source)?;
- ctor.new_instance(scope, &[family.into(), source.into()])
+ let descriptors = v8::Object::new(scope);
+ let _ = descriptors.set_prototype(scope, v8::null(scope).into());
+ if let Some(rule) = rule_css.and_then(moli_css_parse::parse_font_face_rule_view_with_stylo) {
+ for entry in moli_css_parse::parse_declaration_list(
+ &rule.style_text,
+ moli_css_parse::DeclarationParseOptions {
+ canonicalize_property_name: true,
+ unescape_value_semicolons: false,
+ preserve_empty_values: false,
+ },
+ ) {
+ let name = match entry.name.as_str() {
+ "font-style" => "style",
+ "font-weight" => "weight",
+ "font-stretch" => "stretch",
+ "font-variant" => "variant",
+ "font-feature-settings" => "featureSettings",
+ "font-variation-settings" => "variationSettings",
+ "font-display" => "display",
+ _ => continue,
+ };
+ let value = v8_string(scope, &entry.value)?;
+ // Define data properties rather than invoking author Object.prototype setters.
+ let _ = descriptors.create_data_property(
+ scope,
+ crate::util::v8str(scope, name).into(),
+ value.into(),
+ );
+ }
+ }
+ ctor.new_instance(scope, &[family.into(), source.into(), descriptors.into()])
.map(Into::into)
}
@@ -93,7 +124,7 @@ fn construct_font_face<'s>(
scope: &mut v8::PinScope<'s, '_>,
descriptor: &StylesheetFontFaceDescriptor,
) -> Option<v8::Local<'s, v8::Value>> {
- construct_font_face_from_parts(scope, descriptor.family(), descriptor.source())
+ construct_font_face_from_parts(scope, descriptor.family(), descriptor.source(), None)
}
fn collect_font_face_objects<'s>(
@@ -147,7 +178,7 @@ pub(super) fn sync_document_fonts<'s>(
.stylesheet_candidate_handles_for_tree_scope(document);
for owner in candidates.iter().copied() {
let projection = owner_font_face_projection(host, owner);
- set_owner_font_face_contribution(scope, fonts, owner, projection.as_ref());
+ set_owner_font_face_contribution(scope, fonts, host, owner, projection.as_ref());
}
rebuild_connected_font_faces(scope, fonts, host, document);
Some(fonts)
@@ -168,7 +199,7 @@ pub(super) fn apply_font_face_owner_projection<'s>(
let projection = refresh
.then(|| owner_font_face_projection(host, owner))
.flatten();
- set_owner_font_face_contribution(scope, fonts, owner, projection.as_ref());
+ set_owner_font_face_contribution(scope, fonts, host, owner, projection.as_ref());
true
}
@@ -187,6 +218,7 @@ pub(super) fn finish_font_face_owner_projections<'s>(
fn set_owner_font_face_contribution<'s>(
scope: &mut v8::PinScope<'s, '_>,
fonts: v8::Local<'s, v8::Object>,
+ host: &JsContextHost,
owner: DomHandle,
projection: Option<&OwnerFontFaceProjection>,
) {
@@ -197,6 +229,9 @@ fn set_owner_font_face_contribution<'s>(
let _ = contributions.set_index(scope, index, undefined.into());
return;
};
+ let Some(document) = host.dom_host().owner_document_handle(owner) else {
+ return;
+ };
let existing = contributions
.get_index(scope, index)
.and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())
@@ -227,10 +262,18 @@ fn set_owner_font_face_contribution<'s>(
OwnerFontFaceProjection::Live {
stylesheet_id,
projection,
- } => sync_stylesheet_font_face_wrappers(scope, existing, *stylesheet_id, projection, true)
- .into_iter()
- .map(|(_, face)| face.into())
- .collect(),
+ } => sync_stylesheet_font_face_wrappers(
+ scope,
+ existing,
+ *stylesheet_id,
+ projection,
+ true,
+ host,
+ document,
+ )
+ .into_iter()
+ .map(|(_, face)| face.into())
+ .collect(),
};
let faces = serialize_v8_iter_array(scope, faces).unwrap_or_else(|| v8::Array::new(scope, 0));
let _ = contributions.set_index(scope, index, faces.into());
@@ -242,6 +285,8 @@ fn sync_stylesheet_font_face_wrappers<'s>(
stylesheet_id: crate::live_stylesheet::StylesheetId,
projection: &StylesheetFontFaceProjection,
effective_only: bool,
+ host: &JsContextHost,
+ document: DomHandle,
) -> Vec<(u64, v8::Local<'s, v8::Object>)> {
let mut used = vec![false; existing.len()];
let mut all_faces = Vec::with_capacity(projection.all_rules.len());
@@ -269,6 +314,7 @@ fn sync_stylesheet_font_face_wrappers<'s>(
scope,
&rule.descriptor.family,
&rule.descriptor.source,
+ Some(&rule.rule_fingerprint),
)?;
let face = v8::Local::<v8::Object>::try_from(face).ok()?;
set_private_u64(
@@ -292,6 +338,18 @@ fn sync_stylesheet_font_face_wrappers<'s>(
Some(face)
});
if let Some(face) = face {
+ if let Some(font) = rule
+ .resource
+ .as_ref()
+ .and_then(|resource| resource.web_font())
+ {
+ // The resource metadata retains the stylesheet parser's URLs
+ // and the same slot used by CSS resource admission.
+ let load = host.observe_document_font_face(document, font);
+ if !crate::context_bootstrap::bind_stylesheet_font_face(scope, face, load) {
+ continue;
+ }
+ }
all_faces.push((rule.rule_identity, face));
}
}
@@ -398,6 +456,8 @@ fn document_adopted_font_faces<'s>(
scope,
sheet,
&descriptors,
+ host,
+ document,
));
}
faces
@@ -407,6 +467,8 @@ fn sync_adopted_stylesheet_font_faces<'s>(
scope: &mut v8::PinScope<'s, '_>,
sheet: v8::Local<'s, v8::Object>,
projection: &StylesheetFontFaceProjection,
+ host: &JsContextHost,
+ document: DomHandle,
) -> Vec<v8::Local<'s, v8::Value>> {
let existing = get_private_value(scope, sheet, CSS_STYLE_SHEET_FONT_FACE_WRAPPERS_SLOT)
.and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())
@@ -417,8 +479,15 @@ fn sync_adopted_stylesheet_font_faces<'s>(
else {
return Vec::new();
};
- let all_faces =
- sync_stylesheet_font_face_wrappers(scope, existing, stylesheet_id, projection, false);
+ let all_faces = sync_stylesheet_font_face_wrappers(
+ scope,
+ existing,
+ stylesheet_id,
+ projection,
+ false,
+ host,
+ document,
+ );
let stored = serialize_v8_iter_array(scope, all_faces.iter().map(|(_, face)| *face))
.unwrap_or_else(|| v8::Array::new(scope, 0));
set_private_value(
diff --git a/moli-renderer-v8/src/network_host.rs b/moli-renderer-v8/src/network_host.rs
index a8c61ccdc..616cd7309 100644
--- a/moli-renderer-v8/src/network_host.rs
+++ b/moli-renderer-v8/src/network_host.rs
@@ -8,6 +8,7 @@ mod csp_reports;
mod event_source;
mod fetch;
mod fetch_surface;
+mod font_face;
mod headers;
mod image;
mod js_values;
@@ -21,6 +22,7 @@ mod text_track;
mod url_helpers;
mod xhr;
+pub(crate) use font_face::{FontFaceFetchStart, start_font_face_fetch};
use moli_fetch::{Request, Response, observe_cookie_access_report_for_request};
use crate::network::ResourceRequestClient;
diff --git a/moli-renderer-v8/src/network_host/font_face.rs b/moli-renderer-v8/src/network_host/font_face.rs
new file mode 100644
index 000000000..b482053ea
--- /dev/null
+++ b/moli-renderer-v8/src/network_host/font_face.rs
@@ -0,0 +1,195 @@
+use super::*;
+use crate::service_worker_runtime::{
+ ServiceWorkerFetchDispatch, ServiceWorkerRequestDestination,
+ service_worker_fetch_request_metadata,
+};
+use crate::{
+ native_bridge::JsContextHost,
+ types::{
+ AsyncSubresourceNetworkContext, PendingSubresourceFetchInfo,
+ SubresourceRequestInitiatorType, SubresourceResourceType,
+ },
+};
+use moli_fetch::{
+ BrowserRequestMetadata, FetchCancelHandle, RequestCredentialsMode, RequestMode,
+ RequestResourceType,
+};
+
+pub(crate) enum FontFaceFetchStart {
+ Local(Vec<u8>),
+ Pending,
+}
+
+/// Explicit CSS Font Loading requests share document ownership, CORS and the
+/// renderer network queue with other resources. Never call page-defined fetch.
+pub(crate) fn start_font_face_fetch(
+ scope: &mut v8::PinScope<'_, '_>,
+ face: v8::Local<'_, v8::Object>,
+ source: &str,
+) -> Result<FontFaceFetchStart, String> {
+ let host_ptr = crate::util::context_host_ptr_from_global_bridge(scope)
+ .ok_or_else(|| "FontFace URL loader is unavailable in this realm".to_owned())?;
+ // SAFETY: the current live realm owns the bridge. No author callback runs
+ // while the host is used except its existing CSP notification boundary.
+ let host: &mut JsContextHost = unsafe { &mut *host_ptr };
+ let owner = effective_subresource_request_owner(scope, host);
+ let resource_loader = host
+ .document_resource_loader_for_dispatch_scope(owner)
+ .ok_or_else(|| "Font request has no live document resource loader".to_owned())?;
+ let environment = host
+ .subresource_request_environment(&resource_loader, owner)
+ .ok_or_else(|| "Font request has no live document request environment".to_owned())?;
+ let crate::network::context::SubresourceRequestEnvironment {
+ document_url,
+ base_url,
+ request_origin,
+ frame_id,
+ } = environment;
+ let request_url = base_url.join(source).map_err(|e| e.to_string())?;
+ if !host.font_request_allowed_by_csp(
+ scope,
+ owner,
+ &document_url,
+ &request_url,
+ crate::content_security_policy::ContentSecurityPolicyRedirectStatus::NoRedirect,
+ ) {
+ return Err("Font request blocked by Content Security Policy".into());
+ }
+ if let Some(response) = local_url_response(&request_url) {
+ let response: crate::types::NavigationResponse = response.into();
+ let result = if (200..300).contains(&response.status) {
+ Ok(FontFaceFetchStart::Local(response.body_bytes().to_vec()))
+ } else {
+ Err("Font request failed".to_owned())
+ };
+ host.record_get_subresource_network_result_with_initiator(
+ frame_id,
+ document_url,
+ request_url,
+ SubresourceResourceType::Font,
+ SubresourceRequestInitiatorType::Script,
+ &Ok(response),
+ );
+ return result;
+ }
+ let loader = resource_loader.request_client().clone();
+ let network_partition_key = active_subresource_network_partition_key(host, owner);
+ let policy_context = effective_subresource_policy_context(scope, host, owner);
+ let request_cookie_report = observe_subresource_request_cookie_report(
+ &loader,
+ &document_url,
+ &request_origin,
+ &request_url,
+ "GET",
+ RequestCredentialsMode::SameOrigin,
+ );
+ let request = Request::new("GET", request_url.as_str(), None, Vec::new())
+ .map_err(|e| e.to_string())?
+ .with_initiator_url(&document_url)
+ .with_request_origin(request_origin.clone())
+ .with_resource_type(RequestResourceType::Font)
+ .with_page_network_policy()
+ .with_request_mode(RequestMode::Cors)
+ .with_credentials_mode(RequestCredentialsMode::SameOrigin)
+ .with_network_partition_key(network_partition_key.clone())
+ .with_browser_request_metadata(BrowserRequestMetadata::Font)
+ .with_subframe_context(frame_id.is_some());
+ let cancel_handle = FetchCancelHandle::new();
+ let internal_id = host.record_async_font_face_fetch(
+ v8::Global::new(scope, scope.get_current_context()),
+ v8::Global::new(scope, face),
+ owner,
+ cancel_handle.clone(),
+ network_partition_key,
+ policy_context,
+ PendingSubresourceFetchInfo {
+ internal_id: 0,
+ network_request_handle: None,
+ frame_id: frame_id.clone(),
+ document_url: document_url.clone(),
+ url: request_url.clone(),
+ websocket_socket_id: None,
+ method: "GET".into(),
+ request_headers: Default::default(),
+ request_body: None,
+ request_body_bytes: None,
+ resource_type: SubresourceResourceType::Font,
+ request_cookie_report: request_cookie_report.clone(),
+ },
+ );
+ let client_id = host.service_worker_client_id_for_subresource_owner(owner);
+ if matches!(request_url.scheme(), "http" | "https")
+ && host
+ .service_worker_controller_for_fetch(client_id, &document_url, &request_url)
+ .is_some()
+ {
+ let dispatch = ServiceWorkerFetchDispatch {
+ internal_id,
+ request: host.service_worker_fetch_request(
+ client_id,
+ request_url.clone(),
+ "GET".into(),
+ Vec::new(),
+ None,
+ ServiceWorkerRequestDestination::Font,
+ RequestMode::Cors,
+ RequestCredentialsMode::SameOrigin,
+ moli_fetch::RequestRedirectMode::Follow,
+ request.priority_hints.fetch_priority,
+ service_worker_fetch_request_metadata(&request),
+ ),
+ cors_preflight_request_headers: Vec::new(),
+ request_cookie_report,
+ network_context: AsyncSubresourceNetworkContext {
+ request_origin: request_origin.clone(),
+ frame_id,
+ document_url,
+ resource_type: SubresourceResourceType::Font,
+ policy_context,
+ },
+ completion_tx: host.resource_completion_sender(),
+ request_client: loader,
+ resource_task_runner: resource_loader.task_runner(),
+ cancel_handle,
+ direct_completion_tx: None,
+ };
+ if !host.dispatch_service_worker_fetch(dispatch) {
+ let _ = host.resource_completion_sender().send_async_subresource(
+ crate::types::AsyncSubresourceFetchCompletion {
+ internal_id,
+ request_url,
+ request_method: "GET".into(),
+ request_headers: Default::default(),
+ request_body: None,
+ response_status_text: None,
+ skip_fetch_security_validation: false,
+ response_filter: None,
+ network_error_text: None,
+ result: Err("service worker font request dispatch failed".into()).into(),
+ },
+ );
+ }
+ return Ok(FontFaceFetchStart::Pending);
+ }
+ spawn_async_subresource_fetch(
+ resource_loader.task_runner(),
+ host.resource_completion_sender(),
+ loader,
+ request,
+ Some(cancel_handle),
+ Vec::new(),
+ internal_id,
+ AsyncSubresourceNetworkContext {
+ request_origin,
+ frame_id,
+ document_url,
+ resource_type: SubresourceResourceType::Font,
+ policy_context,
+ },
+ request_url,
+ "GET".into(),
+ Default::default(),
+ None,
+ );
+ Ok(FontFaceFetchStart::Pending)
+}
diff --git a/moli-renderer-v8/src/script_vm/layout.rs b/moli-renderer-v8/src/script_vm/layout.rs
index 5fb3efd86..8f06f6aba 100644
--- a/moli-renderer-v8/src/script_vm/layout.rs
+++ b/moli-renderer-v8/src/script_vm/layout.rs
@@ -464,11 +464,11 @@ impl ScriptVm {
else {
return;
};
- match self
+ let completion = self
._context_host
.borrow()
- .complete_document_web_font(document, terminal)
- {
+ .complete_document_web_font(document, terminal);
+ match completion {
web_fonts::DocumentWebFontCompletion::Registered(outcome) => tracing::debug!(
?outcome,
"registered current document web font for the next fresh layout refresh"
@@ -483,8 +483,18 @@ impl ScriptVm {
web_fonts::DocumentWebFontCompletion::Stale => {
tracing::debug!("discarded superseded document web font response")
}
+ web_fonts::DocumentWebFontCompletion::Retry(resource) => {
+ let binding = self
+ ._context_host
+ .borrow_mut()
+ .accept_current_stylesheet_subresource_load_delay_for_document(document);
+ if let Some(binding) = binding {
+ self.start_stylesheet_subresource_fetches(vec![(binding, *resource)]);
+ }
+ }
}
if let Err(error) = self.with_default_context_scope(|scope, host_ptr| {
+ crate::context_bootstrap::publish_font_face_load_changes(scope);
crate::context_bootstrap::settle_document_font_face_set_ready(
scope, host_ptr, document,
);
diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch.rs b/moli-renderer-v8/src/script_vm/subresource_fetch.rs
index 7ed28dde3..20dabe885 100644
--- a/moli-renderer-v8/src/script_vm/subresource_fetch.rs
+++ b/moli-renderer-v8/src/script_vm/subresource_fetch.rs
@@ -737,6 +737,7 @@ fn pending_subresource_continuation_kind(
PendingSubresourceContinuation::Image { .. } => "image",
PendingSubresourceContinuation::Media { .. } => "media",
PendingSubresourceContinuation::TextTrack { .. } => "text_track",
+ PendingSubresourceContinuation::FontFace(_) => "font_face",
PendingSubresourceContinuation::StylesheetSubresource { .. } => "stylesheet_subresource",
PendingSubresourceContinuation::Beacon => "beacon",
PendingSubresourceContinuation::CspReport { .. } => "csp_report",
diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch/fetch_dispatch.rs b/moli-renderer-v8/src/script_vm/subresource_fetch/fetch_dispatch.rs
index 53be0bba5..3552ef049 100644
--- a/moli-renderer-v8/src/script_vm/subresource_fetch/fetch_dispatch.rs
+++ b/moli-renderer-v8/src/script_vm/subresource_fetch/fetch_dispatch.rs
@@ -499,6 +499,11 @@ impl ScriptVm {
let security_started = moli_trace::cdp_runtime_trace_enabled().then(Instant::now);
let mut opaque_response_blocked = false;
let result = result.and_then(|response| {
+ if matches!(pending.continuation, PendingSubresourceContinuation::FontFace(_))
+ && !response.redirect_chain.is_empty()
+ && !context_host.borrow_mut().font_request_allowed_by_csp(scope, pending.execution_context.dispatch_scope(), &pending.info.document_url, &response.final_url, crate::content_security_policy::ContentSecurityPolicyRedirectStatus::FollowedRedirect) {
+ return Err("Font redirect blocked by Content Security Policy".to_owned());
+ }
if !response.redirect_chain.is_empty()
&& let Some(message) = document_connect_csp_redirect_failure_message(
scope,
@@ -760,6 +765,12 @@ impl ScriptVm {
observable_response.body_text(),
),
),
+ PendingSubresourceContinuation::FontFace(face) => {
+ let face = v8::Local::new(scope, face);
+ let bytes = ((200..300).contains(&response_status) && !opaque_response_blocked)
+ .then(|| observable_response.body_bytes());
+ crate::context_bootstrap::finish_font_face_url_load(scope, face, bytes);
+ }
PendingSubresourceContinuation::StylesheetSubresource {
binding,
web_font,
@@ -899,6 +910,10 @@ impl ScriptVm {
pending.info.internal_id,
Err(error_text.clone()),
),
+ PendingSubresourceContinuation::FontFace(face) => {
+ let face = v8::Local::new(scope, face);
+ crate::context_bootstrap::finish_font_face_url_load(scope, face, None);
+ }
PendingSubresourceContinuation::StylesheetSubresource {
binding,
web_font,
diff --git a/moli-renderer-v8/src/script_vm/subresource_fetch/streaming.rs b/moli-renderer-v8/src/script_vm/subresource_fetch/streaming.rs
index 202415197..0071d0650 100644
--- a/moli-renderer-v8/src/script_vm/subresource_fetch/streaming.rs
+++ b/moli-renderer-v8/src/script_vm/subresource_fetch/streaming.rs
@@ -712,6 +712,10 @@ impl ScriptVm {
started.internal_id,
Err(error_text.clone()),
),
+ PendingSubresourceContinuation::FontFace(face) => {
+ let face = v8::Local::new(scope, face);
+ crate::context_bootstrap::finish_font_face_url_load(scope, face, None);
+ }
PendingSubresourceContinuation::StylesheetSubresource { binding, .. } => {
apply_stylesheet_subresource_terminal(&self._context_host, *binding);
}
@@ -950,6 +954,10 @@ impl ScriptVm {
started.internal_id,
Err("text-track response unexpectedly used streaming transport".to_owned()),
),
+ PendingSubresourceContinuation::FontFace(face) => {
+ let face = v8::Local::new(scope, face);
+ crate::context_bootstrap::finish_font_face_url_load(scope, face, None);
+ }
PendingSubresourceContinuation::StylesheetSubresource { binding, .. } => {
apply_stylesheet_subresource_terminal(&self._context_host, *binding);
}
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
new file mode 100644
index 000000000..18fbf4bd6
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/fonts.rs
@@ -0,0 +1,426 @@
+use super::*;
+use base64::Engine;
+use std::time::Duration;
+
+pub(super) fn fixture_font_url() -> String {
+ let bytes = include_bytes!(concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/../moli-layout/tests/fixtures/moli-ahem.woff2"
+ ));
+ format!(
+ "data:font/woff2;base64,{}",
+ base64::engine::general_purpose::STANDARD.encode(bytes)
+ )
+}
+
+#[test]
+fn font_face_missing_local_source_rejects_instead_of_matching_css_fallback() {
+ let mut vm = new_storage_test_vm("https://font-sources.test/");
+ vm.eval(r#"
+globalThis.fontResult = [];
+const face = new FontFace('Missing Face', 'local("MoliDefinitelyNotAFont-0001345")');
+fontResult.push(face.status, face.loaded === face.loaded);
+document.fonts.add(face);
+fontResult.push(document.fonts.check('12px "Missing Face"'), document.fonts.check('12px UnregisteredFace'));
+const promise = face.load();
+fontResult.push(promise === face.loaded, face.status);
+promise.then(() => fontResult.push('WRONG success'), error => fontResult.push(error.name, face.status));
+document.fonts.load('12px "Missing Face"').then(() => fontResult.push('WRONG set success'), error => fontResult.push(error.name));
+"#).unwrap();
+ assert_eq!(
+ vm.eval("JSON.stringify(fontResult)").unwrap(),
+ r#"["unloaded",true,false,true,true,"error","NetworkError","error","NetworkError"]"#
+ );
+}
+
+#[test]
+fn font_face_valid_data_sources_register_and_unregister_real_font_bytes() {
+ let mut vm = new_storage_test_vm("https://font-sources.test/");
+ let url = fixture_font_url();
+ vm.eval(&format!(r#"
+globalThis.fontResult = [];
+globalThis.face = new FontFace('Actual Face', 'local("MoliDefinitelyNotAFont"), url("{url}") format("woff2")');
+document.fonts.add(face);
+fontResult.push(face.status, document.fonts.check('italic 12px "Actual Face", serif'));
+document.fonts.load('12px "Actual Face", serif').then(faces => fontResult.push(faces.length, faces[0] === face, face.status, document.fonts.check('12px "Actual Face"')));
+"#)).unwrap();
+ assert_eq!(
+ vm.eval("JSON.stringify(fontResult)").unwrap(),
+ r#"["unloaded",false,1,true,"loaded",true]"#
+ );
+ assert_eq!(vm.document_web_font_counts_for_test().2, 1);
+ vm.eval("face.family = 'Renamed Face'").unwrap();
+ assert_eq!(
+ vm.document_web_font_counts_for_test().2,
+ 1,
+ "descriptor replacement must not leak the old registration"
+ );
+ vm.eval("document.fonts.delete(face)").unwrap();
+ assert_eq!(vm.document_web_font_counts_for_test().2, 0);
+}
+
+#[test]
+fn font_face_binary_sources_require_real_decodable_fonts() {
+ let mut vm = new_storage_test_vm("https://font-sources.test/");
+ let encoded = fixture_font_url().split_once(',').unwrap().1.to_owned();
+ vm.eval(&format!(
+ r#"
+globalThis.fontResult = [];
+const bytes = Uint8Array.from(atob('{encoded}'), c => c.charCodeAt(0));
+const face = new FontFace('Binary Face', bytes);
+fontResult.push(face.status);
+face.loaded.then(value => fontResult.push(value === face));
+document.fonts.add(face);
+for (const header of [[0,1,0,0], [79,84,84,79], [119,79,70,70], [119,79,70,50]]) {{
+ const bad = new FontFace('Bad Face', new Uint8Array(header));
+ fontResult.push(bad.status);
+ bad.loaded.catch(error => fontResult.push(error.name));
+}}
+"#
+ ))
+ .unwrap();
+ assert_eq!(
+ vm.eval("JSON.stringify(fontResult)").unwrap(),
+ r#"["loaded","error","error","error","error",true,"SyntaxError","SyntaxError","SyntaxError","SyntaxError"]"#
+ );
+ assert_eq!(vm.document_web_font_counts_for_test().2, 1);
+ vm.eval("document.fonts.clear()").unwrap();
+ assert_eq!(vm.document_web_font_counts_for_test().2, 0);
+}
+
+#[test]
+fn font_set_load_and_check_reject_invalid_shorthand_without_page_property_reads() {
+ let mut vm = new_storage_test_vm("https://font-sources.test/");
+ vm.eval(
+ r#"
+globalThis.fontResult = [];
+const face = new FontFace('Test', 'local("Missing Font 9944")');
+document.fonts.add(face);
+Object.defineProperty(face, 'family', {get() {throw new Error('must not read author getter');}});
+fontResult.push(document.fonts.check('12px Test'));
+try { document.fonts.check('not a font'); } catch(e) { fontResult.push(e.name); }
+document.fonts.load('not a font').catch(e => fontResult.push(e.name));
+"#,
+ )
+ .unwrap();
+ assert_eq!(
+ vm.eval("JSON.stringify(fontResult)").unwrap(),
+ r#"[false,"SyntaxError","SyntaxError"]"#
+ );
+}
+
+#[test]
+fn font_set_queries_preserve_system_shorthands_and_reject_unresolved_values() {
+ let mut vm = new_storage_test_vm("https://font-sources.test/");
+ vm.eval(
+ r#"
+globalThis.fontResult = [];
+for (const font of ['caption', 'ICON', 'menu', 'message-box', 'small-caption', 'status-bar', String.raw`c\61 ption`, 'caption/**/']) {
+ fontResult.push(document.fonts.check(font));
+ document.fonts.load(font).then(faces => fontResult.push(faces.length));
+}
+for (const font of ['var(--size, 12px) serif', 'env(size) serif', '12px inherit', '12px default', 'caption garbage']) {
+ try { document.fonts.check(font); fontResult.push('WRONG success'); }
+ catch (error) { fontResult.push(error.name); }
+ document.fonts.load(font).catch(error => fontResult.push(error.name));
+}
+"#,
+ )
+ .unwrap();
+ assert_eq!(
+ vm.eval("JSON.stringify(fontResult)").unwrap(),
+ r#"[true,true,true,true,true,true,true,true,"SyntaxError","SyntaxError","SyntaxError","SyntaxError","SyntaxError",0,0,0,0,0,0,0,0,"SyntaxError","SyntaxError","SyntaxError","SyntaxError","SyntaxError"]"#
+ );
+}
+
+#[tokio::test]
+async fn font_face_url_loading_waits_for_the_network_terminal_and_registers_the_response() {
+ let (url, request_rx, release_tx, server) = spawn_gated_font_resource_server().await;
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
+ let document_url = url.replace("/print-only.woff2", "/page");
+ let (mut vm, mut completions) =
+ new_storage_test_vm_with_loader_and_resource_completion_queue(&document_url, &loader);
+ vm.eval(&format!(r#"
+globalThis.fontResult = [];
+globalThis.face = new FontFace('Network Face', 'url("{url}")');
+document.fonts.add(face);
+document.fonts.load('12px "Network Face"').then(faces => fontResult.push(faces[0] === face, face.status));
+"#)).unwrap();
+ assert_eq!(
+ vm.eval("[face.status, document.fonts.status, fontResult.length].join('|')")
+ .unwrap(),
+ "loading|loading|0"
+ );
+ assert_eq!(vm.document_web_font_counts_for_test().2, 0);
+ let request = tokio::time::timeout(Duration::from_secs(2), request_rx)
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(
+ request
+ .to_ascii_lowercase()
+ .contains("sec-fetch-dest: font"),
+ "{request}"
+ );
+ release_tx.send(()).unwrap();
+ server.await.unwrap();
+ assert!(
+ tokio::time::timeout(
+ Duration::from_secs(2),
+ completions.wait_for_arrival_without_timeout()
+ )
+ .await
+ .unwrap()
+ );
+ let completion = completions.pop_next_async_subresource_event().unwrap();
+ let activity = vm
+ .complete_async_subresource_fetch_event_body(completion)
+ .unwrap();
+ vm.finish_async_subresource_body_checkpoint_for_test(activity)
+ .unwrap();
+ assert_eq!(
+ vm.eval("JSON.stringify(fontResult)").unwrap(),
+ "[true,\"loaded\"]"
+ );
+ assert_eq!(vm.document_web_font_counts_for_test().2, 1);
+ assert_eq!(vm.eval("document.fonts.status").unwrap(), "loaded");
+}
+
+#[test]
+fn font_face_url_sources_enforce_font_src_instead_of_connect_src() {
+ let mut vm = new_storage_test_vm("https://font-sources.test/");
+ vm.set_response_content_security_policies(&["font-src 'none'; connect-src * data:".to_owned()]);
+ vm.eval(&format!(
+ r#"
+globalThis.fontResult = [];
+const face = new FontFace('Blocked Font', 'url("{}")');
+face.load().catch(error => fontResult.push(error.name, face.status));
+"#,
+ fixture_font_url()
+ ))
+ .unwrap();
+ assert_eq!(
+ vm.eval("JSON.stringify(fontResult)").unwrap(),
+ "[\"NetworkError\",\"error\"]"
+ );
+ assert_eq!(vm.document_web_font_counts_for_test().2, 0);
+}
+
+async fn assert_css_and_js_share_font_loading(css_starts: bool, remove_rule: bool) {
+ let (url, request_rx, release_tx, server) = spawn_gated_font_resource_server().await;
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
+ loader.set_optional_resource_fetch_mask(crate::protocol_types::OptionalResourceFetchMask::FONT);
+ let document_url = url.replace("/print-only.woff2", "/page");
+ let (mut vm, mut completions) =
+ new_storage_test_vm_with_loader_and_resource_completion_queue(&document_url, &loader);
+ vm.eval(&format!(
+ r#"
+const html = document.createElement('html');
+html.innerHTML = '<head></head><body>AAAA</body>';
+document.append(html);
+const style = document.createElement('style');
+style.textContent = '@font-face {{ font-family: SharedFace; src: url("{url}"); }}';
+(document.head || document.documentElement).append(style);
+globalThis.face = [...document.fonts][0];
+globalThis.fontResult = [];
+globalThis.fontPromise = face.loaded;
+fontPromise.then(value => fontResult.push(value === face, face.status));
+"#
+ ))
+ .unwrap();
+ assert_eq!(vm.eval("face.status").unwrap(), "unloaded");
+ if !css_starts {
+ assert_eq!(vm.eval("face.load() === fontPromise").unwrap(), "true");
+ }
+ vm.refresh_layout_snapshot_for_test(moli_layout::LayoutViewport::new(800, 600, 1.0))
+ .unwrap();
+ assert_eq!(
+ vm.eval("[face.status, face.load() === fontPromise, document.fonts.status, fontResult.length].join('|')").unwrap(),
+ "loading|true|loading|0"
+ );
+ assert_eq!(
+ vm._context_host
+ .borrow()
+ .pending_subresource_request_count(),
+ 1,
+ "CSS and JS must reuse the same in-flight font, whichever starts first"
+ );
+ tokio::time::timeout(Duration::from_secs(2), request_rx)
+ .await
+ .unwrap()
+ .unwrap();
+ if remove_rule {
+ vm.eval("style.remove()").unwrap();
+ vm.refresh_layout_snapshot_for_test(moli_layout::LayoutViewport::new(800, 600, 1.0))
+ .unwrap();
+ assert_eq!(vm.document_web_font_counts_for_test(), (0, 0, 0));
+ }
+ release_tx.send(()).unwrap();
+ server.await.unwrap();
+ assert!(
+ tokio::time::timeout(
+ Duration::from_secs(2),
+ completions.wait_for_arrival_without_timeout()
+ )
+ .await
+ .unwrap()
+ );
+ let completion = completions.pop_next_async_subresource_event().unwrap();
+ let activity = vm
+ .complete_async_subresource_fetch_event_body(completion)
+ .unwrap();
+ vm.finish_async_subresource_body_checkpoint_for_test(activity)
+ .unwrap();
+ assert_eq!(
+ vm.eval("JSON.stringify(fontResult)").unwrap(),
+ r#"[true,"loaded"]"#
+ );
+ assert_eq!(vm.eval("document.fonts.status").unwrap(), "loaded");
+ assert_eq!(
+ vm.document_web_font_counts_for_test(),
+ if remove_rule { (0, 0, 0) } else { (1, 1, 1) }
+ );
+ assert_eq!(
+ vm.eval("document.fonts.check('12px SharedFace')").unwrap(),
+ "true"
+ );
+ assert_eq!(
+ vm._context_host
+ .borrow()
+ .pending_subresource_request_count(),
+ 0
+ );
+}
+
+#[tokio::test]
+async fn font_face_observes_the_stylesheet_request_without_starting_another() {
+ assert_css_and_js_share_font_loading(true, false).await;
+}
+
+#[tokio::test]
+async fn stylesheet_reuses_the_css_connected_font_face_started_by_javascript() {
+ assert_css_and_js_share_font_loading(false, false).await;
+}
+
+#[tokio::test]
+async fn removed_stylesheet_font_settles_javascript_without_restoring_registration() {
+ assert_css_and_js_share_font_loading(true, true).await;
+}
+
+#[tokio::test]
+async fn failed_stylesheet_font_rejects_the_connected_font_face_promise() {
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
+ loader.set_optional_resource_fetch_mask(crate::protocol_types::OptionalResourceFetchMask::FONT);
+ let (mut vm, _) = new_storage_test_vm_with_loader_and_resource_completion_queue(
+ "https://font-sources.test/",
+ &loader,
+ );
+ vm.eval(r#"
+const html = document.createElement('html');
+html.innerHTML = '<head></head><body>AAAA</body>';
+document.append(html);
+const style = document.createElement('style');
+style.textContent = '@font-face { font-family: FailedFace; src: url("data:font/woff2;base64,YmFk"); }';
+(document.head || document.documentElement).append(style);
+globalThis.face = [...document.fonts][0];
+globalThis.fontResult = [];
+face.loaded.catch(error => fontResult.push(error.name, face.status));
+"#).unwrap();
+ vm.refresh_layout_snapshot_for_test(moli_layout::LayoutViewport::new(800, 600, 1.0))
+ .unwrap();
+ // Layout demand is body-only. This evaluation observes the native terminal
+ // and runs the normal input-independent microtask checkpoint for its promise.
+ assert_eq!(vm.eval("face.status").unwrap(), "error");
+ assert_eq!(
+ vm.eval("JSON.stringify(fontResult)").unwrap(),
+ r#"["NetworkError","error"]"#
+ );
+ assert_eq!(vm.document_web_font_counts_for_test(), (1, 0, 0));
+ assert_eq!(
+ vm.eval("document.fonts.check('12px FailedFace')").unwrap(),
+ "false"
+ );
+}
+
+#[tokio::test]
+async fn stylesheet_font_source_fallback_settles_the_connected_font_face() {
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
+ loader.set_optional_resource_fetch_mask(crate::protocol_types::OptionalResourceFetchMask::FONT);
+ let (mut vm, _) = new_storage_test_vm_with_loader_and_resource_completion_queue(
+ "https://font-sources.test/",
+ &loader,
+ );
+ vm.eval(&format!(
+ r#"
+const html = document.createElement('html');
+html.innerHTML = '<head></head><body>AAAA</body>';
+document.append(html);
+const style = document.createElement('style');
+style.textContent = `@font-face {{
+ font-family: FallbackFace;
+ src: local("MoliDefinitelyNotAFont-0001345"),
+ url("data:font/woff2;base64,YmFk"), url("{}");
+}}`;
+(document.head || document.documentElement).append(style);
+globalThis.face = [...document.fonts][0];
+globalThis.fontResult = [];
+face.loaded.then(value => fontResult.push(value === face, face.status));
+"#,
+ fixture_font_url()
+ ))
+ .unwrap();
+ vm.refresh_layout_snapshot_for_test(moli_layout::LayoutViewport::new(800, 600, 1.0))
+ .unwrap();
+ assert_eq!(vm.eval("face.status").unwrap(), "loaded");
+ assert_eq!(
+ vm.eval("JSON.stringify(fontResult)").unwrap(),
+ r#"[true,"loaded"]"#
+ );
+ assert_eq!(vm.document_web_font_counts_for_test(), (1, 1, 1));
+ vm.eval("style.remove()").unwrap();
+ vm.refresh_layout_snapshot_for_test(moli_layout::LayoutViewport::new(800, 600, 1.0))
+ .unwrap();
+ assert_eq!(vm.document_web_font_counts_for_test(), (0, 0, 0));
+ assert_eq!(
+ vm.eval("face.status").unwrap(),
+ "loaded",
+ "removing CSS membership does not unload the held FontFace"
+ );
+}
+
+#[tokio::test]
+async fn loaded_stylesheet_font_is_reused_by_a_late_native_wrapper() {
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
+ loader.set_optional_resource_fetch_mask(crate::protocol_types::OptionalResourceFetchMask::FONT);
+ let (mut vm, _) = new_storage_test_vm_with_loader_and_resource_completion_queue(
+ "https://font-sources.test/",
+ &loader,
+ );
+ vm.eval(&format!(r#"
+const html = document.createElement('html');
+html.innerHTML = '<head></head><body>AAAA</body>';
+document.append(html);
+const style = document.createElement('style');
+style.textContent = '@font-face {{ font-family: LateFace; src: url("{}"); font-weight: 700; font-style: italic; }}';
+document.head.append(style);
+globalThis.NativeFontFace = FontFace;
+globalThis.FontFace = function() {{ throw new Error('CSS must not call the page constructor'); }};
+"#, fixture_font_url())).unwrap();
+ vm.refresh_layout_snapshot_for_test(moli_layout::LayoutViewport::new(800, 600, 1.0))
+ .unwrap();
+ assert_eq!(vm.document_web_font_counts_for_test(), (1, 1, 1));
+ assert_eq!(
+ vm.eval(
+ r#"
+globalThis.face = [...document.fonts][0];
+globalThis.fontResult = [];
+face.load().then(value => fontResult.push(value === face));
+[face instanceof NativeFontFace, face.status, face.weight, face.style].join('|')
+"#
+ )
+ .unwrap(),
+ "true|loaded|700|italic"
+ );
+ assert_eq!(vm.eval("JSON.stringify(fontResult)").unwrap(), "[true]");
+ assert_eq!(vm.document_web_font_counts_for_test(), (1, 1, 1));
+}
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/fonts.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/fonts.rs
index e7f2ce46b..bbaeee18a 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/fonts.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/fonts.rs
@@ -137,7 +137,7 @@ fn font_face_declared_slots_ignore_prototype_spoofing() {
assert_eq!(
result,
- r#"{"values":"Changed|url(demo.woff)|italic|700|condensed|small-caps|\"kern\"|swap|loaded|function","fake":"TypeError|TypeError|TypeError|TypeError|Promise","descriptors":["family:function:get family:0:function:set family:1:true:true:false","style:function:get style:0:function:set style:1:true:true:false","weight:function:get weight:0:function:set weight:1:true:true:false","stretch:function:get stretch:0:function:set stretch:1:true:true:false","variant:function:get variant:0:function:set variant:1:true:true:false","featureSettings:function:get featureSettings:0:function:set featureSettings:1:true:true:false","display:function:get display:0:function:set display:1:true:true:false","source:function:get source:0:undefined:undefined:undefined:true:true:false","status:function:get status:0:undefined:undefined:undefined:true:true:false","loaded:function:get loaded:0:undefined:undefined:undefined:true:true:false"],"ownSlots":[]}"#
+ r#"{"values":"Changed|url(demo.woff)|italic|700|condensed|small-caps|\"kern\"|swap|unloaded|function","fake":"TypeError|TypeError|TypeError|TypeError|Promise","descriptors":["family:function:get family:0:function:set family:1:true:true:false","style:function:get style:0:function:set style:1:true:true:false","weight:function:get weight:0:function:set weight:1:true:true:false","stretch:function:get stretch:0:function:set stretch:1:true:true:false","variant:function:get variant:0:function:set variant:1:true:true:false","featureSettings:function:get featureSettings:0:function:set featureSettings:1:true:true:false","display:function:get display:0:function:set display:1:true:true:false","source:function:get source:0:undefined:undefined:undefined:true:true:false","status:function:get status:0:undefined:undefined:undefined:true:true:false","loaded:function:get loaded:0:undefined:undefined:undefined:true:true:false"],"ownSlots":[]}"#
);
assert_eq!(vm.eval("fakeLoadedResult").unwrap(), "rejected:TypeError");
}
@@ -196,12 +196,20 @@ fn font_face_variation_settings_use_stylo_descriptor_serialization() {
#[test]
fn font_face_set_load_event_copies_and_freezes_fontfaces() {
let mut vm = new_storage_test_vm("https://font-face-set-load-event.test/");
+ vm.eval(&format!(
+ "globalThis.fixtureFontSource = {:?}",
+ format!(
+ "url({:?})",
+ crate::script_vm::tests::browser_api::fonts::fixture_font_url()
+ )
+ ))
+ .unwrap();
let result = vm
.eval(
r#"
(() => {
- const face = new FontFace('Demo', 'url(demo.woff)');
+ const face = new FontFace('Demo', fixtureFontSource);
const source = [face];
const empty = new FontFaceSetLoadEvent('loading');
const configured = new FontFaceSetLoadEvent('loadingdone', {
@@ -458,12 +466,20 @@ fn font_face_set_listener_uses_callback_realm_and_exact_window_lifetime() {
#[test]
fn font_face_load_updates_owner_sets_once_and_unlinks_removed_faces() {
let mut vm = new_storage_test_vm("https://font-face-owner-sets.test/");
+ vm.eval(&format!(
+ "globalThis.fixtureFontSource = {:?}",
+ format!(
+ "url({:?})",
+ crate::script_vm::tests::browser_api::fonts::fixture_font_url()
+ )
+ ))
+ .unwrap();
let result = vm
.eval(
r#"
(() => {
- const face = new FontFace('Demo', 'url(demo.woff)');
+ const face = new FontFace('Demo', fixtureFontSource);
const documentFonts = document.fonts;
const secondary = document.implementation.createHTMLDocument('').fonts;
documentFonts.add(face);
@@ -497,7 +513,7 @@ fn font_face_load_updates_owner_sets_once_and_unlinks_removed_faces() {
const eventCountAfterFirstLoad = events.length;
const secondLoad = face.load();
- const removed = new FontFace('Removed', 'url(removed.woff)');
+ const removed = new FontFace('Removed', 'local("Missing Removed Font 1337")');
documentFonts.add(removed);
const removedDeleted = documentFonts.delete(removed);
const documentReadyBeforeRemovedLoad = documentFonts.ready;
@@ -505,7 +521,7 @@ fn font_face_load_updates_owner_sets_once_and_unlinks_removed_faces() {
removed.load();
const clearedSet = document.implementation.createHTMLDocument('').fonts;
- const cleared = new FontFace('Cleared', 'url(cleared.woff)');
+ const cleared = new FontFace('Cleared', 'local("Missing Cleared Font 1337")');
clearedSet.add(cleared);
const clearedReadyBeforeLoad = clearedSet.ready;
clearedSet.clear();
@@ -541,12 +557,20 @@ fn font_face_load_updates_owner_sets_once_and_unlinks_removed_faces() {
assert_eq!(
result,
- r#"{"loads":[true,true],"ready":[true,true,true,true],"status":["loaded","loaded"],"events":["document:loading:true:true:true:0:true:true","document:loadingdone:true:true:true:1:true:true","secondary:loading:true:true:true:0:true:true","secondary:loadingdone:true:true:true:1:true:true"],"repeated":true,"removed":[true,true,true],"cleared":[true,true,true]}"#
+ r#"{"loads":[true,true],"ready":[true,true,true,true],"status":["loaded","loaded"],"events":["document:loading:true:true:true:0:true:true","secondary:loading:true:true:true:0:true:true","document:loadingdone:true:true:true:1:true:true","secondary:loadingdone:true:true:true:1:true:true"],"repeated":true,"removed":[true,true,true],"cleared":[true,true,true]}"#
);
}
#[test]
fn stylesheet_font_face_load_updates_document_font_set() {
let mut vm = new_storage_test_vm("https://stylesheet-font-face-owner.test/");
+ vm.eval(&format!(
+ "globalThis.fixtureFontSource = {:?}",
+ format!(
+ "url({:?})",
+ crate::script_vm::tests::browser_api::fonts::fixture_font_url()
+ )
+ ))
+ .unwrap();
let result = vm
.eval(
@@ -565,7 +589,7 @@ fn stylesheet_font_face_load_updates_document_font_set() {
});
}
const style = document.createElement('style');
- style.textContent = '@font-face { font-family: "StylesheetOwner"; src: url(owner.woff); }';
+ style.textContent = `@font-face { font-family: "StylesheetOwner"; src: ${fixtureFontSource}; }`;
(document.head || document.documentElement || document).appendChild(style);
face = [...document.fonts].find(face => face.family === 'StylesheetOwner');
const readyBefore = document.fonts.ready;
@@ -801,7 +825,7 @@ fn font_face_binary_source_union_rejects_invalid_font_data() {
.expect("invalid binary FontFace rejection should settle");
assert_eq!(
result,
- r#"{"source":"","status":"error","samePromise":true,"readyChanged":true,"setStatus":"loaded","events":["loading:0:true","loadingerror:1:true"],"rejection":"SyntaxError"}"#
+ r#"{"source":"","status":"error","samePromise":true,"readyChanged":false,"setStatus":"loaded","events":[],"rejection":"SyntaxError"}"#
);
}
#[test]
@@ -1418,6 +1442,6 @@ fn font_face_rejects_malformed_string_and_magic_prefixed_payloads() {
.expect("malformed FontFace payload promises should settle");
assert_eq!(
result,
- r#"{"initial":["error","error","error"],"settled":["SyntaxError","NetworkError","SyntaxError"]}"#
+ r#"{"initial":["error","unloaded","error"],"settled":["SyntaxError","NetworkError","SyntaxError"]}"#
);
}
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
index e3898e136..ae5fdfaf6 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
@@ -24,6 +24,7 @@ mod event_handlers;
mod event_listener_options;
mod events_selection_storage;
mod fontface_descriptors;
+mod fonts;
mod gamepad;
mod history_worlds;
mod ice_candidate;
diff --git a/moli-renderer-v8/src/script_vm/tests/child_document_web_fonts.rs b/moli-renderer-v8/src/script_vm/tests/child_document_web_fonts.rs
index 1e58fc904..9bf2d019a 100644
--- a/moli-renderer-v8/src/script_vm/tests/child_document_web_fonts.rs
+++ b/moli-renderer-v8/src/script_vm/tests/child_document_web_fonts.rs
@@ -142,20 +142,23 @@ async fn child_document_fonts_ready_waits_for_its_own_resource() {
vm.eval(&format!(r#"
globalThis.child=frame.contentWindow;
child.document.open();
- child.document.write('<!doctype html><style>@font-face{{font-family:ChildReady;src:url({font_url})}}</style><span id=target style="display:inline-block;font:20px ChildReady,serif">iiii</span>');
+ child.document.write('<!doctype html><style>@font-face{{font-family:ChildReady;src:url(data:font/woff2;base64,YmFk),url({font_url})}}</style><span id=target style="display:inline-block;font:20px ChildReady,serif">iiii</span>');
child.document.close();
globalThis.childTarget=child.document.getElementById('target');
globalThis.rootReady=false;globalThis.childReady=false;
document.fonts.ready.then(fonts=>rootReady=fonts===document.fonts);
globalThis.childPromise=child.document.fonts.ready;
childPromise.then(fonts=>childReady=fonts===child.document.fonts);
+ globalThis.childFace=[...child.document.fonts][0];
+ globalThis.childFaceLoaded=false;
+ childFace.loaded.then(face=>childFaceLoaded=face===childFace);
'installed'
"#)).unwrap();
tokio::time::timeout(std::time::Duration::from_secs(2), request_rx)
.await
.unwrap()
.unwrap();
- assert_eq!(vm.eval("JSON.stringify([rootReady,childReady,document.fonts.status,child.document.fonts.status,childPromise===child.document.fonts.ready])").unwrap(), r#"[true,false,"loaded","loading",true]"#);
+ assert_eq!(vm.eval("JSON.stringify([rootReady,childReady,document.fonts.status,child.document.fonts.status,childPromise===child.document.fonts.ready,childFace.status,childFaceLoaded])").unwrap(), r#"[true,false,"loaded","loading",true,"loading",false]"#);
refresh_child_geometry_without_paint(&vm);
let fallback = vm.eval("String(childTarget.offsetWidth)").unwrap();
assert_ne!(fallback, "48");
@@ -176,7 +179,7 @@ async fn child_document_fonts_ready_waits_for_its_own_resource() {
.unwrap();
vm.perform_owner_lane_task_microtask_checkpoints().unwrap();
refresh_child_geometry_without_paint(&vm);
- assert_eq!(vm.eval("JSON.stringify([rootReady,childReady,child.document.fonts.status,childTarget.offsetWidth])").unwrap(), r#"[true,true,"loaded",48]"#);
+ assert_eq!(vm.eval("JSON.stringify([rootReady,childReady,child.document.fonts.status,childTarget.offsetWidth,childFace.status,childFaceLoaded])").unwrap(), r#"[true,true,"loaded",48,"loaded",true]"#);
assert_eq!(vm.eval("String(parentTarget.offsetWidth)").unwrap(), parent);
assert_eq!(vm.document_web_font_counts_for_test(), (0, 0, 0));
assert_eq!(
diff --git a/moli-renderer-v8/src/script_vm/web_fonts.rs b/moli-renderer-v8/src/script_vm/web_fonts.rs
index 065dd73f2..a6b65b210 100644
--- a/moli-renderer-v8/src/script_vm/web_fonts.rs
+++ b/moli-renderer-v8/src/script_vm/web_fonts.rs
@@ -1,39 +1,37 @@
-use std::collections::{BTreeMap, BTreeSet};
-
-use moli_layout::{
- DocumentLayoutServices, WebFontFace, WebFontRegistrationError, WebFontRegistrationOutcome,
+use std::{
+ cell::RefCell,
+ collections::{BTreeMap, BTreeSet},
+ rc::{Rc, Weak},
};
-use url::Url;
-use crate::css_resource_urls::{CompletedStylesheetWebFont, StylesheetLoadBlockingResource};
+use moli_layout::{DocumentLayoutServices, WebFontRegistrationError, WebFontRegistrationOutcome};
-#[derive(Clone, Copy, Debug, Eq, PartialEq)]
-enum WebFontRequestStatus {
- Pending,
- Ready,
- Failed,
-}
+use crate::{
+ css_resource_urls::{
+ CompletedStylesheetWebFont, StylesheetLoadBlockingResource, StylesheetWebFont,
+ },
+ font_loading::{FontFaceLoad, FontFaceResource},
+};
#[derive(Clone, Debug)]
struct WebFontSlot {
- request_url: Url,
- face: WebFontFace,
- request_id: u64,
- status: WebFontRequestStatus,
+ load: FontFaceLoad,
}
-/// Resource state for one Document's downloadable fonts.
-///
-/// A request id is an identity for one concrete fetch, not a generation or a
-/// layout consistency fence. It prevents an old response from committing after
-/// CSSOM replaced or removed the declaration occupying its content-addressed
-/// slot. A fresh layout refresh reads only ready registrations; cached geometry
-/// reads do not consult or mutate this sidecar.
+/// Document membership and exact request identities, not a second font load
+/// state machine. CSS requests and JS wrappers share FontFaceResource.
#[derive(Default)]
pub(crate) struct DocumentWebFontState {
next_request_id: u64,
slots: BTreeMap<String, WebFontSlot>,
resource_generation: Option<crate::style_engine::StylesheetResourceGeneration>,
+ // Observing a CSS rule is not the same as activating it for layout. Weak
+ // entries let a detached rule keep its FontFace state while JS holds it,
+ // without retaining every stylesheet ever seen by the document.
+ loads: BTreeMap<String, Weak<RefCell<FontFaceResource>>>,
+ // Removing a CSS declaration revokes registration, not promises held by JS.
+ // Keep its in-flight resource until the owner-validated response settles it.
+ pending: BTreeMap<u64, FontFaceLoad>,
}
#[derive(Debug)]
@@ -41,6 +39,7 @@ pub(crate) enum DocumentWebFontCompletion {
Registered(WebFontRegistrationOutcome),
Invalid(WebFontRegistrationError),
NetworkFailed,
+ Retry(Box<StylesheetLoadBlockingResource>),
Stale,
}
@@ -66,12 +65,24 @@ impl DocumentWebFontState {
pub(crate) fn has_pending_requests(&self) -> bool {
self.slots
.values()
- .any(|slot| slot.status == WebFontRequestStatus::Pending)
+ .any(|slot| slot.load.borrow().status() == crate::font_loading::FontFaceStatus::Loading)
+ }
+
+ pub(crate) fn observe(&mut self, resource: &StylesheetWebFont) -> FontFaceLoad {
+ if let Some(load) = self.loads.get(resource.slot()).and_then(Weak::upgrade) {
+ return load;
+ }
+ let load = FontFaceResource::new(
+ resource.slot().to_owned(),
+ resource.face().clone(),
+ resource.sources().to_vec(),
+ true,
+ );
+ self.loads
+ .insert(resource.slot().to_owned(), Rc::downgrade(&load));
+ load
}
- /// Removes registrations whose declarations are no longer in the current
- /// Stylo source set. Pending network work may still finish, but its exact
- /// request identity will no longer be accepted by [`Self::complete`].
pub(crate) fn retain_active_slots<'a>(
&mut self,
resources: impl IntoIterator<Item = &'a StylesheetLoadBlockingResource>,
@@ -82,20 +93,29 @@ impl DocumentWebFontState {
.filter_map(StylesheetLoadBlockingResource::web_font)
.map(|font| font.slot().to_owned())
.collect::<BTreeSet<_>>();
- let removed = self
- .slots
- .keys()
- .filter(|slot| !active.contains(*slot))
- .cloned()
- .collect::<Vec<_>>();
- for slot in removed {
- self.slots.remove(&slot);
- services.remove_web_font(&slot);
- }
+ self.slots.retain(|slot, entry| {
+ if active.contains(slot) {
+ return true;
+ }
+ entry.load.borrow().unregister(services);
+ false
+ });
+ self.loads.retain(|_, load| load.strong_count() != 0);
+ }
+
+ fn bind_request(
+ &mut self,
+ resource: StylesheetLoadBlockingResource,
+ load: FontFaceLoad,
+ ) -> StylesheetLoadBlockingResource {
+ self.next_request_id = self
+ .next_request_id
+ .checked_add(1)
+ .expect("document web-font request identity space exhausted");
+ self.pending.insert(self.next_request_id, load);
+ resource.bind_web_font_request(self.next_request_id)
}
- /// Binds a new request identity, or suppresses a duplicate request for a
- /// declaration that is already pending, ready, or terminally failed.
pub(crate) fn admit(
&mut self,
resource: StylesheetLoadBlockingResource,
@@ -104,29 +124,35 @@ impl DocumentWebFontState {
let Some(font) = resource.web_font() else {
return Some(resource);
};
- let slot = font.slot().to_owned();
- if self.slots.get(&slot).is_some_and(|current| {
- current.request_url == *resource.request_url() && current.face == *font.face()
- }) {
+ if let Some(id) = font.request_id() {
+ // A native source fallback already has its next exact request.
+ return self
+ .pending
+ .get(&id)
+ .is_some_and(|load| load.borrow().slot() == font.slot())
+ .then_some(resource);
+ }
+ let load = self.observe(font);
+ self.slots
+ .insert(font.slot().to_owned(), WebFontSlot { load: load.clone() });
+ if !load.borrow_mut().begin() {
+ // Reactivating a previously loaded CSS declaration reuses its data;
+ // it must restore registration without starting a second request.
+ if let Err(error) = load.borrow().register(services) {
+ tracing::warn!(%error, "failed to reactivate stylesheet font");
+ }
return None;
}
-
- self.next_request_id = self
- .next_request_id
- .checked_add(1)
- .expect("document web-font request identity space exhausted");
- let request_id = self.next_request_id;
- services.remove_web_font(&slot);
- self.slots.insert(
- slot,
- WebFontSlot {
- request_url: resource.request_url().clone(),
- face: font.face().clone(),
- request_id,
- status: WebFontRequestStatus::Pending,
- },
- );
- Some(resource.bind_web_font_request(request_id))
+ let next = load.borrow_mut().next_url(services);
+ if let Some(url) = next {
+ let url = url::Url::parse(&url).expect("CSS font sources retain resolved URLs");
+ Some(self.bind_request(resource.with_request_url(url), load))
+ } else {
+ if let Err(error) = load.borrow().register(services) {
+ tracing::warn!(%error, "failed to register local stylesheet font");
+ }
+ None
+ }
}
pub(crate) fn complete(
@@ -135,28 +161,40 @@ impl DocumentWebFontState {
services: &mut DocumentLayoutServices,
) -> DocumentWebFontCompletion {
let (request, bytes) = terminal.into_parts();
- let Some(request_id) = request.request_id() else {
+ let Some(id) = request.request_id() else {
return DocumentWebFontCompletion::Stale;
};
- let Some(slot) = self.slots.get_mut(request.slot()) else {
+ if self
+ .pending
+ .get(&id)
+ .is_none_or(|load| load.borrow().slot() != request.slot())
+ {
return DocumentWebFontCompletion::Stale;
- };
- if slot.request_id != request_id || slot.face != *request.face() {
+ }
+ let load = self
+ .pending
+ .remove(&id)
+ .expect("validated exact font request");
+ let error = load.borrow_mut().accept_response(bytes.as_deref()).err();
+ let next = load.borrow_mut().next_url(services);
+ if let Some(url) = next {
+ let url = url::Url::parse(&url).expect("CSS font fallback retains its parser URL");
+ let resource = StylesheetLoadBlockingResource::font(url, request);
+ return DocumentWebFontCompletion::Retry(Box::new(self.bind_request(resource, load)));
+ }
+ let active = self
+ .slots
+ .get(request.slot())
+ .is_some_and(|slot| std::rc::Rc::ptr_eq(&slot.load, &load));
+ if !active {
return DocumentWebFontCompletion::Stale;
}
- let Some(bytes) = bytes else {
- slot.status = WebFontRequestStatus::Failed;
- return DocumentWebFontCompletion::NetworkFailed;
- };
- match services.register_web_font(request.registration(bytes)) {
- Ok(outcome) => {
- slot.status = WebFontRequestStatus::Ready;
- DocumentWebFontCompletion::Registered(outcome)
- }
- Err(error) => {
- slot.status = WebFontRequestStatus::Failed;
- DocumentWebFontCompletion::Invalid(error)
- }
+ match load.borrow().register(services) {
+ Ok(Some(outcome)) => DocumentWebFontCompletion::Registered(outcome),
+ Err(error) => DocumentWebFontCompletion::Invalid(error),
+ Ok(None) => error
+ .map(DocumentWebFontCompletion::Invalid)
+ .unwrap_or(DocumentWebFontCompletion::NetworkFailed),
}
}
@@ -169,7 +207,9 @@ impl DocumentWebFontState {
pub(crate) fn ready_slot_count(&self) -> usize {
self.slots
.values()
- .filter(|slot| slot.status == WebFontRequestStatus::Ready)
+ .filter(|slot| {
+ slot.load.borrow().status() == crate::font_loading::FontFaceStatus::Loaded
+ })
.count()
}
}
@@ -179,6 +219,7 @@ mod tests {
use super::*;
use crate::css_resource_urls::stylesheet_load_blocking_font_resources;
use crate::protocol_types::OptionalResourceFetchMask;
+ use url::Url;
const TEST_FONT: &[u8] = include_bytes!("../../../moli-layout/tests/fixtures/moli-ahem.woff2");
@@ -259,4 +300,92 @@ mod tests {
DocumentWebFontCompletion::Stale
));
}
+
+ #[test]
+ fn failed_sources_advance_one_native_load_and_reject_duplicate_completions() {
+ let mut state = DocumentWebFontState::default();
+ let mut services = DocumentLayoutServices::new();
+ let resource =
+ resource("@font-face{font-family:Demo;src:url(first.woff2),url(second.woff2)}");
+ let load = state.observe(resource.web_font().unwrap());
+ let first = state.admit(resource.clone(), &mut services).unwrap();
+ assert!(state.admit(resource, &mut services).is_none());
+ assert_eq!(
+ load.borrow().status(),
+ crate::font_loading::FontFaceStatus::Loading
+ );
+ let duplicate = first.clone();
+ let DocumentWebFontCompletion::Retry(second) =
+ state.complete(terminal(first, Some(b"bad".to_vec())), &mut services)
+ else {
+ panic!("invalid first source should advance to its fallback");
+ };
+ assert_eq!(
+ second.request_url().as_str(),
+ "https://example.test/second.woff2"
+ );
+ assert!(matches!(
+ state.complete(terminal(duplicate, Some(TEST_FONT.to_vec())), &mut services),
+ DocumentWebFontCompletion::Stale
+ ));
+ assert_eq!(
+ load.borrow().status(),
+ crate::font_loading::FontFaceStatus::Loading
+ );
+ assert!(matches!(
+ state.complete(terminal(*second, Some(TEST_FONT.to_vec())), &mut services),
+ DocumentWebFontCompletion::Registered(_)
+ ));
+ assert_eq!(
+ load.borrow().status(),
+ crate::font_loading::FontFaceStatus::Loaded
+ );
+ assert_eq!(services.web_font_count(), 1);
+ }
+
+ #[test]
+ fn removed_pending_css_font_still_settles_native_observers_without_registering() {
+ let mut state = DocumentWebFontState::default();
+ let mut services = DocumentLayoutServices::new();
+ let resource = resource("@font-face{font-family:Demo;src:url(font.woff2)}");
+ let observer = state.observe(resource.web_font().unwrap());
+ let request = state.admit(resource, &mut services).unwrap();
+ state.retain_active_slots([], &mut services);
+ assert!(matches!(
+ state.complete(terminal(request, Some(TEST_FONT.to_vec())), &mut services),
+ DocumentWebFontCompletion::Stale
+ ));
+ assert_eq!(
+ observer.borrow().status(),
+ crate::font_loading::FontFaceStatus::Loaded
+ );
+ assert_eq!(services.web_font_count(), 0);
+ }
+
+ #[test]
+ fn observing_is_not_admission_and_reactivation_reuses_loaded_data() {
+ let mut state = DocumentWebFontState::default();
+ let mut services = DocumentLayoutServices::new();
+ let resource = resource("@font-face{font-family:Demo;src:url(font.woff2)}");
+ let observer = state.observe(resource.web_font().unwrap());
+ assert_eq!(
+ state.slot_count(),
+ 0,
+ "a CSSOM observer does not activate the rule"
+ );
+ let request = state.admit(resource.clone(), &mut services).unwrap();
+ state.complete(terminal(request, Some(TEST_FONT.to_vec())), &mut services);
+ state.retain_active_slots([], &mut services);
+ assert_eq!(services.web_font_count(), 0);
+ assert!(Rc::ptr_eq(
+ &observer,
+ &state.observe(resource.web_font().unwrap())
+ ));
+ assert!(
+ state.admit(resource, &mut services).is_none(),
+ "reactivation needs no request"
+ );
+ assert_eq!(state.ready_slot_count(), 1);
+ assert_eq!(services.web_font_count(), 1);
+ }
}
diff --git a/moli-renderer-v8/src/style_engine/stylesheet.rs b/moli-renderer-v8/src/style_engine/stylesheet.rs
index f7c6f7445..58d6a54fa 100644
--- a/moli-renderer-v8/src/style_engine/stylesheet.rs
+++ b/moli-renderer-v8/src/style_engine/stylesheet.rs
@@ -107,9 +107,9 @@ pub(super) fn install_active_stylesheet(
.into_iter()
.filter_map(|rule| {
let resource =
- crate::css_resource_urls::stylesheet_web_font_resource_with_resolved_url(
+ crate::css_resource_urls::stylesheet_web_font_resource_with_resolved_sources(
&rule.rule_fingerprint,
- rule.request_url?,
+ rule.sources,
)?;
Some(ActiveWebFontResource::new(rule.rule, resource))
})
@@ -161,6 +161,7 @@ pub(crate) struct StylesheetFontFaceRuleProjection {
pub(crate) rule_identity: u64,
pub(crate) rule_fingerprint: String,
pub(crate) descriptor: moli_css_parse::CssFontFace,
+ pub(crate) resource: Option<crate::css_resource_urls::StylesheetLoadBlockingResource>,
}
#[derive(Clone, Debug, Default)]
@@ -174,10 +175,10 @@ pub(crate) struct NativeStylesheetFontFaceRuleProjection {
pub(crate) rule: ServoArc<Locked<FontFaceRule>>,
pub(crate) rule_fingerprint: String,
pub(crate) descriptor: moli_css_parse::CssFontFace,
- /// First supported network source, resolved by Stylo in the exact parser
+ /// Supported sources, resolved by Stylo in the exact parser
/// context that owns this rule. Imported rules therefore retain the base
/// URL of their imported stylesheet rather than inheriting the root base.
- pub(crate) request_url: Option<url::Url>,
+ pub(crate) sources: Vec<moli_css_parse::CssFontSource>,
}
#[derive(Clone, Debug, Default)]
@@ -276,7 +277,7 @@ fn collect_font_face_rule_projections(
family: family.name.to_string(),
source: serialized_source,
},
- request_url: preferred_native_font_source_url(source),
+ sources: native_font_sources(source),
});
}
continue;
@@ -285,17 +286,25 @@ fn collect_font_face_rule_projections(
}
}
-fn preferred_native_font_source_url(source_list: &SourceList) -> Option<url::Url> {
- source_list.0.iter().find_map(|source| {
- let Source::Url(source) = source else {
- return None;
- };
- if !native_font_source_format_is_supported(source.format_hint.as_ref()) {
- return None;
- }
- let url = source.url.url()?;
- matches!(url.scheme(), "http" | "https" | "data" | "blob").then(|| (**url).clone())
- })
+fn native_font_sources(source_list: &SourceList) -> Vec<moli_css_parse::CssFontSource> {
+ source_list
+ .0
+ .iter()
+ .filter_map(|source| {
+ if let Source::Local(name) = source {
+ return Some(moli_css_parse::CssFontSource::Local(name.name.to_string()));
+ }
+ let Source::Url(source) = source else {
+ return None;
+ };
+ if !native_font_source_format_is_supported(source.format_hint.as_ref()) {
+ return None;
+ }
+ let url = source.url.url()?;
+ matches!(url.scheme(), "http" | "https" | "data" | "blob")
+ .then(|| moli_css_parse::CssFontSource::Url(url.to_string()))
+ })
+ .collect()
}
fn native_font_source_format_is_supported(format: Option<&FontFaceSourceFormat>) -> bool {
diff --git a/moli-renderer-v8/src/stylesheet_runtime/settlement.rs b/moli-renderer-v8/src/stylesheet_runtime/settlement.rs
index 09490cbee..aeb3fe12e 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/settlement.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/settlement.rs
@@ -330,7 +330,8 @@ impl DocumentRuntime {
_ => admitted.push((binding, resource, None)),
}
}
- for (binding, resource, css_image) in admitted {
+ let mut admitted = std::collections::VecDeque::from(admitted);
+ while let Some((binding, resource, css_image)) = admitted.pop_front() {
let request_url = resource.request_url().clone();
let kind = resource.kind();
let failed_css_image = css_image.clone();
@@ -349,7 +350,14 @@ impl DocumentRuntime {
Ok(crate::network_host::StylesheetSubresourceFetchStart::WebFontSettled(
web_font,
)) => {
- Self::complete_document_web_font(host, binding, web_font);
+ if let Some(resource) =
+ Self::complete_document_web_font(host, binding, web_font)
+ && let Some(document) = host.stylesheet_web_font_document(binding)
+ && let Some(binding) = host
+ .accept_current_stylesheet_subresource_load_delay_for_document(document)
+ {
+ admitted.push_back((binding, resource, None));
+ }
}
Ok(
crate::network_host::StylesheetSubresourceFetchStart::Pending
@@ -360,8 +368,14 @@ impl DocumentRuntime {
let _ = host.fail_stylesheet_css_image(identity);
}
let settlement = host.settle_stylesheet_subresource_load_delay(binding);
- if let Some(web_font) = failed_web_font {
- Self::complete_document_web_font(host, binding, web_font);
+ if let Some(web_font) = failed_web_font
+ && let Some(resource) =
+ Self::complete_document_web_font(host, binding, web_font)
+ && let Some(document) = host.stylesheet_web_font_document(binding)
+ && let Some(binding) = host
+ .accept_current_stylesheet_subresource_load_delay_for_document(document)
+ {
+ admitted.push_back((binding, resource, None));
}
tracing::warn!(
url = %request_url,
@@ -374,6 +388,7 @@ impl DocumentRuntime {
}
}
}
+ crate::context_bootstrap::publish_font_face_load_changes(scope);
tracing::debug!(
resource_count,
elapsed_ms = started.elapsed().as_millis(),
@@ -385,10 +400,8 @@ impl DocumentRuntime {
host: &JsContextHost,
binding: crate::frame_owner_model::StylesheetSubresourceLoadDelayBinding,
terminal: crate::css_resource_urls::CompletedStylesheetWebFont,
- ) {
- let Some(document) = host.stylesheet_web_font_document(binding) else {
- return;
- };
+ ) -> Option<crate::css_resource_urls::StylesheetLoadBlockingResource> {
+ let document = host.stylesheet_web_font_document(binding)?;
match host.complete_document_web_font(document, terminal) {
crate::script_vm::web_fonts::DocumentWebFontCompletion::Registered(outcome) => {
tracing::debug!(
@@ -408,6 +421,10 @@ impl DocumentRuntime {
crate::script_vm::web_fonts::DocumentWebFontCompletion::Stale => {
tracing::debug!("discarded superseded document web font response")
}
+ crate::script_vm::web_fonts::DocumentWebFontCompletion::Retry(resource) => {
+ return Some(*resource);
+ }
}
+ None
}
}
diff --git a/moli-renderer-v8/src/types.rs b/moli-renderer-v8/src/types.rs
index fbb76dad1..1c1934976 100644
--- a/moli-renderer-v8/src/types.rs
+++ b/moli-renderer-v8/src/types.rs
@@ -84,6 +84,7 @@ pub(super) enum PendingSubresourceContinuation {
track_handle: crate::document_runtime::DomHandle,
sequence: crate::native_bridge::TextTrackLoadSequenceId,
},
+ FontFace(v8::Global<v8::Object>),
StylesheetSubresource {
binding: crate::frame_owner_model::StylesheetSubresourceLoadDelayBinding,
web_font: Option<crate::css_resource_urls::StylesheetWebFont>,
diff --git a/moli-wpt-compat/fixtures/wpt/ported/css-font-loading/fontface-basic.html b/moli-wpt-compat/fixtures/wpt/ported/css-font-loading/fontface-basic.html
index 9f9b73211..a92a77e4d 100644
--- a/moli-wpt-compat/fixtures/wpt/ported/css-font-loading/fontface-basic.html
+++ b/moli-wpt-compat/fixtures/wpt/ported/css-font-loading/fontface-basic.html
@@ -4,6 +4,8 @@
<script src="/wpt/resources/testharnessreport.js"></script>
<script src="/wpt/resources/moli-wpt-adapter.js"></script>
<script>
+ // Real project-generated font: moli-layout/tests/fixtures/moli-ahem.woff2.
+ const FONT_FIXTURE_SOURCE = "url(data:font/woff2;base64,d09GMgABAAAAAAKMAAoAAAAAEewAAAI9AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAARAqSGIlCATYCJAOBRguBRgAEIAWDDweHZhsaDBEVjE2QrxO4OaB11Uo4KkNFQmQIgNrHOq+V6mgnvY2fvSQ/uF+9N7PdNFuXpclV2mkpdFaAC3aRoEdFB3L8iVa3NRGchB7CA+kvmysBs3ExDyF+2La9iSrRM8x/YMEH4+YNnI6ADDhw44HnsPGNf2vg8Vh2oEcLbcza3qYp3gsXSOBToI2cQC+UhHthpAFIuk0EVfwGmbm3vt4jtOf5c3NBuwr0P4kB5kvBCdDgYzQftZAtCfcwRbHKu3S8ycdHAOfu8OUAmLjP+bEQEov+i78AFoAP+AEAxAAAAbQvPfKjw6g3kr+bmM88bAz4CAIItbXF3xu9/n2qfwCnW7usCnIKG0p4i7hd9+SA9QzCt8+eB2LUsMiFeojjkCtwessPXvTy47FKi+3KLnHVsltY375HzLDkOf6NhCkpi4iVsmpyVHYpuS67Fdw/4GE+R/a2N2xwfWXnu79JZ8nsauts62iP3v/+6UJH9FXrZ8WIPds2mEHrVuyYtGLNiW0L8jSL6zWd2nTMNs9acejIxsou80QHe+KtWi8h8LdYBGgJlS666aGXPvoZYJAhhhlhlDHGmbAhTCjjQiptrAMfhFGcpFlelFXdtF0/jNO8rNt+nNf9vB8AQjCCYjhBUjTDcrwgSrKiarphWrbjcb2+/jc6gLBCmFDGhVTaWBf+NANEmFDGhVTaWBf+tABEmFDGhVTaWBf+tAJEmFDGhVTaWBf+tAFEmFDGhVTaWBf+tANEmFDGhVTa2PClCtb3AQAAAA==)";
function assert_throws_name(name, callback, description) {
try {
callback();
@@ -15,7 +17,7 @@ function assert_throws_name(name, callback, description) {
}
test(function () {
- const face = new FontFace("FixtureFace", "url(fixture.woff2)", {
+ const face = new FontFace("FixtureFace", FONT_FIXTURE_SOURCE, {
style: "italic",
weight: "700",
stretch: "condensed",
@@ -27,14 +29,14 @@ test(function () {
assert_true(face instanceof FontFace);
assert_equals(FontFace.name, "FontFace");
assert_equals(face.family, "FixtureFace");
- assert_equals(face.source, "url(fixture.woff2)");
+ assert_equals(face.source, FONT_FIXTURE_SOURCE);
assert_equals(face.style, "italic");
assert_equals(face.weight, "700");
assert_equals(face.stretch, "condensed");
assert_equals(face.variant, "small-caps");
assert_equals(face.featureSettings, '"liga" 0');
assert_equals(face.display, "swap");
- assert_equals(face.status, "loaded");
+ assert_equals(face.status, "unloaded");
assert_true(face.loaded instanceof Promise);
assert_true(face.load() instanceof Promise);
}, "FontFace exposes constructor metadata and descriptors");
@@ -68,10 +70,11 @@ test(function () {
}, "FontFace constructor uses WebIDL scalar argument conversion for string sources");
promise_test(async function () {
- const face = new FontFace("PromiseFace", "url(promise.woff)");
+ const face = new FontFace("PromiseFace", FONT_FIXTURE_SOURCE);
- assert_equals(await face.loaded, face);
assert_equals(await face.load(), face);
+ assert_equals(await face.loaded, face);
+ assert_equals(face.status, "loaded");
}, "FontFace loaded and load promises resolve with the face");
promise_test(async function () {
diff --git a/moli-wpt-compat/fixtures/wpt/ported/idl/fontface-idlharness.html b/moli-wpt-compat/fixtures/wpt/ported/idl/fontface-idlharness.html
index ec40b9625..696f47b30 100644
--- a/moli-wpt-compat/fixtures/wpt/ported/idl/fontface-idlharness.html
+++ b/moli-wpt-compat/fixtures/wpt/ported/idl/fontface-idlharness.html
@@ -6,6 +6,8 @@
<script src="/wpt/resources/WebIDLParser.js"></script>
<script src="/wpt/resources/idlharness.js"></script>
<script>
+ // Real project-generated font: moli-layout/tests/fixtures/moli-ahem.woff2.
+ const FONT_FIXTURE_SOURCE = "url(data:font/woff2;base64,d09GMgABAAAAAAKMAAoAAAAAEewAAAI9AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAARAqSGIlCATYCJAOBRguBRgAEIAWDDweHZhsaDBEVjE2QrxO4OaB11Uo4KkNFQmQIgNrHOq+V6mgnvY2fvSQ/uF+9N7PdNFuXpclV2mkpdFaAC3aRoEdFB3L8iVa3NRGchB7CA+kvmysBs3ExDyF+2La9iSrRM8x/YMEH4+YNnI6ADDhw44HnsPGNf2vg8Vh2oEcLbcza3qYp3gsXSOBToI2cQC+UhHthpAFIuk0EVfwGmbm3vt4jtOf5c3NBuwr0P4kB5kvBCdDgYzQftZAtCfcwRbHKu3S8ycdHAOfu8OUAmLjP+bEQEov+i78AFoAP+AEAxAAAAbQvPfKjw6g3kr+bmM88bAz4CAIItbXF3xu9/n2qfwCnW7usCnIKG0p4i7hd9+SA9QzCt8+eB2LUsMiFeojjkCtwessPXvTy47FKi+3KLnHVsltY375HzLDkOf6NhCkpi4iVsmpyVHYpuS67Fdw/4GE+R/a2N2xwfWXnu79JZ8nsauts62iP3v/+6UJH9FXrZ8WIPds2mEHrVuyYtGLNiW0L8jSL6zWd2nTMNs9acejIxsou80QHe+KtWi8h8LdYBGgJlS666aGXPvoZYJAhhhlhlDHGmbAhTCjjQiptrAMfhFGcpFlelFXdtF0/jNO8rNt+nNf9vB8AQjCCYjhBUjTDcrwgSrKiarphWrbjcb2+/jc6gLBCmFDGhVTaWBf+NANEmFDGhVTaWBf+tABEmFDGhVTaWBf+tAJEmFDGhVTaWBf+tAFEmFDGhVTaWBf+tANEmFDGhVTa2PClCtb3AQAAAA==)";
idl_test([`
enum FontFaceLoadStatus { "unloaded", "loading", "loaded", "error" };
enum FontFaceSetLoadStatus { "loading", "loaded" };
@@ -58,13 +60,13 @@ dictionary FontFaceDescriptors {
idlArray.enable_attribute_descriptor_assertions();
idlArray.enable_object_brand_assertions();
idlArray.add_objects({
- FontFace: ["new FontFace('FixtureFace', 'url(fixture.woff2)')"],
+ FontFace: ["new FontFace('FixtureFace', FONT_FIXTURE_SOURCE)"],
FontFaceSet: ["document.fonts"]
});
});
promise_test(async function () {
- const face = new FontFace("FixtureFace", "url(fixture.woff2)", {
+ const face = new FontFace("FixtureFace", FONT_FIXTURE_SOURCE, {
style: "italic",
weight: "700",
stretch: "condensed",
@@ -86,9 +88,10 @@ promise_test(async function () {
assert_equals(face.loaded, face.loaded);
assert_equals(fonts.ready, fonts.ready);
assert_equals(face.family, "FixtureFace");
- assert_equals(face.source, "url(fixture.woff2)");
- assert_equals(face.status, "loaded");
+ assert_equals(face.source, FONT_FIXTURE_SOURCE);
+ assert_equals(face.status, "unloaded");
assert_equals(await face.load(), face);
+ assert_equals(face.status, "loaded");
assert_equals(await face.loaded, face);
fonts.clear();