taskbar-focus 0.5.0

A tiny Pomodoro/focus timer that lives in the Windows tray and toggles Do Not Disturb
//! Locking the PC, and learning whether the session is locked.
//!
//! `LockWorkStation` only starts a lock, so confirmation comes from session
//! notifications, which must be registered before any lock. Nothing here needs
//! elevation.
//!
//! A debug build never locks: it records the call instead, so that development
//! cannot lock the developer out.

use windows::core::PWSTR;
use windows::Win32::Foundation::HWND;
use windows::Win32::System::RemoteDesktop::{
    ProcessIdToSessionId, WTSActive, WTSFreeMemory, WTSQuerySessionInformationW,
    WTSRegisterSessionNotification, WTSSessionInfoEx, WTSUnRegisterSessionNotification,
    NOTIFY_FOR_THIS_SESSION, WTSINFOEXW, WTSINFOEX_LEVEL1_W, WTS_CURRENT_SESSION,
    WTS_SESSIONSTATE_LOCK, WTS_SESSIONSTATE_UNLOCK,
};
use windows::Win32::System::SystemInformation::GetTickCount64;
use windows::Win32::System::Threading::GetCurrentProcessId;
use windows::Win32::System::WindowsProgramming::QueryUnbiasedInterruptTime;
use windows::Win32::UI::WindowsAndMessaging::{
    WTS_CONSOLE_CONNECT, WTS_CONSOLE_DISCONNECT, WTS_REMOTE_CONNECT, WTS_REMOTE_DISCONNECT,
    WTS_SESSION_LOCK, WTS_SESSION_UNLOCK,
};

use crate::lock::{LockState, Moment, Session};

/// Start locking the PC. Success does not mean it is locked.
pub fn lock() -> Result<(), String> {
    if cfg!(debug_assertions) {
        crate::audit::log("lock: debug build, so LockWorkStation was not called");
        return Ok(());
    }
    crate::audit::log("lock: locking the PC");
    unsafe { windows::Win32::System::Shutdown::LockWorkStation() }.map_err(|e| e.message())
}

/// Ask Windows to report locks, unlocks and connections to `hwnd`.
pub fn register(hwnd: HWND) -> bool {
    unsafe { WTSRegisterSessionNotification(hwnd, NOTIFY_FOR_THIS_SESSION) }.is_ok()
}

/// Must run before the window is destroyed.
pub fn unregister(hwnd: HWND) {
    unsafe {
        let _ = WTSUnRegisterSessionNotification(hwnd);
    }
}

/// Apply a `WM_WTSSESSION_CHANGE` to what is known about the session.
///
/// A disconnect does not clear a known lock, and is not one.
pub fn note_change(session: &mut Session, event: u32, session_id: u32) {
    if own_session_id().is_some_and(|own| own != session_id) {
        return;
    }
    match event {
        WTS_SESSION_LOCK => session.lock = LockState::Locked,
        WTS_SESSION_UNLOCK => session.lock = LockState::Unlocked,
        WTS_CONSOLE_CONNECT | WTS_REMOTE_CONNECT => session.connected = true,
        WTS_CONSOLE_DISCONNECT | WTS_REMOTE_DISCONNECT => session.connected = false,
        _ => {}
    }
}

fn own_session_id() -> Option<u32> {
    let mut id = 0;
    unsafe { ProcessIdToSessionId(GetCurrentProcessId(), &mut id) }
        .is_ok()
        .then_some(id)
}

/// The session at startup. Anything that cannot be read is unknown.
pub fn query() -> Session {
    match session_info() {
        Some(info) => Session {
            lock: match info.SessionFlags as u32 {
                WTS_SESSIONSTATE_LOCK => LockState::Locked,
                WTS_SESSIONSTATE_UNLOCK => LockState::Unlocked,
                _ => LockState::Unknown,
            },
            connected: info.SessionState == WTSActive,
        },
        None => Session {
            lock: LockState::Unknown,
            connected: true,
        },
    }
}

/// Session details, only from a successful query of the expected level: a
/// zeroed buffer would otherwise read as locked.
fn session_info() -> Option<WTSINFOEX_LEVEL1_W> {
    unsafe {
        let mut buffer = PWSTR::null();
        let mut bytes = 0;
        WTSQuerySessionInformationW(
            None,
            WTS_CURRENT_SESSION,
            WTSSessionInfoEx,
            &mut buffer,
            &mut bytes,
        )
        .ok()?;
        let whole = bytes as usize >= std::mem::size_of::<WTSINFOEXW>();
        let mut info = None;
        if !buffer.is_null() && whole {
            let raw = buffer.0.cast::<WTSINFOEXW>().read_unaligned();
            if raw.Level == 1 {
                info = Some(raw.Data.WTSInfoExLevel1);
            }
        }
        WTSFreeMemory(buffer.0.cast());
        info
    }
}

/// Identifies this sign-in: its logon time, or a value unique to this process
/// when that cannot be read.
fn sign_in() -> i64 {
    use std::sync::OnceLock;
    static SIGN_IN: OnceLock<i64> = OnceLock::new();
    *SIGN_IN.get_or_init(|| match session_info().map(|i| i.LogonTime) {
        Some(time) if time > 0 => time,
        _ => -wall(),
    })
}

fn wall() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_millis() as i64)
}

/// The current time on every clock the lock engine needs.
pub fn moment() -> Moment {
    let mut unbiased = 0u64;
    unsafe {
        let _ = QueryUnbiasedInterruptTime(&mut unbiased);
    }
    Moment {
        wall: wall(),
        tick: unsafe { GetTickCount64() } as i64,
        awake: (unbiased / 10_000) as i64,
        sign_in: sign_in(),
    }
}