1use std::collections::HashSet;
6use std::ffi::c_void;
7use std::fmt;
8
9use embedder_traits::UntrustedNodeAddress;
10use js::context::JSContext;
11use layout_api::HitTestFlags;
12use script_bindings::codegen::GenericBindings::DocumentBinding::DocumentMethods;
13use script_bindings::codegen::GenericBindings::ShadowRootBinding::ShadowRootMethods;
14use script_bindings::codegen::GenericBindings::WindowBinding::WindowMethods;
15use script_bindings::error::{Error, ErrorResult};
16use servo_arc::Arc;
17use servo_config::pref;
18use style::media_queries::MediaList;
19use style::shared_lock::{SharedRwLock as StyleSharedRwLock, SharedRwLockReadGuard};
20use style::stylesheets::scope_rule::ImplicitScopeRoot;
21use style::stylesheets::{Stylesheet, StylesheetContents};
22use webrender_api::units::LayoutPoint;
23
24use crate::css::stylesheet_set::StylesheetSetRef;
25use crate::dom::Document;
26use crate::dom::bindings::codegen::Bindings::NodeBinding::GetRootNodeOptions;
27use crate::dom::bindings::codegen::Bindings::NodeBinding::Node_Binding::NodeMethods;
28use crate::dom::bindings::inheritance::Castable;
29use crate::dom::bindings::num::Finite;
30use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
31use crate::dom::css::stylesheetlist::StyleSheetListOwner;
32use crate::dom::customelementregistry::CustomElementRegistry;
33use crate::dom::element::Element;
34use crate::dom::node::{self, Node};
35use crate::dom::types::{CSSStyleSheet, EventTarget, ShadowRoot};
36use crate::dom::window::Window;
37
38#[derive(Clone, JSTraceable, MallocSizeOf)]
41#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
42pub(crate) enum StylesheetSource {
43 Element(Dom<Element>),
44 Constructed(Dom<CSSStyleSheet>),
45}
46
47impl StylesheetSource {
48 pub(crate) fn get_cssom_object(&self, cx: &mut JSContext) -> Option<DomRoot<CSSStyleSheet>> {
49 match self {
50 StylesheetSource::Element(el) => el.upcast::<Node>().get_cssom_stylesheet(cx),
51 StylesheetSource::Constructed(ss) => Some(ss.as_rooted()),
52 }
53 }
54
55 pub(crate) fn is_a_valid_owner(&self) -> bool {
56 match self {
57 StylesheetSource::Element(el) => el.as_stylesheet_owner().is_some(),
58 StylesheetSource::Constructed(ss) => ss.is_constructed(),
59 }
60 }
61
62 pub(crate) fn is_constructed(&self) -> bool {
63 matches!(self, StylesheetSource::Constructed(_))
64 }
65}
66
67#[derive(Clone, JSTraceable, MallocSizeOf)]
68#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
69pub(crate) struct ServoStylesheetInDocument {
70 #[ignore_malloc_size_of = "Stylo"]
71 #[no_trace]
72 pub(crate) sheet: Arc<Stylesheet>,
73 pub(crate) owner: StylesheetSource,
77}
78
79impl stylo_malloc_size_of::MallocSizeOf for ServoStylesheetInDocument {
82 fn size_of(&self, ops: &mut stylo_malloc_size_of::MallocSizeOfOps) -> usize {
83 <ServoStylesheetInDocument as malloc_size_of::MallocSizeOf>::size_of(self, ops)
84 }
85}
86
87impl fmt::Debug for ServoStylesheetInDocument {
88 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
89 self.sheet.fmt(formatter)
90 }
91}
92
93impl PartialEq for ServoStylesheetInDocument {
94 fn eq(&self, other: &Self) -> bool {
95 Arc::ptr_eq(&self.sheet, &other.sheet)
96 }
97}
98
99impl ::style::stylesheets::StylesheetInDocument for ServoStylesheetInDocument {
100 fn enabled(&self) -> bool {
101 self.sheet.enabled()
102 }
103
104 fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList> {
105 self.sheet.media(guard)
106 }
107
108 fn contents<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> &'a StylesheetContents {
109 self.sheet.contents(guard)
110 }
111
112 fn implicit_scope_root(&self) -> Option<ImplicitScopeRoot> {
113 None
114 }
115}
116
117#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
119#[derive(JSTraceable, MallocSizeOf)]
120pub(crate) struct DocumentOrShadowRoot {
121 window: Dom<Window>,
122 custom_element_registry: MutNullableDom<CustomElementRegistry>,
123}
124
125impl DocumentOrShadowRoot {
126 pub(crate) fn new(window: &Window) -> Self {
127 Self {
128 window: Dom::from_ref(window),
129 custom_element_registry: MutNullableDom::new(None),
130 }
131 }
132
133 pub(crate) fn custom_element_registry(&self) -> Option<DomRoot<CustomElementRegistry>> {
135 self.custom_element_registry.get()
136 }
137
138 pub(crate) fn set_custom_element_registry(&self, registry: Option<&CustomElementRegistry>) {
139 self.custom_element_registry.set(registry);
140 }
141
142 pub(crate) fn retarget_hit_test_result(
145 &self,
146 this: &Node,
147 node: &Node,
148 ) -> Option<DomRoot<Element>> {
149 let retargeted_node =
150 DomRoot::downcast::<Node>(node.upcast::<EventTarget>().retarget(this.upcast()))?;
151 DomRoot::downcast::<Element>(retargeted_node.clone()).or_else(|| {
152 let parent_node = retargeted_node.GetParentNode()?;
153
154 if let Some(shadow_root) = parent_node.downcast::<ShadowRoot>() {
159 Some(shadow_root.Host())
160 } else {
161 retargeted_node.GetParentElement()
162 }
163 })
164 }
165
166 #[expect(unsafe_code)]
168 pub(crate) fn element_from_point(
169 &self,
170 cx: &mut JSContext,
171 this: &Node,
172 x: Finite<f64>,
173 y: Finite<f64>,
174 document_element: Option<DomRoot<Element>>,
175 has_browsing_context: bool,
176 ) -> Option<DomRoot<Element>> {
177 let x = *x as f32;
178 let y = *y as f32;
179 let viewport = self.window.viewport_details().size;
180
181 if !has_browsing_context {
182 return None;
183 }
184
185 if x < 0.0 || y < 0.0 || x > viewport.width || y > viewport.height {
186 return None;
187 }
188
189 let flags = HitTestFlags::empty();
190 let result = self
191 .window
192 .elements_from_point_query(cx, flags, LayoutPoint::new(x, y));
193 let Some(result) = result.items.first() else {
194 return document_element;
195 };
196
197 let address = UntrustedNodeAddress(result.node.0 as *const c_void);
200 let node = unsafe { node::from_untrusted_node_address(address) };
201
202 self.retarget_hit_test_result(this, &node)
203 }
204
205 #[expect(unsafe_code)]
207 pub(crate) fn elements_from_point(
208 &self,
209 cx: &mut JSContext,
210 this: &Node,
211 x: Finite<f64>,
212 y: Finite<f64>,
213 document_element: Option<DomRoot<Element>>,
214 has_browsing_context: bool,
215 ) -> Vec<DomRoot<Element>> {
216 let x = *x as f32;
217 let y = *y as f32;
218 let viewport = self.window.viewport_details().size;
219
220 if !has_browsing_context {
221 return vec![];
222 }
223
224 if x < 0.0 || y < 0.0 || x > viewport.width || y > viewport.height {
226 return vec![];
227 }
228
229 let flags = HitTestFlags::empty();
235 let result = self
236 .window
237 .elements_from_point_query(cx, flags, LayoutPoint::new(x, y));
238
239 let mut elements: Vec<_> = result
240 .items
241 .iter()
242 .flat_map(|result| {
243 let address = UntrustedNodeAddress(result.node.0 as *const c_void);
246 let node = unsafe { node::from_untrusted_node_address(address) };
247 self.retarget_hit_test_result(this, &node)
248 })
249 .collect();
250
251 let mut last_seen = None;
254 elements.retain(|element| {
255 if Some(element) == last_seen.as_ref() {
256 return false;
257 }
258 last_seen = Some(element.clone());
259 true
260 });
261
262 if let Some(root_element) = document_element &&
265 elements.last() != Some(&root_element)
266 {
267 elements.push(root_element);
268 }
269
270 elements
272 }
273
274 pub(crate) fn active_element(&self, this: &Node) -> Option<DomRoot<Element>> {
276 let document = self.window.Document();
278 let candidate = document
279 .focus_handler()
280 .focused_area()
281 .dom_anchor(&document);
282
283 let candidate =
288 DomRoot::downcast::<Node>(candidate.upcast::<EventTarget>().retarget(this.upcast()))?;
289
290 if this != &*candidate.GetRootNode(&GetRootNodeOptions::empty()) {
292 return None;
293 }
294
295 if let Some(candidate) = DomRoot::downcast::<Element>(candidate.clone()) {
297 return Some(candidate);
298 }
299 assert!(candidate.is::<Document>());
300
301 if let Some(body) = document.GetBody() {
303 return Some(DomRoot::upcast(body));
304 }
305
306 if let Some(document_element) = document.GetDocumentElement() {
308 return Some(document_element);
309 }
310
311 None
313 }
314
315 #[cfg_attr(crown, expect(crown::unrooted_must_root))] pub(crate) fn remove_stylesheet(
318 owner: StylesheetSource,
319 s: &Arc<Stylesheet>,
320 mut stylesheets: StylesheetSetRef<ServoStylesheetInDocument>,
321 ) {
322 let guard = s.shared_lock.read();
323
324 stylesheets.remove_stylesheet(
326 None,
327 ServoStylesheetInDocument {
328 sheet: s.clone(),
329 owner,
330 },
331 &guard,
332 );
333 }
334
335 #[cfg_attr(crown, expect(crown::unrooted_must_root))] pub(crate) fn add_stylesheet(
339 owner: StylesheetSource,
340 mut stylesheets: StylesheetSetRef<ServoStylesheetInDocument>,
341 sheet: Arc<Stylesheet>,
342 insertion_point: Option<ServoStylesheetInDocument>,
343 style_shared_lock: &StyleSharedRwLock,
344 ) {
345 debug_assert!(owner.is_a_valid_owner(), "Wat");
346
347 if owner.is_constructed() && !pref!(dom_adoptedstylesheet_enabled) {
348 return;
349 }
350
351 let sheet = ServoStylesheetInDocument { sheet, owner };
352
353 let guard = style_shared_lock.read();
354
355 match insertion_point {
356 Some(ip) => {
357 stylesheets.insert_stylesheet_before(sheet, ip, &guard);
358 },
359 None => {
360 stylesheets.append_stylesheet(sheet, &guard);
361 },
362 }
363 }
364
365 fn set_adopted_stylesheets(
372 adopted_stylesheets: &mut Vec<Dom<CSSStyleSheet>>,
373 incoming_stylesheets: &[Dom<CSSStyleSheet>],
374 owner: &StyleSheetListOwner,
375 ) -> ErrorResult {
376 if !pref!(dom_adoptedstylesheet_enabled) {
377 return Ok(());
378 }
379
380 let owner_doc = match owner {
381 StyleSheetListOwner::Document(doc) => doc,
382 StyleSheetListOwner::ShadowRoot(root) => root.owner_doc(),
383 };
384
385 for sheet in incoming_stylesheets {
386 if !sheet.constructor_document_matches(owner_doc) {
389 return Err(Error::NotAllowed(Some(
390 "Stylesheet is not constructed or its constructor document does not match"
391 .into(),
392 )));
393 }
394 }
395
396 let mut stylesheet_remove_set = HashSet::with_capacity(adopted_stylesheets.len());
398
399 for sheet_to_remove in adopted_stylesheets.iter() {
402 if stylesheet_remove_set.insert(sheet_to_remove) {
404 owner.remove_stylesheet(
405 StylesheetSource::Constructed(sheet_to_remove.clone()),
406 &sheet_to_remove.style_stylesheet(),
407 );
408 sheet_to_remove.remove_adopter(owner);
409 }
410 }
411
412 let mut stylesheet_add_set = HashSet::with_capacity(incoming_stylesheets.len());
414
415 for sheet in incoming_stylesheets {
418 if !stylesheet_add_set.insert(sheet) {
420 owner.remove_stylesheet(
424 StylesheetSource::Constructed(sheet.clone()),
425 &sheet.style_stylesheet(),
426 );
427 } else {
428 sheet.add_adopter(owner.clone());
429 }
430
431 owner.append_constructed_stylesheet(sheet);
432 }
433
434 *adopted_stylesheets = incoming_stylesheets.to_vec();
435 Ok(())
436 }
437
438 pub(crate) fn on_set_adopted_stylesheets(
440 adopted_stylesheets: &mut Vec<Dom<CSSStyleSheet>>,
441 value: &CSSStyleSheet,
442 index: u32,
443 owner: &StyleSheetListOwner,
444 ) -> ErrorResult {
445 rooted_vec!(let mut incoming_stylesheets <- adopted_stylesheets.iter().cloned());
446 incoming_stylesheets.insert(index as usize, Dom::from_ref(value));
447 Self::set_adopted_stylesheets(adopted_stylesheets, &incoming_stylesheets, owner)
448 }
449
450 pub(crate) fn on_delete_adopted_stylesheets(
452 adopted_stylesheets: &mut Vec<Dom<CSSStyleSheet>>,
453 index: u32,
454 owner: &StyleSheetListOwner,
455 ) -> ErrorResult {
456 rooted_vec!(let mut incoming_stylesheets <- adopted_stylesheets.iter().cloned());
457 incoming_stylesheets.remove(index as usize);
458 Self::set_adopted_stylesheets(adopted_stylesheets, &incoming_stylesheets, owner)
459 }
460
461 pub(crate) fn get_fullscreen_element(
463 node: &Node,
464 fullscreen_element: Option<DomRoot<Element>>,
465 ) -> Option<DomRoot<Element>> {
466 if let Some(shadow_root) = node.downcast::<ShadowRoot>() &&
468 !shadow_root.Host().is_connected()
469 {
470 return None;
471 }
472
473 let retargeted = fullscreen_element?
475 .upcast::<EventTarget>()
476 .retarget(node.upcast());
477 let candidate = DomRoot::downcast::<Element>(retargeted).unwrap();
479
480 if *candidate
482 .upcast::<Node>()
483 .GetRootNode(&GetRootNodeOptions::empty()) ==
484 *node
485 {
486 return Some(candidate);
487 }
488
489 None
491 }
492}