use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use crate::cargo_env::{
build_artifact, build_artifact_with_siblings, ArtifactKind, BuildArtifactSpec, NvSdkRoot,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HostShell {
Macos,
Skia,
Gtk,
Qt,
Windows,
View,
Compose,
}
impl HostShell {
pub(crate) fn parse(raw: &str) -> Result<Self, String> {
let s = raw.trim();
if s.eq_ignore_ascii_case("macos") {
Ok(Self::Macos)
} else if s.eq_ignore_ascii_case("skia") {
Ok(Self::Skia)
} else if s.eq_ignore_ascii_case("gtk") {
Ok(Self::Gtk)
} else if s.eq_ignore_ascii_case("qt") {
Ok(Self::Qt)
} else if s.eq_ignore_ascii_case("windows") {
Ok(Self::Windows)
} else if s.eq_ignore_ascii_case("view") {
Ok(Self::View)
} else if s.eq_ignore_ascii_case("compose") {
Ok(Self::Compose)
} else {
Err(format!(
"unknown --shell '{s}' (expected one of: macos, skia, gtk, qt, windows, view, compose)"
))
}
}
pub(crate) const fn as_str(self) -> &'static str {
match self {
Self::Macos => "macos",
Self::Skia => "skia",
Self::Gtk => "gtk",
Self::Qt => "qt",
Self::Windows => "windows",
Self::View => "view",
Self::Compose => "compose",
}
}
pub(crate) const fn cmake_host_dir(self) -> Option<&'static str> {
match self {
Self::Macos => Some("macos-shell"),
Self::Gtk => Some("gtk-shell"),
Self::Qt => Some("qt-shell"),
Self::Windows => Some("windows-shell"),
Self::Skia | Self::View | Self::Compose => None,
}
}
pub(crate) const fn cmake_target_name(self) -> Option<&'static str> {
match self {
Self::Macos => Some("nv_macos_shell"),
Self::Gtk => Some("nv_gtk_shell"),
Self::Qt => Some("nv_qt_shell"),
Self::Windows => Some("nv_windows_shell"),
Self::Skia | Self::View | Self::Compose => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct BuiltHostShell {
pub binary_path: PathBuf,
pub a11y_dll_path: Option<PathBuf>,
}
pub(crate) fn modules_cache_key(modules: &[String]) -> String {
if modules.is_empty() {
"base".to_owned()
} else {
modules.join("+")
}
}
pub(crate) fn host_cache_dir(
target_dir: &Path,
shell: HostShell,
release: bool,
modules: &[String],
) -> PathBuf {
let profile = if release { "release" } else { "debug" };
let key = modules_cache_key(modules);
target_dir
.join("nv-hosts")
.join(format!("{}-{profile}-{key}", shell.as_str()))
}
pub(crate) fn cmake_build_type(release: bool) -> &'static str {
if release { "Release" } else { "Debug" }
}
pub(crate) fn staticlib_suffix_for_windows_msvc(is_windows_msvc: bool) -> &'static str {
if is_windows_msvc { ".lib" } else { ".a" }
}
pub(crate) fn push_apple_clang_pins(args: &mut Vec<String>) {
args.push("-DCMAKE_C_COMPILER=/usr/bin/clang".to_owned());
args.push("-DCMAKE_CXX_COMPILER=/usr/bin/clang++".to_owned());
args.push("-DCMAKE_OBJC_COMPILER=/usr/bin/clang".to_owned());
args.push("-DCMAKE_OBJCXX_COMPILER=/usr/bin/clang++".to_owned());
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn cmake_configure_args(
source_dir: &Path,
build_dir: &Path,
shell: HostShell,
release: bool,
modules: &[String],
prebuilt_runtime_lib: &Path,
win_a11y: Option<(&Path, &Path)>,
use_ninja: bool,
is_macos_host: bool,
) -> Vec<String> {
let mut args = vec![
"-S".to_owned(),
source_dir.display().to_string(),
"-B".to_owned(),
build_dir.display().to_string(),
];
if use_ninja {
args.push("-G".to_owned());
args.push("Ninja".to_owned());
}
args.push(format!("-DCMAKE_BUILD_TYPE={}", cmake_build_type(release)));
args.push("-DNV_SKIP_CODEGEN=ON".to_owned());
args.push(format!("-DNV_RUNTIME_PREBUILT_LIB={}", prebuilt_runtime_lib.display()));
args.push("-DNV_HOST_SANITIZE=OFF".to_owned());
args.push(format!("-DNV_MODULES={}", modules.join(";")));
if is_macos_host {
push_apple_clang_pins(&mut args);
}
if shell == HostShell::Windows
&& let Some((dll, implib)) = win_a11y
{
args.push(format!("-DNV_A11Y_WIN_PREBUILT_DLL={}", dll.display()));
args.push(format!("-DNV_A11Y_WIN_PREBUILT_IMPLIB={}", implib.display()));
}
args
}
pub(crate) fn reset_stale_cmake_cache(
build_dir: &Path,
expected_source_dir: &Path,
expected_generator: Option<&str>,
) -> Result<bool, String> {
let cache = build_dir.join("CMakeCache.txt");
if !cache.is_file() {
return Ok(false);
}
let text = fs::read_to_string(&cache)
.map_err(|e| format!("failed to read '{}': {e}", cache.display()))?;
let cached_src = text
.lines()
.find_map(|line| line.strip_prefix("CMAKE_HOME_DIRECTORY:INTERNAL="))
.map(str::trim);
let src_mismatch = cached_src.is_some_and(|raw| {
let cached_path = Path::new(raw);
let same = cached_path == expected_source_dir
|| (fs::canonicalize(cached_path).ok() == fs::canonicalize(expected_source_dir).ok()
&& fs::canonicalize(expected_source_dir).is_ok());
!same
});
let cached_gen = text
.lines()
.find_map(|line| line.strip_prefix("CMAKE_GENERATOR:INTERNAL="))
.map(str::trim);
let gen_mismatch = match (expected_generator, cached_gen) {
(Some(want), Some(have)) => !want.eq_ignore_ascii_case(have),
(None, Some(have)) => have.eq_ignore_ascii_case("Ninja"),
_ => false,
};
if src_mismatch || gen_mismatch {
fs::remove_dir_all(build_dir).map_err(|e| {
format!("failed to clear stale CMake build dir '{}': {e}", build_dir.display())
})?;
return Ok(true);
}
Ok(false)
}
pub(crate) fn should_use_ninja_for_host(
is_windows_msvc: bool,
has_ninja: bool,
has_cl_on_path: bool,
) -> bool {
if is_windows_msvc { has_ninja && has_cl_on_path } else { has_ninja }
}
pub(crate) fn expected_cmake_generator(use_ninja: bool) -> Option<&'static str> {
use_ninja.then_some("Ninja")
}
fn has_tool_on_path(bin: &str, arg: &str) -> bool {
Command::new(bin).arg(arg).output().map(|o| o.status.success()).unwrap_or(false)
}
pub(crate) fn has_ninja_on_path() -> bool {
has_tool_on_path("ninja", "--version")
}
fn has_cl_on_path() -> bool {
#[cfg(all(windows, target_env = "msvc"))]
{
Command::new("cl.exe").output().is_ok()
}
#[cfg(not(all(windows, target_env = "msvc")))]
{
false
}
}
pub(crate) fn cmake_build_args(
build_dir: &Path,
target_name: &str,
release: bool,
multi_config: bool,
) -> Vec<String> {
let mut args = vec![
"--build".to_owned(),
build_dir.display().to_string(),
"--target".to_owned(),
target_name.to_owned(),
];
if multi_config {
args.push("--config".to_owned());
args.push(cmake_build_type(release).to_owned());
}
args.push("--parallel".to_owned());
args
}
pub(crate) fn locate_cmake_shell_binary(
build_dir: &Path,
target_name: &str,
release: bool,
exe_suffix: &str,
) -> Option<PathBuf> {
let filename = format!("{target_name}{exe_suffix}");
let config = cmake_build_type(release);
let candidates = [build_dir.join(&filename), build_dir.join(config).join(&filename)];
candidates.into_iter().find(|p| p.is_file())
}
pub(crate) fn prebuild_runtime_spec(
sdk_root: &Path,
target_dir: &Path,
release: bool,
is_windows_msvc: bool,
) -> BuildArtifactSpec {
BuildArtifactSpec {
manifest_path: Some(sdk_root.join("Cargo.toml")),
working_dir: sdk_root.to_path_buf(),
package: "nativeview-runtime".to_owned(),
package_id: String::new(),
artifact_name: "nv_runtime".to_owned(),
kind: ArtifactKind::Staticlib,
crate_type_override: Some("staticlib"),
target_triple: None,
no_default_features: false,
features: Vec::new(),
release,
locked: sdk_root.join("Cargo.lock").is_file(),
target_dir: Some(target_dir.to_path_buf()),
env: BTreeMap::new(),
expected_suffix: staticlib_suffix_for_windows_msvc(is_windows_msvc).to_owned(),
}
}
pub(crate) fn prebuild_win_a11y_spec(
sdk_root: &Path,
target_dir: &Path,
release: bool,
) -> BuildArtifactSpec {
BuildArtifactSpec {
manifest_path: Some(sdk_root.join("Cargo.toml")),
working_dir: sdk_root.to_path_buf(),
package: "nativeview-accessibility-windows".to_owned(),
package_id: String::new(),
artifact_name: "nativeview_accessibility_windows".to_owned(),
kind: ArtifactKind::Cdylib,
crate_type_override: Some("cdylib"),
target_triple: None,
no_default_features: false,
features: Vec::new(),
release,
locked: sdk_root.join("Cargo.lock").is_file(),
target_dir: Some(target_dir.to_path_buf()),
env: BTreeMap::new(),
expected_suffix: ".dll".to_owned(),
}
}
pub(crate) fn select_windows_implib(
siblings: &[PathBuf],
dll_dir: &Path,
is_msvc: bool,
) -> Option<PathBuf> {
let preferred_order = if is_msvc {
[".dll.lib", ".dll.a"]
} else {
[".dll.a", ".dll.lib"]
};
for suffix in preferred_order {
if let Some(hit) = siblings.iter().find(|p| p.to_string_lossy().ends_with(suffix) && p.is_file()) {
return Some(hit.clone());
}
}
let disk_order = if is_msvc {
["nativeview_accessibility_windows.dll.lib", "libnativeview_accessibility_windows.dll.a"]
} else {
["libnativeview_accessibility_windows.dll.a", "nativeview_accessibility_windows.dll.lib"]
};
disk_order.into_iter().map(|n| dll_dir.join(n)).find(|p| p.is_file())
}
fn prebuild_nv_runtime(
sdk_root: &NvSdkRoot,
target_dir: &Path,
release: bool,
) -> Result<PathBuf, String> {
if sdk_root.is_packaged_sdk() {
let triple = crate::cargo_env::host_target_triple()
.ok_or_else(|| "could not determine host target triple via `rustc -vV`".to_owned())?;
return crate::cargo_env::sdk::resolve_prebuilt_runtime_lib(sdk_root, triple)?
.ok_or_else(|| {
format!(
"packaged SDK at '{}' does not provide a prebuilt `libnv_runtime` for '{triple}' (reinstall with `nv sdk install --force`)",
sdk_root.path().display()
)
});
}
let spec = prebuild_runtime_spec(
sdk_root.path(),
target_dir,
release,
cfg!(all(windows, target_env = "msvc")),
);
build_artifact(&spec)
}
fn prebuild_windows_a11y(
sdk_root: &NvSdkRoot,
target_dir: &Path,
release: bool,
) -> Result<Option<(PathBuf, PathBuf)>, String> {
if sdk_root.is_packaged_sdk() {
let triple = crate::cargo_env::host_target_triple().unwrap_or("x86_64-pc-windows-msvc");
return crate::cargo_env::sdk::resolve_prebuilt_win_a11y(sdk_root, triple);
}
let (dll, siblings) =
build_artifact_with_siblings(&prebuild_win_a11y_spec(sdk_root.path(), target_dir, release))?;
let dir = dll.parent().unwrap_or(target_dir);
let implib = select_windows_implib(&siblings, dir, cfg!(target_env = "msvc")).ok_or_else(|| {
format!(
"built '{}' but neither nativeview_accessibility_windows.dll.lib nor libnativeview_accessibility_windows.dll.a was found in '{}'",
dll.display(),
dir.display()
)
})?;
Ok(Some((dll, implib)))
}
fn build_skia_shell(
sdk_root: &NvSdkRoot,
target_dir: &Path,
release: bool,
) -> Result<BuiltHostShell, String> {
if sdk_root.is_packaged_sdk() {
let triple = crate::cargo_env::host_target_triple()
.ok_or_else(|| "could not determine host target triple via `rustc -vV`".to_owned())?;
let binary_path = crate::cargo_env::sdk::resolve_prebuilt_skia_shell(sdk_root, triple)?
.ok_or_else(|| {
format!(
"packaged SDK at '{}' does not provide a prebuilt `nv-skia-shell` for '{triple}' (reinstall with `nv sdk install --force`)",
sdk_root.path().display()
)
})?;
return Ok(BuiltHostShell { binary_path, a11y_dll_path: None });
}
let sdk = sdk_root.path();
println!("==> Building host shell 'nativeview-skia-shell'...");
let binary_path = build_artifact(&BuildArtifactSpec {
manifest_path: Some(sdk.join("Cargo.toml")),
working_dir: sdk.to_path_buf(),
package: "nativeview-skia-shell".to_owned(),
package_id: String::new(),
artifact_name: "nativeview-skia-shell".to_owned(),
kind: ArtifactKind::Bin,
crate_type_override: None,
target_triple: None,
no_default_features: false,
features: Vec::new(),
release,
locked: sdk.join("Cargo.lock").is_file(),
target_dir: Some(target_dir.to_path_buf()),
env: BTreeMap::new(),
expected_suffix: std::env::consts::EXE_SUFFIX.to_owned(),
})?;
Ok(BuiltHostShell { binary_path, a11y_dll_path: None })
}
pub(crate) fn ensure_host_shell(
sdk_root: &NvSdkRoot,
target_dir: &Path,
shell: HostShell,
release: bool,
modules: &[String],
) -> Result<BuiltHostShell, String> {
if shell == HostShell::Skia {
return build_skia_shell(sdk_root, target_dir, release);
}
let host_dir = shell
.cmake_host_dir()
.ok_or_else(|| format!("shell '{}' has no CMake host directory", shell.as_str()))?;
let target_name = shell
.cmake_target_name()
.ok_or_else(|| format!("shell '{}' has no CMake target", shell.as_str()))?;
let source_dir = sdk_root.path().join("hosts").join(host_dir);
if !source_dir.join("CMakeLists.txt").is_file() {
return Err(format!("missing host CMakeLists.txt at '{}'", source_dir.display()));
}
println!("==> Ensuring generated ABI headers...");
crate::codegen::ensure_sdk_abi_headers(sdk_root)?;
println!("==> Resolving nativeview-runtime staticlib...");
let runtime_lib = prebuild_nv_runtime(sdk_root, target_dir, release)?;
let win_a11y = if shell == HostShell::Windows {
println!("==> Resolving nativeview-accessibility-windows cdylib...");
prebuild_windows_a11y(sdk_root, target_dir, release)?
} else {
None
};
let build_dir = host_cache_dir(target_dir, shell, release, modules);
let use_ninja = should_use_ninja_for_host(
cfg!(all(windows, target_env = "msvc")),
has_ninja_on_path(),
has_cl_on_path(),
);
reset_stale_cmake_cache(&build_dir, &source_dir, expected_cmake_generator(use_ninja))?;
let cfg_args = cmake_configure_args(
&source_dir,
&build_dir,
shell,
release,
modules,
&runtime_lib,
win_a11y.as_ref().map(|(d, i)| (d.as_path(), i.as_path())),
use_ninja,
cfg!(target_os = "macos"),
);
println!(
"==> Configuring '{}' (modules={})...",
target_name,
modules_cache_key(modules)
);
let cfg_status = Command::new("cmake")
.args(&cfg_args)
.status()
.map_err(|e| format!("failed to run `cmake` configure: {e}"))?;
if !cfg_status.success() {
return Err(format!("`cmake` configure for '{target_name}' failed with {cfg_status}"));
}
println!("==> Building '{target_name}'...");
let multi_config = cfg!(windows) && !use_ninja;
let build_args = cmake_build_args(&build_dir, target_name, release, multi_config);
let build_status = Command::new("cmake")
.args(&build_args)
.status()
.map_err(|e| format!("failed to run `cmake --build`: {e}"))?;
if !build_status.success() {
return Err(format!("`cmake --build` for '{target_name}' failed with {build_status}"));
}
let binary_path =
locate_cmake_shell_binary(&build_dir, target_name, release, std::env::consts::EXE_SUFFIX)
.ok_or_else(|| {
format!(
"CMake build succeeded but '{target_name}' was not found under '{}'",
build_dir.display()
)
})?;
Ok(BuiltHostShell { binary_path, a11y_dll_path: win_a11y.map(|(d, _)| d) })
}