use super::ScreenModule;
use anyhow::Context;
use serde_json::{json, Value};
use std::process::Command;
pub fn tools() -> Vec<Value> {
vec![
json!({
"name": "screen_ocr",
"description": "Extract text from the screen using OCR (tesseract). Returns recognized text with word-level bounding boxes and confidence scores. Use screen_find instead if you just need to locate specific text. Requires tesseract to be installed (sudo apt install tesseract-ocr).",
"inputSchema": {
"type": "object",
"properties": {
"x": { "type": "number", "description": "Region X (default: full screen)" },
"y": { "type": "number", "description": "Region Y" },
"width": { "type": "number", "description": "Region width" },
"height": { "type": "number", "description": "Region height" },
"window_id": { "type": "string", "description": "Capture a specific window instead of screen region" },
"lang": { "type": "string", "description": "Tesseract language (default: 'eng')" }
},
"required": []
}
}),
json!({
"name": "screen_find",
"description": "Find text on screen and return clickable center coordinates for each match. This is the key tool for avoiding coordinate guessing — find a button/label by text, get its (x, y), then click there. Requires tesseract (sudo apt install tesseract-ocr).",
"inputSchema": {
"type": "object",
"properties": {
"query": { "type": "string", "description": "Text to search for (case-insensitive substring match)" },
"x": { "type": "number", "description": "Limit search to region X" },
"y": { "type": "number", "description": "Region Y" },
"width": { "type": "number", "description": "Region width" },
"height": { "type": "number", "description": "Region height" },
"window_id": { "type": "string", "description": "Search within a specific window" }
},
"required": ["query"]
}
}),
]
}
pub async fn ocr(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
let tesseract = find_tesseract()?;
let lang = args["lang"].as_str().unwrap_or("eng");
let (img_path, offset_x, offset_y) = capture_for_ocr(module, &args).await?;
let output = Command::new(&tesseract)
.args([&img_path, "stdout", "-l", lang, "--psm", "3", "tsv"])
.output()
.context("Failed to run tesseract")?;
let _ = std::fs::remove_file(&img_path);
if !output.status.success() {
return Err(anyhow::anyhow!(
"tesseract failed: {}",
String::from_utf8_lossy(&output.stderr)
));
}
let tsv = String::from_utf8_lossy(&output.stdout);
let (full_text, words) = parse_tesseract_tsv(&tsv, offset_x, offset_y);
Ok(json!({
"text": full_text,
"word_count": words.len(),
"words": words
}))
}
pub async fn find(module: &ScreenModule, args: Value) -> anyhow::Result<Value> {
let query = args["query"].as_str().context("Missing 'query' parameter")?;
let query_lower = query.to_lowercase();
let tesseract = find_tesseract()?;
let lang = args["lang"].as_str().unwrap_or("eng");
let (img_path, offset_x, offset_y) = capture_for_ocr(module, &args).await?;
let output = Command::new(&tesseract)
.args([&img_path, "stdout", "-l", lang, "--psm", "3", "tsv"])
.output()
.context("Failed to run tesseract")?;
let _ = std::fs::remove_file(&img_path);
if !output.status.success() {
return Err(anyhow::anyhow!("tesseract failed: {}", String::from_utf8_lossy(&output.stderr)));
}
let tsv = String::from_utf8_lossy(&output.stdout);
let (_full_text, words) = parse_tesseract_tsv(&tsv, offset_x, offset_y);
let mut matches: Vec<Value> = Vec::new();
for w in &words {
let text = w["text"].as_str().unwrap_or("");
if text.to_lowercase().contains(&query_lower) {
let x = w["x"].as_i64().unwrap_or(0);
let y = w["y"].as_i64().unwrap_or(0);
let width = w["width"].as_i64().unwrap_or(0);
let height = w["height"].as_i64().unwrap_or(0);
matches.push(json!({
"text": text,
"x": x,
"y": y,
"width": width,
"height": height,
"center_x": x + width / 2,
"center_y": y + height / 2,
"confidence": w["confidence"]
}));
}
}
if query.contains(' ') {
let query_words: Vec<&str> = query.split_whitespace().collect();
for i in 0..words.len().saturating_sub(query_words.len() - 1) {
let mut concat = String::new();
let mut last_idx = i;
for j in 0..query_words.len() {
if i + j >= words.len() { break; }
let wtext = words[i + j]["text"].as_str().unwrap_or("");
if !concat.is_empty() { concat.push(' '); }
concat.push_str(wtext);
last_idx = i + j;
}
if concat.to_lowercase().contains(&query_lower) {
let x1 = words[i]["x"].as_i64().unwrap_or(0);
let y1 = words[i]["y"].as_i64().unwrap_or(0);
let x2 = words[last_idx]["x"].as_i64().unwrap_or(0)
+ words[last_idx]["width"].as_i64().unwrap_or(0);
let y2 = words[last_idx]["y"].as_i64().unwrap_or(0)
+ words[last_idx]["height"].as_i64().unwrap_or(0);
matches.push(json!({
"text": concat,
"x": x1,
"y": y1,
"width": x2 - x1,
"height": y2 - y1,
"center_x": (x1 + x2) / 2,
"center_y": (y1 + y2) / 2,
"multi_word": true
}));
}
}
}
Ok(json!({
"query": query,
"match_count": matches.len(),
"matches": matches
}))
}
fn find_tesseract() -> anyhow::Result<String> {
let output = Command::new("which").arg("tesseract").output();
match output {
Ok(o) if o.status.success() => {
Ok(String::from_utf8_lossy(&o.stdout).trim().to_string())
}
_ => Err(anyhow::anyhow!(
"tesseract is not installed. Install with: sudo apt install tesseract-ocr"
)),
}
}
async fn capture_for_ocr(module: &ScreenModule, args: &Value) -> anyhow::Result<(String, i64, i64)> {
let tmp = super::shm_temp_path("ocr", "png");
#[allow(unused_assignments)]
let mut offset_x: i64 = 0;
#[allow(unused_assignments)]
let mut offset_y: i64 = 0;
if let Some(window_id) = args["window_id"].as_str() {
let windows = xcap::Window::all().context("Failed to enumerate windows")?;
let target_id: u32 = if window_id.starts_with("0x") {
u32::from_str_radix(&window_id[2..], 16).context("Invalid hex window ID")?
} else {
window_id.parse().context("Invalid window ID")?
};
for win in &windows {
if win.id() == target_id {
let img = win.capture_image().context("Failed to capture window")?;
img.save(&tmp).context("Failed to save capture")?;
offset_x = win.x() as i64;
offset_y = win.y() as i64;
return Ok((tmp, offset_x, offset_y));
}
}
return Err(anyhow::anyhow!("Window not found: {}", window_id));
}
let has_region = args["x"].as_i64().is_some();
if has_region {
let x = args["x"].as_i64().unwrap_or(0);
let y = args["y"].as_i64().unwrap_or(0);
let w = args["width"].as_i64().context("Missing 'width'")?;
let h = args["height"].as_i64().context("Missing 'height'")?;
offset_x = x;
offset_y = y;
if let Some(ref scrot) = module.scrot_path {
let area = format!("{},{},{},{}", x, y, w, h);
let output = Command::new(scrot).args(["-a", &area, "-o", &tmp]).output();
if let Ok(o) = output {
if o.status.success() {
return Ok((tmp, offset_x, offset_y));
}
}
}
if let Some(ref scrot) = module.scrot_path {
let full_tmp = super::shm_temp_path("ocr_full", "png");
let _ = Command::new(scrot).args(["-o", &full_tmp]).output();
if let Ok(img) = image::open(&full_tmp) {
let cropped = img.crop_imm(x as u32, y as u32, w as u32, h as u32);
cropped.save(&tmp).context("Failed to save cropped")?;
let _ = std::fs::remove_file(&full_tmp);
return Ok((tmp, offset_x, offset_y));
}
let _ = std::fs::remove_file(&full_tmp);
}
}
if let Some(ref scrot) = module.scrot_path {
let output = Command::new(scrot).args(["-o", &tmp]).output();
if let Ok(o) = output {
if o.status.success() {
return Ok((tmp, 0, 0));
}
}
}
let monitors = xcap::Monitor::all().context("Failed to enumerate monitors")?;
let monitor = monitors.first().context("No monitors found")?;
let img = monitor.capture_image().context("Failed to capture screen")?;
img.save(&tmp).context("Failed to save capture")?;
Ok((tmp, 0, 0))
}
fn parse_tesseract_tsv(tsv: &str, offset_x: i64, offset_y: i64) -> (String, Vec<Value>) {
let mut words = Vec::new();
let mut full_text = String::new();
let mut last_line_num = -1i64;
for line in tsv.lines().skip(1) {
let cols: Vec<&str> = line.split('\t').collect();
if cols.len() < 12 {
continue;
}
let conf: f64 = cols[10].parse().unwrap_or(-1.0);
let text = cols[11].trim();
if text.is_empty() || conf < 0.0 {
continue;
}
let left: i64 = cols[6].parse().unwrap_or(0) + offset_x;
let top: i64 = cols[7].parse().unwrap_or(0) + offset_y;
let width: i64 = cols[8].parse().unwrap_or(0);
let height: i64 = cols[9].parse().unwrap_or(0);
let line_num: i64 = cols[4].parse().unwrap_or(0);
if line_num != last_line_num && !full_text.is_empty() {
full_text.push('\n');
} else if !full_text.is_empty() {
full_text.push(' ');
}
full_text.push_str(text);
last_line_num = line_num;
words.push(json!({
"text": text,
"x": left,
"y": top,
"width": width,
"height": height,
"confidence": conf,
}));
}
(full_text, words)
}