nativeview-cli 0.1.0-rc.1

Developer CLI (`nv`) for Native View Engine: dev hot-reload, builds, pairing, SDK management, app scaffolding, and docs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
//! Shared host-shell build cache (`<target_dir>/nv-hosts/<shell>-<profile>-<modules_key>/`)
//! with zero recursive Cargo invocations from CMake.

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,
};

/// Host shell runtime used by `nv build` / `nv run`.
#[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",
        }
    }

    /// Relative host directory under `<sdk_root>/hosts/` for desktop CMake-built shells.
    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,
        }
    }

    /// CMake executable target name for desktop CMake-built shells.
    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,
        }
    }
}

/// Output of building or reusing a cached host shell binary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct BuiltHostShell {
    pub binary_path: PathBuf,
    pub a11y_dll_path: Option<PathBuf>,
}

/// Deterministic cache key segment for a sorted unique list of host modules.
pub(crate) fn modules_cache_key(modules: &[String]) -> String {
    if modules.is_empty() {
        "base".to_owned()
    } else {
        modules.join("+")
    }
}

/// Shared host CMake build directory: `<target_dir>/nv-hosts/<shell>-<profile>-<modules_key>/`.
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" }
}

/// Appends Apple Clang compiler pins so CMake ignores Homebrew LLVM/GCC on macOS hosts.
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());
}

/// Builds the deterministic `cmake` configure argument list (pure, unit-testable).
#[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
}

/// Checks an existing `CMakeCache.txt` in `build_dir`: wipes `build_dir` when
/// `CMAKE_HOME_DIRECTORY` points to a different source directory OR `CMAKE_GENERATOR` mismatches
/// the selected generator. Returns `Ok(true)` when a stale cache was cleared.
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)
}

/// Decides whether `-G Ninja` should be used: on Windows MSVC, requires `cl.exe` on `PATH` so
/// builds outside a Visual Studio Developer Prompt fall back cleanly to the VS generator.
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
    }
}

/// Builds the deterministic `cmake --build` argument list (shared between live builds and `--dry-run`).
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
}

/// Locates the compiled CMake shell executable across single-config and multi-config build layouts.
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 })
}

/// Ensures the requested host shell binary is built in the shared cache (zero recursive Cargo
/// from CMake).
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()));
    }

    // 1. Ensure ABI headers exist (skip when packaged SDK has prebuilt_codegen=true).
    println!("==> Ensuring generated ABI headers...");
    crate::codegen::ensure_sdk_abi_headers(sdk_root)?;

    // 2. Resolve or prebuild libnv_runtime staticlib (and Windows a11y DLL when building windows-shell).
    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
    };

    // 3. Configure + build CMake host shell in the shared cache.
    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) })
}