Skip to main content

euv_cli/builder/android/
fn.rs

1use super::*;
2
3/// Parses a user-supplied Android ABI string into an `AndroidAbi` discriminant.
4///
5/// # Arguments
6///
7/// - `&str` - Raw ABI label such as `arm64-v8a`, `arm64`, `armeabi-v7a`, or `x86_64`.
8///
9/// # Returns
10///
11/// - `io::Result<AndroidAbi>` - Parsed ABI or an `InvalidInput` error.
12pub fn parse_android_abi(raw: &str) -> io::Result<AndroidAbi> {
13    let normalized: String = raw.trim().to_ascii_lowercase();
14    if normalized == ANDROID_ABI_ARM64
15        || normalized == ANDROID_ABI_ALIAS_ARM64
16        || normalized == ANDROID_ABI_ALIAS_AARCH64
17        || normalized == ANDROID_TRIPLE_ARM64
18    {
19        return Ok(AndroidAbi::Arm64V8a);
20    }
21    if normalized == ANDROID_ABI_ARMV7
22        || normalized == ANDROID_ABI_ALIAS_ARMV7
23        || normalized == ANDROID_TRIPLE_ARMV7
24    {
25        return Ok(AndroidAbi::ArmeabiV7a);
26    }
27    if normalized == ANDROID_ABI_X86_64
28        || normalized == ANDROID_ABI_ALIAS_AMD64
29        || normalized == ANDROID_TRIPLE_X86_64
30    {
31        return Ok(AndroidAbi::X86_64);
32    }
33    Err(Error::new(
34        ErrorKind::InvalidInput,
35        format!("unsupported Android ABI '{raw}'"),
36    ))
37}
38
39/// Resolves the dynamic workspace semver from the workspace manifest.
40///
41/// # Arguments
42///
43/// - `&Path` - Root directory of the `euv` workspace or package.
44///
45/// # Returns
46///
47/// - `String` - Parsed semantic version string, falling back to `0.1.0` when unavailable.
48#[must_use]
49pub fn resolve_workspace_semver(workspace_root: &Path) -> String {
50    let manifest_path: PathBuf = workspace_root.join(MOBILE_FILE_CARGO_TOML);
51    let Ok(manifest_text) = fs::read_to_string(&manifest_path) else {
52        return MOBILE_FALLBACK_VERSION.to_string();
53    };
54    if let Some(found) = extract_toml_section_version(&manifest_text, TOML_SECTION_WORKSPACE_PKG) {
55        return found;
56    }
57    if let Some(found) = extract_toml_section_version(&manifest_text, TOML_SECTION_PKG) {
58        return found;
59    }
60    MOBILE_FALLBACK_VERSION.to_string()
61}
62
63/// Extracts `version = "..."` from a named TOML table section.
64///
65/// # Arguments
66///
67/// - `&str` - Full TOML manifest contents.
68/// - `&str` - Exact table header such as `[workspace.package]`.
69///
70/// # Returns
71///
72/// - `Option<String>` - Trimmed version string when found inside the target section.
73fn extract_toml_section_version(manifest_text: &str, section_header: &str) -> Option<String> {
74    let mut in_section: bool = false;
75    for raw_line in manifest_text.lines() {
76        let trimmed: &str = raw_line.trim();
77        if trimmed.is_empty() || trimmed.starts_with('#') {
78            continue;
79        }
80        if trimmed.starts_with('[') && trimmed.ends_with(']') {
81            in_section = trimmed == section_header;
82            continue;
83        }
84        if !in_section {
85            continue;
86        }
87        if let Some((key_raw, val_raw)) = trimmed.split_once('=')
88            && key_raw.trim() == TOML_VERSION_KEY
89        {
90            let cleaned: &str = val_raw.trim().trim_matches('"');
91            if !cleaned.is_empty() {
92                return Some(cleaned.to_string());
93            }
94        }
95    }
96    None
97}
98
99/// Computes a deterministic monotonic numeric version code (`major * 10000 + minor * 100 + patch`).
100///
101/// # Arguments
102///
103/// - `&str` - Semantic version string such as `"0.49.4"`.
104///
105/// # Returns
106///
107/// - `u32` - Positive version code (`>= 1`).
108#[must_use]
109pub fn compute_semver_version_code(version: &str) -> u32 {
110    let core_part: &str = version.split('-').next().unwrap_or(version);
111    let mut segments: Vec<u32> = Vec::new();
112    for token in core_part.split('.') {
113        let parsed: u32 = token.trim().parse::<u32>().unwrap_or(0);
114        segments.push(parsed);
115    }
116    let major: u32 = segments.first().copied().unwrap_or(0);
117    let minor: u32 = segments.get(1).copied().unwrap_or(0);
118    let patch: u32 = segments.get(2).copied().unwrap_or(0);
119    let computed: u32 = major
120        .saturating_mul(10_000)
121        .saturating_add(minor.saturating_mul(100))
122        .saturating_add(patch);
123    computed.max(1)
124}
125
126/// Maps a CLI `RenderArg` variant to its generated Rust `RenderMode` expression.
127///
128/// # Arguments
129///
130/// - `RenderArg` - CLI render mode selector.
131///
132/// # Returns
133///
134/// - `&'static str` - Rust expression string written into `host_config.rs`.
135#[must_use]
136pub fn render_mode_const_expr(render_mode: RenderArg) -> &'static str {
137    match render_mode {
138        RenderArg::Hardware => HOST_RENDER_EXPR_HARDWARE,
139        RenderArg::Hybrid => HOST_RENDER_EXPR_HYBRID,
140        RenderArg::Software => HOST_RENDER_EXPR_SOFTWARE,
141        RenderArg::Auto => HOST_RENDER_EXPR_AUTO,
142    }
143}
144
145/// Counts occurrences of dev-only `euv.ai.schema.v1` and `euv.ai.schema.v2` markers in binary bytes.
146///
147/// # Arguments
148///
149/// - `&[u8]` - Raw compiled binary or library byte slice.
150///
151/// # Returns
152///
153/// - `usize` - Total number of matching dev-only AI schema byte sequences.
154#[must_use]
155pub fn count_ai_schema_markers(bytes: &[u8]) -> usize {
156    let v1_hits: usize = count_subslice_occurrences(bytes, MOBILE_AI_SCHEMA_V1_MARKER);
157    let v2_hits: usize = count_subslice_occurrences(bytes, MOBILE_AI_SCHEMA_V2_MARKER);
158    v1_hits + v2_hits
159}
160
161/// Counts non-overlapping occurrences of `needle` inside `haystack`.
162///
163/// # Arguments
164///
165/// - `&[u8]` - Input byte buffer to search.
166/// - `&[u8]` - Target byte pattern.
167///
168/// # Returns
169///
170/// - `usize` - Number of occurrences found.
171fn count_subslice_occurrences(haystack: &[u8], needle: &[u8]) -> usize {
172    if needle.is_empty() || haystack.len() < needle.len() {
173        return 0;
174    }
175    let mut matches: usize = 0;
176    let mut offset: usize = 0;
177    let limit: usize = haystack.len() - needle.len();
178    while offset <= limit {
179        if &haystack[offset..offset + needle.len()] == needle {
180            matches += 1;
181            offset += needle.len();
182        } else {
183            offset += 1;
184        }
185    }
186    matches
187}
188
189/// Verifies that a compiled release binary contains zero dev-only AI schema markers.
190///
191/// # Arguments
192///
193/// - `&Path` - Path to the compiled release `.so`, `.wasm`, or executable binary.
194///
195/// # Returns
196///
197/// - `io::Result<()>` - `Ok(())` when clean, or an error describing the leak count.
198pub fn assert_release_binary_ai_schema_clean(binary_path: &Path) -> io::Result<()> {
199    let raw_bytes: Vec<u8> = fs::read(binary_path)?;
200    let leak_count: usize = count_ai_schema_markers(&raw_bytes);
201    if leak_count != 0 {
202        return Err(Error::other(format!(
203            "release binary {} leaked {leak_count} dev-only AI schema marker(s)",
204            binary_path.display()
205        )));
206    }
207    Ok(())
208}
209
210/// Writes an icon PNG via the supplied callback or emits the embedded 1x1 transparent PNG fallback.
211///
212/// # Arguments
213///
214/// - `Option<&MobileIconWriter<'_>>` - Optional icon writer callback.
215/// - `&Path` - Destination PNG file path.
216/// - `u32` - Requested square pixel dimension.
217///
218/// # Returns
219///
220/// - `io::Result<()>` - Write outcome.
221pub fn write_icon_or_fallback(
222    icon_writer: Option<&MobileIconWriter<'_>>,
223    output_path: &Path,
224    size_px: u32,
225) -> io::Result<()> {
226    if let Some(parent_dir) = output_path.parent() {
227        fs::create_dir_all(parent_dir)?;
228    }
229    if let Some(writer) = icon_writer {
230        return writer(output_path, size_px);
231    }
232    fs::write(output_path, MOBILE_FALLBACK_ICON_PNG_BYTES)
233}
234
235/// Resolves the Android NDK prebuilt LLVM host directory tag for a given host OS name.
236///
237/// # Arguments
238///
239/// - `&str` - Host operating system identifier (`consts::OS`, e.g. `"macos"`, `"linux"`, `"windows"`).
240///
241/// # Returns
242///
243/// - `&'static str` - Prebuilt LLVM host tag (`darwin-x86_64`, `linux-x86_64`, or `windows-x86_64`).
244#[must_use]
245pub fn resolve_android_ndk_host_tag(host_os: &str) -> &'static str {
246    if host_os == MOBILE_HOST_OS_MACOS {
247        return ANDROID_NDK_HOST_TAG_MACOS;
248    }
249    if host_os == MOBILE_HOST_OS_WINDOWS {
250        return ANDROID_NDK_HOST_TAG_WINDOWS;
251    }
252    ANDROID_NDK_HOST_TAG_LINUX
253}
254
255/// Resolves the exact Android NDK clang linker executable for `abi` and `api_level`.
256///
257/// # Arguments
258///
259/// - `&Path` - Path to `<ndk>/toolchains/llvm/prebuilt/<host_tag>/bin`.
260/// - `AndroidAbi` - Target Android CPU ABI.
261/// - `&str` - Preferred Android API level string such as `"35"`.
262///
263/// # Returns
264///
265/// - `io::Result<PathBuf>` - Resolved executable path or `NotFound` error.
266pub fn resolve_android_ndk_linker(
267    ndk_llvm_bin: &Path,
268    abi: AndroidAbi,
269    api_level: &str,
270) -> io::Result<PathBuf> {
271    let prefix: &str = abi.clang_prefix();
272    let exact_base: String = format!("{prefix}{api_level}{CLANG_SUFFIX}");
273    if let Some(found) = find_host_executable(ndk_llvm_bin, &exact_base) {
274        return Ok(found);
275    }
276    let mut candidates: Vec<(Vec<u64>, String, PathBuf)> = Vec::new();
277    if let Ok(entries) = fs::read_dir(ndk_llvm_bin) {
278        for entry_res in entries {
279            let Ok(entry) = entry_res else {
280                continue;
281            };
282            let entry_path: PathBuf = entry.path();
283            if !entry_path.is_file() {
284                continue;
285            }
286            let Some(file_name) = entry_path.file_name().and_then(OsStr::to_str) else {
287                continue;
288            };
289            let stripped: &str = strip_windows_script_ext(file_name);
290            if !stripped.starts_with(prefix) || !stripped.ends_with(CLANG_SUFFIX) {
291                continue;
292            }
293            let api_slice: &str =
294                &stripped[prefix.len()..stripped.len().saturating_sub(CLANG_SUFFIX.len())];
295            if api_slice.is_empty()
296                || !api_slice
297                    .chars()
298                    .all(|digit_char: char| digit_char.is_ascii_digit())
299            {
300                continue;
301            }
302            let version_key: Vec<u64> = parse_version_sort_key(api_slice);
303            candidates.push((version_key, file_name.to_string(), entry_path));
304        }
305    }
306    candidates.sort_by(
307        |left: &(Vec<u64>, String, PathBuf), right: &(Vec<u64>, String, PathBuf)| {
308            left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1))
309        },
310    );
311    if let Some((_, best_name, best_path)) = candidates.pop() {
312        let stripped: &str = strip_windows_script_ext(&best_name);
313        if let Some(preferred) = find_host_executable(ndk_llvm_bin, stripped) {
314            return Ok(preferred);
315        }
316        return Ok(best_path);
317    }
318    Err(Error::new(
319        ErrorKind::NotFound,
320        format!(
321            "Android NDK clang linker for {} not found in {}",
322            abi.rust_triple(),
323            ndk_llvm_bin.display()
324        ),
325    ))
326}
327
328/// Detects the Android SDK, NDK, and build-tools executables from environment variables and standard paths.
329///
330/// # Arguments
331///
332/// - `Option<&str>` - Optional Android API level override (defaults to `ANDROID_API_LEVEL` or `"35"`).
333/// - `Option<&str>` - Optional build-tools version override (defaults to `ANDROID_BUILD_TOOLS` or `"35.0.0"`).
334///
335/// # Returns
336///
337/// - `io::Result<AndroidToolchain>` - Populated toolchain paths or a diagnostic `NotFound` error.
338pub fn detect_android_toolchain(
339    api_level: Option<&str>,
340    build_tools: Option<&str>,
341) -> io::Result<AndroidToolchain> {
342    let sdk_root: PathBuf = resolve_android_sdk_root()?;
343    let resolved_api: String = api_level
344        .map(str::to_string)
345        .or_else(|| env::var(ENV_ANDROID_API_LEVEL).ok())
346        .filter(|val: &String| !val.trim().is_empty())
347        .unwrap_or_else(|| ANDROID_DEFAULT_API_LEVEL.to_string());
348    let resolved_bt: String = build_tools
349        .map(str::to_string)
350        .or_else(|| env::var(ENV_ANDROID_BUILD_TOOLS).ok())
351        .filter(|val: &String| !val.trim().is_empty())
352        .unwrap_or_else(|| ANDROID_DEFAULT_BUILD_TOOLS.to_string());
353    let ndk_root: PathBuf = resolve_android_ndk_root(&sdk_root)?;
354    let host_tag: String = resolve_android_ndk_host_tag(consts::OS).to_string();
355    let ndk_llvm_bin: PathBuf = ndk_root
356        .join(ANDROID_NDK_PREBUILT_REL)
357        .join(&host_tag)
358        .join(MOBILE_DIR_BIN);
359    if !ndk_llvm_bin.is_dir() {
360        return Err(Error::new(
361            ErrorKind::NotFound,
362            format!(
363                "Android NDK LLVM bin directory not found at {}",
364                ndk_llvm_bin.display()
365            ),
366        ));
367    }
368    let android_jar: PathBuf = sdk_root
369        .join(ANDROID_PLATFORMS_DIR)
370        .join(format!("android-{resolved_api}"))
371        .join(FILE_ANDROID_JAR);
372    if !android_jar.is_file() {
373        return Err(Error::new(
374            ErrorKind::NotFound,
375            format!("Android platform jar missing: {}", android_jar.display()),
376        ));
377    }
378    let bt_dir: PathBuf = sdk_root.join(ANDROID_BUILD_TOOLS_DIR).join(&resolved_bt);
379    let aapt2_bin: PathBuf = require_host_executable(&bt_dir, TOOL_AAPT2)?;
380    let d8_bin: PathBuf = require_host_executable(&bt_dir, TOOL_D8)?;
381    let zipalign_bin: PathBuf = require_host_executable(&bt_dir, TOOL_ZIPALIGN)?;
382    let apksigner_bin: PathBuf = require_host_executable(&bt_dir, TOOL_APKSIGNER)?;
383    let adb_dir: PathBuf = sdk_root.join(ANDROID_PLATFORM_TOOLS_DIR);
384    let adb_bin: PathBuf =
385        find_host_executable(&adb_dir, TOOL_ADB).unwrap_or_else(|| adb_dir.join(TOOL_ADB));
386    let emu_dir: PathBuf = sdk_root.join(ANDROID_EMULATOR_DIR);
387    let emulator_bin: PathBuf = find_host_executable(&emu_dir, TOOL_EMULATOR)
388        .unwrap_or_else(|| emu_dir.join(TOOL_EMULATOR));
389    Ok(AndroidToolchain {
390        sdk_root,
391        ndk_root,
392        api_level: resolved_api,
393        build_tools: resolved_bt,
394        host_tag,
395        ndk_llvm_bin,
396        android_jar,
397        aapt2_bin,
398        d8_bin,
399        zipalign_bin,
400        apksigner_bin,
401        adb_bin,
402        emulator_bin,
403    })
404}
405
406/// Renders the complete `AndroidManifest.xml` for an Android phone or Wear OS build.
407///
408/// # Arguments
409///
410/// - `&AndroidBuildConfig` - Android build configuration specifying package, label, and target kind.
411/// - `&str` - Resolved semantic version name.
412/// - `u32` - Resolved numeric version code.
413///
414/// # Returns
415///
416/// - `String` - Complete UTF-8 `AndroidManifest.xml` text.
417#[must_use]
418pub fn render_android_manifest_xml(
419    config: &AndroidBuildConfig,
420    version: &str,
421    version_code: u32,
422) -> String {
423    let target_kind: AndroidTargetKind = config.get_target_kind();
424    let app_label: &str = config
425        .try_get_app_label()
426        .as_deref()
427        .unwrap_or_else(|| target_kind.default_app_label());
428    let package_id: &str = config.get_package_id();
429    let target_sdk: &str = config
430        .try_get_api_level()
431        .as_deref()
432        .unwrap_or(ANDROID_DEFAULT_API_LEVEL);
433    let wearos_feature: &str = if target_kind.is_wearos() {
434        ANDROID_WEAROS_FEATURE_XML
435    } else {
436        ""
437    };
438    let wearos_meta: &str = if target_kind.is_wearos() {
439        ANDROID_WEAROS_META_XML
440    } else {
441        ""
442    };
443    format!(
444        "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\
445<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n\
446    package=\"{package_id}\"\n\
447    android:versionCode=\"{version_code}\"\n\
448    android:versionName=\"{version}\">\n\
449    <uses-sdk android:minSdkVersion=\"{ANDROID_MIN_SDK_LEVEL}\" android:targetSdkVersion=\"{target_sdk}\" />\n\
450{wearos_feature}\
451    <uses-permission android:name=\"android.permission.VIBRATE\" />\n\
452    <uses-permission android:name=\"android.permission.POST_NOTIFICATIONS\" />\n\
453    <uses-permission android:name=\"android.permission.INTERNET\" />\n\
454    <uses-permission android:name=\"android.permission.CAMERA\" />\n\
455    <uses-permission android:name=\"android.permission.RECORD_AUDIO\" />\n\
456    <uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\" />\n\
457    <uses-permission android:name=\"android.permission.READ_CONTACTS\" />\n\
458    <uses-permission android:name=\"android.permission.READ_CALENDAR\" />\n\
459    <uses-permission android:name=\"android.permission.READ_MEDIA_IMAGES\" />\n\
460    <uses-permission android:name=\"android.permission.BLUETOOTH_CONNECT\" />\n\
461    <uses-permission android:name=\"android.permission.USE_BIOMETRIC\" />\n\
462    <uses-permission android:name=\"android.permission.BODY_SENSORS\" />\n\
463    <uses-permission android:name=\"android.permission.NEARBY_WIFI_DEVICES\" />\n\
464    <application\n\
465        android:label=\"{app_label}\"\n\
466        android:usesCleartextTraffic=\"true\"\n\
467        android:icon=\"@mipmap/ic_launcher\"\n\
468        android:roundIcon=\"@mipmap/ic_launcher\"\n\
469        android:theme=\"@style/EuvLaunchTheme\"\n\
470        android:hardwareAccelerated=\"true\">\n\
471{wearos_meta}\
472        <activity\n\
473            android:name=\".EuvActivity\"\n\
474            android:exported=\"true\"\n\
475            android:windowSoftInputMode=\"adjustResize|stateHidden\"\n\
476            android:configChanges=\"orientation|screenSize|screenLayout|smallestScreenSize|density|fontScale|uiMode|locale|keyboard|keyboardHidden|navigation\">\n\
477            <intent-filter>\n\
478                <action android:name=\"android.intent.action.MAIN\" />\n\
479                <category android:name=\"android.intent.category.LAUNCHER\" />\n\
480            </intent-filter>\n\
481            <intent-filter>\n\
482                <action android:name=\"android.intent.action.VIEW\" />\n\
483                <category android:name=\"android.intent.category.DEFAULT\" />\n\
484                <category android:name=\"android.intent.category.BROWSABLE\" />\n\
485                <data android:scheme=\"euv\" />\n\
486            </intent-filter>\n\
487        </activity>\n\
488    </application>\n\
489</manifest>\n"
490    )
491}
492
493/// Generates the complete standalone Android or Wear OS host project (Rust crate, JNI Java bridge, manifest, styles, icons).
494///
495/// # Arguments
496///
497/// - `&AndroidBuildConfig` - Build configuration specifying workspace root, target kind, ABIs, and output paths.
498/// - `Option<&MobileIconWriter<'_>>` - Optional callback writing mipmap PNG icons at requested sizes.
499///
500/// # Returns
501///
502/// - `io::Result<AndroidBuildReport>` - Summary of generated paths and resolved metadata.
503pub fn generate_android_host_project(
504    config: &AndroidBuildConfig,
505    icon_writer: Option<&MobileIconWriter<'_>>,
506) -> io::Result<AndroidBuildReport> {
507    let workspace_root: PathBuf = resolve_absolute_path(config.get_workspace_root());
508    let target_kind: AndroidTargetKind = config.get_target_kind();
509    let version: String = config
510        .try_get_app_version()
511        .clone()
512        .unwrap_or_else(|| resolve_workspace_semver(&workspace_root));
513    let version_code: u32 = config
514        .try_get_version_code()
515        .unwrap_or_else(|| compute_semver_version_code(&version));
516    let build_dir: PathBuf = config.try_get_build_dir().clone().unwrap_or_else(|| {
517        workspace_root
518            .join(MOBILE_HOSTS_SUBDIR)
519            .join(target_kind.host_dir_name())
520    });
521    let apk_path: PathBuf = config.try_get_out_file().clone().unwrap_or_else(|| {
522        workspace_root
523            .join(MOBILE_DIST_DIR_NAME)
524            .join(target_kind.default_out_subdir())
525            .join(target_kind.default_apk_name())
526    });
527    let rust_src_dir: PathBuf = build_dir.join(MOBILE_DIR_RUST).join(MOBILE_DIR_SRC);
528    let java_pkg_dir: PathBuf = build_dir.join(ANDROID_JAVA_PKG_REL);
529    let res_dir: PathBuf = build_dir.join(DIR_RES);
530    fs::create_dir_all(&rust_src_dir)?;
531    fs::create_dir_all(&java_pkg_dir)?;
532    if let Some(apk_parent) = apk_path.parent() {
533        fs::create_dir_all(apk_parent)?;
534    }
535    let host_config_src: String = render_android_host_config(target_kind, config.get_render_mode());
536    let cargo_toml_src: String = render_android_host_cargo_toml(&workspace_root, &version);
537    fs::write(
538        rust_src_dir.join(MOBILE_FILE_HOST_CONFIG_RS),
539        host_config_src,
540    )?;
541    fs::write(
542        build_dir.join(MOBILE_DIR_RUST).join(MOBILE_FILE_CARGO_TOML),
543        cargo_toml_src,
544    )?;
545    fs::write(
546        rust_src_dir.join(MOBILE_FILE_LIB_RS),
547        ANDROID_HOST_LIB_RS_TEMPLATE,
548    )?;
549    fs::write(
550        java_pkg_dir.join(ANDROID_JAVA_BRIDGE_FILE),
551        ANDROID_JAVA_BRIDGE_TEMPLATE,
552    )?;
553    fs::write(
554        java_pkg_dir.join(ANDROID_JAVA_ACTIVITY_FILE),
555        ANDROID_JAVA_ACTIVITY_TEMPLATE,
556    )?;
557    let manifest_xml: String = render_android_manifest_xml(config, &version, version_code);
558    fs::write(build_dir.join(ANDROID_MANIFEST_FILE), manifest_xml)?;
559    write_android_resources(&res_dir, icon_writer)?;
560    let abis: Vec<String> = resolved_android_abis(config)
561        .iter()
562        .map(|abi_item: &AndroidAbi| abi_item.as_abi_dir().to_string())
563        .collect();
564    Ok(AndroidBuildReport {
565        target_kind: target_kind.as_label().to_string(),
566        version,
567        version_code,
568        abis,
569        build_dir,
570        apk_path,
571        apk_bytes: 0,
572        ai_schema_clean: true,
573        installed: false,
574    })
575}
576
577/// Builds, aligns, signs, verifies, and optionally installs an Android or Wear OS APK in pure Rust.
578///
579/// # Arguments
580///
581/// - `&AndroidBuildConfig` - Full Android build, signing, and deployment configuration.
582/// - `Option<&MobileIconWriter<'_>>` - Optional callback writing mipmap PNG icons at requested sizes.
583///
584/// # Returns
585///
586/// - `io::Result<AndroidBuildReport>` - Detailed build report including final APK path and byte length.
587pub fn build_android_apk(
588    config: &AndroidBuildConfig,
589    icon_writer: Option<&MobileIconWriter<'_>>,
590) -> io::Result<AndroidBuildReport> {
591    let generated: AndroidBuildReport = generate_android_host_project(config, icon_writer)?;
592    if config.get_shell_only() {
593        return Ok(generated);
594    }
595    let toolchain: AndroidToolchain = detect_android_toolchain(
596        config.try_get_api_level().as_deref(),
597        config.try_get_build_tools().as_deref(),
598    )?;
599    let build_dir: &Path = generated.get_build_dir();
600    let rust_dir: PathBuf = build_dir.join(MOBILE_DIR_RUST);
601    let abis: Vec<AndroidAbi> = resolved_android_abis(config);
602    let mut staged_so_files: Vec<(String, Vec<u8>)> = Vec::new();
603    for abi_item in abis.iter().copied() {
604        let so_bytes: Vec<u8> =
605            compile_android_rust_abi(&rust_dir, &toolchain, abi_item, config.get_release())?;
606        let entry_name: String = format!("lib/{}/{}", abi_item.as_abi_dir(), ANDROID_HOST_SO_NAME);
607        staged_so_files.push((entry_name, so_bytes));
608    }
609    let dex_bytes: Vec<u8> = compile_android_java_dex(build_dir, &toolchain)?;
610    let res_dir: PathBuf = build_dir.join(DIR_RES);
611    let res_zip: PathBuf = build_dir.join(FILE_RES_ZIP);
612    let unaligned_apk: PathBuf = build_dir.join(FILE_UNALIGNED_APK);
613    let aligned_apk: PathBuf = build_dir.join(FILE_ALIGNED_APK);
614    let apk_out: &Path = generated.get_apk_path();
615    remove_file_if_exists(&res_zip)?;
616    remove_file_if_exists(&unaligned_apk)?;
617    remove_file_if_exists(&aligned_apk)?;
618    remove_file_if_exists(apk_out)?;
619    run_checked_command(
620        toolchain.get_aapt2_bin(),
621        &[
622            OsStr::new(ARG_COMPILE),
623            OsStr::new(ARG_DIR),
624            res_dir.as_os_str(),
625            OsStr::new("-o"),
626            res_zip.as_os_str(),
627        ],
628        None,
629        &[],
630    )?;
631    let manifest_path: PathBuf = build_dir.join(ANDROID_MANIFEST_FILE);
632    run_checked_command(
633        toolchain.get_aapt2_bin(),
634        &[
635            OsStr::new(ARG_LINK),
636            OsStr::new("-I"),
637            toolchain.get_android_jar().as_os_str(),
638            OsStr::new(ARG_MANIFEST),
639            manifest_path.as_os_str(),
640            OsStr::new(ARG_AUTO_ADD_OVERLAY),
641            OsStr::new("-R"),
642            res_zip.as_os_str(),
643            OsStr::new("-o"),
644            unaligned_apk.as_os_str(),
645        ],
646        None,
647        &[],
648    )?;
649    let mut zip_entries: Vec<(&str, &[u8])> = Vec::with_capacity(1 + staged_so_files.len());
650    zip_entries.push((ANDROID_CLASSES_DEX_NAME, dex_bytes.as_slice()));
651    for (entry_path, so_bytes) in staged_so_files.iter() {
652        zip_entries.push((entry_path.as_str(), so_bytes.as_slice()));
653    }
654    append_stored_entries_to_zip(&unaligned_apk, &zip_entries)?;
655    run_checked_command(
656        toolchain.get_zipalign_bin(),
657        &[
658            OsStr::new("-f"),
659            OsStr::new("-P"),
660            OsStr::new(ARG_ALIGN_PAGE_16),
661            OsStr::new(ARG_ALIGN_BYTES_4),
662            unaligned_apk.as_os_str(),
663            aligned_apk.as_os_str(),
664        ],
665        None,
666        &[],
667    )?;
668    sign_and_verify_apk(config, &toolchain, &aligned_apk, apk_out)?;
669    let apk_bytes: u64 = fs::metadata(apk_out)?.len();
670    let installed: bool = if config.get_install() {
671        install_and_launch_apk(config, &toolchain, apk_out)?;
672        true
673    } else {
674        false
675    };
676    Ok(AndroidBuildReport {
677        target_kind: generated.get_target_kind().clone(),
678        version: generated.get_version().clone(),
679        version_code: generated.get_version_code(),
680        abis: generated.get_abis().clone(),
681        build_dir: generated.get_build_dir().clone(),
682        apk_path: apk_out.to_path_buf(),
683        apk_bytes,
684        ai_schema_clean: true,
685        installed,
686    })
687}
688
689/// Appends uncompressed (`STORED`, method 0) entries to an existing ZIP archive in pure Rust.
690///
691/// # Arguments
692///
693/// - `&Path` - Path to the existing ZIP or unaligned APK file modified in place.
694/// - `&[(&str, &[u8])]` - Ordered `(entry_path, raw_bytes)` pairs appended uncompressed.
695///
696/// # Returns
697///
698/// - `io::Result<()>` - Success or I/O / malformed-ZIP error.
699pub fn append_stored_entries_to_zip(zip_path: &Path, entries: &[(&str, &[u8])]) -> io::Result<()> {
700    let existing: Vec<u8> = fs::read(zip_path)?;
701    let eocd_pos: usize = locate_zip_eocd(&existing)?;
702    let existing_count: usize =
703        u16::from_le_bytes([existing[eocd_pos + 10], existing[eocd_pos + 11]]) as usize;
704    let existing_cd_size: usize = u32::from_le_bytes([
705        existing[eocd_pos + 12],
706        existing[eocd_pos + 13],
707        existing[eocd_pos + 14],
708        existing[eocd_pos + 15],
709    ]) as usize;
710    let existing_cd_offset: usize = u32::from_le_bytes([
711        existing[eocd_pos + 16],
712        existing[eocd_pos + 17],
713        existing[eocd_pos + 18],
714        existing[eocd_pos + 19],
715    ]) as usize;
716    let cd_end: usize = existing_cd_offset.saturating_add(existing_cd_size);
717    if cd_end > eocd_pos {
718        return Err(Error::new(
719            ErrorKind::InvalidData,
720            format!(
721                "corrupt ZIP central directory bounds in {}",
722                zip_path.display()
723            ),
724        ));
725    }
726    let mut output_buf: Vec<u8> = Vec::with_capacity(existing.len());
727    output_buf.extend_from_slice(&existing[..existing_cd_offset]);
728    let mut central_dir: Vec<u8> = Vec::with_capacity(existing_cd_size);
729    central_dir.extend_from_slice(&existing[existing_cd_offset..cd_end]);
730    for (entry_name, entry_bytes) in entries.iter().copied() {
731        let local_offset: u32 = u32::try_from(output_buf.len())
732            .map_err(|_err: TryFromIntError| Error::other(ERR_ZIP_4GIB_LIMIT))?;
733        let entry_size: u32 = u32::try_from(entry_bytes.len())
734            .map_err(|_err: TryFromIntError| Error::other(ERR_ZIP_ENTRY_4GIB))?;
735        let name_bytes: &[u8] = entry_name.as_bytes();
736        let name_len: u16 = u16::try_from(name_bytes.len())
737            .map_err(|_err: TryFromIntError| Error::other(ERR_ZIP_NAME_TOO_LONG))?;
738        let crc: u32 = compute_ieee_crc32(entry_bytes);
739        write_zip_local_header(&mut output_buf, name_bytes, name_len, crc, entry_size);
740        output_buf.extend_from_slice(entry_bytes);
741        write_zip_central_header(
742            &mut central_dir,
743            name_bytes,
744            name_len,
745            crc,
746            entry_size,
747            local_offset,
748        );
749    }
750    let new_cd_offset: u32 = u32::try_from(output_buf.len())
751        .map_err(|_err: TryFromIntError| Error::other(ERR_ZIP_CD_OVERFLOW))?;
752    let new_cd_size: u32 = u32::try_from(central_dir.len())
753        .map_err(|_err: TryFromIntError| Error::other(ERR_ZIP_CD_TOO_LARGE))?;
754    let total_entries: u16 = u16::try_from(existing_count + entries.len())
755        .map_err(|_err: TryFromIntError| Error::other(ERR_ZIP_ENTRY_COUNT_OVERFLOW))?;
756    output_buf.extend_from_slice(&central_dir);
757    write_zip_eocd(&mut output_buf, total_entries, new_cd_size, new_cd_offset);
758    fs::write(zip_path, output_buf)
759}
760
761/// Computes the standard IEEE 802.3 CRC-32 checksum for `data`.
762///
763/// # Arguments
764///
765/// - `&[u8]` - Input byte slice.
766///
767/// # Returns
768///
769/// - `u32` - CRC-32 checksum.
770#[must_use]
771pub fn compute_ieee_crc32(data: &[u8]) -> u32 {
772    let mut crc: u32 = 0xFFFF_FFFF;
773    for byte_val in data.iter().copied() {
774        crc ^= u32::from(byte_val);
775        for _bit in 0..8 {
776            if (crc & 1) != 0 {
777                crc = (crc >> 1) ^ CRC32_POLY_REFLECTED;
778            } else {
779                crc >>= 1;
780            }
781        }
782    }
783    !crc
784}
785
786/// Locates the byte offset of the End-of-Central-Directory record in a ZIP archive.
787///
788/// # Arguments
789///
790/// - `&[u8]` - Raw ZIP archive bytes.
791///
792/// # Returns
793///
794/// - `io::Result<usize>` - Byte offset of the EOCD signature or `InvalidData` error.
795fn locate_zip_eocd(data: &[u8]) -> io::Result<usize> {
796    if data.len() < ZIP_EOCD_MIN_LEN {
797        return Err(Error::new(ErrorKind::InvalidData, ERR_ZIP_SHORT_EOCD));
798    }
799    let min_pos: usize = data
800        .len()
801        .saturating_sub(ZIP_EOCD_MIN_LEN + ZIP_MAX_COMMENT_LEN);
802    let mut cursor: usize = data.len() - ZIP_EOCD_MIN_LEN;
803    loop {
804        let sig: u32 = u32::from_le_bytes([
805            data[cursor],
806            data[cursor + 1],
807            data[cursor + 2],
808            data[cursor + 3],
809        ]);
810        if sig == ZIP_EOCD_SIG {
811            let comment_len: usize =
812                u16::from_le_bytes([data[cursor + 20], data[cursor + 21]]) as usize;
813            if cursor + ZIP_EOCD_MIN_LEN + comment_len == data.len() {
814                return Ok(cursor);
815            }
816        }
817        if cursor == min_pos {
818            break;
819        }
820        cursor -= 1;
821    }
822    Err(Error::new(ErrorKind::InvalidData, ERR_ZIP_NO_EOCD))
823}
824
825/// Appends a 30-byte ZIP Local File Header (method 0 / STORED) to `buf`.
826///
827/// # Arguments
828///
829/// - `&mut Vec<u8>` - Target archive byte buffer.
830/// - `&[u8]` - UTF-8 entry name bytes.
831/// - `u16` - Byte length of `name_bytes`.
832/// - `u32` - IEEE CRC-32 checksum.
833/// - `u32` - Uncompressed and stored byte length.
834fn write_zip_local_header(
835    buf: &mut Vec<u8>,
836    name_bytes: &[u8],
837    name_len: u16,
838    crc: u32,
839    entry_size: u32,
840) {
841    buf.extend_from_slice(&ZIP_LOCAL_FILE_SIG.to_le_bytes());
842    buf.extend_from_slice(&20u16.to_le_bytes());
843    buf.extend_from_slice(&0u16.to_le_bytes());
844    buf.extend_from_slice(&0u16.to_le_bytes());
845    buf.extend_from_slice(&0u16.to_le_bytes());
846    buf.extend_from_slice(&0u16.to_le_bytes());
847    buf.extend_from_slice(&crc.to_le_bytes());
848    buf.extend_from_slice(&entry_size.to_le_bytes());
849    buf.extend_from_slice(&entry_size.to_le_bytes());
850    buf.extend_from_slice(&name_len.to_le_bytes());
851    buf.extend_from_slice(&0u16.to_le_bytes());
852    buf.extend_from_slice(name_bytes);
853}
854
855/// Appends a 46-byte ZIP Central Directory Header (method 0 / STORED) to `buf`.
856///
857/// # Arguments
858///
859/// - `&mut Vec<u8>` - Target central directory byte buffer.
860/// - `&[u8]` - UTF-8 entry name bytes.
861/// - `u16` - Byte length of `name_bytes`.
862/// - `u32` - IEEE CRC-32 checksum.
863/// - `u32` - Uncompressed and stored byte length.
864/// - `u32` - Local file header byte offset inside the archive.
865fn write_zip_central_header(
866    buf: &mut Vec<u8>,
867    name_bytes: &[u8],
868    name_len: u16,
869    crc: u32,
870    entry_size: u32,
871    local_offset: u32,
872) {
873    buf.extend_from_slice(&ZIP_CENTRAL_DIR_SIG.to_le_bytes());
874    buf.extend_from_slice(&20u16.to_le_bytes());
875    buf.extend_from_slice(&20u16.to_le_bytes());
876    buf.extend_from_slice(&0u16.to_le_bytes());
877    buf.extend_from_slice(&0u16.to_le_bytes());
878    buf.extend_from_slice(&0u16.to_le_bytes());
879    buf.extend_from_slice(&0u16.to_le_bytes());
880    buf.extend_from_slice(&crc.to_le_bytes());
881    buf.extend_from_slice(&entry_size.to_le_bytes());
882    buf.extend_from_slice(&entry_size.to_le_bytes());
883    buf.extend_from_slice(&name_len.to_le_bytes());
884    buf.extend_from_slice(&0u16.to_le_bytes());
885    buf.extend_from_slice(&0u16.to_le_bytes());
886    buf.extend_from_slice(&0u16.to_le_bytes());
887    buf.extend_from_slice(&0u16.to_le_bytes());
888    buf.extend_from_slice(&0u32.to_le_bytes());
889    buf.extend_from_slice(&local_offset.to_le_bytes());
890    buf.extend_from_slice(name_bytes);
891}
892
893/// Appends a 22-byte ZIP End-of-Central-Directory record to `buf`.
894///
895/// # Arguments
896///
897/// - `&mut Vec<u8>` - Target archive byte buffer.
898/// - `u16` - Total entry count in the archive.
899/// - `u32` - Total byte length of the central directory.
900/// - `u32` - Byte offset of the central directory start.
901fn write_zip_eocd(buf: &mut Vec<u8>, total_entries: u16, cd_size: u32, cd_offset: u32) {
902    buf.extend_from_slice(&ZIP_EOCD_SIG.to_le_bytes());
903    buf.extend_from_slice(&0u16.to_le_bytes());
904    buf.extend_from_slice(&0u16.to_le_bytes());
905    buf.extend_from_slice(&total_entries.to_le_bytes());
906    buf.extend_from_slice(&total_entries.to_le_bytes());
907    buf.extend_from_slice(&cd_size.to_le_bytes());
908    buf.extend_from_slice(&cd_offset.to_le_bytes());
909    buf.extend_from_slice(&0u16.to_le_bytes());
910}
911
912/// Renders the Android host `host_config.rs` source file.
913///
914/// # Arguments
915///
916/// - `AndroidTargetKind` - Selected Android device form factor.
917/// - `RenderArg` - Selected render pipeline mode.
918///
919/// # Returns
920///
921/// - `String` - Generated `host_config.rs` file contents.
922fn render_android_host_config(target_kind: AndroidTargetKind, render_mode: RenderArg) -> String {
923    let platform_expr: &str = target_kind.platform_kind_expr();
924    let render_expr: &str = render_mode_const_expr(render_mode);
925    let is_wearos: bool = target_kind.is_wearos();
926    format!(
927        "use euv::{{PlatformKind, RenderMode}};\n\n\
928pub const HOST_PLATFORM_KIND: PlatformKind = {platform_expr};\n\
929pub const HOST_RENDER_MODE: RenderMode = {render_expr};\n\
930pub const HOST_IS_WEAROS: bool = {is_wearos};\n"
931    )
932}
933
934/// Renders the standalone Android host crate `Cargo.toml` referencing the active workspace.
935///
936/// # Arguments
937///
938/// - `&Path` - Absolute path to the `euv` workspace root.
939/// - `&str` - Dynamic semantic version string.
940///
941/// # Returns
942///
943/// - `String` - Generated `Cargo.toml` contents.
944fn render_android_host_cargo_toml(workspace_root: &Path, version: &str) -> String {
945    let root_escaped: String = escape_toml_path(workspace_root);
946    let example_escaped: String = escape_toml_path(&workspace_root.join(MOBILE_DIR_EXAMPLE));
947    format!(
948        "[workspace]\n\n\
949[package]\n\
950name = \"euv-android-host\"\n\
951version = \"{version}\"\n\
952edition = \"2024\"\n\n\
953[lib]\n\
954crate-type = [\"cdylib\"]\n\n\
955[dependencies]\n\
956euv = {{ path = \"{root_escaped}\" }}\n\
957euv-example = {{ path = \"{example_escaped}\" }}\n\n\
958[profile.release]\n\
959opt-level = 3\n\
960lto = \"thin\"\n\
961codegen-units = 1\n\
962panic = \"abort\"\n\
963strip = \"symbols\"\n"
964    )
965}
966
967/// Writes Android theme XML resources and all five mipmap launcher icon densities.
968///
969/// # Arguments
970///
971/// - `&Path` - Target Android `res/` staging directory.
972/// - `Option<&MobileIconWriter<'_>>` - Optional icon writer callback.
973///
974/// # Returns
975///
976/// - `io::Result<()>` - Resource staging outcome.
977fn write_android_resources(
978    res_dir: &Path,
979    icon_writer: Option<&MobileIconWriter<'_>>,
980) -> io::Result<()> {
981    if res_dir.exists() {
982        fs::remove_dir_all(res_dir)?;
983    }
984    let style_dirs: [(&str, &str); 4] = [
985        (DIR_VALUES, ANDROID_STYLES_LIGHT_XML),
986        (DIR_VALUES_NIGHT, ANDROID_STYLES_NIGHT_XML),
987        (DIR_VALUES_V31, ANDROID_STYLES_V31_XML),
988        (DIR_VALUES_NIGHT_V31, ANDROID_STYLES_NIGHT_V31_XML),
989    ];
990    for (dir_name, xml_body) in style_dirs.iter().copied() {
991        let style_dir: PathBuf = res_dir.join(dir_name);
992        fs::create_dir_all(&style_dir)?;
993        fs::write(style_dir.join(FILE_STYLES_XML), xml_body)?;
994    }
995    for (density_dir, size_px) in ANDROID_MIPMAP_DENSITIES.iter().copied() {
996        let icon_path: PathBuf = res_dir.join(density_dir).join(ANDROID_LAUNCHER_ICON_FILE);
997        write_icon_or_fallback(icon_writer, &icon_path, size_px)?;
998    }
999    Ok(())
1000}
1001
1002/// Compiles the Android Rust host shared library for a single ABI and verifies release AI-schema stripping.
1003///
1004/// # Arguments
1005///
1006/// - `&Path` - Directory containing the generated `euv-android-host` `Cargo.toml`.
1007/// - `&AndroidToolchain` - Resolved Android SDK/NDK toolchain paths.
1008/// - `AndroidAbi` - Target CPU ABI to compile.
1009/// - `bool` - Whether to compile with `--release` and enforce zero AI-schema markers.
1010///
1011/// # Returns
1012///
1013/// - `io::Result<Vec<u8>>` - Compiled `libeuv_android_host.so` bytes.
1014fn compile_android_rust_abi(
1015    rust_dir: &Path,
1016    toolchain: &AndroidToolchain,
1017    abi: AndroidAbi,
1018    release: bool,
1019) -> io::Result<Vec<u8>> {
1020    let linker: PathBuf =
1021        resolve_android_ndk_linker(toolchain.get_ndk_llvm_bin(), abi, toolchain.get_api_level())?;
1022    let llvm_ar: PathBuf = find_host_executable(toolchain.get_ndk_llvm_bin(), TOOL_LLVM_AR)
1023        .unwrap_or_else(|| toolchain.get_ndk_llvm_bin().join(TOOL_LLVM_AR));
1024    let cc_key: String = format!("CC_{}", abi.cargo_env_triple());
1025    let ar_key: String = format!("AR_{}", abi.cargo_env_triple());
1026    let mut args: Vec<&OsStr> = Vec::new();
1027    args.push(OsStr::new(MOBILE_ARG_BUILD));
1028    if release {
1029        args.push(OsStr::new(MOBILE_ARG_RELEASE));
1030    }
1031    args.push(OsStr::new(MOBILE_ARG_TARGET));
1032    args.push(OsStr::new(abi.rust_triple()));
1033    let envs: [(&str, &OsStr); 3] = [
1034        (abi.cargo_linker_env(), linker.as_os_str()),
1035        (cc_key.as_str(), linker.as_os_str()),
1036        (ar_key.as_str(), llvm_ar.as_os_str()),
1037    ];
1038    run_checked_command(Path::new(MOBILE_CMD_CARGO), &args, Some(rust_dir), &envs)?;
1039    let profile_dir: &str = if release {
1040        MOBILE_DIR_RELEASE
1041    } else {
1042        MOBILE_DIR_DEBUG
1043    };
1044    let so_path: PathBuf = rust_dir
1045        .join(MOBILE_DIR_TARGET)
1046        .join(abi.rust_triple())
1047        .join(profile_dir)
1048        .join(ANDROID_HOST_SO_NAME);
1049    if release {
1050        assert_release_binary_ai_schema_clean(&so_path)?;
1051    }
1052    fs::read(&so_path)
1053}
1054
1055/// Compiles the Android Java bridge sources into bytecode and packages `classes.dex` via `d8`.
1056///
1057/// # Arguments
1058///
1059/// - `&Path` - Android host build staging directory.
1060/// - `&AndroidToolchain` - Resolved Android SDK toolchain paths.
1061///
1062/// # Returns
1063///
1064/// - `io::Result<Vec<u8>>` - Compiled `classes.dex` bytes.
1065fn compile_android_java_dex(build_dir: &Path, toolchain: &AndroidToolchain) -> io::Result<Vec<u8>> {
1066    let classes_dir: PathBuf = build_dir.join(DIR_CLASSES);
1067    let dex_dir: PathBuf = build_dir.join(DIR_DEX);
1068    if classes_dir.exists() {
1069        fs::remove_dir_all(&classes_dir)?;
1070    }
1071    if dex_dir.exists() {
1072        fs::remove_dir_all(&dex_dir)?;
1073    }
1074    fs::create_dir_all(&classes_dir)?;
1075    fs::create_dir_all(&dex_dir)?;
1076    let bridge_java: PathBuf = build_dir
1077        .join(ANDROID_JAVA_PKG_REL)
1078        .join(ANDROID_JAVA_BRIDGE_FILE);
1079    let activity_java: PathBuf = build_dir
1080        .join(ANDROID_JAVA_PKG_REL)
1081        .join(ANDROID_JAVA_ACTIVITY_FILE);
1082    run_checked_command(
1083        Path::new(CMD_JAVAC),
1084        &[
1085            OsStr::new(ARG_SOURCE),
1086            OsStr::new(JAVA_BYTECODE_LEVEL),
1087            OsStr::new(ARG_JAVA_TARGET),
1088            OsStr::new(JAVA_BYTECODE_LEVEL),
1089            OsStr::new(ARG_CLASSPATH),
1090            toolchain.get_android_jar().as_os_str(),
1091            OsStr::new("-d"),
1092            classes_dir.as_os_str(),
1093            bridge_java.as_os_str(),
1094            activity_java.as_os_str(),
1095        ],
1096        None,
1097        &[],
1098    )?;
1099    let mut class_files: Vec<PathBuf> = Vec::new();
1100    collect_files_with_extension(&classes_dir, EXT_CLASS, &mut class_files)?;
1101    class_files.sort();
1102    let mut d8_args: Vec<&OsStr> = vec![
1103        OsStr::new(ARG_MIN_API),
1104        OsStr::new(ANDROID_MIN_SDK_LEVEL),
1105        OsStr::new(MOBILE_ARG_LIB),
1106        toolchain.get_android_jar().as_os_str(),
1107        OsStr::new(ARG_OUTPUT),
1108        dex_dir.as_os_str(),
1109    ];
1110    for class_file in class_files.iter() {
1111        d8_args.push(class_file.as_os_str());
1112    }
1113    run_checked_command(toolchain.get_d8_bin(), &d8_args, None, &[])?;
1114    fs::read(dex_dir.join(ANDROID_CLASSES_DEX_NAME))
1115}
1116
1117/// Signs and verifies the aligned APK using either a custom keystore or an auto-created debug keystore.
1118///
1119/// # Arguments
1120///
1121/// - `&AndroidBuildConfig` - Android build configuration with optional keystore overrides.
1122/// - `&AndroidToolchain` - Resolved Android SDK toolchain paths.
1123/// - `&Path` - Aligned input APK path.
1124/// - `&Path` - Signed final APK output path.
1125///
1126/// # Returns
1127///
1128/// - `io::Result<()>` - Signing and verification outcome.
1129fn sign_and_verify_apk(
1130    config: &AndroidBuildConfig,
1131    toolchain: &AndroidToolchain,
1132    aligned_apk: &Path,
1133    apk_out: &Path,
1134) -> io::Result<()> {
1135    let ks_path: PathBuf = resolve_android_keystore_path(config)?;
1136    let ks_pass: String = config
1137        .try_get_keystore_pass()
1138        .clone()
1139        .or_else(|| env::var(ENV_EUV_ANDROID_KEYSTORE_PASS).ok())
1140        .unwrap_or_else(|| ANDROID_DEFAULT_KEYSTORE_PASS.to_string());
1141    let key_pass: String = config
1142        .try_get_key_pass()
1143        .clone()
1144        .or_else(|| env::var(ENV_EUV_ANDROID_KEY_PASS).ok())
1145        .unwrap_or_else(|| ks_pass.clone());
1146    let key_alias: String = config
1147        .try_get_key_alias()
1148        .clone()
1149        .or_else(|| env::var(ENV_EUV_ANDROID_KEY_ALIAS).ok())
1150        .unwrap_or_else(|| ANDROID_DEFAULT_KEY_ALIAS.to_string());
1151    if !ks_path.is_file() {
1152        if let Some(ks_parent) = ks_path.parent() {
1153            fs::create_dir_all(ks_parent)?;
1154        }
1155        run_checked_command(
1156            Path::new(CMD_KEYTOOL),
1157            &[
1158                OsStr::new(ARG_GENKEYPAIR),
1159                OsStr::new("-v"),
1160                OsStr::new(ARG_KEYSTORE),
1161                ks_path.as_os_str(),
1162                OsStr::new(ARG_STOREPASS),
1163                OsStr::new(&ks_pass),
1164                OsStr::new(ARG_ALIAS),
1165                OsStr::new(&key_alias),
1166                OsStr::new(ARG_KEYTOOL_KEYPASS),
1167                OsStr::new(&key_pass),
1168                OsStr::new(ARG_KEYALG),
1169                OsStr::new(ARG_KEYALG_RSA),
1170                OsStr::new(ARG_KEYSIZE),
1171                OsStr::new(ARG_KEYSIZE_2048),
1172                OsStr::new(ARG_VALIDITY),
1173                OsStr::new(ARG_VALIDITY_10000),
1174                OsStr::new(ARG_DNAME),
1175                OsStr::new(ANDROID_DEBUG_DNAME),
1176            ],
1177            None,
1178            &[],
1179        )?;
1180    }
1181    let ks_pass_arg: String = format!("pass:{ks_pass}");
1182    let key_pass_arg: String = format!("pass:{key_pass}");
1183    run_checked_command(
1184        toolchain.get_apksigner_bin(),
1185        &[
1186            OsStr::new(ARG_SIGN),
1187            OsStr::new(ARG_KS),
1188            ks_path.as_os_str(),
1189            OsStr::new(ARG_KS_PASS),
1190            OsStr::new(&ks_pass_arg),
1191            OsStr::new(ARG_KEY_PASS),
1192            OsStr::new(&key_pass_arg),
1193            OsStr::new(ARG_KS_KEY_ALIAS),
1194            OsStr::new(&key_alias),
1195            OsStr::new(ARG_OUT),
1196            apk_out.as_os_str(),
1197            aligned_apk.as_os_str(),
1198        ],
1199        None,
1200        &[],
1201    )?;
1202    let _: Output = run_checked_command(
1203        toolchain.get_apksigner_bin(),
1204        &[OsStr::new(ARG_VERIFY), apk_out.as_os_str()],
1205        None,
1206        &[],
1207    )?;
1208    Ok(())
1209}
1210
1211/// Installs and launches the signed APK across all online ADB devices, booting an AVD if none are online.
1212///
1213/// # Arguments
1214///
1215/// - `&AndroidBuildConfig` - Android build configuration with package ID and optional AVD name.
1216/// - `&AndroidToolchain` - Resolved Android SDK toolchain paths.
1217/// - `&Path` - Signed APK path to deploy.
1218///
1219/// # Returns
1220///
1221/// - `io::Result<()>` - Installation and launch outcome.
1222fn install_and_launch_apk(
1223    config: &AndroidBuildConfig,
1224    toolchain: &AndroidToolchain,
1225    apk_out: &Path,
1226) -> io::Result<()> {
1227    let adb_bin: &Path = toolchain.get_adb_bin();
1228    let _: io::Result<Output> = Command::new(adb_bin).arg(ARG_ADB_START_SERVER).output();
1229    let mut serials: Vec<String> = list_online_adb_serials(adb_bin)?;
1230    if serials.is_empty() {
1231        let avd_name: String = resolve_android_avd_name(config);
1232        let mut emulator_cmd: Command = Command::new(toolchain.get_emulator_bin());
1233        let _: &mut Command = emulator_cmd
1234            .arg(ARG_EMULATOR_AVD)
1235            .arg(&avd_name)
1236            .arg(ARG_EMULATOR_NO_BOOT_ANIM)
1237            .arg(ARG_EMULATOR_GPU)
1238            .arg(ARG_EMULATOR_GPU_AUTO)
1239            .stdin(Stdio::null())
1240            .stdout(Stdio::null())
1241            .stderr(Stdio::null());
1242        let _: Child = emulator_cmd.spawn()?;
1243        run_checked_command(adb_bin, &[OsStr::new(ARG_ADB_WAIT_FOR_DEVICE)], None, &[])?;
1244        for _attempt in 0..ANDROID_AVD_BOOT_POLL_ATTEMPTS {
1245            let boot_out: Output = Command::new(adb_bin)
1246                .args([ARG_ADB_SHELL, ARG_ADB_GETPROP, ANDROID_PROP_BOOT_COMPLETED])
1247                .output()?;
1248            let prop_val: String = String::from_utf8_lossy(&boot_out.stdout).trim().to_string();
1249            if prop_val == "1" {
1250                break;
1251            }
1252            thread::sleep(Duration::from_secs(ANDROID_AVD_BOOT_POLL_SECS));
1253        }
1254        thread::sleep(Duration::from_secs(ANDROID_AVD_BOOT_SETTLE_SECS));
1255        serials = list_online_adb_serials(adb_bin)?;
1256    }
1257    let activity_component: String =
1258        format!("{}/{}", config.get_package_id(), ANDROID_ACTIVITY_COMPONENT);
1259    for serial in serials.iter() {
1260        run_checked_command(
1261            adb_bin,
1262            &[
1263                OsStr::new("-s"),
1264                OsStr::new(serial),
1265                OsStr::new(ARG_ADB_INSTALL),
1266                OsStr::new("-r"),
1267                apk_out.as_os_str(),
1268            ],
1269            None,
1270            &[],
1271        )?;
1272        run_checked_command(
1273            adb_bin,
1274            &[
1275                OsStr::new("-s"),
1276                OsStr::new(serial),
1277                OsStr::new(ARG_ADB_SHELL),
1278                OsStr::new("am"),
1279                OsStr::new(ARG_ADB_START),
1280                OsStr::new("-n"),
1281                OsStr::new(&activity_component),
1282            ],
1283            None,
1284            &[],
1285        )?;
1286    }
1287    Ok(())
1288}
1289
1290/// Lists all currently online `adb` device serials in `device` state.
1291///
1292/// # Arguments
1293///
1294/// - `&Path` - Path to the `adb` executable.
1295///
1296/// # Returns
1297///
1298/// - `io::Result<Vec<String>>` - Online device serial numbers.
1299fn list_online_adb_serials(adb_bin: &Path) -> io::Result<Vec<String>> {
1300    let output: Output = Command::new(adb_bin).arg(ARG_ADB_DEVICES).output()?;
1301    let stdout_str: Cow<'_, str> = String::from_utf8_lossy(&output.stdout);
1302    let mut serials: Vec<String> = Vec::new();
1303    for raw_line in stdout_str.lines().skip(1) {
1304        let mut parts: SplitWhitespace<'_> = raw_line.split_whitespace();
1305        let Some(serial) = parts.next() else {
1306            continue;
1307        };
1308        let Some(state) = parts.next() else {
1309            continue;
1310        };
1311        if state == ANDROID_ADB_STATUS_DEVICE {
1312            serials.push(serial.to_string());
1313        }
1314    }
1315    Ok(serials)
1316}
1317
1318/// Resolves the active Android ABI list, defaulting to `Arm64V8a` when empty.
1319///
1320/// # Arguments
1321///
1322/// - `&AndroidBuildConfig` - Android build configuration.
1323///
1324/// # Returns
1325///
1326/// - `Vec<AndroidAbi>` - Non-empty ABI list.
1327fn resolved_android_abis(config: &AndroidBuildConfig) -> Vec<AndroidAbi> {
1328    if config.get_abis().is_empty() {
1329        return vec![AndroidAbi::Arm64V8a];
1330    }
1331    config.get_abis().clone()
1332}
1333
1334/// Resolves the Android SDK root directory from environment variables or OS defaults.
1335///
1336/// # Returns
1337///
1338/// - `io::Result<PathBuf>` - Existing Android SDK root path or `NotFound` error.
1339fn resolve_android_sdk_root() -> io::Result<PathBuf> {
1340    for env_key in [ENV_ANDROID_HOME, ENV_ANDROID_SDK_ROOT] {
1341        if let Ok(raw_val) = env::var(env_key) {
1342            let trimmed: &str = raw_val.trim();
1343            if !trimmed.is_empty() {
1344                let candidate: PathBuf = PathBuf::from(trimmed);
1345                if candidate.is_dir() {
1346                    return Ok(candidate);
1347                }
1348            }
1349        }
1350    }
1351    let mut candidates: Vec<PathBuf> = Vec::new();
1352    if let Some(home_dir) = resolve_user_home_dir() {
1353        if consts::OS == MOBILE_HOST_OS_MACOS {
1354            candidates.push(home_dir.join(ANDROID_MACOS_HOME_SDK_REL));
1355        } else if consts::OS == MOBILE_HOST_OS_WINDOWS {
1356            candidates.push(home_dir.join(ANDROID_WINDOWS_HOME_SDK_REL));
1357        } else {
1358            candidates.push(home_dir.join(ANDROID_LINUX_HOME_SDK_REL));
1359        }
1360    }
1361    candidates.push(PathBuf::from(ANDROID_CI_LINUX_SDK_FALLBACK));
1362    for candidate in candidates.into_iter() {
1363        if candidate.is_dir() {
1364            return Ok(candidate);
1365        }
1366    }
1367    Err(Error::new(ErrorKind::NotFound, ERR_ANDROID_SDK_MISSING))
1368}
1369
1370/// Resolves the Android NDK root directory from env vars or highest installed `<sdk>/ndk/<version>`.
1371///
1372/// # Arguments
1373///
1374/// - `&Path` - Resolved Android SDK root directory.
1375///
1376/// # Returns
1377///
1378/// - `io::Result<PathBuf>` - Existing Android NDK root directory or `NotFound` error.
1379fn resolve_android_ndk_root(sdk_root: &Path) -> io::Result<PathBuf> {
1380    for env_key in [ENV_ANDROID_NDK_LATEST_HOME, ENV_ANDROID_NDK_HOME] {
1381        if let Ok(raw_val) = env::var(env_key) {
1382            let trimmed: &str = raw_val.trim();
1383            if !trimmed.is_empty() {
1384                let candidate: PathBuf = PathBuf::from(trimmed);
1385                if candidate.is_dir() {
1386                    return Ok(candidate);
1387                }
1388            }
1389        }
1390    }
1391    if let Ok(preferred) = env::var(ENV_EUV_ANDROID_NDK_VERSION) {
1392        let trimmed: &str = preferred.trim();
1393        if !trimmed.is_empty() {
1394            let preferred_dir: PathBuf = sdk_root.join(ANDROID_NDK_DIR).join(trimmed);
1395            if preferred_dir.is_dir() {
1396                return Ok(preferred_dir);
1397            }
1398        }
1399    }
1400    let ndk_parent: PathBuf = sdk_root.join(ANDROID_NDK_DIR);
1401    let mut versions: Vec<(Vec<u64>, String, PathBuf)> = Vec::new();
1402    if let Ok(entries) = fs::read_dir(&ndk_parent) {
1403        for entry_res in entries {
1404            let Ok(entry) = entry_res else {
1405                continue;
1406            };
1407            let entry_path: PathBuf = entry.path();
1408            if !entry_path.is_dir() {
1409                continue;
1410            }
1411            let Some(name_str) = entry_path.file_name().and_then(OsStr::to_str) else {
1412                continue;
1413            };
1414            versions.push((
1415                parse_version_sort_key(name_str),
1416                name_str.to_string(),
1417                entry_path,
1418            ));
1419        }
1420    }
1421    versions.sort_by(
1422        |left: &(Vec<u64>, String, PathBuf), right: &(Vec<u64>, String, PathBuf)| {
1423            left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1))
1424        },
1425    );
1426    if let Some((_, _, latest_dir)) = versions.pop() {
1427        return Ok(latest_dir);
1428    }
1429    Err(Error::new(
1430        ErrorKind::NotFound,
1431        format!(
1432            "Android NDK not found under {} (set ANDROID_NDK_HOME)",
1433            ndk_parent.display()
1434        ),
1435    ))
1436}
1437
1438/// Resolves the target Android keystore file path from config, env, or `~/.android/debug.keystore`.
1439///
1440/// # Arguments
1441///
1442/// - `&AndroidBuildConfig` - Android build configuration.
1443///
1444/// # Returns
1445///
1446/// - `io::Result<PathBuf>` - Resolved keystore path.
1447fn resolve_android_keystore_path(config: &AndroidBuildConfig) -> io::Result<PathBuf> {
1448    if let Some(custom) = config.try_get_keystore_path() {
1449        return Ok(custom.clone());
1450    }
1451    if let Ok(env_ks) = env::var(ENV_EUV_ANDROID_KEYSTORE) {
1452        let trimmed: &str = env_ks.trim();
1453        if !trimmed.is_empty() {
1454            return Ok(PathBuf::from(trimmed));
1455        }
1456    }
1457    let home_dir: PathBuf = resolve_user_home_dir()
1458        .ok_or_else(|| Error::new(ErrorKind::NotFound, ERR_ANDROID_HOME_MISSING))?;
1459    Ok(home_dir.join(ANDROID_DEBUG_KEYSTORE_REL))
1460}
1461
1462/// Resolves the target Android AVD name from config, environment variables, or target kind defaults.
1463///
1464/// # Arguments
1465///
1466/// - `&AndroidBuildConfig` - Android build configuration.
1467///
1468/// # Returns
1469///
1470/// - `String` - Resolved AVD name.
1471fn resolve_android_avd_name(config: &AndroidBuildConfig) -> String {
1472    if let Some(custom) = config.try_get_avd_name() {
1473        return custom.clone();
1474    }
1475    let env_key: &str = if config.get_target_kind().is_wearos() {
1476        ENV_ANDROID_WEAR_AVD_NAME
1477    } else {
1478        ENV_ANDROID_AVD_NAME
1479    };
1480    if let Ok(val) = env::var(env_key) {
1481        let trimmed: &str = val.trim();
1482        if !trimmed.is_empty() {
1483            return trimmed.to_string();
1484        }
1485    }
1486    config.get_target_kind().default_avd_name().to_string()
1487}
1488
1489/// Resolves the current user home directory across Unix (`HOME`) and Windows (`USERPROFILE`).
1490///
1491/// # Returns
1492///
1493/// - `Option<PathBuf>` - User home directory path when set.
1494pub(crate) fn resolve_user_home_dir() -> Option<PathBuf> {
1495    for env_key in [MOBILE_ENV_HOME, MOBILE_ENV_USERPROFILE] {
1496        if let Ok(raw_val) = env::var(env_key) {
1497            let trimmed: &str = raw_val.trim();
1498            if !trimmed.is_empty() {
1499                return Some(PathBuf::from(trimmed));
1500            }
1501        }
1502    }
1503    None
1504}
1505
1506/// Resolves a path to an absolute canonical path where possible.
1507///
1508/// # Arguments
1509///
1510/// - `&Path` - Input relative or absolute path.
1511///
1512/// # Returns
1513///
1514/// - `PathBuf` - Absolute path suitable for generated host `Cargo.toml` dependencies.
1515pub(crate) fn resolve_absolute_path(path: &Path) -> PathBuf {
1516    if let Ok(canonical) = fs::canonicalize(path) {
1517        return canonical;
1518    }
1519    if path.is_absolute() {
1520        return path.to_path_buf();
1521    }
1522    env::current_dir()
1523        .map(|cwd: PathBuf| cwd.join(path))
1524        .unwrap_or_else(|_err: Error| path.to_path_buf())
1525}
1526
1527/// Formats a filesystem path as a TOML string literal with forward slashes for cross-OS portability.
1528///
1529/// # Arguments
1530///
1531/// - `&Path` - Path to encode inside a double-quoted TOML string.
1532///
1533/// # Returns
1534///
1535/// - `String` - Escaped path string.
1536pub(crate) fn escape_toml_path(path: &Path) -> String {
1537    path.to_string_lossy()
1538        .replace('\\', "/")
1539        .replace('"', "\\\"")
1540}
1541
1542/// Executes an external command and returns a detailed error containing stderr/stdout on failure.
1543///
1544/// # Arguments
1545///
1546/// - `&Path` - Executable program name or absolute path.
1547/// - `&[&OsStr]` - Command-line arguments.
1548/// - `Option<&Path>` - Optional working directory.
1549/// - `&[(&str, &OsStr)]` - Additional environment variable pairs.
1550///
1551/// # Returns
1552///
1553/// - `io::Result<Output>` - Captured command output on zero exit status.
1554pub(crate) fn run_checked_command(
1555    program: &Path,
1556    args: &[&OsStr],
1557    cwd: Option<&Path>,
1558    envs: &[(&str, &OsStr)],
1559) -> io::Result<Output> {
1560    let mut cmd: Command = Command::new(program);
1561    let _: &mut Command = cmd.args(args);
1562    if let Some(dir) = cwd {
1563        let _: &mut Command = cmd.current_dir(dir);
1564    }
1565    for (env_key, env_val) in envs.iter().copied() {
1566        let _: &mut Command = cmd.env(env_key, env_val);
1567    }
1568    let output: Output = cmd.output().map_err(|err: Error| {
1569        Error::new(
1570            err.kind(),
1571            format!("failed to execute {}: {err}", program.display()),
1572        )
1573    })?;
1574    if !output.status.success() {
1575        let stderr_text: Cow<'_, str> = String::from_utf8_lossy(&output.stderr);
1576        let stdout_text: Cow<'_, str> = String::from_utf8_lossy(&output.stdout);
1577        return Err(Error::other(format!(
1578            "command {} failed (status={}): {}{}",
1579            program.display(),
1580            output.status,
1581            stderr_text.trim(),
1582            if stderr_text.trim().is_empty() {
1583                stdout_text.trim()
1584            } else {
1585                ""
1586            }
1587        )));
1588    }
1589    Ok(output)
1590}
1591
1592/// Locates an executable in `dir`, probing `.exe`/`.cmd`/`.bat` suffixes on Windows.
1593///
1594/// # Arguments
1595///
1596/// - `&Path` - Directory containing the tool binary.
1597/// - `&str` - Base executable stem.
1598///
1599/// # Returns
1600///
1601/// - `Option<PathBuf>` - Matching executable path when present on disk.
1602fn find_host_executable(dir: &Path, tool_name: &str) -> Option<PathBuf> {
1603    if cfg!(windows) {
1604        for suffix in [MOBILE_WIN_EXE_EXT, MOBILE_WIN_CMD_EXT, MOBILE_WIN_BAT_EXT] {
1605            let with_ext: PathBuf = dir.join(format!("{tool_name}{suffix}"));
1606            if with_ext.is_file() {
1607                return Some(with_ext);
1608            }
1609        }
1610        let direct: PathBuf = dir.join(tool_name);
1611        if direct.is_file() {
1612            return Some(direct);
1613        }
1614        return None;
1615    }
1616    let direct: PathBuf = dir.join(tool_name);
1617    if direct.is_file() {
1618        return Some(direct);
1619    }
1620    for suffix in [MOBILE_WIN_EXE_EXT, MOBILE_WIN_CMD_EXT, MOBILE_WIN_BAT_EXT] {
1621        let with_ext: PathBuf = dir.join(format!("{tool_name}{suffix}"));
1622        if with_ext.is_file() {
1623            return Some(with_ext);
1624        }
1625    }
1626    None
1627}
1628
1629/// Requires an executable to exist in `dir`, returning a `NotFound` error otherwise.
1630///
1631/// # Arguments
1632///
1633/// - `&Path` - Directory expected to contain the tool.
1634/// - `&str` - Executable stem name.
1635///
1636/// # Returns
1637///
1638/// - `io::Result<PathBuf>` - Existing executable path.
1639fn require_host_executable(dir: &Path, tool_name: &str) -> io::Result<PathBuf> {
1640    find_host_executable(dir, tool_name).ok_or_else(|| {
1641        Error::new(
1642            ErrorKind::NotFound,
1643            format!(
1644                "required Android tool '{tool_name}' not found in {}",
1645                dir.display()
1646            ),
1647        )
1648    })
1649}
1650
1651/// Strips Windows `.exe`/`.cmd`/`.bat` suffixes from a filename for matching.
1652///
1653/// # Arguments
1654///
1655/// - `&str` - Filename string.
1656///
1657/// # Returns
1658///
1659/// - `&str` - Filename without Windows executable suffix.
1660fn strip_windows_script_ext(file_name: &str) -> &str {
1661    for suffix in [MOBILE_WIN_EXE_EXT, MOBILE_WIN_CMD_EXT, MOBILE_WIN_BAT_EXT] {
1662        if let Some(prefix) = file_name.strip_suffix(suffix) {
1663            return prefix;
1664        }
1665    }
1666    file_name
1667}
1668
1669/// Parses dot-delimited numeric segments of a version label for natural version sorting.
1670///
1671/// # Arguments
1672///
1673/// - `&str` - Version label such as `"27.2.12479018"` or `"35"`.
1674///
1675/// # Returns
1676///
1677/// - `Vec<u64>` - Parsed numeric segments.
1678fn parse_version_sort_key(raw: &str) -> Vec<u64> {
1679    raw.split('.')
1680        .map(|part: &str| {
1681            let digits: String = part
1682                .chars()
1683                .take_while(|ch: &char| ch.is_ascii_digit())
1684                .collect();
1685            digits.parse::<u64>().unwrap_or(0)
1686        })
1687        .collect()
1688}
1689
1690/// Recursively collects regular files matching `extension` under `root_dir`.
1691///
1692/// # Arguments
1693///
1694/// - `&Path` - Root directory to traverse.
1695/// - `&str` - Expected file extension without leading dot.
1696/// - `&mut Vec<PathBuf>` - Destination list of discovered file paths.
1697///
1698/// # Returns
1699///
1700/// - `io::Result<()>` - Directory traversal outcome.
1701fn collect_files_with_extension(
1702    root_dir: &Path,
1703    extension: &str,
1704    out: &mut Vec<PathBuf>,
1705) -> io::Result<()> {
1706    for entry_res in fs::read_dir(root_dir)? {
1707        let entry: DirEntry = entry_res?;
1708        let entry_path: PathBuf = entry.path();
1709        if entry_path.is_dir() {
1710            collect_files_with_extension(&entry_path, extension, out)?;
1711        } else if entry_path.extension().and_then(OsStr::to_str) == Some(extension) {
1712            out.push(entry_path);
1713        }
1714    }
1715    Ok(())
1716}
1717
1718/// Removes a regular file if it currently exists on disk.
1719///
1720/// # Arguments
1721///
1722/// - `&Path` - File path to remove when present.
1723///
1724/// # Returns
1725///
1726/// - `io::Result<()>` - Removal outcome.
1727pub(crate) fn remove_file_if_exists(path: &Path) -> io::Result<()> {
1728    if path.exists() {
1729        fs::remove_file(path)?;
1730    }
1731    Ok(())
1732}