waterui-cli 0.4.1

Cross-platform tooling for WaterUI applications
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
//! Android platform build and package utilities.
//!
//! This module provides utility functions for building and packaging Android apps.
//! These functions are used by `AndroidBackend` to implement the `Backend` trait.

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

use askama::Template;
use eyre::{self, bail};
use smol::{fs, unblock};
use target_lexicon::{Aarch64Architecture, Architecture, Triple};

use tracing::{debug, info};

use std::str::FromStr;

use crate::{
    android::{
        backend::AndroidBackend,
        output_metadata::{OutputKind, packaged_artifact},
        toolchain::{AndroidNdk, AndroidSdk, Java, Kotlin, java_proxy_properties_from_env},
    },
    assets::{self, ResolvedFont},
    build::{BuildOptions, BuildProgress, RustBuild, RustDynamicLibraries, RustLinkage},
    device::Artifact,
    platform::{PackageOptions, TargetPlatform},
    project::Project,
    templates::FontRegistrationTemplateEntry,
    toolchain::{Host, ToolchainError, windows_arm64_llvm::WindowsArm64LlvmToolchain},
    utils::copy_file,
};

fn gradle_cmd(gradlew: &Path, backend_path: &Path, task: &str) -> smol::process::Command {
    let mut cmd = smol::process::Command::new(gradlew);
    cmd.arg(task).arg("--project-dir").arg(backend_path);
    cmd
}

fn apply_gradle_proxy_env(host: &Host, cmd: &mut smol::process::Command) -> eyre::Result<()> {
    let proxy_properties = java_proxy_properties_from_env(host)?;
    if proxy_properties.is_empty() {
        return Ok(());
    }

    cmd.args(&proxy_properties);

    let mut gradle_opts = proxy_properties.join(" ");
    if let Some(existing) = host.env_string("GRADLE_OPTS")
        && !existing.trim().is_empty()
    {
        gradle_opts.push(' ');
        gradle_opts.push_str(&existing);
    }
    cmd.env("GRADLE_OPTS", gradle_opts);
    Ok(())
}

/// Get the NDK host tag based on the current machine's OS and architecture.
///
/// On Apple Silicon, prefer the native `darwin-arm64` toolchain when present,
/// falling back to `darwin-x86_64` for older Android NDK releases (Rosetta).
fn ndk_host_tag(ndk_path: &Path) -> &'static str {
    use target_lexicon::{Architecture, OperatingSystem, Triple};

    let host = Triple::host();

    match (&host.operating_system, &host.architecture) {
        (OperatingSystem::Darwin(_), Architecture::Aarch64(_)) => {
            let native = ndk_path
                .join("toolchains/llvm/prebuilt")
                .join("darwin-arm64");
            if native.exists() {
                "darwin-arm64"
            } else {
                "darwin-x86_64"
            }
        }
        (OperatingSystem::Darwin(_), _) => "darwin-x86_64",
        (OperatingSystem::Windows, _) => "windows-x86_64",
        // NDK doesn't have native ARM64 Linux builds
        (OperatingSystem::Linux, _) => "linux-x86_64",
        _ => panic!("Unsupported host triple for Android NDK: {host}"),
    }
}

fn ndk_bin_dir(ndk_path: &Path) -> PathBuf {
    ndk_path
        .join("toolchains/llvm/prebuilt")
        .join(ndk_host_tag(ndk_path))
        .join("bin")
}

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

fn ndk_clang_path(ndk_path: &Path, abi: AndroidAbi, cxx: bool, api_level: u32) -> PathBuf {
    let suffix = if cxx { "clang++" } else { "clang" };
    ndk_bin_dir(ndk_path).join(format!("{}{api_level}-{suffix}", abi.ndk_target()))
}

/// Get the NDK clang linker path for the given ABI.
fn ndk_linker_path(ndk_path: &Path, abi: AndroidAbi, api_level: u32) -> PathBuf {
    ndk_clang_path(ndk_path, abi, false, api_level)
}

