Skip to main content

stynx_code_tui/
clipboard.rs

1use std::path::PathBuf;
2use std::time::{SystemTime, UNIX_EPOCH};
3
4pub enum PasteOutcome {
5
6    Image { path: PathBuf },
7
8    Text(String),
9
10    Empty,
11}
12
13pub fn read_clipboard() -> PasteOutcome {
14    let Ok(mut cb) = arboard::Clipboard::new() else { return PasteOutcome::Empty; };
15
16    if let Ok(img) = cb.get_image() {
17        match save_image_to_temp(&img) {
18            Ok(path) => return PasteOutcome::Image { path },
19            Err(e) => {
20                tracing::warn!("failed to save pasted image: {e}");
21            }
22        }
23    }
24
25    if let Ok(text) = cb.get_text() {
26        if !text.is_empty() {
27            return PasteOutcome::Text(text);
28        }
29    }
30
31    PasteOutcome::Empty
32}
33
34fn save_image_to_temp(img: &arboard::ImageData) -> Result<PathBuf, String> {
35    use image::ImageEncoder;
36
37    let now = SystemTime::now()
38        .duration_since(UNIX_EPOCH)
39        .map(|d| d.as_millis())
40        .unwrap_or(0);
41
42    let dir = std::env::temp_dir().join("stynx-pastes");
43    std::fs::create_dir_all(&dir).map_err(|e| format!("mkdir: {e}"))?;
44    let path = dir.join(format!("paste-{now}.png"));
45
46    let file = std::fs::File::create(&path).map_err(|e| format!("create: {e}"))?;
47    let writer = std::io::BufWriter::new(file);
48    let encoder = image::codecs::png::PngEncoder::new(writer);
49    encoder
50        .write_image(
51            &img.bytes,
52            img.width as u32,
53            img.height as u32,
54            image::ExtendedColorType::Rgba8,
55        )
56        .map_err(|e| format!("encode: {e}"))?;
57    Ok(path)
58}