use super::ScreenModule;
use anyhow::Context;
use enigo::{
Button, Coordinate, Direction, Key, Keyboard, Mouse,
};
use serde_json::{json, Value};
pub fn tools() -> Vec<Value> {
vec![
json!({
"name": "screen_click",
"description": "Click at screen coordinates. Supports left/right/middle buttons, single/double/triple click, and modifier keys (ctrl, shift, alt, super).",
"inputSchema": {
"type": "object",
"properties": {
"x": { "type": "number", "description": "X coordinate (pixels)" },
"y": { "type": "number", "description": "Y coordinate (pixels)" },
"button": {
"type": "string",
"description": "Mouse button: 'left', 'right', or 'middle' (default 'left')",
"enum": ["left", "right", "middle"]
},
"count": {
"type": "number",
"description": "Click count: 1 (single), 2 (double), 3 (triple). Default 1."
},
"modifiers": {
"type": "array",
"items": { "type": "string", "enum": ["ctrl", "shift", "alt", "super"] },
"description": "Modifier keys to hold during click"
}
},
"required": ["x", "y"]
}
}),
json!({
"name": "screen_type",
"description": "Type a text string into the currently focused window. Simulates keyboard input character by character.",
"inputSchema": {
"type": "object",
"properties": {
"text": { "type": "string", "description": "Text to type" },
"delay_ms": {
"type": "number",
"description": "Delay in ms between keystrokes (default 0 for instant)"
}
},
"required": ["text"]
}
}),
json!({
"name": "screen_key",
"description": "Press a key combination, or hold a key for a duration. Examples: 'ctrl+c', 'alt+Tab', 'Return', 'F5', 'ctrl+shift+s', 'super'. Use hold_ms to hold the key(s) for sustained press. Supported keys: a-z, 0-9, F1-F12, Return/Enter, Tab, Escape/Esc, Backspace, Delete, Space, Up/Down/Left/Right, Home, End, PageUp, PageDown, plus modifiers ctrl/shift/alt/super.",
"inputSchema": {
"type": "object",
"properties": {
"keys": {
"type": "string",
"description": "Key combination, e.g. 'ctrl+c', 'Return', 'alt+Tab'"
},
"hold_ms": {
"type": "number",
"description": "Hold duration in ms. If set, keys are pressed, held for this duration, then released."
}
},
"required": ["keys"]
}
}),
json!({
"name": "screen_move",
"description": "Move the mouse cursor to the specified screen coordinates.",
"inputSchema": {
"type": "object",
"properties": {
"x": { "type": "number", "description": "X coordinate (pixels)" },
"y": { "type": "number", "description": "Y coordinate (pixels)" }
},
"required": ["x", "y"]
}
}),
json!({
"name": "screen_scroll",
"description": "Scroll at the specified screen position. Use 'lines' for simple scrolling (positive = down, negative = up) or 'delta_x'/'delta_y' for pixel-precise control.",
"inputSchema": {
"type": "object",
"properties": {
"x": { "type": "number", "description": "X coordinate to scroll at" },
"y": { "type": "number", "description": "Y coordinate to scroll at" },
"lines": {
"type": "number",
"description": "Lines to scroll (positive = down, negative = up)"
},
"delta_x": { "type": "number", "description": "Horizontal scroll pixels" },
"delta_y": { "type": "number", "description": "Vertical scroll pixels (negative = down)" }
},
"required": ["x", "y"]
}
}),
json!({
"name": "screen_drag",
"description": "Click and drag from one position to another. Useful for moving windows, selecting text, or drag-and-drop operations.",
"inputSchema": {
"type": "object",
"properties": {
"from_x": { "type": "number", "description": "Start X coordinate" },
"from_y": { "type": "number", "description": "Start Y coordinate" },
"to_x": { "type": "number", "description": "End X coordinate" },
"to_y": { "type": "number", "description": "End Y coordinate" },
"button": {
"type": "string",
"description": "Mouse button: 'left' or 'right' (default 'left')",
"enum": ["left", "right"]
},
"duration_ms": {
"type": "number",
"description": "Duration of drag in ms (default 300). Longer = smoother."
}
},
"required": ["from_x", "from_y", "to_x", "to_y"]
}
}),
]
}
pub async fn click(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
let x = args["x"].as_i64().context("Missing 'x' parameter")? as i32;
let y = args["y"].as_i64().context("Missing 'y' parameter")? as i32;
let button_str = args["button"].as_str().unwrap_or("left");
let count = args["count"].as_u64().unwrap_or(1).min(3) as usize;
let modifiers = args["modifiers"]
.as_array()
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str())
.collect::<Vec<_>>()
})
.unwrap_or_default();
if let Ok(mut enigo) = module.create_enigo() {
let button = parse_button(button_str)?;
return click_enigo(&mut enigo, x, y, button, button_str, count, &modifiers);
}
if let Some(ref xdotool) = module.xdotool_path {
return click_xdotool(xdotool, x, y, button_str, count);
}
Err(anyhow::anyhow!("No input backend available. Install xdotool: sudo apt install xdotool"))
}
fn click_enigo(
enigo: &mut enigo::Enigo,
x: i32, y: i32,
button: Button,
button_str: &str,
count: usize,
modifiers: &[&str],
) -> anyhow::Result<Value> {
enigo.move_mouse(x, y, Coordinate::Abs)
.map_err(|e| anyhow::anyhow!("Failed to move mouse: {}", e))?;
for m in modifiers {
if let Some(key) = modifier_key(m) {
enigo.key(key, Direction::Press)
.map_err(|e| anyhow::anyhow!("Failed to press modifier {}: {}", m, e))?;
}
}
for _ in 0..count {
enigo.button(button, Direction::Click)
.map_err(|e| anyhow::anyhow!("Failed to click: {}", e))?;
}
for m in modifiers.iter().rev() {
if let Some(key) = modifier_key(m) {
enigo.key(key, Direction::Release)
.map_err(|e| anyhow::anyhow!("Failed to release modifier {}: {}", m, e))?;
}
}
Ok(json!({
"success": true,
"x": x,
"y": y,
"button": button_str,
"count": count
}))
}
fn click_xdotool(
xdotool: &std::path::Path,
x: i32, y: i32,
button_str: &str,
count: usize,
) -> anyhow::Result<Value> {
let btn = match button_str {
"right" => "3",
"middle" => "2",
_ => "1",
};
let output = std::process::Command::new(xdotool)
.args(["mousemove", &x.to_string(), &y.to_string(),
"click", "--repeat", &count.to_string(), btn])
.output()
.map_err(|e| anyhow::anyhow!("xdotool failed: {}", e))?;
if !output.status.success() {
return Err(anyhow::anyhow!("xdotool click failed: {}", String::from_utf8_lossy(&output.stderr)));
}
Ok(json!({
"success": true,
"x": x, "y": y,
"button": button_str,
"count": count,
"backend": "xdotool"
}))
}
pub async fn type_text(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
let text = args["text"].as_str().context("Missing 'text' parameter")?;
let delay_ms = args["delay_ms"].as_u64().unwrap_or(0);
if let Ok(mut enigo) = module.create_enigo() {
if delay_ms == 0 {
enigo.text(text)
.map_err(|e| anyhow::anyhow!("Failed to type text: {}", e))?;
} else {
for ch in text.chars() {
enigo.text(&ch.to_string())
.map_err(|e| anyhow::anyhow!("Failed to type char '{}': {}", ch, e))?;
tokio::time::sleep(tokio::time::Duration::from_millis(delay_ms)).await;
}
}
return Ok(json!({ "success": true, "chars_typed": text.len() }));
}
if let Some(ref xdotool) = module.xdotool_path {
let mut cmd_args = vec!["type"];
let delay_str;
if delay_ms > 0 {
delay_str = delay_ms.to_string();
cmd_args.extend(["--delay", &delay_str]);
}
cmd_args.push(text);
let output = std::process::Command::new(xdotool)
.args(&cmd_args)
.output()
.map_err(|e| anyhow::anyhow!("xdotool type failed: {}", e))?;
if !output.status.success() {
return Err(anyhow::anyhow!("xdotool type failed: {}", String::from_utf8_lossy(&output.stderr)));
}
return Ok(json!({ "success": true, "chars_typed": text.len(), "backend": "xdotool" }));
}
Err(anyhow::anyhow!("No input backend available"))
}
pub async fn key(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
let keys_str = args["keys"].as_str().context("Missing 'keys' parameter")?;
let hold_ms = args["hold_ms"].as_u64();
if let Ok(mut enigo) = module.create_enigo() {
let (modifier_keys, main_key) = parse_key_combo(keys_str)?;
for mk in &modifier_keys {
enigo.key(*mk, Direction::Press)
.map_err(|e| anyhow::anyhow!("Failed to press modifier: {}", e))?;
}
if let Some(duration) = hold_ms {
enigo.key(main_key, Direction::Press)
.map_err(|e| anyhow::anyhow!("Failed to press key: {}", e))?;
tokio::time::sleep(tokio::time::Duration::from_millis(duration)).await;
enigo.key(main_key, Direction::Release)
.map_err(|e| anyhow::anyhow!("Failed to release key: {}", e))?;
} else {
enigo.key(main_key, Direction::Click)
.map_err(|e| anyhow::anyhow!("Failed to press key: {}", e))?;
}
for mk in modifier_keys.iter().rev() {
enigo.key(*mk, Direction::Release)
.map_err(|e| anyhow::anyhow!("Failed to release modifier: {}", e))?;
}
return Ok(json!({ "success": true, "keys": keys_str, "held_ms": hold_ms }));
}
if let Some(ref xdotool) = module.xdotool_path {
let output = std::process::Command::new(xdotool)
.args(["key", keys_str])
.output()
.map_err(|e| anyhow::anyhow!("xdotool key failed: {}", e))?;
if !output.status.success() {
return Err(anyhow::anyhow!("xdotool key failed: {}", String::from_utf8_lossy(&output.stderr)));
}
return Ok(json!({ "success": true, "keys": keys_str, "backend": "xdotool" }));
}
Err(anyhow::anyhow!("No input backend available"))
}
pub async fn move_mouse(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
let x = args["x"].as_i64().context("Missing 'x' parameter")? as i32;
let y = args["y"].as_i64().context("Missing 'y' parameter")? as i32;
if let Ok(mut enigo) = module.create_enigo() {
enigo.move_mouse(x, y, Coordinate::Abs)
.map_err(|e| anyhow::anyhow!("Failed to move mouse: {}", e))?;
return Ok(json!({ "success": true, "x": x, "y": y }));
}
if let Some(ref xdotool) = module.xdotool_path {
let output = std::process::Command::new(xdotool)
.args(["mousemove", &x.to_string(), &y.to_string()])
.output()
.map_err(|e| anyhow::anyhow!("xdotool mousemove failed: {}", e))?;
if output.status.success() {
return Ok(json!({ "success": true, "x": x, "y": y, "backend": "xdotool" }));
}
}
Err(anyhow::anyhow!("No input backend available"))
}
pub async fn scroll(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
let x = args["x"].as_i64().context("Missing 'x' parameter")? as i32;
let y = args["y"].as_i64().context("Missing 'y' parameter")? as i32;
let lines_arg = args["lines"].as_i64();
if let Ok(mut enigo) = module.create_enigo() {
enigo.move_mouse(x, y, Coordinate::Abs)
.map_err(|e| anyhow::anyhow!("Failed to move mouse: {}", e))?;
if let Some(lines) = lines_arg {
enigo.scroll(-lines as i32, enigo::Axis::Vertical)
.map_err(|e| anyhow::anyhow!("Failed to scroll: {}", e))?;
} else {
if let Some(dy) = args["delta_y"].as_i64() {
let scroll_lines = (dy as f64 / 120.0).round() as i32;
if scroll_lines != 0 {
enigo.scroll(scroll_lines, enigo::Axis::Vertical)
.map_err(|e| anyhow::anyhow!("Failed to scroll vertically: {}", e))?;
}
}
if let Some(dx) = args["delta_x"].as_i64() {
let cols = (dx as f64 / 120.0).round() as i32;
if cols != 0 {
enigo.scroll(cols, enigo::Axis::Horizontal)
.map_err(|e| anyhow::anyhow!("Failed to scroll horizontally: {}", e))?;
}
}
}
return Ok(json!({ "success": true, "x": x, "y": y }));
}
if let Some(ref xdotool) = module.xdotool_path {
let scroll_lines = lines_arg.unwrap_or_else(|| {
args["delta_y"].as_i64().map(|dy| (dy as f64 / 120.0).round() as i64).unwrap_or(3)
});
let (btn, count) = if scroll_lines >= 0 {
("5", scroll_lines.unsigned_abs() as usize)
} else {
("4", scroll_lines.unsigned_abs() as usize)
};
let output = std::process::Command::new(xdotool)
.args(["mousemove", &x.to_string(), &y.to_string(),
"click", "--repeat", &count.to_string(), btn])
.output()
.map_err(|e| anyhow::anyhow!("xdotool scroll failed: {}", e))?;
if !output.status.success() {
return Err(anyhow::anyhow!("xdotool scroll failed: {}", String::from_utf8_lossy(&output.stderr)));
}
return Ok(json!({ "success": true, "x": x, "y": y, "backend": "xdotool" }));
}
Err(anyhow::anyhow!("No input backend available"))
}
pub async fn drag(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
let from_x = args["from_x"].as_i64().context("Missing 'from_x'")? as i32;
let from_y = args["from_y"].as_i64().context("Missing 'from_y'")? as i32;
let to_x = args["to_x"].as_i64().context("Missing 'to_x'")? as i32;
let to_y = args["to_y"].as_i64().context("Missing 'to_y'")? as i32;
let button_str = args["button"].as_str().unwrap_or("left");
let duration_ms = args["duration_ms"].as_u64().unwrap_or(300);
let button = parse_button(button_str)?;
let mut enigo = module.create_enigo()?;
enigo.move_mouse(from_x, from_y, Coordinate::Abs)
.map_err(|e| anyhow::anyhow!("Failed to move to start: {}", e))?;
enigo.button(button, Direction::Press)
.map_err(|e| anyhow::anyhow!("Failed to press button: {}", e))?;
let steps = 20u32;
let step_delay = duration_ms / steps as u64;
for i in 1..=steps {
let t = i as f64 / steps as f64;
let cx = from_x as f64 + (to_x - from_x) as f64 * t;
let cy = from_y as f64 + (to_y - from_y) as f64 * t;
enigo.move_mouse(cx as i32, cy as i32, Coordinate::Abs)
.map_err(|e| anyhow::anyhow!("Failed to move during drag: {}", e))?;
if step_delay > 0 {
tokio::time::sleep(tokio::time::Duration::from_millis(step_delay)).await;
}
}
enigo.button(button, Direction::Release)
.map_err(|e| anyhow::anyhow!("Failed to release button: {}", e))?;
Ok(json!({
"success": true,
"from": [from_x, from_y],
"to": [to_x, to_y],
"button": button_str,
"duration_ms": duration_ms
}))
}
fn parse_button(s: &str) -> anyhow::Result<Button> {
match s {
"left" => Ok(Button::Left),
"right" => Ok(Button::Right),
"middle" => Ok(Button::Middle),
_ => Err(anyhow::anyhow!("Unknown button '{}'. Use 'left', 'right', or 'middle'.", s)),
}
}
fn modifier_key(name: &str) -> Option<Key> {
match name.to_lowercase().as_str() {
"ctrl" | "control" => Some(Key::Control),
"shift" => Some(Key::Shift),
"alt" => Some(Key::Alt),
"super" | "meta" | "win" | "command" | "cmd" => Some(Key::Meta),
_ => None,
}
}
fn parse_key_combo(s: &str) -> anyhow::Result<(Vec<Key>, Key)> {
let parts: Vec<&str> = s.split('+').map(str::trim).collect();
if parts.is_empty() {
return Err(anyhow::anyhow!("Empty key combination"));
}
let mut modifiers = Vec::new();
let mut main_key = None;
for (i, part) in parts.iter().enumerate() {
if i < parts.len() - 1 {
let mk = modifier_key(part).ok_or_else(|| {
anyhow::anyhow!("'{}' is not a valid modifier (use ctrl, shift, alt, super)", part)
})?;
modifiers.push(mk);
} else {
if let Some(mk) = modifier_key(part) {
if parts.len() == 1 {
main_key = Some(mk);
} else {
modifiers.push(mk);
main_key = Some(mk);
}
} else {
main_key = Some(parse_single_key(part)?);
}
}
}
let key = main_key.context("No key specified in combination")?;
Ok((modifiers, key))
}
fn parse_single_key(s: &str) -> anyhow::Result<Key> {
match s.to_lowercase().as_str() {
"return" | "enter" => Ok(Key::Return),
"tab" => Ok(Key::Tab),
"escape" | "esc" => Ok(Key::Escape),
"backspace" => Ok(Key::Backspace),
"delete" | "del" => Ok(Key::Delete),
"space" => Ok(Key::Space),
"up" => Ok(Key::UpArrow),
"down" => Ok(Key::DownArrow),
"left" => Ok(Key::LeftArrow),
"right" => Ok(Key::RightArrow),
"home" => Ok(Key::Home),
"end" => Ok(Key::End),
"pageup" | "pgup" => Ok(Key::PageUp),
"pagedown" | "pgdn" | "pgdown" => Ok(Key::PageDown),
"f1" => Ok(Key::F1),
"f2" => Ok(Key::F2),
"f3" => Ok(Key::F3),
"f4" => Ok(Key::F4),
"f5" => Ok(Key::F5),
"f6" => Ok(Key::F6),
"f7" => Ok(Key::F7),
"f8" => Ok(Key::F8),
"f9" => Ok(Key::F9),
"f10" => Ok(Key::F10),
"f11" => Ok(Key::F11),
"f12" => Ok(Key::F12),
"capslock" | "caps" => Ok(Key::CapsLock),
"insert" | "ins" => Ok(Key::Other(0xff63)), "printscreen" | "print" | "prtsc" | "sysrq" => Ok(Key::Other(0xff61)), "numlock" | "num_lock" => Ok(Key::Other(0xff7f)), "scrolllock" | "scroll_lock" => Ok(Key::Other(0xff14)), "pause" | "break" => Ok(Key::Other(0xff13)), "menu" | "contextmenu" | "apps" => Ok(Key::Other(0xff67)), other => {
let chars: Vec<char> = other.chars().collect();
if chars.len() == 1 {
Ok(Key::Unicode(chars[0]))
} else {
Err(anyhow::anyhow!(
"Unknown key '{}'. Use named keys (Return, Tab, F1-F12, etc.) or single characters.",
s
))
}
}
}
}