DevTools: Show HTML tree (#32655)

* feat: watch root node

Signed-off-by: eri <eri@inventati.org>

* reafactor: divide inspector in components

Signed-off-by: eri <eri@inventati.org>

* feat: add css properties actor

Signed-off-by: eri <eri@inventati.org>

* feat: accesibility actor

Signed-off-by: eri <eri@inventati.org>

* feat: layout actor

Signed-off-by: eri <eri@inventati.org>

* feat: network parent and refactor

Signed-off-by: eri <eri@inventati.org>

* feat: progress on the inspector messages

Signed-off-by: eri <eri@inventati.org>

* feat: more progress on inspector

Signed-off-by: eri <eri@inventati.org>

* feat: try to fix nodes showing

Signed-off-by: eri <eri@inventati.org>

* feat: initial dom tree

Signed-off-by: eri <eri@inventati.org>

* feat: some more messages

Signed-off-by: eri <eri@inventati.org>

* feat: clean and add documentation

Signed-off-by: eri <eri@inventati.org>

* refactor: add more docs and clean

Signed-off-by: eri <eri@inventati.org>

* fix: restore deleted node attributes field

Signed-off-by: eri <eri@inventati.org>

* Apply suggestions from code review

Fix a few nits in comments

Signed-off-by: Martin Robinson <mrobinson@igalia.com>

---------

Signed-off-by: eri <eri@inventati.org>
Signed-off-by: Martin Robinson <mrobinson@igalia.com>
Co-authored-by: Martin Robinson <mrobinson@igalia.com>
This commit is contained in:
eri 2024-07-26 17:17:54 +02:00 committed by GitHub
parent f7448b5d61
commit 902bf57331
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
23 changed files with 1487 additions and 833 deletions

View file

@ -0,0 +1,132 @@
/* 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/. */
//! The Accessibility actor is responsible for the Accessibility tab in the DevTools page. Right
//! now it is a placeholder for future functionality.
use std::net::TcpStream;
use serde::Serialize;
use serde_json::{Map, Value};
use crate::actor::{Actor, ActorMessageStatus, ActorRegistry};
use crate::protocol::JsonPacketStream;
use crate::StreamId;
#[derive(Serialize)]
struct BootstrapState {
enabled: bool,
}
#[derive(Serialize)]
struct BootstrapReply {
from: String,
state: BootstrapState,
}
#[derive(Serialize)]
struct GetSimulatorReply {
from: String,
simulator: ActorMsg,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct AccessibilityTraits {
tabbing_order: bool,
}
#[derive(Serialize)]
struct GetTraitsReply {
from: String,
traits: AccessibilityTraits,
}
#[derive(Serialize)]
struct ActorMsg {
actor: String,
}
#[derive(Serialize)]
struct GetWalkerReply {
from: String,
walker: ActorMsg,
}
pub struct AccessibilityActor {
name: String,
}
impl Actor for AccessibilityActor {
fn name(&self) -> String {
self.name.clone()
}
/// The accesibility actor can handle the following messages:
///
/// - `bootstrap`: It is required but it doesn't do anything yet
///
/// - `getSimulator`: Returns a new Simulator actor
///
/// - `getTraits`: Informs the DevTools client about the configuration of the accessibility actor
///
/// - `getWalker`: Returns a new AccessibleWalker actor (not to be confused with the general
/// inspector Walker actor)
fn handle_message(
&self,
registry: &ActorRegistry,
msg_type: &str,
_msg: &Map<String, Value>,
stream: &mut TcpStream,
_id: StreamId,
) -> Result<ActorMessageStatus, ()> {
Ok(match msg_type {
"bootstrap" => {
let msg = BootstrapReply {
from: self.name(),
state: BootstrapState { enabled: false },
};
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"getSimulator" => {
// TODO: Create actual simulator
let simulator = registry.new_name("simulator");
let msg = GetSimulatorReply {
from: self.name(),
simulator: ActorMsg { actor: simulator },
};
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"getTraits" => {
let msg = GetTraitsReply {
from: self.name(),
traits: AccessibilityTraits {
tabbing_order: true,
},
};
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"getWalker" => {
// TODO: Create actual accessible walker
let walker = registry.new_name("accesiblewalker");
let msg = GetWalkerReply {
from: self.name(),
walker: ActorMsg { actor: walker },
};
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
_ => ActorMessageStatus::Ignored,
})
}
}
impl AccessibilityActor {
pub fn new(name: String) -> Self {
Self { name }
}
}

View file

@ -0,0 +1,81 @@
/* 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/. */
//! This actor holds a database of available css properties, their supported values and
//! alternative names
use std::collections::HashMap;
use std::net::TcpStream;
use serde::Serialize;
use serde_json::{Map, Value};
use crate::actor::{Actor, ActorMessageStatus, ActorRegistry};
use crate::protocol::JsonPacketStream;
use crate::StreamId;
pub struct CssPropertiesActor {
name: String,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct CssDatabaseProperty {
is_inherited: bool,
values: Vec<&'static str>,
supports: Vec<&'static str>,
subproperties: Vec<&'static str>,
}
#[derive(Serialize)]
struct GetCssDatabaseReply {
properties: HashMap<&'static str, CssDatabaseProperty>,
from: String,
}
impl Actor for CssPropertiesActor {
fn name(&self) -> String {
self.name.clone()
}
/// The css properties actor can handle the following messages:
///
/// - `getCSSDatabase`: Returns a big list of every supported css property so that the
/// inspector can show the available options
fn handle_message(
&self,
_registry: &ActorRegistry,
msg_type: &str,
_msg: &Map<String, Value>,
stream: &mut TcpStream,
_id: StreamId,
) -> Result<ActorMessageStatus, ()> {
Ok(match msg_type {
"getCSSDatabase" => {
let _ = stream.write_json_packet(&GetCssDatabaseReply {
from: self.name(),
// TODO: Fill this programatically with other properties
properties: HashMap::from([(
"color",
CssDatabaseProperty {
is_inherited: true,
values: vec!["color"],
supports: vec!["color"],
subproperties: vec!["color"],
},
)]),
});
ActorMessageStatus::Processed
},
_ => ActorMessageStatus::Ignored,
})
}
}
impl CssPropertiesActor {
pub fn new(name: String) -> Self {
Self { name }
}
}

View file

@ -0,0 +1,69 @@
/* 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/. */
//! Handles highlighting selected DOM nodes in the inspector. At the moment it only replies and
//! changes nothing on Servo's side.
use std::net::TcpStream;
use serde::Serialize;
use serde_json::{self, Map, Value};
use crate::actor::{Actor, ActorMessageStatus, ActorRegistry};
use crate::protocol::JsonPacketStream;
use crate::{EmptyReplyMsg, StreamId};
#[derive(Serialize)]
pub struct HighlighterMsg {
pub actor: String,
}
pub struct HighlighterActor {
pub name: String,
}
#[derive(Serialize)]
struct ShowReply {
from: String,
value: bool,
}
impl Actor for HighlighterActor {
fn name(&self) -> String {
self.name.clone()
}
/// The highligher actor can handle the following messages:
///
/// - `show`: Enables highlighting for the selected node
///
/// - `hide`: Disables highlighting for the selected node
fn handle_message(
&self,
_registry: &ActorRegistry,
msg_type: &str,
_msg: &Map<String, Value>,
stream: &mut TcpStream,
_id: StreamId,
) -> Result<ActorMessageStatus, ()> {
Ok(match msg_type {
"show" => {
let msg = ShowReply {
from: self.name(),
value: true,
};
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"hide" => {
let msg = EmptyReplyMsg { from: self.name() };
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
_ => ActorMessageStatus::Ignored,
})
}
}

View file

@ -0,0 +1,88 @@
/* 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/. */
//! The layout actor informs the DevTools client of the layout properties of the document, such as
//! grids or flexboxes. It acts as a placeholder for now.
use std::net::TcpStream;
use serde::Serialize;
use serde_json::{Map, Value};
use crate::actor::{Actor, ActorMessageStatus, ActorRegistry};
use crate::protocol::JsonPacketStream;
use crate::StreamId;
#[derive(Serialize)]
pub struct LayoutInspectorActorMsg {
actor: String,
}
pub struct LayoutInspectorActor {
name: String,
}
#[derive(Serialize)]
pub struct GetGridsReply {
from: String,
grids: Vec<String>,
}
#[derive(Serialize)]
pub struct GetCurrentFlexboxReply {
from: String,
flexbox: Option<()>,
}
impl Actor for LayoutInspectorActor {
fn name(&self) -> String {
self.name.clone()
}
/// The layout inspector actor can handle the following messages:
///
/// - `getGrids`: Returns a list of CSS grids, non functional at the moment
///
/// - `getCurrentFlexbox`: Returns the active flexbox, non functional at the moment
fn handle_message(
&self,
_registry: &ActorRegistry,
msg_type: &str,
_msg: &Map<String, Value>,
stream: &mut TcpStream,
_id: StreamId,
) -> Result<ActorMessageStatus, ()> {
Ok(match msg_type {
"getGrids" => {
let msg = GetGridsReply {
from: self.name(),
// TODO: Actually create a list of grids
grids: vec![],
};
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"getCurrentFlexbox" => {
let msg = GetCurrentFlexboxReply {
from: self.name(),
// TODO: Create and return the current flexbox object
flexbox: None,
};
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
_ => ActorMessageStatus::Ignored,
})
}
}
impl LayoutInspectorActor {
pub fn new(name: String) -> Self {
Self { name }
}
pub fn encodable(&self) -> LayoutInspectorActorMsg {
LayoutInspectorActorMsg { actor: self.name() }
}
}

View file

@ -0,0 +1,204 @@
/* 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/. */
//! This actor represents one DOM node. It is created by the Walker actor when it is traversing the
//! document tree.
use std::collections::HashMap;
use std::net::TcpStream;
use base::id::PipelineId;
use devtools_traits::DevtoolScriptControlMsg::{GetDocumentElement, ModifyAttribute};
use devtools_traits::{DevtoolScriptControlMsg, NodeInfo};
use ipc_channel::ipc::{self, IpcSender};
use serde::Serialize;
use serde_json::{self, Map, Value};
use crate::actor::{Actor, ActorMessageStatus, ActorRegistry};
use crate::protocol::JsonPacketStream;
use crate::{EmptyReplyMsg, StreamId};
#[derive(Serialize)]
struct GetUniqueSelectorReply {
from: String,
value: String,
}
#[derive(Clone, Serialize)]
struct AttrMsg {
name: String,
value: String,
}
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NodeActorMsg {
pub actor: String,
#[serde(rename = "baseURI")]
base_uri: String,
causes_overflow: bool,
container_type: Option<()>,
pub display_name: String,
display_type: Option<String>,
is_after_pseudo_element: bool,
is_anonymous: bool,
is_before_pseudo_element: bool,
is_direct_shadow_host_child: Option<bool>,
is_displayed: bool,
#[serde(rename = "isInHTMLDocument")]
is_in_html_document: Option<bool>,
is_marker_pseudo_element: bool,
is_native_anonymous: bool,
is_scrollable: bool,
is_shadow_root: bool,
is_top_level_document: bool,
node_name: String,
node_type: u16,
node_value: Option<()>,
pub num_children: usize,
#[serde(skip_serializing_if = "String::is_empty")]
parent: String,
shadow_root_mode: Option<()>,
traits: HashMap<String, ()>,
attrs: Vec<AttrMsg>,
}
pub struct NodeActor {
name: String,
script_chan: IpcSender<DevtoolScriptControlMsg>,
pipeline: PipelineId,
}
impl Actor for NodeActor {
fn name(&self) -> String {
self.name.clone()
}
/// The node actor can handle the following messages:
///
/// - `modifyAttributes`: Asks the script to change a value in the attribute of the
/// corresponding node
///
/// - `getUniqueSelector`: Returns the display name of this node
fn handle_message(
&self,
registry: &ActorRegistry,
msg_type: &str,
msg: &Map<String, Value>,
stream: &mut TcpStream,
_id: StreamId,
) -> Result<ActorMessageStatus, ()> {
Ok(match msg_type {
"modifyAttributes" => {
let target = msg.get("to").ok_or(())?.as_str().ok_or(())?;
let mods = msg.get("modifications").ok_or(())?.as_array().ok_or(())?;
let modifications = mods
.iter()
.filter_map(|json_mod| {
serde_json::from_str(&serde_json::to_string(json_mod).ok()?).ok()
})
.collect();
self.script_chan
.send(ModifyAttribute(
self.pipeline,
registry.actor_to_script(target.to_owned()),
modifications,
))
.map_err(|_| ())?;
let reply = EmptyReplyMsg { from: self.name() };
let _ = stream.write_json_packet(&reply);
ActorMessageStatus::Processed
},
"getUniqueSelector" => {
let (tx, rx) = ipc::channel().unwrap();
self.script_chan
.send(GetDocumentElement(self.pipeline, tx))
.unwrap();
let doc_elem_info = rx.recv().map_err(|_| ())?.ok_or(())?;
let node =
doc_elem_info.encode(registry, true, self.script_chan.clone(), self.pipeline);
let msg = GetUniqueSelectorReply {
from: self.name(),
value: node.display_name,
};
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
_ => ActorMessageStatus::Ignored,
})
}
}
pub trait NodeInfoToProtocol {
fn encode(
self,
actors: &ActorRegistry,
display: bool,
script_chan: IpcSender<DevtoolScriptControlMsg>,
pipeline: PipelineId,
) -> NodeActorMsg;
}
impl NodeInfoToProtocol for NodeInfo {
fn encode(
self,
actors: &ActorRegistry,
display: bool,
script_chan: IpcSender<DevtoolScriptControlMsg>,
pipeline: PipelineId,
) -> NodeActorMsg {
let actor = if !actors.script_actor_registered(self.unique_id.clone()) {
let name = actors.new_name("node");
let node_actor = NodeActor {
name: name.clone(),
script_chan,
pipeline,
};
actors.register_script_actor(self.unique_id, name.clone());
actors.register_later(Box::new(node_actor));
name
} else {
actors.script_to_actor(self.unique_id)
};
NodeActorMsg {
actor,
base_uri: self.base_uri,
causes_overflow: false,
container_type: None,
display_name: self.node_name.clone().to_lowercase(),
display_type: Some("block".into()),
is_after_pseudo_element: false,
is_anonymous: false,
is_before_pseudo_element: false,
is_direct_shadow_host_child: None,
is_displayed: display,
is_in_html_document: Some(true),
is_marker_pseudo_element: false,
is_native_anonymous: false,
is_scrollable: false,
is_shadow_root: false,
is_top_level_document: self.is_top_level_document,
node_name: self.node_name,
node_type: self.node_type,
node_value: None,
num_children: self.num_children,
parent: actors.script_to_actor(self.parent.clone()),
shadow_root_mode: None,
traits: HashMap::new(),
attrs: self
.attrs
.into_iter()
.map(|attr| AttrMsg {
name: attr.name,
value: attr.value,
})
.collect(),
}
}
}

View file

@ -0,0 +1,263 @@
/* 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/. */
//! The page style actor is responsible of informing the DevTools client of the different style
//! properties applied, including the attributes and layout of each element.
use std::collections::HashMap;
use std::net::TcpStream;
use base::id::PipelineId;
use devtools_traits::DevtoolScriptControlMsg::GetLayout;
use devtools_traits::{ComputedNodeLayout, DevtoolScriptControlMsg};
use ipc_channel::ipc::{self, IpcSender};
use serde::Serialize;
use serde_json::{self, Map, Value};
use crate::actor::{Actor, ActorMessageStatus, ActorRegistry};
use crate::protocol::JsonPacketStream;
use crate::StreamId;
#[derive(Serialize)]
struct GetAppliedReply {
entries: Vec<AppliedEntry>,
rules: Vec<AppliedRule>,
sheets: Vec<AppliedSheet>,
from: String,
}
#[derive(Serialize)]
struct GetComputedReply {
computed: Vec<u32>, //XXX all css props
from: String,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct AppliedEntry {
rule: String,
pseudo_element: Value,
is_system: bool,
matched_selectors: Vec<String>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct AppliedRule {
actor: String,
#[serde(rename = "type")]
type_: String,
href: String,
css_text: String,
line: u32,
column: u32,
parent_style_sheet: String,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct AppliedSheet {
actor: String,
href: String,
node_href: String,
disabled: bool,
title: String,
system: bool,
style_sheet_index: isize,
rule_count: usize,
}
#[derive(Serialize)]
#[serde(rename_all = "kebab-case")]
struct GetLayoutReply {
from: String,
display: String,
position: String,
z_index: String,
box_sizing: String,
// Would be nice to use a proper struct, blocked by
// https://github.com/serde-rs/serde/issues/43
auto_margins: serde_json::value::Value,
margin_top: String,
margin_right: String,
margin_bottom: String,
margin_left: String,
border_top_width: String,
border_right_width: String,
border_bottom_width: String,
border_left_width: String,
padding_top: String,
padding_right: String,
padding_bottom: String,
padding_left: String,
width: f32,
height: f32,
}
#[derive(Serialize)]
pub struct IsPositionEditableReply {
pub from: String,
pub value: bool,
}
#[derive(Serialize)]
pub struct PageStyleMsg {
pub actor: String,
pub traits: HashMap<String, bool>,
}
pub struct PageStyleActor {
pub name: String,
pub script_chan: IpcSender<DevtoolScriptControlMsg>,
pub pipeline: PipelineId,
}
impl Actor for PageStyleActor {
fn name(&self) -> String {
self.name.clone()
}
/// The page style actor can handle the following messages:
///
/// - `getApplied`: Returns the applied styles for a node, placeholder
///
/// - `getComputed`: Returns the computed styles for a node, placeholder
///
/// - `getLayout`: Returns the box layout properties for a node, placeholder
///
/// - `isPositionEditable`: Informs whether you can change a style property in the inspector
fn handle_message(
&self,
registry: &ActorRegistry,
msg_type: &str,
msg: &Map<String, Value>,
stream: &mut TcpStream,
_id: StreamId,
) -> Result<ActorMessageStatus, ()> {
Ok(match msg_type {
"getApplied" => {
// TODO: Query script for relevant applied styles to node (msg.node)
let msg = GetAppliedReply {
entries: vec![],
rules: vec![],
sheets: vec![],
from: self.name(),
};
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"getComputed" => {
// TODO: Query script for relevant computed styles on node (msg.node)
let msg = GetComputedReply {
computed: vec![],
from: self.name(),
};
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"getLayout" => {
// TODO: Query script for box layout properties of node (msg.node)
let target = msg.get("node").ok_or(())?.as_str().ok_or(())?;
let (tx, rx) = ipc::channel().map_err(|_| ())?;
self.script_chan
.send(GetLayout(
self.pipeline,
registry.actor_to_script(target.to_owned()),
tx,
))
.unwrap();
let ComputedNodeLayout {
display,
position,
z_index,
box_sizing,
auto_margins,
margin_top,
margin_right,
margin_bottom,
margin_left,
border_top_width,
border_right_width,
border_bottom_width,
border_left_width,
padding_top,
padding_right,
padding_bottom,
padding_left,
width,
height,
} = rx.recv().map_err(|_| ())?.ok_or(())?;
let msg_auto_margins = msg
.get("autoMargins")
.and_then(Value::as_bool)
.unwrap_or(false);
// https://searchfox.org/mozilla-central/source/devtools/server/actors/page-style.js
let msg = GetLayoutReply {
from: self.name(),
display,
position,
z_index,
box_sizing,
auto_margins: if msg_auto_margins {
let mut m = Map::new();
let auto = serde_json::value::Value::String("auto".to_owned());
if auto_margins.top {
m.insert("top".to_owned(), auto.clone());
}
if auto_margins.right {
m.insert("right".to_owned(), auto.clone());
}
if auto_margins.bottom {
m.insert("bottom".to_owned(), auto.clone());
}
if auto_margins.left {
m.insert("left".to_owned(), auto);
}
serde_json::value::Value::Object(m)
} else {
serde_json::value::Value::Null
},
margin_top,
margin_right,
margin_bottom,
margin_left,
border_top_width,
border_right_width,
border_bottom_width,
border_left_width,
padding_top,
padding_right,
padding_bottom,
padding_left,
width,
height,
};
let msg = serde_json::to_string(&msg).map_err(|_| ())?;
let msg = serde_json::from_str::<Value>(&msg).map_err(|_| ())?;
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"isPositionEditable" => {
let msg = IsPositionEditableReply {
from: self.name(),
value: false,
};
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
_ => ActorMessageStatus::Ignored,
})
}
}

View file

@ -0,0 +1,263 @@
/* 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/. */
//! The walker actor is responsible for traversing the DOM tree in various ways to create new nodes
use std::net::TcpStream;
use base::id::PipelineId;
use devtools_traits::DevtoolScriptControlMsg;
use devtools_traits::DevtoolScriptControlMsg::{GetChildren, GetDocumentElement};
use ipc_channel::ipc::{self, IpcSender};
use serde::Serialize;
use serde_json::{self, Map, Value};
use crate::actor::{Actor, ActorMessageStatus, ActorRegistry};
use crate::actors::inspector::layout::{LayoutInspectorActor, LayoutInspectorActorMsg};
use crate::actors::inspector::node::{NodeActorMsg, NodeInfoToProtocol};
use crate::protocol::JsonPacketStream;
use crate::{EmptyReplyMsg, StreamId};
#[derive(Serialize)]
pub struct WalkerMsg {
pub actor: String,
pub root: NodeActorMsg,
}
pub struct WalkerActor {
pub name: String,
pub script_chan: IpcSender<DevtoolScriptControlMsg>,
pub pipeline: PipelineId,
pub root_node: NodeActorMsg,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct QuerySelectorReply {
from: String,
node: NodeActorMsg,
new_parents: Vec<NodeActorMsg>,
}
#[derive(Serialize)]
struct DocumentElementReply {
from: String,
node: NodeActorMsg,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ChildrenReply {
has_first: bool,
has_last: bool,
nodes: Vec<NodeActorMsg>,
from: String,
}
#[derive(Serialize)]
struct GetLayoutInspectorReply {
actor: LayoutInspectorActorMsg,
from: String,
}
#[derive(Serialize)]
struct WatchRootNodeReply {
#[serde(rename = "type")]
type_: String,
from: String,
node: NodeActorMsg,
}
#[derive(Serialize)]
struct GetOffsetParentReply {
from: String,
node: Option<()>,
}
impl Actor for WalkerActor {
fn name(&self) -> String {
self.name.clone()
}
/// The walker actor can handle the following messages:
///
/// - `children`: Returns a list of children nodes of the specified node
///
/// - `clearPseudoClassLocks`: Placeholder
///
/// - `documentElement`: Returns the base document element node
///
/// - `getLayoutInspector`: Returns the Layout inspector actor, placeholder
///
/// - `getOffsetParent`: Placeholder
///
/// - `querySelector`: Recursively looks for the specified selector in the tree, reutrning the
/// node and its ascendents
fn handle_message(
&self,
registry: &ActorRegistry,
msg_type: &str,
msg: &Map<String, Value>,
stream: &mut TcpStream,
_id: StreamId,
) -> Result<ActorMessageStatus, ()> {
Ok(match msg_type {
"children" => {
let target = msg.get("node").ok_or(())?.as_str().ok_or(())?;
let (tx, rx) = ipc::channel().map_err(|_| ())?;
self.script_chan
.send(GetChildren(
self.pipeline,
registry.actor_to_script(target.into()),
tx,
))
.map_err(|_| ())?;
let children = rx.recv().map_err(|_| ())?.ok_or(())?;
let msg = ChildrenReply {
has_first: true,
has_last: true,
nodes: children
.into_iter()
.map(|child| {
child.encode(registry, true, self.script_chan.clone(), self.pipeline)
})
.collect(),
from: self.name(),
};
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"clearPseudoClassLocks" => {
let msg = EmptyReplyMsg { from: self.name() };
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"documentElement" => {
let (tx, rx) = ipc::channel().map_err(|_| ())?;
self.script_chan
.send(GetDocumentElement(self.pipeline, tx))
.map_err(|_| ())?;
let doc_elem_info = rx.recv().map_err(|_| ())?.ok_or(())?;
let node =
doc_elem_info.encode(registry, true, self.script_chan.clone(), self.pipeline);
let msg = DocumentElementReply {
from: self.name(),
node,
};
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"getLayoutInspector" => {
// TODO: Create actual layout inspector actor
let layout = LayoutInspectorActor::new(registry.new_name("layout"));
let actor = layout.encodable();
registry.register_later(Box::new(layout));
let msg = GetLayoutInspectorReply {
from: self.name(),
actor,
};
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"getOffsetParent" => {
let msg = GetOffsetParentReply {
from: self.name(),
node: None,
};
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"querySelector" => {
let selector = msg.get("selector").ok_or(())?.as_str().ok_or(())?;
let node = msg.get("node").ok_or(())?.as_str().ok_or(())?;
let mut hierarchy = find_child(
&self.script_chan,
self.pipeline,
registry,
selector,
node,
vec![],
)
.map_err(|_| ())?;
hierarchy.reverse();
let node = hierarchy.pop().ok_or(())?;
let msg = QuerySelectorReply {
from: self.name(),
node,
new_parents: hierarchy,
};
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
"watchRootNode" => {
let msg = WatchRootNodeReply {
type_: "root-available".into(),
from: self.name(),
node: self.root_node.clone(),
};
let _ = stream.write_json_packet(&msg);
let msg = EmptyReplyMsg { from: self.name() };
let _ = stream.write_json_packet(&msg);
ActorMessageStatus::Processed
},
_ => ActorMessageStatus::Ignored,
})
}
}
/// Recursively searches for a child with the specified selector
/// If it is found, returns a list with the child and all of its ancestors.
fn find_child(
script_chan: &IpcSender<DevtoolScriptControlMsg>,
pipeline: PipelineId,
registry: &ActorRegistry,
selector: &str,
node: &str,
mut hierarchy: Vec<NodeActorMsg>,
) -> Result<Vec<NodeActorMsg>, Vec<NodeActorMsg>> {
let (tx, rx) = ipc::channel().unwrap();
script_chan
.send(GetChildren(
pipeline,
registry.actor_to_script(node.into()),
tx,
))
.unwrap();
let children = rx.recv().unwrap().ok_or(vec![])?;
for child in children {
let msg = child.encode(registry, true, script_chan.clone(), pipeline);
if msg.display_name == selector {
hierarchy.push(msg);
return Ok(hierarchy);
};
if msg.num_children == 0 {
continue;
}
match find_child(
script_chan,
pipeline,
registry,
selector,
&msg.actor,
hierarchy,
) {
Ok(mut hierarchy) => {
hierarchy.push(msg);
return Ok(hierarchy);
},
Err(e) => {
hierarchy = e;
},
}
}
Err(hierarchy)
}