waterui-cli 0.1.3

A modern UI framework for Rust
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
use std::path::{Path, PathBuf};

use color_eyre::eyre::{self, bail};
use smol::fs;
use target_lexicon::{Aarch64Architecture, Architecture, Triple};

use crate::{
    android::{
        backend::AndroidBackend,
        device::AndroidDevice,
        toolchain::{AndroidNdk, AndroidSdk, AndroidToolchain},
    },
    build::{BuildOptions, RustBuild},
    device::Artifact,
    platform::{PackageOptions, Platform},
    project::Project,
    utils::{copy_file, run_command},
};

fn validate_android_package_name(package: &str) -> eyre::Result<()> {
    if package.is_empty() {
        bail!("Android package name is empty (set `[package].bundle_identifier` in `Water.toml`).");
    }

    if package.contains('-') {
        bail!(
            "Invalid Android package name: '{package}' (hyphens are not allowed). \
Set `[package].bundle_identifier` in `Water.toml` to a valid Java package name (e.g. replace '-' with '_')."
        );
    }

    for segment in package.split('.') {
        if segment.is_empty() {
            bail!("Invalid Android package name: '{package}' (empty segment).");
        }

        let mut chars = segment.chars();
        let Some(first) = chars.next() else {
            bail!("Invalid Android package name: '{package}' (empty segment).");
        };

        if !(first.is_ascii_alphabetic() || first == '_') {
            bail!(
                "Invalid Android package name: '{package}' (segment '{segment}' must start with a letter or underscore)."
            );
        }

        if !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {
            bail!(
                "Invalid Android package name: '{package}' (segment '{segment}' contains invalid characters)."
            );
        }
    }

    Ok(())
}

/// Get the NDK host tag based on the current machine's OS and architecture.
fn ndk_host_tag() -> &'static str {
    use target_lexicon::{Architecture, OperatingSystem, Triple};

    let host = Triple::host();

    // TODO: Better ARM support
    match (&host.operating_system, &host.architecture) {
        (OperatingSystem::Darwin(_), Architecture::Aarch64(_) | _) => "darwin-x86_64", // NDK uses x86_64 even on ARM Macs (Rosetta)
        (OperatingSystem::Windows, _) => "windows-x86_64",
        // NDK doesn't have native ARM64 Linux builds
        (OperatingSystem::Linux, _) => "linux-x86_64",
        _ => unimplemented!(),
    }
}

/// Get the NDK clang linker path for the given ABI.
fn ndk_linker_path(ndk_path: &Path, abi: &str) -> PathBuf {
    let target = match abi {
        "arm64-v8a" => "aarch64-linux-android",
        "x86_64" => "x86_64-linux-android",
        "armeabi-v7a" => "armv7a-linux-androideabi",
        "x86" => "i686-linux-android",
        _ => unimplemented!(),
    };

    // Use API level 24 as minimum (Android 7.0)
    let api_level = 24;

    ndk_path
        .join("toolchains/llvm/prebuilt")
        .join(ndk_host_tag())
        .join("bin")
        .join(format!("{target}{api_level}-clang"))
}

/// Get the NDK ar path.
fn ndk_ar_path(ndk_path: &Path) -> PathBuf {
    ndk_path
        .join("toolchains/llvm/prebuilt")
        .join(ndk_host_tag())
        .join("bin/llvm-ar")
}

/// Create a wrapper `CMake` toolchain file that sets `ANDROID_ABI` before including
/// the NDK's toolchain. This is required because cmake-rs doesn't pass `ANDROID_ABI`
/// as a -D define, causing the NDK toolchain to default to armeabi-v7a.
///
/// Returns the path to the created wrapper toolchain file.
fn create_android_toolchain_wrapper(ndk_path: &Path, abi: &str) -> eyre::Result<PathBuf> {
    use std::io::Write;

    // Create wrapper in a temp directory that persists for the build
    let wrapper_dir = std::env::temp_dir().join("waterui-cmake-toolchains");
    std::fs::create_dir_all(&wrapper_dir)?;

    let wrapper_path = wrapper_dir.join(format!("android-{abi}.cmake"));
    let ndk_toolchain = ndk_path.join("build/cmake/android.toolchain.cmake");

    let content = format!(
        r#"# Auto-generated wrapper toolchain for WaterUI Android builds
# Sets ANDROID_ABI before including the NDK toolchain to fix cmake-rs cross-compilation
set(ANDROID_ABI "{abi}")
set(ANDROID_PLATFORM "android-24")
include("{ndk_toolchain}")
"#,
        abi = abi,
        ndk_toolchain = ndk_toolchain.display()
    );

    let mut file = std::fs::File::create(&wrapper_path)?;
    file.write_all(content.as_bytes())?;

    Ok(wrapper_path)
}

