use super::ScreenModule;
use anyhow::Context;
use serde_json::{json, Value};
use std::process::Command;
pub fn tools() -> Vec<Value> {
vec![
json!({
"name": "screen_clipboard",
"description": "Read or write the system clipboard. Combined with ctrl+c/ctrl+v, this is faster and more reliable than OCR for text extraction.",
"inputSchema": {
"type": "object",
"properties": {
"action": {
"type": "string",
"description": "'read' to get clipboard contents, 'write' to set them",
"enum": ["read", "write"]
},
"text": {
"type": "string",
"description": "Text to write to clipboard (required for action='write')"
}
},
"required": ["action"]
}
}),
json!({
"name": "screen_pixel",
"description": "Get the color of a pixel at screen coordinates. Useful for quick state detection: is a toggle on/off, is a button greyed out, has a loading indicator disappeared. Sub-millisecond, much cheaper than a screenshot.",
"inputSchema": {
"type": "object",
"properties": {
"x": { "type": "number", "description": "X coordinate" },
"y": { "type": "number", "description": "Y coordinate" },
"sample_size": {
"type": "number",
"description": "Average NxN pixel area (default 1). Useful for anti-aliased elements."
}
},
"required": ["x", "y"]
}
}),
json!({
"name": "screen_diff",
"description": "Compare two screenshots and return changed regions. Take a screenshot before an action, take another after, then diff them to see what changed. Accepts base64 image data or 'capture_now' to take a fresh screenshot.",
"inputSchema": {
"type": "object",
"properties": {
"action": {
"type": "string",
"description": "'save' to save current screen as reference, 'compare' to diff against saved reference",
"enum": ["save", "compare"]
},
"name": {
"type": "string",
"description": "Reference name (default 'default')"
},
"threshold": {
"type": "number",
"description": "Pixel difference threshold 0-255 (default 30). Lower = more sensitive."
}
},
"required": ["action"]
}
}),
json!({
"name": "screen_process",
"description": "Launch an application and wait for its window to appear. Returns the window ID for use with other screen tools. Atomic app-open operation.",
"inputSchema": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "Command to launch (e.g. 'firefox', 'discord', 'gnome-calculator')"
},
"args": {
"type": "array",
"items": { "type": "string" },
"description": "Command arguments"
},
"window_title": {
"type": "string",
"description": "Regex pattern for the expected window title (auto-detected from command name if omitted)"
},
"timeout_ms": {
"type": "number",
"description": "Max time to wait for window (default 15000ms)"
}
},
"required": ["command"]
}
}),
]
}
pub async fn clipboard(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
let action = args["action"].as_str().context("Missing 'action'")?;
match action {
"read" => clipboard_read(module),
"write" => {
let text = args["text"].as_str().context("Missing 'text' for write")?;
clipboard_write(module, text)
}
_ => Err(anyhow::anyhow!("Unknown action '{}'. Use 'read' or 'write'.", action)),
}
}
fn clipboard_read(_module: &ScreenModule) -> anyhow::Result<Value> {
use cli_clipboard::ClipboardProvider;
let mut ctx = cli_clipboard::ClipboardContext::new()
.map_err(|e| anyhow::anyhow!("Failed to access clipboard: {}", e))?;
let text = ctx.get_contents()
.map_err(|e| anyhow::anyhow!("Failed to read clipboard: {}", e))?;
Ok(json!({ "text": text, "length": text.len() }))
}
fn clipboard_write(_module: &ScreenModule, text: &str) -> anyhow::Result<Value> {
use cli_clipboard::ClipboardProvider;
let mut ctx = cli_clipboard::ClipboardContext::new()
.map_err(|e| anyhow::anyhow!("Failed to access clipboard: {}", e))?;
ctx.set_contents(text.to_string())
.map_err(|e| anyhow::anyhow!("Failed to write clipboard: {}", e))?;
Ok(json!({ "success": true, "length": text.len() }))
}
pub async fn pixel(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
let x = args["x"].as_u64().context("Missing 'x'")? as u32;
let y = args["y"].as_u64().context("Missing 'y'")? as u32;
let sample_size = args["sample_size"].as_u64().unwrap_or(1).max(1) as u32;
let tmp = super::shm_temp_path("pixel", "png");
if let Some(ref scrot) = module.scrot_path {
let capture_pad = 5u32;
let cx = x.saturating_sub(capture_pad);
let cy = y.saturating_sub(capture_pad);
let cw = sample_size + capture_pad * 2;
let ch = sample_size + capture_pad * 2;
let area = format!("{},{},{},{}", cx, cy, cw, ch);
let output = Command::new(scrot).args(["-a", &area, "-o", &tmp]).output();
if let Ok(o) = output {
if o.status.success() {
if let Ok(img) = image::open(&tmp) {
let _ = std::fs::remove_file(&tmp);
let rgba = img.to_rgba8();
let rel_x = x - cx;
let rel_y = y - cy;
return Ok(pixel_result(&rgba, rel_x, rel_y, sample_size, x, y));
}
}
}
let _ = std::fs::remove_file(&tmp);
}
let monitors = xcap::Monitor::all().context("Failed to enumerate monitors")?;
let monitor = monitors.first().context("No monitors")?;
let img = monitor.capture_image().context("Failed to capture")?;
Ok(pixel_result(&img, x, y, sample_size, x, y))
}
fn pixel_result(img: &image::RgbaImage, img_x: u32, img_y: u32, sample_size: u32, screen_x: u32, screen_y: u32) -> Value {
if img.width() == 0 || img.height() == 0 {
return json!({"error": "Captured image has zero dimensions", "x": screen_x, "y": screen_y});
}
if sample_size <= 1 {
let px = img_x.min(img.width().saturating_sub(1));
let py = img_y.min(img.height().saturating_sub(1));
let p = img.get_pixel(px, py);
let hex = format!("#{:02x}{:02x}{:02x}", p[0], p[1], p[2]);
return json!({
"x": screen_x, "y": screen_y,
"r": p[0], "g": p[1], "b": p[2], "a": p[3],
"hex": hex
});
}
let half = sample_size / 2;
let mut r_sum = 0u64;
let mut g_sum = 0u64;
let mut b_sum = 0u64;
let mut count = 0u64;
for dy in 0..sample_size {
for dx in 0..sample_size {
let px = (img_x + dx).saturating_sub(half);
let py = (img_y + dy).saturating_sub(half);
if px < img.width() && py < img.height() {
let p = img.get_pixel(px, py);
r_sum += p[0] as u64;
g_sum += p[1] as u64;
b_sum += p[2] as u64;
count += 1;
}
}
}
if count == 0 {
return json!({"error": "Coordinates out of bounds"});
}
let r = (r_sum / count) as u8;
let g = (g_sum / count) as u8;
let b = (b_sum / count) as u8;
let hex = format!("#{:02x}{:02x}{:02x}", r, g, b);
json!({
"x": screen_x, "y": screen_y, "sample_size": sample_size,
"r": r, "g": g, "b": b, "hex": hex
})
}
const MAX_DIFF_REFS: usize = 10;
static DIFF_REFS: std::sync::Mutex<Option<Vec<(String, Vec<u8>)>>> =
std::sync::Mutex::new(None);
pub async fn diff(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
let action = args["action"].as_str().context("Missing 'action'")?;
let name = args["name"].as_str().unwrap_or("default");
let threshold = args["threshold"].as_u64().unwrap_or(30) as u8;
match action {
"save" => {
let tmp = super::shm_temp_path("diff", "png");
let img_bytes = if let Some(ref scrot) = module.scrot_path {
let _ = Command::new(scrot).args(["-o", &tmp]).output();
let bytes = std::fs::read(&tmp).context("Failed to read capture")?;
let _ = std::fs::remove_file(&tmp);
bytes
} else {
let monitors = xcap::Monitor::all()?;
let monitor = monitors.first().context("No monitors")?;
let img = monitor.capture_image()?;
let tmp2 = super::shm_temp_path("diff_xcap", "png");
img.save(&tmp2).context("Failed to save capture")?;
let bytes = std::fs::read(&tmp2).context("Failed to read capture")?;
let _ = std::fs::remove_file(&tmp2);
bytes
};
let size = img_bytes.len();
let mut refs = DIFF_REFS.lock().unwrap_or_else(|p| p.into_inner());
let list = refs.get_or_insert_with(Vec::new);
list.retain(|(k, _)| k != name);
while list.len() >= MAX_DIFF_REFS {
list.remove(0);
}
list.push((name.to_string(), img_bytes));
Ok(json!({
"success": true,
"action": "save",
"name": name,
"bytes": size
}))
}
"compare" => {
let ref_bytes = {
let refs = DIFF_REFS.lock().unwrap_or_else(|p| p.into_inner());
refs.as_ref()
.and_then(|list| list.iter().find(|(k, _)| k == name).map(|(_, v)| v.clone()))
.ok_or_else(|| anyhow::anyhow!(
"No reference '{}' saved. Call screen_diff with action='save' first.", name
))?
};
let ref_img = image::load_from_memory(&ref_bytes)
.context("Failed to decode reference image")?
.to_rgba8();
let tmp = super::shm_temp_path("diff_now", "png");
let current_img = if let Some(ref scrot) = module.scrot_path {
let _ = Command::new(scrot).args(["-o", &tmp]).output();
let img = image::open(&tmp).context("Failed to open capture")?.to_rgba8();
let _ = std::fs::remove_file(&tmp);
img
} else {
let monitors = xcap::Monitor::all()?;
let monitor = monitors.first().context("No monitors")?;
monitor.capture_image()?
};
let (changed_pixels, regions) = compare_images(&ref_img, ¤t_img, threshold);
let total_pixels = ref_img.width() as u64 * ref_img.height() as u64;
let change_pct = if total_pixels > 0 {
(changed_pixels as f64 / total_pixels as f64) * 100.0
} else {
0.0
};
Ok(json!({
"changed": changed_pixels > 0,
"changed_pixels": changed_pixels,
"total_pixels": total_pixels,
"change_percent": format!("{:.2}", change_pct),
"regions": regions
}))
}
_ => Err(anyhow::anyhow!("Unknown action '{}'. Use 'save' or 'compare'.", action)),
}
}
fn compare_images(a: &image::RgbaImage, b: &image::RgbaImage, threshold: u8) -> (u64, Vec<Value>) {
let w = a.width().min(b.width());
let h = a.height().min(b.height());
let threshold = threshold as i16;
let mut changed_pixels = 0u64;
let cell_size = 64u32;
let cols = (w + cell_size - 1) / cell_size;
let rows = (h + cell_size - 1) / cell_size;
let mut grid = vec![false; (cols * rows) as usize];
for py in 0..h {
for px in 0..w {
let pa = a.get_pixel(px, py);
let pb = b.get_pixel(px, py);
let dr = (pa[0] as i16 - pb[0] as i16).abs();
let dg = (pa[1] as i16 - pb[1] as i16).abs();
let db = (pa[2] as i16 - pb[2] as i16).abs();
if dr > threshold || dg > threshold || db > threshold {
changed_pixels += 1;
let cx = px / cell_size;
let cy = py / cell_size;
grid[(cy * cols + cx) as usize] = true;
}
}
}
let mut regions: Vec<Value> = Vec::new();
for cy in 0..rows {
for cx in 0..cols {
if grid[(cy * cols + cx) as usize] {
regions.push(json!({
"x": cx * cell_size,
"y": cy * cell_size,
"width": cell_size.min(w - cx * cell_size),
"height": cell_size.min(h - cy * cell_size),
"center_x": cx * cell_size + cell_size / 2,
"center_y": cy * cell_size + cell_size / 2,
}));
}
}
}
(changed_pixels, regions)
}
pub async fn process(args: Value) -> anyhow::Result<Value> {
let command = args["command"].as_str().context("Missing 'command'")?;
let cmd_args: Vec<String> = args["args"]
.as_array()
.map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect())
.unwrap_or_default();
let timeout_ms = args["timeout_ms"].as_u64().unwrap_or(15000);
let window_pattern = args["window_title"]
.as_str()
.map(String::from)
.unwrap_or_else(|| {
let base = command.rsplit('/').next().unwrap_or(command);
format!("(?i){}", regex::escape(base))
});
let re = regex::Regex::new(&window_pattern)
.context("Invalid window_title pattern")?;
let mut child = Command::new(command)
.args(&cmd_args)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.context(format!("Failed to launch '{}'", command))?;
let pid = child.id();
tokio::task::spawn_blocking(move || {
let _ = child.wait();
});
let start = std::time::Instant::now();
let poll_interval = tokio::time::Duration::from_millis(300);
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,
"command": command,
"pid": pid,
"window_id": format!("0x{:08x}", win.id()),
"window_title": win.title(),
"x": win.x(),
"y": win.y(),
"width": win.width(),
"height": win.height(),
"waited_ms": elapsed
}));
}
}
}
if start.elapsed().as_millis() as u64 >= timeout_ms {
return Ok(json!({
"success": false,
"command": command,
"pid": pid,
"error": format!("Window matching '{}' did not appear within {}ms", window_pattern, timeout_ms),
"waited_ms": timeout_ms
}));
}
tokio::time::sleep(poll_interval).await;
}
}