/// The NDK's prebuilt `libclang_rt.builtins-<arch>-android.a` for `abi`.
///
/// `-Zbuild-std` builds `compiler_builtins` with `compiler-builtins-c`, whose
/// build script links the archive named by `LLVM_COMPILER_RT_LIB` instead of
/// rebuilding compiler-rt from source (rust-src ships no compiler-rt C
/// sources). On aarch64 that archive is what provides the LSE outline-atomics
/// helpers (`__aarch64_ldadd4_acq_rel` & friends) NDK-compiled C objects
/// reference — rustc links with `-nodefaultlibs`, so the clang driver's own
/// copy never reaches the link.
fn ndk_builtins_lib(ndk_path: &Path, abi: AndroidAbi) -> eyre::Result<PathBuf> {
    let arch = match abi {
        AndroidAbi::Arm64V8a => "aarch64",
        AndroidAbi::X86_64 => "x86_64",
        AndroidAbi::ArmeabiV7a => "arm",
        AndroidAbi::X86 => "i686",
    };
    let clang_libs = ndk_path
        .join("toolchains/llvm/prebuilt")
        .join(ndk_host_tag(ndk_path))
        .join("lib/clang");
    let mut candidates: Vec<PathBuf> = std::fs::read_dir(&clang_libs)
        .map_err(|error| {
            eyre::eyre!(
                "Failed to read NDK clang libraries at {}: {error}",
                clang_libs.display()
            )
        })?
        .filter_map(|entry| entry.ok().map(|entry| entry.path()))
        .map(|version_dir| {
            version_dir.join(format!("lib/linux/libclang_rt.builtins-{arch}-android.a"))
        })
        .filter(|path| path.is_file())
        .collect();
    candidates.sort_unstable();
    match candidates.as_slice() {
        [path] => Ok(path.clone()),
        [] => Err(eyre::eyre!(
            "The NDK at {} ships no libclang_rt.builtins-{arch}-android.a; \
             a `-Zbuild-std` build needs it for the compiler-rt builtins",
            ndk_path.display()
        )),
        _ => Err(eyre::eyre!(
            "The NDK at {} ships multiple libclang_rt.builtins-{arch}-android.a \
             copies: {candidates:?}",
            ndk_path.display()
        )),
    }
}

/// 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.
async fn create_android_toolchain_wrapper(
    ndk_path: &Path,
    abi: AndroidAbi,
    api_level: u32,
) -> eyre::Result<PathBuf> {
    // Create wrapper in a temp directory that persists for the build
    let wrapper_dir = std::env::temp_dir().join("waterui-cmake-toolchains");
    fs::create_dir_all(&wrapper_dir).await?;

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

    let content = format!(
        include_str!("android_toolchain_wrapper.cmake.tpl"),
        abi = abi.as_str(),
        api_level = api_level,
        ndk_toolchain = ndk_toolchain.display(),
        asm_compiler = ndk_clang_path(ndk_path, abi, false, api_level).display(),
    );
    fs::write(&wrapper_path, content).await?;

    Ok(wrapper_path)
}

/// Get the NDK clang++ (C++ compiler) path for the given ABI.
fn ndk_cxx_path(ndk_path: &Path, abi: AndroidAbi, api_level: u32) -> PathBuf {
    ndk_clang_path(ndk_path, abi, true, api_level)
}

/// Get the path to `libc++_shared.so` in the NDK.
///
/// NDK r23+ ships it under `sysroot/usr/lib/<triple>/`, while older Android
/// NDK releases used `sources/cxx-stl/llvm-libc++/libs/<abi>/`.
fn ndk_libcxx_path(ndk_path: &Path, abi: AndroidAbi) -> PathBuf {
    let new_path = ndk_path
        .join("toolchains/llvm/prebuilt")
        .join(ndk_host_tag(ndk_path))
        .join("sysroot/usr/lib")
        .join(abi.ndk_libcxx_triple())
        .join("libc++_shared.so");

    if new_path.exists() {
        return new_path;
    }

    ndk_path
        .join("sources/cxx-stl/llvm-libc++/libs")
        .join(abi.as_str())
        .join("libc++_shared.so")
}

/// The linker flag that aligns every produced ELF's `LOAD` segments to 16 KB
/// pages — the largest page size Android ships (Pixel 9 class) and Google
/// Play's packaging requirement. The app and every preview module it
/// `dlopen`s must carry the same flag.
pub(crate) const ANDROID_MAX_PAGE_SIZE_LINK_ARG: &str = "-Clink-arg=-Wl,-z,max-page-size=16384";

/// Represents an Android platform for a specific architecture.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AndroidAbi {
    /// ARM64 (arm64-v8a) - modern Android devices
    Arm64V8a,
    /// `x86_64` - emulators on Intel/AMD
    X86_64,
    /// `ARMv7` (armeabi-v7a) - older 32-bit devices
    ArmeabiV7a,
    /// x86 - older 32-bit emulators
    X86,
}

/// Error returned when parsing an unsupported Android ABI string.
#[derive(Debug, thiserror::Error)]
#[error("Unsupported Android ABI: {abi}")]
pub struct UnsupportedAndroidAbi {
    abi: String,
}

impl FromStr for AndroidAbi {
    type Err = UnsupportedAndroidAbi;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "arm64-v8a" => Ok(Self::Arm64V8a),
            "x86_64" => Ok(Self::X86_64),
            "armeabi-v7a" => Ok(Self::ArmeabiV7a),
            "x86" => Ok(Self::X86),
            other => Err(UnsupportedAndroidAbi {
                abi: other.to_string(),
            }),
        }
    }
}

