script/dom/css/
cssstylesheet.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};
6use std::rc::Rc;
7
8use dom_struct::dom_struct;
9use js::rust::HandleObject;
10use script_bindings::inheritance::Castable;
11use script_bindings::realms::InRealm;
12use script_bindings::root::Dom;
13use servo_arc::Arc;
14use style::media_queries::MediaList as StyleMediaList;
15use style::shared_lock::{SharedRwLock, SharedRwLockReadGuard};
16use style::stylesheets::{
17    AllowImportRules, CssRuleTypes, Origin, Stylesheet as StyleStyleSheet, StylesheetContents,
18    StylesheetInDocument, UrlExtraData,
19};
20
21use super::cssrulelist::{CSSRuleList, RulesSource};
22use super::stylesheet::StyleSheet;
23use super::stylesheetlist::StyleSheetListOwner;
24use crate::dom::bindings::cell::DomRefCell;
25use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding::{
26    CSSStyleSheetInit, CSSStyleSheetMethods,
27};
28use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
29use crate::dom::bindings::codegen::GenericBindings::CSSRuleListBinding::CSSRuleList_Binding::CSSRuleListMethods;
30use crate::dom::bindings::codegen::UnionTypes::MediaListOrString;
31use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
32use crate::dom::bindings::refcounted::Trusted;
33use crate::dom::bindings::reflector::{
34    DomGlobal, reflect_dom_object, reflect_dom_object_with_proto,
35};
36use crate::dom::bindings::root::{DomRoot, MutNullableDom};
37use crate::dom::bindings::str::{DOMString, USVString};
38use crate::dom::document::Document;
39use crate::dom::element::Element;
40use crate::dom::html::htmlstyleelement::HTMLStyleElement;
41use crate::dom::medialist::MediaList;
42use crate::dom::node::NodeTraits;
43use crate::dom::types::Promise;
44use crate::dom::window::Window;
45use crate::script_runtime::CanGc;
46use crate::test::TrustedPromise;
47
48#[dom_struct]
49pub(crate) struct CSSStyleSheet {
50    stylesheet: StyleSheet,
51
52    /// <https://drafts.csswg.org/cssom/#concept-css-style-sheet-owner-node>
53    owner_node: MutNullableDom<Element>,
54
55    /// <https://drafts.csswg.org/cssom/#ref-for-concept-css-style-sheet-css-rules>
56    rulelist: MutNullableDom<CSSRuleList>,
57
58    /// The inner Stylo's [Stylesheet].
59    #[ignore_malloc_size_of = "Stylo"]
60    #[no_trace]
61    style_stylesheet: DomRefCell<Arc<StyleStyleSheet>>,
62
63    /// The inner Stylo's [SharedRwLock], stored at here to avoid referencing
64    /// temporary variables.
65    #[no_trace]
66    style_shared_lock: SharedRwLock,
67
68    /// <https://drafts.csswg.org/cssom/#concept-css-style-sheet-origin-clean-flag>
69    origin_clean: Cell<bool>,
70
71    /// In which [Document] that this stylesheet was constructed.
72    ///
73    /// <https://drafts.csswg.org/cssom/#concept-css-style-sheet-constructor-document>
74    constructor_document: Option<Dom<Document>>,
75
76    /// <https://drafts.csswg.org/cssom/#concept-css-style-sheet-disallow-modification-flag>
77    disallow_modification: Cell<bool>,
78
79    /// Documents or shadow DOMs thats adopt this stylesheet, they will be notified whenever
80    /// the stylesheet is modified.
81    adopters: DomRefCell<Vec<StyleSheetListOwner>>,
82}
83
84impl CSSStyleSheet {
85    fn new_inherited(
86        owner: Option<&Element>,
87        type_: DOMString,
88        href: Option<DOMString>,
89        title: Option<DOMString>,
90        stylesheet: Arc<StyleStyleSheet>,
91        constructor_document: Option<&Document>,
92    ) -> CSSStyleSheet {
93        CSSStyleSheet {
94            stylesheet: StyleSheet::new_inherited(type_, href, title),
95            owner_node: MutNullableDom::new(owner),
96            rulelist: MutNullableDom::new(None),
97            style_shared_lock: stylesheet.shared_lock.clone(),
98            style_stylesheet: DomRefCell::new(stylesheet),
99            origin_clean: Cell::new(true),
100            constructor_document: constructor_document.map(Dom::from_ref),
101            adopters: Default::default(),
102            disallow_modification: Cell::new(false),
103        }
104    }
105
106    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
107    #[allow(clippy::too_many_arguments)]
108    pub(crate) fn new(
109        window: &Window,
110        owner: Option<&Element>,
111        type_: DOMString,
112        href: Option<DOMString>,
113        title: Option<DOMString>,
114        stylesheet: Arc<StyleStyleSheet>,
115        constructor_document: Option<&Document>,
116        can_gc: CanGc,
117    ) -> DomRoot<CSSStyleSheet> {
118        reflect_dom_object(
119            Box::new(CSSStyleSheet::new_inherited(
120                owner,
121                type_,
122                href,
123                title,
124                stylesheet,
125                constructor_document,
126            )),
127            window,
128            can_gc,
129        )
130    }
131
132    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
133    #[allow(clippy::too_many_arguments)]
134    fn new_with_proto(
135        window: &Window,
136        proto: Option<HandleObject>,
137        owner: Option<&Element>,
138        type_: DOMString,
139        href: Option<DOMString>,
140        title: Option<DOMString>,
141        stylesheet: Arc<StyleStyleSheet>,
142        constructor_document: Option<&Document>,
143        can_gc: CanGc,
144    ) -> DomRoot<CSSStyleSheet> {
145        reflect_dom_object_with_proto(
146            Box::new(CSSStyleSheet::new_inherited(
147                owner,
148                type_,
149                href,
150                title,
151                stylesheet,
152                constructor_document,
153            )),
154            window,
155            proto,
156            can_gc,
157        )
158    }
159
160    fn rulelist(&self, can_gc: CanGc) -> DomRoot<CSSRuleList> {
161        self.rulelist.or_init(|| {
162            let sheet = self.style_stylesheet.borrow();
163            let guard = sheet.shared_lock.read();
164            let rules = sheet.contents(&guard).rules.clone();
165            CSSRuleList::new(
166                self.global().as_window(),
167                self,
168                RulesSource::Rules(rules),
169                can_gc,
170            )
171        })
172    }
173
174    pub(crate) fn disabled(&self) -> bool {
175        self.style_stylesheet.borrow().disabled()
176    }
177
178    pub(crate) fn owner_node(&self) -> Option<DomRoot<Element>> {
179        self.owner_node.get()
180    }
181
182    pub(crate) fn set_disabled(&self, disabled: bool) {
183        if self.style_stylesheet.borrow().set_disabled(disabled) {
184            self.notify_invalidations();
185        }
186    }
187
188    pub(crate) fn set_owner_node(&self, value: Option<&Element>) {
189        self.owner_node.set(value);
190    }
191
192    pub(crate) fn shared_lock(&self) -> &SharedRwLock {
193        &self.style_shared_lock
194    }
195
196    pub(crate) fn style_stylesheet(&self) -> Ref<'_, Arc<StyleStyleSheet>> {
197        self.style_stylesheet.borrow()
198    }
199
200    pub(crate) fn set_origin_clean(&self, origin_clean: bool) {
201        self.origin_clean.set(origin_clean);
202    }
203
204    pub(crate) fn medialist(&self, can_gc: CanGc) -> DomRoot<MediaList> {
205        MediaList::new(
206            self.global().as_window(),
207            self,
208            self.style_stylesheet().media.clone(),
209            can_gc,
210        )
211    }
212
213    /// <https://drafts.csswg.org/cssom/#concept-css-style-sheet-constructed-flag>
214    #[inline]
215    pub(crate) fn is_constructed(&self) -> bool {
216        self.constructor_document.is_some()
217    }
218
219    pub(crate) fn constructor_document_matches(&self, other_doc: &Document) -> bool {
220        match &self.constructor_document {
221            Some(doc) => *doc == other_doc,
222            None => false,
223        }
224    }
225
226    /// Add a [StyleSheetListOwner] as an adopter to be notified whenever this stylesheet is
227    /// modified.
228    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
229    pub(crate) fn add_adopter(&self, owner: StyleSheetListOwner) {
230        debug_assert!(self.is_constructed());
231        self.adopters.borrow_mut().push(owner);
232    }
233
234    pub(crate) fn remove_adopter(&self, owner: &StyleSheetListOwner) {
235        let adopters = &mut *self.adopters.borrow_mut();
236        if let Some(index) = adopters.iter().position(|o| o == owner) {
237            adopters.swap_remove(index);
238        }
239    }
240
241    pub(crate) fn will_modify(&self) {
242        let Some(node) = self.owner_node.get() else {
243            return;
244        };
245
246        let Some(node) = node.downcast::<HTMLStyleElement>() else {
247            return;
248        };
249
250        node.will_modify_stylesheet();
251    }
252
253    pub(crate) fn update_style_stylesheet(
254        &self,
255        style_stylesheet: &Arc<StyleStyleSheet>,
256        guard: &SharedRwLockReadGuard,
257    ) {
258        // When the shared `StylesheetContents` is about to be modified,
259        // `CSSStyleSheet::owner_node` performs a copy-on-write to avoid
260        // affecting other sharers, see `CSSStyleSheet::will_modify`. And
261        // then updates the references to `CssRule` or `PropertyDeclarationBlock`
262        // stored in the CSSOMs to ensure that modifications are made only
263        // on the new copy.
264        *self.style_stylesheet.borrow_mut() = style_stylesheet.clone();
265        if let Some(rulelist) = self.rulelist.get() {
266            let rules = style_stylesheet.contents(guard).rules.clone();
267            rulelist.update_rules(RulesSource::Rules(rules), guard);
268        }
269    }
270
271    /// Invalidate all stylesheet set this stylesheet is a part on.
272    pub(crate) fn notify_invalidations(&self) {
273        if let Some(owner) = self.owner_node() {
274            owner.stylesheet_list_owner().invalidate_stylesheets();
275        }
276        for adopter in self.adopters.borrow().iter() {
277            adopter.invalidate_stylesheets();
278        }
279    }
280
281    /// <https://drafts.csswg.org/cssom/#concept-css-style-sheet-disallow-modification-flag>
282    pub(crate) fn disallow_modification(&self) -> bool {
283        self.disallow_modification.get()
284    }
285
286    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-replacesync> Steps 2+
287    fn do_replace_sync(&self, text: USVString) {
288        // Step 2. Let rules be the result of running parse a stylesheet’s contents from text.
289        let global = self.global();
290        let window = global.as_window();
291
292        self.will_modify();
293
294        let _span = profile_traits::trace_span!("ParseStylesheet").entered();
295        let sheet = self.style_stylesheet();
296        let new_contents = StylesheetContents::from_str(
297            &text,
298            UrlExtraData(window.get_url().get_arc()),
299            Origin::Author,
300            &self.style_shared_lock,
301            None,
302            Some(window.css_error_reporter()),
303            window.Document().quirks_mode(),
304            AllowImportRules::No, // Step 3.If rules contains one or more @import rules, remove those rules from rules.
305            /* sanitization_data = */ None,
306        );
307
308        {
309            let mut write_guard = self.style_shared_lock.write();
310            *sheet.contents.write_with(&mut write_guard) = new_contents;
311        }
312
313        // Step 4. Set sheet’s CSS rules to rules.
314        // We reset our rule list, which will be initialized properly
315        // at the next getter access.
316        self.rulelist.set(None);
317
318        // Notify invalidation to update the styles immediately.
319        self.notify_invalidations();
320    }
321}
322
323impl CSSStyleSheetMethods<crate::DomTypeHolder> for CSSStyleSheet {
324    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-cssstylesheet>
325    fn Constructor(
326        window: &Window,
327        proto: Option<HandleObject>,
328        can_gc: CanGc,
329        options: &CSSStyleSheetInit,
330    ) -> DomRoot<Self> {
331        let doc = window.Document();
332        let shared_lock = doc.style_shared_lock().clone();
333        let media = Arc::new(shared_lock.wrap(match &options.media {
334            Some(media) => match media {
335                MediaListOrString::MediaList(media_list) => media_list.clone_media_list(),
336                MediaListOrString::String(str) => MediaList::parse_media_list(&str.str(), window),
337            },
338            None => StyleMediaList::empty(),
339        }));
340        let stylesheet = Arc::new(StyleStyleSheet::from_str(
341            "",
342            UrlExtraData(window.get_url().get_arc()),
343            Origin::Author,
344            media,
345            shared_lock,
346            None,
347            Some(window.css_error_reporter()),
348            doc.quirks_mode(),
349            AllowImportRules::No,
350        ));
351        if options.disabled {
352            stylesheet.set_disabled(true);
353        }
354        Self::new_with_proto(
355            window,
356            proto,
357            None, // owner
358            "text/css".into(),
359            None, // href
360            None, // title
361            stylesheet,
362            Some(&window.Document()), // constructor_document
363            can_gc,
364        )
365    }
366
367    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-cssrules>
368    fn GetCssRules(&self, can_gc: CanGc) -> Fallible<DomRoot<CSSRuleList>> {
369        if !self.origin_clean.get() {
370            return Err(Error::Security(None));
371        }
372        Ok(self.rulelist(can_gc))
373    }
374
375    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-insertrule>
376    fn InsertRule(&self, rule: DOMString, index: u32, can_gc: CanGc) -> Fallible<u32> {
377        // Step 1. If the origin-clean flag is unset, throw a SecurityError exception.
378        if !self.origin_clean.get() {
379            return Err(Error::Security(None));
380        }
381
382        // Step 2. If the disallow modification flag is set, throw a NotAllowedError DOMException.
383        if self.disallow_modification() {
384            return Err(Error::NotAllowed(None));
385        }
386
387        self.rulelist(can_gc)
388            .insert_rule(&rule, index, CssRuleTypes::default(), None, can_gc)
389    }
390
391    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-deleterule>
392    fn DeleteRule(&self, index: u32, can_gc: CanGc) -> ErrorResult {
393        // Step 1. If the origin-clean flag is unset, throw a SecurityError exception.
394        if !self.origin_clean.get() {
395            return Err(Error::Security(None));
396        }
397
398        // Step 2. If the disallow modification flag is set, throw a NotAllowedError DOMException.
399        if self.disallow_modification() {
400            return Err(Error::NotAllowed(None));
401        }
402        self.rulelist(can_gc).remove_rule(index)
403    }
404
405    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-rules>
406    fn GetRules(&self, can_gc: CanGc) -> Fallible<DomRoot<CSSRuleList>> {
407        self.GetCssRules(can_gc)
408    }
409
410    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-removerule>
411    fn RemoveRule(&self, index: u32, can_gc: CanGc) -> ErrorResult {
412        self.DeleteRule(index, can_gc)
413    }
414
415    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-addrule>
416    fn AddRule(
417        &self,
418        selector: DOMString,
419        block: DOMString,
420        optional_index: Option<u32>,
421        can_gc: CanGc,
422    ) -> Fallible<i32> {
423        // > 1. Let *rule* be an empty string.
424        // > 2. Append *selector* to *rule*.
425        let mut rule = selector;
426
427        // > 3. Append " { " to *rule*.
428        // > 4. If *block* is not empty, append *block*, followed by a space, to *rule*.
429        // > 5. Append "}" to *rule*.
430        if block.is_empty() {
431            rule.push_str(" { }");
432        } else {
433            rule.push_str(" { ");
434            rule.push_str(&block.str());
435            rule.push_str(" }");
436        };
437
438        // > 6. Let *index* be *optionalIndex* if provided, or the number of CSS rules in the stylesheet otherwise.
439        let index = optional_index.unwrap_or_else(|| self.rulelist(can_gc).Length());
440
441        // > 7. Call `insertRule()`, with *rule* and *index* as arguments.
442        self.InsertRule(rule, index, can_gc)?;
443
444        // > 8. Return -1.
445        Ok(-1)
446    }
447
448    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-replace>
449    fn Replace(&self, text: USVString, comp: InRealm, can_gc: CanGc) -> Fallible<Rc<Promise>> {
450        // Step 1. Let promise be a promise.
451        let promise = Promise::new_in_current_realm(comp, can_gc);
452
453        // Step 2. If the constructed flag is not set, or the disallow modification flag is set,
454        // reject promise with a NotAllowedError DOMException and return promise.
455        if !self.is_constructed() || self.disallow_modification() {
456            return Err(Error::NotAllowed(None));
457        }
458
459        // Step 3. Set the disallow modification flag.
460        self.disallow_modification.set(true);
461
462        // Step 4. In parallel, do these steps:
463        let trusted_sheet = Trusted::new(self);
464        let trusted_promise = TrustedPromise::new(promise.clone());
465
466        self.global()
467            .task_manager()
468            .dom_manipulation_task_source()
469            .queue(task!(cssstylesheet_replace: move || {
470                let sheet = trusted_sheet.root();
471
472                // Step 4.1..4.3
473                sheet.do_replace_sync(text);
474
475                // Step 4.4. Unset sheet’s disallow modification flag.
476                sheet.disallow_modification.set(false);
477
478                // Step 4.5. Resolve promise with sheet.
479                trusted_promise.root().resolve_native(&sheet, CanGc::note());
480            }));
481
482        Ok(promise)
483    }
484
485    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-replacesync>
486    fn ReplaceSync(&self, text: USVString) -> Result<(), Error> {
487        // Step 1. If the constructed flag is not set, or the disallow modification flag is set,
488        // throw a NotAllowedError DOMException.
489        if !self.is_constructed() || self.disallow_modification() {
490            return Err(Error::NotAllowed(None));
491        }
492        self.do_replace_sync(text);
493        Ok(())
494    }
495}