script/dom/html/
htmlstyleelement.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;
6use std::sync::atomic::{AtomicBool, Ordering};
7
8use dom_struct::dom_struct;
9use html5ever::{LocalName, Prefix};
10use js::rust::HandleObject;
11use net_traits::ReferrerPolicy;
12use script_bindings::root::Dom;
13use servo_arc::Arc;
14use style::media_queries::MediaList as StyleMediaList;
15use style::shared_lock::DeepCloneWithLock;
16use style::stylesheets::{
17    AllowImportRules, Origin, Stylesheet, StylesheetContents, StylesheetInDocument, UrlExtraData,
18};
19
20use crate::dom::attr::Attr;
21use crate::dom::bindings::cell::DomRefCell;
22use crate::dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods;
23use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
24use crate::dom::bindings::inheritance::Castable;
25use crate::dom::bindings::root::{DomRoot, MutNullableDom};
26use crate::dom::bindings::str::DOMString;
27use crate::dom::csp::{CspReporting, InlineCheckType};
28use crate::dom::css::cssstylesheet::CSSStyleSheet;
29use crate::dom::css::stylesheet::StyleSheet as DOMStyleSheet;
30use crate::dom::css::stylesheetcontentscache::{
31    StylesheetContentsCache, StylesheetContentsCacheKey,
32};
33use crate::dom::document::Document;
34use crate::dom::documentorshadowroot::StylesheetSource;
35use crate::dom::element::{AttributeMutation, Element, ElementCreator};
36use crate::dom::html::htmlelement::HTMLElement;
37use crate::dom::medialist::MediaList;
38use crate::dom::node::{BindContext, ChildrenMutation, Node, NodeTraits, UnbindContext};
39use crate::dom::virtualmethods::VirtualMethods;
40use crate::script_runtime::CanGc;
41use crate::stylesheet_loader::{ElementStylesheetLoader, StylesheetOwner};
42
43#[dom_struct]
44pub(crate) struct HTMLStyleElement {
45    htmlelement: HTMLElement,
46    #[conditional_malloc_size_of]
47    #[no_trace]
48    stylesheet: DomRefCell<Option<Arc<Stylesheet>>>,
49    #[no_trace]
50    stylesheetcontents_cache_key: DomRefCell<Option<StylesheetContentsCacheKey>>,
51    cssom_stylesheet: MutNullableDom<CSSStyleSheet>,
52    /// <https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts>
53    parser_inserted: Cell<bool>,
54    in_stack_of_open_elements: Cell<bool>,
55    pending_loads: Cell<u32>,
56    any_failed_load: Cell<bool>,
57}
58
59impl HTMLStyleElement {
60    fn new_inherited(
61        local_name: LocalName,
62        prefix: Option<Prefix>,
63        document: &Document,
64        creator: ElementCreator,
65    ) -> HTMLStyleElement {
66        HTMLStyleElement {
67            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
68            stylesheet: DomRefCell::new(None),
69            stylesheetcontents_cache_key: DomRefCell::new(None),
70            cssom_stylesheet: MutNullableDom::new(None),
71            parser_inserted: Cell::new(creator.is_parser_created()),
72            in_stack_of_open_elements: Cell::new(creator.is_parser_created()),
73            pending_loads: Cell::new(0),
74            any_failed_load: Cell::new(false),
75        }
76    }
77
78    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
79    pub(crate) fn new(
80        local_name: LocalName,
81        prefix: Option<Prefix>,
82        document: &Document,
83        proto: Option<HandleObject>,
84        creator: ElementCreator,
85        can_gc: CanGc,
86    ) -> DomRoot<HTMLStyleElement> {
87        Node::reflect_node_with_proto(
88            Box::new(HTMLStyleElement::new_inherited(
89                local_name, prefix, document, creator,
90            )),
91            document,
92            proto,
93            can_gc,
94        )
95    }
96
97    #[inline]
98    fn create_media_list(&self, mq_str: &str) -> StyleMediaList {
99        MediaList::parse_media_list(mq_str, &self.owner_window())
100    }
101
102    pub(crate) fn parse_own_css(&self) {
103        let node = self.upcast::<Node>();
104        assert!(
105            node.is_in_a_document_tree() || node.is_in_a_shadow_tree(),
106            "This stylesheet does not have an owner, so there's no reason to parse its contents"
107        );
108
109        // Step 4. of <https://html.spec.whatwg.org/multipage/#the-style-element%3Aupdate-a-style-block>
110        let mut type_attribute = self.Type();
111        type_attribute.make_ascii_lowercase();
112        if !type_attribute.is_empty() && type_attribute != "text/css" {
113            return;
114        }
115
116        let doc = self.owner_document();
117        let global = &self.owner_global();
118
119        // Step 5: If the Should element's inline behavior be blocked by Content Security Policy? algorithm
120        // returns "Blocked" when executed upon the style element, "style",
121        // and the style element's child text content, then return. [CSP]
122        if global
123            .get_csp_list()
124            .should_elements_inline_type_behavior_be_blocked(
125                global,
126                self.upcast(),
127                InlineCheckType::Style,
128                &node.child_text_content().str(),
129            )
130        {
131            return;
132        }
133
134        let window = node.owner_window();
135        let data = node
136            .GetTextContent()
137            .expect("Element.textContent must be a string");
138        let shared_lock = node.owner_doc().style_shared_lock().clone();
139        let mq = Arc::new(shared_lock.wrap(self.create_media_list(&self.Media().str())));
140        let loader = ElementStylesheetLoader::new(self.upcast());
141
142        let stylesheetcontents_create_callback = || {
143            #[cfg(feature = "tracing")]
144            let _span = tracing::trace_span!("ParseStylesheet", servo_profiling = true).entered();
145            StylesheetContents::from_str(
146                &data.str(),
147                UrlExtraData(window.get_url().get_arc()),
148                Origin::Author,
149                &shared_lock,
150                Some(&loader),
151                window.css_error_reporter(),
152                doc.quirks_mode(),
153                AllowImportRules::Yes,
154                /* sanitized_output = */ None,
155            )
156        };
157
158        // For duplicate style sheets with identical content, `StylesheetContents` can be reused
159        // to avoid reedundant parsing of the style sheets. Additionally, the cache hit rate of
160        // stylo's `CascadeDataCache` can now be significantly improved. When shared `StylesheetContents`
161        // is modified, copy-on-write will occur, see `CSSStyleSheet::will_modify`.
162        let (cache_key, contents) = StylesheetContentsCache::get_or_insert_with(
163            &data.str(),
164            &shared_lock,
165            UrlExtraData(window.get_url().get_arc()),
166            doc.quirks_mode(),
167            stylesheetcontents_create_callback,
168        );
169
170        let sheet = Arc::new(Stylesheet {
171            contents: shared_lock.wrap(contents),
172            shared_lock,
173            media: mq,
174            disabled: AtomicBool::new(false),
175        });
176
177        // No subresource loads were triggered, queue load event
178        if self.pending_loads.get() == 0 {
179            self.owner_global()
180                .task_manager()
181                .dom_manipulation_task_source()
182                .queue_simple_event(self.upcast(), atom!("load"));
183        }
184
185        self.set_stylesheet(sheet, cache_key, true);
186    }
187
188    // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet.
189    //
190    // With the reuse of `StylesheetContent` for same stylesheet string content,
191    // this function has a bit difference with `HTMLLinkElement::set_stylesheet` now.
192    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
193    pub(crate) fn set_stylesheet(
194        &self,
195        s: Arc<Stylesheet>,
196        cache_key: Option<StylesheetContentsCacheKey>,
197        need_clean_cssom: bool,
198    ) {
199        let stylesheets_owner = self.stylesheet_list_owner();
200        if let Some(ref s) = *self.stylesheet.borrow() {
201            stylesheets_owner
202                .remove_stylesheet(StylesheetSource::Element(Dom::from_ref(self.upcast())), s);
203        }
204
205        if need_clean_cssom {
206            self.clean_stylesheet_ownership();
207        } else if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
208            let guard = s.shared_lock.read();
209            cssom_stylesheet.update_style_stylesheet(&s, &guard);
210        }
211
212        *self.stylesheet.borrow_mut() = Some(s.clone());
213        *self.stylesheetcontents_cache_key.borrow_mut() = cache_key;
214        stylesheets_owner.add_owned_stylesheet(self.upcast(), s);
215    }
216
217    pub(crate) fn will_modify_stylesheet(&self) {
218        if let Some(stylesheet_with_owned_contents) = self.create_owned_contents_stylesheet() {
219            self.set_stylesheet(stylesheet_with_owned_contents, None, false);
220        }
221    }
222
223    pub(crate) fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
224        self.stylesheet.borrow().clone()
225    }
226
227    pub(crate) fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> {
228        self.get_stylesheet().map(|sheet| {
229            self.cssom_stylesheet.or_init(|| {
230                CSSStyleSheet::new(
231                    &self.owner_window(),
232                    Some(self.upcast::<Element>()),
233                    "text/css".into(),
234                    None, // todo handle location
235                    None, // todo handle title
236                    sheet,
237                    None, // constructor_document
238                    CanGc::note(),
239                )
240            })
241        })
242    }
243
244    fn create_owned_contents_stylesheet(&self) -> Option<Arc<Stylesheet>> {
245        let cache_key = self.stylesheetcontents_cache_key.borrow_mut().take()?;
246        if cache_key.is_uniquely_owned() {
247            StylesheetContentsCache::remove(cache_key);
248            return None;
249        }
250
251        let stylesheet_with_shared_contents = self.stylesheet.borrow().clone()?;
252        let lock = stylesheet_with_shared_contents.shared_lock.clone();
253        let guard = stylesheet_with_shared_contents.shared_lock.read();
254        let stylesheet_with_owned_contents = Arc::new(Stylesheet {
255            contents: lock.wrap(Arc::new(
256                stylesheet_with_shared_contents
257                    .contents(&guard)
258                    .deep_clone_with_lock(&lock, &guard),
259            )),
260            shared_lock: lock,
261            media: stylesheet_with_shared_contents.media.clone(),
262            disabled: AtomicBool::new(
263                stylesheet_with_shared_contents
264                    .disabled
265                    .load(Ordering::SeqCst),
266            ),
267        });
268
269        Some(stylesheet_with_owned_contents)
270    }
271
272    fn clean_stylesheet_ownership(&self) {
273        if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
274            // If the CSSOMs change from having an owner node to being ownerless, they may still
275            // potentially modify shared stylesheets. Thus, create an new `Stylesheet` with owned
276            // `StylesheetContents` to ensure that the potentially modifications are only made on
277            // the owned `StylesheetContents`.
278            if let Some(stylesheet) = self.create_owned_contents_stylesheet() {
279                let guard = stylesheet.shared_lock.read();
280                cssom_stylesheet.update_style_stylesheet(&stylesheet, &guard);
281            }
282            cssom_stylesheet.set_owner_node(None);
283        }
284        self.cssom_stylesheet.set(None);
285    }
286
287    fn remove_stylesheet(&self) {
288        self.clean_stylesheet_ownership();
289        if let Some(s) = self.stylesheet.borrow_mut().take() {
290            self.stylesheet_list_owner()
291                .remove_stylesheet(StylesheetSource::Element(Dom::from_ref(self.upcast())), &s);
292            let _ = self.stylesheetcontents_cache_key.borrow_mut().take();
293        }
294    }
295}
296
297impl VirtualMethods for HTMLStyleElement {
298    fn super_type(&self) -> Option<&dyn VirtualMethods> {
299        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
300    }
301
302    fn children_changed(&self, mutation: &ChildrenMutation, can_gc: CanGc) {
303        self.super_type()
304            .unwrap()
305            .children_changed(mutation, can_gc);
306
307        // https://html.spec.whatwg.org/multipage/#update-a-style-block
308        // Handles the case when:
309        // "The element is not on the stack of open elements of an HTML parser or XML parser,
310        // and one of its child nodes is modified by a script."
311        // TODO: Handle Text child contents being mutated.
312        let node = self.upcast::<Node>();
313        if (node.is_in_a_document_tree() || node.is_in_a_shadow_tree()) &&
314            !self.in_stack_of_open_elements.get()
315        {
316            self.parse_own_css();
317        }
318    }
319
320    fn bind_to_tree(&self, context: &BindContext, can_gc: CanGc) {
321        self.super_type().unwrap().bind_to_tree(context, can_gc);
322
323        // https://html.spec.whatwg.org/multipage/#update-a-style-block
324        // Handles the case when:
325        // "The element is not on the stack of open elements of an HTML parser or XML parser,
326        // and it becomes connected or disconnected."
327        if context.tree_connected && !self.in_stack_of_open_elements.get() {
328            self.parse_own_css();
329        }
330    }
331
332    fn pop(&self) {
333        self.super_type().unwrap().pop();
334
335        // https://html.spec.whatwg.org/multipage/#update-a-style-block
336        // Handles the case when:
337        // "The element is popped off the stack of open elements of an HTML parser or XML parser."
338        self.in_stack_of_open_elements.set(false);
339        if self.upcast::<Node>().is_in_a_document_tree() {
340            self.parse_own_css();
341        }
342    }
343
344    fn unbind_from_tree(&self, context: &UnbindContext, can_gc: CanGc) {
345        if let Some(s) = self.super_type() {
346            s.unbind_from_tree(context, can_gc);
347        }
348
349        if context.tree_connected {
350            self.remove_stylesheet();
351        }
352    }
353
354    fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation, can_gc: CanGc) {
355        if let Some(s) = self.super_type() {
356            s.attribute_mutated(attr, mutation, can_gc);
357        }
358
359        let node = self.upcast::<Node>();
360        if !(node.is_in_a_document_tree() || node.is_in_a_shadow_tree()) ||
361            self.in_stack_of_open_elements.get()
362        {
363            return;
364        }
365
366        if attr.name() == "type" {
367            if let AttributeMutation::Set(Some(old_value)) = mutation {
368                if **old_value == **attr.value() {
369                    return;
370                }
371            }
372            self.remove_stylesheet();
373            self.parse_own_css();
374        } else if attr.name() == "media" {
375            if let Some(ref stylesheet) = *self.stylesheet.borrow_mut() {
376                let shared_lock = node.owner_doc().style_shared_lock().clone();
377                let mut guard = shared_lock.write();
378                let media = stylesheet.media.write_with(&mut guard);
379                match mutation {
380                    AttributeMutation::Set(_) => *media = self.create_media_list(&attr.value()),
381                    AttributeMutation::Removed => *media = StyleMediaList::empty(),
382                };
383                self.owner_document().invalidate_stylesheets();
384            }
385        }
386    }
387}
388
389impl StylesheetOwner for HTMLStyleElement {
390    fn increment_pending_loads_count(&self) {
391        self.pending_loads.set(self.pending_loads.get() + 1)
392    }
393
394    fn load_finished(&self, succeeded: bool) -> Option<bool> {
395        assert!(self.pending_loads.get() > 0, "What finished?");
396        if !succeeded {
397            self.any_failed_load.set(true);
398        }
399
400        self.pending_loads.set(self.pending_loads.get() - 1);
401        if self.pending_loads.get() != 0 {
402            return None;
403        }
404
405        let any_failed = self.any_failed_load.get();
406        self.any_failed_load.set(false);
407        Some(any_failed)
408    }
409
410    fn parser_inserted(&self) -> bool {
411        self.parser_inserted.get()
412    }
413
414    fn referrer_policy(&self) -> ReferrerPolicy {
415        ReferrerPolicy::EmptyString
416    }
417
418    fn set_origin_clean(&self, origin_clean: bool) {
419        if let Some(stylesheet) = self.get_cssom_stylesheet() {
420            stylesheet.set_origin_clean(origin_clean);
421        }
422    }
423}
424
425impl HTMLStyleElementMethods<crate::DomTypeHolder> for HTMLStyleElement {
426    /// <https://drafts.csswg.org/cssom/#dom-linkstyle-sheet>
427    fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>> {
428        self.get_cssom_stylesheet().map(DomRoot::upcast)
429    }
430
431    /// <https://html.spec.whatwg.org/multipage/#dom-style-disabled>
432    fn Disabled(&self) -> bool {
433        self.get_cssom_stylesheet()
434            .is_some_and(|sheet| sheet.disabled())
435    }
436
437    /// <https://html.spec.whatwg.org/multipage/#dom-style-disabled>
438    fn SetDisabled(&self, value: bool) {
439        if let Some(sheet) = self.get_cssom_stylesheet() {
440            sheet.set_disabled(value);
441        }
442    }
443
444    // <https://html.spec.whatwg.org/multipage/#HTMLStyleElement-partial>
445    make_getter!(Type, "type");
446
447    // <https://html.spec.whatwg.org/multipage/#HTMLStyleElement-partial>
448    make_setter!(SetType, "type");
449
450    // <https://html.spec.whatwg.org/multipage/#attr-style-media>
451    make_getter!(Media, "media");
452
453    // <https://html.spec.whatwg.org/multipage/#attr-style-media>
454    make_setter!(SetMedia, "media");
455}