use super::super::{lock, Browsers, SessionBrowser};
use crate::browser::config::BrowserConfig;
use crate::browser::drive::{PersonTabs, Refused};
use crate::browser::view::{Driver, ViewTab};
use crate::browser::watch::Pointer;
use futures_util::future::BoxFuture;
use pretty_assertions::assert_eq;
use rho_browser::cdp::TargetId;
use rho_protocol::{
BrowserCursor, BrowserDestination, BrowserInput, BrowserKeyAction, BrowserModifiers,
BrowserMouseAction, BrowserMouseButton, BrowserTabAction, ConnectionId,
};
use rho_sdk::SessionId;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::{Notify, Semaphore};
struct Gated {
got: Mutex<Vec<String>>,
dispatching: Notify,
gate: Semaphore,
}
impl Gated {
fn closed() -> Self {
Self {
got: Mutex::default(),
dispatching: Notify::new(),
gate: Semaphore::new(0),
}
}
}
async fn soon<F: std::future::Future>(future: F) -> Result<F::Output, tokio::time::error::Elapsed> {
tokio::time::timeout(Duration::from_secs(10), future).await
}
impl PersonTabs for Gated {
fn input(
&self,
_: String,
input: BrowserInput,
) -> BoxFuture<'_, Result<Option<BrowserCursor>, Refused>> {
Box::pin(async move {
self.got.lock().unwrap().push(name(&input));
self.dispatching.notify_one();
self.gate.acquire().await.unwrap().forget();
Ok(Some(BrowserCursor::Pointer))
})
}
fn navigate(&self, tab: String, _: BrowserDestination) -> BoxFuture<'_, Result<(), Refused>> {
Box::pin(async move { Err(Refused::NoTab(tab)) })
}
fn tab(&self, _: BrowserTabAction) -> BoxFuture<'_, Result<Option<String>, Refused>> {
Box::pin(async { Ok(None) })
}
fn close(&self) -> BoxFuture<'_, ()> {
Box::pin(async {})
}
fn fit(&self) -> BoxFuture<'_, ()> {
Box::pin(async {})
}
fn follow(&self) -> BoxFuture<'_, ()> {
Box::pin(async {})
}
}
fn name(input: &BrowserInput) -> String {
match input {
BrowserInput::Mouse { action, x, .. } => format!("{action:?} {x}"),
BrowserInput::Key { action, key, .. } => format!("{action:?} {key}"),
_ => "other".to_owned(),
}
}
fn mouse(action: BrowserMouseAction, x: f64) -> BrowserInput {
let button = (action != BrowserMouseAction::Moved).then_some(BrowserMouseButton::Left);
BrowserInput::Mouse {
action,
x,
y: 0.0,
button,
clicks: u32::from(button.is_some()),
modifiers: BrowserModifiers::NONE,
}
}
fn driven(home: &tempfile::TempDir, tabs: &Arc<dyn PersonTabs>) -> SessionBrowser {
let config = BrowserConfig {
executable: Some(home.path().join("no-browser")),
..BrowserConfig::default()
};
let browsers = Browsers::for_tests(home.path(), config);
let session = Browsers::session(Some(&browsers), &SessionId::new()).unwrap();
session.drive_with(Arc::downgrade(tabs));
session.show(|view| {
view.tabs.push(ViewTab {
id: "tab-1".into(),
target: TargetId::from("tab-1"),
title: String::new(),
url: String::new(),
loading: false,
});
});
session.control(Driver::Person, ConnectionId::new(1));
session
}
#[tokio::test]
async fn moves_merge_and_other_input_keeps_its_place() {
let home = tempfile::tempdir().unwrap();
let gated = Arc::new(Gated::closed());
let tabs: Arc<dyn PersonTabs> = gated.clone();
let session = driven(&home, &tabs);
let elsewhere = session
.person_input("tab-9".into(), mouse(BrowserMouseAction::Moved, 1.0))
.await;
assert!(matches!(elsewhere, Err(Refused::NoTab(tab)) if tab == "tab-9"));
session
.person_input("tab-1".into(), mouse(BrowserMouseAction::Moved, 1.0))
.await
.unwrap();
soon(gated.dispatching.notified())
.await
.expect("the first move reaches the tab");
for x in [2.0, 3.0, 4.0] {
soon(session.person_input("tab-1".into(), mouse(BrowserMouseAction::Moved, x)))
.await
.expect("a move is answered without waiting for the tab")
.unwrap();
}
let pressing = session.clone();
let clicked = tokio::spawn(async move {
for input in [
mouse(BrowserMouseAction::Pressed, 4.0),
BrowserInput::Key {
action: BrowserKeyAction::Down,
key: "a".into(),
code: None,
text: Some("a".into()),
modifiers: BrowserModifiers::NONE,
},
] {
pressing.person_input("tab-1".into(), input).await.unwrap();
}
});
for _ in 0..8 {
tokio::task::yield_now().await;
}
gated.gate.add_permits(10);
soon(clicked).await.expect("the click is sent").unwrap();
assert_eq!(
*gated.got.lock().unwrap(),
["Moved 1", "Moved 4", "Pressed 4", "Down a"]
);
}
async fn drained(session: &SessionBrowser) {
soon(async {
while lock(&session.moves.waiting).draining {
tokio::task::yield_now().await;
}
})
.await
.expect("the moves are sent");
}
#[tokio::test]
async fn a_cursor_shows_once_and_only_in_the_turn_it_came_in() {
let home = tempfile::tempdir().unwrap();
let gated = Arc::new(Gated::closed());
let tabs: Arc<dyn PersonTabs> = gated.clone();
let session = driven(&home, &tabs);
let mut pointer = session.pointer.subscribe();
let connection = ConnectionId::new(1);
let move_to = |x| session.person_input("tab-1".into(), mouse(BrowserMouseAction::Moved, x));
gated.gate.add_permits(1);
move_to(1.0).await.unwrap();
drained(&session).await;
let shown = pointer.borrow_and_update().clone();
gated.gate.add_permits(1);
move_to(2.0).await.unwrap();
drained(&session).await;
let shown_again = pointer.has_changed().unwrap();
session.control(Driver::Agent, connection);
let handed_back = pointer.borrow_and_update().clone();
let mut late = Vec::new();
for retake in [false, true] {
session.control(Driver::Person, connection);
pointer.borrow_and_update();
move_to(3.0).await.unwrap();
soon(gated.dispatching.notified())
.await
.expect("the move reaches the tab");
session.control(Driver::Agent, connection);
if retake {
session.control(Driver::Person, connection);
}
gated.gate.add_permits(1);
drained(&session).await;
late.push(pointer.borrow_and_update().clone());
}
let pointed = Some(Pointer {
target: TargetId::from("tab-1"),
cursor: BrowserCursor::Pointer,
});
assert_eq!(
(shown, shown_again, handed_back, late),
(pointed, false, None, vec![None, None])
);
}