use std::ffi::OsString;
use std::io;
use std::os::windows::ffi::OsStringExt;
use std::path::Path;
use std::ptr;
use std::thread;
use std::time::{Duration, Instant};
use windows_sys::Win32::Foundation::{
CloseHandle, ERROR_INVALID_PARAMETER, HANDLE, HWND, WAIT_ABANDONED, WAIT_OBJECT_0, WAIT_TIMEOUT,
};
use windows_sys::Win32::System::Threading::{
CreateMutexW, GetCurrentProcessId, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
PROCESS_SYNCHRONIZE, PROCESS_TERMINATE, QueryFullProcessImageNameW, ReleaseMutex,
TerminateProcess, WaitForSingleObject,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{
FindWindowExW, GetWindowThreadProcessId, PostMessageW, WM_APP,
};
use super::diagnostics;
use super::platform::{SingleInstance, wide};
pub(crate) const WINDOW_CLASS: &str = "BrightWheel.HiddenWindow";
pub(crate) const WINDOW_TITLE: &str = "BrightWheel";
pub(crate) const EXIT_FOR_UPDATE: u32 = WM_APP + 5;
const INSTANCE_MUTEX: &str = "Local\\BrightWheel.Singleton";
const STARTUP_MUTEX: &str = "Local\\BrightWheel.Startup";
pub(crate) struct StartupGate(HANDLE);
impl StartupGate {
fn acquire() -> io::Result<Self> {
let name = wide(STARTUP_MUTEX);
let handle = unsafe { CreateMutexW(ptr::null(), 0, name.as_ptr()) };
if handle.is_null() {
return Err(io::Error::last_os_error());
}
let result = unsafe { WaitForSingleObject(handle, 15_000) };
if result == WAIT_OBJECT_0 || result == WAIT_ABANDONED {
Ok(Self(handle))
} else {
let error = if result == WAIT_TIMEOUT {
io::Error::new(
io::ErrorKind::TimedOut,
"another BrightWheel launch is still starting",
)
} else {
io::Error::last_os_error()
};
unsafe { CloseHandle(handle) };
Err(error)
}
}
}
impl Drop for StartupGate {
fn drop(&mut self) {
unsafe {
ReleaseMutex(self.0);
CloseHandle(self.0);
}
}
}
pub(crate) fn begin(skip_if_running: bool) -> io::Result<Option<(SingleInstance, StartupGate)>> {
let gate = StartupGate::acquire()?;
let deadline = Instant::now() + Duration::from_secs(3);
loop {
let instance = SingleInstance::acquire(INSTANCE_MUTEX)?;
if !instance.already_running() {
return Ok(Some((instance, gate)));
}
if skip_if_running {
return Ok(None);
}
let window = find_running_window();
if !window.is_null() && replace_existing(window)? {
return Ok(Some((instance, gate)));
}
drop(instance);
if Instant::now() >= deadline {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"BrightWheel is running, but its application window could not be located",
));
}
thread::sleep(Duration::from_millis(50));
}
}
pub(crate) fn find_running_window() -> HWND {
let class = wide(WINDOW_CLASS);
let title = wide(WINDOW_TITLE);
unsafe {
FindWindowExW(
ptr::null_mut(),
ptr::null_mut(),
class.as_ptr(),
title.as_ptr(),
)
}
}
pub(crate) fn request_exit(expected_pid: Option<u32>) -> io::Result<()> {
let window = find_running_window();
if window.is_null() {
return Ok(());
}
let mut pid = 0;
unsafe { GetWindowThreadProcessId(window, &mut pid) };
if expected_pid.is_some_and(|expected| pid != expected) {
return Ok(());
}
if unsafe { PostMessageW(window, EXIT_FOR_UPDATE, 0, 0) } == 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
struct Process(HANDLE);
impl Drop for Process {
fn drop(&mut self) {
unsafe { CloseHandle(self.0) };
}
}
fn replace_existing(window: HWND) -> io::Result<bool> {
let mut pid = 0;
unsafe { GetWindowThreadProcessId(window, &mut pid) };
if pid == 0 {
return Ok(false);
}
if pid == unsafe { GetCurrentProcessId() } {
return Err(io::Error::other("invalid BrightWheel instance identity"));
}
let handle = unsafe {
OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE | PROCESS_TERMINATE,
0,
pid,
)
};
if handle.is_null() {
let error = io::Error::last_os_error();
return if error.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32) {
Ok(false)
} else {
Err(error)
};
}
let process = Process(handle);
let mut path = vec![0_u16; 32768];
let mut length = path.len() as u32;
if unsafe { QueryFullProcessImageNameW(process.0, 0, path.as_mut_ptr(), &mut length) } == 0 {
let error = io::Error::last_os_error();
return if unsafe { WaitForSingleObject(process.0, 0) } == WAIT_OBJECT_0 {
Ok(false)
} else {
Err(error)
};
}
let path = OsString::from_wide(&path[..length as usize]);
let executable = std::env::current_exe()?;
let existing_name = Path::new(&path)
.file_name()
.unwrap_or_default()
.to_string_lossy();
let current_name = executable.file_name().unwrap_or_default().to_string_lossy();
if !existing_name.eq_ignore_ascii_case(¤t_name)
&& !existing_name.eq_ignore_ascii_case("brightwheel.exe")
{
return Err(io::Error::other(
"the existing window does not belong to BrightWheel",
));
}
let mut current_pid = 0;
unsafe { GetWindowThreadProcessId(window, &mut current_pid) };
if current_pid != pid {
return Ok(false);
}
diagnostics::log(&format!("relaunch: requesting shutdown of pid={pid}"));
unsafe { PostMessageW(window, EXIT_FOR_UPDATE, 0, 0) };
let status = unsafe { WaitForSingleObject(process.0, 1500) };
if status == WAIT_OBJECT_0 {
return Ok(true);
}
if status != WAIT_TIMEOUT {
return Err(io::Error::last_os_error());
}
diagnostics::log(&format!("relaunch: terminating unresponsive pid={pid}"));
if unsafe { TerminateProcess(process.0, 0) } == 0 {
if unsafe { WaitForSingleObject(process.0, 0) } != WAIT_OBJECT_0 {
return Err(io::Error::last_os_error());
}
}
if unsafe { WaitForSingleObject(process.0, 5000) } != WAIT_OBJECT_0 {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"BrightWheel did not stop",
));
}
Ok(true)
}