artifactize-tools 0.27.0

Portable scoped tools and safe file access for artifactize.
Documentation
//! Windows desktop handoff through ShellExecute.

use std::{ffi::OsStr, io, os::windows::ffi::OsStrExt, ptr};
use windows_sys::Win32::UI::{Shell::ShellExecuteW, WindowsAndMessaging::SW_SHOWNORMAL};

/// Hand off without blocking the async runtime. The native call exposes no owned child or
/// cancellation handle; stop waiting at the deadline or interrupt, never kill the user's app.
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();
    // A blocked shell callback must not keep runtime shutdown waiting either.
    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)?
        }
    }
}

/// ShellExecuteW returns an error code at or below 32; greater values mean a successful
/// desktop handoff, not a handle that this process owns.
const SHELL_EXECUTE_ERROR_MAX: isize = 32;

fn shell_execute(target: &OsStr) -> io::Result<()> {
    handoff(target, |target| {
        // SAFETY: handoff supplies a NUL-terminated target alive for this call.
        // No verb, parameters or directory: the file/URL is one literal target.
        unsafe {
            ShellExecuteW(
                ptr::null_mut(),
                ptr::null(),
                target.as_ptr(),
                ptr::null(),
                ptr::null(),
                SW_SHOWNORMAL,
            ) as isize
        }
    })
}

/// The native handoff boundary can be observed without changing a user's default apps.
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);
    // ShellExecute returns a value greater than 32 on success, not an owned handle.
    if result <= SHELL_EXECUTE_ERROR_MAX {
        return Err(io::Error::other(format!(
            "ShellExecute could not open the target (code {result})."
        )));
    }
    Ok(())
}

// Windows has a ShellExecute handoff, not a Unix opener subprocess. Observe its
// native argument seam without launching a browser or changing file associations.
#[cfg(test)]
mod tests;