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};
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())
}
pub fn register(hwnd: HWND) -> bool {
unsafe { WTSRegisterSessionNotification(hwnd, NOTIFY_FOR_THIS_SESSION) }.is_ok()
}
pub fn unregister(hwnd: HWND) {
unsafe {
let _ = WTSUnRegisterSessionNotification(hwnd);
}
}
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)
}
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,
},
}
}
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
}
}
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)
}
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(),
}
}