impl AndroidAbi {
    #[must_use]
    /// Android ABI string used by the Android toolchain (e.g. `arm64-v8a`).
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Arm64V8a => "arm64-v8a",
            Self::X86_64 => "x86_64",
            Self::ArmeabiV7a => "armeabi-v7a",
            Self::X86 => "x86",
        }
    }

    #[must_use]
    /// Target triple prefix used by the NDK toolchain binaries (clang, clang++).
    pub const fn ndk_target(self) -> &'static str {
        match self {
            Self::Arm64V8a => "aarch64-linux-android",
            Self::X86_64 => "x86_64-linux-android",
            Self::ArmeabiV7a => "armv7a-linux-androideabi",
            Self::X86 => "i686-linux-android",
        }
    }

    #[must_use]
    /// Target triple used by NDK sysroot libc++ paths.
    pub const fn ndk_libcxx_triple(self) -> &'static str {
        match self {
            Self::Arm64V8a => "aarch64-linux-android",
            Self::X86_64 => "x86_64-linux-android",
            Self::ArmeabiV7a => "arm-linux-androideabi",
            Self::X86 => "i686-linux-android",
        }
    }

    /// The ABI a Rust target triple names — the inverse of
    /// [`AndroidPlatform::triple`], so call sites holding a triple never keep
    /// a second copy of the architecture mapping.
    #[must_use]
    pub const fn from_triple(triple: &Triple) -> Option<Self> {
        match triple.architecture {
            Architecture::Aarch64(_) => Some(Self::Arm64V8a),
            Architecture::X86_64 => Some(Self::X86_64),
            Architecture::Arm(target_lexicon::ArmArchitecture::Armv7) => Some(Self::ArmeabiV7a),
            Architecture::X86_32(target_lexicon::X86_32Architecture::I686) => Some(Self::X86),
            _ => None,
        }
    }
}

/// Represents an Android platform for a specific ABI.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AndroidPlatform {
    abi: AndroidAbi,
}

struct AndroidBuildContext {
    abi: AndroidAbi,
    ndk_path: PathBuf,
    linker: PathBuf,
    ar: PathBuf,
    cxx: PathBuf,
    target_underscore: String,
    target_upper: String,
    llvm_envs: Vec<(String, std::ffi::OsString)>,
    java_home: PathBuf,
    java_bin_dir: PathBuf,
    kotlin_compiler: PathBuf,
    kotlin_bin_dir: PathBuf,
    kotlin_home: PathBuf,
    sdk_path: PathBuf,
    android_jar: PathBuf,
    wrapper_toolchain: PathBuf,
    android_platform: String,
}

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

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

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

    #[must_use]
    /// Return the ABI for this platform.
    pub const fn abi(&self) -> AndroidAbi {
        self.abi
    }

    #[must_use]
    /// Return the ABI string for this platform.
    pub const fn abi_str(&self) -> &'static str {
        self.abi.as_str()
    }

    /// Create an Android platform from an ABI string.
    ///
    /// # Errors
    /// Returns an error if the ABI is not supported.
    pub fn try_from_abi(abi: &str) -> eyre::Result<Self> {
        let abi = AndroidAbi::from_str(abi).map_err(|e| eyre::eyre!(e))?;
        Ok(Self { abi })
    }
}

