Skip to main content

script/dom/css/
fontfaceset.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6
7use cssparser::{Parser, UnicodeRange};
8use dom_struct::dom_struct;
9use fonts::FontFaceRuleInfo;
10use js::context::JSContext;
11use js::gc::Handle;
12use js::jsapi::Value;
13use js::realm::CurrentRealm;
14use js::rust::HandleObject;
15use layout_api::{QueryMsg, ReflowGoal};
16use script_bindings::cell::DomRefCell;
17use script_bindings::codegen::GenericBindings::FontFaceBinding::{
18    FontFaceLoadStatus, FontFaceMethods,
19};
20use script_bindings::like::Setlike;
21use script_bindings::reflector::reflect_dom_object_with_proto;
22use servo_arc::Arc as ServoArc;
23use style::font_face::FamilyName;
24use style::properties::shorthands::font;
25use style::stylesheets::{CssRuleType, UrlExtraData};
26use style::values::computed::font::{FontFamilyList, SingleFontFamily};
27use style::values::specified::font as specified_font;
28use style_traits::ParsingMode;
29use stylo_atoms::Atom;
30
31use crate::css::css::{parser_context_for_document, parser_context_for_worker};
32use crate::dom::bindings::codegen::Bindings::FontFaceSetBinding::{
33    FontFaceSetLoadStatus, FontFaceSetMethods,
34};
35use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
36use crate::dom::bindings::error::{Error, Fallible};
37use crate::dom::bindings::inheritance::Castable;
38use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
39use crate::dom::bindings::reflector::DomGlobal;
40use crate::dom::bindings::root::{Dom, DomRoot};
41use crate::dom::bindings::str::DOMString;
42use crate::dom::css::fontfacesetloadevent::FontFaceSetLoadEvent;
43use crate::dom::event::Event;
44use crate::dom::eventtarget::EventTarget;
45use crate::dom::fontface::FontFace;
46use crate::dom::globalscope::GlobalScope;
47use crate::dom::promise::{Promise, RootedPromise, TracedPromise};
48use crate::dom::promisenativehandler::Callback;
49use crate::dom::types::PromiseNativeHandler;
50use crate::dom::window::Window;
51use crate::dom::workerglobalscope::WorkerGlobalScope;
52use crate::realms::enter_auto_realm;
53
54/// <https://drafts.csswg.org/css-font-loading/#FontFaceSet-interface>
55#[dom_struct]
56pub(crate) struct FontFaceSet {
57    target: EventTarget,
58
59    /// <https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-readypromise-slot>
60    promise: DomRefCell<TracedPromise>,
61
62    set_entries: DomRefCell<Vec<Dom<FontFace>>>,
63
64    /// <https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-status>
65    status: Cell<FontFaceSetLoadStatus>,
66}
67
68impl FontFaceSet {
69    fn new_inherited(promise: &RootedPromise) -> Self {
70        FontFaceSet {
71            target: EventTarget::new_inherited(),
72            promise: DomRefCell::new(promise.to_traced()),
73            set_entries: Default::default(),
74            // The specification does not define an initial value. The [[ReadyPromise]] starts
75            // out pending, so start out as "loading" so that `status` is "loaded" exactly
76            // when the ready promise is fulfilled.
77            status: Cell::new(FontFaceSetLoadStatus::Loading),
78        }
79    }
80
81    pub(crate) fn new(
82        cx: &mut JSContext,
83        global: &GlobalScope,
84        proto: Option<HandleObject>,
85    ) -> DomRoot<Self> {
86        let promise = Promise::new(cx, global);
87        reflect_dom_object_with_proto(
88            cx,
89            Box::new(FontFaceSet::new_inherited(&promise)),
90            global,
91            proto,
92        )
93    }
94
95    pub(super) fn handle_font_face_status_changed(&self, cx: &mut JSContext, font_face: &FontFace) {
96        match font_face.Status() {
97            FontFaceLoadStatus::Loading => {
98                self.switch_to_loading(cx);
99            },
100            FontFaceLoadStatus::Loaded => {
101                let (family_name, template) = font_face
102                    .template()
103                    .expect("A loaded web font should have a template");
104                let global = self.global();
105                global
106                    .font_context()
107                    .add_template_to_font_context(family_name, template);
108                match global.downcast::<Window>() {
109                    Some(window) => window.Document().dirty_all_nodes(cx.no_gc()),
110                    None => self.maybe_switch_worker_set_to_loaded(cx),
111                }
112            },
113            FontFaceLoadStatus::Error => self.maybe_switch_worker_set_to_loaded(cx),
114            _ => {},
115        }
116    }
117
118    /// Workers are never pending on the environment, so their font face set switches to
119    /// loaded as soon as none of its fonts are loading. For documents this is done by
120    /// `Document::maybe_fulfill_font_ready_promise`.
121    ///
122    /// <https://drafts.csswg.org/css-font-loading/#switch-the-fontfaceset-to-loaded>
123    pub(crate) fn maybe_switch_worker_set_to_loaded(&self, cx: &mut JSContext) {
124        if !self.global().is::<WorkerGlobalScope>() {
125            return;
126        }
127        let any_loading = self
128            .set_entries
129            .borrow()
130            .iter()
131            .any(|font_face| font_face.Status() == FontFaceLoadStatus::Loading);
132        if !any_loading {
133            self.fulfill_ready_promise_if_needed(cx);
134        }
135    }
136
137    /// Fulfill the font ready promise, returning true if it was not already fulfilled beforehand.
138    pub(crate) fn fulfill_ready_promise_if_needed(&self, cx: &mut JSContext) -> bool {
139        let promise = self.promise.borrow();
140        if promise.is_fulfilled() {
141            return false;
142        }
143
144        // From <https://drafts.csswg.org/css-font-loading/#switch-the-fontfaceset-to-loaded>:
145        // Step 3. Set font face set’s status attribute to "loaded".
146        self.status.set(FontFaceSetLoadStatus::Loaded);
147
148        // Step 4. Fulfill font face set’s [[ReadyPromise]] attribute’s value with font face set.
149        promise.resolve_native(cx, self);
150
151        // Step 5. Queue a task to perform the following steps synchronously:
152        let trusted_this = Trusted::new(self);
153        self.global()
154            .task_manager()
155            .font_loading_task_source()
156            .queue(task!(fire_font_set_loadingdone_event: move |cx| {
157                let this = trusted_this.root();
158
159                // Step 5.1. Let loaded fonts be the (possibly empty) contents of font face set’s
160                // [[LoadedFonts]] slot.
161                // Step 5.2. Let failed fonts be the (possibly empty) contents of font face set’s
162                // [[FailedFonts]] slot.
163                // Step 5.3. Reset the [[LoadedFonts]] and [[FailedFonts]] slots to empty lists.
164                // TODO: Keep track of [[LoadedFonts]] and [[FailedFonts]].
165
166                // Step 5.4. Fire a font load event named loadingdone at font face set with loaded fonts.
167                this.fire_font_load_event(cx, Atom::from("loadingdone"), &[]);
168
169                // Step 5.5. If font face set’s failed fonts is non-empty, fire a font load event
170                // named loadingerror at font face set with failed fonts.
171                // TODO: This requires keeping track of [[FailedFonts]].
172            }));
173
174        true
175    }
176
177    pub(crate) fn waiting_to_fullfill_promise(&self) -> bool {
178        !self.promise.borrow().is_fulfilled()
179    }
180
181    fn contains_face(&self, target: &FontFace) -> bool {
182        self.set_entries
183            .borrow()
184            .iter()
185            .any(|face| &**face == target)
186    }
187
188    /// Removes a face from the set's set entries.
189    fn delete_face(&self, target: &FontFace) -> bool {
190        let mut set_entries = self.set_entries.borrow_mut();
191        let Some(index) = set_entries.iter().position(|face| &**face == target) else {
192            return false;
193        };
194        set_entries.remove(index);
195        true
196    }
197
198    /// <https://drafts.csswg.org/css-font-loading/#switch-the-fontfaceset-to-loading>
199    pub(crate) fn switch_to_loading(&self, cx: &mut JSContext) {
200        // Step 1. Let font face set be the given FontFaceSet.
201        // Note: This is self.
202
203        // Step 2. Set the status attribute of font face set to "loading".
204        self.status.set(FontFaceSetLoadStatus::Loading);
205
206        // Step 3. If font face set’s [[ReadyPromise]] slot currently holds a fulfilled
207        // promise, replace it with a fresh pending promise.
208        if self.promise.borrow().is_fulfilled() {
209            let promise = Promise::new(cx, &self.global());
210            *self.promise.safe_borrow_mut(cx.no_gc()) = promise.to_traced()
211        }
212
213        // Step 4. Queue a task to fire a font load event named loading at font face set.
214        let trusted_this = Trusted::new(self);
215        self.global()
216            .task_manager()
217            .font_loading_task_source()
218            .queue(task!(fire_font_set_loading_event: move |cx| {
219                let this = trusted_this.root();
220                this.fire_font_load_event(cx, Atom::from("loading"), &[]);
221            }));
222    }
223
224    /// <https://drafts.csswg.org/css-font-loading/#fire-a-font-load-event>
225    fn fire_font_load_event(
226        &self,
227        cx: &mut JSContext,
228        event_name: Atom,
229        font_faces: &[DomRoot<FontFace>],
230    ) {
231        // The fontfaces attribute is initialized to the given list of FontFace objects,
232        // filtered to only those contained in the FontFaceSet.
233        let font_faces: Vec<DomRoot<FontFace>> = font_faces
234            .iter()
235            .filter(|font_face| self.contains_face(font_face))
236            .cloned()
237            .collect();
238
239        let event = FontFaceSetLoadEvent::new(cx, &self.global(), event_name, &font_faces);
240        event.upcast::<Event>().fire(cx, self.upcast());
241    }
242
243    /// Runs the CSS cascade to ensure that new `@font-face` rules have
244    /// an entry in this set.
245    fn flush_author_font_set(&self, cx: &mut JSContext) {
246        // FIXME: Use a new sort of ReflowGoal that only runs the CSS cascade without
247        //        building a new box tree or running any sort of layout really.
248        //        We query for the box area here, but we're not interested in the result.
249        // Workers have no stylesheets, so there is nothing to flush for them.
250        if let Some(window) = DomRoot::downcast::<Window>(self.global()) {
251            let document = window.Document();
252            if document.stylesheets_changed_since_last_reflow() {
253                window.reflow(cx, ReflowGoal::LayoutQuery(QueryMsg::BoxArea));
254            }
255        }
256    }
257
258    /// Marks the entries corresponding to removed `@font-face` rules as not [css-connected].
259    ///
260    /// [css-connected]: https://drafts.csswg.org/css-font-loading/#css-connected
261    pub(crate) fn notify_font_face_rules_removed(
262        &self,
263        removed_font_face_rules: &[ServoArc<FontFaceRuleInfo>],
264    ) {
265        let entries = self.set_entries.borrow_mut();
266        for removed_font_face_rule in removed_font_face_rules {
267            let Some(matching_font_face_object) = entries
268                .iter()
269                .find(|entry| entry.is_connected_to_font_face_rule(removed_font_face_rule))
270            else {
271                if cfg!(debug_assertions) {
272                    unreachable!("Removed @font-face that was not previously present");
273                }
274                log::warn!("Removed @font-face that was not previously present");
275                continue;
276            };
277
278            // https://drafts.csswg.org/css-font-loading/#font-face-css-connection:
279            // > If a @font-face rule is removed from the document, its corresponding FontFace object is no longer CSS-connected.
280            // > The connection is not restorable by any means.
281            matching_font_face_object.disconnect_from_css();
282        }
283    }
284
285    /// Uses the font matching rules to select font faces within `self` that can be used to
286    /// render the provided text.
287    ///
288    /// This is used to implement Step 6 of
289    /// <https://drafts.csswg.org/css-font-loading/#find-the-matching-font-faces>.
290    fn query_fonts(&self, target_family: &FamilyName, sample_text: &str) -> Vec<DomRoot<FontFace>> {
291        let mut matching_fonts = Vec::default();
292        for font in self.set_entries.borrow().iter() {
293            let font_face_rule = font.css_font_face_rule();
294            let Some(font_face_rule) = font_face_rule.as_ref() else {
295                // FIXME: Don't ignore font faces that are not css-connected here.
296                continue;
297            };
298
299            if font_face_rule
300                .descriptors
301                .font_family
302                .as_ref()
303                .is_none_or(|family| family != target_family)
304            {
305                continue;
306            }
307
308            if font_face_rule
309                .descriptors
310                .unicode_range
311                .as_ref()
312                .is_some_and(|ranges| !any_character_in_any_unicode_range(sample_text, ranges))
313            {
314                continue;
315            }
316
317            // FIXME: Check other fields (weight, style, ...) here too. We need to investigate what other
318            // browsers are doing, because at this point the font isn't actually loaded yet,
319            // so the full descriptor is not available.
320            matching_fonts.push(font.as_rooted());
321        }
322
323        matching_fonts
324    }
325
326    /// <https://drafts.csswg.org/css-font-loading/#find-the-matching-font-faces>
327    fn find_the_matching_font_faces(
328        &self,
329        global: &GlobalScope,
330        font: &str,
331        sample_text: &str,
332    ) -> Result<Vec<DomRoot<FontFace>>, FontQuerySyntaxError> {
333        // Step 1. (Parse "font") and Step 2. (Unpack font shorthand) are implemented
334        // in FontQueryParameters::parse.
335        let parameters = FontQueryParameters::parse(global, font)?;
336
337        // Step 2. If text was not explicitly provided, let it be a string containing a
338        // single space character (U+0020 SPACE).
339        // Note: "text" is not optional in our implementation yet.
340
341        // Step 4. Let available font faces be the available font faces within source.
342        // If the allow system fonts flag is specified, add all system fonts to available font faces.
343
344        // Step 5. Let matched font faces initially be an empty list.
345        let mut matched_faces = vec![];
346
347        // Step 6. For each family in font family list, use the font matching rules to select the font faces
348        // from available font faces that match the font style, and add them to matched font faces.
349        // The use of the unicodeRange attribute means that this may be more than just a single font face.
350        // Step 7. If matched font faces is empty, set the found faces flag to false. Otherwise, set it to true.
351        // Note We don't need this yet.
352        // Step 8. For each font face in matched font faces, if its defined unicode-range does not include the
353        // codepoint of at least one character in text, remove it from the list.
354        for family in parameters.families.list.iter() {
355            let SingleFontFamily::FamilyName(target_family) = family else {
356                continue; // Skip generic font faces
357            };
358
359            matched_faces.extend_from_slice(&self.query_fonts(target_family, sample_text));
360        }
361
362        // Step 9. Return matched font faces and the found faces flag.
363        Ok(matched_faces)
364    }
365}
366
367impl FontFaceSetMethods<crate::DomTypeHolder> for FontFaceSet {
368    /// <https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-ready>
369    fn Ready(&self, cx: &mut JSContext) -> RootedPromise {
370        if self.promise.borrow().is_fulfilled() {
371            // There may be pending style changes that cause new web fonts to start loading,
372            // re-initializing document.fonts.ready.
373            self.flush_author_font_set(cx);
374        }
375        self.promise.borrow().root(cx)
376    }
377
378    /// <https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-status>
379    fn Status(&self) -> FontFaceSetLoadStatus {
380        self.status.get()
381    }
382
383    // <https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-onloading>
384    event_handler!(loading, GetOnloading, SetOnloading);
385
386    // <https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-onloadingdone>
387    event_handler!(loadingdone, GetOnloadingdone, SetOnloadingdone);
388
389    // <https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-onloadingerror>
390    event_handler!(loadingerror, GetOnloadingerror, SetOnloadingerror);
391
392    /// <https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-add>
393    fn Add(&self, cx: &mut JSContext, font_face: &FontFace) -> Fallible<DomRoot<FontFaceSet>> {
394        // Step 1. If font is already in the FontFaceSet’s set entries,
395        // skip to the last step of this algorithm immediately.
396        if self.contains_face(font_face) {
397            return Ok(DomRoot::from_ref(self));
398        }
399
400        // Step 2. If font is CSS-connected, throw an InvalidModificationError
401        // exception and exit this algorithm immediately.
402        if font_face.is_css_connected() {
403            return Err(Error::InvalidModification(Some(
404                "Cannot add CSS-connected FontFace to FontFaceSet".to_owned(),
405            )));
406        }
407
408        // Step 3. Add the font argument to the FontFaceSet’s set entries.
409        self.set_entries
410            .safe_borrow_mut(cx.no_gc())
411            .push(Dom::from_ref(font_face));
412        font_face.set_associated_font_face_set(self);
413
414        // Step 4. If font’s status attribute is "loading":
415        // Step 4.1 If the FontFaceSet’s [[LoadingFonts]] list is empty, switch the FontFaceSet to loading.
416        // Step 4.2 Append font to the FontFaceSet’s [[LoadingFonts]] list.
417        self.handle_font_face_status_changed(cx, font_face);
418
419        // Step 5. Return the FontFaceSet.
420        Ok(DomRoot::from_ref(self))
421    }
422
423    /// <https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-delete>
424    fn Delete(&self, to_delete: &FontFace) -> bool {
425        // Step 1. If font is CSS-connected, return false and exit this algorithm immediately.
426        if to_delete.is_css_connected() {
427            return false;
428        }
429
430        // Step 2. Let deleted be the result of removing font from the FontFaceSet’s set entries.
431        // TODO: Step 3. If font is present in the FontFaceSet’s [[LoadedFonts]], or [[FailedFonts]] lists, remove it.
432        // TODO: Step 4. If font is present in the FontFaceSet’s [[LoadingFonts]] list, remove it. If font was the last
433        // item in that list (and so the list is now empty), switch the FontFaceSet to loaded.
434        // Step 5. Return deleted.
435        self.delete_face(to_delete)
436    }
437
438    /// <https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-clear>
439    fn Clear(&self, cx: &mut JSContext) {
440        self.flush_author_font_set(cx);
441
442        // Step 1. Remove all non-CSS-connected items from the FontFaceSet’s set entries,
443        // its [[LoadedFonts]] list, and its [[FailedFonts]] list.
444        self.set_entries.safe_borrow_mut(cx.no_gc()).clear();
445
446        // TODO Step 2. If the FontFaceSet’s [[LoadingFonts]] list is non-empty, remove all items from it,
447        // then switch the FontFaceSet to loaded.
448    }
449
450    /// <https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-load>
451    fn Load(&self, cx: &mut JSContext, font: DOMString, text: DOMString) -> RootedPromise {
452        // Step 1. Let font face set be the FontFaceSet object this method was called on. Let
453        // promise be a newly-created promise object.
454        let load_promise = Promise::new(cx, &self.global());
455
456        // Step 2. Return promise. Complete the rest of these steps asynchronously.
457        #[derive(MallocSizeOf, JSTraceable)]
458        #[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
459        struct LoadPromiseFulfillmentHandler {
460            /// The font faces that this should wait on.
461            ///
462            /// (Our current implementation waits for `document.fonts.ready` instead)
463            font_face_objects: Vec<Dom<FontFace>>,
464
465            load_promise: TracedPromise,
466        }
467        impl Callback for LoadPromiseFulfillmentHandler {
468            fn callback(&self, cx: &mut CurrentRealm, _: Handle<Value>) {
469                let font_face_objects: Vec<DomRoot<FontFace>> = self
470                    .font_face_objects
471                    .iter()
472                    .map(|font_face| font_face.as_rooted())
473                    .collect();
474                self.load_promise.resolve_native(cx, &font_face_objects);
475            }
476        }
477
478        // Step 4. Queue a task to run the following steps synchronously:
479        let trusted_this = Trusted::new(self);
480        let trusted_load_promise = TrustedPromise::from(&load_promise);
481        let font = font.to_string();
482        let text = text.to_string();
483        self.global()
484            .task_manager()
485            .font_loading_task_source()
486            .queue(task!(resolve_font_face_set_load_task: move |cx| {
487                let load_promise = trusted_load_promise.root(cx);
488                let this = trusted_this.root();
489
490                // Step 3. Find the matching font faces from font face set using the font and text
491                // arguments passed to the function, and let font face list be the return value (ignoring
492                // the found faces flag). If a syntax error was returned, reject promise with a SyntaxError
493                // exception and terminate these steps.
494                let Ok(font_face_objects) = this.find_the_matching_font_faces(&this.global(), &font, &text) else {
495                    load_promise.reject_error(cx, Error::Syntax(Some("Failed to parse font query".into())));
496                    return;
497                };
498
499                // Step 4.1. For all of the font faces in the font face list, call their load()
500                // method.
501                // Step 4.2. Resolve promise with the result of waiting for all of the
502                // [[FontStatusPromise]]s of each font face in the font face list, in order.
503                //
504                // TODO: These steps are not implemented. Instead we wait until all fonts
505                // are loaded by resolving the returned promise when
506                // `document.fonts.ready` is resolved. The return list of fonts will not
507                // be correct, but any code that waits on the promise will have
508                // conservatively consistent behavior. This is important for preventing
509                // intermittent results in WPT tests.
510                let global = this.global();
511                let handler = PromiseNativeHandler::new(
512                    cx,
513                    &global,
514                    Some(Box::new(LoadPromiseFulfillmentHandler {
515                        font_face_objects: font_face_objects.into_iter().map(|font_face| font_face.as_traced()).collect(),
516                        load_promise: load_promise.to_traced(),
517                    })),
518                    None,
519                );
520
521                let ready_promise = this.Ready(cx);
522                let mut realm = enter_auto_realm(cx, &*global);
523                ready_promise.append_native_handler(&mut realm.current_realm(), &handler);
524            }));
525
526        // Step 2. Return promise. Complete the rest of these steps asynchronously.
527        load_promise
528    }
529
530    /// <https://html.spec.whatwg.org/multipage/#customstateset>
531    fn Size(&self, cx: &mut JSContext) -> u32 {
532        self.size(cx)
533    }
534}
535
536impl Setlike for FontFaceSet {
537    type Key = DomRoot<FontFace>;
538
539    #[inline(always)]
540    fn get_index(&self, cx: &mut JSContext, index: u32) -> Option<Self::Key> {
541        self.flush_author_font_set(cx);
542        self.set_entries
543            .borrow()
544            .get(index as usize)
545            .map(|face| face.as_rooted())
546    }
547
548    #[inline(always)]
549    fn size(&self, cx: &mut JSContext) -> u32 {
550        self.flush_author_font_set(cx);
551        self.set_entries.borrow().len() as u32
552    }
553
554    #[inline(always)]
555    fn add(&self, cx: &mut JSContext, face: Self::Key) {
556        self.set_entries
557            .safe_borrow_mut(cx.no_gc())
558            .push(face.as_traced());
559    }
560
561    #[inline(always)]
562    fn has(&self, cx: &mut JSContext, target: Self::Key) -> bool {
563        self.flush_author_font_set(cx);
564        self.contains_face(&target)
565    }
566
567    #[inline(always)]
568    fn clear(&self, cx: &mut JSContext) {
569        self.flush_author_font_set(cx);
570        self.set_entries.safe_borrow_mut(cx.no_gc()).clear();
571    }
572
573    #[inline(always)]
574    fn delete(&self, cx: &mut JSContext, to_delete: Self::Key) -> bool {
575        self.flush_author_font_set(cx);
576        self.delete_face(&to_delete)
577    }
578}
579
580/// Represents a parsed query for [`FontFaceSet::load`] and [`FontFaceSet::check`].
581///
582/// [`FontFaceSet::load`]: https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-load
583/// [`FontFaceSet::check`]: https://drafts.csswg.org/css-font-loading/#dom-fontfaceset-check
584struct FontQueryParameters {
585    families: FontFamilyList,
586    // TODO: Store a font descriptor here once we actually use that for matching.
587}
588
589/// Returned from <https://drafts.csswg.org/css-font-loading/#find-the-matching-font-faces> to indicate failure.
590struct FontQuerySyntaxError;
591
592impl FontQueryParameters {
593    /// Implements Steps 1 and 3 of <https://drafts.csswg.org/css-font-loading/#find-the-matching-font-faces>.
594    fn parse(global: &GlobalScope, font: &str) -> Result<Self, FontQuerySyntaxError> {
595        // Step 1. Parse font using the CSS value syntax of the font property.
596        // If a syntax error occurs, return a syntax error.
597        // If the parsed value is a CSS-wide keyword, return a syntax error.
598        // Absolutize all relative lengths against the initial values of the corresponding properties.
599        // (For example, a relative font weight like bolder is evaluated against the initial value normal.)
600        // Step 3. Let font family list be the list of font families parsed from font,
601        // and font style be the other font style attributes parsed from font.
602        let font_family;
603
604        let document = global.downcast::<Window>().map(|window| window.Document());
605        let urlextradata = UrlExtraData(global.api_base_url().get_arc());
606        let parser_context = match &document {
607            Some(document) => parser_context_for_document(
608                document,
609                CssRuleType::FontFace,
610                ParsingMode::DEFAULT,
611                &urlextradata,
612            ),
613            None => parser_context_for_worker(
614                CssRuleType::FontFace,
615                ParsingMode::DEFAULT,
616                &urlextradata,
617                None,
618            ),
619        };
620
621        let mut parser = Parser::new(font);
622        let Ok(font_shorthand) =
623            parser.parse_entirely(|parser| font::parse_value(&parser_context, parser))
624        else {
625            return Err(FontQuerySyntaxError);
626        };
627
628        match font_shorthand.font_family {
629            specified_font::FontFamily::Values(family_list) => font_family = family_list,
630            specified_font::FontFamily::System(_) => return Err(FontQuerySyntaxError),
631        }
632
633        Ok(Self {
634            families: font_family,
635        })
636    }
637}
638
639fn any_character_in_any_unicode_range(text: &str, unicode_ranges: &[UnicodeRange]) -> bool {
640    for character in text.chars() {
641        for unicode_range in unicode_ranges {
642            if (unicode_range.start..=unicode_range.end).contains(&(character as u32)) {
643                return true;
644            }
645        }
646    }
647    false
648}