Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

5.0 KB
Raw Blame
//! "Copy Image" and "Save Image" from a picture's right-click menu. The file
//! comes from egui's byte loaders (already in memory when it's on screen at
//! full size, otherwise downloaded once); decoding, the clipboard and the
//! save dialog run on their own thread so the window never stalls.

use eframe::egui;
use std::sync::Mutex;

#[derive(Clone, Copy, PartialEq)]
pub enum Kind {
    Copy,
    Save,
}

/// The picture being fetched for the clipboard / a file.
static PENDING: Mutex<Option<(String, Kind)>> = Mutex::new(None);
/// Finished jobs: (toast text, is an error).
static DONE: Mutex<Vec<(String, bool)>> = Mutex::new(Vec::new());

pub fn request(uri: &str, kind: Kind) {
    if let Ok(mut p) = PENDING.lock() {
        *p = Some((uri.split('#').next().unwrap_or(uri).to_string(), kind));
    }
}

/// Call once a frame: moves a requested picture along and returns the
/// toasts of the ones that finished.
pub fn poll(ctx: &egui::Context) -> Vec<(String, bool)> {
    if let Ok(mut pending) = PENDING.lock() {
        if let Some((uri, kind)) = pending.clone() {
            match ctx.try_load_bytes(&uri) {
                Ok(egui::load::BytesPoll::Ready { bytes, .. }) => {
                    *pending = None;
                    let (bytes, ctx) = (bytes.to_vec(), ctx.clone());
                    let _ = std::thread::Builder::new().name("rustcord-media-copy".into()).spawn(move || {
                        let done = match kind {
                            Kind::Copy => Some(match copy(&bytes) {
                                Ok(()) => ("Image copied.".to_string(), false),
                                Err(e) => (format!("Couldn't copy that image: {e}"), true),
                            }),
                            Kind::Save => save(&uri, &bytes),
                        };
                        if let (Some(d), Ok(mut list)) = (done, DONE.lock()) {
                            list.push(d);
                        }
                        ctx.request_repaint();
                    });
                }
                Ok(egui::load::BytesPoll::Pending { .. }) => ctx.request_repaint_after(std::time::Duration::from_millis(100)),
                Err(e) => {
                    *pending = None;
                    log::debug!("media copy: {}: {e}", crate::net_images::log_url(&uri));
                    if let Ok(mut list) = DONE.lock() {
                        list.push(("Couldn't load that image.".into(), true));
                    }
                }
            }
        }
    }
    DONE.lock().map(|mut d| std::mem::take(&mut *d)).unwrap_or_default()
}

/// The picture (an animation's first frame) onto the clipboard, as pixels:
/// what Discord's "Copy Image" leaves there.
fn copy(bytes: &[u8]) -> Result<(), String> {
    let img = crate::net_images::decode_limited(bytes).map_err(|e| e.to_string())?.to_rgba8();
    let (width, height) = (img.width() as usize, img.height() as usize);
    let mut cb = arboard::Clipboard::new().map_err(|e| e.to_string())?;
    cb.set_image(arboard::ImageData { width, height, bytes: img.into_raw().into() }).map_err(|e| e.to_string())
}

/// The file as Discord sent it, wherever the save dialog says (None: cancelled).
fn save(uri: &str, bytes: &[u8]) -> Option<(String, bool)> {
    let path = rfd::FileDialog::new().set_title("Save Image").set_file_name(file_name(uri, bytes)).save_file()?;
    Some(match std::fs::write(&path, bytes) {
        Ok(()) => ("Image saved.".to_string(), false),
        Err(e) => (format!("Couldn't save that image: {e}"), true),
    })
}

/// The URL's file name, with the extension of what the bytes really are
/// (Discord's media proxy often hands out WebP under a .png name). Never the
/// link's own extension: a link ending in .exe or .hta mustn't be offered
/// as one.
fn file_name(uri: &str, bytes: &[u8]) -> String {
    let path = uri.split(['?', '#']).next().unwrap_or(uri);
    let name = path.rsplit('/').next().filter(|n| !n.is_empty()).unwrap_or("image");
    let stem = name.rsplit_once('.').map_or(name, |(s, _)| s);
    let ext = match image::guess_format(bytes) {
        Ok(image::ImageFormat::Jpeg) => "jpg",
        Ok(image::ImageFormat::Gif) => "gif",
        Ok(image::ImageFormat::WebP) => "webp",
        Ok(image::ImageFormat::Avif) => "avif",
        _ => "png",
    };
    format!("{stem}.{ext}")
}

#[cfg(test)]
mod tests {
    #[test]
    fn saved_files_are_named_after_what_they_are() {
        let png = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
        assert_eq!(super::file_name("https://cdn.discordapp.com/attachments/1/2/cat.png?ex=1&is=2", &png), "cat.png");
        let webp = b"RIFF\0\0\0\0WEBPVP8 ";
        assert_eq!(super::file_name("https://media.discordapp.net/a/b/photo.jpg?width=400", webp), "photo.webp");
        assert_eq!(super::file_name("https://example.com/", b"??"), "image.png");
        // Not a picture, under a program's name: never saved as one.
        assert_eq!(super::file_name("https://example.com/setup.exe", b"MZ\x90\0"), "setup.png");
        assert_eq!(super::file_name("https://example.com/x.hta?y=1", b"<html>"), "x.png");
    }
}