use super::{ClickParams, MouseMode};
use crate::mouse::mouse_input;
use crate::script_engine::instruction::{
InstructionData, InstructionHandler, InstructionMetadata, ScriptError,
};
use crate::script_engine::VMContext;
use crate::utils::sleep_ms;
pub struct ClickHandler;
impl InstructionHandler for ClickHandler {
fn name(&self) -> &str {
"click"
}
#[inline]
fn parse(&self, args: &[&str]) -> Result<InstructionData, ScriptError> {
let (mode, mode_offset) = super::parse_mouse_mode(args, MouseMode::Send)?;
let remaining_args = &args[..args.len() - mode_offset];
let (delay_ms, coord_args) = if !remaining_args.is_empty() {
let last_arg = remaining_args[remaining_args.len() - 1];
if last_arg.parse::<u32>().is_ok() {
if remaining_args.len() >= 3 {
let delay = remaining_args[remaining_args.len() - 1]
.parse::<u32>()
.map_err(|e| {
ScriptError::ParseError(format!(
"Invalid delay_ms '{}': {}",
last_arg, e
))
})?;
let coord_slice = &remaining_args[..remaining_args.len() - 1];
(delay, coord_slice)
} else {
(0, remaining_args)
}
} else {
(0, remaining_args)
}
} else {
(0, remaining_args)
};
let (x, y) = if coord_args.len() == 2 {
let x = coord_args[0].parse::<i32>().map_err(|e| {
ScriptError::ParseError(format!("Invalid x coordinate '{}': {}", coord_args[0], e))
})?;
let y = coord_args[1].parse::<i32>().map_err(|e| {
ScriptError::ParseError(format!("Invalid y coordinate '{}': {}", coord_args[1], e))
})?;
(Some(x), Some(y))
} else if coord_args.is_empty() {
(None, None)
} else {
return Err(ScriptError::ParseError(
format!(
"Click requires either 0 or 2 coordinates, got {}",
coord_args.len()
)
.into(),
));
};
if mode == MouseMode::Post && (x.is_none() || y.is_none()) {
return Err(ScriptError::ParseError(
"PostMessage mode requires coordinates. Usage: click <x> <y> [delay_ms] post"
.into(),
));
}
let send_inputs = if mode == MouseMode::Send {
mouse_input::build_click_left().to_vec()
} else {
vec![] };
Ok(InstructionData::Custom(Box::new(ClickParams {
x,
y,
mode,
mode_specified: mode_offset > 0,
delay_ms,
send_inputs,
})))
}
#[inline]
fn execute(
&self,
vm: &mut VMContext,
data: &InstructionData,
_metadata: Option<&InstructionMetadata>,
) -> Result<(), ScriptError> {
let params = data.extract_custom::<ClickParams>("Invalid click parameters")?;
let effective_mode = if params.mode_specified {
params.mode
} else {
match super::get_input_mode(vm).as_str() {
"post" => MouseMode::Post,
_ => MouseMode::Send,
}
};
match effective_mode {
MouseMode::Send => {
let screen_coords = if let (Some(x), Some(y)) = (params.x, params.y) {
#[cfg(feature = "script_process_context")]
{
if vm.process.has_hwnd() {
Some(super::convert_to_window_coords(vm, x, y)?)
} else {
Some((x, y))
}
}
#[cfg(not(feature = "script_process_context"))]
{
Some((x, y))
}
} else {
None
};
if let Some((screen_x, screen_y)) = screen_coords {
mouse_input::set_cursor_pos(screen_x, screen_y).map_err(|e| {
ScriptError::ExecutionError(format!("SetCursorPos failed: {:?}", e))
})?;
mouse_input::execute_inputs(¶ms.send_inputs).map_err(|e| {
ScriptError::ExecutionError(format!("Click failed: {:?}", e))
})?;
if params.delay_ms > 0 {
sleep_ms(params.delay_ms);
}
} else {
mouse_input::execute_inputs(¶ms.send_inputs).map_err(|e| {
ScriptError::ExecutionError(format!("Click failed: {:?}", e))
})?;
if params.delay_ms > 0 {
sleep_ms(params.delay_ms);
}
}
}
MouseMode::Post => {
#[cfg(feature = "script_process_context")]
{
use crate::mouse::mouse_message;
let x = params.x.ok_or_else(|| {
ScriptError::ExecutionError(
"PostMessage click requires x coordinate".into(),
)
})?;
let y = params.y.ok_or_else(|| {
ScriptError::ExecutionError(
"PostMessage click requires y coordinate".into(),
)
})?;
let (client_x, client_y) = super::convert_to_client_coords(vm, x, y)?;
mouse_message::post_click_left_atomic(
vm.process.get_hwnd_or_err()?,
client_x,
client_y,
);
}
#[cfg(not(feature = "script_process_context"))]
{
return Err(ScriptError::ExecutionError(
"PostMessage mode requires 'script_process_context' feature. \
Enable it in Cargo.toml: features = [\"scripts_mouse_with_post\"] \
or use SendInput mode (default)."
.into(),
));
}
}
}
Ok(())
}
}