1use std::cell::{Cell, Ref};
6
7use dom_struct::dom_struct;
8use js::context::{JSContext, NoGC};
9use js::realm::CurrentRealm;
10use js::rust::HandleObject;
11use script_bindings::cell::DomRefCell;
12use script_bindings::codegen::GenericBindings::StyleSheetBinding::StyleSheetMethods;
13use script_bindings::inheritance::Castable;
14use script_bindings::reflector::{reflect_dom_object, reflect_dom_object_with_proto};
15use script_bindings::root::Dom;
16use servo_arc::Arc;
17use servo_url::ServoUrl;
18use style::shared_lock::{SharedRwLock, SharedRwLockReadGuard};
19use style::stylesheets::{
20 AllowImportRules, Origin, Stylesheet as StyleStyleSheet, StylesheetContents,
21 StylesheetInDocument, UrlExtraData,
22};
23
24use super::cssrulelist::{CSSRuleList, RulesSource};
25use super::stylesheet::StyleSheet;
26use super::stylesheetlist::StyleSheetListOwner;
27use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding::{
28 CSSStyleSheetInit, CSSStyleSheetMethods,
29};
30use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
31use crate::dom::bindings::codegen::GenericBindings::CSSRuleListBinding::CSSRuleList_Binding::CSSRuleListMethods;
32use crate::dom::bindings::codegen::UnionTypes::MediaListOrString;
33use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
34use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
35use crate::dom::bindings::reflector::DomGlobal;
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::promise::RootedPromise;
44use crate::dom::types::Promise;
45use crate::dom::window::Window;
46
47#[dom_struct]
48pub(crate) struct CSSStyleSheet {
49 stylesheet: StyleSheet,
50
51 owner_node: MutNullableDom<Element>,
53
54 rule_list: MutNullableDom<CSSRuleList>,
56
57 #[ignore_malloc_size_of = "Stylo"]
59 #[no_trace]
60 style_stylesheet: DomRefCell<Arc<StyleStyleSheet>>,
61
62 #[no_trace]
65 style_shared_lock: SharedRwLock,
66
67 constructor_document: Option<Dom<Document>>,
71
72 disallow_modification: Cell<bool>,
74
75 origin_clean: Cell<bool>,
77
78 #[no_trace]
80 stylesheet_base_url: DomRefCell<Option<ServoUrl>>,
81
82 adopters: DomRefCell<Vec<StyleSheetListOwner>>,
85}
86
87impl CSSStyleSheet {
88 fn new_inherited(
89 owner: Option<&Element>,
90 type_: DOMString,
91 href: Option<DOMString>,
92 stylesheet: Arc<StyleStyleSheet>,
93 constructor_document: Option<&Document>,
94 ) -> CSSStyleSheet {
95 CSSStyleSheet {
96 stylesheet: StyleSheet::new_inherited(type_, href),
97 owner_node: MutNullableDom::new(owner),
98 rule_list: MutNullableDom::new(None),
99 style_shared_lock: stylesheet.shared_lock.clone(),
100 style_stylesheet: DomRefCell::new(stylesheet),
101 origin_clean: Cell::new(true),
102 constructor_document: constructor_document.map(Dom::from_ref),
103 adopters: Default::default(),
104 disallow_modification: Cell::new(false),
105 stylesheet_base_url: Default::default(),
106 }
107 }
108
109 pub(crate) fn new(
110 cx: &mut JSContext,
111 window: &Window,
112 owner: Option<&Element>,
113 type_: DOMString,
114 href: Option<DOMString>,
115 stylesheet: Arc<StyleStyleSheet>,
116 constructor_document: Option<&Document>,
117 ) -> DomRoot<CSSStyleSheet> {
118 reflect_dom_object(
119 cx,
120 Box::new(CSSStyleSheet::new_inherited(
121 owner,
122 type_,
123 href,
124 stylesheet,
125 constructor_document,
126 )),
127 window,
128 )
129 }
130
131 #[expect(clippy::too_many_arguments)]
132 fn new_with_proto(
133 cx: &mut JSContext,
134 window: &Window,
135 proto: Option<HandleObject>,
136 owner: Option<&Element>,
137 type_: DOMString,
138 href: Option<DOMString>,
139 stylesheet: Arc<StyleStyleSheet>,
140 constructor_document: Option<&Document>,
141 ) -> DomRoot<CSSStyleSheet> {
142 reflect_dom_object_with_proto(
143 cx,
144 Box::new(CSSStyleSheet::new_inherited(
145 owner,
146 type_,
147 href,
148 stylesheet,
149 constructor_document,
150 )),
151 window,
152 proto,
153 )
154 }
155
156 pub(crate) fn rulelist(&self, cx: &mut JSContext) -> DomRoot<CSSRuleList> {
157 self.rule_list.or_init(|| {
158 let sheet = self.style_stylesheet.borrow();
159 let guard = sheet.shared_lock.read();
160 let rules = sheet.contents(&guard).rules.clone();
161 CSSRuleList::new(
162 cx,
163 self.global().as_window(),
164 None,
165 self,
166 RulesSource::Rules(rules),
167 )
168 })
169 }
170
171 pub(crate) fn disabled(&self) -> bool {
172 self.style_stylesheet.borrow().disabled()
173 }
174
175 pub(crate) fn href(&self) -> Option<DOMString> {
176 self.upcast::<StyleSheet>().GetHref()
177 }
178
179 pub(crate) fn title(&self) -> DOMString {
180 self.upcast::<StyleSheet>().GetTitle().unwrap_or_default()
181 }
182
183 #[cfg(feature = "devtools")]
184 pub(crate) fn get_rule_count(&self) -> u32 {
185 let sheet = self.style_stylesheet.borrow();
186 let guard = sheet.shared_lock.read();
187 sheet.contents(&guard).rules.read_with(&guard).0.len() as u32
188 }
189
190 pub(crate) fn origin(&self) -> Origin {
191 let guard = self.style_shared_lock.read();
192 self.style_stylesheet()
193 .clone()
194 .contents
195 .read_with(&guard)
196 .origin
197 }
198
199 pub(crate) fn owner_node(&self) -> Option<DomRoot<Element>> {
200 self.owner_node.get()
201 }
202
203 pub(crate) fn set_disabled(&self, no_gc: &NoGC, disabled: bool) {
204 if self.style_stylesheet.borrow().set_disabled(disabled) {
205 self.notify_invalidations(no_gc);
206 }
207 }
208
209 pub(crate) fn set_owner_node(&self, value: Option<&Element>) {
210 self.owner_node.set(value);
211 }
212
213 pub(crate) fn shared_lock(&self) -> &SharedRwLock {
214 &self.style_shared_lock
215 }
216
217 pub(crate) fn style_stylesheet(&self) -> Ref<'_, Arc<StyleStyleSheet>> {
218 self.style_stylesheet.borrow()
219 }
220
221 pub(crate) fn set_origin_clean(&self, origin_clean: bool) {
222 self.origin_clean.set(origin_clean);
223 }
224
225 pub(crate) fn medialist(&self, cx: &mut JSContext) -> DomRoot<MediaList> {
226 MediaList::new(
227 cx,
228 self.global().as_window(),
229 self,
230 self.style_stylesheet().media.clone(),
231 )
232 }
233
234 #[inline]
236 pub(crate) fn is_constructed(&self) -> bool {
237 self.constructor_document.is_some()
238 }
239
240 pub(crate) fn constructor_document_matches(&self, other_doc: &Document) -> bool {
241 match &self.constructor_document {
242 Some(doc) => *doc == other_doc,
243 None => false,
244 }
245 }
246
247 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
250 pub(crate) fn add_adopter(&self, owner: StyleSheetListOwner) {
251 debug_assert!(self.is_constructed());
252 self.adopters.borrow_mut().push(owner);
253 }
254
255 pub(crate) fn remove_adopter(&self, owner: &StyleSheetListOwner) {
256 let adopters = &mut *self.adopters.borrow_mut();
257 if let Some(index) = adopters.iter().position(|o| o == owner) {
258 adopters.swap_remove(index);
259 }
260 }
261
262 pub(crate) fn will_modify(&self, no_gc: &NoGC) {
263 let Some(node) = self.owner_node.get() else {
264 return;
265 };
266
267 let Some(node) = node.downcast::<HTMLStyleElement>() else {
268 return;
269 };
270
271 node.will_modify_stylesheet(no_gc);
272 }
273
274 pub(crate) fn update_style_stylesheet(
275 &self,
276 style_stylesheet: &Arc<StyleStyleSheet>,
277 guard: &SharedRwLockReadGuard,
278 ) {
279 *self.style_stylesheet.borrow_mut() = style_stylesheet.clone();
286 if let Some(rulelist) = self.rule_list.get() {
287 let rules = style_stylesheet.contents(guard).rules.clone();
288 rulelist.update_rules(RulesSource::Rules(rules), guard);
289 }
290 }
291
292 pub(crate) fn notify_invalidations(&self, no_gc: &NoGC) {
294 if let Some(owner) = self.owner_node() {
295 owner.stylesheet_list_owner().invalidate_stylesheets(no_gc);
296 }
297 for adopter in self.adopters.borrow().iter() {
298 adopter.invalidate_stylesheets(no_gc);
299 }
300 }
301
302 pub(crate) fn disallow_modification(&self) -> bool {
304 self.disallow_modification.get()
305 }
306
307 fn do_replace_sync(&self, no_gc: &NoGC, text: USVString) {
309 let global = self.global();
311 let window = global.as_window();
312
313 self.will_modify(no_gc);
314
315 let _span = profile_traits::trace_span!("ParseStylesheet").entered();
316 let sheet = self.style_stylesheet();
317 let stylesheet_base_url = self
318 .stylesheet_base_url
319 .borrow()
320 .clone()
321 .unwrap_or(window.get_url());
322
323 let new_contents = StylesheetContents::from_str(
324 &text,
325 UrlExtraData(stylesheet_base_url.get_arc()),
326 Origin::Author,
327 &self.style_shared_lock,
328 None,
329 Some(window.css_error_reporter()),
330 window.Document().quirks_mode(),
331 AllowImportRules::No, None,
333 );
334
335 {
336 let mut write_guard = self.style_shared_lock.write();
337 *sheet.contents.write_with(&mut write_guard) = new_contents;
338 }
339
340 self.rule_list.set(None);
344
345 self.notify_invalidations(no_gc);
347 }
348}
349
350impl CSSStyleSheetMethods<crate::DomTypeHolder> for CSSStyleSheet {
351 fn Constructor(
353 cx: &mut JSContext,
354 window: &Window,
355 proto: Option<HandleObject>,
356 options: &CSSStyleSheetInit,
357 ) -> DomRoot<Self> {
358 let doc = window.Document();
359 let shared_lock = doc.style_shared_author_lock().clone();
360 let media = Arc::new(shared_lock.wrap(match &options.media {
361 MediaListOrString::MediaList(media_list) => media_list.clone_media_list(),
362 MediaListOrString::String(str) => MediaList::parse_media_list(&str.str(), window),
363 }));
364
365 let stylesheet = Arc::new(StyleStyleSheet::from_str(
366 "",
367 UrlExtraData(window.get_url().get_arc()),
368 Origin::Author,
369 media,
370 shared_lock,
371 None,
372 Some(window.css_error_reporter()),
373 doc.quirks_mode(),
374 AllowImportRules::No,
375 ));
376 if options.disabled {
377 stylesheet.set_disabled(true);
378 }
379
380 let sheet = Self::new_with_proto(
383 cx,
384 window,
385 proto,
386 None, DOMString::from_static("text/css"),
388 None, stylesheet,
390 Some(&window.Document()), );
392
393 let base_url = options
394 .baseURL
395 .as_ref()
396 .and_then(|url| ServoUrl::parse(&url.str()).ok());
397 *sheet.stylesheet_base_url.safe_borrow_mut(cx) = base_url;
399
400 sheet
402 }
403
404 fn GetCssRules(&self, cx: &mut JSContext) -> Fallible<DomRoot<CSSRuleList>> {
406 if !self.origin_clean.get() {
408 return Err(Error::Security(Some(
409 "Not allowed to access cross-origin style sheet".to_string(),
410 )));
411 }
412 Ok(self.rulelist(cx))
413 }
414
415 fn InsertRule(&self, cx: &mut JSContext, rule: DOMString, index: u32) -> Fallible<u32> {
417 if !self.origin_clean.get() {
419 return Err(Error::Security(Some(
420 "Not allowed to access cross-origin style sheet".to_string(),
421 )));
422 }
423
424 if self.disallow_modification() {
426 return Err(Error::NotAllowed(Some(
427 "This method can only be called on modifiable style sheets".to_string(),
428 )));
429 }
430
431 self.rulelist(cx).insert_rule(cx, &rule, index)
432 }
433
434 fn DeleteRule(&self, cx: &mut JSContext, index: u32) -> ErrorResult {
436 if !self.origin_clean.get() {
438 return Err(Error::Security(Some(
439 "Not allowed to access cross-origin style sheet".to_string(),
440 )));
441 }
442
443 if self.disallow_modification() {
445 return Err(Error::NotAllowed(Some(
446 "This method can only be called on modifiable style sheets".to_string(),
447 )));
448 }
449 self.rulelist(cx).remove_rule(cx, index)
450 }
451
452 fn GetRules(&self, cx: &mut JSContext) -> Fallible<DomRoot<CSSRuleList>> {
454 self.GetCssRules(cx)
455 }
456
457 fn RemoveRule(&self, cx: &mut JSContext, index: u32) -> ErrorResult {
459 self.DeleteRule(cx, index)
460 }
461
462 fn AddRule(
464 &self,
465 cx: &mut js::context::JSContext,
466 selector: DOMString,
467 block: DOMString,
468 optional_index: Option<u32>,
469 ) -> Fallible<i32> {
470 let mut rule = selector;
473
474 if block.is_empty() {
478 rule.push_str(" { }");
479 } else {
480 rule.push_str(" { ");
481 rule.push_str(&block.str());
482 rule.push_str(" }");
483 };
484
485 let index = optional_index.unwrap_or_else(|| self.rulelist(cx).Length());
487
488 self.InsertRule(cx, rule, index)?;
490
491 Ok(-1)
493 }
494
495 fn Replace(&self, cx: &mut CurrentRealm, text: USVString) -> Fallible<RootedPromise> {
497 let promise = Promise::new_in_realm(cx);
499
500 if !self.is_constructed() {
503 return Err(Error::NotAllowed(Some(
504 "This method can only be called on constructed style sheets".to_string(),
505 )));
506 }
507 if self.disallow_modification() {
508 return Err(Error::NotAllowed(Some(
509 "This method can only be called on modifiable style sheets".to_string(),
510 )));
511 }
512
513 self.disallow_modification.set(true);
515
516 let trusted_sheet = Trusted::new(self);
518 let trusted_promise = TrustedPromise::from(&promise);
519
520 self.global()
521 .task_manager()
522 .dom_manipulation_task_source()
523 .queue(task!(cssstylesheet_replace: move |cx| {
524 let sheet = trusted_sheet.root();
525
526 sheet.do_replace_sync(cx.no_gc(), text);
528
529 sheet.disallow_modification.set(false);
531
532 trusted_promise.root(cx).resolve_native(cx, &sheet);
534 }));
535
536 Ok(promise)
537 }
538
539 fn ReplaceSync(&self, no_gc: &NoGC, text: USVString) -> Result<(), Error> {
541 if !self.is_constructed() || self.disallow_modification() {
544 return Err(Error::NotAllowed(Some(
545 "This method can only be called on constructed style sheets".to_string(),
546 )));
547 }
548 if self.disallow_modification() {
549 return Err(Error::NotAllowed(Some(
550 "This method can only be called on modifiable style sheets".to_string(),
551 )));
552 }
553 self.do_replace_sync(no_gc, text);
554 Ok(())
555 }
556}