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
//! Cached Jetpack Compose (`com.android.application`) Gradle project synthesis for
//! `nv build/run -t android --shell compose` (zero LOC added to `packages/backends/compose`).

use std::fs;
use std::path::{Path, PathBuf};

use nativeview_cli::manifest::{AndroidShell, ManifestAppInfo, NvManifest};

/// Paths inside a synthesized cached Android Compose Gradle wrapper project.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SynthesizedComposeProject {
    pub project_dir: PathBuf,
    pub settings_gradle: PathBuf,
    pub build_gradle: PathBuf,
    pub gradle_properties: PathBuf,
    pub local_properties: PathBuf,
    pub manifest_xml: PathBuf,
    pub main_activity_kt: PathBuf,
    pub jni_arm64_dir: PathBuf,
}

fn escape_kotlin_str(raw: &str) -> String {
    raw.replace('\\', "\\\\").replace('"', "\\\"").replace('$', "\\$")
}

/// Escapes a filesystem path for a Java `.properties` value (`\`, `:`, `=`, and leading whitespace).
pub(crate) fn escape_properties_path(path: &Path) -> String {
    let raw = path.display().to_string();
    let mut out = String::with_capacity(raw.len() + 8);
    let mut leading_ws = true;
    for ch in raw.chars() {
        match ch {
            '\\' => {
                leading_ws = false;
                out.push_str("\\\\");
            }
            ':' => {
                leading_ws = false;
                out.push_str("\\:");
            }
            '=' => {
                leading_ws = false;
                out.push_str("\\=");
            }
            ' ' | '\t' if leading_ws => {
                out.push('\\');
                out.push(ch);
            }
            other => {
                leading_ws = false;
                out.push(other);
            }
        }
    }
    out
}

/// Returns the cached Gradle project directory (`<target_dir>/nv-apps/<lib_name>/android-compose/`).
pub(crate) fn compose_project_dir(target_dir: &Path, lib_name: &str) -> PathBuf {
    target_dir.join("nv-apps").join(lib_name).join("android-compose")
}

