use super::cursor;
use super::tabs::{answer, Held, Loading, SessionTabs};
use super::text::{self, Destination};
use super::{keys, schema::NAVIGATION_LIMIT};
use crate::browser::drive::{PersonTabs, Refused};
use crate::browser::view::{BrowserState, BrowserView, Driver, ViewTab};
use crate::browser::{navigation, SessionBrowser};
use futures_util::future::BoxFuture;
use rho_browser::cdp::input::{
DispatchKeyEvent, DispatchMouseEvent, InsertText, KeyEventKind, Modifiers, MouseButton,
MouseEventKind,
};
use rho_browser::cdp::target::{
GetTargets, SetDiscoverTargets, TargetCreated, TargetInfo, TargetInfoChanged,
};
use rho_browser::cdp::{BrowserContextId, TargetId};
use rho_browser::tab::{Step, Tab};
use rho_protocol::{
BrowserCursor, BrowserDestination, BrowserInput, BrowserKeyAction, BrowserModifiers,
BrowserMouseAction, BrowserMouseButton, BrowserTabAction,
};
use std::time::Duration;
const TITLES_EVERY: Duration = Duration::from_millis(250);
impl PersonTabs for SessionTabs {
fn input(
&self,
tab: String,
input: BrowserInput,
) -> BoxFuture<'_, Result<Option<BrowserCursor>, Refused>> {
Box::pin(async move {
let mut held = self.person_hold(&tab).await?;
let takeovers = held.browser.takeovers();
let at = match &input {
BrowserInput::Mouse { x, y, .. } => Some((*x, *y)),
_ => None,
};
let command = command(input, held.tabs.person_button.under(takeovers));
let open = held.tabs.get(Some(&tab)).map_err(|_| Refused::NoTab(tab))?;
let sent = match command {
Command::Mouse(event) => open.call(&event).await.map(drop),
Command::Key(event) => open.call(&event).await.map(drop),
Command::Text(event) => open.call(&event).await.map(drop),
};
sent.map_err(|error| Refused::Browser(error.message().to_owned()))?;
let Some((x, y)) = at else {
return Ok(None);
};
Ok(cursor::under(open, x, y).await)
})
}
fn navigate(&self, tab: String, to: BrowserDestination) -> BoxFuture<'_, Result<(), Refused>> {
Box::pin(async move {
let destination = match to {
BrowserDestination::Url { url } => {
let destination = text::destination(&url).map_err(Refused::Invalid)?;
if let Destination::Url(url) = &destination {
navigation::allowed(url.as_str()).await.map_err(|reason| {
Refused::Invalid(format!("Navigation refused: {reason}."))
})?;
}
destination
}
BrowserDestination::Back => Destination::Back,
BrowserDestination::Forward => Destination::Forward,
BrowserDestination::Reload => Destination::Reload,
_ => return Err(Refused::Invalid("an unknown destination".to_owned())),
};
let mut held = self.person_hold(&tab).await?;
let open = held
.tabs
.get(Some(&tab))
.map_err(|_| Refused::NoTab(tab.clone()))?;
let new_url = match &destination {
Destination::Url(url) => Some(url.as_str()),
Destination::Back | Destination::Forward | Destination::Reload => None,
};
let loading = super::tabs::show_loading(held.browser, held.context.id(), open, new_url);
tokio::spawn(load(
held.browser.clone(),
held.context.id().clone(),
open.tab().clone(),
destination,
loading,
));
Ok(())
})
}
fn tab(&self, action: BrowserTabAction) -> BoxFuture<'_, Result<Option<String>, Refused>> {
Box::pin(async move {
let mut held = self.hold_now().await.map_err(browser_error)?;
let opened = match action {
BrowserTabAction::New => {
let opened = held
.tabs
.open(&held.context)
.await
.map_err(|error| Refused::Invalid(error.message().to_owned()))?;
Some(opened.id.clone())
}
BrowserTabAction::Close { tab } => {
if !held.tabs.has(&tab) {
return Err(Refused::NoTab(tab));
}
held.tabs.close(&tab).await.map_err(browser_error)?;
None
}
BrowserTabAction::Activate { tab } => {
held.tabs.switch(&tab).map_err(|_| Refused::NoTab(tab))?;
None
}
_ => return Err(Refused::Invalid("an unknown tab action".to_owned())),
};
held.show_tabs().await;
Ok(opened)
})
}
fn close(&self) -> BoxFuture<'_, ()> {
Box::pin(self.release())
}
fn fit(&self) -> BoxFuture<'_, ()> {
Box::pin(self.fit_running())
}
fn follow(&self) -> BoxFuture<'_, ()> {
Box::pin(async move {
let browser = self.browser();
let mut view = browser.view();
if view.borrow_and_update().state != BrowserState::Running {
return;
}
let (connection, context) = match self.hold_now().await {
Ok(held) => (held.context.connection().clone(), held.context.id().clone()),
Err(_) => return,
};
let mut events = connection.events();
if connection
.call(&SetDiscoverTargets { discover: true })
.await
.is_err()
{
return;
}
let mut titles = tokio::time::interval(TITLES_EVERY);
titles.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
event = events.recv() => {
let Ok(event) = event else { return };
if let Some(Ok(changed)) = event.parse::<TargetInfoChanged>() {
let info = changed.target_info;
browser.show_in(&context, |view| {
if let Some(tab) = shown(view, &info.target_id) {
tab.title = info.title;
tab.url = info.url;
}
});
} else if let Some(Ok(created)) = event.parse::<TargetCreated>() {
let info = created.target_info;
if info.kind == "page" && info.browser_context_id.as_ref() == Some(&context) {
self.take_in_pages().await;
}
}
}
_ = titles.tick() => {
if let Ok(targets) = answer(connection.call(&GetTargets {})).await {
show_titles(browser, &context, targets.target_infos);
}
}
() = agent_drives(&mut view) => return,
}
}
})
}
}
impl SessionTabs {
async fn person_hold(&self, tab: &str) -> Result<Held<'_>, Refused> {
if !self.browser().shows_tab(tab) {
return Err(Refused::NoTab(tab.to_owned()));
}
self.hold_now().await.map_err(browser_error)
}
async fn take_in_pages(&self) {
if let Ok(mut held) = self.hold_now().await {
held.tabs.take_in(&held.context).await;
held.show_tabs().await;
}
}
}
fn show_titles(browser: &SessionBrowser, context: &BrowserContextId, targets: Vec<TargetInfo>) {
browser.show_in(context, |view| {
for info in targets {
if let Some(tab) = shown(view, &info.target_id) {
tab.title = info.title;
}
}
});
}
fn shown<'a>(view: &'a mut BrowserView, target: &TargetId) -> Option<&'a mut ViewTab> {
view.tabs.iter_mut().find(|tab| tab.target == *target)
}
async fn agent_drives(view: &mut tokio::sync::watch::Receiver<crate::browser::view::BrowserView>) {
let _ = view.wait_for(|view| view.driver == Driver::Agent).await;
}
fn browser_error(error: rho_sdk::tool::ToolError) -> Refused {
Refused::Browser(error.message().to_owned())
}
async fn load(
browser: SessionBrowser,
context: BrowserContextId,
tab: Tab,
destination: Destination,
loading: Loading,
) {
let loaded = match &destination {
Destination::Url(url) => tab.load(url.as_str(), NAVIGATION_LIMIT).await,
Destination::Back => tab.go(Step::Back, NAVIGATION_LIMIT).await,
Destination::Forward => tab.go(Step::Forward, NAVIGATION_LIMIT).await,
Destination::Reload => tab.go(Step::Reload, NAVIGATION_LIMIT).await,
};
if let Err(error) = loaded {
tracing::debug!(%error, "a person's navigation did not finish");
}
let info = tab.info().await.ok();
let target = tab.page().target_id().clone();
browser.show_in(&context, |view| {
if let Some(tab) = shown(view, &target) {
if let Some(info) = info {
tab.title = info.title;
tab.url = info.url;
}
}
});
drop(loading);
}
#[derive(Debug, Clone)]
enum Command {
Mouse(DispatchMouseEvent),
Key(DispatchKeyEvent),
Text(InsertText),
}
#[derive(Debug, Default)]
pub(super) struct HeldButton {
takeover: u64,
button: Option<MouseButton>,
}
impl HeldButton {
pub(super) fn under(&mut self, takeover: u64) -> &mut Option<MouseButton> {
if self.takeover != takeover {
*self = Self {
takeover,
button: None,
};
}
&mut self.button
}
}
fn command(input: BrowserInput, held: &mut Option<MouseButton>) -> Command {
match input {
BrowserInput::Mouse {
action,
x,
y,
button,
clicks,
modifiers,
} => {
let button = button.map(mouse_button);
let (kind, button, click_count) = match action {
BrowserMouseAction::Moved => (MouseEventKind::Moved, *held, None),
BrowserMouseAction::Pressed => {
*held = button;
(MouseEventKind::Pressed, button, Some(clicks.max(1)))
}
BrowserMouseAction::Released => {
*held = None;
(MouseEventKind::Released, button, Some(clicks.max(1)))
}
_ => (MouseEventKind::Moved, *held, None),
};
Command::Mouse(DispatchMouseEvent {
kind,
x,
y,
button,
click_count,
modifiers: modifiers_of(modifiers),
delta_x: None,
delta_y: None,
})
}
BrowserInput::Wheel {
x,
y,
dx,
dy,
modifiers,
} => Command::Mouse(DispatchMouseEvent {
kind: MouseEventKind::Wheel,
x,
y,
button: None,
click_count: None,
modifiers: modifiers_of(modifiers),
delta_x: Some(dx),
delta_y: Some(dy),
}),
BrowserInput::Key {
action,
key,
code,
text,
modifiers,
} => {
let modifiers = modifiers_of(modifiers);
let text = text.filter(|text| {
!text.is_empty() && modifiers.without(Modifiers::SHIFT) == Modifiers::NONE
});
let (kind, text) = match (action, text) {
(BrowserKeyAction::Down, Some(text)) => (KeyEventKind::KeyDown, Some(text)),
(BrowserKeyAction::Up, _) => (KeyEventKind::KeyUp, None),
(_, _) => (KeyEventKind::RawKeyDown, None),
};
Command::Key(DispatchKeyEvent {
kind,
windows_virtual_key_code: keys::key_code(&key),
key,
code,
text,
modifiers,
})
}
BrowserInput::Text { text } => Command::Text(InsertText { text }),
_ => Command::Text(InsertText {
text: String::new(),
}),
}
}
fn mouse_button(button: BrowserMouseButton) -> MouseButton {
match button {
BrowserMouseButton::Left => MouseButton::Left,
BrowserMouseButton::Middle => MouseButton::Middle,
BrowserMouseButton::Right => MouseButton::Right,
_ => MouseButton::Left,
}
}
fn modifiers_of(held: BrowserModifiers) -> Modifiers {
[
(held.alt, Modifiers::ALT),
(held.ctrl, Modifiers::CTRL),
(held.meta, Modifiers::META),
(held.shift, Modifiers::SHIFT),
]
.into_iter()
.filter(|(on, _)| *on)
.fold(Modifiers::NONE, |all, (_, modifier)| all.with(modifier))
}
#[cfg(test)]
#[path = "person_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "person_live_tests.rs"]
mod live_tests;