|
1 | 1 | use anyhow::{Context, Result}; |
2 | | - |
3 | | -use crate::platform; |
| 2 | +use xa11y::{App, AppExt, Role}; |
4 | 3 |
|
5 | 4 | pub fn run_screenshot(output_path: &str, scale: f64, app: Option<&str>, pid: Option<u32>) -> Result<()> { |
6 | | - if app.is_some() || pid.is_some() { |
7 | | - platform::take_screenshot_window(output_path, app, pid)?; |
| 5 | + let shot = if app.is_some() || pid.is_some() { |
| 6 | + let xa_app = match (pid, app) { |
| 7 | + (Some(p), _) => App::by_pid(p).map_err(|e| anyhow::anyhow!("{}", e))?, |
| 8 | + (None, Some(name)) => App::by_name(name).map_err(|e| anyhow::anyhow!("{}", e))?, |
| 9 | + _ => unreachable!(), |
| 10 | + }; |
| 11 | + let window = xa_app |
| 12 | + .children() |
| 13 | + .map_err(|e| anyhow::anyhow!("{}", e))? |
| 14 | + .into_iter() |
| 15 | + .find(|e| matches!(e.data().role, Role::Window)) |
| 16 | + .ok_or_else(|| anyhow::anyhow!("No window found for the specified app"))?; |
| 17 | + xa11y::screenshot_element(&window) |
| 18 | + .map_err(|e| anyhow::anyhow!("Screenshot failed: {}", e))? |
8 | 19 | } else { |
9 | | - platform::take_screenshot(output_path)?; |
10 | | - } |
| 20 | + xa11y::screenshot().map_err(|e| anyhow::anyhow!("Screenshot failed: {}", e))? |
| 21 | + }; |
11 | 22 |
|
12 | 23 | if (scale - 1.0).abs() > 1e-9 { |
13 | | - let img = image::open(output_path).context("Failed to open captured screenshot")?; |
14 | | - let (w, h) = (img.width(), img.height()); |
15 | | - let new_w = (w as f64 * scale) as u32; |
16 | | - let new_h = (h as f64 * scale) as u32; |
17 | | - let resized = img.resize_exact(new_w, new_h, image::imageops::FilterType::Lanczos3); |
18 | | - resized |
| 24 | + let rgba = image::RgbaImage::from_raw(shot.width, shot.height, shot.pixels) |
| 25 | + .ok_or_else(|| anyhow::anyhow!("Invalid screenshot pixel data"))?; |
| 26 | + let new_w = ((shot.width as f64) * scale) as u32; |
| 27 | + let new_h = ((shot.height as f64) * scale) as u32; |
| 28 | + image::DynamicImage::ImageRgba8(rgba) |
| 29 | + .resize_exact(new_w, new_h, image::imageops::FilterType::Lanczos3) |
19 | 30 | .save(output_path) |
20 | 31 | .context("Failed to save scaled screenshot")?; |
| 32 | + } else { |
| 33 | + shot.save_png(output_path) |
| 34 | + .map_err(|e| anyhow::anyhow!("Failed to save screenshot: {}", e))?; |
21 | 35 | } |
22 | 36 |
|
23 | 37 | println!("Screenshot saved to {}", output_path); |
|
0 commit comments