Skip to content

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

5.1 KB
Raw Blame
//! Keys read system-wide (also while RustCord isn't the focused window):
//! Push-to-Talk's shortcut. Windows only; elsewhere nothing is ever pressed.
//!
//! While Push to Talk is on, a small thread looks at the key every 8 ms and
//! tells the voice engine whether to send; with it off the thread sleeps.

use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Once;

/// The Push-to-Talk key (a Windows virtual-key code); 0 = voice activity.
static PTT_KEY: AtomicU32 = AtomicU32::new(0);
static WATCHER: Once = Once::new();

/// How long you keep sending after letting go (Discord's default release delay).
const RELEASE_MS: u64 = 20;

#[cfg(windows)]
pub fn pressed(vk: u32) -> bool {
    use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState;
    vk != 0 && unsafe { GetAsyncKeyState(vk as i32) } as u16 & 0x8000 != 0
}

#[cfg(not(windows))]
pub fn pressed(_: u32) -> bool {
    false
}

/// A key or extra mouse button that is down right now (for recording a
/// shortcut). The left and right mouse buttons don't count: they're how you
/// click the button that records.
pub fn any_pressed() -> Option<u32> {
    // 4 middle button, 5/6 side buttons, 8.. keyboard. The generic Shift /
    // Ctrl / Alt codes (0x10–0x12) are skipped for their left/right ones.
    (4..=254u32).filter(|vk| !matches!(vk, 7 | 0x10..=0x12)).find(|vk| pressed(*vk))
}

/// The middle mouse button's code.
pub const MIDDLE_BUTTON: u32 = 4;

/// Whether `vk` is the Push-to-Talk key right now.
pub fn is_push_to_talk(vk: u32) -> bool {
    vk != 0 && PTT_KEY.load(Ordering::Acquire) == vk
}

/// What to call a key in the settings.
pub fn name(vk: u32) -> String {
    match vk {
        0 => "None".into(),
        MIDDLE_BUTTON => "Middle Mouse".into(),
        5 => "Mouse 4".into(),
        6 => "Mouse 5".into(),
        0x08 => "Backspace".into(),
        0x09 => "Tab".into(),
        0x0d => "Enter".into(),
        0x13 => "Pause".into(),
        0x14 => "Caps Lock".into(),
        0x1b => "Esc".into(),
        0x20 => "Space".into(),
        0x21 => "Page Up".into(),
        0x22 => "Page Down".into(),
        0x23 => "End".into(),
        0x24 => "Home".into(),
        0x25 => "Left".into(),
        0x26 => "Up".into(),
        0x27 => "Right".into(),
        0x28 => "Down".into(),
        0x2d => "Insert".into(),
        0x2e => "Delete".into(),
        0x30..=0x39 | 0x41..=0x5a => char::from_u32(vk).map(String::from).unwrap_or_default(),
        0x60..=0x69 => format!("Numpad {}", vk - 0x60),
        0x6a => "Numpad *".into(),
        0x6b => "Numpad +".into(),
        0x6d => "Numpad -".into(),
        0x6e => "Numpad .".into(),
        0x6f => "Numpad /".into(),
        0x70..=0x87 => format!("F{}", vk - 0x6f),
        0x90 => "Num Lock".into(),
        0x91 => "Scroll Lock".into(),
        0xa0 => "Left Shift".into(),
        0xa1 => "Right Shift".into(),
        0xa2 => "Left Ctrl".into(),
        0xa3 => "Right Ctrl".into(),
        0xa4 => "Left Alt".into(),
        0xa5 => "Right Alt".into(),
        0xba => ";".into(),
        0xbb => "=".into(),
        0xbc => ",".into(),
        0xbd => "-".into(),
        0xbe => ".".into(),
        0xbf => "/".into(),
        0xc0 => "`".into(),
        0xdb => "[".into(),
        0xdc => "\\".into(),
        0xdd => "]".into(),
        0xde => "'".into(),
        other => format!("Key {other:#04x}"),
    }
}

/// Voice & Video → Input Mode: `Some(key)` sends your microphone only while
/// that key is held; `None` goes back to voice activity.
pub fn set_push_to_talk(key: Option<u32>) {
    let key = key.filter(|k| *k != 0);
    let before = PTT_KEY.swap(key.unwrap_or(0), Ordering::AcqRel);
    if key.is_none() {
        voice::set_push_to_talk(None);
        return;
    }
    // (Called again with the same key, e.g. while a volume slider moves: a
    // held key must stay held.)
    if before == 0 {
        voice::set_push_to_talk(Some(false));
    }
    WATCHER.call_once(|| {
        let _ = std::thread::Builder::new().name("rustcord-ptt".into()).spawn(|| {
            let mut released_at: Option<std::time::Instant> = None;
            let mut sending = false;
            loop {
                let vk = PTT_KEY.load(Ordering::Acquire);
                if vk == 0 {
                    sending = false;
                    std::thread::sleep(std::time::Duration::from_millis(250));
                    continue;
                }
                let want = if pressed(vk) {
                    released_at = None;
                    true
                } else {
                    let since = *released_at.get_or_insert_with(std::time::Instant::now);
                    sending && since.elapsed() < std::time::Duration::from_millis(RELEASE_MS)
                };
                if want != sending {
                    sending = want;
                    // (Checked again: the mode may have changed while RustCord looked.)
                    if PTT_KEY.load(Ordering::Acquire) != 0 {
                        voice::set_push_to_talk(Some(sending));
                    }
                }
                std::thread::sleep(std::time::Duration::from_millis(8));
            }
        });
    });
}