use std::{ffi::OsStr, io, os::windows::ffi::OsStrExt, ptr};
use windows_sys::Win32::UI::{Shell::ShellExecuteW, WindowsAndMessaging::SW_SHOWNORMAL};
pub(crate) async fn open_desktop(
target: &OsStr,
deadline: std::time::Duration,
cancellation: &tokio_util::sync::CancellationToken,
) -> io::Result<()> {
use crate::platform::process::{handoff_cancelled, handoff_timeout};
if cancellation.is_cancelled() {
return Err(handoff_cancelled());
}
#[cfg(feature = "fixture-opener")]
if let Some(program) = std::env::var_os("ARTIFACTIZE_E2E_BROWSER_PROGRAM") {
let node = std::env::var_os("ARTIFACTIZE_E2E_BROWSER_NODE").ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"the fixture opener requires its declared executable",
)
})?;
let mut command = tokio::process::Command::new(node);
command.arg(program).arg(target);
let status =
crate::platform::process::handoff(&mut command, deadline, cancellation).await?;
return if status.success() {
Ok(())
} else {
Err(io::Error::other(format!("fixture opener exited {status}")))
};
}
let target = target.to_owned();
let (send, receive) = tokio::sync::oneshot::channel();
let pending = cancellation.clone();
std::thread::Builder::new()
.name("desktop-handoff".into())
.spawn(move || {
let _ = send.send(if pending.is_cancelled() {
Err(handoff_cancelled())
} else {
shell_execute(&target)
});
})?;
tokio::select! {
biased;
_ = cancellation.cancelled() => Err(handoff_cancelled()),
result = tokio::time::timeout(deadline, receive) => {
result.map_err(|_| handoff_timeout())?.map_err(io::Error::other)?
}
}
}
const SHELL_EXECUTE_ERROR_MAX: isize = 32;
fn shell_execute(target: &OsStr) -> io::Result<()> {
handoff(target, |target| {
unsafe {
ShellExecuteW(
ptr::null_mut(),
ptr::null(),
target.as_ptr(),
ptr::null(),
ptr::null(),
SW_SHOWNORMAL,
) as isize
}
})
}
fn handoff(target: &OsStr, execute: impl FnOnce(&[u16]) -> isize) -> io::Result<()> {
let mut target: Vec<_> = target.encode_wide().collect();
if target.contains(&0) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Open target contains NUL.",
));
}
target.push(0);
let result = execute(&target);
if result <= SHELL_EXECUTE_ERROR_MAX {
return Err(io::Error::other(format!(
"ShellExecute could not open the target (code {result})."
)));
}
Ok(())
}
#[cfg(test)]
mod tests;