/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use std::cell::{Ref, RefCell, RefMut}; use std::collections::HashMap; use std::str; use devtools_traits::{ AncestorData, AttrModification, AutoMargins, ComputedNodeLayout, CssDatabaseProperty, EventListenerInfo, GetHTMLType, MatchedRule, NodeInfo, NodeStyle, RuleModification, StyleSheetInfo, TimelineMarker, TimelineMarkerType, }; use js::context::JSContext; use markup5ever::{LocalName, ns}; use rustc_hash::FxHashMap; use script_bindings::codegen::GenericBindings::CSSRuleBinding::CSSRuleMethods; use script_bindings::codegen::GenericBindings::NodeBinding::NodeMethods; use script_bindings::root::Dom; use servo_base::generic_channel::GenericSender; use servo_base::id::PipelineId; use servo_config::pref; use style::attr::AttrValue; use style::stylesheets::Origin; use crate::conversions::Convert; use crate::dom::bindings::codegen::Bindings::CSSGroupingRuleBinding::CSSGroupingRuleMethods; use crate::dom::bindings::codegen::Bindings::CSSLayerBlockRuleBinding::CSSLayerBlockRuleMethods; use crate::dom::bindings::codegen::Bindings::CSSRuleListBinding::CSSRuleListMethods; use crate::dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods; use crate::dom::bindings::codegen::Bindings::CSSStyleRuleBinding::CSSStyleRuleMethods; use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding::CSSStyleSheetMethods; use crate::dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods; use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use crate::dom::bindings::codegen::Bindings::ElementBinding::ElementMethods; use crate::dom::bindings::codegen::Bindings::HTMLElementBinding::HTMLElementMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeConstants; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::bindings::trace::NoTrace; use crate::dom::css::cssstyledeclaration::ENABLED_LONGHAND_PROPERTIES; use crate::dom::css::cssstylerule::CSSStyleRule; use crate::dom::document::AnimationFrameCallback; use crate::dom::element::Element; use crate::dom::iterators::ShadowIncluding; use crate::dom::node::{Node, NodeTraits}; use crate::dom::types::{ CSSGroupingRule, CSSLayerBlockRule, EventTarget, HTMLElement, TrustedHTML, }; use crate::event_loop::document_collection::DocumentCollection; use crate::realms::enter_auto_realm; #[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)] #[derive(JSTraceable)] pub(crate) struct PerPipelineState { #[no_trace] pipeline: PipelineId, /// Maps from a node's unique ID to the Node itself known_nodes: FxHashMap>, } #[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)] #[derive(JSTraceable, Default)] pub(crate) struct DevtoolsState { per_pipeline_state: RefCell, PerPipelineState>>, } impl PerPipelineState { fn register_node(&mut self, node: &Node) { let unique_id = node.unique_id(self.pipeline); self.known_nodes .entry(unique_id) .or_insert_with(|| Dom::from_ref(node)); } } impl DevtoolsState { pub(crate) fn notify_pipeline_created(&self, pipeline: PipelineId) { self.per_pipeline_state.borrow_mut().insert( NoTrace(pipeline), PerPipelineState { pipeline, known_nodes: Default::default(), }, ); } pub(crate) fn notify_pipeline_exited(&self, pipeline: PipelineId) { self.per_pipeline_state .borrow_mut() .remove(&NoTrace(pipeline)); } fn pipeline_state_for(&self, pipeline: PipelineId) -> Option> { Ref::filter_map(self.per_pipeline_state.borrow(), |state| { state.get(&NoTrace(pipeline)) }) .ok() } fn mut_pipeline_state_for(&self, pipeline: PipelineId) -> Option> { RefMut::filter_map(self.per_pipeline_state.borrow_mut(), |state| { state.get_mut(&NoTrace(pipeline)) }) .ok() } pub(crate) fn wants_updates_for_node(&self, pipeline: PipelineId, node: &Node) -> bool { let Some(unique_id) = node.unique_id_if_already_present() else { // This node does not have a unique id, so clearly the devtools inspector // hasn't seen it before. return false; }; self.pipeline_state_for(pipeline) .is_some_and(|pipeline_state| pipeline_state.known_nodes.contains_key(&unique_id)) } fn find_node_by_unique_id(&self, pipeline: PipelineId, node_id: &str) -> Option> { self.pipeline_state_for(pipeline)? .known_nodes .get(node_id) .map(|node: &Dom| node.as_rooted()) } } pub(crate) fn handle_set_timeline_markers( documents: &DocumentCollection, pipeline: PipelineId, marker_types: Vec, reply: GenericSender>, ) { match documents.find_window(pipeline) { None => reply.send(None).unwrap(), Some(window) => window.set_devtools_timeline_markers(marker_types, reply), } } pub(crate) fn handle_drop_timeline_markers( documents: &DocumentCollection, pipeline: PipelineId, marker_types: Vec, ) { if let Some(window) = documents.find_window(pipeline) { window.drop_devtools_timeline_markers(marker_types); } } pub(crate) fn handle_request_animation_frame( documents: &DocumentCollection, id: PipelineId, actor_name: String, ) { if let Some(doc) = documents.find_document(id) { doc.request_animation_frame(AnimationFrameCallback::DevtoolsFramerateTick { actor_name }); } } pub(crate) fn handle_get_css_database(reply: GenericSender>) { let database: HashMap<_, _> = ENABLED_LONGHAND_PROPERTIES .iter() .map(|l| { ( l.name().into(), CssDatabaseProperty { is_inherited: l.inherited(), values: vec![], // TODO: Get allowed values for each property supports: vec![], subproperties: vec![l.name().into()], }, ) }) .collect(); let _ = reply.send(database); } pub(crate) fn handle_get_event_listener_info( state: &DevtoolsState, pipeline: PipelineId, node_id: &str, reply: GenericSender>, ) { let Some(node) = state.find_node_by_unique_id(pipeline, node_id) else { reply.send(vec![]).unwrap(); return; }; let event_listeners = node .upcast::() .summarize_event_listeners_for_devtools(); reply.send(event_listeners).unwrap(); } pub(crate) fn handle_get_root_node( cx: &mut JSContext, state: &DevtoolsState, documents: &DocumentCollection, pipeline: PipelineId, reply: GenericSender>, ) { let info = documents .find_document(pipeline) .map(DomRoot::upcast::) .inspect(|node| { state .mut_pipeline_state_for(pipeline) .unwrap() .register_node(node) }) .map(|document| document.upcast::().summarize(cx)); reply.send(info).unwrap(); } pub(crate) fn handle_get_document_element( cx: &mut JSContext, state: &DevtoolsState, documents: &DocumentCollection, pipeline: PipelineId, reply: GenericSender>, ) { let info = documents .find_document(pipeline) .and_then(|document| document.GetDocumentElement()) .inspect(|element| { state .mut_pipeline_state_for(pipeline) .unwrap() .register_node(element.upcast()) }) .map(|element| element.upcast::().summarize(cx)); reply.send(info).unwrap(); } pub(crate) fn handle_get_stylesheets( cx: &mut JSContext, documents: &DocumentCollection, pipeline: PipelineId, reply: GenericSender>, ) { let mut stylesheets = vec![]; if let Some(document) = documents.find_document(pipeline) { let node = document.upcast::(); for i in 0..node.stylesheet_list_owner().stylesheet_count() { if let Some(s) = node.stylesheet_list_owner().stylesheet_at(cx, i) { stylesheets.push(StyleSheetInfo { href: s.href().map(String::from), disabled: s.disabled(), title: String::from(s.title()), style_sheet_index: i as i32, system: s.origin() == Origin::UserAgent, rule_count: s.get_rule_count(), }); } } } reply.send(stylesheets).unwrap(); } pub(crate) fn handle_get_stylesheet_text( cx: &mut JSContext, documents: &DocumentCollection, pipeline: PipelineId, index: i32, reply: GenericSender>, ) { let text = (|| { let document = documents.find_document(pipeline)?; let stylesheet = document .upcast::() .stylesheet_list_owner() .stylesheet_at(cx, index as usize)?; // For inline, Prefer the original "authored" source from the owner node (e.g.,