Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(fonts): separate declaration identity from shared sources
ldm0bf3c9d109390
diff --git a/moli-layout/src/lib.rs b/moli-layout/src/lib.rsindex ee05ac764..9b7fabf81 100644--- a/moli-layout/src/lib.rs+++ b/moli-layout/src/lib.rs@@ -102,9 +102,9 @@ pub use style::{LayoutPosition, ResolvedLayoutStyle,};pub use text::{- DocumentLayoutServices, FontFaceData, SystemFontPolicy, WebFontFace, WebFontRegistration,- WebFontRegistrationError, WebFontRegistrationOutcome, WebFontStyle, WebFontUnicodeRange,- validate_web_font_bytes,+ DocumentLayoutServices, FontFaceData, SystemFontPolicy, WebFontDeclaration, WebFontFace,+ WebFontRegistration, WebFontRegistrationError, WebFontRegistrationOutcome,+ WebFontRegistrationScope, WebFontStyle, WebFontUnicodeRange, validate_web_font_bytes,};pub use world::{LayoutAnonymousReason, LayoutBox, LayoutBoxId, LayoutBoxKind, LayoutCapabilityDiagnostic,diff --git a/moli-layout/src/text.rs b/moli-layout/src/text.rsindex d7964f6b0..25176efb6 100644--- a/moli-layout/src/text.rs+++ b/moli-layout/src/text.rs@@ -673,7 +673,8 @@ pub struct WebFontRegistration {slot: String,face: WebFontFace,payload: WebFontPayload,- stylesheet: bool,+ source_key: Option<String>,+ scope: WebFontRegistrationScope,}#[derive(Clone, Debug)]@@ -703,7 +704,8 @@ impl WebFontRegistration {slot: slot.into(),face,payload: WebFontPayload::Encoded(bytes),- stylesheet: false,+ source_key: None,+ scope: WebFontRegistrationScope::FontFaceSetManual,}}@@ -714,14 +716,26 @@ impl WebFontRegistration {slot: slot.into(),face,payload: WebFontPayload::Validated(data),- stylesheet: false,+ source_key: None,+ scope: WebFontRegistrationScope::FontFaceSetManual,}}/// Restricts this registration to passes where its stylesheet declaration/// is active. Other native/programmatic registrations remain available.pub fn with_stylesheet_scope(mut self) -> Self {- self.stylesheet = true;+ self.scope = WebFontRegistrationScope::Stylesheet;+ self+ }++ /// Identifies shareable source data, independently of this declaration's slot.+ pub fn with_source_key(mut self, source_key: Option<String>) -> Self {+ self.source_key = source_key;+ self+ }++ pub fn with_scope(mut self, scope: WebFontRegistrationScope) -> Self {+ self.scope = scope;self}@@ -738,6 +752,58 @@ impl WebFontRegistration {}}+/// One declaration in the current native stylesheet snapshot. A new declaration+/// may use cached source data without reusing another face's mutable metadata.+pub struct WebFontDeclaration<'a> {+ pub slot: &'a str,+ pub source_key: &'a str,+ pub face: &'a WebFontFace,+}++/// The current registration relation in one Document, independently of where+/// the FontFace or its shared source was originally created.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum WebFontRegistrationScope {+ Stylesheet,+ FontFaceSetConnected,+ FontFaceSetManual,+}++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+enum FontFaceSetMembership {+ Connected,+ Manual,+}++#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]+struct WebFontMembership {+ stylesheet: bool,+ font_face_set: Option<FontFaceSetMembership>,+}++impl WebFontMembership {+ fn with(mut self, scope: WebFontRegistrationScope) -> Self {+ match scope {+ WebFontRegistrationScope::Stylesheet => self.stylesheet = true,+ WebFontRegistrationScope::FontFaceSetConnected => {+ self.font_face_set = Some(FontFaceSetMembership::Connected);+ }+ WebFontRegistrationScope::FontFaceSetManual => {+ self.font_face_set = Some(FontFaceSetMembership::Manual);+ }+ }+ self+ }++ fn is_empty(self) -> bool {+ !self.stylesheet && self.font_face_set.is_none()+ }++ fn is_stylesheet_only(self) -> bool {+ self.font_face_set != Some(FontFaceSetMembership::Manual)+ }+}+#[derive(Clone, Copy, Debug, Eq, PartialEq)]pub enum WebFontRegistrationOutcome {Added,@@ -761,7 +827,8 @@ pub enum WebFontRegistrationError {struct RegisteredWebFont {face: WebFontFace,sfnt_bytes: Blob<u8>,- stylesheet: bool,+ source_key: Option<String>,+ membership: WebFontMembership,}/// Lazily initialized text resources reused by successive layout demands for@@ -894,7 +961,9 @@ impl DocumentLayoutServices {.get(&face.source_slot).copied().unwrap_or((- !self.web_fonts[&face.source_slot].stylesheet,+ !self.web_fonts[&face.source_slot]+ .membership+ .is_stylesheet_only(),usize::MAX,));}@@ -926,6 +995,11 @@ impl DocumentLayoutServices {return Err(WebFontRegistrationError::EmptySlot);}registration.face.validate()?;+ let membership = self+ .web_fonts+ .get(®istration.slot)+ .map_or(WebFontMembership::default(), |font| font.membership)+ .with(registration.scope);let (sfnt_bytes, validated) = match registration.payload {WebFontPayload::Encoded(bytes) => (decode_web_font_bytes(bytes)?, false),WebFontPayload::Validated(data) => (data.bytes, true),@@ -933,12 +1007,14 @@ impl DocumentLayoutServices {let font = RegisteredWebFont {face: registration.face,sfnt_bytes,- stylesheet: registration.stylesheet,+ source_key: registration.source_key,+ membership,};let outcome = match self.web_fonts.get(®istration.slot) {Some(current)if current.face == font.face- && current.stylesheet == font.stylesheet+ && current.membership == font.membership+ && current.source_key == font.source_key&& current.sfnt_bytes.as_ref() == font.sfnt_bytes.as_ref() =>{WebFontRegistrationOutcome::Unchanged@@ -995,8 +1071,48 @@ impl DocumentLayoutServices {true}+ pub fn remove_stylesheet_web_font(&mut self, slot: &str) -> bool {+ self.remove_web_font_membership(slot, WebFontRegistrationScope::Stylesheet)+ }++ pub fn remove_font_face_set_web_font(&mut self, slot: &str) -> bool {+ self.remove_web_font_membership(slot, WebFontRegistrationScope::FontFaceSetManual)+ }++ fn remove_web_font_membership(&mut self, slot: &str, scope: WebFontRegistrationScope) -> bool {+ let Some(font) = self.web_fonts.get_mut(slot) else {+ return false;+ };+ match scope {+ WebFontRegistrationScope::Stylesheet => {+ if !std::mem::take(&mut font.membership.stylesheet) {+ return false;+ }+ }+ WebFontRegistrationScope::FontFaceSetConnected+ | WebFontRegistrationScope::FontFaceSetManual => {+ if font.membership.font_face_set.take().is_none() {+ return false;+ }+ }+ }+ if font.membership.is_empty() {+ return self.remove_web_font(slot);+ }+ if self.parley.is_some() {+ self.parley = Some(Box::new(build_parley_services(+ self.system_font_policy,+ &self.web_fonts,+ &self.web_font_order,+ )));+ }+ true+ }+pub fn has_stylesheet_web_fonts(&self) -> bool {- self.web_fonts.values().any(|font| font.stylesheet)+ self.web_fonts+ .values()+ .any(|font| font.membership.is_stylesheet_only())}/// Selects loaded CSS fonts for one pass without changing the document's@@ -1010,15 +1126,67 @@ impl DocumentLayoutServices {&mut self,is_active: impl Fn(&str) -> bool,consume: impl FnOnce(&mut Self) -> R,+ ) -> R {+ self.with_font_view(is_active, Vec::new(), self.web_font_order.clone(), consume)+ }++ /// Selects this pass's declaration identities and CSS order. Reinserted+ /// rules can reuse loaded source bytes while keeping independent metadata;+ /// temporary view/media changes do not mutate authoritative registrations.+ pub fn with_stylesheet_font_declarations<'a, R>(+ &mut self,+ declarations: impl IntoIterator<Item = WebFontDeclaration<'a>>,+ consume: impl FnOnce(&mut Self) -> R,+ ) -> R {+ let mut active = std::collections::BTreeSet::new();+ let mut additions = Vec::new();+ let mut order = self.web_font_order.clone();+ order.retain(|_, (manual, _)| *manual);+ for (index, declaration) in declarations.into_iter().enumerate() {+ active.insert(declaration.slot);+ order.insert(declaration.slot.to_owned(), (false, index));+ if self.web_fonts.contains_key(declaration.slot) {+ continue;+ }+ let Some(cached) = self.web_fonts.values().find(|font| {+ font.membership.stylesheet+ && font.source_key.as_deref() == Some(declaration.source_key)+ }) else {+ continue;+ };+ // Only typed, validated descriptors may expose a cached payload.+ if declaration.face.validate().is_err() {+ continue;+ }+ additions.push((+ declaration.slot.to_owned(),+ RegisteredWebFont {+ face: declaration.face.clone(),+ sfnt_bytes: cached.sfnt_bytes.clone(),+ source_key: cached.source_key.clone(),+ membership: WebFontMembership::default()+ .with(WebFontRegistrationScope::Stylesheet),+ },+ ));+ }+ self.with_font_view(|slot| active.contains(slot), additions, order, consume)+ }++ fn with_font_view<R>(+ &mut self,+ is_active: impl Fn(&str) -> bool,+ additions: Vec<(String, RegisteredWebFont)>,+ order: BTreeMap<String, (bool, usize)>,+ consume: impl FnOnce(&mut Self) -> R,) -> R {let excluded = self.web_fonts.iter().filter_map(|(slot, font)| {- (font.stylesheet && !is_active(slot)).then_some(slot.as_str())+ (font.membership.is_stylesheet_only() && !is_active(slot)).then_some(slot.as_str())}).collect::<Vec<_>>();- if excluded.is_empty() {+ if excluded.is_empty() && additions.is_empty() && order == self.web_font_order {return consume(self);}// BTreeMap iteration keeps the excluded slots sorted. Font bytes are@@ -1028,13 +1196,14 @@ impl DocumentLayoutServices {.iter().filter(|(slot, _)| excluded.binary_search(&slot.as_str()).is_err()).map(|(slot, font)| (slot.clone(), font.clone()))+ .chain(additions).collect();let mut temporary = Self {parley: None,local_font_sources: None,system_font_policy: self.system_font_policy,web_fonts,- web_font_order: self.web_font_order.clone(),+ web_font_order: order,has_font_face_set_order: self.has_font_face_set_order,text_layout_passes: 0,};@@ -1078,7 +1247,7 @@ fn ordered_web_fonts<'a>(order.get(*slot).copied()- .unwrap_or((!font.stylesheet, usize::MAX))+ .unwrap_or((!font.membership.is_stylesheet_only(), usize::MAX))});fonts}@@ -1147,7 +1316,7 @@ impl ParleyDocumentServices {let source_priority = web_font_order.get(slot).copied()- .unwrap_or((!font.stylesheet, usize::MAX));+ .unwrap_or((!font.membership.is_stylesheet_only(), usize::MAX));let family = self.web_font_families.entry(font_family_name_key(font.face.family_name()))diff --git a/moli-layout/src/text/tests/registration.rs b/moli-layout/src/text/tests/registration.rsindex 1d3b8ff16..c5bed3f8c 100644--- a/moli-layout/src/text/tests/registration.rs+++ b/moli-layout/src/text/tests/registration.rs@@ -117,6 +117,51 @@ fn validated_font_data_keeps_its_blob_through_registration_and_layout() {assert_eq!(font.fonts()[0].load(None).unwrap().id(), blob_id);}+#[test]+fn stylesheet_and_font_face_set_memberships_are_retired_independently() {+ for remove_stylesheet_first in [false, true] {+ let mut services =+ DocumentLayoutServices::with_system_font_policy(SystemFontPolicy::Disabled);+ let data = FontFaceData::from_bytes(TEST_TTF).unwrap();+ services+ .register_web_font(+ WebFontRegistration::from_font_data(+ "face",+ WebFontFace::new("Scoped"),+ data.clone(),+ )+ .with_stylesheet_scope(),+ )+ .unwrap();+ services+ .register_web_font(+ WebFontRegistration::from_font_data("face", WebFontFace::new("Scoped"), data)+ .with_scope(WebFontRegistrationScope::FontFaceSetManual),+ )+ .unwrap();+ services.with_active_stylesheet_fonts(+ |_| false,+ |active| assert_eq!(active.web_font_count(), 1),+ );+ if remove_stylesheet_first {+ assert!(services.remove_stylesheet_web_font("face"));+ assert_eq!(services.web_font_count(), 1);+ assert!(!services.has_stylesheet_web_fonts());+ assert!(services.remove_font_face_set_web_font("face"));+ } else {+ assert!(services.remove_font_face_set_web_font("face"));+ assert_eq!(services.web_font_count(), 1);+ assert!(services.has_stylesheet_web_fonts());+ services.with_active_stylesheet_fonts(+ |_| false,+ |active| assert_eq!(active.web_font_count(), 0),+ );+ assert!(services.remove_stylesheet_web_font("face"));+ }+ assert_eq!(services.web_font_count(), 0);+ }+}+fn source_id(services: &mut ParleyDocumentServices, family: &str) -> parley::fontique::SourceId {let family = resolved_registered_family_name(services, family).unwrap();services@@ -371,25 +416,26 @@ fn replacement_and_removal_preserve_other_same_capability_slots() {}#[test]-fn unchanged_bytes_still_replace_changed_stylesheet_scope() {+fn unchanged_bytes_merge_and_retire_stylesheet_scope_independently() {let mut services = DocumentLayoutServices::with_system_font_policy(SystemFontPolicy::Disabled);services.register_web_font(registration("same", "Same", TEST_TTF)).unwrap();- for stylesheet in [true, false] {- let mut registration = registration("same", "Same", TEST_TTF);- if stylesheet {- registration = registration.with_stylesheet_scope();- }- assert_eq!(- services.register_web_font(registration),- Ok(WebFontRegistrationOutcome::Replaced)- );- services.with_active_stylesheet_fonts(- |_| false,- |selected| assert_eq!(selected.web_font_count(), usize::from(!stylesheet)),- );- }+ assert_eq!(+ services.register_web_font(registration("same", "Same", TEST_TTF).with_stylesheet_scope()),+ Ok(WebFontRegistrationOutcome::Replaced)+ );+ services.with_active_stylesheet_fonts(+ |_| false,+ |selected| assert_eq!(selected.web_font_count(), 1),+ );+ assert!(services.remove_font_face_set_web_font("same"));+ services.with_active_stylesheet_fonts(+ |_| false,+ |selected| assert_eq!(selected.web_font_count(), 0),+ );+ assert!(services.remove_stylesheet_web_font("same"));+ assert_eq!(services.web_font_count(), 0);}#[test]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.rsindex 17b532725..c754a7e6c 100644--- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/loading.rs+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/loading.rs@@ -165,7 +165,6 @@ pub(super) fn new_resource<'s>(format!("js-font-face-{id}"),descriptor(scope, face),sources,- false,)}@@ -371,6 +370,7 @@ pub(super) fn sync_registration<'s>(let Some(load) = super::state::get(scope, face) else {return;};+ let registration_scope = super::storage::font_face_set_registration_scope(scope, owner, face);let Some(context) = owner.get_creation_context(scope) else {return;};@@ -384,7 +384,7 @@ pub(super) fn sync_registration<'s>(let changed = host.with_font_services(document, |services| {let load = load.borrow();if present {- match load.register(services) {+ match load.register(services, registration_scope) {Ok(Some(moli_layout::WebFontRegistrationOutcome::Added| moli_layout::WebFontRegistrationOutcome::Replaced,@@ -396,7 +396,7 @@ pub(super) fn sync_registration<'s>(}}} else {- load.unregister(services)+ services.remove_font_face_set_web_font(load.slot())}});if changed {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.rsindex 3fc8d1369..90ee6f1bd 100644--- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/state.rs+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/state.rs@@ -207,7 +207,6 @@ mod tests {"css".into(),moli_layout::WebFontFace::new("CSS"),Vec::new(),- true,);let js_load = {let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));@@ -220,12 +219,7 @@ mod tests {initialize(scope,js_face,- FontFaceResource::new(- "js".into(),- moli_layout::WebFontFace::new("JS"),- Vec::new(),- false,- ),+ FontFaceResource::new("js".into(), moli_layout::WebFontFace::new("JS"), Vec::new()),None,);Rc::downgrade(&get(scope, js_face).unwrap())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.rsindex bc30c63de..d68f434de 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@@ -214,6 +214,20 @@ fn font_face_set_connected_faces_array<'s>(font_face_set_array_for_slot(scope, object, FONT_FACE_SET_CONNECTED_FACES_SLOT)}+pub(super) fn font_face_set_registration_scope<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ fonts: v8::Local<'s, v8::Object>,+ face: v8::Local<'s, v8::Object>,+) -> moli_layout::WebFontRegistrationScope {+ if font_face_set_connected_faces_array(scope, fonts)+ .is_some_and(|faces| array_contains_value(scope, faces, face.into()))+ {+ moli_layout::WebFontRegistrationScope::FontFaceSetConnected+ } else {+ moli_layout::WebFontRegistrationScope::FontFaceSetManual+ }+}+fn font_face_set_array_for_slot<'s>(scope: &mut v8::PinScope<'s, '_>,object: v8::Local<'s, v8::Object>,@@ -318,8 +332,8 @@ fn sync_font_face_set_owners<'s>(previous: v8::Local<'s, v8::Array>,current: v8::Local<'s, v8::Array>,) {- // Distinct CSS-connected wrappers can share a resource slot. Removing one- // membership must not unregister the resource still used by another face.+ // A declaration projected by multiple stylesheet contributions retains one+ // registration until its final set membership leaves.let mut retained_slots = std::collections::HashSet::new();for index in 0..current.length() {let Some(face) = currentdiff --git a/moli-renderer-v8/src/css_resource_urls.rs b/moli-renderer-v8/src/css_resource_urls.rsindex dd88a149e..40b86b5e0 100644--- a/moli-renderer-v8/src/css_resource_urls.rs+++ b/moli-renderer-v8/src/css_resource_urls.rs@@ -1,3 +1,8 @@+use std::sync::{+ Arc,+ atomic::{AtomicU64, Ordering},+};+use cssparser::{Parser, UnicodeRange};use moli_crypto::sha256_hex;use moli_css_parse::{@@ -8,6 +13,7 @@ use moli_layout::{WebFontFace, WebFontUnicodeRange};use url::Url;use crate::protocol_types::OptionalResourceFetchMask;+static NEXT_CSS_FONT_FACE: AtomicU64 = AtomicU64::new(1);#[derive(Clone, Copy, Debug, Eq, PartialEq)]pub(crate) enum StylesheetLoadBlockingResourceKind {@@ -51,6 +57,13 @@ impl StylesheetLoadBlockingResource {}}+ pub(crate) fn with_registration_slot(mut self, slot: String) -> Self {+ if let Self::Font { font, .. } = &mut self {+ font.registration_slot = slot;+ }+ self+ }+pub(crate) fn kind(&self) -> StylesheetLoadBlockingResourceKind {match self {Self::Image(_) => StylesheetLoadBlockingResourceKind::Image,@@ -108,8 +121,9 @@ impl StylesheetSubresourceRequest {/// Parsed declaration metadata, before any network source is selected.#[derive(Clone, Debug, PartialEq)]pub(crate) struct StylesheetWebFont {- slot: String,- face: WebFontFace,+ resource_key: String,+ registration_slot: String,+ face: Arc<WebFontFace>,sources: Vec<moli_css_parse::CssFontSource>,}@@ -125,11 +139,15 @@ impl StylesheetWebFont {&self.sources}- pub(crate) fn slot(&self) -> &str {- &self.slot+ pub(crate) fn resource_key(&self) -> &str {+ &self.resource_key}- pub(crate) fn face(&self) -> &WebFontFace {+ pub(crate) fn registration_slot(&self) -> &str {+ &self.registration_slot+ }++ pub(crate) fn face(&self) -> &Arc<WebFontFace> {&self.face}}@@ -252,7 +270,6 @@ pub(crate) fn stylesheet_web_font_resource_with_resolved_sources(});let descriptor = parsed_web_font_face(css_text)?;Some(stylesheet_web_font_resource_with_descriptor(- css_text,request_url,descriptor,sources,@@ -260,20 +277,14 @@ pub(crate) fn stylesheet_web_font_resource_with_resolved_sources(}fn stylesheet_web_font_resource_with_descriptor(- css_text: &str,request_url: Option<Url>,descriptor: ParsedWebFontFace,sources: Vec<moli_css_parse::CssFontSource>,) -> StylesheetLoadBlockingResource {- // The slot identifies a shareable resource, not a layout generation or- // an individual declaration. The import response and retained style world- // must converge on one slot. Identical relative declarations parsed under- // different stylesheet bases must not- // alias, so identity includes every resolved fallback, its kind and order.+ // Resource identity includes the complete resolved source list, independently+ // of mutable face descriptors and declaration/registration identity.// Length-prefix strings so source boundaries cannot collide.let mut slot_material = Vec::new();- slot_material.extend_from_slice(&(css_text.len() as u64).to_le_bytes());- slot_material.extend_from_slice(css_text.as_bytes());for source in &sources {let (kind, value) = match source {moli_css_parse::CssFontSource::Local(value) => (0, value),@@ -287,8 +298,12 @@ fn stylesheet_web_font_resource_with_descriptor(StylesheetLoadBlockingResource::font(request_url,StylesheetWebFont {- slot,- face: descriptor.into_face(),+ resource_key: slot,+ registration_slot: format!(+ "stylesheet-font-face:anonymous:{}",+ NEXT_CSS_FONT_FACE.fetch_add(1, Ordering::Relaxed)+ ),+ face: Arc::new(descriptor.into_face()),sources,},)@@ -455,7 +470,7 @@ mod tests {let web_font = resources[0].web_font().expect("font resource should retain its descriptors");- assert!(web_font.slot().starts_with("stylesheet-font:"));+ assert!(web_font.resource_key().starts_with("stylesheet-font:"));assert_eq!(web_font.face().family_name(), "Demo");assert_eq!(web_font.face().weight(), Some(625.0));assert_eq!(web_font.face().stretch(), Some(87.5));@@ -530,8 +545,11 @@ mod tests {response_projection.web_font().expect("response font")- .slot(),- native_projection.web_font().expect("native font").slot(),+ .resource_key(),+ native_projection+ .web_font()+ .expect("native font")+ .resource_key(),"the early import-response registration and retained manifest must keep one slot",);assert_eq!(@@ -560,8 +578,8 @@ mod tests {.expect("second native resource");assert_ne!(- first.web_font().expect("first font").slot(),- second.web_font().expect("second font").slot(),+ first.web_font().expect("first font").resource_key(),+ second.web_font().expect("second font").resource_key(),"equal relative text parsed in different stylesheet directories must not alias",);}@@ -583,15 +601,15 @@ mod tests {.unwrap();assert_eq!(first.request_url(), second.request_url());assert_ne!(- first.web_font().unwrap().slot(),- second.web_font().unwrap().slot()+ first.web_font().unwrap().resource_key(),+ second.web_font().unwrap().resource_key());let slot = |sources| {stylesheet_web_font_resource_with_resolved_sources(css, sources).unwrap().web_font().unwrap()- .slot()+ .resource_key().to_owned()};let url = "https://example.test/font.woff2".to_owned();diff --git a/moli-renderer-v8/src/font_loading.rs b/moli-renderer-v8/src/font_loading.rsindex cc800e5b9..46da7572e 100644--- a/moli-renderer-v8/src/font_loading.rs+++ b/moli-renderer-v8/src/font_loading.rs@@ -4,15 +4,16 @@//! 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 std::{cell::RefCell, rc::Rc, sync::Arc};use moli_css_parse::CssFontSource;use moli_layout::{DocumentLayoutServices, FontFaceData, WebFontFace, WebFontRegistration,- WebFontRegistrationError, WebFontRegistrationOutcome,+ WebFontRegistrationError, WebFontRegistrationOutcome, WebFontRegistrationScope,};pub(crate) type FontFaceLoad = Rc<RefCell<FontFaceResource>>;+pub(crate) type FontSourceLoad = Rc<RefCell<FontSourceResource>>;pub(crate) fn script_font_descriptor(family: &str,@@ -62,12 +63,31 @@ enum LoadState {}#[derive(Debug)]-pub(crate) struct FontFaceResource {- slot: String,- descriptor: WebFontFace,- stylesheet: bool,+pub(crate) struct FontSourceResource {+ source_key: Option<String>,sources: std::vec::IntoIter<CssFontSource>,state: LoadState,+}++impl FontSourceResource {+ pub(crate) fn new(sources: Vec<CssFontSource>, source_key: Option<String>) -> FontSourceLoad {+ Rc::new(RefCell::new(Self {+ sources: sources.into_iter(),+ source_key,+ state: LoadState::Unloaded,+ }))+ }+}++/// One independent FontFace declaration. The source operation and immutable+/// font data may be shared; descriptors, activation and registration identity+/// belong to this face. Document membership is supplied at registration time.+#[derive(Debug)]+pub(crate) struct FontFaceResource {+ slot: String,+ descriptor: Arc<WebFontFace>,+ source: FontSourceLoad,+ activated: bool,started: bool,}@@ -76,14 +96,24 @@ impl FontFaceResource {slot: String,descriptor: WebFontFace,sources: Vec<CssFontSource>,- stylesheet: bool,+ ) -> FontFaceLoad {+ Self::with_source(+ slot,+ Arc::new(descriptor),+ FontSourceResource::new(sources, None),+ )+ }++ pub(crate) fn with_source(+ slot: String,+ descriptor: Arc<WebFontFace>,+ source: FontSourceLoad,) -> FontFaceLoad {Rc::new(RefCell::new(Self {slot,descriptor,- stylesheet,- sources: sources.into_iter(),- state: LoadState::Unloaded,+ source,+ activated: false,started: false,}))}@@ -93,11 +123,24 @@ impl FontFaceResource {}pub(crate) fn set_descriptor(&mut self, descriptor: WebFontFace) {- self.descriptor = descriptor;+ if self.descriptor().as_ref() != &descriptor {+ self.descriptor = Arc::new(descriptor);+ }+ }++ pub(crate) fn descriptor(&self) -> &Arc<WebFontFace> {+ &self.descriptor+ }++ pub(crate) fn shares_source(&self, other: &Self) -> bool {+ Rc::ptr_eq(&self.source, &other.source)}pub(crate) fn status(&self) -> FontFaceStatus {- match self.state {+ if !self.activated {+ return FontFaceStatus::Unloaded;+ }+ match self.source.borrow().state {LoadState::Unloaded => FontFaceStatus::Unloaded,LoadState::Loading => FontFaceStatus::Loading,LoadState::Loaded(_) => FontFaceStatus::Loaded,@@ -106,7 +149,10 @@ impl FontFaceResource {}pub(crate) fn error(&self) -> Option<FontFaceError> {- match self.state {+ if !self.activated {+ return None;+ }+ match self.source.borrow().state {LoadState::Error(error) => Some(error),_ => None,}@@ -117,12 +163,16 @@ impl FontFaceResource {}pub(crate) fn fail(&mut self, name: &'static str, message: &'static str) {- self.state = LoadState::Error(FontFaceError { name, message });+ self.activated = true;+ self.source.borrow_mut().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),+ Ok(data) => {+ self.activated = true;+ self.source.borrow_mut().state = LoadState::Loaded(data);+ }Err(_) => self.fail("SyntaxError", "Invalid font data in ArrayBuffer."),}}@@ -132,9 +182,15 @@ impl FontFaceResource {if self.status() != FontFaceStatus::Unloaded {return false;}- self.state = LoadState::Loading;+ self.activated = true;self.started = true;- true+ let mut source = self.source.borrow_mut();+ if matches!(source.state, LoadState::Unloaded) {+ source.state = LoadState::Loading;+ true+ } else {+ false+ }}/// Advance after starting or after a failed URL. Local lookup and source@@ -143,21 +199,23 @@ impl FontFaceResource {if self.status() != FontFaceStatus::Loading {return None;}- for source in self.sources.by_ref() {+ let mut resource = self.source.borrow_mut();+ let FontSourceResource { sources, state, .. } = &mut *resource;+ for source in sources.by_ref() {match source {CssFontSource::Local(name) => {if let Some(data) = services.local_font_source(&name) {- self.state = LoadState::Loaded(data);+ *state = LoadState::Loaded(data);return None;}}CssFontSource::Url(url) => return Some(url),}}- self.fail(- "NetworkError",- "A network error occurred while loading the font.",- );+ *state = LoadState::Error(FontFaceError {+ name: "NetworkError",+ message: "A network error occurred while loading the font.",+ });None}@@ -169,7 +227,7 @@ impl FontFaceResource {bytes: Option<&[u8]>,) -> Result<(), WebFontRegistrationError> {if let Some(bytes) = bytes {- self.state = LoadState::Loaded(FontFaceData::from_bytes(bytes)?);+ self.source.borrow_mut().state = LoadState::Loaded(FontFaceData::from_bytes(bytes)?);}Ok(())}@@ -177,22 +235,22 @@ impl FontFaceResource {pub(crate) fn register(&self,services: &mut DocumentLayoutServices,+ scope: WebFontRegistrationScope,) -> Result<Option<WebFontRegistrationOutcome>, WebFontRegistrationError> {- let LoadState::Loaded(data) = &self.state else {+ if !self.activated {+ return Ok(None);+ }+ let source = self.source.borrow();+ let LoadState::Loaded(data) = &source.state else {return Ok(None);};- let mut registration = WebFontRegistration::from_font_data(+ let registration = WebFontRegistration::from_font_data(self.slot.clone(),- self.descriptor.clone(),+ self.descriptor.as_ref().clone(),data.clone(),- );- if self.stylesheet {- registration = registration.with_stylesheet_scope();- }+ )+ .with_scope(scope)+ .with_source_key(source.source_key.clone());services.register_web_font(registration).map(Some)}-- pub(crate) fn unregister(&self, services: &mut DocumentLayoutServices) -> bool {- services.remove_web_font(&self.slot)- }}diff --git a/moli-renderer-v8/src/layout_renderer/mod.rs b/moli-renderer-v8/src/layout_renderer/mod.rsindex e86daa494..491fa96ac 100644--- a/moli-renderer-v8/src/layout_renderer/mod.rs+++ b/moli-renderer-v8/src/layout_renderer/mod.rs@@ -83,13 +83,15 @@ fn build_native_layout_pass_recursive(};if services.has_stylesheet_web_fonts() {if let Some(resources) = styles.stylesheet_resources(root) {- let active = resources- .web_fonts()- .iter()- .filter_map(|resource| resource.web_font().map(|font| font.slot()))- .collect::<std::collections::HashSet<_>>();- services.with_active_stylesheet_fonts(- |slot| active.contains(slot),+ services.with_stylesheet_font_declarations(+ resources.web_fonts().iter().filter_map(|resource| {+ let font = resource.web_font()?;+ Some(moli_layout::WebFontDeclaration {+ slot: font.registration_slot(),+ source_key: font.resource_key(),+ face: font.face(),+ })+ }),|services| {build_layout_pass_with_embedded_frames(&source,diff --git a/moli-renderer-v8/src/live_stylesheet/mod.rs b/moli-renderer-v8/src/live_stylesheet/mod.rsindex e9ce4d9d7..f30818e6a 100644--- a/moli-renderer-v8/src/live_stylesheet/mod.rs+++ b/moli-renderer-v8/src/live_stylesheet/mod.rs@@ -1023,8 +1023,6 @@ pub(crate) struct LiveStylesheet {Rc<crate::style_engine::StylesheetFontFaceProjection>,)>,>,- next_font_face_rule_identity: Cell<u64>,- font_face_rule_identities: RefCell<Vec<FontFaceRuleIdentity>>,shared_initial_contents: RefCell<Option<StdArc<SharedStylesheetContents>>>,rule_wrapper_leases: RefCell<HashMap<@@ -1093,8 +1091,15 @@ struct FontFaceRuleIdentity {fingerprint: String,}+#[derive(Debug, Default)]+struct FontFaceRuleIdentities {+ next_id: u64,+ entries: Vec<FontFaceRuleIdentity>,+}+#[derive(Debug, Default)]pub(crate) struct LiveStylesheetDerivedState {+ font_face_rule_identities: Mutex<FontFaceRuleIdentities>,serialized_css_text_cache: Mutex<Option<(u64, StdArc<str>)>>,dependency_summary_cache: Mutex<Option<(@@ -1105,6 +1110,55 @@ pub(crate) struct LiveStylesheetDerivedState {}impl LiveStylesheetDerivedState {+ pub(crate) fn retain_font_face_rule_identities(+ &self,+ rules: &[crate::style_engine::NativeStylesheetFontFaceRuleProjection],+ ) {+ self.font_face_rule_identities+ .lock()+ .entries+ .retain(|entry| {+ rules+ .iter()+ .any(|rule| ServoArc::ptr_eq(&entry.rule, &rule.rule))+ });+ }++ /// Both native resource discovery and lazy JS projection use the same+ /// declaration identity. Strong rule references prevent address reuse.+ pub(crate) fn font_face_rule_identity(+ &self,+ rule: &ServoArc<Locked<FontFaceRule>>,+ fingerprint: &str,+ ) -> u64 {+ let mut identities = self.font_face_rule_identities.lock();+ let existing = identities+ .entries+ .iter()+ .position(|entry| ServoArc::ptr_eq(&entry.rule, rule));+ if let Some(index) = existing+ && identities.entries[index].fingerprint == fingerprint+ {+ return identities.entries[index].id;+ }+ identities.next_id = identities+ .next_id+ .checked_add(1)+ .expect("font-face rule identity space exhausted");+ let id = identities.next_id;+ let entry = FontFaceRuleIdentity {+ id,+ rule: rule.clone(),+ fingerprint: fingerprint.to_owned(),+ };+ if let Some(index) = existing {+ identities.entries[index] = entry;+ } else {+ identities.entries.push(entry);+ }+ id+ }+pub(crate) fn serialized_css_text(&self,contents_revision: u64,@@ -1295,8 +1349,6 @@ impl LiveStylesheet {import_edges: RefCell::new(Vec::new()),derived_state: StdArc::new(LiveStylesheetDerivedState::default()),font_face_cache: RefCell::new(None),- next_font_face_rule_identity: Cell::new(0),- font_face_rule_identities: RefCell::new(Vec::new()),shared_initial_contents: RefCell::new(shared_initial_contents),rule_wrapper_leases: RefCell::new(HashMap::new()),};@@ -1694,44 +1746,31 @@ impl LiveStylesheet {&self,native_projection: crate::style_engine::NativeStylesheetFontFaceProjection,) -> crate::style_engine::StylesheetFontFaceProjection {- let mut identities = self.font_face_rule_identities.borrow_mut();let mut projection = crate::style_engine::StylesheetFontFaceProjection::default();for native_rule in &native_projection.all_rules {let rule_address = native_rule.rule.raw_ptr().as_ptr() as usize;- let identity = match identities- .iter_mut()- .find(|identity| ServoArc::ptr_eq(&identity.rule, &native_rule.rule))- {- Some(identity) if identity.fingerprint == native_rule.rule_fingerprint => {- identity.id- }- Some(identity) => {- let id = self.allocate_font_face_rule_identity();- identity.id = id;- identity.fingerprint = native_rule.rule_fingerprint.clone();- id- }- None => {- let id = self.allocate_font_face_rule_identity();- identities.push(FontFaceRuleIdentity {- id,- rule: native_rule.rule.clone(),- fingerprint: native_rule.rule_fingerprint.clone(),- });- id- }- };+ let identity = self+ .derived_state+ .font_face_rule_identity(&native_rule.rule, &native_rule.rule_fingerprint);projection.all_rules.push(crate::style_engine::StylesheetFontFaceRuleProjection {- 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(),- ),- });+ 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(),+ )+ .map(|resource| {+ resource.with_registration_slot(format!(+ "stylesheet-font-face:live:{}:{identity}",+ self.id.get()+ ))+ }),+ });if native_projection.effective_rule_addresses.contains(&rule_address)@@ -1740,25 +1779,19 @@ impl LiveStylesheet {}}- identities.retain(|identity| {- native_projection- .all_rules- .iter()- .any(|native_rule| ServoArc::ptr_eq(&identity.rule, &native_rule.rule))- });+ self.derived_state+ .font_face_rule_identities+ .lock()+ .entries+ .retain(|identity| {+ native_projection+ .all_rules+ .iter()+ .any(|native_rule| ServoArc::ptr_eq(&identity.rule, &native_rule.rule))+ });projection}- fn allocate_font_face_rule_identity(&self) -> u64 {- let next = self- .next_font_face_rule_identity- .get()- .checked_add(1)- .expect("font-face rule identity space exhausted");- self.next_font_face_rule_identity.set(next);- next- }-pub(crate) fn ensure_owned_contents_for_mutation(&self) {let Some(shared_contents) = self.shared_initial_contents.borrow_mut().take() else {return;@@ -1767,7 +1800,12 @@ impl LiveStylesheet {return;}- let preserve_font_face_identities = !self.font_face_rule_identities.borrow().is_empty();+ let preserve_font_face_identities = !self+ .derived_state+ .font_face_rule_identities+ .lock()+ .entries+ .is_empty();let previous_font_face_rules = preserve_font_face_identities.then(|| crate::style_engine::native_font_face_rules_for_stylesheet(&self.stylesheet));let shared_lock = self.stylesheet.shared_lock.clone();@@ -1920,7 +1958,13 @@ impl LiveStylesheet {previous_rules: &[crate::style_engine::NativeStylesheetFontFaceRuleProjection],current_rules: &[crate::style_engine::NativeStylesheetFontFaceRuleProjection],) {- for identity in self.font_face_rule_identities.borrow_mut().iter_mut() {+ for identity in self+ .derived_state+ .font_face_rule_identities+ .lock()+ .entries+ .iter_mut()+ {let Some(index) = previous_rules.iter().position(|rule| ServoArc::ptr_eq(&identity.rule, &rule.rule))diff --git a/moli-renderer-v8/src/live_stylesheet/mutation.rs b/moli-renderer-v8/src/live_stylesheet/mutation.rsindex 7b300f48d..4c299e490 100644--- a/moli-renderer-v8/src/live_stylesheet/mutation.rs+++ b/moli-renderer-v8/src/live_stylesheet/mutation.rs@@ -1180,7 +1180,11 @@ impl LiveStylesheet {*self.stylesheet.contents.write_with(&mut guard) = replacement_contents;}self.reconcile_import_edges();- self.font_face_rule_identities.borrow_mut().clear();+ self.derived_state+ .font_face_rule_identities+ .lock()+ .entries+ .clear();self.note_contents_mutation();}diff --git a/moli-renderer-v8/src/native_bridge/context_host/layout.rs b/moli-renderer-v8/src/native_bridge/context_host/layout.rsindex ff55fb8e7..346e41e26 100644--- a/moli-renderer-v8/src/native_bridge/context_host/layout.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/layout.rs@@ -662,9 +662,15 @@ impl JsContextHost {document: DomHandle,resource: StylesheetLoadBlockingResource,) -> Option<StylesheetSubresourceRequest> {- self.document_layout_state- .borrow_mut()- .admit(document, self.document_handle(), resource)+ let prepared = self.document_layout_state.borrow_mut().admit(+ document,+ self.document_handle(),+ resource,+ );+ if prepared.fonts_changed {+ self.invalidate_document_font_layout(document);+ }+ prepared.request}pub(crate) fn complete_document_web_font(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.rsindex 0de9bb1ae..c863d4698 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@@ -4,11 +4,11 @@ use moli_layout::{DocumentLayoutServices, FrozenLayoutTree, LayoutViewport};use super::layout_snapshot::LatestLayoutTreeCache;use crate::{- css_resource_urls::{- CompletedStylesheetWebFont, StylesheetLoadBlockingResource, StylesheetSubresourceRequest,- },+ css_resource_urls::{CompletedStylesheetWebFont, StylesheetLoadBlockingResource},document_runtime::DomHandle,- script_vm::web_fonts::{DocumentWebFontCompletion, DocumentWebFontState},+ script_vm::web_fonts::{+ DocumentWebFontCompletion, DocumentWebFontState, PreparedStylesheetResourceLoad,+ },style_engine::{StyleViewport, StylesheetResourceGeneration, StyloStyleEnvironment},};@@ -338,7 +338,7 @@ impl DocumentLayoutState {document: DomHandle,main_document: DomHandle,resource: StylesheetLoadBlockingResource,- ) -> Option<StylesheetSubresourceRequest> {+ ) -> PreparedStylesheetResourceLoad {// Ready faces are revisited by read-only font projections.self.with_web_fonts_for_document(document, main_document, |fonts, services| {fonts.admit(resource, services)diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/selection_order.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/selection_order.rsindex 44fb51934..0b96dfa61 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/selection_order.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/fonts/selection_order.rs@@ -23,6 +23,95 @@ pub(super) fn order_vm() -> StandaloneScriptVmHarness {vm}+#[tokio::test]+async fn detached_css_faces_can_be_registered_manually_before_or_after_native_cleanup() {+ let (_, wide) = order_font_data();+ for automatic in [false, true] {+ for cleanup_before_add in [false, true] {+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();+ if automatic {+ loader.set_optional_resource_fetch_mask(+ crate::protocol_types::OptionalResourceFetchMask::FONT,+ );+ }+ let (mut vm, _completions) =+ new_parsed_test_vm_with_loader_and_resource_completion_queue(+ "https://font-selection-order.test/",+ "<!doctype html><span id=probe style='display:inline-block;font:40px OrderFace'>AAAA</span>",+ &loader,+ );+ vm.set_layout_policy(moli_page_types::LayoutPolicy::OnDemand);+ vm.eval(&format!(r#"+ globalThis.style=document.createElement('style');+ style.textContent='@font-face{{font-family:OrderFace;src:url(data:font/ttf;base64,{wide})}}';document.head.append(style);+ globalThis.face=[...document.fonts][0];face.load();+ "#)).unwrap();+ assert_eq!(+ vm.eval("String(probe.getBoundingClientRect().width)")+ .unwrap(),+ "160"+ );+ vm.eval("style.sheet.deleteRule(0);void document.fonts.size")+ .unwrap();+ if cleanup_before_add {+ assert_ne!(+ vm.eval("String(probe.getBoundingClientRect().width)")+ .unwrap(),+ "160"+ );+ }+ vm.eval("document.fonts.add(face)").unwrap();+ assert_eq!(+ vm.eval("String(probe.getBoundingClientRect().width)")+ .unwrap(),+ "160",+ "a manual member must survive native CSS cleanup"+ );+ assert_eq!(vm.eval("face.status==='loaded'&&document.fonts.has(face)&&document.fonts.check('40px OrderFace','AAAA')").unwrap(), "true");+ vm.eval("document.fonts.delete(face)").unwrap();+ assert_ne!(+ vm.eval("String(probe.getBoundingClientRect().width)")+ .unwrap(),+ "160"+ );+ }+ }+}++#[test]+fn css_faces_with_shared_sources_keep_independent_mutable_descriptors() {+ let (_, wide) = order_font_data();+ for detached in [false, true] {+ let mut vm = order_vm();+ vm.eval(&format!(r#"+ globalThis.style=document.createElement('style');+ const rule='@font-face{{font-family:OrderFace;src:url(data:font/ttf;base64,{wide})}}';+ style.textContent=rule+rule;document.head.append(style);+ globalThis.faces=[...document.fonts];document.fonts.load('40px OrderFace','AAAA');+ globalThis.moved=document.createElement('span');moved.textContent='AAAA';moved.style.cssText='display:inline-block;font:40px Moved';document.body.append(moved);+ "#)).unwrap();+ assert_eq!(+ vm.eval("String(probe.getBoundingClientRect().width)")+ .unwrap(),+ "160"+ );+ if detached {+ vm.eval("style.sheet.deleteRule(0);void document.fonts.size")+ .unwrap();+ }+ vm.eval("faces[0].family='Moved'").unwrap();+ if detached {+ vm.eval("document.fonts.add(faces[0])").unwrap();+ }+ assert_eq!(vm.eval("[probe.getBoundingClientRect().width,moved.getBoundingClientRect().width].join(',')").unwrap(), "160,160");+ assert_eq!(vm.eval("faces[1].family==='OrderFace'&&faces[1].status==='loaded'&&document.fonts.has(faces[1])").unwrap(), "true");+ assert_eq!(+ vm.eval("style.sheet.cssRules[0].style.fontFamily").unwrap(),+ "OrderFace"+ );+ }+}+#[tokio::test]async fn font_face_css_selection_keeps_declaration_order_without_js_projection() {use crate::native_bridge::document::take_owner_font_face_projection_count_for_test;@@ -80,7 +169,19 @@ async fn font_face_css_reordering_preserves_last_duplicate_and_manual_priority()"#)).unwrap();let width = |vm: &mut StandaloneScriptVmHarness| {vm.reconcile_document_web_fonts_for_layout();- assert_eq!(vm.document_web_font_counts_for_test(), (2, 2, 2));+ let declarations = if vm+ .eval("String(!!globalThis.duplicate?.isConnected)")+ .unwrap()+ == "true"+ {+ 3+ } else {+ 2+ };+ assert_eq!(+ vm.document_web_font_counts_for_test(),+ (declarations, declarations, declarations)+ );vm.eval("String(probe.getBoundingClientRect().width)").unwrap()};diff --git a/moli-renderer-v8/src/script_vm/web_fonts.rs b/moli-renderer-v8/src/script_vm/web_fonts.rsindex d12140057..9768fe930 100644--- a/moli-renderer-v8/src/script_vm/web_fonts.rs+++ b/moli-renderer-v8/src/script_vm/web_fonts.rs@@ -4,14 +4,17 @@ use std::{rc::{Rc, Weak},};-use moli_layout::{DocumentLayoutServices, WebFontRegistrationError, WebFontRegistrationOutcome};+use moli_layout::{+ DocumentLayoutServices, WebFontRegistrationError, WebFontRegistrationOutcome,+ WebFontRegistrationScope,+};use crate::{css_resource_urls::{CompletedStylesheetWebFont, StylesheetLoadBlockingResource, StylesheetSubresourceRequest,StylesheetWebFont,},- font_loading::{FontFaceLoad, FontFaceResource},+ font_loading::{FontFaceLoad, FontFaceResource, FontSourceResource},};#[derive(Clone, Debug)]@@ -30,6 +33,7 @@ pub(crate) struct DocumentWebFontState {// 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>>>,+ sources: BTreeMap<String, Weak<RefCell<FontSourceResource>>>,// 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>,@@ -44,6 +48,13 @@ pub(crate) enum DocumentWebFontCompletion {Stale,}+/// Loading can finish from cached/local data without producing a request.+/// Publish registration changes independently so geometry is invalidated then.+pub(crate) struct PreparedStylesheetResourceLoad {+ pub(crate) request: Option<StylesheetSubresourceRequest>,+ pub(crate) fonts_changed: bool,+}+impl DocumentWebFontState {pub(crate) fn is_pristine(&self) -> bool {self.resource_generation.is_none() && self.slots.is_empty()@@ -70,17 +81,35 @@ impl DocumentWebFontState {}pub(crate) fn observe(&mut self, resource: &StylesheetWebFont) -> FontFaceLoad {- if let Some(load) = self.loads.get(resource.slot()).and_then(Weak::upgrade) {+ if let Some(load) = self+ .loads+ .get(resource.registration_slot())+ .and_then(Weak::upgrade)+ {return load;}- let load = FontFaceResource::new(- resource.slot().to_owned(),+ let source = self+ .sources+ .get(resource.resource_key())+ .and_then(Weak::upgrade)+ .unwrap_or_else(|| {+ let source = FontSourceResource::new(+ resource.sources().to_vec(),+ Some(resource.resource_key().to_owned()),+ );+ self.sources+ .insert(resource.resource_key().to_owned(), Rc::downgrade(&source));+ source+ });+ let load = FontFaceResource::with_source(+ resource.registration_slot().to_owned(),resource.face().clone(),- resource.sources().to_vec(),- true,+ source,+ );+ self.loads.insert(+ resource.registration_slot().to_owned(),+ Rc::downgrade(&load),);- self.loads- .insert(resource.slot().to_owned(), Rc::downgrade(&load));load}@@ -89,21 +118,33 @@ impl DocumentWebFontState {resources: impl IntoIterator<Item = &'a StylesheetLoadBlockingResource>,services: &mut DocumentLayoutServices,) -> bool {- let order = resources+ let resources = resources.into_iter().filter_map(StylesheetLoadBlockingResource::web_font)- .map(|font| font.slot().to_owned())+ .collect::<Vec<_>>();+ // Establish the new declarations before retiring old ones, so their+ // shared decoded source survives an owner/projection identity change.+ for font in &resources {+ let load = self.observe(font);+ self.slots+ .entry(font.registration_slot().to_owned())+ .or_insert(WebFontSlot { load });+ }+ let order = resources+ .into_iter()+ .map(|font| font.registration_slot().to_owned()).collect::<Vec<_>>();let active = order.iter().collect::<BTreeSet<_>>();let mut changed = false;- self.slots.retain(|slot, entry| {+ self.slots.retain(|slot, _| {if active.contains(slot) {return true;}- changed |= entry.load.borrow().unregister(services);+ changed |= services.remove_stylesheet_web_font(slot);false});self.loads.retain(|_, load| load.strong_count() != 0);+ self.sources.retain(|_, source| source.strong_count() != 0);changed | services.set_stylesheet_web_font_order(&order)}@@ -126,33 +167,49 @@ impl DocumentWebFontState {&mut self,resource: StylesheetLoadBlockingResource,services: &mut DocumentLayoutServices,- ) -> Option<StylesheetSubresourceRequest> {+ ) -> PreparedStylesheetResourceLoad {let font = match resource {StylesheetLoadBlockingResource::Image(url) => {- return Some(StylesheetSubresourceRequest::image(url, None));+ return PreparedStylesheetResourceLoad {+ request: Some(StylesheetSubresourceRequest::image(url, None)),+ fonts_changed: false,+ };}StylesheetLoadBlockingResource::Font { font, .. } => font,};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;- }- let next = load.borrow_mut().next_url(services);+ self.slots.insert(+ font.registration_slot().to_owned(),+ WebFontSlot { load: load.clone() },+ );+ let next = if load.borrow_mut().begin() {+ load.borrow_mut().next_url(services)+ } else {+ None+ };if let Some(url) = next {let url = url::Url::parse(&url).expect("CSS font sources retain resolved URLs");- Some(self.bind_request(url, font, load))- } else {- if let Err(error) = load.borrow().register(services) {- tracing::warn!(%error, "failed to register local stylesheet font");+ return PreparedStylesheetResourceLoad {+ request: Some(self.bind_request(url, font, load)),+ fonts_changed: false,+ };+ }+ let fonts_changed = match load+ .borrow()+ .register(services, WebFontRegistrationScope::Stylesheet)+ {+ Ok(Some(WebFontRegistrationOutcome::Added | WebFontRegistrationOutcome::Replaced)) => {+ true}- None+ Ok(_) => false,+ Err(error) => {+ tracing::warn!(%error, "failed to register cached/local stylesheet font");+ false+ }+ };+ PreparedStylesheetResourceLoad {+ request: None,+ fonts_changed,}}@@ -166,7 +223,7 @@ impl DocumentWebFontState {if self.pending.get(&id)- .is_none_or(|load| load.borrow().slot() != request.font().slot())+ .is_none_or(|load| load.borrow().slot() != request.font().registration_slot()){return DocumentWebFontCompletion::Stale;}@@ -184,19 +241,33 @@ impl DocumentWebFontState {load,)));}- let active = self- .slots- .get(request.font().slot())- .is_some_and(|slot| std::rc::Rc::ptr_eq(&slot.load, &load));+ let mut active = false;+ let mut registered = None;+ let mut registration_error = None;+ for entry in self.slots.values() {+ let face = entry.load.borrow();+ if !face.shares_source(&load.borrow()) {+ continue;+ }+ active = true;+ match face.register(services, WebFontRegistrationScope::Stylesheet) {+ Ok(Some(outcome)) => {+ registered.get_or_insert(outcome);+ }+ Err(error) => registration_error = Some(error),+ Ok(None) => {}+ }+ }if !active {return DocumentWebFontCompletion::Stale;}- match load.borrow().register(services) {- Ok(Some(outcome)) => DocumentWebFontCompletion::Registered(outcome),- Err(error) => DocumentWebFontCompletion::Invalid(error),- Ok(None) => error+ if let Some(outcome) = registered {+ DocumentWebFontCompletion::Registered(outcome)+ } else {+ registration_error+ .or(error).map(DocumentWebFontCompletion::Invalid)- .unwrap_or(DocumentWebFontCompletion::NetworkFailed),+ .unwrap_or(DocumentWebFontCompletion::NetworkFailed)}}@@ -227,6 +298,44 @@ mod tests {const TEST_FONT: &[u8] = include_bytes!("../../../moli-layout/tests/fixtures/moli-ahem.woff2");+ #[test]+ fn independent_declarations_share_source_loading_but_not_descriptors_or_registrations() {+ let mut state = DocumentWebFontState::default();+ let mut services = DocumentLayoutServices::new();+ let first = resource("@font-face{font-family:First;src:url(font.woff2)}");+ let second = resource("@font-face{font-family:Second;src:url(font.woff2)}");+ assert_eq!(+ first.web_font().unwrap().resource_key(),+ second.web_font().unwrap().resource_key()+ );+ let first_load = state.observe(first.web_font().unwrap());+ let second_load = state.observe(second.web_font().unwrap());+ assert!(!Rc::ptr_eq(&first_load, &second_load));+ assert!(first_load.borrow().shares_source(&second_load.borrow()));+ let request = state.admit(first, &mut services).request.unwrap();+ assert_eq!(+ second_load.borrow().status(),+ crate::font_loading::FontFaceStatus::Unloaded+ );+ assert!(+ state.admit(second, &mut services).request.is_none(),+ "the second face joins the existing source operation"+ );+ assert_eq!(state.pending.len(), 1);+ assert!(matches!(+ state.complete(terminal(request, Some(TEST_FONT.to_vec())), &mut services),+ DocumentWebFontCompletion::Registered(_)+ ));+ assert_eq!(services.web_font_count(), 2);+ assert_eq!(state.ready_slot_count(), 2);+ assert!(state.pending.is_empty());+ first_load+ .borrow_mut()+ .set_descriptor(moli_layout::WebFontFace::new("Moved"));+ assert_eq!(second_load.borrow().descriptor().family_name(), "Second");+ assert_ne!(first_load.borrow().slot(), second_load.borrow().slot());+ }+fn resource(css: &str) -> StylesheetLoadBlockingResource {stylesheet_load_blocking_font_resources(css,@@ -261,9 +370,13 @@ mod tests {resource("@font-face{font-family:First;src:url(font.woff2)}"),&mut services,)+ .request+ .unwrap();+ let second_resource = resource("@font-face{font-family:Second;src:url(replacement.woff2)}");+ let second = state+ .admit(second_resource.clone(), &mut services)+ .request.unwrap();- let second_resource = resource("@font-face{font-family:Second;src:url(font.woff2)}");- let second = state.admit(second_resource.clone(), &mut services).unwrap();state.retain_active_slots([&second_resource], &mut services);assert!(matches!(@@ -287,6 +400,7 @@ mod tests {resource("@font-face{font-family:Demo;src:url(font.woff2)}"),&mut services,)+ .request.unwrap();let late = admitted.clone();assert!(matches!(@@ -310,8 +424,11 @@ mod tests {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());+ let first = state+ .admit(resource.clone(), &mut services)+ .request+ .unwrap();+ assert!(state.admit(resource, &mut services).request.is_none());assert_eq!(load.borrow().status(),crate::font_loading::FontFaceStatus::Loading@@ -348,7 +465,7 @@ mod tests {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();+ let request = state.admit(resource, &mut services).request.unwrap();state.retain_active_slots([], &mut services);assert!(matches!(state.complete(terminal(request, Some(TEST_FONT.to_vec())), &mut services),@@ -372,7 +489,10 @@ mod tests {0,"a CSSOM observer does not activate the rule");- let request = state.admit(resource.clone(), &mut services).unwrap();+ let request = state+ .admit(resource.clone(), &mut services)+ .request+ .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);@@ -381,7 +501,7 @@ mod tests {&state.observe(resource.web_font().unwrap())));assert!(- state.admit(resource, &mut services).is_none(),+ state.admit(resource, &mut services).request.is_none(),"reactivation needs no request");assert_eq!(state.ready_slot_count(), 1);diff --git a/moli-renderer-v8/src/style_engine/source/store.rs b/moli-renderer-v8/src/style_engine/source/store.rsindex 823ce883e..5017302b1 100644--- a/moli-renderer-v8/src/style_engine/source/store.rs+++ b/moli-renderer-v8/src/style_engine/source/store.rs@@ -1,6 +1,9 @@use std::{hash::{Hash, Hasher},- sync::{Arc as StdArc, LazyLock},+ sync::{+ Arc as StdArc, LazyLock,+ atomic::{AtomicU64, Ordering},+ },};use moli_crypto::Sha256Context;@@ -26,9 +29,11 @@ pub(crate) struct StylesheetFontFaceDescriptor {static EMPTY_STYLESHEET_FONT_FACES: LazyLock<StdArc<[StylesheetFontFaceDescriptor]>> =LazyLock::new(|| StdArc::from([]));+static NEXT_TEXT_FONT_SOURCE_ID: AtomicU64 = AtomicU64::new(1);#[derive(Clone, Debug)]pub(crate) struct StyloStylesheetSource {+ font_face_identity: u64,contents: StyloStylesheetSourceContents,/// Final response URL used as the external stylesheet parser base.pub(in crate::style_engine) base_url: StdArc<url::Url>,@@ -94,6 +99,7 @@ impl StyloStylesheetSource {StyleSourceKey::from_css_fingerprint(shared.css_fingerprint(), shared.base_url());let base_url = shared.base_url_handle();Self {+ font_face_identity: NEXT_TEXT_FONT_SOURCE_ID.fetch_add(1, Ordering::Relaxed),contents: StyloStylesheetSourceContents::Text { shared },sheet_url: StdArc::clone(&base_url),base_url,@@ -115,6 +121,7 @@ impl StyloStylesheetSource {parsed_stylesheet.media.read_with(&guard).to_css_string()};Self {+ font_face_identity: stylesheet.id().get(),contents: StyloStylesheetSourceContents::Live {stylesheet: parsed_stylesheet,id: stylesheet.id(),@@ -254,6 +261,46 @@ impl StyloStylesheetSource {}}+ pub(in crate::style_engine) fn font_face_registration_slot(+ &self,+ rule: &style::servo_arc::Arc<style::shared_lock::Locked<style::font_face::FontFaceRule>>,+ fingerprint: &str,+ occurrence: usize,+ ) -> String {+ match &self.contents {+ StyloStylesheetSourceContents::Live {+ id, derived_state, ..+ } => {+ let identity = derived_state.font_face_rule_identity(rule, fingerprint);+ format!("stylesheet-font-face:live:{}:{identity}", id.get())+ }+ StyloStylesheetSourceContents::Text { .. } => {+ let namespace = self.source_id.as_ref().map_or_else(+ || self.font_face_identity.to_string(),+ |id| format!("{id:?}"),+ );+ let identity = format!(+ "{}:{namespace}:{}:{fingerprint}:{occurrence}",+ namespace.len(),+ fingerprint.len()+ );+ format!(+ "stylesheet-font-face:text:{}",+ moli_crypto::sha256_hex(identity.as_bytes())+ )+ }+ }+ }++ pub(in crate::style_engine) fn retain_font_face_rule_identities(+ &self,+ rules: &[super::super::NativeStylesheetFontFaceRuleProjection],+ ) {+ if let StyloStylesheetSourceContents::Live { derived_state, .. } = &self.contents {+ derived_state.retain_font_face_rule_identities(rules);+ }+ }+pub(in crate::style_engine) fn live_cascade_update_since(&self,previous: &Self,diff --git a/moli-renderer-v8/src/style_engine/stylesheet.rs b/moli-renderer-v8/src/style_engine/stylesheet.rsindex 58d6a54fa..752c87f1f 100644--- a/moli-renderer-v8/src/style_engine/stylesheet.rs+++ b/moli-renderer-v8/src/style_engine/stylesheet.rs@@ -103,15 +103,27 @@ pub(super) fn install_active_stylesheet(quirks_mode: QuirksMode,) -> ActiveStylesheet {let stylesheet = author_stylesheet_for_source(shared_lock, source, quirks_mode);- let web_font_resources = native_font_face_rules_for_stylesheet(&stylesheet)+ let rules = native_font_face_rules_for_stylesheet(&stylesheet);+ source.retain_font_face_rule_identities(&rules);+ let mut occurrences = std::collections::HashMap::new();+ let web_font_resources = rules.into_iter().filter_map(|rule| {+ let occurrence = occurrences+ .entry(rule.rule_fingerprint.clone())+ .or_insert(0);+ let slot =+ source.font_face_registration_slot(&rule.rule, &rule.rule_fingerprint, *occurrence);+ *occurrence += 1;let resource =crate::css_resource_urls::stylesheet_web_font_resource_with_resolved_sources(&rule.rule_fingerprint,rule.sources,)?;- Some(ActiveWebFontResource::new(rule.rule, resource))+ Some(ActiveWebFontResource::new(+ rule.rule,+ resource.with_registration_slot(slot),+ ))}).collect::<Vec<_>>();ActiveStylesheet::new(diff --git a/moli-renderer-v8/src/style_engine/stylesheet_resources.rs b/moli-renderer-v8/src/style_engine/stylesheet_resources.rsindex 37be1936b..d482a8c27 100644--- a/moli-renderer-v8/src/style_engine/stylesheet_resources.rs+++ b/moli-renderer-v8/src/style_engine/stylesheet_resources.rs@@ -118,8 +118,8 @@ impl StylesheetResourceManifest {&mut imports,);}- // Slots share resource identity, but priority follows declarations.- // Keep the last occurrence when identical rules reuse the same slot.+ // A declaration may be adopted by more than one scope. Keep its last+ // occurrence, while independent rules retain independent registrations.let mut seen = BTreeSet::new();web_fonts.reverse();web_fonts.retain(|resource| {@@ -127,7 +127,7 @@ impl StylesheetResourceManifest {resource.web_font().expect("font resource")- .slot()+ .registration_slot().to_owned(),)});diff --git a/moli-renderer-v8/src/style_engine/tests/subtree_cache/retained_stylesheets.rs b/moli-renderer-v8/src/style_engine/tests/subtree_cache/retained_stylesheets.rsindex 8e028f778..1f697c1ca 100644--- a/moli-renderer-v8/src/style_engine/tests/subtree_cache/retained_stylesheets.rs+++ b/moli-renderer-v8/src/style_engine/tests/subtree_cache/retained_stylesheets.rs@@ -595,7 +595,7 @@ fn retained_imported_font_resources_keep_each_import_parser_base_and_response_slresource.web_font().expect("font manifest entry")- .slot()+ .resource_key().to_owned(),)})@@ -627,8 +627,11 @@ fn retained_imported_font_resources_keep_each_import_parser_base_and_response_sl.as_str()];assert_eq!(retained_slot,- early.web_font().expect("early response font").slot(),- "response-time registration and retained reconciliation must share a slot",+ early+ .web_font()+ .expect("early response font")+ .resource_key(),+ "response-time discovery and retained reconciliation must share a source key",);}}