Skip to main content

script/dom/css/
fontface.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, Ref, RefCell};
6
7use cssparser::Parser;
8use dom_struct::dom_struct;
9use fonts::{
10    FontContext, FontContextWebFontMethods, FontFaceRuleInfo, FontTemplate, LowercaseFontFamilyName,
11};
12use js::context::JSContext;
13use js::rust::HandleObject;
14use script_bindings::cell::DomRefCell;
15use script_bindings::domstring::TracedDOMString;
16use script_bindings::reflector::{Reflector, reflect_dom_object_with_proto};
17use servo_arc::Arc as ServoArc;
18use style::error_reporting::ParseErrorReporter;
19use style::font_face::SourceList;
20use style::properties::font_face::Descriptors;
21use style::stylesheets::{CssRuleType, FontFaceRule, UrlExtraData};
22use style_traits::{ParsingMode, ToCss};
23
24use crate::css::css::{parser_context_for_document_with_reporter, parser_context_for_worker};
25use crate::dom::bindings::buffer_source::get_buffer_source_copy;
26use crate::dom::bindings::codegen::Bindings::FontFaceBinding::{
27    FontFaceDescriptors as FontFaceInputDescriptors, FontFaceLoadStatus, FontFaceMethods,
28};
29use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
30use crate::dom::bindings::codegen::UnionTypes;
31use crate::dom::bindings::codegen::UnionTypes::StringOrArrayBufferViewOrArrayBuffer;
32use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
33use crate::dom::bindings::inheritance::Castable;
34use crate::dom::bindings::refcounted::Trusted;
35use crate::dom::bindings::reflector::DomGlobal;
36use crate::dom::bindings::root::{DomRoot, MutNullableDom};
37use crate::dom::bindings::str::DOMString;
38use crate::dom::css::fontfaceset::FontFaceSet;
39use crate::dom::globalscope::GlobalScope;
40use crate::dom::promise::{Promise, RootedPromise, TracedPromise};
41use crate::dom::window::Window;
42
43/// <https://drafts.csswg.org/css-font-loading/#fontface-interface>
44#[dom_struct]
45pub struct FontFace {
46    reflector: Reflector,
47    status: Cell<FontFaceLoadStatus>,
48    family_name: DomRefCell<TracedDOMString>,
49
50    #[no_trace = "Does not contain managed objects"]
51    descriptors: DomRefCell<FontFaceDescriptors>,
52
53    /// A reference to the [`FontFaceSet`] that this `FontFace` is a member of, if it has been
54    /// added to one. `None` otherwise. The spec suggests that a `FontFace` can be a member of
55    /// multiple `FontFaceSet`s, but this doesn't seem to be the case in practice, as the
56    /// `FontFaceSet` constructor is not exposed on the global scope.
57    font_face_set: MutNullableDom<FontFaceSet>,
58
59    /// This holds the [`FontTemplate`] resulting from loading this `FontFace`, to be used when the
60    /// `FontFace` is added to the global `FontFaceSet` and thus the `[FontContext]`.
61    //
62    // TODO: This could potentially share the `FontTemplateRef` created by `FontContext`, rather
63    // than having its own copy of the template.
64    #[no_trace = "Does not contain managed objects"]
65    template: RefCell<Option<(LowercaseFontFamilyName, FontTemplate)>>,
66
67    #[no_trace = "Does not contain managed objects"]
68    /// <https://drafts.csswg.org/css-font-loading/#m-fontface-urls-slot>
69    urls: DomRefCell<Option<SourceList>>,
70
71    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-fontstatuspromise-slot>
72    font_status_promise: TracedPromise,
73
74    /// The `@font-face` rule that this `FontFace` object is [css-connected] to, if any.
75    ///
76    /// [css-connected]: https://drafts.csswg.org/css-font-loading/#css-connected
77    #[no_trace]
78    #[conditional_malloc_size_of]
79    css_font_face_rule: DomRefCell<Option<ServoArc<FontFaceRuleInfo>>>,
80}
81
82/// Given the various font face descriptors, construct the equivalent `@font-face` css rule as a
83/// string and parse it using `style` crate. Returns `Err(Error::Syntax)` if parsing fails.
84///
85/// Due to lack of support in the `style` crate, parsing the whole `@font-face` rule is much easier
86/// to implement than parsing each declaration on its own.
87fn parse_font_face_descriptors(
88    global: &GlobalScope,
89    family_name: &TracedDOMString,
90    sources: Option<&DOMString>,
91    input_descriptors: &FontFaceDescriptors,
92) -> Fallible<FontFaceRule> {
93    let document = global.downcast::<Window>().map(|window| window.Document());
94    let url_data = UrlExtraData(global.api_base_url().get_arc());
95    let error_reporter = FontFaceErrorReporter {
96        not_encountered_error: Cell::new(true),
97    };
98    let parser_context = match &document {
99        Some(document) => parser_context_for_document_with_reporter(
100            document,
101            CssRuleType::FontFace,
102            ParsingMode::DEFAULT,
103            &url_data,
104            &error_reporter,
105        ),
106        // Workers have no document, so the descriptors are parsed against the worker's URL.
107        None => parser_context_for_worker(
108            CssRuleType::FontFace,
109            ParsingMode::DEFAULT,
110            &url_data,
111            Some(&error_reporter),
112        ),
113    };
114
115    let FontFaceDescriptors {
116        ascent_override,
117        descent_override,
118        display,
119        feature_settings,
120        line_gap_override,
121        width,
122        style,
123        unicode_range,
124        variation_settings,
125        weight,
126    } = input_descriptors;
127
128    let maybe_sources = sources.map_or_else(String::new, |sources| format!("src: {sources};"));
129    let font_face_rule = format!(
130        r"
131        ascent-override: {ascent_override};
132        descent-override: {descent_override};
133        font-display: {display};
134        font-family: {family_name};
135        font-feature-settings: {feature_settings};
136        font-style: {style};
137        font-variation-settings: {variation_settings};
138        font-weight: {weight};
139        font-width: {width};
140        line-gap-override: {line_gap_override};
141        unicode-range: {unicode_range};
142        {maybe_sources}
143    "
144    );
145
146    // TODO: Should this be the source location in the script that invoked the font face API?
147    let location = cssparser::SourceLocation { line: 0, column: 0 };
148    let mut parser = Parser::new(&font_face_rule);
149    let mut parsed_font_face_rule =
150        style::font_face::parse_font_face_block(&parser_context, &mut parser, location);
151
152    if let Some(ref mut sources) = parsed_font_face_rule.descriptors.src {
153        let supported_sources: Vec<_> = sources
154            .0
155            .iter()
156            .rev()
157            .filter(FontContext::is_supported_web_font_source)
158            .cloned()
159            .collect();
160        if supported_sources.is_empty() {
161            error_reporter.not_encountered_error.set(false);
162        } else {
163            sources.0 = supported_sources;
164        }
165    }
166
167    if error_reporter.not_encountered_error.get() {
168        Ok(parsed_font_face_rule)
169    } else {
170        Err(Error::Syntax(Some(
171            "Failed to parse `@font-face` descriptors".into(),
172        )))
173    }
174}
175
176#[derive(Clone, MallocSizeOf)]
177pub(crate) struct FontFaceDescriptors {
178    ascent_override: DOMString,
179    descent_override: DOMString,
180    display: DOMString,
181    feature_settings: DOMString,
182    line_gap_override: DOMString,
183    style: DOMString,
184    unicode_range: DOMString,
185    variation_settings: DOMString,
186    weight: DOMString,
187    width: DOMString,
188}
189
190impl From<&FontFaceInputDescriptors> for FontFaceDescriptors {
191    fn from(descriptors: &FontFaceInputDescriptors) -> Self {
192        Self {
193            ascent_override: descriptors.ascentOverride.clone(),
194            descent_override: descriptors.descentOverride.clone(),
195            display: descriptors.display.clone(),
196            feature_settings: descriptors.featureSettings.clone(),
197            line_gap_override: descriptors.lineGapOverride.clone(),
198            style: descriptors.style.clone(),
199            unicode_range: descriptors.unicodeRange.clone(),
200            variation_settings: descriptors.variationSettings.clone(),
201            weight: descriptors.weight.clone(),
202            width: descriptors
203                .width
204                .clone()
205                .unwrap_or(descriptors.stretch.clone()),
206        }
207    }
208}
209
210/// Converts the descriptors of a `@font-face` rule (as defined by stylo) to
211/// the the IDL `FontFaceDescriptors` dictionary used by the JS interface.
212fn serialize_parsed_descriptors(descriptors: &Descriptors) -> FontFaceDescriptors {
213    FontFaceDescriptors {
214        ascent_override: descriptors.ascent_override.to_css_string().into(),
215        descent_override: descriptors.descent_override.to_css_string().into(),
216        display: descriptors.font_display.to_css_string().into(),
217        feature_settings: descriptors.font_feature_settings.to_css_string().into(),
218        line_gap_override: descriptors.line_gap_override.to_css_string().into(),
219        style: descriptors.font_style.to_css_string().into(),
220        unicode_range: descriptors.unicode_range.to_css_string().into(),
221        variation_settings: descriptors.font_variation_settings.to_css_string().into(),
222        weight: descriptors.font_weight.to_css_string().into(),
223        width: descriptors.font_width.to_css_string().into(),
224    }
225}
226
227struct FontFaceErrorReporter {
228    not_encountered_error: Cell<bool>,
229}
230
231impl ParseErrorReporter for FontFaceErrorReporter {
232    fn report_error(
233        &self,
234        _url: &UrlExtraData,
235        _location: cssparser::SourceLocation,
236        _error: style::error_reporting::ContextualParseError,
237    ) {
238        self.not_encountered_error.set(false);
239    }
240}
241
242impl FontFace {
243    /// Construct a [`FontFace`] to be used in the case of failure in parsing the
244    /// font face descriptors.
245    fn new_failed_font_face(
246        cx: &mut JSContext,
247        global: &GlobalScope,
248        proto: Option<HandleObject>,
249    ) -> DomRoot<Self> {
250        let font_status_promise = Promise::new(cx, global);
251        // If any of them fail to parse correctly, reject font face’s [[FontStatusPromise]] with a
252        // DOMException named "SyntaxError"
253        font_status_promise
254            .reject_error(cx, Error::Syntax(Some("Failed to parse font face".into())));
255
256        // set font face’s corresponding attributes to the empty string, and set font face’s status
257        // attribute to "error"
258        reflect_dom_object_with_proto(
259            cx,
260            Box::new(Self {
261                reflector: Reflector::new(),
262                font_face_set: MutNullableDom::default(),
263                font_status_promise: font_status_promise.to_traced(),
264                family_name: DomRefCell::default(),
265                urls: Default::default(),
266                descriptors: DomRefCell::new(FontFaceDescriptors {
267                    ascent_override: DOMString::new(),
268                    descent_override: DOMString::new(),
269                    display: DOMString::new(),
270                    feature_settings: DOMString::new(),
271                    line_gap_override: DOMString::new(),
272                    style: DOMString::new(),
273                    unicode_range: DOMString::new(),
274                    variation_settings: DOMString::new(),
275                    weight: DOMString::new(),
276                    width: DOMString::new(),
277                }),
278                status: Cell::new(FontFaceLoadStatus::Error),
279                template: RefCell::default(),
280                css_font_face_rule: Default::default(),
281            }),
282            global,
283            proto,
284        )
285    }
286
287    /// <https://drafts.csswg.org/css-font-loading/#font-face-constructor>
288    fn new_inherited(
289        family_name: DOMString,
290        urls: Option<SourceList>,
291        descriptors: &Descriptors,
292        font_status_promise: &RootedPromise,
293    ) -> Self {
294        Self {
295            reflector: Reflector::new(),
296
297            // Set font face’s status attribute to "unloaded".
298            status: Cell::new(FontFaceLoadStatus::Unloaded),
299
300            // Set font face’s corresponding attributes to the serialization of the parsed values.
301            descriptors: DomRefCell::new(serialize_parsed_descriptors(descriptors)),
302
303            font_face_set: MutNullableDom::default(),
304            family_name: DomRefCell::new(family_name.traced()),
305            urls: DomRefCell::new(urls),
306            template: RefCell::default(),
307            font_status_promise: font_status_promise.to_traced(),
308            css_font_face_rule: Default::default(),
309        }
310    }
311
312    /// <https://drafts.csswg.org/css-font-loading/#font-face-constructor>
313    pub(crate) fn new(
314        cx: &mut JSContext,
315        global: &GlobalScope,
316        proto: Option<HandleObject>,
317        font_family: DOMString,
318        urls: Option<SourceList>,
319        descriptors: &Descriptors,
320        font_status_promise: &RootedPromise,
321    ) -> DomRoot<Self> {
322        reflect_dom_object_with_proto(
323            cx,
324            Box::new(Self::new_inherited(
325                font_family,
326                urls,
327                descriptors,
328                font_status_promise,
329            )),
330            global,
331            proto,
332        )
333    }
334
335    /// Constructs a unrooted `FontFace` object for a font that is backed by a `@font-face` rule.
336    pub(crate) fn new_inherited_for_web_font(
337        family_name: DOMString,
338        descriptors: FontFaceDescriptors,
339        src: Option<SourceList>,
340        font_status_promise: &RootedPromise,
341        font_face_rule: ServoArc<FontFaceRuleInfo>,
342    ) -> Self {
343        Self {
344            reflector: Reflector::new(),
345            status: Cell::new(FontFaceLoadStatus::Loading),
346            descriptors: DomRefCell::new(descriptors),
347            font_face_set: MutNullableDom::default(),
348            family_name: DomRefCell::new(family_name.traced()),
349            urls: DomRefCell::new(src),
350            template: RefCell::default(),
351            font_status_promise: font_status_promise.to_traced(),
352            css_font_face_rule: DomRefCell::new(Some(font_face_rule)),
353        }
354    }
355
356    /// Constructs a `FontFace` object for a font that is backed by a `@font-face` rule.
357    pub(crate) fn new_for_web_font(
358        cx: &mut JSContext,
359        global: &GlobalScope,
360        font_face_rule: ServoArc<FontFaceRuleInfo>,
361    ) -> Option<DomRoot<Self>> {
362        let Some(family_name) = font_face_rule
363            .descriptors
364            .font_family
365            .as_ref()
366            .map(|name| TracedDOMString::from(name.name.clone()).root())
367        else {
368            // Web fonts without a family name are not loaded, and they should not appear in document.fonts either.
369            return None;
370        };
371
372        // https://drafts.csswg.org/css-font-loading/#font-face-css-connection
373        // > The FontFace object corresponding to a @font-face rule has its family, style, weight, stretch,
374        // > unicodeRange, variant, and featureSettings attributes set to the same value as the corresponding
375        // > descriptors in the @font-face rule.
376        let descriptors = serialize_parsed_descriptors(&font_face_rule.descriptors);
377
378        let font_status_promise = Promise::new(cx, global);
379        Some(reflect_dom_object_with_proto(
380            cx,
381            Box::new(Self::new_inherited_for_web_font(
382                family_name,
383                descriptors,
384                font_face_rule.descriptors.src.clone(),
385                &font_status_promise,
386                font_face_rule,
387            )),
388            global,
389            None,
390        ))
391    }
392
393    /// Mark this font face as *not* [css-connected].
394    ///
395    /// [css-connected]: https://drafts.csswg.org/css-font-loading/#css-connected
396    pub(crate) fn disconnect_from_css(&self) {
397        *self.css_font_face_rule.borrow_mut() = None;
398    }
399
400    /// <https://drafts.csswg.org/css-font-loading/#css-connected>
401    pub(crate) fn is_css_connected(&self) -> bool {
402        self.css_font_face_rule().is_some()
403    }
404
405    pub(crate) fn css_font_face_rule(&self) -> Ref<'_, Option<ServoArc<FontFaceRuleInfo>>> {
406        self.css_font_face_rule.borrow()
407    }
408
409    /// Return true if the `FontFace` is [css-connected] *and* was created by the provided
410    /// `@font-face` rule.
411    ///
412    /// [css-connected]: https://drafts.csswg.org/css-font-loading/#css-connected
413    pub(crate) fn is_connected_to_font_face_rule(
414        &self,
415        target_rule: &ServoArc<FontFaceRuleInfo>,
416    ) -> bool {
417        self.css_font_face_rule()
418            .as_ref()
419            .is_some_and(|connected_rule| ServoArc::ptr_eq(connected_rule, target_rule))
420    }
421
422    /// Step 3 of <https://drafts.csswg.org/css-font-loading/#font-face-constructor>
423    fn load_from_data(&self, cx: &mut JSContext, global: &GlobalScope, data: Vec<u8>) {
424        // Step 3.1 Set font face’s status attribute to "loading".
425        self.status.set(FontFaceLoadStatus::Loading);
426
427        // Step 3.2 For each FontFaceSet font face is in:
428        if let Some(font_face_set) = self.font_face_set.get() {
429            font_face_set.handle_font_face_status_changed(cx, self);
430        }
431
432        // Asynchronously, attempt to parse the data in it as a font. When this is completed,
433        // successfully or not, queue a task to run the following steps synchronously:
434        // FIXME: This is not asynchronous.
435        let parsed_font_face_rule = self.font_face_rule(global);
436        let result = parsed_font_face_rule
437            .ok()
438            .and_then(|parsed_font_face_rule| {
439                global
440                    .font_context()
441                    .construct_web_font_from_data(&data, (&parsed_font_face_rule).into())
442            });
443
444        if let Some(template) = result {
445            // Step 1. If the load was successful, font face now represents the parsed font; fulfill font face’s
446            // [[FontStatusPromise]] with font face, and set its status attribute to "loaded".
447            self.font_status_promise.resolve_native(cx, &self);
448            self.status.set(FontFaceLoadStatus::Loaded);
449            *self.template.borrow_mut() = Some(template);
450
451            // For each FontFaceSet font face is in:
452            if let Some(font_face_set) = self.font_face_set.get() {
453                // Add font face to the FontFaceSet’s [[LoadedFonts]] list.
454                // Remove font face from the FontFaceSet’s [[LoadingFonts]] list.
455                // If font was the last item in that list (and so the list is now empty),
456                // switch the FontFaceSet to loaded.
457                font_face_set.handle_font_face_status_changed(cx, self);
458            }
459        } else {
460            // Step 2. Otherwise, reject font face’s [[FontStatusPromise]] with a DOMException named "SyntaxError"
461            // and set font face’s status attribute to "error".
462            self.font_status_promise
463                .reject_error(cx, Error::Syntax(Some("Failed to parse font data".into())));
464            self.status.set(FontFaceLoadStatus::Error);
465
466            // For each FontFaceSet font face is in:
467            if let Some(font_face_set) = self.font_face_set.get() {
468                // Add font face to the FontFaceSet’s [[FailedFonts]] list.
469                // Remove font face from the FontFaceSet’s [[LoadingFonts]] list.
470                // If font was the last item in that list (and so the list is now empty),
471                // switch the FontFaceSet to loaded.
472                font_face_set.handle_font_face_status_changed(cx, self);
473            }
474        }
475    }
476
477    pub(super) fn set_associated_font_face_set(&self, font_face_set: &FontFaceSet) {
478        self.font_face_set.set(Some(font_face_set));
479    }
480
481    pub(super) fn template(&self) -> Option<(LowercaseFontFamilyName, FontTemplate)> {
482        self.template.borrow().clone()
483    }
484
485    /// Implements the body of the setter for the descriptor attributes of the [`FontFace`] interface.
486    ///
487    /// <https://drafts.csswg.org/css-font-loading/#fontface-interface>:
488    /// On setting, parse the string according to the grammar for the corresponding @font-face
489    /// descriptor. If it does not match the grammar, throw a SyntaxError; otherwise, set the attribute
490    /// to the serialization of the parsed value.
491    fn validate_and_set_descriptors(&self, new_descriptors: FontFaceDescriptors) -> ErrorResult {
492        let global = self.global();
493        let parsed_font_face_rule = parse_font_face_descriptors(
494            &global,
495            &self.family_name.borrow(),
496            None,
497            &new_descriptors,
498        )?;
499
500        *self.descriptors.borrow_mut() =
501            serialize_parsed_descriptors(&parsed_font_face_rule.descriptors);
502        Ok(())
503    }
504
505    fn font_face_rule(&self, global: &GlobalScope) -> Fallible<FontFaceRule> {
506        // TODO: We should not have to parse the descriptors over and over again here.
507        // We can probably store them on the `FontFace` instead.
508        parse_font_face_descriptors(
509            global,
510            &self.family_name.borrow(),
511            None,
512            &self.descriptors.borrow(),
513        )
514    }
515}
516
517impl FontFaceMethods<crate::DomTypeHolder> for FontFace {
518    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-family>
519    fn Family(&self) -> DOMString {
520        self.family_name.borrow().clone().root()
521    }
522
523    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-family>
524    fn SetFamily(&self, family_name: DOMString) -> ErrorResult {
525        let descriptors = self.descriptors.borrow();
526        let global = self.global();
527        let _ = parse_font_face_descriptors(&global, &family_name, None, &descriptors)?;
528        *self.family_name.borrow_mut() = family_name.traced();
529        Ok(())
530    }
531
532    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-style>
533    fn Style(&self) -> DOMString {
534        self.descriptors.borrow().style.clone()
535    }
536
537    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-style>
538    fn SetStyle(&self, value: DOMString) -> ErrorResult {
539        let mut new_descriptors = self.descriptors.borrow().clone();
540        new_descriptors.style = value;
541        self.validate_and_set_descriptors(new_descriptors)
542    }
543
544    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-weight>
545    fn Weight(&self) -> DOMString {
546        self.descriptors.borrow().weight.clone()
547    }
548
549    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-weight>
550    fn SetWeight(&self, value: DOMString) -> ErrorResult {
551        let mut new_descriptors = self.descriptors.borrow().clone();
552        new_descriptors.weight = value;
553        self.validate_and_set_descriptors(new_descriptors)
554    }
555
556    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-width>
557    fn Width(&self) -> DOMString {
558        self.descriptors.borrow().width.clone()
559    }
560
561    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-width>
562    fn SetWidth(&self, value: DOMString) -> ErrorResult {
563        let mut new_descriptors = self.descriptors.borrow().clone();
564        new_descriptors.width = value;
565        self.validate_and_set_descriptors(new_descriptors)
566    }
567
568    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-unicoderange>
569    fn UnicodeRange(&self) -> DOMString {
570        self.descriptors.borrow().unicode_range.clone()
571    }
572
573    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-unicoderange>
574    fn SetUnicodeRange(&self, value: DOMString) -> ErrorResult {
575        let mut new_descriptors = self.descriptors.borrow().clone();
576        new_descriptors.unicode_range = value;
577        self.validate_and_set_descriptors(new_descriptors)
578    }
579
580    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-featuresettings>
581    fn FeatureSettings(&self) -> DOMString {
582        self.descriptors.borrow().feature_settings.clone()
583    }
584
585    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-featuresettings>
586    fn SetFeatureSettings(&self, value: DOMString) -> ErrorResult {
587        let mut new_descriptors = self.descriptors.borrow().clone();
588        new_descriptors.feature_settings = value;
589        self.validate_and_set_descriptors(new_descriptors)
590    }
591
592    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-variationsettings>
593    fn VariationSettings(&self) -> DOMString {
594        self.descriptors.borrow().variation_settings.clone()
595    }
596
597    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-variationsettings>
598    fn SetVariationSettings(&self, value: DOMString) -> ErrorResult {
599        let mut new_descriptors = self.descriptors.borrow().clone();
600        new_descriptors.variation_settings = value;
601        self.validate_and_set_descriptors(new_descriptors)
602    }
603
604    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-display>
605    fn Display(&self) -> DOMString {
606        self.descriptors.borrow().display.clone()
607    }
608
609    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-display>
610    fn SetDisplay(&self, value: DOMString) -> ErrorResult {
611        let mut new_descriptors = self.descriptors.borrow().clone();
612        new_descriptors.display = value;
613        self.validate_and_set_descriptors(new_descriptors)
614    }
615
616    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-ascentoverride>
617    fn AscentOverride(&self) -> DOMString {
618        self.descriptors.borrow().ascent_override.clone()
619    }
620
621    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-ascentoverride>
622    fn SetAscentOverride(&self, value: DOMString) -> ErrorResult {
623        let mut new_descriptors = self.descriptors.borrow().clone();
624        new_descriptors.ascent_override = value;
625        self.validate_and_set_descriptors(new_descriptors)
626    }
627
628    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-descentoverride>
629    fn DescentOverride(&self) -> DOMString {
630        self.descriptors.borrow().descent_override.clone()
631    }
632
633    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-descentoverride>
634    fn SetDescentOverride(&self, value: DOMString) -> ErrorResult {
635        let mut new_descriptors = self.descriptors.borrow().clone();
636        new_descriptors.descent_override = value;
637        self.validate_and_set_descriptors(new_descriptors)
638    }
639
640    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-linegapoverride>
641    fn LineGapOverride(&self) -> DOMString {
642        self.descriptors.borrow().line_gap_override.clone()
643    }
644
645    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-linegapoverride>
646    fn SetLineGapOverride(&self, value: DOMString) -> ErrorResult {
647        let mut new_descriptors = self.descriptors.borrow().clone();
648        new_descriptors.line_gap_override = value;
649        self.validate_and_set_descriptors(new_descriptors)
650    }
651
652    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-status>
653    fn Status(&self) -> FontFaceLoadStatus {
654        self.status.get()
655    }
656
657    /// The load() method of FontFace forces a url-based font face to request its font data and
658    /// load. For fonts constructed from a buffer source, or fonts that are already loading or
659    /// loaded, it does nothing.
660    /// <https://drafts.csswg.org/css-font-loading/#font-face-load>
661    fn Load(&self, cx: &mut JSContext) -> RootedPromise {
662        // Step 2. If font face’s [[Urls]] slot is null, or its status attribute is anything
663        // other than "unloaded", return font face’s [[FontStatusPromise]] and abort these
664        // steps.
665        let Some(sources) = self.urls.safe_borrow_mut(cx.no_gc()).take() else {
666            return self.font_status_promise.root(cx);
667        };
668        if self.status.get() != FontFaceLoadStatus::Unloaded {
669            return self.font_status_promise.root(cx);
670        }
671
672        let global = self.global();
673        let trusted = Trusted::new(self);
674        let task_source = global
675            .task_manager()
676            .font_loading_task_source()
677            .to_sendable();
678
679        let finished_callback = Box::new(
680            move |family_name: LowercaseFontFamilyName, load_result: Option<_>| {
681                let trusted = trusted.clone();
682
683                // Step 5. When the load operation completes, successfully or not, queue a task to
684                // run the following steps synchronously:
685                task_source.queue(task!(resolve_font_face_load_task: move |cx| {
686                    let font_face = trusted.root();
687
688                    match load_result {
689                        None => {
690                            // Step 5.1. If the attempt to load fails, reject font face’s
691                            // [[FontStatusPromise]] with a DOMException whose name is "NetworkError"
692                            // and set font face’s status attribute to "error".
693                            font_face.status.set(FontFaceLoadStatus::Error);
694                            font_face.font_status_promise.reject_error(cx, Error::Network(Some("Failed to load font data".into())));
695                        }
696                        Some(template) => {
697                            // Step 5.2. Otherwise, font face now represents the loaded font;
698                            // fulfill font face’s [[FontStatusPromise]] with font face and set
699                            // font face’s status attribute to "loaded".
700                            font_face.status.set(FontFaceLoadStatus::Loaded);
701                            let old_template = font_face.template.borrow_mut().replace((family_name, template));
702                            debug_assert!(old_template.is_none(), "FontFace's template must be intialized only once");
703                            font_face.font_status_promise.resolve_native(cx, &font_face);
704                        }
705                    }
706
707                    if let Some(font_face_set) = font_face.font_face_set.get() {
708                        // For each FontFaceSet font face is in: ...
709                        //
710                        // This implements steps 5.1.1, 5.1.2, 5.2.1 and 5.2.2 - these
711                        // take care of changing the status of the `FontFaceSet` in which this
712                        // `FontFace` is a member, for both failed and successful load.
713                        font_face_set.handle_font_face_status_changed(cx, &font_face);
714                    }
715                }));
716            },
717        );
718
719        // We parse the descriptors again because they are stored as `DOMString`s in this `FontFace`
720        // but the `load_web_font_for_script` API needs parsed values.
721        let parsed_font_face_rule = self
722            .font_face_rule(&global)
723            .expect("Parsing shouldn't fail as descriptors are valid by construction");
724
725        // Construct a WebFontDocumentContext object for this global.
726        let document_context = global.web_font_context(cx.no_gc());
727
728        // Step 4. Using the value of font face’s [[Urls]] slot, attempt to load a font as defined
729        // in [CSS-FONTS-3], as if it was the value of a @font-face rule’s src descriptor.
730        global.font_context().load_web_font_for_script(
731            global.webview_id(),
732            sources,
733            (&parsed_font_face_rule).into(),
734            finished_callback,
735            &document_context,
736        );
737
738        // Step 3. Set font face’s status attribute to "loading", return font face’s
739        // [[FontStatusPromise]], and continue executing the rest of this algorithm asynchronously.
740        self.status.set(FontFaceLoadStatus::Loading);
741
742        // See <https://github.com/w3c/csswg-drafts/issues/13235>:
743        // All browsers switch the FontFaceSet to loading, but this is currently missing
744        // from the specification.
745        if let Some(font_face_set) = self.font_face_set.get() {
746            font_face_set.handle_font_face_status_changed(cx, self);
747        }
748
749        self.font_status_promise.root(cx)
750    }
751
752    /// <https://drafts.csswg.org/css-font-loading/#dom-fontface-loaded>
753    fn Loaded(&self, cx: &JSContext) -> RootedPromise {
754        self.font_status_promise.root(cx)
755    }
756
757    /// <https://drafts.csswg.org/css-font-loading/#font-face-constructor>
758    fn Constructor(
759        cx: &mut JSContext,
760        global: &GlobalScope,
761        proto: Option<HandleObject>,
762        family: DOMString,
763        source: UnionTypes::StringOrArrayBufferViewOrArrayBuffer,
764        descriptors: &FontFaceInputDescriptors,
765    ) -> DomRoot<FontFace> {
766        // Step 2. If the source argument was a CSSOMString, set font face’s internal [[Urls]] slot to the string.
767        let url_source = if let StringOrArrayBufferViewOrArrayBuffer::String(source) = &source {
768            Some(source)
769        } else {
770            None
771        };
772        // All the rest of the comments are part of step 1:
773
774        // Parse the family argument, and the members of the descriptors argument,
775        // according to the grammars of the corresponding descriptors of the CSS @font-face rule If
776        // the source argument is a CSSOMString, parse it according to the grammar of the CSS src
777        // descriptor of the @font-face rule.
778        let parse_result =
779            parse_font_face_descriptors(global, &family, url_source, &descriptors.into());
780
781        let Ok(ref parsed_font_face_rule) = parse_result else {
782            // If any of them fail to parse correctly, reject font face’s
783            // [[FontStatusPromise]] with a DOMException named "SyntaxError", set font face’s
784            // corresponding attributes to the empty string, and set font face’s status attribute
785            // to "error".
786            return Self::new_failed_font_face(cx, global, proto);
787        };
788
789        // Set its internal [[FontStatusPromise]] slot to a fresh pending Promise object.
790        let font_status_promise = Promise::new(cx, global);
791
792        let sources = parsed_font_face_rule.descriptors.src.clone();
793        // Let font face be a fresh FontFace object.
794        let font_face = FontFace::new(
795            cx,
796            global,
797            proto,
798            family,
799            sources,
800            &parsed_font_face_rule.descriptors,
801            &font_status_promise,
802        );
803
804        // If font face’s status is "error", terminate this algorithm;
805        // otherwise, complete the rest of these steps asynchronously.
806        if font_face.Status() == FontFaceLoadStatus::Error {
807            return font_face;
808        }
809
810        // Step 2. If the source argument was a BufferSource, set font face’s internal
811        // [[Data]] slot to the passed argument.
812        // Step 3. If font face’s [[Data]] slot is not null, queue a task to run the following steps
813        // synchronously:
814        let font_face_bytes = match &source {
815            StringOrArrayBufferViewOrArrayBuffer::String(_) => {
816                // Return font face.
817                return font_face;
818            },
819            StringOrArrayBufferViewOrArrayBuffer::ArrayBufferView(view) => {
820                get_buffer_source_copy(view.into())
821            },
822            StringOrArrayBufferViewOrArrayBuffer::ArrayBuffer(buffer) => {
823                get_buffer_source_copy(buffer.into())
824            },
825        };
826        let trusted_font_face = Trusted::new(&*font_face);
827        let trusted_global = Trusted::new(global);
828        global
829            .task_manager()
830            .font_loading_task_source()
831            .queue(task!(
832                load_font_from_arraybuffer: move |cx| {
833                    let font_face = trusted_font_face.root();
834                    let global = trusted_global.root();
835
836                    font_face.load_from_data(cx, &global, font_face_bytes);
837                }
838            ));
839
840        // Return font face.
841        font_face
842    }
843}