use super::actions::{Act, Pointer, Target};
use super::keys;
use super::opt_in;
use super::schema::{Action, DEFAULT_NOTCHES, KEY_REPEAT, SCROLL_NOTCHES, WAIT_SECONDS};
use super::snapshot::Filter;
use super::text::{self, Destination};
use crate::browser::VIEWPORT;
use rho_browser::cdp::input::Modifiers;
use rho_sdk::tool::{ToolError, ToolErrorKind};
use serde::Deserialize;
use serde_json::Value;
use std::path::{Path, PathBuf};
pub(super) enum Request {
Wait { seconds: f64 },
Tabs(TabsRequest),
}
pub(super) enum TabsRequest {
Navigate {
destination: Destination,
tab_id: Option<String>,
},
ReadPage {
filter: Filter,
depth: usize,
element: Option<String>,
tab_id: Option<String>,
},
Find {
query: String,
tab_id: Option<String>,
},
GetPageText {
tab_id: Option<String>,
},
Screenshot {
tab_id: Option<String>,
},
Zoom {
region: Region,
tab_id: Option<String>,
},
Scroll {
x: u32,
y: u32,
direction: Direction,
notches: u8,
tab_id: Option<String>,
},
ScrollTo {
element: String,
tab_id: Option<String>,
},
Act {
act: Act,
tab_id: Option<String>,
},
NewTab,
ListTabs,
SwitchTab {
tab_id: String,
},
CloseTab {
tab_id: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum CardTab {
Named(String),
ActedOn,
Current,
Nothing,
}
impl CardTab {
pub(super) fn linked(
self,
before: Option<&str>,
after: Option<&str>,
has: impl Fn(&str) -> bool,
) -> Option<String> {
match self {
Self::Named(id) => Some(id),
Self::ActedOn => before.or(after).map(str::to_owned),
Self::Current => after.map(str::to_owned),
Self::Nothing => None,
}
.filter(|id| has(id))
}
}
impl TabsRequest {
pub(super) fn card_tab(&self) -> CardTab {
match self {
Self::Navigate { tab_id, .. }
| Self::ReadPage { tab_id, .. }
| Self::Find { tab_id, .. }
| Self::GetPageText { tab_id }
| Self::Screenshot { tab_id }
| Self::Zoom { tab_id, .. }
| Self::Scroll { tab_id, .. }
| Self::ScrollTo { tab_id, .. }
| Self::Act { tab_id, .. } => tab_id.clone().map_or(CardTab::ActedOn, CardTab::Named),
Self::NewTab | Self::SwitchTab { .. } => CardTab::Current,
Self::ListTabs | Self::CloseTab { .. } => CardTab::Nothing,
}
}
}
#[derive(Debug, Clone, Copy)]
pub(super) struct Region {
pub(super) x0: u32,
pub(super) y0: u32,
pub(super) x1: u32,
pub(super) y1: u32,
}
#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(super) enum Direction {
Up,
Down,
Left,
Right,
}
impl Direction {
pub(super) fn name(self) -> &'static str {
match self {
Self::Up => "up",
Self::Down => "down",
Self::Left => "left",
Self::Right => "right",
}
}
}
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum ReadFilter {
Interactive,
All,
}
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
enum CoordinateTarget {
Coordinate { x: i64, y: i64 },
}
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
enum AnyTarget {
Coordinate {
x: i64,
y: i64,
},
Ref {
#[serde(rename = "ref")]
element: String,
},
}
impl AnyTarget {
fn parse(self) -> Result<Target, ToolError> {
match self {
Self::Coordinate { x, y } => {
let (x, y) = point(x, y)?;
Ok(Target::Point { x, y })
}
Self::Ref { element } => Ok(Target::Ref(element)),
}
}
}
fn pointing(pointer: Pointer, arguments: Value) -> Result<TabsRequest, ToolError> {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Input {
target: AnyTarget,
modifiers: Option<String>,
tab_id: Option<String>,
}
let input: Input = parse(arguments)?;
let modifiers = match input.modifiers.as_deref() {
None | Some("") => Modifiers::NONE,
Some(text) => keys::modifiers(text).map_err(invalid)?,
};
let act = Act::Point {
pointer,
target: input.target.parse()?,
modifiers,
};
Ok(TabsRequest::Act {
act,
tab_id: input.tab_id,
})
}
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
enum RefTarget {
Ref {
#[serde(rename = "ref")]
element: String,
},
}
impl Request {
pub(super) fn parse(
action: Action,
arguments: Value,
upload_dir: Option<&Path>,
) -> Result<Self, ToolError> {
let tabs = match action {
Action::Wait => {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Input {
duration: f64,
#[allow(dead_code)]
tab_id: Option<String>,
}
let input: Input = parse(arguments)?;
if !(0.0..=WAIT_SECONDS).contains(&input.duration) {
return Err(invalid(format!(
"duration must be 0 to {WAIT_SECONDS} seconds; got {}",
input.duration
)));
}
return Ok(Self::Wait {
seconds: input.duration,
});
}
Action::Navigate => {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Input {
url: String,
tab_id: Option<String>,
}
let input: Input = parse(arguments)?;
TabsRequest::Navigate {
destination: text::destination(&input.url).map_err(invalid)?,
tab_id: input.tab_id,
}
}
Action::ReadPage => {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Input {
filter: Option<ReadFilter>,
depth: Option<usize>,
#[serde(rename = "ref")]
element: Option<String>,
tab_id: Option<String>,
}
let input: Input = parse(arguments)?;
TabsRequest::ReadPage {
filter: match input.filter {
None => Filter::Visible,
Some(ReadFilter::Interactive) => Filter::Interactive,
Some(ReadFilter::All) => Filter::All,
},
depth: input.depth.unwrap_or(super::schema::DEFAULT_DEPTH).max(1),
element: input.element,
tab_id: input.tab_id,
}
}
Action::Find => {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Input {
query: String,
tab_id: Option<String>,
}
let input: Input = parse(arguments)?;
TabsRequest::Find {
query: input.query,
tab_id: input.tab_id,
}
}
Action::GetPageText => TabsRequest::GetPageText {
tab_id: parse::<TabOnly>(arguments)?.tab_id,
},
Action::Screenshot => TabsRequest::Screenshot {
tab_id: parse::<TabOnly>(arguments)?.tab_id,
},
Action::Zoom => {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Input {
region: [i64; 4],
tab_id: Option<String>,
}
let input: Input = parse(arguments)?;
TabsRequest::Zoom {
region: region(input.region)?,
tab_id: input.tab_id,
}
}
Action::Scroll => {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Input {
target: CoordinateTarget,
scroll_direction: Direction,
scroll_amount: Option<u8>,
tab_id: Option<String>,
}
let input: Input = parse(arguments)?;
let CoordinateTarget::Coordinate { x, y } = input.target;
let notches = input.scroll_amount.unwrap_or(DEFAULT_NOTCHES);
if !SCROLL_NOTCHES.contains(¬ches) {
return Err(invalid(format!(
"scroll_amount must be {} to {}; got {notches}",
SCROLL_NOTCHES.start(),
SCROLL_NOTCHES.end()
)));
}
let (x, y) = point(x, y)?;
TabsRequest::Scroll {
x,
y,
direction: input.scroll_direction,
notches,
tab_id: input.tab_id,
}
}
Action::ScrollTo => {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Input {
target: RefTarget,
tab_id: Option<String>,
}
let input: Input = parse(arguments)?;
let RefTarget::Ref { element } = input.target;
TabsRequest::ScrollTo {
element,
tab_id: input.tab_id,
}
}
Action::LeftClick => pointing(Pointer::Left, arguments)?,
Action::RightClick => pointing(Pointer::Right, arguments)?,
Action::MiddleClick => pointing(Pointer::Middle, arguments)?,
Action::DoubleClick => pointing(Pointer::Double, arguments)?,
Action::TripleClick => pointing(Pointer::Triple, arguments)?,
Action::Hover => {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Input {
target: AnyTarget,
tab_id: Option<String>,
}
let input: Input = parse(arguments)?;
let act = Act::Point {
pointer: Pointer::Hover,
target: input.target.parse()?,
modifiers: Modifiers::NONE,
};
TabsRequest::Act {
act,
tab_id: input.tab_id,
}
}
Action::Type => {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Input {
text: String,
tab_id: Option<String>,
}
let input: Input = parse(arguments)?;
TabsRequest::Act {
act: Act::Type(input.text),
tab_id: input.tab_id,
}
}
Action::Key => {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Input {
text: String,
repeat: Option<u8>,
tab_id: Option<String>,
}
let input: Input = parse(arguments)?;
let repeat = input.repeat.unwrap_or(1);
if !KEY_REPEAT.contains(&repeat) {
return Err(invalid(format!(
"repeat must be {} to {}; got {repeat}",
KEY_REPEAT.start(),
KEY_REPEAT.end()
)));
}
let act = Act::Key {
chords: keys::sequence(&input.text).map_err(invalid)?,
text: input.text,
repeat,
};
TabsRequest::Act {
act,
tab_id: input.tab_id,
}
}
Action::FormInput => {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Input {
target: RefTarget,
value: Value,
tab_id: Option<String>,
}
let input: Input = parse(arguments)?;
if !matches!(
input.value,
Value::String(_) | Value::Number(_) | Value::Bool(_)
) {
return Err(invalid(format!(
"value must be a string, number or boolean; got {}",
input.value
)));
}
let RefTarget::Ref { element } = input.target;
TabsRequest::Act {
act: Act::FormInput {
element,
value: input.value,
},
tab_id: input.tab_id,
}
}
Action::JavascriptExec => {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Input {
text: String,
tab_id: Option<String>,
}
let input: Input = parse(arguments)?;
TabsRequest::Act {
act: Act::Script(input.text),
tab_id: input.tab_id,
}
}
Action::FileUpload => {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Input {
target: RefTarget,
paths: Vec<PathBuf>,
tab_id: Option<String>,
}
let input: Input = parse(arguments)?;
let dir = upload_dir.ok_or_else(|| {
invalid("file_upload is not enabled: set browser.upload_dir in config")
})?;
let files = opt_in::uploads(dir, &input.paths).map_err(invalid)?;
let RefTarget::Ref { element } = input.target;
TabsRequest::Act {
act: Act::Upload { element, files },
tab_id: input.tab_id,
}
}
Action::NewTab => {
parse::<NoInput>(arguments)?;
TabsRequest::NewTab
}
Action::ListTabs => {
parse::<NoInput>(arguments)?;
TabsRequest::ListTabs
}
Action::SwitchTab => TabsRequest::SwitchTab {
tab_id: parse::<TabInput>(arguments)?.tab_id,
},
Action::CloseTab => TabsRequest::CloseTab {
tab_id: parse::<TabInput>(arguments)?.tab_id,
},
};
Ok(Self::Tabs(tabs))
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct NoInput {}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TabOnly {
tab_id: Option<String>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TabInput {
tab_id: String,
}
fn parse<T: serde::de::DeserializeOwned>(arguments: Value) -> Result<T, ToolError> {
serde_json::from_value(arguments).map_err(|error| invalid(error.to_string()))
}
fn invalid(message: impl Into<String>) -> ToolError {
ToolError::new(ToolErrorKind::InvalidArguments, message)
}
fn region([x0, y0, x1, y1]: [i64; 4]) -> Result<Region, ToolError> {
let (width, height) = (i64::from(VIEWPORT.width), i64::from(VIEWPORT.height));
if !(0 <= x0 && x0 < x1 && x1 <= width && 0 <= y0 && y0 < y1 && y1 <= height) {
return Err(invalid(format!(
"region must be [x0, y0, x1, y1] with 0 <= x0 < x1 <= {width} and 0 <= y0 < y1 <= {height}; got [{x0}, {y0}, {x1}, {y1}]"
)));
}
let pixels = |value: i64| u32::try_from(value).expect("checked against the viewport");
Ok(Region {
x0: pixels(x0),
y0: pixels(y0),
x1: pixels(x1),
y1: pixels(y1),
})
}
fn point(x: i64, y: i64) -> Result<(u32, u32), ToolError> {
let (width, height) = (i64::from(VIEWPORT.width), i64::from(VIEWPORT.height));
if (0..width).contains(&x) && (0..height).contains(&y) {
let pixels = |value: i64| u32::try_from(value).expect("checked against the viewport");
Ok((pixels(x), pixels(y)))
} else {
Err(invalid(format!(
"({x}, {y}) is outside the {width}x{height} viewport"
)))
}
}
#[cfg(test)]
#[path = "inputs_tests.rs"]
mod tests;