/// All supported Android ABIs.
pub const ALL_ABIS: &[AndroidAbi] = &[
    AndroidAbi::Arm64V8a,
    AndroidAbi::X86_64,
    AndroidAbi::ArmeabiV7a,
    AndroidAbi::X86,
];

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

    /// Get the target triple for this Android platform.
    #[must_use]
    pub const fn triple(&self) -> Triple {
        let architecture = match self.abi {
            AndroidAbi::Arm64V8a => Architecture::Aarch64(Aarch64Architecture::Aarch64),
            AndroidAbi::X86_64 => Architecture::X86_64,
            AndroidAbi::ArmeabiV7a => Architecture::Arm(target_lexicon::ArmArchitecture::Armv7),
            AndroidAbi::X86 => Architecture::X86_32(target_lexicon::X86_32Architecture::I686),
        };
        Triple {
            architecture,
            vendor: target_lexicon::Vendor::Unknown,
            operating_system: target_lexicon::OperatingSystem::Linux,
            environment: target_lexicon::Environment::Android,
            binary_format: target_lexicon::BinaryFormat::Elf,
        }
    }

    /// Build Rust library for this Android platform.
    ///
    /// # Errors
    /// Returns an error if the build fails.
    pub async fn build(&self, project: &Project, options: BuildOptions) -> eyre::Result<PathBuf> {
        // Only an app that will `dlopen` WaterUI modules — the preview support
        // app — ships the shared Rust runtime. `-Cprefer-dynamic` on Android
        // cannot resolve `std` to rustup's prebuilt `libstd.so` (its LOAD
        // segments are 4 KB-aligned and 16 KB-page devices reject the whole
        // package), so the shared-runtime path below builds `std` from source
        // under the page-size link flag instead. Every other build links the
        // runtime in, which is what a packaged build already does.
        let options = if options.loads_dynamic_modules() {
            options
        } else {
            options.with_static_runtime()
        };
        // Resolve fonts BEFORE cargo build - this ensures icons.json is downloaded
        // for crates like fontawesome7 that need it during build.rs
        let font_declarations = crate::assets::scan_fonts(project).await?;
        let _resolved_fonts = crate::assets::resolve_fonts(font_declarations).await?;

        let abi = self.abi();
        let triple = self.triple();
        let min_api_level = project
            .resolved_framework()
            .await?
            .android_min_api_level()?;
        let host = Host::current();
        let build_context =
            resolve_android_build_context(&host, abi, &triple, min_api_level).await?;
        let build = configure_android_rust_build(&host, project, &triple, &build_context, &options)
            .await?
            .with_envs(options.cargo_envs().iter().cloned())
            .with_target_dir(project.water_target_dir(options.linkage()).await?);

        let built_target = build.build_lib(options.is_release()).await?;
        copy_android_build_outputs(
            project,
            &options,
            abi,
            &build_context.ndk_path,
            &built_target.profile_dir,
            &built_target.artifact,
        )
        .await?;
        Ok(built_target.profile_dir)
    }

    /// 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.
    pub async fn package_with_abis(
        project: &Project,
        options: PackageOptions,
        abis: &[AndroidAbi],
    ) -> eyre::Result<Artifact> {
        let backend_path = project.backend_path::<AndroidBackend>();

        // Copy project assets and dependency fonts
        copy_assets_and_fonts(
            project,
            &backend_path,
            None,
            options.uses_dev_server(),
            options.progress(),
        )
        .await?;

        let gradlew = backend_path.join(if cfg!(windows) {
            "gradlew.bat"
        } else {
            "gradlew"
        });

        let (command_name, output_kind, variant) =
            match (options.is_distribution(), options.is_debug()) {
                (true, false) => ("bundleRelease", OutputKind::Bundle, "release"),
                (false, false) => ("assembleRelease", OutputKind::Apk, "release"),
                (false, true) => ("assembleDebug", OutputKind::Apk, "debug"),
                (true, true) => ("bundleDebug", OutputKind::Bundle, "debug"),
            };

        // Join ABIs with comma for the environment variable
        let abis_str = abis
            .iter()
            .map(|a| a.as_str())
            .collect::<Vec<_>>()
            .join(",");

        // Set JAVA_HOME to Android Studio's bundled JDK to avoid JDK version conflicts
        // (e.g., Homebrew's JDK 25 is not supported by Android Gradle Plugin)
        let mut cmd = gradle_cmd(&gradlew, &backend_path, command_name);
        cmd.env("WATERUI_SKIP_RUST_BUILD", "1")
            .env("WATERUI_ANDROID_ABIS", &abis_str);

        let host = Host::current();
        if let Some(java_home) = Java::detect_home(&host).await {
            cmd.env("JAVA_HOME", java_home);
        }
        if let Some(sdk_path) = AndroidSdk::detect_path(&host) {
            cmd.env("ANDROID_HOME", &sdk_path)
                .env("ANDROID_SDK_ROOT", &sdk_path);
        }
        apply_gradle_proxy_env(&host, &mut cmd)?;

        let output = cmd.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());
        }

        let path = packaged_artifact(&backend_path, output_kind, variant).await?;
        Ok(Artifact::new(project.bundle_identifier(), path))
    }

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

        let output = host.output(&emulator_path, ["-list-avds"]).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)
    }
}

async fn resolve_android_build_context(
    host: &Host,
    abi: AndroidAbi,
    triple: &Triple,
    api_level: u32,
) -> eyre::Result<AndroidBuildContext> {
    let ndk_path = AndroidNdk::detect_path(host).ok_or_else(|| {
        eyre::eyre!("Android NDK not found. Please install it via Android Studio.")
    })?;
    let linker = ndk_linker_path(&ndk_path, abi, api_level);
    let ar = ndk_ar_path(&ndk_path);
    let cxx = ndk_cxx_path(&ndk_path, abi, api_level);
    // The toolchain gate only proves the NDK's host toolchain executes; the
    // wrapper for the framework's floor is a separate fact, and a missing one
    // otherwise surfaces minutes later as a linker cargo cannot find.
    for wrapper in [&linker, &cxx] {
        if !wrapper.is_file() {
            eyre::bail!(
                "the Android NDK at {} ships no compiler wrapper for API {api_level} \
                 ({}); the framework's android-min-api-level needs an NDK that targets it",
                ndk_path.display(),
                wrapper.display()
            );
        }
    }
    let target_underscore = triple.to_string().replace('-', "_");
    let target_upper = target_underscore.to_uppercase();
    let llvm_envs = resolve_windows_arm64_llvm_envs(host).await?;
    let (java_home, java_bin_dir) = resolve_java_home(host).await?;
    let (kotlin_compiler, kotlin_bin_dir, kotlin_home) = resolve_kotlin_home(host).await?;
    let (sdk_path, android_jar) = resolve_android_sdk_paths(host).await?;
    let wrapper_toolchain = create_android_toolchain_wrapper(&ndk_path, abi, api_level).await?;

    Ok(AndroidBuildContext {
        abi,
        ndk_path,
        linker,
        ar,
        cxx,
        target_underscore,
        target_upper,
        llvm_envs,
        java_home,
        java_bin_dir,
        kotlin_compiler,
        kotlin_bin_dir,
        kotlin_home,
        sdk_path,
        android_jar,
        wrapper_toolchain,
        android_platform: format!("android-{api_level}"),
    })
}

