windows-troll 0.1.0

Modular Windows prank library
//! Window hiding/minimizing module.
//!
//! Ported from the `window-hider` binary: lets callers minimize (hide) or
//! restore windows.

use rand::{rng, RngExt};
use windows::Win32::Foundation::HWND;
use windows::Win32::UI::WindowsAndMessaging::{ShowWindow, SW_MINIMIZE, SW_RESTORE};

pub use crate::desktop::{list_windows, WindowInfo};

/// Minimizes a random eligible window.
///
/// Returns the [`WindowInfo`] of the hidden window, or `None` if no eligible
/// window was found.
pub fn hide_random_window() -> Option<WindowInfo> {
    let windows = list_windows();
    hide_random_window_from(&windows)
}

fn hide_random_window_from(windows: &[WindowInfo]) -> Option<WindowInfo> {
    if windows.is_empty() {
        return None;
    }
    let mut rng = rng();
    let index = rng.random_range(0..windows.len());
    let target = &windows[index];
    hide_window(target.handle());
    Some(target.clone())
}

/// Minimizes the window with the given handle.
///
/// Returns `true` if the window was previously visible (per the Win32
/// return semantics of [`ShowWindow`]).
pub fn hide_window(window: HWND) -> bool {
    unsafe { ShowWindow(window, SW_MINIMIZE).as_bool() }
}

/// Minimizes the first window whose title matches `title` exactly.
///
/// Returns the [`WindowInfo`] of the hidden window, or `None` if no window
/// with that title was found.
pub fn hide_by_title(title: &str) -> Option<WindowInfo> {
    list_windows()
        .into_iter()
        .find(|w| w.title() == title)
        .inspect(|w| {
            hide_window(w.handle());
        })
}

/// Restores a previously minimized window to its normal state.
///
/// Returns `true` if the window was previously visible (per the Win32
/// return semantics of [`ShowWindow`]).
pub fn restore_window(window: HWND) -> bool {
    unsafe { ShowWindow(window, SW_RESTORE).as_bool() }
}