use super::ScreenModule;
use anyhow::Context;
use serde_json::{json, Value};
use std::process::Command;
pub fn tools() -> Vec<Value> {
vec![
json!({
"name": "screen_windows",
"description": "List all open windows with their IDs, titles, positions, and sizes. Use the window ID with screen_capture (target='window') or screen_focus. Optionally filter by title pattern.",
"inputSchema": {
"type": "object",
"properties": {
"filter": {
"type": "string",
"description": "Optional regex pattern to filter window titles"
}
},
"required": []
}
}),
json!({
"name": "screen_focus",
"description": "Manage a window: focus, minimize, maximize, close, resize, or move it. Target by window_id or title pattern. Uses xdotool (no extra install needed).",
"inputSchema": {
"type": "object",
"properties": {
"window_id": {
"type": "string",
"description": "Window ID (hex from screen_windows, or decimal)"
},
"title": {
"type": "string",
"description": "Window title pattern (used if window_id not provided)"
},
"action": {
"type": "string",
"description": "Action to perform",
"enum": ["focus", "minimize", "maximize", "close", "resize", "move"]
},
"width": { "type": "number", "description": "New width (for resize)" },
"height": { "type": "number", "description": "New height (for resize)" },
"x": { "type": "number", "description": "New X position (for move)" },
"y": { "type": "number", "description": "New Y position (for move)" }
},
"required": ["action"]
}
}),
json!({
"name": "screen_wait",
"description": "Wait for a specified time or until a window with a matching title appears.",
"inputSchema": {
"type": "object",
"properties": {
"ms": {
"type": "number",
"description": "Milliseconds to wait (simple delay)"
},
"window_title": {
"type": "string",
"description": "Wait until a window with this title pattern appears"
},
"timeout_ms": {
"type": "number",
"description": "Timeout for window_title wait (default 10000ms)"
}
},
"required": []
}
}),
]
}
pub async fn list_windows(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
let filter = args["filter"].as_str();
let filter_regex = if let Some(pattern) = filter {
Some(regex::Regex::new(pattern).context("Invalid filter regex")?)
} else {
None
};
let mut windows: Vec<Value> = Vec::new();
if let Ok(xcap_windows) = xcap::Window::all() {
let active_id = get_active_window_id(module);
for win in &xcap_windows {
let title = win.title();
if title.is_empty() {
continue;
}
if let Some(ref re) = filter_regex {
if !re.is_match(title) {
continue;
}
}
let id = win.id();
windows.push(json!({
"id": format!("0x{:08x}", id),
"title": title,
"x": win.x(),
"y": win.y(),
"width": win.width(),
"height": win.height(),
"is_focused": active_id.map_or(false, |aid| aid == id),
"is_minimized": win.is_minimized(),
}));
}
} else if let Some(ref wmctrl) = module.wmctrl_path {
windows = list_windows_wmctrl(wmctrl, &filter_regex, module)?;
} else if let Some(ref xdotool) = module.xdotool_path {
windows = list_windows_xdotool(xdotool, &filter_regex)?;
}
Ok(json!({
"window_count": windows.len(),
"windows": windows
}))
}
pub async fn focus_window(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
let action = args["action"].as_str().context("Missing 'action' parameter")?;
let window_id = args["window_id"].as_str();
let title = args["title"].as_str();
if window_id.is_none() && title.is_none() {
return Err(anyhow::anyhow!("Provide either 'window_id' or 'title' to target a window"));
}
let resolved_id = resolve_window_id(module, window_id, title)?;
let target_desc = if let Some(id) = window_id {
format!("window {}", id)
} else {
format!("window titled '{}'", title.unwrap_or("?"))
};
if let Some(ref xdotool) = module.xdotool_path {
return focus_with_xdotool(xdotool, &resolved_id, action, &args, &target_desc);
}
if let Some(ref wmctrl) = module.wmctrl_path {
return focus_with_wmctrl(wmctrl, &resolved_id, action, &args, &target_desc);
}
Err(anyhow::anyhow!(
"Neither xdotool nor wmctrl found. Install one: sudo apt install xdotool"
))
}
pub async fn wait(_module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
let ms = args["ms"].as_u64();
let window_title = args["window_title"].as_str();
let timeout_ms = args["timeout_ms"].as_u64().unwrap_or(10000);
if let Some(delay) = ms {
tokio::time::sleep(tokio::time::Duration::from_millis(delay)).await;
return Ok(json!({
"success": true,
"waited_ms": delay
}));
}
if let Some(title_pattern) = window_title {
let re = regex::Regex::new(title_pattern).context("Invalid window_title pattern")?;
let start = std::time::Instant::now();
let poll_interval = tokio::time::Duration::from_millis(200);
loop {
if let Ok(windows) = xcap::Window::all() {
for win in &windows {
if re.is_match(win.title()) {
let elapsed = start.elapsed().as_millis();
return Ok(json!({
"success": true,
"waited_ms": elapsed,
"found_window": win.title()
}));
}
}
}
if start.elapsed().as_millis() as u64 >= timeout_ms {
return Ok(json!({
"success": false,
"waited_ms": timeout_ms,
"error": format!("Timed out waiting for window matching '{}'", title_pattern)
}));
}
tokio::time::sleep(poll_interval).await;
}
}
Ok(json!({
"success": true,
"waited_ms": 0,
"note": "No wait condition specified. Provide 'ms' or 'window_title'."
}))
}
fn resolve_window_id(
module: &ScreenModule,
window_id: Option<&str>,
title: Option<&str>,
) -> anyhow::Result<String> {
if let Some(id) = window_id {
if id.starts_with("0x") || id.starts_with("0X") {
let decimal = u64::from_str_radix(&id[2..], 16)
.context("Invalid hex window ID")?;
return Ok(decimal.to_string());
}
return Ok(id.to_string());
}
if let Some(pattern) = title {
if let Some(ref xdotool) = module.xdotool_path {
let output = Command::new(xdotool)
.args(["search", "--name", pattern])
.output()
.context("Failed to search for window")?;
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
if let Some(first_id) = stdout.lines().next() {
if !first_id.trim().is_empty() {
return Ok(first_id.trim().to_string());
}
}
}
}
}
Err(anyhow::anyhow!("Could not resolve window target"))
}
fn focus_with_xdotool(
xdotool: &std::path::Path,
window_id: &str,
action: &str,
args: &Value,
target_desc: &str,
) -> anyhow::Result<Value> {
let result = match action {
"focus" => run_cmd(xdotool, &["windowactivate", window_id]),
"minimize" => run_cmd(xdotool, &["windowminimize", window_id]),
"maximize" => {
run_cmd(xdotool, &["windowsize", window_id, "100%", "100%"])
}
"close" => run_cmd(xdotool, &["windowclose", window_id]),
"resize" => {
let w = args["width"].as_i64().context("Missing 'width' for resize")?;
let h = args["height"].as_i64().context("Missing 'height' for resize")?;
run_cmd(xdotool, &["windowsize", window_id, &w.to_string(), &h.to_string()])
}
"move" => {
let x = args["x"].as_i64().context("Missing 'x' for move")?;
let y = args["y"].as_i64().context("Missing 'y' for move")?;
run_cmd(xdotool, &["windowmove", window_id, &x.to_string(), &y.to_string()])
}
_ => return Err(anyhow::anyhow!(
"Unknown action '{}'. Use: focus, minimize, maximize, close, resize, move",
action
)),
};
match result {
Ok(()) => Ok(json!({
"success": true,
"action": action,
"target": target_desc,
"backend": "xdotool"
})),
Err(e) => Err(anyhow::anyhow!("Failed to {} {}: {}", action, target_desc, e)),
}
}
fn focus_with_wmctrl(
wmctrl: &std::path::Path,
window_id: &str,
action: &str,
args: &Value,
target_desc: &str,
) -> anyhow::Result<Value> {
let result = match action {
"focus" => run_cmd(wmctrl, &["-i", "-a", window_id]),
"minimize" => run_cmd(wmctrl, &["-i", "-r", window_id, "-b", "add,hidden"]),
"maximize" => run_cmd(wmctrl, &["-i", "-r", window_id, "-b", "add,maximized_vert,maximized_horz"]),
"close" => run_cmd(wmctrl, &["-i", "-c", window_id]),
"resize" => {
let w = args["width"].as_i64().context("Missing 'width' for resize")?;
let h = args["height"].as_i64().context("Missing 'height' for resize")?;
let geom = format!("0,-1,-1,{},{}", w, h);
run_cmd(wmctrl, &["-i", "-r", window_id, "-e", &geom])
}
"move" => {
let x = args["x"].as_i64().context("Missing 'x' for move")?;
let y = args["y"].as_i64().context("Missing 'y' for move")?;
let geom = format!("0,{},{},-1,-1", x, y);
run_cmd(wmctrl, &["-i", "-r", window_id, "-e", &geom])
}
_ => return Err(anyhow::anyhow!(
"Unknown action '{}'. Use: focus, minimize, maximize, close, resize, move",
action
)),
};
match result {
Ok(()) => Ok(json!({
"success": true,
"action": action,
"target": target_desc,
"backend": "wmctrl"
})),
Err(e) => Err(anyhow::anyhow!("Failed to {} {}: {}", action, target_desc, e)),
}
}
fn list_windows_wmctrl(
wmctrl: &std::path::Path,
filter: &Option<regex::Regex>,
module: &ScreenModule,
) -> anyhow::Result<Vec<Value>> {
let output = Command::new(wmctrl)
.args(["-lG"])
.output()
.context("Failed to run wmctrl -lG")?;
if !output.status.success() {
return Err(anyhow::anyhow!("wmctrl -lG failed: {}", String::from_utf8_lossy(&output.stderr)));
}
let stdout = String::from_utf8_lossy(&output.stdout);
let active_id = get_active_window_id(module);
let mut windows = Vec::new();
let re = regex::Regex::new(r"(0x\w+)\s+\d+\s+(-?\d+)\s+(-?\d+)\s+(\d+)\s+(\d+)\s+\S+\s+(.*)")
.context("Invalid regex")?;
for line in stdout.lines() {
let caps = match re.captures(line) {
Some(c) => c,
None => continue,
};
let id_hex = caps.get(1).unwrap().as_str();
let x: i64 = caps[2].parse().unwrap_or(0);
let y: i64 = caps[3].parse().unwrap_or(0);
let w: i64 = caps[4].parse().unwrap_or(0);
let h: i64 = caps[5].parse().unwrap_or(0);
let title = caps.get(6).unwrap().as_str().trim();
if title.is_empty() || title == "N/A" {
continue;
}
if let Some(ref re) = filter {
if !re.is_match(title) {
continue;
}
}
let id_decimal: u32 = if id_hex.starts_with("0x") || id_hex.starts_with("0X") {
u32::from_str_radix(&id_hex[2..], 16).unwrap_or(0)
} else {
id_hex.parse().unwrap_or(0)
};
windows.push(json!({
"id": id_hex,
"title": title,
"x": x,
"y": y,
"width": w,
"height": h,
"is_focused": active_id.map_or(false, |aid| aid == id_decimal),
}));
}
Ok(windows)
}
fn list_windows_xdotool(
xdotool: &std::path::Path,
filter: &Option<regex::Regex>,
) -> anyhow::Result<Vec<Value>> {
let search_args = if let Some(ref re) = filter {
vec!["search", "--name", re.as_str()]
} else {
vec!["search", "--name", ""]
};
let output = Command::new(xdotool)
.args(&search_args)
.output()
.context("Failed to run xdotool search")?;
let stdout = String::from_utf8_lossy(&output.stdout);
let active_id = get_active_window_id_str(xdotool);
let mut windows = Vec::new();
for line in stdout.lines() {
let wid = line.trim();
if wid.is_empty() {
continue;
}
let name_output = Command::new(xdotool)
.args(["getwindowname", wid])
.output();
let title = name_output
.ok()
.filter(|o| o.status.success())
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
.unwrap_or_default();
if title.is_empty() {
continue;
}
let geom_output = Command::new(xdotool)
.args(["getwindowgeometry", "--shell", wid])
.output();
let (x, y, w, h) = parse_xdotool_geometry(
&geom_output
.ok()
.filter(|o| o.status.success())
.map(|o| String::from_utf8_lossy(&o.stdout).to_string())
.unwrap_or_default(),
);
let id_num: u64 = wid.parse().unwrap_or(0);
windows.push(json!({
"id": format!("0x{:08x}", id_num),
"title": title,
"x": x,
"y": y,
"width": w,
"height": h,
"is_focused": active_id.as_deref() == Some(wid),
}));
}
Ok(windows)
}
fn get_active_window_id(module: &ScreenModule) -> Option<u32> {
if let Some(ref path) = module.xdotool_path {
if let Ok(output) = Command::new(path).arg("getactivewindow").output() {
if output.status.success() {
let s = String::from_utf8_lossy(&output.stdout);
return s.trim().parse().ok();
}
}
}
None
}
fn get_active_window_id_str(xdotool: &std::path::Path) -> Option<String> {
Command::new(xdotool)
.arg("getactivewindow")
.output()
.ok()
.filter(|o| o.status.success())
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
}
fn parse_xdotool_geometry(shell_output: &str) -> (i64, i64, i64, i64) {
let mut x = 0i64;
let mut y = 0i64;
let mut w = 0i64;
let mut h = 0i64;
for line in shell_output.lines() {
let line = line.trim();
if let Some(val) = line.strip_prefix("X=") {
x = val.parse().unwrap_or(0);
} else if let Some(val) = line.strip_prefix("Y=") {
y = val.parse().unwrap_or(0);
} else if let Some(val) = line.strip_prefix("WIDTH=") {
w = val.parse().unwrap_or(0);
} else if let Some(val) = line.strip_prefix("HEIGHT=") {
h = val.parse().unwrap_or(0);
}
}
(x, y, w, h)
}
fn run_cmd(bin: &std::path::Path, args: &[&str]) -> anyhow::Result<()> {
let output = Command::new(bin)
.args(args)
.output()
.context(format!("Failed to run {}", bin.display()))?;
if output.status.success() {
Ok(())
} else {
Err(anyhow::anyhow!(
"{} exited with {}: {}",
bin.display(),
output.status,
String::from_utf8_lossy(&output.stderr)
))
}
}