async fn resolve_windows_arm64_llvm_envs(
    host: &Host,
) -> eyre::Result<Vec<(String, std::ffi::OsString)>> {
    WindowsArm64LlvmToolchain
        .cargo_envs(host)
        .await
        .map_err(|error| match error {
            ToolchainError::Fixable(_) => eyre::eyre!(
                "Windows ARM64 LLVM toolchain is missing. Run `water doctor --fix` to install it automatically."
            ),
            ToolchainError::Unfixable(unfixable) => {
                eyre::eyre!("Windows ARM64 LLVM toolchain check failed: {unfixable}")
            }
        })
}

async fn resolve_java_home(host: &Host) -> eyre::Result<(PathBuf, PathBuf)> {
    let java_home = Java::detect_home(host).await.ok_or_else(|| {
        eyre::eyre!(
            "Java runtime not found. Install a JDK (or Android Studio JBR), then re-run `water doctor --fix`."
        )
    })?;
    let java_bin_dir = java_home.join("bin");
    Ok((java_home, java_bin_dir))
}

async fn resolve_kotlin_home(host: &Host) -> eyre::Result<(PathBuf, PathBuf, PathBuf)> {
    let kotlin_compiler = Kotlin::detect_path(host).await.ok_or_else(|| {
        eyre::eyre!(
            "Kotlin compiler (kotlinc) not found. Install Android Studio or set `KOTLIN_HOME`, then re-run `water doctor`."
        )
    })?;
    let kotlin_bin_dir = kotlin_compiler.parent().map(PathBuf::from).ok_or_else(|| {
        eyre::eyre!(
            "Failed to determine Kotlin bin directory from `{}`.",
            kotlin_compiler.display()
        )
    })?;
    let kotlin_home = kotlin_bin_dir.parent().map(PathBuf::from).ok_or_else(|| {
        eyre::eyre!(
            "Failed to determine KOTLIN_HOME from `{}`.",
            kotlin_bin_dir.display()
        )
    })?;
    Ok((kotlin_compiler, kotlin_bin_dir, kotlin_home))
}

/// Resolve the SDK root and its newest `android.jar` on `host`.
///
/// `AndroidSdk::android_jar_path` walks `platforms/` on disk, so the whole
/// resolution runs on a blocking thread instead of the executor.
async fn resolve_android_sdk_paths(host: &Host) -> eyre::Result<(PathBuf, PathBuf)> {
    let host = host.clone();
    smol::unblock(move || {
        let sdk_path = AndroidSdk::detect_path(&host).ok_or_else(|| {
            eyre::eyre!("Android SDK not found. Please install it via Android Studio.")
        })?;
        let android_jar = AndroidSdk::android_jar_path(&host).ok_or_else(|| {
            eyre::eyre!(
                "Android platforms not found in SDK at {}. Install an Android platform (SDK) in Android Studio.",
                sdk_path.display()
            )
        })?;
        Ok((sdk_path, android_jar))
    })
    .await
}

/// The `waterui-ffi` features an Android runtime is compiled with.
///
/// See [`crate::apple::platform::apple_ffi_dependency_features`] for why anything
/// loaded into that runtime must be compiled with the same set.
///
/// # Errors
///
/// Returns an error when the project's enabled capabilities cannot be resolved.
pub(crate) async fn android_ffi_dependency_features(
    project: &Project,
) -> eyre::Result<Vec<String>> {
    let mut features = vec!["waterui-ffi/android-jni".to_string()];
    features.extend(crate::project_model::assets::capability_ffi_features(project).await?);
    // Android has no player or map WaterUI bridges, so it draws both itself.
    features.extend(crate::project_model::assets::self_drawn_realization_features(project).await?);
    Ok(features)
}