/// Get the NDK clang++ (C++ compiler) path for the given ABI.
fn ndk_cxx_path(ndk_path: &Path, abi: &str) -> PathBuf {
    let target = match abi {
        "arm64-v8a" => "aarch64-linux-android",
        "x86_64" => "x86_64-linux-android",
        "armeabi-v7a" => "armv7a-linux-androideabi",
        "x86" => "i686-linux-android",
        _ => unimplemented!(),
    };

    // Use API level 24 as minimum (Android 7.0)
    let api_level = 24;

    ndk_path
        .join("toolchains/llvm/prebuilt")
        .join(ndk_host_tag())
        .join("bin")
        .join(format!("{target}{api_level}-clang++"))
}

/// Represents an Android platform for a specific architecture.
#[derive(Debug, Clone)]
pub struct AndroidPlatform {
    architecture: Architecture,
}

impl AndroidPlatform {
    /// Create a new Android platform with the specified architecture.
    #[must_use]
    pub const fn new(architecture: Architecture) -> Self {
        Self { architecture }
    }

    /// Create an Android platform for arm64-v8a (most common modern Android devices).
    #[must_use]
    pub const fn arm64() -> Self {
        Self {
            architecture: Architecture::Aarch64(Aarch64Architecture::Aarch64),
        }
    }

    /// Create an Android platform for `x86_64` (emulators on Intel/AMD).
    #[must_use]
    pub const fn x86_64() -> Self {
        Self {
            architecture: Architecture::X86_64,
        }
    }

    /// Get the Android ABI name for this architecture.
    #[must_use]
    pub const fn abi(&self) -> &'static str {
        match self.architecture {
            Architecture::Aarch64(_) => "arm64-v8a",
            Architecture::X86_64 => "x86_64",
            Architecture::Arm(_) => "armeabi-v7a",
            Architecture::X86_32(_) => "x86",
            _ => unimplemented!(),
        }
    }

    /// Get the architecture from an Android ABI name.
    #[must_use]
    pub fn from_abi(abi: &str) -> Self {
        let architecture = match abi {
            "arm64-v8a" => Architecture::Aarch64(Aarch64Architecture::Aarch64),
            "x86_64" => Architecture::X86_64,
            "armeabi-v7a" => Architecture::Arm(target_lexicon::ArmArchitecture::Armv7),
            "x86" => Architecture::X86_32(target_lexicon::X86_32Architecture::I686),
            _ => unimplemented!(),
        };
        Self { architecture }
    }
}

/// All supported Android ABIs.
pub const ALL_ABIS: &[&str] = &["arm64-v8a", "x86_64", "armeabi-v7a", "x86"];

impl AndroidPlatform {
    /// Returns all supported Android platforms (all architectures).
    #[must_use]
    pub fn all() -> Vec<Self> {
        ALL_ABIS.iter().map(|abi| Self::from_abi(abi)).collect()
    }

    /// Clean all jniLibs directories to remove stale libraries from previous builds.
    ///
    /// # Errors
    /// Returns an error if the directory cannot be removed.
    pub async fn clean_jni_libs(project: &Project) -> eyre::Result<()> {
        let jni_libs_dir = project
            .backend_path::<AndroidBackend>()
            .join("app/src/main/jniLibs");

        if jni_libs_dir.exists() {
            fs::remove_dir_all(&jni_libs_dir).await?;
        }
        Ok(())
    }

    /// Package the Android app with specific ABIs.
    ///
    /// This is used when building for multiple architectures. The ABIs parameter
    /// controls which native libraries are included in the final APK.
    ///
    /// # Errors
    /// Returns an error if Gradle build fails.
    ///
    /// # Panics
    ///
    /// Panics if an unsupported ABI is provided.
    pub async fn package_with_abis(
        project: &Project,
        options: PackageOptions,
        abis: &[&str],
    ) -> eyre::Result<Artifact> {
        validate_android_package_name(project.bundle_identifier())?;

        let backend_path = project.backend_path::<AndroidBackend>();
        let gradlew = backend_path.join(if cfg!(windows) {
            "gradlew.bat"
        } else {
            "gradlew"
        });

        let (command_name, path) = if options.is_distribution() && !options.is_debug() {
            (
                "bundleRelease",
                backend_path.join("app/build/outputs/bundle/release/app-release.aab"),
            )
        } else if !options.is_distribution() && !options.is_debug() {
            (
                "assembleRelease",
                backend_path.join("app/build/outputs/apk/release/app-release.apk"),
            )
        } else if !options.is_distribution() && options.is_debug() {
            (
                "assembleDebug",
                backend_path.join("app/build/outputs/apk/debug/app-debug.apk"),
            )
        } else if options.is_distribution() && options.is_debug() {
            (
                "bundleDebug",
                backend_path.join("app/build/outputs/bundle/debug/app-debug.aab"),
            )
        } else {
            unreachable!()
        };

        // Join ABIs with comma for the environment variable
        let abis_str = abis.join(",");

        let output = smol::process::Command::new(gradlew.to_str().unwrap())
            .args([
                command_name,
                "--project-dir",
                backend_path.to_str().unwrap(),
            ])
            .env("WATERUI_SKIP_RUST_BUILD", "1")
            .env("WATERUI_ANDROID_ABIS", &abis_str)
            .output()
            .await?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let stdout = String::from_utf8_lossy(&output.stdout);
            bail!("Gradle build failed:\n{}\n{}", stdout.trim(), stderr.trim());
        }

