use super::keys::{self, Chord, Typed};
use super::opt_in::{self, Uploads};
use super::schema::{FIND_LIMIT, NAVIGATION_LIMIT};
use super::tabs::{execution, Node, OpenTab};
use super::text;
use crate::browser::view::Placed;
use crate::browser::VIEWPORT;
use rho_browser::cdp::dom::GetContentQuads;
use rho_browser::cdp::input::{
DispatchMouseEvent, InsertText, Modifiers, MouseButton, MouseEventKind,
};
use rho_browser::tab::{Effect, LoadError, Viewport, Watch};
use rho_protocol::{BrowserRect, BrowserViewport};
use rho_sdk::tool::ToolError;
use serde::Deserialize;
use serde_json::{json, Value};
#[derive(Debug, Clone, PartialEq)]
pub(super) enum Act {
Point {
pointer: Pointer,
target: Target,
modifiers: Modifiers,
},
Type(String),
Key {
text: String,
chords: Vec<Chord>,
repeat: u8,
},
FormInput { element: String, value: Value },
Script(String),
Upload { element: String, files: Uploads },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Target {
Ref(String),
Point { x: u32, y: u32 },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Pointer {
Left,
Right,
Middle,
Double,
Triple,
Hover,
}
impl Pointer {
fn clicks(self) -> Option<(MouseButton, u32)> {
match self {
Self::Left => Some((MouseButton::Left, 1)),
Self::Right => Some((MouseButton::Right, 1)),
Self::Middle => Some((MouseButton::Middle, 1)),
Self::Double => Some((MouseButton::Left, 2)),
Self::Triple => Some((MouseButton::Left, 3)),
Self::Hover => None,
}
}
fn done(self, what: &str) -> String {
match self {
Self::Left => format!("Clicked {what}."),
Self::Right => format!("Right-clicked {what}."),
Self::Middle => format!("Middle-clicked {what}."),
Self::Double => format!("Double-clicked {what}."),
Self::Triple => format!("Triple-clicked {what}."),
Self::Hover => format!("Hovered over {what}."),
}
}
}
#[derive(Debug)]
pub(super) struct Done {
pub(super) text: String,
pub(super) placed: Option<Placed>,
}
impl From<String> for Done {
fn from(text: String) -> Self {
Self { text, placed: None }
}
}
pub(super) async fn run(open: &mut OpenTab, act: &Act) -> Result<Done, ToolError> {
match act {
Act::Point {
pointer,
target,
modifiers,
} => point(open, *pointer, target, *modifiers).await,
Act::Type(text) => type_text(open, text).await.map(Done::from),
Act::Key {
text,
chords,
repeat,
} => press_keys(open, text, chords, *repeat)
.await
.map(Done::from),
Act::FormInput { element, value } => form_input(open, element, value).await.map(Done::from),
Act::Script(script) => {
let watch = open.watch();
let value = opt_in::run_script(open, script).await?;
settle(open, watch, value).await.map(Done::from)
}
Act::Upload { element, files } => {
let node = open.node(element).await?;
let watch = open.watch();
let done = opt_in::upload(open, &node, files).await?;
settle(open, watch, done).await.map(Done::from)
}
}
}
const UNCOVERED: &str = r##"function (x, y) {
const self = this.nodeType === Node.ELEMENT_NODE ? this : this.parentElement;
const root = this.getRootNode();
const hit = (typeof root.elementFromPoint === "function" ? root : document).elementFromPoint(x, y);
if (hit === null) return { tag: null, id: "", classes: "" };
if (self === null || self === hit || self.contains(hit)) return null;
if (hit.closest("label")?.control === self) return null;
const classes = typeof hit.className === "string" ? hit.className.trim() : "";
return { tag: hit.localName, id: hit.id, classes };
}"##;
#[derive(Deserialize)]
struct Cover {
tag: Option<String>,
id: String,
classes: String,
}
impl Cover {
fn describe(&self) -> String {
let Some(tag) = &self.tag else {
return "no element".to_owned();
};
let mut text = format!("<{tag}");
for (name, value) in [("id", &self.id), ("class", &self.classes)] {
if !value.is_empty() {
text.push_str(&format!(" {name}={}", text::quoted(value)));
}
}
text.push('>');
text
}
}
const SET_VALUE: &str = r##"function (value, limit) {
const el = this;
if (el.nodeType !== Node.ELEMENT_NODE) return { refused: "not_field", tag: "#text" };
const tag = el.localName;
const fire = () => {
el.dispatchEvent(new Event("input", { bubbles: true }));
el.dispatchEvent(new Event("change", { bubbles: true }));
};
if (el.matches(":disabled")) return { refused: "disabled" };
if (tag === "select") {
const wanted = String(value);
const options = [...el.options];
const option = options.find(o => o.value === wanted)
?? options.find(o => o.textContent.trim() === wanted.trim());
if (option === undefined) {
return { refused: "no_option", options: options.slice(0, limit).map(o => o.textContent.trim()) };
}
if (option.disabled) return { refused: "option_disabled" };
if (el.multiple) option.selected = true;
else for (const other of options) other.selected = other === option;
fire();
return { set: option.textContent.trim() };
}
if (tag === "input" && (el.type === "checkbox" || el.type === "radio")) {
if (typeof value !== "boolean") return { refused: "needs_boolean", type: el.type };
if (el.type === "radio" && el.checked && !value) return { refused: "radio_off" };
if (el.checked !== value) el.click();
if (el.checked !== value) return { refused: "unchanged" };
return { set: value };
}
if (tag === "input" && ["file", "button", "submit", "reset", "image"].includes(el.type)) {
return { refused: "not_field", tag: "input type=" + el.type };
}
if (tag === "input" || tag === "textarea") {
if (el.readOnly) return { refused: "readonly" };
const text = String(value);
const before = el.value;
el.focus();
el.value = text;
if (el.value !== text) {
const shows = el.value;
el.value = before;
return { refused: "rejected", type: el.type, shows };
}
fire();
return { set: el.value };
}
return { refused: el.isContentEditable ? "editable" : "not_field", tag };
}"##;
#[derive(Deserialize)]
#[serde(untagged)]
enum SetValue {
Set { set: Value },
Refused(Refusal),
}
#[derive(Deserialize)]
#[serde(tag = "refused", rename_all = "snake_case")]
enum Refusal {
Disabled,
Readonly,
RadioOff,
Unchanged,
NoOption {
options: Vec<String>,
},
OptionDisabled,
NeedsBoolean {
#[serde(rename = "type")]
kind: String,
},
Rejected {
#[serde(rename = "type")]
kind: String,
shows: String,
},
Editable {
tag: String,
},
NotField {
tag: String,
},
}
impl Refusal {
fn message(&self, element: &str) -> String {
match self {
Self::Disabled => format!("{element} is disabled, so it cannot be set."),
Self::Readonly => format!("{element} is read-only, so it cannot be set."),
Self::NoOption { options } => format!(
"{element} has no option with that value or text. Its options: {}.",
options
.iter()
.map(|option| text::quoted(option))
.collect::<Vec<_>>()
.join(", ")
),
Self::OptionDisabled => {
format!("{element}'s option with that value or text is disabled.")
}
Self::NeedsBoolean { kind } => {
format!("{element} is a {kind}; set it with true or false.")
}
Self::RadioOff => format!(
"{element} is a radio button, which is turned off by setting another in its group."
),
Self::Unchanged => format!("{element} did not change: the page kept it as it was."),
Self::Rejected { kind, shows } => format!(
"{element} is a {kind} field and did not take that value: it showed {} with it, so it was left as it was.",
text::quoted(shows)
),
Self::Editable { tag } => format!(
"{element} is an editable <{tag}>, not a form field: click it and type instead."
),
Self::NotField { tag } => format!(
"{element} is a <{tag}>, not a form field form_input can set: use a text field, text area, checkbox, radio button or select."
),
}
}
}
async fn point(
open: &mut OpenTab,
pointer: Pointer,
target: &Target,
modifiers: Modifiers,
) -> Result<Done, ToolError> {
let ((x, y), placed) = match target {
Target::Point { x, y } => ((f64::from(*x), f64::from(*y)), None),
Target::Ref(element) => {
let drawn = element_box(open, element).await?;
let placed = Placed {
element: element.clone(),
rect: drawn.rect(),
viewport: BrowserViewport::new(VIEWPORT.width, VIEWPORT.height),
};
(drawn.center(), Some(placed))
}
};
let watch = open.watch();
let mouse = |kind, button, click_count| DispatchMouseEvent {
kind,
x,
y,
button,
click_count,
modifiers,
delta_x: None,
delta_y: None,
};
open.call(&mouse(
MouseEventKind::Moved,
None,
None,
))
.await?;
if let Some((button, count)) = pointer.clicks() {
for click in 1..=count {
for kind in [MouseEventKind::Pressed, MouseEventKind::Released] {
open.call(&mouse(kind, Some(button), Some(click))).await?;
}
}
}
let what = match target {
Target::Ref(element) => format!("element {element}"),
Target::Point { x, y } => format!("({x}, {y})"),
};
let text = settle(open, watch, pointer.done(&what)).await?;
Ok(Done { text, placed })
}
async fn type_text(open: &mut OpenTab, text: &str) -> Result<String, ToolError> {
let watch = open.watch();
for step in keys::typing(text) {
match step {
Typed::Key(key) => {
let chord = Chord {
modifiers: Modifiers::NONE,
key,
};
press(open, &chord).await?;
}
Typed::Text(text) => {
open.call(&InsertText { text }).await?;
}
}
}
let count = text.chars().count();
settle(open, watch, format!("Typed {count} characters.")).await
}
async fn press_keys(
open: &mut OpenTab,
text: &str,
chords: &[Chord],
repeat: u8,
) -> Result<String, ToolError> {
let watch = open.watch();
for _ in 0..repeat {
for chord in chords {
press(open, chord).await?;
}
}
let times = match repeat {
1 => String::new(),
repeat => format!(" {repeat} times"),
};
settle(open, watch, format!("Pressed {text}{times}.")).await
}
async fn form_input(open: &mut OpenTab, element: &str, value: &Value) -> Result<String, ToolError> {
let node = open.node(element).await?;
let watch = open.watch();
let answer = open
.call_on(&node, SET_VALUE, vec![value.clone(), json!(FIND_LIMIT)])
.await?;
let answer: SetValue = serde_json::from_value(answer)
.map_err(|error| execution(format!("the browser answered oddly: {error}")))?;
let shown = match answer {
SetValue::Set { set } => set,
SetValue::Refused(refusal) => return Err(execution(refusal.message(element))),
};
let shown = match shown {
Value::String(shown) => text::quoted(&shown),
other => other.to_string(),
};
settle(open, watch, format!("Set {element} to {shown}.")).await
}
async fn element_box(open: &mut OpenTab, element: &str) -> Result<Visible, ToolError> {
let node = open.node(element).await?;
open.scroll_into_view(&node).await?;
let drawn = drawn_box(open, &node).await?;
let (x, y) = drawn.center();
let cover = open
.call_on(&node, UNCOVERED, vec![json!(x), json!(y)])
.await?;
let cover: Option<Cover> = serde_json::from_value(cover)
.map_err(|error| execution(format!("the browser answered oddly: {error}")))?;
match cover {
None => Ok(drawn),
Some(cover) => Err(execution(format!(
"{element} is covered by {} at ({x:.0}, {y:.0}), which would get the click instead. Close or move what covers it, or click by coordinate.",
cover.describe()
))),
}
}
async fn drawn_box(open: &OpenTab, node: &Node<'_>) -> Result<Visible, ToolError> {
let quads = open
.on_node(&GetContentQuads {
backend_node_id: node.id,
})
.await?
.map(|quads| quads.quads)
.unwrap_or_default();
visible_box(&quads, VIEWPORT).ok_or_else(|| {
execution(format!(
"{} is not visible in the viewport, so it cannot be clicked: it may be hidden or have no size. Use read_page or screenshot to find what to click.",
node.name
))
})
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Visible {
left: f64,
top: f64,
right: f64,
bottom: f64,
}
impl Visible {
fn center(self) -> (f64, f64) {
(
(self.left + self.right) / 2.0,
(self.top + self.bottom) / 2.0,
)
}
fn rect(self) -> BrowserRect {
let (left, top) = (self.left.floor(), self.top.floor());
BrowserRect::new(
left as u32,
top as u32,
(self.right.ceil() - left) as u32,
(self.bottom.ceil() - top) as u32,
)
}
}
fn visible_box(quads: &[[f64; 8]], viewport: Viewport) -> Option<Visible> {
let (width, height) = (f64::from(viewport.width), f64::from(viewport.height));
quads.iter().find_map(|quad| {
let xs = [quad[0], quad[2], quad[4], quad[6]];
let ys = [quad[1], quad[3], quad[5], quad[7]];
let left = xs.iter().copied().fold(f64::INFINITY, f64::min).max(0.0);
let right = xs
.iter()
.copied()
.fold(f64::NEG_INFINITY, f64::max)
.min(width);
let top = ys.iter().copied().fold(f64::INFINITY, f64::min).max(0.0);
let bottom = ys
.iter()
.copied()
.fold(f64::NEG_INFINITY, f64::max)
.min(height);
(right - left >= 1.0 && bottom - top >= 1.0).then_some(Visible {
left,
top,
right,
bottom,
})
})
}
async fn press(open: &OpenTab, chord: &Chord) -> Result<(), ToolError> {
let held: Vec<_> = keys::held(chord.modifiers).collect();
let mut modifiers = Modifiers::NONE;
for (modifier, key) in &held {
modifiers = modifiers.with(*modifier);
open.call(&key.down(modifiers)).await?;
}
open.call(&chord.key.down(modifiers)).await?;
open.call(&chord.key.up(modifiers)).await?;
for (modifier, key) in held.iter().rev() {
modifiers = modifiers.without(*modifier);
open.call(&key.up(modifiers)).await?;
}
Ok(())
}
async fn settle(open: &mut OpenTab, watch: Watch, done: String) -> Result<String, ToolError> {
let drawn = async {
let _ = open.drawn().await;
};
match watch.settle(drawn, NAVIGATION_LIMIT).await {
Ok(Effect::Stayed | Effect::Navigated) => Ok(done),
Err(LoadError::TimedOut(limit)) => Ok(format!(
"{done} The page it led to was still loading after {} s, so its loading was stopped. Use screenshot or read_page to see what loaded.",
limit.as_secs()
)),
Err(LoadError::Closed) => Err(execution(format!(
"{done} Then the tab closed, or the browser exited."
))),
Err(error @ (LoadError::Cdp(_) | LoadError::Failed(_) | LoadError::NoHistory(_))) => Err(
execution(format!("{done} Then the browser could not tell what it did: {error}")),
),
}
}
#[cfg(test)]
#[path = "actions_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "actions_live_tests.rs"]
mod live_tests;