async fn configure_android_rust_build(
    host: &Host,
    project: &Project,
    triple: &Triple,
    context: &AndroidBuildContext,
    options: &BuildOptions,
) -> eyre::Result<RustBuild> {
    // Android loads the JNI shared object and nothing else, so build only that crate
    // type instead of also archiving the whole dependency graph into a staticlib.
    let mut build = RustBuild::new(project.ffi_crate_path(), triple.clone())
        .with_project(project)
        .with_features(android_ffi_dependency_features(project).await?)
        .with_crate_type_override("cdylib")
        .with_rustc_flag(ANDROID_MAX_PAGE_SIZE_LINK_ARG);
    if options.linkage() == RustLinkage::SharedRuntime {
        // The preview support app dlopens the pushed module, so the runtime is
        // shared: the `dev` feature resolves `waterui-dylib`, `-Cprefer-dynamic`
        // links `std` dynamically, and `-Zbuild-std` compiles that `libstd` from
        // source — rustup's prebuilt one is 4 KB-aligned and a 16 KB-page device
        // would reject the package for it. The `water` rustc wrapper Cargo runs
        // under supplies the `dylib` crate type Cargo strips from `std`.
        let nightly = crate::toolchain::rust::nightly_toolchain_with_rust_src(host).await?;
        build = build
            .with_feature("dev")
            .with_preferred_dynamic_linking()
            .with_build_std(nightly)
            .with_env(
                "LLVM_COMPILER_RT_LIB",
                ndk_builtins_lib(&context.ndk_path, context.abi)?,
            );
    }
    if let Some(sccache_path) = options.sccache_path() {
        build = build.with_sccache(sccache_path.to_path_buf());
    }
    if let Some(progress) = options.progress() {
        build = build.with_progress(progress.clone());
    }
    for (key, value) in &context.llvm_envs {
        build = build.with_env(key.clone(), value.clone());
    }

    build = build.with_envs(android_cargo_envs(context, triple));

    let current_path = host
        .env("PATH")
        .ok_or_else(|| eyre::eyre!("PATH environment variable is not set"))?;
    let mut paths: Vec<PathBuf> = std::env::split_paths(&current_path).collect();
    paths.insert(0, context.java_bin_dir.clone());
    paths.insert(0, context.kotlin_bin_dir.clone());
    let new_path = std::env::join_paths(paths).map_err(|error| {
        eyre::eyre!("Failed to construct PATH for Java/Kotlin compiler resolution: {error}")
    })?;

    Ok(build.with_env("PATH", new_path))
}

/// The environment every Cargo invocation targeting an Android ABI needs:
/// the NDK clang as linker and `cc`/`cxx`/`ar`, the SDK/NDK locations build
/// scripts probe, the `CMake` toolchain file for native dependencies, and the
/// `pkg-config` cross overrides.
///
/// The support app and the preview module it loads must compile their shared
/// dependency graph identically, so both take their environment from this one
/// list rather than each spelling it out.
fn android_cargo_envs(
    context: &AndroidBuildContext,
    triple: &Triple,
) -> Vec<(String, std::ffi::OsString)> {
    [
        (
            format!("CARGO_TARGET_{}_LINKER", context.target_upper),
            context.linker.as_os_str().to_os_string(),
        ),
        (
            format!("CARGO_TARGET_{}_AR", context.target_upper),
            context.ar.as_os_str().to_os_string(),
        ),
        (
            format!("CC_{}", context.target_underscore),
            context.linker.as_os_str().to_os_string(),
        ),
        (
            format!("CXX_{}", context.target_underscore),
            context.cxx.as_os_str().to_os_string(),
        ),
        (
            format!("AR_{}", context.target_underscore),
            context.ar.as_os_str().to_os_string(),
        ),
        (
            "ANDROID_NDK".to_string(),
            context.ndk_path.as_os_str().to_os_string(),
        ),
        (
            "ANDROID_NDK_HOME".to_string(),
            context.ndk_path.as_os_str().to_os_string(),
        ),
        (
            "ANDROID_NDK_ROOT".to_string(),
            context.ndk_path.as_os_str().to_os_string(),
        ),
        (
            "ANDROID_HOME".to_string(),
            context.sdk_path.as_os_str().to_os_string(),
        ),
        (
            "ANDROID_SDK_ROOT".to_string(),
            context.sdk_path.as_os_str().to_os_string(),
        ),
        (
            "ANDROID_JAR".to_string(),
            context.android_jar.as_os_str().to_os_string(),
        ),
        (
            "JAVA_HOME".to_string(),
            context.java_home.as_os_str().to_os_string(),
        ),
        (
            "KOTLIN_HOME".to_string(),
            context.kotlin_home.as_os_str().to_os_string(),
        ),
        (
            "KOTLINC".to_string(),
            context.kotlin_compiler.as_os_str().to_os_string(),
        ),
        (
            "CMAKE_TOOLCHAIN_FILE".to_string(),
            context.wrapper_toolchain.as_os_str().to_os_string(),
        ),
        (
            format!("CMAKE_TOOLCHAIN_FILE_{}", context.target_underscore),
            context.wrapper_toolchain.as_os_str().to_os_string(),
        ),
        (
            "CMAKE_ASM_COMPILER".to_string(),
            context.linker.as_os_str().to_os_string(),
        ),
        ("ANDROID_ABI".to_string(), context.abi.as_str().into()),
        (
            "ANDROID_PLATFORM".to_string(),
            context.android_platform.clone().into(),
        ),
        ("PKG_CONFIG_ALLOW_CROSS".to_string(), "1".into()),
        (
            format!("PKG_CONFIG_ALLOW_CROSS_{}", context.target_underscore),
            "1".into(),
        ),
        (format!("PKG_CONFIG_ALLOW_CROSS_{triple}"), "1".into()),
    ]
    .into_iter()
    .collect()
}

