1use std::cell::{Ref, RefCell, RefMut};
6use std::collections::HashMap;
7use std::fmt::Write as _;
8use std::str;
9
10use cssparser::{
11 AtRuleParser, CowRcStr, DeclarationParser, Delimiter, ParseError, Parser, ParserState,
12 QualifiedRuleParser, RuleBodyItemParser, RuleBodyParser, parse_important,
13};
14use devtools_traits::{
15 AncestorData, AttrModification, AutoMargins, ComputedNodeLayout, CssDatabaseProperty,
16 EventListenerInfo, GetHTMLType, MatchedRule, NodeInfo, NodeStyle, RuleModification,
17 StyleSheetInfo, TimelineMarker, TimelineMarkerType,
18};
19use html5ever::local_name;
20use js::context::JSContext;
21use markup5ever::{LocalName, ns};
22use rustc_hash::FxHashMap;
23use script_bindings::codegen::GenericBindings::CSSRuleBinding::CSSRuleMethods;
24use script_bindings::codegen::GenericBindings::NodeBinding::NodeMethods;
25use script_bindings::root::Dom;
26use servo_base::generic_channel::GenericSender;
27use servo_base::id::PipelineId;
28use servo_config::pref;
29use style::properties::{NonCustomPropertyId, PropertyId};
30use style::stylesheets::Origin;
31
32use crate::conversions::Convert;
33use crate::dom::bindings::codegen::Bindings::CSSGroupingRuleBinding::CSSGroupingRuleMethods;
34use crate::dom::bindings::codegen::Bindings::CSSLayerBlockRuleBinding::CSSLayerBlockRuleMethods;
35use crate::dom::bindings::codegen::Bindings::CSSRuleListBinding::CSSRuleListMethods;
36use crate::dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods;
37use crate::dom::bindings::codegen::Bindings::CSSStyleRuleBinding::CSSStyleRuleMethods;
38use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding::CSSStyleSheetMethods;
39use crate::dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods;
40use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
41use crate::dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
42use crate::dom::bindings::codegen::Bindings::HTMLElementBinding::HTMLElementMethods;
43use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeConstants;
44use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
45use crate::dom::bindings::inheritance::Castable;
46use crate::dom::bindings::root::DomRoot;
47use crate::dom::bindings::str::DOMString;
48use crate::dom::bindings::trace::NoTrace;
49use crate::dom::css::cssstylerule::CSSStyleRule;
50use crate::dom::document::AnimationFrameCallback;
51use crate::dom::element::Element;
52use crate::dom::iterators::ShadowIncluding;
53use crate::dom::node::{Node, NodeTraits};
54use crate::dom::types::{
55 CSSGroupingRule, CSSLayerBlockRule, EventTarget, HTMLElement, TrustedHTML,
56};
57use crate::event_loop::document_collection::DocumentCollection;
58use crate::realms::enter_auto_realm;
59
60#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
61#[derive(JSTraceable)]
62pub(crate) struct PerPipelineState {
63 #[no_trace]
64 pipeline: PipelineId,
65
66 known_nodes: FxHashMap<String, Dom<Node>>,
68}
69
70#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
71#[derive(JSTraceable, Default)]
72pub(crate) struct DevtoolsState {
73 per_pipeline_state: RefCell<FxHashMap<NoTrace<PipelineId>, PerPipelineState>>,
74}
75
76impl PerPipelineState {
77 fn register_node(&mut self, node: &Node) {
78 let unique_id = node.unique_id(self.pipeline);
79 self.known_nodes
80 .entry(unique_id)
81 .or_insert_with(|| Dom::from_ref(node));
82 }
83}
84
85impl DevtoolsState {
86 pub(crate) fn notify_pipeline_created(&self, pipeline: PipelineId) {
87 self.per_pipeline_state.borrow_mut().insert(
88 NoTrace(pipeline),
89 PerPipelineState {
90 pipeline,
91 known_nodes: Default::default(),
92 },
93 );
94 }
95 pub(crate) fn notify_pipeline_exited(&self, pipeline: PipelineId) {
96 self.per_pipeline_state
97 .borrow_mut()
98 .remove(&NoTrace(pipeline));
99 }
100
101 fn pipeline_state_for(&self, pipeline: PipelineId) -> Option<Ref<'_, PerPipelineState>> {
102 Ref::filter_map(self.per_pipeline_state.borrow(), |state| {
103 state.get(&NoTrace(pipeline))
104 })
105 .ok()
106 }
107
108 fn mut_pipeline_state_for(&self, pipeline: PipelineId) -> Option<RefMut<'_, PerPipelineState>> {
109 RefMut::filter_map(self.per_pipeline_state.borrow_mut(), |state| {
110 state.get_mut(&NoTrace(pipeline))
111 })
112 .ok()
113 }
114
115 pub(crate) fn wants_updates_for_node(&self, pipeline: PipelineId, node: &Node) -> bool {
116 let Some(unique_id) = node.unique_id_if_already_present() else {
117 return false;
120 };
121 self.pipeline_state_for(pipeline)
122 .is_some_and(|pipeline_state| pipeline_state.known_nodes.contains_key(&unique_id))
123 }
124
125 fn find_node_by_unique_id(&self, pipeline: PipelineId, node_id: &str) -> Option<DomRoot<Node>> {
126 self.pipeline_state_for(pipeline)?
127 .known_nodes
128 .get(node_id)
129 .map(|node: &Dom<Node>| node.as_rooted())
130 }
131}
132
133pub(crate) fn handle_set_timeline_markers(
134 documents: &DocumentCollection,
135 pipeline: PipelineId,
136 marker_types: Vec<TimelineMarkerType>,
137 reply: GenericSender<Option<TimelineMarker>>,
138) {
139 match documents.find_window(pipeline) {
140 None => reply.send(None).unwrap(),
141 Some(window) => window.set_devtools_timeline_markers(marker_types, reply),
142 }
143}
144
145pub(crate) fn handle_drop_timeline_markers(
146 documents: &DocumentCollection,
147 pipeline: PipelineId,
148 marker_types: Vec<TimelineMarkerType>,
149) {
150 if let Some(window) = documents.find_window(pipeline) {
151 window.drop_devtools_timeline_markers(marker_types);
152 }
153}
154
155pub(crate) fn handle_request_animation_frame(
156 documents: &DocumentCollection,
157 id: PipelineId,
158 actor_name: String,
159) {
160 if let Some(doc) = documents.find_document(id) {
161 doc.request_animation_frame(AnimationFrameCallback::DevtoolsFramerateTick { actor_name });
162 }
163}
164
165pub(crate) fn handle_get_favicon(
166 documents: &DocumentCollection,
167 pipeline: PipelineId,
168 reply: GenericSender<Option<Vec<u8>>>,
169) {
170 let favicon = documents
171 .find_document(pipeline)
172 .and_then(|doc| doc.favicon())
173 .map(|image| image.data().to_vec());
174 let _ = reply.send(favicon);
175}
176
177pub(crate) fn handle_get_css_database(reply: GenericSender<HashMap<String, CssDatabaseProperty>>) {
178 let database: HashMap<_, _> = NonCustomPropertyId::iter()
179 .filter(|id| PropertyId::NonCustom(*id).enabled_for_all_content())
180 .map(|id| {
181 let (is_inherited, subproperties) = match id.longhand_or_shorthand() {
182 Ok(longhand) => (longhand.inherited(), vec![longhand.name().into()]),
183 Err(shorthand) => (
184 shorthand.longhands().next().is_some_and(|l| l.inherited()),
185 shorthand.longhands().map(|l| l.name().into()).collect(),
186 ),
187 };
188 (
189 id.name().into(),
190 CssDatabaseProperty {
191 is_inherited,
192 values: vec![], supports: vec![],
194 subproperties,
195 },
196 )
197 })
198 .collect();
199 let _ = reply.send(database);
200}
201
202pub(crate) fn handle_get_event_listener_info(
203 state: &DevtoolsState,
204 pipeline: PipelineId,
205 node_id: &str,
206 reply: GenericSender<Vec<EventListenerInfo>>,
207) {
208 let Some(node) = state.find_node_by_unique_id(pipeline, node_id) else {
209 reply.send(vec![]).unwrap();
210 return;
211 };
212
213 let event_listeners = node
214 .upcast::<EventTarget>()
215 .summarize_event_listeners_for_devtools();
216 reply.send(event_listeners).unwrap();
217}
218
219pub(crate) fn handle_get_root_node(
220 cx: &mut JSContext,
221 state: &DevtoolsState,
222 documents: &DocumentCollection,
223 pipeline: PipelineId,
224 reply: GenericSender<Option<NodeInfo>>,
225) {
226 let info = documents
227 .find_document(pipeline)
228 .map(DomRoot::upcast::<Node>)
229 .inspect(|node| {
230 state
231 .mut_pipeline_state_for(pipeline)
232 .unwrap()
233 .register_node(node)
234 })
235 .map(|document| document.upcast::<Node>().summarize(cx));
236 reply.send(info).unwrap();
237}
238
239pub(crate) fn handle_get_document_element(
240 cx: &mut JSContext,
241 state: &DevtoolsState,
242 documents: &DocumentCollection,
243 pipeline: PipelineId,
244 reply: GenericSender<Option<NodeInfo>>,
245) {
246 let info = documents
247 .find_document(pipeline)
248 .and_then(|document| document.GetDocumentElement())
249 .inspect(|element| {
250 state
251 .mut_pipeline_state_for(pipeline)
252 .unwrap()
253 .register_node(element.upcast())
254 })
255 .map(|element| element.upcast::<Node>().summarize(cx));
256 reply.send(info).unwrap();
257}
258
259pub(crate) fn handle_get_stylesheets(
260 cx: &mut JSContext,
261 documents: &DocumentCollection,
262 pipeline: PipelineId,
263 reply: GenericSender<Vec<StyleSheetInfo>>,
264) {
265 let mut stylesheets = vec![];
266 if let Some(document) = documents.find_document(pipeline) {
267 let node = document.upcast::<Node>();
268 for i in 0..node.stylesheet_list_owner().stylesheet_count() {
269 if let Some(s) = node.stylesheet_list_owner().stylesheet_at(cx, i) {
270 stylesheets.push(StyleSheetInfo {
271 href: s.href().map(String::from),
272 disabled: s.disabled(),
273 title: String::from(s.title()),
274 style_sheet_index: i as i32,
275 system: s.origin() == Origin::UserAgent,
276 rule_count: s.get_rule_count(),
277 });
278 }
279 }
280 }
281 reply.send(stylesheets).unwrap();
282}
283
284pub(crate) fn handle_get_stylesheet_text(
285 cx: &mut JSContext,
286 documents: &DocumentCollection,
287 pipeline: PipelineId,
288 index: i32,
289 reply: GenericSender<Option<String>>,
290) {
291 let text = (|| {
292 let document = documents.find_document(pipeline)?;
293 let stylesheet = document
294 .upcast::<Node>()
295 .stylesheet_list_owner()
296 .stylesheet_at(cx, index as usize)?;
297
298 if let Some(node) = stylesheet.owner_node() {
300 let text = node.upcast::<Node>().GetTextContent().unwrap_or_default();
301 if !text.is_empty() {
302 return Some(String::from(text));
303 }
304 }
305
306 let rules = stylesheet.rulelist(cx);
308 let mut css_text = String::new();
309 for i in 0..rules.Length() {
310 if let Some(rule) = rules.Item(cx, i) {
311 css_text.push_str(&rule.CssText().str());
312 css_text.push('\n');
313 }
314 }
315 Some(css_text)
316 })();
317 reply.send(text).unwrap();
318}
319
320pub(crate) fn handle_get_children(
321 cx: &mut JSContext,
322 state: &DevtoolsState,
323 pipeline: PipelineId,
324 node_id: &str,
325 reply: GenericSender<Option<Vec<NodeInfo>>>,
326) {
327 let Some(parent) = state.find_node_by_unique_id(pipeline, node_id) else {
328 reply.send(None).unwrap();
329 return;
330 };
331 let is_whitespace = |node: &NodeInfo| {
332 node.node_type == NodeConstants::TEXT_NODE &&
333 node.node_value.as_ref().is_none_or(|v| v.trim().is_empty())
334 };
335 let mut pipeline_state = state.mut_pipeline_state_for(pipeline).unwrap();
336
337 let inline: Vec<_> = parent
338 .children()
339 .map(|child| {
340 let window = child.owner_window();
341 let Some(elem) = child.downcast::<Element>() else {
342 return false;
343 };
344 let computed_style = window.GetComputedStyle(cx, elem, None);
345 let display = computed_style.Display();
346 display == "inline"
347 })
348 .collect();
349
350 let mut children = vec![];
351 if let Some(shadow_root) = parent.downcast::<Element>().and_then(Element::shadow_root) &&
352 (!shadow_root.is_user_agent_widget() ||
353 pref!(inspector_show_servo_internal_shadow_roots))
354 {
355 children.push(shadow_root.upcast::<Node>().summarize(cx));
356 pipeline_state.register_node(shadow_root.upcast::<Node>());
357 }
358 let children_iter = parent.children().enumerate().filter_map(|(i, child)| {
359 let prev_inline = i > 0 && inline[i - 1];
362 let next_inline = i < inline.len() - 1 && inline[i + 1];
363 let is_inline_level = prev_inline && next_inline;
364
365 let info = child.summarize(cx);
366 if is_whitespace(&info) && !is_inline_level {
367 return None;
368 }
369 pipeline_state.register_node(&child);
370
371 Some(info)
372 });
373 children.extend(children_iter);
374
375 reply.send(Some(children)).unwrap();
376}
377
378struct NodeStyleParser;
380
381impl<'i> AtRuleParser<'i> for NodeStyleParser {
382 type Prelude = ();
383 type AtRule = NodeStyle;
384 type Error = ();
385}
386
387impl<'i> QualifiedRuleParser<'i> for NodeStyleParser {
388 type Prelude = ();
389 type QualifiedRule = NodeStyle;
390 type Error = ();
391}
392
393impl<'i> RuleBodyItemParser<'i, NodeStyle, ()> for NodeStyleParser {
394 fn parse_declarations(&self) -> bool {
395 true
396 }
397 fn parse_qualified(&self) -> bool {
398 false
399 }
400}
401
402impl<'i> DeclarationParser<'i> for NodeStyleParser {
403 type Declaration = NodeStyle;
404 type Error = ();
405
406 fn parse_value(
407 &mut self,
408 name: CowRcStr<'i>,
409 input: &mut Parser<'i>,
410 _declaration_start: &ParserState,
411 ) -> Result<NodeStyle, ParseError<()>> {
412 let start = input.position();
413 input.parse_until_before(Delimiter::Bang, |i| {
414 while i.next().is_ok() {}
415 Ok::<(), ParseError<()>>(())
416 })?;
417 let value = input.slice_from(start).trim().to_string();
418
419 let priority = if input.try_parse(parse_important).is_ok() {
420 "important".to_string()
421 } else {
422 String::new()
423 };
424 Ok(NodeStyle {
425 name: name.to_string(),
426 value,
427 priority,
428 })
429 }
430}
431
432fn node_styles_from_css_text(text: &str) -> Vec<NodeStyle> {
434 let mut parser = Parser::new(text);
435 RuleBodyParser::new(&mut parser, &mut NodeStyleParser)
436 .filter_map(Result::ok)
437 .collect()
438}
439
440pub(crate) fn handle_get_attribute_style(
441 _cx: &mut JSContext,
442 state: &DevtoolsState,
443 pipeline: PipelineId,
444 node_id: &str,
445 reply: GenericSender<Option<Vec<NodeStyle>>>,
446) {
447 let node = match state.find_node_by_unique_id(pipeline, node_id) {
448 None => return reply.send(None).unwrap(),
449 Some(found_node) => found_node,
450 };
451
452 let Some(elem) = node.downcast::<HTMLElement>() else {
453 reply.send(None).unwrap();
455 return;
456 };
457
458 let style_text = elem
459 .upcast::<Element>()
460 .get_string_attribute(&local_name!("style"));
461 let msg = node_styles_from_css_text(&style_text.str());
462
463 reply.send(Some(msg)).unwrap();
464}
465
466fn build_rule_map(
467 cx: &mut JSContext,
468 list: &crate::dom::css::cssrulelist::CSSRuleList,
469 stylesheet_index: usize,
470 ancestors: &[AncestorData],
471 map: &mut HashMap<usize, MatchedRule>,
472) {
473 for i in 0..list.Length() {
474 let Some(rule) = list.Item(cx, i) else {
475 continue;
476 };
477
478 if let Some(style_rule) = rule.downcast::<CSSStyleRule>() {
479 let block_id = style_rule.block_id();
480 map.entry(block_id).or_insert_with(|| MatchedRule {
481 selector: style_rule.SelectorText().into(),
482 stylesheet_index,
483 block_id,
484 ancestor_data: ancestors.to_vec(),
485 });
486 continue;
487 }
488
489 if let Some(layer_rule) = rule.downcast::<CSSLayerBlockRule>() {
490 let name = String::from(layer_rule.Name());
491 let mut next = ancestors.to_vec();
492 next.push(AncestorData::Layer {
493 actor_id: None,
494 value: (!name.is_empty()).then_some(name),
495 });
496 let inner = layer_rule.upcast::<CSSGroupingRule>().CssRules(cx);
497 build_rule_map(cx, &inner, stylesheet_index, &next, map);
498 continue;
499 }
500
501 if let Some(group_rule) = rule.downcast::<CSSGroupingRule>() {
502 let inner = group_rule.CssRules(cx);
503 build_rule_map(cx, &inner, stylesheet_index, ancestors, map);
504 }
505 }
506}
507
508fn find_rule_by_block_id(
509 cx: &mut JSContext,
510 list: &crate::dom::css::cssrulelist::CSSRuleList,
511 target_block_id: usize,
512) -> Option<DomRoot<CSSStyleRule>> {
513 for i in 0..list.Length() {
514 let Some(rule) = list.Item(cx, i) else {
515 continue;
516 };
517
518 if let Some(style_rule) = rule.downcast::<CSSStyleRule>() {
519 if style_rule.block_id() == target_block_id {
520 return Some(DomRoot::from_ref(style_rule));
521 }
522 continue;
523 }
524
525 if let Some(group_rule) = rule.downcast::<CSSGroupingRule>() {
526 let inner = group_rule.CssRules(cx);
527 if let Some(found) = find_rule_by_block_id(cx, &inner, target_block_id) {
528 return Some(found);
529 }
530 }
531 }
532 None
533}
534
535#[cfg_attr(crown, expect(crown::unrooted_must_root))]
536pub(crate) fn handle_get_selectors(
537 cx: &mut JSContext,
538 state: &DevtoolsState,
539 documents: &DocumentCollection,
540 pipeline: PipelineId,
541 node_id: &str,
542 reply: GenericSender<Option<Vec<MatchedRule>>>,
543) {
544 let msg = (|| {
545 let node = state.find_node_by_unique_id(pipeline, node_id)?;
546 let elem = node.downcast::<Element>()?;
547 let document = documents.find_document(pipeline)?;
548 let mut realm = enter_auto_realm(cx, document.window());
549 let cx = &mut realm.current_realm();
550 let owner = node.stylesheet_list_owner();
551
552 let mut decl_map = HashMap::new();
553 for i in 0..owner.stylesheet_count() {
554 let Some(stylesheet) = owner.stylesheet_at(cx, i) else {
555 continue;
556 };
557 let Ok(list) = stylesheet.GetCssRules(cx) else {
558 continue;
559 };
560 build_rule_map(cx, &list, i, &[], &mut decl_map);
561 }
562
563 let mut rules = Vec::new();
564 let computed = elem.style(cx)?;
565
566 if let Some(rule_node) = computed.rules.as_ref() {
567 for rn in rule_node.self_and_ancestors() {
568 if let Some(source) = rn.style_source() {
569 let ptr = source.get().raw_ptr().as_ptr() as usize;
570
571 if let Some(matched) = decl_map.get(&ptr) {
572 rules.push(matched.clone());
573 }
574 }
575 }
576 }
577
578 Some(rules)
579 })();
580
581 reply.send(msg).unwrap();
582}
583
584#[cfg_attr(crown, expect(crown::unrooted_must_root))]
585#[allow(clippy::too_many_arguments)]
586pub(crate) fn handle_get_stylesheet_style(
587 cx: &mut JSContext,
588 state: &DevtoolsState,
589 documents: &DocumentCollection,
590 pipeline: PipelineId,
591 node_id: &str,
592 matched_rule: MatchedRule,
593 reply: GenericSender<Option<Vec<NodeStyle>>>,
594) {
595 let msg = (|| {
596 let node = state.find_node_by_unique_id(pipeline, node_id)?;
597 let document = documents.find_document(pipeline)?;
598 let mut realm = enter_auto_realm(cx, document.window());
599 let cx = &mut realm.current_realm();
600 let owner = node.stylesheet_list_owner();
601
602 let stylesheet = owner.stylesheet_at(cx, matched_rule.stylesheet_index)?;
603 let list = stylesheet.GetCssRules(cx).ok()?;
604
605 let style_rule = find_rule_by_block_id(cx, &list, matched_rule.block_id)?;
606 let declaration = style_rule.Style(cx);
607
608 Some(node_styles_from_css_text(&declaration.CssText().str()))
609 })();
610
611 reply.send(msg).unwrap();
612}
613
614pub(crate) fn handle_get_computed_style(
615 cx: &mut JSContext,
616 state: &DevtoolsState,
617 pipeline: PipelineId,
618 node_id: &str,
619 reply: GenericSender<Option<Vec<NodeStyle>>>,
620) {
621 let node = match state.find_node_by_unique_id(pipeline, node_id) {
622 None => return reply.send(None).unwrap(),
623 Some(found_node) => found_node,
624 };
625
626 let window = node.owner_window();
627 let elem = node
628 .downcast::<Element>()
629 .expect("This should be an element");
630 let computed_style = window.GetComputedStyle(cx, elem, None);
631
632 let msg = (0..computed_style.Length())
633 .map(|i| {
634 let name = computed_style.Item(i);
635 NodeStyle {
636 value: String::from(computed_style.GetPropertyValue(name.clone())),
637 priority: String::from(computed_style.GetPropertyPriority(name.clone())),
638 name: String::from(name),
639 }
640 })
641 .collect();
642
643 reply.send(Some(msg)).unwrap();
644}
645
646pub(crate) fn handle_get_layout(
647 cx: &mut JSContext,
648 state: &DevtoolsState,
649 pipeline: PipelineId,
650 node_id: &str,
651 reply: GenericSender<Option<(ComputedNodeLayout, AutoMargins)>>,
652) {
653 let node = match state.find_node_by_unique_id(pipeline, node_id) {
654 None => return reply.send(None).unwrap(),
655 Some(found_node) => found_node,
656 };
657
658 let element = node
659 .downcast::<Element>()
660 .expect("should be getting layout of element");
661
662 let rect = element.GetBoundingClientRect(cx);
663 let width = rect.Width() as f32;
664 let height = rect.Height() as f32;
665
666 let window = node.owner_window();
667 let computed_style = window.GetComputedStyle(cx, element, None);
668 let computed_layout = ComputedNodeLayout {
669 display: computed_style.Display().into(),
670 position: computed_style.Position().into(),
671 z_index: computed_style.ZIndex().into(),
672 box_sizing: computed_style.BoxSizing().into(),
673 margin_top: computed_style.MarginTop().into(),
674 margin_right: computed_style.MarginRight().into(),
675 margin_bottom: computed_style.MarginBottom().into(),
676 margin_left: computed_style.MarginLeft().into(),
677 border_top_width: computed_style.BorderTopWidth().into(),
678 border_right_width: computed_style.BorderRightWidth().into(),
679 border_bottom_width: computed_style.BorderBottomWidth().into(),
680 border_left_width: computed_style.BorderLeftWidth().into(),
681 padding_top: computed_style.PaddingTop().into(),
682 padding_right: computed_style.PaddingRight().into(),
683 padding_bottom: computed_style.PaddingBottom().into(),
684 padding_left: computed_style.PaddingLeft().into(),
685 width,
686 height,
687 };
688
689 let auto_margins = element.determine_auto_margins(cx);
690 reply.send(Some((computed_layout, auto_margins))).unwrap();
691}
692
693pub(crate) fn handle_get_xpath(
694 state: &DevtoolsState,
695 pipeline: PipelineId,
696 node_id: &str,
697 reply: GenericSender<String>,
698) {
699 let Some(node) = state.find_node_by_unique_id(pipeline, node_id) else {
700 return reply.send(Default::default()).unwrap();
701 };
702
703 let selector = node
704 .inclusive_ancestors(ShadowIncluding::Yes)
705 .filter_map(|ancestor| {
706 let Some(element) = ancestor.downcast::<Element>() else {
707 return None;
709 };
710
711 let mut result = "/".to_owned();
712 if *element.namespace() != ns!(html) {
713 result.push_str(element.namespace());
714 result.push(':');
715 }
716
717 result.push_str(element.local_name());
718
719 let would_node_also_match_selector = |sibling: &Node| {
720 let Some(sibling) = sibling.downcast::<Element>() else {
721 return false;
722 };
723 sibling.namespace() == element.namespace() &&
724 sibling.local_name() == element.local_name()
725 };
726
727 let matching_elements_before = ancestor
728 .preceding_siblings()
729 .filter(|node| would_node_also_match_selector(node))
730 .count();
731 let matching_elements_after = ancestor
732 .following_siblings()
733 .filter(|node| would_node_also_match_selector(node))
734 .count();
735
736 if matching_elements_before + matching_elements_after != 0 {
737 write!(result, "[{}]", matching_elements_before + 1).unwrap();
739 }
740
741 Some(result)
742 })
743 .collect::<Vec<_>>()
744 .into_iter()
745 .rev()
746 .collect::<Vec<_>>()
747 .join("");
748
749 reply.send(selector).unwrap();
750}
751
752pub(crate) fn handle_get_inner_or_outer_html(
753 cx: &mut JSContext,
754 state: &DevtoolsState,
755 pipeline_id: PipelineId,
756 node_id: &str,
757 reply: GenericSender<Option<String>>,
758 html_type: GetHTMLType,
759) {
760 let node = state.find_node_by_unique_id(pipeline_id, node_id);
761
762 let selector = node.and_then(|node| {
763 let element = node.downcast::<Element>();
764
765 if let Some(element) = element {
766 let inner_or_outer_html = match html_type {
767 GetHTMLType::InnerHTML => element.GetInnerHTML(cx),
768 GetHTMLType::OuterHTML => element.GetOuterHTML(cx),
769 };
770
771 if let Ok(trusted_html) = inner_or_outer_html {
772 let trusted_html_or_string = trusted_html.convert();
773
774 let Ok(html_dom_string) = TrustedHTML::get_trusted_type_compliant_string(
775 cx,
776 &element.owner_global(),
777 trusted_html_or_string,
778 "Devtools GetInnerOrOuterHTML",
779 ) else {
780 return None;
781 };
782
783 return Some(html_dom_string.to_string());
784 };
785 }
786 Some(String::new())
787 });
788
789 reply.send(selector).unwrap();
790}
791
792pub(crate) fn handle_modify_attribute(
793 cx: &mut JSContext,
794 state: &DevtoolsState,
795 documents: &DocumentCollection,
796 pipeline: PipelineId,
797 node_id: &str,
798 modifications: Vec<AttrModification>,
799) {
800 let Some(document) = documents.find_document(pipeline) else {
801 return warn!("document for pipeline id {} is not found", pipeline);
802 };
803 let mut realm = enter_auto_realm(cx, document.window());
804 let cx = &mut realm.current_realm();
805
806 let node = match state.find_node_by_unique_id(pipeline, node_id) {
807 None => {
808 return warn!(
809 "node id {} for pipeline id {} is not found",
810 node_id, pipeline
811 );
812 },
813 Some(found_node) => found_node,
814 };
815
816 let elem = node
817 .downcast::<Element>()
818 .expect("should be getting layout of element");
819
820 for modification in modifications {
821 match modification.new_value {
822 Some(string) => {
823 let name = LocalName::from(modification.attribute_name);
824 let value = elem.parse_attribute(&ns!(), &name, DOMString::from(string));
825 elem.set_attribute(cx, &name, value);
826 },
827 None => elem.RemoveAttribute(cx, DOMString::from(modification.attribute_name)),
828 }
829 }
830}
831
832pub(crate) fn handle_modify_rule(
833 cx: &mut JSContext,
834 state: &DevtoolsState,
835 documents: &DocumentCollection,
836 pipeline: PipelineId,
837 node_id: &str,
838 modifications: Vec<RuleModification>,
839) {
840 let Some(document) = documents.find_document(pipeline) else {
841 return warn!("Document for pipeline id {} is not found", pipeline);
842 };
843 let mut realm = enter_auto_realm(cx, document.window());
844 let cx = &mut realm.current_realm();
845
846 let Some(node) = state.find_node_by_unique_id(pipeline, node_id) else {
847 return warn!(
848 "Node id {} for pipeline id {} is not found",
849 node_id, pipeline
850 );
851 };
852
853 let elem = node
854 .downcast::<HTMLElement>()
855 .expect("This should be an HTMLElement");
856 let style = elem.Style(cx);
857
858 for modification in modifications {
859 let _ = style.SetProperty(
860 cx,
861 modification.name.into(),
862 modification.value.into(),
863 modification.priority.into(),
864 );
865 }
866}
867
868pub(crate) fn handle_highlight_dom_node(
869 state: &DevtoolsState,
870 documents: &DocumentCollection,
871 id: PipelineId,
872 node_id: Option<&str>,
873) {
874 let node = node_id.and_then(|node_id| {
875 let node = state.find_node_by_unique_id(id, node_id);
876 if node.is_none() {
877 log::warn!("Node id {node_id} for pipeline id {id} is not found",);
878 }
879 node
880 });
881
882 if let Some(window) = documents.find_window(id) {
883 window.Document().highlight_dom_node(node.as_deref());
884 }
885}
886
887impl Element {
888 fn determine_auto_margins(&self, cx: &mut JSContext) -> AutoMargins {
889 let Some(style) = self.style(cx) else {
890 return AutoMargins::default();
891 };
892 let margin = style.get_margin();
893 AutoMargins {
894 top: margin.margin_top.is_auto(),
895 right: margin.margin_right.is_auto(),
896 bottom: margin.margin_bottom.is_auto(),
897 left: margin.margin_left.is_auto(),
898 }
899 }
900}