/// Renders `settings.gradle.kts` `includeBuild`ing `packages/packs/standard-android` plus its
/// transitive core/backend/module builds and (when `"camera"` is in `host_modules`)
/// `packages/modules/camera/android`.
pub(crate) fn render_compose_settings_gradle(
    sdk_root: &Path,
    lib_name: &str,
    has_camera: bool,
) -> String {
    let project_name = escape_kotlin_str(&format!("{}-android", lib_name.replace('_', "-")));
    let included = [
        ("packages/core/host-java", "nativeview-host-java"),
        ("packages/backends/android", "nativeview-backend-android"),
        ("packages/backends/compose", "nativeview-backend-compose"),
        ("packages/modules/app-scene/android", "nativeview-app-scene-android"),
        ("packages/modules/canvas/android", "nativeview-canvas-android"),
        ("packages/modules/canvas/compose", "nativeview-canvas-compose"),
        ("packages/modules/charts/android", "nativeview-charts-android"),
        ("packages/modules/charts/compose", "nativeview-charts-compose"),
        ("packages/modules/clipboard/android", "nativeview-clipboard-android"),
        ("packages/modules/date-text/android", "nativeview-date-text-android"),
        ("packages/modules/date-text/compose", "nativeview-date-text-compose"),
        ("packages/modules/filesystem/android", "nativeview-filesystem-android"),
        ("packages/modules/gauge/android", "nativeview-gauge-android"),
        ("packages/modules/gauge/compose", "nativeview-gauge-compose"),
        ("packages/modules/haptics/android", "nativeview-haptics-android"),
        ("packages/modules/image/android", "nativeview-image-android"),
        ("packages/modules/image/compose", "nativeview-image-compose"),
        ("packages/modules/linking/android", "nativeview-linking-android"),
        ("packages/modules/media-fit/android", "nativeview-media-fit-android"),
        ("packages/modules/progress/android", "nativeview-progress-android"),
        ("packages/modules/progress/compose", "nativeview-progress-compose"),
        ("packages/modules/secure-store/android", "nativeview-secure-store-android"),
        ("packages/modules/svg/android", "nativeview-svg-android"),
        ("packages/modules/svg/compose", "nativeview-svg-compose"),
        ("packages/modules/system-env/android", "nativeview-system-env-android"),
        ("packages/modules/text-input/android", "nativeview-text-input-android"),
        ("packages/modules/text-input/compose", "nativeview-text-input-compose"),
        ("packages/modules/toggle/android", "nativeview-toggle-android"),
        ("packages/modules/toggle/compose", "nativeview-toggle-compose"),
        ("packages/packs/standard-android", "nativeview-standard-android"),
    ];
    let mut out = format!(
        "pluginManagement {{\n\
         \x20   repositories {{\n\
         \x20       google()\n\
         \x20       mavenCentral()\n\
         \x20       gradlePluginPortal()\n\
         \x20   }}\n\
         }}\n\
         \n\
         dependencyResolutionManagement {{\n\
         \x20   repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)\n\
         \x20   repositories {{\n\
         \x20       google()\n\
         \x20       mavenCentral()\n\
         \x20   }}\n\
         }}\n\
         \n\
         rootProject.name = \"{project_name}\"\n\n",
    );
    for (rel, build_name) in included {
        let dir = escape_kotlin_str(&sdk_root.join(rel).display().to_string());
        out.push_str(&format!("includeBuild(\"{dir}\") {{ name = \"{build_name}\" }}\n"));
    }
    if has_camera {
        let cam = escape_kotlin_str(
            &sdk_root.join("packages/modules/camera/android").display().to_string(),
        );
        out.push_str(&format!(
            "\nincludeBuild(\"{cam}\") {{\n\
             \x20   name = \"nativeview-module-camera-android\"\n\
             \x20   dependencySubstitution {{\n\
             \x20       substitute(module(\"io.github.nativeview:camera\")).using(project(\":\"))\n\
             \x20   }}\n\
             }}\n",
        ));
    }
    out
}

/// Renders `build.gradle.kts` for the synthesized `com.android.application` project.
pub(crate) fn render_compose_build_gradle(
    android_id: &str,
    manifest: &NvManifest,
    info: &ManifestAppInfo,
    has_camera: bool,
) -> String {
    let app_id = escape_kotlin_str(android_id);
    let version_name = escape_kotlin_str(&info.package_version);
    let min_sdk = manifest.android.min_sdk;
    let target_sdk = manifest.android.target_sdk;
    let compile_sdk = target_sdk.max(36);

    let mut deps = String::from(
        "    implementation(\"io.github.nativeview:nativeview-standard-android\")\n\
         \x20   implementation(\"androidx.activity:activity-compose:1.10.0\")\n",
    );
    if has_camera {
        deps.push_str("    implementation(\"io.github.nativeview:camera\")\n");
    }

    format!(
        "plugins {{\n\
         \x20   id(\"com.android.application\") version \"8.8.2\"\n\
         \x20   id(\"org.jetbrains.kotlin.android\") version \"2.1.10\"\n\
         \x20   id(\"org.jetbrains.kotlin.plugin.compose\") version \"2.1.10\"\n\
         }}\n\
         \n\
         android {{\n\
         \x20   namespace = \"{app_id}\"\n\
         \x20   compileSdk = {compile_sdk}\n\
         \n\
         \x20   defaultConfig {{\n\
         \x20       applicationId = \"{app_id}\"\n\
         \x20       minSdk = {min_sdk}\n\
         \x20       targetSdk = {target_sdk}\n\
         \x20       versionCode = 1\n\
         \x20       versionName = \"{version_name}\"\n\
         \x20       ndk {{\n\
         \x20           abiFilters += listOf(\"arm64-v8a\")\n\
         \x20       }}\n\
         \x20   }}\n\
         \n\
         \x20   buildTypes {{\n\
         \x20       getByName(\"release\") {{\n\
         \x20           signingConfig = signingConfigs.getByName(\"debug\")\n\
         \x20       }}\n\
         \x20   }}\n\
         \n\
         \x20   compileOptions {{\n\
         \x20       sourceCompatibility = JavaVersion.VERSION_17\n\
         \x20       targetCompatibility = JavaVersion.VERSION_17\n\
         \x20   }}\n\
         \n\
         \x20   kotlinOptions {{\n\
         \x20       jvmTarget = \"17\"\n\
         \x20   }}\n\
         \n\
         \x20   buildFeatures {{\n\
         \x20       compose = true\n\
         \x20       buildConfig = false\n\
         \x20   }}\n\
         \n\
         \x20   packaging {{\n\
         \x20       jniLibs {{\n\
         \x20           useLegacyPackaging = true\n\
         \x20       }}\n\
         \x20   }}\n\
         }}\n\
         \n\
         dependencies {{\n\
         {deps}}}\n"
    )
}

