Skip to main content

cosmic_applet_avestruz/handlers/
screenshot.rs

1// SPDX-License-Identifier: MIT
2
3//! A picture of the popup, taken by the popup itself: Ctrl+Shift+S.
4//!
5//! The popup closes when anything else is clicked, so a screenshot tool
6//! that is clicked on has nothing left to take. This asks the renderer for
7//! what it last drew of the popup and writes that as a PNG to the user's
8//! pictures folder, as `avestruz-<date>_<time>.png`. The popup's rounded
9//! corners are transparent in it, as they were drawn.
10//!
11//! The picture is of whatever shows: other people's notes, and anything
12//! being written. It goes to a file and nowhere else, and where it went
13//! is said in the journal.
14
15use std::path::{Path, PathBuf};
16
17use cosmic::iced::core::window::Screenshot;
18use cosmic::iced::runtime::window::screenshot;
19use cosmic::prelude::*;
20use image::{ImageBuffer, Rgba};
21
22use crate::messages::Message;
23use crate::state::AppModel;
24
25/// Why a picture of the popup was not written.
26#[derive(Debug)]
27pub enum ScreenshotError {
28    /// What the renderer handed over is not as many bytes as its size says.
29    Size { width: u32, height: u32, expected: usize, got: usize },
30    /// The folder could not be made.
31    Folder(PathBuf, std::io::Error),
32    /// The file could not be written.
33    File(PathBuf, image::ImageError),
34}
35
36impl std::fmt::Display for ScreenshotError {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        match self {
39            Self::Size { width, height, expected, got } => {
40                write!(f, "{width}×{height} pixels are {expected} bytes, and {got} came")
41            }
42            Self::Folder(folder, e) => write!(f, "{} could not be made: {e}", folder.display()),
43            Self::File(path, e) => write!(f, "{} could not be written: {e}", path.display()),
44        }
45    }
46}
47
48/// What a picture taken at `at` is called.
49fn file_name(at: chrono::DateTime<chrono::Local>) -> String {
50    format!("avestruz-{}.png", at.format("%Y-%m-%d_%H-%M-%S"))
51}
52
53/// Where pictures go: the user's pictures folder, or `Pictures` at home
54/// where the desktop names none.
55fn pictures_folder() -> PathBuf {
56    dirs::picture_dir().unwrap_or_else(|| dirs::home_dir().unwrap_or_else(|| PathBuf::from(".")).join("Pictures"))
57}
58
59/// Write `taken` as a PNG called `name` in `folder`, which is made if it
60/// is not there, and say where it is. The pixels are written as they
61/// came, transparency included.
62fn save_png(taken: &Screenshot, folder: &Path, name: &str) -> Result<PathBuf, ScreenshotError> {
63    let (width, height) = (taken.size.width, taken.size.height);
64    let Some(picture) = ImageBuffer::<Rgba<u8>, _>::from_raw(width, height, taken.rgba.to_vec()) else {
65        return Err(ScreenshotError::Size {
66            width,
67            height,
68            expected: (width as usize) * (height as usize) * 4,
69            got: taken.rgba.len(),
70        });
71    };
72    std::fs::create_dir_all(folder).map_err(|e| ScreenshotError::Folder(folder.to_path_buf(), e))?;
73    let path = folder.join(name);
74    picture.save(&path).map_err(|e| ScreenshotError::File(path.clone(), e))?;
75    Ok(path)
76}
77
78impl AppModel {
79    /// Ctrl+Shift+S: ask the renderer for what it drew of the popup.
80    /// Nothing comes of it with the popup closed: there is nothing drawn.
81    pub fn handle_take_screenshot(&mut self) -> Task<cosmic::Action<Message>> {
82        let Some(id) = self.popup else {
83            return Task::none();
84        };
85        screenshot(id).map(|taken| cosmic::Action::App(Message::ScreenshotTaken(taken)))
86    }
87
88    /// The renderer handed the picture over: write it to the pictures
89    /// folder. Encoding a PNG as large as the popup takes a moment, which
90    /// a thread of its own spends, so that the popup goes on being drawn.
91    pub fn handle_screenshot_taken(&mut self, taken: Screenshot) {
92        let name = file_name(chrono::Local::now());
93        let saving = std::thread::Builder::new().name("screenshot".into()).spawn(move || {
94            match save_png(&taken, &pictures_folder(), &name) {
95                Ok(path) => {
96                    tracing::info!(
97                        "a picture of the popup is at {} ({}×{})",
98                        path.display(),
99                        taken.size.width,
100                        taken.size.height
101                    );
102                }
103                Err(e) => tracing::error!("a picture of the popup was not kept: {e}"),
104            }
105        });
106        if let Err(e) = saving {
107            tracing::error!("a picture of the popup was not kept: no thread to write it on: {e}");
108        }
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::{ScreenshotError, file_name, save_png};
115    use chrono::TimeZone;
116    use cosmic::iced::Size;
117    use cosmic::iced::core::window::Screenshot;
118
119    /// A folder of this test's own, with nothing in it, to write into.
120    fn folder(name: &str) -> std::path::PathBuf {
121        let folder = std::env::temp_dir().join(format!("avestruz-test-{}-screenshot-{name}", std::process::id()));
122        let _ = std::fs::remove_dir_all(&folder);
123        folder
124    }
125
126    /// A picture `width` by `height`, of these bytes.
127    fn taken(width: u32, height: u32, rgba: Vec<u8>) -> Screenshot {
128        Screenshot::new(rgba, Size::new(width, height), 1.0)
129    }
130
131    #[test]
132    fn a_picture_is_called_after_when_it_was_taken() {
133        let at = chrono::Local.with_ymd_and_hms(2026, 3, 9, 7, 5, 2).unwrap();
134        assert_eq!(file_name(at), "avestruz-2026-03-09_07-05-02.png");
135    }
136
137    #[test]
138    fn a_picture_is_written_as_it_came_transparency_included() {
139        // Two pixels: one opaque, one a corner the popup did not draw on.
140        let pixels = vec![200, 100, 50, 255, 0, 0, 0, 0];
141        // The folder is not there yet, and is made on the way.
142        let into = folder("written").join("Pictures");
143        let path = save_png(&taken(2, 1, pixels.clone()), &into, "shot.png").unwrap();
144        assert_eq!(path, into.join("shot.png"));
145        let read = image::open(&path).unwrap().into_rgba8();
146        assert_eq!((read.width(), read.height()), (2, 1));
147        assert_eq!(read.into_raw(), pixels);
148        let _ = std::fs::remove_dir_all(folder("written"));
149    }
150
151    #[test]
152    fn a_picture_that_is_not_the_size_it_says_is_not_written() {
153        let into = folder("wrong-size");
154        let problem = save_png(&taken(2, 2, vec![0; 8]), &into, "shot.png").unwrap_err();
155        assert!(matches!(problem, ScreenshotError::Size { expected: 16, got: 8, .. }), "{problem}");
156        assert!(!into.exists(), "nothing was made for it");
157    }
158}