Skip to content

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

2.7 KB
Raw Blame
//! Pasting into the message box like Discord: text goes into the box, and
//! files or a picture on the clipboard (a screenshot, "Copy image") become
//! uploads. egui itself only ever pastes text, and on Ctrl+V with no text on
//! the clipboard it reports nothing at all, so the key is watched here too.

use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};

/// What a paste brings in.
pub enum Clip {
    Text(String),
    Files(Vec<PathBuf>),
    /// A picture, as Discord names it: image.png.
    Image(Vec<u8>),
}

/// The clipboard's contents, files and pictures first (Discord uploads
/// those rather than pasting any text that came with them).
pub fn read() -> Option<Clip> {
    let mut cb = arboard::Clipboard::new().ok()?;
    if let Ok(files) = cb.get().file_list() {
        if !files.is_empty() {
            return Some(Clip::Files(files));
        }
    }
    if let Ok(img) = cb.get_image() {
        if let Some(png) = encode_png(img.width, img.height, img.bytes.into_owned()) {
            return Some(Clip::Image(png));
        }
    }
    cb.get_text().ok().filter(|t| !t.is_empty()).map(|t| Clip::Text(t.replace("\r\n", "\n")))
}

/// Just the attachments (files / a picture), or None for text or nothing.
pub fn read_attachments() -> Option<Clip> {
    read().filter(|c| !matches!(c, Clip::Text(_)))
}

fn encode_png(width: usize, height: usize, rgba: Vec<u8>) -> Option<Vec<u8>> {
    let img = image::RgbaImage::from_raw(width as u32, height as u32, rgba)?;
    let mut out = std::io::Cursor::new(Vec::new());
    img.write_to(&mut out, image::ImageFormat::Png).ok()?;
    Some(out.into_inner())
}

/// Ctrl+V (or Shift+Insert) went down since the last call. Call once a frame.
pub fn paste_pressed() -> bool {
    static WAS_DOWN: AtomicBool = AtomicBool::new(false);
    let down = paste_keys_down();
    let was = WAS_DOWN.swap(down, Ordering::Relaxed);
    down && !was
}

#[cfg(windows)]
fn paste_keys_down() -> bool {
    use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_CONTROL, VK_INSERT, VK_MENU, VK_SHIFT};
    // SAFETY: GetAsyncKeyState only reads the keyboard state.
    let down = |vk: u16| unsafe { GetAsyncKeyState(vk as i32) } as u16 & 0x8000 != 0;
    (down(VK_CONTROL) && !down(VK_MENU) && down(b'V' as u16)) || (down(VK_SHIFT) && down(VK_INSERT))
}

#[cfg(not(windows))]
fn paste_keys_down() -> bool {
    false
}

#[cfg(test)]
mod tests {
    #[test]
    fn pasted_pictures_become_pngs() {
        let rgba = vec![255u8, 0, 0, 255, 0, 255, 0, 128];
        let png = super::encode_png(2, 1, rgba.clone()).expect("encodes");
        let back = image::load_from_memory(&png).expect("decodes").to_rgba8();
        assert_eq!((back.width(), back.height()), (2, 1));
        assert_eq!(back.into_raw(), rgba);
    }
}