/// Renders `gradle.properties` for the synthesized Compose application.
pub(crate) fn render_compose_gradle_properties(compile_sdk: u32) -> String {
    format!(
        "android.useAndroidX=true\n\
         android.suppressUnsupportedCompileSdk={compile_sdk}\n\
         org.gradle.jvmargs=-Xmx2g\n"
    )
}

/// Renders `MainActivity.kt` extending `NvHostActivity()` (which loads bundled `libnv_app.so`
/// by default), forwarding `EXTRA_NV_SURFACE_KEY` / `EXTRA_NV_SURFACE_TITLE` into
/// `controller?.setProps`, and registering `AndroidCameraHost` via `CameraHostBridge.register(...)`
/// when `"camera"` is in `host_modules`.
pub(crate) fn render_compose_main_activity(android_id: &str, has_camera: bool) -> String {
    let camera_imports = if has_camera {
        "import androidx.activity.ComponentActivity\n\
         import io.github.nativeview.camera.ActivityCameraDelegate\n\
         import io.github.nativeview.camera.AndroidCameraHost\n\
         import io.github.nativeview.host.NativeRuntime\n\
         import io.github.nativeview.hybrid.CameraHostBridge\n"
    } else {
        ""
    };

    let camera_on_create = if has_camera {
        "        acquireCamera(this)\n"
    } else {
        ""
    };

    let camera_lifecycle = if has_camera {
        "\n    override fun onDestroy() {\n\
         \x20       // Tear down the NV surface first so HostOpsKeepAlive leases drop to 0.\n\
         \x20       super.onDestroy()\n\
         \x20       releaseCamera(this)\n\
         \x20   }\n\
         \n\
         \x20   companion object {\n\
         \x20       init {\n\
         \x20           runCatching { System.loadLibrary(\"nv_android_shell\") }\n\
         \x20       }\n\
         \n\
         \x20       private val cameraLock = Any()\n\
         \x20       private var sharedCameraHost: AndroidCameraHost? = null\n\
         \x20       private var sharedCameraReg: AutoCloseable? = null\n\
         \x20       private val cameraActivities = ArrayList<ComponentActivity>()\n\
         \x20       private val cameraDelegates = java.util.IdentityHashMap<ComponentActivity, ActivityCameraDelegate>()\n\
         \n\
         \x20       private fun acquireCamera(activity: ComponentActivity) {\n\
         \x20           val delegate = ActivityCameraDelegate(activity)\n\
         \x20           val host: AndroidCameraHost\n\
         \x20           val newlyCreated: Boolean\n\
         \x20           synchronized(cameraLock) {\n\
         \x20               val existing = sharedCameraHost\n\
         \x20               if (existing != null) {\n\
         \x20                   host = existing\n\
         \x20                   newlyCreated = false\n\
         \x20               } else {\n\
         \x20                   host = AndroidCameraHost(activity.applicationContext ?: activity, delegate)\n\
         \x20                   sharedCameraHost = host\n\
         \x20                   newlyCreated = true\n\
         \x20               }\n\
         \x20               cameraActivities.remove(activity)\n\
         \x20               cameraActivities.add(activity)\n\
         \x20               cameraDelegates[activity] = delegate\n\
         \x20               host.attachActivityDelegate(delegate)\n\
         \x20           }\n\
         \x20           if (newlyCreated) {\n\
         \x20               try {\n\
         \x20                   val regFn = NativeRuntime.registerHostOpsPtr()\n\
         \x20                   if (regFn != 0L) {\n\
         \x20                       val reg = CameraHostBridge.register(\n\
         \x20                           regFn,\n\
         \x20                           host,\n\
         \x20                           NativeRuntime.unregisterHostOpsPtr(),\n\
         \x20                           NativeRuntime.registerWireBridgePtr(),\n\
         \x20                       )\n\
         \x20                       synchronized(cameraLock) { sharedCameraReg = reg }\n\
         \x20                       val eventSink = NativeRuntime.directEventEmitPtr()\n\
         \x20                       if (eventSink != 0L) {\n\
         \x20                           host.attachEventSink(eventSink)\n\
         \x20                       }\n\
         \x20                   }\n\
         \x20               } catch (_: UnsatisfiedLinkError) {\n\
         \x20                   // Host unit tests without libnv_android_shell.so stay runnable.\n\
         \x20               } catch (t: Throwable) {\n\
         \x20                   releaseCamera(activity)\n\
         \x20                   throw t\n\
         \x20               }\n\
         \x20           }\n\
         \x20       }\n\
         \n\
         \x20       private fun releaseCamera(activity: ComponentActivity) {\n\
         \x20           var regToClose: AutoCloseable? = null\n\
         \x20           var hostToClose: AndroidCameraHost? = null\n\
         \x20           synchronized(cameraLock) {\n\
         \x20               cameraActivities.remove(activity)\n\
         \x20               cameraDelegates.remove(activity)\n\
         \x20               val current = sharedCameraHost ?: return\n\
         \x20               val fallback = cameraActivities.lastOrNull()\n\
         \x20               if (fallback != null) {\n\
         \x20                   current.attachActivityDelegate(cameraDelegates[fallback])\n\
         \x20               } else {\n\
         \x20                   sharedCameraHost = null\n\
         \x20                   regToClose = sharedCameraReg\n\
         \x20                   sharedCameraReg = null\n\
         \x20                   hostToClose = current\n\
         \x20               }\n\
         \x20           }\n\
         \x20           hostToClose?.detachEventSink()\n\
         \x20           regToClose?.close()\n\
         \x20           hostToClose?.close()\n\
         \x20       }\n\
         \x20   }\n"
    } else {
        ""
    };

    format!(
        "package {android_id}\n\
         \n\
         import android.content.Intent\n\
         import android.os.Bundle\n\
         {camera_imports}import io.github.nativeview.appscene.AndroidAppSceneHost\n\
         import io.github.nativeview.compose.NvHostActivity\n\
         \n\
         class MainActivity : NvHostActivity() {{\n\
         \x20   override fun onCreate(savedInstanceState: Bundle?) {{\n\
         {camera_on_create}\
         \x20       intent?.let {{ applySurfaceIntentMetadata(it) }}\n\
         \x20       super.onCreate(savedInstanceState)\n\
         \x20       intent?.let {{ applySurfaceKeyProp(it) }}\n\
         \x20   }}\n\
         \n\
         \x20   override fun onNewIntent(intent: Intent) {{\n\
         \x20       super.onNewIntent(intent)\n\
         \x20       applySurfaceIntentMetadata(intent)\n\
         \x20       applySurfaceKeyProp(intent)\n\
         \x20   }}\n\
         \n\
         \x20   private fun applySurfaceIntentMetadata(source: Intent) {{\n\
         \x20       val surfaceTitle = source.getStringExtra(AndroidAppSceneHost.EXTRA_NV_SURFACE_TITLE)\n\
         \x20       if (!surfaceTitle.isNullOrBlank()) {{\n\
         \x20           title = surfaceTitle\n\
         \x20       }}\n\
         \x20   }}\n\
         \n\
         \x20   private fun applySurfaceKeyProp(source: Intent) {{\n\
         \x20       val surfaceKey = source.getStringExtra(AndroidAppSceneHost.EXTRA_NV_SURFACE_KEY)?.trim()\n\
         \x20       if (!surfaceKey.isNullOrEmpty()) {{\n\
         \x20           controller?.setProps {{ w ->\n\
         \x20               val mark = w.beginMap(1)\n\
         \x20               w.writeMapKey(\"surface_key\")\n\
         \x20               w.writeStr(surfaceKey)\n\
         \x20               w.end(mark)\n\
         \x20           }}\n\
         \x20       }}\n\
         \x20   }}\n\
         {camera_lifecycle}}}\n"
    )
}

