Skip to main content

computer_use_linux/
screenshot.rs

1use crate::diagnostics::hydrate_session_bus_env;
2use crate::x11_display::{is_native_x11_session, with_x11_display, X11_CAPTURE_TIMEOUT};
3use anyhow::{anyhow, bail, Context, Result};
4use base64::{engine::general_purpose::STANDARD, Engine};
5use futures_util::StreamExt;
6use image::codecs::jpeg::JpegEncoder;
7use image::imageops::FilterType;
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10use std::{
11    collections::{HashMap, HashSet},
12    fs::{self, File, OpenOptions},
13    io::{Cursor, Read},
14    os::unix::fs::{MetadataExt, OpenOptionsExt},
15    path::{Path, PathBuf},
16    process::Stdio,
17    time::{Duration, SystemTime, UNIX_EPOCH},
18};
19use tokio::process::Command;
20use zbus::{
21    message::{Message, Type as MessageType},
22    names::{BusName, OwnedUniqueName, WellKnownName},
23    zvariant::{OwnedObjectPath, OwnedValue, Value},
24    MatchRule, MessageStream, Proxy,
25};
26
27const PORTAL_DESKTOP_SERVICE: &str = "org.freedesktop.portal.Desktop";
28const PORTAL_DESKTOP_PATH: &str = "/org/freedesktop/portal/desktop";
29const PORTAL_SCREENSHOT_INTERFACE: &str = "org.freedesktop.portal.Screenshot";
30const PORTAL_REQUEST_INTERFACE: &str = "org.freedesktop.portal.Request";
31const PORTAL_REQUEST_PATH_NAMESPACE: &str = "/org/freedesktop/portal/desktop/request";
32const MAX_SCREENSHOT_SOURCE_BYTES: u64 = 64 * 1024 * 1024;
33const MAX_SCREENSHOT_SOURCE_PIXELS: u64 = 128 * 1024 * 1024;
34
35pub const DEFAULT_SCREENSHOT_MAX_DIMENSION: u32 = 1920;
36pub const DEFAULT_SCREENSHOT_MAX_BYTES: usize = 2 * 1024 * 1024;
37pub const ABSOLUTE_SCREENSHOT_MAX_DIMENSION: u32 = 4096;
38pub const ABSOLUTE_SCREENSHOT_MAX_BYTES: usize = 4 * 1024 * 1024;
39pub const DEFAULT_SCREENSHOT_JPEG_QUALITY: u8 = 80;
40pub const MIN_SCREENSHOT_JPEG_QUALITY: u8 = 1;
41pub const MAX_SCREENSHOT_JPEG_QUALITY: u8 = 95;
42const MIN_SCREENSHOT_MAX_BYTES: usize = 1024;
43
44#[derive(Debug, Clone)]
45pub struct RawScreenshotCapture {
46    pub mime_type: String,
47    pub bytes: Vec<u8>,
48    pub source: String,
49    pub width: u32,
50    pub height: u32,
51}
52
53#[derive(Debug, Clone, Serialize, JsonSchema)]
54pub struct ScreenshotCapture {
55    pub mime_type: String,
56    pub data_url: String,
57    pub source: String,
58    /// Width of the returned image payload.
59    pub width: u32,
60    /// Height of the returned image payload.
61    pub height: u32,
62    /// Coordinate-space width before payload downscaling.
63    pub coordinate_width: u32,
64    /// Coordinate-space height before payload downscaling.
65    pub coordinate_height: u32,
66    /// Returned pixels per coordinate-space pixel.
67    pub scale: f32,
68    pub resized: bool,
69    pub bytes: usize,
70    pub original_bytes: usize,
71    pub max_bytes: usize,
72    pub format: ScreenshotOutputFormat,
73    pub quality: Option<u8>,
74}
75
76#[derive(Debug, Clone, Copy, Default)]
77pub struct ScreenshotPayloadOptions {
78    pub max_width: Option<u32>,
79    pub max_height: Option<u32>,
80    pub max_bytes: Option<usize>,
81    pub scale: Option<f32>,
82    pub format: Option<ScreenshotOutputFormat>,
83    pub quality: Option<u8>,
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
87#[serde(rename_all = "lowercase")]
88pub enum ScreenshotOutputFormat {
89    Png,
90    Jpeg,
91}
92
93impl ScreenshotOutputFormat {
94    fn mime_type(self) -> &'static str {
95        match self {
96            Self::Png => "image/png",
97            Self::Jpeg => "image/jpeg",
98        }
99    }
100}
101
102#[derive(Debug, Clone, Copy)]
103struct ResolvedScreenshotPayloadOptions {
104    max_width: u32,
105    max_height: u32,
106    max_bytes: usize,
107    scale: f32,
108    format: ScreenshotOutputFormat,
109    quality: u8,
110}
111
112#[derive(Debug)]
113struct PortalScreenshotRequest {
114    requested_at: SystemTime,
115    pictures: Option<PortalPicturesSnapshot>,
116}
117
118#[derive(Debug)]
119struct PortalPicturesSnapshot {
120    path: PathBuf,
121    directory: File,
122    names: HashSet<std::ffi::OsString>,
123}
124
125impl PortalPicturesSnapshot {
126    fn new(path: PathBuf) -> std::io::Result<Self> {
127        let path = fs::canonicalize(path)?;
128        let directory = File::open(&path)?;
129        let names = fs::read_dir(&path)?
130            .map(|entry| entry.map(|entry| entry.file_name()))
131            .collect::<std::io::Result<HashSet<_>>>()?;
132        Ok(Self {
133            path,
134            directory,
135            names,
136        })
137    }
138
139    fn contains_new_path(&self, path: &Path) -> bool {
140        if path.parent() != Some(self.path.as_path()) {
141            return false;
142        }
143        let same_directory = self
144            .directory
145            .metadata()
146            .ok()
147            .zip(fs::metadata(&self.path).ok())
148            .is_some_and(|(before, current)| {
149                (before.dev(), before.ino()) == (current.dev(), current.ino())
150            });
151        same_directory
152            && path
153                .file_name()
154                .is_some_and(|name| !self.names.contains(name))
155    }
156}
157
158#[derive(Debug)]
159enum ScreenshotCleanup {
160    DeletePath(PathBuf),
161    #[cfg(test)]
162    Preserve,
163    PortalPath {
164        path: PathBuf,
165        request: PortalScreenshotRequest,
166    },
167}
168
169struct OwnedScreenshotCleanup {
170    strategy: Option<ScreenshotCleanup>,
171    portal_file: Option<File>,
172}
173
174impl OwnedScreenshotCleanup {
175    fn new(strategy: ScreenshotCleanup) -> Self {
176        let portal_file = match &strategy {
177            ScreenshotCleanup::PortalPath { path, request } => OpenOptions::new()
178                .read(true)
179                .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
180                .open(path)
181                .ok()
182                .filter(|file| {
183                    file.metadata().is_ok_and(|metadata| {
184                        if !metadata.is_file() || metadata.uid() != unsafe { libc::geteuid() } {
185                            return false;
186                        }
187                        if let Some(pictures) = &request.pictures {
188                            if path.parent() == Some(pictures.path.as_path()) {
189                                return pictures.contains_new_path(path);
190                            }
191                        }
192                        // Unknown locations need proof of creation after the request.
193                        // Missing birth times preserve the file.
194                        metadata
195                            .created()
196                            .is_ok_and(|created| created >= request.requested_at)
197                    })
198                }),
199            _ => None,
200        };
201        Self {
202            strategy: Some(strategy),
203            portal_file,
204        }
205    }
206}
207
208impl OwnedScreenshotCleanup {
209    fn cleanup_now(&mut self) {
210        if let Some(strategy) = self.strategy.take() {
211            cleanup_screenshot_path(strategy, self.portal_file.take());
212        }
213    }
214}
215
216impl Drop for OwnedScreenshotCleanup {
217    fn drop(&mut self) {
218        let Some(strategy) = self.strategy.take() else {
219            return;
220        };
221        let portal_file = self.portal_file.take();
222        if matches!(strategy, ScreenshotCleanup::PortalPath { .. }) {
223            if let Ok(runtime) = tokio::runtime::Handle::try_current() {
224                // A queued read can be cancelled on the single-thread runtime.
225                // Keep the pinned file alive and unlink on a blocking worker.
226                runtime.spawn_blocking(move || cleanup_screenshot_path(strategy, portal_file));
227                return;
228            }
229        }
230        cleanup_screenshot_path(strategy, portal_file);
231    }
232}
233
234fn cleanup_screenshot_path(strategy: ScreenshotCleanup, portal_file: Option<File>) {
235    let path = match &strategy {
236        ScreenshotCleanup::DeletePath(path) => Some(path),
237        ScreenshotCleanup::PortalPath { path, .. } => portal_file.as_ref().and_then(|file| {
238            file.metadata()
239                .ok()
240                .zip(fs::symlink_metadata(path).ok())
241                .filter(|(original, current)| {
242                    current.file_type().is_file()
243                        && (original.dev(), original.ino()) == (current.dev(), current.ino())
244                })
245                .map(|_| path)
246        }),
247        #[cfg(test)]
248        ScreenshotCleanup::Preserve => None,
249    };
250    if let Some(path) = path {
251        if let Err(error) = fs::remove_file(path) {
252            if error.kind() != std::io::ErrorKind::NotFound {
253                eprintln!("Failed to remove screenshot capture file: {error}");
254            }
255        }
256    }
257}
258
259impl ScreenshotPayloadOptions {
260    fn resolve(self) -> ResolvedScreenshotPayloadOptions {
261        let max_width = self
262            .max_width
263            .unwrap_or(DEFAULT_SCREENSHOT_MAX_DIMENSION)
264            .clamp(1, ABSOLUTE_SCREENSHOT_MAX_DIMENSION);
265        let max_height = self
266            .max_height
267            .unwrap_or(DEFAULT_SCREENSHOT_MAX_DIMENSION)
268            .clamp(1, ABSOLUTE_SCREENSHOT_MAX_DIMENSION);
269        let max_bytes = self
270            .max_bytes
271            .unwrap_or(DEFAULT_SCREENSHOT_MAX_BYTES)
272            .clamp(MIN_SCREENSHOT_MAX_BYTES, ABSOLUTE_SCREENSHOT_MAX_BYTES);
273        let scale = self
274            .scale
275            .filter(|value| value.is_finite() && *value > 0.0)
276            .unwrap_or(1.0)
277            .min(1.0);
278        let format = self.format.unwrap_or(ScreenshotOutputFormat::Png);
279        let quality = self
280            .quality
281            .unwrap_or(DEFAULT_SCREENSHOT_JPEG_QUALITY)
282            .clamp(MIN_SCREENSHOT_JPEG_QUALITY, MAX_SCREENSHOT_JPEG_QUALITY);
283
284        ResolvedScreenshotPayloadOptions {
285            max_width,
286            max_height,
287            max_bytes,
288            scale,
289            format,
290            quality,
291        }
292    }
293}
294
295/// Environment variable forcing a single capture backend, skipping the
296/// fallback chain. Accepts `gnome-shell`, `portal`, `x11`, or `gnome-screenshot`.
297const SCREENSHOT_BACKEND_ENV: &str = "COMPUTER_USE_LINUX_SCREENSHOT_BACKEND";
298
299#[derive(Debug, Clone, Copy, PartialEq, Eq)]
300enum ScreenshotBackend {
301    GnomeShell,
302    Portal,
303    X11,
304    GnomeScreenshot,
305}
306
307impl ScreenshotBackend {
308    fn parse(value: &str) -> Option<Self> {
309        match value.trim().to_ascii_lowercase().as_str() {
310            "gnome-shell" | "gnome_shell" | "shell" => Some(Self::GnomeShell),
311            "portal" | "xdg-portal" | "xdg_portal" => Some(Self::Portal),
312            "x11" | "x11-native" | "x11_native" | "xgetimage" => Some(Self::X11),
313            "gnome-screenshot" | "gnome_screenshot" => Some(Self::GnomeScreenshot),
314            _ => None,
315        }
316    }
317
318    async fn capture(self) -> Result<RawScreenshotCapture> {
319        match self {
320            Self::GnomeShell => capture_with_gnome_shell().await,
321            Self::Portal => capture_with_portal().await,
322            Self::X11 => capture_with_x11().await,
323            Self::GnomeScreenshot => capture_with_gnome_screenshot().await,
324        }
325    }
326}
327
328pub async fn capture_screenshot_raw() -> Result<RawScreenshotCapture> {
329    hydrate_session_bus_env();
330
331    // Explicit override: use exactly the requested backend, no fallback. Lets
332    // background/systemd contexts pin `gnome-screenshot` when the DBus paths are
333    // blocked, and aids debugging.
334    if let Some(forced) = forced_backend()? {
335        return forced.capture().await;
336    }
337
338    // The Shell and portal DBus paths can fail for background processes (systemd
339    // user services, non-interactive parent shells): GNOME Shell's
340    // DBusSenderChecker rejects unknown bus names, and a portal consent dialog
341    // may be denied when the caller is not the focused app. Response code 2
342    // can also indicate other portal failures. `gnome-screenshot` claims an
343    // allowlisted bus name, so try it as the final fallback. See issue #20.
344    let gnome_error = match capture_with_gnome_shell().await {
345        Ok(capture) => return Ok(capture),
346        Err(error) => error,
347    };
348    let portal_error = match capture_with_portal().await {
349        Ok(capture) => return Ok(capture),
350        Err(error) => error,
351    };
352    // Native X11 only, and ahead of gnome-screenshot: gnome-screenshot 41 masks
353    // everything outside the GDK monitor geometry, which is 1/4 of the frame at
354    // window-scaling-factor 2 on MATE (issue #155). GetImage has no GDK layer.
355    let x11_error = match capture_with_x11().await {
356        Ok(capture) => return Ok(capture),
357        Err(error) => error,
358    };
359    let cli_error = match capture_with_gnome_screenshot().await {
360        Ok(capture) => return Ok(capture),
361        Err(error) => error,
362    };
363
364    Err(anyhow!(
365        "GNOME Shell screenshot failed: {gnome_error:#}; \
366         XDG portal screenshot failed: {portal_error:#}; \
367         native X11 screenshot failed: {x11_error:#}; \
368         gnome-screenshot fallback failed: {cli_error:#}"
369    ))
370}
371
372/// `GetImage` on the root window of a native X11 session. Pixels are device
373/// pixels, the space xdotool/XTEST input and X11 window origins use.
374async fn capture_with_x11() -> Result<RawScreenshotCapture> {
375    if !is_native_x11_session() {
376        bail!("not a native X11 session (needs DISPLAY on an X11, not Wayland, session)");
377    }
378    let image = with_x11_display(X11_CAPTURE_TIMEOUT, |display| display.capture_root()).await??;
379    let (width, height) = (image.width, image.height);
380    let bytes =
381        tokio::task::spawn_blocking(move || encode_rgb_png(image.width, image.height, image.rgb))
382            .await
383            .context("X11 screenshot encoder task failed")??;
384    Ok(RawScreenshotCapture {
385        mime_type: "image/png".to_string(),
386        bytes,
387        source: "x11".to_string(),
388        width,
389        height,
390    })
391}
392
393fn encode_rgb_png(width: u32, height: u32, rgb: Vec<u8>) -> Result<Vec<u8>> {
394    let buffer = image::RgbImage::from_raw(width, height, rgb)
395        .context("X11 root image did not match its dimensions")?;
396    let mut out = Vec::new();
397    image::DynamicImage::ImageRgb8(buffer)
398        .write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png)
399        .context("failed to encode X11 screenshot PNG")?;
400    Ok(out)
401}
402
403fn forced_backend() -> Result<Option<ScreenshotBackend>> {
404    match std::env::var(SCREENSHOT_BACKEND_ENV) {
405        Ok(value) if !value.trim().is_empty() => {
406            ScreenshotBackend::parse(&value).map(Some).ok_or_else(|| {
407                anyhow!(
408                    "{SCREENSHOT_BACKEND_ENV}={value:?} is not a recognized backend \
409                     (expected gnome-shell, portal, x11, or gnome-screenshot)"
410                )
411            })
412        }
413        _ => Ok(None),
414    }
415}
416
417pub async fn capture_screenshot() -> Result<ScreenshotCapture> {
418    let _pipeline = screenshot_pipeline_permit().await?;
419    let raw = capture_screenshot_raw().await?;
420    run_image_task(move || prepare_screenshot_payload(raw, ScreenshotPayloadOptions::default()))
421        .await
422}
423
424pub(crate) async fn screenshot_pipeline_permit() -> Result<tokio::sync::SemaphorePermit<'static>> {
425    static CAPTURE_PIPELINE: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(1);
426    Ok(CAPTURE_PIPELINE.acquire().await?)
427}
428
429pub(crate) async fn run_image_task<T: Send + 'static>(
430    work: impl FnOnce() -> Result<T> + Send + 'static,
431) -> Result<T> {
432    static IMAGE_WORKER: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(1);
433    let permit = IMAGE_WORKER.acquire().await?;
434    tokio::task::spawn_blocking(move || {
435        let _permit = permit;
436        work()
437    })
438    .await
439    .context("screenshot processing task failed")?
440}
441
442pub fn prepare_screenshot_payload(
443    raw: RawScreenshotCapture,
444    options: ScreenshotPayloadOptions,
445) -> Result<ScreenshotCapture> {
446    if raw.bytes.is_empty() {
447        bail!("screenshot file was empty");
448    }
449    let (coordinate_width, coordinate_height) = png_dimensions(&raw.bytes)?;
450    let original_bytes = raw.bytes.len();
451    let options = options.resolve();
452    let (target_width, target_height) =
453        target_dimensions(coordinate_width, coordinate_height, options);
454
455    let (bytes, width, height) = if options.format == ScreenshotOutputFormat::Png
456        && target_width == coordinate_width
457        && target_height == coordinate_height
458        && original_bytes <= options.max_bytes
459    {
460        (raw.bytes, coordinate_width, coordinate_height)
461    } else {
462        encode_screenshot_to_fit_bytes(
463            &raw.bytes,
464            coordinate_width,
465            coordinate_height,
466            target_width,
467            target_height,
468            options,
469        )?
470    };
471
472    let encoded = STANDARD.encode(&bytes);
473    let scale = if coordinate_width == 0 {
474        1.0
475    } else {
476        width as f32 / coordinate_width as f32
477    };
478
479    Ok(ScreenshotCapture {
480        mime_type: options.format.mime_type().to_string(),
481        data_url: format!("data:{};base64,{encoded}", options.format.mime_type()),
482        source: raw.source,
483        width,
484        height,
485        coordinate_width,
486        coordinate_height,
487        scale,
488        resized: width != coordinate_width || height != coordinate_height,
489        bytes: bytes.len(),
490        original_bytes,
491        max_bytes: options.max_bytes,
492        format: options.format,
493        quality: (options.format == ScreenshotOutputFormat::Jpeg).then_some(options.quality),
494    })
495}
496
497async fn capture_with_gnome_shell() -> Result<RawScreenshotCapture> {
498    let connection = zbus::Connection::session()
499        .await
500        .context("failed to connect to session bus")?;
501    let proxy = Proxy::new(
502        &connection,
503        "org.gnome.Shell.Screenshot",
504        "/org/gnome/Shell/Screenshot",
505        "org.gnome.Shell.Screenshot",
506    )
507    .await
508    .context("failed to create GNOME Shell screenshot proxy")?;
509    let path = temp_png_path("gnome-shell");
510    let filename = path
511        .to_str()
512        .context("temporary screenshot path is not valid UTF-8")?;
513    let result = proxy.call("Screenshot", &(false, false, filename)).await;
514    let (success, filename_used): (bool, String) = match result {
515        Ok(result) => result,
516        Err(error) => {
517            cleanup_gnome_requested_path(&path);
518            return Err(error).context("GNOME Shell Screenshot call failed");
519        }
520    };
521
522    if !success {
523        cleanup_gnome_requested_path(&path);
524        bail!("GNOME Shell reported screenshot failure");
525    }
526
527    read_png_as_capture(
528        PathBuf::from(filename_used),
529        "gnome-shell",
530        ScreenshotCleanup::DeletePath(path),
531    )
532    .await
533}
534
535async fn capture_with_portal() -> Result<RawScreenshotCapture> {
536    let connection = zbus::Connection::session()
537        .await
538        .context("failed to connect to session bus")?;
539    let portal_owner = portal_desktop_owner(&connection).await?;
540    let token = request_token();
541    // Some portals rewrite the request handle, so subscribe before calling Screenshot
542    // and filter by the returned handle instead of subscribing after the call.
543    let mut response_stream = portal_response_stream(&connection, &portal_owner).await?;
544
545    let portal_proxy = Proxy::new(
546        &connection,
547        portal_owner.clone(),
548        PORTAL_DESKTOP_PATH,
549        PORTAL_SCREENSHOT_INTERFACE,
550    )
551    .await
552    .context("failed to create XDG portal screenshot proxy")?;
553    let mut options: HashMap<&str, Value<'_>> = HashMap::new();
554    options.insert("handle_token", Value::from(token.as_str()));
555    options.insert("interactive", Value::from(false));
556    let mut pictures_command = Command::new("xdg-user-dir");
557    pictures_command.arg("PICTURES");
558    let pictures = crate::command_runner::output(pictures_command, "locate Pictures directory")
559        .await
560        .ok()
561        .filter(|output| output.status.success())
562        .and_then(|output| String::from_utf8(output.stdout).ok())
563        .map(|path| PathBuf::from(path.trim_end_matches('\n')))
564        .filter(|path| path.is_absolute());
565    let pictures = match pictures {
566        // Match the command helper's one-second metadata budget. A stalled
567        // Pictures mount must not prevent the portal request from starting.
568        Some(path) => match tokio::time::timeout(
569            Duration::from_secs(1),
570            tokio::task::spawn_blocking(move || PortalPicturesSnapshot::new(path)),
571        )
572        .await
573        {
574            Ok(Ok(Ok(snapshot))) => Some(snapshot),
575            _ => None,
576        },
577        None => None,
578    };
579    let request = PortalScreenshotRequest {
580        requested_at: SystemTime::now(),
581        pictures,
582    };
583    let handle: OwnedObjectPath = portal_proxy
584        .call("Screenshot", &("", options))
585        .await
586        .context("XDG portal Screenshot call failed")?;
587
588    let (response_code, results) = tokio::time::timeout(
589        Duration::from_secs(20),
590        wait_for_portal_response(&mut response_stream, handle.as_str(), portal_owner.as_str()),
591    )
592    .await
593    .context("timed out waiting for XDG portal screenshot response")??;
594
595    match response_code {
596        0 => {}
597        1 => bail!("XDG portal screenshot was cancelled by the user (response code 1)"),
598        2 => bail!(
599            "XDG portal screenshot ended without success (response code 2); \
600             check the desktop portal logs for permission or backend errors"
601        ),
602        _ => bail!("XDG portal screenshot returned unknown response code {response_code}"),
603    }
604
605    let uri_value = results
606        .get("uri")
607        .context("XDG portal screenshot response did not include a uri")?;
608    let uri: String = uri_value
609        .try_clone()
610        .context("failed to clone XDG portal screenshot uri")?
611        .try_into()
612        .context("XDG portal screenshot uri was not a string")?;
613    let path = file_uri_to_path(&uri)?;
614
615    read_portal_png_as_capture(path, request).await
616}
617
618async fn read_portal_png_as_capture(
619    path: PathBuf,
620    request: PortalScreenshotRequest,
621) -> Result<RawScreenshotCapture> {
622    // Portal URIs can reference user files. Snapshot names before requesting
623    // capture, and pin the returned file until cleanup to prevent inode reuse.
624    let cleanup = ScreenshotCleanup::PortalPath {
625        path: path.clone(),
626        request,
627    };
628    read_png_as_capture(path, "xdg-desktop-portal", cleanup).await
629}
630
631/// Upper bound on how long we wait for `gnome-screenshot` before killing it.
632/// Matches the portal timeout: a hung capture must not block the tool forever.
633const GNOME_SCREENSHOT_TIMEOUT: Duration = Duration::from_secs(20);
634
635async fn capture_with_gnome_screenshot() -> Result<RawScreenshotCapture> {
636    let path = temp_png_path("gnome-screenshot");
637    let filename = path
638        .to_str()
639        .context("temporary screenshot path is not valid UTF-8")?;
640
641    // `-f <file>` writes a full-screen PNG without prompting; no portal, no
642    // foreground window required. `tokio::process::Command` searches PATH and
643    // provides an async, non-polling wait.
644    let mut command = Command::new("gnome-screenshot");
645    command
646        .args(["-f", filename])
647        .stdin(Stdio::null())
648        .stdout(Stdio::null())
649        .stderr(Stdio::null());
650    let mut child = match crate::command_runner::spawn_retrying_busy(&mut command).await {
651        Ok(child) => child,
652        Err(error) => {
653            cleanup_gnome_requested_path(&path);
654            return Err(error).context("failed to spawn gnome-screenshot");
655        }
656    };
657
658    // A hung capture must not block the tool forever, so bound the wait and
659    // kill the child if it outlives the deadline.
660    let status = match tokio::time::timeout(GNOME_SCREENSHOT_TIMEOUT, child.wait()).await {
661        Ok(Ok(status)) => status,
662        Ok(Err(error)) => {
663            cleanup_gnome_requested_path(&path);
664            return Err(error).context("failed to wait for gnome-screenshot");
665        }
666        Err(_) => {
667            let _ = child.kill().await;
668            cleanup_gnome_requested_path(&path);
669            bail!("gnome-screenshot timed out");
670        }
671    };
672
673    if !status.success() {
674        cleanup_gnome_requested_path(&path);
675        bail!("gnome-screenshot exited with {status}");
676    }
677
678    read_png_as_capture(
679        path.clone(),
680        "gnome-screenshot",
681        ScreenshotCleanup::DeletePath(path),
682    )
683    .await
684}
685
686async fn portal_desktop_owner(connection: &zbus::Connection) -> Result<OwnedUniqueName> {
687    let dbus = zbus::fdo::DBusProxy::new(connection)
688        .await
689        .context("failed to create session-bus identity proxy")?;
690    let _: u32 = dbus
691        .start_service_by_name(WellKnownName::try_from(PORTAL_DESKTOP_SERVICE)?, 0)
692        .await
693        .context("failed to activate the XDG desktop portal")?;
694    dbus.get_name_owner(BusName::try_from(PORTAL_DESKTOP_SERVICE)?)
695        .await
696        .context("failed to resolve the XDG desktop portal owner")
697}
698
699async fn portal_response_stream(
700    connection: &zbus::Connection,
701    portal_owner: &OwnedUniqueName,
702) -> Result<MessageStream> {
703    let response_rule = MatchRule::builder()
704        .msg_type(MessageType::Signal)
705        .sender(portal_owner.clone())?
706        .interface(PORTAL_REQUEST_INTERFACE)?
707        .member("Response")?
708        .path_namespace(PORTAL_REQUEST_PATH_NAMESPACE)?
709        .build();
710
711    MessageStream::for_match_rule(response_rule, connection, None)
712        .await
713        .context("failed to subscribe to XDG portal screenshot responses")
714}
715
716async fn wait_for_portal_response(
717    response_stream: &mut MessageStream,
718    request_path: &str,
719    portal_owner: &str,
720) -> Result<(u32, HashMap<String, OwnedValue>)> {
721    loop {
722        let response = response_stream
723            .next()
724            .await
725            .context("XDG portal screenshot response stream ended")?
726            .context("XDG portal screenshot response stream failed")?;
727
728        if !portal_response_matches(&response, request_path, portal_owner) {
729            continue;
730        }
731
732        return response
733            .body()
734            .deserialize()
735            .context("failed to decode XDG portal screenshot response");
736    }
737}
738
739fn portal_response_matches(response: &Message, request_path: &str, portal_owner: &str) -> bool {
740    let header = response.header();
741    header
742        .sender()
743        .is_some_and(|sender| sender.as_str() == portal_owner)
744        && header
745            .path()
746            .is_some_and(|path| path.as_str() == request_path)
747}
748
749async fn read_png_as_capture(
750    path: PathBuf,
751    source: &str,
752    cleanup: ScreenshotCleanup,
753) -> Result<RawScreenshotCapture> {
754    let source = source.to_string();
755    let (path, mut cleanup) = if matches!(cleanup, ScreenshotCleanup::PortalPath { .. }) {
756        tokio::time::timeout(
757            Duration::from_secs(1),
758            tokio::task::spawn_blocking(move || {
759                // Resolve parent aliases without following the final symlink.
760                let path = path
761                    .parent()
762                    .and_then(|parent| fs::canonicalize(parent).ok())
763                    .zip(path.file_name())
764                    .map(|(parent, name)| parent.join(name))
765                    .unwrap_or(path);
766                let cleanup = match cleanup {
767                    ScreenshotCleanup::PortalPath { request, .. } => {
768                        ScreenshotCleanup::PortalPath {
769                            path: path.clone(),
770                            request,
771                        }
772                    }
773                    other => other,
774                };
775                (path, OwnedScreenshotCleanup::new(cleanup))
776            }),
777        )
778        .await
779        .context("timed out preparing portal screenshot file")?
780        .context("portal screenshot preparation task failed")?
781    } else {
782        (path, OwnedScreenshotCleanup::new(cleanup))
783    };
784    run_image_task(move || {
785        let result = read_png_as_capture_inner(&path, &source);
786        cleanup.cleanup_now();
787        result
788    })
789    .await
790}
791
792fn read_png_as_capture_inner(path: &Path, source: &str) -> Result<RawScreenshotCapture> {
793    let file = OpenOptions::new()
794        .read(true)
795        .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
796        .open(path)
797        .with_context(|| format!("failed to open screenshot file {}", path.display()))?;
798    let metadata = file
799        .metadata()
800        .with_context(|| format!("failed to inspect screenshot file {}", path.display()))?;
801    if !metadata.file_type().is_file() {
802        bail!("screenshot path is not a regular file: {}", path.display());
803    }
804    if metadata.len() > MAX_SCREENSHOT_SOURCE_BYTES {
805        bail!(
806            "screenshot file is {} bytes, over the {}-byte source limit",
807            metadata.len(),
808            MAX_SCREENSHOT_SOURCE_BYTES
809        );
810    }
811    let mut bytes = Vec::with_capacity(metadata.len() as usize);
812    file.take(MAX_SCREENSHOT_SOURCE_BYTES + 1)
813        .read_to_end(&mut bytes)
814        .with_context(|| format!("failed to read screenshot file {}", path.display()))?;
815    if bytes.len() as u64 > MAX_SCREENSHOT_SOURCE_BYTES {
816        bail!(
817            "screenshot file grew beyond the {}-byte source limit",
818            MAX_SCREENSHOT_SOURCE_BYTES
819        );
820    }
821    if bytes.is_empty() {
822        bail!("screenshot file was empty: {}", path.display());
823    }
824    let (width, height) = png_dimensions(&bytes)?;
825    Ok(RawScreenshotCapture {
826        mime_type: "image/png".to_string(),
827        bytes,
828        source: source.to_string(),
829        width,
830        height,
831    })
832}
833
834fn target_dimensions(
835    width: u32,
836    height: u32,
837    options: ResolvedScreenshotPayloadOptions,
838) -> (u32, u32) {
839    let width_scale = options.max_width as f64 / width as f64;
840    let height_scale = options.max_height as f64 / height as f64;
841    let scale = f64::from(options.scale)
842        .min(width_scale)
843        .min(height_scale)
844        .min(1.0);
845
846    let target_width = ((width as f64 * scale).round() as u32).clamp(1, width);
847    let target_height = ((height as f64 * scale).round() as u32).clamp(1, height);
848    (target_width, target_height)
849}
850
851fn encode_screenshot_to_fit_bytes(
852    raw: &[u8],
853    original_width: u32,
854    original_height: u32,
855    mut target_width: u32,
856    mut target_height: u32,
857    options: ResolvedScreenshotPayloadOptions,
858) -> Result<(Vec<u8>, u32, u32)> {
859    let img = image::load_from_memory_with_format(raw, image::ImageFormat::Png)
860        .context("failed to decode screenshot PNG for encoding")?;
861
862    loop {
863        let bytes = if options.format == ScreenshotOutputFormat::Png
864            && target_width == original_width
865            && target_height == original_height
866        {
867            raw.to_vec()
868        } else {
869            let output = if target_width == original_width && target_height == original_height {
870                img.clone()
871            } else {
872                img.resize_exact(target_width, target_height, FilterType::Lanczos3)
873            };
874            encode_image(&output, options)?
875        };
876
877        if bytes.len() <= options.max_bytes {
878            return Ok((bytes, target_width, target_height));
879        }
880
881        if target_width == 1 && target_height == 1 {
882            bail!(
883                "screenshot payload is {} bytes at 1x1, over max_bytes {}",
884                bytes.len(),
885                options.max_bytes
886            );
887        }
888
889        (target_width, target_height) = next_dimensions_for_byte_cap(
890            target_width,
891            target_height,
892            bytes.len(),
893            options.max_bytes,
894        );
895    }
896}
897
898fn encode_image(
899    img: &image::DynamicImage,
900    options: ResolvedScreenshotPayloadOptions,
901) -> Result<Vec<u8>> {
902    let mut out = Vec::new();
903    match options.format {
904        ScreenshotOutputFormat::Png => {
905            img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png)
906                .context("failed to encode screenshot PNG")?;
907        }
908        ScreenshotOutputFormat::Jpeg => {
909            let rgb = img.to_rgb8();
910            JpegEncoder::new_with_quality(&mut out, options.quality)
911                .encode_image(&rgb)
912                .context("failed to encode screenshot JPEG")?;
913        }
914    }
915    Ok(out)
916}
917
918fn next_dimensions_for_byte_cap(
919    width: u32,
920    height: u32,
921    encoded_bytes: usize,
922    max_bytes: usize,
923) -> (u32, u32) {
924    let shrink = ((max_bytes as f64 / encoded_bytes as f64).sqrt() * 0.9).clamp(0.1, 0.95);
925    let mut next_width = ((width as f64 * shrink).floor() as u32).max(1);
926    let mut next_height = ((height as f64 * shrink).floor() as u32).max(1);
927
928    if next_width >= width && width > 1 {
929        next_width = width - 1;
930    }
931    if next_height >= height && height > 1 {
932        next_height = height - 1;
933    }
934
935    (next_width, next_height)
936}
937
938fn cleanup_gnome_requested_path(path: &Path) {
939    let _ = fs::remove_file(path);
940}
941
942fn png_dimensions(bytes: &[u8]) -> Result<(u32, u32)> {
943    const PNG_SIGNATURE: &[u8; 8] = b"\x89PNG\r\n\x1a\n";
944    if bytes.len() < 24 || &bytes[..8] != PNG_SIGNATURE || &bytes[12..16] != b"IHDR" {
945        bail!("screenshot file was not a valid PNG");
946    }
947    let width = u32::from_be_bytes(bytes[16..20].try_into().unwrap());
948    let height = u32::from_be_bytes(bytes[20..24].try_into().unwrap());
949    if width == 0 || height == 0 {
950        bail!("screenshot PNG had invalid dimensions {width}x{height}");
951    }
952    let pixels = u64::from(width) * u64::from(height);
953    if pixels > MAX_SCREENSHOT_SOURCE_PIXELS {
954        bail!(
955            "screenshot PNG has {pixels} pixels, over the {MAX_SCREENSHOT_SOURCE_PIXELS}-pixel source limit"
956        );
957    }
958    Ok((width, height))
959}
960
961fn file_uri_to_path(uri: &str) -> Result<PathBuf> {
962    let Some(rest) = uri.strip_prefix("file://") else {
963        bail!("unsupported screenshot uri: {uri}");
964    };
965    let path = PathBuf::from(percent_decode(rest));
966    if !path.is_absolute() {
967        bail!("screenshot uri did not contain an absolute file path: {uri}");
968    }
969    Ok(path)
970}
971
972fn percent_decode(value: &str) -> String {
973    let bytes = value.as_bytes();
974    let mut decoded = Vec::with_capacity(bytes.len());
975    let mut index = 0;
976
977    while index < bytes.len() {
978        if bytes[index] == b'%' && index + 2 < bytes.len() {
979            if let Ok(hex) = std::str::from_utf8(&bytes[index + 1..index + 3]) {
980                if let Ok(byte) = u8::from_str_radix(hex, 16) {
981                    decoded.push(byte);
982                    index += 3;
983                    continue;
984                }
985            }
986        }
987
988        decoded.push(bytes[index]);
989        index += 1;
990    }
991
992    String::from_utf8_lossy(&decoded).into_owned()
993}
994
995fn temp_png_path(source: &str) -> PathBuf {
996    std::env::temp_dir().join(format!(
997        "computer-use-linux-{source}-{}.png",
998        unique_suffix()
999    ))
1000}
1001
1002fn request_token() -> String {
1003    format!("computer_use_linux_{}", unique_suffix().replace('-', "_"))
1004}
1005
1006fn unique_suffix() -> String {
1007    let nanos = SystemTime::now()
1008        .duration_since(UNIX_EPOCH)
1009        .map(|duration| duration.as_nanos())
1010        .unwrap_or_default();
1011    format!("{}-{nanos}", std::process::id())
1012}
1013
1014#[cfg(test)]
1015mod tests {
1016    use super::*;
1017
1018    fn test_path(name: &str) -> PathBuf {
1019        std::env::temp_dir().join(format!(
1020            "computer-use-linux-screenshot-test-{name}-{}",
1021            unique_suffix()
1022        ))
1023    }
1024
1025    fn valid_png(width: u32, height: u32) -> Vec<u8> {
1026        let mut png = Vec::new();
1027        png.extend_from_slice(b"\x89PNG\r\n\x1a\n");
1028        png.extend_from_slice(&13_u32.to_be_bytes());
1029        png.extend_from_slice(b"IHDR");
1030        png.extend_from_slice(&width.to_be_bytes());
1031        png.extend_from_slice(&height.to_be_bytes());
1032        png.extend_from_slice(&[8, 6, 0, 0, 0]);
1033        png
1034    }
1035
1036    fn solid_png(width: u32, height: u32) -> Vec<u8> {
1037        let img = image::RgbaImage::from_pixel(width, height, image::Rgba([24, 96, 160, 255]));
1038        encode_test_png(img)
1039    }
1040
1041    fn noisy_png(width: u32, height: u32) -> Vec<u8> {
1042        let mut img = image::RgbaImage::new(width, height);
1043        for (x, y, pixel) in img.enumerate_pixels_mut() {
1044            let r = ((x * 31 + y * 17) % 256) as u8;
1045            let g = ((x * 13 + y * 47) % 256) as u8;
1046            let b = ((x * 97 + y * 7) % 256) as u8;
1047            *pixel = image::Rgba([r, g, b, 255]);
1048        }
1049        encode_test_png(img)
1050    }
1051
1052    fn encode_test_png(img: image::RgbaImage) -> Vec<u8> {
1053        let mut out = Vec::new();
1054        image::DynamicImage::ImageRgba8(img)
1055            .write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png)
1056            .unwrap();
1057        out
1058    }
1059
1060    fn raw_capture(bytes: Vec<u8>) -> RawScreenshotCapture {
1061        let (width, height) = png_dimensions(&bytes).unwrap();
1062        RawScreenshotCapture {
1063            mime_type: "image/png".to_string(),
1064            bytes,
1065            source: "test".to_string(),
1066            width,
1067            height,
1068        }
1069    }
1070
1071    #[test]
1072    fn decodes_file_uri_percent_escapes() {
1073        assert_eq!(
1074            file_uri_to_path("file:///tmp/Codex%20Screenshot.png").unwrap(),
1075            PathBuf::from("/tmp/Codex Screenshot.png")
1076        );
1077    }
1078
1079    #[test]
1080    fn file_uri_requires_an_absolute_path() {
1081        assert!(file_uri_to_path("file://relative/path.png").is_err());
1082    }
1083
1084    #[test]
1085    fn portal_response_requires_the_pinned_sender_and_exact_path() {
1086        let request_path = "/org/freedesktop/portal/desktop/request/1_7/token";
1087        let response = Message::signal(request_path, PORTAL_REQUEST_INTERFACE, "Response")
1088            .unwrap()
1089            .sender(":1.42")
1090            .unwrap()
1091            .build(&())
1092            .unwrap();
1093
1094        assert!(portal_response_matches(&response, request_path, ":1.42"));
1095        assert!(!portal_response_matches(&response, request_path, ":1.99"));
1096        assert!(!portal_response_matches(
1097            &response,
1098            "/org/freedesktop/portal/desktop/request/1_7/other",
1099            ":1.42"
1100        ));
1101    }
1102
1103    #[test]
1104    fn parses_known_backend_names() {
1105        assert_eq!(
1106            ScreenshotBackend::parse("gnome-shell"),
1107            Some(ScreenshotBackend::GnomeShell)
1108        );
1109        assert_eq!(
1110            ScreenshotBackend::parse("  Portal "),
1111            Some(ScreenshotBackend::Portal)
1112        );
1113        assert_eq!(
1114            ScreenshotBackend::parse("GNOME_SCREENSHOT"),
1115            Some(ScreenshotBackend::GnomeScreenshot)
1116        );
1117        assert_eq!(
1118            ScreenshotBackend::parse("x11"),
1119            Some(ScreenshotBackend::X11)
1120        );
1121        assert_eq!(
1122            ScreenshotBackend::parse(" X11-Native "),
1123            Some(ScreenshotBackend::X11)
1124        );
1125        assert_eq!(ScreenshotBackend::parse("nonsense"), None);
1126    }
1127
1128    #[test]
1129    fn forced_backend_reads_env_override() {
1130        // Only this test touches SCREENSHOT_BACKEND_ENV, so no cross-test race.
1131        std::env::set_var(SCREENSHOT_BACKEND_ENV, "gnome-screenshot");
1132        assert_eq!(
1133            forced_backend().unwrap(),
1134            Some(ScreenshotBackend::GnomeScreenshot)
1135        );
1136
1137        std::env::set_var(SCREENSHOT_BACKEND_ENV, "   ");
1138        assert_eq!(forced_backend().unwrap(), None);
1139
1140        std::env::set_var(SCREENSHOT_BACKEND_ENV, "bogus");
1141        let error = forced_backend().unwrap_err();
1142        assert!(error.to_string().contains("not a recognized backend"));
1143
1144        std::env::remove_var(SCREENSHOT_BACKEND_ENV);
1145        assert_eq!(forced_backend().unwrap(), None);
1146    }
1147
1148    #[test]
1149    fn request_token_is_portal_safe() {
1150        let token = request_token();
1151        assert!(token.starts_with("computer_use_linux_"));
1152        assert!(token.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'));
1153    }
1154
1155    #[test]
1156    fn reads_png_dimensions_from_ihdr() {
1157        let png = valid_png(3840, 1080);
1158
1159        assert_eq!(png_dimensions(&png).unwrap(), (3840, 1080));
1160    }
1161
1162    #[test]
1163    fn default_payload_downscales_long_edge() {
1164        let capture =
1165            prepare_screenshot_payload(raw_capture(solid_png(4000, 1000)), Default::default())
1166                .unwrap();
1167
1168        assert_eq!((capture.width, capture.height), (1920, 480));
1169        assert_eq!(
1170            (capture.coordinate_width, capture.coordinate_height),
1171            (4000, 1000)
1172        );
1173        assert!(capture.resized);
1174        assert!(capture.bytes <= DEFAULT_SCREENSHOT_MAX_BYTES);
1175        assert!(capture.data_url.starts_with("data:image/png;base64,"));
1176    }
1177
1178    #[test]
1179    fn larger_bounded_request_can_keep_more_detail() {
1180        let capture = prepare_screenshot_payload(
1181            raw_capture(solid_png(3000, 1000)),
1182            ScreenshotPayloadOptions {
1183                max_width: Some(3000),
1184                max_height: Some(3000),
1185                max_bytes: Some(DEFAULT_SCREENSHOT_MAX_BYTES),
1186                ..Default::default()
1187            },
1188        )
1189        .unwrap();
1190
1191        assert_eq!((capture.width, capture.height), (3000, 1000));
1192        assert_eq!(
1193            (capture.coordinate_width, capture.coordinate_height),
1194            (3000, 1000)
1195        );
1196        assert!(!capture.resized);
1197    }
1198
1199    #[test]
1200    fn byte_cap_downscales_until_payload_fits() {
1201        let capture = prepare_screenshot_payload(
1202            raw_capture(noisy_png(512, 512)),
1203            ScreenshotPayloadOptions {
1204                max_width: Some(512),
1205                max_height: Some(512),
1206                max_bytes: Some(20_000),
1207                ..Default::default()
1208            },
1209        )
1210        .unwrap();
1211
1212        assert!(capture.bytes <= 20_000);
1213        assert!(capture.width < 512);
1214        assert_eq!(
1215            (capture.coordinate_width, capture.coordinate_height),
1216            (512, 512)
1217        );
1218        assert!(capture.resized);
1219    }
1220
1221    #[test]
1222    fn jpeg_format_compresses_when_requested() {
1223        let capture = prepare_screenshot_payload(
1224            raw_capture(noisy_png(512, 512)),
1225            ScreenshotPayloadOptions {
1226                max_width: Some(512),
1227                max_height: Some(512),
1228                max_bytes: Some(DEFAULT_SCREENSHOT_MAX_BYTES),
1229                format: Some(ScreenshotOutputFormat::Jpeg),
1230                quality: Some(60),
1231                ..Default::default()
1232            },
1233        )
1234        .unwrap();
1235
1236        assert_eq!(capture.mime_type, "image/jpeg");
1237        assert_eq!(capture.format, ScreenshotOutputFormat::Jpeg);
1238        assert_eq!(capture.quality, Some(60));
1239        assert_eq!((capture.width, capture.height), (512, 512));
1240        assert_eq!(
1241            (capture.coordinate_width, capture.coordinate_height),
1242            (512, 512)
1243        );
1244        assert!(capture.bytes < capture.original_bytes);
1245        assert!(capture.data_url.starts_with("data:image/jpeg;base64,"));
1246    }
1247
1248    #[tokio::test]
1249    async fn cancelled_queued_capture_removes_its_owned_file() {
1250        let cache = std::env::var_os("XDG_CACHE_HOME")
1251            .map(PathBuf::from)
1252            .unwrap_or_else(|| PathBuf::from(std::env::var_os("HOME").unwrap()).join(".cache"));
1253        let path = cache.join(format!(
1254            "cul-cancelled-capture-{}.png",
1255            getrandom::u64().unwrap()
1256        ));
1257        fs::create_dir_all(&cache).unwrap();
1258        fs::write(&path, valid_png(1, 1)).unwrap();
1259        let (release, wait) = std::sync::mpsc::channel();
1260        let (started, ready) = tokio::sync::oneshot::channel();
1261        let busy = tokio::spawn(run_image_task(move || {
1262            started.send(()).unwrap();
1263            wait.recv().unwrap();
1264            Ok(())
1265        }));
1266        ready.await.unwrap();
1267        let mut queued = tokio::spawn(read_png_as_capture(
1268            path.clone(),
1269            "owned-test-capture",
1270            ScreenshotCleanup::DeletePath(path.clone()),
1271        ));
1272        assert!(tokio::time::timeout(Duration::from_millis(20), &mut queued)
1273            .await
1274            .is_err());
1275        queued.abort();
1276        assert!(queued.await.unwrap_err().is_cancelled());
1277        release.send(()).unwrap();
1278        busy.await.unwrap().unwrap();
1279        let removed = !path.exists();
1280        let _ = fs::remove_file(path);
1281        assert!(removed, "cancelled screenshot left its owned file behind");
1282    }
1283
1284    #[tokio::test]
1285    async fn portal_capture_removes_new_returned_path() {
1286        let path = test_path("portal-valid");
1287        let requested_at = SystemTime::now();
1288        // Linux filesystem timestamps can lag the wall clock by one tick.
1289        // A real portal round trip also separates request and file creation.
1290        tokio::time::sleep(Duration::from_millis(20)).await;
1291        fs::write(&path, valid_png(1, 1)).unwrap();
1292        let capture = read_portal_png_as_capture(
1293            path.clone(),
1294            PortalScreenshotRequest {
1295                requested_at,
1296                pictures: None,
1297            },
1298        )
1299        .await
1300        .unwrap();
1301        assert_eq!(capture.source, "xdg-desktop-portal");
1302        let retained = path.exists();
1303        let _ = fs::remove_file(&path);
1304        assert!(!retained, "portal screenshot was left behind");
1305    }
1306
1307    #[tokio::test]
1308    async fn portal_capture_removes_new_invalid_returned_path() {
1309        let path = test_path("portal-invalid");
1310        let requested_at = SystemTime::now();
1311        // Linux filesystem timestamps can lag the wall clock by one tick.
1312        // A real portal round trip also separates request and file creation.
1313        tokio::time::sleep(Duration::from_millis(20)).await;
1314        fs::write(&path, b"").unwrap();
1315        let error = read_portal_png_as_capture(
1316            path.clone(),
1317            PortalScreenshotRequest {
1318                requested_at,
1319                pictures: None,
1320            },
1321        )
1322        .await
1323        .unwrap_err();
1324        assert!(error.to_string().contains("screenshot file was empty"));
1325        let retained = path.exists();
1326        let _ = fs::remove_file(&path);
1327        assert!(!retained, "failed portal screenshot was left behind");
1328    }
1329
1330    #[tokio::test]
1331    async fn portal_capture_preserves_preexisting_returned_path() {
1332        let path = test_path("portal-existing");
1333        fs::write(&path, valid_png(1, 1)).unwrap();
1334        let requested_at = SystemTime::now();
1335        let capture = read_portal_png_as_capture(
1336            path.clone(),
1337            PortalScreenshotRequest {
1338                requested_at,
1339                pictures: None,
1340            },
1341        )
1342        .await
1343        .unwrap();
1344        assert_eq!(capture.source, "xdg-desktop-portal");
1345        assert!(path.exists(), "preexisting user image was removed");
1346        let _ = fs::remove_file(path);
1347    }
1348
1349    #[tokio::test]
1350    async fn portal_capture_cleans_same_tick_picture_and_preserves_existing_name() {
1351        let directory = test_path("portal-pictures");
1352        fs::create_dir_all(&directory).unwrap();
1353        let existing = directory.join("existing.png");
1354        fs::write(&existing, valid_png(1, 1)).unwrap();
1355        let pictures = PortalPicturesSnapshot::new(directory.clone()).unwrap();
1356        let path = directory.join("new.png");
1357        let request = PortalScreenshotRequest {
1358            requested_at: SystemTime::now(),
1359            pictures: Some(pictures),
1360        };
1361        fs::write(&path, valid_png(1, 1)).unwrap();
1362        let capture = read_portal_png_as_capture(path.clone(), request)
1363            .await
1364            .unwrap();
1365        assert_eq!(capture.source, "xdg-desktop-portal");
1366        assert!(!path.exists(), "same-tick portal capture was left behind");
1367        let pictures = PortalPicturesSnapshot::new(directory.clone()).unwrap();
1368        fs::remove_file(&existing).unwrap();
1369        fs::write(&existing, valid_png(1, 1)).unwrap();
1370        let request = PortalScreenshotRequest {
1371            requested_at: UNIX_EPOCH,
1372            pictures: Some(pictures),
1373        };
1374        read_portal_png_as_capture(existing.clone(), request)
1375            .await
1376            .unwrap();
1377        assert!(existing.exists(), "preexisting filename was removed");
1378        fs::remove_dir_all(directory).unwrap();
1379    }
1380
1381    #[test]
1382    fn portal_cleanup_preserves_a_replacement_file() {
1383        let path = test_path("portal-replaced");
1384        fs::write(&path, valid_png(1, 1)).unwrap();
1385        let created = fs::metadata(&path).unwrap().created().unwrap();
1386        let cleanup = OwnedScreenshotCleanup::new(ScreenshotCleanup::PortalPath {
1387            path: path.clone(),
1388            request: PortalScreenshotRequest {
1389                requested_at: created,
1390                pictures: None,
1391            },
1392        });
1393        fs::remove_file(&path).unwrap();
1394        fs::write(&path, b"user replacement").unwrap();
1395        drop(cleanup);
1396        let result = fs::read(&path);
1397        let _ = fs::remove_file(&path);
1398        assert_eq!(result.unwrap(), b"user replacement");
1399    }
1400
1401    #[tokio::test]
1402    async fn screenshot_reader_rejects_symlinks() {
1403        let target = test_path("symlink-target");
1404        let link = test_path("symlink-link");
1405        fs::write(&target, valid_png(1, 1)).unwrap();
1406        std::os::unix::fs::symlink(&target, &link).unwrap();
1407
1408        let error = read_png_as_capture(link.clone(), "test", ScreenshotCleanup::Preserve)
1409            .await
1410            .unwrap_err();
1411
1412        assert!(error.to_string().contains("failed to open screenshot file"));
1413        let _ = fs::remove_file(link);
1414        let _ = fs::remove_file(target);
1415    }
1416
1417    #[tokio::test]
1418    async fn screenshot_reader_rejects_oversized_source_files() {
1419        let path = test_path("oversized-source");
1420        let file = fs::File::create(&path).unwrap();
1421        file.set_len(MAX_SCREENSHOT_SOURCE_BYTES + 1).unwrap();
1422
1423        let error = read_png_as_capture(path.clone(), "test", ScreenshotCleanup::Preserve)
1424            .await
1425            .unwrap_err();
1426
1427        assert!(error.to_string().contains("over the"));
1428        let _ = fs::remove_file(path);
1429    }
1430
1431    #[test]
1432    fn png_dimensions_reject_decompression_bomb_dimensions() {
1433        let png = valid_png(u32::MAX, u32::MAX);
1434
1435        assert!(png_dimensions(&png)
1436            .unwrap_err()
1437            .to_string()
1438            .contains("pixel source limit"));
1439    }
1440
1441    #[tokio::test]
1442    async fn gnome_capture_deletes_backend_temp_path_on_success() {
1443        let path = test_path("gnome-valid");
1444        fs::write(&path, valid_png(1, 1)).unwrap();
1445
1446        let capture = read_png_as_capture(
1447            path.clone(),
1448            "gnome-shell",
1449            ScreenshotCleanup::DeletePath(path.clone()),
1450        )
1451        .await
1452        .unwrap();
1453
1454        assert_eq!(capture.source, "gnome-shell");
1455        assert!(!path.exists());
1456    }
1457
1458    #[tokio::test]
1459    async fn gnome_capture_deletes_backend_temp_path_on_parse_failure() {
1460        let path = test_path("gnome-invalid");
1461        fs::write(&path, b"").unwrap();
1462
1463        let error = read_png_as_capture(
1464            path.clone(),
1465            "gnome-shell",
1466            ScreenshotCleanup::DeletePath(path.clone()),
1467        )
1468        .await
1469        .unwrap_err();
1470
1471        assert!(error.to_string().contains("screenshot file was empty"));
1472        assert!(!path.exists());
1473    }
1474
1475    #[test]
1476    fn gnome_failure_cleanup_removes_requested_temp_path() {
1477        let path = test_path("gnome-pre-read-failure");
1478        fs::write(&path, b"partial").unwrap();
1479
1480        cleanup_gnome_requested_path(&path);
1481
1482        assert!(!path.exists());
1483    }
1484
1485    #[tokio::test]
1486    async fn gnome_deletes_requested_temp_path_and_preserves_unexpected_returned_path() {
1487        let requested = test_path("gnome-requested");
1488        let returned = test_path("gnome-returned");
1489        fs::write(&requested, b"partial").unwrap();
1490        fs::write(&returned, valid_png(1, 1)).unwrap();
1491
1492        let capture = read_png_as_capture(
1493            returned.clone(),
1494            "gnome-shell",
1495            ScreenshotCleanup::DeletePath(requested.clone()),
1496        )
1497        .await
1498        .unwrap();
1499
1500        assert_eq!(capture.source, "gnome-shell");
1501        assert!(!requested.exists());
1502        assert!(returned.exists());
1503        let _ = fs::remove_file(returned);
1504    }
1505}