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