script/dom/html/documentmetadata/
htmlstyleelement.rs1use std::cell::Cell;
6use std::sync::atomic::{AtomicBool, Ordering};
7
8use dom_struct::dom_struct;
9use html5ever::{LocalName, Prefix, local_name};
10use js::context::JSContext;
11use js::rust::HandleObject;
12use net_traits::ReferrerPolicy;
13use script_bindings::cell::DomRefCell;
14use script_bindings::root::Dom;
15use servo_arc::Arc;
16use style::media_queries::MediaList as StyleMediaList;
17use style::stylesheets::{Stylesheet, StylesheetInDocument, UrlExtraData};
18use stylo_atoms::Atom;
19
20use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenList_Binding::DOMTokenListMethods;
21use crate::dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods;
22use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
23use crate::dom::bindings::inheritance::Castable;
24use crate::dom::bindings::root::{DomRoot, MutNullableDom};
25use crate::dom::bindings::str::DOMString;
26use crate::dom::csp::{CspReporting, InlineCheckType};
27use crate::dom::css::cssstylesheet::CSSStyleSheet;
28use crate::dom::css::stylesheet::StyleSheet as DOMStyleSheet;
29use crate::dom::css::stylesheetcontentscache::{
30 StylesheetContentsCache, StylesheetContentsCacheKey,
31};
32use crate::dom::document::Document;
33use crate::dom::documentorshadowroot::StylesheetSource;
34use crate::dom::domtokenlist::DOMTokenList;
35use crate::dom::element::attributes::storage::AttrRef;
36use crate::dom::element::{AttributeMutation, Element, ElementCreator};
37use crate::dom::html::htmlelement::HTMLElement;
38use crate::dom::medialist::MediaList;
39use crate::dom::node::virtualmethods::VirtualMethods;
40use crate::dom::node::{BindContext, ChildrenMutation, Node, NodeTraits, UnbindContext};
41use crate::stylesheet_loader::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 parser_inserted: Cell<bool>,
54 in_stack_of_open_elements: Cell<bool>,
55 pending_loads: Cell<u32>,
56 any_failed_load: Cell<bool>,
57 blocking: MutNullableDom<DOMTokenList>,
59}
60
61impl HTMLStyleElement {
62 fn new_inherited(
63 local_name: LocalName,
64 prefix: Option<Prefix>,
65 document: &Document,
66 creator: ElementCreator,
67 ) -> HTMLStyleElement {
68 HTMLStyleElement {
69 htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
70 stylesheet: DomRefCell::new(None),
71 stylesheetcontents_cache_key: DomRefCell::new(None),
72 cssom_stylesheet: MutNullableDom::new(None),
73 parser_inserted: Cell::new(creator.is_parser_created()),
74 in_stack_of_open_elements: Cell::new(creator.is_parser_created()),
75 pending_loads: Cell::new(0),
76 any_failed_load: Cell::new(false),
77 blocking: Default::default(),
78 }
79 }
80
81 pub(crate) fn new(
82 cx: &mut JSContext,
83 local_name: LocalName,
84 prefix: Option<Prefix>,
85 document: &Document,
86 proto: Option<HandleObject>,
87 creator: ElementCreator,
88 ) -> DomRoot<HTMLStyleElement> {
89 Node::reflect_node_with_proto(
90 cx,
91 Box::new(HTMLStyleElement::new_inherited(
92 local_name, prefix, document, creator,
93 )),
94 document,
95 proto,
96 )
97 }
98
99 #[inline]
100 fn create_media_list(&self, mq_str: &str) -> StyleMediaList {
101 MediaList::parse_media_list(mq_str, &self.owner_window())
102 }
103
104 pub(crate) fn update_a_style_block(&self, cx: &mut JSContext) {
106 self.remove_stylesheet();
112
113 let node = self.upcast::<Node>();
115 if !node.is_connected() {
116 return;
117 }
118 assert!(
119 node.is_in_a_document_tree() || node.is_in_a_shadow_tree(),
120 "This stylesheet does not have an owner, so there's no reason to parse its contents"
121 );
122
123 let mut type_attribute = self.Type();
126 type_attribute.make_ascii_lowercase();
127 if !type_attribute.is_empty() && type_attribute != "text/css" {
128 return;
129 }
130
131 let doc = self.owner_document();
135 let global = &self.owner_global();
136 if global
137 .get_csp_list()
138 .should_elements_inline_type_behavior_be_blocked(
139 cx,
140 global,
141 self.upcast(),
142 InlineCheckType::Style,
143 &node.child_text_content().str(),
144 doc.get_current_parser_line(),
145 )
146 {
147 return;
148 }
149
150 let data = node
152 .GetTextContent()
153 .expect("Element.textContent must be a string");
154 let shared_lock = node.owner_doc().style_shared_author_lock().clone();
155 let mq = Arc::new(shared_lock.wrap(self.create_media_list(&self.Media().str())));
156
157 let (cache_key, contents) = StylesheetContentsCache::get_or_insert_with(
162 &data.str(),
163 &shared_lock,
164 UrlExtraData(doc.base_url().get_arc()),
165 doc.quirks_mode(),
166 self.upcast(),
167 );
168
169 let sheet = Arc::new(Stylesheet {
170 contents: shared_lock.wrap(contents),
171 shared_lock,
172 media: mq,
173 disabled: AtomicBool::new(false),
174 });
175
176 if self.pending_loads.get() == 0 {
191 self.owner_global()
196 .task_manager()
197 .networking_task_source()
198 .queue_simple_event(self.upcast(), atom!("load"));
199 }
200
201 self.clean_stylesheet_ownership();
213 self.set_stylesheet(sheet, cache_key);
214 }
215
216 pub(crate) fn set_stylesheet(
221 &self,
222 s: Arc<Stylesheet>,
223 cache_key: Option<StylesheetContentsCacheKey>,
224 ) {
225 *self.stylesheet.borrow_mut() = Some(s.clone());
226 *self.stylesheetcontents_cache_key.borrow_mut() = cache_key;
227 self.stylesheet_list_owner()
228 .add_owned_stylesheet(self.upcast(), s);
229 }
230
231 pub(crate) fn will_modify_stylesheet(&self) {
232 if let Some(stylesheet_with_owned_contents) = self.create_owned_contents_stylesheet() {
233 self.remove_stylesheet();
234 if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
235 let guard = stylesheet_with_owned_contents.shared_lock.read();
236 cssom_stylesheet.update_style_stylesheet(&stylesheet_with_owned_contents, &guard);
237 }
238 self.set_stylesheet(stylesheet_with_owned_contents, None);
239 }
240 }
241
242 pub(crate) fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
243 self.stylesheet.borrow().clone()
244 }
245
246 pub(crate) fn get_cssom_stylesheet(
247 &self,
248 cx: &mut JSContext,
249 ) -> Option<DomRoot<CSSStyleSheet>> {
250 self.get_stylesheet().map(|sheet| {
251 self.cssom_stylesheet.or_init(|| {
252 CSSStyleSheet::new(
253 cx,
254 &self.owner_window(),
255 Some(self.upcast::<Element>()),
256 "text/css".into(),
257 None, None, sheet,
260 None, )
262 })
263 })
264 }
265
266 fn create_owned_contents_stylesheet(&self) -> Option<Arc<Stylesheet>> {
267 let cache_key = self.stylesheetcontents_cache_key.borrow_mut().take()?;
268 if cache_key.is_uniquely_owned() {
269 StylesheetContentsCache::remove(cache_key);
270 return None;
271 }
272
273 let stylesheet_with_shared_contents = self.stylesheet.borrow().clone()?;
274 let lock = stylesheet_with_shared_contents.shared_lock.clone();
275 let guard = stylesheet_with_shared_contents.shared_lock.read();
276 let stylesheet_with_owned_contents = Arc::new(Stylesheet {
277 contents: lock.wrap(
278 stylesheet_with_shared_contents
279 .contents(&guard)
280 .deep_clone(&lock, None, &guard),
281 ),
282 shared_lock: lock,
283 media: stylesheet_with_shared_contents.media.clone(),
284 disabled: AtomicBool::new(
285 stylesheet_with_shared_contents
286 .disabled
287 .load(Ordering::SeqCst),
288 ),
289 });
290
291 Some(stylesheet_with_owned_contents)
292 }
293
294 fn clean_stylesheet_ownership(&self) {
295 if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
296 if let Some(stylesheet) = self.create_owned_contents_stylesheet() {
301 let guard = stylesheet.shared_lock.read();
302 cssom_stylesheet.update_style_stylesheet(&stylesheet, &guard);
303 }
304 cssom_stylesheet.set_owner_node(None);
305 }
306 self.cssom_stylesheet.set(None);
307 }
308
309 fn remove_stylesheet(&self) {
310 self.clean_stylesheet_ownership();
311 if let Some(s) = self.stylesheet.borrow_mut().take() {
312 self.stylesheet_list_owner()
313 .remove_stylesheet(StylesheetSource::Element(Dom::from_ref(self.upcast())), &s);
314 let _ = self.stylesheetcontents_cache_key.borrow_mut().take();
315 }
316 }
317}
318
319impl VirtualMethods for HTMLStyleElement {
320 fn super_type(&self) -> Option<&dyn VirtualMethods> {
321 Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
322 }
323
324 fn children_changed(&self, cx: &mut JSContext, mutation: &ChildrenMutation) {
325 self.super_type().unwrap().children_changed(cx, mutation);
326
327 if !self.in_stack_of_open_elements.get() {
330 self.update_a_style_block(cx);
331 }
332 }
333
334 fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
335 self.super_type().unwrap().bind_to_tree(cx, context);
336
337 if !self.in_stack_of_open_elements.get() {
340 self.update_a_style_block(cx);
341 }
342 }
343
344 fn pop(&self, cx: &mut js::context::JSContext) {
345 self.super_type().unwrap().pop(cx);
346 self.in_stack_of_open_elements.set(false);
347
348 self.update_a_style_block(cx);
351 }
352
353 fn unbind_from_tree(&self, cx: &mut js::context::JSContext, context: &UnbindContext) {
354 if let Some(s) = self.super_type() {
355 s.unbind_from_tree(cx, context);
356 }
357
358 if !self.in_stack_of_open_elements.get() {
361 self.update_a_style_block(cx);
362 }
363 }
364
365 fn attribute_mutated(
366 &self,
367 cx: &mut js::context::JSContext,
368 attr: AttrRef<'_>,
369 mutation: AttributeMutation,
370 ) {
371 if let Some(s) = self.super_type() {
372 s.attribute_mutated(cx, attr, mutation);
373 }
374
375 let node = self.upcast::<Node>();
376 if !(node.is_in_a_document_tree() || node.is_in_a_shadow_tree()) ||
377 self.in_stack_of_open_elements.get()
378 {
379 return;
380 }
381
382 if attr.name() == "type" {
383 if let AttributeMutation::Set(Some(old_value), _) = mutation &&
384 **old_value == **attr.value()
385 {
386 return;
387 }
388 self.remove_stylesheet();
389 self.update_a_style_block(cx);
390 } else if attr.name() == "media" &&
391 let Some(ref stylesheet) = *self.stylesheet.borrow_mut()
392 {
393 let shared_lock = node.owner_doc().style_shared_author_lock().clone();
394 let mut guard = shared_lock.write();
395 let media = stylesheet.media.write_with(&mut guard);
396 match mutation {
397 AttributeMutation::Set(..) => *media = self.create_media_list(&attr.value()),
398 AttributeMutation::Removed => *media = StyleMediaList::empty(),
399 };
400 self.owner_document().invalidate_stylesheets(cx.no_gc());
401 }
402 }
403}
404
405impl StylesheetOwner for HTMLStyleElement {
406 fn increment_pending_loads_count(&self) {
407 self.pending_loads.set(self.pending_loads.get() + 1)
408 }
409
410 fn load_finished(&self, succeeded: bool) -> Option<bool> {
411 assert!(self.pending_loads.get() > 0, "What finished?");
412 if !succeeded {
413 self.any_failed_load.set(true);
414 }
415
416 self.pending_loads.set(self.pending_loads.get() - 1);
417 if self.pending_loads.get() != 0 {
418 return None;
419 }
420
421 let any_failed = self.any_failed_load.get();
422 self.any_failed_load.set(false);
423 Some(any_failed)
424 }
425
426 fn parser_inserted(&self) -> bool {
427 self.parser_inserted.get()
428 }
429
430 fn potentially_render_blocking(&self) -> bool {
432 self.parser_inserted() ||
439 self.blocking
440 .get()
441 .is_some_and(|list| list.Contains("render".into()))
442 }
443
444 fn referrer_policy(&self, _cx: &mut JSContext) -> ReferrerPolicy {
445 ReferrerPolicy::EmptyString
446 }
447
448 fn set_origin_clean(&self, cx: &mut JSContext, origin_clean: bool) {
449 if let Some(stylesheet) = self.get_cssom_stylesheet(cx) {
450 stylesheet.set_origin_clean(origin_clean);
451 }
452 }
453}
454
455impl HTMLStyleElementMethods<crate::DomTypeHolder> for HTMLStyleElement {
456 fn GetSheet(&self, cx: &mut JSContext) -> Option<DomRoot<DOMStyleSheet>> {
458 self.get_cssom_stylesheet(cx).map(DomRoot::upcast)
459 }
460
461 fn Disabled(&self, cx: &mut JSContext) -> bool {
463 self.get_cssom_stylesheet(cx)
464 .is_some_and(|sheet| sheet.disabled())
465 }
466
467 fn SetDisabled(&self, cx: &mut js::context::JSContext, value: bool) {
469 if let Some(sheet) = self.get_cssom_stylesheet(cx) {
470 sheet.set_disabled(cx.no_gc(), value);
471 }
472 }
473
474 make_getter!(Type, "type");
476
477 make_setter!(SetType, "type");
479
480 make_getter!(Media, "media");
482
483 make_setter!(SetMedia, "media");
485
486 fn Blocking(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
488 self.blocking.or_init(|| {
489 DOMTokenList::new(
490 cx,
491 self.upcast(),
492 &local_name!("blocking"),
493 Some(vec![Atom::from("render")]),
494 )
495 })
496 }
497}