        Ok(Artifact::new(project.bundle_identifier(), path))
    }

    /// List available Android Virtual Devices (emulators).
    ///
    /// # Errors
    /// Returns an error if the emulator tool is not found.
    pub async fn list_avds() -> eyre::Result<Vec<String>> {
        let emulator_path =
            AndroidSdk::emulator_path().ok_or_else(|| eyre::eyre!("Android emulator not found"))?;

        let output = smol::process::Command::new(&emulator_path)
            .arg("-list-avds")
            .output()
            .await?;

        let stdout = String::from_utf8_lossy(&output.stdout);
        let avds: Vec<String> = stdout
            .lines()
            .filter(|line| !line.is_empty())
            .map(String::from)
            .collect();

        Ok(avds)
    }
}

impl Platform for AndroidPlatform {
    type Device = AndroidDevice;
    type Toolchain = AndroidToolchain;

    async fn scan(&self) -> eyre::Result<Vec<Self::Device>> {
        let adb = AndroidSdk::adb_path()
            .ok_or_else(|| eyre::eyre!("Android SDK not found or adb not installed"))?;

        // Use adb to list connected devices
        let output = run_command(adb.to_str().unwrap(), ["devices"]).await?;

        let mut devices = Vec::new();

        for line in output.lines().skip(1) {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 2 && parts[1] == "device" {
                let identifier = parts[0].to_string();

                // Query the device's primary ABI
                let abi = run_command(
                    adb.to_str().unwrap(),
                    ["-s", &identifier, "shell", "getprop", "ro.product.cpu.abi"],
                )
                .await
                .map_or_else(|_| "arm64-v8a".to_string(), |abi| abi.trim().to_string());

                devices.push(AndroidDevice::new(identifier, abi));
            }
        }

        Ok(devices)
    }

    fn toolchain(&self) -> Self::Toolchain {
        AndroidToolchain::default()
    }

    async fn clean(&self, project: &Project) -> eyre::Result<()> {
        let backend_path = project.backend_path::<AndroidBackend>();
        let gradlew = backend_path.join(if cfg!(windows) {
            "gradlew.bat"
        } else {
            "gradlew"
        });

        if !gradlew.exists() {
            // No Android project to clean
            return Ok(());
        }

        run_command(
            gradlew.to_str().unwrap(),
            ["clean", "--project-dir", backend_path.to_str().unwrap()],
        )
        .await?;

        Ok(())
    }

