#![allow(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::cast_precision_loss
)]
use std::time::Duration;
use objc2::rc::Retained;
use objc2::{msg_send, MainThreadMarker};
use objc2_app_kit::{NSEvent, NSEventModifierFlags, NSEventType, NSWindow};
use objc2_foundation::NSPoint;
use objc2_web_kit::WKWebView;
use crate::engine::{EngineError, EngineResult};
use super::eval::{eval_js_string, run_loop_until};
#[derive(Debug, Clone, Copy)]
pub(super) struct ClientRect {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
fn click_settle(mode: vs_humanize::InputMode) -> (u64, u64) {
match mode {
vs_humanize::InputMode::Robotic => (2, 6),
_ => (15, 30),
}
}
pub(super) fn ref_rect(
web_view: &Retained<WKWebView>,
r: vs_protocol::Ref,
) -> EngineResult<Option<ClientRect>> {
let js = format!(
r#"(function() {{
var el = (window.__vsFindRef ? window.__vsFindRef({r}) : null) || document.querySelector('[data-vs-ref="{r}"]');
if (!el) return 'null';
// Scroll into the viewport's vertical center if it's
// off-screen. `instant` keeps the test deterministic
// (no smooth-scroll animation racing the rect read).
try {{
el.scrollIntoView({{behavior: 'instant', block: 'center', inline: 'center'}});
}} catch (e) {{
el.scrollIntoView();
}}
var b = window.__vsTopRect ? window.__vsTopRect(el) : el.getBoundingClientRect();
return JSON.stringify({{x: b.x, y: b.y, w: b.width, h: b.height}});
}})()"#,
r = r.0,
);
let result = eval_js_string(web_view, &js, Duration::from_secs(5))?;
let unwrapped = serde_json::from_str::<String>(&result).unwrap_or(result);
if unwrapped == "null" {
return Ok(None);
}
let v: serde_json::Value = serde_json::from_str(&unwrapped)
.map_err(|e| EngineError::Other(format!("ref_rect parse: {e}")))?;
Ok(Some(ClientRect {
x: v["x"].as_f64().unwrap_or(0.0),
y: v["y"].as_f64().unwrap_or(0.0),
width: v["w"].as_f64().unwrap_or(0.0),
height: v["h"].as_f64().unwrap_or(0.0),
}))
}
pub(super) fn click_at_rect(
web_view: &Retained<WKWebView>,
window: &Retained<NSWindow>,
rect: ClientRect,
webview_height: f64,
start: vs_humanize::Point,
mode: vs_humanize::InputMode,
seed: u64,
) -> EngineResult<vs_humanize::Point> {
let cx = rect.x + rect.width / 2.0;
let cy = rect.y + rect.height / 2.0;
let end = vs_humanize::Point { x: cx, y: cy };
let window_number = window.windowNumber();
let make_event = |ty: NSEventType, p: vs_humanize::Point| -> EngineResult<Retained<NSEvent>> {
let loc = NSPoint::new(p.x, webview_height - p.y);
NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure(
ty,
loc,
NSEventModifierFlags::empty(),
0.0,
window_number,
None,
0,
1,
1.0,
)
.ok_or_else(|| EngineError::Other(format!("NSEvent::mouseEventWithType returned nil for {ty:?}")))
};
let path = vs_humanize::mouse_path(start, end, mode, seed);
let mut prev_ms: u128 = 0;
for step in &path {
if step.kind == vs_humanize::MouseStepKind::Move {
let mv = make_event(NSEventType::MouseMoved, step.point)?;
deliver_mouse_moved(web_view, &mv);
let now_ms = step.at.as_millis();
let delta = now_ms.saturating_sub(prev_ms);
if delta > 0 {
let _ = run_loop_until(
|| false,
Duration::from_millis(u64::try_from(delta).unwrap_or(0)),
);
}
prev_ms = now_ms;
}
}
let down = make_event(NSEventType::LeftMouseDown, end)?;
let up = make_event(NSEventType::LeftMouseUp, end)?;
let (down_ms, up_ms) = click_settle(mode);
web_view.mouseDown(&down);
let _ = run_loop_until(|| false, Duration::from_millis(down_ms));
web_view.mouseUp(&up);
super::headless_webview::end_suppressed_drag(web_view, up.locationInWindow());
let _ = run_loop_until(|| false, Duration::from_millis(up_ms));
Ok(end)
}
const TRACKING_MOUSE_MOVED: usize = 0x02;
fn deliver_mouse_moved(web_view: &WKWebView, event: &NSEvent) {
use objc2::runtime::AnyObject;
use objc2::sel;
let view_ptr: *const AnyObject = std::ptr::from_ref(web_view).cast();
let owner: Option<Retained<AnyObject>> = unsafe {
let areas: Retained<AnyObject> = msg_send![web_view, trackingAreas];
let n: usize = msg_send![&areas, count];
(0..n).find_map(|i| {
let area: *mut AnyObject = msg_send![&areas, objectAtIndex: i];
let opts: usize = msg_send![area, options];
let owner: Option<Retained<AnyObject>> = msg_send![area, owner];
owner.filter(|o| {
opts & TRACKING_MOUSE_MOVED != 0
&& !std::ptr::eq(Retained::as_ptr(o), view_ptr)
&& o.class().responds_to(sel!(mouseMoved:))
})
})
};
match owner {
Some(o) => unsafe {
let _: () = msg_send![&o, mouseMoved: event];
},
None => web_view.mouseMoved(event),
}
}
#[allow(clippy::too_many_arguments)]
pub(super) fn move_along_path(
web_view: &Retained<WKWebView>,
window: &Retained<NSWindow>,
webview_height: f64,
start: vs_humanize::Point,
end: vs_humanize::Point,
mode: vs_humanize::InputMode,
seed: u64,
button_down: bool,
rec: Option<(&super::record::RecSink, MainThreadMarker)>,
) -> EngineResult<vs_humanize::Point> {
let window_number = window.windowNumber();
let make_event = |ty: NSEventType, p: vs_humanize::Point| -> EngineResult<Retained<NSEvent>> {
let loc = NSPoint::new(p.x, webview_height - p.y);
NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure(
ty,
loc,
NSEventModifierFlags::empty(),
0.0,
window_number,
None,
0,
1,
if button_down { 1.0 } else { 0.0 },
)
.ok_or_else(|| EngineError::Other(format!("NSEvent::mouseEventWithType returned nil for {ty:?}")))
};
let path = vs_humanize::mouse_path(start, end, mode, seed);
let mut prev_ms: u128 = 0;
let move_type = if button_down {
NSEventType::LeftMouseDragged
} else {
NSEventType::MouseMoved
};
for step in &path {
if step.kind == vs_humanize::MouseStepKind::Move {
let mv = make_event(move_type, step.point)?;
if button_down {
web_view.mouseDragged(&mv);
} else {
deliver_mouse_moved(web_view, &mv);
}
let now_ms = step.at.as_millis();
let delta = now_ms.saturating_sub(prev_ms);
if let Some((sink, mtm)) = rec {
sink.step(web_view, mtm, step.point.x, step.point.y, delta as f64);
}
if delta > 0 {
let _ = run_loop_until(
|| false,
Duration::from_millis(u64::try_from(delta).unwrap_or(0)),
);
}
prev_ms = now_ms;
}
}
let final_mv = make_event(move_type, end)?;
if button_down {
web_view.mouseDragged(&final_mv);
} else {
deliver_mouse_moved(web_view, &final_mv);
}
if let Some((sink, mtm)) = rec {
sink.frame(web_view, mtm, end.x, end.y, 0.0, 16);
}
Ok(end)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn click_at_xy(
web_view: &Retained<WKWebView>,
window: &Retained<NSWindow>,
webview_height: f64,
start: vs_humanize::Point,
target: vs_humanize::Point,
mode: vs_humanize::InputMode,
seed: u64,
rec: Option<(&super::record::RecSink, MainThreadMarker)>,
) -> EngineResult<vs_humanize::Point> {
let landed = move_along_path(
web_view,
window,
webview_height,
start,
target,
mode,
seed,
false,
rec,
)?;
let window_number = window.windowNumber();
let loc = NSPoint::new(target.x, webview_height - target.y);
let make = |ty: NSEventType| -> EngineResult<Retained<NSEvent>> {
NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure(
ty, loc, NSEventModifierFlags::empty(), 0.0, window_number, None, 0, 1, 1.0,
).ok_or_else(|| EngineError::Other(format!("NSEvent::mouseEventWithType returned nil for {ty:?}")))
};
let (down_ms, up_ms) = click_settle(mode);
let down = make(NSEventType::LeftMouseDown)?;
if let Some((sink, mtm)) = rec {
sink.frame(web_view, mtm, target.x, target.y, 1.0, 60);
}
web_view.mouseDown(&down);
let _ = run_loop_until(|| false, Duration::from_millis(down_ms));
if let Some((sink, mtm)) = rec {
sink.frame(web_view, mtm, target.x, target.y, 0.55, down_ms as u32);
}
let up = make(NSEventType::LeftMouseUp)?;
web_view.mouseUp(&up);
super::headless_webview::end_suppressed_drag(web_view, up.locationInWindow());
let _ = run_loop_until(|| false, Duration::from_millis(up_ms));
if let Some((sink, mtm)) = rec {
sink.frame(web_view, mtm, target.x, target.y, 0.2, up_ms as u32);
}
Ok(landed)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn drag_xy(
web_view: &Retained<WKWebView>,
window: &Retained<NSWindow>,
webview_height: f64,
start: vs_humanize::Point,
target: vs_humanize::Point,
mode: vs_humanize::InputMode,
seed: u64,
rec: Option<(&super::record::RecSink, MainThreadMarker)>,
) -> EngineResult<vs_humanize::Point> {
let window_number = window.windowNumber();
let make = |ty: NSEventType, p: vs_humanize::Point| -> EngineResult<Retained<NSEvent>> {
let loc = NSPoint::new(p.x, webview_height - p.y);
NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure(
ty, loc, NSEventModifierFlags::empty(), 0.0, window_number, None, 0, 1, 1.0,
).ok_or_else(|| EngineError::Other(format!("NSEvent::mouseEventWithType returned nil for {ty:?}")))
};
let down = make(NSEventType::LeftMouseDown, start)?;
web_view.mouseDown(&down);
let _ = run_loop_until(|| false, Duration::from_millis(15));
let landed = move_along_path(
web_view,
window,
webview_height,
start,
target,
mode,
seed,
true,
rec,
)?;
let up = make(NSEventType::LeftMouseUp, target)?;
web_view.mouseUp(&up);
super::headless_webview::end_suppressed_drag(web_view, up.locationInWindow());
let _ = run_loop_until(|| false, Duration::from_millis(30));
Ok(landed)
}
pub(super) fn type_text(
web_view: &Retained<WKWebView>,
text: &str,
mode: vs_humanize::InputMode,
seed: u64,
rec: Option<(&super::record::RecSink, MainThreadMarker)>,
cursor: vs_humanize::Point,
) -> EngineResult<()> {
let make_key = |ty: NSEventType, ch: &str| -> EngineResult<Retained<NSEvent>> {
let chars = objc2_foundation::NSString::from_str(ch);
NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
ty,
NSPoint::new(0.0, 0.0),
NSEventModifierFlags::empty(),
0.0,
0,
None,
&chars,
&chars,
false,
0,
)
.ok_or_else(|| EngineError::Other(format!("keyEventWithType returned nil for {ch:?}")))
};
let base_delay = match mode {
vs_humanize::InputMode::Robotic => 0u64,
vs_humanize::InputMode::Careful => 120,
vs_humanize::InputMode::Human => 45,
};
let mut jitter = seed | 1;
for (i, ch) in text.chars().enumerate() {
let s = ch.to_string();
let down = make_key(NSEventType::KeyDown, &s)?;
let up = make_key(NSEventType::KeyUp, &s)?;
web_view.keyDown(&down);
let hold = if base_delay == 0 { 1 } else { base_delay / 3 };
let _ = run_loop_until(|| false, Duration::from_millis(hold.max(1)));
web_view.keyUp(&up);
if base_delay > 0 {
jitter ^= jitter << 13;
jitter ^= jitter >> 7;
jitter ^= jitter << 17;
let span = if matches!(mode, vs_humanize::InputMode::Human) {
base_delay * 4 / 10
} else {
0
};
let extra = if span == 0 {
0
} else {
jitter % (span * 2 + 1)
};
let wait = base_delay.saturating_sub(span).saturating_add(extra);
let _ = run_loop_until(|| false, Duration::from_millis(wait.max(1)));
if let Some((sink, mtm)) = rec {
sink.frame(web_view, mtm, cursor.x, cursor.y, 0.0, (hold + wait) as u32);
}
} else if i % 8 == 0 {
let _ = run_loop_until(|| false, Duration::from_millis(1));
}
}
for _ in 0..6 {
let _ = run_loop_until(|| false, Duration::from_millis(25));
}
Ok(())
}