fn write_if_changed(path: &Path, content: &str) -> Result<(), String> {
    if let Ok(existing) = fs::read_to_string(path)
        && existing == content
    {
        return Ok(());
    }
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?;
    }
    fs::write(path, content).map_err(|e| format!("failed to write '{}': {e}", path.display()))
}

fn remove_stale_kotlin_files(kotlin_root: &Path, keep: &Path) -> Result<(), String> {
    if !kotlin_root.is_dir() {
        return Ok(());
    }
    let mut stack = vec![kotlin_root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                stack.push(path);
            } else if path.extension().and_then(|e| e.to_str()) == Some("kt") && path != keep {
                fs::remove_file(&path)
                    .map_err(|e| format!("failed to remove stale '{}': {e}", path.display()))?;
            }
        }
    }
    Ok(())
}

/// Synthesizes or updates the cached Gradle Compose project on disk (preserving mtimes on unchanged files).
pub(crate) fn synthesize_compose_project(
    project_dir: &Path,
    sdk_root: &Path,
    android_sdk_root: &Path,
    manifest: &NvManifest,
    info: &ManifestAppInfo,
    host_modules: &[String],
) -> Result<SynthesizedComposeProject, String> {
    let has_camera = host_modules.iter().any(|m| m == "camera");
    let android_id = manifest.resolved_android_id(info).map_err(|e| e.to_string())?;
    let compile_sdk = manifest.android.target_sdk.max(36);

    let settings_gradle = project_dir.join("settings.gradle.kts");
    let build_gradle = project_dir.join("build.gradle.kts");
    let gradle_properties = project_dir.join("gradle.properties");
    let local_properties = project_dir.join("local.properties");
    let manifest_xml = project_dir.join("src/main/AndroidManifest.xml");
    let kotlin_root = project_dir.join("src/main/kotlin");
    let mut pkg_dir = kotlin_root.clone();
    for seg in android_id.split('.') {
        pkg_dir.push(seg);
    }
    let main_activity_kt = pkg_dir.join("MainActivity.kt");
    let jni_arm64_dir = project_dir.join("src/main/jniLibs/arm64-v8a");

    write_if_changed(
        &settings_gradle,
        &render_compose_settings_gradle(sdk_root, &info.lib_name, has_camera),
    )?;
    write_if_changed(
        &build_gradle,
        &render_compose_build_gradle(&android_id, manifest, info, has_camera),
    )?;
    write_if_changed(&gradle_properties, &render_compose_gradle_properties(compile_sdk))?;
    write_if_changed(
        &local_properties,
        &format!("sdk.dir={}\n", escape_properties_path(android_sdk_root)),
    )?;
    write_if_changed(
        &manifest_xml,
        &manifest.emit_android_manifest_xml_for(info, AndroidShell::Compose),
    )?;
    remove_stale_kotlin_files(&kotlin_root, &main_activity_kt)?;
    write_if_changed(&main_activity_kt, &render_compose_main_activity(&android_id, has_camera))?;
    fs::create_dir_all(&jni_arm64_dir)
        .map_err(|e| format!("failed to create '{}': {e}", jni_arm64_dir.display()))?;

    Ok(SynthesizedComposeProject {
        project_dir: project_dir.to_path_buf(),
        settings_gradle,
        build_gradle,
        gradle_properties,
        local_properties,
        manifest_xml,
        main_activity_kt,
        jni_arm64_dir,
    })
}