windows-troll 0.1.0

Modular Windows prank library
//! Random mouse teleporter module.
//!
//! Ported from `PaulDotSH/random-mouse-teleporter`: moves the cursor to a
//! chosen or random position on the primary display.

use rand::{rng, RngExt};
use windows::Win32::UI::WindowsAndMessaging::{
    GetSystemMetrics, SetCursorPos, SM_CXSCREEN, SM_CYSCREEN,
};

/// The size of the primary display, in pixels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Resolution {
    pub width: i32,
    pub height: i32,
}

/// Returns the resolution of the primary display.
pub fn get_resolution() -> Resolution {
    let width = unsafe { GetSystemMetrics(SM_CXSCREEN) };
    let height = unsafe { GetSystemMetrics(SM_CYSCREEN) };
    Resolution {
        width: width.max(1),
        height: height.max(1),
    }
}

/// Moves the cursor to `(x, y)` in screen coordinates.
///
/// Returns `true` on success.
pub fn teleport_mouse(x: i32, y: i32) -> bool {
    unsafe { SetCursorPos(x, y).is_ok() }
}

/// Moves the cursor to a random position on the primary display.
///
/// Returns the target position.
pub fn teleport_random() -> (i32, i32) {
    let res = get_resolution();
    let mut rng = rng();
    let x = rng.random_range(0..res.width);
    let y = rng.random_range(0..res.height);
    teleport_mouse(x, y);
    (x, y)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn resolution_is_positive() {
        let res = get_resolution();
        assert!(res.width > 0);
        assert!(res.height > 0);
    }
}