use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Command as ProcessCommand;
use crossbeam_channel::Receiver;
use nativeview_cli::manifest::NvManifest;
use crate::build::host_cache::{ensure_host_shell, HostShell};
use crate::build::apple::macos_bundle::{macos_bundle_id, package_or_reuse_macos_dev_bundle};
use crate::build::pipeline::append_manifest_shell_args;
use crate::cargo_env::{AppContext, NvSdkRoot};
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum SkiaLaunchMode {
Direct,
MacosAppBundle {
out_dir: PathBuf,
bundle_id: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SkiaDevLaunchPlan {
pub mode: SkiaLaunchMode,
pub args: Vec<OsString>,
}
pub(crate) fn wait_for_skia_launch_ready(
initial_ok: bool,
ready_rx: &Receiver<()>,
) -> Result<(), &'static str> {
if initial_ok {
return Ok(());
}
ready_rx
.recv()
.map_err(|_| "watch loop terminated before first successful rebuild")
}
pub(crate) fn resolve_explicit_skia_shell_bin(
explicit: &std::ffi::OsStr,
) -> Result<PathBuf, String> {
let p = PathBuf::from(explicit);
if !p.as_os_str().is_empty() && p.is_file() {
Ok(p)
} else {
Err(format!(
"NV_SKIA_SHELL_BIN='{}' does not exist or is not a regular file",
p.display()
))
}
}
fn resolve_skia_shell_binary(
sdk_root: &NvSdkRoot,
target_dir: &Path,
) -> Result<PathBuf, String> {
if let Some(explicit) = std::env::var_os("NV_SKIA_SHELL_BIN") {
return resolve_explicit_skia_shell_bin(&explicit);
}
println!("[dev] ensuring binary-only host `nativeview-skia-shell` is up to date...");
let host = ensure_host_shell(sdk_root, target_dir, HostShell::Skia, false, &[])?;
Ok(host.binary_path)
}
pub(crate) fn skia_shell_args(
dylib_path: &Path,
ws_url: &str,
manifest: &NvManifest,
) -> Vec<OsString> {
let mut args = vec![
OsString::from("--dylib"),
dylib_path.as_os_str().to_os_string(),
OsString::from("--ws"),
OsString::from(ws_url),
];
let mut manifest_args = Vec::new();
append_manifest_shell_args(&mut manifest_args, manifest);
args.extend(manifest_args.into_iter().map(OsString::from));
args
}
pub(crate) fn plan_skia_dev_launch(
app: &AppContext,
manifest: &NvManifest,
dylib_path: &Path,
ws_url: &str,
is_macos: bool,
) -> SkiaDevLaunchPlan {
let args = skia_shell_args(dylib_path, ws_url, manifest);
let mode = if is_macos && manifest.requires_macos_app_bundle() {
let info = app.manifest_app_info();
SkiaLaunchMode::MacosAppBundle {
out_dir: app
.target_directory
.join("nv-dev")
.join("bundles")
.join(&app.lib_name),
bundle_id: macos_bundle_id(manifest, &info, HostShell::Skia),
}
} else {
SkiaLaunchMode::Direct
};
SkiaDevLaunchPlan { mode, args }
}
pub(crate) struct ChildProcessGuard(pub(crate) Option<std::process::Child>);
impl ChildProcessGuard {
fn wait(mut self) -> std::io::Result<std::process::ExitStatus> {
let res = self.0.as_mut().expect("ChildProcessGuard active").wait();
if res.is_ok() {
self.0 = None;
}
res
}
}
impl Drop for ChildProcessGuard {
fn drop(&mut self) {
if let Some(mut child) = self.0.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}
pub(crate) fn run_skia_shell_subprocess(
app: &AppContext,
sdk_root: &NvSdkRoot,
manifest: &NvManifest,
dylib_path: &Path,
ws_url: &str,
) -> Result<(), String> {
let plan = plan_skia_dev_launch(app, manifest, dylib_path, ws_url, cfg!(target_os = "macos"));
let shell_bin = resolve_skia_shell_binary(sdk_root, &app.target_directory)?;
let launch_bin = match &plan.mode {
SkiaLaunchMode::Direct => shell_bin,
SkiaLaunchMode::MacosAppBundle { out_dir, bundle_id } => {
let info = app.manifest_app_info();
let (executable_path, reused) = package_or_reuse_macos_dev_bundle(
out_dir,
manifest,
&info,
HostShell::Skia,
&shell_bin,
)?;
if reused {
println!("[dev] reusing cached macOS `.app` bundle ({bundle_id})");
} else {
println!("[dev] packaged signed macOS `.app` bundle ({bundle_id}) for TCC/presence");
}
executable_path
}
};
let child = ProcessCommand::new(&launch_bin)
.args(&plan.args)
.spawn()
.map_err(|e| format!("failed to launch '{}': {e}", launch_bin.display()))?;
let guard = ChildProcessGuard(Some(child));
let status = guard
.wait()
.map_err(|e| format!("failed waiting for '{}': {e}", launch_bin.display()))?;
if status.success() {
Ok(())
} else {
Err(format!("`{}` exited with status {status}", launch_bin.display()))
}
}