/// The NDK/SDK toolchain environment a Rust build for `triple` on `abi`
/// needs — shared between the app build and the preview module it `dlopen`s.
///
/// # Errors
/// Returns an error when the NDK or the SDK-side tooling cannot be resolved.
pub(crate) async fn android_rust_build_envs(
    host: &Host,
    project: &Project,
    abi: AndroidAbi,
    triple: &Triple,
    build_std: bool,
) -> eyre::Result<Vec<(String, std::ffi::OsString)>> {
    let min_api_level = project
        .resolved_framework()
        .await?
        .android_min_api_level()?;
    let context = resolve_android_build_context(host, abi, triple, min_api_level).await?;
    let mut envs = android_cargo_envs(&context, triple);
    if build_std {
        envs.push((
            "LLVM_COMPILER_RT_LIB".to_string(),
            ndk_builtins_lib(&context.ndk_path, abi)?.into_os_string(),
        ));
    }
    Ok(envs)
}

async fn copy_android_build_outputs(
    project: &Project,
    options: &BuildOptions,
    abi: AndroidAbi,
    ndk_path: &Path,
    lib_dir: &Path,
    source_lib: &Path,
) -> eyre::Result<()> {
    let output_dir = options.output_dir().map_or_else(
        || {
            project
                .backend_path::<AndroidBackend>()
                .join("app/src/main/jniLibs")
                .join(abi.as_str())
        },
        std::path::Path::to_path_buf,
    );
    fs::create_dir_all(&output_dir).await?;
    copy_file(source_lib, &output_dir.join("libwaterui_app.so")).await?;

    if options.linkage() == RustLinkage::SharedRuntime {
        let triple = AndroidPlatform::new(abi).triple();
        let libraries = RustDynamicLibraries::resolve(lib_dir, &triple, project).await?;
        libraries.stage(&output_dir).await?;
    } else {
        RustDynamicLibraries::remove_staged(&output_dir, &AndroidPlatform::new(abi).triple())
            .await?;
    }

    // `libc++_shared.so` only belongs in the package when a staged native
    // library actually links the C++ STL — Rust-only builds never reference it,
    // and shipping it unconditionally cost ~9 MB per ABI of dead weight.
    let libcxx_target = output_dir.join("libc++_shared.so");
    if staged_libs_need_libcxx(&output_dir).await? {
        let libcxx_path = ndk_libcxx_path(ndk_path, abi);
        if libcxx_path.exists() {
            copy_file(&libcxx_path, &libcxx_target).await?;
        }
    } else if libcxx_target.exists() {
        // Drop the copy an earlier build staged; nothing links it now.
        fs::remove_file(&libcxx_target).await?;
    }

    // Every library about to ship must map its LOAD segments at the largest
    // page size Android runs with; a 4 KB-aligned one is rejected at install
    // time on 16 KB devices, so fail here naming the file instead.
    crate::elf::require_aligned_shared_libraries(&output_dir).await?;

    Ok(())
}

/// True when any `.so` staged in `output_dir` lists `libc++_shared.so` in its
/// `DT_NEEDED` entries.
///
/// An unreadable or unparsable library counts as needing it: including the STL
/// when in doubt is the same behavior the packaging had before, and a corrupt
/// native library is going to fail loudly on the device anyway.
async fn staged_libs_need_libcxx(output_dir: &Path) -> eyre::Result<bool> {
    let output_dir = output_dir.to_path_buf();
    unblock(move || {
        let mut needs = false;
        for entry in std::fs::read_dir(&output_dir)? {
            let path = entry?.path();
            if path.extension() != Some(std::ffi::OsStr::new("so")) {
                continue;
            }
            let needed = std::fs::read(&path)
                .ok()
                .and_then(|data| elf_needs_libcxx(&data))
                .unwrap_or_else(|| {
                    tracing::warn!(
                        library = %path.display(),
                        "could not parse staged library; assuming it needs libc++_shared.so"
                    );
                    true
                });
            needs |= needed;
        }
        Ok(needs)
    })
    .await
}

/// `true` when the ELF data's dynamic section `DT_NEEDED`s `libc++_shared.so`;
/// `None` when the data is not a parseable ELF image at all.
fn elf_needs_libcxx(data: &[u8]) -> Option<bool> {
    use object::read::elf::{Dyn as _, ElfFile, FileHeader};

    fn scan<Elf>(data: &[u8]) -> Option<bool>
    where
        Elf: FileHeader<Endian = object::Endianness>,
    {
        let file = ElfFile::<Elf>::parse(data).ok()?;
        let endian = file.endian();
        let sections = file.elf_section_table();
        let (dyns, strings_index) = sections.dynamic(endian, data).ok()??;
        let strings = sections.strings(endian, data, strings_index).ok()?;
        Some(dyns.iter().any(|d| {
            d.tag32(endian) == Some(object::elf::DT_NEEDED)
                && d.string(endian, strings).ok() == Some(&b"libc++_shared.so"[..])
        }))
    }

    scan::<object::elf::FileHeader64<object::Endianness>>(data)
        .or_else(|| scan::<object::elf::FileHeader32<object::Endianness>>(data))
}