    async fn build(
        &self,
        project: &Project,
        options: BuildOptions,
    ) -> eyre::Result<std::path::PathBuf> {
        // Get NDK path for configuring the linker
        let ndk_path = AndroidNdk::detect_path().ok_or_else(|| {
            eyre::eyre!("Android NDK not found. Please install it via Android Studio.")
        })?;

        // Configure NDK environment for cargo
        let linker = ndk_linker_path(&ndk_path, self.abi());
        let ar = ndk_ar_path(&ndk_path);
        let cxx = ndk_cxx_path(&ndk_path, self.abi());

        // Set environment variables for the linker
        let target_upper = self.triple().to_string().replace('-', "_").to_uppercase();

        // Build with RustBuild
        let build = RustBuild::new(project.root(), self.triple(), options.is_hot_reload());

        // Set environment variables for cargo, cc-rs, and cmake before building
        // SAFETY: CLI is single-threaded at this point
        unsafe {
            // For cargo/rustc linker
            std::env::set_var(format!("CARGO_TARGET_{target_upper}_LINKER"), &linker);
            std::env::set_var(format!("CARGO_TARGET_{target_upper}_AR"), &ar);

            // For cc-rs crate (used by ring, aws-lc-sys, etc.) - uses underscore format
            let target_underscore = self.triple().to_string().replace('-', "_");
            std::env::set_var(format!("CC_{target_underscore}"), &linker);
            std::env::set_var(format!("CXX_{target_underscore}"), &cxx);
            std::env::set_var(format!("AR_{target_underscore}"), &ar);

            // For CMake-based builds (aws-lc-sys, etc.)
            // Set all variants as different crates check different env vars
            std::env::set_var("ANDROID_NDK", &ndk_path);
            std::env::set_var("ANDROID_NDK_HOME", &ndk_path);
            std::env::set_var("ANDROID_NDK_ROOT", &ndk_path);

            // Create a wrapper CMake toolchain file that sets ANDROID_ABI before
            // including the NDK toolchain. This is required because cmake-rs doesn't
            // pass ANDROID_ABI as a -D define, causing the NDK toolchain to default
            // to armeabi-v7a (32-bit ARM) instead of the correct architecture.
            let android_abi = self.abi();
            let wrapper_toolchain = create_android_toolchain_wrapper(&ndk_path, android_abi)?;

            std::env::set_var("CMAKE_TOOLCHAIN_FILE", &wrapper_toolchain);
            std::env::set_var(
                format!("CMAKE_TOOLCHAIN_FILE_{target_underscore}"),
                &wrapper_toolchain,
            );

            // Also set these for other tools that might check them
            std::env::set_var("ANDROID_ABI", android_abi);
            std::env::set_var("ANDROID_PLATFORM", "android-24");

            // Use Ninja generator if available to avoid Xcode/Make conflicts on macOS
            // The system Make on macOS can inject -arch and -isysroot flags that break Android builds
            if which::which("ninja").is_ok() {
                std::env::set_var("CMAKE_GENERATOR", "Ninja");
            }
        }

        let lib_dir = build.build_lib(options.is_release()).await?;

        // Get the crate name and find the built .so file
        let lib_name = project.crate_name().replace('-', "_");
        let source_lib = lib_dir.join(format!("lib{lib_name}.so"));

        if !source_lib.exists() {
            bail!(
                "Rust shared library not found at {}. Did the build succeed?",
                source_lib.display()
            );
        }

        // Determine output directory: use specified output_dir or default to jniLibs
        let output_dir = options.output_dir().map_or_else(
            || {
                project
                    .backend_path::<AndroidBackend>()
                    .join("app/src/main/jniLibs")
                    .join(self.abi())
            },
            std::path::Path::to_path_buf,
        );
        fs::create_dir_all(&output_dir).await?;

        // Copy with standardized name
        let dest_lib = output_dir.join("libwaterui_app.so");
        copy_file(&source_lib, &dest_lib).await?;

        Ok(lib_dir)
    }

    fn triple(&self) -> Triple {
        Triple {
            architecture: self.architecture,
            vendor: target_lexicon::Vendor::Unknown,
            operating_system: target_lexicon::OperatingSystem::Linux,
            environment: target_lexicon::Environment::Android,
            binary_format: target_lexicon::BinaryFormat::Elf,
        }
    }

    async fn package(
        &self,
        project: &Project,
        options: PackageOptions,
    ) -> color_eyre::eyre::Result<Artifact> {
        let backend_path = project.backend_path::<AndroidBackend>();
        let gradlew = backend_path.join(if cfg!(windows) {
            "gradlew.bat"
        } else {
            "gradlew"
        });

        let (command_name, path) = if options.is_distribution() && !options.is_debug() {
            (
                "bundleRelease",
                backend_path.join("app/build/outputs/bundle/release/app-release.aab"),
            )
        } else if !options.is_distribution() && !options.is_debug() {
            (
                "assembleRelease",
                backend_path.join("app/build/outputs/apk/release/app-release.apk"),
            )
        } else if !options.is_distribution() && options.is_debug() {
            (
                "assembleDebug",
                backend_path.join("app/build/outputs/apk/debug/app-debug.apk"),
            )
        } else if options.is_distribution() && options.is_debug() {
            (
                "bundleDebug",
                backend_path.join("app/build/outputs/bundle/debug/app-debug.aab"),
            )
        } else {
            unreachable!()
        };

        // Skip Rust build in Gradle - we already built the library via `water build`
        // The Gradle build.gradle.kts checks this env var and skips its buildRust tasks
        //
        // Also pass the target ABI to filter which native libraries are included
        // This ensures only the architectures we built are packaged in the APK
        let output = smol::process::Command::new(gradlew.to_str().unwrap())
            .args([
                command_name,
                "--project-dir",
                backend_path.to_str().unwrap(),
            ])
            .env("WATERUI_SKIP_RUST_BUILD", "1")
            .env("WATERUI_ANDROID_ABIS", self.abi())
            .output()
            .await?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let stdout = String::from_utf8_lossy(&output.stdout);
            bail!("Gradle build failed:\n{}\n{}", stdout.trim(), stderr.trim());
        }

        Ok(Artifact::new(project.bundle_identifier(), path))
    }
}