Truly independent web browser
LibWeb: Implement FontFaceSet in Rust
Andreas Kling166cec48a0e3
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rsindex cce47170a60..6bd20b7b21e 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs@@ -71,6 +71,7 @@ pub(crate) enum TaskSource {Networking = 3,PostedMessage = 6,FileReading = 13,+ FontLoading = 19,}// SAFETY: A task source holds no cells.diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/setlike.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/setlike.rsindex afab417ca60..43f1685e405 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/setlike.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/setlike.rs@@ -9,7 +9,7 @@use core::cell::RefCell;use libjs_rust::api::{- Attribute, ErrorKind, ErrorType, Gc, GcWeak, Object, PropertyAttributes, PropertyKey, PropertyKind,+ Attribute, ErrorKind, ErrorType, Gc, GcWeak, MarkedVec, Object, PropertyAttributes, PropertyKey, PropertyKind,RawNativeFunctionPointer, Realm, Set, SetIterator, ThrowCompletionOr, Trace, Value, Vm, call,};@@ -55,13 +55,18 @@ impl<T> WorldEntries<T> {entries}- /// The live collections, which the caller updates when the object changes.- pub(crate) fn live(&self) -> Vec<Gc<T>> {- self.entries- .borrow()- .iter()- .filter_map(|(_, entries)| entries.get())- .collect()+ /// Calls back with each live collection, for the caller to update when the object changes. The collections stay+ /// alive through the walk, as updating one can allocate and nothing else holds the rest.+ pub(crate) fn for_each_live(&self, vm: &Vm, mut callback: impl FnMut(Gc<T>)) {+ let live = MarkedVec::new(vm);+ for (_, entries) in self.entries.borrow().iter() {+ if let Some(entries) = entries.get() {+ live.push(entries);+ }+ }+ for entries in live.values().iter() {+ callback(*entries);+ }}}@@ -69,6 +74,13 @@ impl<T> WorldEntries<T> {pub(crate) trait Setlike: Interface {// https://webidl.spec.whatwg.org/#dfn-set-entriesfn set_entries(&self, cx: &CallContext) -> Gc<Set>;++ /// The size of the set entries, without creating them and the wrappers they hold.+ fn set_entries_size(&self) -> usize;++ /// Whether the set entries contain the value, which the bindings checked against the value type, without creating+ /// them and the wrappers they hold.+ fn set_entries_contain(&self, value: Value) -> bool;}/// What the implementation of an interface with a read-write setlike declaration implements, for the operations that@@ -119,13 +131,12 @@ pub(crate) fn context_of_set<'vm>(cx: &CallContext<'vm>, set: Gc<Set>) -> CallCo// https://webidl.spec.whatwg.org/#js-set-sizepub(crate) fn set_size<T: Setlike>(vm: &Vm) -> ThrowCompletionOr<Value> {// 1. Let O be the this value, implementation-checked against A with identifier "size" and type "getter".- let (_, implementation, cx) = this_implementation::<T>(vm)?;+ let (_, implementation, _) = this_implementation::<T>(vm)?;// 2. Let set be the set entries of the IDL value that represents a reference to O.- let set = implementation.set_entries(&cx);-// 3. Return set's size, converted to a JavaScript value.- Ok(Value::from_f64(set.set_size() as f64))+ // OPTIMIZATION: The implementation knows the size without creating the set entries.+ Ok(Value::from_f64(implementation.set_entries_size() as f64))}fn create_set_iterator<T: Setlike>(vm: &Vm, kind: PropertyKind) -> ThrowCompletionOr<Value> {@@ -188,11 +199,9 @@ pub(crate) fn set_for_each<T: Setlike>(vm: &Vm) -> ThrowCompletionOr<Value> {// https://webidl.spec.whatwg.org/#js-set-haspub(crate) fn set_has<T: SetlikeDeclaration>(vm: &Vm) -> ThrowCompletionOr<Value> {// 1. Let O be the this value, implementation-checked against A with identifier "has" and type "method".- let (_, implementation, cx) = this_implementation::<T>(vm)?;+ let (_, implementation, _) = this_implementation::<T>(vm)?;// 2. Let set be the set entries of the IDL value that represents a reference to O.- let set = implementation.set_entries(&cx);-// 3. Let valueType be the value type specified in the setlike declaration.// 4. Let valueArg be the first argument passed to this function, or undefined if not supplied.// 5. Let value be valueArg converted to an IDL value of type valueType.@@ -200,7 +209,8 @@ pub(crate) fn set_has<T: SetlikeDeclaration>(vm: &Vm) -> ThrowCompletionOr<ValueT::check_value(vm, value)?;// 7. If set contains value, then return true, otherwise return false.- Ok(Value::from_bool(set.set_has(value)))+ // OPTIMIZATION: The implementation looks for the value without creating the set entries.+ Ok(Value::from_bool(implementation.set_entries_contain(value)))}// https://webidl.spec.whatwg.org/#js-set-adddiff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_font_feature_values_map.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_font_feature_values_map.rsindex db9cf27546c..fdb35dcdf71 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_font_feature_values_map.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_font_feature_values_map.rs@@ -8,7 +8,7 @@//! CSSFontFeatureValuesMap, https://drafts.csswg.org/css-fonts-4/#cssfontfeaturevaluesmapuse ak::Utf16String;-use libjs_rust::api::{Array, Gc, Map, Object, Trace, Value, Vm};+use libjs_rust::api::{Array, Gc, Map, MarkedVec, Object, Trace, Value, Vm};use libweb_rust::FontFeatureValuesRuleKind;use super::css_font_feature_values_rule::CSSFontFeatureValuesRule;@@ -23,8 +23,11 @@ use crate::bindings::{CallContext, Exception, WebIdlResult};use crate::notifications_api::notification::VibratePattern;fn create_map_value(cx: &CallContext, values: &[u32]) -> Value {- let values: Vec<Value> = values.iter().map(|value| Value::from_f64(f64::from(*value))).collect();- Value::from_object(Array::create_from(cx.vm(), cx.realm(), &values).upcast::<Object>())+ let list = MarkedVec::with_capacity(cx.vm(), values.len());+ for value in values {+ list.push(Value::from_f64(f64::from(*value)));+ }+ Value::from_object(Array::create_from(cx.vm(), cx.realm(), &list.values()).upcast::<Object>())}fn set_map_entry(cx: &CallContext, map: Gc<Map>, name: &Utf16String, values: &[u32]) {@@ -117,9 +120,9 @@ impl CSSFontFeatureValuesMap {values.clone(),);self.parent_rule.clear_caches();- for map in self.map_entries.live() {+ self.map_entries.for_each_live(cx.vm(), |map| {set_map_entry(&context_of_map(cx, map), map, &feature_value_name, &values);- }+ });Ok(())}}@@ -158,10 +161,10 @@ impl WritableMaplike for CSSFontFeatureValuesMap {.remove_font_feature_value(self.kind, &key.to_utf16());if removed {self.parent_rule.clear_caches();- for map in self.map_entries.live() {+ self.map_entries.for_each_live(cx.vm(), |map| {let key = key.clone().to_js(cx).expect("a string converts to a JS value");map.map_remove(cx.vm(), key);- }+ });}removed}@@ -172,8 +175,8 @@ impl WritableMaplike for CSSFontFeatureValuesMap {.native_rule().clear_font_feature_values(self.kind);self.parent_rule.clear_caches();- for map in self.map_entries.live() {+ self.map_entries.for_each_live(cx.vm(), |map| {map.map_clear(cx.vm());- }+ });}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rsindex cd3d3ac3e22..8b02a221b33 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs@@ -47,7 +47,7 @@ use super::css_numeric_value::AnyCSSNumericValue;use super::css_page_rule::CSSPageRule;use super::css_position_try_rule::CSSPositionTryRule;use super::css_property_rule::CSSPropertyRule;-use super::css_rule::{AnyCSSRule, wrap_cpp_cell};+use super::css_rule::AnyCSSRule;use super::css_rule_list::CSSRuleList;use super::css_scope_rule::CSSScopeRule;use super::css_style_rule::CSSStyleRule;@@ -57,7 +57,7 @@ use super::css_supports_rule::CSSSupportsRule;use super::css_transform_value::CSSTransformValue;use super::css_unit_value::CSSUnitValue;use super::css_unparsed_value::CSSUnparsedValue;-use super::font_face_set_load_event::{FontFaceSetLoadEvent, FontFaceSetLoadEventInit};+use super::font_face_set::{CppFontFaceState, FontFaceSet};use super::highlight_registry::HighlightRegistry;use super::media_list::MediaList;use super::media_query_list::MediaQueryList;@@ -68,10 +68,10 @@ use super::style_sheet_list::StyleSheetList;use super::transition_event::{TransitionEvent, TransitionEventInit};use super::typed_om;use super::visual_viewport::VisualViewport;+use crate::bindings::Exception;use crate::bindings::conversions::CppInterface;use crate::bindings::cpp_cell::CppCell;use crate::bindings::interface::{Ref, allocate, cell_from_abi, cell_if_abi, cell_into_abi, realm_arguments};-use crate::bindings::{CallContext, Exception};use crate::dom::event::EventInit;/// # Safety@@ -503,43 +503,150 @@ pub unsafe extern "C" fn web_media_query_list_evaluate_and_report_change(vm: *mulist.evaluate_and_report_change(vm);}-/// A new FontFaceSetLoadEvent with the name, as the Event that C++ dispatches, whose fontfaces attribute holds the-/// FontFace objects that C++ passes.+/// A new FontFaceSet of the environment settings object.////// # Safety///-/// `vm` must be the live VM, `realm` a live realm, `name` a raw string that C++ hands over, and `font_faces` must point-/// to `count` live FontFace objects.+/// `vm` must be the live VM, `realm` a live realm, and `environment` a live environment settings object.#[unsafe(no_mangle)]-pub unsafe extern "C" fn web_font_face_set_load_event_create(+pub unsafe extern "C" fn web_font_face_set_create(vm: *mut c_void,realm: *mut c_void,- name: usize,- font_faces: *const *mut c_void,- count: usize,+ environment: *mut c_void,) -> *mut c_void {- // SAFETY: The caller passes the live VM, a live realm and a raw string that it hands over.- let ((vm, realm), name) = unsafe { (realm_arguments(vm, realm), Utf16String::from_raw_owned(name)) };- let cx = CallContext::new(vm, realm);- let fontfaces = MarkedVec::with_capacity(vm, count);- // SAFETY: The caller passes `count` live FontFace objects.- for font_face in unsafe { ak::slice_from_raw_parts(font_faces, count) } {- // SAFETY: The caller passes live FontFace objects.- fontfaces.push(wrap_cpp_cell(&cx, &unsafe { CppCell::from_raw(*font_face) }));- }- let event_init = FontFaceSetLoadEventInit {- parent: EventInit {- bubbles: false,- cancelable: false,- composed: false,- },- fontfaces,+ // SAFETY: The caller passes the live VM, a live realm and a live environment settings object.+ let (vm, realm, environment) = unsafe {+ let (vm, realm) = realm_arguments(vm, realm);+ (vm, realm, CppCell::from_raw(environment))};- FontFaceSetLoadEvent::create(vm, realm, &name, event_init)- .event()+ cell_into_abi(FontFaceSet::create(vm, realm, environment))+}++/// # Safety+///+/// `set` must be a live FontFaceSet.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_font_face_set_size(set: *mut c_void) -> usize {+ // SAFETY: The caller passes a live FontFaceSet.+ unsafe { cell_from_abi::<FontFaceSet>(set) }.size()+}++/// # Safety+///+/// `set` must be a live FontFaceSet.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_font_face_set_relevant_settings_object(set: *mut c_void) -> *mut c_void {+ // SAFETY: The caller passes a live FontFaceSet.+ unsafe { cell_from_abi::<FontFaceSet>(set) }+ .relevant_settings_object().as_ptr()}+/// # Safety+///+/// `vm` must be the live VM, `set` a live FontFaceSet, and `font_face` a live FontFaceState.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_font_face_set_add_css_connected_font(+ vm: *mut c_void,+ set: *mut c_void,+ font_face: *mut c_void,+) {+ // SAFETY: The caller passes the live VM, a live FontFaceSet and a live FontFaceState.+ let (vm, set, font_face) = unsafe {+ (+ vm_from_abi(vm),+ cell_from_abi::<FontFaceSet>(set),+ CppFontFaceState::from_raw(font_face),+ )+ };+ set.add_css_connected_font(vm, font_face);+}++/// # Safety+///+/// `vm` must be the live VM, `set` a live FontFaceSet, and `font_face` a live FontFaceState.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_font_face_set_remove_css_connected_font(+ vm: *mut c_void,+ set: *mut c_void,+ font_face: *mut c_void,+) {+ // SAFETY: The caller passes the live VM, a live FontFaceSet and a live FontFaceState.+ let (vm, set, font_face) = unsafe {+ (+ vm_from_abi(vm),+ cell_from_abi::<FontFaceSet>(set),+ CppFontFaceState::from_raw(font_face),+ )+ };+ set.remove_css_connected_font(vm, &font_face);+}++/// # Safety+///+/// `vm` must be the live VM, and `set` a live FontFaceSet.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_font_face_set_synchronize_css_connected_font_order(vm: *mut c_void, set: *mut c_void) {+ // SAFETY: The caller passes the live VM and a live FontFaceSet.+ let (vm, set) = unsafe { (vm_from_abi(vm), cell_from_abi::<FontFaceSet>(set)) };+ set.synchronize_css_connected_font_order(vm);+}++/// # Safety+///+/// `vm` must be the live VM, and `set` a live FontFaceSet.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_font_face_set_set_is_pending_on_the_environment(+ vm: *mut c_void,+ set: *mut c_void,+ is_pending_on_the_environment: bool,+) {+ // SAFETY: The caller passes the live VM and a live FontFaceSet.+ let (vm, set) = unsafe { (vm_from_abi(vm), cell_from_abi::<FontFaceSet>(set)) };+ set.set_is_pending_on_the_environment(vm, is_pending_on_the_environment);+}++/// # Safety+///+/// `vm` must be the live VM, `set` a live FontFaceSet, and `font_face` a live FontFaceState.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_font_face_set_font_started_loading(+ vm: *mut c_void,+ set: *mut c_void,+ font_face: *mut c_void,+) {+ // SAFETY: The caller passes the live VM, a live FontFaceSet and a live FontFaceState.+ let (vm, set, font_face) = unsafe {+ (+ vm_from_abi(vm),+ cell_from_abi::<FontFaceSet>(set),+ CppFontFaceState::from_raw(font_face),+ )+ };+ set.font_started_loading(vm, font_face);+}++/// # Safety+///+/// `vm` must be the live VM, `set` a live FontFaceSet, and `font_face` a live FontFaceState.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_font_face_set_font_finished_loading(+ vm: *mut c_void,+ set: *mut c_void,+ font_face: *mut c_void,+ succeeded: bool,+) {+ // SAFETY: The caller passes the live VM, a live FontFaceSet and a live FontFaceState.+ let (vm, set, font_face) = unsafe {+ (+ vm_from_abi(vm),+ cell_from_abi::<FontFaceSet>(set),+ CppFontFaceState::from_raw(font_face),+ )+ };+ set.font_finished_loading(vm, font_face, succeeded);+}+/// A new HighlightRegistry of the document.////// # Safetydiff --git a/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs b/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rsnew file mode 100644index 00000000000..75fdbacb2b5--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs@@ -0,0 +1,857 @@+/*+ * Copyright (c) 2024, Andrew Kaster <[email protected]>+ * Copyright (c) 2024, Jamie Mansfield <[email protected]>+ * Copyright (c) 2026, Sam Atkins <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! FontFaceSet, https://drafts.csswg.org/css-font-loading/#fontfaceset++use core::cell::Cell;+use core::ffi::c_void;+use core::ptr::NonNull;+use std::collections::{HashMap, HashSet};++use ak::Utf16String;+use libjs_rust::api::{+ Array, Gc, GcRefCell, MarkedVec, Must, Object, PrimitiveString, PropertyKey, Realm, Set, Trace, Value, Visitor, Vm,+ length_of_array_like,+};+use libweb_rust::typed_om::font_family_names;++use super::css_rule::wrap_cpp_cell;+use super::font_face_set_load_event::FontFaceSetLoadEvent;+use crate::bindings::conversions::{CppInterface, ToJs};+use crate::bindings::cpp_cell::CppCell;+use crate::bindings::event_target::{CppEventTarget, GetTheParent};+use crate::bindings::interface::{+ Ref, Wrappable, allocate, cell_into_abi, with_temporary_execution_context,+ with_temporary_execution_context_and_callbacks,+};+use crate::bindings::promise::{+ TaskSource, WebIdlPromise, create_promise, get_promise_for_wait_for_all, in_parallel, is_promise_fulfilled,+ promise_from_abi, queue_a_task, react_to_promise, reject_promise, reject_promise_with_exception, resolve_promise,+};+use crate::bindings::setlike::context_of_set;+use crate::bindings::setlike::{Setlike, WorldEntries};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::dom::event::EventInit;++unsafe extern "C" {+ fn web_css_font_face_of_wrapper(wrapper: *mut c_void) -> *mut c_void;+ fn web_css_font_face_ref(font_face: *mut c_void);+ fn web_css_font_face_unref(font_face: *mut c_void);+ fn web_css_font_face_visit_edges(font_face: *mut c_void, visitor: *mut c_void);+ fn web_css_font_face_cssom_font_face(font_face: *mut c_void) -> *mut c_void;+ fn web_css_font_face_is_css_connected(font_face: *mut c_void) -> bool;+ fn web_css_font_face_css_rule_identity(font_face: *mut c_void, identity: *mut u64) -> bool;+ fn web_css_font_face_is_loading(font_face: *mut c_void) -> bool;+ fn web_css_font_face_is_loaded(font_face: *mut c_void) -> bool;+ fn web_css_font_face_family_name(font_face: *mut c_void) -> usize;+ fn web_css_font_face_unicode_ranges_include_any_of(font_face: *mut c_void, text: usize) -> bool;+ fn web_css_font_face_load(font_face: *mut c_void) -> *mut c_void;+ fn web_css_font_face_did_join_set(font_face: *mut c_void, set: *mut c_void);+ fn web_css_font_face_did_leave_set(font_face: *mut c_void, set: *mut c_void);+ fn web_css_font_face_set_record_loading_fonts(set: *mut c_void, count: usize);+ fn web_css_font_face_set_update_layout(set: *mut c_void, skip_if_running: bool);+ fn web_css_font_face_set_for_each_font_face_rule(+ set: *mut c_void,+ context: *mut c_void,+ callback: unsafe extern "C" fn(*mut c_void, u64),+ ) -> bool;+ fn web_css_font_face_set_synchronize_font_computer(set: *mut c_void, font_faces: *const *mut c_void, count: usize);+}++/// The enumeration FontFaceSetLoadStatus of CSS/FontFaceSet.idl.+#[derive(Clone, Copy, Eq, PartialEq)]+pub(crate) enum FontFaceSetLoadStatus {+ Loading,+ Loaded,+}++/// The reference-counted state of a font face, which LibWeb implements in C++. The FontFace object that script sees is+/// only made from it when something wraps it.+pub(crate) struct CppFontFaceState(NonNull<c_void>);++impl Clone for CppFontFaceState {+ fn clone(&self) -> Self {+ // SAFETY: This holds a reference, so the state is live.+ unsafe { Self::from_raw(self.as_ptr()) }+ }+}++impl Drop for CppFontFaceState {+ fn drop(&mut self) {+ // SAFETY: This holds a reference.+ unsafe { web_css_font_face_unref(self.as_ptr()) };+ }+}++// SAFETY: The state visits every cell it can reach.+unsafe impl Trace for CppFontFaceState {+ fn trace(&self, visitor: &mut Visitor) {+ // SAFETY: This holds a reference, and the visitor is live.+ unsafe { web_css_font_face_visit_edges(self.as_ptr(), visitor.as_raw().cast()) };+ }+}++impl CppFontFaceState {+ /// # Safety+ ///+ /// `font_face` must be a live FontFaceState, which this takes a reference to.+ pub(crate) unsafe fn from_raw(font_face: *mut c_void) -> Self {+ let font_face = NonNull::new(font_face).expect("C++ passes a font face");+ // SAFETY: The caller passes a live state.+ unsafe { web_css_font_face_ref(font_face.as_ptr()) };+ Self(font_face)+ }++ pub(crate) fn of_wrapper(wrapper: Gc<Object>) -> Self {+ // SAFETY: The caller passes a wrapper of a FontFace, whose state is live.+ unsafe { Self::from_raw(web_css_font_face_of_wrapper(wrapper.as_ptr().cast())) }+ }++ fn as_ptr(&self) -> *mut c_void {+ self.0.as_ptr()+ }++ fn is(&self, other: &Self) -> bool {+ self.as_ptr() == other.as_ptr()+ }++ pub(crate) fn interface(&self, cx: &CallContext) -> CppInterface {+ // SAFETY: This holds a reference, and LibWeb returns a live FontFace.+ let font_face = unsafe { CppCell::from_raw(web_css_font_face_cssom_font_face(self.as_ptr())) };+ wrap_cpp_cell(cx, &font_face)+ }++ fn wrapper(&self, cx: &CallContext) -> Value {+ Value::from_object(self.interface(cx).wrapper())+ }++ fn is_css_connected(&self) -> bool {+ // SAFETY: The FontFace is live.+ unsafe { web_css_font_face_is_css_connected(self.as_ptr()) }+ }++ fn css_rule_identity(&self) -> Option<u64> {+ let mut identity = 0;+ // SAFETY: The FontFace is live, and the identity outlives the call.+ unsafe { web_css_font_face_css_rule_identity(self.as_ptr(), &raw mut identity) }.then_some(identity)+ }++ fn is_loading(&self) -> bool {+ // SAFETY: The FontFace is live.+ unsafe { web_css_font_face_is_loading(self.as_ptr()) }+ }++ fn is_loaded(&self) -> bool {+ // SAFETY: The FontFace is live.+ unsafe { web_css_font_face_is_loaded(self.as_ptr()) }+ }++ fn family_name(&self) -> Utf16String {+ // SAFETY: The FontFace is live, and LibWeb hands over the string.+ unsafe { Utf16String::from_raw_owned(web_css_font_face_family_name(self.as_ptr())) }+ }++ fn unicode_ranges_include_any_of(&self, text: &Utf16String) -> bool {+ // SAFETY: The FontFace is live, and this hands over a reference to the string.+ unsafe { web_css_font_face_unicode_ranges_include_any_of(self.as_ptr(), text.clone().into_raw()) }+ }++ /// Calls load() on the FontFace, and returns its [[FontStatusPromise]].+ fn load(&self) -> WebIdlPromise {+ // SAFETY: The FontFace is live, and LibWeb returns a live promise.+ unsafe { promise_from_abi(web_css_font_face_load(self.as_ptr())) }+ }+}++fn contains(font_faces: &[CppFontFaceState], font_face: &CppFontFaceState) -> bool {+ font_faces.iter().any(|entry| entry.is(font_face))+}++fn take_font_faces<'vm>(vm: &'vm Vm, list: &GcRefCell<Vec<CppFontFaceState>>) -> MarkedVec<'vm, CppFontFaceState> {+ let font_faces = MarkedVec::with_capacity(vm, list.borrow().len());+ font_faces.extend_from_slice(&list.borrow());+ list.borrow_mut(vm).clear();+ font_faces+}++// https://drafts.csswg.org/css-font-loading/#fontfaceset+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct FontFaceSet {+ event_target: CppEventTarget,+ realm: Gc<Realm>,+ environment: CppCell,+ this: Cell<Option<Ref<FontFaceSet>>>,++ /// The set entries of this setlike object, in insertion order.+ font_faces: GcRefCell<Vec<CppFontFaceState>>,+ set_entries: WorldEntries<Set>,++ ready_promise: Cell<Option<WebIdlPromise>>, // [[ReadyPromise]]+ loading_fonts: GcRefCell<Vec<CppFontFaceState>>, // [[LoadingFonts]]+ loaded_fonts: GcRefCell<Vec<CppFontFaceState>>, // [[LoadedFonts]]+ failed_fonts: GcRefCell<Vec<CppFontFaceState>>, // [[FailedFonts]]++ #[gc(untraced)]+ status: Cell<FontFaceSetLoadStatus>,+ is_pending_on_the_environment: Cell<bool>,+}++impl Wrappable for FontFaceSet {+ fn relevant_realm(&self) -> Option<Gc<Realm>> {+ Some(self.realm)+ }++ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event_target.as_cpp_parent()+ }+}++impl GetTheParent for FontFaceSet {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ None+ }+}++impl FontFaceSet {+ pub(crate) fn create(vm: &Vm, realm: Gc<Realm>, environment: CppCell) -> Ref<Self> {+ let object = allocate(vm, |_| FontFaceSet {+ event_target: CppEventTarget::new(),+ realm,+ environment,+ this: Cell::new(None),+ font_faces: GcRefCell::new(Vec::new()),+ set_entries: WorldEntries::default(),+ ready_promise: Cell::new(None),+ loading_fonts: GcRefCell::new(Vec::new()),+ loaded_fonts: GcRefCell::new(Vec::new()),+ failed_fonts: GcRefCell::new(Vec::new()),+ status: Cell::new(FontFaceSetLoadStatus::Loaded),+ is_pending_on_the_environment: Cell::new(true),+ });+ object.this.set(Some(object));+ object.event_target.set_owner(object);+ object+ .ready_promise+ .set(Some(with_temporary_execution_context(realm, || {+ create_promise(vm, realm)+ })));+ object+ }++ fn this(&self) -> Ref<Self> {+ self.this.get().expect("a FontFaceSet knows itself once it is created")+ }++ fn as_abi(&self) -> *mut c_void {+ cell_into_abi(self.this())+ }++ fn ready_promise(&self) -> WebIdlPromise {+ self.ready_promise.get().expect("a FontFaceSet has a [[ReadyPromise]]")+ }++ pub(crate) fn relevant_settings_object(&self) -> &CppCell {+ &self.environment+ }++ pub(crate) fn size(&self) -> usize {+ self.font_faces.borrow().len()+ }++ fn did_change_loading_fonts(&self) {+ // SAFETY: The set is live.+ unsafe { web_css_font_face_set_record_loading_fonts(self.as_abi(), self.loading_fonts.borrow().len()) };+ }++ fn entries<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, CppFontFaceState> {+ let entries = MarkedVec::with_capacity(vm, self.font_faces.borrow().len());+ entries.extend_from_slice(&self.font_faces.borrow());+ entries+ }++ // https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-add+ pub(crate) fn add(&self, cx: &mut CallContext, font: CppInterface) -> WebIdlResult<Ref<FontFaceSet>> {+ let font = CppFontFaceState::of_wrapper(font.wrapper());++ // 1. If font is already in the FontFaceSet’s set entries, skip to the last step of this algorithm immediately.+ if contains(&self.font_faces.borrow(), &font) {+ return Ok(self.this());+ }++ // 2. If font is CSS-connected, throw an InvalidModificationError exception and exit this algorithm immediately.+ if font.is_css_connected() {+ return Err(Exception::Dom(+ "InvalidModificationError",+ Utf16String::from_ascii(b"Cannot add a CSS-connected FontFace to a FontFaceSet"),+ ));+ }++ // NB: This method implements steps 3 and 4.+ self.add_css_connected_font(cx.vm(), font);++ // 5. Return the FontFaceSet.+ Ok(self.this())+ }++ // https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-add+ pub(crate) fn add_css_connected_font(&self, vm: &Vm, font: CppFontFaceState) {+ // 3. Add the font argument to the FontFaceSet’s set entries.+ if contains(&self.font_faces.borrow(), &font) {+ return;+ }++ self.font_faces.borrow_mut(vm).push(font.clone());+ let cx = CallContext::new(vm, self.realm);+ self.set_entries.for_each_live(vm, |set| {+ set.set_add(vm, font.wrapper(&context_of_set(&cx, set)));+ });+ // SAFETY: The FontFace and the set are live.+ unsafe { web_css_font_face_did_join_set(font.as_ptr(), self.as_abi()) };++ // 4. If font’s status attribute is "loading"+ if font.is_loading() {+ self.font_started_loading(vm, font);+ }+ }++ /// Removes the font face of a CSS @font-face rule from the set entries.+ pub(crate) fn remove_css_connected_font(&self, vm: &Vm, font: &CppFontFaceState) {+ self.remove_font_face(vm, font, AllowCSSConnected::Yes);+ }++ /// What every FontFaceSet does when a font in it starts to load, or when a font that is loading joins it.+ pub(crate) fn font_started_loading(&self, vm: &Vm, font: CppFontFaceState) {+ // 1. If the FontFaceSet’s [[LoadingFonts]] list is empty, switch the FontFaceSet to loading.+ if self.loading_fonts.borrow().is_empty() {+ self.switch_to_loading(vm);+ }++ // 2. Append font to the FontFaceSet’s [[LoadingFonts]] list.+ self.loading_fonts.borrow_mut(vm).push(font);+ self.did_change_loading_fonts();+ }++ /// What every FontFaceSet does when a font in it loaded, or failed to.+ pub(crate) fn font_finished_loading(&self, vm: &Vm, font: CppFontFaceState, succeeded: bool) {+ // 1. Add font face to the FontFaceSet’s [[LoadedFonts]] list, or to its [[FailedFonts]] list.+ let list = if succeeded {+ &self.loaded_fonts+ } else {+ &self.failed_fonts+ };+ list.borrow_mut(vm).push(font.clone());++ // 2. Remove font face from the FontFaceSet’s [[LoadingFonts]] list. If font was the last item in that list+ // (and so the list is now empty), switch the FontFaceSet to loaded.+ self.loading_fonts.borrow_mut(vm).retain(|entry| !entry.is(&font));+ self.did_change_loading_fonts();+ if self.loading_fonts.borrow().is_empty() {+ self.switch_to_loaded(vm);+ }+ }++ // https://drafts.csswg.org/css-font-loading/#document-font-face-set+ // The FontFaceSet entries for a document's font source must be initially populated with all the CSS-connected+ // FontFace objects from all of the CSS @font-face rules in the document or shadow root CSS style sheets, in+ // document order. As @font-face rules are added or removed, the corresponding objects must be added or removed and+ // maintain this ordering. Any manually-added FontFace objects must be ordered after the CSS-connected ones.+ pub(crate) fn synchronize_css_connected_font_order(&self, vm: &Vm) {+ unsafe extern "C" fn append_identity(context: *mut c_void, identity: u64) {+ // SAFETY: The context is the list below, which outlives the call.+ unsafe { &mut *context.cast::<Vec<u64>>() }.push(identity);+ }++ let font_faces = self.entries(vm);+ let font_faces = font_faces.values();+ let mut connected_font_faces = HashMap::new();+ for (index, font_face) in font_faces.iter().enumerate() {+ if let Some(identity) = font_face.css_rule_identity() {+ connected_font_faces.insert(identity, index);+ }+ }++ // Every sheet added or removed asks again. Without a face from a rule the walk over their rules finds nothing.+ let mut rule_identities = Vec::new();+ if !connected_font_faces.is_empty() {+ // SAFETY: The set is live, and the list outlives the call.+ let has_window = unsafe {+ web_css_font_face_set_for_each_font_face_rule(+ self.as_abi(),+ (&raw mut rule_identities).cast(),+ append_identity,+ )+ };+ if !has_window {+ return;+ }+ }++ let ordered_font_faces = MarkedVec::with_capacity(vm, font_faces.len());+ let mut seen = HashSet::new();+ for identity in rule_identities {+ if let Some(index) = connected_font_faces.get(&identity)+ && seen.insert(font_faces[*index].as_ptr())+ {+ ordered_font_faces.push(font_faces[*index].clone());+ }+ }+ for font_face in font_faces.iter() {+ if font_face.is_css_connected() && seen.insert(font_face.as_ptr()) {+ ordered_font_faces.push(font_face.clone());+ }+ }+ for font_face in font_faces.iter() {+ if !font_face.is_css_connected() {+ ordered_font_faces.push(font_face.clone());+ }+ }++ let order_changed = ordered_font_faces.len() != font_faces.len()+ || ordered_font_faces+ .values()+ .iter()+ .zip(font_faces.iter())+ .any(|(ordered, entry)| !ordered.is(entry));+ if !order_changed {+ return;+ }++ *self.font_faces.borrow_mut(vm) = ordered_font_faces.to_vec();+ let cx = CallContext::new(vm, self.realm);+ self.set_entries.for_each_live(vm, |set| {+ set.set_clear(vm);+ let cx = context_of_set(&cx, set);+ for font_face in ordered_font_faces.values().iter() {+ set.set_add(vm, font_face.wrapper(&cx));+ }+ });+ let cells: Vec<*mut c_void> = ordered_font_faces+ .values()+ .iter()+ .map(CppFontFaceState::as_ptr)+ .collect();+ // SAFETY: The set and the FontFaces are live, and the list outlives the call.+ unsafe { web_css_font_face_set_synchronize_font_computer(self.as_abi(), cells.as_ptr(), cells.len()) };+ }++ // https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-delete+ pub(crate) fn delete(&self, cx: &mut CallContext, font: CppInterface) -> WebIdlResult<bool> {+ let font = CppFontFaceState::of_wrapper(font.wrapper());+ Ok(self.remove_font_face(cx.vm(), &font, AllowCSSConnected::No))+ }++ fn remove_font_face(&self, vm: &Vm, font: &CppFontFaceState, allow_css_connected: AllowCSSConnected) -> bool {+ // 1. If font is CSS-connected, return false and exit this algorithm immediately.+ if allow_css_connected == AllowCSSConnected::No && font.is_css_connected() {+ return false;+ }++ // 2. Let deleted be the result of removing font from the FontFaceSet’s set entries.+ if !contains(&self.font_faces.borrow(), font) {+ return false;+ }+ self.font_faces.borrow_mut(vm).retain(|entry| !entry.is(font));+ self.did_remove_from_set_entries(vm, font);++ // 3. If font is present in the FontFaceSet’s [[LoadedFonts]], or [[FailedFonts]] lists, remove it.+ self.loaded_fonts.borrow_mut(vm).retain(|entry| !entry.is(font));+ self.failed_fonts.borrow_mut(vm).retain(|entry| !entry.is(font));++ // 4. If font is present in the FontFaceSet’s [[LoadingFonts]] list, remove it.+ // If font was the last item in that list (and so the list is now empty), switch the FontFaceSet to loaded.+ let was_in_loading_fonts = contains(&self.loading_fonts.borrow(), font);+ self.loading_fonts.borrow_mut(vm).retain(|entry| !entry.is(font));+ self.did_change_loading_fonts();+ if was_in_loading_fonts && self.loading_fonts.borrow().is_empty() {+ self.switch_to_loaded(vm);+ }++ true+ }++ fn did_remove_from_set_entries(&self, vm: &Vm, font: &CppFontFaceState) {+ let cx = CallContext::new(vm, self.realm);+ self.set_entries.for_each_live(vm, |set| {+ set.set_remove(vm, font.wrapper(&context_of_set(&cx, set)));+ });+ // SAFETY: The FontFace and the set are live.+ unsafe { web_css_font_face_did_leave_set(font.as_ptr(), self.as_abi()) };+ }++ // https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-clear+ pub(crate) fn clear(&self, cx: &mut CallContext) -> WebIdlResult<()> {+ let vm = cx.vm();++ // 1. Remove all non-CSS-connected items from the FontFaceSet's set entries,+ // its [[LoadedFonts]] list, and its [[FailedFonts]] list.+ for font_face in self+ .entries(vm)+ .values()+ .iter()+ .filter(|font_face| !font_face.is_css_connected())+ {+ self.did_remove_from_set_entries(vm, font_face);+ }+ self.font_faces+ .borrow_mut(vm)+ .retain(CppFontFaceState::is_css_connected);+ self.loaded_fonts+ .borrow_mut(vm)+ .retain(CppFontFaceState::is_css_connected);+ self.failed_fonts+ .borrow_mut(vm)+ .retain(CppFontFaceState::is_css_connected);++ // 2. If the FontFaceSet's [[LoadingFonts]] list is non-empty, remove all items from it,+ // then switch the FontFaceSet to loaded.+ if !self.loading_fonts.borrow().is_empty() {+ self.loading_fonts.borrow_mut(vm).clear();+ self.did_change_loading_fonts();+ self.switch_to_loaded(vm);+ }+ Ok(())+ }++ // https://drafts.csswg.org/css-font-loading/#find-the-matching-font-faces+ fn find_matching_font_faces<'vm>(+ &self,+ vm: &'vm Vm,+ font: &Utf16String,+ text: &Utf16String,+ ) -> WebIdlResult<MarkedVec<'vm, CppFontFaceState>> {+ // 1. Parse font using the CSS value syntax of the font property. If a syntax error occurs, return a syntax+ // error.+ // If the parsed value is a CSS-wide keyword, return a syntax error.+ // Note: This case is already caught by font_family_names().++ // FIXME: Absolutize all relative lengths against the initial values of the corresponding properties. (For+ // example, a relative font weight like bolder is evaluated against the initial value normal.)++ // FIXME: 2. If text was not explicitly provided, let it be a string containing a single space character+ // (U+0020 SPACE).++ // 3. Let font family list be the list of font families parsed from font, and font style be the other font+ // style attributes parsed from font.+ // NB: The generic font family keywords are skipped.+ let Some(font_family_list) = font_family_names(font) else {+ return Err(Exception::Dom(+ "SyntaxError",+ Utf16String::from_ascii(b"Unable to parse font"),+ ));+ };++ // 5. Let matched font faces initially be an empty list.+ let matched_font_faces = MarkedVec::new(vm);++ // 6. For each family in font family list, use the font matching rules to select the font faces from available+ // font faces that match the font style, and add them to matched font faces. The use of the unicodeRange+ // attribute means that this may be more than just a single font face.+ let font_faces = self.entries(vm);+ let font_faces = font_faces.values();+ let family_names: Vec<_> = font_faces.iter().map(CppFontFaceState::family_name).collect();+ for font_family_name in &font_family_list {+ // FIXME: The matching below is super basic. We currently just match font family names by their string value.+ for (font_face, family_name) in font_faces.iter().zip(&family_names) {+ if family_name == font_family_name && !contains(&matched_font_faces.values(), font_face) {+ matched_font_faces.push(font_face.clone());+ }+ }+ }++ // FIXME: 7. If matched font faces is empty, set the found faces flag to false. Otherwise, set it to true.++ // 8. For each font face in matched font faces, if its defined unicode-range does not include the codepoint of+ // at least one character in text, remove it from the list.+ let remaining_font_faces = MarkedVec::with_capacity(vm, matched_font_faces.len());+ for font_face in matched_font_faces.values().iter() {+ if font_face.unicode_ranges_include_any_of(text) {+ remaining_font_faces.push(font_face.clone());+ }+ }++ // 9. Return matched font faces and the found faces flag.+ Ok(remaining_font_faces)+ }++ // https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-load+ pub(crate) fn load(+ &self,+ cx: &mut CallContext,+ font: Utf16String,+ text: Utf16String,+ ) -> WebIdlResult<WebIdlPromise> {+ let vm = cx.vm();+ let realm = self.realm;++ // 1. Let font face set be the FontFaceSet object this method was called on. Let promise be a newly-created+ // promise object.+ let promise = create_promise(vm, realm);++ // NB: What steps capture is copied, so the strings travel as JS strings.+ let font = PrimitiveString::create(vm, font);+ let text = PrimitiveString::create(vm, text);+ in_parallel(+ vm,+ realm,+ (self.this(), promise, font, text),+ |vm, (this, promise, font, text)| {+ let realm = this.realm;++ // 3. Find the matching font faces from font face set using the font and text arguments passed to the+ // function, and let font face list be the return value (ignoring the found faces flag). If a syntax+ // error was returned, reject promise with a SyntaxError exception and terminate these steps.+ let font_face_list = match this.find_matching_font_faces(vm, &font.utf16_string(), &text.utf16_string())+ {+ Ok(font_face_list) => font_face_list,+ Err(exception) => {+ with_temporary_execution_context_and_callbacks(realm, || {+ reject_promise_with_exception(vm, promise, exception);+ });+ return;+ }+ };++ // NB: The list travels as the array that promise is resolved with, of the wrappers of the font faces.+ let cx = CallContext::new(vm, realm);+ let wrappers = MarkedVec::with_capacity(vm, font_face_list.len());+ for font_face in font_face_list.values().iter() {+ wrappers.push(font_face.wrapper(&cx));+ }+ let font_face_list = Array::create_from(vm, realm, &wrappers.to_vec());++ // 4. Queue a task to run the following steps synchronously:+ queue_a_task(+ vm,+ realm,+ TaskSource::FontLoading,+ (realm, promise, font_face_list),+ |vm, (realm, promise, font_face_list)| {+ // 1. For all of the font faces in the font face list, call their load() method.+ let promises = MarkedVec::new(vm);+ let font_face_list_object = font_face_list.upcast::<Object>();+ let length = length_of_array_like(vm, &font_face_list_object).must();+ for index in 0..length {+ let wrapper =+ font_face_list_object.get_without_side_effects(vm, &PropertyKey::from(index as u32));+ promises.push(CppFontFaceState::of_wrapper(wrapper.as_object()).load());+ }++ // 2. Resolve promise with the result of waiting for all of the [[FontStatusPromise]]s of each font+ // face in the font face list, in order.+ with_temporary_execution_context_and_callbacks(realm, || {+ react_to_promise(+ vm,+ get_promise_for_wait_for_all(vm, realm, &promises.values()),+ (promise, font_face_list),+ Some(|cx, (promise, font_face_list), _| {+ resolve_promise(+ cx.vm(),+ promise,+ Value::from_object(font_face_list.upcast::<Object>()),+ );+ Ok(Value::UNDEFINED)+ }),+ Some(|cx, (promise, _), reason| {+ reject_promise(cx.vm(), promise, reason);+ Ok(Value::UNDEFINED)+ }),+ );+ });+ },+ );+ },+ );++ // 2. Return promise. Complete the rest of these steps asynchronously.+ Ok(promise)+ }++ // https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-check+ pub(crate) fn check(&self, cx: &mut CallContext, font: Utf16String, text: Utf16String) -> WebIdlResult<bool> {+ // 1. Let font face set be the FontFaceSet object this method was called on.+ // 2. Find the matching font faces from font face set using the font and text arguments passed to the function,+ // and including system fonts, and let font face list be the returned list of font faces, and found faces be+ // the returned found faces flag. If a syntax error was returned, throw a SyntaxError exception and terminate+ // these steps.+ let font_face_list = self.find_matching_font_faces(cx.vm(), &font, &text)?;++ // 3. If font face list is empty, or all fonts in the font face list either have a status attribute of "loaded"+ // or are system fonts, return true. Otherwise, return false.+ // FIXME: We should check if the font face is a system font here.+ Ok(font_face_list.values().iter().all(CppFontFaceState::is_loaded))+ }++ // https://drafts.csswg.org/css-font-loading/#font-face-set-ready+ pub(crate) fn ready(&self, _: &mut CallContext) -> WebIdlResult<WebIdlPromise> {+ // Pending style or layout changes can start a deferred font load. Flush them before returning an already+ // fulfilled promise so switching the FontFaceSet to loading can replace it with a new pending promise.+ if is_promise_fulfilled(self.ready_promise()) {+ // SAFETY: The set is live.+ unsafe { web_css_font_face_set_update_layout(self.as_abi(), false) };+ }++ Ok(self.ready_promise())+ }++ pub(crate) fn status(&self, _: &mut CallContext) -> WebIdlResult<FontFaceSetLoadStatus> {+ Ok(self.status.get())+ }++ // https://drafts.csswg.org/css-font-loading/#fire-a-font-load-event+ fn fire_a_font_load_event(&self, vm: &Vm, name: &str, font_faces: &MarkedVec<'_, CppFontFaceState>) {+ // To fire a font load event named e at a FontFaceSet target with optional font faces means to fire a simple+ // event named e using the FontFaceSetLoadEvent interface that also meets these conditions:+ // 1. The fontfaces attribute is initialized to the result of filtering font faces to only contain FontFace+ // objects contained in target.+ let fontfaces = MarkedVec::with_capacity(vm, font_faces.len());+ for font_face in font_faces.values().iter() {+ if contains(&self.font_faces.borrow(), font_face) {+ fontfaces.push(font_face.clone());+ }+ }+ let event_init = EventInit {+ bubbles: false,+ cancelable: false,+ composed: false,+ };+ let event = FontFaceSetLoadEvent::create(vm, self.realm, &Utf16String::from_utf8(name), event_init, &fontfaces);+ event.event().set_is_trusted(true);+ self.event_target.dispatch_event(event.event());+ }++ // https://drafts.csswg.org/css-font-loading/#ref-for-fontfaceset-pending-on-the-environment%E2%91%A1+ pub(crate) fn set_is_pending_on_the_environment(&self, vm: &Vm, is_pending_on_the_environment: bool) {+ if is_pending_on_the_environment == self.is_pending_on_the_environment.get() {+ return;+ }+ self.is_pending_on_the_environment.set(is_pending_on_the_environment);++ // Whenever a FontFaceSet goes from pending on the environment to not pending on the environment, the user agent+ // must run the following steps:+ if !is_pending_on_the_environment {+ // 1. If the FontFaceSet is stuck on the environment and its [[LoadingFonts]] list is empty, switch the+ // FontFaceSet to loaded.+ // FIXME: We also need to mark empty FontFaceSets as loaded, so that the [[ReadyPromise]] gets resolved.+ // Spec issue: https://github.com/w3c/csswg-drafts/issues/13538#issuecomment-3933951987+ // AD-HOC: Also switch when nothing has ever entered the LoadingFonts list: an empty set, or a set whose+ // entries all have deferred unicode-ranges that no rendered codepoint matched. Without this the+ // ready promise stays pending forever.+ if self.loading_fonts.borrow().is_empty() {+ self.switch_to_loaded(vm);+ }++ // 2. If the FontFaceSet is stuck on the environment, unmark it as such.+ // NB: The AD-HOC condition above covers being stuck, so nothing records it.+ }+ }++ // https://drafts.csswg.org/css-font-loading/#switch-the-fontfaceset-to-loading+ fn switch_to_loading(&self, vm: &Vm) {+ // 1. Let font face set be the given FontFaceSet.+ // 2. Set the status attribute of font face set to "loading".+ self.status.set(FontFaceSetLoadStatus::Loading);++ // 3. If font face set’s [[ReadyPromise]] slot currently holds a fulfilled promise, replace it with a fresh+ // pending promise.+ if is_promise_fulfilled(self.ready_promise()) {+ let realm = self.realm;+ self.ready_promise.set(Some(with_temporary_execution_context(realm, || {+ create_promise(vm, realm)+ })));+ }++ // 4. Queue a task to fire a font load event named loading at font face set.+ queue_a_task(vm, self.realm, TaskSource::FontLoading, self.this(), |vm, this| {+ this.fire_a_font_load_event(vm, "loading", &MarkedVec::new(vm));+ });+ }++ // https://drafts.csswg.org/css-font-loading/#switch-the-fontfaceset-to-loaded+ fn switch_to_loaded(&self, vm: &Vm) {+ // 1. Let font face set be the given FontFaceSet.+ // 2. If font face set is pending on the environment, mark it as stuck on the environment, and exit this+ // algorithm.+ if self.is_pending_on_the_environment.get() {+ return;+ }++ // NB: Pending style or layout changes can depend on a recently loaded font or start another deferred font load.+ // SAFETY: The set is live.+ unsafe { web_css_font_face_set_update_layout(self.as_abi(), true) };+ if !self.loading_fonts.borrow().is_empty() {+ return;+ }++ // 3. Set font face set’s status attribute to "loaded".+ let was_loading = self.status.get() == FontFaceSetLoadStatus::Loading;+ self.status.set(FontFaceSetLoadStatus::Loaded);++ // 4. Fulfill font face set’s [[ReadyPromise]] attribute’s value with font face set.+ let realm = self.realm;+ with_temporary_execution_context_and_callbacks(realm, || {+ let cx = CallContext::new(vm, realm);+ let value = self.this().to_js(&cx).expect("wrapping a FontFaceSet can't throw");+ resolve_promise(vm, self.ready_promise(), value);+ });++ // AD-HOC: A set that never switched to loading only fulfills its ready promise. Firing loadingdone for it would+ // report a load that never happened.+ if !was_loading {+ return;+ }++ // 5. Queue a task to perform the following steps synchronously:+ queue_a_task(vm, realm, TaskSource::FontLoading, self.this(), |vm, this| {+ // 1. Let loaded fonts be the (possibly empty) contents of font face set’s [[LoadedFonts]] slot.+ // 2. Let failed fonts be the (possibly empty) contents of font face set’s [[FailedFonts]] slot.+ // 3. Reset the [[LoadedFonts]] and [[FailedFonts]] slots to empty lists.+ let loaded_fonts = take_font_faces(vm, &this.loaded_fonts);+ let failed_fonts = take_font_faces(vm, &this.failed_fonts);++ // 4. Fire a font load event named loadingdone at font face set with loaded fonts.+ this.fire_a_font_load_event(vm, "loadingdone", &loaded_fonts);++ // 5. If font face set’s failed fonts is non-empty, fire a font load event named loadingerror at font face+ // set with failed fonts.+ if !failed_fonts.is_empty() {+ this.fire_a_font_load_event(vm, "loadingerror", &failed_fonts);+ }+ });+ }+}++#[derive(Clone, Copy, Eq, PartialEq)]+enum AllowCSSConnected {+ No,+ Yes,+}++impl Setlike for FontFaceSet {+ fn set_entries(&self, cx: &CallContext) -> Gc<Set> {+ self.set_entries.get_or_create(cx, || {+ let set = Set::create(cx.vm(), cx.realm());+ for font_face in self.entries(cx.vm()).values().iter() {+ set.set_add(cx.vm(), font_face.wrapper(cx));+ }+ set+ })+ }++ fn set_entries_size(&self) -> usize {+ self.font_faces.borrow().len()+ }++ fn set_entries_contain(&self, value: Value) -> bool {+ contains(+ &self.font_faces.borrow(),+ &CppFontFaceState::of_wrapper(value.as_object()),+ )+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set_load_event.rs b/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set_load_event.rsindex fe173dd1e74..fd28374d43c 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set_load_event.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set_load_event.rs@@ -17,6 +17,7 @@ use crate::bindings::conversions::CppInterface;use crate::bindings::event_target::CppEvent;use crate::bindings::interface::{Ref, Wrappable, allocate};use crate::bindings::{CallContext, WebIdlResult};+use crate::css::font_face_set::CppFontFaceState;use crate::dom::event::EventInit;/// The dictionary FontFaceSetLoadEventInit of CSS/FontFaceSetLoadEvent.idl.@@ -30,7 +31,7 @@ pub(crate) struct FontFaceSetLoadEventInit<'vm> {#[gc(crate = libjs_rust)]pub(crate) struct FontFaceSetLoadEvent {event: CppEvent,- fontfaces: Vec<CppInterface>,+ fontfaces: Vec<CppFontFaceState>,}impl Wrappable for FontFaceSetLoadEvent {@@ -44,18 +45,19 @@ impl FontFaceSetLoadEvent {vm: &Vm,realm: Gc<Realm>,event_name: &Utf16String,- event_init: FontFaceSetLoadEventInit<'_>,+ event_init: EventInit,+ fontfaces: &MarkedVec<'_, CppFontFaceState>,) -> Ref<FontFaceSetLoadEvent> {let event = CppEvent::create_for_owner(realm,event_name,- event_init.parent.bubbles,- event_init.parent.cancelable,- event_init.parent.composed,+ event_init.bubbles,+ event_init.cancelable,+ event_init.composed,);let object = allocate(vm, |_| FontFaceSetLoadEvent {event,- fontfaces: event_init.fontfaces.to_vec(),+ fontfaces: fontfaces.to_vec(),});object.event.set_owner(object);object@@ -67,7 +69,17 @@ impl FontFaceSetLoadEvent {r#type: Utf16String,event_init_dict: FontFaceSetLoadEventInit<'_>,) -> WebIdlResult<Ref<FontFaceSetLoadEvent>> {- Ok(Self::create(cx.vm(), cx.realm(), &r#type, event_init_dict))+ let fontfaces = MarkedVec::with_capacity(cx.vm(), event_init_dict.fontfaces.len());+ for font_face in event_init_dict.fontfaces.values().iter() {+ fontfaces.push(CppFontFaceState::of_wrapper(font_face.wrapper()));+ }+ Ok(Self::create(+ cx.vm(),+ cx.realm(),+ &r#type,+ event_init_dict.parent,+ &fontfaces,+ ))}pub(crate) fn event(&self) -> &CppEvent {@@ -77,7 +89,9 @@ impl FontFaceSetLoadEvent {// https://drafts.csswg.org/css-font-loading/#dom-fontfacesetloadevent-fontfacespub(crate) fn fontfaces<'vm>(&self, cx: &mut CallContext<'vm>) -> WebIdlResult<MarkedVec<'vm, CppInterface>> {let fontfaces = MarkedVec::with_capacity(cx.vm(), self.fontfaces.len());- fontfaces.extend_from_slice(&self.fontfaces);+ for font_face in &self.fontfaces {+ fontfaces.push(font_face.interface(cx));+ }Ok(fontfaces)}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/highlight.rs b/Libraries/LibWeb/Bindings/Rust/src/css/highlight.rsindex 5e705fe690f..65a765c2a5a 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/highlight.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/highlight.rs@@ -10,7 +10,7 @@ use core::cell::{Cell, RefCell};use core::ffi::c_void;use std::collections::HashSet;-use libjs_rust::api::{Gc, GcRefCell, MarkedVec, Set, Trace, Value};+use libjs_rust::api::{Gc, GcRefCell, MarkedVec, Set, Trace, Value, Vm};use super::css_rule::wrap_cpp_cell;use crate::bindings::conversions::CppInterface;@@ -81,7 +81,7 @@ impl Highlight {// then run the steps for a built-in setlike add function, with highlight as the this value, and rangeArg as// the argument.// NB: highlight has no wrapper yet, so there are no set entries in any world to update.- for range in initial_ranges.to_vec() {+ for range in initial_ranges.values().iter() {highlight.add_range(cx, range_of_value(Value::from_object(range.wrapper())));}@@ -113,8 +113,10 @@ impl Highlight {}/// The ranges of the highlight, in insertion order.- pub(crate) fn ranges(&self) -> Vec<CppCell> {- self.ranges.borrow().clone()+ pub(crate) fn ranges<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, CppCell> {+ let ranges = MarkedVec::new(vm);+ ranges.extend_from_slice(&self.ranges.borrow());+ ranges}fn add_range(&self, cx: &CallContext, range: CppCell) -> bool {@@ -130,12 +132,22 @@ impl Setlike for Highlight {fn set_entries(&self, cx: &CallContext) -> Gc<Set> {self.set_entries.get_or_create(cx, || {let set = Set::create(cx.vm(), cx.realm());- for range in self.ranges() {- set.set_add(cx.vm(), range_wrapper(cx, &range));+ for range in self.ranges(cx.vm()).values().iter() {+ set.set_add(cx.vm(), range_wrapper(cx, range));}set})}++ fn set_entries_size(&self) -> usize {+ self.ranges.borrow().len()+ }++ fn set_entries_contain(&self, value: Value) -> bool {+ self.range_addresses+ .borrow()+ .contains(&(range_of_value(value).as_ptr() as usize))+ }}impl WritableSetlike for Highlight {@@ -144,9 +156,9 @@ impl WritableSetlike for Highlight {if !self.add_range(cx, range.clone()) {return;}- for set in self.set_entries.live() {+ self.set_entries.for_each_live(cx.vm(), |set| {set.set_add(cx.vm(), range_wrapper(&context_of_set(cx, set), &range));- }+ });// FIXME: https://drafts.csswg.org/css-highlight-api-1/#repaint// The addition or removal of a range in a registered custom highlight must cause the user agent to// reevaluate the rendering, and to repaint if appropriate. We do not paint custom highlights yet.@@ -160,17 +172,17 @@ impl WritableSetlike for Highlight {self.ranges.borrow_mut(cx.vm()).retain(|existing| existing.as_ptr() != range.as_ptr());- for set in self.set_entries.live() {+ self.set_entries.for_each_live(cx.vm(), |set| {set.set_remove(cx.vm(), range_wrapper(&context_of_set(cx, set), &range));- }+ });true}fn set_clear(&self, cx: &CallContext) {self.range_addresses.borrow_mut().clear();self.ranges.borrow_mut(cx.vm()).clear();- for set in self.set_entries.live() {+ self.set_entries.for_each_live(cx.vm(), |set| {set.set_clear(cx.vm());- }+ });}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/highlight_registry.rs b/Libraries/LibWeb/Bindings/Rust/src/css/highlight_registry.rsindex c8f4979d941..e80b83a8f5b 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/highlight_registry.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/highlight_registry.rs@@ -67,6 +67,12 @@ fn set_map_entry(cx: &CallContext, map: Gc<Map>, name: &Utf16String, highlight:}impl HighlightRegistry {+ fn registered_highlights<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, RegisteredHighlight> {+ let highlights = MarkedVec::new(vm);+ highlights.extend_from_slice(&self.highlights.borrow());+ highlights+ }+pub(crate) fn create(vm: &Vm, document: CppCell) -> Ref<Self> {allocate(vm, |_| Self {document,@@ -119,14 +125,14 @@ impl HighlightRegistry {let mut sort_keys: Vec<(i32, usize)> = Vec::new();// 3. For each Highlight highlight in this HighlightRegistry:- for (registration_index, entry) in self.highlights.borrow().clone().into_iter().enumerate() {+ for (registration_index, entry) in self.registered_highlights(vm).values().iter().enumerate() {let highlight = entry.highlight;// 1. Let result be a new HighlightHitResult with highlight set to highlight.let ranges = MarkedVec::new(vm);// 2. For each AbstractRange abstractRange in highlight:- for abstract_range in highlight.ranges() {+ for abstract_range in highlight.ranges(vm).values().iter() {// 1. If abstractRange is an invalid StaticRange, then continue.// 2. Let range be a new Range whose start node and end node are set to abstractRange’s start node and// end node respectively, and start offset and end offset are set to abstractRange’s start offset@@ -135,7 +141,7 @@ impl HighlightRegistry {// getClientRects() on range, then append abstractRange to result.ranges.// SAFETY: The range is live.if unsafe { web_css_highlight_registry_range_is_hit(abstract_range.as_ptr(), x, y) } {- ranges.push(wrap_cpp_cell(cx, &abstract_range));+ ranges.push(wrap_cpp_cell(cx, abstract_range));}}@@ -170,7 +176,7 @@ impl Maplike for HighlightRegistry {fn map_entries(&self, cx: &CallContext) -> Gc<Map> {self.map_entries.get_or_create(cx, || {let map = Map::create(cx.vm(), cx.realm());- for entry in self.highlights.borrow().clone() {+ for entry in self.registered_highlights(cx.vm()).values().iter() {set_map_entry(cx, map, &entry.name, entry.highlight);}map@@ -194,9 +200,9 @@ impl WritableMaplike for HighlightRegistry {}),}}- for map in self.map_entries.live() {+ self.map_entries.for_each_live(cx.vm(), |map| {set_map_entry(&context_of_map(cx, map), map, &key, highlight);- }+ });}fn map_remove(&self, cx: &CallContext, key: &Utf16String) -> bool {@@ -205,17 +211,17 @@ impl WritableMaplike for HighlightRegistry {return false;};self.highlights.borrow_mut(cx.vm()).remove(position);- for map in self.map_entries.live() {+ self.map_entries.for_each_live(cx.vm(), |map| {let key = key.clone().to_js(cx).expect("a string converts to a JS value");map.map_remove(cx.vm(), key);- }+ });true}fn map_clear(&self, cx: &CallContext) {self.highlights.borrow_mut(cx.vm()).clear();- for map in self.map_entries.live() {+ self.map_entries.for_each_live(cx.vm(), |map| {map.map_clear(cx.vm());- }+ });}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rsindex c4b6302efdd..5901de22302 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs@@ -70,6 +70,7 @@ pub(crate) mod css_unit_value;pub(crate) mod css_unparsed_value;pub(crate) mod css_variable_reference_value;pub(crate) mod exports;+pub(crate) mod font_face_set;pub(crate) mod font_face_set_load_event;pub(crate) mod highlight;pub(crate) mod highlight_registry;diff --git a/Libraries/LibWeb/CSS/BindingsGlue.h b/Libraries/LibWeb/CSS/BindingsGlue.hindex c45ff5e7bfd..1590b26a7a6 100644--- a/Libraries/LibWeb/CSS/BindingsGlue.h+++ b/Libraries/LibWeb/CSS/BindingsGlue.h@@ -21,23 +21,3 @@#include <LibWeb/HTML/Window.h>#include <LibWeb/WebIDL/ExceptionOr.h>#include <LibWeb/WebIDL/Promise.h>--namespace Web::CSS {--class FontFace;-class FontFaceState;-class FontFaceSet;--}--namespace Web::Bindings {--WEB_API void resolve_font_face_list_promise(JS::Realm&, WebIDL::Promise const&, Vector<NonnullRefPtr<CSS::FontFaceState>> const&);-WEB_API void resolve_font_face_set_promise(JS::Realm&, WebIDL::Promise const&, CSS::FontFaceSet&);-WEB_API GC::Ref<JS::Set> setlike_entries(JS::Realm&, WrapperWorld const&, CSS::FontFaceSet const&);-WEB_API bool setlike_has(CSS::FontFaceSet const&, JS::Value);-WEB_API void did_add_font_face(CSS::FontFaceSet const&, NonnullRefPtr<CSS::FontFaceState>);-WEB_API void did_remove_font_face(CSS::FontFaceSet const&, NonnullRefPtr<CSS::FontFaceState>);-WEB_API void did_reorder_font_faces(CSS::FontFaceSet const&, Vector<NonnullRefPtr<CSS::FontFaceState>> const&);--}diff --git a/Libraries/LibWeb/CSS/FontFace.cpp b/Libraries/LibWeb/CSS/FontFace.cppindex c3390563c82..267416856c2 100644--- a/Libraries/LibWeb/CSS/FontFace.cpp+++ b/Libraries/LibWeb/CSS/FontFace.cpp@@ -314,12 +314,8 @@ GC::Ref<FontFace> FontFaceState::create_for_constructor(JS::Object& relevant_glo// 2. For each FontFaceSet font face is in:for (auto& font_face_set : font_face->m_containing_sets) {// 1. If the FontFaceSet’s [[LoadingFonts]] list is empty, switch the FontFaceSet to loading.- if (font_face_set->loading_fonts().is_empty())- font_face_set->switch_to_loading();-// 2. Append font face to the FontFaceSet’s [[LoadingFonts]] list.- font_face_set->loading_fonts().append(font_face);- font_face_set->did_change_loading_fonts();+ font_face_set->font_started_loading(*font_face);}// 3. Asynchronously, attempt to parse the data in it as a font.@@ -344,21 +340,7 @@ GC::Ref<FontFace> FontFaceState::create_for_constructor(JS::Object& relevant_gloif (auto font_computer = font->font_computer(); font_computer.has_value())font_computer->register_font_face(*font);- // For each FontFaceSet font face is in:- for (auto& font_face_set : font->containing_sets()) {- if (!font->m_containing_sets.contains(font_face_set))- continue;-- // 1. Add font face to the FontFaceSet’s [[LoadedFonts]] list.- font_face_set->loaded_fonts().append(font);-- // 2. Remove font face from the FontFaceSet’s [[LoadingFonts]] list. If font was the last item in- // that list (and so the list is now empty), switch the FontFaceSet to loaded.- font_face_set->loading_fonts().remove_all_matching([font](auto const& entry) { return entry == font; });- font_face_set->did_change_loading_fonts();- if (font_face_set->loading_fonts().is_empty())- font_face_set->switch_to_loaded();- }+ font->did_finish_loading_in_containing_sets(true);font->m_font_load_promise = nullptr;}));@@ -373,21 +355,7 @@ GC::Ref<FontFace> FontFaceState::create_for_constructor(JS::Object& relevant_glo// and set font face’s status attribute to "error".font->reject_status_promise(WebIDL::SyntaxError::create(Utf16String::formatted("Failed to load font: {}", error)));- // For each FontFaceSet font face is in:- for (auto& font_face_set : font->containing_sets()) {- if (!font->m_containing_sets.contains(font_face_set))- continue;-- // 1. Add font face to the FontFaceSet’s [[FailedFonts]] list.- font_face_set->failed_fonts().append(font);-- // 2. Remove font face from the FontFaceSet’s [[LoadingFonts]] list. If font was the last item in- // that list (and so the list is now empty), switch the FontFaceSet to loaded.- font_face_set->loading_fonts().remove_all_matching([font](auto const& entry) { return entry == font; });- font_face_set->did_change_loading_fonts();- if (font_face_set->loading_fonts().is_empty())- font_face_set->switch_to_loaded();- }+ font->did_finish_loading_in_containing_sets(false);font->m_font_load_promise = nullptr;}));@@ -928,12 +896,8 @@ void FontFaceState::load_for_style()// Spec issue: https://github.com/w3c/csswg-drafts/issues/13235{HTML::TemporaryExecutionContext context(*m_environment, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- for (auto& font_face_set : m_containing_sets) {- if (font_face_set->loading_fonts().is_empty())- font_face_set->switch_to_loading();- font_face_set->loading_fonts().append(*this);- font_face_set->did_change_loading_fonts();- }+ for (auto& font_face_set : m_containing_sets)+ font_face_set->font_started_loading(*this);}// AD-HOC: The remaining steps run on the current task rather than truly async. So the fetch is observably in flight@@ -984,21 +948,7 @@ void FontFaceState::did_load(RefPtr<Gfx::Typeface const> maybe_typeface)reject_status_promise(WebIDL::NetworkError::create("Failed to load font"_utf16));invalidate_font_display();- // For each FontFaceSet font face is in:- for (auto& font_face_set : containing_sets()) {- if (!m_containing_sets.contains(font_face_set))- continue;-- // 1. Add font face to the FontFaceSet’s [[FailedFonts]] list.- font_face_set->failed_fonts().append(*this);-- // 2. Remove font face from the FontFaceSet’s [[LoadingFonts]] list. If font was the last item- // in that list (and so the list is now empty), switch the FontFaceSet to loaded.- font_face_set->loading_fonts().remove_all_matching([this](auto const& entry) { return entry == NonnullRefPtr<FontFaceState> { *this }; });- font_face_set->did_change_loading_fonts();- if (font_face_set->loading_fonts().is_empty())- font_face_set->switch_to_loaded();- }+ did_finish_loading_in_containing_sets(false);}// 2. Otherwise, font face now represents the loaded font; fulfill font face’s [[FontStatusPromise]] with font face@@ -1013,26 +963,26 @@ void FontFaceState::did_load(RefPtr<Gfx::Typeface const> maybe_typeface)if (auto font_computer = this->font_computer(); font_computer.has_value())font_computer->register_font_face(*this);- // For each FontFaceSet font face is in:- for (auto& font_face_set : containing_sets()) {- if (!m_containing_sets.contains(font_face_set))- continue;-- // 1. Add font face to the FontFaceSet’s [[LoadedFonts]] list.- font_face_set->loaded_fonts().append(*this);-- // 2. Remove font face from the FontFaceSet’s [[LoadingFonts]] list. If font was the last item- // in that list (and so the list is now empty), switch the FontFaceSet to loaded.- font_face_set->loading_fonts().remove_all_matching([this](auto const& entry) { return entry == NonnullRefPtr<FontFaceState> { *this }; });- font_face_set->did_change_loading_fonts();- if (font_face_set->loading_fonts().is_empty())- font_face_set->switch_to_loaded();- }+ did_finish_loading_in_containing_sets(true);}m_font_loader = nullptr;}+void FontFaceState::did_finish_loading_in_containing_sets(bool succeeded)+{+ // For each FontFaceSet font face is in:+ for (auto& font_face_set : containing_sets()) {+ if (!m_containing_sets.contains(font_face_set))+ continue;++ // 1. Add font face to the FontFaceSet’s [[LoadedFonts]] list, or to its [[FailedFonts]] list.+ // 2. Remove font face from the FontFaceSet’s [[LoadingFonts]] list. If font was the last item in that list+ // (and so the list is now empty), switch the FontFaceSet to loaded.+ font_face_set->font_finished_loading(*this, succeeded);+ }+}+void FontFaceState::add_to_set(FontFaceSet& set){m_containing_sets.set(set);diff --git a/Libraries/LibWeb/CSS/FontFaceSet.cpp b/Libraries/LibWeb/CSS/FontFaceSet.cppindex 4766df4b0cf..c56fdbd5151 100644--- a/Libraries/LibWeb/CSS/FontFaceSet.cpp+++ b/Libraries/LibWeb/CSS/FontFaceSet.cpp@@ -6,675 +6,264 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/HashMap.h>#include <LibGC/Heap.h>-#include <LibGC/HeapVector.h>-#include <LibGC/Root.h>#include <LibJS/HostClassBuilder.h>-#include <LibJS/Runtime/Array.h>-#include <LibJS/Runtime/Realm.h>-#include <LibJS/Runtime/Set.h>#include <LibJS/Runtime/VM.h>-#include <LibWeb/Bindings/FontFace.h>-#include <LibWeb/Bindings/FontFaceSet.h>#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Bindings/WrapperWorld.h>-#include <LibWeb/CSS/BindingsGlue.h>#include <LibWeb/CSS/FontComputer.h>#include <LibWeb/CSS/FontFace.h>#include <LibWeb/CSS/FontFaceSet.h>-#include <LibWeb/CSS/Parser/Parser.h>-#include <LibWeb/CSS/PropertyID.h>#include <LibWeb/CSS/StyleSheetState.h>-#include <LibWeb/CSS/StyleValues/ShorthandStyleValue.h>-#include <LibWeb/CSS/StyleValues/StyleValueList.h>#include <LibWeb/DOM/Document.h>-#include <LibWeb/DOM/Event.h>-#include <LibWeb/HTML/EventNames.h>#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/HTML/Window.h>#include <LibWeb/Page/RenderingStats.h>-#include <LibWeb/Platform/EventLoopPlugin.h>#include <LibWeb/WebIDL/Promise.h>+// The FontFaceSet implementation is in Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs. This is what C++ asks+// of it, and what it asks of the FontFace objects and the document that LibWeb keeps in C++.+namespace Web::CSS {extern "C" {// Defined in Bindings/Rust/src/css/exports.rs.-void* web_font_face_set_load_event_create(JSVM*, void* realm, FlatPtr name, void* const* font_faces, size_t count);-}--GC_DEFINE_ALLOCATOR(FontFaceSet);+void* web_font_face_set_create(JSVM*, void* realm, void* environment);+size_t web_font_face_set_size(void* set);+void* web_font_face_set_relevant_settings_object(void* set);+void web_font_face_set_add_css_connected_font(JSVM*, void* set, void* font_face);+void web_font_face_set_remove_css_connected_font(JSVM*, void* set, void* font_face);+void web_font_face_set_synchronize_css_connected_font_order(JSVM*, void* set);+void web_font_face_set_set_is_pending_on_the_environment(JSVM*, void* set, bool is_pending_on_the_environment);+void web_font_face_set_font_started_loading(JSVM*, void* set, void* font_face);+void web_font_face_set_font_finished_loading(JSVM*, void* set, void* font_face, bool succeeded);-GC::Ref<FontFaceSet> FontFaceSet::create(HTML::EnvironmentSettingsObject& environment)-{- auto& realm = environment.realm();- HTML::TemporaryExecutionContext temporary_execution_context { realm };- auto font_face_set = GC::Heap::the().allocate<FontFaceSet>(environment);- return font_face_set;+// Declared in Bindings/Rust/src/css/font_face_set.rs.+void* web_css_font_face_of_wrapper(void* wrapper);+void web_css_font_face_ref(void* font_face);+void web_css_font_face_unref(void* font_face);+void web_css_font_face_visit_edges(void* font_face, void* visitor);+void* web_css_font_face_cssom_font_face(void* font_face);+bool web_css_font_face_is_css_connected(void* font_face);+bool web_css_font_face_css_rule_identity(void* font_face, u64* identity);+bool web_css_font_face_is_loading(void* font_face);+bool web_css_font_face_is_loaded(void* font_face);+FlatPtr web_css_font_face_family_name(void* font_face);+bool web_css_font_face_unicode_ranges_include_any_of(void* font_face, FlatPtr text);+void* web_css_font_face_load(void* font_face);+void web_css_font_face_did_join_set(void* font_face, void* set);+void web_css_font_face_did_leave_set(void* font_face, void* set);+void web_css_font_face_set_record_loading_fonts(void* set, size_t count);+void web_css_font_face_set_update_layout(void* set, bool skip_if_running);+bool web_css_font_face_set_for_each_font_face_rule(void* set, void* context, void (*callback)(void*, u64));+void web_css_font_face_set_synchronize_font_computer(void* set, void* const* font_faces, size_t count);}-void FontFaceSet::record_loading_fonts()+static FontFaceState& state_from_abi(void* font_face){- if (!Core::StatsLog::the())- return;- auto* window = HTML::window_from_global_object(relevant_settings_object().global_object());- if (!window || window->associated_document().fonts().ptr() != this)- return;- set_rendering_pending(window->associated_document(), RenderingPendingReason::FontLoads, m_loading_fonts.size());+ return *static_cast<FontFaceState*>(font_face);}-FontFaceSet::FontFaceSet(HTML::EnvironmentSettingsObject& environment)- : DOM::EventTarget()- , m_environment(environment)- , m_ready_promise(WebIDL::create_promise_for(environment.global_object()))- , m_status(FontFaceSetLoadStatus::Loaded)+static FontFaceSet& set_from_abi(void* set){+ return *static_cast<FontFaceSet*>(set);}-void FontFaceSet::visit_edges(Cell::Visitor& visitor)+static JSVM* vm_abi(){- Base::visit_edges(visitor);- visitor.visit(m_font_faces);- visitor.visit(m_environment);- visitor.visit(m_ready_promise);- visitor.visit(m_loading_fonts);- visitor.visit(m_loaded_fonts);- visitor.visit(m_failed_fonts);+ return JS::HostABI::vm_to_abi(JS::VM::the());}-// https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-add-WebIDL::ExceptionOr<GC::Ref<FontFaceSet>> FontFaceSet::add(GC::Ref<FontFace> exposed_face)+GC::Ref<FontFaceSet> FontFaceSet::create(HTML::EnvironmentSettingsObject& environment){- NonnullRefPtr face { exposed_face->state() };- // 1. If font is already in the FontFaceSet’s set entries, skip to the last step of this algorithm immediately.- if (m_font_faces.contains([&](auto const& entry) { return entry.ptr() == face.ptr(); }))- return GC::Ref<FontFaceSet>(*this);-- // 2. If font is CSS-connected, throw an InvalidModificationError exception and exit this algorithm immediately.- if (face->is_css_connected()) {- return WebIDL::InvalidModificationError::create("Cannot add a CSS-connected FontFace to a FontFaceSet"_utf16);- }-- // NB: This method implements steps 3 and 4.- add_css_connected_font(*face);-- // 5. Return the FontFaceSet.- return GC::Ref<FontFaceSet>(*this);+ return *static_cast<FontFaceSet*>(web_font_face_set_create(vm_abi(), &environment.realm(), static_cast<GC::Cell*>(&environment)));}-// https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-add-void FontFaceSet::add_css_connected_font(NonnullRefPtr<FontFaceState> face)+size_t FontFaceSet::set_size(){- // 3. Add the font argument to the FontFaceSet’s set entries.- if (m_font_faces.contains_slow(face))- return;-- m_font_faces.append(face);- Bindings::did_add_font_face(*this, face);- face->add_to_set(*this);-- if (face->should_be_registered_with_font_computer()) {- if (auto font_computer = font_computer_for_font_source(relevant_settings_object().global_object()); font_computer.has_value())- font_computer->register_font_face(face);- }-- // 4. If font’s status attribute is "loading"- if (face->status() == FontFaceLoadStatus::Loading) {-- // 1. If the FontFaceSet’s [[LoadingFonts]] list is empty, switch the FontFaceSet to loading.- if (m_loading_fonts.is_empty())- switch_to_loading();-- // 2. Append font to the FontFaceSet’s [[LoadingFonts]] list.- m_loading_fonts.append(*face);- did_change_loading_fonts();- }+ return web_font_face_set_size(this);}-// https://drafts.csswg.org/css-font-loading/#document-font-face-set-// The FontFaceSet entries for a document's font source must be initially populated with all the CSS-connected FontFace-// objects from all of the CSS @font-face rules in the document or shadow root CSS style sheets, in document order. As-// @font-face rules are added or removed, the corresponding objects must be added or removed and maintain this ordering.-// Any manually-added FontFace objects must be ordered after the CSS-connected ones.-void FontFaceSet::synchronize_css_connected_font_order()+void FontFaceSet::add_css_connected_font(NonnullRefPtr<FontFaceState> font_face){- auto* window = HTML::window_from_global_object(relevant_settings_object().global_object());- if (!window)- return;-- HashMap<u64, NonnullRefPtr<FontFaceState>> connected_font_faces;- for (auto& font_face : m_font_faces) {- if (auto identity = font_face->css_rule_identity(); identity.has_value())- connected_font_faces.set(*identity, font_face);- }- Vector<NonnullRefPtr<FontFaceState>> ordered_font_faces;- Function<void(StyleSheetState&)> append_fonts_from_sheet = [&](StyleSheetState& sheet) {- sheet.for_each_effective_rule_data(TraversalOrder::Preorder, [&](RustRuleView const& rule, Utf16View) {- if (rule.type() != RustRule::Type::FontFace)- return;- auto font_face = connected_font_faces.get(rule.identity());- if (!font_face.has_value())- return;- NonnullRefPtr font_face_ref { **font_face };- if (!ordered_font_faces.contains_slow(font_face_ref))- ordered_font_faces.append(font_face_ref);- });- };-- // Every sheet added or removed asks again. Without a face from a rule the walk over their rules finds nothing.- auto& document = window->associated_document();- if (!connected_font_faces.is_empty())- document.for_each_active_css_style_sheet(append_fonts_from_sheet);-- for (auto& font_face : m_font_faces) {- if (font_face->is_css_connected() && !ordered_font_faces.contains_slow(font_face))- ordered_font_faces.append(font_face);- }- for (auto& font_face : m_font_faces) {- if (!font_face->is_css_connected())- ordered_font_faces.append(font_face);- }-- bool order_changed = ordered_font_faces.size() != m_font_faces.size();- if (!order_changed) {- for (size_t index = 0; index < m_font_faces.size(); ++index) {- if (ordered_font_faces[index] != m_font_faces[index]) {- order_changed = true;- break;- }- }- }- if (!order_changed)- return;-- m_font_faces = move(ordered_font_faces);- Bindings::did_reorder_font_faces(*this, m_font_faces);- document.font_computer().synchronize_font_face_order(m_font_faces);+ web_font_face_set_add_css_connected_font(vm_abi(), this, font_face.ptr());}-// https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-delete-bool FontFaceSet::delete_(GC::Ref<FontFace> face)+void FontFaceSet::remove_css_connected_font(NonnullRefPtr<FontFaceState> font_face){- return remove_font_face(face->state(), AllowCSSConnected::No);+ web_font_face_set_remove_css_connected_font(vm_abi(), this, font_face.ptr());}-void FontFaceSet::remove_css_connected_font(NonnullRefPtr<FontFaceState> face)+void FontFaceSet::synchronize_css_connected_font_order(){- remove_font_face(face, AllowCSSConnected::Yes);+ web_font_face_set_synchronize_css_connected_font_order(vm_abi(), this);}-bool FontFaceSet::remove_font_face(NonnullRefPtr<FontFaceState> face, AllowCSSConnected allow_css_connected)+HTML::EnvironmentSettingsObject& FontFaceSet::relevant_settings_object(){- // 1. If font is CSS-connected, return false and exit this algorithm immediately.- if (allow_css_connected == AllowCSSConnected::No && face->is_css_connected()) {- return false;- }-- if (!m_font_faces.contains_slow(face))- return false;-- if (face->should_be_registered_with_font_computer()) {- if (auto font_computer = font_computer_for_font_source(relevant_settings_object().global_object()); font_computer.has_value())- font_computer->unregister_font_face(*face);- }-- // 2. Let deleted be the result of removing font from the FontFaceSet’s set entries.- bool deleted = m_font_faces.remove_first_matching([&](auto const& entry) { return entry.ptr() == face.ptr(); });- VERIFY(deleted);- Bindings::did_remove_font_face(*this, *face);- face->remove_from_set(*this);-- // 3. If font is present in the FontFaceSet’s [[LoadedFonts]], or [[FailedFonts]] lists, remove it.- m_loaded_fonts.remove_all_matching([face](auto const& entry) { return entry == face; });- m_failed_fonts.remove_all_matching([face](auto const& entry) { return entry == face; });-- // 4. If font is present in the FontFaceSet’s [[LoadingFonts]] list, remove it.- // If font was the last item in that list (and so the list is now empty), switch the FontFaceSet to loaded.- bool was_in_loading_fonts = m_loading_fonts.remove_all_matching([face](auto const& entry) { return entry == face; });- did_change_loading_fonts();- if (was_in_loading_fonts && m_loading_fonts.is_empty())- switch_to_loaded();-- return deleted;+ return *static_cast<HTML::EnvironmentSettingsObject*>(static_cast<GC::Cell*>(web_font_face_set_relevant_settings_object(this)));}-// https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-clear-void FontFaceSet::clear()+void FontFaceSet::set_is_pending_on_the_environment(bool is_pending_on_the_environment){- // 1. Remove all non-CSS-connected items from the FontFaceSet's set entries,- // its [[LoadedFonts]] list, and its [[FailedFonts]] list.- auto font_computer = font_computer_for_font_source(relevant_settings_object().global_object());- for (auto& font_face : m_font_faces) {- if (font_face->is_css_connected())- continue;- if (font_computer.has_value() && font_face->should_be_registered_with_font_computer())- font_computer->unregister_font_face(font_face);- Bindings::did_remove_font_face(*this, font_face);- font_face->remove_from_set(*this);- }- m_font_faces.remove_all_matching([](auto const& font) { return !font->is_css_connected(); });-- m_loaded_fonts.remove_all_matching([](auto const& font) { return !font->is_css_connected(); });- m_failed_fonts.remove_all_matching([](auto const& font) { return !font->is_css_connected(); });-- // 2. If the FontFaceSet's [[LoadingFonts]] list is non-empty, remove all items from it,- // then switch the FontFaceSet to loaded.- if (!m_loading_fonts.is_empty()) {- m_loading_fonts.clear();- did_change_loading_fonts();- switch_to_loaded();- }+ web_font_face_set_set_is_pending_on_the_environment(vm_abi(), this, is_pending_on_the_environment);}-// https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-onloading-void FontFaceSet::set_onloading(WebIDL::CallbackType* event_handler)+void FontFaceSet::font_started_loading(FontFaceState& font_face){- set_event_handler_attribute(HTML::EventNames::loading, event_handler);+ web_font_face_set_font_started_loading(vm_abi(), this, &font_face);}-// https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-onloading-WebIDL::CallbackType* FontFaceSet::onloading()+void FontFaceSet::font_finished_loading(FontFaceState& font_face, bool succeeded){- return event_handler_attribute(HTML::EventNames::loading);+ web_font_face_set_font_finished_loading(vm_abi(), this, &font_face, succeeded);}-// https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-onloadingdone-void FontFaceSet::set_onloadingdone(WebIDL::CallbackType* event_handler)+void* web_css_font_face_of_wrapper(void* wrapper){- set_event_handler_attribute(HTML::EventNames::loadingdone, event_handler);+ auto* font_face = Bindings::impl_from<FontFace>(static_cast<JS::Object*>(wrapper));+ VERIFY(font_face);+ return &font_face->state();}-// https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-onloadingdone-WebIDL::CallbackType* FontFaceSet::onloadingdone()+void web_css_font_face_ref(void* font_face){- return event_handler_attribute(HTML::EventNames::loadingdone);+ state_from_abi(font_face).ref();}-// https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-onloadingerror-void FontFaceSet::set_onloadingerror(WebIDL::CallbackType* event_handler)+void web_css_font_face_unref(void* font_face){- set_event_handler_attribute(HTML::EventNames::loadingerror, event_handler);+ state_from_abi(font_face).unref();}-// https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-onloadingerror-WebIDL::CallbackType* FontFaceSet::onloadingerror()+void web_css_font_face_visit_edges(void* font_face, void* visitor){- return event_handler_attribute(HTML::EventNames::loadingerror);+ state_from_abi(font_face).visit_edges(*static_cast<GC::Cell::Visitor*>(visitor));}-// https://drafts.csswg.org/css-font-loading/#find-the-matching-font-faces-static WebIDL::ExceptionOr<GC::Ref<GC::HeapVector<NonnullRefPtr<FontFaceState>>>> find_matching_font_faces(FontFaceSet& font_face_set, Utf16String const& font, Utf16String const& text)+void* web_css_font_face_cssom_font_face(void* font_face){- // 1. Parse font using the CSS value syntax of the font property. If a syntax error occurs, return a syntax error.- auto property = parse_css_value(CSS::Parser::ParsingParams(), font, PropertyID::Font);- if (!property || !property->is_shorthand())- return WebIDL::SyntaxError::create("Unable to parse font"_utf16);-- // If the parsed value is a CSS-wide keyword, return a syntax error.- // Note: This case is already caught by the is_shorthand check.-- // FIXME: Absolutize all relative lengths against the initial values of the corresponding properties. (For example, a- // relative font weight like bolder is evaluated against the initial value normal.)-- // FIXME: 2. If text was not explicitly provided, let it be a string containing a single space character (U+0020 SPACE).-- // 3. Let font family list be the list of font families parsed from font, and font style be the other font style- // attributes parsed from font.- auto font_family_value = property->as_shorthand().longhand(PropertyID::FontFamily);- auto const& font_family_list = font_family_value->as_value_list();-- // 5. Let matched font faces initially be an empty list.- auto matched_font_faces = GC::Heap::the().allocate<GC::HeapVector<NonnullRefPtr<FontFaceState>>>();-- // 6. For each family in font family list, use the font matching rules to select the font faces from available font- // faces that match the font style, and add them to matched font faces. The use of the unicodeRange attribute means- // that this may be more than just a single font face.- for (auto const& font_family : font_family_list.values()) {- // NB: Skip generic font family keywords- if (font_family->is_keyword())- continue;-- // FIXME: The matching below is super basic. We currently just match font family names by their string value.- auto font_family_name = string_from_style_value(font_family);-- for (auto font_face : font_face_set.font_faces()) {- if (font_face->family_name() != font_family_name)- continue;-- if (!matched_font_faces->elements().contains_slow(font_face))- matched_font_faces->elements().append(font_face);- }- }-- // FIXME: 7. If matched font faces is empty, set the found faces flag to false. Otherwise, set it to true.-- // 8. For each font face in matched font faces, if its defined unicode-range does not include the codepoint of at- // least one character in text, remove it from the list.- matched_font_faces->elements().remove_all_matching([&](auto const& font_face) {- bool includes_at_least_one_text_code_point = false;- for (auto code_point : text.utf16_view()) {- for (auto const& range : font_face->unicode_ranges()) {- if (range.contains(code_point)) {- includes_at_least_one_text_code_point = true;- break;- }- }- if (includes_at_least_one_text_code_point)- break;- }- return !includes_at_least_one_text_code_point;- });-- // 9. Return matched font faces and the found faces flag.- return GC::Ref { *matched_font_faces };+ return static_cast<GC::Cell*>(&state_from_abi(font_face).cssom_font_face());}-// https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-load-JS::ThrowCompletionOr<GC::Ref<WebIDL::Promise>> FontFaceSet::load(Utf16String font, Utf16String text)+bool web_css_font_face_is_css_connected(void* font_face){- auto& realm = relevant_settings_object().realm();-- // 1. Let font face set be the FontFaceSet object this method was called on. Let promise be a newly-created promise object.- GC::Ref font_face_set = *this;- auto promise = WebIDL::create_promise_for(relevant_settings_object().global_object());-- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, font_face_set, promise, font, text]() mutable {- // 3. Find the matching font faces from font face set using the font and text arguments passed to the function,- // and let font face list be the return value (ignoring the found faces flag). If a syntax error was returned,- // reject promise with a SyntaxError exception and terminate these steps.- auto result = find_matching_font_faces(font_face_set, font, text);- if (result.is_error()) {- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- WebIDL::reject_promise_with_exception(promise, result.release_error());- return;- }-- auto matched_font_faces = result.release_value();-- // 4. Queue a task to run the following steps synchronously:- HTML::queue_a_task(HTML::Task::Source::FontLoading, nullptr, nullptr, GC::create_function(GC::Heap::the(), [&realm, promise, matched_font_faces] {- GC::RootVector<GC::Ref<WebIDL::Promise>> promises;-- // 1. For all of the font faces in the font face list, call their load() method.- for (auto font_face : matched_font_faces->elements()) {- font_face->load();-- promises.append(font_face->font_status_promise());- }-- // 2. Resolve promise with the result of waiting for all of the [[FontStatusPromise]]s of each font face in- // the font face list, in order.- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };-- WebIDL::wait_for_all(- realm, promises,- [&realm, promise, matched_font_faces](auto const&) {- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- Bindings::resolve_font_face_list_promise(realm, promise, matched_font_faces->elements());- },- [&realm, promise](auto error) {- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- WebIDL::reject_promise(promise, error);- });- }));- }));-- // 2. Return promise. Complete the rest of these steps asynchronously.- return promise;+ return state_from_abi(font_face).is_css_connected();}-// https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-check-WebIDL::ExceptionOr<bool> FontFaceSet::check(Utf16String const& font, Utf16String const& text)+bool web_css_font_face_css_rule_identity(void* font_face, u64* identity){- // 1. Let font face set be the FontFaceSet object this method was called on.- GC::Ref font_face_set = *this;-- // 2. Find the matching font faces from font face set using the font and text arguments passed to the function, and- // including system fonts, and let font face list be the returned list of font faces, and found faces be the- // returned found faces flag. If a syntax error was returned, throw a SyntaxError exception and terminate these- // steps.- auto result = TRY(find_matching_font_faces(font_face_set, font, text));-- // 3. If font face list is empty, or all fonts in the font face list either have a status attribute of "loaded" or- // are system fonts, return true. Otherwise, return false.- if (result->elements().is_empty())- return true;-- for (auto font_face : result->elements()) {- // FIXME: We should check if the font face is a system font here.- if (font_face->status() != FontFaceLoadStatus::Loaded)- return false;- }-+ auto rule_identity = state_from_abi(font_face).css_rule_identity();+ if (!rule_identity.has_value())+ return false;+ *identity = *rule_identity;return true;}-// https://drafts.csswg.org/css-font-loading/#font-face-set-ready-GC::Ref<WebIDL::Promise> FontFaceSet::ready()+bool web_css_font_face_is_loading(void* font_face){- // Pending style or layout changes can start a deferred font load. Flush them before returning an already fulfilled- // promise so switching the FontFaceSet to loading can replace it with a new pending promise.- if (WebIDL::is_promise_fulfilled(m_ready_promise)) {- auto& global = relevant_settings_object().global_object();- if (auto* window = HTML::window_from_global_object(global))- window->associated_document().update_layout(DOM::UpdateLayoutReason::FontFaceSetReady);- }-- return m_ready_promise;+ return state_from_abi(font_face).status() == FontFaceLoadStatus::Loading;}-// https://drafts.csswg.org/css-font-loading/#fire-a-font-load-event-void FontFaceSet::fire_a_font_load_event(Utf16FlyString name, Vector<NonnullRefPtr<FontFaceState>> font_faces)-{- // To fire a font load event named e at a FontFaceSet target with optional font faces means to fire a simple- // event named e using the FontFaceSetLoadEvent interface that also meets these conditions:- // 1. The fontfaces attribute is initialized to the result of filtering font faces to only contain FontFace- // objects contained in target.- font_faces.remove_all_matching([&](auto const& font_face) { return !m_font_faces.contains_slow(font_face); });- GC::RootVector<GC::Ref<FontFace>> objects;- objects.ensure_capacity(font_faces.size());- for (auto const& font_face : font_faces)- objects.unchecked_append(font_face->cssom_font_face());- Vector<void*> cells;- cells.ensure_capacity(objects.size());- for (auto font_face : objects)- cells.unchecked_append(static_cast<GC::Cell*>(font_face.ptr()));- auto* event = web_font_face_set_load_event_create(JS::HostABI::vm_to_abi(JS::VM::the()), &relevant_settings_object().realm(), name.to_utf16_string().into_raw(), cells.data(), cells.size());- dispatch_event(*static_cast<DOM::Event*>(static_cast<GC::Cell*>(event)));-}--// https://drafts.csswg.org/css-font-loading/#ref-for-fontfaceset-pending-on-the-environment%E2%91%A1-void FontFaceSet::set_is_pending_on_the_environment(bool is_pending_on_the_environment)+bool web_css_font_face_is_loaded(void* font_face){- if (is_pending_on_the_environment == m_is_pending_on_the_environment)- return;- m_is_pending_on_the_environment = is_pending_on_the_environment;-- // Whenever a FontFaceSet goes from pending on the environment to not pending on the environment, the user agent- // must run the following steps:- if (!is_pending_on_the_environment) {- // 1. If the FontFaceSet is stuck on the environment and its [[LoadingFonts]] list is empty, switch the- // FontFaceSet to loaded.- // FIXME: We also need to mark empty FontFaceSets as loaded, so that the [[ReadyPromise]] gets resolved.- // Spec issue: https://github.com/w3c/csswg-drafts/issues/13538#issuecomment-3933951987- if (m_font_faces.is_empty() || (m_is_stuck_on_the_environment && m_loading_fonts.is_empty()))- switch_to_loaded();- // AD-HOC: Also switch when nothing has ever entered the LoadingFonts list — an empty set, or a set whose- // entries all have deferred unicode-ranges that no rendered codepoint matched. Without this the- // ready promise stays pending forever.- else if (m_loading_fonts.is_empty())- switch_to_loaded();-- // 2. If the FontFaceSet is stuck on the environment, unmark it as such.- m_is_stuck_on_the_environment = false;- }+ return state_from_abi(font_face).status() == FontFaceLoadStatus::Loaded;}-// https://drafts.csswg.org/css-font-loading/#switch-the-fontfaceset-to-loading-void FontFaceSet::switch_to_loading()+FlatPtr web_css_font_face_family_name(void* font_face){- // 1. Let font face set be the given FontFaceSet.- // 2. Set the status attribute of font face set to "loading".- m_status = FontFaceSetLoadStatus::Loading;-- // 3. If font face set’s [[ReadyPromise]] slot currently holds a fulfilled promise, replace it with a fresh pending- // promise.- if (WebIDL::is_promise_fulfilled(m_ready_promise))- m_ready_promise = WebIDL::create_promise_for(relevant_settings_object().global_object());-- // 4. Queue a task to fire a font load event named loading at font face set.- HTML::queue_a_task(HTML::Task::Source::FontLoading, nullptr, nullptr, GC::create_function(relevant_settings_object().realm().heap(), [this] {- fire_a_font_load_event(HTML::EventNames::loading);- }));+ return state_from_abi(font_face).family_name().to_utf16_string().into_raw();}-// https://drafts.csswg.org/css-font-loading/#switch-the-fontfaceset-to-loaded-void FontFaceSet::switch_to_loaded()+bool web_css_font_face_unicode_ranges_include_any_of(void* font_face, FlatPtr raw_text){- // 1. Let font face set be the given FontFaceSet.- // 2. If font face set is pending on the environment, mark it as stuck on the environment, and exit this algorithm.- if (m_is_pending_on_the_environment) {- m_is_stuck_on_the_environment = true;- return;- }-- // NB: Pending style or layout changes can depend on a recently loaded font or start another deferred font load.- auto& global = relevant_settings_object().global_object();- if (auto* window = HTML::window_from_global_object(global)) {- auto& document = window->associated_document();- if (!document.is_running_update_layout())- document.update_layout(DOM::UpdateLayoutReason::FontFaceSetReady);+ auto text = Utf16String::from_raw(raw_text);+ auto const& ranges = state_from_abi(font_face).unicode_ranges();+ for (auto code_point : text.utf16_view()) {+ for (auto const& range : ranges) {+ if (range.contains(code_point))+ return true;+ }}- if (!m_loading_fonts.is_empty())- return;-- // 3. Set font face set’s status attribute to "loaded".- auto was_loading = m_status == FontFaceSetLoadStatus::Loading;- m_status = FontFaceSetLoadStatus::Loaded;-- // 4. Fulfill font face set’s [[ReadyPromise]] attribute’s value with font face set.- auto& realm = relevant_settings_object().realm();- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- Bindings::resolve_font_face_set_promise(realm, m_ready_promise, *this);-- // AD-HOC: A set that never switched to loading only fulfills its ready promise. Firing loadingdone for it would- // report a load that never happened.- if (!was_loading)- return;-- // 5. Queue a task to perform the following steps synchronously:- HTML::queue_a_task(HTML::Task::Source::FontLoading, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this] {- // 1. Let loaded fonts be the (possibly empty) contents of font face set’s [[LoadedFonts]] slot.- // 2. Let failed fonts be the (possibly empty) contents of font face set’s [[FailedFonts]] slot.- // 3. Reset the [[LoadedFonts]] and [[FailedFonts]] slots to empty lists.- auto loaded_fonts = move(m_loaded_fonts);- auto failed_fonts = move(m_failed_fonts);-- // 4. Fire a font load event named loadingdone at font face set with loaded fonts.- fire_a_font_load_event(HTML::EventNames::loadingdone, move(loaded_fonts));-- // 5. If font face set’s failed fonts is non-empty, fire a font load event named loadingerror at font face set- // with failed fonts.- if (!failed_fonts.is_empty())- fire_a_font_load_event(HTML::EventNames::loadingerror, move(failed_fonts));- }));-}-+ return false;}-namespace Web::Bindings {--static WrapperWorldWeakValueCacheMap<CSS::FontFaceSet const, JS::Set>& font_face_set_caches()+void* web_css_font_face_load(void* font_face){- static NeverDestroyed<WrapperWorldWeakValueCacheMap<CSS::FontFaceSet const, JS::Set>> caches;- return *caches;+ auto& state = state_from_abi(font_face);+ state.load();+ return state.font_status_promise().ptr();}-static WrapperWorldWeakValueCache<JS::Set>& font_face_set_cache_for(CSS::FontFaceSet const& font_face_set)+void web_css_font_face_did_join_set(void* font_face, void* raw_set){- return font_face_set_caches().cache_for(font_face_set);-}--static JS::Value wrap_font_face(JS::Realm& realm, NonnullRefPtr<CSS::FontFaceState> font_face)-{- return Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref { font_face->cssom_font_face() });-}--static void add_font_face_to_set(JS::Set& set_entries, NonnullRefPtr<CSS::FontFaceState> font_face)-{- auto& realm = HTML::relevant_realm(set_entries);- set_entries.set_add(wrap_font_face(realm, font_face));-}--static void remove_font_face_from_set(JS::Set& set_entries, NonnullRefPtr<CSS::FontFaceState> font_face)-{- auto& realm = HTML::relevant_realm(set_entries);- set_entries.set_remove(wrap_font_face(realm, font_face));-}--static GC::Root<JS::Set> create_set_entries(JS::Realm& realm, Vector<NonnullRefPtr<CSS::FontFaceState>> const& font_faces)-{- auto set_entries = GC::make_root(JS::Set::create(realm));- for (auto font_face : font_faces)- add_font_face_to_set(*set_entries, font_face);- return set_entries;-}--void resolve_font_face_list_promise(JS::Realm& realm, WebIDL::Promise const& promise, Vector<NonnullRefPtr<CSS::FontFaceState>> const& font_faces)-{- auto wrapped_font_faces = GC::Heap::the().allocate<GC::HeapVector<JS::Value>>();- for (auto font_face : font_faces)- wrapped_font_faces->elements().append(wrap_font_face(realm, font_face));- WebIDL::resolve_promise(promise, JS::Array::create_from(realm, wrapped_font_faces->elements()));-}--void resolve_font_face_set_promise(JS::Realm& realm, WebIDL::Promise const& promise, CSS::FontFaceSet& font_face_set)-{- WebIDL::resolve_promise(promise, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref { font_face_set }));+ auto& state = state_from_abi(font_face);+ auto& set = set_from_abi(raw_set);+ state.add_to_set(set);+ if (state.should_be_registered_with_font_computer()) {+ if (auto font_computer = font_computer_for_font_source(set.relevant_settings_object().global_object()); font_computer.has_value())+ font_computer->register_font_face(state);+ }}-GC::Ref<JS::Set> setlike_entries(JS::Realm& realm, WrapperWorld const& wrapper_world, CSS::FontFaceSet const& font_face_set)+void web_css_font_face_did_leave_set(void* font_face, void* raw_set){- auto& cache = font_face_set_cache_for(font_face_set);- if (auto set_entries = cache.get(wrapper_world))- return *set_entries;-- auto set_entries = create_set_entries(realm, font_face_set.font_faces());- cache.set(wrapper_world, set_entries.ptr());- return GC::Ref { *set_entries };+ auto& state = state_from_abi(font_face);+ auto& set = set_from_abi(raw_set);+ if (state.should_be_registered_with_font_computer()) {+ if (auto font_computer = font_computer_for_font_source(set.relevant_settings_object().global_object()); font_computer.has_value())+ font_computer->unregister_font_face(state);+ }+ state.remove_from_set(set);}-bool setlike_has(CSS::FontFaceSet const& font_face_set, JS::Value value)+void web_css_font_face_set_record_loading_fonts(void* raw_set, size_t count){- auto* font_face = Bindings::impl_from<CSS::FontFace>(&value.as_object());- VERIFY(font_face);- return font_face_set.font_faces().contains([&](auto const& entry) { return entry.ptr() == &font_face->state(); });+ if (!Core::StatsLog::the())+ return;+ auto& set = set_from_abi(raw_set);+ auto* window = HTML::window_from_global_object(set.relevant_settings_object().global_object());+ if (!window || window->associated_document().fonts().ptr() != &set)+ return;+ set_rendering_pending(window->associated_document(), RenderingPendingReason::FontLoads, count);}-void did_add_font_face(CSS::FontFaceSet const& font_face_set, NonnullRefPtr<CSS::FontFaceState> font_face)+void web_css_font_face_set_update_layout(void* set, bool skip_if_running){- font_face_set_cache_for(font_face_set).for_each([&](auto& set_entries) {- add_font_face_to_set(set_entries, font_face);- });+ auto* window = HTML::window_from_global_object(set_from_abi(set).relevant_settings_object().global_object());+ if (!window)+ return;+ auto& document = window->associated_document();+ if (!skip_if_running || !document.is_running_update_layout())+ document.update_layout(DOM::UpdateLayoutReason::FontFaceSetReady);}-void did_remove_font_face(CSS::FontFaceSet const& font_face_set, NonnullRefPtr<CSS::FontFaceState> font_face)+bool web_css_font_face_set_for_each_font_face_rule(void* set, void* context, void (*callback)(void*, u64)){- font_face_set_cache_for(font_face_set).for_each([&](auto& set_entries) {- remove_font_face_from_set(set_entries, font_face);- });+ auto* window = HTML::window_from_global_object(set_from_abi(set).relevant_settings_object().global_object());+ if (!window)+ return false;+ Function<void(StyleSheetState&)> for_each_rule = [&](StyleSheetState& sheet) {+ sheet.for_each_effective_rule_data(TraversalOrder::Preorder, [&](RustRuleView const& rule, Utf16View) {+ if (rule.type() == RustRule::Type::FontFace)+ callback(context, rule.identity());+ });+ };+ window->associated_document().for_each_active_css_style_sheet(for_each_rule);+ return true;}-void did_reorder_font_faces(CSS::FontFaceSet const& font_face_set, Vector<NonnullRefPtr<CSS::FontFaceState>> const& font_faces)+void web_css_font_face_set_synchronize_font_computer(void* set, void* const* font_faces, size_t count){- font_face_set_cache_for(font_face_set).for_each([&](auto& set_entries) {- set_entries.set_clear();- for (auto& font_face : font_faces)- add_font_face_to_set(set_entries, font_face);- });+ auto* window = HTML::window_from_global_object(set_from_abi(set).relevant_settings_object().global_object());+ if (!window)+ return;+ Vector<NonnullRefPtr<FontFaceState>> states;+ states.ensure_capacity(count);+ for (size_t index = 0; index < count; ++index)+ states.unchecked_append(state_from_abi(font_faces[index]));+ window->associated_document().font_computer().synchronize_font_face_order(states);}}diff --git a/Libraries/LibWeb/CSS/FontFaceSet.h b/Libraries/LibWeb/CSS/FontFaceSet.hindex 8267e2a34b4..0befc63a232 100644--- a/Libraries/LibWeb/CSS/FontFaceSet.h+++ b/Libraries/LibWeb/CSS/FontFaceSet.h@@ -7,100 +7,35 @@#pragma once-#include <AK/Utf16String.h>-#include <LibCore/StatsLog.h>-#include <LibJS/Runtime/Set.h>-#include <LibJS/Runtime/Value.h>+#include <AK/NonnullRefPtr.h>+#include <LibGC/Ptr.h>#include <LibWeb/Bindings/FontFaceSet.h>-#include <LibWeb/Bindings/WrapperWorld.h>-#include <LibWeb/CSS/FontFace.h>-#include <LibWeb/DOM/EventTarget.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Export.h>#include <LibWeb/Forward.h>-namespace Web::Bindings {--enum class FontFaceSetLoadStatus : u8;--}-namespace Web::CSS {-using FontFaceSetLoadStatus = Bindings::FontFaceSetLoadStatus;--class FontFaceSet final : public DOM::EventTarget {- WEB_WRAPPABLE(FontFaceSet, DOM::EventTarget);- GC_DECLARE_ALLOCATOR(FontFaceSet);+// https://drafts.csswg.org/css-font-loading/#fontfaceset+class WEB_API FontFaceSet final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(FontFaceSet, font_face_set)public:[[nodiscard]] static GC::Ref<FontFaceSet> create(HTML::EnvironmentSettingsObject&);- virtual ~FontFaceSet() override = default;- size_t set_size() const { return m_font_faces.size(); }- Vector<NonnullRefPtr<FontFaceState>> const& font_faces() const { return m_font_faces; }-- WebIDL::ExceptionOr<GC::Ref<FontFaceSet>> add(GC::Ref<FontFace>);- bool delete_(GC::Ref<FontFace>);- void clear();+ size_t set_size();void add_css_connected_font(NonnullRefPtr<FontFaceState>);void remove_css_connected_font(NonnullRefPtr<FontFaceState>);void synchronize_css_connected_font_order();- void set_onloading(WebIDL::CallbackType*);- WebIDL::CallbackType* onloading();- void set_onloadingdone(WebIDL::CallbackType*);- WebIDL::CallbackType* onloadingdone();- void set_onloadingerror(WebIDL::CallbackType*);- WebIDL::CallbackType* onloadingerror();-- JS::ThrowCompletionOr<GC::Ref<WebIDL::Promise>> load(Utf16String font, Utf16String text);- WebIDL::ExceptionOr<bool> check(Utf16String const& font, Utf16String const& text);-- Vector<NonnullRefPtr<FontFaceState>>& loading_fonts() { return m_loading_fonts; }- Vector<NonnullRefPtr<FontFaceState>>& loaded_fonts() { return m_loaded_fonts; }- Vector<NonnullRefPtr<FontFaceState>>& failed_fonts() { return m_failed_fonts; }- void did_change_loading_fonts()- {- if (Core::StatsLog::the())- record_loading_fonts();- }-- GC::Ref<WebIDL::Promise> ready();- HTML::EnvironmentSettingsObject& relevant_settings_object() const { return *m_environment; }- FontFaceSetLoadStatus status() const { return m_status; }+ HTML::EnvironmentSettingsObject& relevant_settings_object();- void fire_a_font_load_event(Utf16FlyString name, Vector<NonnullRefPtr<FontFaceState>> = {});void set_is_pending_on_the_environment(bool);- void switch_to_loading();- void switch_to_loaded();--private:- void record_loading_fonts();-- enum class AllowCSSConnected {- No,- Yes,- };-- explicit FontFaceSet(HTML::EnvironmentSettingsObject&);- virtual void visit_edges(Cell::Visitor&) override;- bool remove_font_face(NonnullRefPtr<FontFaceState>, AllowCSSConnected);-- Vector<NonnullRefPtr<FontFaceState>> m_font_faces;- GC::Ref<HTML::EnvironmentSettingsObject> m_environment;- GC::Ref<WebIDL::Promise> m_ready_promise; // [[ReadyPromise]]-- Vector<NonnullRefPtr<FontFaceState>> m_loading_fonts {}; // [[LoadingFonts]]- Vector<NonnullRefPtr<FontFaceState>> m_loaded_fonts {}; // [[LoadedFonts]]- Vector<NonnullRefPtr<FontFaceState>> m_failed_fonts {}; // [[FailedFonts]]-- FontFaceSetLoadStatus m_status;-- bool m_is_pending_on_the_environment { true };-- // https://drafts.csswg.org/css-font-loading/#fontfaceset-stuck-on-the-environment- bool m_is_stuck_on_the_environment { false };+ // What the set does when a font in it starts to load, and when that load ended.+ void font_started_loading(FontFaceState&);+ void font_finished_loading(FontFaceState&, bool succeeded);};}diff --git a/Libraries/LibWeb/CSS/FontFaceSet.idl b/Libraries/LibWeb/CSS/FontFaceSet.idlindex 026f121c0de..7be9183d674 100644--- a/Libraries/LibWeb/CSS/FontFaceSet.idl+++ b/Libraries/LibWeb/CSS/FontFaceSet.idl@@ -1,7 +1,7 @@enum FontFaceSetLoadStatus { "loading", "loaded" };// https://drafts.csswg.org/css-font-loading/#fontfaceset-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface FontFaceSet : EventTarget {setlike<FontFace>;FontFaceSet add(FontFace font);diff --git a/Libraries/LibWeb/CSS/FontFaceState.h b/Libraries/LibWeb/CSS/FontFaceState.hindex bd51e4b6221..420b46f8145 100644--- a/Libraries/LibWeb/CSS/FontFaceState.h+++ b/Libraries/LibWeb/CSS/FontFaceState.h@@ -124,6 +124,7 @@ private:JS::Object& task_global_object() const;void reject_status_promise(WebIDL::Exception);void did_load(RefPtr<Gfx::Typeface const>);+ void did_finish_loading_in_containing_sets(bool succeeded);void set_parsed_font(RefPtr<Gfx::Typeface const>);Optional<FontComputer&> font_computer() const;diff --git a/Libraries/LibWeb/Rust/src/css/typed_om.rs b/Libraries/LibWeb/Rust/src/css/typed_om.rsindex 04f3ba60c53..d763e4ea8f0 100644--- a/Libraries/LibWeb/Rust/src/css/typed_om.rs+++ b/Libraries/LibWeb/Rust/src/css/typed_om.rs@@ -1110,6 +1110,34 @@ impl RetainedStyleValue {}}+/// The non-generic font families of a value of the font property, or None if it does not parse as one.+pub fn font_family_names(font: &ak::Utf16String) -> Option<Vec<ak::Utf16String>> {+ let value = parse_value_for_property(property_id::FONT, font)?;+ let StyleValueData::Shorthand(shorthand) = value.data() else {+ return None;+ };+ let index = shorthand+ .sub_properties+ .as_slice()+ .iter()+ .position(|&property| property == property_id::FONT_FAMILY)?;+ let StyleValueData::ValueList { values, .. } = shorthand.values.as_slice()[index].data() else {+ unreachable!("the font-family of a font shorthand is a list");+ };+ Some(+ values+ .as_slice()+ .iter()+ .filter_map(|family| match family.data() {+ StyleValueData::Keyword { .. } => None,+ StyleValueData::String { string, .. } => Some(ak::Utf16String::from_utf16(string.units())),+ StyleValueData::CustomIdent { custom_ident } => Some(ak::Utf16String::from_utf16(custom_ident.units())),+ _ => unreachable!("a font family is a keyword, a string or a custom identifier"),+ })+ .collect(),+ )+}+/// Whether the text matches as a <supports-condition>, with no document to parse it for.pub fn supports_condition_matches(condition_text: &ak::Utf16String) -> bool {let units = condition_text.to_utf16();diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex c3a5eddcd1e..d88ead654e0 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -37,8 +37,8 @@ CHECKED_SUFFIXES = {ALLOWED_REALM_MENTIONS = {"Animations": (5, 14, "animation callbacks/events and CSS value materialization still pass spec-selected realms"),"CSS": (- 8,- 17,+ 7,+ 11,"CSS Typed OM, parser-facing reification, style-value JS materialization, setlike/maplike glue, and wrappers of declaration blocks owned by Rust objects",),"Clipboard": (4, 16, "clipboard item/data callbacks still materialize JS values in caller-selected realms"),diff --git a/Tests/LibWeb/Text/expected/css/FontFaceSet-clear-size-has.txt b/Tests/LibWeb/Text/expected/css/FontFaceSet-clear-size-has.txtnew file mode 100644index 00000000000..6b176df73c9--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/FontFaceSet-clear-size-has.txt@@ -0,0 +1,10 @@+size after add: 100+has an entry: true+has a face that is not in the set: false+values: 100+size after delete: 99+has the deleted face: false+size after clear: 0+has a cleared face: false+values after clear: 0+has with a wrong value: TypeErrordiff --git a/Tests/LibWeb/Text/expected/css/FontFaceSet-load-events-are-trusted.txt b/Tests/LibWeb/Text/expected/css/FontFaceSet-load-events-are-trusted.txtnew file mode 100644index 00000000000..7f09f73cc61--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/FontFaceSet-load-events-are-trusted.txt@@ -0,0 +1,3 @@+loading trusted: true+loadingerror trusted: true+fontfaces: 1diff --git a/Tests/LibWeb/Text/input/css/FontFaceSet-clear-size-has.html b/Tests/LibWeb/Text/input/css/FontFaceSet-clear-size-has.htmlnew file mode 100644index 00000000000..6617f8996b6--- /dev/null+++ b/Tests/LibWeb/Text/input/css/FontFaceSet-clear-size-has.html@@ -0,0 +1,33 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ test(() => {+ const set = document.fonts;+ const faces = [];+ for (let i = 0; i < 100; ++i) {+ const face = new FontFace(`Face${i}`, "url(about:blank)");+ set.add(face);+ if (i < 2)+ faces.push(face);+ }+ println(`size after add: ${set.size}`);+ println(`has an entry: ${set.has(faces[0])}`);+ println(`has a face that is not in the set: ${set.has(new FontFace("Other", "url(about:blank)"))}`);+ println(`values: ${[...set].length}`);++ set.delete(faces[0]);+ println(`size after delete: ${set.size}`);+ println(`has the deleted face: ${set.has(faces[0])}`);++ set.clear();+ println(`size after clear: ${set.size}`);+ println(`has a cleared face: ${set.has(faces[1])}`);+ println(`values after clear: ${[...set].length}`);++ try {+ set.has({});+ } catch (error) {+ println(`has with a wrong value: ${error.name}`);+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/FontFaceSet-load-events-are-trusted.html b/Tests/LibWeb/Text/input/css/FontFaceSet-load-events-are-trusted.htmlnew file mode 100644index 00000000000..2717e6439c5--- /dev/null+++ b/Tests/LibWeb/Text/input/css/FontFaceSet-load-events-are-trusted.html@@ -0,0 +1,15 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ asyncTest(done => {+ document.fonts.addEventListener("loading", event => println(`loading trusted: ${event.isTrusted}`));+ document.fonts.addEventListener("loadingerror", event => {+ println(`loadingerror trusted: ${event.isTrusted}`);+ println(`fontfaces: ${event.fontfaces.length}`);+ done();+ });+ const face = new FontFace("Broken", "url(does-not-exist.woff2)");+ document.fonts.add(face);+ face.load().catch(() => {});+ });+</script>