// ============================================================================
// Clean
// ============================================================================

/// Clean Gradle build artifacts for Android.
///
/// # Errors
/// Returns an error if the Gradle clean command fails.
pub async fn clean_android(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(());
    }

    // Set JAVA_HOME to Android Studio's bundled JDK to avoid JDK version conflicts
    let host = Host::current();
    let mut cmd = gradle_cmd(&gradlew, &backend_path, "clean");

    if let Some(java_home) = Java::detect_home(&host).await {
        cmd.env("JAVA_HOME", java_home);
    }
    if let Some(sdk_path) = AndroidSdk::detect_path(&host) {
        cmd.env("ANDROID_HOME", &sdk_path)
            .env("ANDROID_SDK_ROOT", &sdk_path);
    }
    apply_gradle_proxy_env(&host, &mut cmd)?;

    let output = cmd.output().await?;

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

    Ok(())
}

// ============================================================================
// Platform Support Check
// ============================================================================

/// Check if a platform is supported by the Android backend.
#[must_use]
pub const fn is_android_platform(platform: TargetPlatform) -> bool {
    matches!(platform, TargetPlatform::Android)
}

// ============================================================================
// Asset and Font Handling
// ============================================================================

/// Copy project assets and dependency fonts to the Android assets directory.
async fn copy_assets_and_fonts(
    project: &Project,
    backend_path: &Path,
    sccache_path: Option<&Path>,
    dev_server: bool,
    progress: Option<&BuildProgress>,
) -> eyre::Result<()> {
    let assets_dir = backend_path.join("app/src/main/assets");

    // Stage project assets using platform-native conventions.
    let manifest = assets::stage_project_assets_for_android(
        project,
        backend_path,
        sccache_path,
        dev_server,
        progress,
    )
    .await?;

    // Scan and resolve dependency fonts
    let font_declarations = assets::scan_fonts(project).await?;
    let mut resolved_fonts = assets::resolve_fonts(font_declarations).await?;
    resolved_fonts.extend(assets::scan_project_font_assets(&manifest)?);

    if !resolved_fonts.is_empty() {
        // Copy fonts to assets/fonts/
        let fonts_dest = assets_dir.join("fonts");
        assets::copy_fonts(&resolved_fonts, &fonts_dest).await?;

        info!("Copied {} fonts to Android app", resolved_fonts.len());
    }

    // Always generate WaterUIFonts.kt (even if empty) since MainActivity references it
    let java_dir = backend_path.join("app/src/main/java");
    generate_font_registration_kotlin(project, &resolved_fonts, &java_dir).await?;

    Ok(())
}

#[derive(Template)]
#[template(
    path = "src/templates/android_dynamic/WaterUIFonts.kt.tpl",
    escape = "none"
)]
struct WaterUiFontsKotlinTemplate<'a> {
    namespace: &'a str,
    font_entries: &'a [FontRegistrationTemplateEntry],
}

/// Generate WaterUIFonts.kt file for registering custom fonts.
async fn generate_font_registration_kotlin(
    project: &Project,
    fonts: &[ResolvedFont],
    java_dir: &Path,
) -> eyre::Result<()> {
    // Get the package namespace from the project
    let namespace = project.bundle_identifier().android_package_name();

    // Clean up legacy layout: older CLI versions wrote `WaterUIFonts.kt` directly under
    // `app/src/main/java/` (but still declared the app package), which can cause
    // Kotlin redeclaration errors after we started generating into the package dir.
    let legacy_path = java_dir.join("WaterUIFonts.kt");
    let _ = fs::remove_file(&legacy_path).await;

    // Build font entries
    let font_entries = fonts
        .iter()
        .map(|font| FontRegistrationTemplateEntry {
            family_name: font.name.clone(),
            file_name: font
                .path
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or_default()
                .to_string(),
        })
        .collect::<Vec<_>>();

    let content = WaterUiFontsKotlinTemplate {
        namespace: namespace.as_str(),
        font_entries: &font_entries,
    }
    .render()
    .map_err(|error| eyre::eyre!("Failed to render WaterUIFonts.kt template: {error}"))?;

    // Create the package directory structure
    let package_dir = java_dir.join(namespace.as_str().replace('.', "/"));
    fs::create_dir_all(&package_dir).await?;

    let kotlin_path = package_dir.join("WaterUIFonts.kt");
    fs::write(&kotlin_path, content).await?;

    debug!("Generated {}", kotlin_path.display());

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::elf_needs_libcxx;

    #[test]
    fn elf_needs_libcxx_rejects_non_elf_data() {
        // Verified against real NDK binaries during development (a clang++
        // shared object reports `Some(true)`, `libc++_shared.so` itself
        // `Some(false)`); the committed test covers only the reject path so it
        // needs no fixtures.
        assert_eq!(elf_needs_libcxx(b"not an elf"), None);
        assert_eq!(elf_needs_libcxx(&[]), None);
        assert_eq!(elf_needs_libcxx(&[0x7f, b'E', b'L', b'F']), None);
    }
}