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