use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use nativeview_cli::manifest::{ManifestAppInfo, NvManifest};
use super::macos_bundle::{run_checked, set_mode, sign_apple_bundle};
use crate::build::host_cache::{
cmake_build_args, cmake_build_type, expected_cmake_generator, has_ninja_on_path,
locate_cmake_shell_binary, modules_cache_key, push_apple_clang_pins, reset_stale_cmake_cache,
};
use crate::cargo_env::{build_artifact, AppContext, ArtifactKind, BuildArtifactSpec, NvSdkRoot};
pub(crate) const IOS_SIM_RUST_TARGET: &str = "aarch64-apple-ios-sim";
pub(crate) const IOS_SIM_CMAKE_TARGET: &str = "nv_ios_shell";
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct IosSimBundleOutput {
pub app_bundle: PathBuf,
pub executable_path: PathBuf,
pub dylib_path: Option<PathBuf>,
pub plist_path: PathBuf,
pub bundle_id: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SimDevice {
pub udid: String,
pub name: String,
pub state: String,
pub runtime: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum SimulatorGuiApp {
SimulatorApp(PathBuf),
DeviceHubApp(PathBuf),
OpenByName,
}
pub(crate) fn ios_sim_host_cache_dir(
target_dir: &Path,
release: bool,
min_ios: &str,
modules: &[String],
) -> PathBuf {
let profile = if release { "release" } else { "debug" };
let key = modules_cache_key(modules);
target_dir.join("nv-hosts").join(format!("ios-sim-shell-{profile}-ios{min_ios}-{key}"))
}
pub(crate) fn ios_cargo_env(sdkroot: Option<&str>, min_ios: &str) -> BTreeMap<String, String> {
let mut env = BTreeMap::new();
if let Some(root) = sdkroot
&& !root.trim().is_empty()
{
env.insert("SDKROOT".to_owned(), root.trim().to_owned());
}
env.insert("IPHONEOS_DEPLOYMENT_TARGET".to_owned(), min_ios.to_owned());
env
}
pub(crate) fn ios_runtime_staticlib_spec(
sdk_root: &Path,
target_dir: &Path,
rust_triple: &str,
release: bool,
sdkroot: Option<&str>,
min_ios: &str,
) -> 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: Some(rust_triple.to_owned()),
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: ios_cargo_env(sdkroot, min_ios),
expected_suffix: ".a".to_owned(),
}
}
pub(crate) fn ios_sim_runtime_spec(
sdk_root: &Path,
target_dir: &Path,
release: bool,
sdkroot: Option<&str>,
min_ios: &str,
) -> BuildArtifactSpec {
ios_runtime_staticlib_spec(sdk_root, target_dir, IOS_SIM_RUST_TARGET, release, sdkroot, min_ios)
}
pub(crate) fn ios_sim_app_cdylib_spec(
app: &AppContext,
release: bool,
sdkroot: Option<&str>,
min_ios: &str,
) -> BuildArtifactSpec {
BuildArtifactSpec {
manifest_path: Some(app.manifest_path.clone()),
working_dir: app.manifest_dir.clone(),
package: app.package_name.clone(),
package_id: app.package_id.clone(),
artifact_name: app.lib_name.clone(),
kind: ArtifactKind::Cdylib,
crate_type_override: None,
target_triple: Some(IOS_SIM_RUST_TARGET.to_owned()),
no_default_features: false,
features: Vec::new(),
release,
locked: app.has_lockfile,
target_dir: Some(app.target_directory.clone()),
env: ios_cargo_env(sdkroot, min_ios),
expected_suffix: ".dylib".to_owned(),
}
}
pub(crate) fn ios_sim_cmake_configure_args(
source_dir: &Path,
build_dir: &Path,
release: bool,
modules: &[String],
prebuilt_runtime_lib: &Path,
min_ios: &str,
use_ninja: 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("-DCMAKE_SYSTEM_NAME=iOS".to_owned());
args.push("-DCMAKE_OSX_SYSROOT=iphonesimulator".to_owned());
args.push("-DCMAKE_OSX_ARCHITECTURES=arm64".to_owned());
args.push(format!("-DCMAKE_OSX_DEPLOYMENT_TARGET={min_ios}"));
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(";")));
push_apple_clang_pins(&mut args);
args
}
use nativeview_abi::contains_ignore_ascii_case;
fn parse_ios_runtime_version(runtime: &str) -> (u32, u32, u32) {
let Some(pos) = runtime.find("iOS-") else {
return (0, 0, 0);
};
let mut nums = runtime[pos + 4..]
.split('-')
.take_while(|seg| !seg.is_empty() && seg.bytes().all(|b| b.is_ascii_digit()))
.filter_map(|seg| seg.parse::<u32>().ok());
(nums.next().unwrap_or(0), nums.next().unwrap_or(0), nums.next().unwrap_or(0))
}
pub(crate) fn select_simulator_device(
devices_json: &str,
query: Option<&str>,
) -> Result<SimDevice, String> {
let parsed: serde_json::Value = serde_json::from_str(devices_json)
.map_err(|e| format!("failed to parse `xcrun simctl list` JSON: {e}"))?;
let map = parsed
.get("devices")
.and_then(serde_json::Value::as_object)
.ok_or_else(|| "`xcrun simctl list` JSON missing `devices` map".to_owned())?;
let mut candidates: Vec<SimDevice> = Vec::new();
for (runtime, list) in map {
if !runtime.contains("iOS") {
continue;
}
let Some(arr) = list.as_array() else {
continue;
};
for dev in arr {
if !dev.get("isAvailable").and_then(serde_json::Value::as_bool).unwrap_or(false) {
continue;
}
let Some(udid) = dev.get("udid").and_then(serde_json::Value::as_str) else {
continue;
};
let Some(name) = dev.get("name").and_then(serde_json::Value::as_str) else {
continue;
};
let state = dev
.get("state")
.and_then(serde_json::Value::as_str)
.unwrap_or("Shutdown");
candidates.push(SimDevice {
udid: udid.to_owned(),
name: name.to_owned(),
state: state.to_owned(),
runtime: runtime.clone(),
});
}
}
if candidates.is_empty() {
return Err("no available iOS Simulator devices found (check Xcode Simulator runtimes)".to_owned());
}
candidates.sort_by(|a, b| {
parse_ios_runtime_version(&a.runtime)
.cmp(&parse_ios_runtime_version(&b.runtime))
.then_with(|| a.runtime.cmp(&b.runtime))
.then_with(|| a.name.cmp(&b.name))
});
if let Some(raw) = query.map(str::trim).filter(|s| !s.is_empty()) {
let exact: Vec<&SimDevice> =
candidates.iter().filter(|d| d.udid == raw || d.name == raw).collect();
let matches: Vec<&SimDevice> = if !exact.is_empty() {
exact
} else {
candidates.iter().filter(|d| contains_ignore_ascii_case(&d.name, raw)).collect()
};
if let Some(booted) = matches.iter().rev().find(|d| d.state == "Booted") {
return Ok((*booted).clone());
}
if let Some(newest) = matches.last() {
return Ok((*newest).clone());
}
return Err(format!("no available iOS Simulator matching '{raw}'"));
}
if let Some(booted_iphone) =
candidates.iter().rev().find(|d| d.state == "Booted" && d.name.contains("iPhone"))
{
return Ok(booted_iphone.clone());
}
if let Some(booted_any) = candidates.iter().rev().find(|d| d.state == "Booted") {
return Ok(booted_any.clone());
}
if let Some(newest_iphone) = candidates.iter().rev().find(|d| d.name.contains("iPhone")) {
return Ok(newest_iphone.clone());
}
Ok(candidates[candidates.len() - 1].clone())
}
pub(crate) fn resolve_simulator_gui_app(dev_dir: Option<&Path>) -> SimulatorGuiApp {
if let Some(dir) = dev_dir {
let sim_app = dir.join("Applications").join("Simulator.app");
if sim_app.is_dir() {
return SimulatorGuiApp::SimulatorApp(sim_app);
}
if let Some(parent) = dir.parent() {
let hub_app = parent.join("Applications").join("DeviceHub.app");
if hub_app.is_dir() {
return SimulatorGuiApp::DeviceHubApp(hub_app);
}
}
}
SimulatorGuiApp::OpenByName
}
fn ensure_ios_sim_target_installed() -> Result<(), String> {
let out = Command::new("rustup")
.args(["target", "list", "--installed"])
.output()
.map_err(|e| format!("failed to run `rustup target list --installed`: {e}"))?;
if !out.status.success() {
return Err(format!(
"`rustup target list --installed` failed with {}",
out.status
));
}
let stdout = String::from_utf8_lossy(&out.stdout);
if !stdout.lines().any(|l| l.trim() == IOS_SIM_RUST_TARGET) {
return Err(format!(
"Rust target '{IOS_SIM_RUST_TARGET}' is not installed. Run: rustup target add {IOS_SIM_RUST_TARGET}"
));
}
Ok(())
}
pub(crate) fn resolve_apple_sdk(sdk_name: &str) -> Result<String, String> {
let out = Command::new("xcrun")
.args(["--sdk", sdk_name, "--show-sdk-path"])
.output()
.map_err(|e| format!("failed to run `xcrun --sdk {sdk_name} --show-sdk-path`: {e}"))?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
return Err(format!(
"Apple SDK '{sdk_name}' not available (`xcrun --sdk {sdk_name} --show-sdk-path` failed): {}",
stderr.trim()
));
}
let path = String::from_utf8_lossy(&out.stdout).trim().to_owned();
if path.is_empty() {
return Err(format!("`xcrun --sdk {sdk_name} --show-sdk-path` returned an empty path"));
}
Ok(path)
}
fn resolve_iphonesimulator_sdkroot() -> Result<String, String> {
resolve_apple_sdk("iphonesimulator")
}
fn ensure_ios_sim_host_shell(
sdk_root: &NvSdkRoot,
target_dir: &Path,
release: bool,
modules: &[String],
min_ios: &str,
sdkroot: &str,
) -> Result<PathBuf, String> {
let source_dir = sdk_root.path().join("hosts").join("ios-shell");
if !source_dir.join("CMakeLists.txt").is_file() {
return Err(format!("missing iOS shell CMakeLists.txt at '{}'", source_dir.display()));
}
println!("==> Ensuring generated ABI headers...");
crate::codegen::ensure_sdk_abi_headers(sdk_root)?;
let runtime_lib = if sdk_root.is_packaged_sdk() {
let xcf = crate::cargo_env::sdk::resolve_prebuilt_xcframework(sdk_root)?
.ok_or_else(|| "packaged SDK missing NvRuntime.xcframework".to_owned())?;
let sim_lib = xcf.join("ios-arm64_x86_64-simulator/libnv_runtime.a");
if sim_lib.is_file() {
sim_lib
} else {
return Err(format!(
"prebuilt NvRuntime.xcframework at '{}' missing ios-arm64_x86_64-simulator/libnv_runtime.a",
xcf.display()
));
}
} else {
println!("==> Prebuilding nativeview-runtime staticlib ({IOS_SIM_RUST_TARGET})...");
let rt_spec = ios_sim_runtime_spec(sdk_root.path(), target_dir, release, Some(sdkroot), min_ios);
build_artifact(&rt_spec)?
};
let build_dir = ios_sim_host_cache_dir(target_dir, release, min_ios, modules);
let use_ninja = has_ninja_on_path();
reset_stale_cmake_cache(&build_dir, &source_dir, expected_cmake_generator(use_ninja))?;
let cfg_args = ios_sim_cmake_configure_args(
&source_dir,
&build_dir,
release,
modules,
&runtime_lib,
min_ios,
use_ninja,
);
println!(
"==> Configuring '{IOS_SIM_CMAKE_TARGET}' (modules={}, min_ios={min_ios})...",
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 '{IOS_SIM_CMAKE_TARGET}' failed with {cfg_status}"
));
}
println!("==> Building '{IOS_SIM_CMAKE_TARGET}'...");
let build_args = cmake_build_args(&build_dir, IOS_SIM_CMAKE_TARGET, release, false);
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 '{IOS_SIM_CMAKE_TARGET}' failed with {build_status}"
));
}
locate_cmake_shell_binary(&build_dir, IOS_SIM_CMAKE_TARGET, release, "").ok_or_else(|| {
format!(
"CMake build succeeded but '{IOS_SIM_CMAKE_TARGET}' was not found under '{}'",
build_dir.display()
)
})
}
pub(crate) fn package_ios_sim_app_bundle(
out_dir: &Path,
manifest: &NvManifest,
info: &ManifestAppInfo,
shell_binary: &Path,
app_dylib: Option<&Path>,
) -> Result<IosSimBundleOutput, String> {
let executable = manifest.resolved_executable(info);
let bundle_id = manifest.resolved_id(info);
let app_bundle = out_dir.join(format!("{executable}.app"));
if app_bundle.exists() {
fs::remove_dir_all(&app_bundle).map_err(|e| {
format!("failed to clean previous bundle '{}': {e}", app_bundle.display())
})?;
}
fs::create_dir_all(&app_bundle)
.map_err(|e| format!("failed to create '{}': {e}", app_bundle.display()))?;
let executable_path = app_bundle.join(&executable);
fs::copy(shell_binary, &executable_path).map_err(|e| {
format!(
"failed to copy iOS shell binary '{}' -> '{}': {e}",
shell_binary.display(),
executable_path.display()
)
})?;
set_mode(&executable_path, 0o755)?;
let dylib_path = match app_dylib {
Some(src) => {
let dest = app_bundle.join("libnv_app.dylib");
fs::copy(src, &dest).map_err(|e| {
format!("failed to copy app dylib '{}' -> '{}': {e}", src.display(), dest.display())
})?;
set_mode(&dest, 0o755)?;
run_checked(
"install_name_tool",
&[
"-id".to_owned(),
"@executable_path/libnv_app.dylib".to_owned(),
dest.display().to_string(),
],
)?;
Some(dest)
}
None => None,
};
let plist_path = app_bundle.join("Info.plist");
let plist_xml = manifest.emit_ios_sim_info_plist(info);
fs::write(&plist_path, plist_xml)
.map_err(|e| format!("failed to write '{}': {e}", plist_path.display()))?;
run_checked("plutil", &["-lint".to_owned(), plist_path.display().to_string()])?;
let ent_xml = manifest.emit_ios_entitlements_plist();
sign_apple_bundle(
out_dir,
&app_bundle,
&executable,
&bundle_id,
dylib_path.as_deref(),
ent_xml.as_deref(),
)?;
Ok(IosSimBundleOutput { app_bundle, executable_path, dylib_path, plist_path, bundle_id })
}
pub(crate) fn build_ios_sim_app(
app: &AppContext,
sdk_root: &NvSdkRoot,
manifest: &NvManifest,
out_dir: &Path,
release: bool,
pair_only: bool,
) -> Result<IosSimBundleOutput, String> {
ensure_ios_sim_target_installed()?;
let sdkroot = resolve_iphonesimulator_sdkroot()?;
let min_ios = manifest.apple.min_ios.as_str();
let dylib = if pair_only {
println!("==> Skipping app cdylib cross-compile (--pair-only).");
None
} else {
println!("==> Building app cdylib '{}' ({IOS_SIM_RUST_TARGET})...", app.package_name);
let spec = ios_sim_app_cdylib_spec(app, release, Some(&sdkroot), min_ios);
Some(build_artifact(&spec)?)
};
let shell_bin = ensure_ios_sim_host_shell(
sdk_root,
&app.target_directory,
release,
&app.host_modules,
min_ios,
&sdkroot,
)?;
let info = app.manifest_app_info();
println!("==> Packaging iOS Simulator .app bundle...");
package_ios_sim_app_bundle(out_dir, manifest, &info, &shell_bin, dylib.as_deref())
}
pub(crate) fn launch_ios_sim_app(
app_bundle: &Path,
bundle_id: &str,
device_query: Option<&str>,
headless: bool,
pair_uri: Option<&str>,
shell_args: &[String],
) -> Result<(), String> {
let list_out = Command::new("xcrun")
.args(["simctl", "list", "devices", "available", "-j"])
.output()
.map_err(|e| format!("failed to run `xcrun simctl list`: {e}"))?;
if !list_out.status.success() {
let stderr = String::from_utf8_lossy(&list_out.stderr);
return Err(format!("`xcrun simctl list` failed: {}", stderr.trim()));
}
let json = String::from_utf8_lossy(&list_out.stdout);
let device = select_simulator_device(&json, device_query)?;
println!("==> Simulator: {} ({}, state={})", device.name, device.udid, device.state);
if device.state == "Shutdown" {
run_checked("xcrun", &["simctl".to_owned(), "boot".to_owned(), device.udid.clone()])?;
}
run_checked(
"xcrun",
&["simctl".to_owned(), "bootstatus".to_owned(), device.udid.clone(), "-b".to_owned()],
)?;
if !headless {
let dev_dir = Command::new("xcode-select")
.arg("-p")
.output()
.ok()
.filter(|o| o.status.success())
.map(|o| PathBuf::from(String::from_utf8_lossy(&o.stdout).trim()));
match resolve_simulator_gui_app(dev_dir.as_deref()) {
SimulatorGuiApp::SimulatorApp(path) => {
let _ = Command::new("open")
.arg(&path)
.args(["--args", "-CurrentDeviceUDID", &device.udid])
.status();
}
SimulatorGuiApp::DeviceHubApp(path) => {
let _ = Command::new("open").arg(&path).status();
}
SimulatorGuiApp::OpenByName => {
let ok = Command::new("open")
.args(["-a", "Simulator", "--args", "-CurrentDeviceUDID", &device.udid])
.status()
.map(|s| s.success())
.unwrap_or(false);
if !ok {
println!(
"note: Simulator GUI app not found; continuing install/launch on booted device {}",
device.udid
);
}
}
}
}
let _ = Command::new("xcrun")
.args(["simctl", "terminate", &device.udid, bundle_id])
.output();
println!("==> Installing {}...", app_bundle.display());
run_checked(
"xcrun",
&[
"simctl".to_owned(),
"install".to_owned(),
device.udid.clone(),
app_bundle.display().to_string(),
],
)?;
println!("==> Launching {bundle_id} on {}...", device.name);
let mut launch = Command::new("xcrun");
launch.args(["simctl", "launch", &device.udid, bundle_id]).args(shell_args);
if let Some(uri) = pair_uri {
launch.env("SIMCTL_CHILD_NV_PAIR_CONNECT", uri);
}
let status = launch
.status()
.map_err(|e| format!("failed to run `xcrun simctl launch`: {e}"))?;
if !status.success() {
return Err(format!("`xcrun simctl launch` failed with {status}"));
}
Ok(())
}